1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "c/timer.h"
17 #include "sync/poller.h"
18 #include "internal_inc/osal.h"
19 #include "dfx/log/ffrt_log_api.h"
20 #include "util/ffrt_facade.h"
21 
QosConvert(ffrt_qos_t qos,ffrt::QoS & mappedQos)22 static bool QosConvert(ffrt_qos_t qos, ffrt::QoS& mappedQos)
23 {
24     if (ffrt::GetFuncQosMap() == nullptr) {
25         FFRT_LOGE("FuncQosMap has not regist");
26         return false;
27     }
28     mappedQos = ffrt::GetFuncQosMap()(qos);
29     if (mappedQos == ffrt::qos_inherit) {
30         mappedQos = ffrt::ExecuteCtx::Cur()->qos();
31     }
32     return true;
33 }
34 
35 API_ATTRIBUTE((visibility("default")))
36 ffrt_timer_t ffrt_timer_start(ffrt_qos_t qos, uint64_t timeout, void* data, ffrt_timer_cb cb, bool repeat)
37 {
38     ffrt::QoS pollerQos;
39     if (!QosConvert(qos, pollerQos)) {
40         return -1;
41     }
42 
43     if (cb == nullptr) {
44         FFRT_LOGE("[Poller] cb cannot be null");
45         return -1;
46     }
47 
48     int handle = ffrt::FFRTFacade::GetPPInstance().GetPoller(pollerQos).RegisterTimer(timeout, data, cb, repeat);
49     if (handle >= 0) {
50         ffrt::FFRTFacade::GetEUInstance().NotifyLocalTaskAdded(pollerQos);
51     }
52     return handle;
53 }
54 
55 API_ATTRIBUTE((visibility("default")))
56 int ffrt_timer_stop(ffrt_qos_t qos, int handle)
57 {
58     ffrt::QoS pollerQos;
59     if (!QosConvert(qos, pollerQos)) {
60         return -1;
61     }
62 
63     return ffrt::FFRTFacade::GetPPInstance().GetPoller(pollerQos).UnregisterTimer(handle);
64 }
65 
66 API_ATTRIBUTE((visibility("default")))
67 ffrt_timer_query_t ffrt_timer_query(ffrt_qos_t qos, int handle)
68 {
69     ffrt::QoS pollerQos;
70     if (!QosConvert(qos, pollerQos)) {
71         return ffrt_timer_notfound;
72     }
73 
74     return ffrt::FFRTFacade::GetPPInstance().GetPoller(pollerQos).GetTimerStatus(handle);
75 }