• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
16 #ifndef POWERMGR_POWER_STATE_MACHINE_H
17 #define POWERMGR_POWER_STATE_MACHINE_H
18 
19 #include <set>
20 #include <map>
21 #include <singleton.h>
22 
23 #include "actions/idevice_state_action.h"
24 #include "ffrt_utils.h"
25 #ifdef POWER_MANAGER_POWER_ENABLE_S4
26 #include "hibernate_controller.h"
27 #endif
28 #include "ipower_state_callback.h"
29 #include "power_common.h"
30 #include "power_state_machine_info.h"
31 #include "running_lock_info.h"
32 #include "power_mgr_notify.h"
33 #include "window_manager_lite.h"
34 #include "suspend/itake_over_suspend_callback.h"
35 #include "parameters.h"
36 
37 namespace OHOS {
38 namespace PowerMgr {
39 class RunningLockMgr;
40 class PowerMgrService;
41 
42 struct ScreenState {
43     DisplayState state;
44     int64_t lastOnTime;
45     int64_t lastOffTime;
46 };
47 
48 struct DevicePowerState {
49     ScreenState screenState;
50     // record the last time when get wakeup event from A side
51     int64_t lastWakeupEventTime;
52     // record the last time when calling func RefreshActivityInner
53     int64_t lastRefreshActivityTime;
54     // record the last time when calling func WakeupDeviceInner
55     int64_t lastWakeupDeviceTime;
56     // record the last time when calling func SuspendDeviceInner
57     int64_t lastSuspendDeviceTime;
58 };
59 
60 enum class TransitResult {
61     SUCCESS = 0,
62     ALREADY_IN_STATE = 1,
63     LOCKING = 2,
64     HDI_ERR = 3,
65     DISPLAY_ON_ERR = 4,
66     DISPLAY_OFF_ERR = 5,
67     FORBID_TRANSIT = 6,
68     PRE_BRIGHT_ERR = 7,
69     TAKEN_OVER = 8,
70     OTHER_ERR = 99
71 };
72 
73 class PowerStateMachine : public std::enable_shared_from_this<PowerStateMachine> {
74 public:
75     PowerStateMachine(const wptr<PowerMgrService>& pms, const std::shared_ptr<FFRTTimer>& ffrtTimer = nullptr);
76     ~PowerStateMachine();
77 
78     enum {
79         CHECK_USER_ACTIVITY_TIMEOUT_MSG = 0,
80         CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG,
81         CHECK_PRE_BRIGHT_AUTH_TIMEOUT_MSG,
82         CHECK_PROXIMITY_SCREEN_OFF_MSG,
83         SET_INTERNAL_SCREEN_STATE_MSG,
84         CHECK_PROXIMITY_SCREEN_SWITCH_TO_SUB_MSG,
85     };
86 
87     class PowerStateCallbackDeathRecipient : public IRemoteObject::DeathRecipient {
88     public:
89         PowerStateCallbackDeathRecipient() = default;
90         virtual void OnRemoteDied(const wptr<IRemoteObject>& remote);
91         virtual ~PowerStateCallbackDeathRecipient() = default;
92     };
93 
94 #ifdef POWER_MANAGER_ENABLE_CHARGING_TYPE_SETTING
95     static constexpr int32_t DEFAULT_AC_DISPLAY_OFF_TIME_MS = 600000;
96     static constexpr int32_t DEFAULT_DC_DISPLAY_OFF_TIME_MS = 300000
97     static constexpr int32_t DEFAULT_DISPLAY_OFF_TIME_MS = DEFAULT_DC_DISPLAY_OFF_TIME_MS;
98 #else
99     static constexpr int32_t DEFAULT_DISPLAY_OFF_TIME_MS = 30000;
100 #endif
101     static constexpr int32_t DEFAULT_SLEEP_TIME_MS = 5000;
102     static constexpr int64_t OFF_TIMEOUT_FACTOR = 5;
103     static constexpr int64_t MAX_DIM_TIME_MS = 7500;
104     static constexpr int64_t COORDINATED_STATE_SCREEN_OFF_TIME_MS = 10000;
105     static constexpr uint32_t SCREEN_CHANGE_TIMEOUT_MS = 10000;
106     static constexpr uint32_t SCREEN_CHANGE_REPORT_INTERVAL_MS = 600000;
107 
108     static void onSuspend();
109     static void onWakeup();
110     static void DisplayOffTimeUpdateFunc();
111     static void RegisterDisplayOffTimeObserver();
112     static void UnregisterDisplayOffTimeObserver();
113 
114     bool Init();
115     void InitState();
116     void SuspendDeviceInner(
117         pid_t pid, int64_t callTimeMs, SuspendDeviceType type, bool suspendImmed, bool ignoreScreenState = false);
118     void WakeupDeviceInner(
119         pid_t pid, int64_t callTimeMs, WakeupDeviceType type, const std::string& details, const std::string& pkgName);
120     void HandlePreBrightWakeUp(int64_t callTimeMs, WakeupDeviceType type, const std::string& details,
121         const std::string& pkgName, bool timeoutTriggered = false);
122     void RefreshActivityInner(pid_t pid, int64_t callTimeMs, UserActivityType type, bool needChangeBacklight);
123     bool CheckRefreshTime();
124     bool OverrideScreenOffTimeInner(int64_t timeout);
125     bool RestoreScreenOffTimeInner();
126     void ReceiveScreenEvent(bool isScreenOn);
127     bool IsScreenOn(bool needPrintLog = true);
128     bool IsScreenOnAcqLock();
129     bool IsFoldScreenOn();
130     bool IsCollaborationScreenOn();
131     bool CheckFFRTTaskAvailability(PowerState state, StateChangeReason reason) const;
132     bool IsTimeoutReason(StateChangeReason reason) const;
133     void Reset();
134     int64_t GetSleepTime();
135 #ifdef MSDP_MOVEMENT_ENABLE
136     bool IsMovementStateOn();
137 #endif
138     bool IsWakeupDeviceSkip();
139 
GetState()140     PowerState GetState()
141     {
142         return currentState_;
143     };
GetStateAction()144     const std::shared_ptr<IDeviceStateAction>& GetStateAction()
145     {
146         return stateAction_;
147     };
148     bool ForceSuspendDeviceInner(pid_t pid, int64_t callTimeMs);
149 #ifdef POWER_MANAGER_POWER_ENABLE_S4
150     bool HibernateInner(bool clearMemory, const std::string& reason);
151 #endif
152     void RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback, bool isSync = true);
153     void UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback);
154     void SetDelayTimer(int64_t delayTime, int32_t event);
155     void SetDelayTimer(int64_t delayTime, int32_t event, FFRTTask& task);
156     void CancelDelayTimer(int32_t event);
157     void ResetInactiveTimer(bool needPrintLog = true);
158     void ResetSleepTimer();
159     void SetAutoSuspend(SuspendDeviceType type, uint32_t delay);
160     bool SetState(PowerState state, StateChangeReason reason, bool force = false);
161     bool TryToCancelScreenOff();
162     void BeginPowerkeyScreenOff();
163     void EndPowerkeyScreenOff();
164     void SetDisplaySuspend(bool enable);
165     void WriteHiSysEvent(TransitResult ret, StateChangeReason reason, int32_t beginTimeMs, PowerState state);
166     bool IsTransitFailed(TransitResult ret);
167     SuspendDeviceType GetSuspendTypeByReason(StateChangeReason reason);
168     StateChangeReason GetReasonByWakeType(WakeupDeviceType type);
169     StateChangeReason GetReasonBySuspendType(SuspendDeviceType type);
170 #ifdef POWER_MANAGER_ENABLE_EXTERNAL_SCREEN_MANAGEMENT
GetExternalScreenNumber()171     int32_t GetExternalScreenNumber() const
172     {
173         return externalScreenNumber_;
174     }
SetExternalScreenNumber(int32_t exScreenNumber)175     void SetExternalScreenNumber(int32_t exScreenNumber)
176     {
177         externalScreenNumber_ = exScreenNumber;
178     }
IsOnlySecondDisplayModeSupported()179     bool IsOnlySecondDisplayModeSupported() const
180     {
181         int32_t displayMode = system::GetIntParameter("const.product.support_display_mode", 0);
182         return (displayMode & DISPLAY_MODE_ONLY_SECOND_SCREEN) > 0;
183     }
184 #endif
185 
186     // only use for test
GetLastSuspendDeviceTime()187     int64_t GetLastSuspendDeviceTime() const
188     {
189         return mDeviceState_.lastSuspendDeviceTime;
190     }
GetLastWakeupDeviceTime()191     int64_t GetLastWakeupDeviceTime() const
192     {
193         return mDeviceState_.lastWakeupDeviceTime;
194     }
GetLastRefreshActivityTime()195     int64_t GetLastRefreshActivityTime() const
196     {
197         return mDeviceState_.lastRefreshActivityTime;
198     }
GetLastWakeupEventTime()199     int64_t GetLastWakeupEventTime() const
200     {
201         return mDeviceState_.lastWakeupEventTime;
202     }
SetSwitchAction(uint32_t value)203     void SetSwitchAction(uint32_t value)
204     {
205         switchActionValue_ = value;
206     }
GetSwitchAction()207     uint32_t GetSwitchAction()
208     {
209         return switchActionValue_;
210     }
SetSwitchState(bool switchOpen)211     void SetSwitchState(bool switchOpen)
212     {
213         switchOpen_ = switchOpen;
214     }
IsSwitchOpen()215     bool IsSwitchOpen() const
216     {
217         return switchOpen_;
218     }
219     bool IsSwitchOpenByPath();
220 #ifdef POWER_MANAGER_POWER_ENABLE_S4
IsHibernating()221     bool IsHibernating() const
222     {
223         return hibernating_;
224     }
225 #endif
GetLastOnTime()226     int64_t GetLastOnTime() const
227     {
228         return mDeviceState_.screenState.lastOnTime;
229     }
SetDuringCallState(bool state)230     void SetDuringCallState(bool state)
231     {
232         isDuringCall_ = state;
233     }
IsDuringCall()234     bool IsDuringCall()
235     {
236         return isDuringCall_;
237     }
238 
239     void DumpInfo(std::string& result);
240     void EnableMock(IDeviceStateAction* mockAction);
241     int64_t GetDisplayOffTime();
242     int64_t GetDimTime(int64_t displayOffTime);
243     void SetDisplayOffTime(int64_t time, bool needUpdateSetting = true);
244     void SetSleepTime(int64_t time);
245     bool IsRunningLockEnabled(RunningLockType type);
246     void SetForceTimingOut(bool enabled);
247     void LockScreenAfterTimingOut(bool enabled, bool checkScreenOnLock, bool sendScreenOffEvent);
248     bool IsSettingState(PowerState state);
249     void SetEnableDoze(bool enable);
250     bool SetDozeMode(DisplayState state);
251 #ifdef POWER_MANAGER_ENABLE_EXTERNAL_SCREEN_MANAGEMENT
252     void SetInternalScreenDisplayState(DisplayState state, StateChangeReason reason);
253 #endif
254     bool HandleDuringCall(bool isProximityClose);
255 
256 private:
257     enum PreBrightState : uint32_t {
258         PRE_BRIGHT_UNSTART = 0,
259         PRE_BRIGHT_STARTED,
260         PRE_BRIGHT_FINISHED,
261     };
262 
263     class SettingStateFlag {
264     public:
SettingStateFlag(PowerState state,std::shared_ptr<PowerStateMachine> owner,StateChangeReason reason)265         SettingStateFlag(PowerState state, std::shared_ptr<PowerStateMachine> owner, StateChangeReason reason)
266             : owner_(owner)
267         {
268             std::shared_ptr<PowerStateMachine> stateMachine = owner_.lock();
269             int64_t flag;
270             if (state == PowerState::DIM && reason == StateChangeReason::STATE_CHANGE_REASON_COORDINATION) {
271                 flag = static_cast<int64_t>(StateFlag::FORCE_SETTING_DIM);
272             } else {
273                 flag = static_cast<int64_t>(state);
274             }
275             stateMachine->settingStateFlag_ = flag;
276         }
277         SettingStateFlag(const SettingStateFlag&) = delete;
278         SettingStateFlag& operator=(const SettingStateFlag&) = delete;
279         SettingStateFlag(SettingStateFlag&&) = delete;
280         SettingStateFlag& operator=(SettingStateFlag&&) = delete;
~SettingStateFlag()281         ~SettingStateFlag()
282         {
283             std::shared_ptr<PowerStateMachine> stateMachine = owner_.lock();
284             stateMachine->settingStateFlag_ = static_cast<int64_t>(StateFlag::NONE);
285         }
286         enum class StateFlag : int64_t {
287             FORCE_SETTING_DIM = -3,
288             SETTING_DIM_INTERRUPTED = -2,
289             NONE = -1
290         };
291     protected:
292         std::weak_ptr<PowerStateMachine> owner_;
293     };
294     class StateController {
295     public:
StateController(PowerState state,std::shared_ptr<PowerStateMachine> owner,std::function<TransitResult (StateChangeReason)> action)296         StateController(PowerState state, std::shared_ptr<PowerStateMachine> owner,
297             std::function<TransitResult(StateChangeReason)> action)
298             : state_(state),
299             owner_(owner), action_(action)
300         {
301         }
302         ~StateController() = default;
GetState()303         PowerState GetState()
304         {
305             return state_;
306         }
307         TransitResult TransitTo(StateChangeReason reason, bool ignoreLock = false);
308         void RecordFailure(PowerState from, StateChangeReason trigger, TransitResult failReason);
309         static bool IsReallyFailed(StateChangeReason reason);
310         StateChangeReason lastReason_;
311         int64_t lastTime_ {0};
312         PowerState failFrom_;
313         StateChangeReason failTrigger_;
314         std::string failReason_;
315         int64_t failTime_ {0};
316 
317     protected:
318         bool CheckState();
319         bool NeedNotify(PowerState currentState);
320         void MatchState(PowerState& currentState, DisplayState state);
321         void CorrectState(PowerState& currentState, PowerState correctState, DisplayState state);
322         PowerState state_;
323         std::weak_ptr<PowerStateMachine> owner_;
324         std::function<TransitResult(StateChangeReason)> action_;
325     };
326 
327     struct classcomp {
operatorclasscomp328         bool operator()(const sptr<IPowerStateCallback>& l, const sptr<IPowerStateCallback>& r) const
329         {
330             return l->AsObject() < r->AsObject();
331         }
332     };
333 
334     class ScreenChangeCheck {
335     public:
336         ScreenChangeCheck(std::shared_ptr<FFRTTimer> ffrtTimer, PowerState state, StateChangeReason reason);
337         ~ScreenChangeCheck() noexcept;
338         void SetReportTimerStartFlag(bool flag) const;
339         void ReportSysEvent(const std::string& msg) const;
340 
341     private:
342         pid_t pid_ {-1};
343         pid_t uid_ {-1};
344         mutable bool isReportTimerStarted_ {false};
345         std::shared_ptr<FFRTTimer> ffrtTimer_ {nullptr};
346         PowerState state_;
347         StateChangeReason reason_;
348     };
349 
350     static std::string GetTransitResultString(TransitResult result);
351 
352     void UpdateSettingStateFlag(PowerState state, StateChangeReason reason);
353     void RestoreSettingStateFlag();
354     void InitStateMap();
355     void EmplaceAwake();
356     void EmplaceFreeze();
357     void EmplaceInactive();
358     void EmplaceStandBy();
359     void EmplaceDoze();
360     void EmplaceSleep();
361     void EmplaceHibernate();
362     void EmplaceShutdown();
363     void EmplaceDim();
364     void InitTransitMap();
365     bool CanTransitTo(PowerState from, PowerState to, StateChangeReason reason);
366     void NotifyPowerStateChanged(PowerState state,
367         StateChangeReason reason = StateChangeReason::STATE_CHANGE_REASON_APPLICATION);
368     void SendEventToPowerMgrNotify(PowerState state, int64_t callTime);
369     bool CheckRunningLock(PowerState state);
370     void HandleActivityTimeout();
371     void HandleActivitySleepTimeout();
372     void HandleSystemWakeup();
373     void AppendDumpInfo(std::string& result, std::string& reason, std::string& time);
374     std::shared_ptr<StateController> GetStateController(PowerState state);
375     void ResetScreenOffPreTimeForSwing(int64_t displayOffTime);
376     void ShowCurrentScreenLocks();
377     void HandleProximityScreenOffTimer(PowerState state, StateChangeReason reason);
378     bool HandlePreBrightState(PowerState targetState, StateChangeReason reason);
379     bool IsPreBrightAuthReason(StateChangeReason reason);
380     bool IsPreBrightWakeUp(WakeupDeviceType type);
381     bool NeedShowScreenLocks(PowerState state);
382 #ifdef POWER_MANAGER_POWER_ENABLE_S4
383     void DelayForHibernateInactive(bool clearMemory);
384     bool PrepareHibernate(bool clearMemory);
385     bool PrepareHibernateWithTimeout(bool clearMemory);
386     void RestoreHibernate(bool clearMemory, HibernateStatus status,
387         const std::shared_ptr<HibernateController>& hibernateController, const std::shared_ptr<PowerMgrNotify>& notify);
388     void RollbackHibernate(
389         PowerState originalState, bool clearMemory, bool needShutdown, const sptr<PowerMgrService>& pms);
390     uint32_t GetPreHibernateDelay();
391 #endif
392 #ifdef HAS_SENSORS_SENSOR_PART
393     bool IsProximityClose();
394 #endif
395     void StartSleepTimer(PowerState from);
396 #ifdef HAS_HIVIEWDFX_HISYSEVENT_PART
397     bool ReportScreenOffInvalidEvent(StateChangeReason reason);
398     bool ReportAbnormalScreenOffEvent(StateChangeReason reason);
399 #endif
400 #ifdef POWER_MANAGER_TAKEOVER_SUSPEND
401     TransitResult TakeOverSuspendAction(StateChangeReason reason);
402 #endif
403 
404     const wptr<PowerMgrService> pms_;
405     std::shared_ptr<FFRTTimer> ffrtTimer_ {nullptr};
406     PowerState currentState_;
407     std::map<PowerState, std::shared_ptr<std::vector<RunningLockType>>> lockMap_;
408     std::map<PowerState, std::shared_ptr<StateController>> controllerMap_;
409     std::mutex mutex_;
410     // all change to currentState_ should be inside stateMutex_
411     std::mutex stateMutex_;
412     DevicePowerState mDeviceState_;
413     sptr<IRemoteObject::DeathRecipient> powerStateCBDeathRecipient_;
414     std::set<const sptr<IPowerStateCallback>, classcomp> syncPowerStateListeners_;
415     std::set<const sptr<IPowerStateCallback>, classcomp> asyncPowerStateListeners_;
416     std::map<sptr<IPowerStateCallback>, std::pair<int32_t, int32_t>, classcomp> cachedRegister_;
417     std::shared_ptr<IDeviceStateAction> stateAction_;
418 
419     std::atomic<int64_t> displayOffTime_ {DEFAULT_DISPLAY_OFF_TIME_MS};
420     int64_t sleepTime_ {DEFAULT_SLEEP_TIME_MS};
421     bool enableDisplaySuspend_ {false};
422     bool isScreenOffTimeOverride_ {false};
423     std::unordered_map<PowerState, std::set<PowerState>> forbidMap_;
424     uint32_t switchActionValue_ {2}; // default value is 2 (stand for ACTION_FORCE_SUSPEND)
425     std::atomic<bool> switchOpen_ {true};
426 #ifdef POWER_MANAGER_POWER_ENABLE_S4
427     std::atomic<bool> hibernating_ {false};
428 #endif
429     std::unordered_map<StateChangeReason, std::unordered_map<PowerState, std::set<PowerState>>> allowMapByReason_;
430     std::atomic<bool> forceTimingOut_ {false};
431     std::atomic<bool> enabledTimingOutLockScreen_ {true};
432     std::atomic<bool> enabledTimingOutLockScreenCheckLock_ {false};
433     std::atomic<bool> enabledScreenOffEvent_{true};
434     std::atomic<int64_t> settingStateFlag_ {-1};
435     std::atomic<bool> settingOnStateFlag_ {false};
436     std::atomic<bool> settingOffStateFlag_ {false};
437     std::atomic<bool> isAwakeNotified_ {false};
438     std::atomic<PreBrightState> preBrightState_ {PRE_BRIGHT_UNSTART};
439     std::atomic<bool> proximityScreenOffTimerStarted_ {false};
440     std::atomic<bool> isDozeEnabled_ {false};
441 #ifdef POWER_MANAGER_ENABLE_EXTERNAL_SCREEN_MANAGEMENT
442     std::atomic<int32_t> externalScreenNumber_ {0};
443     std::mutex internalScreenStateMutex_;
444     static constexpr int32_t DISPLAY_MODE_ONLY_SECOND_SCREEN = 8;
445 #endif
446     std::atomic<bool> isDuringCall_ {false};
447     bool SetDreamingState(StateChangeReason reason);
448 };
449 } // namespace PowerMgr
450 } // namespace OHOS
451 #endif // POWERMGR_POWER_STATE_MACHINE_H
452