1 /*
2  * Copyright (C) 2021-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 #ifndef TIMER_MANAGER_H
16 #define TIMER_MANAGER_H
17 
18 #include <atomic>
19 #include <chrono>
20 #include <cinttypes>
21 #include <functional>
22 #include <map>
23 #include <mutex>
24 #include <random>
25 #include <thread>
26 #include <vector>
27 #include <unordered_set>
28 #include <utility>
29 
30 #include "batch.h"
31 #include "timer_handler.h"
32 #include "want_agent_helper.h"
33 #include "time_common.h"
34 
35 #ifdef POWER_MANAGER_ENABLE
36 #include "completed_callback.h"
37 #include "power_mgr_client.h"
38 #endif
39 
40 namespace OHOS {
41 namespace MiscServices {
42 static std::vector<std::string> NEED_RECOVER_ON_REBOOT = { "not_support" };
43 
44 class TimerManager : public ITimerManager {
45 public:
46     int32_t CreateTimer(TimerPara &paras,
47                         std::function<int32_t (const uint64_t)> callback,
48                         std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> wantAgent,
49                         int uid,
50                         int pid,
51                         uint64_t &timerId,
52                         DatabaseType type) override;
53     void ReCreateTimer(uint64_t timerId, std::shared_ptr<TimerEntry> timerInfo);
54     int32_t StartTimer(uint64_t timerId, uint64_t triggerTime) override;
55     int32_t StopTimer(uint64_t timerId) override;
56     int32_t DestroyTimer(uint64_t timerId) override;
57     bool ProxyTimer(int32_t uid, bool isProxy, bool needRetrigger) override;
58     bool ProxyTimer(int32_t uid, std::set<int> pidList, bool isProxy, bool needRetrigger) override;
59     bool AdjustTimer(bool isAdjust, uint32_t interval) override;
60     void SetTimerExemption(const std::unordered_set<std::string> &nameArr, bool isExemption) override;
61     bool ResetAllProxy() override;
62     bool ShowTimerEntryMap(int fd);
63     bool ShowTimerEntryById(int fd, uint64_t timerId);
64     bool ShowTimerTriggerById(int fd, uint64_t timerId);
65     bool ShowIdleTimerInfo(int fd);
66     ~TimerManager() override;
67     void HandleRSSDeath();
68     static TimerManager* GetInstance();
69 
70 private:
71     explicit TimerManager(std::shared_ptr<TimerHandler> impl);
72     void TimerLooper();
73 
74     void SetHandler(uint64_t id,
75                     int type,
76                     uint64_t triggerAtTime,
77                     int64_t windowLength,
78                     uint64_t interval,
79                     int flag,
80                     std::function<int32_t (const uint64_t)> callback,
81                     std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> wantAgent,
82                     int uid,
83                     int pid,
84                     const std::string &bundleName);
85     void SetHandlerLocked(uint64_t id,
86                           int type,
87                           std::chrono::milliseconds when,
88                           std::chrono::steady_clock::time_point whenElapsed,
89                           std::chrono::milliseconds windowLength,
90                           std::chrono::steady_clock::time_point maxWhen,
91                           std::chrono::milliseconds interval,
92                           std::function<int32_t (const uint64_t)> callback,
93                           const std::shared_ptr<OHOS::AbilityRuntime::WantAgent::WantAgent> &wantAgent,
94                           uint32_t flags,
95                           uint64_t callingUid,
96                           uint64_t callingPid,
97                           const std::string &bundleName);
98     void RemoveHandler(uint64_t id);
99     void RemoveLocked(uint64_t id, bool needReschedule);
100     void ReBatchAllTimers();
101     void ReAddTimerLocked(std::shared_ptr<TimerInfo> timer,
102                           std::chrono::steady_clock::time_point nowElapsed);
103     void ReCalcuOriWhenElapsed(std::shared_ptr<TimerInfo> timer,
104                           std::chrono::steady_clock::time_point nowElapsed);
105     void SetHandlerLocked(std::shared_ptr<TimerInfo> alarm, bool rebatching, bool isRebatched);
106     void InsertAndBatchTimerLocked(std::shared_ptr<TimerInfo> alarm);
107     int64_t AttemptCoalesceLocked(std::chrono::steady_clock::time_point whenElapsed,
108                                   std::chrono::steady_clock::time_point maxWhen);
109     void TriggerIdleTimer();
110     bool ProcTriggerTimer(std::shared_ptr<TimerInfo> &alarm,
111                           const std::chrono::steady_clock::time_point &nowElapsed);
112     bool TriggerTimersLocked(std::vector<std::shared_ptr<TimerInfo>> &triggerList,
113                              std::chrono::steady_clock::time_point nowElapsed);
114     void RescheduleKernelTimerLocked();
115     void DeliverTimersLocked(const std::vector<std::shared_ptr<TimerInfo>> &triggerList);
116     void NotifyWantAgentRetry(std::shared_ptr<TimerInfo> timer);
117     std::shared_ptr<Batch> FindFirstWakeupBatchLocked();
118     void SetLocked(int type, std::chrono::nanoseconds when, std::chrono::steady_clock::time_point bootTime);
119     std::chrono::steady_clock::time_point ConvertToElapsed(std::chrono::milliseconds when, int type);
120     std::chrono::steady_clock::time_point GetBootTimeNs();
121     int32_t StopTimerInner(uint64_t timerNumber, bool needDestroy);
122     int32_t CheckUserIdForNotify(const std::shared_ptr<TimerInfo> &timer);
123     bool NotifyWantAgent(const std::shared_ptr<TimerInfo> &timer);
124     bool CheckAllowWhileIdle(const std::shared_ptr<TimerInfo> &alarm);
125     bool AdjustDeliveryTimeBasedOnDeviceIdle(const std::shared_ptr<TimerInfo> &alarm);
126     bool AdjustTimersBasedOnDeviceIdle();
127     void HandleRepeatTimer(const std::shared_ptr<TimerInfo> &timer, std::chrono::steady_clock::time_point nowElapsed);
128     inline bool CheckNeedRecoverOnReboot(std::string bundleName, int type);
129     #ifdef POWER_MANAGER_ENABLE
130     void HandleRunningLock(const std::shared_ptr<Batch> &firstWakeup);
131     void AddRunningLock(long long holdLockTime);
132     void AddRunningLockRetry(long long holdLockTime);
133     #endif
134 
135     void UpdateTimersState(std::shared_ptr<TimerInfo> &alarm);
136     bool AdjustSingleTimer(std::shared_ptr<TimerInfo> timer);
137     void IncreaseTimerCount(int uid);
138     void DecreaseTimerCount(int uid);
139     void CheckTimerCount();
140     void ShowTimerCountByUid();
141 
142     std::map<uint64_t, std::shared_ptr<TimerEntry>> timerEntryMap_;
143     // vector<uid, count>
144     std::vector<std::pair<int32_t, int32_t>> timerCount_;
145     std::default_random_engine random_;
146     std::atomic_bool runFlag_;
147     std::shared_ptr<TimerHandler> handler_;
148     std::unique_ptr<std::thread> alarmThread_;
149     std::vector<std::shared_ptr<Batch>> alarmBatches_;
150     std::mutex mutex_;
151     std::mutex entryMapMutex_;
152     std::chrono::system_clock::time_point lastTimeChangeClockTime_;
153     std::chrono::steady_clock::time_point lastTimeChangeRealtime_;
154     static std::mutex instanceLock_;
155     static TimerManager* instance_;
156 
157     std::vector<std::shared_ptr<TimerInfo>> pendingDelayTimers_;
158     // map<timerId, original trigger time> for delayed timers
159     std::map<uint64_t, std::chrono::steady_clock::time_point> delayedTimers_;
160     // idle timer
161     std::shared_ptr<TimerInfo> mPendingIdleUntil_;
162     bool adjustPolicy_ = false;
163     uint32_t adjustInterval_ = 0;
164     int64_t timerOutOfRangeTimes_ = 0;
165     std::chrono::steady_clock::time_point lastTimerOutOfRangeTime_;
166     #ifdef POWER_MANAGER_ENABLE
167     std::mutex runningLockMutex_;
168     std::shared_ptr<PowerMgr::RunningLock> runningLock_;
169     int64_t lockExpiredTime_ = 0;
170     #endif
171 }; // timer_manager
172 } // MiscServices
173 } // OHOS
174 
175 #endif