• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2022-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 "timer_manager.h"
17 
18 #include <algorithm>
19 #include <ctime>
20 #include <iostream>
21 #include <sys/time.h>
22 #include <utility>
23 #include <vector>
24 
25 #include "system_ability_definition.h"
26 #ifdef DEVICE_STANDBY_ENABLE
27 #include "allow_type.h"
28 #include "standby_service_client.h"
29 #endif
30 #include "ipc_skeleton.h"
31 #include "time_file_utils.h"
32 #include "time_permission.h"
33 #include "timer_proxy.h"
34 
35 namespace OHOS {
36 namespace MiscServices {
37 using namespace std::chrono;
38 using namespace OHOS::AppExecFwk;
39 namespace {
40 constexpr uint32_t TIME_CHANGED_BITS = 16;
41 constexpr uint32_t TIME_CHANGED_MASK = 1 << TIME_CHANGED_BITS;
42 const int ONE_THOUSAND = 1000;
43 const float_t BATCH_WINDOW_COE = 0.75;
44 const auto ZERO_FUTURITY = seconds(0);
45 const auto MIN_INTERVAL_ONE_SECONDS = seconds(1);
46 const auto MAX_INTERVAL = hours(24 * 365);
47 const auto INTERVAL_HOUR = hours(1);
48 const auto INTERVAL_HALF_DAY = hours(12);
49 const auto MIN_FUZZABLE_INTERVAL = milliseconds(10000);
50 const int NANO_TO_SECOND =  1000000000;
51 const int WANTAGENT_CODE_ELEVEN = 11;
52 
53 #ifdef POWER_MANAGER_ENABLE
54 constexpr int64_t USE_LOCK_TIME_IN_NANO = 2 * NANO_TO_SECOND;
55 constexpr int32_t USE_LOCK_DELAY_TIME_IN_MICRO = 10000;
56 constexpr int32_t MAX_RETRY_LOCK_TIMES = 3;
57 constexpr int32_t NANO_TO_MILLI = 1000000;
58 constexpr int64_t ONE_HUNDRED_MILLI = 100000000; // 100ms
59 #endif
60 
61 #ifdef DEVICE_STANDBY_ENABLE
62 const int REASON_NATIVE_API = 0;
63 const int REASON_APP_API = 1;
64 #endif
65 }
66 
67 extern bool AddBatchLocked(std::vector<std::shared_ptr<Batch>> &list, const std::shared_ptr<Batch> &batch);
68 extern steady_clock::time_point MaxTriggerTime(steady_clock::time_point now,
69                                                steady_clock::time_point triggerAtTime,
70                                                milliseconds interval);
71 
Create()72 std::shared_ptr<TimerManager> TimerManager::Create()
73 {
74     auto impl = TimerHandler::Create();
75     if (impl == nullptr) {
76         TIME_HILOGE(TIME_MODULE_SERVICE, "Create Timer handle failed.");
77         return nullptr;
78     }
79     return std::shared_ptr<TimerManager>(new TimerManager(impl));
80 }
81 
TimerManager(std::shared_ptr<TimerHandler> impl)82 TimerManager::TimerManager(std::shared_ptr<TimerHandler> impl)
83     : random_ {static_cast<uint64_t>(time(nullptr))},
84       runFlag_ {true},
85       handler_ {std::move(impl)},
86       lastTimeChangeClockTime_ {system_clock::time_point::min()},
87       lastTimeChangeRealtime_ {steady_clock::time_point::min()}
88 {
89     alarmThread_.reset(new std::thread(&TimerManager::TimerLooper, this));
90 }
91 
CreateTimer(TimerPara & paras,std::function<void (const uint64_t)> callback,std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> wantAgent,int uid,uint64_t & timerId)92 int32_t TimerManager::CreateTimer(TimerPara &paras,
93                                   std::function<void (const uint64_t)> callback,
94                                   std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> wantAgent,
95                                   int uid,
96                                   uint64_t &timerId)
97 {
98     while (timerId == 0) {
99         timerId = random_();
100     }
101     TIME_HILOGI(TIME_MODULE_SERVICE,
102                 "Create timer: %{public}d windowLength:%{public}" PRId64 "interval:%{public}" PRId64 "flag:%{public}d"
103                 "uid:%{public}d pid:%{public}d", paras.timerType, paras.windowLength, paras.interval, paras.flag,
104                 IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid());
105     std::string bundleName = TimeFileUtils::GetBundleNameByTokenID(IPCSkeleton::GetCallingTokenID());
106     auto timerInfo = std::make_shared<TimerEntry>(TimerEntry {
107         timerId,
108         paras.timerType,
109         static_cast<uint64_t>(paras.windowLength),
110         paras.interval,
111         paras.flag,
112         std::move(callback),
113         wantAgent,
114         uid,
115         bundleName
116     });
117     std::lock_guard<std::mutex> lock(entryMapMutex_);
118     timerEntryMap_.insert(std::make_pair(timerId, timerInfo));
119     return E_TIME_OK;
120 }
121 
StartTimer(uint64_t timerId,uint64_t triggerTime)122 int32_t TimerManager::StartTimer(uint64_t timerId, uint64_t triggerTime)
123 {
124     std::lock_guard<std::mutex> lock(entryMapMutex_);
125     auto it = timerEntryMap_.find(timerId);
126     if (it == timerEntryMap_.end()) {
127         TIME_HILOGE(TIME_MODULE_SERVICE, "Timer id not found: %{public}" PRId64 "", timerId);
128         return E_TIME_NOT_FOUND;
129     }
130     TIME_HILOGI(TIME_MODULE_SERVICE, "Start timer: %{public}" PRIu64 " TriggerTime: %{public}" PRIu64""
131                 "uid:%{public}d pid:%{public}d", timerId, triggerTime, IPCSkeleton::GetCallingUid(),
132                 IPCSkeleton::GetCallingPid());
133     auto timerInfo = it->second;
134     if (TimerProxy::GetInstance().IsUidProxy(timerInfo->uid)) {
135         TIME_HILOGI(TIME_MODULE_SERVICE,
136             "Do not start timer, timer already proxy, id=%{public}" PRId64 ", uid = %{public}d",
137             timerInfo->id, timerInfo->uid);
138         return E_TIME_DEAL_FAILED;
139     }
140     SetHandler(timerInfo->id,
141                timerInfo->type,
142                triggerTime,
143                timerInfo->windowLength,
144                timerInfo->interval,
145                timerInfo->flag,
146                timerInfo->callback,
147                timerInfo->wantAgent,
148                timerInfo->uid,
149                timerInfo->bundleName);
150     return E_TIME_OK;
151 }
152 
StopTimer(uint64_t timerId)153 int32_t TimerManager::StopTimer(uint64_t timerId)
154 {
155     return StopTimerInner(timerId, false);
156 }
157 
DestroyTimer(uint64_t timerId)158 int32_t TimerManager::DestroyTimer(uint64_t timerId)
159 {
160     return StopTimerInner(timerId, true);
161 }
162 
StopTimerInner(uint64_t timerNumber,bool needDestroy)163 int32_t TimerManager::StopTimerInner(uint64_t timerNumber, bool needDestroy)
164 {
165     TIME_HILOGI(TIME_MODULE_SERVICE, "start id: %{public}" PRId64 ", needDestroy: %{public}d",
166         timerNumber, needDestroy);
167     std::lock_guard<std::mutex> lock(entryMapMutex_);
168     auto it = timerEntryMap_.find(timerNumber);
169     if (it == timerEntryMap_.end()) {
170         TIME_HILOGW(TIME_MODULE_SERVICE, "timer not exist");
171         return E_TIME_DEAL_FAILED;
172     }
173     RemoveHandler(timerNumber);
174     if (it->second) {
175         int32_t uid = it->second->uid;
176         TimerProxy::GetInstance().RemoveProxy(timerNumber, uid);
177         TimerProxy::GetInstance().EraseTimerFromProxyUidMap(timerNumber, uid);
178     }
179     if (needDestroy) {
180         timerEntryMap_.erase(it);
181     }
182     return E_TIME_OK;
183 }
184 
SetHandler(uint64_t id,int type,uint64_t triggerAtTime,uint64_t windowLength,uint64_t interval,int flag,std::function<void (const uint64_t)> callback,std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> wantAgent,int uid,const std::string & bundleName)185 void TimerManager::SetHandler(uint64_t id,
186                               int type,
187                               uint64_t triggerAtTime,
188                               uint64_t windowLength,
189                               uint64_t interval,
190                               int flag,
191                               std::function<void (const uint64_t)> callback,
192                               std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> wantAgent,
193                               int uid,
194                               const std::string &bundleName)
195 {
196     TIME_HILOGI(TIME_MODULE_SERVICE,
197                 "start type:%{public}d windowLength:%{public}" PRIu64"interval:%{public}" PRIu64"flag:%{public}d",
198         type, windowLength, interval, flag);
199     auto windowLengthDuration = milliseconds(windowLength);
200     if (windowLengthDuration > INTERVAL_HALF_DAY) {
201         windowLengthDuration = INTERVAL_HOUR;
202     }
203     auto minInterval = MIN_INTERVAL_ONE_SECONDS;
204     auto intervalDuration = milliseconds(interval);
205     if (intervalDuration > milliseconds::zero() && intervalDuration < minInterval) {
206         intervalDuration = minInterval;
207     } else if (intervalDuration > MAX_INTERVAL) {
208         intervalDuration = MAX_INTERVAL;
209     }
210 
211     auto nowElapsed = GetBootTimeNs();
212     auto nominalTrigger = ConvertToElapsed(milliseconds(triggerAtTime), type);
213     if (nominalTrigger < nowElapsed) {
214         TIME_HILOGI(TIME_MODULE_SERVICE, "invalid trigger time.");
215         return;
216     }
217     auto minTrigger = nowElapsed + ZERO_FUTURITY;
218     auto triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
219 
220     steady_clock::time_point maxElapsed;
221     if (windowLengthDuration == milliseconds::zero()) {
222         maxElapsed = triggerElapsed;
223     } else if (windowLengthDuration < milliseconds::zero()) {
224         maxElapsed = MaxTriggerTime(nominalTrigger, triggerElapsed, intervalDuration);
225         windowLengthDuration = duration_cast<milliseconds>(maxElapsed - triggerElapsed);
226     } else {
227         maxElapsed = triggerElapsed + windowLengthDuration;
228     }
229     TIME_HILOGD(TIME_MODULE_SERVICE, "Try get lock");
230     std::lock_guard<std::mutex> lockGuard(mutex_);
231     TIME_HILOGD(TIME_MODULE_SERVICE, "Lock guard");
232     SetHandlerLocked(id,
233                      type,
234                      milliseconds(triggerAtTime),
235                      triggerElapsed,
236                      windowLengthDuration,
237                      maxElapsed,
238                      intervalDuration,
239                      std::move(callback),
240                      wantAgent,
241                      static_cast<uint32_t>(flag),
242                      true,
243                      uid,
244                      bundleName);
245 }
246 
SetHandlerLocked(uint64_t id,int type,std::chrono::milliseconds when,std::chrono::steady_clock::time_point whenElapsed,std::chrono::milliseconds windowLength,std::chrono::steady_clock::time_point maxWhen,std::chrono::milliseconds interval,std::function<void (const uint64_t)> callback,const std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> & wantAgent,uint32_t flags,bool doValidate,uint64_t callingUid,const std::string & bundleName)247 void TimerManager::SetHandlerLocked(uint64_t id, int type,
248                                     std::chrono::milliseconds when,
249                                     std::chrono::steady_clock::time_point whenElapsed,
250                                     std::chrono::milliseconds windowLength,
251                                     std::chrono::steady_clock::time_point maxWhen,
252                                     std::chrono::milliseconds interval,
253                                     std::function<void (const uint64_t)> callback,
254                                     const std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> &wantAgent,
255                                     uint32_t flags,
256                                     bool doValidate,
257                                     uint64_t callingUid,
258                                     const std::string &bundleName)
259 {
260     TIME_HILOGD(TIME_MODULE_SERVICE, "start id: %{public}" PRId64 "", id);
261     auto alarm = std::make_shared<TimerInfo>(id, type, when, whenElapsed, windowLength, maxWhen,
262                                              interval, std::move(callback), wantAgent, flags, callingUid, bundleName);
263     SetHandlerLocked(alarm, false, doValidate, false);
264     TIME_HILOGD(TIME_MODULE_SERVICE, "end");
265 }
266 
RemoveHandler(uint64_t id)267 void TimerManager::RemoveHandler(uint64_t id)
268 {
269     std::lock_guard<std::mutex> lock(mutex_);
270     RemoveLocked(id);
271     TimerProxy::GetInstance().RemoveUidTimerMap(id);
272 }
273 
RemoveLocked(uint64_t id)274 void TimerManager::RemoveLocked(uint64_t id)
275 {
276     TIME_HILOGI(TIME_MODULE_SERVICE, "start id: %{public}" PRIu64 "", id);
277     auto whichAlarms = [id](const TimerInfo &timer) {
278         return timer.id == id;
279     };
280 
281     bool didRemove = false;
282     for (auto it = alarmBatches_.begin(); it != alarmBatches_.end();) {
283         auto batch = *it;
284         didRemove = batch->Remove(whichAlarms);
285         if (batch->Size() == 0) {
286             TIME_HILOGD(TIME_MODULE_SERVICE, "erase");
287             it = alarmBatches_.erase(it);
288         } else {
289             ++it;
290         }
291     }
292     pendingDelayTimers_.erase(remove_if(pendingDelayTimers_.begin(), pendingDelayTimers_.end(),
293         [id](const std::shared_ptr<TimerInfo> &timer) {
294             return timer->id == id;
295         }), pendingDelayTimers_.end());
296     delayedTimers_.erase(id);
297     bool isAdjust = false;
298     if (mPendingIdleUntil_ != nullptr && id == mPendingIdleUntil_->id) {
299         TIME_HILOGI(TIME_MODULE_SERVICE, "Idle alarm removed.");
300         mPendingIdleUntil_ = nullptr;
301         isAdjust = AdjustTimersBasedOnDeviceIdle();
302         delayedTimers_.clear();
303         for (const auto &pendingTimer : pendingDelayTimers_) {
304             TIME_HILOGI(TIME_MODULE_SERVICE, "Set timer from delay list, id=%{public}" PRId64 "", pendingTimer->id);
305             if (pendingTimer->whenElapsed <= GetBootTimeNs()) {
306                 // 2 means the time of performing task.
307                 pendingTimer->UpdateWhenElapsed(GetBootTimeNs(), milliseconds(2));
308             } else {
309                 pendingTimer->UpdateWhenElapsed(GetBootTimeNs(), pendingTimer->offset);
310             }
311             SetHandlerLocked(pendingTimer, false, true, false);
312         }
313         pendingDelayTimers_.clear();
314     }
315 
316     if (didRemove || isAdjust) {
317         ReBatchAllTimersLocked(true);
318     }
319 }
320 
SetHandlerLocked(std::shared_ptr<TimerInfo> alarm,bool rebatching,bool doValidate,bool isRebatched)321 void TimerManager::SetHandlerLocked(std::shared_ptr<TimerInfo> alarm, bool rebatching, bool doValidate,
322                                     bool isRebatched)
323 {
324     TIME_HILOGD(TIME_MODULE_SERVICE, "start rebatching= %{public}d, doValidate= %{public}d", rebatching, doValidate);
325     TimerProxy::GetInstance().RecordUidTimerMap(alarm, isRebatched);
326 
327     if (!isRebatched && mPendingIdleUntil_ != nullptr && !CheckAllowWhileIdle(alarm)) {
328         TIME_HILOGI(TIME_MODULE_SERVICE, "Pending not-allowed alarm in idle state, id=%{public}" PRId64 "",
329             alarm->id);
330         alarm->offset = duration_cast<milliseconds>(alarm->whenElapsed - GetBootTimeNs());
331         pendingDelayTimers_.push_back(alarm);
332         return;
333     }
334     bool isAdjust = false;
335     if (!isRebatched && alarm->flags & static_cast<uint32_t>(IDLE_UNTIL)) {
336         TIME_HILOGI(TIME_MODULE_SERVICE, "Set idle timer, id=%{public}" PRId64 "", alarm->id);
337         mPendingIdleUntil_ = alarm;
338         isAdjust = AdjustTimersBasedOnDeviceIdle();
339     }
340     InsertAndBatchTimerLocked(std::move(alarm));
341     if (isAdjust) {
342         ReBatchAllTimers();
343         rebatching = true;
344     }
345     if (!rebatching) {
346         RescheduleKernelTimerLocked();
347     }
348 }
349 
ReBatchAllTimers()350 void TimerManager::ReBatchAllTimers()
351 {
352     TIME_HILOGD(TIME_MODULE_SERVICE, "start");
353     ReBatchAllTimersLocked(true);
354     TIME_HILOGD(TIME_MODULE_SERVICE, "end");
355 }
356 
ReBatchAllTimersLocked(bool doValidate)357 void TimerManager::ReBatchAllTimersLocked(bool doValidate)
358 {
359     auto oldSet = alarmBatches_;
360     alarmBatches_.clear();
361     auto nowElapsed = GetBootTimeNs();
362     for (const auto &batch : oldSet) {
363         auto n = batch->Size();
364         for (unsigned int i = 0; i < n; i++) {
365             ReAddTimerLocked(batch->Get(i), nowElapsed, doValidate);
366         }
367     }
368     RescheduleKernelTimerLocked();
369 }
370 
ReAddTimerLocked(std::shared_ptr<TimerInfo> timer,std::chrono::steady_clock::time_point nowElapsed,bool doValidate)371 void TimerManager::ReAddTimerLocked(std::shared_ptr<TimerInfo> timer,
372                                     std::chrono::steady_clock::time_point nowElapsed,
373                                     bool doValidate)
374 {
375     TIME_HILOGD(TIME_MODULE_SERVICE, "ReAddTimerLocked start. uid= %{public}d, id=%{public}" PRId64 ""
376         ", timer whenElapsed=%{public}lld, now=%{public}lld",
377         timer->uid, timer->id, timer->whenElapsed.time_since_epoch().count(),
378         GetBootTimeNs().time_since_epoch().count());
379     auto whenElapsed = ConvertToElapsed(timer->when, timer->type);
380     steady_clock::time_point maxElapsed;
381     if (timer->windowLength == milliseconds::zero()) {
382         maxElapsed = whenElapsed;
383     } else {
384         maxElapsed = (timer->windowLength > milliseconds::zero()) ?
385                      (whenElapsed + timer->windowLength) :
386                      MaxTriggerTime(nowElapsed, whenElapsed, timer->repeatInterval);
387     }
388     timer->whenElapsed = whenElapsed;
389     timer->maxWhenElapsed = maxElapsed;
390     SetHandlerLocked(timer, true, doValidate, true);
391 }
392 
ConvertToElapsed(std::chrono::milliseconds when,int type)393 std::chrono::steady_clock::time_point TimerManager::ConvertToElapsed(std::chrono::milliseconds when, int type)
394 {
395     auto bootTimePoint = GetBootTimeNs();
396     if (type == RTC || type == RTC_WAKEUP) {
397         auto systemTimeNow = system_clock::now().time_since_epoch();
398         auto offset = when - systemTimeNow;
399         TIME_HILOGD(TIME_MODULE_SERVICE, "systemTimeNow : %{public}lld offset : %{public}lld",
400                     systemTimeNow.count(), offset.count());
401         return bootTimePoint + offset;
402     }
403     auto bootTimeNow = bootTimePoint.time_since_epoch();
404     auto offset = when - bootTimeNow;
405     TIME_HILOGD(TIME_MODULE_SERVICE, "bootTimeNow : %{public}lld offset : %{public}lld",
406                 bootTimeNow.count(), offset.count());
407     return bootTimePoint + offset;
408 }
409 
TimerLooper()410 void TimerManager::TimerLooper()
411 {
412     TIME_HILOGD(TIME_MODULE_SERVICE, "Start timer wait loop");
413     pthread_setname_np(pthread_self(), "timer_loop");
414     std::vector<std::shared_ptr<TimerInfo>> triggerList;
415     while (runFlag_) {
416         uint32_t result = handler_->WaitForAlarm();
417         TIME_HILOGI(TIME_MODULE_SERVICE, "result: %{public}u", result);
418         auto nowRtc = std::chrono::system_clock::now();
419         auto nowElapsed = GetBootTimeNs();
420         triggerList.clear();
421 
422         if ((result & TIME_CHANGED_MASK) != 0) {
423             system_clock::time_point lastTimeChangeClockTime;
424             system_clock::time_point expectedClockTime;
425             std::lock_guard<std::mutex> lock(mutex_);
426             lastTimeChangeClockTime = lastTimeChangeClockTime_;
427             expectedClockTime = lastTimeChangeClockTime +
428                 (duration_cast<milliseconds>(nowElapsed.time_since_epoch()) -
429                 duration_cast<milliseconds>(lastTimeChangeRealtime_.time_since_epoch()));
430             if (lastTimeChangeClockTime == system_clock::time_point::min()
431                 || nowRtc < (expectedClockTime - milliseconds(ONE_THOUSAND))
432                 || nowRtc > (expectedClockTime + milliseconds(ONE_THOUSAND))) {
433                 ReBatchAllTimers();
434                 lastTimeChangeClockTime_ = nowRtc;
435                 lastTimeChangeRealtime_ = nowElapsed;
436             }
437         }
438 
439         if (result != TIME_CHANGED_MASK) {
440             std::lock_guard<std::mutex> lock(mutex_);
441             TriggerTimersLocked(triggerList, nowElapsed);
442             DeliverTimersLocked(triggerList);
443             RescheduleKernelTimerLocked();
444         } else {
445             std::lock_guard<std::mutex> lock(mutex_);
446             RescheduleKernelTimerLocked();
447         }
448     }
449 }
450 
~TimerManager()451 TimerManager::~TimerManager()
452 {
453     if (alarmThread_ && alarmThread_->joinable()) {
454         runFlag_ = false;
455         alarmThread_->join();
456     }
457 }
458 
GetBootTimeNs()459 steady_clock::time_point TimerManager::GetBootTimeNs()
460 {
461     int64_t timeNow = -1;
462     struct timespec tv {};
463     if (clock_gettime(CLOCK_BOOTTIME, &tv) < 0) {
464         return steady_clock::now();
465     }
466     timeNow = tv.tv_sec * NANO_TO_SECOND + tv.tv_nsec;
467     steady_clock::time_point tp_epoch ((nanoseconds(timeNow)));
468     return tp_epoch;
469 }
470 
TriggerIdleTimer()471 void TimerManager::TriggerIdleTimer()
472 {
473     TIME_HILOGI(TIME_MODULE_SERVICE, "Idle alarm triggers.");
474     std::lock_guard<std::mutex> lock(idleTimerMutex_);
475     mPendingIdleUntil_ = nullptr;
476     delayedTimers_.clear();
477     std::for_each(pendingDelayTimers_.begin(), pendingDelayTimers_.end(),
478         [this](const std::shared_ptr<TimerInfo> &pendingTimer) {
479             TIME_HILOGI(TIME_MODULE_SERVICE, "Set timer from delay list, id=%{public}" PRId64 "", pendingTimer->id);
480             if (pendingTimer->whenElapsed > GetBootTimeNs()) {
481                 pendingTimer->UpdateWhenElapsed(GetBootTimeNs(), pendingTimer->offset);
482             } else {
483                 // 2 means the time of performing task.
484                 pendingTimer->UpdateWhenElapsed(GetBootTimeNs(), milliseconds(2));
485             }
486             SetHandlerLocked(pendingTimer, false, true, false);
487         });
488     pendingDelayTimers_.clear();
489     ReBatchAllTimers();
490 }
491 
ProcTriggerTimer(std::shared_ptr<TimerInfo> & alarm,std::vector<std::shared_ptr<TimerInfo>> & triggerList,const std::chrono::steady_clock::time_point & nowElapsed)492 void TimerManager::ProcTriggerTimer(std::shared_ptr<TimerInfo> &alarm,
493     std::vector<std::shared_ptr<TimerInfo>> &triggerList, const std::chrono::steady_clock::time_point &nowElapsed)
494 {
495     alarm->count = 1;
496     if (mPendingIdleUntil_ != nullptr && mPendingIdleUntil_->id == alarm->id) {
497         TriggerIdleTimer();
498     }
499     if (TimerProxy::GetInstance().IsUidProxy(alarm->uid)) {
500         alarm->UpdateWhenElapsed(nowElapsed, milliseconds(TimerProxy::GetInstance().GetProxyDelayTime()));
501         TIME_HILOGD(TIME_MODULE_SERVICE, "UpdateWhenElapsed for proxy timer trigger. "
502             "uid= %{public}d, id=%{public}" PRId64 ", timer whenElapsed=%{public}lld, now=%{public}lld",
503             alarm->uid, alarm->id, alarm->whenElapsed.time_since_epoch().count(),
504             nowElapsed.time_since_epoch().count());
505         SetHandlerLocked(alarm->id, alarm->type, alarm->when, alarm->whenElapsed, alarm->windowLength,
506             alarm->maxWhenElapsed, alarm->repeatInterval, alarm->callback,
507             alarm->wantAgent, alarm->flags, true, alarm->uid, alarm->bundleName);
508     } else {
509         triggerList.push_back(alarm);
510         HandleRepeatTimer(alarm, nowElapsed);
511     }
512 }
513 
TriggerTimersLocked(std::vector<std::shared_ptr<TimerInfo>> & triggerList,std::chrono::steady_clock::time_point nowElapsed)514 bool TimerManager::TriggerTimersLocked(std::vector<std::shared_ptr<TimerInfo>> &triggerList,
515                                        std::chrono::steady_clock::time_point nowElapsed)
516 {
517     bool hasWakeup = false;
518     TIME_HILOGD(TIME_MODULE_SERVICE, "current time %{public}lld", GetBootTimeNs().time_since_epoch().count());
519     while (!alarmBatches_.empty()) {
520         auto batch = alarmBatches_.at(0);
521         TIME_HILOGD(TIME_MODULE_SERVICE, "first batch trigger time %{public}lld",
522             batch->GetStart().time_since_epoch().count());
523         if (batch->GetStart() > nowElapsed) {
524             break;
525         }
526         alarmBatches_.erase(alarmBatches_.begin());
527         TIME_HILOGI(
528             TIME_MODULE_SERVICE, "after erase alarmBatches_.size= %{public}d", static_cast<int>(alarmBatches_.size()));
529         const auto n = batch->Size();
530         for (unsigned int i = 0; i < n; ++i) {
531             auto alarm = batch->Get(i);
532             ProcTriggerTimer(alarm, triggerList, nowElapsed);
533             TIME_HILOGI(TIME_MODULE_SERVICE, "alarm uid= %{public}d, id=%{public}" PRId64 " bundleName=%{public}s",
534                         alarm->uid, alarm->id, alarm->bundleName.c_str());
535 
536             if (alarm->wakeup) {
537                 hasWakeup = true;
538             }
539         }
540     }
541     std::sort(triggerList.begin(), triggerList.end(),
542         [](const std::shared_ptr<TimerInfo> &l, const std::shared_ptr<TimerInfo> &r) {
543             return l->whenElapsed < r->whenElapsed;
544         });
545 
546     return hasWakeup;
547 }
548 
RescheduleKernelTimerLocked()549 void TimerManager::RescheduleKernelTimerLocked()
550 {
551     auto nextNonWakeup = std::chrono::steady_clock::time_point::min();
552     if (!alarmBatches_.empty()) {
553         auto firstWakeup = FindFirstWakeupBatchLocked();
554         auto firstBatch = alarmBatches_.front();
555         if (firstWakeup != nullptr) {
556             #ifdef POWER_MANAGER_ENABLE
557             HandleRunningLock(firstWakeup);
558             #endif
559             auto alarmPtr = firstWakeup->Get(0);
560             SetLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup->GetStart().time_since_epoch());
561         }
562         if (firstBatch != firstWakeup) {
563             auto alarmPtr = firstBatch->Get(0);
564             nextNonWakeup = firstBatch->GetStart();
565         }
566     }
567 
568     if (nextNonWakeup != std::chrono::steady_clock::time_point::min()) {
569         SetLocked(ELAPSED_REALTIME, nextNonWakeup.time_since_epoch());
570     }
571 }
572 
FindFirstWakeupBatchLocked()573 std::shared_ptr<Batch> TimerManager::FindFirstWakeupBatchLocked()
574 {
575     auto it = std::find_if(alarmBatches_.begin(),
576                            alarmBatches_.end(),
577                            [](const std::shared_ptr<Batch> &batch) {
578                                return batch->HasWakeups();
579                            });
580     return (it != alarmBatches_.end()) ? *it : nullptr;
581 }
582 
SetLocked(int type,std::chrono::nanoseconds when)583 void TimerManager::SetLocked(int type, std::chrono::nanoseconds when)
584 {
585     TIME_HILOGI(TIME_MODULE_SERVICE, "current bootTime: %{public}lld", GetBootTimeNs().time_since_epoch().count());
586     int ret = handler_->Set(static_cast<uint32_t>(type), when);
587     TIME_HILOGI(TIME_MODULE_SERVICE, "Set timer to kernel. ret: %{public}d", ret);
588 }
589 
InsertAndBatchTimerLocked(std::shared_ptr<TimerInfo> alarm)590 void TimerManager::InsertAndBatchTimerLocked(std::shared_ptr<TimerInfo> alarm)
591 {
592     int64_t whichBatch = (alarm->flags & static_cast<uint32_t>(STANDALONE)) ?
593                          -1 :
594                          AttemptCoalesceLocked(alarm->whenElapsed, alarm->maxWhenElapsed);
595     TIME_HILOGI(TIME_MODULE_SERVICE, "whichBatch= %{public}" PRId64 ", id=%{public}" PRId64 "", whichBatch, alarm->id);
596     if (whichBatch < 0) {
597         AddBatchLocked(alarmBatches_, std::make_shared<Batch>(*alarm));
598     } else {
599         auto batch = alarmBatches_.at(whichBatch);
600         if (batch->Add(alarm)) {
601             alarmBatches_.erase(alarmBatches_.begin() + whichBatch);
602             AddBatchLocked(alarmBatches_, batch);
603         }
604     }
605 }
606 
AttemptCoalesceLocked(std::chrono::steady_clock::time_point whenElapsed,std::chrono::steady_clock::time_point maxWhen)607 int64_t TimerManager::AttemptCoalesceLocked(std::chrono::steady_clock::time_point whenElapsed,
608                                             std::chrono::steady_clock::time_point maxWhen)
609 {
610     auto it = std::find_if(alarmBatches_.begin(), alarmBatches_.end(),
611         [whenElapsed, maxWhen](const std::shared_ptr<Batch> &batch) {
612             return (batch->GetFlags() & static_cast<uint32_t>(STANDALONE)) == 0 &&
613                    (batch->CanHold(whenElapsed, maxWhen));
614         });
615     if (it != alarmBatches_.end()) {
616         return std::distance(alarmBatches_.begin(), it);
617     }
618     return -1;
619 }
620 
DeliverTimersLocked(const std::vector<std::shared_ptr<TimerInfo>> & triggerList)621 void TimerManager::DeliverTimersLocked(const std::vector<std::shared_ptr<TimerInfo>> &triggerList)
622 {
623     for (const auto &alarm : triggerList) {
624         if (alarm->callback) {
625             TimerProxy::GetInstance().CallbackAlarmIfNeed(alarm);
626         }
627         if (alarm->wantAgent) {
628             NotifyWantAgent(alarm->wantAgent);
629         }
630     }
631 }
632 
NotifyWantAgent(const std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> & wantAgent)633 void TimerManager::NotifyWantAgent(const std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> &wantAgent)
634 {
635     TIME_HILOGD(TIME_MODULE_SERVICE, "trigger wantAgent.");
636     std::shared_ptr<AAFwk::Want> want = OHOS::AbilityRuntime::WantAgent::WantAgentHelper::GetWant(wantAgent);
637     if (want == nullptr) {
638         TIME_HILOGE(TIME_MODULE_SERVICE, "want is nullptr");
639         return;
640     }
641     OHOS::AbilityRuntime::WantAgent::TriggerInfo paramsInfo("", nullptr, want, WANTAGENT_CODE_ELEVEN);
642     auto code = OHOS::AbilityRuntime::WantAgent::WantAgentHelper::TriggerWantAgent(wantAgent, nullptr, paramsInfo);
643     TIME_HILOGI(TIME_MODULE_SERVICE, "trigger wantAgent result: %{public}d", code);
644 }
645 
UpdateTimersState(std::shared_ptr<TimerInfo> & alarm)646 void TimerManager::UpdateTimersState(std::shared_ptr<TimerInfo> &alarm)
647 {
648     RemoveLocked(alarm->id);
649     InsertAndBatchTimerLocked(alarm);
650     RescheduleKernelTimerLocked();
651 }
652 
ProxyTimer(int32_t uid,bool isProxy,bool needRetrigger)653 bool TimerManager::ProxyTimer(int32_t uid, bool isProxy, bool needRetrigger)
654 {
655     std::lock_guard<std::mutex> lock(mutex_);
656     return TimerProxy::GetInstance().ProxyTimer(uid, isProxy, needRetrigger, GetBootTimeNs(),
657         [this] (std::shared_ptr<TimerInfo> &alarm) { UpdateTimersState(alarm); });
658 }
659 
ResetAllProxy()660 bool TimerManager::ResetAllProxy()
661 {
662     std::lock_guard<std::mutex> lock(mutex_);
663     return TimerProxy::GetInstance().ResetAllProxy(GetBootTimeNs(),
664         [this] (std::shared_ptr<TimerInfo> &alarm) { UpdateTimersState(alarm); });
665 }
666 
CheckAllowWhileIdle(const std::shared_ptr<TimerInfo> & alarm)667 bool TimerManager::CheckAllowWhileIdle(const std::shared_ptr<TimerInfo> &alarm)
668 {
669 #ifdef DEVICE_STANDBY_ENABLE
670     if (TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
671         std::vector<DevStandbyMgr::AllowInfo> restrictList;
672         DevStandbyMgr::StandbyServiceClient::GetInstance().GetRestrictList(DevStandbyMgr::AllowType::TIMER,
673             restrictList, REASON_APP_API);
674         auto it = std::find_if(restrictList.begin(), restrictList.end(),
675             [&alarm](const DevStandbyMgr::AllowInfo &allowInfo) { return allowInfo.GetName() == alarm->bundleName; });
676         if (it != restrictList.end()) {
677             return false;
678         }
679     }
680 
681     if (TimePermission::CheckProxyCallingPermission()) {
682         pid_t pid = IPCSkeleton::GetCallingPid();
683         std::string procName = TimeFileUtils::GetNameByPid(pid);
684         if (alarm->flags & static_cast<uint32_t>(INEXACT_REMINDER)) {
685             return false;
686         }
687         std::vector<DevStandbyMgr::AllowInfo> restrictList;
688         DevStandbyMgr::StandbyServiceClient::GetInstance().GetRestrictList(DevStandbyMgr::AllowType::TIMER,
689             restrictList, REASON_NATIVE_API);
690         auto it = std::find_if(restrictList.begin(), restrictList.end(),
691             [procName](const DevStandbyMgr::AllowInfo &allowInfo) { return allowInfo.GetName() == procName; });
692         if (it != restrictList.end()) {
693             return false;
694         }
695     }
696 #endif
697     return true;
698 }
699 
AdjustDeliveryTimeBasedOnDeviceIdle(const std::shared_ptr<TimerInfo> & alarm)700 bool TimerManager::AdjustDeliveryTimeBasedOnDeviceIdle(const std::shared_ptr<TimerInfo> &alarm)
701 {
702     TIME_HILOGI(TIME_MODULE_SERVICE, "start adjust timer, uid=%{public}d, id=%{public}" PRId64 "",
703         alarm->uid, alarm->id);
704     if (mPendingIdleUntil_ == alarm) {
705         return false;
706     }
707     if (mPendingIdleUntil_ == nullptr) {
708         auto itMap = delayedTimers_.find(alarm->id);
709         if (itMap != delayedTimers_.end()) {
710             std::chrono::milliseconds currentTime;
711             if (alarm->type == RTC || alarm->type == RTC_WAKEUP) {
712                 currentTime = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
713             } else {
714                 currentTime = duration_cast<milliseconds>(GetBootTimeNs().time_since_epoch());
715             }
716 
717             if (alarm->origWhen > currentTime) {
718                 auto offset = alarm->origWhen - currentTime;
719                 return alarm->UpdateWhenElapsed(GetBootTimeNs(), offset);
720             }
721             // 2 means the time of performing task.
722             return alarm->UpdateWhenElapsed(GetBootTimeNs(), milliseconds(2));
723         }
724         return false;
725     }
726 
727     if (CheckAllowWhileIdle(alarm)) {
728         TIME_HILOGI(TIME_MODULE_SERVICE, "Timer unrestricted, not adjust. id=%{public}" PRId64 "", alarm->id);
729         return false;
730     } else if (alarm->whenElapsed > mPendingIdleUntil_->whenElapsed) {
731         TIME_HILOGI(TIME_MODULE_SERVICE, "Timer not allowed, not adjust. id=%{public}" PRId64 "", alarm->id);
732         return false;
733     } else {
734         TIME_HILOGI(TIME_MODULE_SERVICE, "Timer not allowed, id=%{public}" PRId64 "", alarm->id);
735         delayedTimers_[alarm->id] = alarm->whenElapsed;
736         auto offset = ConvertToElapsed(mPendingIdleUntil_->when, mPendingIdleUntil_->type) - GetBootTimeNs();
737         return alarm->UpdateWhenElapsed(GetBootTimeNs(), offset);
738     }
739 }
740 
AdjustTimersBasedOnDeviceIdle()741 bool TimerManager::AdjustTimersBasedOnDeviceIdle()
742 {
743     TIME_HILOGD(TIME_MODULE_SERVICE, "start adjust alarmBatches_.size=%{public}d",
744         static_cast<int>(alarmBatches_.size()));
745     bool isAdjust = false;
746     for (const auto &batch : alarmBatches_) {
747         auto n = batch->Size();
748         for (unsigned int i = 0; i < n; i++) {
749             auto alarm = batch->Get(i);
750             isAdjust = AdjustDeliveryTimeBasedOnDeviceIdle(alarm) || isAdjust;
751         }
752     }
753     return isAdjust;
754 }
755 
AddBatchLocked(std::vector<std::shared_ptr<Batch>> & list,const std::shared_ptr<Batch> & newBatch)756 bool AddBatchLocked(std::vector<std::shared_ptr<Batch>> &list, const std::shared_ptr<Batch> &newBatch)
757 {
758     auto it = std::upper_bound(list.begin(),
759                                list.end(),
760                                newBatch,
761                                [](const std::shared_ptr<Batch> &first, const std::shared_ptr<Batch> &second) {
762                                    return first->GetStart() < second->GetStart();
763                                });
764     list.insert(it, newBatch);
765     return it == list.begin();
766 }
767 
MaxTriggerTime(steady_clock::time_point now,steady_clock::time_point triggerAtTime,milliseconds interval)768 steady_clock::time_point MaxTriggerTime(steady_clock::time_point now,
769                                         steady_clock::time_point triggerAtTime,
770                                         milliseconds interval)
771 {
772     milliseconds futurity = (interval == milliseconds::zero()) ?
773                             (duration_cast<milliseconds>(triggerAtTime - now)) : interval;
774     if (futurity < MIN_FUZZABLE_INTERVAL) {
775         futurity = milliseconds::zero();
776     }
777     return triggerAtTime + milliseconds(static_cast<long>(BATCH_WINDOW_COE * futurity.count()));
778 }
779 
ShowTimerEntryMap(int fd)780 bool TimerManager::ShowTimerEntryMap(int fd)
781 {
782     TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
783     std::lock_guard<std::mutex> lock(showTimerMutex_);
784     auto iter = timerEntryMap_.begin();
785     for (; iter != timerEntryMap_.end(); iter++) {
786         dprintf(fd, " - dump timer number   = %lu\n", iter->first);
787         dprintf(fd, " * timer id            = %lu\n", iter->second->id);
788         dprintf(fd, " * timer type          = %d\n", iter->second->type);
789         dprintf(fd, " * timer flag          = %lu\n", iter->second->flag);
790         dprintf(fd, " * timer window Length = %lu\n", iter->second->windowLength);
791         dprintf(fd, " * timer interval      = %lu\n", iter->second->interval);
792         dprintf(fd, " * timer uid           = %d\n\n", iter->second->uid);
793     }
794     TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
795     return true;
796 }
797 
ShowTimerEntryById(int fd,uint64_t timerId)798 bool TimerManager::ShowTimerEntryById(int fd, uint64_t timerId)
799 {
800     TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
801     std::lock_guard<std::mutex> lock(showTimerMutex_);
802     auto iter = timerEntryMap_.find(timerId);
803     if (iter == timerEntryMap_.end()) {
804         TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
805         return false;
806     } else {
807         dprintf(fd, " - dump timer number   = %lu\n", iter->first);
808         dprintf(fd, " * timer id            = %lu\n", iter->second->id);
809         dprintf(fd, " * timer type          = %d\n", iter->second->type);
810         dprintf(fd, " * timer window Length = %lu\n", iter->second->windowLength);
811         dprintf(fd, " * timer interval      = %lu\n", iter->second->interval);
812         dprintf(fd, " * timer uid           = %d\n\n", iter->second->uid);
813     }
814     TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
815     return true;
816 }
817 
ShowTimerTriggerById(int fd,uint64_t timerId)818 bool TimerManager::ShowTimerTriggerById(int fd, uint64_t timerId)
819 {
820     TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
821     std::lock_guard<std::mutex> lock(showTimerMutex_);
822     for (size_t i = 0; i < alarmBatches_.size(); i++) {
823         for (size_t j = 0; j < alarmBatches_[i]->Size(); j++) {
824             if (alarmBatches_[i]->Get(j)->id == timerId) {
825                 dprintf(fd, " - dump timer id   = %lu\n", alarmBatches_[i]->Get(j)->id);
826                 dprintf(fd, " * timer trigger   = %lld\n", alarmBatches_[i]->Get(j)->origWhen);
827             }
828         }
829     }
830     TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
831     return true;
832 }
833 
ShowIdleTimerInfo(int fd)834 bool TimerManager::ShowIdleTimerInfo(int fd)
835 {
836     TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
837     std::lock_guard<std::mutex> lock(showTimerMutex_);
838     dprintf(fd, " - dump idle state         = %d\n", (mPendingIdleUntil_ != nullptr));
839     if (mPendingIdleUntil_ != nullptr) {
840         dprintf(fd, " - dump idle timer id  = %lu\n", mPendingIdleUntil_->id);
841         dprintf(fd, " * timer type          = %d\n", mPendingIdleUntil_->type);
842         dprintf(fd, " * timer flag          = %lu\n", mPendingIdleUntil_->flags);
843         dprintf(fd, " * timer window Length = %lu\n", mPendingIdleUntil_->windowLength);
844         dprintf(fd, " * timer interval      = %lu\n", mPendingIdleUntil_->repeatInterval);
845         dprintf(fd, " * timer whenElapsed   = %lu\n", mPendingIdleUntil_->whenElapsed);
846         dprintf(fd, " * timer uid           = %d\n\n", mPendingIdleUntil_->uid);
847     }
848     for (const auto &pendingTimer : pendingDelayTimers_) {
849         dprintf(fd, " - dump pending delay timer id  = %lu\n", pendingTimer->id);
850         dprintf(fd, " * timer type          = %d\n", pendingTimer->type);
851         dprintf(fd, " * timer flag          = %lu\n", pendingTimer->flags);
852         dprintf(fd, " * timer window Length = %lu\n", pendingTimer->windowLength);
853         dprintf(fd, " * timer interval      = %lu\n", pendingTimer->repeatInterval);
854         dprintf(fd, " * timer whenElapsed   = %lu\n", pendingTimer->whenElapsed);
855         dprintf(fd, " * timer uid           = %d\n\n", pendingTimer->uid);
856     }
857     for (const auto &delayedTimer : delayedTimers_) {
858         dprintf(fd, " - dump delayed timer id = %lu\n", delayedTimer.first);
859         dprintf(fd, " * timer whenElapsed     = %lu\n", delayedTimer.second);
860     }
861     TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
862     return true;
863 }
864 
HandleRSSDeath()865 void TimerManager::HandleRSSDeath()
866 {
867     TIME_HILOGI(TIME_MODULE_CLIENT, "RSSSaDeathRecipient died.");
868     std::lock_guard<std::mutex> idleTimerLock(idleTimerMutex_);
869     if (mPendingIdleUntil_ != nullptr) {
870         StopTimerInner(mPendingIdleUntil_->id, true);
871     }
872 }
873 
HandleRepeatTimer(const std::shared_ptr<TimerInfo> & timer,std::chrono::steady_clock::time_point nowElapsed)874 void TimerManager::HandleRepeatTimer(
875     const std::shared_ptr<TimerInfo> &timer, std::chrono::steady_clock::time_point nowElapsed)
876 {
877     if (timer->repeatInterval > milliseconds::zero()) {
878         timer->count += static_cast<uint64_t>(
879             duration_cast<milliseconds>(nowElapsed - timer->expectedWhenElapsed) / timer->repeatInterval);
880         auto delta = timer->count * timer->repeatInterval;
881         auto nextElapsed = timer->whenElapsed + delta;
882         SetHandlerLocked(timer->id, timer->type, timer->when + delta, nextElapsed, timer->windowLength,
883             MaxTriggerTime(nowElapsed, nextElapsed, timer->repeatInterval), timer->repeatInterval, timer->callback,
884             timer->wantAgent, timer->flags, true, timer->uid, timer->bundleName);
885     } else {
886         TimerProxy::GetInstance().RemoveUidTimerMap(timer);
887     }
888 }
889 
890 #ifdef POWER_MANAGER_ENABLE
HandleRunningLock(const std::shared_ptr<Batch> & firstWakeup)891 void TimerManager::HandleRunningLock(const std::shared_ptr<Batch> &firstWakeup)
892 {
893     auto currentTime = duration_cast<nanoseconds>(GetBootTimeNs().time_since_epoch()).count();
894     auto nextTimerOffset =
895         duration_cast<nanoseconds>(firstWakeup->GetStart().time_since_epoch()).count() - currentTime;
896     auto lockOffset = currentTime - lockExpiredTime_;
897     if (nextTimerOffset > 0 && nextTimerOffset <= USE_LOCK_TIME_IN_NANO &&
898         ((lockOffset < 0 && std::abs(lockOffset) <= nextTimerOffset) || lockOffset >= 0)) {
899         auto firstAlarm = firstWakeup->Get(0);
900         if (firstAlarm == nullptr) {
901             TIME_HILOGI(TIME_MODULE_SERVICE, "first alarm is null");
902             return;
903         }
904         auto holdLockTime = nextTimerOffset + ONE_HUNDRED_MILLI;
905         TIME_HILOGI(TIME_MODULE_SERVICE, "runningLock time:%{public}" PRIu64 ", timerId:%{public}"
906                     PRIu64", uid:%{public}d  bundleName=%{public}s", static_cast<uint64_t>(holdLockTime),
907                     firstAlarm->id, firstAlarm->uid, firstAlarm->bundleName.c_str());
908         lockExpiredTime_ = currentTime + holdLockTime;
909         std::thread lockingThread([this, holdLockTime] {
910             TIME_HILOGI(TIME_MODULE_SERVICE, "start add runningLock thread");
911             int32_t retryCount = 0;
912             while (retryCount < MAX_RETRY_LOCK_TIMES) {
913                 AddRunningLock(holdLockTime);
914                 usleep(USE_LOCK_DELAY_TIME_IN_MICRO);
915                 ++retryCount;
916             }
917         });
918         lockingThread.detach();
919     }
920 }
921 
AddRunningLock(long long holdLockTime)922 void TimerManager::AddRunningLock(long long holdLockTime)
923 {
924     if (runningLock_ == nullptr) {
925         TIME_HILOGI(TIME_MODULE_SERVICE, "runningLock is nullptr, create runningLock");
926         runningLock_ = PowerMgr::PowerMgrClient::GetInstance().CreateRunningLock("timeServiceRunningLock",
927             PowerMgr::RunningLockType::RUNNINGLOCK_BACKGROUND_NOTIFICATION);
928     }
929     if (runningLock_ != nullptr) {
930         TIME_HILOGI(TIME_MODULE_SERVICE, "runningLock is not nullptr");
931         runningLock_->UnLock();
932         runningLock_->Lock(static_cast<int32_t>(holdLockTime / NANO_TO_MILLI));
933     }
934 }
935 #endif
936 } // MiscServices
937 } // OHOS