• 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 #include "power_mgr_service.h"
17 
18 #include <datetime_ex.h>
19 #include <file_ex.h>
20 #include <hisysevent.h>
21 #include <if_system_ability_manager.h>
22 #include <input_manager.h>
23 #include <ipc_skeleton.h>
24 #include <iservice_registry.h>
25 #include <securec.h>
26 #include <string_ex.h>
27 #include <system_ability_definition.h>
28 #include <unistd.h>
29 
30 #include "ability_connect_callback_stub.h"
31 #include "ability_manager_client.h"
32 #include "ffrt_utils.h"
33 #include "permission.h"
34 #include "power_common.h"
35 #include "power_mgr_dumper.h"
36 #include "sysparam.h"
37 #include "system_suspend_controller.h"
38 #include "xcollie/watchdog.h"
39 
40 #include "errors.h"
41 #include "standby_service_client.h"
42 
43 using namespace OHOS::AppExecFwk;
44 using namespace OHOS::AAFwk;
45 
46 namespace OHOS {
47 namespace PowerMgr {
48 namespace {
49 const std::string POWERMGR_SERVICE_NAME = "PowerMgrService";
50 const std::string REASON_POWER_KEY = "power_key";
51 static std::string g_wakeupReason = "";
52 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
53 const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(pms.GetRefPtr());
54 SysParam::BootCompletedCallback g_bootCompletedCallback;
55 FFRTQueue g_queue("power_mgr_service");
56 FFRTHandle g_screenTimeoutHandle;
57 } // namespace
58 
59 std::atomic_bool PowerMgrService::isBootCompleted_ = false;
60 using namespace MMI;
61 
PowerMgrService()62 PowerMgrService::PowerMgrService() : SystemAbility(POWER_MANAGER_SERVICE_ID, true) {}
63 
~PowerMgrService()64 PowerMgrService::~PowerMgrService() {}
65 
OnStart()66 void PowerMgrService::OnStart()
67 {
68     POWER_HILOGD(COMP_SVC, "Power Management startup");
69     if (ready_) {
70         POWER_HILOGW(COMP_SVC, "OnStart is ready, nothing to do");
71         return;
72     }
73     if (!Init()) {
74         POWER_HILOGE(COMP_SVC, "Call init fail");
75         return;
76     }
77     AddSystemAbilityListener(SUSPEND_MANAGER_SYSTEM_ABILITY_ID);
78     AddSystemAbilityListener(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
79     SystemSuspendController::GetInstance().RegisterHdiStatusListener();
80     if (!Publish(DelayedSpSingleton<PowerMgrService>::GetInstance())) {
81         POWER_HILOGE(COMP_SVC, "Register to system ability manager failed");
82         return;
83     }
84     ready_ = true;
85     POWER_HILOGI(COMP_SVC, "Add system ability success");
86 }
87 
Init()88 bool PowerMgrService::Init()
89 {
90     POWER_HILOGI(COMP_SVC, "Init start");
91     if (!runningLockMgr_) {
92         runningLockMgr_ = std::make_shared<RunningLockMgr>(pms);
93     }
94     if (!runningLockMgr_->Init()) {
95         POWER_HILOGE(COMP_SVC, "Running lock init fail");
96         return false;
97     }
98     if (!shutdownController_) {
99         shutdownController_ = std::make_shared<ShutdownController>();
100     }
101     if (!PowerStateMachineInit()) {
102         POWER_HILOGE(COMP_SVC, "Power state machine init fail");
103     }
104 
105     RegisterBootCompletedCallback();
106     POWER_HILOGI(COMP_SVC, "Init success");
107     return true;
108 }
109 
RegisterBootCompletedCallback()110 void PowerMgrService::RegisterBootCompletedCallback()
111 {
112     g_bootCompletedCallback = []() {
113         POWER_HILOGI(COMP_SVC, "BootCompletedCallback triggered");
114         auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
115         if (power == nullptr) {
116             POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
117             return;
118         }
119         if (DelayedSpSingleton<PowerSaveMode>::GetInstance()) {
120             auto& powerModeModule = power->GetPowerModeModule();
121             powerModeModule.EnableMode(powerModeModule.GetModeItem(), true);
122         }
123         auto powerStateMachine = power->GetPowerStateMachine();
124         powerStateMachine->RegisterDisplayOffTimeObserver();
125         powerStateMachine->InitState();
126         power->GetShutdownDialog().KeyMonitorInit();
127         power->HallSensorSubscriberInit();
128         power->SwitchSubscriberInit();
129         power->SuspendControllerInit();
130         power->WakeupControllerInit();
131         isBootCompleted_ = true;
132     };
133     WakeupRunningLock::Create();
134     SysParam::RegisterBootCompletedCallback(g_bootCompletedCallback);
135 }
136 
PowerStateMachineInit()137 bool PowerMgrService::PowerStateMachineInit()
138 {
139     if (powerStateMachine_ == nullptr) {
140         powerStateMachine_ = std::make_shared<PowerStateMachine>(pms);
141         if (!(powerStateMachine_->Init())) {
142             POWER_HILOGE(COMP_SVC, "Power state machine start fail!");
143             return false;
144         }
145     }
146     if (powerMgrNotify_ == nullptr) {
147         powerMgrNotify_ = std::make_shared<PowerMgrNotify>();
148         powerMgrNotify_->RegisterPublishEvents();
149     }
150     return true;
151 }
152 
KeyMonitorCancel()153 void PowerMgrService::KeyMonitorCancel()
154 {
155     POWER_HILOGI(FEATURE_INPUT, "Unsubscribe key information");
156     InputManager* inputManager = InputManager::GetInstance();
157     if (inputManager == nullptr) {
158         POWER_HILOGI(FEATURE_INPUT, "InputManager is null");
159         return;
160     }
161     shutdownDialog_.KeyMonitorCancel();
162     if (doubleClickId_ >= 0) {
163         inputManager->UnsubscribeKeyEvent(doubleClickId_);
164     }
165     if (monitorId_ >= 0) {
166         inputManager->RemoveMonitor(monitorId_);
167     }
168 }
169 
HallSensorSubscriberInit()170 void PowerMgrService::HallSensorSubscriberInit()
171 {
172     if (!IsSupportSensor(SENSOR_TYPE_ID_HALL)) {
173         POWER_HILOGW(FEATURE_INPUT, "SENSOR_TYPE_ID_HALL sensor not support");
174         return;
175     }
176     if (strcpy_s(sensorUser_.name, sizeof(sensorUser_.name), "PowerManager") != EOK) {
177         POWER_HILOGW(FEATURE_INPUT, "strcpy_s error");
178         return;
179     }
180     sensorUser_.userData = nullptr;
181     sensorUser_.callback = &HallSensorCallback;
182     SubscribeSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
183     SetBatch(SENSOR_TYPE_ID_HALL, &sensorUser_, HALL_SAMPLING_RATE, HALL_REPORT_INTERVAL);
184     ActivateSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
185 }
186 
IsSupportSensor(SensorTypeId typeId)187 bool PowerMgrService::IsSupportSensor(SensorTypeId typeId)
188 {
189     bool isSupport = false;
190     SensorInfo* sensorInfo = nullptr;
191     int32_t count;
192     int32_t ret = GetAllSensors(&sensorInfo, &count);
193     if (ret != 0 || sensorInfo == nullptr) {
194         POWER_HILOGW(FEATURE_INPUT, "Get sensors fail, ret=%{public}d", ret);
195         return isSupport;
196     }
197     for (int32_t i = 0; i < count; i++) {
198         if (sensorInfo[i].sensorTypeId == typeId) {
199             isSupport = true;
200             break;
201         }
202     }
203     return isSupport;
204 }
205 
HallSensorCallback(SensorEvent * event)206 void PowerMgrService::HallSensorCallback(SensorEvent* event)
207 {
208     if (event == nullptr || event->sensorTypeId != SENSOR_TYPE_ID_HALL || event->data == nullptr) {
209         POWER_HILOGW(FEATURE_INPUT, "Hall sensor event is invalid");
210         return;
211     }
212 
213     std::shared_ptr<SuspendController> suspendController = pms->GetSuspendController();
214     if (suspendController == nullptr) {
215         POWER_HILOGE(FEATURE_INPUT, "get suspendController instance error");
216         return;
217     }
218 
219     std::shared_ptr<WakeupController> wakeupController = pms->GetWakeupController();
220     if (wakeupController == nullptr) {
221         POWER_HILOGE(FEATURE_INPUT, "wakeupController is not init");
222         return;
223     }
224     const uint32_t LID_CLOSED_HALL_FLAG = 0x1;
225     auto data = reinterpret_cast<HallData*>(event->data);
226     auto status = static_cast<uint32_t>(data->status);
227 
228     if (status & LID_CLOSED_HALL_FLAG) {
229         POWER_HILOGI(FEATURE_SUSPEND, "Lid close event received, begin to suspend");
230         SuspendDeviceType reason = SuspendDeviceType::SUSPEND_DEVICE_REASON_LID;
231         suspendController->ExecSuspendMonitorByReason(reason);
232     } else {
233         POWER_HILOGI(FEATURE_WAKEUP, "Lid open event received, begin to wakeup");
234         WakeupDeviceType reason = WakeupDeviceType::WAKEUP_DEVICE_LID;
235         wakeupController->ExecWakeupMonitorByReason(reason);
236     }
237 }
238 
HallSensorSubscriberCancel()239 void PowerMgrService::HallSensorSubscriberCancel()
240 {
241     if (IsSupportSensor(SENSOR_TYPE_ID_HALL)) {
242         DeactivateSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
243         UnsubscribeSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
244     }
245 }
246 
CheckDialogAndShuttingDown()247 bool PowerMgrService::CheckDialogAndShuttingDown()
248 {
249     bool isShuttingDown = shutdownController_->IsShuttingDown();
250     bool isLongPress = shutdownDialog_.IsLongPress();
251     if (isLongPress || isShuttingDown) {
252         POWER_HILOGW(
253             FEATURE_INPUT, "isLongPress: %{public}d, isShuttingDown: %{public}d", isLongPress, isShuttingDown);
254         shutdownDialog_.ResetLongPressFlag();
255         return true;
256     }
257     return false;
258 }
259 
SwitchSubscriberInit()260 void PowerMgrService::SwitchSubscriberInit()
261 {
262     POWER_HILOGW(FEATURE_INPUT, "Initialize the subscription switch");
263     switchId_ =
264         InputManager::GetInstance()->SubscribeSwitchEvent([this](std::shared_ptr<OHOS::MMI::SwitchEvent> switchEvent) {
265             POWER_HILOGI(FEATURE_WAKEUP, "switch event received");
266             std::shared_ptr<SuspendController> suspendController = pms->GetSuspendController();
267             if (suspendController == nullptr) {
268                 POWER_HILOGE(FEATURE_INPUT, "get suspendController instance error");
269                 return;
270             }
271             std::shared_ptr<WakeupController> wakeupController = pms->GetWakeupController();
272             if (wakeupController == nullptr) {
273                 POWER_HILOGE(FEATURE_INPUT, "wakeupController is not init");
274                 return;
275             }
276             if (switchEvent->GetSwitchValue() == SwitchEvent::SWITCH_OFF) {
277                 POWER_HILOGI(FEATURE_SUSPEND, "Switch close event received, begin to suspend");
278                 SuspendDeviceType reason = SuspendDeviceType::SUSPEND_DEVICE_REASON_SWITCH;
279                 suspendController->ExecSuspendMonitorByReason(reason);
280             } else {
281                 POWER_HILOGI(FEATURE_WAKEUP, "Switch close event received, begin to suspend");
282                 WakeupDeviceType reason = WakeupDeviceType::WAKEUP_DEVICE_SWITCH;
283                 wakeupController->ExecWakeupMonitorByReason(reason);
284             }
285         });
286 }
287 
SwitchSubscriberCancel()288 void PowerMgrService::SwitchSubscriberCancel()
289 {
290     POWER_HILOGI(FEATURE_INPUT, "Unsubscribe switch information");
291     if (switchId_ >= 0) {
292         InputManager::GetInstance()->UnsubscribeSwitchEvent(switchId_);
293         switchId_ = -1;
294     }
295 }
296 
HandleKeyEvent(int32_t keyCode)297 void PowerMgrService::HandleKeyEvent(int32_t keyCode)
298 {
299     POWER_HILOGD(FEATURE_INPUT, "keyCode: %{public}d", keyCode);
300     int64_t now = static_cast<int64_t>(time(nullptr));
301     if (IsScreenOn()) {
302         this->RefreshActivity(now, UserActivityType::USER_ACTIVITY_TYPE_BUTTON, false);
303     } else {
304         if (keyCode == KeyEvent::KEYCODE_F1) {
305             POWER_HILOGI(FEATURE_WAKEUP, "Wakeup by double click");
306             std::string reason = "double click";
307             reason.append(std::to_string(keyCode));
308             this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_DOUBLE_CLICK, reason);
309         } else if (keyCode >= KeyEvent::KEYCODE_0 && keyCode <= KeyEvent::KEYCODE_NUMPAD_RIGHT_PAREN) {
310             POWER_HILOGI(FEATURE_WAKEUP, "Wakeup by keyboard");
311             std::string reason = "keyboard:";
312             reason.append(std::to_string(keyCode));
313             this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_KEYBOARD, reason);
314         }
315     }
316 }
317 
HandlePointEvent(int32_t type)318 void PowerMgrService::HandlePointEvent(int32_t type)
319 {
320     POWER_HILOGD(FEATURE_INPUT, "type: %{public}d", type);
321     int64_t now = static_cast<int64_t>(time(nullptr));
322     if (this->IsScreenOn()) {
323         this->RefreshActivity(now, UserActivityType::USER_ACTIVITY_TYPE_ATTENTION, false);
324     } else {
325         if (type == PointerEvent::SOURCE_TYPE_MOUSE) {
326             std::string reason = "mouse click";
327             POWER_HILOGI(FEATURE_WAKEUP, "Wakeup by mouse");
328             this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_MOUSE, reason);
329         }
330     }
331 }
332 
OnStop()333 void PowerMgrService::OnStop()
334 {
335     POWER_HILOGW(COMP_SVC, "Stop service");
336     if (!ready_) {
337         return;
338     }
339     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
340     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
341     powerStateMachine_->UnregisterDisplayOffTimeObserver();
342     if (suspendController_) {
343         suspendController_->StopSleep();
344     }
345 
346     SystemSuspendController::GetInstance().UnRegisterPowerHdiCallback();
347 
348     KeyMonitorCancel();
349     HallSensorSubscriberCancel();
350     SwitchSubscriberCancel();
351     ready_ = false;
352     isBootCompleted_ = false;
353     RemoveSystemAbilityListener(SUSPEND_MANAGER_SYSTEM_ABILITY_ID);
354     RemoveSystemAbilityListener(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
355 }
356 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)357 void PowerMgrService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
358 {
359     POWER_HILOGI(COMP_SVC, "systemAbilityId=%{public}d, deviceId=%{private}s", systemAbilityId, deviceId.c_str());
360     if (systemAbilityId == SUSPEND_MANAGER_SYSTEM_ABILITY_ID ||
361         systemAbilityId == DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID) {
362         std::lock_guard lock(lockMutex_);
363         runningLockMgr_->ResetRunningLocks();
364     }
365 }
366 
Dump(int32_t fd,const std::vector<std::u16string> & args)367 int32_t PowerMgrService::Dump(int32_t fd, const std::vector<std::u16string>& args)
368 {
369     if (!isBootCompleted_) {
370         return ERR_NO_INIT;
371     }
372     if (!Permission::IsSystem()) {
373         return ERR_PERMISSION_DENIED;
374     }
375     std::vector<std::string> argsInStr;
376     std::transform(args.begin(), args.end(), std::back_inserter(argsInStr), [](const std::u16string& arg) {
377         std::string ret = Str16ToStr8(arg);
378         POWER_HILOGI(COMP_SVC, "arg: %{public}s", ret.c_str());
379         return ret;
380     });
381     std::string result;
382     PowerMgrDumper::Dump(argsInStr, result);
383     if (!SaveStringToFd(fd, result)) {
384         POWER_HILOGE(COMP_SVC, "Dump failed, save to fd failed.");
385         POWER_HILOGE(COMP_SVC, "Dump Info:\n");
386         POWER_HILOGE(COMP_SVC, "%{public}s", result.c_str());
387         return ERR_OK;
388     }
389     return ERR_OK;
390 }
391 
RebootDevice(const std::string & reason)392 PowerErrors PowerMgrService::RebootDevice(const std::string& reason)
393 {
394     if (!Permission::IsSystem()) {
395         return PowerErrors::ERR_SYSTEM_API_DENIED;
396     }
397     return RebootDeviceForDeprecated(reason);
398 }
399 
RebootDeviceForDeprecated(const std::string & reason)400 PowerErrors PowerMgrService::RebootDeviceForDeprecated(const std::string& reason)
401 {
402     std::lock_guard lock(shutdownMutex_);
403     pid_t pid = IPCSkeleton::GetCallingPid();
404     auto uid = IPCSkeleton::GetCallingUid();
405     if (!Permission::IsPermissionGranted("ohos.permission.REBOOT")) {
406         return PowerErrors::ERR_PERMISSION_DENIED;
407     }
408     POWER_HILOGI(FEATURE_SHUTDOWN, "Cancel auto sleep timer");
409     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
410     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
411     if (suspendController_) {
412         suspendController_->StopSleep();
413     }
414     POWER_HILOGI(FEATURE_SHUTDOWN, "Do reboot, called pid: %{public}d, uid: %{public}d", pid, uid);
415     shutdownController_->Reboot(reason);
416     return PowerErrors::ERR_OK;
417 }
418 
ShutDownDevice(const std::string & reason)419 PowerErrors PowerMgrService::ShutDownDevice(const std::string& reason)
420 {
421     auto now = static_cast<int64_t>(time(nullptr));
422     if (!Permission::IsSystem()) {
423         return PowerErrors::ERR_SYSTEM_API_DENIED;
424     }
425     if (!Permission::IsPermissionGranted("ohos.permission.REBOOT")) {
426         return PowerErrors::ERR_PERMISSION_DENIED;
427     }
428     if (reason == SHUTDOWN_FAST_REASON) {
429         g_wakeupReason = reason;
430         POWER_HILOGD(FEATURE_SHUTDOWN, "Calling Fast ShutDownDevice success");
431         return SuspendDevice(now, SuspendDeviceType::SUSPEND_DEVICE_REASON_STR, true);
432     }
433     g_wakeupReason = "";
434     std::lock_guard lock(shutdownMutex_);
435     pid_t pid = IPCSkeleton::GetCallingPid();
436     auto uid = IPCSkeleton::GetCallingUid();
437     POWER_HILOGI(FEATURE_SHUTDOWN, "Cancel auto sleep timer");
438     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
439     powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
440     if (suspendController_) {
441         suspendController_->StopSleep();
442     }
443 
444     POWER_HILOGI(FEATURE_SHUTDOWN, "Do shutdown, called pid: %{public}d, uid: %{public}d", pid, uid);
445     shutdownController_->Shutdown(reason);
446     return PowerErrors::ERR_OK;
447 }
448 
SuspendDevice(int64_t callTimeMs,SuspendDeviceType reason,bool suspendImmed)449 PowerErrors PowerMgrService::SuspendDevice(int64_t callTimeMs, SuspendDeviceType reason, bool suspendImmed)
450 {
451     std::lock_guard lock(suspendMutex_);
452     pid_t pid = IPCSkeleton::GetCallingPid();
453     auto uid = IPCSkeleton::GetCallingUid();
454     if (!Permission::IsSystem()) {
455         return PowerErrors::ERR_SYSTEM_API_DENIED;
456     }
457     if (shutdownController_->IsShuttingDown()) {
458         POWER_HILOGW(FEATURE_SUSPEND, "System is shutting down, can't suspend");
459         return PowerErrors::ERR_OK;
460     }
461     POWER_HILOGI(FEATURE_SUSPEND, "Try to suspend device, pid: %{public}d, uid: %{public}d", pid, uid);
462     powerStateMachine_->SuspendDeviceInner(pid, callTimeMs, reason, suspendImmed);
463     return PowerErrors::ERR_OK;
464 }
465 
WakeupDevice(int64_t callTimeMs,WakeupDeviceType reason,const std::string & details)466 PowerErrors PowerMgrService::WakeupDevice(int64_t callTimeMs, WakeupDeviceType reason, const std::string& details)
467 {
468     std::lock_guard lock(wakeupMutex_);
469     if (!Permission::IsSystem()) {
470         return PowerErrors::ERR_SYSTEM_API_DENIED;
471     }
472     pid_t pid = IPCSkeleton::GetCallingPid();
473     auto uid = IPCSkeleton::GetCallingUid();
474     POWER_HILOGI(FEATURE_WAKEUP, "Try to wakeup device, pid: %{public}d, uid: %{public}d", pid, uid);
475     WakeupRunningLock::Lock();
476     powerStateMachine_->WakeupDeviceInner(pid, callTimeMs, reason, details, "OHOS");
477     WakeupRunningLock::Unlock();
478     return PowerErrors::ERR_OK;
479 }
480 
RefreshActivity(int64_t callTimeMs,UserActivityType type,bool needChangeBacklight)481 bool PowerMgrService::RefreshActivity(int64_t callTimeMs, UserActivityType type, bool needChangeBacklight)
482 {
483     std::lock_guard lock(screenMutex_);
484     if (powerStateMachine_->CheckRefreshTime()) {
485         return false;
486     }
487     if (!Permission::IsPermissionGranted("ohos.permission.REFRESH_USER_ACTION") || !Permission::IsSystem()) {
488         return false;
489     }
490     pid_t pid = IPCSkeleton::GetCallingPid();
491     auto uid = IPCSkeleton::GetCallingUid();
492     POWER_HILOGD(FEATURE_ACTIVITY, "Try to refresh activity, pid: %{public}d, uid: %{public}d", pid, uid);
493     powerStateMachine_->RefreshActivityInner(pid, callTimeMs, type, needChangeBacklight);
494     return true;
495 }
496 
OverrideScreenOffTime(int64_t timeout)497 bool PowerMgrService::OverrideScreenOffTime(int64_t timeout)
498 {
499     std::lock_guard lock(screenMutex_);
500     if (!Permission::IsSystem()) {
501         return false;
502     }
503     POWER_HILOGD(COMP_SVC, "Try to override screen off time");
504     return powerStateMachine_->OverrideScreenOffTimeInner(timeout);
505 }
506 
RestoreScreenOffTime()507 bool PowerMgrService::RestoreScreenOffTime()
508 {
509     std::lock_guard lock(screenMutex_);
510     if (!Permission::IsSystem()) {
511         return false;
512     }
513     POWER_HILOGD(COMP_SVC, "Try to restore screen off time");
514     return powerStateMachine_->RestoreScreenOffTimeInner();
515 }
516 
GetState()517 PowerState PowerMgrService::GetState()
518 {
519     std::lock_guard lock(stateMutex_);
520     auto state = powerStateMachine_->GetState();
521     POWER_HILOGD(FEATURE_POWER_STATE, "state: %{public}d", state);
522     return state;
523 }
524 
IsScreenOn()525 bool PowerMgrService::IsScreenOn()
526 {
527     std::lock_guard lock(stateMutex_);
528     auto isScreenOn = powerStateMachine_->IsScreenOn();
529     POWER_HILOGI(COMP_SVC, "isScreenOn: %{public}d", isScreenOn);
530     return isScreenOn;
531 }
532 
ForceSuspendDevice(int64_t callTimeMs)533 bool PowerMgrService::ForceSuspendDevice(int64_t callTimeMs)
534 {
535     std::lock_guard lock(suspendMutex_);
536     pid_t pid = IPCSkeleton::GetCallingPid();
537     auto uid = IPCSkeleton::GetCallingUid();
538     if (!Permission::IsSystem()) {
539         return false;
540     }
541     if (shutdownController_->IsShuttingDown()) {
542         POWER_HILOGI(FEATURE_SUSPEND, "System is shutting down, can't force suspend");
543         return false;
544     }
545     POWER_HILOGI(FEATURE_SUSPEND, "Try to force suspend device, pid: %{public}d, uid: %{public}d", pid, uid);
546     return powerStateMachine_->ForceSuspendDeviceInner(pid, callTimeMs);
547 }
548 
FillRunningLockParam(const RunningLockInfo & info,int32_t timeOutMS)549 RunningLockParam PowerMgrService::FillRunningLockParam(const RunningLockInfo& info, int32_t timeOutMS)
550 {
551     RunningLockParam filledParam {};
552     filledParam.name = info.name;
553     filledParam.type = info.type;
554     filledParam.timeoutMs = timeOutMS;
555     filledParam.pid = IPCSkeleton::GetCallingPid();
556     filledParam.uid = IPCSkeleton::GetCallingUid();
557     return filledParam;
558 }
559 
CreateRunningLock(const sptr<IRemoteObject> & remoteObj,const RunningLockInfo & runningLockInfo)560 PowerErrors PowerMgrService::CreateRunningLock(
561     const sptr<IRemoteObject>& remoteObj, const RunningLockInfo& runningLockInfo)
562 {
563     std::lock_guard lock(lockMutex_);
564     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
565         return PowerErrors::ERR_PERMISSION_DENIED;
566     }
567     if (!IsRunningLockTypeSupported(runningLockInfo.type)) {
568         POWER_HILOGW(FEATURE_RUNNING_LOCK, "Create runninglock failed, name: %{public}s, type: %{public}d",
569             runningLockInfo.name.c_str(), runningLockInfo.type);
570         return PowerErrors::ERR_PARAM_INVALID;
571     }
572     POWER_HILOGI(
573         FEATURE_RUNNING_LOCK, "name: %{public}s, type: %{public}d", runningLockInfo.name.c_str(), runningLockInfo.type);
574 
575     RunningLockParam runningLockParam = FillRunningLockParam(runningLockInfo);
576     runningLockMgr_->CreateRunningLock(remoteObj, runningLockParam);
577     return PowerErrors::ERR_OK;
578 }
579 
ReleaseRunningLock(const sptr<IRemoteObject> & remoteObj)580 bool PowerMgrService::ReleaseRunningLock(const sptr<IRemoteObject>& remoteObj)
581 {
582     std::lock_guard lock(lockMutex_);
583     bool result = false;
584     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
585         return result;
586     }
587 
588     result = runningLockMgr_->ReleaseLock(remoteObj);
589     return result;
590 }
591 
IsRunningLockTypeSupported(RunningLockType type)592 bool PowerMgrService::IsRunningLockTypeSupported(RunningLockType type)
593 {
594     if (Permission::IsHap()) {
595         return type <= RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL;
596     }
597     return type == RunningLockType::RUNNINGLOCK_SCREEN ||
598         type == RunningLockType::RUNNINGLOCK_BACKGROUND || // this will be instead by BACKGROUND_XXX types.
599         type == RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL ||
600         type == RunningLockType::RUNNINGLOCK_BACKGROUND_PHONE ||
601         type == RunningLockType::RUNNINGLOCK_BACKGROUND_NOTIFICATION ||
602         type == RunningLockType::RUNNINGLOCK_BACKGROUND_AUDIO ||
603         type == RunningLockType::RUNNINGLOCK_BACKGROUND_SPORT ||
604         type == RunningLockType::RUNNINGLOCK_BACKGROUND_NAVIGATION ||
605         type == RunningLockType::RUNNINGLOCK_BACKGROUND_TASK;
606 }
607 
Lock(const sptr<IRemoteObject> & remoteObj,int32_t timeOutMS)608 bool PowerMgrService::Lock(const sptr<IRemoteObject>& remoteObj, int32_t timeOutMS)
609 {
610     std::lock_guard lock(lockMutex_);
611     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
612         return false;
613     }
614 
615     POWER_HILOGI(FEATURE_RUNNING_LOCK, "timeOutMS: %{public}d", timeOutMS);
616     runningLockMgr_->Lock(remoteObj, timeOutMS);
617     return true;
618 }
619 
UnLock(const sptr<IRemoteObject> & remoteObj)620 bool PowerMgrService::UnLock(const sptr<IRemoteObject>& remoteObj)
621 {
622     std::lock_guard lock(lockMutex_);
623     if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
624         return false;
625     }
626     runningLockMgr_->UnLock(remoteObj);
627     return true;
628 }
629 
ForceUnLock(const sptr<IRemoteObject> & remoteObj)630 void PowerMgrService::ForceUnLock(const sptr<IRemoteObject>& remoteObj)
631 {
632     std::lock_guard lock(lockMutex_);
633     runningLockMgr_->UnLock(remoteObj);
634     runningLockMgr_->ReleaseLock(remoteObj);
635 }
636 
IsUsed(const sptr<IRemoteObject> & remoteObj)637 bool PowerMgrService::IsUsed(const sptr<IRemoteObject>& remoteObj)
638 {
639     std::lock_guard lock(lockMutex_);
640     auto isUsed = runningLockMgr_->IsUsed(remoteObj);
641     POWER_HILOGD(FEATURE_RUNNING_LOCK, "RunningLock is Used: %{public}d", isUsed);
642     return isUsed;
643 }
644 
NotifyRunningLockChanged(bool isUnLock)645 void PowerMgrService::NotifyRunningLockChanged(bool isUnLock)
646 {
647     if (isUnLock) {
648         // When unlock we try to suspend
649         if (!runningLockMgr_->ExistValidRunningLock() && !powerStateMachine_->IsScreenOn()) {
650             // runninglock is empty and Screen is off,
651             // so we try to suspend device from Z side.
652             POWER_HILOGI(FEATURE_RUNNING_LOCK, "RunningLock is empty, try to suspend");
653             powerStateMachine_->SuspendDeviceInner(
654                 getpid(), GetTickCount(), SuspendDeviceType::SUSPEND_DEVICE_REASON_MIN, true, true);
655         }
656     }
657 }
658 
ProxyRunningLock(bool isProxied,pid_t pid,pid_t uid)659 bool PowerMgrService::ProxyRunningLock(bool isProxied, pid_t pid, pid_t uid)
660 {
661     std::lock_guard lock(lockMutex_);
662     if (!Permission::IsSystem()) {
663         return false;
664     }
665     return runningLockMgr_->ProxyRunningLock(isProxied, pid, uid);
666 }
667 
ProxyRunningLocks(bool isProxied,const std::vector<std::pair<pid_t,pid_t>> & processInfos)668 bool PowerMgrService::ProxyRunningLocks(bool isProxied, const std::vector<std::pair<pid_t, pid_t>>& processInfos)
669 {
670     if (!Permission::IsSystem()) {
671         return false;
672     }
673     std::lock_guard lock(lockMutex_);
674     runningLockMgr_->ProxyRunningLocks(isProxied, processInfos);
675     return true;
676 }
677 
ResetRunningLocks()678 bool PowerMgrService::ResetRunningLocks()
679 {
680     if (!Permission::IsSystem()) {
681         return false;
682     }
683     std::lock_guard lock(lockMutex_);
684     runningLockMgr_->ResetRunningLocks();
685     return true;
686 }
687 
RegisterPowerStateCallback(const sptr<IPowerStateCallback> & callback)688 bool PowerMgrService::RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
689 {
690     std::lock_guard lock(stateMutex_);
691     pid_t pid = IPCSkeleton::GetCallingPid();
692     auto uid = IPCSkeleton::GetCallingUid();
693     if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
694         return false;
695     }
696     POWER_HILOGI(FEATURE_POWER_STATE, "pid: %{public}d, uid: %{public}d", pid, uid);
697     powerStateMachine_->RegisterPowerStateCallback(callback);
698     return true;
699 }
700 
UnRegisterPowerStateCallback(const sptr<IPowerStateCallback> & callback)701 bool PowerMgrService::UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
702 {
703     std::lock_guard lock(stateMutex_);
704     pid_t pid = IPCSkeleton::GetCallingPid();
705     auto uid = IPCSkeleton::GetCallingUid();
706     if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
707         return false;
708     }
709     POWER_HILOGI(FEATURE_POWER_STATE, "pid: %{public}d, uid: %{public}d", pid, uid);
710     powerStateMachine_->UnRegisterPowerStateCallback(callback);
711     return true;
712 }
713 
RegisterPowerModeCallback(const sptr<IPowerModeCallback> & callback)714 bool PowerMgrService::RegisterPowerModeCallback(const sptr<IPowerModeCallback>& callback)
715 {
716     std::lock_guard lock(modeMutex_);
717     pid_t pid = IPCSkeleton::GetCallingPid();
718     auto uid = IPCSkeleton::GetCallingUid();
719     if (!Permission::IsSystem()) {
720         return false;
721     }
722     POWER_HILOGI(FEATURE_POWER_MODE, "pid: %{public}d, uid: %{public}d", pid, uid);
723     powerModeModule_.AddPowerModeCallback(callback);
724     return true;
725 }
726 
UnRegisterPowerModeCallback(const sptr<IPowerModeCallback> & callback)727 bool PowerMgrService::UnRegisterPowerModeCallback(const sptr<IPowerModeCallback>& callback)
728 {
729     std::lock_guard lock(modeMutex_);
730     pid_t pid = IPCSkeleton::GetCallingPid();
731     auto uid = IPCSkeleton::GetCallingUid();
732     if (!Permission::IsSystem()) {
733         return false;
734     }
735     POWER_HILOGI(FEATURE_POWER_MODE, "pid: %{public}d, uid: %{public}d", pid, uid);
736     powerModeModule_.DelPowerModeCallback(callback);
737     return true;
738 }
739 
SetDisplaySuspend(bool enable)740 bool PowerMgrService::SetDisplaySuspend(bool enable)
741 {
742     std::lock_guard lock(screenMutex_);
743     pid_t pid = IPCSkeleton::GetCallingPid();
744     auto uid = IPCSkeleton::GetCallingUid();
745     if (!Permission::IsSystem()) {
746         return false;
747     }
748     POWER_HILOGI(FEATURE_SUSPEND, "pid: %{public}d, uid: %{public}d, enable: %{public}d", pid, uid, enable);
749     powerStateMachine_->SetDisplaySuspend(enable);
750     return true;
751 }
752 
SetDeviceMode(const PowerMode & mode)753 PowerErrors PowerMgrService::SetDeviceMode(const PowerMode& mode)
754 {
755     std::lock_guard lock(modeMutex_);
756     pid_t pid = IPCSkeleton::GetCallingPid();
757     auto uid = IPCSkeleton::GetCallingUid();
758     POWER_HILOGI(FEATURE_POWER_MODE, "pid: %{public}d, uid: %{public}d, mode: %{public}u", pid, uid, mode);
759     if (!Permission::IsSystem()) {
760         return PowerErrors::ERR_SYSTEM_API_DENIED;
761     }
762     if (!Permission::IsPermissionGranted("ohos.permission.POWER_OPTIMIZATION")) {
763         return PowerErrors::ERR_PERMISSION_DENIED;
764     }
765     powerModeModule_.SetModeItem(mode);
766     return PowerErrors::ERR_OK;
767 }
768 
GetDeviceMode()769 PowerMode PowerMgrService::GetDeviceMode()
770 {
771     std::lock_guard lock(modeMutex_);
772     pid_t pid = IPCSkeleton::GetCallingPid();
773     auto uid = IPCSkeleton::GetCallingUid();
774     auto mode = powerModeModule_.GetModeItem();
775     POWER_HILOGI(FEATURE_POWER_MODE, "pid: %{public}d, uid: %{public}d, mode: %{public}u", pid, uid, mode);
776     return mode;
777 }
778 
ShellDump(const std::vector<std::string> & args,uint32_t argc)779 std::string PowerMgrService::ShellDump(const std::vector<std::string>& args, uint32_t argc)
780 {
781     if (!Permission::IsSystem() || !isBootCompleted_) {
782         return "";
783     }
784     std::lock_guard lock(dumpMutex_);
785     pid_t pid = IPCSkeleton::GetCallingPid();
786     auto uid = IPCSkeleton::GetCallingUid();
787     POWER_HILOGI(COMP_SVC, "pid: %{public}d, uid: %{public}d", pid, uid);
788 
789     std::string result;
790     bool ret = PowerMgrDumper::Dump(args, result);
791     POWER_HILOGI(COMP_SVC, "ret :%{public}d", ret);
792     return result;
793 }
794 
RegisterShutdownCallback(const sptr<ITakeOverShutdownCallback> & callback,ShutdownPriority priority)795 void PowerMgrService::RegisterShutdownCallback(
796     const sptr<ITakeOverShutdownCallback>& callback, ShutdownPriority priority)
797 {
798     RETURN_IF (callback == nullptr);
799     RETURN_IF (!Permission::IsSystem());
800 
801     std::lock_guard lock(shutdownMutex_);
802     shutdownController_->AddCallback(callback, priority);
803 }
804 
UnRegisterShutdownCallback(const sptr<ITakeOverShutdownCallback> & callback)805 void PowerMgrService::UnRegisterShutdownCallback(const sptr<ITakeOverShutdownCallback>& callback)
806 {
807     RETURN_IF (callback == nullptr);
808     RETURN_IF (!Permission::IsSystem());
809 
810     std::lock_guard lock(shutdownMutex_);
811     shutdownController_->RemoveCallback(callback);
812 }
813 
RegisterShutdownCallback(const sptr<IAsyncShutdownCallback> & callback,ShutdownPriority priority)814 void PowerMgrService::RegisterShutdownCallback(
815     const sptr<IAsyncShutdownCallback>& callback, ShutdownPriority priority)
816 {
817     RETURN_IF (callback == nullptr);
818     RETURN_IF (!Permission::IsSystem());
819 
820     std::lock_guard lock(shutdownMutex_);
821     shutdownController_->AddCallback(callback, priority);
822 }
823 
UnRegisterShutdownCallback(const sptr<IAsyncShutdownCallback> & callback)824 void PowerMgrService::UnRegisterShutdownCallback(const sptr<IAsyncShutdownCallback>& callback)
825 {
826     RETURN_IF (callback == nullptr);
827     RETURN_IF (!Permission::IsSystem());
828 
829     std::lock_guard lock(shutdownMutex_);
830     shutdownController_->RemoveCallback(callback);
831 }
832 
RegisterShutdownCallback(const sptr<ISyncShutdownCallback> & callback,ShutdownPriority priority)833 void PowerMgrService::RegisterShutdownCallback(
834     const sptr<ISyncShutdownCallback>& callback, ShutdownPriority priority)
835 {
836     RETURN_IF (callback == nullptr);
837     RETURN_IF (!Permission::IsSystem());
838 
839     std::lock_guard lock(shutdownMutex_);
840     shutdownController_->AddCallback(callback, priority);
841 }
842 
UnRegisterShutdownCallback(const sptr<ISyncShutdownCallback> & callback)843 void PowerMgrService::UnRegisterShutdownCallback(const sptr<ISyncShutdownCallback>& callback)
844 {
845     RETURN_IF (callback == nullptr);
846     RETURN_IF (!Permission::IsSystem());
847 
848     std::lock_guard lock(shutdownMutex_);
849     shutdownController_->RemoveCallback(callback);
850 }
851 
852 sptr<RunningLockTokenStub> PowerMgrService::WakeupRunningLock::token_;
853 
Create()854 void PowerMgrService::WakeupRunningLock::Create()
855 {
856     token_ = new (std::nothrow) RunningLockTokenStub();
857     if (!token_) {
858         POWER_HILOGE(COMP_SVC, "create runninglock token failed");
859         return;
860     }
861     RunningLockInfo info = {"PowerMgrWakeupLock", OHOS::PowerMgr::RunningLockType::RUNNINGLOCK_BACKGROUND_TASK};
862     pms->CreateRunningLock(token_->AsObject(), info);
863 }
864 
Lock()865 void PowerMgrService::WakeupRunningLock::Lock()
866 {
867     if (!token_) {
868         return;
869     }
870     pms->Lock(token_->AsObject(), TIMEOUT);
871 }
872 
Unlock()873 void PowerMgrService::WakeupRunningLock::Unlock()
874 {
875     if (!token_) {
876         return;
877     }
878     if (pms->IsUsed(token_)) {
879         pms->UnLock(token_->AsObject());
880     }
881 }
882 
SuspendControllerInit()883 void PowerMgrService::SuspendControllerInit()
884 {
885     if (!suspendController_) {
886         suspendController_ = std::make_shared<SuspendController>(shutdownController_, powerStateMachine_);
887     }
888     suspendController_->Init();
889 }
890 
WakeupControllerInit()891 void PowerMgrService::WakeupControllerInit()
892 {
893     if (!wakeupController_) {
894         wakeupController_ = std::make_shared<WakeupController>(powerStateMachine_);
895     }
896     wakeupController_->Init();
897 }
898 
IsStandby(bool & isStandby)899 PowerErrors PowerMgrService::IsStandby(bool& isStandby)
900 {
901     DevStandbyMgr::StandbyServiceClient& standbyServiceClient = DevStandbyMgr::StandbyServiceClient::GetInstance();
902     ErrCode code = standbyServiceClient.IsDeviceInStandby(isStandby);
903     if (code == ERR_OK) {
904         return PowerErrors::ERR_OK;
905     }
906     return PowerErrors::ERR_CONNECTION_FAIL;
907 }
908 
909 } // namespace PowerMgr
910 } // namespace OHOS
911