pthread.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839
  1. // Copyright 2018 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. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. //
  14. // This module implements pthread API on top of FreeRTOS. API is implemented to the level allowing
  15. // libstdcxx threading framework to operate correctly. So not all original pthread routines are supported.
  16. //
  17. #include <time.h>
  18. #include <errno.h>
  19. #include <pthread.h>
  20. #include <string.h>
  21. #include "esp_err.h"
  22. #include "esp_attr.h"
  23. #include "sys/queue.h"
  24. #include "freertos/FreeRTOS.h"
  25. #include "freertos/task.h"
  26. #include "freertos/semphr.h"
  27. #include "soc/soc_memory_layout.h"
  28. #include "pthread_internal.h"
  29. #include "esp_pthread.h"
  30. #include "esp_log.h"
  31. const static char *TAG = "pthread";
  32. /** task state */
  33. enum esp_pthread_task_state {
  34. PTHREAD_TASK_STATE_RUN,
  35. PTHREAD_TASK_STATE_EXIT
  36. };
  37. /** pthread thread FreeRTOS wrapper */
  38. typedef struct esp_pthread_entry {
  39. SLIST_ENTRY(esp_pthread_entry) list_node; ///< Tasks list node struct.
  40. TaskHandle_t handle; ///< FreeRTOS task handle
  41. TaskHandle_t join_task; ///< Handle of the task waiting to join
  42. enum esp_pthread_task_state state; ///< pthread task state
  43. bool detached; ///< True if pthread is detached
  44. void *retval; ///< Value supplied to calling thread during join
  45. void *task_arg; ///< Task arguments
  46. } esp_pthread_t;
  47. /** pthread wrapper task arg */
  48. typedef struct {
  49. void *(*func)(void *); ///< user task entry
  50. void *arg; ///< user task argument
  51. esp_pthread_cfg_t cfg; ///< pthread configuration
  52. } esp_pthread_task_arg_t;
  53. /** pthread mutex FreeRTOS wrapper */
  54. typedef struct {
  55. SemaphoreHandle_t sem; ///< Handle of the task waiting to join
  56. int type; ///< Mutex type. Currently supported PTHREAD_MUTEX_NORMAL and PTHREAD_MUTEX_RECURSIVE
  57. } esp_pthread_mutex_t;
  58. static SemaphoreHandle_t s_threads_mux = NULL;
  59. portMUX_TYPE pthread_lazy_init_lock = portMUX_INITIALIZER_UNLOCKED; // Used for mutexes and cond vars
  60. static SLIST_HEAD(esp_thread_list_head, esp_pthread_entry) s_threads_list
  61. = SLIST_HEAD_INITIALIZER(s_threads_list);
  62. static pthread_key_t s_pthread_cfg_key;
  63. static int IRAM_ATTR pthread_mutex_lock_internal(esp_pthread_mutex_t *mux, TickType_t tmo);
  64. static void esp_pthread_cfg_key_destructor(void *value)
  65. {
  66. free(value);
  67. }
  68. esp_err_t esp_pthread_init(void)
  69. {
  70. if (pthread_key_create(&s_pthread_cfg_key, esp_pthread_cfg_key_destructor) != 0) {
  71. return ESP_ERR_NO_MEM;
  72. }
  73. s_threads_mux = xSemaphoreCreateMutex();
  74. if (s_threads_mux == NULL) {
  75. pthread_key_delete(s_pthread_cfg_key);
  76. return ESP_ERR_NO_MEM;
  77. }
  78. return ESP_OK;
  79. }
  80. static void *pthread_list_find_item(void *(*item_check)(esp_pthread_t *, void *arg), void *check_arg)
  81. {
  82. esp_pthread_t *it;
  83. SLIST_FOREACH(it, &s_threads_list, list_node) {
  84. void *val = item_check(it, check_arg);
  85. if (val) {
  86. return val;
  87. }
  88. }
  89. return NULL;
  90. }
  91. static void *pthread_get_handle_by_desc(esp_pthread_t *item, void *desc)
  92. {
  93. if (item == desc) {
  94. return item->handle;
  95. }
  96. return NULL;
  97. }
  98. static void *pthread_get_desc_by_handle(esp_pthread_t *item, void *hnd)
  99. {
  100. if (hnd == item->handle) {
  101. return item;
  102. }
  103. return NULL;
  104. }
  105. static inline TaskHandle_t pthread_find_handle(pthread_t thread)
  106. {
  107. return pthread_list_find_item(pthread_get_handle_by_desc, (void *)thread);
  108. }
  109. static esp_pthread_t *pthread_find(TaskHandle_t task_handle)
  110. {
  111. return pthread_list_find_item(pthread_get_desc_by_handle, task_handle);
  112. }
  113. static void pthread_delete(esp_pthread_t *pthread)
  114. {
  115. SLIST_REMOVE(&s_threads_list, pthread, esp_pthread_entry, list_node);
  116. free(pthread);
  117. }
  118. /* Call this function to configure pthread stacks in Pthreads */
  119. esp_err_t esp_pthread_set_cfg(const esp_pthread_cfg_t *cfg)
  120. {
  121. if (cfg->stack_size < PTHREAD_STACK_MIN) {
  122. return ESP_ERR_INVALID_ARG;
  123. }
  124. /* If a value is already set, update that value */
  125. esp_pthread_cfg_t *p = pthread_getspecific(s_pthread_cfg_key);
  126. if (!p) {
  127. p = malloc(sizeof(esp_pthread_cfg_t));
  128. if (!p) {
  129. return ESP_ERR_NO_MEM;
  130. }
  131. }
  132. *p = *cfg;
  133. pthread_setspecific(s_pthread_cfg_key, p);
  134. return 0;
  135. }
  136. esp_err_t esp_pthread_get_cfg(esp_pthread_cfg_t *p)
  137. {
  138. esp_pthread_cfg_t *cfg = pthread_getspecific(s_pthread_cfg_key);
  139. if (cfg) {
  140. *p = *cfg;
  141. return ESP_OK;
  142. }
  143. memset(p, 0, sizeof(*p));
  144. return ESP_ERR_NOT_FOUND;
  145. }
  146. static int get_default_pthread_core(void)
  147. {
  148. return CONFIG_PTHREAD_TASK_CORE_DEFAULT == -1 ? tskNO_AFFINITY : CONFIG_PTHREAD_TASK_CORE_DEFAULT;
  149. }
  150. esp_pthread_cfg_t esp_pthread_get_default_config(void)
  151. {
  152. esp_pthread_cfg_t cfg = {
  153. .stack_size = CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT,
  154. .prio = CONFIG_PTHREAD_TASK_PRIO_DEFAULT,
  155. .inherit_cfg = false,
  156. .thread_name = NULL,
  157. .pin_to_core = get_default_pthread_core()
  158. };
  159. return cfg;
  160. }
  161. static void pthread_task_func(void *arg)
  162. {
  163. void *rval = NULL;
  164. esp_pthread_task_arg_t *task_arg = (esp_pthread_task_arg_t *)arg;
  165. ESP_LOGV(TAG, "%s ENTER %p", __FUNCTION__, task_arg->func);
  166. // wait for start
  167. xTaskNotifyWait(0, 0, NULL, portMAX_DELAY);
  168. if (task_arg->cfg.inherit_cfg) {
  169. /* If inherit option is set, then do a set_cfg() ourselves for future forks,
  170. but first set thread_name to NULL to enable inheritance of the name too.
  171. (This also to prevents dangling pointers to name of tasks that might
  172. possibly have been deleted when we use the configuration).*/
  173. esp_pthread_cfg_t *cfg = &task_arg->cfg;
  174. cfg->thread_name = NULL;
  175. esp_pthread_set_cfg(cfg);
  176. }
  177. ESP_LOGV(TAG, "%s START %p", __FUNCTION__, task_arg->func);
  178. rval = task_arg->func(task_arg->arg);
  179. ESP_LOGV(TAG, "%s END %p", __FUNCTION__, task_arg->func);
  180. pthread_exit(rval);
  181. ESP_LOGV(TAG, "%s EXIT", __FUNCTION__);
  182. }
  183. int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
  184. void *(*start_routine) (void *), void *arg)
  185. {
  186. TaskHandle_t xHandle = NULL;
  187. ESP_LOGV(TAG, "%s", __FUNCTION__);
  188. esp_pthread_task_arg_t *task_arg = calloc(1, sizeof(esp_pthread_task_arg_t));
  189. if (task_arg == NULL) {
  190. ESP_LOGE(TAG, "Failed to allocate task args!");
  191. return ENOMEM;
  192. }
  193. esp_pthread_t *pthread = calloc(1, sizeof(esp_pthread_t));
  194. if (pthread == NULL) {
  195. ESP_LOGE(TAG, "Failed to allocate pthread data!");
  196. free(task_arg);
  197. return ENOMEM;
  198. }
  199. uint32_t stack_size = CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT;
  200. BaseType_t prio = CONFIG_PTHREAD_TASK_PRIO_DEFAULT;
  201. BaseType_t core_id = get_default_pthread_core();
  202. const char *task_name = CONFIG_PTHREAD_TASK_NAME_DEFAULT;
  203. esp_pthread_cfg_t *pthread_cfg = pthread_getspecific(s_pthread_cfg_key);
  204. if (pthread_cfg) {
  205. if (pthread_cfg->stack_size) {
  206. stack_size = pthread_cfg->stack_size;
  207. }
  208. if (pthread_cfg->prio && pthread_cfg->prio < configMAX_PRIORITIES) {
  209. prio = pthread_cfg->prio;
  210. }
  211. if (pthread_cfg->inherit_cfg) {
  212. if (pthread_cfg->thread_name == NULL) {
  213. // Inherit task name from current task.
  214. task_name = pcTaskGetTaskName(NULL);
  215. } else {
  216. // Inheriting, but new task name.
  217. task_name = pthread_cfg->thread_name;
  218. }
  219. } else if (pthread_cfg->thread_name == NULL) {
  220. task_name = CONFIG_PTHREAD_TASK_NAME_DEFAULT;
  221. } else {
  222. task_name = pthread_cfg->thread_name;
  223. }
  224. if (pthread_cfg->pin_to_core >= 0 && pthread_cfg->pin_to_core < portNUM_PROCESSORS) {
  225. core_id = pthread_cfg->pin_to_core;
  226. }
  227. task_arg->cfg = *pthread_cfg;
  228. }
  229. if (attr) {
  230. /* Overwrite attributes */
  231. stack_size = attr->stacksize;
  232. switch (attr->detachstate) {
  233. case PTHREAD_CREATE_DETACHED:
  234. pthread->detached = true;
  235. break;
  236. case PTHREAD_CREATE_JOINABLE:
  237. default:
  238. pthread->detached = false;
  239. }
  240. }
  241. task_arg->func = start_routine;
  242. task_arg->arg = arg;
  243. pthread->task_arg = task_arg;
  244. BaseType_t res = xTaskCreatePinnedToCore(&pthread_task_func,
  245. task_name,
  246. // stack_size is in bytes. This transformation ensures that the units are
  247. // transformed to the units used in FreeRTOS.
  248. // Note: float division of ceil(m / n) ==
  249. // integer division of (m + n - 1) / n
  250. (stack_size + sizeof(StackType_t) - 1) / sizeof(StackType_t),
  251. task_arg,
  252. prio,
  253. &xHandle,
  254. core_id);
  255. if (res != pdPASS) {
  256. ESP_LOGE(TAG, "Failed to create task!");
  257. free(pthread);
  258. free(task_arg);
  259. if (res == errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY) {
  260. return ENOMEM;
  261. } else {
  262. return EAGAIN;
  263. }
  264. }
  265. pthread->handle = xHandle;
  266. if (xSemaphoreTake(s_threads_mux, portMAX_DELAY) != pdTRUE) {
  267. assert(false && "Failed to lock threads list!");
  268. }
  269. SLIST_INSERT_HEAD(&s_threads_list, pthread, list_node);
  270. xSemaphoreGive(s_threads_mux);
  271. // start task
  272. xTaskNotify(xHandle, 0, eNoAction);
  273. *thread = (pthread_t)pthread; // pointer value fit into pthread_t (uint32_t)
  274. ESP_LOGV(TAG, "Created task %x", (uint32_t)xHandle);
  275. return 0;
  276. }
  277. int pthread_join(pthread_t thread, void **retval)
  278. {
  279. esp_pthread_t *pthread = (esp_pthread_t *)thread;
  280. int ret = 0;
  281. bool wait = false;
  282. void *child_task_retval = 0;
  283. ESP_LOGV(TAG, "%s %p", __FUNCTION__, pthread);
  284. // find task
  285. if (xSemaphoreTake(s_threads_mux, portMAX_DELAY) != pdTRUE) {
  286. assert(false && "Failed to lock threads list!");
  287. }
  288. TaskHandle_t handle = pthread_find_handle(thread);
  289. if (!handle) {
  290. // not found
  291. ret = ESRCH;
  292. } else if (pthread->detached) {
  293. // Thread is detached
  294. ret = EDEADLK;
  295. } else if (pthread->join_task) {
  296. // already have waiting task to join
  297. ret = EINVAL;
  298. } else if (handle == xTaskGetCurrentTaskHandle()) {
  299. // join to self not allowed
  300. ret = EDEADLK;
  301. } else {
  302. esp_pthread_t *cur_pthread = pthread_find(xTaskGetCurrentTaskHandle());
  303. if (cur_pthread && cur_pthread->join_task == handle) {
  304. // join to each other not allowed
  305. ret = EDEADLK;
  306. } else {
  307. if (pthread->state == PTHREAD_TASK_STATE_RUN) {
  308. pthread->join_task = xTaskGetCurrentTaskHandle();
  309. wait = true;
  310. } else { // thread has exited and task is already suspended, or about to be suspended
  311. child_task_retval = pthread->retval;
  312. pthread_delete(pthread);
  313. }
  314. }
  315. }
  316. xSemaphoreGive(s_threads_mux);
  317. if (ret == 0) {
  318. if (wait) {
  319. xTaskNotifyWait(0, 0, NULL, portMAX_DELAY);
  320. if (xSemaphoreTake(s_threads_mux, portMAX_DELAY) != pdTRUE) {
  321. assert(false && "Failed to lock threads list!");
  322. }
  323. child_task_retval = pthread->retval;
  324. pthread_delete(pthread);
  325. xSemaphoreGive(s_threads_mux);
  326. }
  327. vTaskDelete(handle);
  328. }
  329. if (retval) {
  330. *retval = child_task_retval;
  331. }
  332. ESP_LOGV(TAG, "%s %p EXIT %d", __FUNCTION__, pthread, ret);
  333. return ret;
  334. }
  335. int pthread_detach(pthread_t thread)
  336. {
  337. esp_pthread_t *pthread = (esp_pthread_t *)thread;
  338. int ret = 0;
  339. if (xSemaphoreTake(s_threads_mux, portMAX_DELAY) != pdTRUE) {
  340. assert(false && "Failed to lock threads list!");
  341. }
  342. TaskHandle_t handle = pthread_find_handle(thread);
  343. if (!handle) {
  344. ret = ESRCH;
  345. } else if (pthread->detached) {
  346. // already detached
  347. ret = EINVAL;
  348. } else if (pthread->join_task) {
  349. // already have waiting task to join
  350. ret = EINVAL;
  351. } else if (pthread->state == PTHREAD_TASK_STATE_RUN) {
  352. // pthread still running
  353. pthread->detached = true;
  354. } else {
  355. // pthread already stopped
  356. pthread_delete(pthread);
  357. vTaskDelete(handle);
  358. }
  359. xSemaphoreGive(s_threads_mux);
  360. ESP_LOGV(TAG, "%s %p EXIT %d", __FUNCTION__, pthread, ret);
  361. return ret;
  362. }
  363. void pthread_exit(void *value_ptr)
  364. {
  365. bool detached = false;
  366. /* preemptively clean up thread local storage, rather than
  367. waiting for the idle task to clean up the thread */
  368. pthread_internal_local_storage_destructor_callback();
  369. if (xSemaphoreTake(s_threads_mux, portMAX_DELAY) != pdTRUE) {
  370. assert(false && "Failed to lock threads list!");
  371. }
  372. esp_pthread_t *pthread = pthread_find(xTaskGetCurrentTaskHandle());
  373. if (!pthread) {
  374. assert(false && "Failed to find pthread for current task!");
  375. }
  376. if (pthread->task_arg) {
  377. free(pthread->task_arg);
  378. }
  379. if (pthread->detached) {
  380. // auto-free for detached threads
  381. pthread_delete(pthread);
  382. detached = true;
  383. } else {
  384. // Set return value
  385. pthread->retval = value_ptr;
  386. // Remove from list, it indicates that task has exited
  387. if (pthread->join_task) {
  388. // notify join
  389. xTaskNotify(pthread->join_task, 0, eNoAction);
  390. } else {
  391. pthread->state = PTHREAD_TASK_STATE_EXIT;
  392. }
  393. }
  394. ESP_LOGD(TAG, "Task stk_wm = %d", uxTaskGetStackHighWaterMark(NULL));
  395. xSemaphoreGive(s_threads_mux);
  396. // note: if this thread is joinable then after giving back s_threads_mux
  397. // this task could be deleted at any time, so don't take another lock or
  398. // do anything that might lock (such as printing to stdout)
  399. if (detached) {
  400. vTaskDelete(NULL);
  401. } else {
  402. vTaskSuspend(NULL);
  403. }
  404. // Should never be reached
  405. abort();
  406. }
  407. int pthread_cancel(pthread_t thread)
  408. {
  409. ESP_LOGE(TAG, "%s: not supported!", __FUNCTION__);
  410. return ENOSYS;
  411. }
  412. int sched_yield( void )
  413. {
  414. vTaskDelay(0);
  415. return 0;
  416. }
  417. pthread_t pthread_self(void)
  418. {
  419. if (xSemaphoreTake(s_threads_mux, portMAX_DELAY) != pdTRUE) {
  420. assert(false && "Failed to lock threads list!");
  421. }
  422. esp_pthread_t *pthread = pthread_find(xTaskGetCurrentTaskHandle());
  423. if (!pthread) {
  424. assert(false && "Failed to find current thread ID!");
  425. }
  426. xSemaphoreGive(s_threads_mux);
  427. return (pthread_t)pthread;
  428. }
  429. int pthread_equal(pthread_t t1, pthread_t t2)
  430. {
  431. return t1 == t2 ? 1 : 0;
  432. }
  433. /***************** ONCE ******************/
  434. int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
  435. {
  436. if (once_control == NULL || init_routine == NULL || !once_control->is_initialized) {
  437. ESP_LOGE(TAG, "%s: Invalid args!", __FUNCTION__);
  438. return EINVAL;
  439. }
  440. uint32_t res = 1;
  441. #if defined(CONFIG_SPIRAM)
  442. if (esp_ptr_external_ram(once_control)) {
  443. uxPortCompareSetExtram((uint32_t *) &once_control->init_executed, 0, &res);
  444. } else {
  445. #endif
  446. uxPortCompareSet((uint32_t *) &once_control->init_executed, 0, &res);
  447. #if defined(CONFIG_SPIRAM)
  448. }
  449. #endif
  450. // Check if compare and set was successful
  451. if (res == 0) {
  452. ESP_LOGV(TAG, "%s: call init_routine %p", __FUNCTION__, once_control);
  453. init_routine();
  454. }
  455. return 0;
  456. }
  457. /***************** MUTEX ******************/
  458. static int mutexattr_check(const pthread_mutexattr_t *attr)
  459. {
  460. if (attr->type != PTHREAD_MUTEX_NORMAL &&
  461. attr->type != PTHREAD_MUTEX_RECURSIVE &&
  462. attr->type != PTHREAD_MUTEX_ERRORCHECK) {
  463. return EINVAL;
  464. }
  465. return 0;
  466. }
  467. int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
  468. {
  469. int type = PTHREAD_MUTEX_NORMAL;
  470. if (!mutex) {
  471. return EINVAL;
  472. }
  473. if (attr) {
  474. if (!attr->is_initialized) {
  475. return EINVAL;
  476. }
  477. int res = mutexattr_check(attr);
  478. if (res) {
  479. return res;
  480. }
  481. type = attr->type;
  482. }
  483. esp_pthread_mutex_t *mux = (esp_pthread_mutex_t *)malloc(sizeof(esp_pthread_mutex_t));
  484. if (!mux) {
  485. return ENOMEM;
  486. }
  487. mux->type = type;
  488. if (mux->type == PTHREAD_MUTEX_RECURSIVE) {
  489. mux->sem = xSemaphoreCreateRecursiveMutex();
  490. } else {
  491. mux->sem = xSemaphoreCreateMutex();
  492. }
  493. if (!mux->sem) {
  494. free(mux);
  495. return EAGAIN;
  496. }
  497. *mutex = (pthread_mutex_t)mux; // pointer value fit into pthread_mutex_t (uint32_t)
  498. return 0;
  499. }
  500. int pthread_mutex_destroy(pthread_mutex_t *mutex)
  501. {
  502. esp_pthread_mutex_t *mux;
  503. ESP_LOGV(TAG, "%s %p", __FUNCTION__, mutex);
  504. if (!mutex) {
  505. return EINVAL;
  506. }
  507. if ((intptr_t) *mutex == PTHREAD_MUTEX_INITIALIZER) {
  508. return 0; // Static mutex was never initialized
  509. }
  510. mux = (esp_pthread_mutex_t *)*mutex;
  511. if (!mux) {
  512. return EINVAL;
  513. }
  514. // check if mux is busy
  515. int res = pthread_mutex_lock_internal(mux, 0);
  516. if (res == EBUSY) {
  517. return EBUSY;
  518. }
  519. if (mux->type == PTHREAD_MUTEX_RECURSIVE) {
  520. res = xSemaphoreGiveRecursive(mux->sem);
  521. } else {
  522. res = xSemaphoreGive(mux->sem);
  523. }
  524. if (res != pdTRUE) {
  525. assert(false && "Failed to release mutex!");
  526. }
  527. vSemaphoreDelete(mux->sem);
  528. free(mux);
  529. return 0;
  530. }
  531. static int IRAM_ATTR pthread_mutex_lock_internal(esp_pthread_mutex_t *mux, TickType_t tmo)
  532. {
  533. if (!mux) {
  534. return EINVAL;
  535. }
  536. if ((mux->type == PTHREAD_MUTEX_ERRORCHECK) &&
  537. (xSemaphoreGetMutexHolder(mux->sem) == xTaskGetCurrentTaskHandle())) {
  538. return EDEADLK;
  539. }
  540. if (mux->type == PTHREAD_MUTEX_RECURSIVE) {
  541. if (xSemaphoreTakeRecursive(mux->sem, tmo) != pdTRUE) {
  542. return EBUSY;
  543. }
  544. } else {
  545. if (xSemaphoreTake(mux->sem, tmo) != pdTRUE) {
  546. return EBUSY;
  547. }
  548. }
  549. return 0;
  550. }
  551. static int pthread_mutex_init_if_static(pthread_mutex_t *mutex)
  552. {
  553. int res = 0;
  554. if ((intptr_t) *mutex == PTHREAD_MUTEX_INITIALIZER) {
  555. portENTER_CRITICAL(&pthread_lazy_init_lock);
  556. if ((intptr_t) *mutex == PTHREAD_MUTEX_INITIALIZER) {
  557. res = pthread_mutex_init(mutex, NULL);
  558. }
  559. portEXIT_CRITICAL(&pthread_lazy_init_lock);
  560. }
  561. return res;
  562. }
  563. int IRAM_ATTR pthread_mutex_lock(pthread_mutex_t *mutex)
  564. {
  565. if (!mutex) {
  566. return EINVAL;
  567. }
  568. int res = pthread_mutex_init_if_static(mutex);
  569. if (res != 0) {
  570. return res;
  571. }
  572. return pthread_mutex_lock_internal((esp_pthread_mutex_t *)*mutex, portMAX_DELAY);
  573. }
  574. int IRAM_ATTR pthread_mutex_timedlock(pthread_mutex_t *mutex, const struct timespec *timeout)
  575. {
  576. if (!mutex) {
  577. return EINVAL;
  578. }
  579. int res = pthread_mutex_init_if_static(mutex);
  580. if (res != 0) {
  581. return res;
  582. }
  583. struct timespec currtime;
  584. clock_gettime(CLOCK_REALTIME, &currtime);
  585. TickType_t tmo = ((timeout->tv_sec - currtime.tv_sec)*1000 +
  586. (timeout->tv_nsec - currtime.tv_nsec)/1000000)/portTICK_PERIOD_MS;
  587. res = pthread_mutex_lock_internal((esp_pthread_mutex_t *)*mutex, tmo);
  588. if (res == EBUSY) {
  589. return ETIMEDOUT;
  590. }
  591. return res;
  592. }
  593. int IRAM_ATTR pthread_mutex_trylock(pthread_mutex_t *mutex)
  594. {
  595. if (!mutex) {
  596. return EINVAL;
  597. }
  598. int res = pthread_mutex_init_if_static(mutex);
  599. if (res != 0) {
  600. return res;
  601. }
  602. return pthread_mutex_lock_internal((esp_pthread_mutex_t *)*mutex, 0);
  603. }
  604. int IRAM_ATTR pthread_mutex_unlock(pthread_mutex_t *mutex)
  605. {
  606. esp_pthread_mutex_t *mux;
  607. if (!mutex) {
  608. return EINVAL;
  609. }
  610. mux = (esp_pthread_mutex_t *)*mutex;
  611. if (!mux) {
  612. return EINVAL;
  613. }
  614. if (((mux->type == PTHREAD_MUTEX_RECURSIVE) ||
  615. (mux->type == PTHREAD_MUTEX_ERRORCHECK)) &&
  616. (xSemaphoreGetMutexHolder(mux->sem) != xTaskGetCurrentTaskHandle())) {
  617. return EPERM;
  618. }
  619. int ret;
  620. if (mux->type == PTHREAD_MUTEX_RECURSIVE) {
  621. ret = xSemaphoreGiveRecursive(mux->sem);
  622. } else {
  623. ret = xSemaphoreGive(mux->sem);
  624. }
  625. if (ret != pdTRUE) {
  626. assert(false && "Failed to unlock mutex!");
  627. }
  628. return 0;
  629. }
  630. int pthread_mutexattr_init(pthread_mutexattr_t *attr)
  631. {
  632. if (!attr) {
  633. return EINVAL;
  634. }
  635. memset(attr, 0, sizeof(*attr));
  636. attr->type = PTHREAD_MUTEX_NORMAL;
  637. attr->is_initialized = 1;
  638. return 0;
  639. }
  640. int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
  641. {
  642. if (!attr) {
  643. return EINVAL;
  644. }
  645. attr->is_initialized = 0;
  646. return 0;
  647. }
  648. int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
  649. {
  650. if (!attr) {
  651. return EINVAL;
  652. }
  653. *type = attr->type;
  654. return 0;
  655. }
  656. int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
  657. {
  658. if (!attr) {
  659. return EINVAL;
  660. }
  661. pthread_mutexattr_t tmp_attr = {.type = type};
  662. int res = mutexattr_check(&tmp_attr);
  663. if (!res) {
  664. attr->type = type;
  665. }
  666. return res;
  667. }
  668. /***************** ATTRIBUTES ******************/
  669. int pthread_attr_init(pthread_attr_t *attr)
  670. {
  671. if (attr) {
  672. /* Nothing to allocate. Set everything to default */
  673. memset(attr, 0, sizeof(*attr));
  674. attr->stacksize = CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT;
  675. attr->detachstate = PTHREAD_CREATE_JOINABLE;
  676. return 0;
  677. }
  678. return EINVAL;
  679. }
  680. int pthread_attr_destroy(pthread_attr_t *attr)
  681. {
  682. /* Nothing to deallocate. Reset everything to default */
  683. return pthread_attr_init(attr);
  684. }
  685. int pthread_attr_getstacksize(const pthread_attr_t *attr, size_t *stacksize)
  686. {
  687. if (attr) {
  688. *stacksize = attr->stacksize;
  689. return 0;
  690. }
  691. return EINVAL;
  692. }
  693. int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize)
  694. {
  695. if (attr && !(stacksize < PTHREAD_STACK_MIN)) {
  696. attr->stacksize = stacksize;
  697. return 0;
  698. }
  699. return EINVAL;
  700. }
  701. int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate)
  702. {
  703. if (attr) {
  704. *detachstate = attr->detachstate;
  705. return 0;
  706. }
  707. return EINVAL;
  708. }
  709. int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate)
  710. {
  711. if (attr) {
  712. switch (detachstate) {
  713. case PTHREAD_CREATE_DETACHED:
  714. attr->detachstate = PTHREAD_CREATE_DETACHED;
  715. break;
  716. case PTHREAD_CREATE_JOINABLE:
  717. attr->detachstate = PTHREAD_CREATE_JOINABLE;
  718. break;
  719. default:
  720. return EINVAL;
  721. }
  722. return 0;
  723. }
  724. return EINVAL;
  725. }
  726. /* Hook function to force linking this file */
  727. void pthread_include_pthread_impl(void)
  728. {
  729. }