timer_routines.c 15 KB

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