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