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