chiark / gitweb /
eglibc (2.11.3-4+deb6u3) squeeze-lts; urgency=medium
[eglibc.git] / linuxthreads / pthread.c
1
2 /* Linuxthreads - a simple clone()-based implementation of Posix        */
3 /* threads for Linux.                                                   */
4 /* Copyright (C) 1996 Xavier Leroy (Xavier.Leroy@inria.fr)              */
5 /*                                                                      */
6 /* This program is free software; you can redistribute it and/or        */
7 /* modify it under the terms of the GNU Library General Public License  */
8 /* as published by the Free Software Foundation; either version 2       */
9 /* of the License, or (at your option) any later version.               */
10 /*                                                                      */
11 /* This program 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        */
14 /* GNU Library General Public License for more details.                 */
15
16 /* Thread creation, initialization, and basic low-level routines */
17
18 #include <errno.h>
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 <sys/time.h>
28 #include <shlib-compat.h>
29 #include "pthread.h"
30 #include "internals.h"
31 #include "spinlock.h"
32 #include "restart.h"
33 #include "smp.h"
34 #include <ldsodefs.h>
35 #include <tls.h>
36 #include <version.h>
37 #include <not-cancel.h>
38
39 /* Sanity check.  */
40 #if !defined PTHREAD_SIGBASE && (!defined __SIGRTMIN || (__SIGRTMAX - __SIGRTMIN) < 3)
41 # error "This must not happen"
42 #endif
43
44 #if !(USE_TLS && HAVE___THREAD)
45 /* These variables are used by the setup code.  */
46 extern int _errno;
47 extern int _h_errno;
48
49 /* We need the global/static resolver state here.  */
50 # include <resolv.h>
51 # undef _res
52
53 extern struct __res_state _res;
54 #endif
55
56 #ifdef USE_TLS
57
58 /* We need only a few variables.  */
59 #define manager_thread __pthread_manager_threadp
60 pthread_descr __pthread_manager_threadp attribute_hidden;
61
62 #else
63
64 /* Descriptor of the initial thread */
65
66 struct _pthread_descr_struct __pthread_initial_thread = {
67   .p_header.data.self = &__pthread_initial_thread,
68   .p_nextlive = &__pthread_initial_thread,
69   .p_prevlive = &__pthread_initial_thread,
70   .p_tid = PTHREAD_THREADS_MAX,
71   .p_lock = &__pthread_handles[0].h_lock,
72   .p_start_args = PTHREAD_START_ARGS_INITIALIZER(NULL),
73 #if !(USE_TLS && HAVE___THREAD)
74   .p_errnop = &_errno,
75   .p_h_errnop = &_h_errno,
76   .p_resp = &_res,
77 #endif
78   .p_userstack = 1,
79   .p_resume_count = __ATOMIC_INITIALIZER,
80   .p_alloca_cutoff = __MAX_ALLOCA_CUTOFF
81 };
82
83 /* Descriptor of the manager thread; none of this is used but the error
84    variables, the p_pid and p_priority fields,
85    and the address for identification.  */
86
87 #define manager_thread (&__pthread_manager_thread)
88 struct _pthread_descr_struct __pthread_manager_thread = {
89   .p_header.data.self = &__pthread_manager_thread,
90   .p_header.data.multiple_threads = 1,
91   .p_lock = &__pthread_handles[1].h_lock,
92   .p_start_args = PTHREAD_START_ARGS_INITIALIZER(__pthread_manager),
93 #if !(USE_TLS && HAVE___THREAD)
94   .p_errnop = &__pthread_manager_thread.p_errno,
95 #endif
96   .p_nr = 1,
97   .p_resume_count = __ATOMIC_INITIALIZER,
98   .p_alloca_cutoff = PTHREAD_STACK_MIN / 4
99 };
100 #endif
101
102 /* Pointer to the main thread (the father of the thread manager thread) */
103 /* Originally, this is the initial thread, but this changes after fork() */
104
105 #ifdef USE_TLS
106 pthread_descr __pthread_main_thread;
107 #else
108 pthread_descr __pthread_main_thread = &__pthread_initial_thread;
109 #endif
110
111 /* Limit between the stack of the initial thread (above) and the
112    stacks of other threads (below). Aligned on a STACK_SIZE boundary. */
113
114 char *__pthread_initial_thread_bos;
115
116 /* File descriptor for sending requests to the thread manager. */
117 /* Initially -1, meaning that the thread manager is not running. */
118
119 int __pthread_manager_request = -1;
120
121 int __pthread_multiple_threads attribute_hidden;
122
123 /* Other end of the pipe for sending requests to the thread manager. */
124
125 int __pthread_manager_reader;
126
127 /* Limits of the thread manager stack */
128
129 char *__pthread_manager_thread_bos;
130 char *__pthread_manager_thread_tos;
131
132 /* For process-wide exit() */
133
134 int __pthread_exit_requested;
135 int __pthread_exit_code;
136
137 /* Maximum stack size.  */
138 size_t __pthread_max_stacksize;
139
140 /* Nozero if the machine has more than one processor.  */
141 int __pthread_smp_kernel;
142
143
144 #if !__ASSUME_REALTIME_SIGNALS
145 /* Pointers that select new or old suspend/resume functions
146    based on availability of rt signals. */
147
148 void (*__pthread_restart)(pthread_descr) = __pthread_restart_old;
149 void (*__pthread_suspend)(pthread_descr) = __pthread_suspend_old;
150 int (*__pthread_timedsuspend)(pthread_descr, const struct timespec *) = __pthread_timedsuspend_old;
151 #endif  /* __ASSUME_REALTIME_SIGNALS */
152
153 /* Communicate relevant LinuxThreads constants to gdb */
154
155 const int __pthread_threads_max = PTHREAD_THREADS_MAX;
156 const int __pthread_sizeof_handle = sizeof(struct pthread_handle_struct);
157 const int __pthread_offsetof_descr = offsetof(struct pthread_handle_struct,
158                                               h_descr);
159 const int __pthread_offsetof_pid = offsetof(struct _pthread_descr_struct,
160                                             p_pid);
161 const int __linuxthreads_pthread_sizeof_descr
162   = sizeof(struct _pthread_descr_struct);
163
164 const int __linuxthreads_initial_report_events;
165
166 const char __linuxthreads_version[] = VERSION;
167
168 /* Forward declarations */
169
170 static void pthread_onexit_process(int retcode, void *arg);
171 #ifndef HAVE_Z_NODELETE
172 static void pthread_atexit_process(void *arg, int retcode);
173 static void pthread_atexit_retcode(void *arg, int retcode);
174 #endif
175 static void pthread_handle_sigcancel(int sig);
176 static void pthread_handle_sigrestart(int sig);
177 static void pthread_handle_sigdebug(int sig);
178
179 /* Signal numbers used for the communication.
180    In these variables we keep track of the used variables.  If the
181    platform does not support any real-time signals we will define the
182    values to some unreasonable value which will signal failing of all
183    the functions below.  */
184 #if defined (PTHREAD_SIGBASE)
185 int __pthread_sig_restart = PTHREAD_SIGBASE;
186 int __pthread_sig_cancel = PTHREAD_SIGBASE + 1;
187 int __pthread_sig_debug = PTHREAD_SIGBASE + 2;
188 #else
189 int __pthread_sig_restart = __SIGRTMIN;
190 int __pthread_sig_cancel = __SIGRTMIN + 1;
191 int __pthread_sig_debug = __SIGRTMIN + 2;
192 #endif
193
194 extern int __libc_current_sigrtmin_private (void);
195
196 #if !__ASSUME_REALTIME_SIGNALS
197 static int rtsigs_initialized;
198
199 static void
200 init_rtsigs (void)
201 {
202   if (rtsigs_initialized)
203     return;
204
205   if (__libc_current_sigrtmin_private () == -1)
206     {
207 #ifndef PTHREAD_SIGBASE
208       __pthread_sig_restart = SIGUSR1;
209       __pthread_sig_cancel = SIGUSR2;
210       __pthread_sig_debug = 0;
211 #endif
212     }
213   else
214     {
215       __pthread_restart = __pthread_restart_new;
216       __pthread_suspend = __pthread_wait_for_restart_signal;
217       __pthread_timedsuspend = __pthread_timedsuspend_new;
218     }
219
220   rtsigs_initialized = 1;
221 }
222 #endif
223
224
225 /* Initialize the pthread library.
226    Initialization is split in two functions:
227    - a constructor function that blocks the __pthread_sig_restart signal
228      (must do this very early, since the program could capture the signal
229       mask with e.g. sigsetjmp before creating the first thread);
230    - a regular function called from pthread_create when needed. */
231
232 static void pthread_initialize(void) __attribute__((constructor));
233
234 #ifndef HAVE_Z_NODELETE
235 extern void *__dso_handle __attribute__ ((weak));
236 #endif
237
238
239 #if defined USE_TLS && !defined SHARED
240 extern void __libc_setup_tls (size_t tcbsize, size_t tcbalign);
241 #endif
242
243 struct pthread_functions __pthread_functions =
244   {
245 #if !(USE_TLS && HAVE___THREAD)
246     .ptr_pthread_internal_tsd_set = __pthread_internal_tsd_set,
247     .ptr_pthread_internal_tsd_get = __pthread_internal_tsd_get,
248     .ptr_pthread_internal_tsd_address = __pthread_internal_tsd_address,
249 #endif
250     .ptr_pthread_fork = __pthread_fork,
251     .ptr_pthread_attr_destroy = __pthread_attr_destroy,
252 #if SHLIB_COMPAT(libpthread, GLIBC_2_0, GLIBC_2_1)
253     .ptr___pthread_attr_init_2_0 = __pthread_attr_init_2_0,
254 #endif
255     .ptr___pthread_attr_init_2_1 = __pthread_attr_init_2_1,
256     .ptr_pthread_attr_getdetachstate = __pthread_attr_getdetachstate,
257     .ptr_pthread_attr_setdetachstate = __pthread_attr_setdetachstate,
258     .ptr_pthread_attr_getinheritsched = __pthread_attr_getinheritsched,
259     .ptr_pthread_attr_setinheritsched = __pthread_attr_setinheritsched,
260     .ptr_pthread_attr_getschedparam = __pthread_attr_getschedparam,
261     .ptr_pthread_attr_setschedparam = __pthread_attr_setschedparam,
262     .ptr_pthread_attr_getschedpolicy = __pthread_attr_getschedpolicy,
263     .ptr_pthread_attr_setschedpolicy = __pthread_attr_setschedpolicy,
264     .ptr_pthread_attr_getscope = __pthread_attr_getscope,
265     .ptr_pthread_attr_setscope = __pthread_attr_setscope,
266     .ptr_pthread_condattr_destroy = __pthread_condattr_destroy,
267     .ptr_pthread_condattr_init = __pthread_condattr_init,
268     .ptr___pthread_cond_broadcast = __pthread_cond_broadcast,
269     .ptr___pthread_cond_destroy = __pthread_cond_destroy,
270     .ptr___pthread_cond_init = __pthread_cond_init,
271     .ptr___pthread_cond_signal = __pthread_cond_signal,
272     .ptr___pthread_cond_wait = __pthread_cond_wait,
273     .ptr___pthread_cond_timedwait = __pthread_cond_timedwait,
274     .ptr_pthread_equal = __pthread_equal,
275     .ptr___pthread_exit = __pthread_exit,
276     .ptr_pthread_getschedparam = __pthread_getschedparam,
277     .ptr_pthread_setschedparam = __pthread_setschedparam,
278     .ptr_pthread_mutex_destroy = __pthread_mutex_destroy,
279     .ptr_pthread_mutex_init = __pthread_mutex_init,
280     .ptr_pthread_mutex_lock = __pthread_mutex_lock,
281     .ptr_pthread_mutex_trylock = __pthread_mutex_trylock,
282     .ptr_pthread_mutex_unlock = __pthread_mutex_unlock,
283     .ptr_pthread_self = __pthread_self,
284     .ptr_pthread_setcancelstate = __pthread_setcancelstate,
285     .ptr_pthread_setcanceltype = __pthread_setcanceltype,
286     .ptr_pthread_do_exit = __pthread_do_exit,
287     .ptr_pthread_thread_self = __pthread_thread_self,
288     .ptr_pthread_cleanup_upto = __pthread_cleanup_upto,
289     .ptr_pthread_sigaction = __pthread_sigaction,
290     .ptr_pthread_sigwait = __pthread_sigwait,
291     .ptr_pthread_raise = __pthread_raise,
292     .ptr__pthread_cleanup_push = _pthread_cleanup_push,
293     .ptr__pthread_cleanup_pop = _pthread_cleanup_pop
294   };
295 #ifdef SHARED
296 # define ptr_pthread_functions &__pthread_functions
297 #else
298 # define ptr_pthread_functions NULL
299 #endif
300
301 static int *__libc_multiple_threads_ptr;
302
303 /* Do some minimal initialization which has to be done during the
304    startup of the C library.  */
305 void
306 __pthread_initialize_minimal(void)
307 {
308 #ifdef USE_TLS
309   pthread_descr self;
310
311   /* First of all init __pthread_handles[0] and [1] if needed.  */
312 # if __LT_SPINLOCK_INIT != 0
313   __pthread_handles[0].h_lock = __LOCK_INITIALIZER;
314   __pthread_handles[1].h_lock = __LOCK_INITIALIZER;
315 # endif
316 # ifndef SHARED
317   /* Unlike in the dynamically linked case the dynamic linker has not
318      taken care of initializing the TLS data structures.  */
319   __libc_setup_tls (TLS_TCB_SIZE, TLS_TCB_ALIGN);
320 # elif !USE___THREAD
321   if (__builtin_expect (GL(dl_tls_dtv_slotinfo_list) == NULL, 0))
322     {
323       tcbhead_t *tcbp;
324
325       /* There is no actual TLS being used, so the thread register
326          was not initialized in the dynamic linker.  */
327
328       /* We need to install special hooks so that the malloc and memalign
329          calls in _dl_tls_setup and _dl_allocate_tls won't cause full
330          malloc initialization that will try to set up its thread state.  */
331
332       extern void __libc_malloc_pthread_startup (bool first_time);
333       __libc_malloc_pthread_startup (true);
334
335       if (__builtin_expect (_dl_tls_setup (), 0)
336           || __builtin_expect ((tcbp = _dl_allocate_tls (NULL)) == NULL, 0))
337         {
338           static const char msg[] = "\
339 cannot allocate TLS data structures for initial thread\n";
340           TEMP_FAILURE_RETRY (write_not_cancel (STDERR_FILENO,
341                                                 msg, sizeof msg - 1));
342           abort ();
343         }
344       const char *lossage = TLS_INIT_TP (tcbp, 0);
345       if (__builtin_expect (lossage != NULL, 0))
346         {
347           static const char msg[] = "cannot set up thread-local storage: ";
348           const char nl = '\n';
349           TEMP_FAILURE_RETRY (write_not_cancel (STDERR_FILENO,
350                                                 msg, sizeof msg - 1));
351           TEMP_FAILURE_RETRY (write_not_cancel (STDERR_FILENO,
352                                                 lossage, strlen (lossage)));
353           TEMP_FAILURE_RETRY (write_not_cancel (STDERR_FILENO, &nl, 1));
354         }
355
356       /* Though it was allocated with libc's malloc, that was done without
357          the user's __malloc_hook installed.  A later realloc that uses
358          the hooks might not work with that block from the plain malloc.
359          So we record this block as unfreeable just as the dynamic linker
360          does when it allocates the DTV before the libc malloc exists.  */
361       GL(dl_initial_dtv) = GET_DTV (tcbp);
362
363       __libc_malloc_pthread_startup (false);
364     }
365 # endif
366
367   self = THREAD_SELF;
368
369   /* The memory for the thread descriptor was allocated elsewhere as
370      part of the TLS allocation.  We have to initialize the data
371      structure by hand.  This initialization must mirror the struct
372      definition above.  */
373   self->p_nextlive = self->p_prevlive = self;
374   self->p_tid = PTHREAD_THREADS_MAX;
375   self->p_lock = &__pthread_handles[0].h_lock;
376 # ifndef HAVE___THREAD
377   self->p_errnop = &_errno;
378   self->p_h_errnop = &_h_errno;
379 # endif
380   /* self->p_start_args need not be initialized, it's all zero.  */
381   self->p_userstack = 1;
382 # if __LT_SPINLOCK_INIT != 0
383   self->p_resume_count = (struct pthread_atomic) __ATOMIC_INITIALIZER;
384 # endif
385   self->p_alloca_cutoff = __MAX_ALLOCA_CUTOFF;
386
387   /* Another variable which points to the thread descriptor.  */
388   __pthread_main_thread = self;
389
390   /* And fill in the pointer the the thread __pthread_handles array.  */
391   __pthread_handles[0].h_descr = self;
392
393 #else  /* USE_TLS */
394
395   /* First of all init __pthread_handles[0] and [1].  */
396 # if __LT_SPINLOCK_INIT != 0
397   __pthread_handles[0].h_lock = __LOCK_INITIALIZER;
398   __pthread_handles[1].h_lock = __LOCK_INITIALIZER;
399 # endif
400   __pthread_handles[0].h_descr = &__pthread_initial_thread;
401   __pthread_handles[1].h_descr = &__pthread_manager_thread;
402
403   /* If we have special thread_self processing, initialize that for the
404      main thread now.  */
405 # ifdef INIT_THREAD_SELF
406   INIT_THREAD_SELF(&__pthread_initial_thread, 0);
407 # endif
408 #endif
409
410 #if HP_TIMING_AVAIL
411 # ifdef USE_TLS
412   self->p_cpuclock_offset = GL(dl_cpuclock_offset);
413 # else
414   __pthread_initial_thread.p_cpuclock_offset = GL(dl_cpuclock_offset);
415 # endif
416 #endif
417
418   __libc_multiple_threads_ptr = __libc_pthread_init (ptr_pthread_functions);
419 }
420
421
422 void
423 __pthread_init_max_stacksize(void)
424 {
425   struct rlimit limit;
426   size_t max_stack;
427
428   getrlimit(RLIMIT_STACK, &limit);
429 #ifdef FLOATING_STACKS
430   if (limit.rlim_cur == RLIM_INFINITY)
431     limit.rlim_cur = ARCH_STACK_MAX_SIZE;
432 # ifdef NEED_SEPARATE_REGISTER_STACK
433   max_stack = limit.rlim_cur / 2;
434 # else
435   max_stack = limit.rlim_cur;
436 # endif
437 #else
438   /* Play with the stack size limit to make sure that no stack ever grows
439      beyond STACK_SIZE minus one page (to act as a guard page). */
440 # ifdef NEED_SEPARATE_REGISTER_STACK
441   /* STACK_SIZE bytes hold both the main stack and register backing
442      store. The rlimit value applies to each individually.  */
443   max_stack = STACK_SIZE/2 - __getpagesize ();
444 # else
445   max_stack = STACK_SIZE - __getpagesize();
446 # endif
447   if (limit.rlim_cur > max_stack) {
448     limit.rlim_cur = max_stack;
449     setrlimit(RLIMIT_STACK, &limit);
450   }
451 #endif
452   __pthread_max_stacksize = max_stack;
453   if (max_stack / 4 < __MAX_ALLOCA_CUTOFF)
454     {
455 #ifdef USE_TLS
456       pthread_descr self = THREAD_SELF;
457       self->p_alloca_cutoff = max_stack / 4;
458 #else
459       __pthread_initial_thread.p_alloca_cutoff = max_stack / 4;
460 #endif
461     }
462 }
463
464 #ifdef SHARED
465 # if USE___THREAD
466 /* When using __thread for this, we do it in libc so as not
467    to give libpthread its own TLS segment just for this.  */
468 extern void **__libc_dl_error_tsd (void) __attribute__ ((const));
469 # else
470 static void ** __attribute__ ((const))
471 __libc_dl_error_tsd (void)
472 {
473   return &thread_self ()->p_libc_specific[_LIBC_TSD_KEY_DL_ERROR];
474 }
475 # endif
476 #endif
477
478 #ifdef USE_TLS
479 static inline void __attribute__((always_inline))
480 init_one_static_tls (pthread_descr descr, struct link_map *map)
481 {
482 # if TLS_TCB_AT_TP
483   dtv_t *dtv = GET_DTV (descr);
484   void *dest = (char *) descr - map->l_tls_offset;
485 # elif TLS_DTV_AT_TP
486   dtv_t *dtv = GET_DTV ((pthread_descr) ((char *) descr + TLS_PRE_TCB_SIZE));
487   void *dest = (char *) descr + map->l_tls_offset + TLS_PRE_TCB_SIZE;
488 # else
489 #  error "Either TLS_TCB_AT_TP or TLS_DTV_AT_TP must be defined"
490 # endif
491
492   /* Fill in the DTV slot so that a later LD/GD access will find it.  */
493   dtv[map->l_tls_modid].pointer.val = dest;
494   dtv[map->l_tls_modid].pointer.is_static = true;
495
496   /* Initialize the memory.  */
497   memset (__mempcpy (dest, map->l_tls_initimage, map->l_tls_initimage_size),
498           '\0', map->l_tls_blocksize - map->l_tls_initimage_size);
499 }
500
501 static void
502 __pthread_init_static_tls (struct link_map *map)
503 {
504   size_t i;
505
506   for (i = 0; i < PTHREAD_THREADS_MAX; ++i)
507     if (__pthread_handles[i].h_descr != NULL && i != 1)
508       {
509         __pthread_lock (&__pthread_handles[i].h_lock, NULL);
510         if (__pthread_handles[i].h_descr != NULL)
511           init_one_static_tls (__pthread_handles[i].h_descr, map);
512         __pthread_unlock (&__pthread_handles[i].h_lock);
513       }
514 }
515 #endif
516
517 static void pthread_initialize(void)
518 {
519   struct sigaction sa;
520   sigset_t mask;
521
522   /* If already done (e.g. by a constructor called earlier!), bail out */
523   if (__pthread_initial_thread_bos != NULL) return;
524 #ifdef TEST_FOR_COMPARE_AND_SWAP
525   /* Test if compare-and-swap is available */
526   __pthread_has_cas = compare_and_swap_is_available();
527 #endif
528 #ifdef FLOATING_STACKS
529   /* We don't need to know the bottom of the stack.  Give the pointer some
530      value to signal that initialization happened.  */
531   __pthread_initial_thread_bos = (void *) -1l;
532 #else
533   /* Determine stack size limits .  */
534   __pthread_init_max_stacksize ();
535 # ifdef _STACK_GROWS_UP
536   /* The initial thread already has all the stack it needs */
537   __pthread_initial_thread_bos = (char *)
538     ((long)CURRENT_STACK_FRAME &~ (STACK_SIZE - 1));
539 # else
540   /* For the initial stack, reserve at least STACK_SIZE bytes of stack
541      below the current stack address, and align that on a
542      STACK_SIZE boundary. */
543   __pthread_initial_thread_bos =
544     (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
545 # endif
546 #endif
547 #ifdef USE_TLS
548   /* Update the descriptor for the initial thread. */
549   THREAD_SETMEM (((pthread_descr) NULL), p_pid, __getpid());
550 # ifndef HAVE___THREAD
551   /* Likewise for the resolver state _res.  */
552   THREAD_SETMEM (((pthread_descr) NULL), p_resp, &_res);
553 # endif
554 #else
555   /* Update the descriptor for the initial thread. */
556   __pthread_initial_thread.p_pid = __getpid();
557   /* Likewise for the resolver state _res.  */
558   __pthread_initial_thread.p_resp = &_res;
559 #endif
560 #if !__ASSUME_REALTIME_SIGNALS
561   /* Initialize real-time signals. */
562   init_rtsigs ();
563 #endif
564   /* Setup signal handlers for the initial thread.
565      Since signal handlers are shared between threads, these settings
566      will be inherited by all other threads. */
567   sa.sa_handler = pthread_handle_sigrestart;
568   sigemptyset(&sa.sa_mask);
569   sa.sa_flags = 0;
570   __libc_sigaction(__pthread_sig_restart, &sa, NULL);
571   sa.sa_handler = pthread_handle_sigcancel;
572   sigaddset(&sa.sa_mask, __pthread_sig_restart);
573   // sa.sa_flags = 0;
574   __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
575   if (__pthread_sig_debug > 0) {
576     sa.sa_handler = pthread_handle_sigdebug;
577     sigemptyset(&sa.sa_mask);
578     // sa.sa_flags = 0;
579     __libc_sigaction(__pthread_sig_debug, &sa, NULL);
580   }
581   /* Initially, block __pthread_sig_restart. Will be unblocked on demand. */
582   sigemptyset(&mask);
583   sigaddset(&mask, __pthread_sig_restart);
584   sigprocmask(SIG_BLOCK, &mask, NULL);
585   /* And unblock __pthread_sig_cancel if it has been blocked. */
586   sigdelset(&mask, __pthread_sig_restart);
587   sigaddset(&mask, __pthread_sig_cancel);
588   sigprocmask(SIG_UNBLOCK, &mask, NULL);
589   /* Register an exit function to kill all other threads. */
590   /* Do it early so that user-registered atexit functions are called
591      before pthread_*exit_process. */
592 #ifndef HAVE_Z_NODELETE
593   if (__builtin_expect (&__dso_handle != NULL, 1))
594     __cxa_atexit ((void (*) (void *)) pthread_atexit_process, NULL,
595                   __dso_handle);
596   else
597 #endif
598     __on_exit (pthread_onexit_process, NULL);
599   /* How many processors.  */
600   __pthread_smp_kernel = is_smp_system ();
601
602 #ifdef SHARED
603   /* Transfer the old value from the dynamic linker's internal location.  */
604   *__libc_dl_error_tsd () = *(*GL(dl_error_catch_tsd)) ();
605   GL(dl_error_catch_tsd) = &__libc_dl_error_tsd;
606
607   /* Make __rtld_lock_{,un}lock_recursive use pthread_mutex_{,un}lock,
608      keep the lock count from the ld.so implementation.  */
609   GL(dl_rtld_lock_recursive) = (void *) __pthread_mutex_lock;
610   GL(dl_rtld_unlock_recursive) = (void *) __pthread_mutex_unlock;
611   unsigned int rtld_lock_count = GL(dl_load_lock).mutex.__m_count;
612   GL(dl_load_lock).mutex.__m_count = 0;
613   while (rtld_lock_count-- > 0)
614     __pthread_mutex_lock (&GL(dl_load_lock).mutex);
615 #endif
616
617 #ifdef USE_TLS
618   GL(dl_init_static_tls) = &__pthread_init_static_tls;
619 #endif
620 }
621
622 void __pthread_initialize(void)
623 {
624   pthread_initialize();
625 }
626
627 int __pthread_initialize_manager(void)
628 {
629   int manager_pipe[2];
630   int pid;
631   struct pthread_request request;
632   int report_events;
633   pthread_descr mgr;
634 #ifdef USE_TLS
635   tcbhead_t *tcbp;
636 #endif
637
638   __pthread_multiple_threads = 1;
639 #if TLS_MULTIPLE_THREADS_IN_TCB || !defined USE_TLS || !TLS_DTV_AT_TP
640   __pthread_main_thread->p_multiple_threads = 1;
641 #endif
642   *__libc_multiple_threads_ptr = 1;
643
644 #ifndef HAVE_Z_NODELETE
645   if (__builtin_expect (&__dso_handle != NULL, 1))
646     __cxa_atexit ((void (*) (void *)) pthread_atexit_retcode, NULL,
647                   __dso_handle);
648 #endif
649
650   if (__pthread_max_stacksize == 0)
651     __pthread_init_max_stacksize ();
652   /* If basic initialization not done yet (e.g. we're called from a
653      constructor run before our constructor), do it now */
654   if (__pthread_initial_thread_bos == NULL) pthread_initialize();
655   /* Setup stack for thread manager */
656   __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
657   if (__pthread_manager_thread_bos == NULL) return -1;
658   __pthread_manager_thread_tos =
659     __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;
660   /* Setup pipe to communicate with thread manager */
661   if (pipe(manager_pipe) == -1) {
662     free(__pthread_manager_thread_bos);
663     return -1;
664   }
665
666 #ifdef USE_TLS
667   /* Allocate memory for the thread descriptor and the dtv.  */
668   tcbp = _dl_allocate_tls (NULL);
669   if (tcbp == NULL) {
670     free(__pthread_manager_thread_bos);
671     close_not_cancel(manager_pipe[0]);
672     close_not_cancel(manager_pipe[1]);
673     return -1;
674   }
675
676 # if TLS_TCB_AT_TP
677   mgr = (pthread_descr) tcbp;
678 # elif TLS_DTV_AT_TP
679   /* pthread_descr is located right below tcbhead_t which _dl_allocate_tls
680      returns.  */
681   mgr = (pthread_descr) ((char *) tcbp - TLS_PRE_TCB_SIZE);
682 # endif
683   __pthread_handles[1].h_descr = manager_thread = mgr;
684
685   /* Initialize the descriptor.  */
686 #if !defined USE_TLS || !TLS_DTV_AT_TP
687   mgr->p_header.data.tcb = tcbp;
688   mgr->p_header.data.self = mgr;
689   mgr->p_header.data.multiple_threads = 1;
690 #elif TLS_MULTIPLE_THREADS_IN_TCB
691   mgr->p_multiple_threads = 1;
692 #endif
693   mgr->p_lock = &__pthread_handles[1].h_lock;
694 # ifndef HAVE___THREAD
695   mgr->p_errnop = &mgr->p_errno;
696 # endif
697   mgr->p_start_args = (struct pthread_start_args) PTHREAD_START_ARGS_INITIALIZER(__pthread_manager);
698   mgr->p_nr = 1;
699 # if __LT_SPINLOCK_INIT != 0
700   self->p_resume_count = (struct pthread_atomic) __ATOMIC_INITIALIZER;
701 # endif
702   mgr->p_alloca_cutoff = PTHREAD_STACK_MIN / 4;
703 #else
704   mgr = &__pthread_manager_thread;
705 #endif
706
707   /* Copy the stack guard canary.  */
708 #ifdef THREAD_COPY_STACK_GUARD
709   THREAD_COPY_STACK_GUARD (mgr);
710 #endif
711
712   /* Copy the pointer guard value.  */
713 #ifdef THREAD_COPY_POINTER_GUARD
714   THREAD_COPY_POINTER_GUARD (mgr);
715 #endif
716
717   __pthread_manager_request = manager_pipe[1]; /* writing end */
718   __pthread_manager_reader = manager_pipe[0]; /* reading end */
719
720   /* Start the thread manager */
721   pid = 0;
722 #ifdef USE_TLS
723   if (__linuxthreads_initial_report_events != 0)
724     THREAD_SETMEM (((pthread_descr) NULL), p_report_events,
725                    __linuxthreads_initial_report_events);
726   report_events = THREAD_GETMEM (((pthread_descr) NULL), p_report_events);
727 #else
728   if (__linuxthreads_initial_report_events != 0)
729     __pthread_initial_thread.p_report_events
730       = __linuxthreads_initial_report_events;
731   report_events = __pthread_initial_thread.p_report_events;
732 #endif
733   if (__builtin_expect (report_events, 0))
734     {
735       /* It's a bit more complicated.  We have to report the creation of
736          the manager thread.  */
737       int idx = __td_eventword (TD_CREATE);
738       uint32_t mask = __td_eventmask (TD_CREATE);
739       uint32_t event_bits;
740
741 #ifdef USE_TLS
742       event_bits = THREAD_GETMEM_NC (((pthread_descr) NULL),
743                                      p_eventbuf.eventmask.event_bits[idx]);
744 #else
745       event_bits = __pthread_initial_thread.p_eventbuf.eventmask.event_bits[idx];
746 #endif
747
748       if ((mask & (__pthread_threads_events.event_bits[idx] | event_bits))
749           != 0)
750         {
751           __pthread_lock(mgr->p_lock, NULL);
752
753 #ifdef NEED_SEPARATE_REGISTER_STACK
754           pid = __clone2(__pthread_manager_event,
755                          (void **) __pthread_manager_thread_bos,
756                          THREAD_MANAGER_STACK_SIZE,
757                          CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_SYSVSEM,
758                          mgr);
759 #elif _STACK_GROWS_UP
760           pid = __clone(__pthread_manager_event,
761                         (void **) __pthread_manager_thread_bos,
762                         CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_SYSVSEM,
763                         mgr);
764 #else
765           pid = __clone(__pthread_manager_event,
766                         (void **) __pthread_manager_thread_tos,
767                         CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_SYSVSEM,
768                         mgr);
769 #endif
770
771           if (pid != -1)
772             {
773               /* Now fill in the information about the new thread in
774                  the newly created thread's data structure.  We cannot let
775                  the new thread do this since we don't know whether it was
776                  already scheduled when we send the event.  */
777               mgr->p_eventbuf.eventdata = mgr;
778               mgr->p_eventbuf.eventnum = TD_CREATE;
779               __pthread_last_event = mgr;
780               mgr->p_tid = 2* PTHREAD_THREADS_MAX + 1;
781               mgr->p_pid = pid;
782
783               /* Now call the function which signals the event.  */
784               __linuxthreads_create_event ();
785             }
786
787           /* Now restart the thread.  */
788           __pthread_unlock(mgr->p_lock);
789         }
790     }
791
792   if (__builtin_expect (pid, 0) == 0)
793     {
794 #ifdef NEED_SEPARATE_REGISTER_STACK
795       pid = __clone2(__pthread_manager, (void **) __pthread_manager_thread_bos,
796                      THREAD_MANAGER_STACK_SIZE,
797                      CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_SYSVSEM, mgr);
798 #elif _STACK_GROWS_UP
799       pid = __clone(__pthread_manager, (void **) __pthread_manager_thread_bos,
800                     CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_SYSVSEM, mgr);
801 #else
802       pid = __clone(__pthread_manager, (void **) __pthread_manager_thread_tos,
803                     CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_SYSVSEM, mgr);
804 #endif
805     }
806   if (__builtin_expect (pid, 0) == -1) {
807 #ifdef USE_TLS
808     _dl_deallocate_tls (tcbp, true);
809 #endif
810     free(__pthread_manager_thread_bos);
811     close_not_cancel(manager_pipe[0]);
812     close_not_cancel(manager_pipe[1]);
813     return -1;
814   }
815   mgr->p_tid = 2* PTHREAD_THREADS_MAX + 1;
816   mgr->p_pid = pid;
817   /* Make gdb aware of new thread manager */
818   if (__builtin_expect (__pthread_threads_debug, 0) && __pthread_sig_debug > 0)
819     {
820       raise(__pthread_sig_debug);
821       /* We suspend ourself and gdb will wake us up when it is
822          ready to handle us. */
823       __pthread_wait_for_restart_signal(thread_self());
824     }
825   /* Synchronize debugging of the thread manager */
826   request.req_kind = REQ_DEBUG;
827   TEMP_FAILURE_RETRY(write_not_cancel(__pthread_manager_request,
828                                       (char *) &request, sizeof(request)));
829   return 0;
830 }
831
832 /* Thread creation */
833
834 int __pthread_create_2_1(pthread_t *thread, const pthread_attr_t *attr,
835                          void * (*start_routine)(void *), void *arg)
836 {
837   pthread_descr self = thread_self();
838   struct pthread_request request;
839   int retval;
840   if (__builtin_expect (__pthread_manager_request, 0) < 0) {
841     if (__pthread_initialize_manager() < 0) return EAGAIN;
842   }
843   request.req_thread = self;
844   request.req_kind = REQ_CREATE;
845   request.req_args.create.attr = attr;
846   request.req_args.create.fn = start_routine;
847   request.req_args.create.arg = arg;
848   sigprocmask(SIG_SETMASK, (const sigset_t *) NULL,
849               &request.req_args.create.mask);
850   TEMP_FAILURE_RETRY(write_not_cancel(__pthread_manager_request,
851                                       (char *) &request, sizeof(request)));
852   suspend(self);
853   retval = THREAD_GETMEM(self, p_retcode);
854   if (__builtin_expect (retval, 0) == 0)
855     *thread = (pthread_t) THREAD_GETMEM(self, p_retval);
856   return retval;
857 }
858
859 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
860
861 #if SHLIB_COMPAT (libpthread, GLIBC_2_0, GLIBC_2_1)
862
863 int __pthread_create_2_0(pthread_t *thread, const pthread_attr_t *attr,
864                          void * (*start_routine)(void *), void *arg)
865 {
866   /* The ATTR attribute is not really of type `pthread_attr_t *'.  It has
867      the old size and access to the new members might crash the program.
868      We convert the struct now.  */
869   pthread_attr_t new_attr;
870
871   if (attr != NULL)
872     {
873       size_t ps = __getpagesize ();
874
875       memcpy (&new_attr, attr,
876               (size_t) &(((pthread_attr_t*)NULL)->__guardsize));
877       new_attr.__guardsize = ps;
878       new_attr.__stackaddr_set = 0;
879       new_attr.__stackaddr = NULL;
880       new_attr.__stacksize = STACK_SIZE - ps;
881       attr = &new_attr;
882     }
883   return __pthread_create_2_1 (thread, attr, start_routine, arg);
884 }
885 compat_symbol (libpthread, __pthread_create_2_0, pthread_create, GLIBC_2_0);
886 #endif
887
888 /* Simple operations on thread identifiers */
889
890 pthread_descr __pthread_thread_self(void)
891 {
892   return thread_self();
893 }
894
895 pthread_t __pthread_self(void)
896 {
897   pthread_descr self = thread_self();
898   return THREAD_GETMEM(self, p_tid);
899 }
900 strong_alias (__pthread_self, pthread_self);
901
902 int __pthread_equal(pthread_t thread1, pthread_t thread2)
903 {
904   return thread1 == thread2;
905 }
906 strong_alias (__pthread_equal, pthread_equal);
907
908 /* Helper function for thread_self in the case of user-provided stacks */
909
910 #ifndef THREAD_SELF
911
912 pthread_descr __pthread_find_self(void)
913 {
914   char * sp = CURRENT_STACK_FRAME;
915   pthread_handle h;
916
917   /* __pthread_handles[0] is the initial thread, __pthread_handles[1] is
918      the manager threads handled specially in thread_self(), so start at 2 */
919   h = __pthread_handles + 2;
920 # ifdef _STACK_GROWS_UP
921   while (! (sp >= (char *) h->h_descr && sp < h->h_descr->p_guardaddr)) h++;
922 # else
923   while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;
924 # endif
925   return h->h_descr;
926 }
927
928 #else
929
930 pthread_descr __pthread_self_stack(void)
931 {
932   char *sp = CURRENT_STACK_FRAME;
933   pthread_handle h;
934
935   if (sp >= __pthread_manager_thread_bos && sp < __pthread_manager_thread_tos)
936     return manager_thread;
937   h = __pthread_handles + 2;
938 # ifdef USE_TLS
939 #  ifdef _STACK_GROWS_UP
940   while (h->h_descr == NULL
941          || ! (sp >= h->h_descr->p_stackaddr && sp < h->h_descr->p_guardaddr))
942     h++;
943 #  else
944   while (h->h_descr == NULL
945          || ! (sp <= (char *) h->h_descr->p_stackaddr && sp >= h->h_bottom))
946     h++;
947 #  endif
948 # else
949 #  ifdef _STACK_GROWS_UP
950   while (! (sp >= (char *) h->h_descr && sp < h->h_descr->p_guardaddr))
951     h++;
952 #  else
953   while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom))
954     h++;
955 #  endif
956 # endif
957   return h->h_descr;
958 }
959
960 #endif
961
962 /* Thread scheduling */
963
964 int __pthread_setschedparam(pthread_t thread, int policy,
965                             const struct sched_param *param)
966 {
967   pthread_handle handle = thread_handle(thread);
968   pthread_descr th;
969
970   __pthread_lock(&handle->h_lock, NULL);
971   if (__builtin_expect (invalid_handle(handle, thread), 0)) {
972     __pthread_unlock(&handle->h_lock);
973     return ESRCH;
974   }
975   th = handle->h_descr;
976   if (__builtin_expect (__sched_setscheduler(th->p_pid, policy, param) == -1,
977                         0)) {
978     __pthread_unlock(&handle->h_lock);
979     return errno;
980   }
981   th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
982   __pthread_unlock(&handle->h_lock);
983   if (__pthread_manager_request >= 0)
984     __pthread_manager_adjust_prio(th->p_priority);
985   return 0;
986 }
987 strong_alias (__pthread_setschedparam, pthread_setschedparam);
988
989 int __pthread_getschedparam(pthread_t thread, int *policy,
990                             struct sched_param *param)
991 {
992   pthread_handle handle = thread_handle(thread);
993   int pid, pol;
994
995   __pthread_lock(&handle->h_lock, NULL);
996   if (__builtin_expect (invalid_handle(handle, thread), 0)) {
997     __pthread_unlock(&handle->h_lock);
998     return ESRCH;
999   }
1000   pid = handle->h_descr->p_pid;
1001   __pthread_unlock(&handle->h_lock);
1002   pol = __sched_getscheduler(pid);
1003   if (__builtin_expect (pol, 0) == -1) return errno;
1004   if (__sched_getparam(pid, param) == -1) return errno;
1005   *policy = pol;
1006   return 0;
1007 }
1008 strong_alias (__pthread_getschedparam, pthread_getschedparam);
1009
1010 int __pthread_yield (void)
1011 {
1012   /* For now this is equivalent with the POSIX call.  */
1013   return sched_yield ();
1014 }
1015 weak_alias (__pthread_yield, pthread_yield)
1016
1017 /* Process-wide exit() request */
1018
1019 static void pthread_onexit_process(int retcode, void *arg)
1020 {
1021   if (__builtin_expect (__pthread_manager_request, 0) >= 0) {
1022     struct pthread_request request;
1023     pthread_descr self = thread_self();
1024
1025     /* Make sure we come back here after suspend(), in case we entered
1026        from a signal handler.  */
1027     THREAD_SETMEM(self, p_signal_jmp, NULL);
1028
1029     request.req_thread = self;
1030     request.req_kind = REQ_PROCESS_EXIT;
1031     request.req_args.exit.code = retcode;
1032     TEMP_FAILURE_RETRY(write_not_cancel(__pthread_manager_request,
1033                                         (char *) &request, sizeof(request)));
1034     suspend(self);
1035     /* Main thread should accumulate times for thread manager and its
1036        children, so that timings for main thread account for all threads. */
1037     if (self == __pthread_main_thread)
1038       {
1039 #ifdef USE_TLS
1040         waitpid(manager_thread->p_pid, NULL, __WCLONE);
1041 #else
1042         waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
1043 #endif
1044         /* Since all threads have been asynchronously terminated
1045            (possibly holding locks), free cannot be used any more.
1046            For mtrace, we'd like to print something though.  */
1047         /* #ifdef USE_TLS
1048            tcbhead_t *tcbp = (tcbhead_t *) manager_thread;
1049            # if TLS_DTV_AT_TP
1050            tcbp = (tcbhead_t) ((char *) tcbp + TLS_PRE_TCB_SIZE);
1051            # endif
1052            _dl_deallocate_tls (tcbp, true);
1053            #endif
1054            free (__pthread_manager_thread_bos); */
1055         __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
1056       }
1057   }
1058 }
1059
1060 #ifndef HAVE_Z_NODELETE
1061 static int __pthread_atexit_retcode;
1062
1063 static void pthread_atexit_process(void *arg, int retcode)
1064 {
1065   pthread_onexit_process (retcode ?: __pthread_atexit_retcode, arg);
1066 }
1067
1068 static void pthread_atexit_retcode(void *arg, int retcode)
1069 {
1070   __pthread_atexit_retcode = retcode;
1071 }
1072 #endif
1073
1074 /* The handler for the RESTART signal just records the signal received
1075    in the thread descriptor, and optionally performs a siglongjmp
1076    (for pthread_cond_timedwait). */
1077
1078 static void pthread_handle_sigrestart(int sig)
1079 {
1080   pthread_descr self = check_thread_self();
1081   THREAD_SETMEM(self, p_signal, sig);
1082   if (THREAD_GETMEM(self, p_signal_jmp) != NULL)
1083     siglongjmp(*THREAD_GETMEM(self, p_signal_jmp), 1);
1084 }
1085
1086 /* The handler for the CANCEL signal checks for cancellation
1087    (in asynchronous mode), for process-wide exit and exec requests.
1088    For the thread manager thread, redirect the signal to
1089    __pthread_manager_sighandler. */
1090
1091 static void pthread_handle_sigcancel(int sig)
1092 {
1093   pthread_descr self = check_thread_self();
1094   sigjmp_buf * jmpbuf;
1095
1096   if (self == manager_thread)
1097     {
1098       __pthread_manager_sighandler(sig);
1099       return;
1100     }
1101   if (__builtin_expect (__pthread_exit_requested, 0)) {
1102     /* Main thread should accumulate times for thread manager and its
1103        children, so that timings for main thread account for all threads. */
1104     if (self == __pthread_main_thread) {
1105 #ifdef USE_TLS
1106       waitpid(manager_thread->p_pid, NULL, __WCLONE);
1107 #else
1108       waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
1109 #endif
1110     }
1111     _exit(__pthread_exit_code);
1112   }
1113   if (__builtin_expect (THREAD_GETMEM(self, p_canceled), 0)
1114       && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
1115     if (THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
1116       __pthread_do_exit(PTHREAD_CANCELED, CURRENT_STACK_FRAME);
1117     jmpbuf = THREAD_GETMEM(self, p_cancel_jmp);
1118     if (jmpbuf != NULL) {
1119       THREAD_SETMEM(self, p_cancel_jmp, NULL);
1120       siglongjmp(*jmpbuf, 1);
1121     }
1122   }
1123 }
1124
1125 /* Handler for the DEBUG signal.
1126    The debugging strategy is as follows:
1127    On reception of a REQ_DEBUG request (sent by new threads created to
1128    the thread manager under debugging mode), the thread manager throws
1129    __pthread_sig_debug to itself. The debugger (if active) intercepts
1130    this signal, takes into account new threads and continue execution
1131    of the thread manager by propagating the signal because it doesn't
1132    know what it is specifically done for. In the current implementation,
1133    the thread manager simply discards it. */
1134
1135 static void pthread_handle_sigdebug(int sig)
1136 {
1137   /* Nothing */
1138 }
1139
1140 /* Reset the state of the thread machinery after a fork().
1141    Close the pipe used for requests and set the main thread to the forked
1142    thread.
1143    Notice that we can't free the stack segments, as the forked thread
1144    may hold pointers into them. */
1145
1146 void __pthread_reset_main_thread(void)
1147 {
1148   pthread_descr self = thread_self();
1149
1150   if (__pthread_manager_request != -1) {
1151     /* Free the thread manager stack */
1152     free(__pthread_manager_thread_bos);
1153     __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
1154     /* Close the two ends of the pipe */
1155     close_not_cancel(__pthread_manager_request);
1156     close_not_cancel(__pthread_manager_reader);
1157     __pthread_manager_request = __pthread_manager_reader = -1;
1158   }
1159
1160   /* Update the pid of the main thread */
1161   THREAD_SETMEM(self, p_pid, __getpid());
1162   /* Make the forked thread the main thread */
1163   __pthread_main_thread = self;
1164   THREAD_SETMEM(self, p_nextlive, self);
1165   THREAD_SETMEM(self, p_prevlive, self);
1166 #if !(USE_TLS && HAVE___THREAD)
1167   /* Now this thread modifies the global variables.  */
1168   THREAD_SETMEM(self, p_errnop, &_errno);
1169   THREAD_SETMEM(self, p_h_errnop, &_h_errno);
1170   THREAD_SETMEM(self, p_resp, &_res);
1171 #endif
1172
1173 #ifndef FLOATING_STACKS
1174   /* This is to undo the setrlimit call in __pthread_init_max_stacksize.
1175      XXX This can be wrong if the user set the limit during the run.  */
1176  {
1177    struct rlimit limit;
1178    if (getrlimit (RLIMIT_STACK, &limit) == 0
1179        && limit.rlim_cur != limit.rlim_max)
1180      {
1181        limit.rlim_cur = limit.rlim_max;
1182        setrlimit(RLIMIT_STACK, &limit);
1183      }
1184  }
1185 #endif
1186 }
1187
1188 /* Process-wide exec() request */
1189
1190 void __pthread_kill_other_threads_np(void)
1191 {
1192   struct sigaction sa;
1193   /* Terminate all other threads and thread manager */
1194   pthread_onexit_process(0, NULL);
1195   /* Make current thread the main thread in case the calling thread
1196      changes its mind, does not exec(), and creates new threads instead. */
1197   __pthread_reset_main_thread();
1198
1199   /* Reset the signal handlers behaviour for the signals the
1200      implementation uses since this would be passed to the new
1201      process.  */
1202   sigemptyset(&sa.sa_mask);
1203   sa.sa_flags = 0;
1204   sa.sa_handler = SIG_DFL;
1205   __libc_sigaction(__pthread_sig_restart, &sa, NULL);
1206   __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
1207   if (__pthread_sig_debug > 0)
1208     __libc_sigaction(__pthread_sig_debug, &sa, NULL);
1209 }
1210 weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
1211
1212 /* Concurrency symbol level.  */
1213 static int current_level;
1214
1215 int __pthread_setconcurrency(int level)
1216 {
1217   /* We don't do anything unless we have found a useful interpretation.  */
1218   current_level = level;
1219   return 0;
1220 }
1221 weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
1222
1223 int __pthread_getconcurrency(void)
1224 {
1225   return current_level;
1226 }
1227 weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
1228
1229 /* Primitives for controlling thread execution */
1230
1231 void __pthread_wait_for_restart_signal(pthread_descr self)
1232 {
1233   sigset_t mask;
1234
1235   sigprocmask(SIG_SETMASK, NULL, &mask); /* Get current signal mask */
1236   sigdelset(&mask, __pthread_sig_restart); /* Unblock the restart signal */
1237   THREAD_SETMEM(self, p_signal, 0);
1238   do {
1239     __pthread_sigsuspend(&mask);        /* Wait for signal.  Must not be a
1240                                            cancellation point. */
1241   } while (THREAD_GETMEM(self, p_signal) !=__pthread_sig_restart);
1242
1243   READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
1244 }
1245
1246 #if !__ASSUME_REALTIME_SIGNALS
1247 /* The _old variants are for 2.0 and early 2.1 kernels which don't have RT
1248    signals.
1249    On these kernels, we use SIGUSR1 and SIGUSR2 for restart and cancellation.
1250    Since the restart signal does not queue, we use an atomic counter to create
1251    queuing semantics. This is needed to resolve a rare race condition in
1252    pthread_cond_timedwait_relative. */
1253
1254 void __pthread_restart_old(pthread_descr th)
1255 {
1256   if (pthread_atomic_increment(&th->p_resume_count) == -1)
1257     kill(th->p_pid, __pthread_sig_restart);
1258 }
1259
1260 void __pthread_suspend_old(pthread_descr self)
1261 {
1262   if (pthread_atomic_decrement(&self->p_resume_count) <= 0)
1263     __pthread_wait_for_restart_signal(self);
1264 }
1265
1266 int
1267 __pthread_timedsuspend_old(pthread_descr self, const struct timespec *abstime)
1268 {
1269   sigset_t unblock, initial_mask;
1270   int was_signalled = 0;
1271   sigjmp_buf jmpbuf;
1272
1273   if (pthread_atomic_decrement(&self->p_resume_count) == 0) {
1274     /* Set up a longjmp handler for the restart signal, unblock
1275        the signal and sleep. */
1276
1277     if (sigsetjmp(jmpbuf, 1) == 0) {
1278       THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
1279       THREAD_SETMEM(self, p_signal, 0);
1280       /* Unblock the restart signal */
1281       sigemptyset(&unblock);
1282       sigaddset(&unblock, __pthread_sig_restart);
1283       sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
1284
1285       while (1) {
1286         struct timeval now;
1287         struct timespec reltime;
1288
1289         /* Compute a time offset relative to now.  */
1290         __gettimeofday (&now, NULL);
1291         reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
1292         reltime.tv_sec = abstime->tv_sec - now.tv_sec;
1293         if (reltime.tv_nsec < 0) {
1294           reltime.tv_nsec += 1000000000;
1295           reltime.tv_sec -= 1;
1296         }
1297
1298         /* Sleep for the required duration. If woken by a signal,
1299            resume waiting as required by Single Unix Specification.  */
1300         if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
1301           break;
1302       }
1303
1304       /* Block the restart signal again */
1305       sigprocmask(SIG_SETMASK, &initial_mask, NULL);
1306       was_signalled = 0;
1307     } else {
1308       was_signalled = 1;
1309     }
1310     THREAD_SETMEM(self, p_signal_jmp, NULL);
1311   }
1312
1313   /* Now was_signalled is true if we exited the above code
1314      due to the delivery of a restart signal.  In that case,
1315      we know we have been dequeued and resumed and that the
1316      resume count is balanced.  Otherwise, there are some
1317      cases to consider. First, try to bump up the resume count
1318      back to zero. If it goes to 1, it means restart() was
1319      invoked on this thread. The signal must be consumed
1320      and the count bumped down and everything is cool. We
1321      can return a 1 to the caller.
1322      Otherwise, no restart was delivered yet, so a potential
1323      race exists; we return a 0 to the caller which must deal
1324      with this race in an appropriate way; for example by
1325      atomically removing the thread from consideration for a
1326      wakeup---if such a thing fails, it means a restart is
1327      being delivered. */
1328
1329   if (!was_signalled) {
1330     if (pthread_atomic_increment(&self->p_resume_count) != -1) {
1331       __pthread_wait_for_restart_signal(self);
1332       pthread_atomic_decrement(&self->p_resume_count); /* should be zero now! */
1333       /* woke spontaneously and consumed restart signal */
1334       return 1;
1335     }
1336     /* woke spontaneously but did not consume restart---caller must resolve */
1337     return 0;
1338   }
1339   /* woken due to restart signal */
1340   return 1;
1341 }
1342 #endif /* __ASSUME_REALTIME_SIGNALS */
1343
1344 void __pthread_restart_new(pthread_descr th)
1345 {
1346   /* The barrier is proabably not needed, in which case it still documents
1347      our assumptions. The intent is to commit previous writes to shared
1348      memory so the woken thread will have a consistent view.  Complementary
1349      read barriers are present to the suspend functions. */
1350   WRITE_MEMORY_BARRIER();
1351   kill(th->p_pid, __pthread_sig_restart);
1352 }
1353
1354 /* There is no __pthread_suspend_new because it would just
1355    be a wasteful wrapper for __pthread_wait_for_restart_signal */
1356
1357 int
1358 __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime)
1359 {
1360   sigset_t unblock, initial_mask;
1361   int was_signalled = 0;
1362   sigjmp_buf jmpbuf;
1363
1364   if (sigsetjmp(jmpbuf, 1) == 0) {
1365     THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
1366     THREAD_SETMEM(self, p_signal, 0);
1367     /* Unblock the restart signal */
1368     sigemptyset(&unblock);
1369     sigaddset(&unblock, __pthread_sig_restart);
1370     sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
1371
1372     while (1) {
1373       struct timeval now;
1374       struct timespec reltime;
1375
1376       /* Compute a time offset relative to now.  */
1377       __gettimeofday (&now, NULL);
1378       reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
1379       reltime.tv_sec = abstime->tv_sec - now.tv_sec;
1380       if (reltime.tv_nsec < 0) {
1381         reltime.tv_nsec += 1000000000;
1382         reltime.tv_sec -= 1;
1383       }
1384
1385       /* Sleep for the required duration. If woken by a signal,
1386          resume waiting as required by Single Unix Specification.  */
1387       if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
1388         break;
1389     }
1390
1391     /* Block the restart signal again */
1392     sigprocmask(SIG_SETMASK, &initial_mask, NULL);
1393     was_signalled = 0;
1394   } else {
1395     was_signalled = 1;
1396   }
1397   THREAD_SETMEM(self, p_signal_jmp, NULL);
1398
1399   /* Now was_signalled is true if we exited the above code
1400      due to the delivery of a restart signal.  In that case,
1401      everything is cool. We have been removed from whatever
1402      we were waiting on by the other thread, and consumed its signal.
1403
1404      Otherwise we this thread woke up spontaneously, or due to a signal other
1405      than restart. This is an ambiguous case  that must be resolved by
1406      the caller; the thread is still eligible for a restart wakeup
1407      so there is a race. */
1408
1409   READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
1410   return was_signalled;
1411 }
1412
1413
1414 /* Debugging aid */
1415
1416 #ifdef DEBUG
1417 #include <stdarg.h>
1418
1419 void __pthread_message(const char * fmt, ...)
1420 {
1421   char buffer[1024];
1422   va_list args;
1423   sprintf(buffer, "%05d : ", __getpid());
1424   va_start(args, fmt);
1425   vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
1426   va_end(args);
1427   TEMP_FAILURE_RETRY(write_not_cancel(2, buffer, strlen(buffer)));
1428 }
1429
1430 #endif