]> rtime.felk.cvut.cz Git - l4.git/blob - l4/pkg/uclibc/lib/contrib/uclibc/libpthread/linuxthreads.old/pthread.c
update
[l4.git] / l4 / pkg / uclibc / lib / contrib / uclibc / libpthread / linuxthreads.old / pthread.c
1 /* Linuxthreads - a simple clone()-based implementation of Posix        */
2 /* threads for Linux.                                                   */
3 /* Copyright (C) 1996 Xavier Leroy (Xavier.Leroy@inria.fr)              */
4 /*                                                                      */
5 /* This program is free software; you can redistribute it and/or        */
6 /* modify it under the terms of the GNU Library General Public License  */
7 /* as published by the Free Software Foundation; either version 2       */
8 /* of the License, or (at your option) any later version.               */
9 /*                                                                      */
10 /* This program is distributed in the hope that it will be useful,      */
11 /* but WITHOUT ANY WARRANTY; without even the implied warranty of       */
12 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        */
13 /* GNU Library General Public License for more details.                 */
14
15 /* Thread creation, initialization, and basic low-level routines */
16
17 #include <errno.h>
18 #include <netdb.h>      /* for h_errno */
19 #include <stddef.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <fcntl.h>
25 #include <sys/wait.h>
26 #include <sys/resource.h>
27 #include "pthread.h"
28 #include "internals.h"
29 #include "spinlock.h"
30 #include "restart.h"
31 #include "debug.h"      /* added to linuxthreads -StS */
32
33
34 /* Mods for uClibc: Some includes */
35 #include <signal.h>
36 #include <sys/types.h>
37 #include <sys/syscall.h>
38
39 libpthread_hidden_proto(waitpid)
40 libpthread_hidden_proto(raise)
41
42 /* These variables are used by the setup code.  */
43 extern int _errno;
44 extern int _h_errno;
45
46
47 /* Descriptor of the initial thread */
48
49 struct _pthread_descr_struct __pthread_initial_thread = {
50   &__pthread_initial_thread,  /* pthread_descr p_nextlive */
51   &__pthread_initial_thread,  /* pthread_descr p_prevlive */
52   NULL,                       /* pthread_descr p_nextwaiting */
53   NULL,                       /* pthread_descr p_nextlock */
54   PTHREAD_THREADS_MAX,        /* pthread_t p_tid */
55   0,                          /* int p_pid */
56   0,                          /* int p_priority */
57   &__pthread_handles[0].h_lock, /* struct _pthread_fastlock * p_lock */
58   0,                          /* int p_signal */
59   NULL,                       /* sigjmp_buf * p_signal_buf */
60   NULL,                       /* sigjmp_buf * p_cancel_buf */
61   0,                          /* char p_terminated */
62   0,                          /* char p_detached */
63   0,                          /* char p_exited */
64   NULL,                       /* void * p_retval */
65   0,                          /* int p_retval */
66   NULL,                       /* pthread_descr p_joining */
67   NULL,                       /* struct _pthread_cleanup_buffer * p_cleanup */
68   0,                          /* char p_cancelstate */
69   0,                          /* char p_canceltype */
70   0,                          /* char p_canceled */
71   &_errno,                       /* int *p_errnop */
72   0,                          /* int p_errno */
73   &_h_errno,                       /* int *p_h_errnop */
74   0,                          /* int p_h_errno */
75   NULL,                       /* char * p_in_sighandler */
76   0,                          /* char p_sigwaiting */
77   PTHREAD_START_ARGS_INITIALIZER, /* struct pthread_start_args p_start_args */
78   {NULL},                     /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
79   {NULL},                     /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
80   0,                          /* int p_userstack */
81   NULL,                       /* void * p_guardaddr */
82   0,                          /* size_t p_guardsize */
83   &__pthread_initial_thread,  /* pthread_descr p_self */
84   0,                          /* Always index 0 */
85   0,                          /* int p_report_events */
86   {{{0, }}, 0, NULL},         /* td_eventbuf_t p_eventbuf */
87   __ATOMIC_INITIALIZER,         /* struct pthread_atomic p_resume_count */
88   0,                          /* char p_woken_by_cancel */
89   0,                          /* char p_condvar_avail */
90   0,                          /* char p_sem_avail */
91   NULL,                       /* struct pthread_extricate_if *p_extricate */
92   NULL,                       /* pthread_readlock_info *p_readlock_list; */
93   NULL,                       /* pthread_readlock_info *p_readlock_free; */
94   0                           /* int p_untracked_readlock_count; */
95 #ifdef __UCLIBC_HAS_XLOCALE__
96   ,
97   &__global_locale_data,      /* __locale_t locale; */
98 #endif /* __UCLIBC_HAS_XLOCALE__ */
99 };
100
101 /* Descriptor of the manager thread; none of this is used but the error
102    variables, the p_pid and p_priority fields,
103    and the address for identification.  */
104 #define manager_thread (&__pthread_manager_thread)
105 struct _pthread_descr_struct __pthread_manager_thread = {
106   NULL,                       /* pthread_descr p_nextlive */
107   NULL,                       /* pthread_descr p_prevlive */
108   NULL,                       /* pthread_descr p_nextwaiting */
109   NULL,                       /* pthread_descr p_nextlock */
110   0,                          /* int p_tid */
111   0,                          /* int p_pid */
112   0,                          /* int p_priority */
113   &__pthread_handles[1].h_lock, /* struct _pthread_fastlock * p_lock */
114   0,                          /* int p_signal */
115   NULL,                       /* sigjmp_buf * p_signal_buf */
116   NULL,                       /* sigjmp_buf * p_cancel_buf */
117   0,                          /* char p_terminated */
118   0,                          /* char p_detached */
119   0,                          /* char p_exited */
120   NULL,                       /* void * p_retval */
121   0,                          /* int p_retval */
122   NULL,                       /* pthread_descr p_joining */
123   NULL,                       /* struct _pthread_cleanup_buffer * p_cleanup */
124   0,                          /* char p_cancelstate */
125   0,                          /* char p_canceltype */
126   0,                          /* char p_canceled */
127   &__pthread_manager_thread.p_errno, /* int *p_errnop */
128   0,                          /* int p_errno */
129   NULL,                       /* int *p_h_errnop */
130   0,                          /* int p_h_errno */
131   NULL,                       /* char * p_in_sighandler */
132   0,                          /* char p_sigwaiting */
133   PTHREAD_START_ARGS_INITIALIZER, /* struct pthread_start_args p_start_args */
134   {NULL},                     /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
135   {NULL},                     /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
136   0,                          /* int p_userstack */
137   NULL,                       /* void * p_guardaddr */
138   0,                          /* size_t p_guardsize */
139   &__pthread_manager_thread,  /* pthread_descr p_self */
140   1,                          /* Always index 1 */
141   0,                          /* int p_report_events */
142   {{{0, }}, 0, NULL},         /* td_eventbuf_t p_eventbuf */
143   __ATOMIC_INITIALIZER,         /* struct pthread_atomic p_resume_count */
144   0,                          /* char p_woken_by_cancel */
145   0,                          /* char p_condvar_avail */
146   0,                          /* char p_sem_avail */
147   NULL,                       /* struct pthread_extricate_if *p_extricate */
148   NULL,                       /* pthread_readlock_info *p_readlock_list; */
149   NULL,                       /* pthread_readlock_info *p_readlock_free; */
150   0                           /* int p_untracked_readlock_count; */
151 #ifdef __UCLIBC_HAS_XLOCALE__
152   ,
153   &__global_locale_data,      /* __locale_t locale; */
154 #endif /* __UCLIBC_HAS_XLOCALE__ */
155 };
156
157 /* Pointer to the main thread (the father of the thread manager thread) */
158 /* Originally, this is the initial thread, but this changes after fork() */
159
160 pthread_descr __pthread_main_thread = &__pthread_initial_thread;
161
162 /* Limit between the stack of the initial thread (above) and the
163    stacks of other threads (below). Aligned on a STACK_SIZE boundary. */
164
165 char *__pthread_initial_thread_bos = NULL;
166
167 #ifndef __ARCH_USE_MMU__
168 /* See nommu notes in internals.h and pthread_initialize() below. */
169 char *__pthread_initial_thread_tos = NULL;
170 char *__pthread_initial_thread_mid = NULL;
171 #endif /* __ARCH_USE_MMU__ */
172
173 /* File descriptor for sending requests to the thread manager. */
174 /* Initially -1, meaning that the thread manager is not running. */
175
176 int __pthread_manager_request = -1;
177
178 /* Other end of the pipe for sending requests to the thread manager. */
179
180 int __pthread_manager_reader;
181
182 /* Limits of the thread manager stack */
183
184 char *__pthread_manager_thread_bos = NULL;
185 char *__pthread_manager_thread_tos = NULL;
186
187 /* For process-wide exit() */
188
189 int __pthread_exit_requested = 0;
190 int __pthread_exit_code = 0;
191
192 /* Communicate relevant LinuxThreads constants to gdb */
193
194 const int __pthread_threads_max = PTHREAD_THREADS_MAX;
195 const int __pthread_sizeof_handle = sizeof(struct pthread_handle_struct);
196 const int __pthread_offsetof_descr = offsetof(struct pthread_handle_struct, h_descr);
197 const int __pthread_offsetof_pid = offsetof(struct _pthread_descr_struct,
198                                             p_pid);
199 const int __linuxthreads_pthread_sizeof_descr
200   = sizeof(struct _pthread_descr_struct);
201
202 const int __linuxthreads_initial_report_events;
203
204 const char __linuxthreads_version[] = VERSION;
205
206 /* Forward declarations */
207 static void pthread_onexit_process(int retcode, void *arg);
208 static void pthread_handle_sigcancel(int sig);
209 static void pthread_handle_sigrestart(int sig);
210 static void pthread_handle_sigdebug(int sig);
211 int __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime);
212
213 /* Signal numbers used for the communication.
214    In these variables we keep track of the used variables.  If the
215    platform does not support any real-time signals we will define the
216    values to some unreasonable value which will signal failing of all
217    the functions below.  */
218 #ifndef __NR_rt_sigaction
219 static int current_rtmin = -1;
220 static int current_rtmax = -1;
221 int __pthread_sig_restart = SIGUSR1;
222 int __pthread_sig_cancel = SIGUSR2;
223 int __pthread_sig_debug;
224 #else
225
226 #if __SIGRTMAX - __SIGRTMIN >= 3
227 static int current_rtmin = __SIGRTMIN + 3;
228 static int current_rtmax = __SIGRTMAX;
229 int __pthread_sig_restart = __SIGRTMIN;
230 int __pthread_sig_cancel = __SIGRTMIN + 1;
231 int __pthread_sig_debug = __SIGRTMIN + 2;
232 void (*__pthread_restart)(pthread_descr) = __pthread_restart_new;
233 void (*__pthread_suspend)(pthread_descr) = __pthread_wait_for_restart_signal;
234 int (*__pthread_timedsuspend)(pthread_descr, const struct timespec *) = __pthread_timedsuspend_new;
235 #else
236 static int current_rtmin = __SIGRTMIN;
237 static int current_rtmax = __SIGRTMAX;
238 int __pthread_sig_restart = SIGUSR1;
239 int __pthread_sig_cancel = SIGUSR2;
240 int __pthread_sig_debug;
241 void (*__pthread_restart)(pthread_descr) = __pthread_restart_old;
242 void (*__pthread_suspend)(pthread_descr) = __pthread_suspend_old;
243 int (*__pthread_timedsuspend)(pthread_descr, const struct timespec *) = __pthread_timedsuspend_old;
244
245 #endif
246
247 /* Return number of available real-time signal with highest priority.  */
248 int __libc_current_sigrtmin (void)
249 {
250     return current_rtmin;
251 }
252
253 /* Return number of available real-time signal with lowest priority.  */
254 int __libc_current_sigrtmax (void)
255 {
256     return current_rtmax;
257 }
258
259 #if 0
260 /* Allocate real-time signal with highest/lowest available
261    priority.  Please note that we don't use a lock since we assume
262    this function to be called at program start.  */
263 int __libc_allocate_rtsig (int high);
264 int __libc_allocate_rtsig (int high)
265 {
266     if (current_rtmin == -1 || current_rtmin > current_rtmax)
267         /* We don't have anymore signal available.  */
268         return -1;
269     return high ? current_rtmin++ : current_rtmax--;
270 }
271 #endif
272 #endif
273
274 /* Initialize the pthread library.
275    Initialization is split in two functions:
276    - a constructor function that blocks the __pthread_sig_restart signal
277      (must do this very early, since the program could capture the signal
278       mask with e.g. sigsetjmp before creating the first thread);
279    - a regular function called from pthread_create when needed. */
280
281 static void pthread_initialize(void) __attribute__((constructor));
282
283 libpthread_hidden_proto(pthread_attr_destroy)
284 libpthread_hidden_proto(pthread_attr_init)
285 libpthread_hidden_proto(pthread_attr_getdetachstate)
286 libpthread_hidden_proto(pthread_attr_setdetachstate)
287 libpthread_hidden_proto(pthread_attr_getinheritsched)
288 libpthread_hidden_proto(pthread_attr_setinheritsched)
289 libpthread_hidden_proto(pthread_attr_setschedparam)
290 libpthread_hidden_proto(pthread_attr_getschedparam)
291 libpthread_hidden_proto(pthread_attr_getschedpolicy)
292 libpthread_hidden_proto(pthread_attr_setschedpolicy)
293 libpthread_hidden_proto(pthread_attr_getscope)
294 libpthread_hidden_proto(pthread_attr_setscope)
295
296 libpthread_hidden_proto(pthread_exit)
297
298 libpthread_hidden_proto(pthread_equal)
299 libpthread_hidden_proto(pthread_self)
300 libpthread_hidden_proto(pthread_getschedparam)
301 libpthread_hidden_proto(pthread_setschedparam)
302
303 libpthread_hidden_proto(pthread_setcancelstate)
304 libpthread_hidden_proto(pthread_setcanceltype)
305 libpthread_hidden_proto(_pthread_cleanup_push_defer)
306 libpthread_hidden_proto(_pthread_cleanup_pop_restore)
307
308 libpthread_hidden_proto(pthread_cond_broadcast)
309 libpthread_hidden_proto(pthread_cond_destroy)
310 libpthread_hidden_proto(pthread_cond_init)
311 libpthread_hidden_proto(pthread_cond_signal)
312 libpthread_hidden_proto(pthread_cond_wait)
313 libpthread_hidden_proto(pthread_cond_timedwait)
314
315 libpthread_hidden_proto(pthread_condattr_destroy)
316 libpthread_hidden_proto(pthread_condattr_init)
317
318 struct pthread_functions __pthread_functions =
319   {
320 #if !defined __UCLIBC_HAS_TLS__ && defined __UCLIBC_HAS_RPC__
321     .ptr_pthread_internal_tsd_set = __pthread_internal_tsd_set,
322     .ptr_pthread_internal_tsd_get = __pthread_internal_tsd_get,
323     .ptr_pthread_internal_tsd_address = __pthread_internal_tsd_address,
324 #endif
325 /*
326     .ptr_pthread_fork = __pthread_fork,
327 */
328     .ptr_pthread_attr_destroy = pthread_attr_destroy,
329     .ptr_pthread_attr_init = pthread_attr_init,
330     .ptr_pthread_attr_getdetachstate = pthread_attr_getdetachstate,
331     .ptr_pthread_attr_setdetachstate = pthread_attr_setdetachstate,
332     .ptr_pthread_attr_getinheritsched = pthread_attr_getinheritsched,
333     .ptr_pthread_attr_setinheritsched = pthread_attr_setinheritsched,
334     .ptr_pthread_attr_getschedparam = pthread_attr_getschedparam,
335     .ptr_pthread_attr_setschedparam = pthread_attr_setschedparam,
336     .ptr_pthread_attr_getschedpolicy = pthread_attr_getschedpolicy,
337     .ptr_pthread_attr_setschedpolicy = pthread_attr_setschedpolicy,
338     .ptr_pthread_attr_getscope = pthread_attr_getscope,
339     .ptr_pthread_attr_setscope = pthread_attr_setscope,
340     .ptr_pthread_condattr_destroy = pthread_condattr_destroy,
341     .ptr_pthread_condattr_init = pthread_condattr_init,
342     .ptr_pthread_cond_broadcast = pthread_cond_broadcast,
343     .ptr_pthread_cond_destroy = pthread_cond_destroy,
344     .ptr_pthread_cond_init = pthread_cond_init,
345     .ptr_pthread_cond_signal = pthread_cond_signal,
346     .ptr_pthread_cond_wait = pthread_cond_wait,
347     .ptr_pthread_cond_timedwait = pthread_cond_timedwait,
348     .ptr_pthread_equal = pthread_equal,
349     .ptr___pthread_exit = pthread_exit,
350     .ptr_pthread_getschedparam = pthread_getschedparam,
351     .ptr_pthread_setschedparam = pthread_setschedparam,
352     .ptr_pthread_mutex_destroy = __pthread_mutex_destroy,
353     .ptr_pthread_mutex_init = __pthread_mutex_init,
354     .ptr_pthread_mutex_lock = __pthread_mutex_lock,
355     .ptr_pthread_mutex_trylock = __pthread_mutex_trylock,
356     .ptr_pthread_mutex_unlock = __pthread_mutex_unlock,
357     .ptr_pthread_self = pthread_self,
358     .ptr_pthread_setcancelstate = pthread_setcancelstate,
359     .ptr_pthread_setcanceltype = pthread_setcanceltype,
360 /*
361     .ptr_pthread_do_exit = pthread_do_exit,
362     .ptr_pthread_thread_self = pthread_thread_self,
363     .ptr_pthread_cleanup_upto = pthread_cleanup_upto,
364     .ptr_pthread_sigaction = pthread_sigaction,
365     .ptr_pthread_sigwait = pthread_sigwait,
366     .ptr_pthread_raise = pthread_raise,
367     .ptr__pthread_cleanup_push = _pthread_cleanup_push,
368     .ptr__pthread_cleanup_pop = _pthread_cleanup_pop,
369 */
370     .ptr__pthread_cleanup_push_defer = __pthread_cleanup_push_defer,
371     .ptr__pthread_cleanup_pop_restore = __pthread_cleanup_pop_restore
372   };
373 #ifdef SHARED
374 # define ptr_pthread_functions &__pthread_functions
375 #else
376 # define ptr_pthread_functions NULL
377 #endif
378
379 static int *__libc_multiple_threads_ptr;
380
381  /* Do some minimal initialization which has to be done during the
382     startup of the C library.  */
383 void __pthread_initialize_minimal(void)
384 {
385     /* If we have special thread_self processing, initialize
386      * that for the main thread now.  */
387 #ifdef INIT_THREAD_SELF
388     INIT_THREAD_SELF(&__pthread_initial_thread, 0);
389 #endif
390
391     __libc_multiple_threads_ptr = __libc_pthread_init (ptr_pthread_functions);
392 }
393
394
395 static void pthread_initialize(void)
396 {
397   struct sigaction sa;
398   sigset_t mask;
399 #ifdef __ARCH_USE_MMU__
400   struct rlimit limit;
401   rlim_t max_stack;
402 #endif
403
404   /* If already done (e.g. by a constructor called earlier!), bail out */
405   if (__pthread_initial_thread_bos != NULL) return;
406 #ifdef TEST_FOR_COMPARE_AND_SWAP
407   /* Test if compare-and-swap is available */
408   __pthread_has_cas = compare_and_swap_is_available();
409 #endif
410   /* For the initial stack, reserve at least STACK_SIZE bytes of stack
411      below the current stack address, and align that on a
412      STACK_SIZE boundary. */
413   __pthread_initial_thread_bos =
414     (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
415   /* Update the descriptor for the initial thread. */
416   __pthread_initial_thread.p_pid = getpid();
417   /* If we have special thread_self processing, initialize that for the
418      main thread now.  */
419 #ifdef INIT_THREAD_SELF
420   INIT_THREAD_SELF(&__pthread_initial_thread, 0);
421 #endif
422   /* The errno/h_errno variable of the main thread are the global ones.  */
423   __pthread_initial_thread.p_errnop = &_errno;
424   __pthread_initial_thread.p_h_errnop = &_h_errno;
425
426 #ifdef __UCLIBC_HAS_XLOCALE__
427   /* The locale of the main thread is the current locale in use. */
428   __pthread_initial_thread.locale = __curlocale_var;
429 #endif /* __UCLIBC_HAS_XLOCALE__ */
430
431  {                         /* uClibc-specific stdio initialization for threads. */
432          FILE *fp;
433
434          _stdio_user_locking = 0;       /* 2 if threading not initialized */
435          for (fp = _stdio_openlist; fp != NULL; fp = fp->__nextopen) {
436                  if (fp->__user_locking != 1) {
437                          fp->__user_locking = 0;
438                  }
439          }
440  }
441
442   /* Play with the stack size limit to make sure that no stack ever grows
443      beyond STACK_SIZE minus two pages (one page for the thread descriptor
444      immediately beyond, and one page to act as a guard page). */
445
446 #ifdef __ARCH_USE_MMU__
447   /* We cannot allocate a huge chunk of memory to mmap all thread stacks later
448    * on a non-MMU system. Thus, we don't need the rlimit either. -StS */
449   getrlimit(RLIMIT_STACK, &limit);
450   max_stack = STACK_SIZE - 2 * getpagesize();
451   if (limit.rlim_cur > max_stack) {
452     limit.rlim_cur = max_stack;
453     setrlimit(RLIMIT_STACK, &limit);
454   }
455 #else
456   /* For non-MMU, the initial thread stack can reside anywhere in memory.
457    * We don't have a way of knowing where the kernel started things -- top
458    * or bottom (well, that isn't exactly true, but the solution is fairly
459    * complex and error prone).  All we can determine here is an address
460    * that lies within that stack.  Save that address as a reference so that
461    * as other thread stacks are created, we can adjust the estimated bounds
462    * of the initial thread's stack appropriately.
463    *
464    * This checking is handled in NOMMU_INITIAL_THREAD_BOUNDS(), so see that
465    * for a few more details.
466    */
467   __pthread_initial_thread_mid = CURRENT_STACK_FRAME;
468   __pthread_initial_thread_tos = (char *) -1;
469   __pthread_initial_thread_bos = (char *) 1; /* set it non-zero so we know we have been here */
470   PDEBUG("initial thread stack bounds: bos=%p, tos=%p\n",
471          __pthread_initial_thread_bos, __pthread_initial_thread_tos);
472 #endif /* __ARCH_USE_MMU__ */
473
474   /* Setup signal handlers for the initial thread.
475      Since signal handlers are shared between threads, these settings
476      will be inherited by all other threads. */
477   memset(&sa, 0, sizeof(sa));
478   sa.sa_handler = pthread_handle_sigrestart;
479   __libc_sigaction(__pthread_sig_restart, &sa, NULL);
480   sa.sa_handler = pthread_handle_sigcancel;
481   sigaddset(&sa.sa_mask, __pthread_sig_restart);
482   __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
483   if (__pthread_sig_debug > 0) {
484       sa.sa_handler = pthread_handle_sigdebug;
485       __sigemptyset(&sa.sa_mask);
486       __libc_sigaction(__pthread_sig_debug, &sa, NULL);
487   }
488   /* Initially, block __pthread_sig_restart. Will be unblocked on demand. */
489   __sigemptyset(&mask);
490   sigaddset(&mask, __pthread_sig_restart);
491   sigprocmask(SIG_BLOCK, &mask, NULL);
492   /* And unblock __pthread_sig_cancel if it has been blocked. */
493   sigdelset(&mask, __pthread_sig_restart);
494   sigaddset(&mask, __pthread_sig_cancel);
495   sigprocmask(SIG_UNBLOCK, &mask, NULL);
496   /* Register an exit function to kill all other threads. */
497   /* Do it early so that user-registered atexit functions are called
498      before pthread_onexit_process. */
499   on_exit(pthread_onexit_process, NULL);
500 }
501
502 void __pthread_initialize(void);
503 void __pthread_initialize(void)
504 {
505   pthread_initialize();
506 }
507
508 int __pthread_initialize_manager(void)
509 {
510   int manager_pipe[2];
511   int pid;
512   int report_events;
513   struct pthread_request request;
514
515   *__libc_multiple_threads_ptr = 1;
516
517   /* If basic initialization not done yet (e.g. we're called from a
518      constructor run before our constructor), do it now */
519   if (__pthread_initial_thread_bos == NULL) pthread_initialize();
520   /* Setup stack for thread manager */
521   __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
522   if (__pthread_manager_thread_bos == NULL) return -1;
523   __pthread_manager_thread_tos =
524     __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;
525
526   /* On non-MMU systems we make sure that the initial thread bounds don't overlap
527    * with the manager stack frame */
528   NOMMU_INITIAL_THREAD_BOUNDS(__pthread_manager_thread_tos,__pthread_manager_thread_bos);
529   PDEBUG("manager stack: size=%ld, bos=%p, tos=%p\n", THREAD_MANAGER_STACK_SIZE,
530          __pthread_manager_thread_bos, __pthread_manager_thread_tos);
531 #if 0
532   PDEBUG("initial stack: estimate bos=%p, tos=%p\n",
533          __pthread_initial_thread_bos, __pthread_initial_thread_tos);
534 #endif
535
536   /* Setup pipe to communicate with thread manager */
537   if (pipe(manager_pipe) == -1) {
538     free(__pthread_manager_thread_bos);
539     return -1;
540   }
541   /* Start the thread manager */
542   pid = 0;
543 #if defined(USE_TLS) && USE_TLS
544   if (__linuxthreads_initial_report_events != 0)
545     THREAD_SETMEM (((pthread_descr) NULL), p_report_events,
546                    __linuxthreads_initial_report_events);
547   report_events = THREAD_GETMEM (((pthread_descr) NULL), p_report_events);
548 #else
549   if (__linuxthreads_initial_report_events != 0)
550     __pthread_initial_thread.p_report_events
551       = __linuxthreads_initial_report_events;
552   report_events = __pthread_initial_thread.p_report_events;
553 #endif
554   if (__builtin_expect (report_events, 0))
555     {
556       /* It's a bit more complicated.  We have to report the creation of
557          the manager thread.  */
558       int idx = __td_eventword (TD_CREATE);
559       uint32_t mask = __td_eventmask (TD_CREATE);
560
561       if ((mask & (__pthread_threads_events.event_bits[idx]
562                    | __pthread_initial_thread.p_eventbuf.eventmask.event_bits[idx]))
563           != 0)
564         {
565
566          __pthread_lock(__pthread_manager_thread.p_lock, NULL);
567
568 #ifdef __ia64__
569           pid = __clone2(__pthread_manager_event,
570                         (void **) __pthread_manager_thread_tos,
571                         THREAD_MANAGER_STACK_SIZE,
572                         CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
573                         (void *)(long)manager_pipe[0]);
574 #else
575           pid = clone(__pthread_manager_event,
576                         (void **) __pthread_manager_thread_tos,
577                         CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
578                         (void *)(long)manager_pipe[0]);
579 #endif
580
581           if (pid != -1)
582             {
583               /* Now fill in the information about the new thread in
584                  the newly created thread's data structure.  We cannot let
585                  the new thread do this since we don't know whether it was
586                  already scheduled when we send the event.  */
587               __pthread_manager_thread.p_eventbuf.eventdata =
588                   &__pthread_manager_thread;
589               __pthread_manager_thread.p_eventbuf.eventnum = TD_CREATE;
590               __pthread_last_event = &__pthread_manager_thread;
591               __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
592               __pthread_manager_thread.p_pid = pid;
593
594               /* Now call the function which signals the event.  */
595               __linuxthreads_create_event ();
596             }
597           /* Now restart the thread.  */
598           __pthread_unlock(__pthread_manager_thread.p_lock);
599         }
600     }
601
602   if (pid == 0) {
603 #ifdef __ia64__
604     pid = __clone2(__pthread_manager, (void **) __pthread_manager_thread_tos,
605                   THREAD_MANAGER_STACK_SIZE,
606                   CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
607                   (void *)(long)manager_pipe[0]);
608 #else
609     pid = clone(__pthread_manager, (void **) __pthread_manager_thread_tos,
610                   CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
611                   (void *)(long)manager_pipe[0]);
612 #endif
613   }
614   if (pid == -1) {
615     free(__pthread_manager_thread_bos);
616     close(manager_pipe[0]);
617     close(manager_pipe[1]);
618     return -1;
619   }
620   __pthread_manager_request = manager_pipe[1]; /* writing end */
621   __pthread_manager_reader = manager_pipe[0]; /* reading end */
622   __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
623   __pthread_manager_thread.p_pid = pid;
624
625   /* Make gdb aware of new thread manager */
626   if (__pthread_threads_debug && __pthread_sig_debug > 0)
627     {
628       raise(__pthread_sig_debug);
629       /* We suspend ourself and gdb will wake us up when it is
630          ready to handle us. */
631       __pthread_wait_for_restart_signal(thread_self());
632     }
633   /* Synchronize debugging of the thread manager */
634   PDEBUG("send REQ_DEBUG to manager thread\n");
635   request.req_kind = REQ_DEBUG;
636   TEMP_FAILURE_RETRY(write(__pthread_manager_request,
637               (char *) &request, sizeof(request)));
638   return 0;
639 }
640
641 /* Thread creation */
642
643 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
644                          void * (*start_routine)(void *), void *arg)
645 {
646   pthread_descr self = thread_self();
647   struct pthread_request request;
648   if (__pthread_manager_request < 0) {
649     if (__pthread_initialize_manager() < 0) return EAGAIN;
650   }
651   request.req_thread = self;
652   request.req_kind = REQ_CREATE;
653   request.req_args.create.attr = attr;
654   request.req_args.create.fn = start_routine;
655   request.req_args.create.arg = arg;
656   sigprocmask(SIG_SETMASK, NULL, &request.req_args.create.mask);
657   PDEBUG("write REQ_CREATE to manager thread\n");
658   TEMP_FAILURE_RETRY(write(__pthread_manager_request,
659               (char *) &request, sizeof(request)));
660   PDEBUG("before suspend(self)\n");
661   suspend(self);
662   PDEBUG("after suspend(self)\n");
663   if (THREAD_GETMEM(self, p_retcode) == 0)
664     *thread = (pthread_t) THREAD_GETMEM(self, p_retval);
665   return THREAD_GETMEM(self, p_retcode);
666 }
667
668 /* Simple operations on thread identifiers */
669
670 pthread_t pthread_self(void)
671 {
672   pthread_descr self = thread_self();
673   return THREAD_GETMEM(self, p_tid);
674 }
675 libpthread_hidden_def (pthread_self)
676
677 int pthread_equal(pthread_t thread1, pthread_t thread2)
678 {
679   return thread1 == thread2;
680 }
681 libpthread_hidden_def (pthread_equal)
682
683 /* Helper function for thread_self in the case of user-provided stacks */
684
685 #ifndef THREAD_SELF
686
687 pthread_descr __pthread_find_self(void)
688 {
689   char * sp = CURRENT_STACK_FRAME;
690   pthread_handle h;
691
692   /* __pthread_handles[0] is the initial thread, __pthread_handles[1] is
693      the manager threads handled specially in thread_self(), so start at 2 */
694   h = __pthread_handles + 2;
695   while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;
696
697 #ifdef DEBUG_PT
698   if (h->h_descr == NULL) {
699       printf("*** %s ERROR descriptor is NULL!!!!! ***\n\n", __FUNCTION__);
700       _exit(1);
701   }
702 #endif
703
704   return h->h_descr;
705 }
706 #else
707
708 static pthread_descr thread_self_stack(void)
709 {
710     char *sp = CURRENT_STACK_FRAME;
711     pthread_handle h;
712
713     if (sp >= __pthread_manager_thread_bos && sp < __pthread_manager_thread_tos)
714         return manager_thread;
715     h = __pthread_handles + 2;
716 # if defined(USE_TLS) && USE_TLS
717     while (h->h_descr == NULL
718             || ! (sp <= (char *) h->h_descr->p_stackaddr && sp >= h->h_bottom))
719         h++;
720 # else
721     while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom))
722         h++;
723 # endif
724     return h->h_descr;
725 }
726
727 #endif
728
729 /* Thread scheduling */
730
731 int pthread_setschedparam(pthread_t thread, int policy,
732                           const struct sched_param *param)
733 {
734   pthread_handle handle = thread_handle(thread);
735   pthread_descr th;
736
737   __pthread_lock(&handle->h_lock, NULL);
738   if (invalid_handle(handle, thread)) {
739     __pthread_unlock(&handle->h_lock);
740     return ESRCH;
741   }
742   th = handle->h_descr;
743   if (sched_setscheduler(th->p_pid, policy, param) == -1) {
744     __pthread_unlock(&handle->h_lock);
745     return errno;
746   }
747   th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
748   __pthread_unlock(&handle->h_lock);
749   if (__pthread_manager_request >= 0)
750     __pthread_manager_adjust_prio(th->p_priority);
751   return 0;
752 }
753 libpthread_hidden_def(pthread_setschedparam)
754
755 int pthread_getschedparam(pthread_t thread, int *policy,
756                           struct sched_param *param)
757 {
758   pthread_handle handle = thread_handle(thread);
759   int pid, pol;
760
761   __pthread_lock(&handle->h_lock, NULL);
762   if (invalid_handle(handle, thread)) {
763     __pthread_unlock(&handle->h_lock);
764     return ESRCH;
765   }
766   pid = handle->h_descr->p_pid;
767   __pthread_unlock(&handle->h_lock);
768   pol = sched_getscheduler(pid);
769   if (pol == -1) return errno;
770   if (sched_getparam(pid, param) == -1) return errno;
771   *policy = pol;
772   return 0;
773 }
774 libpthread_hidden_def(pthread_getschedparam)
775
776 /* Process-wide exit() request */
777
778 static void pthread_onexit_process(int retcode, void *arg attribute_unused)
779 {
780     struct pthread_request request;
781     pthread_descr self = thread_self();
782
783     if (__pthread_manager_request >= 0) {
784         request.req_thread = self;
785         request.req_kind = REQ_PROCESS_EXIT;
786         request.req_args.exit.code = retcode;
787         TEMP_FAILURE_RETRY(write(__pthread_manager_request,
788                     (char *) &request, sizeof(request)));
789         suspend(self);
790         /* Main thread should accumulate times for thread manager and its
791            children, so that timings for main thread account for all threads. */
792         if (self == __pthread_main_thread) {
793             waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
794             /* Since all threads have been asynchronously terminated
795              * (possibly holding locks), free cannot be used any more.  */
796             __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
797         }
798     }
799 }
800
801 /* The handler for the RESTART signal just records the signal received
802    in the thread descriptor, and optionally performs a siglongjmp
803    (for pthread_cond_timedwait). */
804
805 static void pthread_handle_sigrestart(int sig)
806 {
807     pthread_descr self = thread_self();
808     THREAD_SETMEM(self, p_signal, sig);
809     if (THREAD_GETMEM(self, p_signal_jmp) != NULL)
810         siglongjmp(*THREAD_GETMEM(self, p_signal_jmp), 1);
811 }
812
813 /* The handler for the CANCEL signal checks for cancellation
814    (in asynchronous mode), for process-wide exit and exec requests.
815    For the thread manager thread, redirect the signal to
816    __pthread_manager_sighandler. */
817
818 static void pthread_handle_sigcancel(int sig)
819 {
820   pthread_descr self = thread_self();
821   sigjmp_buf * jmpbuf;
822
823
824   if (self == &__pthread_manager_thread)
825     {
826 #ifdef THREAD_SELF
827       /* A new thread might get a cancel signal before it is fully
828          initialized, so that the thread register might still point to the
829          manager thread.  Double check that this is really the manager
830          thread.  */
831       pthread_descr real_self = thread_self_stack();
832       if (real_self == &__pthread_manager_thread)
833         {
834           __pthread_manager_sighandler(sig);
835           return;
836         }
837       /* Oops, thread_self() isn't working yet..  */
838       self = real_self;
839 # ifdef INIT_THREAD_SELF
840       INIT_THREAD_SELF(self, self->p_nr);
841 # endif
842 #else
843       __pthread_manager_sighandler(sig);
844       return;
845 #endif
846     }
847   if (__builtin_expect (__pthread_exit_requested, 0)) {
848     /* Main thread should accumulate times for thread manager and its
849        children, so that timings for main thread account for all threads. */
850     if (self == __pthread_main_thread) {
851 #if defined(USE_TLS) && USE_TLS
852       waitpid(__pthread_manager_thread->p_pid, NULL, __WCLONE);
853 #else
854       waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
855 #endif
856     }
857     _exit(__pthread_exit_code);
858   }
859   if (__builtin_expect (THREAD_GETMEM(self, p_canceled), 0)
860       && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
861     if (THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
862       __pthread_do_exit(PTHREAD_CANCELED, CURRENT_STACK_FRAME);
863     jmpbuf = THREAD_GETMEM(self, p_cancel_jmp);
864     if (jmpbuf != NULL) {
865       THREAD_SETMEM(self, p_cancel_jmp, NULL);
866       siglongjmp(*jmpbuf, 1);
867     }
868   }
869 }
870
871 /* Handler for the DEBUG signal.
872    The debugging strategy is as follows:
873    On reception of a REQ_DEBUG request (sent by new threads created to
874    the thread manager under debugging mode), the thread manager throws
875    __pthread_sig_debug to itself. The debugger (if active) intercepts
876    this signal, takes into account new threads and continue execution
877    of the thread manager by propagating the signal because it doesn't
878    know what it is specifically done for. In the current implementation,
879    the thread manager simply discards it. */
880
881 static void pthread_handle_sigdebug(int sig attribute_unused)
882 {
883   /* Nothing */
884 }
885
886 /* Reset the state of the thread machinery after a fork().
887    Close the pipe used for requests and set the main thread to the forked
888    thread.
889    Notice that we can't free the stack segments, as the forked thread
890    may hold pointers into them. */
891
892 void __pthread_reset_main_thread(void)
893 {
894   pthread_descr self = thread_self();
895
896   if (__pthread_manager_request != -1) {
897     /* Free the thread manager stack */
898     free(__pthread_manager_thread_bos);
899     __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
900     /* Close the two ends of the pipe */
901     close(__pthread_manager_request);
902     close(__pthread_manager_reader);
903     __pthread_manager_request = __pthread_manager_reader = -1;
904   }
905
906   /* Update the pid of the main thread */
907   THREAD_SETMEM(self, p_pid, getpid());
908   /* Make the forked thread the main thread */
909   __pthread_main_thread = self;
910   THREAD_SETMEM(self, p_nextlive, self);
911   THREAD_SETMEM(self, p_prevlive, self);
912   /* Now this thread modifies the global variables.  */
913   THREAD_SETMEM(self, p_errnop, &_errno);
914   THREAD_SETMEM(self, p_h_errnop, &_h_errno);
915 }
916
917 /* Process-wide exec() request */
918
919 void __pthread_kill_other_threads_np(void)
920 {
921   struct sigaction sa;
922   /* Terminate all other threads and thread manager */
923   pthread_onexit_process(0, NULL);
924   /* Make current thread the main thread in case the calling thread
925      changes its mind, does not exec(), and creates new threads instead. */
926   __pthread_reset_main_thread();
927   /* Reset the signal handlers behaviour for the signals the
928      implementation uses since this would be passed to the new
929      process.  */
930   memset(&sa, 0, sizeof(sa));
931   if (SIG_DFL) /* if it's constant zero, it's already done */
932     sa.sa_handler = SIG_DFL;
933   __libc_sigaction(__pthread_sig_restart, &sa, NULL);
934   __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
935   if (__pthread_sig_debug > 0)
936     __libc_sigaction(__pthread_sig_debug, &sa, NULL);
937 }
938 weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
939
940 /* Concurrency symbol level.  */
941 static int current_level;
942
943 int __pthread_setconcurrency(int level)
944 {
945   /* We don't do anything unless we have found a useful interpretation.  */
946   current_level = level;
947   return 0;
948 }
949 weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
950
951 int __pthread_getconcurrency(void)
952 {
953   return current_level;
954 }
955 weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
956
957
958 /* Primitives for controlling thread execution */
959
960 void __pthread_wait_for_restart_signal(pthread_descr self)
961 {
962     sigset_t mask;
963
964     sigprocmask(SIG_SETMASK, NULL, &mask); /* Get current signal mask */
965     sigdelset(&mask, __pthread_sig_restart); /* Unblock the restart signal */
966     THREAD_SETMEM(self, p_signal, 0);
967     do {
968         sigsuspend(&mask);                   /* Wait for signal */
969     } while (THREAD_GETMEM(self, p_signal) !=__pthread_sig_restart);
970
971     READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
972 }
973
974 #ifndef __NR_rt_sigaction
975 /* The _old variants are for 2.0 and early 2.1 kernels which don't have RT
976    signals.
977    On these kernels, we use SIGUSR1 and SIGUSR2 for restart and cancellation.
978    Since the restart signal does not queue, we use an atomic counter to create
979    queuing semantics. This is needed to resolve a rare race condition in
980    pthread_cond_timedwait_relative. */
981
982 void __pthread_restart_old(pthread_descr th)
983 {
984     if (atomic_increment(&th->p_resume_count) == -1)
985         kill(th->p_pid, __pthread_sig_restart);
986 }
987
988 void __pthread_suspend_old(pthread_descr self)
989 {
990     if (atomic_decrement(&self->p_resume_count) <= 0)
991         __pthread_wait_for_restart_signal(self);
992 }
993
994 int
995 __pthread_timedsuspend_old(pthread_descr self, const struct timespec *abstime)
996 {
997   sigset_t unblock, initial_mask;
998   int was_signalled = 0;
999   sigjmp_buf jmpbuf;
1000
1001   if (atomic_decrement(&self->p_resume_count) == 0) {
1002     /* Set up a longjmp handler for the restart signal, unblock
1003        the signal and sleep. */
1004
1005     if (sigsetjmp(jmpbuf, 1) == 0) {
1006       THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
1007       THREAD_SETMEM(self, p_signal, 0);
1008       /* Unblock the restart signal */
1009       __sigemptyset(&unblock);
1010       sigaddset(&unblock, __pthread_sig_restart);
1011       sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
1012
1013       while (1) {
1014         struct timeval now;
1015         struct timespec reltime;
1016
1017         /* Compute a time offset relative to now.  */
1018         gettimeofday (&now, NULL);
1019         reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
1020         reltime.tv_sec = abstime->tv_sec - now.tv_sec;
1021         if (reltime.tv_nsec < 0) {
1022           reltime.tv_nsec += 1000000000;
1023           reltime.tv_sec -= 1;
1024         }
1025
1026         /* Sleep for the required duration. If woken by a signal,
1027            resume waiting as required by Single Unix Specification.  */
1028         if (reltime.tv_sec < 0 || nanosleep(&reltime, NULL) == 0)
1029           break;
1030       }
1031
1032       /* Block the restart signal again */
1033       sigprocmask(SIG_SETMASK, &initial_mask, NULL);
1034       was_signalled = 0;
1035     } else {
1036       was_signalled = 1;
1037     }
1038     THREAD_SETMEM(self, p_signal_jmp, NULL);
1039   }
1040
1041   /* Now was_signalled is true if we exited the above code
1042      due to the delivery of a restart signal.  In that case,
1043      we know we have been dequeued and resumed and that the
1044      resume count is balanced.  Otherwise, there are some
1045      cases to consider. First, try to bump up the resume count
1046      back to zero. If it goes to 1, it means restart() was
1047      invoked on this thread. The signal must be consumed
1048      and the count bumped down and everything is cool. We
1049      can return a 1 to the caller.
1050      Otherwise, no restart was delivered yet, so a potential
1051      race exists; we return a 0 to the caller which must deal
1052      with this race in an appropriate way; for example by
1053      atomically removing the thread from consideration for a
1054      wakeup---if such a thing fails, it means a restart is
1055      being delivered. */
1056
1057   if (!was_signalled) {
1058     if (atomic_increment(&self->p_resume_count) != -1) {
1059       __pthread_wait_for_restart_signal(self);
1060       atomic_decrement(&self->p_resume_count); /* should be zero now! */
1061       /* woke spontaneously and consumed restart signal */
1062       return 1;
1063     }
1064     /* woke spontaneously but did not consume restart---caller must resolve */
1065     return 0;
1066   }
1067   /* woken due to restart signal */
1068   return 1;
1069 }
1070 #endif /* __NR_rt_sigaction */
1071
1072
1073 #ifdef __NR_rt_sigaction
1074 void __pthread_restart_new(pthread_descr th)
1075 {
1076     /* The barrier is proabably not needed, in which case it still documents
1077        our assumptions. The intent is to commit previous writes to shared
1078        memory so the woken thread will have a consistent view.  Complementary
1079        read barriers are present to the suspend functions. */
1080     WRITE_MEMORY_BARRIER();
1081     kill(th->p_pid, __pthread_sig_restart);
1082 }
1083
1084 int __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime)
1085 {
1086     sigset_t unblock, initial_mask;
1087     int was_signalled = 0;
1088     sigjmp_buf jmpbuf;
1089
1090     if (sigsetjmp(jmpbuf, 1) == 0) {
1091         THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
1092         THREAD_SETMEM(self, p_signal, 0);
1093         /* Unblock the restart signal */
1094         __sigemptyset(&unblock);
1095         sigaddset(&unblock, __pthread_sig_restart);
1096         sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
1097
1098         while (1) {
1099             struct timeval now;
1100             struct timespec reltime;
1101
1102             /* Compute a time offset relative to now.  */
1103             gettimeofday (&now, NULL);
1104             reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
1105             reltime.tv_sec = abstime->tv_sec - now.tv_sec;
1106             if (reltime.tv_nsec < 0) {
1107                 reltime.tv_nsec += 1000000000;
1108                 reltime.tv_sec -= 1;
1109             }
1110
1111             /* Sleep for the required duration. If woken by a signal,
1112                resume waiting as required by Single Unix Specification.  */
1113             if (reltime.tv_sec < 0 || nanosleep(&reltime, NULL) == 0)
1114                 break;
1115         }
1116
1117         /* Block the restart signal again */
1118         sigprocmask(SIG_SETMASK, &initial_mask, NULL);
1119         was_signalled = 0;
1120     } else {
1121         was_signalled = 1;
1122     }
1123     THREAD_SETMEM(self, p_signal_jmp, NULL);
1124
1125     /* Now was_signalled is true if we exited the above code
1126        due to the delivery of a restart signal.  In that case,
1127        everything is cool. We have been removed from whatever
1128        we were waiting on by the other thread, and consumed its signal.
1129
1130        Otherwise we this thread woke up spontaneously, or due to a signal other
1131        than restart. This is an ambiguous case  that must be resolved by
1132        the caller; the thread is still eligible for a restart wakeup
1133        so there is a race. */
1134
1135     READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
1136     return was_signalled;
1137 }
1138 #endif
1139
1140 /* Debugging aid */
1141
1142 #ifdef DEBUG_PT
1143 #include <stdarg.h>
1144
1145 void __pthread_message(char * fmt, ...)
1146 {
1147   char buffer[1024];
1148   va_list args;
1149   sprintf(buffer, "%05d : ", getpid());
1150   va_start(args, fmt);
1151   vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
1152   va_end(args);
1153   TEMP_FAILURE_RETRY(write(2, buffer, strlen(buffer)));
1154 }
1155
1156 #endif
1157
1158
1159 #ifndef __PIC__
1160 /* We need a hook to force the cancellation wrappers to be linked in when
1161    static libpthread is used.  */
1162 extern const char __pthread_provide_wrappers;
1163 static const char *const __pthread_require_wrappers =
1164   &__pthread_provide_wrappers;
1165 #endif