• 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 "hitrace_meter.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 "system_suspend_controller.h"
30 
31 using namespace std;
32 
33 namespace OHOS {
34 namespace PowerMgr {
35 namespace {
36 const string TASK_RUNNINGLOCK_FORCEUNLOCK = "RunningLock_ForceUnLock";
37 constexpr int32_t VALID_PID_LIMIT = 1;
38 FFRTQueue g_queue("power_running_lock_mgr");
39 FFRTHandle g_runningLockTimeoutHandle;
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     return true;
78 }
79 
InitLocksTypeScreen()80 void RunningLockMgr::InitLocksTypeScreen()
81 {
82     lockCounters_.emplace(RunningLockType::RUNNINGLOCK_SCREEN,
83         std::make_shared<LockCounter>(
84         RunningLockType::RUNNINGLOCK_SCREEN, [this](bool active) {
85             POWER_HILOGD(FEATURE_RUNNING_LOCK, "RUNNINGLOCK_SCREEN action start");
86             auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
87             if (pms == nullptr) {
88                 return;
89             }
90             auto stateMachine = pms->GetPowerStateMachine();
91             if (stateMachine == nullptr) {
92                 return;
93             }
94             if (active) {
95                 POWER_HILOGI(FEATURE_RUNNING_LOCK, "RUNNINGLOCK_SCREEN active");
96                 SystemSuspendController::GetInstance().Wakeup();
97                 stateMachine->SetState(PowerState::AWAKE,
98                     StateChangeReason::STATE_CHANGE_REASON_RUNNING_LOCK);
99                 stateMachine->CancelDelayTimer(
100                     PowerStateMachine::CHECK_USER_ACTIVITY_TIMEOUT_MSG);
101                 stateMachine->CancelDelayTimer(
102                     PowerStateMachine::CHECK_USER_ACTIVITY_OFF_TIMEOUT_MSG);
103             } else {
104                 POWER_HILOGI(FEATURE_RUNNING_LOCK, "RUNNINGLOCK_SCREEN inactive");
105                 if (stateMachine->GetState() == PowerState::AWAKE) {
106                     stateMachine->ResetInactiveTimer();
107                 } else {
108                     POWER_HILOGD(FEATURE_RUNNING_LOCK, "Screen unlock in state: %{public}d",
109                         stateMachine->GetState());
110                 }
111             }
112         })
113     );
114 }
115 
InitLocksTypeBackground()116 void RunningLockMgr::InitLocksTypeBackground()
117 {
118     lockCounters_.emplace(RunningLockType::RUNNINGLOCK_BACKGROUND,
119         std::make_shared<LockCounter>(
120         RunningLockType::RUNNINGLOCK_BACKGROUND, [this](bool active) {
121             POWER_HILOGD(FEATURE_RUNNING_LOCK, "RUNNINGLOCK_BACKGROUND action start");
122             auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
123             if (pms == nullptr) {
124                 return;
125             }
126             auto stateMachine = pms->GetPowerStateMachine();
127             if (stateMachine == nullptr) {
128                 return;
129             }
130             if (active) {
131                 POWER_HILOGI(FEATURE_RUNNING_LOCK, "RUNNINGLOCK_BACKGROUND active");
132                 backgroundLock_->Lock();
133             } else {
134                 POWER_HILOGI(FEATURE_RUNNING_LOCK, "RUNNINGLOCK_BACKGROUND inactive");
135                 if (stateMachine->GetState() == PowerState::INACTIVE) {
136                     stateMachine->ResetSleepTimer();
137                 } else {
138                     POWER_HILOGD(FEATURE_RUNNING_LOCK, "Background unlock in state: %{public}d",
139                         stateMachine->GetState());
140                 }
141                 backgroundLock_->Unlock();
142             }
143         })
144     );
145 }
146 
InitLocksTypeProximity()147 void RunningLockMgr::InitLocksTypeProximity()
148 {
149     lockCounters_.emplace(RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL,
150         std::make_shared<LockCounter>(
151         RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL, [this](bool active) {
152             POWER_HILOGD(FEATURE_RUNNING_LOCK, "RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL action start");
153             auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
154             if (pms == nullptr) {
155                 return;
156             }
157             auto stateMachine = pms->GetPowerStateMachine();
158             if (stateMachine == nullptr) {
159                 return;
160             }
161             if (active) {
162                 POWER_HILOGI(FEATURE_RUNNING_LOCK, "RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL active");
163                 proximityController_.Enable();
164                 if (proximityController_.IsClose()) {
165                     POWER_HILOGI(FEATURE_RUNNING_LOCK, "INACTIVE when proximity is closed");
166                     stateMachine->SetState(PowerState::INACTIVE,
167                         StateChangeReason::STATE_CHANGE_REASON_RUNNING_LOCK, true);
168                 } else {
169                     POWER_HILOGI(FEATURE_RUNNING_LOCK, "AWAKE when proximity is away");
170                     stateMachine->SetState(PowerState::AWAKE,
171                         StateChangeReason::STATE_CHANGE_REASON_RUNNING_LOCK, true);
172                 }
173                 backgroundLock_->Lock();
174             } else {
175                 POWER_HILOGI(FEATURE_RUNNING_LOCK, "RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL inactive");
176                 stateMachine->SetState(PowerState::AWAKE,
177                     StateChangeReason::STATE_CHANGE_REASON_RUNNING_LOCK);
178                 stateMachine->ResetInactiveTimer();
179                 backgroundLock_->Unlock();
180                 proximityController_.Disable();
181             }
182         })
183     );
184 }
185 
GetRunningLockInner(const sptr<IRemoteObject> & remoteObj)186 std::shared_ptr<RunningLockInner> RunningLockMgr::GetRunningLockInner(
187     const sptr<IRemoteObject>& remoteObj)
188 {
189     std::lock_guard<std::mutex> lock(mutex_);
190     auto iterator = runningLocks_.find(remoteObj);
191     if (iterator != runningLocks_.end()) {
192         return iterator->second;
193     }
194     return nullptr;
195 }
196 
CreateRunningLock(const sptr<IRemoteObject> & remoteObj,const RunningLockParam & runningLockParam)197 std::shared_ptr<RunningLockInner> RunningLockMgr::CreateRunningLock(const sptr<IRemoteObject>& remoteObj,
198     const RunningLockParam& runningLockParam)
199 {
200     auto lockInner = RunningLockInner::CreateRunningLockInner(runningLockParam);
201     if (lockInner == nullptr) {
202         return nullptr;
203     }
204     POWER_HILOGD(FEATURE_RUNNING_LOCK, "Create lock success, name=%{public}s, type=%{public}d",
205         runningLockParam.name.c_str(), runningLockParam.type);
206 
207     mutex_.lock();
208     runningLocks_.emplace(remoteObj, lockInner);
209     runninglockProxy_->AddRunningLock(lockInner->GetPid(), lockInner->GetUid(), remoteObj);
210     mutex_.unlock();
211     remoteObj->AddDeathRecipient(runningLockDeathRecipient_);
212     return lockInner;
213 }
214 
ReleaseLock(const sptr<IRemoteObject> remoteObj)215 bool RunningLockMgr::ReleaseLock(const sptr<IRemoteObject> remoteObj)
216 {
217     bool result = false;
218     auto lockInner = GetRunningLockInner(remoteObj);
219     if (lockInner == nullptr) {
220         return result;
221     }
222 
223     UnLock(remoteObj);
224 
225     mutex_.lock();
226     runningLocks_.erase(remoteObj);
227     runninglockProxy_->RemoveRunningLock(lockInner->GetPid(), lockInner->GetUid(), remoteObj);
228     mutex_.unlock();
229     result = remoteObj->RemoveDeathRecipient(runningLockDeathRecipient_);
230     return result;
231 }
232 
RemoveAndPostUnlockTask(const sptr<IRemoteObject> & remoteObj,int32_t timeOutMS)233 void RunningLockMgr::RemoveAndPostUnlockTask(const sptr<IRemoteObject>& remoteObj, int32_t timeOutMS)
234 {
235     POWER_HILOGD(FEATURE_RUNNING_LOCK, "timeOutMS=%{public}d", timeOutMS);
236     FFRTUtils::CancelTask(g_runningLockTimeoutHandle, g_queue);
237     if (timeOutMS > 0) {
238         FFRTTask task = std::bind(&RunningLockMgr::UnLock, this, remoteObj);
239         g_runningLockTimeoutHandle = FFRTUtils::SubmitDelayTask(task, timeOutMS, g_queue);
240     }
241 }
242 
IsSceneRunningLockType(RunningLockType type)243 bool RunningLockMgr::IsSceneRunningLockType(RunningLockType type)
244 {
245     return type == RunningLockType::RUNNINGLOCK_BACKGROUND_PHONE ||
246         type == RunningLockType::RUNNINGLOCK_BACKGROUND_NOTIFICATION ||
247         type == RunningLockType::RUNNINGLOCK_BACKGROUND_AUDIO ||
248         type == RunningLockType::RUNNINGLOCK_BACKGROUND_SPORT ||
249         type == RunningLockType::RUNNINGLOCK_BACKGROUND_NAVIGATION ||
250         type == RunningLockType::RUNNINGLOCK_BACKGROUND_TASK;
251 }
252 
Lock(const sptr<IRemoteObject> & remoteObj,int32_t timeOutMS)253 void RunningLockMgr::Lock(const sptr<IRemoteObject>& remoteObj, int32_t timeOutMS)
254 {
255     StartTrace(HITRACE_TAG_POWER, "RunningLock_Lock");
256 
257     auto lockInner = GetRunningLockInner(remoteObj);
258     if (lockInner == nullptr) {
259         POWER_HILOGE(FEATURE_RUNNING_LOCK, "LockInner is nullptr");
260         return;
261     }
262     if (lockInner->IsProxied()) {
263         POWER_HILOGW(FEATURE_RUNNING_LOCK, "Runninglock is proxied");
264         return;
265     }
266     if (runninglockProxy_->IsProxied(lockInner->GetPid(), lockInner->GetUid())) {
267         POWER_HILOGW(FEATURE_RUNNING_LOCK, "Runninglock is proxied, do not allow lock");
268         return;
269     }
270     lockInner->SetTimeOutMs(timeOutMS);
271     RunningLockParam lockInnerParam = lockInner->GetParam();
272     POWER_HILOGD(FEATURE_RUNNING_LOCK, "name=%{public}s, type=%{public}d, timeoutMs=%{public}d",
273         lockInnerParam.name.c_str(), lockInnerParam.type, timeOutMS);
274     if (IsSceneRunningLockType(lockInnerParam.type)) {
275         runningLockAction_->Lock(lockInnerParam);
276         NotifyRunningLockChanged(remoteObj, lockInner, NOTIFY_RUNNINGLOCK_ADD);
277         return;
278     }
279 
280     if (lockInner->GetState() == RunningLockState::RUNNINGLOCK_STATE_ENABLE) {
281         POWER_HILOGD(FEATURE_RUNNING_LOCK, "Lock is already enabled");
282         return;
283     }
284     auto iterator = lockCounters_.find(lockInnerParam.type);
285     if (iterator == lockCounters_.end()) {
286         POWER_HILOGE(FEATURE_RUNNING_LOCK, "Lock failed unsupported type, type=%{public}d", lockInnerParam.type);
287         return;
288     }
289     lockInner->SetState(RunningLockState::RUNNINGLOCK_STATE_ENABLE);
290     std::shared_ptr<LockCounter> counter = iterator->second;
291     counter->Increase(remoteObj, lockInner);
292     POWER_HILOGD(FEATURE_RUNNING_LOCK, "LockCounter type=%{public}d, count=%{public}d", lockInnerParam.type,
293         counter->GetCount());
294     if (timeOutMS > 0) {
295         RemoveAndPostUnlockTask(remoteObj, timeOutMS);
296     }
297     FinishTrace(HITRACE_TAG_POWER);
298 }
299 
UnLock(const sptr<IRemoteObject> remoteObj)300 void RunningLockMgr::UnLock(const sptr<IRemoteObject> remoteObj)
301 {
302     StartTrace(HITRACE_TAG_POWER, "RunningLock_Unlock");
303 
304     auto lockInner = GetRunningLockInner(remoteObj);
305     if (lockInner == nullptr) {
306         return;
307     }
308     if (lockInner->IsProxied()) {
309         POWER_HILOGW(FEATURE_RUNNING_LOCK, "Runninglock is proxied");
310         return;
311     }
312     auto lockInnerParam = lockInner->GetParam();
313     POWER_HILOGD(
314         FEATURE_RUNNING_LOCK, "name=%{public}s, type=%{public}d", lockInnerParam.name.c_str(), lockInnerParam.type);
315     if (IsSceneRunningLockType(lockInnerParam.type)) {
316         runningLockAction_->Unlock(lockInnerParam);
317         NotifyRunningLockChanged(remoteObj, lockInner, NOTIFY_RUNNINGLOCK_REMOVE);
318         return;
319     }
320 
321     if (lockInner->GetState() == RunningLockState::RUNNINGLOCK_STATE_DISABLE) {
322         POWER_HILOGD(FEATURE_RUNNING_LOCK, "Lock is not enabled, name=%{public}s", lockInner->GetName().c_str());
323         return;
324     }
325 
326     auto iterator = lockCounters_.find(lockInnerParam.type);
327     if (iterator == lockCounters_.end()) {
328         POWER_HILOGE(FEATURE_RUNNING_LOCK, "Unlock failed unsupported type, type=%{public}d",
329             lockInnerParam.type);
330         return;
331     }
332     RemoveAndPostUnlockTask(remoteObj);
333     lockInner->SetState(RunningLockState::RUNNINGLOCK_STATE_DISABLE);
334     std::shared_ptr<LockCounter> counter = iterator->second;
335     counter->Decrease(remoteObj, lockInner);
336     POWER_HILOGD(FEATURE_RUNNING_LOCK, "LockCounter type=%{public}d, count=%{public}d", lockInnerParam.type,
337         counter->GetCount());
338     FinishTrace(HITRACE_TAG_POWER);
339 }
340 
IsUsed(const sptr<IRemoteObject> & remoteObj)341 bool RunningLockMgr::IsUsed(const sptr<IRemoteObject>& remoteObj)
342 {
343     auto lockInner = GetRunningLockInner(remoteObj);
344     if (lockInner == nullptr || lockInner->GetState() != RunningLockState::RUNNINGLOCK_STATE_ENABLE) {
345         return false;
346     }
347     return true;
348 }
349 
GetRunningLockNum(RunningLockType type)350 uint32_t RunningLockMgr::GetRunningLockNum(RunningLockType type)
351 {
352     std::lock_guard<std::mutex> lock(mutex_);
353     if (type == RunningLockType::RUNNINGLOCK_BUTT) {
354         return runningLocks_.size();
355     }
356     return std::count_if(runningLocks_.begin(), runningLocks_.end(),
357         [&type](const auto& pair) {
358             return pair.second->GetType() == type;
359         });
360 }
361 
GetValidRunningLockNum(RunningLockType type)362 uint32_t RunningLockMgr::GetValidRunningLockNum(RunningLockType type)
363 {
364     auto iterator = lockCounters_.find(type);
365     if (iterator == lockCounters_.end()) {
366         POWER_HILOGD(FEATURE_RUNNING_LOCK, "No specific lock, type=%{public}d", type);
367         return 0;
368     }
369     std::shared_ptr<LockCounter> counter = iterator->second;
370     return counter->GetCount();
371 }
372 
ExistValidRunningLock()373 bool RunningLockMgr::ExistValidRunningLock()
374 {
375     std::lock_guard<std::mutex> lock(mutex_);
376     for (auto it = runningLocks_.begin(); it != runningLocks_.end(); it++) {
377         auto& lockinner = it->second;
378         if (lockinner->GetState() == RunningLockState::RUNNINGLOCK_STATE_ENABLE) {
379             return true;
380         }
381     }
382     return false;
383 }
384 
NotifyHiViewRunningLockInfo(const RunningLockInner & lockInner,RunningLockChangedType changeType) const385 void RunningLockMgr::NotifyHiViewRunningLockInfo(const RunningLockInner& lockInner,
386     RunningLockChangedType changeType) const
387 {
388     NotifyHiView(changeType, lockInner);
389 }
390 
CheckOverTime()391 void RunningLockMgr::CheckOverTime()
392 {
393     FFRTUtils::CancelTask(g_runningLockTimeoutHandle, g_queue);
394     if (runningLocks_.empty()) {
395         return;
396     }
397     int64_t curTime = GetTickCount();
398     int64_t detectTime = curTime - CHECK_TIMEOUT_INTERVAL_MS;
399     POWER_HILOGI(FEATURE_RUNNING_LOCK, "curTime=%{public}" PRId64 " detectTime=%{public}" PRId64 "", curTime,
400         detectTime);
401     if (detectTime < 0) {
402         return;
403     }
404     int64_t nextDetectTime = INT_MAX;
405     for (auto& it : runningLocks_) {
406         auto lockInner = it.second;
407         if (lockInner->GetState() == RunningLockState::RUNNINGLOCK_STATE_ENABLE &&
408             (!lockInner->GetOverTimeFlag())) {
409             if (lockInner->GetLockTimeMs() < detectTime) {
410                 lockInner->SetOverTimeFlag(true);
411                 NotifyRunningLockChanged(it.first, lockInner, NOTIFY_RUNNINGLOCK_OVERTIME);
412             } else {
413                 if (lockInner->GetLockTimeMs() < nextDetectTime) {
414                     nextDetectTime = lockInner->GetLockTimeMs();
415                 }
416             }
417         }
418     }
419     if (nextDetectTime != INT_MAX) {
420         detectTime = nextDetectTime - curTime + CHECK_TIMEOUT_INTERVAL_MS;
421         SendCheckOverTimeMsg(detectTime);
422     }
423 }
424 
SendCheckOverTimeMsg(int64_t delayTime)425 void RunningLockMgr::SendCheckOverTimeMsg(int64_t delayTime)
426 {
427     POWER_HILOGD(FEATURE_RUNNING_LOCK, "delayTime=%{public}" PRId64 "", delayTime);
428     FFRTTask task = [this] {
429         CheckOverTime();
430     };
431     FFRTUtils::SubmitDelayTask(task, delayTime, g_queue);
432 }
433 
NotifyRunningLockChanged(const sptr<IRemoteObject> & remoteObj,std::shared_ptr<RunningLockInner> & lockInner,RunningLockChangedType changeType)434 void RunningLockMgr::NotifyRunningLockChanged(const sptr<IRemoteObject>& remoteObj,
435     std::shared_ptr<RunningLockInner>& lockInner, RunningLockChangedType changeType)
436 {
437     if (changeType >= RUNNINGLOCK_CHANGED_BUTT) {
438         return;
439     }
440     const string& remoteObjStr = to_string(reinterpret_cast<uintptr_t>(remoteObj.GetRefPtr()));
441     switch (changeType) {
442         case NOTIFY_RUNNINGLOCK_ADD: {
443             NotifyHiViewRunningLockInfo(*lockInner, changeType);
444             SendCheckOverTimeMsg(CHECK_TIMEOUT_INTERVAL_MS);
445             break;
446         }
447         case NOTIFY_RUNNINGLOCK_REMOVE: {
448             NotifyHiView(changeType, *lockInner);
449             break;
450         }
451         case NOTIFY_RUNNINGLOCK_OVERTIME: {
452             break;
453         }
454         default: {
455             break;
456         }
457     }
458 }
459 
ProxyRunningLock(bool isProxied,pid_t pid,pid_t uid)460 bool RunningLockMgr::ProxyRunningLock(bool isProxied, pid_t pid, pid_t uid)
461 {
462     bool isSuccess = false;
463     if (pid < VALID_PID_LIMIT) {
464         POWER_HILOGW(FEATURE_RUNNING_LOCK, "Proxy runninglock failed, pid=%{public}d is invalid", pid);
465         return isSuccess;
466     }
467 
468     if (isProxied) {
469         runninglockProxy_->IncreaseProxyCnt(pid, uid, [this, pid, uid] () {
470             this->ProxyRunningLockInner(true, pid, uid);
471         });
472     } else {
473         runninglockProxy_->DecreaseProxyCnt(pid, uid, [this, pid, uid] () {
474             this->ProxyRunningLockInner(false, pid, uid);
475         });
476     }
477     return true;
478 }
479 
ProxyRunningLockInner(bool isProxied,pid_t pid,pid_t uid)480 void RunningLockMgr::ProxyRunningLockInner(bool isProxied, pid_t pid, pid_t uid)
481 {
482     auto remoteObjList = runninglockProxy_->GetRemoteObjectList(pid, uid);
483     if (remoteObjList.empty()) {
484         POWER_HILOGW(FEATURE_RUNNING_LOCK, "Proxy runninglock failed, no matching runninglock exist");
485         return;
486     }
487     for (auto it : remoteObjList) {
488         auto lockInner = GetRunningLockInner(it);
489         if (lockInner == nullptr) {
490             continue;
491         }
492         if (isProxied) {
493             UnlockInnerByProxy(it, lockInner);
494         } else {
495             LockInnerByProxy(it, lockInner);
496         }
497     }
498 }
499 
ProxyRunningLocks(bool isProxied,const std::vector<std::pair<pid_t,pid_t>> & processInfos)500 void RunningLockMgr::ProxyRunningLocks(bool isProxied, const std::vector<std::pair<pid_t, pid_t>>& processInfos)
501 {
502     for (const auto& [pid, uid] : processInfos) {
503         ProxyRunningLock(isProxied, pid, uid);
504     }
505 }
506 
ResetRunningLocks()507 void RunningLockMgr::ResetRunningLocks()
508 {
509     POWER_HILOGI(FEATURE_RUNNING_LOCK, "Reset runninglock proxy");
510     for (auto& it : runningLocks_) {
511         LockInnerByProxy(it.first, it.second);
512     }
513     runninglockProxy_->ResetRunningLocks();
514 }
515 
LockInnerByProxy(const sptr<IRemoteObject> & remoteObj,std::shared_ptr<RunningLockInner> & lockInner)516 void RunningLockMgr::LockInnerByProxy(const sptr<IRemoteObject>& remoteObj,
517     std::shared_ptr<RunningLockInner>& lockInner)
518 {
519     if (!lockInner->IsProxied()) {
520         return;
521     }
522     RunningLockState lastState = lockInner->GetState();
523     lockInner->SetState(RunningLockState::RUNNINGLOCK_STATE_DISABLE);
524     if (lastState == RunningLockState::RUNNINGLOCK_STATE_UNPROXIED_RESTORE) {
525         Lock(remoteObj, lockInner->GetTimeOutMs());
526     }
527 }
528 
UnlockInnerByProxy(const sptr<IRemoteObject> & remoteObj,std::shared_ptr<RunningLockInner> & lockInner)529 void RunningLockMgr::UnlockInnerByProxy(const sptr<IRemoteObject>& remoteObj,
530     std::shared_ptr<RunningLockInner>& lockInner)
531 {
532     RunningLockState lastState = lockInner->GetState();
533     lockInner->SetState(RunningLockState::RUNNINGLOCK_STATE_PROXIED);
534     auto lockParam = lockInner->GetParam();
535     if (IsSceneRunningLockType(lockInner->GetType()) &&
536         runningLockAction_->Unlock(lockParam) == RUNNINGLOCK_SUCCESS) {
537         lockInner->SetState(RunningLockState::RUNNINGLOCK_STATE_UNPROXIED_RESTORE);
538         NotifyRunningLockChanged(remoteObj, lockInner, NOTIFY_RUNNINGLOCK_REMOVE);
539         return;
540     }
541     if (lastState == RunningLockState::RUNNINGLOCK_STATE_DISABLE) {
542         return;
543     }
544     auto counterIter = lockCounters_.find(lockParam.type);
545     if (counterIter == lockCounters_.end()) {
546         return;
547     }
548     lockInner->SetState(RunningLockState::RUNNINGLOCK_STATE_UNPROXIED_RESTORE);
549     RemoveAndPostUnlockTask(remoteObj);
550     counterIter->second->Decrease(remoteObj, lockInner);
551 }
552 
NotifyHiView(RunningLockChangedType changeType,const RunningLockInner & lockInner) const553 void RunningLockMgr::NotifyHiView(RunningLockChangedType changeType, const RunningLockInner& lockInner) const
554 {
555     int32_t pid = lockInner.GetPid();
556     int32_t uid = lockInner.GetUid();
557     int32_t state = static_cast<int32_t>(lockInner.GetState());
558     int32_t type = static_cast <int32_t>(lockInner.GetType());
559     string name = lockInner.GetName();
560     const int logLevel = 2;
561     const string &tag = runninglockNotifyStr_.at(changeType);
562     HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::POWER, "RUNNINGLOCK",
563         HiviewDFX::HiSysEvent::EventType::STATISTIC,
564         "PID", pid, "UID", uid, "STATE", state, "TYPE", type, "NAME", name,
565         "LOG_LEVEL", logLevel, "TAG", tag);
566     POWER_HILOGD(FEATURE_RUNNING_LOCK, "pid = %{public}d, uid= %{public}d, tag=%{public}s",
567         pid, uid, tag.c_str());
568 }
569 
EnableMock(IRunningLockAction * mockAction)570 void RunningLockMgr::EnableMock(IRunningLockAction* mockAction)
571 {
572     // reset lock list
573     runningLocks_.clear();
574     for (auto it = lockCounters_.begin(); it != lockCounters_.end(); it++) {
575         it->second->Clear();
576     }
577     runninglockProxy_->Clear();
578     proximityController_.Clear();
579     std::shared_ptr<IRunningLockAction> mock(mockAction);
580     backgroundLock_->EnableMock(mock);
581     runningLockAction_ = mock;
582 }
583 
GetRunningLockTypeString(RunningLockType type)584 static const std::string GetRunningLockTypeString(RunningLockType type)
585 {
586     switch (type) {
587         case RunningLockType::RUNNINGLOCK_SCREEN:
588             return "SCREEN";
589         case RunningLockType::RUNNINGLOCK_BACKGROUND:
590             return "BACKGROUND";
591         case RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL:
592             return "PROXIMITY_SCREEN_CONTROL";
593         case RunningLockType::RUNNINGLOCK_BACKGROUND_PHONE:
594             return "BACKGROUND_PHONE";
595         case RunningLockType::RUNNINGLOCK_BACKGROUND_NOTIFICATION:
596             return "BACKGROUND_NOTIFICATION";
597         case RunningLockType::RUNNINGLOCK_BACKGROUND_AUDIO:
598             return "BACKGROUND_AUDIO";
599         case RunningLockType::RUNNINGLOCK_BACKGROUND_SPORT:
600             return "BACKGROUND_SPORT";
601         case RunningLockType::RUNNINGLOCK_BACKGROUND_NAVIGATION:
602             return "BACKGROUND_NAVIGATION";
603         case RunningLockType::RUNNINGLOCK_BACKGROUND_TASK:
604             return "BACKGROUND_TASK";
605         case RunningLockType::RUNNINGLOCK_BUTT:
606             return "BUTT";
607         default:
608             break;
609     }
610 
611     return "UNKNOWN";
612 }
613 
DumpInfo(std::string & result)614 void RunningLockMgr::DumpInfo(std::string& result)
615 {
616     auto validSize = GetValidRunningLockNum();
617     std::lock_guard<std::mutex> lock(mutex_);
618 
619     result.append("RUNNING LOCK DUMP:\n");
620     result.append("  totalSize=").append(ToString(runningLocks_.size()))
621             .append(" validSize=").append(ToString(validSize)).append("\n");
622     result.append("Summary By Type: \n");
623     for (auto it = lockCounters_.begin(); it != lockCounters_.end(); it++) {
624         result.append("  ")
625             .append(GetRunningLockTypeString(it->first))
626             .append(": ")
627             .append(ToString(it->second->GetCount()))
628             .append("\n");
629     }
630 
631     if (runningLocks_.empty()) {
632         result.append("Lock List is Empty. \n");
633         return;
634     }
635 
636     result.append("Dump Lock List: \n");
637     auto curTick = GetTickCount();
638     int index = 0;
639     for (const auto& it : runningLocks_) {
640         index++;
641         auto lockInner = it.second;
642         if (lockInner == nullptr) {
643             return;
644         }
645         auto& lockParam = lockInner->GetParam();
646         result.append("  index=").append(ToString(index))
647             .append(" time=").append(ToString(curTick - lockInner->GetLockTimeMs()))
648             .append(" type=").append(GetRunningLockTypeString(lockParam.type))
649             .append(" name=").append(lockParam.name)
650             .append(" uid=").append(ToString(lockInner->GetUid()))
651             .append(" pid=").append(ToString(lockInner->GetPid()))
652             .append(" state=").append(ToString(static_cast<uint32_t>(lockInner->GetState())))
653             .append("\n");
654     }
655 
656     result.append("Dump Proxy List: \n");
657     result.append(runninglockProxy_->DumpProxyInfo());
658 
659     result.append("Peripherals Info: \n")
660             .append("  Proximity: ")
661             .append("Enabled=")
662             .append(ToString(proximityController_.IsEnabled()))
663             .append(" Status=")
664             .append(ToString(proximityController_.GetStatus()))
665             .append("\n");
666 }
667 
OnRemoteDied(const wptr<IRemoteObject> & remote)668 void RunningLockMgr::RunningLockDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& remote)
669 {
670     if (remote == nullptr || remote.promote() == nullptr) {
671         POWER_HILOGW(FEATURE_RUNNING_LOCK, "Remote is nullptr");
672         return;
673     }
674     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
675     if (pms == nullptr) {
676         POWER_HILOGW(FEATURE_RUNNING_LOCK, "Power service is nullptr");
677         return;
678     }
679     pms->ForceUnLock(remote.promote());
680 }
681 
SystemLock(std::shared_ptr<IRunningLockAction> action,RunningLockType type,const std::string & name)682 RunningLockMgr::SystemLock::SystemLock(std::shared_ptr<IRunningLockAction> action, RunningLockType type,
683     const std::string& name) : action_(action), locking_(false)
684 {
685     param_.type = type;
686     param_.name = name;
687 }
688 
Lock()689 void RunningLockMgr::SystemLock::Lock()
690 {
691     if (!locking_) {
692         action_->Lock(param_);
693         locking_ = true;
694     }
695 }
696 
Unlock()697 void RunningLockMgr::SystemLock::Unlock()
698 {
699     if (locking_) {
700         action_->Unlock(param_);
701         locking_ = false;
702     }
703 }
704 
Increase(const sptr<IRemoteObject> & remoteObj,std::shared_ptr<RunningLockInner> & lockInner)705 uint32_t RunningLockMgr::LockCounter::Increase(const sptr<IRemoteObject>& remoteObj,
706     std::shared_ptr<RunningLockInner>& lockInner)
707 {
708     ++counter_;
709     if (counter_ == 1) {
710         activate_(true);
711     }
712     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
713     if (pms == nullptr) {
714         POWER_HILOGW(FEATURE_RUNNING_LOCK, "No power service instance");
715         return counter_;
716     }
717     pms->GetRunningLockMgr()->NotifyRunningLockChanged(remoteObj, lockInner, NOTIFY_RUNNINGLOCK_ADD);
718     return counter_;
719 }
720 
Decrease(const sptr<IRemoteObject> remoteObj,std::shared_ptr<RunningLockInner> & lockInner)721 uint32_t RunningLockMgr::LockCounter::Decrease(const sptr<IRemoteObject> remoteObj,
722     std::shared_ptr<RunningLockInner>& lockInner)
723 {
724     --counter_;
725     if (counter_ == 0) {
726         activate_(false);
727     }
728     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
729     if (pms == nullptr) {
730         POWER_HILOGW(FEATURE_RUNNING_LOCK, "No power service instance");
731         return counter_;
732     }
733     pms->GetRunningLockMgr()->NotifyRunningLockChanged(remoteObj, lockInner, NOTIFY_RUNNINGLOCK_REMOVE);
734     return counter_;
735 }
736 
Clear()737 void RunningLockMgr::LockCounter::Clear()
738 {
739     counter_ = 0;
740 }
741 
RecordSensorCallback(SensorEvent * event)742 void RunningLockMgr::ProximityController::RecordSensorCallback(SensorEvent *event)
743 {
744     POWER_HILOGD(FEATURE_RUNNING_LOCK, "Sensor Callback come in");
745     if (event == nullptr) {
746         POWER_HILOGW(FEATURE_RUNNING_LOCK, "Sensor event is nullptr");
747         return;
748     }
749     if (event->sensorTypeId != SENSOR_TYPE_ID_PROXIMITY) {
750         POWER_HILOGW(FEATURE_RUNNING_LOCK, "Sensor type is not PROXIMITY");
751         return;
752     }
753     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
754     if (pms == nullptr) {
755         POWER_HILOGE(FEATURE_RUNNING_LOCK, "Power service is nullptr");
756         return;
757     }
758     auto runningLock = pms->GetRunningLockMgr();
759     ProximityData* data = reinterpret_cast<ProximityData*>(event->data);
760     int32_t distance = static_cast<int32_t>(data->distance);
761 
762     POWER_HILOGD(FEATURE_RUNNING_LOCK, "Sensor Callback data->distance=%{public}d", distance);
763     if (distance == PROXIMITY_CLOSE_SCALAR) {
764         runningLock->SetProximity(PROXIMITY_CLOSE);
765     } else if (distance == PROXIMITY_AWAY_SCALAR) {
766         runningLock->SetProximity(PROXIMITY_AWAY);
767     }
768 }
769 
ProximityController()770 RunningLockMgr::ProximityController::ProximityController()
771 {
772     POWER_HILOGD(FEATURE_RUNNING_LOCK, "Instance enter");
773     SensorInfo* sensorInfo = nullptr;
774     int32_t count;
775     int ret = GetAllSensors(&sensorInfo, &count);
776     if (ret != 0 || sensorInfo == nullptr) {
777         POWER_HILOGE(FEATURE_RUNNING_LOCK, "Get sensors fail, ret=%{public}d", ret);
778         return;
779     }
780     for (int32_t i = 0; i < count; i++) {
781         if (sensorInfo[i].sensorTypeId == SENSOR_TYPE_ID_PROXIMITY) {
782             POWER_HILOGD(FEATURE_RUNNING_LOCK, "Support PROXIMITY sensor");
783             support_ = true;
784             break;
785         }
786     }
787     if (!support_) {
788         POWER_HILOGE(FEATURE_RUNNING_LOCK, "PROXIMITY sensor not support");
789         return;
790     }
791     if (strcpy_s(user_.name, sizeof(user_.name), "RunningLock") != EOK) {
792         POWER_HILOGE(FEATURE_RUNNING_LOCK, "strcpy_s error");
793         return;
794     }
795     user_.userData = nullptr;
796     user_.callback = &RecordSensorCallback;
797 }
798 
~ProximityController()799 RunningLockMgr::ProximityController::~ProximityController()
800 {
801     if (support_) {
802         UnsubscribeSensor(SENSOR_TYPE_ID_PROXIMITY, &user_);
803     }
804 }
805 
Enable()806 void RunningLockMgr::ProximityController::Enable()
807 {
808     POWER_HILOGD(FEATURE_RUNNING_LOCK, "Enter");
809     enabled_ = true;
810     if (!support_) {
811         POWER_HILOGE(FEATURE_RUNNING_LOCK, "PROXIMITY sensor not support");
812         return;
813     }
814 
815     int32_t errorCode = SubscribeSensor(SENSOR_TYPE_ID_PROXIMITY, &user_);
816     if (errorCode != ERR_OK) {
817         POWER_HILOGW(FEATURE_RUNNING_LOCK, "SubscribeSensor PROXIMITY failed, errorCode=%{public}d", errorCode);
818         return;
819     }
820     SetBatch(SENSOR_TYPE_ID_PROXIMITY, &user_, SAMPLING_RATE, SAMPLING_RATE);
821     errorCode = ActivateSensor(SENSOR_TYPE_ID_PROXIMITY, &user_);
822     if (errorCode != ERR_OK) {
823         POWER_HILOGW(FEATURE_RUNNING_LOCK, "ActivateSensor PROXIMITY failed, errorCode=%{public}d", errorCode);
824         return;
825     }
826     SetMode(SENSOR_TYPE_ID_PROXIMITY, &user_, SENSOR_ON_CHANGE);
827 }
828 
Disable()829 void RunningLockMgr::ProximityController::Disable()
830 {
831     POWER_HILOGD(FEATURE_RUNNING_LOCK, "Enter");
832     enabled_ = false;
833     if (!support_) {
834         POWER_HILOGE(FEATURE_RUNNING_LOCK, "PROXIMITY sensor not support");
835         return;
836     }
837 
838     DeactivateSensor(SENSOR_TYPE_ID_PROXIMITY, &user_);
839     int32_t errorCode = UnsubscribeSensor(SENSOR_TYPE_ID_PROXIMITY, &user_);
840     if (errorCode != ERR_OK) {
841         POWER_HILOGW(FEATURE_RUNNING_LOCK, "UnsubscribeSensor PROXIMITY failed, errorCode=%{public}d", errorCode);
842     }
843 }
844 
IsClose()845 bool RunningLockMgr::ProximityController::IsClose()
846 {
847     POWER_HILOGD(FEATURE_RUNNING_LOCK, "PROXIMITY IsClose: %{public}d", isClose);
848     return isClose;
849 }
850 
OnClose()851 void RunningLockMgr::ProximityController::OnClose()
852 {
853     if (!enabled_ || IsClose()) {
854         POWER_HILOGD(FEATURE_RUNNING_LOCK, "PROXIMITY is disabled or closed already");
855         return;
856     }
857     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
858     if (pms == nullptr) {
859         POWER_HILOGE(FEATURE_RUNNING_LOCK, "Power service is nullptr");
860         return;
861     }
862     auto stateMachine = pms->GetPowerStateMachine();
863     if (stateMachine == nullptr) {
864         POWER_HILOGE(FEATURE_RUNNING_LOCK, "state machine is nullptr");
865         return;
866     }
867     isClose = true;
868     POWER_HILOGD(FEATURE_RUNNING_LOCK, "PROXIMITY is closed");
869     auto runningLock = pms->GetRunningLockMgr();
870     if (runningLock->GetValidRunningLockNum(
871         RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL) > 0) {
872         POWER_HILOGD(FEATURE_RUNNING_LOCK, "Change state to INACITVE when holding PROXIMITY LOCK");
873         stateMachine->SetState(PowerState::INACTIVE, StateChangeReason::STATE_CHANGE_REASON_SENSOR, true);
874     }
875 }
876 
OnAway()877 void RunningLockMgr::ProximityController::OnAway()
878 {
879     if (!enabled_ || !IsClose()) {
880         POWER_HILOGD(FEATURE_RUNNING_LOCK, "PROXIMITY is disabled or away already");
881         return;
882     }
883     auto pms = DelayedSpSingleton<PowerMgrService>::GetInstance();
884     if (pms == nullptr) {
885         POWER_HILOGE(FEATURE_RUNNING_LOCK, "Power service is nullptr");
886         return;
887     }
888     auto stateMachine = pms->GetPowerStateMachine();
889     if (stateMachine == nullptr) {
890         POWER_HILOGE(FEATURE_RUNNING_LOCK, "state machine is nullptr");
891         return;
892     }
893     isClose = false;
894     POWER_HILOGD(FEATURE_RUNNING_LOCK, "PROXIMITY is away");
895     auto runningLock = pms->GetRunningLockMgr();
896     if (runningLock->GetValidRunningLockNum(
897         RunningLockType::RUNNINGLOCK_PROXIMITY_SCREEN_CONTROL) > 0) {
898         POWER_HILOGD(FEATURE_RUNNING_LOCK, "Change state to AWAKE when holding PROXIMITY LOCK");
899         stateMachine->SetState(PowerState::AWAKE, StateChangeReason::STATE_CHANGE_REASON_SENSOR, true);
900     }
901 }
902 
Clear()903 void RunningLockMgr::ProximityController::Clear()
904 {
905     isClose = false;
906 }
907 
SetProximity(uint32_t status)908 void RunningLockMgr::SetProximity(uint32_t status)
909 {
910     switch (status) {
911         case PROXIMITY_CLOSE:
912             proximityController_.OnClose();
913             break;
914         case PROXIMITY_AWAY:
915             proximityController_.OnAway();
916             break;
917         default:
918             break;
919     }
920 }
921 } // namespace PowerMgr
922 } // namespace OHOS
923