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