1a2888f3c69d964d5613aec3a4ec5d2a5e6bdc53
[platform/upstream/glibc.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/sysctl.h>
28 #include <shlib-compat.h>
29 #include "pthread.h"
30 #include "internals.h"
31 #include "spinlock.h"
32 #include "restart.h"
33
34 /* We need the global/static resolver state here.  */
35 #include <resolv.h>
36 #undef _res
37
38 extern struct __res_state _res;
39
40 /* Sanity check.  */
41 #if __ASSUME_REALTIME_SIGNALS && !defined __SIGRTMIN
42 # error "This must not happen; new kernel assumed but old headers"
43 #endif
44
45 /* These variables are used by the setup code.  */
46 extern int _errno;
47 extern int _h_errno;
48
49 /* Descriptor of the initial thread */
50
51 struct _pthread_descr_struct __pthread_initial_thread = {
52   {
53     {
54       &__pthread_initial_thread /* pthread_descr self */
55     }
56   },
57   &__pthread_initial_thread,  /* pthread_descr p_nextlive */
58   &__pthread_initial_thread,  /* pthread_descr p_prevlive */
59   NULL,                       /* pthread_descr p_nextwaiting */
60   NULL,                       /* pthread_descr p_nextlock */
61   PTHREAD_THREADS_MAX,        /* pthread_t p_tid */
62   0,                          /* int p_pid */
63   0,                          /* int p_priority */
64   &__pthread_handles[0].h_lock, /* struct _pthread_fastlock * p_lock */
65   0,                          /* int p_signal */
66   NULL,                       /* sigjmp_buf * p_signal_buf */
67   NULL,                       /* sigjmp_buf * p_cancel_buf */
68   0,                          /* char p_terminated */
69   0,                          /* char p_detached */
70   0,                          /* char p_exited */
71   NULL,                       /* void * p_retval */
72   0,                          /* int p_retval */
73   NULL,                       /* pthread_descr p_joining */
74   NULL,                       /* struct _pthread_cleanup_buffer * p_cleanup */
75   0,                          /* char p_cancelstate */
76   0,                          /* char p_canceltype */
77   0,                          /* char p_canceled */
78   &_errno,                    /* int *p_errnop */
79   0,                          /* int p_errno */
80   &_h_errno,                  /* int *p_h_errnop */
81   0,                          /* int p_h_errno */
82   NULL,                       /* char * p_in_sighandler */
83   0,                          /* char p_sigwaiting */
84   PTHREAD_START_ARGS_INITIALIZER(NULL),
85                               /* struct pthread_start_args p_start_args */
86   {NULL},                     /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
87   {NULL},                     /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
88   1,                          /* int p_userstack */
89   NULL,                       /* void * p_guardaddr */
90   0,                          /* size_t p_guardsize */
91   0,                          /* Always index 0 */
92   0,                          /* int p_report_events */
93   {{{0, }}, 0, NULL},         /* td_eventbuf_t p_eventbuf */
94   __ATOMIC_INITIALIZER,       /* struct pthread_atomic p_resume_count */
95   0,                          /* char p_woken_by_cancel */
96   0,                          /* char p_condvar_avail */
97   0,                          /* char p_sem_avail */
98   NULL,                       /* struct pthread_extricate_if *p_extricate */
99   NULL,                       /* pthread_readlock_info *p_readlock_list; */
100   NULL,                       /* pthread_readlock_info *p_readlock_free; */
101   0                           /* int p_untracked_readlock_count; */
102 };
103
104 /* Descriptor of the manager thread; none of this is used but the error
105    variables, the p_pid and p_priority fields,
106    and the address for identification.  */
107
108 struct _pthread_descr_struct __pthread_manager_thread = {
109   {
110     {
111       &__pthread_manager_thread /* pthread_descr self */
112     }
113   },
114   NULL,                       /* pthread_descr p_nextlive */
115   NULL,                       /* pthread_descr p_prevlive */
116   NULL,                       /* pthread_descr p_nextwaiting */
117   NULL,                       /* pthread_descr p_nextlock */
118   0,                          /* int p_tid */
119   0,                          /* int p_pid */
120   0,                          /* int p_priority */
121   &__pthread_handles[1].h_lock, /* struct _pthread_fastlock * p_lock */
122   0,                          /* int p_signal */
123   NULL,                       /* sigjmp_buf * p_signal_buf */
124   NULL,                       /* sigjmp_buf * p_cancel_buf */
125   0,                          /* char p_terminated */
126   0,                          /* char p_detached */
127   0,                          /* char p_exited */
128   NULL,                       /* void * p_retval */
129   0,                          /* int p_retval */
130   NULL,                       /* pthread_descr p_joining */
131   NULL,                       /* struct _pthread_cleanup_buffer * p_cleanup */
132   0,                          /* char p_cancelstate */
133   0,                          /* char p_canceltype */
134   0,                          /* char p_canceled */
135   &__pthread_manager_thread.p_errno, /* int *p_errnop */
136   0,                          /* int p_errno */
137   NULL,                       /* int *p_h_errnop */
138   0,                          /* int p_h_errno */
139   NULL,                       /* char * p_in_sighandler */
140   0,                          /* char p_sigwaiting */
141   PTHREAD_START_ARGS_INITIALIZER(__pthread_manager),
142                               /* struct pthread_start_args p_start_args */
143   {NULL},                     /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
144   {NULL},                     /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
145   0,                          /* int p_userstack */
146   NULL,                       /* void * p_guardaddr */
147   0,                          /* size_t p_guardsize */
148   1,                          /* Always index 1 */
149   0,                          /* int p_report_events */
150   {{{0, }}, 0, NULL},         /* td_eventbuf_t p_eventbuf */
151   __ATOMIC_INITIALIZER,       /* struct pthread_atomic p_resume_count */
152   0,                          /* char p_woken_by_cancel */
153   0,                          /* char p_condvar_avail */
154   0,                          /* char p_sem_avail */
155   NULL,                       /* struct pthread_extricate_if *p_extricate */
156   NULL,                       /* pthread_readlock_info *p_readlock_list; */
157   NULL,                       /* pthread_readlock_info *p_readlock_free; */
158   0                           /* int p_untracked_readlock_count; */
159 };
160
161 /* Pointer to the main thread (the father of the thread manager thread) */
162 /* Originally, this is the initial thread, but this changes after fork() */
163
164 pthread_descr __pthread_main_thread = &__pthread_initial_thread;
165
166 /* Limit between the stack of the initial thread (above) and the
167    stacks of other threads (below). Aligned on a STACK_SIZE boundary. */
168
169 char *__pthread_initial_thread_bos;
170
171 /* File descriptor for sending requests to the thread manager. */
172 /* Initially -1, meaning that the thread manager is not running. */
173
174 int __pthread_manager_request = -1;
175
176 /* Other end of the pipe for sending requests to the thread manager. */
177
178 int __pthread_manager_reader;
179
180 /* Limits of the thread manager stack */
181
182 char *__pthread_manager_thread_bos;
183 char *__pthread_manager_thread_tos;
184
185 /* For process-wide exit() */
186
187 int __pthread_exit_requested;
188 int __pthread_exit_code;
189
190 /* Maximum stack size.  */
191 size_t __pthread_max_stacksize;
192
193 /* Nozero if the machine has more than one processor.  */
194 int __pthread_smp_kernel;
195
196
197 #if !__ASSUME_REALTIME_SIGNALS
198 /* Pointers that select new or old suspend/resume functions
199    based on availability of rt signals. */
200
201 void (*__pthread_restart)(pthread_descr) = __pthread_restart_old;
202 void (*__pthread_suspend)(pthread_descr) = __pthread_suspend_old;
203 int (*__pthread_timedsuspend)(pthread_descr, const struct timespec *) = __pthread_timedsuspend_old;
204 #endif  /* __ASSUME_REALTIME_SIGNALS */
205
206 /* Communicate relevant LinuxThreads constants to gdb */
207
208 const int __pthread_threads_max = PTHREAD_THREADS_MAX;
209 const int __pthread_sizeof_handle = sizeof(struct pthread_handle_struct);
210 const int __pthread_offsetof_descr = offsetof(struct pthread_handle_struct,
211                                               h_descr);
212 const int __pthread_offsetof_pid = offsetof(struct _pthread_descr_struct,
213                                             p_pid);
214 const int __linuxthreads_pthread_sizeof_descr
215   = sizeof(struct _pthread_descr_struct);
216
217 /* Forward declarations */
218
219 static void pthread_onexit_process(int retcode, void *arg);
220 #ifndef HAVE_Z_NODELETE
221 static void pthread_atexit_process(void *arg, int retcode);
222 static void pthread_atexit_retcode(void *arg, int retcode);
223 #endif
224 static void pthread_handle_sigcancel(int sig);
225 static void pthread_handle_sigrestart(int sig);
226 static void pthread_handle_sigdebug(int sig);
227
228 /* CPU clock handling.  */
229 #if HP_TIMING_AVAIL
230 extern hp_timing_t _dl_cpuclock_offset;
231 #endif
232
233 /* Signal numbers used for the communication.
234    In these variables we keep track of the used variables.  If the
235    platform does not support any real-time signals we will define the
236    values to some unreasonable value which will signal failing of all
237    the functions below.  */
238 #ifndef __SIGRTMIN
239 static int current_rtmin = -1;
240 static int current_rtmax = -1;
241 int __pthread_sig_restart = SIGUSR1;
242 int __pthread_sig_cancel = SIGUSR2;
243 int __pthread_sig_debug;
244 #else
245 static int current_rtmin;
246 static int current_rtmax;
247
248 #if __SIGRTMAX - __SIGRTMIN >= 3
249 int __pthread_sig_restart = __SIGRTMIN;
250 int __pthread_sig_cancel = __SIGRTMIN + 1;
251 int __pthread_sig_debug = __SIGRTMIN + 2;
252 #else
253 int __pthread_sig_restart = SIGUSR1;
254 int __pthread_sig_cancel = SIGUSR2;
255 int __pthread_sig_debug;
256 #endif
257
258 static int rtsigs_initialized;
259
260 #if !__ASSUME_REALTIME_SIGNALS
261 # include "testrtsig.h"
262 #endif
263
264 static void
265 init_rtsigs (void)
266 {
267 #if !__ASSUME_REALTIME_SIGNALS
268   if (__builtin_expect (!kernel_has_rtsig (), 0))
269     {
270       current_rtmin = -1;
271       current_rtmax = -1;
272 # if __SIGRTMAX - __SIGRTMIN >= 3
273       __pthread_sig_restart = SIGUSR1;
274       __pthread_sig_cancel = SIGUSR2;
275       __pthread_sig_debug = 0;
276 # endif
277     }
278   else
279 #endif  /* __ASSUME_REALTIME_SIGNALS */
280     {
281 #if __SIGRTMAX - __SIGRTMIN >= 3
282       current_rtmin = __SIGRTMIN + 3;
283 # if !__ASSUME_REALTIME_SIGNALS
284       __pthread_restart = __pthread_restart_new;
285       __pthread_suspend = __pthread_wait_for_restart_signal;
286       __pthread_timedsuspend = __pthread_timedsuspend_new;
287 # endif /* __ASSUME_REALTIME_SIGNALS */
288 #else
289       current_rtmin = __SIGRTMIN;
290 #endif
291
292       current_rtmax = __SIGRTMAX;
293     }
294
295   rtsigs_initialized = 1;
296 }
297 #endif
298
299 /* Return number of available real-time signal with highest priority.  */
300 int
301 __libc_current_sigrtmin (void)
302 {
303 #ifdef __SIGRTMIN
304   if (__builtin_expect (!rtsigs_initialized, 0))
305     init_rtsigs ();
306 #endif
307   return current_rtmin;
308 }
309
310 /* Return number of available real-time signal with lowest priority.  */
311 int
312 __libc_current_sigrtmax (void)
313 {
314 #ifdef __SIGRTMIN
315   if (__builtin_expect (!rtsigs_initialized, 0))
316     init_rtsigs ();
317 #endif
318   return current_rtmax;
319 }
320
321 /* Allocate real-time signal with highest/lowest available
322    priority.  Please note that we don't use a lock since we assume
323    this function to be called at program start.  */
324 int
325 __libc_allocate_rtsig (int high)
326 {
327 #ifndef __SIGRTMIN
328   return -1;
329 #else
330   if (__builtin_expect (!rtsigs_initialized, 0))
331     init_rtsigs ();
332   if (__builtin_expect (current_rtmin == -1, 0)
333       || __builtin_expect (current_rtmin > current_rtmax, 0))
334     /* We don't have anymore signal available.  */
335     return -1;
336
337   return high ? current_rtmin++ : current_rtmax--;
338 #endif
339 }
340
341 /* The function we use to get the kernel revision.  */
342 extern int __sysctl (int *name, int nlen, void *oldval, size_t *oldlenp,
343                      void *newval, size_t newlen);
344
345 /* Test whether the machine has more than one processor.  This is not the
346    best test but good enough.  More complicated tests would require `malloc'
347    which is not available at that time.  */
348 static int
349 is_smp_system (void)
350 {
351   static const int sysctl_args[] = { CTL_KERN, KERN_VERSION };
352   char buf[512];
353   size_t reslen = sizeof (buf);
354
355   /* Try reading the number using `sysctl' first.  */
356   if (__sysctl ((int *) sysctl_args,
357                 sizeof (sysctl_args) / sizeof (sysctl_args[0]),
358                 buf, &reslen, NULL, 0) < 0)
359     {
360       /* This was not successful.  Now try reading the /proc filesystem.  */
361       int fd = __open ("/proc/sys/kernel/version", O_RDONLY);
362       if (__builtin_expect (fd, 0) == -1
363           || (reslen = __read (fd, buf, sizeof (buf))) <= 0)
364         /* This also didn't work.  We give up and say it's a UP machine.  */
365         buf[0] = '\0';
366
367       __close (fd);
368     }
369
370   return strstr (buf, "SMP") != NULL;
371 }
372
373
374 /* Initialize the pthread library.
375    Initialization is split in two functions:
376    - a constructor function that blocks the __pthread_sig_restart signal
377      (must do this very early, since the program could capture the signal
378       mask with e.g. sigsetjmp before creating the first thread);
379    - a regular function called from pthread_create when needed. */
380
381 static void pthread_initialize(void) __attribute__((constructor));
382
383 #ifndef HAVE_Z_NODELETE
384 extern void *__dso_handle __attribute__ ((weak));
385 #endif
386
387
388 /* Do some minimal initialization which has to be done during the
389    startup of the C library.  */
390 void
391 __pthread_initialize_minimal(void)
392 {
393   /* If we have special thread_self processing, initialize that for the
394      main thread now.  */
395 #ifdef INIT_THREAD_SELF
396   INIT_THREAD_SELF(&__pthread_initial_thread, 0);
397 #endif
398 #if HP_TIMING_AVAIL
399   __pthread_initial_thread.p_cpuclock_offset = _dl_cpuclock_offset;
400 #endif
401 }
402
403
404 void
405 __pthread_init_max_stacksize(void)
406 {
407   struct rlimit limit;
408   size_t max_stack;
409
410   getrlimit(RLIMIT_STACK, &limit);
411 #ifdef FLOATING_STACKS
412   if (limit.rlim_cur == RLIM_INFINITY)
413     limit.rlim_cur = ARCH_STACK_MAX_SIZE;
414 # ifdef NEED_SEPARATE_REGISTER_STACK
415   max_stack = limit.rlim_cur / 2;
416 # else
417   max_stack = limit.rlim_cur;
418 # endif
419 #else
420   /* Play with the stack size limit to make sure that no stack ever grows
421      beyond STACK_SIZE minus one page (to act as a guard page). */
422 # ifdef NEED_SEPARATE_REGISTER_STACK
423   /* STACK_SIZE bytes hold both the main stack and register backing
424      store. The rlimit value applies to each individually.  */
425   max_stack = STACK_SIZE/2 - __getpagesize ();
426 # else
427   max_stack = STACK_SIZE - __getpagesize();
428 # endif
429   if (limit.rlim_cur > max_stack) {
430     limit.rlim_cur = max_stack;
431     setrlimit(RLIMIT_STACK, &limit);
432   }
433 #endif
434   __pthread_max_stacksize = max_stack;
435 }
436
437
438 static void pthread_initialize(void)
439 {
440   struct sigaction sa;
441   sigset_t mask;
442
443   /* If already done (e.g. by a constructor called earlier!), bail out */
444   if (__pthread_initial_thread_bos != NULL) return;
445 #ifdef TEST_FOR_COMPARE_AND_SWAP
446   /* Test if compare-and-swap is available */
447   __pthread_has_cas = compare_and_swap_is_available();
448 #endif
449 #ifdef FLOATING_STACKS
450   /* We don't need to know the bottom of the stack.  Give the pointer some
451      value to signal that initialization happened.  */
452   __pthread_initial_thread_bos = (void *) -1l;
453 #else
454   /* Determine stack size limits .  */
455   __pthread_init_max_stacksize ();
456 # ifdef _STACK_GROWS_UP
457   /* The initial thread already has all the stack it needs */
458   __pthread_initial_thread_bos = (char *)
459     ((long)CURRENT_STACK_FRAME &~ (STACK_SIZE - 1));
460 # else
461   /* For the initial stack, reserve at least STACK_SIZE bytes of stack
462      below the current stack address, and align that on a
463      STACK_SIZE boundary. */
464   __pthread_initial_thread_bos =
465     (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
466 # endif
467 #endif
468   /* Update the descriptor for the initial thread. */
469   __pthread_initial_thread.p_pid = __getpid();
470   /* Likewise for the resolver state _res.  */
471   __pthread_initial_thread.p_resp = &_res;
472 #ifdef __SIGRTMIN
473   /* Initialize real-time signals. */
474   init_rtsigs ();
475 #endif
476   /* Setup signal handlers for the initial thread.
477      Since signal handlers are shared between threads, these settings
478      will be inherited by all other threads. */
479   sa.sa_handler = pthread_handle_sigrestart;
480   sigemptyset(&sa.sa_mask);
481   sa.sa_flags = 0;
482   __libc_sigaction(__pthread_sig_restart, &sa, NULL);
483   sa.sa_handler = pthread_handle_sigcancel;
484   // sa.sa_flags = 0;
485   __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
486   if (__pthread_sig_debug > 0) {
487     sa.sa_handler = pthread_handle_sigdebug;
488     sigemptyset(&sa.sa_mask);
489     // sa.sa_flags = 0;
490     __libc_sigaction(__pthread_sig_debug, &sa, NULL);
491   }
492   /* Initially, block __pthread_sig_restart. Will be unblocked on demand. */
493   sigemptyset(&mask);
494   sigaddset(&mask, __pthread_sig_restart);
495   sigprocmask(SIG_BLOCK, &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_*exit_process. */
499 #ifndef HAVE_Z_NODELETE
500   if (__builtin_expect (&__dso_handle != NULL, 1))
501     __cxa_atexit ((void (*) (void *)) pthread_atexit_process, NULL,
502                   __dso_handle);
503   else
504 #endif
505     __on_exit (pthread_onexit_process, NULL);
506   /* How many processors.  */
507   __pthread_smp_kernel = is_smp_system ();
508 }
509
510 void __pthread_initialize(void)
511 {
512   pthread_initialize();
513 }
514
515 int __pthread_initialize_manager(void)
516 {
517   int manager_pipe[2];
518   int pid;
519   struct pthread_request request;
520
521 #ifndef HAVE_Z_NODELETE
522   if (__builtin_expect (&__dso_handle != NULL, 1))
523     __cxa_atexit ((void (*) (void *)) pthread_atexit_retcode, NULL,
524                   __dso_handle);
525 #endif
526
527   if (__pthread_max_stacksize == 0)
528     __pthread_init_max_stacksize ();
529   /* If basic initialization not done yet (e.g. we're called from a
530      constructor run before our constructor), do it now */
531   if (__pthread_initial_thread_bos == NULL) pthread_initialize();
532   /* Setup stack for thread manager */
533   __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
534   if (__pthread_manager_thread_bos == NULL) return -1;
535   __pthread_manager_thread_tos =
536     __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;
537   /* Setup pipe to communicate with thread manager */
538   if (pipe(manager_pipe) == -1) {
539     free(__pthread_manager_thread_bos);
540     return -1;
541   }
542   /* Start the thread manager */
543   pid = 0;
544   if (__builtin_expect (__pthread_initial_thread.p_report_events, 0))
545     {
546       /* It's a bit more complicated.  We have to report the creation of
547          the manager thread.  */
548       int idx = __td_eventword (TD_CREATE);
549       uint32_t mask = __td_eventmask (TD_CREATE);
550
551       if ((mask & (__pthread_threads_events.event_bits[idx]
552                    | __pthread_initial_thread.p_eventbuf.eventmask.event_bits[idx]))
553           != 0)
554         {
555           __pthread_lock(__pthread_manager_thread.p_lock, NULL);
556
557 #ifdef NEED_SEPARATE_REGISTER_STACK
558           pid = __clone2(__pthread_manager_event,
559                          (void **) __pthread_manager_thread_bos,
560                          THREAD_MANAGER_STACK_SIZE,
561                          CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
562                          (void *)(long)manager_pipe[0]);
563 #elif _STACK_GROWS_UP
564           pid = __clone(__pthread_manager_event,
565                         (void **) __pthread_manager_thread_bos,
566                         CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
567                         (void *)(long)manager_pipe[0]);
568 #else
569           pid = __clone(__pthread_manager_event,
570                         (void **) __pthread_manager_thread_tos,
571                         CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
572                         (void *)(long)manager_pipe[0]);
573 #endif
574
575           if (pid != -1)
576             {
577               /* Now fill in the information about the new thread in
578                  the newly created thread's data structure.  We cannot let
579                  the new thread do this since we don't know whether it was
580                  already scheduled when we send the event.  */
581               __pthread_manager_thread.p_eventbuf.eventdata =
582                 &__pthread_manager_thread;
583               __pthread_manager_thread.p_eventbuf.eventnum = TD_CREATE;
584               __pthread_last_event = &__pthread_manager_thread;
585               __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
586               __pthread_manager_thread.p_pid = pid;
587
588               /* Now call the function which signals the event.  */
589               __linuxthreads_create_event ();
590             }
591
592           /* Now restart the thread.  */
593           __pthread_unlock(__pthread_manager_thread.p_lock);
594         }
595     }
596
597   if (__builtin_expect (pid, 0) == 0)
598     {
599 #ifdef NEED_SEPARATE_REGISTER_STACK
600       pid = __clone2(__pthread_manager, (void **) __pthread_manager_thread_bos,
601                      THREAD_MANAGER_STACK_SIZE,
602                      CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
603                      (void *)(long)manager_pipe[0]);
604 #elif _STACK_GROWS_UP
605       pid = __clone(__pthread_manager, (void **) __pthread_manager_thread_bos,
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 (__builtin_expect (pid, 0) == -1) {
615     free(__pthread_manager_thread_bos);
616     __libc_close(manager_pipe[0]);
617     __libc_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   /* Make gdb aware of new thread manager */
625   if (__builtin_expect (__pthread_threads_debug, 0) && __pthread_sig_debug > 0)
626     {
627       raise(__pthread_sig_debug);
628       /* We suspend ourself and gdb will wake us up when it is
629          ready to handle us. */
630       __pthread_wait_for_restart_signal(thread_self());
631     }
632   /* Synchronize debugging of the thread manager */
633   request.req_kind = REQ_DEBUG;
634   TEMP_FAILURE_RETRY(__libc_write(__pthread_manager_request,
635                                   (char *) &request, sizeof(request)));
636   return 0;
637 }
638
639 /* Thread creation */
640
641 int __pthread_create_2_1(pthread_t *thread, const pthread_attr_t *attr,
642                          void * (*start_routine)(void *), void *arg)
643 {
644   pthread_descr self = thread_self();
645   struct pthread_request request;
646   int retval;
647   if (__builtin_expect (__pthread_manager_request, 0) < 0) {
648     if (__pthread_initialize_manager() < 0) return EAGAIN;
649   }
650   request.req_thread = self;
651   request.req_kind = REQ_CREATE;
652   request.req_args.create.attr = attr;
653   request.req_args.create.fn = start_routine;
654   request.req_args.create.arg = arg;
655   sigprocmask(SIG_SETMASK, (const sigset_t *) NULL,
656               &request.req_args.create.mask);
657   TEMP_FAILURE_RETRY(__libc_write(__pthread_manager_request,
658                                   (char *) &request, sizeof(request)));
659   suspend(self);
660   retval = THREAD_GETMEM(self, p_retcode);
661   if (__builtin_expect (retval, 0) == 0)
662     *thread = (pthread_t) THREAD_GETMEM(self, p_retval);
663   return retval;
664 }
665
666 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
667
668 #if SHLIB_COMPAT (libpthread, GLIBC_2_0, GLIBC_2_1)
669
670 int __pthread_create_2_0(pthread_t *thread, const pthread_attr_t *attr,
671                          void * (*start_routine)(void *), void *arg)
672 {
673   /* The ATTR attribute is not really of type `pthread_attr_t *'.  It has
674      the old size and access to the new members might crash the program.
675      We convert the struct now.  */
676   pthread_attr_t new_attr;
677
678   if (attr != NULL)
679     {
680       size_t ps = __getpagesize ();
681
682       memcpy (&new_attr, attr,
683               (size_t) &(((pthread_attr_t*)NULL)->__guardsize));
684       new_attr.__guardsize = ps;
685       new_attr.__stackaddr_set = 0;
686       new_attr.__stackaddr = NULL;
687       new_attr.__stacksize = STACK_SIZE - ps;
688       attr = &new_attr;
689     }
690   return __pthread_create_2_1 (thread, attr, start_routine, arg);
691 }
692 compat_symbol (libpthread, __pthread_create_2_0, pthread_create, GLIBC_2_0);
693 #endif
694
695 /* Simple operations on thread identifiers */
696
697 pthread_t pthread_self(void)
698 {
699   pthread_descr self = thread_self();
700   return THREAD_GETMEM(self, p_tid);
701 }
702
703 int pthread_equal(pthread_t thread1, pthread_t thread2)
704 {
705   return thread1 == thread2;
706 }
707
708 /* Helper function for thread_self in the case of user-provided stacks */
709
710 #ifndef THREAD_SELF
711
712 pthread_descr __pthread_find_self(void)
713 {
714   char * sp = CURRENT_STACK_FRAME;
715   pthread_handle h;
716
717   /* __pthread_handles[0] is the initial thread, __pthread_handles[1] is
718      the manager threads handled specially in thread_self(), so start at 2 */
719   h = __pthread_handles + 2;
720   while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;
721   return h->h_descr;
722 }
723
724 #else
725
726 static pthread_descr thread_self_stack(void)
727 {
728   char *sp = CURRENT_STACK_FRAME;
729   pthread_handle h;
730
731   if (sp >= __pthread_manager_thread_bos && sp < __pthread_manager_thread_tos)
732     return &__pthread_manager_thread;
733   h = __pthread_handles + 2;
734   while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom))
735     h++;
736   return h->h_descr;
737 }
738
739 #endif
740
741 /* Thread scheduling */
742
743 int pthread_setschedparam(pthread_t thread, int policy,
744                           const struct sched_param *param)
745 {
746   pthread_handle handle = thread_handle(thread);
747   pthread_descr th;
748
749   __pthread_lock(&handle->h_lock, NULL);
750   if (__builtin_expect (invalid_handle(handle, thread), 0)) {
751     __pthread_unlock(&handle->h_lock);
752     return ESRCH;
753   }
754   th = handle->h_descr;
755   if (__builtin_expect (__sched_setscheduler(th->p_pid, policy, param) == -1,
756                         0)) {
757     __pthread_unlock(&handle->h_lock);
758     return errno;
759   }
760   th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
761   __pthread_unlock(&handle->h_lock);
762   if (__pthread_manager_request >= 0)
763     __pthread_manager_adjust_prio(th->p_priority);
764   return 0;
765 }
766
767 int pthread_getschedparam(pthread_t thread, int *policy,
768                           struct sched_param *param)
769 {
770   pthread_handle handle = thread_handle(thread);
771   int pid, pol;
772
773   __pthread_lock(&handle->h_lock, NULL);
774   if (__builtin_expect (invalid_handle(handle, thread), 0)) {
775     __pthread_unlock(&handle->h_lock);
776     return ESRCH;
777   }
778   pid = handle->h_descr->p_pid;
779   __pthread_unlock(&handle->h_lock);
780   pol = __sched_getscheduler(pid);
781   if (__builtin_expect (pol, 0) == -1) return errno;
782   if (__sched_getparam(pid, param) == -1) return errno;
783   *policy = pol;
784   return 0;
785 }
786
787 int __pthread_yield (void)
788 {
789   /* For now this is equivalent with the POSIX call.  */
790   return sched_yield ();
791 }
792 weak_alias (__pthread_yield, pthread_yield)
793
794 /* Process-wide exit() request */
795
796 static void pthread_onexit_process(int retcode, void *arg)
797 {
798   if (__builtin_expect (__pthread_manager_request, 0) >= 0) {
799     struct pthread_request request;
800     pthread_descr self = thread_self();
801
802     request.req_thread = self;
803     request.req_kind = REQ_PROCESS_EXIT;
804     request.req_args.exit.code = retcode;
805     TEMP_FAILURE_RETRY(__libc_write(__pthread_manager_request,
806                                     (char *) &request, sizeof(request)));
807     suspend(self);
808     /* Main thread should accumulate times for thread manager and its
809        children, so that timings for main thread account for all threads. */
810     if (self == __pthread_main_thread)
811       {
812         waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
813         /* Since all threads have been asynchronously terminated
814            (possibly holding locks), free cannot be used any more.  */
815         /*free (__pthread_manager_thread_bos);*/
816         __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
817       }
818   }
819 }
820
821 #ifndef HAVE_Z_NODELETE
822 static int __pthread_atexit_retcode;
823
824 static void pthread_atexit_process(void *arg, int retcode)
825 {
826   pthread_onexit_process (retcode ?: __pthread_atexit_retcode, arg);
827 }
828
829 static void pthread_atexit_retcode(void *arg, int retcode)
830 {
831   __pthread_atexit_retcode = retcode;
832 }
833 #endif
834
835 /* The handler for the RESTART signal just records the signal received
836    in the thread descriptor, and optionally performs a siglongjmp
837    (for pthread_cond_timedwait). */
838
839 static void pthread_handle_sigrestart(int sig)
840 {
841   pthread_descr self = thread_self();
842   THREAD_SETMEM(self, p_signal, sig);
843   if (THREAD_GETMEM(self, p_signal_jmp) != NULL)
844     siglongjmp(*THREAD_GETMEM(self, p_signal_jmp), 1);
845 }
846
847 /* The handler for the CANCEL signal checks for cancellation
848    (in asynchronous mode), for process-wide exit and exec requests.
849    For the thread manager thread, redirect the signal to
850    __pthread_manager_sighandler. */
851
852 static void pthread_handle_sigcancel(int sig)
853 {
854   pthread_descr self = thread_self();
855   sigjmp_buf * jmpbuf;
856
857   if (self == &__pthread_manager_thread)
858     {
859 #ifdef THREAD_SELF
860       /* A new thread might get a cancel signal before it is fully
861          initialized, so that the thread register might still point to the
862          manager thread.  Double check that this is really the manager
863          thread.  */
864       pthread_descr real_self = thread_self_stack();
865       if (real_self == &__pthread_manager_thread)
866         {
867           __pthread_manager_sighandler(sig);
868           return;
869         }
870       /* Oops, thread_self() isn't working yet..  */
871       self = real_self;
872 # ifdef INIT_THREAD_SELF
873       INIT_THREAD_SELF(self, self->p_nr);
874 # endif
875 #else
876       __pthread_manager_sighandler(sig);
877       return;
878 #endif
879     }
880   if (__builtin_expect (__pthread_exit_requested, 0)) {
881     /* Main thread should accumulate times for thread manager and its
882        children, so that timings for main thread account for all threads. */
883     if (self == __pthread_main_thread)
884       waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
885     _exit(__pthread_exit_code);
886   }
887   if (__builtin_expect (THREAD_GETMEM(self, p_canceled), 0)
888       && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
889     if (THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
890       __pthread_do_exit(PTHREAD_CANCELED, CURRENT_STACK_FRAME);
891     jmpbuf = THREAD_GETMEM(self, p_cancel_jmp);
892     if (jmpbuf != NULL) {
893       THREAD_SETMEM(self, p_cancel_jmp, NULL);
894       siglongjmp(*jmpbuf, 1);
895     }
896   }
897 }
898
899 /* Handler for the DEBUG signal.
900    The debugging strategy is as follows:
901    On reception of a REQ_DEBUG request (sent by new threads created to
902    the thread manager under debugging mode), the thread manager throws
903    __pthread_sig_debug to itself. The debugger (if active) intercepts
904    this signal, takes into account new threads and continue execution
905    of the thread manager by propagating the signal because it doesn't
906    know what it is specifically done for. In the current implementation,
907    the thread manager simply discards it. */
908
909 static void pthread_handle_sigdebug(int sig)
910 {
911   /* Nothing */
912 }
913
914 /* Reset the state of the thread machinery after a fork().
915    Close the pipe used for requests and set the main thread to the forked
916    thread.
917    Notice that we can't free the stack segments, as the forked thread
918    may hold pointers into them. */
919
920 void __pthread_reset_main_thread(void)
921 {
922   pthread_descr self = thread_self();
923   struct rlimit limit;
924
925   if (__pthread_manager_request != -1) {
926     /* Free the thread manager stack */
927     free(__pthread_manager_thread_bos);
928     __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
929     /* Close the two ends of the pipe */
930     __libc_close(__pthread_manager_request);
931     __libc_close(__pthread_manager_reader);
932     __pthread_manager_request = __pthread_manager_reader = -1;
933   }
934
935   /* Update the pid of the main thread */
936   THREAD_SETMEM(self, p_pid, __getpid());
937   /* Make the forked thread the main thread */
938   __pthread_main_thread = self;
939   THREAD_SETMEM(self, p_nextlive, self);
940   THREAD_SETMEM(self, p_prevlive, self);
941   /* Now this thread modifies the global variables.  */
942   THREAD_SETMEM(self, p_errnop, &_errno);
943   THREAD_SETMEM(self, p_h_errnop, &_h_errno);
944   THREAD_SETMEM(self, p_resp, &_res);
945
946   if (getrlimit (RLIMIT_STACK, &limit) == 0
947       && limit.rlim_cur != limit.rlim_max) {
948     limit.rlim_cur = limit.rlim_max;
949     setrlimit(RLIMIT_STACK, &limit);
950   }
951 }
952
953 /* Process-wide exec() request */
954
955 void __pthread_kill_other_threads_np(void)
956 {
957   struct sigaction sa;
958   /* Terminate all other threads and thread manager */
959   pthread_onexit_process(0, NULL);
960   /* Make current thread the main thread in case the calling thread
961      changes its mind, does not exec(), and creates new threads instead. */
962   __pthread_reset_main_thread();
963
964   /* Reset the signal handlers behaviour for the signals the
965      implementation uses since this would be passed to the new
966      process.  */
967   sigemptyset(&sa.sa_mask);
968   sa.sa_flags = 0;
969   sa.sa_handler = SIG_DFL;
970   __libc_sigaction(__pthread_sig_restart, &sa, NULL);
971   __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
972   if (__pthread_sig_debug > 0)
973     __libc_sigaction(__pthread_sig_debug, &sa, NULL);
974 }
975 weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
976
977 /* Concurrency symbol level.  */
978 static int current_level;
979
980 int __pthread_setconcurrency(int level)
981 {
982   /* We don't do anything unless we have found a useful interpretation.  */
983   current_level = level;
984   return 0;
985 }
986 weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
987
988 int __pthread_getconcurrency(void)
989 {
990   return current_level;
991 }
992 weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
993
994 /* Primitives for controlling thread execution */
995
996 void __pthread_wait_for_restart_signal(pthread_descr self)
997 {
998   sigset_t mask;
999
1000   sigprocmask(SIG_SETMASK, NULL, &mask); /* Get current signal mask */
1001   sigdelset(&mask, __pthread_sig_restart); /* Unblock the restart signal */
1002   THREAD_SETMEM(self, p_signal, 0);
1003   do {
1004     sigsuspend(&mask);                   /* Wait for signal */
1005   } while (THREAD_GETMEM(self, p_signal) !=__pthread_sig_restart);
1006
1007   READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
1008 }
1009
1010 #if !__ASSUME_REALTIME_SIGNALS
1011 /* The _old variants are for 2.0 and early 2.1 kernels which don't have RT
1012    signals.
1013    On these kernels, we use SIGUSR1 and SIGUSR2 for restart and cancellation.
1014    Since the restart signal does not queue, we use an atomic counter to create
1015    queuing semantics. This is needed to resolve a rare race condition in
1016    pthread_cond_timedwait_relative. */
1017
1018 void __pthread_restart_old(pthread_descr th)
1019 {
1020   if (atomic_increment(&th->p_resume_count) == -1)
1021     kill(th->p_pid, __pthread_sig_restart);
1022 }
1023
1024 void __pthread_suspend_old(pthread_descr self)
1025 {
1026   if (atomic_decrement(&self->p_resume_count) <= 0)
1027     __pthread_wait_for_restart_signal(self);
1028 }
1029
1030 int
1031 __pthread_timedsuspend_old(pthread_descr self, const struct timespec *abstime)
1032 {
1033   sigset_t unblock, initial_mask;
1034   int was_signalled = 0;
1035   sigjmp_buf jmpbuf;
1036
1037   if (atomic_decrement(&self->p_resume_count) == 0) {
1038     /* Set up a longjmp handler for the restart signal, unblock
1039        the signal and sleep. */
1040
1041     if (sigsetjmp(jmpbuf, 1) == 0) {
1042       THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
1043       THREAD_SETMEM(self, p_signal, 0);
1044       /* Unblock the restart signal */
1045       sigemptyset(&unblock);
1046       sigaddset(&unblock, __pthread_sig_restart);
1047       sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
1048
1049       while (1) {
1050         struct timeval now;
1051         struct timespec reltime;
1052
1053         /* Compute a time offset relative to now.  */
1054         __gettimeofday (&now, NULL);
1055         reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
1056         reltime.tv_sec = abstime->tv_sec - now.tv_sec;
1057         if (reltime.tv_nsec < 0) {
1058           reltime.tv_nsec += 1000000000;
1059           reltime.tv_sec -= 1;
1060         }
1061
1062         /* Sleep for the required duration. If woken by a signal,
1063            resume waiting as required by Single Unix Specification.  */
1064         if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
1065           break;
1066       }
1067
1068       /* Block the restart signal again */
1069       sigprocmask(SIG_SETMASK, &initial_mask, NULL);
1070       was_signalled = 0;
1071     } else {
1072       was_signalled = 1;
1073     }
1074     THREAD_SETMEM(self, p_signal_jmp, NULL);
1075   }
1076
1077   /* Now was_signalled is true if we exited the above code
1078      due to the delivery of a restart signal.  In that case,
1079      we know we have been dequeued and resumed and that the
1080      resume count is balanced.  Otherwise, there are some
1081      cases to consider. First, try to bump up the resume count
1082      back to zero. If it goes to 1, it means restart() was
1083      invoked on this thread. The signal must be consumed
1084      and the count bumped down and everything is cool. We
1085      can return a 1 to the caller.
1086      Otherwise, no restart was delivered yet, so a potential
1087      race exists; we return a 0 to the caller which must deal
1088      with this race in an appropriate way; for example by
1089      atomically removing the thread from consideration for a
1090      wakeup---if such a thing fails, it means a restart is
1091      being delivered. */
1092
1093   if (!was_signalled) {
1094     if (atomic_increment(&self->p_resume_count) != -1) {
1095       __pthread_wait_for_restart_signal(self);
1096       atomic_decrement(&self->p_resume_count); /* should be zero now! */
1097       /* woke spontaneously and consumed restart signal */
1098       return 1;
1099     }
1100     /* woke spontaneously but did not consume restart---caller must resolve */
1101     return 0;
1102   }
1103   /* woken due to restart signal */
1104   return 1;
1105 }
1106 #endif /* __ASSUME_REALTIME_SIGNALS */
1107
1108 void __pthread_restart_new(pthread_descr th)
1109 {
1110   /* The barrier is proabably not needed, in which case it still documents
1111      our assumptions. The intent is to commit previous writes to shared
1112      memory so the woken thread will have a consistent view.  Complementary
1113      read barriers are present to the suspend functions. */
1114   WRITE_MEMORY_BARRIER();
1115   kill(th->p_pid, __pthread_sig_restart);
1116 }
1117
1118 /* There is no __pthread_suspend_new because it would just
1119    be a wasteful wrapper for __pthread_wait_for_restart_signal */
1120
1121 int
1122 __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime)
1123 {
1124   sigset_t unblock, initial_mask;
1125   int was_signalled = 0;
1126   sigjmp_buf jmpbuf;
1127
1128   if (sigsetjmp(jmpbuf, 1) == 0) {
1129     THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
1130     THREAD_SETMEM(self, p_signal, 0);
1131     /* Unblock the restart signal */
1132     sigemptyset(&unblock);
1133     sigaddset(&unblock, __pthread_sig_restart);
1134     sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
1135
1136     while (1) {
1137       struct timeval now;
1138       struct timespec reltime;
1139
1140       /* Compute a time offset relative to now.  */
1141       __gettimeofday (&now, NULL);
1142       reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
1143       reltime.tv_sec = abstime->tv_sec - now.tv_sec;
1144       if (reltime.tv_nsec < 0) {
1145         reltime.tv_nsec += 1000000000;
1146         reltime.tv_sec -= 1;
1147       }
1148
1149       /* Sleep for the required duration. If woken by a signal,
1150          resume waiting as required by Single Unix Specification.  */
1151       if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
1152         break;
1153     }
1154
1155     /* Block the restart signal again */
1156     sigprocmask(SIG_SETMASK, &initial_mask, NULL);
1157     was_signalled = 0;
1158   } else {
1159     was_signalled = 1;
1160   }
1161   THREAD_SETMEM(self, p_signal_jmp, NULL);
1162
1163   /* Now was_signalled is true if we exited the above code
1164      due to the delivery of a restart signal.  In that case,
1165      everything is cool. We have been removed from whatever
1166      we were waiting on by the other thread, and consumed its signal.
1167
1168      Otherwise we this thread woke up spontaneously, or due to a signal other
1169      than restart. This is an ambiguous case  that must be resolved by
1170      the caller; the thread is still eligible for a restart wakeup
1171      so there is a race. */
1172
1173   READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
1174   return was_signalled;
1175 }
1176
1177
1178 /* Debugging aid */
1179
1180 #ifdef DEBUG
1181 #include <stdarg.h>
1182
1183 void __pthread_message(char * fmt, ...)
1184 {
1185   char buffer[1024];
1186   va_list args;
1187   sprintf(buffer, "%05d : ", __getpid());
1188   va_start(args, fmt);
1189   vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
1190   va_end(args);
1191   TEMP_FAILURE_RETRY(__libc_write(2, buffer, strlen(buffer)));
1192 }
1193
1194 #endif
1195
1196
1197 #ifndef SHARED
1198 /* We need a hook to force the cancelation wrappers and file locking
1199    to be linked in when static libpthread is used.  */
1200 extern const int __pthread_provide_wrappers;
1201 static const int *const __pthread_require_wrappers =
1202   &__pthread_provide_wrappers;
1203 extern const int __pthread_provide_lockfile;
1204 static const int *const __pthread_require_lockfile =
1205   &__pthread_provide_lockfile;
1206 #endif