1 /*
2 * Copyright (c) 2021 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 <stdint.h>
17 #include <stdio.h>
18 #include <string.h>
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <sys/stat.h>
22 #include <unistd.h>
23
24 #include "hilog_wrapper.h"
25 #include "power/suspend_ops.h"
26
27 static int32_t g_lockFd = -1;
28 static int32_t g_unlockFd = -1;
29
OpenLockFile(const char * path)30 static int32_t OpenLockFile(const char* path)
31 {
32 int32_t fd = open(path, O_RDWR);
33 if (fd < 0) {
34 POWER_HILOGE("Failed to open %{public}s, err: %{public}s", path, strerror(errno));
35 }
36 return fd;
37 }
38
WriteLock(int32_t fd,const char * name)39 static int32_t WriteLock(int32_t fd, const char *name)
40 {
41 if ((fd < 0) || (name == NULL)) {
42 POWER_HILOGE("Invalid parameter");
43 return -1;
44 }
45
46 int32_t ret = write(fd, name, strlen(name));
47 if (ret < 0) {
48 POWER_HILOGE("Failed to write lock: %{public}s, error: %{public}s", name, strerror(errno));
49 return -1;
50 }
51 return 0;
52 }
53
RunningLockAcquire(const char * name)54 static void RunningLockAcquire(const char *name)
55 {
56 int32_t ret = WriteLock(g_lockFd, name);
57 POWER_HILOGD("Acquire runninglock: %{public}s, ret: %{public}d", name, ret);
58 }
59
RunningLockRelease(const char * name)60 static void RunningLockRelease(const char *name)
61 {
62 int32_t ret = WriteLock(g_unlockFd, name);
63 POWER_HILOGD("Release runninglock: %{public}s, ret: %{public}d", name, ret);
64 }
65
66 static struct RunningLockOps g_ops = {
67 .Acquire = RunningLockAcquire,
68 .Release = RunningLockRelease,
69 };
70
RunningLockOpsInit()71 struct RunningLockOps* RunningLockOpsInit()
72 {
73 g_lockFd = OpenLockFile("/proc/power/power_lock");
74 if (g_lockFd < 0) {
75 return NULL;
76 }
77
78 g_unlockFd = OpenLockFile("/proc/power/power_unlock");
79 if (g_unlockFd < 0) {
80 close(g_lockFd);
81 g_lockFd = -1;
82 return NULL;
83 }
84
85 return &g_ops;
86 }
87