1 /*
2 * osal_sem.c
3 *
4 * osal driver
5 *
6 * Copyright (c) 2020-2021 Huawei Device Co., Ltd.
7 *
8 * This software is licensed under the terms of the GNU General Public
9 * License version 2, as published by the Free Software Foundation, and
10 * may be copied, distributed, and modified under those terms.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 */
18
19 #include "osal_sem.h"
20 #include <linux/errno.h>
21 #include <linux/export.h>
22 #include <linux/semaphore.h>
23 #include <linux/timer.h>
24 #include "hdf_log.h"
25 #include "osal_mem.h"
26
27 #define HDF_LOG_TAG osal_sem
28
OsalSemInit(struct OsalSem * sem,uint32_t value)29 int32_t OsalSemInit(struct OsalSem *sem, uint32_t value)
30 {
31 struct semaphore *sem_tmp = NULL;
32
33 if (sem == NULL) {
34 HDF_LOGE("%s invalid param", __func__);
35 return HDF_ERR_INVALID_PARAM;
36 }
37
38 sem_tmp = (struct semaphore *)OsalMemCalloc(sizeof(*sem_tmp));
39 if (sem_tmp == NULL) {
40 HDF_LOGE("%s malloc fail", __func__);
41 return HDF_ERR_MALLOC_FAIL;
42 }
43 sema_init(sem_tmp, value);
44 sem->realSemaphore = (void *)sem_tmp;
45
46 return HDF_SUCCESS;
47 }
48 EXPORT_SYMBOL(OsalSemInit);
49
OsalSemWait(struct OsalSem * sem,uint32_t millisec)50 int32_t OsalSemWait(struct OsalSem *sem, uint32_t millisec)
51 {
52 int32_t ret;
53
54 if (sem == NULL || sem->realSemaphore == NULL) {
55 HDF_LOGE("%s invalid param", __func__);
56 return HDF_ERR_INVALID_PARAM;
57 }
58
59 if (millisec == HDF_WAIT_FOREVER) {
60 do {
61 ret = down_interruptible((struct semaphore *)sem->realSemaphore);
62 } while (ret == -EINTR);
63 } else {
64 ret = down_timeout((struct semaphore *)sem->realSemaphore, msecs_to_jiffies(millisec));
65 if (ret != 0) {
66 if (ret == -ETIME) {
67 return HDF_ERR_TIMEOUT;
68 } else {
69 HDF_LOGE("%s time_out %d %d", __func__, millisec, ret);
70 return HDF_FAILURE;
71 }
72 }
73 }
74
75 return HDF_SUCCESS;
76 }
77 EXPORT_SYMBOL(OsalSemWait);
78
OsalSemPost(struct OsalSem * sem)79 int32_t OsalSemPost(struct OsalSem *sem)
80 {
81 if (sem == NULL || sem->realSemaphore == NULL) {
82 HDF_LOGE("%s invalid param", __func__);
83 return HDF_ERR_INVALID_PARAM;
84 }
85
86 up((struct semaphore *)sem->realSemaphore);
87
88 return HDF_SUCCESS;
89 }
90 EXPORT_SYMBOL(OsalSemPost);
91
OsalSemDestroy(struct OsalSem * sem)92 int32_t OsalSemDestroy(struct OsalSem *sem)
93 {
94 if (sem == NULL || sem->realSemaphore == NULL) {
95 HDF_LOGE("%s invalid param", __func__);
96 return HDF_ERR_INVALID_PARAM;
97 }
98
99 OsalMemFree(sem->realSemaphore);
100 sem->realSemaphore = NULL;
101
102 return HDF_SUCCESS;
103 }
104 EXPORT_SYMBOL(OsalSemDestroy);
105
106