OSDN Git Service

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