semaphore.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. /*
  2. * Copyright (c) 2006-2021, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2010-10-26 Bernard the first version
  9. */
  10. #include <rtthread.h>
  11. #include <string.h>
  12. #include <fcntl.h>
  13. #include <sys/errno.h>
  14. #include "semaphore.h"
  15. static sem_t *posix_sem_list = RT_NULL;
  16. static struct rt_semaphore posix_sem_lock;
  17. /* initialize posix semaphore */
  18. static int posix_sem_system_init(void)
  19. {
  20. rt_sem_init(&posix_sem_lock, "psem", 1, RT_IPC_FLAG_FIFO);
  21. return 0;
  22. }
  23. INIT_COMPONENT_EXPORT(posix_sem_system_init);
  24. /**
  25. * @brief Inserts a semaphore into the linked list of semaphores.
  26. * @param psem Pointer to the semaphore structure to be inserted.
  27. *
  28. * @note This function inserts the specified semaphore into a linked list of semaphores.
  29. * The newly inserted semaphore becomes the head of the list.
  30. * It updates the 'next' pointer of the semaphore structure to link it to the
  31. * current head of the list and then sets the head of the list to point to the
  32. * newly inserted semaphore.
  33. */
  34. rt_inline void posix_sem_insert(sem_t *psem)
  35. {
  36. psem->next = posix_sem_list;
  37. posix_sem_list = psem;
  38. }
  39. /**
  40. * @brief Deletes a semaphore from the linked list of semaphores.
  41. * @param psem Pointer to the semaphore structure to be deleted.
  42. *
  43. * @note This function deletes the specified semaphore from a linked list of semaphores.
  44. * If the semaphore to be deleted is the head of the list, it updates the head of the list
  45. * to point to the next semaphore. Otherwise, it traverses the list to find the semaphore
  46. * to be deleted and updates the 'next' pointer of the preceding semaphore to skip over
  47. * the semaphore to be deleted.
  48. * After deleting the semaphore, it also deletes the underlying RT-Thread semaphore if it exists
  49. * and frees the memory associated with the semaphore structure if it's not unnamed.
  50. */
  51. static void posix_sem_delete(sem_t *psem)
  52. {
  53. sem_t *iter;
  54. if (posix_sem_list == psem)
  55. {
  56. posix_sem_list = psem->next;
  57. rt_sem_delete(psem->sem);
  58. if(psem->unamed == 0)
  59. rt_free(psem);
  60. return;
  61. }
  62. for (iter = posix_sem_list; iter->next != RT_NULL; iter = iter->next)
  63. {
  64. if (iter->next == psem)
  65. {
  66. /* delete this mq */
  67. if (psem->next != RT_NULL)
  68. iter->next = psem->next;
  69. else
  70. iter->next = RT_NULL;
  71. /* delete RT-Thread mqueue */
  72. rt_sem_delete(psem->sem);
  73. if(psem->unamed == 0)
  74. rt_free(psem);
  75. return ;
  76. }
  77. }
  78. }
  79. /**
  80. * @brief Finds a semaphore by name in the linked list of semaphores.
  81. * @param name Pointer to the name of the semaphore to be found.
  82. * @return Pointer to the semaphore structure if found; otherwise, RT_NULL.
  83. *
  84. * @note This function searches for a semaphore with the specified name in the linked list of semaphores.
  85. * It iterates through the list and compares the name of each semaphore with the given name.
  86. * If a semaphore with a matching name is found, a pointer to its structure is returned.
  87. * Otherwise, RT_NULL is returned to indicate that no semaphore with the given name was found.
  88. */
  89. static sem_t *posix_sem_find(const char* name)
  90. {
  91. sem_t *iter;
  92. rt_object_t object;
  93. for (iter = posix_sem_list; iter != RT_NULL; iter = iter->next)
  94. {
  95. object = (rt_object_t)iter->sem;
  96. if (strncmp(object->name, name, RT_NAME_MAX) == 0)
  97. {
  98. return iter;
  99. }
  100. }
  101. return RT_NULL;
  102. }
  103. /**
  104. * @brief Closes a POSIX semaphore.
  105. * @param sem Pointer to the semaphore to be closed.
  106. * @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
  107. *
  108. * @note This function decreases the reference count of the specified semaphore.
  109. * If the reference count reaches zero, the semaphore is removed from the list
  110. * of POSIX semaphores if it was unlinked. The memory associated with the semaphore
  111. * is not immediately freed; instead, it will be freed when the last reference to
  112. * the semaphore is released.
  113. */
  114. int sem_close(sem_t *sem)
  115. {
  116. if (sem == RT_NULL)
  117. {
  118. rt_set_errno(EINVAL);
  119. return -1;
  120. }
  121. /* lock posix semaphore list */
  122. rt_sem_take(&posix_sem_lock, RT_WAITING_FOREVER);
  123. sem->refcount --;
  124. if (sem->refcount == 0)
  125. {
  126. /* delete from posix semaphore list */
  127. if (sem->unlinked)
  128. posix_sem_delete(sem);
  129. sem = RT_NULL;
  130. }
  131. rt_sem_release(&posix_sem_lock);
  132. return 0;
  133. }
  134. RTM_EXPORT(sem_close);
  135. /**
  136. * @brief Destroys a POSIX semaphore.
  137. * @param sem Pointer to the semaphore to be destroyed.
  138. * @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
  139. *
  140. * @note This function destroys an unnamed POSIX semaphore.
  141. * It first checks if the semaphore pointer is valid and if the semaphore is unnamed.
  142. * If the semaphore is still in use (i.e., there are threads waiting on it),
  143. * the function returns with an error code (EBUSY) without destroying the semaphore.
  144. * Otherwise, it removes the semaphore from the list of POSIX semaphores and frees
  145. * the memory associated with the semaphore structure.
  146. */
  147. int sem_destroy(sem_t *sem)
  148. {
  149. if ((!sem) || !(sem->unamed))
  150. {
  151. rt_set_errno(EINVAL);
  152. return -1;
  153. }
  154. /* lock posix semaphore list */
  155. rt_sem_take(&posix_sem_lock, RT_WAITING_FOREVER);
  156. if(rt_list_len(&sem->sem->parent.suspend_thread) != 0)
  157. {
  158. rt_sem_release(&posix_sem_lock);
  159. rt_set_errno(EBUSY);
  160. return -1;
  161. }
  162. /* destroy an unamed posix semaphore */
  163. posix_sem_delete(sem);
  164. rt_sem_release(&posix_sem_lock);
  165. return 0;
  166. }
  167. RTM_EXPORT(sem_destroy);
  168. /**
  169. * @brief Unlinks a named POSIX semaphore.
  170. * @param name Pointer to the name of the semaphore to be unlinked.
  171. * @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
  172. *
  173. * @note This function unlinks a named POSIX semaphore identified by the given name.
  174. * It first searches for the semaphore with the specified name in the list of
  175. * POSIX semaphores. If the semaphore is found, it marks the semaphore as unlinked.
  176. * If the reference count of the semaphore is zero, indicating that no threads are
  177. * currently using the semaphore, it removes the semaphore from the list and frees
  178. * the associated memory. Otherwise, the semaphore is not immediately removed; it
  179. * will be removed when its reference count reaches zero.
  180. */
  181. int sem_unlink(const char *name)
  182. {
  183. sem_t *psem;
  184. /* lock posix semaphore list */
  185. rt_sem_take(&posix_sem_lock, RT_WAITING_FOREVER);
  186. psem = posix_sem_find(name);
  187. if (psem != RT_NULL)
  188. {
  189. psem->unlinked = 1;
  190. if (psem->refcount == 0)
  191. {
  192. /* remove this semaphore */
  193. posix_sem_delete(psem);
  194. }
  195. rt_sem_release(&posix_sem_lock);
  196. return 0;
  197. }
  198. rt_sem_release(&posix_sem_lock);
  199. /* no this entry */
  200. rt_set_errno(ENOENT);
  201. return -1;
  202. }
  203. RTM_EXPORT(sem_unlink);
  204. /**
  205. * @brief Retrieves the value of a POSIX semaphore.
  206. * @param sem Pointer to the semaphore.
  207. * @param sval Pointer to an integer where the semaphore value will be stored.
  208. * @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
  209. *
  210. * @note This function retrieves the current value of the specified POSIX semaphore.
  211. * It copies the semaphore value into the memory location pointed to by sval.
  212. * If either sem or sval is a null pointer, the function sets errno to EINVAL
  213. * to indicate an invalid argument and returns -1.
  214. */
  215. int sem_getvalue(sem_t *sem, int *sval)
  216. {
  217. if (!sem || !sval)
  218. {
  219. rt_set_errno(EINVAL);
  220. return -1;
  221. }
  222. *sval = sem->sem->value;
  223. return 0;
  224. }
  225. RTM_EXPORT(sem_getvalue);
  226. /**
  227. * @brief Initializes a POSIX semaphore.
  228. * @param sem Pointer to the semaphore structure to be initialized.
  229. * @param pshared Flag indicating whether the semaphore is to be shared between processes.
  230. * @param value Initial value of the semaphore.
  231. * @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
  232. *
  233. * @note This function initializes a POSIX semaphore with the specified initial value.
  234. * If sem is a null pointer, the function sets errno to EINVAL to indicate an invalid argument and returns -1.
  235. * The pshared parameter is not used in this implementation, as all semaphores are created as local (unshared).
  236. * The value parameter specifies the initial value of the semaphore.
  237. * The semaphore is given a unique name using a static counter, and it is created using the RT-Thread semaphore
  238. * creation function rt_sem_create(). If memory allocation fails during semaphore creation, errno is set to ENOMEM.
  239. * After successful initialization, the semaphore structure is inserted into the linked list of POSIX semaphores.
  240. */
  241. int sem_init(sem_t *sem, int pshared, unsigned int value)
  242. {
  243. char name[RT_NAME_MAX];
  244. static rt_uint16_t psem_number = 0;
  245. if (sem == RT_NULL)
  246. {
  247. rt_set_errno(EINVAL);
  248. return -1;
  249. }
  250. rt_snprintf(name, sizeof(name), "psem%02d", psem_number++);
  251. sem->sem = rt_sem_create(name, value, RT_IPC_FLAG_FIFO);
  252. if (sem->sem == RT_NULL)
  253. {
  254. rt_set_errno(ENOMEM);
  255. return -1;
  256. }
  257. /* initialize posix semaphore */
  258. sem->refcount = 1;
  259. sem->unlinked = 0;
  260. sem->unamed = 1;
  261. /* lock posix semaphore list */
  262. rt_sem_take(&posix_sem_lock, RT_WAITING_FOREVER);
  263. posix_sem_insert(sem);
  264. rt_sem_release(&posix_sem_lock);
  265. return 0;
  266. }
  267. RTM_EXPORT(sem_init);
  268. /**
  269. * @brief Opens or creates a POSIX semaphore.
  270. * @param name Pointer to the name of the semaphore.
  271. * @param oflag Bitwise OR of flags indicating the operation mode.
  272. * @param ... Additional arguments (optional).
  273. * @return Upon successful completion, returns a pointer to the semaphore;
  274. * otherwise, returns RT_NULL and sets errno to indicate the error.
  275. *
  276. * @note This function opens or creates a POSIX semaphore specified by the name argument.
  277. * If the oflag argument includes O_CREAT, the semaphore is created if it does not already exist.
  278. * Additional arguments may include the mode (not used in this implementation) and the initial value of the semaphore.
  279. * If the oflag argument includes O_EXCL along with O_CREAT, the function fails if the semaphore already exists.
  280. * If memory allocation fails during semaphore creation, errno is set to ENFILE.
  281. * After successful creation or opening, the semaphore's reference count is incremented, and it is inserted into
  282. * the linked list of POSIX semaphores. If the semaphore already exists and is successfully opened, its reference
  283. * count is incremented. If the semaphore cannot be opened or created for any reason, errno is set to indicate the error,
  284. * and the function returns RT_NULL.
  285. */
  286. sem_t *sem_open(const char *name, int oflag, ...)
  287. {
  288. sem_t* sem;
  289. va_list arg;
  290. mode_t mode;
  291. unsigned int value;
  292. sem = RT_NULL;
  293. /* lock posix semaphore list */
  294. rt_sem_take(&posix_sem_lock, RT_WAITING_FOREVER);
  295. if (oflag & O_CREAT)
  296. {
  297. va_start(arg, oflag);
  298. mode = (mode_t) va_arg( arg, unsigned int); mode = mode;
  299. value = va_arg( arg, unsigned int);
  300. va_end(arg);
  301. if (oflag & O_EXCL)
  302. {
  303. if (posix_sem_find(name) != RT_NULL)
  304. {
  305. rt_set_errno(EEXIST);
  306. goto __return;
  307. }
  308. }
  309. sem = (sem_t*) rt_malloc (sizeof(struct posix_sem));
  310. if (sem == RT_NULL)
  311. {
  312. rt_set_errno(ENFILE);
  313. goto __return;
  314. }
  315. /* create RT-Thread semaphore */
  316. sem->sem = rt_sem_create(name, value, RT_IPC_FLAG_FIFO);
  317. if (sem->sem == RT_NULL) /* create failed */
  318. {
  319. rt_set_errno(ENFILE);
  320. goto __return;
  321. }
  322. /* initialize reference count */
  323. sem->refcount = 1;
  324. sem->unlinked = 0;
  325. sem->unamed = 0;
  326. /* insert semaphore to posix semaphore list */
  327. posix_sem_insert(sem);
  328. }
  329. else
  330. {
  331. /* find semaphore */
  332. sem = posix_sem_find(name);
  333. if (sem != RT_NULL)
  334. {
  335. sem->refcount ++; /* increase reference count */
  336. }
  337. else
  338. {
  339. rt_set_errno(ENOENT);
  340. goto __return;
  341. }
  342. }
  343. rt_sem_release(&posix_sem_lock);
  344. return sem;
  345. __return:
  346. /* release lock */
  347. rt_sem_release(&posix_sem_lock);
  348. /* release allocated memory */
  349. if (sem != RT_NULL)
  350. {
  351. /* delete RT-Thread semaphore */
  352. if (sem->sem != RT_NULL)
  353. rt_sem_delete(sem->sem);
  354. rt_free(sem);
  355. }
  356. return RT_NULL;
  357. }
  358. RTM_EXPORT(sem_open);
  359. /**
  360. * @brief Posts (increments) a POSIX semaphore.
  361. * @param sem Pointer to the semaphore.
  362. * @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
  363. *
  364. * @note This function increments the value of the specified POSIX semaphore by one.
  365. * If sem is a null pointer, errno is set to EINVAL to indicate an invalid argument, and the function returns -1.
  366. * The semaphore is released using the RT-Thread semaphore release function rt_sem_release().
  367. * If the semaphore release operation succeeds, the function returns 0; otherwise, errno is set to EINVAL,
  368. * indicating an error, and the function returns -1.
  369. */
  370. int sem_post(sem_t *sem)
  371. {
  372. rt_err_t result;
  373. if (!sem)
  374. {
  375. rt_set_errno(EINVAL);
  376. return -1;
  377. }
  378. result = rt_sem_release(sem->sem);
  379. if (result == RT_EOK)
  380. return 0;
  381. rt_set_errno(EINVAL);
  382. return -1;
  383. }
  384. RTM_EXPORT(sem_post);
  385. /**
  386. * @brief Waits for a POSIX semaphore with a timeout.
  387. * @param sem Pointer to the semaphore.
  388. * @param abs_timeout Pointer to the absolute timeout value.
  389. * @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
  390. *
  391. * @note This function waits for the specified POSIX semaphore to become available within the specified timeout.
  392. * If either sem or abs_timeout is a null pointer, the function returns EINVAL, indicating an invalid argument.
  393. * The abs_timeout parameter specifies an absolute timeout value based on the CLOCK_REALTIME clock.
  394. * The timeout is converted to RT-Thread ticks using the rt_timespec_to_tick() function.
  395. * The semaphore is waited upon using the RT-Thread semaphore take function rt_sem_take().
  396. * If the semaphore is successfully acquired within the specified timeout, the function returns 0.
  397. * If the timeout expires before the semaphore becomes available, errno is set to ETIMEDOUT,
  398. * and the function returns -1. If the semaphore wait operation is interrupted by a signal,
  399. * errno is set to EINTR, and the function returns -1.
  400. */
  401. int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout)
  402. {
  403. rt_err_t result;
  404. rt_int32_t tick;
  405. if (!sem || !abs_timeout)
  406. return EINVAL;
  407. /* calculate os tick */
  408. tick = rt_timespec_to_tick(abs_timeout);
  409. result = rt_sem_take(sem->sem, tick);
  410. if (result == -RT_ETIMEOUT)
  411. {
  412. rt_set_errno(ETIMEDOUT);
  413. return -1;
  414. }
  415. if (result == RT_EOK)
  416. return 0;
  417. rt_set_errno(EINTR);
  418. return -1;
  419. }
  420. RTM_EXPORT(sem_timedwait);
  421. /**
  422. * @brief Attempts to wait for a POSIX semaphore without blocking.
  423. * @param sem Pointer to the semaphore.
  424. * @return Upon successful completion, returns 0 if the semaphore was acquired;
  425. * otherwise, returns -1 and sets errno to indicate the error.
  426. *
  427. * @note This function attempts to acquire the specified POSIX semaphore without blocking.
  428. * If sem is a null pointer, errno is set to EINVAL to indicate an invalid argument, and the function returns -1.
  429. * The semaphore is waited upon using the RT-Thread semaphore take function rt_sem_take() with a timeout of 0,
  430. * meaning that the function does not block if the semaphore is not available.
  431. * If the semaphore is successfully acquired, the function returns 0. If the semaphore is not available,
  432. * errno is set to EAGAIN to indicate that the operation would result in blocking, and the function returns -1.
  433. * If the semaphore wait operation is interrupted by a signal, errno is set to EINTR, and the function returns -1.
  434. */
  435. int sem_trywait(sem_t *sem)
  436. {
  437. rt_err_t result;
  438. if (!sem)
  439. {
  440. rt_set_errno(EINVAL);
  441. return -1;
  442. }
  443. result = rt_sem_take(sem->sem, 0);
  444. if (result == -RT_ETIMEOUT)
  445. {
  446. rt_set_errno(EAGAIN);
  447. return -1;
  448. }
  449. if (result == RT_EOK)
  450. return 0;
  451. rt_set_errno(EINTR);
  452. return -1;
  453. }
  454. RTM_EXPORT(sem_trywait);
  455. /**
  456. * @brief Waits indefinitely for a POSIX semaphore to become available.
  457. * @param sem Pointer to the semaphore.
  458. * @return Upon successful completion, returns 0; otherwise, returns -1 and sets errno to indicate the error.
  459. *
  460. * @note This function waits indefinitely for the specified POSIX semaphore to become available.
  461. * If sem is a null pointer, errno is set to EINVAL to indicate an invalid argument, and the function returns -1.
  462. * The semaphore is waited upon using the RT-Thread semaphore take function rt_sem_take() with a timeout
  463. * value of RT_WAITING_FOREVER, indicating an infinite wait time.
  464. * If the semaphore is successfully acquired, the function returns 0. If the semaphore wait operation is interrupted
  465. * by a signal, errno is set to EINTR, and the function returns -1.
  466. */
  467. int sem_wait(sem_t *sem)
  468. {
  469. rt_err_t result;
  470. if (!sem)
  471. {
  472. rt_set_errno(EINVAL);
  473. return -1;
  474. }
  475. result = rt_sem_take(sem->sem, RT_WAITING_FOREVER);
  476. if (result == RT_EOK)
  477. return 0;
  478. rt_set_errno(EINTR);
  479. return -1;
  480. }
  481. RTM_EXPORT(sem_wait);