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 {
__anon08b519a50202null108 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 ¶s)
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 ¶s,
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 }
221 TIME_HILOGI(TIME_MODULE_SERVICE,
222 "id: %{public}" PRIu64 " typ:%{public}d len: %{public}" PRId64 " int: %{public}" PRId64 " "
223 "flg :%{public}d trig: %{public}s uid:%{public}d pid:%{public}d",
224 timerId, timerInfo->type, timerInfo->windowLength, timerInfo->interval, timerInfo->flag,
225 std::to_string(triggerTime).c_str(), IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid());
226 {
227 // To prevent the same ID from being started repeatedly,
228 // the later start overwrites the earlier start.
229 std::lock_guard<std::mutex> lock(mutex_);
230 RemoveLocked(timerId, false);
231 }
232 SetHandler(timerInfo->id, timerInfo->type, triggerTime, timerInfo->windowLength, timerInfo->interval,
233 timerInfo->flag, timerInfo->callback, timerInfo->wantAgent, timerInfo->uid, timerInfo->pid,
234 timerInfo->bundleName);
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->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->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 } else {
657 std::lock_guard<std::mutex> lock(mutex_);
658 RescheduleKernelTimerLocked();
659 }
660 }
661 }
662
~TimerManager()663 TimerManager::~TimerManager()
664 {
665 if (alarmThread_ && alarmThread_->joinable()) {
666 runFlag_ = false;
667 alarmThread_->join();
668 }
669 }
670
GetBootTimeNs()671 steady_clock::time_point TimerManager::GetBootTimeNs()
672 {
673 int64_t timeNow = -1;
674 struct timespec tv {};
675 if (clock_gettime(CLOCK_BOOTTIME, &tv) < 0) {
676 return steady_clock::now();
677 }
678 timeNow = tv.tv_sec * NANO_TO_SECOND + tv.tv_nsec;
679 steady_clock::time_point tp_epoch ((nanoseconds(timeNow)));
680 return tp_epoch;
681 }
682
683 // needs to acquire the lock `mutex_` before calling this method
TriggerIdleTimer()684 void TimerManager::TriggerIdleTimer()
685 {
686 TIME_HILOGI(TIME_MODULE_SERVICE, "Idle alarm triggers.");
687 mPendingIdleUntil_ = nullptr;
688 delayedTimers_.clear();
689 std::for_each(pendingDelayTimers_.begin(), pendingDelayTimers_.end(),
690 [this](const std::shared_ptr<TimerInfo> &pendingTimer) {
691 TIME_HILOGI(TIME_MODULE_SERVICE, "Set timer from delay list, id=%{public}" PRId64 "", pendingTimer->id);
692 if (pendingTimer->whenElapsed > GetBootTimeNs()) {
693 pendingTimer->UpdateWhenElapsedFromNow(GetBootTimeNs(), pendingTimer->offset);
694 } else {
695 // 2 means the time of performing task.
696 pendingTimer->UpdateWhenElapsedFromNow(GetBootTimeNs(), milliseconds(2));
697 }
698 SetHandlerLocked(pendingTimer, false, false);
699 });
700 pendingDelayTimers_.clear();
701 ReBatchAllTimers();
702 }
703
704 // needs to acquire the lock `mutex_` before calling this method
ProcTriggerTimer(std::shared_ptr<TimerInfo> & alarm,const std::chrono::steady_clock::time_point & nowElapsed)705 bool TimerManager::ProcTriggerTimer(std::shared_ptr<TimerInfo> &alarm,
706 const std::chrono::steady_clock::time_point &nowElapsed)
707 {
708 if (mPendingIdleUntil_ != nullptr && mPendingIdleUntil_->id == alarm->id) {
709 TriggerIdleTimer();
710 }
711 if (TimerProxy::GetInstance().IsUidProxy(alarm->uid)) {
712 alarm->UpdateWhenElapsedFromNow(nowElapsed, milliseconds(TimerProxy::GetInstance().GetProxyDelayTime()));
713 TIME_HILOGD(TIME_MODULE_SERVICE, "UpdateWhenElapsed for proxy timer trigger. "
714 "uid= %{public}d, id=%{public}" PRId64 ", timer whenElapsed=%{public}lld, now=%{public}lld",
715 alarm->uid, alarm->id, alarm->whenElapsed.time_since_epoch().count(),
716 nowElapsed.time_since_epoch().count());
717 SetHandlerLocked(alarm, false, false);
718 return false;
719 } else if (TimerProxy::GetInstance().IsPidProxy(alarm->pid)) {
720 alarm->UpdateWhenElapsedFromNow(nowElapsed, milliseconds(TimerProxy::GetInstance().GetProxyDelayTime()));
721 TIME_HILOGD(TIME_MODULE_SERVICE, "UpdateWhenElapsed for proxy timer trigger. "
722 "pid= %{public}d, id=%{public}" PRId64 ", timer whenElapsed=%{public}lld, now=%{public}lld",
723 alarm->pid, alarm->id, alarm->whenElapsed.time_since_epoch().count(),
724 nowElapsed.time_since_epoch().count());
725 SetHandlerLocked(alarm, false, false);
726 return false;
727 } else {
728 HandleRepeatTimer(alarm, nowElapsed);
729 return true;
730 }
731 }
732
733 // 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)734 bool TimerManager::TriggerTimersLocked(std::vector<std::shared_ptr<TimerInfo>> &triggerList,
735 std::chrono::steady_clock::time_point nowElapsed)
736 {
737 bool hasWakeup = false;
738 TIME_HILOGD(TIME_MODULE_SERVICE, "current time %{public}lld", GetBootTimeNs().time_since_epoch().count());
739
740 for (auto iter = alarmBatches_.begin(); iter != alarmBatches_.end();) {
741 if (*iter == nullptr) {
742 TIME_HILOGE(TIME_MODULE_SERVICE, "alarmBatches_ has nullptr");
743 iter = alarmBatches_.erase(iter);
744 continue;
745 }
746 if ((*iter)->GetStart() > nowElapsed) {
747 ++iter;
748 continue;
749 }
750 auto batch = *iter;
751 iter = alarmBatches_.erase(iter);
752 TIME_HILOGD(
753 TIME_MODULE_SERVICE, "batch size= %{public}d", static_cast<int>(alarmBatches_.size()));
754 const auto n = batch->Size();
755 for (unsigned int i = 0; i < n; ++i) {
756 auto alarm = batch->Get(i);
757 triggerList.push_back(alarm);
758 TIME_SIMPLIFY_HILOGI(TIME_MODULE_SERVICE, "uid: %{public}d id:%{public}" PRId64 " name:%{public}s"
759 " wk:%{public}u",
760 alarm->uid, alarm->id, alarm->bundleName.c_str(), alarm->wakeup);
761
762 if (alarm->wakeup) {
763 hasWakeup = true;
764 }
765 }
766 }
767 for (auto iter = triggerList.begin(); iter != triggerList.end();) {
768 auto alarm = *iter;
769 if (!ProcTriggerTimer(alarm, nowElapsed)) {
770 iter = triggerList.erase(iter);
771 } else {
772 ++iter;
773 }
774 }
775
776 std::sort(triggerList.begin(), triggerList.end(),
777 [](const std::shared_ptr<TimerInfo> &l, const std::shared_ptr<TimerInfo> &r) {
778 return l->whenElapsed < r->whenElapsed;
779 });
780
781 return hasWakeup;
782 }
783
784 // needs to acquire the lock `mutex_` before calling this method
RescheduleKernelTimerLocked()785 void TimerManager::RescheduleKernelTimerLocked()
786 {
787 auto nextNonWakeup = std::chrono::steady_clock::time_point::min();
788 auto bootTime = GetBootTimeNs();
789 if (!alarmBatches_.empty()) {
790 auto firstWakeup = FindFirstWakeupBatchLocked();
791 auto firstBatch = alarmBatches_.front();
792 if (firstWakeup != nullptr) {
793 #ifdef POWER_MANAGER_ENABLE
794 HandleRunningLock(firstWakeup);
795 #endif
796 SetLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup->GetStart().time_since_epoch(), bootTime);
797 }
798 if (firstBatch != firstWakeup) {
799 nextNonWakeup = firstBatch->GetStart();
800 }
801 }
802
803 if (nextNonWakeup != std::chrono::steady_clock::time_point::min()) {
804 SetLocked(ELAPSED_REALTIME, nextNonWakeup.time_since_epoch(), bootTime);
805 }
806 }
807
808 // needs to acquire the lock `mutex_` before calling this method
FindFirstWakeupBatchLocked()809 std::shared_ptr<Batch> TimerManager::FindFirstWakeupBatchLocked()
810 {
811 auto it = std::find_if(alarmBatches_.begin(),
812 alarmBatches_.end(),
813 [](const std::shared_ptr<Batch> &batch) {
814 return batch->HasWakeups();
815 });
816 return (it != alarmBatches_.end()) ? *it : nullptr;
817 }
818
SetLocked(int type,std::chrono::nanoseconds when,std::chrono::steady_clock::time_point bootTime)819 void TimerManager::SetLocked(int type, std::chrono::nanoseconds when, std::chrono::steady_clock::time_point bootTime)
820 {
821 handler_->Set(static_cast<uint32_t>(type), when, bootTime);
822 }
823
824 // needs to acquire the lock `mutex_` before calling this method
InsertAndBatchTimerLocked(std::shared_ptr<TimerInfo> alarm)825 void TimerManager::InsertAndBatchTimerLocked(std::shared_ptr<TimerInfo> alarm)
826 {
827 int64_t whichBatch = (alarm->flags & static_cast<uint32_t>(STANDALONE)) ?
828 -1 :
829 AttemptCoalesceLocked(alarm->whenElapsed, alarm->maxWhenElapsed);
830 TIME_SIMPLIFY_HILOGI(TIME_MODULE_SERVICE, "bat: %{public}" PRId64 " id:%{public}" PRIu64 " "
831 "we:%{public}lld mwe:%{public}lld",
832 whichBatch, alarm->id, alarm->whenElapsed.time_since_epoch().count(),
833 alarm->maxWhenElapsed.time_since_epoch().count());
834 if (whichBatch < 0) {
835 AddBatchLocked(alarmBatches_, std::make_shared<Batch>(*alarm));
836 } else {
837 auto batch = alarmBatches_.at(whichBatch);
838 if (batch->Add(alarm)) {
839 alarmBatches_.erase(alarmBatches_.begin() + whichBatch);
840 AddBatchLocked(alarmBatches_, batch);
841 }
842 }
843 }
844
845 // 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)846 int64_t TimerManager::AttemptCoalesceLocked(std::chrono::steady_clock::time_point whenElapsed,
847 std::chrono::steady_clock::time_point maxWhen)
848 {
849 auto it = std::find_if(alarmBatches_.begin(), alarmBatches_.end(),
850 [whenElapsed, maxWhen](const std::shared_ptr<Batch> &batch) {
851 return (batch->GetFlags() & static_cast<uint32_t>(STANDALONE)) == 0 &&
852 (batch->CanHold(whenElapsed, maxWhen));
853 });
854 if (it != alarmBatches_.end()) {
855 return std::distance(alarmBatches_.begin(), it);
856 }
857 return -1;
858 }
859
NotifyWantAgentRetry(std::shared_ptr<TimerInfo> timer)860 void TimerManager::NotifyWantAgentRetry(std::shared_ptr<TimerInfo> timer)
861 {
862 auto retryRegister = [timer]() {
863 for (int i = 0; i < WANT_RETRY_TIMES; i++) {
864 sleep(WANT_RETRY_INTERVAL << i);
865 if (TimerManager::GetInstance()->NotifyWantAgent(timer)) {
866 return;
867 }
868 }
869 };
870 std::thread thread(retryRegister);
871 thread.detach();
872 }
873
CheckUserIdForNotify(const std::shared_ptr<TimerInfo> & timer)874 int32_t TimerManager::CheckUserIdForNotify(const std::shared_ptr<TimerInfo> &timer)
875 {
876 int userIdOfTimer = -1;
877 int foregroundUserId = -1;
878 int getLocalIdErr = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(timer->uid, userIdOfTimer);
879 if (getLocalIdErr != ERR_OK) {
880 TIME_HILOGE(TIME_MODULE_SERVICE, "Get account id from uid failed, errcode: %{public}d", getLocalIdErr);
881 return E_TIME_ACCOUNT_ERROR;
882 }
883 int getForegroundIdErr = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(foregroundUserId);
884 if (getForegroundIdErr != ERR_OK) {
885 TIME_HILOGE(TIME_MODULE_SERVICE, "Get foreground account id failed, errcode: %{public}d", getForegroundIdErr);
886 return E_TIME_ACCOUNT_ERROR;
887 }
888 if (userIdOfTimer == foregroundUserId || userIdOfTimer == SYSTEM_USER_ID) {
889 return E_TIME_OK;
890 } else {
891 TIME_HILOGI(TIME_MODULE_SERVICE, "WA wait switch user, uid: %{public}d, timerId: %{public}" PRId64,
892 timer->uid, timer->id);
893 return E_TIME_ACCOUNT_NOT_MATCH;
894 }
895 }
896
DeliverTimersLocked(const std::vector<std::shared_ptr<TimerInfo>> & triggerList)897 void TimerManager::DeliverTimersLocked(const std::vector<std::shared_ptr<TimerInfo>> &triggerList)
898 {
899 auto wakeupNums = std::count_if(triggerList.begin(), triggerList.end(), [](auto timer) {return timer->wakeup;});
900 for (const auto &timer : triggerList) {
901 if (timer->wakeup) {
902 #ifdef POWER_MANAGER_ENABLE
903 TIME_HILOGD(TIME_MODULE_SERVICE, "id: %{public}" PRId64 ", uid: %{public}d bundleName: %{public}s",
904 timer->id, timer->uid, timer->bundleName.c_str());
905 AddRunningLock(USE_LOCK_ONE_SEC_IN_NANO);
906 #endif
907 StatisticReporter(IPCSkeleton::GetCallingPid(), wakeupNums, timer);
908 }
909 if (timer->callback) {
910 if (TimerProxy::GetInstance().CallbackAlarmIfNeed(timer) == PEER_END_DEAD
911 && !timer->wantAgent) {
912 DestroyTimer(timer->id);
913 continue;
914 }
915 }
916 if (timer->wantAgent) {
917 if (!NotifyWantAgent(timer) && CheckNeedRecoverOnReboot(timer->bundleName, timer->type)) {
918 NotifyWantAgentRetry(timer);
919 }
920 if (CheckNeedRecoverOnReboot(timer->bundleName, timer->type)) {
921 OHOS::NativeRdb::ValuesBucket values;
922 values.PutInt("state", 0);
923 OHOS::NativeRdb::RdbPredicates rdbPredicates(HOLD_ON_REBOOT);
924 rdbPredicates.EqualTo("state", 1)
925 ->And()
926 ->EqualTo("timerId", static_cast<int64_t>(timer->id));
927 TimeDatabase::GetInstance().Update(values, rdbPredicates);
928 } else {
929 OHOS::NativeRdb::ValuesBucket values;
930 values.PutInt("state", 0);
931 OHOS::NativeRdb::RdbPredicates rdbPredicates(DROP_ON_REBOOT);
932 rdbPredicates.EqualTo("state", 1)
933 ->And()
934 ->EqualTo("timerId", static_cast<int64_t>(timer->id));
935 TimeDatabase::GetInstance().Update(values, rdbPredicates);
936 }
937 }
938 if (((timer->flags & static_cast<uint32_t>(IS_DISPOSABLE)) > 0) &&
939 (timer->repeatInterval == milliseconds::zero())) {
940 DestroyTimer(timer->id);
941 }
942 }
943 }
944
NotifyWantAgent(const std::shared_ptr<TimerInfo> & timer)945 bool TimerManager::NotifyWantAgent(const std::shared_ptr<TimerInfo> &timer)
946 {
947 TIME_HILOGD(TIME_MODULE_SERVICE, "trigger wantAgent.");
948 auto wantAgent = timer->wantAgent;
949 std::shared_ptr<AAFwk::Want> want = OHOS::AbilityRuntime::WantAgent::WantAgentHelper::GetWant(wantAgent);
950 if (want == nullptr) {
951 switch (CheckUserIdForNotify(timer)) {
952 case E_TIME_ACCOUNT_NOT_MATCH:
953 // No need to retry.
954 return true;
955 case E_TIME_ACCOUNT_ERROR:
956 TIME_HILOGE(TIME_MODULE_SERVICE, "want is nullptr, id=%{public}" PRId64 "", timer->id);
957 return false;
958 default:
959 break;
960 }
961 auto database = TimeDatabase::GetInstance();
962 OHOS::NativeRdb::RdbPredicates holdRdbPredicates(HOLD_ON_REBOOT);
963 holdRdbPredicates.EqualTo("timerId", static_cast<int64_t>(timer->id));
964 auto holdResultSet = database.Query(holdRdbPredicates, ALL_DATA);
965 if (holdResultSet == nullptr || holdResultSet->GoToFirstRow() != OHOS::NativeRdb::E_OK) {
966 TIME_HILOGE(TIME_MODULE_SERVICE, "db query failed nullptr");
967 if (holdResultSet != nullptr) {
968 holdResultSet->Close();
969 }
970 return false;
971 }
972 // Line 7 is 'wantAgent'
973 wantAgent = OHOS::AbilityRuntime::WantAgent::WantAgentHelper::FromString(GetString(holdResultSet, 7));
974 holdResultSet->Close();
975 switch (CheckUserIdForNotify(timer)) {
976 case E_TIME_ACCOUNT_NOT_MATCH:
977 TIME_HILOGI(TIME_MODULE_SERVICE, "user sw after FS, id=%{public}" PRId64 "", timer->id);
978 // No need to retry.
979 return true;
980 case E_TIME_ACCOUNT_ERROR:
981 TIME_HILOGE(TIME_MODULE_SERVICE, "want is nullptr, id=%{public}" PRId64 "", timer->id);
982 return false;
983 default:
984 break;
985 }
986 want = OHOS::AbilityRuntime::WantAgent::WantAgentHelper::GetWant(wantAgent);
987 if (want == nullptr) {
988 TIME_HILOGE(TIME_MODULE_SERVICE, "want is nullptr, id=%{public}" PRId64 "", timer->id);
989 return false;
990 }
991 }
992 OHOS::AbilityRuntime::WantAgent::TriggerInfo paramsInfo("", nullptr, want, WANTAGENT_CODE_ELEVEN);
993 auto code = AbilityRuntime::WantAgent::WantAgentHelper::TriggerWantAgent(wantAgent, nullptr, paramsInfo);
994 TIME_SIMPLIFY_HILOGI(TIME_MODULE_SERVICE, "trigWA ret: %{public}d", code);
995 return code == ERR_OK;
996 }
997
998 // needs to acquire the lock `mutex_` before calling this method
UpdateTimersState(std::shared_ptr<TimerInfo> & alarm)999 void TimerManager::UpdateTimersState(std::shared_ptr<TimerInfo> &alarm)
1000 {
1001 RemoveLocked(alarm->id, false);
1002 AdjustSingleTimer(alarm);
1003 InsertAndBatchTimerLocked(alarm);
1004 RescheduleKernelTimerLocked();
1005 }
1006
ProxyTimer(int32_t uid,bool isProxy,bool needRetrigger)1007 bool TimerManager::ProxyTimer(int32_t uid, bool isProxy, bool needRetrigger)
1008 {
1009 std::lock_guard<std::mutex> lock(mutex_);
1010 return TimerProxy::GetInstance().ProxyTimer(uid, isProxy, needRetrigger, GetBootTimeNs(),
1011 [this] (std::shared_ptr<TimerInfo> &alarm) { UpdateTimersState(alarm); });
1012 }
1013
AdjustTimer(bool isAdjust,uint32_t interval)1014 bool TimerManager::AdjustTimer(bool isAdjust, uint32_t interval)
1015 {
1016 std::lock_guard<std::mutex> lock(mutex_);
1017 if (adjustPolicy_ == isAdjust && adjustInterval_ == interval) {
1018 TIME_HILOGI(TIME_MODULE_SERVICE, "already deal timer adjust, flag: %{public}d", isAdjust);
1019 return false;
1020 }
1021 std::chrono::steady_clock::time_point now = GetBootTimeNs();
1022 adjustPolicy_ = isAdjust;
1023 adjustInterval_ = interval;
1024 auto callback = [this] (AdjustTimerCallback adjustTimer) {
1025 bool isChanged = false;
1026 auto nowElapsed = GetBootTimeNs();
1027 for (const auto &batch : alarmBatches_) {
1028 if (!batch) {
1029 continue;
1030 }
1031 auto n = batch->Size();
1032 for (unsigned int i = 0; i < n; i++) {
1033 auto timer = batch->Get(i);
1034 ReCalcuOriWhenElapsed(timer, nowElapsed);
1035 isChanged = adjustTimer(timer) || isChanged;
1036 }
1037 }
1038 if (isChanged) {
1039 TIME_HILOGI(TIME_MODULE_SERVICE, "timer adjust executing, policy: %{public}d", adjustPolicy_);
1040 ReBatchAllTimers();
1041 }
1042 };
1043
1044 return TimerProxy::GetInstance().AdjustTimer(isAdjust, interval, now, callback);
1045 }
1046
ProxyTimer(int32_t uid,std::set<int> pidList,bool isProxy,bool needRetrigger)1047 bool TimerManager::ProxyTimer(int32_t uid, std::set<int> pidList, bool isProxy, bool needRetrigger)
1048 {
1049 std::set<int> failurePid;
1050 std::lock_guard<std::mutex> lock(mutex_);
1051 for (std::set<int>::iterator pid = pidList.begin(); pid != pidList.end(); ++pid) {
1052 if (!TimerProxy::GetInstance().PidProxyTimer(uid, *pid, isProxy, needRetrigger, GetBootTimeNs(),
1053 [this] (std::shared_ptr<TimerInfo> &alarm) { UpdateTimersState(alarm); })) {
1054 failurePid.insert(*pid);
1055 }
1056 }
1057 return (failurePid.size() == 0);
1058 }
1059
ReCalcuOriWhenElapsed(std::shared_ptr<TimerInfo> timer,std::chrono::steady_clock::time_point nowElapsed)1060 void TimerManager::ReCalcuOriWhenElapsed(std::shared_ptr<TimerInfo> timer,
1061 std::chrono::steady_clock::time_point nowElapsed)
1062 {
1063 if (adjustPolicy_) {
1064 return;
1065 }
1066 auto whenElapsed = ConvertToElapsed(timer->origWhen, timer->type);
1067 steady_clock::time_point maxElapsed;
1068 if (timer->windowLength == milliseconds::zero()) {
1069 maxElapsed = whenElapsed;
1070 } else {
1071 maxElapsed = (timer->windowLength > milliseconds::zero()) ?
1072 (whenElapsed + timer->windowLength) :
1073 MaxTriggerTime(nowElapsed, whenElapsed, timer->repeatInterval);
1074 }
1075 timer->originWhenElapsed = whenElapsed;
1076 timer->originMaxWhenElapsed = maxElapsed;
1077 }
1078
SetTimerExemption(const std::unordered_set<std::string> & nameArr,bool isExemption)1079 void TimerManager::SetTimerExemption(const std::unordered_set<std::string> &nameArr, bool isExemption)
1080 {
1081 std::lock_guard<std::mutex> lock(mutex_);
1082 TimerProxy::GetInstance().SetTimerExemption(nameArr, isExemption);
1083 }
1084
AdjustSingleTimer(std::shared_ptr<TimerInfo> timer)1085 bool TimerManager::AdjustSingleTimer(std::shared_ptr<TimerInfo> timer)
1086 {
1087 if (!adjustPolicy_) {
1088 return false;
1089 }
1090 return TimerProxy::GetInstance().AdjustTimer(adjustPolicy_, adjustInterval_, GetBootTimeNs(),
1091 [this, timer] (AdjustTimerCallback adjustTimer) { adjustTimer(timer); });
1092 }
1093
ResetAllProxy()1094 bool TimerManager::ResetAllProxy()
1095 {
1096 std::lock_guard<std::mutex> lock(mutex_);
1097 return TimerProxy::GetInstance().ResetAllProxy(GetBootTimeNs(),
1098 [this] (std::shared_ptr<TimerInfo> &alarm) { UpdateTimersState(alarm); });
1099 }
1100
CheckAllowWhileIdle(const std::shared_ptr<TimerInfo> & alarm)1101 bool TimerManager::CheckAllowWhileIdle(const std::shared_ptr<TimerInfo> &alarm)
1102 {
1103 #ifdef DEVICE_STANDBY_ENABLE
1104 if (TimePermission::CheckSystemUidCallingPermission(IPCSkeleton::GetCallingFullTokenID())) {
1105 std::vector<DevStandbyMgr::AllowInfo> restrictList;
1106 DevStandbyMgr::StandbyServiceClient::GetInstance().GetRestrictList(DevStandbyMgr::AllowType::TIMER,
1107 restrictList, REASON_APP_API);
1108 auto it = std::find_if(restrictList.begin(), restrictList.end(),
1109 [&alarm](const DevStandbyMgr::AllowInfo &allowInfo) { return allowInfo.GetName() == alarm->bundleName; });
1110 if (it != restrictList.end()) {
1111 return false;
1112 }
1113 }
1114
1115 if (TimePermission::CheckProxyCallingPermission()) {
1116 pid_t pid = IPCSkeleton::GetCallingPid();
1117 std::string procName = TimeFileUtils::GetNameByPid(pid);
1118 if (alarm->flags & static_cast<uint32_t>(INEXACT_REMINDER)) {
1119 return false;
1120 }
1121 std::vector<DevStandbyMgr::AllowInfo> restrictList;
1122 DevStandbyMgr::StandbyServiceClient::GetInstance().GetRestrictList(DevStandbyMgr::AllowType::TIMER,
1123 restrictList, REASON_NATIVE_API);
1124 auto it = std::find_if(restrictList.begin(), restrictList.end(),
1125 [procName](const DevStandbyMgr::AllowInfo &allowInfo) { return allowInfo.GetName() == procName; });
1126 if (it != restrictList.end()) {
1127 return false;
1128 }
1129 }
1130 #endif
1131 return true;
1132 }
1133
1134 // needs to acquire the lock `mutex_` before calling this method
AdjustDeliveryTimeBasedOnDeviceIdle(const std::shared_ptr<TimerInfo> & alarm)1135 bool TimerManager::AdjustDeliveryTimeBasedOnDeviceIdle(const std::shared_ptr<TimerInfo> &alarm)
1136 {
1137 TIME_HILOGD(TIME_MODULE_SERVICE, "start adjust timer, uid=%{public}d, id=%{public}" PRId64 "",
1138 alarm->uid, alarm->id);
1139 if (mPendingIdleUntil_ == alarm) {
1140 return false;
1141 }
1142 if (mPendingIdleUntil_ == nullptr) {
1143 auto itMap = delayedTimers_.find(alarm->id);
1144 if (itMap != delayedTimers_.end()) {
1145 std::chrono::milliseconds currentTime;
1146 if (alarm->type == RTC || alarm->type == RTC_WAKEUP) {
1147 currentTime = duration_cast<milliseconds>(system_clock::now().time_since_epoch());
1148 } else {
1149 currentTime = duration_cast<milliseconds>(GetBootTimeNs().time_since_epoch());
1150 }
1151
1152 if (alarm->origWhen > currentTime) {
1153 auto offset = alarm->origWhen - currentTime;
1154 return alarm->UpdateWhenElapsedFromNow(GetBootTimeNs(), offset);
1155 }
1156 // 2 means the time of performing task.
1157 return alarm->UpdateWhenElapsedFromNow(GetBootTimeNs(), milliseconds(2));
1158 }
1159 return false;
1160 }
1161
1162 if (CheckAllowWhileIdle(alarm)) {
1163 TIME_HILOGD(TIME_MODULE_SERVICE, "Timer unrestricted, not adjust. id=%{public}" PRId64 "", alarm->id);
1164 return false;
1165 } else if (alarm->whenElapsed > mPendingIdleUntil_->whenElapsed) {
1166 TIME_HILOGD(TIME_MODULE_SERVICE, "Timer not allowed, not adjust. id=%{public}" PRId64 "", alarm->id);
1167 return false;
1168 } else {
1169 TIME_HILOGD(TIME_MODULE_SERVICE, "Timer not allowed, id=%{public}" PRId64 "", alarm->id);
1170 delayedTimers_[alarm->id] = alarm->whenElapsed;
1171 auto offset = ConvertToElapsed(mPendingIdleUntil_->when, mPendingIdleUntil_->type) - GetBootTimeNs();
1172 return alarm->UpdateWhenElapsedFromNow(GetBootTimeNs(), offset);
1173 }
1174 }
1175
1176 // needs to acquire the lock `mutex_` before calling this method
AdjustTimersBasedOnDeviceIdle()1177 bool TimerManager::AdjustTimersBasedOnDeviceIdle()
1178 {
1179 TIME_HILOGD(TIME_MODULE_SERVICE, "start adjust alarmBatches_.size=%{public}d",
1180 static_cast<int>(alarmBatches_.size()));
1181 bool isAdjust = false;
1182 for (const auto &batch : alarmBatches_) {
1183 auto n = batch->Size();
1184 for (unsigned int i = 0; i < n; i++) {
1185 auto alarm = batch->Get(i);
1186 isAdjust = AdjustDeliveryTimeBasedOnDeviceIdle(alarm) || isAdjust;
1187 }
1188 }
1189 return isAdjust;
1190 }
1191
1192 // needs to acquire the lock `mutex_` before calling this method
AddBatchLocked(std::vector<std::shared_ptr<Batch>> & list,const std::shared_ptr<Batch> & newBatch)1193 bool AddBatchLocked(std::vector<std::shared_ptr<Batch>> &list, const std::shared_ptr<Batch> &newBatch)
1194 {
1195 auto it = std::upper_bound(list.begin(),
1196 list.end(),
1197 newBatch,
1198 [](const std::shared_ptr<Batch> &first, const std::shared_ptr<Batch> &second) {
1199 return first->GetStart() < second->GetStart();
1200 });
1201 list.insert(it, newBatch);
1202 return it == list.begin();
1203 }
1204
MaxTriggerTime(steady_clock::time_point now,steady_clock::time_point triggerAtTime,milliseconds interval)1205 steady_clock::time_point MaxTriggerTime(steady_clock::time_point now,
1206 steady_clock::time_point triggerAtTime,
1207 milliseconds interval)
1208 {
1209 milliseconds futurity = (interval == milliseconds::zero()) ?
1210 (duration_cast<milliseconds>(triggerAtTime - now)) : interval;
1211 if (futurity < MIN_FUZZABLE_INTERVAL) {
1212 futurity = milliseconds::zero();
1213 }
1214 return triggerAtTime + milliseconds(static_cast<long>(BATCH_WINDOW_COE * futurity.count()));
1215 }
1216
ShowTimerEntryMap(int fd)1217 bool TimerManager::ShowTimerEntryMap(int fd)
1218 {
1219 TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
1220 std::lock_guard<std::mutex> lock(entryMapMutex_);
1221 auto iter = timerEntryMap_.begin();
1222 for (; iter != timerEntryMap_.end(); iter++) {
1223 dprintf(fd, " - dump timer number = %lu\n", iter->first);
1224 dprintf(fd, " * timer id = %lu\n", iter->second->id);
1225 dprintf(fd, " * timer type = %d\n", iter->second->type);
1226 dprintf(fd, " * timer flag = %lu\n", iter->second->flag);
1227 dprintf(fd, " * timer window Length = %lld\n", iter->second->windowLength);
1228 dprintf(fd, " * timer interval = %lu\n", iter->second->interval);
1229 dprintf(fd, " * timer uid = %d\n\n", iter->second->uid);
1230 }
1231 TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
1232 return true;
1233 }
1234
ShowTimerEntryById(int fd,uint64_t timerId)1235 bool TimerManager::ShowTimerEntryById(int fd, uint64_t timerId)
1236 {
1237 TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
1238 std::lock_guard<std::mutex> lock(entryMapMutex_);
1239 auto iter = timerEntryMap_.find(timerId);
1240 if (iter == timerEntryMap_.end()) {
1241 TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
1242 return false;
1243 } else {
1244 dprintf(fd, " - dump timer number = %lu\n", iter->first);
1245 dprintf(fd, " * timer id = %lu\n", iter->second->id);
1246 dprintf(fd, " * timer type = %d\n", iter->second->type);
1247 dprintf(fd, " * timer window Length = %lld\n", iter->second->windowLength);
1248 dprintf(fd, " * timer interval = %lu\n", iter->second->interval);
1249 dprintf(fd, " * timer uid = %d\n\n", iter->second->uid);
1250 }
1251 TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
1252 return true;
1253 }
1254
ShowTimerTriggerById(int fd,uint64_t timerId)1255 bool TimerManager::ShowTimerTriggerById(int fd, uint64_t timerId)
1256 {
1257 TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
1258 std::lock_guard<std::mutex> lock(mutex_);
1259 for (size_t i = 0; i < alarmBatches_.size(); i++) {
1260 for (size_t j = 0; j < alarmBatches_[i]->Size(); j++) {
1261 if (alarmBatches_[i]->Get(j)->id == timerId) {
1262 dprintf(fd, " - dump timer id = %lu\n", alarmBatches_[i]->Get(j)->id);
1263 dprintf(fd, " * timer trigger = %lld\n", alarmBatches_[i]->Get(j)->origWhen);
1264 }
1265 }
1266 }
1267 TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
1268 return true;
1269 }
1270
ShowIdleTimerInfo(int fd)1271 bool TimerManager::ShowIdleTimerInfo(int fd)
1272 {
1273 TIME_HILOGD(TIME_MODULE_SERVICE, "start.");
1274 std::lock_guard<std::mutex> lock(mutex_);
1275 dprintf(fd, " - dump idle state = %d\n", (mPendingIdleUntil_ != nullptr));
1276 if (mPendingIdleUntil_ != nullptr) {
1277 dprintf(fd, " - dump idle timer id = %lu\n", mPendingIdleUntil_->id);
1278 dprintf(fd, " * timer type = %d\n", mPendingIdleUntil_->type);
1279 dprintf(fd, " * timer flag = %lu\n", mPendingIdleUntil_->flags);
1280 dprintf(fd, " * timer window Length = %lu\n", mPendingIdleUntil_->windowLength);
1281 dprintf(fd, " * timer interval = %lu\n", mPendingIdleUntil_->repeatInterval);
1282 dprintf(fd, " * timer whenElapsed = %lu\n", mPendingIdleUntil_->whenElapsed);
1283 dprintf(fd, " * timer uid = %d\n\n", mPendingIdleUntil_->uid);
1284 }
1285 for (const auto &pendingTimer : pendingDelayTimers_) {
1286 dprintf(fd, " - dump pending delay timer id = %lu\n", pendingTimer->id);
1287 dprintf(fd, " * timer type = %d\n", pendingTimer->type);
1288 dprintf(fd, " * timer flag = %lu\n", pendingTimer->flags);
1289 dprintf(fd, " * timer window Length = %lu\n", pendingTimer->windowLength);
1290 dprintf(fd, " * timer interval = %lu\n", pendingTimer->repeatInterval);
1291 dprintf(fd, " * timer whenElapsed = %lu\n", pendingTimer->whenElapsed);
1292 dprintf(fd, " * timer uid = %d\n\n", pendingTimer->uid);
1293 }
1294 for (const auto &delayedTimer : delayedTimers_) {
1295 dprintf(fd, " - dump delayed timer id = %lu\n", delayedTimer.first);
1296 dprintf(fd, " * timer whenElapsed = %lu\n", delayedTimer.second);
1297 }
1298 TIME_HILOGD(TIME_MODULE_SERVICE, "end.");
1299 return true;
1300 }
1301
HandleRSSDeath()1302 void TimerManager::HandleRSSDeath()
1303 {
1304 TIME_HILOGI(TIME_MODULE_CLIENT, "RSSSaDeathRecipient died.");
1305 uint64_t id = 0;
1306 {
1307 std::lock_guard <std::mutex> lock(mutex_);
1308 if (mPendingIdleUntil_ != nullptr) {
1309 id = mPendingIdleUntil_->id;
1310 } else {
1311 return;
1312 }
1313 }
1314 StopTimerInner(id, true);
1315 }
1316
HandleRepeatTimer(const std::shared_ptr<TimerInfo> & timer,std::chrono::steady_clock::time_point nowElapsed)1317 void TimerManager::HandleRepeatTimer(
1318 const std::shared_ptr<TimerInfo> &timer, std::chrono::steady_clock::time_point nowElapsed)
1319 {
1320 if (timer->repeatInterval > milliseconds::zero()) {
1321 uint64_t count = 1 + static_cast<uint64_t>(
1322 duration_cast<milliseconds>(nowElapsed - timer->whenElapsed) / timer->repeatInterval);
1323 auto delta = count * timer->repeatInterval;
1324 auto nextElapsed = timer->whenElapsed + delta;
1325 SetHandlerLocked(timer->id, timer->type, timer->when + delta, nextElapsed, timer->windowLength,
1326 MaxTriggerTime(nowElapsed, nextElapsed, timer->repeatInterval), timer->repeatInterval, timer->callback,
1327 timer->wantAgent, timer->flags, timer->uid, timer->pid, timer->bundleName);
1328 } else {
1329 TimerProxy::GetInstance().RemoveUidTimerMap(timer);
1330 TimerProxy::GetInstance().RemovePidTimerMap(timer);
1331 }
1332 }
1333
CheckNeedRecoverOnReboot(std::string bundleName,int type)1334 inline bool TimerManager::CheckNeedRecoverOnReboot(std::string bundleName, int type)
1335 {
1336 return (std::find(NEED_RECOVER_ON_REBOOT.begin(), NEED_RECOVER_ON_REBOOT.end(), bundleName) !=
1337 NEED_RECOVER_ON_REBOOT.end() && (type == RTC || type == RTC_WAKEUP));
1338 }
1339
1340 #ifdef POWER_MANAGER_ENABLE
1341 // needs to acquire the lock `mutex_` before calling this method
HandleRunningLock(const std::shared_ptr<Batch> & firstWakeup)1342 void TimerManager::HandleRunningLock(const std::shared_ptr<Batch> &firstWakeup)
1343 {
1344 auto currentTime = duration_cast<nanoseconds>(GetBootTimeNs().time_since_epoch()).count();
1345 auto nextTimerOffset =
1346 duration_cast<nanoseconds>(firstWakeup->GetStart().time_since_epoch()).count() - currentTime;
1347 auto lockOffset = currentTime - lockExpiredTime_;
1348 if (nextTimerOffset > 0 && nextTimerOffset <= USE_LOCK_TIME_IN_NANO &&
1349 ((lockOffset < 0 && std::abs(lockOffset) <= nextTimerOffset) || lockOffset >= 0)) {
1350 auto firstAlarm = firstWakeup->Get(0);
1351 if (firstAlarm == nullptr) {
1352 TIME_HILOGI(TIME_MODULE_SERVICE, "first alarm is null");
1353 return;
1354 }
1355 auto holdLockTime = nextTimerOffset + ONE_HUNDRED_MILLI;
1356 TIME_HILOGI(TIME_MODULE_SERVICE, "runningLock time:%{public}" PRIu64 ", timerId:%{public}"
1357 PRIu64", uid:%{public}d bundleName=%{public}s", static_cast<uint64_t>(holdLockTime),
1358 firstAlarm->id, firstAlarm->uid, firstAlarm->bundleName.c_str());
1359 lockExpiredTime_ = currentTime + holdLockTime;
1360 AddRunningLock(holdLockTime);
1361 }
1362 }
1363
AddRunningLockRetry(long long holdLockTime)1364 void TimerManager::AddRunningLockRetry(long long holdLockTime)
1365 {
1366 auto retryRegister = [this, holdLockTime]() {
1367 for (int i = 0; i < POWER_RETRY_TIMES; i++) {
1368 usleep(POWER_RETRY_INTERVAL);
1369 runningLock_->Lock(static_cast<int32_t>(holdLockTime / NANO_TO_MILLI));
1370 if (runningLock_->IsUsed()) {
1371 return;
1372 }
1373 }
1374 };
1375 std::thread thread(retryRegister);
1376 thread.detach();
1377 }
1378
AddRunningLock(long long holdLockTime)1379 void TimerManager::AddRunningLock(long long holdLockTime)
1380 {
1381 if (runningLock_ == nullptr) {
1382 std::lock_guard<std::mutex> lock(runningLockMutex_);
1383 if (runningLock_ == nullptr) {
1384 TIME_HILOGI(TIME_MODULE_SERVICE, "runningLock is nullptr, create runningLock");
1385 runningLock_ = PowerMgr::PowerMgrClient::GetInstance().CreateRunningLock("timeServiceRunningLock",
1386 PowerMgr::RunningLockType::RUNNINGLOCK_BACKGROUND_NOTIFICATION);
1387 }
1388 }
1389 if (runningLock_ != nullptr) {
1390 runningLock_->Lock(static_cast<int32_t>(holdLockTime / NANO_TO_MILLI));
1391 if (!runningLock_->IsUsed()) {
1392 AddRunningLockRetry(holdLockTime);
1393 }
1394 }
1395 }
1396 #endif
1397 } // MiscServices
1398 } // OHOS