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 "running_lock_mgr.h"
17
18 #include <cinttypes>
19 #include <datetime_ex.h>
20 #ifdef HAS_HIVIEWDFX_HISYSEVENT_PART
21 #include <hisysevent.h>
22 #endif
23 #include <ipc_skeleton.h>
24 #include <securec.h>
25 #ifdef HAS_HIVIEWDFX_HITRACE_PART
26 #include "power_hitrace.h"
27 #endif
28 #include "ffrt_utils.h"
29 #include "power_log.h"
30 #include "power_mgr_factory.h"
31 #include "power_mgr_service.h"
32 #include "power_utils.h"
33 #include "system_suspend_controller.h"
34
35 using namespace std;
36
37 namespace OHOS {
38 namespace PowerMgr {
39 namespace {
40 const string TASK_RUNNINGLOCK_FORCEUNLOCK = "RunningLock_ForceUnLock";
41 constexpr int32_t VALID_PID_LIMIT = 1;
42 constexpr uint32_t COORDINATION_LOCK_AUTO_SUSPEND_DELAY_TIME = 0;
43 sptr<IPowerRunninglockCallback> g_runningLockCallback = nullptr;
44 const string INCALL_APP_BUNDLE_NAME = "com.ohos.callui";
45 #ifdef HAS_SENSORS_SENSOR_PART
46 constexpr uint32_t FOREGROUND_INCALL_DELAY_TIME_MS = 300;
47 constexpr uint32_t BACKGROUND_INCALL_DELAY_TIME_MS = 800;
48 #endif
49 }
50
~RunningLockMgr()51 RunningLockMgr::~RunningLockMgr() {}
52
Init()53 bool RunningLockMgr::Init()
54 {
55 POWER_HILOGD(FEATURE_RUNNING_LOCK, "Init start");
56 if (runningLockDeathRecipient_ == nullptr) {
57 runningLockDeathRecipient_ = new RunningLockDeathRecipient();
58 }
59 if (runningLockAction_ == nullptr) {
60 runningLockAction_ = PowerMgrFactory::GetRunningLockAction();
61 if (!runningLockAction_) {
62 POWER_HILOGE(FEATURE_RUNNING_LOCK, "Get running lock action fail");
63 return false;
64 }
65 }
66 if (runninglockProxy_ == nullptr) {
67 runninglockProxy_ = std::make_shared<RunningLockProxy>();
68 }
69 bool ret = InitLocks();
70 POWER_HILOGI(FEATURE_RUNNING_LOCK, "Init success");
71 return ret;
72 }
73
InitLocks()74 bool RunningLockMgr::InitLocks()
75 {
76 InitLocksTypeScreen();
77 InitLocksTypeBackground();
78 #ifdef HAS_SENSORS_SENSOR_PART
79 InitLocksTypeProximity();
80 #endif
81 InitLocksTypeCoordination();
82 return true;
83 }
84
InitLocksTypeScreen()85 void RunningLockMgr::InitLocksTypeScreen()
86 {
87 lockCounters_.emplace(RunningLockType::RUNNINGLOCK_SCREEN,
88 std::make_shared<LockCounter>(RunningLockType::RUNNINGLOCK_SCREEN,
89 [this](bool active, [[maybe_unused]] RunningLockParam runningLockParam) -> int32_t {
90 POWER_HILOGD(FEATURE_RUNNING_LOCK, "RUNNINGLOCK_SCREEN action start");
91 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
92 if (pms == nullptr) {
93 return RUNNINGLOCK_FAILURE;
94 }
95 auto stateMachine = pms->GetPowerStateMachine();
96 if (stateMachine == nullptr) {
97 return RUNNINGLOCK_FAILURE;
98 }
99 if (active) {
100 // RUNNINGLOCK_SCREEN active
101 POWER_HILOGI(FEATURE_RUNNING_LOCK, "SL active");
102 pms->RefreshActivityInner(GetTickCount(), UserActivityType::USER_ACTIVITY_TYPE_SOFTWARE, true);
103 } else {
104 // RUNNINGLOCK_SCREEN inactive
105 POWER_HILOGI(FEATURE_RUNNING_LOCK, "SL inactive");
106 if (stateMachine->GetState() == PowerState::AWAKE) {
107 stateMachine->ResetInactiveTimer();
108 } else {
109 POWER_HILOGD(FEATURE_RUNNING_LOCK, "Screen unlock in state: %{public}d",
110 stateMachine->GetState());
111 }
112 }
113 return RUNNINGLOCK_SUCCESS;
114 })
115 );
116 }
117
InitLocksTypeBackground()118 void RunningLockMgr::InitLocksTypeBackground()
119 {
120 std::function<int32_t(bool, RunningLockParam)> activate =
121 [this](bool active, RunningLockParam lockInnerParam) -> int32_t {
122 if (active) {
123 return runningLockAction_->Lock(lockInnerParam);
124 } else {
125 return runningLockAction_->Unlock(lockInnerParam);
126 }
127 };
128 lockCounters_.emplace(RunningLockType::RUNNINGLOCK_BACKGROUND_PHONE,
129 std::make_shared<LockCounter>(RunningLockType::RUNNINGLOCK_BACKGROUND_PHONE, activate));
130 lockCounters_.emplace(RunningLockType::RUNNINGLOCK_BACKGROUND_NOTIFICATION,
131 std::make_shared<LockCounter>(RunningLockType::RUNNINGLOCK_BACKGROUND_NOTIFICATION, activate));
132 lockCounters_.emplace(RunningLockType::RUNNINGLOCK_BACKGROUND_AUDIO,
133 std::make_shared<LockCounter>(RunningLockType::RUNNINGLOCK_BACKGROUND_AUDIO, activate));
134 lockCounters_.emplace(RunningLockType::RUNNINGLOCK_BACKGROUND_SPORT,
135 std::make_shared<LockCounter>(RunningLockType::RUNNINGLOCK_BACKGROUND_SPORT, activate));
136 lockCounters_.emplace(RunningLockType::RUNNINGLOCK_BACKGROUND_NAVIGATION,
137 std::make_shared<LockCounter>(RunningLockType::RUNNINGLOCK_BACKGROUND_NAVIGATION, activate));
138 lockCounters_.emplace(RunningLockType::RUNNINGLOCK_BACKGROUND_TASK,
139 std::make_shared<LockCounter>(RunningLockType::RUNNINGLOCK_BACKGROUND_TASK, activate));
140 }
141
142 #ifdef HAS_SENSORS_SENSOR_PART
ProximityLockOn()143 void RunningLockMgr::ProximityLockOn()
144 {
145 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
146 if (pms == nullptr) {
147 return;
148 }
149 auto stateMachine = pms->GetPowerStateMachine();
150 auto suspendController = pms->GetSuspendController();
151 if (stateMachine == nullptr || suspendController == nullptr) {
152 return;
153 }
154
155 POWER_HILOGI(FEATURE_RUNNING_LOCK, "RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL active");
156 proximityController_.Enable();
157 if (proximityController_.IsClose()) {
158 POWER_HILOGI(FEATURE_RUNNING_LOCK, "[UL_POWER] INACTIVE when proximity is closed");
159 bool ret = stateMachine->SetState(PowerState::INACTIVE,
160 StateChangeReason::STATE_CHANGE_REASON_PROXIMITY, true);
161 if (ret) {
162 suspendController->StartSleepTimer(SuspendDeviceType::SUSPEND_DEVICE_REASON_APPLICATION,
163 static_cast<uint32_t>(SuspendAction::ACTION_AUTO_SUSPEND), 0);
164 }
165 } else {
166 POWER_HILOGI(FEATURE_RUNNING_LOCK, "[UL_POWER] AWAKE when proximity is away");
167 PreprocessBeforeAwake();
168 stateMachine->SetState(PowerState::AWAKE,
169 StateChangeReason::STATE_CHANGE_REASON_PROXIMITY, true);
170 }
171 }
172
InitLocksTypeProximity()173 void RunningLockMgr::InitLocksTypeProximity()
174 {
175 lockCounters_.emplace(RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL,
176 std::make_shared<LockCounter>(RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL,
177 [this](bool active, [[maybe_unused]] RunningLockParam runningLockParam) -> int32_t {
178 POWER_HILOGD(FEATURE_RUNNING_LOCK, "RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL action start");
179 FFRTTask task = [this] {
180 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
181 if (pms == nullptr) {
182 return;
183 }
184 auto stateMachine = pms->GetPowerStateMachine();
185 if (stateMachine == nullptr) {
186 return;
187 }
188 PreprocessBeforeAwake();
189 stateMachine->SetState(PowerState::AWAKE, StateChangeReason::STATE_CHANGE_REASON_RUNNING_LOCK);
190 };
191 if (active) {
192 POWER_HILOGI(FEATURE_RUNNING_LOCK, "[UL_POWER] RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL active");
193 proximityController_.Enable();
194 } else {
195 POWER_HILOGI(FEATURE_RUNNING_LOCK, "[UL_POWER] RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL inactive");
196 FFRTUtils::SubmitTask(task);
197 proximityController_.Disable();
198 proximityController_.Clear();
199 }
200 return RUNNINGLOCK_SUCCESS;
201 })
202 );
203 }
204 #endif
205
AsyncWakeup()206 void RunningLockMgr::AsyncWakeup()
207 {
208 FFRTTask asyncWakeup = []() {
209 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
210 if (pms == nullptr) {
211 POWER_HILOGI(FEATURE_RUNNING_LOCK, "Coordination unlock wakeup device, pms is nullptr");
212 return;
213 }
214 pms->WakeupDevice(GetTickCount(), WakeupDeviceType::WAKEUP_DEVICE_APPLICATION, "EndCollaboration");
215 };
216 FFRTUtils::SubmitTask(asyncWakeup);
217 }
218
InitLocksTypeCoordination()219 void RunningLockMgr::InitLocksTypeCoordination()
220 {
221 lockCounters_.emplace(RunningLockType::RUNNINGLOCK_COORDINATION,
222 std::make_shared<LockCounter>(RunningLockType::RUNNINGLOCK_COORDINATION,
223 [this](bool active, [[maybe_unused]] RunningLockParam runningLockParam) -> int32_t {
224 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
225 if (pms == nullptr) {
226 return RUNNINGLOCK_FAILURE;
227 }
228 auto stateMachine = pms->GetPowerStateMachine();
229 if (stateMachine == nullptr) {
230 return RUNNINGLOCK_FAILURE;
231 }
232 auto stateAction = stateMachine->GetStateAction();
233 if (stateAction == nullptr) {
234 return RUNNINGLOCK_FAILURE;
235 }
236 POWER_HILOGI(FEATURE_RUNNING_LOCK, "Coordination runninglock action, active=%{public}d, state=%{public}d",
237 active, stateMachine->GetState());
238 struct RunningLockParam backgroundLockParam = runningLockParam;
239 backgroundLockParam.name = PowerUtils::GetRunningLockTypeString(RunningLockType::RUNNINGLOCK_COORDINATION),
240 backgroundLockParam.type = RunningLockType::RUNNINGLOCK_BACKGROUND_TASK;
241 auto iterator = lockCounters_.find(backgroundLockParam.type);
242 if (iterator == lockCounters_.end()) {
243 POWER_HILOGE(FEATURE_RUNNING_LOCK, "unsupported type, type=%{public}d", backgroundLockParam.type);
244 return RUNNINGLOCK_NOT_SUPPORT;
245 }
246 std::shared_ptr<LockCounter> counter = iterator->second;
247 int32_t result = RUNNINGLOCK_SUCCESS;
248 if (active) {
249 result = counter->Increase(backgroundLockParam);
250 stateAction->SetCoordinated(true);
251 } else {
252 stateAction->SetCoordinated(false);
253 result = counter->Decrease(backgroundLockParam);
254 AsyncWakeup();
255 }
256 return result;
257 })
258 );
259 }
260
GetRunningLockInner(const sptr<IRemoteObject> & remoteObj)261 std::shared_ptr<RunningLockInner> RunningLockMgr::GetRunningLockInner(
262 const sptr<IRemoteObject>& remoteObj)
263 {
264 std::lock_guard<std::mutex> lock(mutex_);
265 auto iterator = runningLocks_.find(remoteObj);
266 if (iterator != runningLocks_.end()) {
267 return iterator->second;
268 }
269 return nullptr;
270 }
271
GetRunningLockInnerByName(const std::string & name)272 std::shared_ptr<RunningLockInner> RunningLockMgr::GetRunningLockInnerByName(
273 const std::string& name)
274 {
275 std::lock_guard<std::mutex> lock(mutex_);
276 std::shared_ptr<RunningLockInner> lockInner = nullptr;
277 std::string result = ToString(runningLocks_.size());
278 for (auto& iter : runningLocks_) {
279 if (iter.second == nullptr) {
280 POWER_HILOGE(FEATURE_RUNNING_LOCK, "GetRunningLockInnerByName nullptr");
281 continue;
282 }
283 if (iter.second->GetName() == name) {
284 lockInner = iter.second;
285 }
286 auto& lockParam = iter.second->GetParam();
287 result.append(" name=").append(lockParam.name);
288 }
289 POWER_HILOGI(FEATURE_RUNNING_LOCK, "DumpInfo: %{public}s", result.c_str());
290 return lockInner;
291 }
292
CreateRunningLock(const sptr<IRemoteObject> & remoteObj,const RunningLockParam & runningLockParam)293 std::shared_ptr<RunningLockInner> RunningLockMgr::CreateRunningLock(const sptr<IRemoteObject>& remoteObj,
294 const RunningLockParam& runningLockParam)
295 {
296 auto lockInner = RunningLockInner::CreateRunningLockInner(runningLockParam);
297 if (lockInner == nullptr) {
298 return nullptr;
299 }
300 POWER_HILOGI(FEATURE_RUNNING_LOCK, "CrtN:%{public}s,T:%{public}d",
301 lockInner->GetName().c_str(), lockInner->GetType());
302 {
303 std::lock_guard<std::mutex> lock(mutex_);
304 runningLocks_.emplace(remoteObj, lockInner);
305 }
306 if (lockInner->GetType() != RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL) {
307 runninglockProxy_->AddRunningLock(lockInner->GetPid(), lockInner->GetUid(), remoteObj);
308 }
309 remoteObj->AddDeathRecipient(runningLockDeathRecipient_);
310 return lockInner;
311 }
312
ReleaseLock(const sptr<IRemoteObject> remoteObj,const std::string & name)313 bool RunningLockMgr::ReleaseLock(const sptr<IRemoteObject> remoteObj, const std::string& name)
314 {
315 bool result = false;
316 auto lockInner = GetRunningLockInner(remoteObj);
317 if (lockInner == nullptr) {
318 POWER_HILOGE(FEATURE_RUNNING_LOCK, "RInner=null");
319 lockInner = GetRunningLockInnerByName(name);
320 if (lockInner == nullptr) {
321 POWER_HILOGE(FEATURE_RUNNING_LOCK, "%{public}s:LockInner not existed", __func__);
322 return result;
323 }
324 }
325 // ReleaseLock name type bundleName
326 POWER_HILOGI(FEATURE_RUNNING_LOCK, "RlsN:%{public}s,T:%{public}d,B:%{public}s",
327 lockInner->GetName().c_str(), lockInner->GetType(), lockInner->GetBundleName().c_str());
328 UnLock(remoteObj);
329 {
330 std::lock_guard<std::mutex> lock(mutex_);
331 runningLocks_.erase(remoteObj);
332 }
333 if (lockInner->GetType() != RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL) {
334 runninglockProxy_->RemoveRunningLock(lockInner->GetPid(), lockInner->GetUid(), remoteObj);
335 }
336 result = remoteObj->RemoveDeathRecipient(runningLockDeathRecipient_);
337 return result;
338 }
339
IsSceneRunningLockType(RunningLockType type)340 bool RunningLockMgr::IsSceneRunningLockType(RunningLockType type)
341 {
342 return type == RunningLockType::RUNNINGLOCK_BACKGROUND_PHONE ||
343 type == RunningLockType::RUNNINGLOCK_BACKGROUND_NOTIFICATION ||
344 type == RunningLockType::RUNNINGLOCK_BACKGROUND_AUDIO ||
345 type == RunningLockType::RUNNINGLOCK_BACKGROUND_SPORT ||
346 type == RunningLockType::RUNNINGLOCK_BACKGROUND_NAVIGATION ||
347 type == RunningLockType::RUNNINGLOCK_BACKGROUND_TASK;
348 }
349
NeedNotify(RunningLockType type)350 bool RunningLockMgr::NeedNotify(RunningLockType type)
351 {
352 return IsSceneRunningLockType(type) ||
353 type == RunningLockType::RUNNINGLOCK_SCREEN ||
354 type == RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL;
355 }
356
UpdateUnSceneLockLists(RunningLockParam & singleLockParam,bool fill)357 void RunningLockMgr::UpdateUnSceneLockLists(RunningLockParam& singleLockParam, bool fill)
358 {
359 std::lock_guard<std::mutex> lock(screenLockListsMutex_);
360 auto iterator = unSceneLockLists_.find(std::to_string(singleLockParam.lockid));
361 if (fill) {
362 if (iterator == unSceneLockLists_.end()) {
363 POWER_HILOGD(FEATURE_RUNNING_LOCK, "Add non-scene lock information from lists");
364 RunningLockInfo unSceneAppLockInfo = FillAppRunningLockInfo(singleLockParam);
365 unSceneLockLists_.insert(
366 std::pair<std::string, RunningLockInfo>(std::to_string(singleLockParam.lockid), unSceneAppLockInfo));
367 }
368 return;
369 }
370 if (iterator != unSceneLockLists_.end()) {
371 POWER_HILOGD(FEATURE_RUNNING_LOCK, "Remove non-scene lock information from lists");
372 unSceneLockLists_.erase(iterator);
373 }
374 return;
375 }
376
FillAppRunningLockInfo(const RunningLockParam & info)377 RunningLockInfo RunningLockMgr::FillAppRunningLockInfo(const RunningLockParam& info)
378 {
379 RunningLockInfo tempAppRunningLockInfo = {};
380 tempAppRunningLockInfo.name = info.name;
381 tempAppRunningLockInfo.bundleName = info.bundleName;
382 tempAppRunningLockInfo.type = info.type;
383 tempAppRunningLockInfo.pid = info.pid;
384 tempAppRunningLockInfo.uid = info.uid;
385 return tempAppRunningLockInfo;
386 }
387
IsValidType(RunningLockType type)388 bool RunningLockMgr::IsValidType(RunningLockType type)
389 {
390 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
391 if (pms == nullptr) {
392 return true;
393 }
394 PowerState state = pms->GetState();
395 POWER_HILOGD(FEATURE_RUNNING_LOCK, "state=%{public}d, type=%{public}d", state, type);
396 switch (state) {
397 case PowerState::AWAKE:
398 case PowerState::FREEZE:
399 case PowerState::INACTIVE:
400 case PowerState::STAND_BY:
401 case PowerState::DOZE:
402 return true;
403 case PowerState::SLEEP:
404 case PowerState::HIBERNATE:
405 return type != RunningLockType::RUNNINGLOCK_COORDINATION;
406 default:
407 break;
408 }
409 return true;
410 }
411
PreprocessBeforeAwake()412 void RunningLockMgr::PreprocessBeforeAwake()
413 {
414 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
415 if (pms == nullptr) {
416 return;
417 }
418 auto stateMachine = pms->GetPowerStateMachine();
419 auto suspendController = pms->GetSuspendController();
420 if (stateMachine == nullptr || suspendController == nullptr) {
421 return;
422 }
423
424 suspendController->StopSleep();
425 POWER_HILOGI(FEATURE_RUNNING_LOCK, "wake up.");
426 SystemSuspendController::GetInstance().Wakeup();
427 if (stateMachine->GetState() == PowerState::SLEEP) {
428 POWER_HILOGI(FEATURE_RUNNING_LOCK, "TriggerSyncSleepCallback start.");
429 suspendController->TriggerSyncSleepCallback(true);
430 }
431 }
432
UpdateWorkSource(const sptr<IRemoteObject> & remoteObj,const std::map<int32_t,std::string> & workSources)433 bool RunningLockMgr::UpdateWorkSource(const sptr<IRemoteObject>& remoteObj,
434 const std::map<int32_t, std::string>& workSources)
435 {
436 auto lockInner = GetRunningLockInner(remoteObj);
437 if (lockInner == nullptr) {
438 POWER_HILOGD(FEATURE_RUNNING_LOCK, "%{public}s:LockInner is nullptr", __func__);
439 return false;
440 }
441 RunningLockParam lockInnerParam = lockInner->GetParam();
442 POWER_HILOGD(FEATURE_RUNNING_LOCK, "try UpdateWorkSource, name: %{public}s, type: %{public}d",
443 lockInnerParam.name.c_str(), lockInnerParam.type);
444 runninglockProxy_->UpdateWorkSource(lockInner->GetPid(), lockInner->GetUid(), remoteObj, workSources);
445 return true;
446 }
447
Lock(const sptr<IRemoteObject> & remoteObj)448 bool RunningLockMgr::Lock(const sptr<IRemoteObject>& remoteObj)
449 {
450 #ifdef HAS_HIVIEWDFX_HITRACE_PART
451 PowerHitrace powerHitrace("RunningLock_Lock");
452 #endif
453 auto lockInner = GetRunningLockInner(remoteObj);
454 if (lockInner == nullptr) {
455 POWER_HILOGE(FEATURE_RUNNING_LOCK, "LInner=null");
456 return false;
457 }
458 RunningLockParam lockInnerParam = lockInner->GetParam();
459 // try lock
460 POWER_HILOGD(FEATURE_RUNNING_LOCK, "LockN:%{public}s,T:%{public}d",
461 lockInnerParam.name.c_str(), lockInnerParam.type);
462 if (lockInner->IsProxied()) {
463 // Runninglock is proxied
464 POWER_HILOGW(FEATURE_RUNNING_LOCK,
465 "try lock proxied fail,N:%{public}s,T:%{public}d", lockInnerParam.name.c_str(), lockInnerParam.type);
466 return false;
467 }
468 if (!IsValidType(lockInnerParam.type)) {
469 // Type is invalid
470 POWER_HILOGE(FEATURE_RUNNING_LOCK,
471 "try lock type fail,N:%{public}s,T:%{public}d", lockInnerParam.name.c_str(), lockInnerParam.type);
472 return false;
473 }
474 if (lockInner->GetState() == RunningLockState::RUNNINGLOCK_STATE_ENABLE) {
475 // Lock is already enabled
476 POWER_HILOGI(FEATURE_RUNNING_LOCK, "Locked N=%{public}s", lockInner->GetName().c_str());
477 return false;
478 }
479 if (lockInnerParam.type == RunningLockType::RUNNINGLOCK_SCREEN) {
480 UpdateUnSceneLockLists(lockInnerParam, true);
481 }
482 auto iterator = lockCounters_.find(lockInnerParam.type);
483 if (iterator == lockCounters_.end()) {
484 // Lock failed unsupported
485 POWER_HILOGE(FEATURE_RUNNING_LOCK,
486 "try lock fail,N:%{public}s,T:%{public}d", lockInnerParam.name.c_str(), lockInnerParam.type);
487 return false;
488 }
489 std::shared_ptr<LockCounter> counter = iterator->second;
490 if (counter->Increase(lockInnerParam) != RUNNINGLOCK_SUCCESS) {
491 POWER_HILOGE(FEATURE_RUNNING_LOCK, "try lock increase fail,N:%{public}s,T:%{public}d,C:%{public}d",
492 lockInnerParam.name.c_str(), counter->GetType(), counter->GetCount());
493 return false;
494 }
495 #ifdef HAS_HIVIEWDFX_HISYSEVENT_PART
496 lockInner->SetBeginTime(GetTickCount());
497 #endif
498 lockInner->SetState(RunningLockState::RUNNINGLOCK_STATE_ENABLE);
499 return true;
500 }
501
UnLock(const sptr<IRemoteObject> remoteObj,const std::string & name)502 bool RunningLockMgr::UnLock(const sptr<IRemoteObject> remoteObj, const std::string& name)
503 {
504 #ifdef HAS_HIVIEWDFX_HITRACE_PART
505 PowerHitrace powerHitrace("RunningLock_Unlock");
506 #endif
507 auto lockInner = GetRunningLockInner(remoteObj);
508 if (lockInner == nullptr) {
509 POWER_HILOGD(FEATURE_RUNNING_LOCK, "UnInner=null");
510 lockInner = GetRunningLockInnerByName(name);
511 if (lockInner == nullptr) {
512 POWER_HILOGD(FEATURE_RUNNING_LOCK, "%{public}s:LockInner not existed", __func__);
513 return false;
514 }
515 }
516 if (lockInner->IsProxied()) {
517 POWER_HILOGW(FEATURE_RUNNING_LOCK, "Runninglock is proxied, unProxy");
518 runninglockProxy_->UpdateProxyState(lockInner->GetPid(), lockInner->GetUid(), remoteObj, false);
519 lockInner->SetState(RunningLockState::RUNNINGLOCK_STATE_DISABLE);
520 }
521 auto lockInnerParam = lockInner->GetParam();
522 // try unlock
523 POWER_HILOGD(FEATURE_RUNNING_LOCK, "UnLockN:%{public}s,T:%{public}d",
524 lockInnerParam.name.c_str(), lockInnerParam.type);
525 if (lockInner->GetState() == RunningLockState::RUNNINGLOCK_STATE_DISABLE) {
526 // Lock is already disabled
527 POWER_HILOGI(FEATURE_RUNNING_LOCK, "UnLocked N=%{public}s", lockInner->GetName().c_str());
528 return false;
529 }
530 if (lockInnerParam.type == RunningLockType::RUNNINGLOCK_SCREEN) {
531 UpdateUnSceneLockLists(lockInnerParam, false);
532 }
533 auto iterator = lockCounters_.find(lockInnerParam.type);
534 if (iterator == lockCounters_.end()) {
535 // Unlock failed unsupported type
536 POWER_HILOGE(FEATURE_RUNNING_LOCK, "try unlock fail,N:%{public}s,T:%{public}d",
537 lockInnerParam.name.c_str(), lockInnerParam.type);
538 return false;
539 }
540 std::shared_ptr<LockCounter> counter = iterator->second;
541 if (counter->Decrease(lockInnerParam)) {
542 POWER_HILOGE(FEATURE_RUNNING_LOCK, "try unlock decrease fail,N:%{public}s,T:%{public}d,C:%{public}d",
543 lockInnerParam.name.c_str(), counter->GetType(), counter->GetCount());
544 return false;
545 }
546 WriteHiSysEvent(lockInner);
547 lockInner->SetState(RunningLockState::RUNNINGLOCK_STATE_DISABLE);
548 return true;
549 }
550
WriteHiSysEvent(std::shared_ptr<RunningLockInner> & lockInner)551 void RunningLockMgr::WriteHiSysEvent(std::shared_ptr<RunningLockInner>& lockInner)
552 {
553 #ifdef HAS_HIVIEWDFX_HISYSEVENT_PART
554 constexpr int32_t APP_HOLD_RUNNINGLOCK_TIMEOUT = 7200000;
555 int32_t endTimeMs = GetTickCount();
556 int32_t beginTimeMs = lockInner->GetBeginTime();
557 if (endTimeMs - beginTimeMs > APP_HOLD_RUNNINGLOCK_TIMEOUT) {
558 POWER_HILOGI(FEATURE_RUNNING_LOCK, "app hold runninglock timeout=%{public}d", (endTimeMs - beginTimeMs));
559 HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::POWER, "APP_HOLD_RUNNINGLOCK_TIMEOUT",
560 HiviewDFX::HiSysEvent::EventType::BEHAVIOR, "PID", lockInner->GetPid(), "UID", lockInner->GetUid(),
561 "TYPE", static_cast<int32_t>(lockInner->GetParam().type), "NAME", lockInner->GetParam().name);
562 }
563 #endif
564 }
565
RegisterRunningLockCallback(const sptr<IPowerRunninglockCallback> & callback)566 void RunningLockMgr::RegisterRunningLockCallback(const sptr<IPowerRunninglockCallback>& callback)
567 {
568 if (g_runningLockCallback != nullptr) {
569 UnRegisterRunningLockCallback(callback);
570 }
571 g_runningLockCallback = callback;
572 POWER_HILOGI(FEATURE_RUNNING_LOCK, "RegisterRunningLockCallback success");
573 }
574
UnRegisterRunningLockCallback(const sptr<IPowerRunninglockCallback> & callback)575 void RunningLockMgr::UnRegisterRunningLockCallback(const sptr<IPowerRunninglockCallback>& callback)
576 {
577 g_runningLockCallback = nullptr;
578 POWER_HILOGI(FEATURE_RUNNING_LOCK, "UnRegisterRunningLockCallback success");
579 }
580
QueryRunningLockLists(std::map<std::string,RunningLockInfo> & runningLockLists)581 void RunningLockMgr::QueryRunningLockLists(std::map<std::string, RunningLockInfo>& runningLockLists)
582 {
583 std::lock_guard<std::mutex> lock(screenLockListsMutex_);
584 for (auto &iter : unSceneLockLists_) {
585 runningLockLists.insert(std::pair<std::string, RunningLockInfo>(iter.first, iter.second));
586 }
587 return;
588 }
589
IsUsed(const sptr<IRemoteObject> & remoteObj)590 bool RunningLockMgr::IsUsed(const sptr<IRemoteObject>& remoteObj)
591 {
592 auto lockInner = GetRunningLockInner(remoteObj);
593 if (lockInner == nullptr || lockInner->GetState() != RunningLockState::RUNNINGLOCK_STATE_ENABLE) {
594 return false;
595 }
596 return true;
597 }
598
GetRunningLockNum(RunningLockType type)599 uint32_t RunningLockMgr::GetRunningLockNum(RunningLockType type)
600 {
601 std::lock_guard<std::mutex> lock(mutex_);
602 if (type == RunningLockType::RUNNINGLOCK_BUTT) {
603 return runningLocks_.size();
604 }
605 return std::count_if(runningLocks_.begin(), runningLocks_.end(),
606 [&type](const auto& pair) {
607 return pair.second->GetType() == type;
608 });
609 }
610
GetValidRunningLockNum(RunningLockType type)611 uint32_t RunningLockMgr::GetValidRunningLockNum(RunningLockType type)
612 {
613 auto iterator = lockCounters_.find(type);
614 if (iterator == lockCounters_.end()) {
615 POWER_HILOGD(FEATURE_RUNNING_LOCK, "No specific lock, type=%{public}d", type);
616 return 0;
617 }
618 std::shared_ptr<LockCounter> counter = iterator->second;
619 return counter->GetCount();
620 }
621
ExistValidRunningLock()622 bool RunningLockMgr::ExistValidRunningLock()
623 {
624 std::lock_guard<std::mutex> lock(mutex_);
625 for (auto it = runningLocks_.begin(); it != runningLocks_.end(); it++) {
626 auto& lockinner = it->second;
627 if (lockinner->GetState() == RunningLockState::RUNNINGLOCK_STATE_ENABLE) {
628 return true;
629 }
630 }
631 return false;
632 }
633
NotifyRunningLockChanged(const RunningLockParam & lockInnerParam,const std::string & tag,const std::string & logTag)634 void RunningLockMgr::NotifyRunningLockChanged(const RunningLockParam& lockInnerParam, const std::string &tag,
635 const std::string &logTag)
636 {
637 uint64_t lockid = lockInnerParam.lockid;
638 int32_t pid = lockInnerParam.pid;
639 int32_t uid = lockInnerParam.uid;
640 int32_t type = static_cast <int32_t>(lockInnerParam.type);
641 auto pos = lockInnerParam.name.rfind('_');
642 string name = lockInnerParam.name.substr(0, pos);
643 string bundleName = lockInnerParam.bundleName;
644 auto now = std::chrono::system_clock::now();
645 auto timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
646 std::string message;
647 message.append("LOCKID=").append(std::to_string(lockid))
648 .append(" PID=").append(std::to_string(pid))
649 .append(" UID=").append(std::to_string(uid))
650 .append(" TYPE=").append(std::to_string(type))
651 .append(" NAME=").append(name)
652 .append(" BUNDLENAME=").append(bundleName)
653 .append(" TAG=").append(tag)
654 .append(" TIMESTAMP=").append(std::to_string(timestamp));
655 // runninglock message
656 POWER_HILOGI(COMP_LOCK, "P=%{public}dU=%{public}dT=%{public}dN=%{public}sB=%{public}sTA=%{public}s",
657 pid, uid, type, lockInnerParam.name.c_str(), bundleName.c_str(), logTag.c_str());
658 if (g_runningLockCallback != nullptr) {
659 g_runningLockCallback->HandleRunningLockMessage(message);
660 }
661 }
662
TransformLockid(const sptr<IRemoteObject> & remoteObj)663 uint64_t RunningLockMgr::TransformLockid(const sptr<IRemoteObject>& remoteObj)
664 {
665 uintptr_t remoteObjPtr = reinterpret_cast<uintptr_t>(remoteObj.GetRefPtr());
666 uint64_t lockid = std::hash<uintptr_t>()(remoteObjPtr);
667 return lockid;
668 }
669
ProxyRunningLock(bool isProxied,pid_t pid,pid_t uid)670 bool RunningLockMgr::ProxyRunningLock(bool isProxied, pid_t pid, pid_t uid)
671 {
672 if (pid < VALID_PID_LIMIT) {
673 POWER_HILOGW(FEATURE_RUNNING_LOCK, "Proxy runninglock failed, pid=%{public}d is invalid", pid);
674 return false;
675 }
676
677 if (isProxied) {
678 runninglockProxy_->IncreaseProxyCnt(pid, uid);
679 } else {
680 runninglockProxy_->DecreaseProxyCnt(pid, uid);
681 }
682 return true;
683 }
684
ProxyRunningLocks(bool isProxied,const std::vector<std::pair<pid_t,pid_t>> & processInfos)685 void RunningLockMgr::ProxyRunningLocks(bool isProxied, const std::vector<std::pair<pid_t, pid_t>>& processInfos)
686 {
687 for (const auto& [pid, uid] : processInfos) {
688 ProxyRunningLock(isProxied, pid, uid);
689 }
690 }
691
ResetRunningLocks()692 void RunningLockMgr::ResetRunningLocks()
693 {
694 POWER_HILOGI(FEATURE_RUNNING_LOCK, "Reset runninglock proxy");
695 runninglockProxy_->ResetRunningLocks();
696 }
697
LockInnerByProxy(const sptr<IRemoteObject> & remoteObj,std::shared_ptr<RunningLockInner> & lockInner)698 void RunningLockMgr::LockInnerByProxy(const sptr<IRemoteObject>& remoteObj,
699 std::shared_ptr<RunningLockInner>& lockInner)
700 {
701 if (!lockInner->IsProxied()) {
702 // LockInnerByProxy failed, runninglock UnProxied
703 POWER_HILOGW(FEATURE_RUNNING_LOCK, "Lock UnProxied");
704 return;
705 }
706 RunningLockParam lockInnerParam = lockInner->GetParam();
707 POWER_HILOGD(FEATURE_RUNNING_LOCK, "try LockInnerByProxy, name: %{public}s, type: %{public}d",
708 lockInnerParam.name.c_str(), lockInnerParam.type);
709 RunningLockState lastState = lockInner->GetState();
710 if (lastState == RunningLockState::RUNNINGLOCK_STATE_PROXIED) {
711 lockInner->SetState(RunningLockState::RUNNINGLOCK_STATE_DISABLE);
712 Lock(remoteObj);
713 }
714 }
715
UnlockInnerByProxy(const sptr<IRemoteObject> & remoteObj,std::shared_ptr<RunningLockInner> & lockInner)716 void RunningLockMgr::UnlockInnerByProxy(const sptr<IRemoteObject>& remoteObj,
717 std::shared_ptr<RunningLockInner>& lockInner)
718 {
719 RunningLockState lastState = lockInner->GetState();
720 if (lastState == RunningLockState::RUNNINGLOCK_STATE_DISABLE) {
721 // UnlockInnerByProxy failed, runninglock Disable
722 POWER_HILOGW(FEATURE_RUNNING_LOCK, "Unlock Disable");
723 return;
724 }
725 if (lastState == RunningLockState::RUNNINGLOCK_STATE_PROXIED) {
726 POWER_HILOGW(FEATURE_RUNNING_LOCK, "UnlockInnerByProxy failed, runninglock Proxied");
727 return;
728 }
729 RunningLockParam lockInnerParam = lockInner->GetParam();
730 POWER_HILOGD(FEATURE_RUNNING_LOCK, "try UnlockInnerByProxy, name: %{public}s, type: %{public}d",
731 lockInnerParam.name.c_str(), lockInnerParam.type);
732 UnLock(remoteObj);
733 lockInner->SetState(RunningLockState::RUNNINGLOCK_STATE_PROXIED);
734 }
735
EnableMock(IRunningLockAction * mockAction)736 void RunningLockMgr::EnableMock(IRunningLockAction* mockAction)
737 {
738 // reset lock list
739 runningLocks_.clear();
740 for (auto it = lockCounters_.begin(); it != lockCounters_.end(); it++) {
741 it->second->Clear();
742 }
743 runninglockProxy_->Clear();
744 #ifdef HAS_SENSORS_SENSOR_PART
745 proximityController_.Clear();
746 #endif
747 std::shared_ptr<IRunningLockAction> mock(mockAction);
748 runningLockAction_ = mock;
749 }
750
DumpInfo(std::string & result)751 void RunningLockMgr::DumpInfo(std::string& result)
752 {
753 auto validSize = GetValidRunningLockNum();
754 std::lock_guard<std::mutex> lock(mutex_);
755
756 result.append("RUNNING LOCK DUMP:\n");
757 result.append(" totalSize=").append(ToString(runningLocks_.size()))
758 .append(" validSize=").append(ToString(validSize)).append("\n");
759 result.append("Summary By Type: \n");
760 for (auto it = lockCounters_.begin(); it != lockCounters_.end(); it++) {
761 result.append(" ")
762 .append(PowerUtils::GetRunningLockTypeString(it->first))
763 .append(": ")
764 .append(ToString(it->second->GetCount()))
765 .append("\n");
766 }
767
768 if (runningLocks_.empty()) {
769 result.append("Lock List is Empty. \n");
770 return;
771 }
772
773 result.append("Dump Lock List: \n");
774 auto curTick = GetTickCount();
775 int index = 0;
776 for (const auto& it : runningLocks_) {
777 index++;
778 auto lockInner = it.second;
779 if (lockInner == nullptr) {
780 return;
781 }
782 auto& lockParam = lockInner->GetParam();
783 result.append(" index=").append(ToString(index))
784 .append(" time=").append(ToString(curTick - lockInner->GetLockTimeMs()))
785 .append(" type=").append(PowerUtils::GetRunningLockTypeString(lockParam.type))
786 .append(" name=").append(lockParam.name)
787 .append(" uid=").append(ToString(lockInner->GetUid()))
788 .append(" pid=").append(ToString(lockInner->GetPid()))
789 .append(" state=").append(ToString(static_cast<uint32_t>(lockInner->GetState())))
790 .append("\n");
791 }
792
793 result.append("Dump Proxy List: \n");
794 result.append(runninglockProxy_->DumpProxyInfo());
795 #ifdef HAS_SENSORS_SENSOR_PART
796 result.append("Peripherals Info: \n")
797 .append(" Proximity: ")
798 .append("Enabled=")
799 .append(ToString(proximityController_.IsEnabled()))
800 .append(" Status=")
801 .append(ToString(proximityController_.GetStatus()))
802 .append("\n");
803 #endif
804 }
805
OnRemoteDied(const wptr<IRemoteObject> & remote)806 void RunningLockMgr::RunningLockDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
807 {
808 if (remote == nullptr || remote.promote() == nullptr) {
809 POWER_HILOGW(FEATURE_RUNNING_LOCK, "Remote is nullptr");
810 return;
811 }
812 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
813 if (pms == nullptr) {
814 POWER_HILOGW(FEATURE_RUNNING_LOCK, "Power service is nullptr");
815 return;
816 }
817 pms->ForceUnLock(remote.promote());
818 }
819
Increase(const RunningLockParam & lockInnerParam)820 int32_t RunningLockMgr::LockCounter::Increase(const RunningLockParam& lockInnerParam)
821 {
822 ++counter_;
823 int32_t result = RUNNINGLOCK_SUCCESS;
824 if (counter_ == 1) {
825 result = activate_(true, lockInnerParam);
826 if (result != RUNNINGLOCK_SUCCESS) {
827 --counter_;
828 }
829 }
830 if (result == RUNNINGLOCK_SUCCESS && NeedNotify(lockInnerParam.type)) {
831 NotifyRunningLockChanged(lockInnerParam, "DUBAI_TAG_RUNNINGLOCK_ADD", "AD");
832 }
833 return result;
834 }
835
Decrease(const RunningLockParam & lockInnerParam)836 int32_t RunningLockMgr::LockCounter::Decrease(const RunningLockParam& lockInnerParam)
837 {
838 --counter_;
839 int32_t result = RUNNINGLOCK_SUCCESS;
840 if (counter_ == 0) {
841 result = activate_(false, lockInnerParam);
842 if (result != RUNNINGLOCK_SUCCESS) {
843 ++counter_;
844 }
845 }
846 if (result == RUNNINGLOCK_SUCCESS && NeedNotify(lockInnerParam.type)) {
847 NotifyRunningLockChanged(lockInnerParam, "DUBAI_TAG_RUNNINGLOCK_REMOVE", "RE");
848 }
849 return result;
850 }
851
Clear()852 void RunningLockMgr::LockCounter::Clear()
853 {
854 counter_ = 0;
855 }
856
857 #ifdef HAS_SENSORS_SENSOR_PART
RecordSensorCallback(SensorEvent * event)858 void RunningLockMgr::ProximityController::RecordSensorCallback(SensorEvent *event)
859 {
860 POWER_HILOGD(FEATURE_RUNNING_LOCK, "Sensor Callback come in");
861 if (event == nullptr) {
862 POWER_HILOGW(FEATURE_RUNNING_LOCK, "Sensor event is nullptr");
863 return;
864 }
865 if (event->sensorTypeId != SENSOR_TYPE_ID_PROXIMITY) {
866 POWER_HILOGW(FEATURE_RUNNING_LOCK, "Sensor type is not PROXIMITY");
867 return;
868 }
869 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
870 if (pms == nullptr) {
871 POWER_HILOGE(FEATURE_RUNNING_LOCK, "Power service is nullptr");
872 return;
873 }
874 auto runningLock = pms->GetRunningLockMgr();
875 ProximityData* data = reinterpret_cast<ProximityData*>(event->data);
876 int32_t distance = static_cast<int32_t>(data->distance);
877
878 POWER_HILOGI(FEATURE_RUNNING_LOCK, "SensorD=%{public}d", distance);
879 if (distance == PROXIMITY_CLOSE_SCALAR) {
880 runningLock->SetProximity(PROXIMITY_CLOSE);
881 } else if (distance == PROXIMITY_AWAY_SCALAR) {
882 runningLock->SetProximity(PROXIMITY_AWAY);
883 }
884 }
885
OnClose()886 void RunningLockMgr::ProximityController::OnClose()
887 {
888 if (!enabled_ || IsClose()) {
889 POWER_HILOGI(FEATURE_RUNNING_LOCK, "PROXIMITY is disabled or closed already");
890 return;
891 }
892 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
893 if (pms == nullptr) {
894 POWER_HILOGE(FEATURE_RUNNING_LOCK, "Power service is nullptr");
895 return;
896 }
897 auto stateMachine = pms->GetPowerStateMachine();
898 auto suspendController = pms->GetSuspendController();
899 if (stateMachine == nullptr || suspendController == nullptr) {
900 POWER_HILOGE(FEATURE_RUNNING_LOCK, "state machine is nullptr");
901 return;
902 }
903 isClose_ = true;
904 POWER_HILOGD(FEATURE_RUNNING_LOCK, "PROXIMITY is closed");
905 auto runningLock = pms->GetRunningLockMgr();
906 if (runningLock->GetValidRunningLockNum(RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL) > 0) {
907 POWER_HILOGI(FEATURE_RUNNING_LOCK, "Change state to INACITVE when holding PROXIMITY LOCK");
908 uint32_t delayTime = FOREGROUND_INCALL_DELAY_TIME_MS;
909 if (!PowerUtils::IsForegroundApplication(INCALL_APP_BUNDLE_NAME)) {
910 delayTime = BACKGROUND_INCALL_DELAY_TIME_MS;
911 }
912 POWER_HILOGI(FEATURE_RUNNING_LOCK, "Start proximity-screen-off timer, delay time:%{public}u", delayTime);
913 stateMachine->SetDelayTimer(delayTime, PowerStateMachine::CHECK_PROXIMITY_SCREEN_OFF_MSG);
914 } else {
915 POWER_HILOGI(FEATURE_RUNNING_LOCK, "Unholding PROXIMITY LOCK");
916 }
917 }
918
OnAway()919 void RunningLockMgr::ProximityController::OnAway()
920 {
921 if (!enabled_ || !IsClose()) {
922 POWER_HILOGI(FEATURE_RUNNING_LOCK, "PROXIMITY is disabled or away already");
923 return;
924 }
925 auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
926 if (pms == nullptr) {
927 POWER_HILOGE(FEATURE_RUNNING_LOCK, "Power service is nullptr");
928 return;
929 }
930 auto stateMachine = pms->GetPowerStateMachine();
931 if (stateMachine == nullptr) {
932 POWER_HILOGE(FEATURE_RUNNING_LOCK, "state machine is nullptr");
933 return;
934 }
935 isClose_ = false;
936 POWER_HILOGD(FEATURE_RUNNING_LOCK, "PROXIMITY is away");
937 auto runningLock = pms->GetRunningLockMgr();
938 if (runningLock->GetValidRunningLockNum(
939 RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL) > 0) {
940 POWER_HILOGI(FEATURE_RUNNING_LOCK, "Change state to AWAKE when holding PROXIMITY LOCK");
941 runningLock->PreprocessBeforeAwake();
942 stateMachine->SetState(PowerState::AWAKE, StateChangeReason::STATE_CHANGE_REASON_PROXIMITY, true);
943 } else {
944 POWER_HILOGI(FEATURE_RUNNING_LOCK, "Unholding PROXIMITY LOCK");
945 }
946 }
947
SetProximity(uint32_t status)948 void RunningLockMgr::SetProximity(uint32_t status)
949 {
950 switch (status) {
951 case PROXIMITY_CLOSE:
952 proximityController_.OnClose();
953 break;
954 case PROXIMITY_AWAY:
955 proximityController_.OnAway();
956 break;
957 default:
958 break;
959 }
960 }
961
IsProximityClose()962 bool RunningLockMgr::IsProximityClose()
963 {
964 return proximityController_.IsClose();
965 }
966 #endif
967
968 } // namespace PowerMgr
969 } // namespace OHOS
970