locks.c 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <sys/lock.h>
  15. #include <stdlib.h>
  16. #include <sys/reent.h>
  17. #include "esp_attr.h"
  18. #include "soc/cpu.h"
  19. #include "freertos/FreeRTOS.h"
  20. #include "freertos/semphr.h"
  21. #include "freertos/portmacro.h"
  22. #include "freertos/task.h"
  23. #include "freertos/portable.h"
  24. /* Notes on our newlib lock implementation:
  25. *
  26. * - Use FreeRTOS mutex semaphores as locks.
  27. * - lock_t is int, but we store an xSemaphoreHandle there.
  28. * - Locks are no-ops until the FreeRTOS scheduler is running.
  29. * - Due to this, locks need to be lazily initialised the first time
  30. * they are acquired. Initialisation/deinitialisation of locks is
  31. * protected by lock_init_spinlock.
  32. * - Race conditions around lazy initialisation (via lock_acquire) are
  33. * protected against.
  34. * - Anyone calling lock_close is reponsible for ensuring noone else
  35. * is holding the lock at this time.
  36. * - Race conditions between lock_close & lock_init (for the same lock)
  37. * are the responsibility of the caller.
  38. */
  39. static portMUX_TYPE lock_init_spinlock = portMUX_INITIALIZER_UNLOCKED;
  40. /* Initialize the given lock by allocating a new mutex semaphore
  41. as the _lock_t value.
  42. Called by _lock_init*, also called by _lock_acquire* to lazily initialize locks that might have
  43. been initialised (to zero only) before the RTOS scheduler started.
  44. */
  45. static void IRAM_ATTR lock_init_generic(_lock_t *lock, uint8_t mutex_type) {
  46. portENTER_CRITICAL(&lock_init_spinlock);
  47. if (xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED) {
  48. /* nothing to do until the scheduler is running */
  49. portEXIT_CRITICAL(&lock_init_spinlock);
  50. return;
  51. }
  52. if (*lock) {
  53. /* Lock already initialised (either we didn't check earlier,
  54. or it got initialised while we were waiting for the
  55. spinlock.) */
  56. }
  57. else
  58. {
  59. /* Create a new semaphore
  60. this is a bit of an API violation, as we're calling the
  61. private function xQueueCreateMutex(x) directly instead of
  62. the xSemaphoreCreateMutex / xSemaphoreCreateRecursiveMutex
  63. wrapper functions...
  64. The better alternative would be to pass pointers to one of
  65. the two xSemaphoreCreate___Mutex functions, but as FreeRTOS
  66. implements these as macros instead of inline functions
  67. (*party like it's 1998!*) it's not possible to do this
  68. without writing wrappers. Doing it this way seems much less
  69. spaghetti-like.
  70. */
  71. xSemaphoreHandle new_sem = xQueueCreateMutex(mutex_type);
  72. if (!new_sem) {
  73. abort(); /* No more semaphores available or OOM */
  74. }
  75. *lock = (_lock_t)new_sem;
  76. }
  77. portEXIT_CRITICAL(&lock_init_spinlock);
  78. }
  79. void IRAM_ATTR _lock_init(_lock_t *lock) {
  80. *lock = 0; // In case lock's memory is uninitialized
  81. lock_init_generic(lock, queueQUEUE_TYPE_MUTEX);
  82. }
  83. void IRAM_ATTR _lock_init_recursive(_lock_t *lock) {
  84. *lock = 0; // In case lock's memory is uninitialized
  85. lock_init_generic(lock, queueQUEUE_TYPE_RECURSIVE_MUTEX);
  86. }
  87. /* Free the mutex semaphore pointed to by *lock, and zero it out.
  88. Note that FreeRTOS doesn't account for deleting mutexes while they
  89. are held, and neither do we... so take care not to delete newlib
  90. locks while they may be held by other tasks!
  91. Also, deleting a lock in this way will cause it to be lazily
  92. re-initialised if it is used again. Caller has to avoid doing
  93. this!
  94. */
  95. void IRAM_ATTR _lock_close(_lock_t *lock) {
  96. portENTER_CRITICAL(&lock_init_spinlock);
  97. if (*lock) {
  98. xSemaphoreHandle h = (xSemaphoreHandle)(*lock);
  99. #if (INCLUDE_xSemaphoreGetMutexHolder == 1)
  100. configASSERT(xSemaphoreGetMutexHolder(h) == NULL); /* mutex should not be held */
  101. #endif
  102. vSemaphoreDelete(h);
  103. *lock = 0;
  104. }
  105. portEXIT_CRITICAL(&lock_init_spinlock);
  106. }
  107. void _lock_close_recursive(_lock_t *lock) __attribute__((alias("_lock_close")));
  108. /* Acquire the mutex semaphore for lock. wait up to delay ticks.
  109. mutex_type is queueQUEUE_TYPE_RECURSIVE_MUTEX or queueQUEUE_TYPE_MUTEX
  110. */
  111. static int IRAM_ATTR lock_acquire_generic(_lock_t *lock, uint32_t delay, uint8_t mutex_type) {
  112. xSemaphoreHandle h = (xSemaphoreHandle)(*lock);
  113. if (!h) {
  114. if (xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED) {
  115. return 0; /* locking is a no-op before scheduler is up, so this "succeeds" */
  116. }
  117. /* lazy initialise lock - might have had a static initializer in newlib (that we don't use),
  118. or _lock_init might have been called before the scheduler was running... */
  119. lock_init_generic(lock, mutex_type);
  120. h = (xSemaphoreHandle)(*lock);
  121. configASSERT(h != NULL);
  122. }
  123. BaseType_t success;
  124. if (!xPortCanYield()) {
  125. /* In ISR Context */
  126. if (mutex_type == queueQUEUE_TYPE_RECURSIVE_MUTEX) {
  127. abort(); /* recursive mutexes make no sense in ISR context */
  128. }
  129. BaseType_t higher_task_woken = false;
  130. success = xSemaphoreTakeFromISR(h, &higher_task_woken);
  131. if (!success && delay > 0) {
  132. abort(); /* Tried to block on mutex from ISR, couldn't... rewrite your program to avoid libc interactions in ISRs! */
  133. }
  134. if (higher_task_woken) {
  135. portYIELD_FROM_ISR();
  136. }
  137. }
  138. else {
  139. /* In task context */
  140. if (mutex_type == queueQUEUE_TYPE_RECURSIVE_MUTEX) {
  141. success = xSemaphoreTakeRecursive(h, delay);
  142. } else {
  143. success = xSemaphoreTake(h, delay);
  144. }
  145. }
  146. return (success == pdTRUE) ? 0 : -1;
  147. }
  148. void IRAM_ATTR _lock_acquire(_lock_t *lock) {
  149. lock_acquire_generic(lock, portMAX_DELAY, queueQUEUE_TYPE_MUTEX);
  150. }
  151. void IRAM_ATTR _lock_acquire_recursive(_lock_t *lock) {
  152. lock_acquire_generic(lock, portMAX_DELAY, queueQUEUE_TYPE_RECURSIVE_MUTEX);
  153. }
  154. int IRAM_ATTR _lock_try_acquire(_lock_t *lock) {
  155. return lock_acquire_generic(lock, 0, queueQUEUE_TYPE_MUTEX);
  156. }
  157. int IRAM_ATTR _lock_try_acquire_recursive(_lock_t *lock) {
  158. return lock_acquire_generic(lock, 0, queueQUEUE_TYPE_RECURSIVE_MUTEX);
  159. }
  160. /* Release the mutex semaphore for lock.
  161. mutex_type is queueQUEUE_TYPE_RECURSIVE_MUTEX or queueQUEUE_TYPE_MUTEX
  162. */
  163. static void IRAM_ATTR lock_release_generic(_lock_t *lock, uint8_t mutex_type) {
  164. xSemaphoreHandle h = (xSemaphoreHandle)(*lock);
  165. if (h == NULL) {
  166. /* This is probably because the scheduler isn't running yet,
  167. or the scheduler just started running and some code was
  168. "holding" a not-yet-initialised lock... */
  169. return;
  170. }
  171. if (!xPortCanYield()) {
  172. if (mutex_type == queueQUEUE_TYPE_RECURSIVE_MUTEX) {
  173. abort(); /* indicates logic bug, it shouldn't be possible to lock recursively in ISR */
  174. }
  175. BaseType_t higher_task_woken = false;
  176. xSemaphoreGiveFromISR(h, &higher_task_woken);
  177. if (higher_task_woken) {
  178. portYIELD_FROM_ISR();
  179. }
  180. } else {
  181. if (mutex_type == queueQUEUE_TYPE_RECURSIVE_MUTEX) {
  182. xSemaphoreGiveRecursive(h);
  183. } else {
  184. xSemaphoreGive(h);
  185. }
  186. }
  187. }
  188. void IRAM_ATTR _lock_release(_lock_t *lock) {
  189. lock_release_generic(lock, queueQUEUE_TYPE_MUTEX);
  190. }
  191. void IRAM_ATTR _lock_release_recursive(_lock_t *lock) {
  192. lock_release_generic(lock, queueQUEUE_TYPE_RECURSIVE_MUTEX);
  193. }