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