2 * Lua RTOS, mutex api implementation over FreeRTOS
4 * Copyright (C) 2015 - 2017
5 * IBEROXARXA SERVICIOS INTEGRALES, S.L. & CSS IBÉRICA, S.L.
7 * Author: Jaume Olivé (jolive@iberoxarxa.com / jolive@whitecatboard.org)
11 * Permission to use, copy, modify, and distribute this software
12 * and its documentation for any purpose and without fee is hereby
13 * granted, provided that the above copyright notice appear in all
14 * copies and that both that the copyright notice and this
15 * permission notice and warranty disclaimer appear in supporting
16 * documentation, and that the name of the author not be used in
17 * advertising or publicity pertaining to distribution of the
18 * software without specific, written prior permission.
20 * The author disclaim all warranties with regard to this
21 * software, including all implied warranties of merchantability
22 * and fitness. In no event shall the author be liable for any
23 * special, indirect or consequential damages or any damages
24 * whatsoever resulting from loss of use, data or profits, whether
25 * in an action of contract, negligence or other tortious action,
26 * arising out of or in connection with the use or performance of
29 * Modified by: LoBo (loboris@gmail.com / https://github.com/loboris)
33 #include "freertos/FreeRTOS.h"
38 #define portEND_SWITCHING_ISR(xSwitchRequired) \
39 if (xSwitchRequired) { \
40 _frxt_setup_switch(); \
43 extern unsigned port_interruptNesting[portNUM_PROCESSORS];
48 void mtx_init(struct mtx *mutex, const char *name, const char *type, int opts) {
49 mutex->sem = xSemaphoreCreateBinary();
52 if (port_interruptNesting[xPortGetCoreID()] != 0) {
53 BaseType_t xHigherPriorityTaskWoken = pdFALSE;
54 xSemaphoreGiveFromISR( mutex->sem, &xHigherPriorityTaskWoken);
55 portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
57 xSemaphoreGive( mutex->sem );
62 void IRAM_ATTR mtx_lock(struct mtx *mutex) {
63 if (port_interruptNesting[xPortGetCoreID()] != 0) {
64 BaseType_t xHigherPriorityTaskWoken = pdFALSE;
65 xSemaphoreTakeFromISR( mutex->sem, &xHigherPriorityTaskWoken );
66 portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
68 xSemaphoreTake( mutex->sem, portMAX_DELAY );
72 int mtx_trylock(struct mtx *mutex) {
73 if (xSemaphoreTake( mutex->sem, 0 ) == pdTRUE) {
80 void IRAM_ATTR mtx_unlock(struct mtx *mutex) {
81 if (port_interruptNesting[xPortGetCoreID()] != 0) {
82 BaseType_t xHigherPriorityTaskWoken = pdFALSE;
83 xSemaphoreGiveFromISR( mutex->sem, &xHigherPriorityTaskWoken );
84 portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
86 xSemaphoreGive( mutex->sem );
90 void mtx_destroy(struct mtx *mutex) {
91 if (port_interruptNesting[xPortGetCoreID()] != 0) {
92 BaseType_t xHigherPriorityTaskWoken = pdFALSE;
93 xSemaphoreGiveFromISR( mutex->sem, &xHigherPriorityTaskWoken );
94 portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
96 xSemaphoreGive( mutex->sem );
99 vSemaphoreDelete( mutex->sem );