OSDN Git Service

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