2.9
[glibc/nacl-glibc.git] / nptl / sysdeps / pthread / timer_routines.c
blob8d5b1d13a5cc26abf40e915738db9c1b15c4984d
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>.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public License as
8 published by the Free Software Foundation; either version 2.1 of the
9 License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; see the file COPYING.LIB. If not,
18 write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19 Boston, MA 02111-1307, USA. */
21 #include <assert.h>
22 #include <errno.h>
23 #include <pthread.h>
24 #include <stddef.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <sysdep.h>
28 #include <time.h>
29 #include <unistd.h>
30 #include <sys/syscall.h>
32 #include "posix-timer.h"
33 #include <pthreadP.h>
36 /* Number of threads used. */
37 #define THREAD_MAXNODES 16
39 /* Array containing the descriptors for the used threads. */
40 static struct thread_node thread_array[THREAD_MAXNODES];
42 /* Static array with the structures for all the timers. */
43 struct timer_node __timer_array[TIMER_MAX];
45 /* Global lock to protect operation on the lists. */
46 pthread_mutex_t __timer_mutex = PTHREAD_MUTEX_INITIALIZER;
48 /* Variable to protext initialization. */
49 pthread_once_t __timer_init_once_control = PTHREAD_ONCE_INIT;
51 /* Nonzero if initialization of timer implementation failed. */
52 int __timer_init_failed;
54 /* Node for the thread used to deliver signals. */
55 struct thread_node __timer_signal_thread_rclk;
57 /* Lists to keep free and used timers and threads. */
58 struct list_links timer_free_list;
59 struct list_links thread_free_list;
60 struct list_links thread_active_list;
63 #ifdef __NR_rt_sigqueueinfo
64 extern int __syscall_rt_sigqueueinfo (int, int, siginfo_t *);
65 #endif
68 /* List handling functions. */
69 static inline void
70 list_init (struct list_links *list)
72 list->next = list->prev = list;
75 static inline void
76 list_append (struct list_links *list, struct list_links *newp)
78 newp->prev = list->prev;
79 newp->next = list;
80 list->prev->next = newp;
81 list->prev = newp;
84 static inline void
85 list_insbefore (struct list_links *list, struct list_links *newp)
87 list_append (list, newp);
91 * Like list_unlink_ip, except that calling it on a node that
92 * is already unlinked is disastrous rather than a noop.
95 static inline void
96 list_unlink (struct list_links *list)
98 struct list_links *lnext = list->next, *lprev = list->prev;
100 lnext->prev = lprev;
101 lprev->next = lnext;
104 static inline struct list_links *
105 list_first (struct list_links *list)
107 return list->next;
110 static inline struct list_links *
111 list_null (struct list_links *list)
113 return list;
116 static inline struct list_links *
117 list_next (struct list_links *list)
119 return list->next;
122 static inline int
123 list_isempty (struct list_links *list)
125 return list->next == list;
129 /* Functions build on top of the list functions. */
130 static inline struct thread_node *
131 thread_links2ptr (struct list_links *list)
133 return (struct thread_node *) ((char *) list
134 - offsetof (struct thread_node, links));
137 static inline struct timer_node *
138 timer_links2ptr (struct list_links *list)
140 return (struct timer_node *) ((char *) list
141 - offsetof (struct timer_node, links));
145 /* Initialize a newly allocated thread structure. */
146 static void
147 thread_init (struct thread_node *thread, const pthread_attr_t *attr, clockid_t clock_id)
149 if (attr != NULL)
150 thread->attr = *attr;
151 else
153 pthread_attr_init (&thread->attr);
154 pthread_attr_setdetachstate (&thread->attr, PTHREAD_CREATE_DETACHED);
157 thread->exists = 0;
158 list_init (&thread->timer_queue);
159 pthread_cond_init (&thread->cond, 0);
160 thread->current_timer = 0;
161 thread->captured = pthread_self ();
162 thread->clock_id = clock_id;
166 /* Initialize the global lists, and acquire global resources. Error
167 reporting is done by storing a non-zero value to the global variable
168 timer_init_failed. */
169 static void
170 init_module (void)
172 int i;
174 list_init (&timer_free_list);
175 list_init (&thread_free_list);
176 list_init (&thread_active_list);
178 for (i = 0; i < TIMER_MAX; ++i)
180 list_append (&timer_free_list, &__timer_array[i].links);
181 __timer_array[i].inuse = TIMER_FREE;
184 for (i = 0; i < THREAD_MAXNODES; ++i)
185 list_append (&thread_free_list, &thread_array[i].links);
187 thread_init (&__timer_signal_thread_rclk, 0, CLOCK_REALTIME);
191 /* This is a handler executed in a child process after a fork()
192 occurs. It reinitializes the module, resetting all of the data
193 structures to their initial state. The mutex is initialized in
194 case it was locked in the parent process. */
195 static void
196 reinit_after_fork (void)
198 init_module ();
199 pthread_mutex_init (&__timer_mutex, 0);
203 /* Called once form pthread_once in timer_init. This initializes the
204 module and ensures that reinit_after_fork will be executed in any
205 child process. */
206 void
207 __timer_init_once (void)
209 init_module ();
210 pthread_atfork (0, 0, reinit_after_fork);
214 /* Deinitialize a thread that is about to be deallocated. */
215 static void
216 thread_deinit (struct thread_node *thread)
218 assert (list_isempty (&thread->timer_queue));
219 pthread_cond_destroy (&thread->cond);
223 /* Allocate a thread structure from the global free list. Global
224 mutex lock must be held by caller. The thread is moved to
225 the active list. */
226 struct thread_node *
227 __timer_thread_alloc (const pthread_attr_t *desired_attr, clockid_t clock_id)
229 struct list_links *node = list_first (&thread_free_list);
231 if (node != list_null (&thread_free_list))
233 struct thread_node *thread = thread_links2ptr (node);
234 list_unlink (node);
235 thread_init (thread, desired_attr, clock_id);
236 list_append (&thread_active_list, node);
237 return thread;
240 return 0;
244 /* Return a thread structure to the global free list. Global lock
245 must be held by caller. */
246 void
247 __timer_thread_dealloc (struct thread_node *thread)
249 thread_deinit (thread);
250 list_unlink (&thread->links);
251 list_append (&thread_free_list, &thread->links);
255 /* Each of our threads which terminates executes this cleanup
256 handler. We never terminate threads ourselves; if a thread gets here
257 it means that the evil application has killed it. If the thread has
258 timers, these require servicing and so we must hire a replacement
259 thread right away. We must also unblock another thread that may
260 have been waiting for this thread to finish servicing a timer (see
261 timer_delete()). */
263 static void
264 thread_cleanup (void *val)
266 if (val != NULL)
268 struct thread_node *thread = val;
270 /* How did the signal thread get killed? */
271 assert (thread != &__timer_signal_thread_rclk);
273 pthread_mutex_lock (&__timer_mutex);
275 thread->exists = 0;
277 /* We are no longer processing a timer event. */
278 thread->current_timer = 0;
280 if (list_isempty (&thread->timer_queue))
281 __timer_thread_dealloc (thread);
282 else
283 (void) __timer_thread_start (thread);
285 pthread_mutex_unlock (&__timer_mutex);
287 /* Unblock potentially blocked timer_delete(). */
288 pthread_cond_broadcast (&thread->cond);
293 /* Handle a timer which is supposed to go off now. */
294 static void
295 thread_expire_timer (struct thread_node *self, struct timer_node *timer)
297 self->current_timer = timer; /* Lets timer_delete know timer is running. */
299 pthread_mutex_unlock (&__timer_mutex);
301 switch (__builtin_expect (timer->event.sigev_notify, SIGEV_SIGNAL))
303 case SIGEV_NONE:
304 break;
306 case SIGEV_SIGNAL:
307 #ifdef __NR_rt_sigqueueinfo
309 siginfo_t info;
311 /* First, clear the siginfo_t structure, so that we don't pass our
312 stack content to other tasks. */
313 memset (&info, 0, sizeof (siginfo_t));
314 /* We must pass the information about the data in a siginfo_t
315 value. */
316 info.si_signo = timer->event.sigev_signo;
317 info.si_code = SI_TIMER;
318 info.si_pid = timer->creator_pid;
319 info.si_uid = getuid ();
320 info.si_value = timer->event.sigev_value;
322 INLINE_SYSCALL (rt_sigqueueinfo, 3, info.si_pid, info.si_signo, &info);
324 #else
325 if (pthread_kill (self->captured, timer->event.sigev_signo) != 0)
327 if (pthread_kill (self->id, timer->event.sigev_signo) != 0)
328 abort ();
330 #endif
331 break;
333 case SIGEV_THREAD:
334 timer->event.sigev_notify_function (timer->event.sigev_value);
335 break;
337 default:
338 assert (! "unknown event");
339 break;
342 pthread_mutex_lock (&__timer_mutex);
344 self->current_timer = 0;
346 pthread_cond_broadcast (&self->cond);
350 /* Thread function; executed by each timer thread. The job of this
351 function is to wait on the thread's timer queue and expire the
352 timers in chronological order as close to their scheduled time as
353 possible. */
354 static void
355 __attribute__ ((noreturn))
356 thread_func (void *arg)
358 struct thread_node *self = arg;
360 /* Register cleanup handler, in case rogue application terminates
361 this thread. (This cannot happen to __timer_signal_thread, which
362 doesn't invoke application callbacks). */
364 pthread_cleanup_push (thread_cleanup, self);
366 pthread_mutex_lock (&__timer_mutex);
368 while (1)
370 struct list_links *first;
371 struct timer_node *timer = NULL;
373 /* While the timer queue is not empty, inspect the first node. */
374 first = list_first (&self->timer_queue);
375 if (first != list_null (&self->timer_queue))
377 struct timespec now;
379 timer = timer_links2ptr (first);
381 /* This assumes that the elements of the list of one thread
382 are all for the same clock. */
383 clock_gettime (timer->clock, &now);
385 while (1)
387 /* If the timer is due or overdue, remove it from the queue.
388 If it's a periodic timer, re-compute its new time and
389 requeue it. Either way, perform the timer expiry. */
390 if (timespec_compare (&now, &timer->expirytime) < 0)
391 break;
393 list_unlink_ip (first);
395 if (__builtin_expect (timer->value.it_interval.tv_sec, 0) != 0
396 || timer->value.it_interval.tv_nsec != 0)
398 timer->overrun_count = 0;
399 timespec_add (&timer->expirytime, &timer->expirytime,
400 &timer->value.it_interval);
401 while (timespec_compare (&timer->expirytime, &now) < 0)
403 timespec_add (&timer->expirytime, &timer->expirytime,
404 &timer->value.it_interval);
405 if (timer->overrun_count < DELAYTIMER_MAX)
406 ++timer->overrun_count;
408 __timer_thread_queue_timer (self, timer);
411 thread_expire_timer (self, timer);
413 first = list_first (&self->timer_queue);
414 if (first == list_null (&self->timer_queue))
415 break;
417 timer = timer_links2ptr (first);
421 /* If the queue is not empty, wait until the expiry time of the
422 first node. Otherwise wait indefinitely. Insertions at the
423 head of the queue must wake up the thread by broadcasting
424 this condition variable. */
425 if (timer != NULL)
426 pthread_cond_timedwait (&self->cond, &__timer_mutex,
427 &timer->expirytime);
428 else
429 pthread_cond_wait (&self->cond, &__timer_mutex);
431 /* This macro will never be executed since the while loop loops
432 forever - but we have to add it for proper nesting. */
433 pthread_cleanup_pop (1);
437 /* Enqueue a timer in wakeup order in the thread's timer queue.
438 Returns 1 if the timer was inserted at the head of the queue,
439 causing the queue's next wakeup time to change. */
442 __timer_thread_queue_timer (struct thread_node *thread,
443 struct timer_node *insert)
445 struct list_links *iter;
446 int athead = 1;
448 for (iter = list_first (&thread->timer_queue);
449 iter != list_null (&thread->timer_queue);
450 iter = list_next (iter))
452 struct timer_node *timer = timer_links2ptr (iter);
454 if (timespec_compare (&insert->expirytime, &timer->expirytime) < 0)
455 break;
456 athead = 0;
459 list_insbefore (iter, &insert->links);
460 return athead;
464 /* Start a thread and associate it with the given thread node. Global
465 lock must be held by caller. */
467 __timer_thread_start (struct thread_node *thread)
469 int retval = 1;
471 assert (!thread->exists);
472 thread->exists = 1;
474 if (pthread_create (&thread->id, &thread->attr,
475 (void *(*) (void *)) thread_func, thread) != 0)
477 thread->exists = 0;
478 retval = -1;
481 return retval;
485 void
486 __timer_thread_wakeup (struct thread_node *thread)
488 pthread_cond_broadcast (&thread->cond);
492 /* Compare two pthread_attr_t thread attributes for exact equality.
493 Returns 1 if they are equal, otherwise zero if they are not equal
494 or contain illegal values. This version is NPTL-specific for
495 performance reason. One could use the access functions to get the
496 values of all the fields of the attribute structure. */
497 static int
498 thread_attr_compare (const pthread_attr_t *left, const pthread_attr_t *right)
500 struct pthread_attr *ileft = (struct pthread_attr *) left;
501 struct pthread_attr *iright = (struct pthread_attr *) right;
503 return (ileft->flags == iright->flags
504 && ileft->schedpolicy == iright->schedpolicy
505 && (ileft->schedparam.sched_priority
506 == iright->schedparam.sched_priority)
507 && ileft->guardsize == iright->guardsize
508 && ileft->stackaddr == iright->stackaddr
509 && ileft->stacksize == iright->stacksize
510 && ((ileft->cpuset == NULL && iright->cpuset == NULL)
511 || (ileft->cpuset != NULL && iright->cpuset != NULL
512 && ileft->cpusetsize == iright->cpusetsize
513 && memcmp (ileft->cpuset, iright->cpuset,
514 ileft->cpusetsize) == 0)));
518 /* Search the list of active threads and find one which has matching
519 attributes. Global mutex lock must be held by caller. */
520 struct thread_node *
521 __timer_thread_find_matching (const pthread_attr_t *desired_attr,
522 clockid_t desired_clock_id)
524 struct list_links *iter = list_first (&thread_active_list);
526 while (iter != list_null (&thread_active_list))
528 struct thread_node *candidate = thread_links2ptr (iter);
530 if (thread_attr_compare (desired_attr, &candidate->attr)
531 && desired_clock_id == candidate->clock_id)
532 return candidate;
534 iter = list_next (iter);
537 return NULL;
541 /* Grab a free timer structure from the global free list. The global
542 lock must be held by the caller. */
543 struct timer_node *
544 __timer_alloc (void)
546 struct list_links *node = list_first (&timer_free_list);
548 if (node != list_null (&timer_free_list))
550 struct timer_node *timer = timer_links2ptr (node);
551 list_unlink_ip (node);
552 timer->inuse = TIMER_INUSE;
553 timer->refcount = 1;
554 return timer;
557 return NULL;
561 /* Return a timer structure to the global free list. The global lock
562 must be held by the caller. */
563 void
564 __timer_dealloc (struct timer_node *timer)
566 assert (timer->refcount == 0);
567 timer->thread = NULL; /* Break association between timer and thread. */
568 timer->inuse = TIMER_FREE;
569 list_append (&timer_free_list, &timer->links);
573 /* Thread cancellation handler which unlocks a mutex. */
574 void
575 __timer_mutex_cancel_handler (void *arg)
577 pthread_mutex_unlock (arg);