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 
20 #include "osi/semaphore.h"
21 
22 /*-----------------------------------------------------------------------------------*/
23 //  Creates and returns a new semaphore. The "init_count" argument specifies
24 //  the initial state of the semaphore, "max_count" specifies the maximum value
25 //  that can be reached.
osi_sem_new(osi_sem_t * sem,uint32_t max_count,uint32_t init_count)26 int osi_sem_new(osi_sem_t *sem, uint32_t max_count, uint32_t init_count)
27 {
28     int ret = -1;
29 
30     if (sem) {
31         *sem = xSemaphoreCreateCounting(max_count, init_count);
32         if ((*sem) != NULL) {
33             ret = 0;
34         }
35     }
36 
37     return ret;
38 }
39 
40 /*-----------------------------------------------------------------------------------*/
41 // Give a semaphore
osi_sem_give(osi_sem_t * sem)42 void osi_sem_give(osi_sem_t *sem)
43 {
44     xSemaphoreGive(*sem);
45 }
46 
47 /*
48   Blocks the thread while waiting for the semaphore to be
49   signaled. If the "timeout" argument is non-zero, the thread should
50   only be blocked for the specified time (measured in
51   milliseconds).
52 
53 */
54 int
osi_sem_take(osi_sem_t * sem,uint32_t timeout)55 osi_sem_take(osi_sem_t *sem, uint32_t timeout)
56 {
57     int ret = 0;
58 
59     if (timeout ==  OSI_SEM_MAX_TIMEOUT) {
60         if (xSemaphoreTake(*sem, portMAX_DELAY) != pdTRUE) {
61             ret = -1;
62         }
63     } else {
64         if (xSemaphoreTake(*sem, timeout / portTICK_PERIOD_MS) != pdTRUE) {
65             ret = -2;
66         }
67     }
68 
69     return ret;
70 }
71 
72 // Deallocates a semaphore
osi_sem_free(osi_sem_t * sem)73 void osi_sem_free(osi_sem_t *sem)
74 {
75     vSemaphoreDelete(*sem);
76     *sem = NULL;
77 }
78