timer_routines.c 15 KB

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