semtimedop implementation for Linux/m68k.
[glibc.git] / linuxthreads / sysdeps / pthread / timer_routines.c
blobb88c5e055699dde528aef275360dd67ab3517e27
1 /* Helper code for POSIX timer implementation on LinuxThreads.
2 Copyright (C) 2000, 2001, 2002 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"
35 /* Number of threads used. */
36 #define THREAD_MAXNODES 16
38 /* Array containing the descriptors for the used threads. */
39 static struct thread_node thread_array[THREAD_MAXNODES];
41 /* Static array with the structures for all the timers. */
42 struct timer_node __timer_array[TIMER_MAX];
44 /* Global lock to protect operation on the lists. */
45 pthread_mutex_t __timer_mutex = PTHREAD_MUTEX_INITIALIZER;
47 /* Variable to protext initialization. */
48 pthread_once_t __timer_init_once_control = PTHREAD_ONCE_INIT;
50 /* Nonzero if initialization of timer implementation failed. */
51 int __timer_init_failed;
53 /* Node for the thread used to deliver signals. */
54 struct thread_node __timer_signal_thread_rclk;
55 #ifdef _POSIX_CPUTIME
56 struct thread_node __timer_signal_thread_pclk;
57 #endif
58 #ifdef _POSIX_THREAD_CPUTIME
59 struct thread_node __timer_signal_thread_tclk;
60 #endif
62 /* Lists to keep free and used timers and threads. */
63 struct list_links timer_free_list;
64 struct list_links thread_free_list;
65 struct list_links thread_active_list;
68 #ifdef __NR_rt_sigqueueinfo
69 extern int __syscall_rt_sigqueueinfo (int, int, siginfo_t *);
70 #endif
73 /* List handling functions. */
74 static inline void
75 list_init (struct list_links *list)
77 list->next = list->prev = list;
80 static inline void
81 list_append (struct list_links *list, struct list_links *newp)
83 newp->prev = list->prev;
84 newp->next = list;
85 list->prev->next = newp;
86 list->prev = newp;
89 static inline void
90 list_insbefore (struct list_links *list, struct list_links *newp)
92 list_append (list, newp);
96 * Like list_unlink_ip, except that calling it on a node that
97 * is already unlinked is disastrous rather than a noop.
100 static inline void
101 list_unlink (struct list_links *list)
103 struct list_links *lnext = list->next, *lprev = list->prev;
105 lnext->prev = lprev;
106 lprev->next = lnext;
109 static inline struct list_links *
110 list_first (struct list_links *list)
112 return list->next;
115 static inline struct list_links *
116 list_null (struct list_links *list)
118 return list;
121 static inline struct list_links *
122 list_next (struct list_links *list)
124 return list->next;
127 static inline int
128 list_isempty (struct list_links *list)
130 return list->next == list;
134 /* Functions build on top of the list functions. */
135 static inline struct thread_node *
136 thread_links2ptr (struct list_links *list)
138 return (struct thread_node *) ((char *) list
139 - offsetof (struct thread_node, links));
142 static inline struct timer_node *
143 timer_links2ptr (struct list_links *list)
145 return (struct timer_node *) ((char *) list
146 - offsetof (struct timer_node, links));
150 /* Initialize a newly allocated thread structure. */
151 static void
152 thread_init (struct thread_node *thread, const pthread_attr_t *attr, clockid_t clock_id)
154 if (attr != NULL)
155 thread->attr = *attr;
156 else
158 pthread_attr_init (&thread->attr);
159 pthread_attr_setdetachstate (&thread->attr, PTHREAD_CREATE_DETACHED);
162 thread->exists = 0;
163 list_init (&thread->timer_queue);
164 pthread_cond_init (&thread->cond, 0);
165 thread->current_timer = 0;
166 thread->captured = pthread_self ();
167 thread->clock_id = clock_id;
171 /* Initialize the global lists, and acquire global resources. Error
172 reporting is done by storing a non-zero value to the global variable
173 timer_init_failed. */
174 static void
175 init_module (void)
177 int i;
179 list_init (&timer_free_list);
180 list_init (&thread_free_list);
181 list_init (&thread_active_list);
183 for (i = 0; i < TIMER_MAX; ++i)
185 list_append (&timer_free_list, &__timer_array[i].links);
186 __timer_array[i].inuse = TIMER_FREE;
189 for (i = 0; i < THREAD_MAXNODES; ++i)
190 list_append (&thread_free_list, &thread_array[i].links);
192 thread_init (&__timer_signal_thread_rclk, 0, CLOCK_REALTIME);
193 #ifdef _POSIX_CPUTIME
194 thread_init (&__timer_signal_thread_pclk, 0, CLOCK_PROCESS_CPUTIME_ID);
195 #endif
196 #ifdef _POSIX_THREAD_CPUTIME
197 thread_init (&__timer_signal_thread_tclk, 0, CLOCK_THREAD_CPUTIME_ID);
198 #endif
202 /* This is a handler executed in a child process after a fork()
203 occurs. It reinitializes the module, resetting all of the data
204 structures to their initial state. The mutex is initialized in
205 case it was locked in the parent process. */
206 static void
207 reinit_after_fork (void)
209 init_module ();
210 pthread_mutex_init (&__timer_mutex, 0);
214 /* Called once form pthread_once in timer_init. This initializes the
215 module and ensures that reinit_after_fork will be executed in any
216 child process. */
217 void
218 __timer_init_once (void)
220 init_module ();
221 pthread_atfork (0, 0, reinit_after_fork);
225 /* Deinitialize a thread that is about to be deallocated. */
226 static void
227 thread_deinit (struct thread_node *thread)
229 assert (list_isempty (&thread->timer_queue));
230 pthread_cond_destroy (&thread->cond);
234 /* Allocate a thread structure from the global free list. Global
235 mutex lock must be held by caller. The thread is moved to
236 the active list. */
237 struct thread_node *
238 __timer_thread_alloc (const pthread_attr_t *desired_attr, clockid_t clock_id)
240 struct list_links *node = list_first (&thread_free_list);
242 if (node != list_null (&thread_free_list))
244 struct thread_node *thread = thread_links2ptr (node);
245 list_unlink (node);
246 thread_init (thread, desired_attr, clock_id);
247 list_append (&thread_active_list, node);
248 return thread;
251 return 0;
255 /* Return a thread structure to the global free list. Global lock
256 must be held by caller. */
257 void
258 __timer_thread_dealloc (struct thread_node *thread)
260 thread_deinit (thread);
261 list_unlink (&thread->links);
262 list_append (&thread_free_list, &thread->links);
266 /* Each of our threads which terminates executes this cleanup
267 handler. We never terminate threads ourselves; if a thread gets here
268 it means that the evil application has killed it. If the thread has
269 timers, these require servicing and so we must hire a replacement
270 thread right away. We must also unblock another thread that may
271 have been waiting for this thread to finish servicing a timer (see
272 timer_delete()). */
274 static void
275 thread_cleanup (void *val)
277 if (val != NULL)
279 struct thread_node *thread = val;
281 /* How did the signal thread get killed? */
282 assert (thread != &__timer_signal_thread_rclk);
283 #ifdef _POSIX_CPUTIME
284 assert (thread != &__timer_signal_thread_pclk);
285 #endif
286 #ifdef _POSIX_THREAD_CPUTIME
287 assert (thread != &__timer_signal_thread_tclk);
288 #endif
290 pthread_mutex_lock (&__timer_mutex);
292 thread->exists = 0;
294 /* We are no longer processing a timer event. */
295 thread->current_timer = 0;
297 if (list_isempty (&thread->timer_queue))
298 __timer_thread_dealloc (thread);
299 else
300 (void) __timer_thread_start (thread);
302 pthread_mutex_unlock (&__timer_mutex);
304 /* Unblock potentially blocked timer_delete(). */
305 pthread_cond_broadcast (&thread->cond);
310 /* Handle a timer which is supposed to go off now. */
311 static void
312 thread_expire_timer (struct thread_node *self, struct timer_node *timer)
314 self->current_timer = timer; /* Lets timer_delete know timer is running. */
316 pthread_mutex_unlock (&__timer_mutex);
318 switch (__builtin_expect (timer->event.sigev_notify, SIGEV_SIGNAL))
320 case SIGEV_NONE:
321 assert (! "timer_create should never have created such a timer");
322 break;
324 case SIGEV_SIGNAL:
325 #ifdef __NR_rt_sigqueueinfo
327 siginfo_t info;
329 /* First, clear the siginfo_t structure, so that we don't pass our
330 stack content to other tasks. */
331 memset (&info, 0, sizeof (siginfo_t));
332 /* We must pass the information about the data in a siginfo_t
333 value. */
334 info.si_signo = timer->event.sigev_signo;
335 info.si_code = SI_TIMER;
336 info.si_pid = timer->creator_pid;
337 info.si_uid = getuid ();
338 info.si_value = timer->event.sigev_value;
340 INLINE_SYSCALL (rt_sigqueueinfo, 3, info.si_pid, info.si_signo, &info);
342 #else
343 if (pthread_kill (self->captured, timer->event.sigev_signo) != 0)
345 if (pthread_kill (self->id, timer->event.sigev_signo) != 0)
346 abort ();
348 #endif
349 break;
351 case SIGEV_THREAD:
352 timer->event.sigev_notify_function (timer->event.sigev_value);
353 break;
355 default:
356 assert (! "unknown event");
357 break;
360 pthread_mutex_lock (&__timer_mutex);
362 self->current_timer = 0;
364 pthread_cond_broadcast (&self->cond);
368 /* Thread function; executed by each timer thread. The job of this
369 function is to wait on the thread's timer queue and expire the
370 timers in chronological order as close to their scheduled time as
371 possible. */
372 static void
373 __attribute__ ((noreturn))
374 thread_func (void *arg)
376 struct thread_node *self = arg;
378 /* Register cleanup handler, in case rogue application terminates
379 this thread. (This cannot happen to __timer_signal_thread, which
380 doesn't invoke application callbacks). */
382 pthread_cleanup_push (thread_cleanup, self);
384 pthread_mutex_lock (&__timer_mutex);
386 while (1)
388 struct list_links *first;
389 struct timer_node *timer = NULL;
391 /* While the timer queue is not empty, inspect the first node. */
392 first = list_first (&self->timer_queue);
393 if (first != list_null (&self->timer_queue))
395 struct timespec now;
397 timer = timer_links2ptr (first);
399 /* This assumes that the elements of the list of one thread
400 are all for the same clock. */
401 clock_gettime (timer->clock, &now);
403 while (1)
405 /* If the timer is due or overdue, remove it from the queue.
406 If it's a periodic timer, re-compute its new time and
407 requeue it. Either way, perform the timer expiry. */
408 if (timespec_compare (&now, &timer->expirytime) < 0)
409 break;
411 list_unlink_ip (first);
413 if (__builtin_expect (timer->value.it_interval.tv_sec, 0) != 0
414 || timer->value.it_interval.tv_nsec != 0)
416 timer->overrun_count = 0;
417 timespec_add (&timer->expirytime, &timer->expirytime,
418 &timer->value.it_interval);
419 while (timespec_compare (&timer->expirytime, &now) < 0)
421 timespec_add (&timer->expirytime, &timer->expirytime,
422 &timer->value.it_interval);
423 if (timer->overrun_count < DELAYTIMER_MAX)
424 ++timer->overrun_count;
426 __timer_thread_queue_timer (self, timer);
429 thread_expire_timer (self, timer);
431 first = list_first (&self->timer_queue);
432 if (first == list_null (&self->timer_queue))
433 break;
435 timer = timer_links2ptr (first);
439 /* If the queue is not empty, wait until the expiry time of the
440 first node. Otherwise wait indefinitely. Insertions at the
441 head of the queue must wake up the thread by broadcasting
442 this condition variable. */
443 if (timer != NULL)
444 pthread_cond_timedwait (&self->cond, &__timer_mutex,
445 &timer->expirytime);
446 else
447 pthread_cond_wait (&self->cond, &__timer_mutex);
449 /* This macro will never be executed since the while loop loops
450 forever - but we have to add it for proper nesting. */
451 pthread_cleanup_pop (1);
455 /* Enqueue a timer in wakeup order in the thread's timer queue.
456 Returns 1 if the timer was inserted at the head of the queue,
457 causing the queue's next wakeup time to change. */
460 __timer_thread_queue_timer (struct thread_node *thread,
461 struct timer_node *insert)
463 struct list_links *iter;
464 int athead = 1;
466 for (iter = list_first (&thread->timer_queue);
467 iter != list_null (&thread->timer_queue);
468 iter = list_next (iter))
470 struct timer_node *timer = timer_links2ptr (iter);
472 if (timespec_compare (&insert->expirytime, &timer->expirytime) < 0)
473 break;
474 athead = 0;
477 list_insbefore (iter, &insert->links);
478 return athead;
482 /* Start a thread and associate it with the given thread node. Global
483 lock must be held by caller. */
485 __timer_thread_start (struct thread_node *thread)
487 int retval = 1;
489 assert (!thread->exists);
490 thread->exists = 1;
492 if (pthread_create (&thread->id, &thread->attr,
493 (void *(*) (void *)) thread_func, thread) != 0)
495 thread->exists = 0;
496 retval = -1;
499 return retval;
503 void
504 __timer_thread_wakeup (struct thread_node *thread)
506 pthread_cond_broadcast (&thread->cond);
510 /* Compare two pthread_attr_t thread attributes for exact equality.
511 Returns 1 if they are equal, otherwise zero if they are not equal or
512 contain illegal values. This version is LinuxThreads-specific for
513 performance reason. One could use the access functions to get the
514 values of all the fields of the attribute structure. */
515 static int
516 thread_attr_compare (const pthread_attr_t *left, const pthread_attr_t *right)
518 return (left->__detachstate == right->__detachstate
519 && left->__schedpolicy == right->__schedpolicy
520 && (left->__schedparam.sched_priority
521 == right->__schedparam.sched_priority)
522 && left->__inheritsched == right->__inheritsched
523 && left->__scope == right->__scope);
527 /* Search the list of active threads and find one which has matching
528 attributes. Global mutex lock must be held by caller. */
529 struct thread_node *
530 __timer_thread_find_matching (const pthread_attr_t *desired_attr,
531 clockid_t desired_clock_id)
533 struct list_links *iter = list_first (&thread_active_list);
535 while (iter != list_null (&thread_active_list))
537 struct thread_node *candidate = thread_links2ptr (iter);
539 if (thread_attr_compare (desired_attr, &candidate->attr)
540 && desired_clock_id == candidate->clock_id)
542 list_unlink (iter);
543 return candidate;
546 iter = list_next (iter);
549 return NULL;
553 /* Grab a free timer structure from the global free list. The global
554 lock must be held by the caller. */
555 struct timer_node *
556 __timer_alloc (void)
558 struct list_links *node = list_first (&timer_free_list);
560 if (node != list_null (&timer_free_list))
562 struct timer_node *timer = timer_links2ptr (node);
563 list_unlink_ip (node);
564 timer->inuse = TIMER_INUSE;
565 timer->refcount = 1;
566 return timer;
569 return NULL;
573 /* Return a timer structure to the global free list. The global lock
574 must be held by the caller. */
575 void
576 __timer_dealloc (struct timer_node *timer)
578 assert (timer->refcount == 0);
579 timer->thread = NULL; /* Break association between timer and thread. */
580 timer->inuse = TIMER_FREE;
581 list_append (&timer_free_list, &timer->links);
585 /* Thread cancellation handler which unlocks a mutex. */
586 void
587 __timer_mutex_cancel_handler (void *arg)
589 pthread_mutex_unlock (arg);