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 #include "rdb_errno.h"
27 #include "rdb_helper.h"
28 #include "rdb_open_callback.h"
29 #include "rdb_predicates.h"
30 #include "rdb_store.h"
31 #ifdef DEVICE_STANDBY_ENABLE
32 #include "allow_type.h"
33 #include "standby_service_client.h"
34 #endif
35 #include "ipc_skeleton.h"
36 #include "time_file_utils.h"
37 #include "time_permission.h"
38 #include "timer_proxy.h"
39 #include "time_sysevent.h"
40 #include "timer_database.h"
41 #include "os_account.h"
42 #include "os_account_manager.h"
43 #ifdef POWER_MANAGER_ENABLE
44 #include "time_system_ability.h"
45 #endif
46 
47 namespace OHOS {
48 namespace MiscServices {
49 using namespace std::chrono;
50 using namespace OHOS::AppExecFwk;
51 namespace {
52 constexpr uint32_t TIME_CHANGED_BITS = 16;
53 constexpr uint32_t TIME_CHANGED_MASK = 1 << TIME_CHANGED_BITS;
54 constexpr int64_t MAX_MILLISECOND = std::numeric_limits<int64_t>::max() / 1000000;
55 const int ONE_THOUSAND = 1000;
56 const float_t BATCH_WINDOW_COE = 0.75;
57 const auto ZERO_FUTURITY = seconds(0);
58 const auto MIN_INTERVAL_ONE_SECONDS = seconds(1);
59 const auto MAX_INTERVAL = hours(24 * 365);
60 const auto INTERVAL_HOUR = hours(1);
61 const auto INTERVAL_HALF_DAY = hours(12);
62 const auto MIN_FUZZABLE_INTERVAL = milliseconds(10000);
63 const int NANO_TO_SECOND =  1000000000;
64 const int WANTAGENT_CODE_ELEVEN = 11;
65 const int WANT_RETRY_TIMES = 6;
66 const int WANT_RETRY_INTERVAL = 1;
67 const int SYSTEM_USER_ID  = 0;
68 // an error code of ipc which means peer end is dead
69 constexpr int PEER_END_DEAD = 29189;
70 constexpr int TIMER_ALARM_COUNT = 50;
71 constexpr int MAX_TIMER_ALARM_COUNT = 100;
72 constexpr int TIMER_ALRAM_INTERVAL = 60;
73 constexpr int TIMER_COUNT_TOP_NUM = 5;
74 static const std::vector<std::string> ALL_DATA = { "timerId", "type", "flag", "windowLength", "interval", \
75                                                    "uid", "bundleName", "wantAgent", "state", "triggerTime" };
76 
77 #ifdef POWER_MANAGER_ENABLE
78 constexpr int64_t USE_LOCK_ONE_SEC_IN_NANO = 1 * NANO_TO_SECOND;
79 constexpr int64_t USE_LOCK_TIME_IN_NANO = 2 * NANO_TO_SECOND;
80 constexpr int32_t NANO_TO_MILLI = 1000000;
81 constexpr int64_t ONE_HUNDRED_MILLI = 100000000; // 100ms
82 const int POWER_RETRY_TIMES = 10;
83 const int POWER_RETRY_INTERVAL = 10000;
84 #endif
85 
86 #ifdef DEVICE_STANDBY_ENABLE
87 const int REASON_NATIVE_API = 0;
88 const int REASON_APP_API = 1;
89 #endif
90 }
91 
92 std::mutex TimerManager::instanceLock_;
93 TimerManager* TimerManager::instance_ = nullptr;
94 
95 extern bool AddBatchLocked(std::vector<std::shared_ptr<Batch>> &list, const std::shared_ptr<Batch> &batch);
96 extern steady_clock::time_point MaxTriggerTime(steady_clock::time_point now,
97                                                steady_clock::time_point triggerAtTime,
98                                                milliseconds interval);
99 
TimerManager(std::shared_ptr<TimerHandler> impl)100 TimerManager::TimerManager(std::shared_ptr<TimerHandler> impl)
101     : random_ {static_cast<uint64_t>(time(nullptr))},
102       runFlag_ {true},
103       handler_ {std::move(impl)},
104       lastTimeChangeClockTime_ {system_clock::time_point::min()},
105       lastTimeChangeRealtime_ {steady_clock::time_point::min()},
106       lastTimerOutOfRangeTime_ {steady_clock::time_point::min()}
107 {
__anonbe1d56dd0202null108     alarmThread_.reset(new std::thread([this] { this->TimerLooper(); }));
109 }
110 
GetInstance()111 TimerManager* TimerManager::GetInstance()
112 {
113     if (instance_ == nullptr) {
114         std::lock_guard<std::mutex> autoLock(instanceLock_);
115         if (instance_ == nullptr) {
116             auto impl = TimerHandler::Create();
117             if (impl == nullptr) {
118                 TIME_HILOGE(TIME_MODULE_SERVICE, "Create Timer handle failed.");
119                 return nullptr;
120             }
121             instance_ = new TimerManager(impl);
122             std::vector<std::string> bundleList = TimeFileUtils::GetBundleList();
123             if (!bundleList.empty()) {
124                 NEED_RECOVER_ON_REBOOT = bundleList;
125             }
126         }
127     }
128     if (instance_ == nullptr) {
129         TIME_HILOGE(TIME_MODULE_SERVICE, "Create Timer manager failed.");
130     }
131     return instance_;
132 }
133 
GetInsertValues(std::shared_ptr<TimerEntry> timerInfo,TimerPara & paras)134 OHOS::NativeRdb::ValuesBucket GetInsertValues(std::shared_ptr<TimerEntry> timerInfo, TimerPara &paras)
135 {
136     OHOS::NativeRdb::ValuesBucket insertValues;
137     insertValues.PutLong("timerId", timerInfo->id);
138     insertValues.PutInt("type", paras.timerType);
139     insertValues.PutInt("flag", paras.flag);
140     insertValues.PutLong("windowLength", paras.windowLength);
141     insertValues.PutLong("interval", paras.interval);
142     insertValues.PutInt("uid", timerInfo->uid);
143     insertValues.PutString("bundleName", timerInfo->bundleName);
144     insertValues.PutString("wantAgent",
145         OHOS::AbilityRuntime::WantAgent::WantAgentHelper::ToString(timerInfo->wantAgent));
146     insertValues.PutInt("state", 0);
147     insertValues.PutLong("triggerTime", 0);
148     insertValues.PutInt("pid", timerInfo->pid);
149     return insertValues;
150 }
151 
CreateTimer(TimerPara & paras,std::function<int32_t (const uint64_t)> callback,std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> wantAgent,int uid,int pid,uint64_t & timerId,DatabaseType type)152 int32_t TimerManager::CreateTimer(TimerPara &paras,
153                                   std::function<int32_t (const uint64_t)> callback,
154                                   std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> wantAgent,
155                                   int uid,
156                                   int pid,
157                                   uint64_t &timerId,
158                                   DatabaseType type)
159 {
160     TIME_HILOGD(TIME_MODULE_SERVICE,
161                 "Create timer: %{public}d windowLength:%{public}" PRId64 "interval:%{public}" PRId64 "flag:%{public}d"
162                 "uid:%{public}d pid:%{public}d timerId:%{public}" PRId64 "", paras.timerType, paras.windowLength,
163                 paras.interval, paras.flag, IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid(), timerId);
164     std::string bundleName = TimeFileUtils::GetBundleNameByTokenID(IPCSkeleton::GetCallingTokenID());
165     if (bundleName.empty()) {
166         bundleName = TimeFileUtils::GetNameByPid(IPCSkeleton::GetCallingPid());
167     }
168     std::shared_ptr<TimerEntry> timerInfo;
169     {
170         std::lock_guard<std::mutex> lock(entryMapMutex_);
171         while (timerId == 0) {
172             // random_() needs to be protected in a lock.
173             timerId = random_();
174         }
175         timerInfo = std::make_shared<TimerEntry>(TimerEntry {
176             timerId,
177             paras.timerType,
178             paras.windowLength,
179             paras.interval,
180             paras.flag,
181             std::move(callback),
182             wantAgent,
183             uid,
184             pid,
185             bundleName
186         });
187         timerEntryMap_.insert(std::make_pair(timerId, timerInfo));
188         IncreaseTimerCount(uid);
189     }
190     if (type == NOT_STORE) {
191         return E_TIME_OK;
192     } else if (CheckNeedRecoverOnReboot(bundleName, paras.timerType)) {
193         TimeDatabase::GetInstance().Insert(std::string(HOLD_ON_REBOOT),
194                                            GetInsertValues(timerInfo, paras));
195     } else {
196         TimeDatabase::GetInstance().Insert(std::string(DROP_ON_REBOOT),
197                                            GetInsertValues(timerInfo, paras));
198     }
199     return E_TIME_OK;
200 }
201 
ReCreateTimer(uint64_t timerId,std::shared_ptr<TimerEntry> timerInfo)202 void TimerManager::ReCreateTimer(uint64_t timerId, std::shared_ptr<TimerEntry> timerInfo)
203 {
204     std::lock_guard<std::mutex> lock(entryMapMutex_);
205     timerEntryMap_.insert(std::make_pair(timerId, timerInfo));
206     IncreaseTimerCount(timerInfo->uid);
207 }
208 
StartTimer(uint64_t timerId,uint64_t triggerTime)209 int32_t TimerManager::StartTimer(uint64_t timerId, uint64_t triggerTime)
210 {
211     std::shared_ptr<TimerEntry> timerInfo;
212     {
213         std::lock_guard<std::mutex> lock(entryMapMutex_);
214         auto it = timerEntryMap_.find(timerId);
215         if (it == timerEntryMap_.end()) {
216             TIME_HILOGE(TIME_MODULE_SERVICE, "Timer id not found: %{public}" PRId64 "", timerId);
217             return E_TIME_NOT_FOUND;
218         }
219         timerInfo = it->second;
220         TIME_HILOGI(TIME_MODULE_SERVICE,
221             "id: %{public}" PRIu64 " typ:%{public}d len: %{public}" PRId64 " int: %{public}" PRId64 " "
222             "flg :%{public}d trig: %{public}s uid:%{public}d pid:%{public}d",
223             timerId, timerInfo->type, timerInfo->windowLength, timerInfo->interval, timerInfo->flag,
224             std::to_string(triggerTime).c_str(), IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid());
225         {
226             // To prevent the same ID from being started repeatedly,
227             // the later start overwrites the earlier start.
228             std::lock_guard<std::mutex> lock(mutex_);
229             RemoveLocked(timerId, false);
230         }
231         SetHandler(timerInfo->id, timerInfo->type, triggerTime, timerInfo->windowLength, timerInfo->interval,
232             timerInfo->flag, timerInfo->callback, timerInfo->wantAgent, timerInfo->uid, timerInfo->pid,
233             timerInfo->bundleName);
234     }
235     auto tableName = (CheckNeedRecoverOnReboot(timerInfo->bundleName, timerInfo->type)
236                       ? HOLD_ON_REBOOT
237                       : DROP_ON_REBOOT);
238     OHOS::NativeRdb::ValuesBucket values;
239     values.PutInt("state", 1);
240     values.PutLong("triggerTime", static_cast<int64_t>(triggerTime));
241     OHOS::NativeRdb::RdbPredicates rdbPredicates(tableName);
242     rdbPredicates.EqualTo("state", 0)->And()->EqualTo("timerId", static_cast<int64_t>(timerId));
243     TimeDatabase::GetInstance().Update(values, rdbPredicates);
244     return E_TIME_OK;
245 }
246 
IncreaseTimerCount(int uid)247 void TimerManager::IncreaseTimerCount(int uid)
248 {
249     auto it = std::find_if(timerCount_.begin(), timerCount_.end(),
250         [uid](const std::pair<int32_t, size_t>& pair) {
251             return pair.first == uid;
252         });
253     if (it == timerCount_.end()) {
254         timerCount_.push_back(std::make_pair(uid, 1));
255     } else {
256         it->second++;
257     }
258     CheckTimerCount();
259 }
260 
DecreaseTimerCount(int uid)261 void TimerManager::DecreaseTimerCount(int uid)
262 {
263     auto it = std::find_if(timerCount_.begin(), timerCount_.end(),
264         [uid](const std::pair<int32_t, size_t>& pair) {
265             return pair.first == uid;
266         });
267     if (it == timerCount_.end()) {
268         TIME_HILOGE(TIME_MODULE_SERVICE, "uid: %{public}d has no timer", uid);
269     } else {
270         it->second--;
271     }
272 }
273 
CheckTimerCount()274 void TimerManager::CheckTimerCount()
275 {
276     int count = static_cast<int>(timerEntryMap_.size());
277     if (count > (timerOutOfRangeTimes_ + 1) * TIMER_ALARM_COUNT) {
278         timerOutOfRangeTimes_ += 1;
279         TIME_HILOGI(TIME_MODULE_SERVICE, "%{public}d timer in system", count);
280         ShowTimerCountByUid();
281         lastTimerOutOfRangeTime_ = GetBootTimeNs();
282         return;
283     }
284     auto currentBootTime = GetBootTimeNs();
285     if (count > MAX_TIMER_ALARM_COUNT &&
286         currentBootTime - lastTimerOutOfRangeTime_ > std::chrono::minutes(TIMER_ALRAM_INTERVAL)) {
287         TIME_HILOGI(TIME_MODULE_SERVICE, "%{public}d timer in system", count);
288         ShowTimerCountByUid();
289         lastTimerOutOfRangeTime_ = currentBootTime;
290         return;
291     }
292 }
293 
ShowTimerCountByUid()294 void TimerManager::ShowTimerCountByUid()
295 {
296     std::string uidStr = "";
297     std::string countStr = "";
298     auto size = static_cast<int>(timerCount_.size());
299     std::sort(timerCount_.begin(), timerCount_.end(),
300         [](const std::pair<int32_t, int32_t>& a, const std::pair<int32_t, int32_t>& b) {
301             return a.second > b.second;
302         });
303     auto limitedSize = (size > TIMER_COUNT_TOP_NUM) ? TIMER_COUNT_TOP_NUM : size;
304     for (auto it = timerCount_.begin(); it != timerCount_.begin() + limitedSize; ++it) {
305         uidStr = uidStr + std::to_string(it->first) + " ";
306         countStr = countStr + std::to_string(it->second) + " ";
307     }
308     TIME_HILOGI(TIME_MODULE_SERVICE, "Top uid:[%{public}s], nums:[%{public}s]", uidStr.c_str(), countStr.c_str());
309 }
310 
StopTimer(uint64_t timerId)311 int32_t TimerManager::StopTimer(uint64_t timerId)
312 {
313     return StopTimerInner(timerId, false);
314 }
315 
DestroyTimer(uint64_t timerId)316 int32_t TimerManager::DestroyTimer(uint64_t timerId)
317 {
318     return StopTimerInner(timerId, true);
319 }
320 
StopTimerInner(uint64_t timerNumber,bool needDestroy)321 int32_t TimerManager::StopTimerInner(uint64_t timerNumber, bool needDestroy)
322 {
323     TIME_HILOGI(TIME_MODULE_SERVICE, "id: %{public}" PRId64 ", needDestroy: %{public}d", timerNumber, needDestroy);
324     bool needRecoverOnReboot;
325     {
326         std::lock_guard<std::mutex> lock(entryMapMutex_);
327         auto it = timerEntryMap_.find(timerNumber);
328         if (it == timerEntryMap_.end()) {
329             TIME_HILOGW(TIME_MODULE_SERVICE, "timer not exist");
330             return E_TIME_DEAL_FAILED;
331         }
332         RemoveHandler(timerNumber);
333         TimerProxy::GetInstance().RemoveProxy(timerNumber, it->second->uid);
334         TimerProxy::GetInstance().RemovePidProxy(timerNumber, it->second->pid);
335         TimerProxy::GetInstance().EraseTimerFromProxyUidMap(timerNumber, it->second->uid);
336         TimerProxy::GetInstance().EraseTimerFromProxyPidMap(timerNumber, it->second->uid, it->second->pid);
337         needRecoverOnReboot = CheckNeedRecoverOnReboot(it->second->bundleName, it->second->type);
338         if (needDestroy) {
339             int uid = it->second->uid;
340             timerEntryMap_.erase(it);
341             DecreaseTimerCount(uid);
342         }
343     }
344     if (needRecoverOnReboot) {
345         OHOS::NativeRdb::ValuesBucket values;
346         values.PutInt("state", 0);
347         OHOS::NativeRdb::RdbPredicates rdbPredicates(HOLD_ON_REBOOT);
348         rdbPredicates.EqualTo("state", 1)->And()->EqualTo("timerId", static_cast<int64_t>(timerNumber));
349         TimeDatabase::GetInstance().Update(values, rdbPredicates);
350         if (needDestroy) {
351             OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete(HOLD_ON_REBOOT);
352             rdbPredicatesDelete.EqualTo("timerId", static_cast<int64_t>(timerNumber));
353             TimeDatabase::GetInstance().Delete(rdbPredicatesDelete);
354         }
355     } else {
356         OHOS::NativeRdb::ValuesBucket values;
357         values.PutInt("state", 0);
358         OHOS::NativeRdb::RdbPredicates rdbPredicates(DROP_ON_REBOOT);
359         rdbPredicates.EqualTo("state", 1)->And()->EqualTo("timerId", static_cast<int64_t>(timerNumber));
360         TimeDatabase::GetInstance().Update(values, rdbPredicates);
361         if (needDestroy) {
362             OHOS::NativeRdb::RdbPredicates rdbPredicatesDelete(DROP_ON_REBOOT);
363             rdbPredicatesDelete.EqualTo("timerId", static_cast<int64_t>(timerNumber));
364             TimeDatabase::GetInstance().Delete(rdbPredicatesDelete);
365         }
366     }
367     return E_TIME_OK;
368 }
369 
SetHandler(uint64_t id,int type,uint64_t triggerAtTime,int64_t windowLength,uint64_t interval,int flag,std::function<int32_t (const uint64_t)> callback,std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> wantAgent,int uid,int pid,const std::string & bundleName)370 void TimerManager::SetHandler(uint64_t id,
371                               int type,
372                               uint64_t triggerAtTime,
373                               int64_t windowLength,
374                               uint64_t interval,
375                               int flag,
376                               std::function<int32_t (const uint64_t)> callback,
377                               std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> wantAgent,
378                               int uid,
379                               int pid,
380                               const std::string &bundleName)
381 {
382     auto windowLengthDuration = milliseconds(windowLength);
383     if (windowLengthDuration > INTERVAL_HALF_DAY) {
384         windowLengthDuration = INTERVAL_HOUR;
385     }
386     auto intervalDuration = milliseconds(interval > MAX_MILLISECOND ? MAX_MILLISECOND : interval);
387     if (intervalDuration > milliseconds::zero() && intervalDuration < MIN_INTERVAL_ONE_SECONDS) {
388         intervalDuration = MIN_INTERVAL_ONE_SECONDS;
389     } else if (intervalDuration > MAX_INTERVAL) {
390         intervalDuration = MAX_INTERVAL;
391     }
392 
393     auto nowElapsed = GetBootTimeNs();
394     auto when = milliseconds(triggerAtTime > MAX_MILLISECOND ? MAX_MILLISECOND : triggerAtTime);
395     auto nominalTrigger = ConvertToElapsed(when, type);
396     auto minTrigger = nowElapsed + ZERO_FUTURITY;
397     auto triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
398 
399     steady_clock::time_point maxElapsed;
400     if (windowLengthDuration == milliseconds::zero()) {
401         maxElapsed = triggerElapsed;
402     } else if (windowLengthDuration < milliseconds::zero()) {
403         maxElapsed = MaxTriggerTime(nominalTrigger, triggerElapsed, intervalDuration);
404         windowLengthDuration = duration_cast<milliseconds>(maxElapsed - triggerElapsed);
405     } else {
406         maxElapsed = triggerElapsed + windowLengthDuration;
407     }
408     std::lock_guard<std::mutex> lockGuard(mutex_);
409     SetHandlerLocked(id,
410                      type,
411                      when,
412                      triggerElapsed,
413                      windowLengthDuration,
414                      maxElapsed,
415                      intervalDuration,
416                      std::move(callback),
417                      wantAgent,
418                      static_cast<uint32_t>(flag),
419                      uid,
420                      pid,
421                      bundleName);
422 }
423 
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<int32_t (const uint64_t)> callback,const std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> & wantAgent,uint32_t flags,uint64_t callingUid,uint64_t callingPid,const std::string & bundleName)424 void TimerManager::SetHandlerLocked(uint64_t id, int type,
425                                     std::chrono::milliseconds when,
426                                     std::chrono::steady_clock::time_point whenElapsed,
427                                     std::chrono::milliseconds windowLength,
428                                     std::chrono::steady_clock::time_point maxWhen,
429                                     std::chrono::milliseconds interval,
430                                     std::function<int32_t (const uint64_t)> callback,
431                                     const std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> &wantAgent,
432                                     uint32_t flags,
433                                     uint64_t callingUid,
434                                     uint64_t callingPid,
435                                     const std::string &bundleName)
436 {
437     TIME_HILOGD(TIME_MODULE_SERVICE, "start id: %{public}" PRId64 "", id);
438     auto alarm = std::make_shared<TimerInfo>(id, type, when, whenElapsed, windowLength, maxWhen,
439                                              interval, std::move(callback), wantAgent, flags, callingUid,
440                                              callingPid, bundleName);
441     if (TimerProxy::GetInstance().IsUidProxy(alarm->uid)) {
442         TIME_HILOGI(TIME_MODULE_SERVICE, "Timer already proxy, uid=%{public}" PRIu64 " id=%{public}" PRId64 "",
443             callingUid, alarm->id);
444         TimerProxy::GetInstance().RecordProxyUidTimerMap(alarm);
445         alarm->UpdateWhenElapsedFromNow(GetBootTimeNs(), milliseconds(TimerProxy::GetInstance().GetProxyDelayTime()));
446     }
447     if (TimerProxy::GetInstance().IsPidProxy(alarm->uid, alarm->pid)) {
448         TIME_HILOGI(TIME_MODULE_SERVICE, "Timer already proxy, pid=%{public}" PRIu64 " id=%{public}" PRId64 "",
449             callingPid, alarm->id);
450         TimerProxy::GetInstance().RecordProxyPidTimerMap(alarm);
451         alarm->UpdateWhenElapsedFromNow(GetBootTimeNs(), milliseconds(TimerProxy::GetInstance().GetProxyDelayTime()));
452     }
453 
454     SetHandlerLocked(alarm, false, false);
455     TIME_HILOGD(TIME_MODULE_SERVICE, "end");
456 }
457 
RemoveHandler(uint64_t id)458 void TimerManager::RemoveHandler(uint64_t id)
459 {
460     std::lock_guard<std::mutex> lock(mutex_);
461     RemoveLocked(id, true);
462     TimerProxy::GetInstance().RemoveUidTimerMap(id);
463     TimerProxy::GetInstance().RemovePidTimerMap(id);
464 }
465 
466 // needs to acquire the lock `mutex_` before calling this method
RemoveLocked(uint64_t id,bool needReschedule)467 void TimerManager::RemoveLocked(uint64_t id, bool needReschedule)
468 {
469     auto whichAlarms = [id](const TimerInfo &timer) {
470         return timer.id == id;
471     };
472 
473     bool didRemove = false;
474     for (auto it = alarmBatches_.begin(); it != alarmBatches_.end();) {
475         auto batch = *it;
476         didRemove = batch->Remove(whichAlarms);
477         if (didRemove) {
478             TIME_HILOGI(TIME_MODULE_SERVICE, "remove id: %{public}" PRIu64 "", id);
479             it = alarmBatches_.erase(it);
480             if (batch->Size() != 0) {
481                 TIME_HILOGI(TIME_MODULE_SERVICE, "reorder batch");
482                 AddBatchLocked(alarmBatches_, batch);
483             }
484             break;
485         }
486         ++it;
487     }
488     pendingDelayTimers_.erase(remove_if(pendingDelayTimers_.begin(), pendingDelayTimers_.end(),
489         [id](const std::shared_ptr<TimerInfo> &timer) {
490             return timer->id == id;
491         }), pendingDelayTimers_.end());
492     delayedTimers_.erase(id);
493     if (mPendingIdleUntil_ != nullptr && id == mPendingIdleUntil_->id) {
494         TIME_HILOGI(TIME_MODULE_SERVICE, "Idle alarm removed.");
495         mPendingIdleUntil_ = nullptr;
496         bool isAdjust = AdjustTimersBasedOnDeviceIdle();
497         delayedTimers_.clear();
498         for (const auto &pendingTimer : pendingDelayTimers_) {
499             TIME_HILOGI(TIME_MODULE_SERVICE, "Set timer from delay list, id=%{public}" PRId64 "", pendingTimer->id);
500             if (pendingTimer->whenElapsed <= GetBootTimeNs()) {
501                 // 2 means the time of performing task.
502                 pendingTimer->UpdateWhenElapsedFromNow(GetBootTimeNs(), milliseconds(2));
503             } else {
504                 pendingTimer->UpdateWhenElapsedFromNow(GetBootTimeNs(), pendingTimer->offset);
505             }
506             SetHandlerLocked(pendingTimer, false, false);
507         }
508         pendingDelayTimers_.clear();
509         if (isAdjust) {
510             ReBatchAllTimers();
511             return;
512         }
513     }
514 
515     if (needReschedule && didRemove) {
516         RescheduleKernelTimerLocked();
517     }
518 }
519 
520 // needs to acquire the lock `mutex_` before calling this method
SetHandlerLocked(std::shared_ptr<TimerInfo> alarm,bool rebatching,bool isRebatched)521 void TimerManager::SetHandlerLocked(std::shared_ptr<TimerInfo> alarm, bool rebatching, bool isRebatched)
522 {
523     TIME_HILOGD(TIME_MODULE_SERVICE, "start rebatching= %{public}d", rebatching);
524     TimerProxy::GetInstance().RecordUidTimerMap(alarm, isRebatched);
525     TimerProxy::GetInstance().RecordPidTimerMap(alarm, isRebatched);
526 
527     if (!isRebatched && mPendingIdleUntil_ != nullptr && !CheckAllowWhileIdle(alarm)) {
528         TIME_HILOGI(TIME_MODULE_SERVICE, "Pending not-allowed alarm in idle state, id=%{public}" PRId64 "",
529             alarm->id);
530         alarm->offset = duration_cast<milliseconds>(alarm->whenElapsed - GetBootTimeNs());
531         pendingDelayTimers_.push_back(alarm);
532         return;
533     }
534     if (!rebatching) {
535         AdjustSingleTimer(alarm);
536     }
537     bool isAdjust = false;
538     if (!isRebatched && alarm->flags & static_cast<uint32_t>(IDLE_UNTIL)) {
539         TIME_HILOGI(TIME_MODULE_SERVICE, "Set idle timer, id=%{public}" PRId64 "", alarm->id);
540         mPendingIdleUntil_ = alarm;
541         isAdjust = AdjustTimersBasedOnDeviceIdle();
542     }
543     InsertAndBatchTimerLocked(std::move(alarm));
544     if (isAdjust) {
545         ReBatchAllTimers();
546         rebatching = true;
547     }
548     if (!rebatching) {
549         RescheduleKernelTimerLocked();
550     }
551 }
552 
553 // needs to acquire the lock `mutex_` before calling this method
ReBatchAllTimers()554 void TimerManager::ReBatchAllTimers()
555 {
556     auto oldSet = alarmBatches_;
557     alarmBatches_.clear();
558     auto nowElapsed = GetBootTimeNs();
559     for (const auto &batch : oldSet) {
560         auto n = batch->Size();
561         for (unsigned int i = 0; i < n; i++) {
562             ReAddTimerLocked(batch->Get(i), nowElapsed);
563         }
564     }
565     RescheduleKernelTimerLocked();
566 }
567 
ReAddTimerLocked(std::shared_ptr<TimerInfo> timer,std::chrono::steady_clock::time_point nowElapsed)568 void TimerManager::ReAddTimerLocked(std::shared_ptr<TimerInfo> timer,
569                                     std::chrono::steady_clock::time_point nowElapsed)
570 {
571     TIME_HILOGD(TIME_MODULE_SERVICE, "ReAddTimerLocked start. uid= %{public}d, id=%{public}" PRId64 ""
572         ", timer originMaxWhenElapsed=%{public}lld, whenElapsed=%{public}lld, now=%{public}lld",
573         timer->uid, timer->id, timer->originWhenElapsed.time_since_epoch().count(),
574         timer->whenElapsed.time_since_epoch().count(), GetBootTimeNs().time_since_epoch().count());
575     auto whenElapsed = ConvertToElapsed(timer->when, timer->type);
576     steady_clock::time_point maxElapsed;
577     if (timer->windowLength == milliseconds::zero()) {
578         maxElapsed = whenElapsed;
579     } else {
580         maxElapsed = (timer->windowLength > milliseconds::zero()) ?
581                      (whenElapsed + timer->windowLength) :
582                      MaxTriggerTime(nowElapsed, whenElapsed, timer->repeatInterval);
583     }
584     timer->whenElapsed = whenElapsed;
585     timer->maxWhenElapsed = maxElapsed;
586     SetHandlerLocked(timer, true, true);
587 }
588 
ConvertToElapsed(std::chrono::milliseconds when,int type)589 std::chrono::steady_clock::time_point TimerManager::ConvertToElapsed(std::chrono::milliseconds when, int type)
590 {
591     auto bootTimePoint = GetBootTimeNs();
592     if (type == RTC || type == RTC_WAKEUP) {
593         auto systemTimeNow = system_clock::now().time_since_epoch();
594         auto offset = when - systemTimeNow;
595         TIME_HILOGD(TIME_MODULE_SERVICE, "systemTimeNow : %{public}lld offset : %{public}lld",
596                     systemTimeNow.count(), offset.count());
597         if (offset.count() <= 0) {
598             return bootTimePoint;
599         } else {
600             return bootTimePoint + offset;
601         }
602     }
603     auto bootTimeNow = bootTimePoint.time_since_epoch();
604     auto offset = when - bootTimeNow;
605     TIME_HILOGD(TIME_MODULE_SERVICE, "bootTimeNow : %{public}lld offset : %{public}lld",
606                 bootTimeNow.count(), offset.count());
607     if (offset.count() <= 0) {
608         return bootTimePoint;
609     } else {
610         return bootTimePoint + offset;
611     }
612 }
613 
TimerLooper()614 void TimerManager::TimerLooper()
615 {
616     TIME_HILOGD(TIME_MODULE_SERVICE, "Start timer wait loop");
617     pthread_setname_np(pthread_self(), "timer_loop");
618     std::vector<std::shared_ptr<TimerInfo>> triggerList;
619     while (runFlag_) {
620         uint32_t result = handler_->WaitForAlarm();
621         auto nowRtc = std::chrono::system_clock::now();
622         auto nowElapsed = GetBootTimeNs();
623         triggerList.clear();
624 
625         if ((result & TIME_CHANGED_MASK) != 0) {
626             TIME_HILOGI(TIME_MODULE_SERVICE, "ret: %{public}u", result);
627             system_clock::time_point lastTimeChangeClockTime;
628             system_clock::time_point expectedClockTime;
629             std::lock_guard<std::mutex> lock(mutex_);
630             lastTimeChangeClockTime = lastTimeChangeClockTime_;
631             expectedClockTime = lastTimeChangeClockTime +
632                 (duration_cast<milliseconds>(nowElapsed.time_since_epoch()) -
633                 duration_cast<milliseconds>(lastTimeChangeRealtime_.time_since_epoch()));
634             if (lastTimeChangeClockTime == system_clock::time_point::min()
635                 || nowRtc < expectedClockTime
636                 || nowRtc > (expectedClockTime + milliseconds(ONE_THOUSAND))) {
637                 ReBatchAllTimers();
638                 lastTimeChangeClockTime_ = nowRtc;
639                 lastTimeChangeRealtime_ = nowElapsed;
640             }
641         }
642 
643         if (result != TIME_CHANGED_MASK) {
644             {
645                 std::lock_guard<std::mutex> lock(mutex_);
646                 TriggerTimersLocked(triggerList, nowElapsed);
647             }
648             // in this function, timeservice apply a runninglock from powermanager
649             // release mutex to prevent powermanager from using the interface of timeservice
650             // which may cause deadlock
651             DeliverTimersLocked(triggerList);
652             {
653                 std::lock_guard<std::mutex> lock(mutex_);
654                 RescheduleKernelTimerLocked();
655             }
656         }
657     }
658 }
659 
~TimerManager()660 TimerManager::~TimerManager()
661 {
662     if (alarmThread_ && alarmThread_->joinable()) {
663         runFlag_ = false;
664         alarmThread_->join();
665     }
666 }
667 
GetBootTimeNs()668 steady_clock::time_point TimerManager::GetBootTimeNs()
669 {
670     int64_t timeNow = -1;
671     struct timespec tv {};
672     if (clock_gettime(CLOCK_BOOTTIME, &tv) < 0) {
673         return steady_clock::now();
674     }
675     timeNow = tv.tv_sec * NANO_TO_SECOND + tv.tv_nsec;
676     steady_clock::time_point tp_epoch ((nanoseconds(timeNow)));
677     return tp_epoch;
678 }
679 
680 // needs to acquire the lock `mutex_` before calling this method
TriggerIdleTimer()681 void TimerManager::TriggerIdleTimer()
682 {
683     TIME_HILOGI(TIME_MODULE_SERVICE, "Idle alarm triggers.");
684     mPendingIdleUntil_ = nullptr;
685     delayedTimers_.clear();
686     std::for_each(pendingDelayTimers_.begin(), pendingDelayTimers_.end(),
687         [this](const std::shared_ptr<TimerInfo> &pendingTimer) {
688             TIME_HILOGI(TIME_MODULE_SERVICE, "Set timer from delay list, id=%{public}" PRId64 "", pendingTimer->id);
689             if (pendingTimer->whenElapsed > GetBootTimeNs()) {
690                 pendingTimer->UpdateWhenElapsedFromNow(GetBootTimeNs(), pendingTimer->offset);
691             } else {
692                 // 2 means the time of performing task.
693                 pendingTimer->UpdateWhenElapsedFromNow(GetBootTimeNs(), milliseconds(2));
694             }
695             SetHandlerLocked(pendingTimer, false, false);
696         });
697     pendingDelayTimers_.clear();
698     ReBatchAllTimers();
699 }
700 
701 // needs to acquire the lock `mutex_` before calling this method
ProcTriggerTimer(std::shared_ptr<TimerInfo> & alarm,const std::chrono::steady_clock::time_point & nowElapsed)702 bool TimerManager::ProcTriggerTimer(std::shared_ptr<TimerInfo> &alarm,
703                                     const std::chrono::steady_clock::time_point &nowElapsed)
704 {
705     if (mPendingIdleUntil_ != nullptr && mPendingIdleUntil_->id == alarm->id) {
706         TriggerIdleTimer();
707     }
708     if (TimerProxy::GetInstance().IsUidProxy(alarm->uid)) {
709         alarm->UpdateWhenElapsedFromNow(nowElapsed, milliseconds(TimerProxy::GetInstance().GetProxyDelayTime()));
710         TIME_HILOGD(TIME_MODULE_SERVICE, "UpdateWhenElapsed for proxy timer trigger. "
711             "uid= %{public}d, id=%{public}" PRId64 ", timer whenElapsed=%{public}lld, now=%{public}lld",
712             alarm->uid, alarm->id, alarm->whenElapsed.time_since_epoch().count(),
713             nowElapsed.time_since_epoch().count());
714         SetHandlerLocked(alarm, false, false);
715         return false;
716     } else if (TimerProxy::GetInstance().IsPidProxy(alarm->uid, alarm->pid)) {
717         alarm->UpdateWhenElapsedFromNow(nowElapsed, milliseconds(TimerProxy::GetInstance().GetProxyDelayTime()));
718         TIME_HILOGD(TIME_MODULE_SERVICE, "UpdateWhenElapsed for proxy timer trigger. "
719             "pid= %{public}d, id=%{public}" PRId64 ", timer whenElapsed=%{public}lld, now=%{public}lld",
720             alarm->pid, alarm->id, alarm->whenElapsed.time_since_epoch().count(),
721             nowElapsed.time_since_epoch().count());
722         SetHandlerLocked(alarm, false, false);
723         return false;
724     } else {
725         HandleRepeatTimer(alarm, nowElapsed);
726         return true;
727     }
728 }
729 
730 // needs to acquire the lock `mutex_` before calling this method
TriggerTimersLocked(std::vector<std::shared_ptr<TimerInfo>> & triggerList,std::chrono::steady_clock::time_point nowElapsed)731 bool TimerManager::TriggerTimersLocked(std::vector<std::shared_ptr<TimerInfo>> &triggerList,
732                                        std::chrono::steady_clock::time_point nowElapsed)
733 {
734     bool hasWakeup = false;
735     TIME_HILOGD(TIME_MODULE_SERVICE, "current time %{public}lld", GetBootTimeNs().time_since_epoch().count());
736 
737     for (auto iter = alarmBatches_.begin(); iter != alarmBatches_.end();) {
738         if (*iter == nullptr) {
739             TIME_HILOGE(TIME_MODULE_SERVICE, "alarmBatches_ has nullptr");
740             iter = alarmBatches_.erase(iter);
741             continue;
742         }
743         if ((*iter)->GetStart() > nowElapsed) {
744             ++iter;
745             continue;
746         }
747         auto batch = *iter;
748         iter = alarmBatches_.erase(iter);
749         TIME_HILOGD(
750             TIME_MODULE_SERVICE, "batch size= %{public}d", static_cast<int>(alarmBatches_.size()));
751         const auto n = batch->Size();
752         for (unsigned int i = 0; i < n; ++i) {
753             auto alarm = batch->Get(i);
754             triggerList.push_back(alarm);
755             TIME_SIMPLIFY_HILOGI(TIME_MODULE_SERVICE, "uid: %{public}d id:%{public}" PRId64 " name:%{public}s"
756                 " wk:%{public}u",
757                 alarm->uid, alarm->id, alarm->bundleName.c_str(), alarm->wakeup);
758 
759             if (alarm->wakeup) {
760                 hasWakeup = true;
761             }
762         }
763     }
764     for (auto iter = triggerList.begin(); iter != triggerList.end();) {
765         auto alarm = *iter;
766         if (!ProcTriggerTimer(alarm, nowElapsed)) {
767             iter = triggerList.erase(iter);
768         } else {
769             ++iter;
770         }
771     }
772 
773     std::sort(triggerList.begin(), triggerList.end(),
774         [](const std::shared_ptr<TimerInfo> &l, const std::shared_ptr<TimerInfo> &r) {
775             return l->whenElapsed < r->whenElapsed;
776         });
777 
778     return hasWakeup;
779 }
780 
781 // needs to acquire the lock `mutex_` before calling this method
RescheduleKernelTimerLocked()782 void TimerManager::RescheduleKernelTimerLocked()
783 {
784     auto nextNonWakeup = std::chrono::steady_clock::time_point::min();
785     auto bootTime = GetBootTimeNs();
786     if (!alarmBatches_.empty()) {
787         auto firstWakeup = FindFirstWakeupBatchLocked();
788         auto firstBatch = alarmBatches_.front();
789         if (firstWakeup != nullptr) {
790             #ifdef POWER_MANAGER_ENABLE
791             HandleRunningLock(firstWakeup);
792             #endif
793             SetLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup->GetStart().time_since_epoch(), bootTime);
794         }
795         if (firstBatch != firstWakeup) {
796             nextNonWakeup = firstBatch->GetStart();
797         }
798     }
799 
800     if (nextNonWakeup != std::chrono::steady_clock::time_point::min()) {
801         SetLocked(ELAPSED_REALTIME, nextNonWakeup.time_since_epoch(), bootTime);
802     }
803 }
804 
805 // needs to acquire the lock `mutex_` before calling this method
FindFirstWakeupBatchLocked()806 std::shared_ptr<Batch> TimerManager::FindFirstWakeupBatchLocked()
807 {
808     auto it = std::find_if(alarmBatches_.begin(),
809                            alarmBatches_.end(),
810                            [](const std::shared_ptr<Batch> &batch) {
811                                return batch->HasWakeups();
812                            });
813     return (it != alarmBatches_.end()) ? *it : nullptr;
814 }
815 
SetLocked(int type,std::chrono::nanoseconds when,std::chrono::steady_clock::time_point bootTime)816 void TimerManager::SetLocked(int type, std::chrono::nanoseconds when, std::chrono::steady_clock::time_point bootTime)
817 {
818     handler_->Set(static_cast<uint32_t>(type), when, bootTime);
819 }
820 
821 // needs to acquire the lock `mutex_` before calling this method
InsertAndBatchTimerLocked(std::shared_ptr<TimerInfo> alarm)822 void TimerManager::InsertAndBatchTimerLocked(std::shared_ptr<TimerInfo> alarm)
823 {
824     int64_t whichBatch = (alarm->flags & static_cast<uint32_t>(STANDALONE)) ?
825                          -1 :
826                          AttemptCoalesceLocked(alarm->whenElapsed, alarm->maxWhenElapsed);
827     TIME_SIMPLIFY_HILOGI(TIME_MODULE_SERVICE, "bat: %{public}" PRId64 " id:%{public}" PRIu64 " "
828                          "we:%{public}lld mwe:%{public}lld",
829                          whichBatch, alarm->id, alarm->whenElapsed.time_since_epoch().count(),
830                          alarm->maxWhenElapsed.time_since_epoch().count());
831     if (whichBatch < 0) {
832         AddBatchLocked(alarmBatches_, std::make_shared<Batch>(*alarm));
833     } else {
834         auto batch = alarmBatches_.at(whichBatch);
835         if (batch->Add(alarm)) {
836             alarmBatches_.erase(alarmBatches_.begin() + whichBatch);
837             AddBatchLocked(alarmBatches_, batch);
838         }
839     }
840 }
841 
842 // needs to acquire the lock `mutex_` before calling this method
AttemptCoalesceLocked(std::chrono::steady_clock::time_point whenElapsed,std::chrono::steady_clock::time_point maxWhen)843 int64_t TimerManager::AttemptCoalesceLocked(std::chrono::steady_clock::time_point whenElapsed,
844                                             std::chrono::steady_clock::time_point maxWhen)
845 {
846     auto it = std::find_if(alarmBatches_.begin(), alarmBatches_.end(),
847         [whenElapsed, maxWhen](const std::shared_ptr<Batch> &batch) {
848             return (batch->GetFlags() & static_cast<uint32_t>(STANDALONE)) == 0 &&
849                    (batch->CanHold(whenElapsed, maxWhen));
850         });
851     if (it != alarmBatches_.end()) {
852         return std::distance(alarmBatches_.begin(), it);
853     }
854     return -1;
855 }
856 
NotifyWantAgentRetry(std::shared_ptr<TimerInfo> timer)857 void TimerManager::NotifyWantAgentRetry(std::shared_ptr<TimerInfo> timer)
858 {
859     auto retryRegister = [timer]() {
860         for (int i = 0; i < WANT_RETRY_TIMES; i++) {
861             sleep(WANT_RETRY_INTERVAL << i);
862             if (TimerManager::GetInstance()->NotifyWantAgent(timer)) {
863                 return;
864             }
865         }
866     };
867     std::thread thread(retryRegister);
868     thread.detach();
869 }
870 
CheckUserIdForNotify(const std::shared_ptr<TimerInfo> & timer)871 int32_t TimerManager::CheckUserIdForNotify(const std::shared_ptr<TimerInfo> &timer)
872 {
873     int userIdOfTimer = -1;
874     int foregroundUserId = -1;
875     int getLocalIdErr = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(timer->uid, userIdOfTimer);
876     if (getLocalIdErr != ERR_OK) {
877         TIME_HILOGE(TIME_MODULE_SERVICE, "Get account id from uid failed, errcode: %{public}d", getLocalIdErr);
878         return E_TIME_ACCOUNT_ERROR;
879     }
880     int getForegroundIdErr = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(foregroundUserId);
881     if (getForegroundIdErr != ERR_OK) {
882         TIME_HILOGE(TIME_MODULE_SERVICE, "Get foreground account id failed, errcode: %{public}d", getForegroundIdErr);
883         return E_TIME_ACCOUNT_ERROR;
884     }
885     if (userIdOfTimer == foregroundUserId || userIdOfTimer == SYSTEM_USER_ID) {
886         return E_TIME_OK;
887     } else {
888         TIME_HILOGI(TIME_MODULE_SERVICE, "WA wait switch user, uid: %{public}d, timerId: %{public}" PRId64,
889             timer->uid, timer->id);
890         return E_TIME_ACCOUNT_NOT_MATCH;
891     }
892 }
893 
DeliverTimersLocked(const std::vector<std::shared_ptr<TimerInfo>> & triggerList)894 void TimerManager::DeliverTimersLocked(const std::vector<std::shared_ptr<TimerInfo>> &triggerList)
895 {
896     auto wakeupNums = std::count_if(triggerList.begin(), triggerList.end(), [](auto timer) {return timer->wakeup;});
897     for (const auto &timer : triggerList) {
898         if (timer->wakeup) {
899             #ifdef POWER_MANAGER_ENABLE
900             TIME_HILOGD(TIME_MODULE_SERVICE, "id: %{public}" PRId64 ", uid: %{public}d bundleName: %{public}s",
901                         timer->id, timer->uid, timer->bundleName.c_str());
902             AddRunningLock(USE_LOCK_ONE_SEC_IN_NANO);
903             #endif
904             StatisticReporter(IPCSkeleton::GetCallingPid(), wakeupNums, timer);
905         }
906         if (timer->callback) {
907             if (TimerProxy::GetInstance().CallbackAlarmIfNeed(timer) == PEER_END_DEAD
908                 && !timer->wantAgent) {
909                 DestroyTimer(timer->id);
910                 continue;
911             }
912         }
913         if (timer->wantAgent) {
914             if (!NotifyWantAgent(timer) && CheckNeedRecoverOnReboot(timer->bundleName, timer->type)) {
915                 NotifyWantAgentRetry(timer);
916             }
917             if (CheckNeedRecoverOnReboot(timer->bundleName, timer->type)) {
918                 OHOS::NativeRdb::ValuesBucket values;
919                 values.PutInt("state", 0);
920                 OHOS::NativeRdb::RdbPredicates rdbPredicates(HOLD_ON_REBOOT);
921                 rdbPredicates.EqualTo("state", 1)
922                     ->And()
923                     ->EqualTo("timerId", static_cast<int64_t>(timer->id));
924                 TimeDatabase::GetInstance().Update(values, rdbPredicates);
925             } else {
926                 OHOS::NativeRdb::ValuesBucket values;
927                 values.PutInt("state", 0);
928                 OHOS::NativeRdb::RdbPredicates rdbPredicates(DROP_ON_REBOOT);
929                 rdbPredicates.EqualTo("state", 1)
930                     ->And()
931                     ->EqualTo("timerId", static_cast<int64_t>(timer->id));
932                 TimeDatabase::GetInstance().Update(values, rdbPredicates);
933             }
934         }
935         if (((timer->flags & static_cast<uint32_t>(IS_DISPOSABLE)) > 0) &&
936             (timer->repeatInterval == milliseconds::zero())) {
937             DestroyTimer(timer->id);
938         }
939     }
940 }
941 
NotifyWantAgent(const std::shared_ptr<TimerInfo> & timer)942 bool TimerManager::NotifyWantAgent(const std::shared_ptr<TimerInfo> &timer)
943 {
944     TIME_HILOGD(TIME_MODULE_SERVICE, "trigger wantAgent.");
945     auto wantAgent = timer->wantAgent;
946     std::shared_ptr<AAFwk::Want> want = OHOS::AbilityRuntime::WantAgent::WantAgentHelper::GetWant(wantAgent);
947     if (want == nullptr) {
948         switch (CheckUserIdForNotify(timer)) {
949             case E_TIME_ACCOUNT_NOT_MATCH:
950                 // No need to retry.
951                 return true;
952             case E_TIME_ACCOUNT_ERROR:
953                 TIME_HILOGE(TIME_MODULE_SERVICE, "want is nullptr, id=%{public}" PRId64 "", timer->id);
954                 return false;
955             default:
956                 break;
957         }
958         auto database = TimeDatabase::GetInstance();
959         OHOS::NativeRdb::RdbPredicates holdRdbPredicates(HOLD_ON_REBOOT);
960         holdRdbPredicates.EqualTo("timerId", static_cast<int64_t>(timer->id));
961         auto holdResultSet = database.Query(holdRdbPredicates, ALL_DATA);
962         if (holdResultSet == nullptr || holdResultSet->GoToFirstRow() != OHOS::NativeRdb::E_OK) {
963             TIME_HILOGE(TIME_MODULE_SERVICE, "db query failed nullptr");
964             if (holdResultSet != nullptr) {
965                 holdResultSet->Close();
966             }
967             return false;
968         }
969         // Line 7 is 'wantAgent'
970         wantAgent = OHOS::AbilityRuntime::WantAgent::WantAgentHelper::FromString(GetString(holdResultSet, 7));
971         holdResultSet->Close();
972         switch (CheckUserIdForNotify(timer)) {
973             case E_TIME_ACCOUNT_NOT_MATCH:
974                 TIME_HILOGI(TIME_MODULE_SERVICE, "user sw after FS, id=%{public}" PRId64 "", timer->id);
975                 // No need to retry.
976                 return true;
977             case E_TIME_ACCOUNT_ERROR:
978                 TIME_HILOGE(TIME_MODULE_SERVICE, "want is nullptr, id=%{public}" PRId64 "", timer->id);
979                 return false;
980             default:
981                 break;
982         }
983         want = OHOS::AbilityRuntime::WantAgent::WantAgentHelper::GetWant(wantAgent);
984         if (want == nullptr) {
985             TIME_HILOGE(TIME_MODULE_SERVICE, "want is nullptr, id=%{public}" PRId64 "", timer->id);
986             return false;
987         }
988     }
989     OHOS::AbilityRuntime::WantAgent::TriggerInfo paramsInfo("", nullptr, want, WANTAGENT_CODE_ELEVEN);
990     auto code = AbilityRuntime::WantAgent::WantAgentHelper::TriggerWantAgent(wantAgent, nullptr, paramsInfo);
991     TIME_SIMPLIFY_HILOGI(TIME_MODULE_SERVICE, "trigWA ret: %{public}d", code);
992     return code == ERR_OK;
993 }
994 
995 // needs to acquire the lock `mutex_` before calling this method
UpdateTimersState(std::shared_ptr<TimerInfo> & alarm)996 void TimerManager::UpdateTimersState(std::shared_ptr<TimerInfo> &alarm)
997 {
998     RemoveLocked(alarm->id, false);
999     AdjustSingleTimer(alarm);
1000     InsertAndBatchTimerLocked(alarm);
1001     RescheduleKernelTimerLocked();
1002 }
1003 
ProxyTimer(int32_t uid,bool isProxy,bool needRetrigger)1004 bool TimerManager::ProxyTimer(int32_t uid, bool isProxy, bool needRetrigger)
1005 {
1006     std::lock_guard<std::mutex> lock(mutex_);
1007     return TimerProxy::GetInstance().ProxyTimer(uid, isProxy, needRetrigger, GetBootTimeNs(),
1008         [this] (std::shared_ptr<TimerInfo> &alarm) { UpdateTimersState(alarm); });
1009 }
1010 
AdjustTimer(bool isAdjust,uint32_t interval)1011 bool TimerManager::AdjustTimer(bool isAdjust, uint32_t interval)
1012 {
1013     std::lock_guard<std::mutex> lock(mutex_);
1014     if (adjustPolicy_ == isAdjust && adjustInterval_ == interval) {
1015         TIME_HILOGI(TIME_MODULE_SERVICE, "already deal timer adjust, flag: %{public}d", isAdjust);
1016         return false;
1017     }
1018     std::chrono::steady_clock::time_point now = GetBootTimeNs();
1019     adjustPolicy_ = isAdjust;
1020     adjustInterval_ = interval;
1021     auto callback = [this] (AdjustTimerCallback adjustTimer) {
1022         bool isChanged = false;
1023         auto nowElapsed = GetBootTimeNs();
1024         for (const auto &batch : alarmBatches_) {
1025             if (!batch) {
1026                 continue;
1027             }
1028             auto n = batch->Size();
1029             for (unsigned int i = 0; i < n; i++) {
1030                 auto timer = batch->Get(i);
1031                 ReCalcuOriWhenElapsed(timer, nowElapsed);
1032                 isChanged = adjustTimer(timer) || isChanged;
1033             }
1034         }
1035         if (isChanged) {
1036             TIME_HILOGI(TIME_MODULE_SERVICE, "timer adjust executing, policy: %{public}d", adjustPolicy_);
1037             ReBatchAllTimers();
1038         }
1039     };
1040 
1041     return TimerProxy::GetInstance().AdjustTimer(isAdjust, interval, now, callback);
1042 }
1043 
ProxyTimer(int32_t uid,std::set<int> pidList,bool isProxy,bool needRetrigger)1044 bool TimerManager::ProxyTimer(int32_t uid, std::set<int> pidList, bool isProxy, bool needRetrigger)
1045 {
1046     std::set<int> failurePid;
1047     std::lock_guard<std::mutex> lock(mutex_);
1048     for (std::set<int>::iterator pid = pidList.begin(); pid != pidList.end(); ++pid) {
1049         if (!TimerProxy::GetInstance().PidProxyTimer(uid, *pid, isProxy, needRetrigger, GetBootTimeNs(),
1050             [this] (std::shared_ptr<TimerInfo> &alarm) { UpdateTimersState(alarm); })) {
1051             failurePid.insert(*pid);
1052         }
1053     }
1054     return (failurePid.size() == 0);
1055 }
1056 
ReCalcuOriWhenElapsed(std::shared_ptr<TimerInfo> timer,std::chrono::steady_clock::time_point nowElapsed)1057 void TimerManager::ReCalcuOriWhenElapsed(std::shared_ptr<TimerInfo> timer,
1058                                          std::chrono::steady_clock::time_point nowElapsed)
1059 {
1060     if (adjustPolicy_) {
1061         return;
1062     }
1063     auto whenElapsed = ConvertToElapsed(timer->origWhen, timer->type);
1064     steady_clock::time_point maxElapsed;
1065     if (timer->windowLength == milliseconds::zero()) {
1066         maxElapsed = whenElapsed;
1067     } else {
1068         maxElapsed = (timer->windowLength > milliseconds::zero()) ?
1069                      (whenElapsed + timer->windowLength) :
1070                      MaxTriggerTime(nowElapsed, whenElapsed, timer->repeatInterval);
1071     }
1072     timer->originWhenElapsed = whenElapsed;
1073     timer->originMaxWhenElapsed = maxElapsed;
1074 }
1075 
SetTimerExemption(const std::unordered_set<std::string> & nameArr,bool isExemption)1076 void TimerManager::SetTimerExemption(const std::unordered_set<std::string> &nameArr, bool isExemption)
1077 {
1078     std::lock_guard<std::mutex> lock(mutex_);
1079     TimerProxy::GetInstance().SetTimerExemption(nameArr, isExemption);
1080 }
1081 
AdjustSingleTimer(std::shared_ptr<TimerInfo> timer)1082 bool TimerManager::AdjustSingleTimer(std::shared_ptr<TimerInfo> timer)
1083 {
1084     if (!adjustPolicy_) {
1085         return false;
1086     }
1087     return TimerProxy::GetInstance().AdjustTimer(adjustPolicy_, adjustInterval_, GetBootTimeNs(),
1088         [this, timer] (AdjustTimerCallback adjustTimer) { adjustTimer(timer); });
1089 }
1090 
ResetAllProxy()1091 bool TimerManager::ResetAllProxy()
1092 {
1093     std::lock_guard<std::mutex> lock(mutex_);
1094     return TimerProxy::GetInstance().ResetAllProxy(GetBootTimeNs(),
1095         [this] (std::shared_ptr<TimerInfo> &alarm) { UpdateTimersState(alarm); });
1096 }
1097 
CheckAllowWhileIdle(const std::shared_ptr<TimerInfo> & alarm)1098 bool TimerManager::CheckAllowWhileIdle(const std::shared_ptr<TimerInfo> &alarm)
1099 {
1100 #ifdef DEVICE_STANDBY_ENABLE
1101     if (TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
1102         std::vector<DevStandbyMgr::AllowInfo> restrictList;
1103         DevStandbyMgr::StandbyServiceClient::GetInstance().GetRestrictList(DevStandbyMgr::AllowType::TIMER,
1104             restrictList, REASON_APP_API);
1105         auto it = std::find_if(restrictList.begin(), restrictList.end(),
1106             [&alarm](const DevStandbyMgr::AllowInfo &allowInfo) { return allowInfo.GetName() == alarm->bundleName; });
1107         if (it != restrictList.end()) {
1108             return false;
1109         }
1110     }
1111 
1112     if (TimePermission::CheckProxyCallingPermission()) {
1113         pid_t pid = IPCSkeleton::GetCallingPid();
1114         std::string procName = TimeFileUtils::GetNameByPid(pid);
1115         if (alarm->flags & static_cast<uint32_t>(INEXACT_REMINDER)) {
1116             return false;
1117         }
1118         std::vector<DevStandbyMgr::AllowInfo> restrictList;
1119         DevStandbyMgr::StandbyServiceClient::GetInstance().GetRestrictList(DevStandbyMgr::AllowType::TIMER,
1120             restrictList, REASON_NATIVE_API);
1121         auto it = std::find_if(restrictList.begin(), restrictList.end(),
1122             [procName](const DevStandbyMgr::AllowInfo &allowInfo) { return allowInfo.GetName() == procName; });
1123         if (it != restrictList.end()) {
1124             return false;
1125         }
1126     }
1127 #endif
1128     return true;
1129 }
1130 
1131 // needs to acquire the lock `mutex_` before calling this method
AdjustDeliveryTimeBasedOnDeviceIdle(const std::shared_ptr<TimerInfo> & alarm)1132 bool TimerManager::AdjustDeliveryTimeBasedOnDeviceIdle(const std::shared_ptr<TimerInfo> &alarm)
1133 {
1134     TIME_HILOGD(TIME_MODULE_SERVICE, "start adjust timer, uid=%{public}d, id=%{public}" PRId64 "",
1135         alarm->uid, alarm->id);
1136     if (mPendingIdleUntil_ == alarm) {
1137         return false;
1138     }
1139     if (mPendingIdleUntil_ == nullptr) {
1140         auto itMap = delayedTimers_.find(alarm->id);
1141         if (itMap != delayedTimers_.end()) {
1142             std::chrono::milliseconds currentTime;
1143             if (alarm->type == RTC || alarm->type == RTC_WAKEUP) {
1144                 currentTime = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
1145             } else {
1146                 currentTime = duration_cast<milliseconds>(GetBootTimeNs().time_since_epoch());
1147             }
1148 
1149             if (alarm->origWhen > currentTime) {
1150                 auto offset = alarm->origWhen - currentTime;
1151                 return alarm->UpdateWhenElapsedFromNow(GetBootTimeNs(), offset);
1152             }
1153             // 2 means the time of performing task.
1154             return alarm->UpdateWhenElapsedFromNow(GetBootTimeNs(), milliseconds(2));
1155         }
1156         return false;
1157     }
1158 
1159     if (CheckAllowWhileIdle(alarm)) {
1160         TIME_HILOGD(TIME_MODULE_SERVICE, "Timer unrestricted, not adjust. id=%{public}" PRId64 "", alarm->id);
1161         return false;
1162     } else if (alarm->whenElapsed > mPendingIdleUntil_->whenElapsed) {
1163         TIME_HILOGD(TIME_MODULE_SERVICE, "Timer not allowed, not adjust. id=%{public}" PRId64 "", alarm->id);
1164         return false;
1165     } else {
1166         TIME_HILOGD(TIME_MODULE_SERVICE, "Timer not allowed, id=%{public}" PRId64 "", alarm->id);
1167         delayedTimers_[alarm->id] = alarm->whenElapsed;
1168         auto offset = ConvertToElapsed(mPendingIdleUntil_->when, mPendingIdleUntil_->type) - GetBootTimeNs();
1169         return alarm->UpdateWhenElapsedFromNow(GetBootTimeNs(), offset);
1170     }
1171 }
1172 
1173 // needs to acquire the lock `mutex_` before calling this method
AdjustTimersBasedOnDeviceIdle()1174 bool TimerManager::AdjustTimersBasedOnDeviceIdle()
1175 {
1176     TIME_HILOGD(TIME_MODULE_SERVICE, "start adjust alarmBatches_.size=%{public}d",
1177         static_cast<int>(alarmBatches_.size()));
1178     bool isAdjust = false;
1179     for (const auto &batch : alarmBatches_) {
1180         auto n = batch->Size();
1181         for (unsigned int i = 0; i < n; i++) {
1182             auto alarm = batch->Get(i);
1183             isAdjust = AdjustDeliveryTimeBasedOnDeviceIdle(alarm) || isAdjust;
1184         }
1185     }
1186     return isAdjust;
1187 }
1188 
1189 // needs to acquire the lock `mutex_` before calling this method
AddBatchLocked(std::vector<std::shared_ptr<Batch>> & list,const std::shared_ptr<Batch> & newBatch)1190 bool AddBatchLocked(std::vector<std::shared_ptr<Batch>> &list, const std::shared_ptr<Batch> &newBatch)
1191 {
1192     auto it = std::upper_bound(list.begin(),
1193                                list.end(),
1194                                newBatch,
1195                                [](const std::shared_ptr<Batch> &first, const std::shared_ptr<Batch> &second) {
1196                                    return first->GetStart() < second->GetStart();
1197                                });
1198     list.insert(it, newBatch);
1199     return it == list.begin();
1200 }
1201 
MaxTriggerTime(steady_clock::time_point now,steady_clock::time_point triggerAtTime,milliseconds interval)1202 steady_clock::time_point MaxTriggerTime(steady_clock::time_point now,
1203                                         steady_clock::time_point triggerAtTime,
1204                                         milliseconds interval)
1205 {
1206     milliseconds futurity = (interval == milliseconds::zero()) ?
1207                             (duration_cast<milliseconds>(triggerAtTime - now)) : interval;
1208     if (futurity < MIN_FUZZABLE_INTERVAL) {
1209         futurity = milliseconds::zero();
1210     }
1211     return triggerAtTime + milliseconds(static_cast<long>(BATCH_WINDOW_COE * futurity.count()));
1212 }
1213 
ShowTimerEntryMap(int fd)1214 bool TimerManager::ShowTimerEntryMap(int fd)
1215 {
1216     TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
1217     std::lock_guard<std::mutex> lock(entryMapMutex_);
1218     auto iter = timerEntryMap_.begin();
1219     for (; iter != timerEntryMap_.end(); iter++) {
1220         dprintf(fd, " - dump timer number   = %lu\n", iter->first);
1221         dprintf(fd, " * timer id            = %lu\n", iter->second->id);
1222         dprintf(fd, " * timer type          = %d\n", iter->second->type);
1223         dprintf(fd, " * timer flag          = %lu\n", iter->second->flag);
1224         dprintf(fd, " * timer window Length = %lld\n", iter->second->windowLength);
1225         dprintf(fd, " * timer interval      = %lu\n", iter->second->interval);
1226         dprintf(fd, " * timer uid           = %d\n\n", iter->second->uid);
1227     }
1228     TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
1229     return true;
1230 }
1231 
ShowTimerEntryById(int fd,uint64_t timerId)1232 bool TimerManager::ShowTimerEntryById(int fd, uint64_t timerId)
1233 {
1234     TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
1235     std::lock_guard<std::mutex> lock(entryMapMutex_);
1236     auto iter = timerEntryMap_.find(timerId);
1237     if (iter == timerEntryMap_.end()) {
1238         TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
1239         return false;
1240     } else {
1241         dprintf(fd, " - dump timer number   = %lu\n", iter->first);
1242         dprintf(fd, " * timer id            = %lu\n", iter->second->id);
1243         dprintf(fd, " * timer type          = %d\n", iter->second->type);
1244         dprintf(fd, " * timer window Length = %lld\n", iter->second->windowLength);
1245         dprintf(fd, " * timer interval      = %lu\n", iter->second->interval);
1246         dprintf(fd, " * timer uid           = %d\n\n", iter->second->uid);
1247     }
1248     TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
1249     return true;
1250 }
1251 
ShowTimerTriggerById(int fd,uint64_t timerId)1252 bool TimerManager::ShowTimerTriggerById(int fd, uint64_t timerId)
1253 {
1254     TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
1255     std::lock_guard<std::mutex> lock(mutex_);
1256     for (size_t i = 0; i < alarmBatches_.size(); i++) {
1257         for (size_t j = 0; j < alarmBatches_[i]->Size(); j++) {
1258             if (alarmBatches_[i]->Get(j)->id == timerId) {
1259                 dprintf(fd, " - dump timer id   = %lu\n", alarmBatches_[i]->Get(j)->id);
1260                 dprintf(fd, " * timer trigger   = %lld\n", alarmBatches_[i]->Get(j)->origWhen);
1261             }
1262         }
1263     }
1264     TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
1265     return true;
1266 }
1267 
ShowIdleTimerInfo(int fd)1268 bool TimerManager::ShowIdleTimerInfo(int fd)
1269 {
1270     TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
1271     std::lock_guard<std::mutex> lock(mutex_);
1272     dprintf(fd, " - dump idle state         = %d\n", (mPendingIdleUntil_ != nullptr));
1273     if (mPendingIdleUntil_ != nullptr) {
1274         dprintf(fd, " - dump idle timer id  = %lu\n", mPendingIdleUntil_->id);
1275         dprintf(fd, " * timer type          = %d\n", mPendingIdleUntil_->type);
1276         dprintf(fd, " * timer flag          = %lu\n", mPendingIdleUntil_->flags);
1277         dprintf(fd, " * timer window Length = %lu\n", mPendingIdleUntil_->windowLength);
1278         dprintf(fd, " * timer interval      = %lu\n", mPendingIdleUntil_->repeatInterval);
1279         dprintf(fd, " * timer whenElapsed   = %lu\n", mPendingIdleUntil_->whenElapsed);
1280         dprintf(fd, " * timer uid           = %d\n\n", mPendingIdleUntil_->uid);
1281     }
1282     for (const auto &pendingTimer : pendingDelayTimers_) {
1283         dprintf(fd, " - dump pending delay timer id  = %lu\n", pendingTimer->id);
1284         dprintf(fd, " * timer type          = %d\n", pendingTimer->type);
1285         dprintf(fd, " * timer flag          = %lu\n", pendingTimer->flags);
1286         dprintf(fd, " * timer window Length = %lu\n", pendingTimer->windowLength);
1287         dprintf(fd, " * timer interval      = %lu\n", pendingTimer->repeatInterval);
1288         dprintf(fd, " * timer whenElapsed   = %lu\n", pendingTimer->whenElapsed);
1289         dprintf(fd, " * timer uid           = %d\n\n", pendingTimer->uid);
1290     }
1291     for (const auto &delayedTimer : delayedTimers_) {
1292         dprintf(fd, " - dump delayed timer id = %lu\n", delayedTimer.first);
1293         dprintf(fd, " * timer whenElapsed     = %lu\n", delayedTimer.second);
1294     }
1295     TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
1296     return true;
1297 }
1298 
HandleRSSDeath()1299 void TimerManager::HandleRSSDeath()
1300 {
1301     TIME_HILOGI(TIME_MODULE_CLIENT, "RSSSaDeathRecipient died.");
1302     uint64_t id = 0;
1303     {
1304         std::lock_guard <std::mutex> lock(mutex_);
1305         if (mPendingIdleUntil_ != nullptr) {
1306             id = mPendingIdleUntil_->id;
1307         } else {
1308             return;
1309         }
1310     }
1311     StopTimerInner(id, true);
1312 }
1313 
HandleRepeatTimer(const std::shared_ptr<TimerInfo> & timer,std::chrono::steady_clock::time_point nowElapsed)1314 void TimerManager::HandleRepeatTimer(
1315     const std::shared_ptr<TimerInfo> &timer, std::chrono::steady_clock::time_point nowElapsed)
1316 {
1317     if (timer->repeatInterval > milliseconds::zero()) {
1318         uint64_t count = 1 + static_cast<uint64_t>(
1319             duration_cast<milliseconds>(nowElapsed - timer->whenElapsed) / timer->repeatInterval);
1320         auto delta = count * timer->repeatInterval;
1321         auto nextElapsed = timer->whenElapsed + delta;
1322         SetHandlerLocked(timer->id, timer->type, timer->when + delta, nextElapsed, timer->windowLength,
1323             MaxTriggerTime(nowElapsed, nextElapsed, timer->repeatInterval), timer->repeatInterval, timer->callback,
1324             timer->wantAgent, timer->flags, timer->uid, timer->pid, timer->bundleName);
1325     } else {
1326         TimerProxy::GetInstance().RemoveUidTimerMap(timer);
1327         TimerProxy::GetInstance().RemovePidTimerMap(timer);
1328     }
1329 }
1330 
CheckNeedRecoverOnReboot(std::string bundleName,int type)1331 inline bool TimerManager::CheckNeedRecoverOnReboot(std::string bundleName, int type)
1332 {
1333     return (std::find(NEED_RECOVER_ON_REBOOT.begin(), NEED_RECOVER_ON_REBOOT.end(), bundleName) !=
1334         NEED_RECOVER_ON_REBOOT.end() && (type == RTC || type == RTC_WAKEUP));
1335 }
1336 
1337 #ifdef POWER_MANAGER_ENABLE
1338 // needs to acquire the lock `mutex_` before calling this method
HandleRunningLock(const std::shared_ptr<Batch> & firstWakeup)1339 void TimerManager::HandleRunningLock(const std::shared_ptr<Batch> &firstWakeup)
1340 {
1341     auto currentTime = duration_cast<nanoseconds>(GetBootTimeNs().time_since_epoch()).count();
1342     auto nextTimerOffset =
1343         duration_cast<nanoseconds>(firstWakeup->GetStart().time_since_epoch()).count() - currentTime;
1344     auto lockOffset = currentTime - lockExpiredTime_;
1345     if (nextTimerOffset > 0 && nextTimerOffset <= USE_LOCK_TIME_IN_NANO &&
1346         ((lockOffset < 0 && std::abs(lockOffset) <= nextTimerOffset) || lockOffset >= 0)) {
1347         auto firstAlarm = firstWakeup->Get(0);
1348         if (firstAlarm == nullptr) {
1349             TIME_HILOGI(TIME_MODULE_SERVICE, "first alarm is null");
1350             return;
1351         }
1352         auto holdLockTime = nextTimerOffset + ONE_HUNDRED_MILLI;
1353         TIME_HILOGI(TIME_MODULE_SERVICE, "runningLock time:%{public}" PRIu64 ", timerId:%{public}"
1354                     PRIu64", uid:%{public}d  bundleName=%{public}s", static_cast<uint64_t>(holdLockTime),
1355                     firstAlarm->id, firstAlarm->uid, firstAlarm->bundleName.c_str());
1356         lockExpiredTime_ = currentTime + holdLockTime;
1357         AddRunningLock(holdLockTime);
1358     }
1359 }
1360 
AddRunningLockRetry(long long holdLockTime)1361 void TimerManager::AddRunningLockRetry(long long holdLockTime)
1362 {
1363     auto retryRegister = [this, holdLockTime]() {
1364         for (int i = 0; i < POWER_RETRY_TIMES; i++) {
1365             usleep(POWER_RETRY_INTERVAL);
1366             runningLock_->Lock(static_cast<int32_t>(holdLockTime / NANO_TO_MILLI));
1367             if (runningLock_->IsUsed()) {
1368                 return;
1369             }
1370         }
1371     };
1372     std::thread thread(retryRegister);
1373     thread.detach();
1374 }
1375 
AddRunningLock(long long holdLockTime)1376 void TimerManager::AddRunningLock(long long holdLockTime)
1377 {
1378     if (runningLock_ == nullptr) {
1379         std::lock_guard<std::mutex> lock(runningLockMutex_);
1380         if (runningLock_ == nullptr) {
1381             TIME_HILOGI(TIME_MODULE_SERVICE, "runningLock is nullptr, create runningLock");
1382             runningLock_ = PowerMgr::PowerMgrClient::GetInstance().CreateRunningLock("timeServiceRunningLock",
1383                 PowerMgr::RunningLockType::RUNNINGLOCK_BACKGROUND_NOTIFICATION);
1384         }
1385     }
1386     if (runningLock_ != nullptr) {
1387         runningLock_->Lock(static_cast<int32_t>(holdLockTime / NANO_TO_MILLI));
1388         if (!runningLock_->IsUsed()) {
1389             AddRunningLockRetry(holdLockTime);
1390         }
1391     }
1392 }
1393 #endif
1394 } // MiscServices
1395 } // OHOS