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 <pthread.h>
17
18#include "hilog_wrapper.h"
19#include "power/running_lock_hub.h"
20#include "power/suspend_ops.h"
21
22static const char* WAKEUP_HOLDER = "OHOSPowerMgr.WakeupHolder";
23
24static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
25static struct AutoSuspendOps* g_suspendOps = NULL;
26static BOOL g_suspendEnabled = FALSE;
27
28void ScAcquireRunningLock(const char *name)
29{
30    RunningLockHubLock(name);
31}
32
33void ScReleaseRunningLock(const char *name)
34{
35    RunningLockHubUnlock(name);
36}
37
38void EnableSuspend()
39{
40    if (!g_suspendOps) {
41        return;
42    }
43
44    pthread_mutex_lock(&g_mutex);
45    if (g_suspendEnabled == FALSE) {
46        ScReleaseRunningLock(WAKEUP_HOLDER);
47        g_suspendEnabled = TRUE;
48    }
49    pthread_mutex_unlock(&g_mutex);
50    g_suspendOps->Enable();
51}
52
53void DisableSuspend()
54{
55    pthread_mutex_lock(&g_mutex);
56    if (g_suspendEnabled == TRUE) {
57        ScAcquireRunningLock(WAKEUP_HOLDER);
58        g_suspendEnabled = FALSE;
59    }
60    pthread_mutex_unlock(&g_mutex);
61}
62
63void SuspendControllerInit()
64{
65    g_suspendOps = AutoSuspendOpsInit();
66    if (!g_suspendOps) {
67        POWER_HILOGE("Failed to init auto suspend ops");
68        return;
69    }
70    if (RunningLockHubInit(g_suspendOps) == FALSE) {
71        POWER_HILOGE("Failed to init running lock hub");
72        return;
73    }
74    ScAcquireRunningLock(WAKEUP_HOLDER);
75}
76