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