timer_routines.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. /* Helper code for POSIX timer implementation on NPTL.
  2. Copyright (C) 2000-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. Contributed by Kaz Kylheku <kaz@ashi.footprints.net>.
  5. The GNU C Library is free software; you can redistribute it and/or
  6. modify it under the terms of the GNU Lesser General Public License as
  7. published by the Free Software Foundation; either version 2.1 of the
  8. License, or (at your option) any later version.
  9. The GNU C Library is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. Lesser General Public License for more details.
  13. You should have received a copy of the GNU Lesser General Public
  14. License along with the GNU C Library; see the file COPYING.LIB. If
  15. not, see <http://www.gnu.org/licenses/>. */
  16. #include <assert.h>
  17. #include <errno.h>
  18. #include <pthread.h>
  19. #include <stddef.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <sysdep.h>
  23. #include <time.h>
  24. #include <unistd.h>
  25. #include <sys/syscall.h>
  26. #include "posix-timer.h"
  27. #include <timer_routines.h>
  28. #ifndef DELAYTIMER_MAX
  29. # define DELAYTIMER_MAX INT_MAX
  30. #endif
  31. /* Number of threads used. */
  32. #define THREAD_MAXNODES 16
  33. /* Array containing the descriptors for the used threads. */
  34. static struct thread_node thread_array[THREAD_MAXNODES];
  35. /* Static array with the structures for all the timers. */
  36. struct timer_node __timer_array[TIMER_MAX];
  37. /* Global lock to protect operation on the lists. */
  38. pthread_mutex_t __timer_mutex = PTHREAD_MUTEX_INITIALIZER;
  39. /* Variable to protext initialization. */
  40. pthread_once_t __timer_init_once_control = PTHREAD_ONCE_INIT;
  41. /* Nonzero if initialization of timer implementation failed. */
  42. int __timer_init_failed;
  43. /* Node for the thread used to deliver signals. */
  44. struct thread_node __timer_signal_thread_rclk;
  45. /* Lists to keep free and used timers and threads. */
  46. static struct list_head timer_free_list;
  47. static struct list_head thread_free_list;
  48. static struct list_head thread_active_list;
  49. #ifdef __NR_rt_sigqueueinfo
  50. extern int __syscall_rt_sigqueueinfo (int, int, siginfo_t *);
  51. #endif
  52. /* List handling functions. */
  53. static inline void
  54. list_append (struct list_head *list, struct list_head *newp)
  55. {
  56. newp->prev = list->prev;
  57. newp->next = list;
  58. list->prev->next = newp;
  59. list->prev = newp;
  60. }
  61. static inline void
  62. list_insbefore (struct list_head *list, struct list_head *newp)
  63. {
  64. list_append (list, newp);
  65. }
  66. /*
  67. * Like list_unlink_ip, except that calling it on a node that
  68. * is already unlinked is disastrous rather than a noop.
  69. */
  70. static inline void
  71. list_unlink (struct list_head *list)
  72. {
  73. struct list_head *lnext = list->next, *lprev = list->prev;
  74. lnext->prev = lprev;
  75. lprev->next = lnext;
  76. }
  77. static inline struct list_head *
  78. list_first (struct list_head *list)
  79. {
  80. return list->next;
  81. }
  82. static inline struct list_head *
  83. list_null (struct list_head *list)
  84. {
  85. return list;
  86. }
  87. static inline struct list_head *
  88. list_next (struct list_head *list)
  89. {
  90. return list->next;
  91. }
  92. static inline int
  93. list_isempty (struct list_head *list)
  94. {
  95. return list->next == list;
  96. }
  97. /* Functions build on top of the list functions. */
  98. static inline struct thread_node *
  99. thread_links2ptr (struct list_head *list)
  100. {
  101. return (struct thread_node *) ((char *) list
  102. - offsetof (struct thread_node, links));
  103. }
  104. static inline struct timer_node *
  105. timer_links2ptr (struct list_head *list)
  106. {
  107. return (struct timer_node *) ((char *) list
  108. - offsetof (struct timer_node, links));
  109. }
  110. /* Initialize a newly allocated thread structure. */
  111. static void
  112. thread_init (struct thread_node *thread, const pthread_attr_t *attr, clockid_t clock_id)
  113. {
  114. if (attr != NULL)
  115. thread->attr = *attr;
  116. else
  117. {
  118. pthread_attr_init (&thread->attr);
  119. pthread_attr_setdetachstate (&thread->attr, PTHREAD_CREATE_DETACHED);
  120. }
  121. thread->exists = 0;
  122. INIT_LIST_HEAD (&thread->timer_queue);
  123. pthread_cond_init (&thread->cond, 0);
  124. thread->current_timer = 0;
  125. thread->captured = pthread_self ();
  126. thread->clock_id = clock_id;
  127. }
  128. /* Initialize the global lists, and acquire global resources. Error
  129. reporting is done by storing a non-zero value to the global variable
  130. timer_init_failed. */
  131. static void
  132. init_module (void)
  133. {
  134. int i;
  135. INIT_LIST_HEAD (&timer_free_list);
  136. INIT_LIST_HEAD (&thread_free_list);
  137. INIT_LIST_HEAD (&thread_active_list);
  138. for (i = 0; i < TIMER_MAX; ++i)
  139. {
  140. list_append (&timer_free_list, &__timer_array[i].links);
  141. __timer_array[i].inuse = TIMER_FREE;
  142. }
  143. for (i = 0; i < THREAD_MAXNODES; ++i)
  144. list_append (&thread_free_list, &thread_array[i].links);
  145. thread_init (&__timer_signal_thread_rclk, 0, CLOCK_REALTIME);
  146. }
  147. /* This is a handler executed in a child process after a fork()
  148. occurs. It reinitializes the module, resetting all of the data
  149. structures to their initial state. The mutex is initialized in
  150. case it was locked in the parent process. */
  151. static void
  152. reinit_after_fork (void)
  153. {
  154. init_module ();
  155. pthread_mutex_init (&__timer_mutex, 0);
  156. }
  157. /* Called once form pthread_once in timer_init. This initializes the
  158. module and ensures that reinit_after_fork will be executed in any
  159. child process. */
  160. void
  161. __timer_init_once (void)
  162. {
  163. init_module ();
  164. pthread_atfork (0, 0, reinit_after_fork);
  165. }
  166. /* Deinitialize a thread that is about to be deallocated. */
  167. static void
  168. thread_deinit (struct thread_node *thread)
  169. {
  170. assert (list_isempty (&thread->timer_queue));
  171. pthread_cond_destroy (&thread->cond);
  172. }
  173. /* Allocate a thread structure from the global free list. Global
  174. mutex lock must be held by caller. The thread is moved to
  175. the active list. */
  176. struct thread_node *
  177. __timer_thread_alloc (const pthread_attr_t *desired_attr, clockid_t clock_id)
  178. {
  179. struct list_head *node = list_first (&thread_free_list);
  180. if (node != list_null (&thread_free_list))
  181. {
  182. struct thread_node *thread = thread_links2ptr (node);
  183. list_unlink (node);
  184. thread_init (thread, desired_attr, clock_id);
  185. list_append (&thread_active_list, node);
  186. return thread;
  187. }
  188. return 0;
  189. }
  190. /* Return a thread structure to the global free list. Global lock
  191. must be held by caller. */
  192. void
  193. __timer_thread_dealloc (struct thread_node *thread)
  194. {
  195. thread_deinit (thread);
  196. list_unlink (&thread->links);
  197. list_append (&thread_free_list, &thread->links);
  198. }
  199. /* Each of our threads which terminates executes this cleanup
  200. handler. We never terminate threads ourselves; if a thread gets here
  201. it means that the evil application has killed it. If the thread has
  202. timers, these require servicing and so we must hire a replacement
  203. thread right away. We must also unblock another thread that may
  204. have been waiting for this thread to finish servicing a timer (see
  205. timer_delete()). */
  206. static void
  207. thread_cleanup (void *val)
  208. {
  209. if (val != NULL)
  210. {
  211. struct thread_node *thread = val;
  212. /* How did the signal thread get killed? */
  213. assert (thread != &__timer_signal_thread_rclk);
  214. pthread_mutex_lock (&__timer_mutex);
  215. thread->exists = 0;
  216. /* We are no longer processing a timer event. */
  217. thread->current_timer = 0;
  218. if (list_isempty (&thread->timer_queue))
  219. __timer_thread_dealloc (thread);
  220. else
  221. (void) __timer_thread_start (thread);
  222. pthread_mutex_unlock (&__timer_mutex);
  223. /* Unblock potentially blocked timer_delete(). */
  224. pthread_cond_broadcast (&thread->cond);
  225. }
  226. }
  227. /* Handle a timer which is supposed to go off now. */
  228. static void
  229. thread_expire_timer (struct thread_node *self, struct timer_node *timer)
  230. {
  231. self->current_timer = timer; /* Lets timer_delete know timer is running. */
  232. pthread_mutex_unlock (&__timer_mutex);
  233. switch (__builtin_expect (timer->event.sigev_notify, SIGEV_SIGNAL))
  234. {
  235. case SIGEV_NONE:
  236. break;
  237. case SIGEV_SIGNAL:
  238. #ifdef __NR_rt_sigqueueinfo
  239. {
  240. siginfo_t info;
  241. /* First, clear the siginfo_t structure, so that we don't pass our
  242. stack content to other tasks. */
  243. memset (&info, 0, sizeof (siginfo_t));
  244. /* We must pass the information about the data in a siginfo_t
  245. value. */
  246. info.si_signo = timer->event.sigev_signo;
  247. info.si_code = SI_TIMER;
  248. info.si_pid = timer->creator_pid;
  249. info.si_uid = getuid ();
  250. info.si_value = timer->event.sigev_value;
  251. INLINE_SYSCALL (rt_sigqueueinfo, 3, info.si_pid, info.si_signo, &info);
  252. }
  253. #else
  254. if (pthread_kill (self->captured, timer->event.sigev_signo) != 0)
  255. {
  256. if (pthread_kill (self->id, timer->event.sigev_signo) != 0)
  257. abort ();
  258. }
  259. #endif
  260. break;
  261. case SIGEV_THREAD:
  262. timer->event.sigev_notify_function (timer->event.sigev_value);
  263. break;
  264. default:
  265. assert (! "unknown event");
  266. break;
  267. }
  268. pthread_mutex_lock (&__timer_mutex);
  269. self->current_timer = 0;
  270. pthread_cond_broadcast (&self->cond);
  271. }
  272. /* Thread function; executed by each timer thread. The job of this
  273. function is to wait on the thread's timer queue and expire the
  274. timers in chronological order as close to their scheduled time as
  275. possible. */
  276. static void
  277. __attribute__ ((noreturn))
  278. thread_func (void *arg)
  279. {
  280. struct thread_node *self = arg;
  281. /* Register cleanup handler, in case rogue application terminates
  282. this thread. (This cannot happen to __timer_signal_thread, which
  283. doesn't invoke application callbacks). */
  284. pthread_cleanup_push (thread_cleanup, self);
  285. pthread_mutex_lock (&__timer_mutex);
  286. while (1)
  287. {
  288. struct list_head *first;
  289. struct timer_node *timer = NULL;
  290. /* While the timer queue is not empty, inspect the first node. */
  291. first = list_first (&self->timer_queue);
  292. if (first != list_null (&self->timer_queue))
  293. {
  294. struct timespec now;
  295. timer = timer_links2ptr (first);
  296. /* This assumes that the elements of the list of one thread
  297. are all for the same clock. */
  298. __clock_gettime (timer->clock, &now);
  299. while (1)
  300. {
  301. /* If the timer is due or overdue, remove it from the queue.
  302. If it's a periodic timer, re-compute its new time and
  303. requeue it. Either way, perform the timer expiry. */
  304. if (timespec_compare (&now, &timer->expirytime) < 0)
  305. break;
  306. list_unlink_ip (first);
  307. if (__builtin_expect (timer->value.it_interval.tv_sec, 0) != 0
  308. || timer->value.it_interval.tv_nsec != 0)
  309. {
  310. timer->overrun_count = 0;
  311. timespec_add (&timer->expirytime, &timer->expirytime,
  312. &timer->value.it_interval);
  313. while (timespec_compare (&timer->expirytime, &now) < 0)
  314. {
  315. timespec_add (&timer->expirytime, &timer->expirytime,
  316. &timer->value.it_interval);
  317. if (timer->overrun_count < DELAYTIMER_MAX)
  318. ++timer->overrun_count;
  319. }
  320. __timer_thread_queue_timer (self, timer);
  321. }
  322. thread_expire_timer (self, timer);
  323. first = list_first (&self->timer_queue);
  324. if (first == list_null (&self->timer_queue))
  325. break;
  326. timer = timer_links2ptr (first);
  327. }
  328. }
  329. /* If the queue is not empty, wait until the expiry time of the
  330. first node. Otherwise wait indefinitely. Insertions at the
  331. head of the queue must wake up the thread by broadcasting
  332. this condition variable. */
  333. if (timer != NULL)
  334. pthread_cond_timedwait (&self->cond, &__timer_mutex,
  335. &timer->expirytime);
  336. else
  337. pthread_cond_wait (&self->cond, &__timer_mutex);
  338. }
  339. /* This macro will never be executed since the while loop loops
  340. forever - but we have to add it for proper nesting. */
  341. pthread_cleanup_pop (1);
  342. }
  343. /* Enqueue a timer in wakeup order in the thread's timer queue.
  344. Returns 1 if the timer was inserted at the head of the queue,
  345. causing the queue's next wakeup time to change. */
  346. int
  347. __timer_thread_queue_timer (struct thread_node *thread,
  348. struct timer_node *insert)
  349. {
  350. struct list_head *iter;
  351. int athead = 1;
  352. for (iter = list_first (&thread->timer_queue);
  353. iter != list_null (&thread->timer_queue);
  354. iter = list_next (iter))
  355. {
  356. struct timer_node *timer = timer_links2ptr (iter);
  357. if (timespec_compare (&insert->expirytime, &timer->expirytime) < 0)
  358. break;
  359. athead = 0;
  360. }
  361. list_insbefore (iter, &insert->links);
  362. return athead;
  363. }
  364. /* Start a thread and associate it with the given thread node. Global
  365. lock must be held by caller. */
  366. int
  367. __timer_thread_start (struct thread_node *thread)
  368. {
  369. int retval = 1;
  370. sigset_t set, oset;
  371. assert (!thread->exists);
  372. thread->exists = 1;
  373. sigfillset (&set);
  374. pthread_sigmask (SIG_SETMASK, &set, &oset);
  375. if (pthread_create (&thread->id, &thread->attr,
  376. (void *(*) (void *)) thread_func, thread) != 0)
  377. {
  378. thread->exists = 0;
  379. retval = -1;
  380. }
  381. pthread_sigmask (SIG_SETMASK, &oset, NULL);
  382. return retval;
  383. }
  384. void
  385. __timer_thread_wakeup (struct thread_node *thread)
  386. {
  387. pthread_cond_broadcast (&thread->cond);
  388. }
  389. /* Search the list of active threads and find one which has matching
  390. attributes. Global mutex lock must be held by caller. */
  391. struct thread_node *
  392. __timer_thread_find_matching (const pthread_attr_t *desired_attr,
  393. clockid_t desired_clock_id)
  394. {
  395. struct list_head *iter = list_first (&thread_active_list);
  396. while (iter != list_null (&thread_active_list))
  397. {
  398. struct thread_node *candidate = thread_links2ptr (iter);
  399. if (thread_attr_compare (desired_attr, &candidate->attr)
  400. && desired_clock_id == candidate->clock_id)
  401. return candidate;
  402. iter = list_next (iter);
  403. }
  404. return NULL;
  405. }
  406. /* Grab a free timer structure from the global free list. The global
  407. lock must be held by the caller. */
  408. struct timer_node *
  409. __timer_alloc (void)
  410. {
  411. struct list_head *node = list_first (&timer_free_list);
  412. if (node != list_null (&timer_free_list))
  413. {
  414. struct timer_node *timer = timer_links2ptr (node);
  415. list_unlink_ip (node);
  416. timer->inuse = TIMER_INUSE;
  417. timer->refcount = 1;
  418. return timer;
  419. }
  420. return NULL;
  421. }
  422. /* Return a timer structure to the global free list. The global lock
  423. must be held by the caller. */
  424. void
  425. __timer_dealloc (struct timer_node *timer)
  426. {
  427. assert (timer->refcount == 0);
  428. timer->thread = NULL; /* Break association between timer and thread. */
  429. timer->inuse = TIMER_FREE;
  430. list_append (&timer_free_list, &timer->links);
  431. }
  432. /* Thread cancellation handler which unlocks a mutex. */
  433. void
  434. __timer_mutex_cancel_handler (void *arg)
  435. {
  436. pthread_mutex_unlock (arg);
  437. }