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 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
23 #include <input_manager.h>
24 #endif
25 #include <ipc_skeleton.h>
26 #include <iservice_registry.h>
27 #include <securec.h>
28 #include <string_ex.h>
29 #include <system_ability_definition.h>
30 #include <sys_mgr_client.h>
31 #include <bundle_mgr_client.h>
32 #include <unistd.h>
33 #include "ability_connect_callback_stub.h"
34 #include "ability_manager_client.h"
35 #include "ffrt_utils.h"
36 #include "permission.h"
37 #include "power_common.h"
38 #include "power_mgr_dumper.h"
39 #include "power_vibrator.h"
40 #include "power_xcollie.h"
41 #include "setting_helper.h"
42 #include "running_lock_timer_handler.h"
43 #include "sysparam.h"
44 #include "system_suspend_controller.h"
45 #include "xcollie/watchdog.h"
46 #include "errors.h"
47 #include "parameters.h"
48 #ifdef HAS_DEVICE_STANDBY_PART
49 #include "standby_service_client.h"
50 #endif
51 #ifdef MSDP_MOVEMENT_ENABLE
52 #include <dlfcn.h>
53 #endif
54
55 using namespace OHOS::AppExecFwk;
56 using namespace OHOS::AAFwk;
57 namespace OHOS {
58 namespace PowerMgr {
59 namespace {
60 const std::string POWERMGR_SERVICE_NAME = "PowerMgrService";
61 const std::string REASON_POWER_KEY = "power_key";
62 static std::string g_wakeupReason = "";
63 const std::string POWER_VIBRATOR_CONFIG_FILE = "etc/power_config/power_vibrator.json";
64 const std::string VENDOR_POWER_VIBRATOR_CONFIG_FILE = "/vendor/etc/power_config/power_vibrator.json";
65 const std::string SYSTEM_POWER_VIBRATOR_CONFIG_FILE = "/system/etc/power_config/power_vibrator.json";
66 constexpr int32_t WAKEUP_LOCK_TIMEOUT_MS = 5000;
67 constexpr int32_t COLLABORATION_REMOTE_DEVICE_ID = 0xAAAAAAFF;
68 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
69 const bool G_REGISTER_RESULT = SystemAbility::MakeAndRegisterAbility(pms.GetRefPtr());
70 SysParam::BootCompletedCallback g_bootCompletedCallback;
71 bool g_inLidMode = false;
72 } // namespace
73
74 std::atomic_bool PowerMgrService::isBootCompleted_ = false;
75 using namespace MMI;
76
PowerMgrService()77 PowerMgrService::PowerMgrService() : SystemAbility(POWER_MANAGER_SERVICE_ID, true) {}
78
~PowerMgrService()79 PowerMgrService::~PowerMgrService() {}
80
OnStart()81 void PowerMgrService::OnStart()
82 {
83 POWER_HILOGD(COMP_SVC, "Power Management startup");
84 if (ready_) {
85 POWER_HILOGW(COMP_SVC, "OnStart is ready, nothing to do");
86 return;
87 }
88 if (!Init()) {
89 POWER_HILOGE(COMP_SVC, "Call init fail");
90 return;
91 }
92 AddSystemAbilityListener(SUSPEND_MANAGER_SYSTEM_ABILITY_ID);
93 AddSystemAbilityListener(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
94 AddSystemAbilityListener(DISPLAY_MANAGER_SERVICE_ID);
95 AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID);
96 #ifdef MSDP_MOVEMENT_ENABLE
97 AddSystemAbilityListener(MSDP_MOVEMENT_SERVICE_ID);
98 #endif
99 SystemSuspendController::GetInstance().RegisterHdiStatusListener();
100 if (!Publish(DelayedSpSingleton<PowerMgrService>::GetInstance())) {
101 POWER_HILOGE(COMP_SVC, "Register to system ability manager failed");
102 return;
103 }
104 ready_ = true;
105 POWER_HILOGI(COMP_SVC, "Add system ability success");
106 }
107
Init()108 bool PowerMgrService::Init()
109 {
110 POWER_HILOGI(COMP_SVC, "Init start");
111 if (!runningLockMgr_) {
112 runningLockMgr_ = std::make_shared<RunningLockMgr>(pms);
113 }
114 if (!runningLockMgr_->Init()) {
115 POWER_HILOGE(COMP_SVC, "Running lock init fail");
116 return false;
117 }
118 if (!shutdownController_) {
119 shutdownController_ = std::make_shared<ShutdownController>();
120 }
121 if (!PowerStateMachineInit()) {
122 POWER_HILOGE(COMP_SVC, "Power state machine init fail");
123 }
124 if (!screenOffPreController_) {
125 screenOffPreController_ = std::make_shared<ScreenOffPreController>(powerStateMachine_);
126 screenOffPreController_->Init();
127 }
128 POWER_HILOGI(COMP_SVC, "Init success");
129 return true;
130 }
131
RegisterBootCompletedCallback()132 void PowerMgrService::RegisterBootCompletedCallback()
133 {
134 g_bootCompletedCallback = []() {
135 POWER_HILOGI(COMP_SVC, "BootCompletedCallback triggered");
136 auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
137 if (power == nullptr) {
138 POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
139 return;
140 }
141 auto powerStateMachine = power->GetPowerStateMachine();
142 powerStateMachine->RegisterDisplayOffTimeObserver();
143 powerStateMachine->InitState();
144 #ifdef POWER_MANAGER_POWER_DIALOG
145 power->GetShutdownDialog().LoadDialogConfig();
146 power->GetShutdownDialog().KeyMonitorInit();
147 #endif
148 #ifndef CONFIG_FACTORY_MODE
149 power->RegisterSettingWakeUpLidObserver();
150 POWER_HILOGI(COMP_SVC, "Allow subscribe Hall sensor");
151 #else
152 POWER_HILOGI(COMP_SVC, "Not allow subscribe Hall sensor");
153 #endif
154 power->SwitchSubscriberInit();
155 power->InputMonitorInit();
156 SettingHelper::UpdateCurrentUserId();
157 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
158 SettingHelper::CopyDataForUpdateScene();
159 #endif
160 power->SuspendControllerInit();
161 power->WakeupControllerInit();
162 power->SubscribeCommonEvent();
163 #ifdef POWER_MANAGER_WAKEUP_ACTION
164 power->WakeupActionControllerInit();
165 #endif
166 power->VibratorInit();
167 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
168 power->RegisterSettingObservers();
169 power->RegisterSettingWakeupPickupGestureObserver();
170 #endif
171 power->RegisterSettingPowerModeObservers();
172 power->KeepScreenOnInit();
173 isBootCompleted_ = true;
174 };
175 SysParam::RegisterBootCompletedCallback(g_bootCompletedCallback);
176 }
177
RegisterSettingPowerModeObservers()178 void PowerMgrService::RegisterSettingPowerModeObservers()
179 {
180 SettingObserver::UpdateFunc updateFunc = [&](const std::string &key) { PowerModeSettingUpdateFunc(key); };
181 SettingHelper::RegisterSettingPowerModeObserver(updateFunc);
182 }
183
PowerModeSettingUpdateFunc(const std::string & key)184 void PowerMgrService::PowerModeSettingUpdateFunc(const std::string &key)
185 {
186 auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
187 int32_t currMode = static_cast<int32_t>(power->GetDeviceMode());
188 int32_t saveMode = SettingHelper::ReadCurrentMode(currMode);
189 if (currMode == saveMode) {
190 return;
191 }
192 POWER_HILOGI(COMP_SVC, "PowerModeSettingUpdateFunc curr:%{public}d, saveMode:%{public}d", currMode, saveMode);
193 power->SetDeviceMode(static_cast<PowerMode>(saveMode));
194 }
195
IsDeveloperMode()196 bool PowerMgrService::IsDeveloperMode()
197 {
198 return OHOS::system::GetBoolParameter("const.security.developermode.state", true);
199 }
200
KeepScreenOnInit()201 void PowerMgrService::KeepScreenOnInit()
202 {
203 if (ptoken_ != nullptr) {
204 POWER_HILOGI(COMP_SVC, "runninglock token is not null");
205 return;
206 }
207 ptoken_ = new (std::nothrow) RunningLockTokenStub();
208 if (ptoken_ == nullptr) {
209 POWER_HILOGI(COMP_SVC, "create runninglock token failed");
210 return;
211 }
212 RunningLockInfo info = {"PowerMgrKeepOnLock", OHOS::PowerMgr::RunningLockType::RUNNINGLOCK_SCREEN};
213 PowerErrors ret = pms->CreateRunningLock(ptoken_, info);
214 if (ret != PowerErrors::ERR_OK) {
215 POWER_HILOGI(COMP_SVC, "create runninglock failed");
216 }
217 return;
218 }
219
KeepScreenOn(bool isOpenOn)220 void PowerMgrService::KeepScreenOn(bool isOpenOn)
221 {
222 if (!IsDeveloperMode()) {
223 POWER_HILOGI(COMP_SVC, "not developer mode");
224 return;
225 }
226 if (ptoken_ == nullptr) {
227 POWER_HILOGI(COMP_SVC, "runninglock token is null");
228 return;
229 }
230 if (isOpenOn) {
231 POWER_HILOGI(COMP_SVC, "try lock RUNNINGLOCK_SCREEN");
232 pms->Lock(ptoken_);
233 } else {
234 POWER_HILOGI(COMP_SVC, "try unlock RUNNINGLOCK_SCREEN");
235 pms->UnLock(ptoken_);
236 }
237 return;
238 }
239
240 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
RegisterSettingObservers()241 void PowerMgrService::RegisterSettingObservers()
242 {
243 RegisterSettingWakeupDoubleClickObservers();
244 }
245
RegisterSettingWakeupDoubleClickObservers()246 void PowerMgrService::RegisterSettingWakeupDoubleClickObservers()
247 {
248 SettingObserver::UpdateFunc updateFunc = [&](const std::string& key) {WakeupDoubleClickSettingUpdateFunc(key); };
249 SettingHelper::RegisterSettingWakeupDoubleObserver(updateFunc);
250 }
251
WakeupDoubleClickSettingUpdateFunc(const std::string & key)252 void PowerMgrService::WakeupDoubleClickSettingUpdateFunc(const std::string& key)
253 {
254 bool isSettingEnable = GetSettingWakeupDoubleClick(key);
255 WakeupController::ChangeWakeupSourceConfig(isSettingEnable);
256 WakeupController::SetWakeupDoubleClickSensor(isSettingEnable);
257 POWER_HILOGI(COMP_SVC, "WakeupDoubleClickSettingUpdateFunc isSettingEnable=%{public}d", isSettingEnable);
258 }
259
GetSettingWakeupDoubleClick(const std::string & key)260 bool PowerMgrService::GetSettingWakeupDoubleClick(const std::string& key)
261 {
262 return SettingHelper::GetSettingWakeupDouble(key);
263 }
264
RegisterSettingWakeupPickupGestureObserver()265 void PowerMgrService::RegisterSettingWakeupPickupGestureObserver()
266 {
267 SettingObserver::UpdateFunc updateFunc = [&](const std::string& key) {WakeupPickupGestureSettingUpdateFunc(key);};
268 SettingHelper::RegisterSettingWakeupPickupObserver(updateFunc);
269 }
270
WakeupPickupGestureSettingUpdateFunc(const std::string & key)271 void PowerMgrService::WakeupPickupGestureSettingUpdateFunc(const std::string& key)
272 {
273 bool isSettingEnable = SettingHelper::GetSettingWakeupPickup(key);
274 WakeupController::PickupConnectMotionConfig(isSettingEnable);
275 POWER_HILOGI(COMP_SVC, "PickupConnectMotionConfig done, isSettingEnable=%{public}d", isSettingEnable);
276 WakeupController::ChangePickupWakeupSourceConfig(isSettingEnable);
277 POWER_HILOGI(COMP_SVC, "ChangePickupWakeupSourceConfig done");
278 }
279 #endif
280
PowerStateMachineInit()281 bool PowerMgrService::PowerStateMachineInit()
282 {
283 if (powerStateMachine_ == nullptr) {
284 powerStateMachine_ = std::make_shared<PowerStateMachine>(pms);
285 if (!(powerStateMachine_->Init())) {
286 POWER_HILOGE(COMP_SVC, "Power state machine start fail!");
287 return false;
288 }
289 }
290 if (powerMgrNotify_ == nullptr) {
291 powerMgrNotify_ = std::make_shared<PowerMgrNotify>();
292 powerMgrNotify_->RegisterPublishEvents();
293 }
294 return true;
295 }
296
KeyMonitorCancel()297 void PowerMgrService::KeyMonitorCancel()
298 {
299 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
300 POWER_HILOGI(FEATURE_INPUT, "Unsubscribe key information");
301 InputManager* inputManager = InputManager::GetInstance();
302 if (inputManager == nullptr) {
303 POWER_HILOGI(FEATURE_INPUT, "InputManager is null");
304 return;
305 }
306 shutdownDialog_.KeyMonitorCancel();
307 if (doubleClickId_ >= 0) {
308 inputManager->UnsubscribeKeyEvent(doubleClickId_);
309 }
310 if (monitorId_ >= 0) {
311 inputManager->RemoveMonitor(monitorId_);
312 }
313 #endif
314 }
315
WakeupLidSettingUpdateFunc(const std::string & key)316 void PowerMgrService::WakeupLidSettingUpdateFunc(const std::string& key)
317 {
318 POWER_HILOGI(COMP_SVC, "Receive lid wakeup setting update.");
319 bool enable = SettingHelper::GetSettingWakeupLid(key);
320 if (enable) {
321 pms->HallSensorSubscriberInit();
322 } else {
323 pms->HallSensorSubscriberCancel();
324 }
325 std::shared_ptr<WakeupController> wakeupController = pms->GetWakeupController();
326 if (wakeupController == nullptr) {
327 POWER_HILOGE(FEATURE_INPUT, "wakeupController is not init");
328 return;
329 }
330 wakeupController->ChangeLidWakeupSourceConfig(enable);
331 POWER_HILOGI(COMP_SVC, "ChangeLidWakeupSourceConfig done");
332 }
333
RegisterSettingWakeUpLidObserver()334 void PowerMgrService::RegisterSettingWakeUpLidObserver()
335 {
336 pms->HallSensorSubscriberInit();
337 POWER_HILOGI(COMP_SVC, "Start to registerSettingWakeUpLidObserver");
338 if (!SettingHelper::IsWakeupLidSettingValid()) {
339 POWER_HILOGE(COMP_UTILS, "settings.power.wakeup_lid is valid.");
340 return;
341 }
342 SettingObserver::UpdateFunc updateFunc = [&](const std::string& key) {WakeupLidSettingUpdateFunc(key);};
343 SettingHelper::RegisterSettingWakeupLidObserver(updateFunc);
344 }
345
HallSensorSubscriberInit()346 void PowerMgrService::HallSensorSubscriberInit()
347 {
348 #ifdef HAS_SENSORS_SENSOR_PART
349 POWER_HILOGI(COMP_SVC, "Start to subscribe hall sensor");
350 if (!IsSupportSensor(SENSOR_TYPE_ID_HALL)) {
351 POWER_HILOGW(FEATURE_INPUT, "SENSOR_TYPE_ID_HALL sensor not support");
352 return;
353 }
354 if (strcpy_s(sensorUser_.name, sizeof(sensorUser_.name), "PowerManager") != EOK) {
355 POWER_HILOGW(FEATURE_INPUT, "strcpy_s error");
356 return;
357 }
358 sensorUser_.userData = nullptr;
359 sensorUser_.callback = &HallSensorCallback;
360 SubscribeSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
361 SetBatch(SENSOR_TYPE_ID_HALL, &sensorUser_, HALL_SAMPLING_RATE, HALL_REPORT_INTERVAL);
362 ActivateSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
363 #endif
364 }
365
366 #ifdef HAS_SENSORS_SENSOR_PART
IsSupportSensor(SensorTypeId typeId)367 bool PowerMgrService::IsSupportSensor(SensorTypeId typeId)
368 {
369 bool isSupport = false;
370 SensorInfo* sensorInfo = nullptr;
371 int32_t count;
372 int32_t ret = GetAllSensors(&sensorInfo, &count);
373 if (ret != 0 || sensorInfo == nullptr) {
374 POWER_HILOGW(FEATURE_INPUT, "Get sensors fail, ret=%{public}d", ret);
375 return isSupport;
376 }
377 for (int32_t i = 0; i < count; i++) {
378 if (sensorInfo[i].sensorTypeId == typeId) {
379 isSupport = true;
380 break;
381 }
382 }
383 return isSupport;
384 }
385
HallSensorCallback(SensorEvent * event)386 void PowerMgrService::HallSensorCallback(SensorEvent* event)
387 {
388 if (event == nullptr || event->sensorTypeId != SENSOR_TYPE_ID_HALL || event->data == nullptr) {
389 POWER_HILOGW(FEATURE_INPUT, "Hall sensor event is invalid");
390 return;
391 }
392
393 std::shared_ptr<SuspendController> suspendController = pms->GetSuspendController();
394 if (suspendController == nullptr) {
395 POWER_HILOGE(FEATURE_INPUT, "get suspendController instance error");
396 return;
397 }
398
399 std::shared_ptr<WakeupController> wakeupController = pms->GetWakeupController();
400 if (wakeupController == nullptr) {
401 POWER_HILOGE(FEATURE_INPUT, "wakeupController is not init");
402 return;
403 }
404 const uint32_t LID_CLOSED_HALL_FLAG = 0x1;
405 auto data = reinterpret_cast<HallData*>(event->data);
406 auto status = static_cast<uint32_t>(data->status);
407
408 if (status & LID_CLOSED_HALL_FLAG) {
409 POWER_HILOGI(FEATURE_SUSPEND, "[UL_POWER] Lid close event received, begin to suspend");
410 g_inLidMode = true;
411 SuspendDeviceType reason = SuspendDeviceType::SUSPEND_DEVICE_REASON_LID;
412 suspendController->ExecSuspendMonitorByReason(reason);
413 } else {
414 if (!g_inLidMode) {
415 return;
416 }
417 POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Lid open event received, begin to wakeup");
418 g_inLidMode = false;
419 WakeupDeviceType reason = WakeupDeviceType::WAKEUP_DEVICE_LID;
420 wakeupController->ExecWakeupMonitorByReason(reason);
421 }
422 }
423 #endif
424
HallSensorSubscriberCancel()425 void PowerMgrService::HallSensorSubscriberCancel()
426 {
427 #ifdef HAS_SENSORS_SENSOR_PART
428 POWER_HILOGI(COMP_SVC, "Start to cancel the subscribe of hall sensor");
429 if (IsSupportSensor(SENSOR_TYPE_ID_HALL)) {
430 DeactivateSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
431 UnsubscribeSensor(SENSOR_TYPE_ID_HALL, &sensorUser_);
432 }
433 #endif
434 }
435
CheckDialogFlag()436 bool PowerMgrService::CheckDialogFlag()
437 {
438 bool isLongPress = shutdownDialog_.IsLongPress();
439 if (isLongPress) {
440 shutdownDialog_.ResetLongPressFlag();
441 }
442 return true;
443 }
444
CheckDialogAndShuttingDown()445 bool PowerMgrService::CheckDialogAndShuttingDown()
446 {
447 bool isShuttingDown = shutdownController_->IsShuttingDown();
448 bool isLongPress = shutdownDialog_.IsLongPress();
449 if (isLongPress || isShuttingDown) {
450 POWER_HILOGW(
451 FEATURE_INPUT, "isLongPress: %{public}d, isShuttingDown: %{public}d", isLongPress, isShuttingDown);
452 shutdownDialog_.ResetLongPressFlag();
453 return true;
454 }
455 return false;
456 }
457
SwitchSubscriberInit()458 void PowerMgrService::SwitchSubscriberInit()
459 {
460 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
461 POWER_HILOGW(FEATURE_INPUT, "Initialize the subscription switch");
462 switchId_ =
463 InputManager::GetInstance()->SubscribeSwitchEvent([this](std::shared_ptr<OHOS::MMI::SwitchEvent> switchEvent) {
464 POWER_HILOGI(FEATURE_WAKEUP, "switch event received");
465 std::shared_ptr<SuspendController> suspendController = pms->GetSuspendController();
466 if (suspendController == nullptr) {
467 POWER_HILOGE(FEATURE_INPUT, "get suspendController instance error");
468 return;
469 }
470 std::shared_ptr<WakeupController> wakeupController = pms->GetWakeupController();
471 if (wakeupController == nullptr) {
472 POWER_HILOGE(FEATURE_INPUT, "wakeupController is not init");
473 return;
474 }
475 if (switchEvent->GetSwitchValue() == SwitchEvent::SWITCH_OFF) {
476 POWER_HILOGI(FEATURE_SUSPEND, "[UL_POWER] Switch close event received, begin to suspend");
477 powerStateMachine_->SetSwitchState(false);
478 SuspendDeviceType reason = SuspendDeviceType::SUSPEND_DEVICE_REASON_SWITCH;
479 suspendController->ExecSuspendMonitorByReason(reason);
480 } else {
481 POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Switch open event received, begin to wakeup");
482 powerStateMachine_->SetSwitchState(true);
483 WakeupDeviceType reason = WakeupDeviceType::WAKEUP_DEVICE_SWITCH;
484 wakeupController->ExecWakeupMonitorByReason(reason);
485 }
486 });
487 #endif
488 }
489
SwitchSubscriberCancel()490 void PowerMgrService::SwitchSubscriberCancel()
491 {
492 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
493 POWER_HILOGI(FEATURE_INPUT, "Unsubscribe switch information");
494 if (switchId_ >= 0) {
495 InputManager::GetInstance()->UnsubscribeSwitchEvent(switchId_);
496 switchId_ = -1;
497 }
498 #endif
499 }
500
InputMonitorInit()501 void PowerMgrService::InputMonitorInit()
502 {
503 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
504 POWER_HILOGI(FEATURE_INPUT, "PowerMgr service input monitor init");
505 std::shared_ptr<PowerMgrInputMonitor> inputMonitor = std::make_shared<PowerMgrInputMonitor>();
506 if (inputMonitorId_ < 0) {
507 inputMonitorId_ =
508 InputManager::GetInstance()->AddMonitor(std::static_pointer_cast<IInputEventConsumer>(inputMonitor));
509 }
510 #endif
511 }
512
InputMonitorCancel()513 void PowerMgrService::InputMonitorCancel()
514 {
515 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
516 POWER_HILOGI(FEATURE_INPUT, "PowerMgr service input monitor cancel");
517 InputManager* inputManager = InputManager::GetInstance();
518 if (inputMonitorId_ >= 0) {
519 inputManager->RemoveMonitor(inputMonitorId_);
520 inputMonitorId_ = -1;
521 }
522 #endif
523 }
524
HandleKeyEvent(int32_t keyCode)525 void PowerMgrService::HandleKeyEvent(int32_t keyCode)
526 {
527 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
528 POWER_HILOGD(FEATURE_INPUT, "keyCode: %{public}d", keyCode);
529 int64_t now = static_cast<int64_t>(time(nullptr));
530 if (IsScreenOn()) {
531 this->RefreshActivityInner(now, UserActivityType::USER_ACTIVITY_TYPE_BUTTON, false);
532 } else {
533 if (keyCode == KeyEvent::KEYCODE_F1) {
534 POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Wakeup by double click");
535 std::string reason = "double click";
536 reason.append(std::to_string(keyCode));
537 this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_DOUBLE_CLICK, reason);
538 } else if (keyCode >= KeyEvent::KEYCODE_0 && keyCode <= KeyEvent::KEYCODE_NUMPAD_RIGHT_PAREN) {
539 POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Wakeup by keyboard");
540 std::string reason = "keyboard:";
541 reason.append(std::to_string(keyCode));
542 this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_KEYBOARD, reason);
543 }
544 }
545 #endif
546 }
547
HandlePointEvent(int32_t type)548 void PowerMgrService::HandlePointEvent(int32_t type)
549 {
550 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
551 POWER_HILOGD(FEATURE_INPUT, "type: %{public}d", type);
552 int64_t now = static_cast<int64_t>(time(nullptr));
553 if (this->IsScreenOn()) {
554 this->RefreshActivityInner(now, UserActivityType::USER_ACTIVITY_TYPE_ATTENTION, false);
555 } else {
556 if (type == PointerEvent::SOURCE_TYPE_MOUSE) {
557 std::string reason = "mouse click";
558 POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Wakeup by mouse");
559 this->WakeupDevice(now, WakeupDeviceType::WAKEUP_DEVICE_MOUSE, reason);
560 }
561 }
562 #endif
563 }
564
OnStop()565 void PowerMgrService::OnStop()
566 {
567 POWER_HILOGW(COMP_SVC, "Stop service");
568 if (!ready_) {
569 return;
570 }
571 powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
572 powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
573 powerStateMachine_->UnregisterDisplayOffTimeObserver();
574 if (suspendController_) {
575 suspendController_->StopSleep();
576 }
577
578 SystemSuspendController::GetInstance().UnRegisterPowerHdiCallback();
579 KeyMonitorCancel();
580 HallSensorSubscriberCancel();
581 SwitchSubscriberCancel();
582 InputMonitorCancel();
583 ready_ = false;
584 isBootCompleted_ = false;
585 RemoveSystemAbilityListener(SUSPEND_MANAGER_SYSTEM_ABILITY_ID);
586 RemoveSystemAbilityListener(DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID);
587 RemoveSystemAbilityListener(DISPLAY_MANAGER_SERVICE_ID);
588 #ifdef MSDP_MOVEMENT_ENABLE
589 RemoveSystemAbilityListener(MSDP_MOVEMENT_SERVICE_ID);
590 #endif
591 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
592 SettingHelper::UnregisterSettingWakeupDoubleObserver();
593 SettingHelper::UnregisterSettingWakeupPickupObserver();
594 #endif
595 SettingHelper::UnRegisterSettingWakeupLidObserver();
596 SettingHelper::UnRegisterSettingPowerModeObserver();
597 if (!OHOS::EventFwk::CommonEventManager::UnSubscribeCommonEvent(subscriberPtr_)) {
598 POWER_HILOGE(COMP_SVC, "Power Onstop unregister to commonevent manager failed!");
599 }
600 #ifdef MSDP_MOVEMENT_ENABLE
601 UnRegisterMovementCallback();
602 #endif
603 }
604
Reset()605 void PowerMgrService::Reset()
606 {
607 POWER_HILOGW(COMP_SVC, "start destruct ffrt_queue");
608 if (powerStateMachine_) {
609 powerStateMachine_->Reset();
610 }
611 if (suspendController_) {
612 suspendController_->Reset();
613 }
614 if (screenOffPreController_) {
615 screenOffPreController_->Reset();
616 }
617 }
618
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)619 void PowerMgrService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
620 {
621 POWER_HILOGI(COMP_SVC, "systemAbilityId=%{public}d, deviceId=%{private}s", systemAbilityId, deviceId.c_str());
622 if (systemAbilityId == SUSPEND_MANAGER_SYSTEM_ABILITY_ID ||
623 systemAbilityId == DEVICE_STANDBY_SERVICE_SYSTEM_ABILITY_ID) {
624 std::lock_guard lock(lockMutex_);
625 runningLockMgr_->ResetRunningLocks();
626 }
627 #ifdef MSDP_MOVEMENT_ENABLE
628 if (systemAbilityId == MSDP_MOVEMENT_SERVICE_ID) {
629 auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
630 if (power == nullptr) {
631 POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
632 return;
633 }
634 power->ResetMovementState();
635 }
636 #endif
637 }
638
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)639 void PowerMgrService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
640 {
641 POWER_HILOGI(COMP_SVC, "systemAbilityId=%{public}d, deviceId=%{private}s Add",
642 systemAbilityId, deviceId.c_str());
643 if (systemAbilityId == DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID) {
644 if (DelayedSpSingleton<PowerSaveMode>::GetInstance()) {
645 this->GetPowerModeModule().InitPowerMode();
646 }
647 }
648 if (systemAbilityId == DISPLAY_MANAGER_SERVICE_ID) {
649 RegisterBootCompletedCallback();
650 }
651 #ifdef MSDP_MOVEMENT_ENABLE
652 if (systemAbilityId == MSDP_MOVEMENT_SERVICE_ID) {
653 auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
654 if (power == nullptr) {
655 POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
656 return;
657 }
658 power->UnRegisterMovementCallback();
659 power->RegisterMovementCallback();
660 }
661 #endif
662 }
663
664 #ifdef MSDP_MOVEMENT_ENABLE
665 static const char* MOVEMENT_SUBSCRIBER_CONFIG = "RegisterMovementCallback";
666 static const char* MOVEMENT_UNSUBSCRIBER_CONFIG = "UnRegisterMovementCallback";
667 static const char* RESET_MOVEMENT_STATE_CONFIG = "ResetMovementState";
668 static const char* POWER_MANAGER_EXT_PATH = "/system/lib64/libpower_manager_ext.z.so";
669 typedef void(*FuncMovementSubscriber)();
670 typedef void(*FuncMovementUnsubscriber)();
671 typedef void(*FuncResetMovementState)();
672
RegisterMovementCallback()673 void PowerMgrService::RegisterMovementCallback()
674 {
675 POWER_HILOGI(COMP_SVC, "Start to RegisterMovementCallback");
676 void *subscriberHandler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
677 if (subscriberHandler == nullptr) {
678 POWER_HILOGE(COMP_SVC, "Dlopen RegisterMovementCallback failed, reason : %{public}s", dlerror());
679 return;
680 }
681
682 FuncMovementSubscriber MovementSubscriberFlag =
683 reinterpret_cast<FuncMovementSubscriber>(dlsym(subscriberHandler, MOVEMENT_SUBSCRIBER_CONFIG));
684 if (MovementSubscriberFlag == nullptr) {
685 POWER_HILOGE(COMP_SVC, "RegisterMovementCallback is null, reason : %{public}s", dlerror());
686 dlclose(subscriberHandler);
687 subscriberHandler = nullptr;
688 return;
689 }
690 MovementSubscriberFlag();
691 POWER_HILOGI(COMP_SVC, "RegisterMovementCallback Success");
692 dlclose(subscriberHandler);
693 subscriberHandler = nullptr;
694 return;
695 }
696
UnRegisterMovementCallback()697 void PowerMgrService::UnRegisterMovementCallback()
698 {
699 POWER_HILOGI(COMP_SVC, "Start to UnRegisterMovementCallback");
700 void *unSubscriberHandler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
701 if (unSubscriberHandler == nullptr) {
702 POWER_HILOGE(COMP_SVC, "Dlopen UnRegisterMovementCallback failed, reason : %{public}s", dlerror());
703 return;
704 }
705
706 FuncMovementUnsubscriber MovementUnsubscriberFlag =
707 reinterpret_cast<FuncMovementUnsubscriber>(dlsym(unSubscriberHandler, MOVEMENT_UNSUBSCRIBER_CONFIG));
708 if (MovementUnsubscriberFlag == nullptr) {
709 POWER_HILOGE(COMP_SVC, "UnRegisterMovementCallback is null, reason : %{public}s", dlerror());
710 dlclose(unSubscriberHandler);
711 unSubscriberHandler = nullptr;
712 return;
713 }
714 MovementUnsubscriberFlag();
715 POWER_HILOGI(COMP_SVC, "UnRegisterMovementCallback Success");
716 dlclose(unSubscriberHandler);
717 unSubscriberHandler = nullptr;
718 return;
719 }
720
ResetMovementState()721 void PowerMgrService::ResetMovementState()
722 {
723 POWER_HILOGI(COMP_SVC, "Start to ResetMovementState");
724 void *resetMovementStateHandler = dlopen(POWER_MANAGER_EXT_PATH, RTLD_LAZY | RTLD_NODELETE);
725 if (resetMovementStateHandler == nullptr) {
726 POWER_HILOGE(COMP_SVC, "Dlopen ResetMovementState failed, reason : %{public}s", dlerror());
727 return;
728 }
729
730 FuncResetMovementState ResetMovementStateFlag =
731 reinterpret_cast<FuncResetMovementState>(dlsym(resetMovementStateHandler, RESET_MOVEMENT_STATE_CONFIG));
732 if (ResetMovementStateFlag == nullptr) {
733 POWER_HILOGE(COMP_SVC, "ResetMovementState is null, reason : %{public}s", dlerror());
734 dlclose(resetMovementStateHandler);
735 resetMovementStateHandler = nullptr;
736 return;
737 }
738 ResetMovementStateFlag();
739 POWER_HILOGI(COMP_SVC, "ResetMovementState Success");
740 dlclose(resetMovementStateHandler);
741 resetMovementStateHandler = nullptr;
742 return;
743 }
744 #endif
745
Dump(int32_t fd,const std::vector<std::u16string> & args)746 int32_t PowerMgrService::Dump(int32_t fd, const std::vector<std::u16string>& args)
747 {
748 if (!isBootCompleted_) {
749 return ERR_NO_INIT;
750 }
751 if (!Permission::IsSystem()) {
752 return ERR_PERMISSION_DENIED;
753 }
754 std::vector<std::string> argsInStr;
755 std::transform(args.begin(), args.end(), std::back_inserter(argsInStr), [](const std::u16string& arg) {
756 std::string ret = Str16ToStr8(arg);
757 POWER_HILOGD(COMP_SVC, "arg: %{public}s", ret.c_str());
758 return ret;
759 });
760 std::string result;
761 PowerMgrDumper::Dump(argsInStr, result);
762 if (!SaveStringToFd(fd, result)) {
763 POWER_HILOGE(COMP_SVC, "Dump failed, save to fd failed.");
764 POWER_HILOGE(COMP_SVC, "Dump Info:\n");
765 POWER_HILOGE(COMP_SVC, "%{public}s", result.c_str());
766 return ERR_OK;
767 }
768 return ERR_OK;
769 }
770
RebootDevice(const std::string & reason)771 PowerErrors PowerMgrService::RebootDevice(const std::string& reason)
772 {
773 if (!Permission::IsSystem()) {
774 return PowerErrors::ERR_SYSTEM_API_DENIED;
775 }
776 return RebootDeviceForDeprecated(reason);
777 }
778
RebootDeviceForDeprecated(const std::string & reason)779 PowerErrors PowerMgrService::RebootDeviceForDeprecated(const std::string& reason)
780 {
781 std::lock_guard lock(shutdownMutex_);
782 pid_t pid = IPCSkeleton::GetCallingPid();
783 auto uid = IPCSkeleton::GetCallingUid();
784 if (!Permission::IsPermissionGranted("ohos.permission.REBOOT")) {
785 return PowerErrors::ERR_PERMISSION_DENIED;
786 }
787 POWER_HILOGI(FEATURE_SHUTDOWN, "Cancel auto sleep timer");
788 powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
789 powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
790 if (suspendController_) {
791 suspendController_->StopSleep();
792 }
793 POWER_HILOGI(FEATURE_SHUTDOWN, "Do reboot, called pid: %{public}d, uid: %{public}d", pid, uid);
794 shutdownController_->Reboot(reason);
795 return PowerErrors::ERR_OK;
796 }
797
ShutDownDevice(const std::string & reason)798 PowerErrors PowerMgrService::ShutDownDevice(const std::string& reason)
799 {
800 auto now = static_cast<int64_t>(time(nullptr));
801 if (!Permission::IsSystem()) {
802 return PowerErrors::ERR_SYSTEM_API_DENIED;
803 }
804 if (!Permission::IsPermissionGranted("ohos.permission.REBOOT")) {
805 return PowerErrors::ERR_PERMISSION_DENIED;
806 }
807 if (reason == SHUTDOWN_FAST_REASON) {
808 g_wakeupReason = reason;
809 POWER_HILOGD(FEATURE_SHUTDOWN, "Calling Fast ShutDownDevice success");
810 return SuspendDevice(now, SuspendDeviceType::SUSPEND_DEVICE_REASON_STR, true);
811 }
812 g_wakeupReason = "";
813 std::lock_guard lock(shutdownMutex_);
814 pid_t pid = IPCSkeleton::GetCallingPid();
815 auto uid = IPCSkeleton::GetCallingUid();
816 POWER_HILOGI(FEATURE_SHUTDOWN, "Cancel auto sleep timer");
817 powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
818 powerStateMachine_->CancelDelayTimer(PowerStateMachine::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
819 if (suspendController_) {
820 suspendController_->StopSleep();
821 }
822
823 POWER_HILOGI(FEATURE_SHUTDOWN, "[UL_POWER] Do shutdown, called pid: %{public}d, uid: %{public}d", pid, uid);
824 shutdownController_->Shutdown(reason);
825 return PowerErrors::ERR_OK;
826 }
827
SetSuspendTag(const std::string & tag)828 PowerErrors PowerMgrService::SetSuspendTag(const std::string& tag)
829 {
830 std::lock_guard lock(suspendMutex_);
831 pid_t pid = IPCSkeleton::GetCallingPid();
832 auto uid = IPCSkeleton::GetCallingUid();
833 if (!Permission::IsSystem()) {
834 return PowerErrors::ERR_SYSTEM_API_DENIED;
835 }
836 POWER_HILOGI(FEATURE_SUSPEND, "pid: %{public}d, uid: %{public}d, tag: %{public}s", pid, uid, tag.c_str());
837 SystemSuspendController::GetInstance().SetSuspendTag(tag);
838 return PowerErrors::ERR_OK;
839 }
840
SuspendDevice(int64_t callTimeMs,SuspendDeviceType reason,bool suspendImmed)841 PowerErrors PowerMgrService::SuspendDevice(int64_t callTimeMs, SuspendDeviceType reason, bool suspendImmed)
842 {
843 std::lock_guard lock(suspendMutex_);
844 pid_t pid = IPCSkeleton::GetCallingPid();
845 auto uid = IPCSkeleton::GetCallingUid();
846 if (!Permission::IsSystem()) {
847 return PowerErrors::ERR_SYSTEM_API_DENIED;
848 }
849 if (shutdownController_->IsShuttingDown()) {
850 POWER_HILOGW(FEATURE_SUSPEND, "System is shutting down, can't suspend");
851 return PowerErrors::ERR_OK;
852 }
853 POWER_HILOGI(FEATURE_SUSPEND, "[UL_POWER] Try to suspend device, pid: %{public}d, uid: %{public}d", pid, uid);
854 powerStateMachine_->SuspendDeviceInner(pid, callTimeMs, reason, suspendImmed);
855 return PowerErrors::ERR_OK;
856 }
857
WakeupDevice(int64_t callTimeMs,WakeupDeviceType reason,const std::string & details)858 PowerErrors PowerMgrService::WakeupDevice(int64_t callTimeMs, WakeupDeviceType reason, const std::string& details)
859 {
860 std::lock_guard lock(wakeupMutex_);
861 if (!Permission::IsSystem()) {
862 return PowerErrors::ERR_SYSTEM_API_DENIED;
863 }
864 pid_t pid = IPCSkeleton::GetCallingPid();
865 auto uid = IPCSkeleton::GetCallingUid();
866 POWER_HILOGI(FEATURE_WAKEUP, "[UL_POWER] Try to wakeup device, pid: %{public}d, uid: %{public}d", pid, uid);
867 WakeupRunningLock wakeupRunningLock;
868 powerStateMachine_->WakeupDeviceInner(pid, callTimeMs, reason, details, "OHOS");
869 return PowerErrors::ERR_OK;
870 }
871
RefreshActivity(int64_t callTimeMs,UserActivityType type,bool needChangeBacklight)872 bool PowerMgrService::RefreshActivity(int64_t callTimeMs, UserActivityType type, bool needChangeBacklight)
873 {
874 if (!Permission::IsPermissionGranted("ohos.permission.REFRESH_USER_ACTION") || !Permission::IsSystem()) {
875 return false;
876 }
877 pid_t pid = IPCSkeleton::GetCallingPid();
878 auto uid = IPCSkeleton::GetCallingUid();
879 POWER_HILOGI(FEATURE_ACTIVITY, "Try to refresh activity, pid: %{public}d, uid: %{public}d", pid, uid);
880 return RefreshActivityInner(callTimeMs, type, needChangeBacklight);
881 }
882
RefreshActivityInner(int64_t callTimeMs,UserActivityType type,bool needChangeBacklight)883 bool PowerMgrService::RefreshActivityInner(int64_t callTimeMs, UserActivityType type, bool needChangeBacklight)
884 {
885 std::lock_guard lock(screenMutex_);
886 if (powerStateMachine_->CheckRefreshTime()) {
887 return false;
888 }
889 pid_t pid = IPCSkeleton::GetCallingPid();
890 powerStateMachine_->RefreshActivityInner(pid, callTimeMs, type, needChangeBacklight);
891 return true;
892 }
893
OverrideScreenOffTime(int64_t timeout)894 PowerErrors PowerMgrService::OverrideScreenOffTime(int64_t timeout)
895 {
896 std::lock_guard lock(screenMutex_);
897 pid_t pid = IPCSkeleton::GetCallingPid();
898 auto uid = IPCSkeleton::GetCallingUid();
899 POWER_HILOGI(COMP_SVC,
900 "Try to override screenOffTime, timeout=%{public}" PRId64 ", pid: %{public}d, uid: %{public}d",
901 timeout, pid, uid);
902 if (!Permission::IsSystem()) {
903 POWER_HILOGI(COMP_SVC, "OverrideScreenOffTime failed, System permission intercept");
904 return PowerErrors::ERR_SYSTEM_API_DENIED;
905 }
906 return powerStateMachine_->OverrideScreenOffTimeInner(timeout) ?
907 PowerErrors::ERR_OK : PowerErrors::ERR_FAILURE;
908 }
909
RestoreScreenOffTime()910 PowerErrors PowerMgrService::RestoreScreenOffTime()
911 {
912 std::lock_guard lock(screenMutex_);
913 if (!Permission::IsSystem()) {
914 POWER_HILOGI(COMP_SVC, "RestoreScreenOffTime failed, System permission intercept");
915 return PowerErrors::ERR_SYSTEM_API_DENIED;
916 }
917 POWER_HILOGD(COMP_SVC, "Try to restore screen off time");
918 return powerStateMachine_->RestoreScreenOffTimeInner() ?
919 PowerErrors::ERR_OK : PowerErrors::ERR_FAILURE;
920 }
921
GetState()922 PowerState PowerMgrService::GetState()
923 {
924 std::lock_guard lock(stateMutex_);
925 auto state = powerStateMachine_->GetState();
926 POWER_HILOGD(FEATURE_POWER_STATE, "state: %{public}d", state);
927 return state;
928 }
929
IsScreenOn(bool needPrintLog)930 bool PowerMgrService::IsScreenOn(bool needPrintLog)
931 {
932 std::lock_guard lock(stateMutex_);
933 auto isScreenOn = powerStateMachine_->IsScreenOn();
934 if (needPrintLog) {
935 POWER_HILOGD(COMP_SVC, "isScreenOn: %{public}d", isScreenOn);
936 }
937 return isScreenOn;
938 }
939
IsFoldScreenOn()940 bool PowerMgrService::IsFoldScreenOn()
941 {
942 std::lock_guard lock(stateMutex_);
943 auto isFoldScreenOn = powerStateMachine_->IsFoldScreenOn();
944 POWER_HILOGI(COMP_SVC, "isFoldScreenOn: %{public}d", isFoldScreenOn);
945 return isFoldScreenOn;
946 }
947
IsCollaborationScreenOn()948 bool PowerMgrService::IsCollaborationScreenOn()
949 {
950 std::lock_guard lock(stateMutex_);
951 auto isCollaborationScreenOn = powerStateMachine_->IsCollaborationScreenOn();
952 POWER_HILOGI(COMP_SVC, "isCollaborationScreenOn: %{public}d", isCollaborationScreenOn);
953 return isCollaborationScreenOn;
954 }
955
ForceSuspendDevice(int64_t callTimeMs)956 PowerErrors PowerMgrService::ForceSuspendDevice(int64_t callTimeMs)
957 {
958 std::lock_guard lock(suspendMutex_);
959 pid_t pid = IPCSkeleton::GetCallingPid();
960 auto uid = IPCSkeleton::GetCallingUid();
961 if (!Permission::IsSystem()) {
962 POWER_HILOGI(FEATURE_SUSPEND, "ForceSuspendDevice failed, System permission intercept");
963 return PowerErrors::ERR_SYSTEM_API_DENIED;
964 }
965 if (shutdownController_->IsShuttingDown()) {
966 POWER_HILOGI(FEATURE_SUSPEND, "System is shutting down, can't force suspend");
967 return PowerErrors::ERR_FAILURE;
968 }
969 POWER_HILOGI(FEATURE_SUSPEND, "[UL_POWER] Try to force suspend device, pid: %{public}d, uid: %{public}d", pid, uid);
970 powerStateMachine_->ForceSuspendDeviceInner(pid, callTimeMs);
971 return PowerErrors::ERR_OK;
972 }
973
Hibernate(bool clearMemory)974 PowerErrors PowerMgrService::Hibernate(bool clearMemory)
975 {
976 POWER_HILOGI(FEATURE_SUSPEND, "power mgr service hibernate begin.");
977 if (!Permission::IsSystem()) {
978 POWER_HILOGI(FEATURE_SUSPEND, "Hibernate failed, System permission intercept");
979 return PowerErrors::ERR_SYSTEM_API_DENIED;
980 }
981 #ifdef POWER_MANAGER_POWER_ENABLE_S4
982 std::lock_guard lock(hibernateMutex_);
983 pid_t pid = IPCSkeleton::GetCallingPid();
984 auto uid = IPCSkeleton::GetCallingUid();
985 if (shutdownController_->IsShuttingDown()) {
986 POWER_HILOGI(FEATURE_SUSPEND, "System is shutting down, can't hibernate");
987 return PowerErrors::ERR_FAILURE;
988 }
989 POWER_HILOGI(FEATURE_SUSPEND,
990 "[UL_POWER] Try to hibernate, pid: %{public}d, uid: %{public}d, clearMemory: %{public}d",
991 pid, uid, static_cast<int>(clearMemory));
992 HibernateControllerInit();
993 bool ret = powerStateMachine_->HibernateInner(clearMemory);
994 return ret ? PowerErrors::ERR_OK : PowerErrors::ERR_FAILURE;
995 #else
996 POWER_HILOGI(FEATURE_SUSPEND, "Hibernate interface not supported.");
997 return PowerErrors::ERR_FAILURE;
998 #endif
999 }
1000
GetBundleNameByUid(const int32_t uid)1001 std::string PowerMgrService::GetBundleNameByUid(const int32_t uid)
1002 {
1003 std::string tempBundleName = "";
1004 if (uid < OHOS::AppExecFwk::Constants::BASE_APP_UID) {
1005 return tempBundleName;
1006 }
1007 BundleMgrClient bundleObj;
1008
1009 std::string identity = IPCSkeleton::ResetCallingIdentity();
1010 ErrCode res = bundleObj.GetNameForUid(uid, tempBundleName);
1011 IPCSkeleton::SetCallingIdentity(identity);
1012 if (res != ERR_OK) {
1013 POWER_HILOGE(FEATURE_RUNNING_LOCK, "Failed to get bundle name for uid=%{public}d, ErrCode=%{public}d",
1014 uid, static_cast<int32_t>(res));
1015 }
1016 POWER_HILOGI(FEATURE_RUNNING_LOCK, "bundle name for uid=%{public}d, name=%{public}s", uid, tempBundleName.c_str());
1017 return tempBundleName;
1018 }
1019
FillRunningLockParam(const RunningLockInfo & info,const uint64_t lockid,int32_t timeOutMS)1020 RunningLockParam PowerMgrService::FillRunningLockParam(const RunningLockInfo& info,
1021 const uint64_t lockid, int32_t timeOutMS)
1022 {
1023 RunningLockParam filledParam {};
1024 filledParam.lockid = lockid;
1025 filledParam.name = info.name;
1026 filledParam.type = info.type;
1027 if (filledParam.type == RunningLockType::RUNNINGLOCK_BACKGROUND) {
1028 filledParam.type = RunningLockType::RUNNINGLOCK_BACKGROUND_TASK;
1029 }
1030 filledParam.timeoutMs = timeOutMS;
1031 filledParam.pid = IPCSkeleton::GetCallingPid();
1032 filledParam.uid = IPCSkeleton::GetCallingUid();
1033 filledParam.bundleName = GetBundleNameByUid(filledParam.uid);
1034 return filledParam;
1035 }
1036
CreateRunningLock(const sptr<IRemoteObject> & remoteObj,const RunningLockInfo & runningLockInfo)1037 PowerErrors PowerMgrService::CreateRunningLock(
1038 const sptr<IRemoteObject>& remoteObj, const RunningLockInfo& runningLockInfo)
1039 {
1040 PowerXCollie powerXCollie("PowerMgrService::CreateRunningLock", true);
1041 std::lock_guard lock(lockMutex_);
1042 if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1043 return PowerErrors::ERR_PERMISSION_DENIED;
1044 }
1045 if (!IsRunningLockTypeSupported(runningLockInfo.type)) {
1046 POWER_HILOGW(FEATURE_RUNNING_LOCK,
1047 "runninglock type is not supported, name=%{public}s, type=%{public}d",
1048 runningLockInfo.name.c_str(), runningLockInfo.type);
1049 return PowerErrors::ERR_PARAM_INVALID;
1050 }
1051
1052 uintptr_t remoteObjPtr = reinterpret_cast<uintptr_t>(remoteObj.GetRefPtr());
1053 uint64_t lockid = std::hash<uintptr_t>()(remoteObjPtr);
1054 RunningLockParam runningLockParam = FillRunningLockParam(runningLockInfo, lockid);
1055 runningLockMgr_->CreateRunningLock(remoteObj, runningLockParam);
1056 return PowerErrors::ERR_OK;
1057 }
1058
ReleaseRunningLock(const sptr<IRemoteObject> & remoteObj,const std::string & name)1059 bool PowerMgrService::ReleaseRunningLock(const sptr<IRemoteObject>& remoteObj, const std::string& name)
1060 {
1061 PowerXCollie powerXCollie("PowerMgrService::ReleaseRunningLock", true);
1062 std::lock_guard lock(lockMutex_);
1063 bool result = false;
1064 if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1065 return result;
1066 }
1067
1068 result = runningLockMgr_->ReleaseLock(remoteObj, name);
1069 return result;
1070 }
1071
IsRunningLockTypeSupported(RunningLockType type)1072 bool PowerMgrService::IsRunningLockTypeSupported(RunningLockType type)
1073 {
1074 if (Permission::IsHap()) {
1075 if (Permission::IsSystem()) {
1076 return type <= RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL;
1077 }
1078 return type == RunningLockType::RUNNINGLOCK_BACKGROUND ||
1079 type == RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL;
1080 }
1081 return type == RunningLockType::RUNNINGLOCK_SCREEN ||
1082 type == RunningLockType::RUNNINGLOCK_BACKGROUND || // this will be instead by BACKGROUND_XXX types.
1083 type == RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL ||
1084 type == RunningLockType::RUNNINGLOCK_COORDINATION ||
1085 type == RunningLockType::RUNNINGLOCK_BACKGROUND_PHONE ||
1086 type == RunningLockType::RUNNINGLOCK_BACKGROUND_NOTIFICATION ||
1087 type == RunningLockType::RUNNINGLOCK_BACKGROUND_AUDIO ||
1088 type == RunningLockType::RUNNINGLOCK_BACKGROUND_SPORT ||
1089 type == RunningLockType::RUNNINGLOCK_BACKGROUND_NAVIGATION ||
1090 type == RunningLockType::RUNNINGLOCK_BACKGROUND_TASK;
1091 }
1092
UpdateWorkSource(const sptr<IRemoteObject> & remoteObj,const std::map<int32_t,std::string> & workSources)1093 bool PowerMgrService::UpdateWorkSource(const sptr<IRemoteObject>& remoteObj,
1094 const std::map<int32_t, std::string>& workSources)
1095 {
1096 PowerXCollie powerXCollie("PowerMgrService::UpdateWorkSource", true);
1097 if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1098 return false;
1099 }
1100 std::lock_guard lock(lockMutex_);
1101 runningLockMgr_->UpdateWorkSource(remoteObj, workSources);
1102 return true;
1103 }
1104
Lock(const sptr<IRemoteObject> & remoteObj,int32_t timeOutMs)1105 PowerErrors PowerMgrService::Lock(const sptr<IRemoteObject>& remoteObj, int32_t timeOutMs)
1106 {
1107 PowerXCollie powerXCollie("PowerMgrService::Lock", true);
1108 if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1109 return PowerErrors::ERR_PERMISSION_DENIED;
1110 }
1111 std::lock_guard lock(lockMutex_);
1112 runningLockMgr_->Lock(remoteObj);
1113 if (timeOutMs > 0) {
1114 std::function<void()> task = [this, remoteObj, timeOutMs]() {
1115 std::lock_guard lock(lockMutex_);
1116 RunningLockTimerHandler::GetInstance().UnregisterRunningLockTimer(remoteObj);
1117 runningLockMgr_->UpdateWorkSource(remoteObj, {});
1118 runningLockMgr_->UnLock(remoteObj);
1119 };
1120 RunningLockTimerHandler::GetInstance().RegisterRunningLockTimer(remoteObj, task, timeOutMs);
1121 }
1122 return PowerErrors::ERR_OK;
1123 }
1124
UnLock(const sptr<IRemoteObject> & remoteObj,const std::string & name)1125 PowerErrors PowerMgrService::UnLock(const sptr<IRemoteObject>& remoteObj, const std::string& name)
1126 {
1127 PowerXCollie powerXCollie("PowerMgrService::UnLock", true);
1128 if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1129 return PowerErrors::ERR_PERMISSION_DENIED;
1130 }
1131 std::lock_guard lock(lockMutex_);
1132 RunningLockTimerHandler::GetInstance().UnregisterRunningLockTimer(remoteObj);
1133 runningLockMgr_->UnLock(remoteObj, name);
1134 return PowerErrors::ERR_OK;
1135 }
1136
QueryRunningLockLists(std::map<std::string,RunningLockInfo> & runningLockLists)1137 bool PowerMgrService::QueryRunningLockLists(std::map<std::string, RunningLockInfo>& runningLockLists)
1138 {
1139 PowerXCollie powerXCollie("PowerMgrService::QueryRunningLockLists", true);
1140 std::lock_guard lock(lockMutex_);
1141 if (!Permission::IsPermissionGranted("ohos.permission.RUNNING_LOCK")) {
1142 return false;
1143 }
1144 QueryRunningLockListsInner(runningLockLists);
1145 return true;
1146 }
1147
QueryRunningLockListsInner(std::map<std::string,RunningLockInfo> & runningLockLists)1148 void PowerMgrService::QueryRunningLockListsInner(std::map<std::string, RunningLockInfo>& runningLockLists)
1149 {
1150 runningLockMgr_->QueryRunningLockLists(runningLockLists);
1151 }
1152
RegisterRunningLockCallback(const sptr<IPowerRunninglockCallback> & callback)1153 bool PowerMgrService::RegisterRunningLockCallback(const sptr<IPowerRunninglockCallback>& callback)
1154 {
1155 std::lock_guard lock(lockMutex_);
1156 pid_t pid = IPCSkeleton::GetCallingPid();
1157 auto uid = IPCSkeleton::GetCallingUid();
1158 if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1159 return false;
1160 }
1161 POWER_HILOGI(FEATURE_RUNNING_LOCK, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1162 runningLockMgr_->RegisterRunningLockCallback(callback);
1163 return true;
1164 }
1165
UnRegisterRunningLockCallback(const sptr<IPowerRunninglockCallback> & callback)1166 bool PowerMgrService::UnRegisterRunningLockCallback(const sptr<IPowerRunninglockCallback>& callback)
1167 {
1168 std::lock_guard lock(lockMutex_);
1169 pid_t pid = IPCSkeleton::GetCallingPid();
1170 auto uid = IPCSkeleton::GetCallingUid();
1171 if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1172 return false;
1173 }
1174 POWER_HILOGI(FEATURE_RUNNING_LOCK, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1175 runningLockMgr_->RegisterRunningLockCallback(callback);
1176 return true;
1177 }
1178
ForceUnLock(const sptr<IRemoteObject> & remoteObj)1179 void PowerMgrService::ForceUnLock(const sptr<IRemoteObject>& remoteObj)
1180 {
1181 PowerXCollie powerXCollie("PowerMgrService::ForceUnLock", true);
1182 std::lock_guard lock(lockMutex_);
1183 runningLockMgr_->UnLock(remoteObj);
1184 runningLockMgr_->ReleaseLock(remoteObj);
1185 }
1186
IsUsed(const sptr<IRemoteObject> & remoteObj)1187 bool PowerMgrService::IsUsed(const sptr<IRemoteObject>& remoteObj)
1188 {
1189 PowerXCollie powerXCollie("PowerMgrService::IsUsed", true);
1190 std::lock_guard lock(lockMutex_);
1191 auto isUsed = runningLockMgr_->IsUsed(remoteObj);
1192 POWER_HILOGD(FEATURE_RUNNING_LOCK, "RunningLock is Used: %{public}d", isUsed);
1193 return isUsed;
1194 }
1195
ProxyRunningLock(bool isProxied,pid_t pid,pid_t uid)1196 bool PowerMgrService::ProxyRunningLock(bool isProxied, pid_t pid, pid_t uid)
1197 {
1198 PowerXCollie powerXCollie("PowerMgrService::ProxyRunningLock", true);
1199 std::lock_guard lock(lockMutex_);
1200 if (!Permission::IsSystem()) {
1201 return false;
1202 }
1203 return runningLockMgr_->ProxyRunningLock(isProxied, pid, uid);
1204 }
1205
ProxyRunningLocks(bool isProxied,const std::vector<std::pair<pid_t,pid_t>> & processInfos)1206 bool PowerMgrService::ProxyRunningLocks(bool isProxied, const std::vector<std::pair<pid_t, pid_t>>& processInfos)
1207 {
1208 PowerXCollie powerXCollie("PowerMgrService::ProxyRunningLocks", true);
1209 if (!Permission::IsSystem()) {
1210 return false;
1211 }
1212 std::lock_guard lock(lockMutex_);
1213 runningLockMgr_->ProxyRunningLocks(isProxied, processInfos);
1214 return true;
1215 }
1216
ResetRunningLocks()1217 bool PowerMgrService::ResetRunningLocks()
1218 {
1219 PowerXCollie powerXCollie("PowerMgrService::ResetRunningLocks", true);
1220 if (!Permission::IsSystem()) {
1221 return false;
1222 }
1223 std::lock_guard lock(lockMutex_);
1224 runningLockMgr_->ResetRunningLocks();
1225 return true;
1226 }
1227
RegisterPowerStateCallback(const sptr<IPowerStateCallback> & callback,bool isSync)1228 bool PowerMgrService::RegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback, bool isSync)
1229 {
1230 std::lock_guard lock(stateMutex_);
1231 pid_t pid = IPCSkeleton::GetCallingPid();
1232 auto uid = IPCSkeleton::GetCallingUid();
1233 if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1234 return false;
1235 }
1236 POWER_HILOGI(FEATURE_POWER_STATE, "%{public}s: pid: %{public}d, uid: %{public}d, isSync: %{public}u", __func__, pid,
1237 uid, static_cast<uint32_t>(isSync));
1238 powerStateMachine_->RegisterPowerStateCallback(callback, isSync);
1239 return true;
1240 }
1241
UnRegisterPowerStateCallback(const sptr<IPowerStateCallback> & callback)1242 bool PowerMgrService::UnRegisterPowerStateCallback(const sptr<IPowerStateCallback>& callback)
1243 {
1244 std::lock_guard lock(stateMutex_);
1245 pid_t pid = IPCSkeleton::GetCallingPid();
1246 auto uid = IPCSkeleton::GetCallingUid();
1247 if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1248 return false;
1249 }
1250 POWER_HILOGI(FEATURE_POWER_STATE, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1251 powerStateMachine_->UnRegisterPowerStateCallback(callback);
1252 return true;
1253 }
1254
RegisterSyncSleepCallback(const sptr<ISyncSleepCallback> & callback,SleepPriority priority)1255 bool PowerMgrService::RegisterSyncSleepCallback(const sptr<ISyncSleepCallback>& callback, SleepPriority priority)
1256 {
1257 std::lock_guard lock(suspendMutex_);
1258 pid_t pid = IPCSkeleton::GetCallingPid();
1259 auto uid = IPCSkeleton::GetCallingUid();
1260 if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1261 return false;
1262 }
1263 POWER_HILOGI(FEATURE_SUSPEND, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1264 suspendController_->AddCallback(callback, priority);
1265 return true;
1266 }
1267
UnRegisterSyncSleepCallback(const sptr<ISyncSleepCallback> & callback)1268 bool PowerMgrService::UnRegisterSyncSleepCallback(const sptr<ISyncSleepCallback>& callback)
1269 {
1270 std::lock_guard lock(suspendMutex_);
1271 pid_t pid = IPCSkeleton::GetCallingPid();
1272 auto uid = IPCSkeleton::GetCallingUid();
1273 if (!Permission::IsPermissionGranted("ohos.permission.POWER_MANAGER")) {
1274 return false;
1275 }
1276 POWER_HILOGI(FEATURE_SUSPEND, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1277 suspendController_->RemoveCallback(callback);
1278 return true;
1279 }
1280
RegisterSyncHibernateCallback(const sptr<ISyncHibernateCallback> & callback)1281 bool PowerMgrService::RegisterSyncHibernateCallback(const sptr<ISyncHibernateCallback>& callback)
1282 {
1283 #ifdef POWER_MANAGER_POWER_ENABLE_S4
1284 POWER_HILOGI(FEATURE_SUSPEND, "RegisterSyncHibernateCallback begin.");
1285 HibernateControllerInit();
1286 hibernateController_->RegisterSyncHibernateCallback(callback);
1287 return true;
1288 #else
1289 POWER_HILOGI(FEATURE_SUSPEND, "RegisterSyncHibernateCallback interface not supported.");
1290 return false;
1291 #endif
1292 }
1293
UnRegisterSyncHibernateCallback(const sptr<ISyncHibernateCallback> & callback)1294 bool PowerMgrService::UnRegisterSyncHibernateCallback(const sptr<ISyncHibernateCallback>& callback)
1295 {
1296 #ifdef POWER_MANAGER_POWER_ENABLE_S4
1297 POWER_HILOGI(FEATURE_SUSPEND, "UnRegisterSyncHibernateCallback begin.");
1298 HibernateControllerInit();
1299 hibernateController_->UnregisterSyncHibernateCallback(callback);
1300 return true;
1301 #else
1302 POWER_HILOGI(FEATURE_SUSPEND, "UnRegisterSyncHibernateCallback interface not supported.");
1303 return false;
1304 #endif
1305 }
1306
RegisterPowerModeCallback(const sptr<IPowerModeCallback> & callback)1307 bool PowerMgrService::RegisterPowerModeCallback(const sptr<IPowerModeCallback>& callback)
1308 {
1309 std::lock_guard lock(modeMutex_);
1310 pid_t pid = IPCSkeleton::GetCallingPid();
1311 auto uid = IPCSkeleton::GetCallingUid();
1312 if (!Permission::IsSystem()) {
1313 return false;
1314 }
1315 POWER_HILOGI(FEATURE_POWER_MODE, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1316 powerModeModule_.AddPowerModeCallback(callback);
1317 return true;
1318 }
1319
UnRegisterPowerModeCallback(const sptr<IPowerModeCallback> & callback)1320 bool PowerMgrService::UnRegisterPowerModeCallback(const sptr<IPowerModeCallback>& callback)
1321 {
1322 std::lock_guard lock(modeMutex_);
1323 pid_t pid = IPCSkeleton::GetCallingPid();
1324 auto uid = IPCSkeleton::GetCallingUid();
1325 if (!Permission::IsSystem()) {
1326 return false;
1327 }
1328 POWER_HILOGI(FEATURE_POWER_MODE, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1329 powerModeModule_.DelPowerModeCallback(callback);
1330 return true;
1331 }
1332
RegisterScreenStateCallback(int32_t remainTime,const sptr<IScreenOffPreCallback> & callback)1333 bool PowerMgrService::RegisterScreenStateCallback(int32_t remainTime, const sptr<IScreenOffPreCallback>& callback)
1334 {
1335 std::lock_guard lock(screenOffPreMutex_);
1336 pid_t pid = IPCSkeleton::GetCallingPid();
1337 auto uid = IPCSkeleton::GetCallingUid();
1338 if (!Permission::IsSystem()) {
1339 return false;
1340 }
1341 POWER_HILOGI(FEATURE_SCREEN_OFF_PRE, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1342 screenOffPreController_->AddScreenStateCallback(remainTime, callback);
1343 return true;
1344 }
1345
UnRegisterScreenStateCallback(const sptr<IScreenOffPreCallback> & callback)1346 bool PowerMgrService::UnRegisterScreenStateCallback(const sptr<IScreenOffPreCallback>& callback)
1347 {
1348 std::lock_guard lock(screenOffPreMutex_);
1349 pid_t pid = IPCSkeleton::GetCallingPid();
1350 auto uid = IPCSkeleton::GetCallingUid();
1351 if (!Permission::IsSystem()) {
1352 return false;
1353 }
1354 POWER_HILOGI(FEATURE_SCREEN_OFF_PRE, "%{public}s: pid: %{public}d, uid: %{public}d", __func__, pid, uid);
1355 screenOffPreController_->DelScreenStateCallback(callback);
1356 return true;
1357 }
1358
SetDisplaySuspend(bool enable)1359 bool PowerMgrService::SetDisplaySuspend(bool enable)
1360 {
1361 std::lock_guard lock(screenMutex_);
1362 pid_t pid = IPCSkeleton::GetCallingPid();
1363 auto uid = IPCSkeleton::GetCallingUid();
1364 if (!Permission::IsSystem()) {
1365 return false;
1366 }
1367 POWER_HILOGI(FEATURE_SUSPEND, "%{public}s: pid: %{public}d, uid: %{public}d, enable: %{public}d",
1368 __func__, pid, uid, enable);
1369 powerStateMachine_->SetDisplaySuspend(enable);
1370 return true;
1371 }
1372
SetDeviceMode(const PowerMode & mode)1373 PowerErrors PowerMgrService::SetDeviceMode(const PowerMode& mode)
1374 {
1375 std::lock_guard lock(modeMutex_);
1376 pid_t pid = IPCSkeleton::GetCallingPid();
1377 auto uid = IPCSkeleton::GetCallingUid();
1378 POWER_HILOGI(FEATURE_POWER_MODE, "%{public}s: pid: %{public}d, uid: %{public}d, mode: %{public}u",
1379 __func__, pid, uid, mode);
1380 if (!Permission::IsSystem()) {
1381 return PowerErrors::ERR_SYSTEM_API_DENIED;
1382 }
1383 if (!Permission::IsPermissionGranted("ohos.permission.POWER_OPTIMIZATION")) {
1384 return PowerErrors::ERR_PERMISSION_DENIED;
1385 }
1386 powerModeModule_.SetModeItem(mode);
1387 return PowerErrors::ERR_OK;
1388 }
1389
GetDeviceMode()1390 PowerMode PowerMgrService::GetDeviceMode()
1391 {
1392 std::lock_guard lock(modeMutex_);
1393 pid_t pid = IPCSkeleton::GetCallingPid();
1394 auto uid = IPCSkeleton::GetCallingUid();
1395 auto mode = powerModeModule_.GetModeItem();
1396 POWER_HILOGI(FEATURE_POWER_MODE, "%{public}s: pid: %{public}d, uid: %{public}d, mode: %{public}u",
1397 __func__, pid, uid, mode);
1398 return mode;
1399 }
1400
ShellDump(const std::vector<std::string> & args,uint32_t argc)1401 std::string PowerMgrService::ShellDump(const std::vector<std::string>& args, uint32_t argc)
1402 {
1403 if (!Permission::IsSystem() || !isBootCompleted_) {
1404 return "";
1405 }
1406 std::lock_guard lock(dumpMutex_);
1407 pid_t pid = IPCSkeleton::GetCallingPid();
1408 auto uid = IPCSkeleton::GetCallingUid();
1409
1410 std::string result;
1411 bool ret = PowerMgrDumper::Dump(args, result);
1412 POWER_HILOGI(COMP_SVC, "%{public}s: pid: %{public}d, uid: %{public}d ret :%{public}d", __func__, pid, uid, ret);
1413 return result;
1414 }
1415
RegisterShutdownCallback(const sptr<ITakeOverShutdownCallback> & callback,ShutdownPriority priority)1416 void PowerMgrService::RegisterShutdownCallback(
1417 const sptr<ITakeOverShutdownCallback>& callback, ShutdownPriority priority)
1418 {
1419 RETURN_IF (callback == nullptr);
1420 RETURN_IF (!Permission::IsSystem());
1421
1422 std::lock_guard lock(shutdownMutex_);
1423 shutdownController_->AddCallback(callback, priority);
1424 }
1425
UnRegisterShutdownCallback(const sptr<ITakeOverShutdownCallback> & callback)1426 void PowerMgrService::UnRegisterShutdownCallback(const sptr<ITakeOverShutdownCallback>& callback)
1427 {
1428 RETURN_IF (callback == nullptr);
1429 RETURN_IF (!Permission::IsSystem());
1430
1431 std::lock_guard lock(shutdownMutex_);
1432 shutdownController_->RemoveCallback(callback);
1433 }
1434
RegisterShutdownCallback(const sptr<IAsyncShutdownCallback> & callback,ShutdownPriority priority)1435 void PowerMgrService::RegisterShutdownCallback(
1436 const sptr<IAsyncShutdownCallback>& callback, ShutdownPriority priority)
1437 {
1438 RETURN_IF (callback == nullptr);
1439 RETURN_IF (!Permission::IsSystem());
1440
1441 std::lock_guard lock(shutdownMutex_);
1442 shutdownController_->AddCallback(callback, priority);
1443 }
1444
UnRegisterShutdownCallback(const sptr<IAsyncShutdownCallback> & callback)1445 void PowerMgrService::UnRegisterShutdownCallback(const sptr<IAsyncShutdownCallback>& callback)
1446 {
1447 RETURN_IF (callback == nullptr);
1448 RETURN_IF (!Permission::IsSystem());
1449
1450 std::lock_guard lock(shutdownMutex_);
1451 shutdownController_->RemoveCallback(callback);
1452 }
1453
RegisterShutdownCallback(const sptr<ISyncShutdownCallback> & callback,ShutdownPriority priority)1454 void PowerMgrService::RegisterShutdownCallback(
1455 const sptr<ISyncShutdownCallback>& callback, ShutdownPriority priority)
1456 {
1457 RETURN_IF (callback == nullptr);
1458 RETURN_IF (!Permission::IsSystem());
1459
1460 std::lock_guard lock(shutdownMutex_);
1461 shutdownController_->AddCallback(callback, priority);
1462 }
1463
UnRegisterShutdownCallback(const sptr<ISyncShutdownCallback> & callback)1464 void PowerMgrService::UnRegisterShutdownCallback(const sptr<ISyncShutdownCallback>& callback)
1465 {
1466 RETURN_IF (callback == nullptr);
1467 RETURN_IF (!Permission::IsSystem());
1468
1469 std::lock_guard lock(shutdownMutex_);
1470 shutdownController_->RemoveCallback(callback);
1471 }
1472
WakeupRunningLock()1473 PowerMgrService::WakeupRunningLock::WakeupRunningLock()
1474 {
1475 token_ = new (std::nothrow) RunningLockTokenStub();
1476 if (token_ == nullptr) {
1477 POWER_HILOGE(COMP_SVC, "create runninglock token failed");
1478 return;
1479 }
1480 RunningLockInfo info = {"PowerMgrWakeupLock", OHOS::PowerMgr::RunningLockType::RUNNINGLOCK_BACKGROUND};
1481 pms->CreateRunningLock(token_, info);
1482 pms->Lock(token_, WAKEUP_LOCK_TIMEOUT_MS);
1483 }
1484
~WakeupRunningLock()1485 PowerMgrService::WakeupRunningLock::~WakeupRunningLock()
1486 {
1487 if (token_ == nullptr) {
1488 POWER_HILOGE(COMP_SVC, "token_ is nullptr");
1489 return;
1490 }
1491 pms->ReleaseRunningLock(token_);
1492 }
1493
SuspendControllerInit()1494 void PowerMgrService::SuspendControllerInit()
1495 {
1496 if (!suspendController_) {
1497 suspendController_ = std::make_shared<SuspendController>(shutdownController_, powerStateMachine_);
1498 }
1499 suspendController_->Init();
1500 }
1501
WakeupControllerInit()1502 void PowerMgrService::WakeupControllerInit()
1503 {
1504 if (!wakeupController_) {
1505 wakeupController_ = std::make_shared<WakeupController>(powerStateMachine_);
1506 }
1507 wakeupController_->Init();
1508 }
1509
1510 #ifdef POWER_MANAGER_POWER_ENABLE_S4
HibernateControllerInit()1511 void PowerMgrService::HibernateControllerInit()
1512 {
1513 if (!hibernateController_) {
1514 hibernateController_ = std::make_shared<HibernateController>();
1515 }
1516 }
1517 #endif
1518
IsCollaborationState()1519 bool PowerMgrService::IsCollaborationState()
1520 {
1521 bool collaborationState = false;
1522 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
1523 if (pms == nullptr) {
1524 return collaborationState;
1525 }
1526 auto stateMachine = pms->GetPowerStateMachine();
1527 if (stateMachine == nullptr) {
1528 return collaborationState;
1529 }
1530 collaborationState = stateMachine->IsRunningLockEnabled(RunningLockType::RUNNINGLOCK_COORDINATION);
1531 return collaborationState;
1532 }
1533
1534 #ifdef POWER_MANAGER_WAKEUP_ACTION
WakeupActionControllerInit()1535 void PowerMgrService::WakeupActionControllerInit()
1536 {
1537 if (!wakeupActionController_) {
1538 wakeupActionController_ = std::make_shared<WakeupActionController>(shutdownController_, powerStateMachine_);
1539 }
1540 wakeupActionController_->Init();
1541 }
1542 #endif
1543
VibratorInit()1544 void PowerMgrService::VibratorInit()
1545 {
1546 std::shared_ptr<PowerVibrator> vibrator = PowerVibrator::GetInstance();
1547 vibrator->LoadConfig(POWER_VIBRATOR_CONFIG_FILE,
1548 VENDOR_POWER_VIBRATOR_CONFIG_FILE, SYSTEM_POWER_VIBRATOR_CONFIG_FILE);
1549 }
1550
IsStandby(bool & isStandby)1551 PowerErrors PowerMgrService::IsStandby(bool& isStandby)
1552 {
1553 #ifdef HAS_DEVICE_STANDBY_PART
1554 DevStandbyMgr::StandbyServiceClient& standbyServiceClient = DevStandbyMgr::StandbyServiceClient::GetInstance();
1555 ErrCode code = standbyServiceClient.IsDeviceInStandby(isStandby);
1556 if (code == ERR_OK) {
1557 return PowerErrors::ERR_OK;
1558 }
1559 return PowerErrors::ERR_CONNECTION_FAIL;
1560 #else
1561 return PowerErrors::ERR_OK;
1562 #endif
1563 }
1564
OnRemoteDied(const wptr<IRemoteObject> & remote)1565 void PowerMgrService::InvokerDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
1566 {
1567 POWER_HILOGI(COMP_SVC, "OnRemoteDied Called");
1568 if (!remote.promote()) {
1569 POWER_HILOGI(COMP_SVC, "proxy no longer exists, return early");
1570 return;
1571 }
1572 POWER_HILOGI(COMP_SVC, "the last client using %{public}s has died", interfaceName_.c_str());
1573 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
1574 if (!pms) {
1575 POWER_HILOGE(COMP_SVC, "cannot get PowerMgrService, return early");
1576 return;
1577 }
1578 callback_(pms);
1579 }
1580
SetForceTimingOut(bool enabled,const sptr<IRemoteObject> & token)1581 PowerErrors PowerMgrService::SetForceTimingOut(bool enabled, const sptr<IRemoteObject>& token)
1582 {
1583 static sptr<IRemoteObject> thisInterfaceInvoker = nullptr;
1584 static std::mutex localMutex;
1585 static sptr<InvokerDeathRecipient> drt =
1586 sptr<InvokerDeathRecipient>::MakeSptr(__func__, [](const sptr<PowerMgrService>& pms) {
1587 auto stateMachine = pms->GetPowerStateMachine();
1588 if (!stateMachine) {
1589 POWER_HILOGE(COMP_SVC, "cannot get PowerStateMachine, return early");
1590 return;
1591 }
1592 stateMachine->SetForceTimingOut(false);
1593 POWER_HILOGI(COMP_SVC, "the variables related to SetForceTimingOut has been reset");
1594 });
1595
1596 if (!Permission::IsSystem()) {
1597 return PowerErrors::ERR_SYSTEM_API_DENIED;
1598 }
1599
1600 // even if drt is nullptr(unlikely), it will be checked in IPCObjectProxy::SendObituary()
1601 localMutex.lock();
1602 if (token && token->IsProxyObject() && token != thisInterfaceInvoker) {
1603 // The localMutex only ensures that the "remove, assign, add" actions for THIS drt are thread safe.
1604 // AddDeathRecipient/RemoveDeathRecipient are thread safe theirselves.
1605 // Different remote objects(invokers) do not interfere wich each other
1606 // Different DeathRecipients for the same invoker do not interfere wich each other
1607 // Only one RemoteObject may hold the death recipient defined in this method and only once.
1608 if (thisInterfaceInvoker) {
1609 thisInterfaceInvoker->RemoveDeathRecipient(drt);
1610 } // removed from the old invoker
1611 thisInterfaceInvoker = token;
1612 thisInterfaceInvoker->AddDeathRecipient(drt); // added to the new invoker
1613 }
1614 localMutex.unlock();
1615 powerStateMachine_->SetForceTimingOut(enabled);
1616 return PowerErrors::ERR_OK;
1617 }
1618
LockScreenAfterTimingOut(bool enabledLockScreen,bool checkLock,bool sendScreenOffEvent,const sptr<IRemoteObject> & token)1619 PowerErrors PowerMgrService::LockScreenAfterTimingOut(
1620 bool enabledLockScreen, bool checkLock, bool sendScreenOffEvent, const sptr<IRemoteObject>& token)
1621 {
1622 static sptr<IRemoteObject> thisInterfaceInvoker = nullptr;
1623 static std::mutex localMutex;
1624 static sptr<InvokerDeathRecipient> drt =
1625 sptr<InvokerDeathRecipient>::MakeSptr(__func__, [](sptr<PowerMgrService> pms) {
1626 auto stateMachine = pms->GetPowerStateMachine();
1627 if (!stateMachine) {
1628 POWER_HILOGE(COMP_SVC, "cannot get PowerStateMachine, return early");
1629 return;
1630 }
1631 stateMachine->LockScreenAfterTimingOut(true, false, true);
1632 POWER_HILOGI(COMP_SVC, "the variables related to LockScreenAfterTimingOut has been reset");
1633 });
1634
1635 if (!Permission::IsSystem()) {
1636 return PowerErrors::ERR_SYSTEM_API_DENIED;
1637 }
1638 localMutex.lock();
1639 if (token && token->IsProxyObject() && token != thisInterfaceInvoker) {
1640 // The localMutex only ensures that the "remove, assign, add" actions are thread safe.
1641 // AddDeathRecipient/RemoveDeathRecipient are thread safe theirselves.
1642 if (thisInterfaceInvoker) {
1643 thisInterfaceInvoker->RemoveDeathRecipient(drt);
1644 } // removed from the old invoker
1645 thisInterfaceInvoker = token;
1646 thisInterfaceInvoker->AddDeathRecipient(drt); // added to the new invoker
1647 }
1648 localMutex.unlock();
1649 powerStateMachine_->LockScreenAfterTimingOut(enabledLockScreen, checkLock, sendScreenOffEvent);
1650 return PowerErrors::ERR_OK;
1651 }
1652
1653 #ifdef HAS_MULTIMODALINPUT_INPUT_PART
OnInputEvent(std::shared_ptr<KeyEvent> keyEvent) const1654 void PowerMgrInputMonitor::OnInputEvent(std::shared_ptr<KeyEvent> keyEvent) const
1655 {
1656 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
1657 if (pms == nullptr) {
1658 return;
1659 }
1660 auto stateMachine = pms->GetPowerStateMachine();
1661 if (stateMachine == nullptr) {
1662 return;
1663 }
1664 if (keyEvent->GetDeviceId() == COLLABORATION_REMOTE_DEVICE_ID &&
1665 stateMachine->IsRunningLockEnabled(RunningLockType::RUNNINGLOCK_COORDINATION) &&
1666 stateMachine->GetState() == PowerState::AWAKE) {
1667 stateMachine->SetState(PowerState::DIM, StateChangeReason::STATE_CHANGE_REASON_COORDINATION, true);
1668 POWER_HILOGD(FEATURE_INPUT, "remote Key event in coordinated state, override screen off time");
1669 }
1670 }
1671
OnInputEvent(std::shared_ptr<PointerEvent> pointerEvent) const1672 void PowerMgrInputMonitor::OnInputEvent(std::shared_ptr<PointerEvent> pointerEvent) const
1673 {
1674 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
1675 if (pms == nullptr) {
1676 return;
1677 }
1678 auto stateMachine = pms->GetPowerStateMachine();
1679 if (stateMachine == nullptr) {
1680 return;
1681 }
1682 auto action = pointerEvent->GetPointerAction();
1683 if (action == PointerEvent::POINTER_ACTION_ENTER_WINDOW ||
1684 action == PointerEvent::POINTER_ACTION_LEAVE_WINDOW ||
1685 action == PointerEvent::POINTER_ACTION_PULL_IN_WINDOW ||
1686 action == PointerEvent::POINTER_ACTION_PULL_OUT_WINDOW) {
1687 return;
1688 }
1689 if (pointerEvent->GetDeviceId() == COLLABORATION_REMOTE_DEVICE_ID &&
1690 stateMachine->IsRunningLockEnabled(RunningLockType::RUNNINGLOCK_COORDINATION) &&
1691 stateMachine->GetState() == PowerState::AWAKE) {
1692 stateMachine->SetState(PowerState::DIM, StateChangeReason::STATE_CHANGE_REASON_COORDINATION, true);
1693 POWER_HILOGD(FEATURE_INPUT, "remote pointer event in coordinated state, override screen off time");
1694 }
1695 }
1696
OnInputEvent(std::shared_ptr<AxisEvent> axisEvent) const1697 void PowerMgrInputMonitor::OnInputEvent(std::shared_ptr<AxisEvent> axisEvent) const {};
1698 #endif
1699
SubscribeCommonEvent()1700 void PowerMgrService::SubscribeCommonEvent()
1701 {
1702 using namespace OHOS::EventFwk;
1703 MatchingSkills matchingSkills;
1704 matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED);
1705 CommonEventSubscribeInfo subscribeInfo(matchingSkills);
1706 subscribeInfo.SetThreadMode(CommonEventSubscribeInfo::ThreadMode::COMMON);
1707 if (!subscriberPtr_) {
1708 subscriberPtr_ = std::make_shared<PowerCommonEventSubscriber>(subscribeInfo);
1709 }
1710 bool result = CommonEventManager::SubscribeCommonEvent(subscriberPtr_);
1711 if (!result) {
1712 POWER_HILOGE(COMP_SVC, "Subscribe COMMON_EVENT_USER_SWITCHED failed");
1713 }
1714 }
1715
OnReceiveEvent(const OHOS::EventFwk::CommonEventData & data)1716 void PowerCommonEventSubscriber::OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data)
1717 {
1718 std::string action = data.GetWant().GetAction();
1719 auto power = DelayedSpSingleton<PowerMgrService>::GetInstance();
1720 if (power == nullptr) {
1721 POWER_HILOGI(COMP_SVC, "get PowerMgrService fail");
1722 return;
1723 }
1724 if (action == OHOS::EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) {
1725 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
1726 SettingHelper::UnregisterSettingWakeupDoubleObserver();
1727 SettingHelper::UnregisterSettingWakeupPickupObserver();
1728 #endif
1729 power->GetWakeupController()->UnregisterSettingsObserver();
1730 SettingHelper::UpdateCurrentUserId();
1731 #ifdef POWER_WAKEUPDOUBLE_OR_PICKUP_ENABLE
1732 power->RegisterSettingObservers();
1733 power->RegisterSettingWakeupPickupGestureObserver();
1734 #endif
1735 power->WakeupControllerInit();
1736 }
1737 }
1738 } // namespace PowerMgr
1739 } // namespace OHOS
1740