1 /*
2 * Copyright (c) 2021-2022 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 "suspend/running_lock_hub.h"
17
18 #include <file_ex.h>
19 #include <sys/eventfd.h>
20
21 #include "power_log.h"
22
23 namespace OHOS {
24 namespace PowerMgr {
25 namespace Suspend {
Acquire(const std::string & name)26 void RunningLockHub::Acquire(const std::string& name)
27 {
28 {
29 std::lock_guard lock(mutex_);
30 if (!SaveLockFile(name, true)) {
31 POWER_HILOGE(FEATURE_RUNNING_LOCK, "Failed to write the lock state");
32 }
33 runningLockMap_[name]++;
34 }
35 NotifySuspendCounter(true);
36 POWER_HILOGI(FEATURE_RUNNING_LOCK, "Acquire runningLock, name: %{public}s", name.c_str());
37 }
38
Release(const std::string & name)39 void RunningLockHub::Release(const std::string& name)
40 {
41 {
42 std::lock_guard lock(mutex_);
43 if (InitFd()) {
44 if (!SaveStringToFd(unlockFd_, name.c_str())) {
45 POWER_HILOGE(FEATURE_RUNNING_LOCK, "Failed to write the unlock state");
46 }
47 }
48 if (runningLockMap_.find(name) == runningLockMap_.end()) {
49 return;
50 }
51 runningLockMap_[name]--;
52 if (runningLockMap_[name] == 0) {
53 runningLockMap_.erase(name);
54 }
55 }
56 NotifySuspendCounter(false);
57 POWER_HILOGI(FEATURE_RUNNING_LOCK, "Release runningLock, name: %{public}s", name.c_str());
58 }
59
InitFd()60 bool RunningLockHub::InitFd()
61 {
62 static bool inited = false;
63 if (inited) {
64 return (lockFd_ >= 0 && unlockFd_ >= 0);
65 }
66 lockFd_ = UniqueFd(TEMP_FAILURE_RETRY(open(LOCK_PATH, O_RDWR | O_CLOEXEC)));
67 unlockFd_ = UniqueFd(TEMP_FAILURE_RETRY(open(UNLOCK_PATH, O_RDWR | O_CLOEXEC)));
68 inited = true;
69 if (lockFd_ < 0 || unlockFd_ < 0) {
70 POWER_HILOGE(FEATURE_RUNNING_LOCK, "Running lock fd initialization failed");
71 return false;
72 }
73 return inited;
74 }
75
SaveLockFile(const std::string & name,bool isAcquire)76 bool RunningLockHub::SaveLockFile(const std::string& name, bool isAcquire)
77 {
78 if (InitFd()) {
79 int32_t fd = isAcquire ? lockFd_ : unlockFd_;
80 return SaveStringToFd(fd, name.c_str());
81 }
82 return false;
83 }
84
NotifySuspendCounter(bool isAcquire)85 void RunningLockHub::NotifySuspendCounter(bool isAcquire)
86 {
87 isAcquire ? sc_->IncSuspendBlockCounter() : sc_->DecSuspendBlockCounter();
88 }
89 } // namespace Suspend
90 } // namespace PowerMgr
91 } // namespace OHOS
92