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