1 /******************************************************************************
2  *
3  *  Copyright (C) 2015 Google, Inc.
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 #include "osi/mutex.h"
20 
21 
22 /* static section */
23 static osi_mutex_t gl_mutex; /* Recursive Type */
24 
25 
26 /** Create a new mutex
27  * @param mutex pointer to the mutex to create
28  * @return a new mutex */
osi_mutex_new(osi_mutex_t * mutex)29 int osi_mutex_new(osi_mutex_t *mutex)
30 {
31     int xReturn = -1;
32 
33     *mutex = xSemaphoreCreateMutex();
34 
35     if (*mutex != NULL) {
36         xReturn = 0;
37     }
38 
39     return xReturn;
40 }
41 
42 /** Lock a mutex
43  * @param mutex the mutex to lock */
osi_mutex_lock(osi_mutex_t * mutex,uint32_t timeout)44 int osi_mutex_lock(osi_mutex_t *mutex, uint32_t timeout)
45 {
46     int ret = 0;
47 
48     if (timeout == OSI_MUTEX_MAX_TIMEOUT) {
49         if (xSemaphoreTake(*mutex, portMAX_DELAY) != pdTRUE) {
50             ret = -1;
51         }
52     } else {
53         if (xSemaphoreTake(*mutex, timeout / portTICK_PERIOD_MS) != pdTRUE)  {
54             ret = -2;
55         }
56     }
57 
58     return ret;
59 }
60 
61 /** Unlock a mutex
62  * @param mutex the mutex to unlock */
osi_mutex_unlock(osi_mutex_t * mutex)63 void osi_mutex_unlock(osi_mutex_t *mutex)
64 {
65     xSemaphoreGive(*mutex);
66 }
67 
68 /** Delete a semaphore
69  * @param mutex the mutex to delete */
osi_mutex_free(osi_mutex_t * mutex)70 void osi_mutex_free(osi_mutex_t *mutex)
71 {
72     vSemaphoreDelete(*mutex);
73     *mutex = NULL;
74 }
75 
osi_mutex_global_init(void)76 int osi_mutex_global_init(void)
77 {
78     gl_mutex = xSemaphoreCreateRecursiveMutex();
79     if (gl_mutex == NULL) {
80         return -1;
81     }
82 
83     return 0;
84 }
85 
osi_mutex_global_deinit(void)86 void osi_mutex_global_deinit(void)
87 {
88     vSemaphoreDelete(gl_mutex);
89 }
90 
osi_mutex_global_lock(void)91 void osi_mutex_global_lock(void)
92 {
93     xSemaphoreTakeRecursive(gl_mutex, portMAX_DELAY);
94 }
95 
osi_mutex_global_unlock(void)96 void osi_mutex_global_unlock(void)
97 {
98     xSemaphoreGiveRecursive(gl_mutex);
99 }
100