1 /*
2  * Copyright (c) 2016, Xilinx Inc. and Contributors. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 /*
8  * @file	freertos/mutex.h
9  * @brief	FreeRTOS mutex primitives for libmetal.
10  */
11 
12 #ifndef __METAL_MUTEX__H__
13 #error "Include metal/mutex.h instead of metal/freertos/mutex.h"
14 #endif
15 
16 #ifndef __METAL_FREERTOS_MUTEX__H__
17 #define __METAL_FREERTOS_MUTEX__H__
18 
19 #include <metal/assert.h>
20 #include "FreeRTOS.h"
21 #include "semphr.h"
22 
23 
24 #ifdef __cplusplus
25 extern "C" {
26 #endif
27 
28 typedef struct {
29 	SemaphoreHandle_t m;
30 } metal_mutex_t;
31 
32 /*
33  * METAL_MUTEX_DEFINE - used for defining and initializing a global or
34  * static singleton mutex
35  */
36 #define METAL_MUTEX_DEFINE(m) metal_mutex_t m = METAL_MUTEX_INIT(m)
37 
__metal_mutex_init(metal_mutex_t * mutex)38 static inline void __metal_mutex_init(metal_mutex_t *mutex)
39 {
40 	metal_assert(mutex);
41 	mutex->m = xSemaphoreCreateMutex();
42 	metal_assert(mutex->m);
43 }
44 
__metal_mutex_deinit(metal_mutex_t * mutex)45 static inline void __metal_mutex_deinit(metal_mutex_t *mutex)
46 {
47 	metal_assert(mutex && mutex->m);
48 	vSemaphoreDelete(mutex->m);
49 	mutex->m = NULL;
50 }
51 
__metal_mutex_try_acquire(metal_mutex_t * mutex)52 static inline int __metal_mutex_try_acquire(metal_mutex_t *mutex)
53 {
54 	metal_assert(mutex && mutex->m);
55 	return xSemaphoreTake(mutex->m, (TickType_t)0);
56 }
57 
__metal_mutex_acquire(metal_mutex_t * mutex)58 static inline void __metal_mutex_acquire(metal_mutex_t *mutex)
59 {
60 	metal_assert(mutex && mutex->m);
61 	xSemaphoreTake(mutex->m, portMAX_DELAY);
62 }
63 
__metal_mutex_release(metal_mutex_t * mutex)64 static inline void __metal_mutex_release(metal_mutex_t *mutex)
65 {
66 	metal_assert(mutex && mutex->m);
67 	xSemaphoreGive(mutex->m);
68 }
69 
__metal_mutex_is_acquired(metal_mutex_t * mutex)70 static inline int __metal_mutex_is_acquired(metal_mutex_t *mutex)
71 {
72 	metal_assert(mutex && mutex->m);
73 	return (!xSemaphoreGetMutexHolder(mutex->m)) ? 0 : 1;
74 }
75 
76 #ifdef __cplusplus
77 }
78 #endif
79 
80 #endif /* __METAL_FREERTOS_MUTEX__H__ */
81