Update.
[glibc.git] / linuxthreads / pthread.c
blob0e713e74daacbf871d695867d6f8dd99c72366c2
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. */
15 /* Thread creation, initialization, and basic low-level routines */
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 <shlib-compat.h>
27 #include "pthread.h"
28 #include "internals.h"
29 #include "spinlock.h"
30 #include "restart.h"
32 /* Sanity check. */
33 #if __ASSUME_REALTIME_SIGNALS && !defined __SIGRTMIN
34 # error "This must not happen; new kernel assumed but old headers"
35 #endif
37 /* Descriptor of the initial thread */
39 struct _pthread_descr_struct __pthread_initial_thread = {
42 &__pthread_initial_thread /* pthread_descr self */
45 &__pthread_initial_thread, /* pthread_descr p_nextlive */
46 &__pthread_initial_thread, /* pthread_descr p_prevlive */
47 NULL, /* pthread_descr p_nextwaiting */
48 NULL, /* pthread_descr p_nextlock */
49 PTHREAD_THREADS_MAX, /* pthread_t p_tid */
50 0, /* int p_pid */
51 0, /* int p_priority */
52 &__pthread_handles[0].h_lock, /* struct _pthread_fastlock * p_lock */
53 0, /* int p_signal */
54 NULL, /* sigjmp_buf * p_signal_buf */
55 NULL, /* sigjmp_buf * p_cancel_buf */
56 0, /* char p_terminated */
57 0, /* char p_detached */
58 0, /* char p_exited */
59 NULL, /* void * p_retval */
60 0, /* int p_retval */
61 NULL, /* pthread_descr p_joining */
62 NULL, /* struct _pthread_cleanup_buffer * p_cleanup */
63 0, /* char p_cancelstate */
64 0, /* char p_canceltype */
65 0, /* char p_canceled */
66 NULL, /* int *p_errnop */
67 0, /* int p_errno */
68 NULL, /* int *p_h_errnop */
69 0, /* int p_h_errno */
70 NULL, /* char * p_in_sighandler */
71 0, /* char p_sigwaiting */
72 PTHREAD_START_ARGS_INITIALIZER(NULL),
73 /* struct pthread_start_args p_start_args */
74 {NULL}, /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
75 {NULL}, /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
76 0, /* int p_userstack */
77 NULL, /* void * p_guardaddr */
78 0, /* size_t p_guardsize */
79 0, /* Always index 0 */
80 0, /* int p_report_events */
81 {{{0, }}, 0, NULL}, /* td_eventbuf_t p_eventbuf */
82 ATOMIC_INITIALIZER, /* struct pthread_atomic p_resume_count */
83 0, /* char p_woken_by_cancel */
84 NULL, /* struct pthread_extricate_if *p_extricate */
85 NULL, /* pthread_readlock_info *p_readlock_list; */
86 NULL, /* pthread_readlock_info *p_readlock_free; */
87 0 /* int p_untracked_readlock_count; */
90 /* Descriptor of the manager thread; none of this is used but the error
91 variables, the p_pid and p_priority fields,
92 and the address for identification. */
94 struct _pthread_descr_struct __pthread_manager_thread = {
97 &__pthread_manager_thread /* pthread_descr self */
100 NULL, /* pthread_descr p_nextlive */
101 NULL, /* pthread_descr p_prevlive */
102 NULL, /* pthread_descr p_nextwaiting */
103 NULL, /* pthread_descr p_nextlock */
104 0, /* int p_tid */
105 0, /* int p_pid */
106 0, /* int p_priority */
107 &__pthread_handles[1].h_lock, /* struct _pthread_fastlock * p_lock */
108 0, /* int p_signal */
109 NULL, /* sigjmp_buf * p_signal_buf */
110 NULL, /* sigjmp_buf * p_cancel_buf */
111 0, /* char p_terminated */
112 0, /* char p_detached */
113 0, /* char p_exited */
114 NULL, /* void * p_retval */
115 0, /* int p_retval */
116 NULL, /* pthread_descr p_joining */
117 NULL, /* struct _pthread_cleanup_buffer * p_cleanup */
118 0, /* char p_cancelstate */
119 0, /* char p_canceltype */
120 0, /* char p_canceled */
121 &__pthread_manager_thread.p_errno, /* int *p_errnop */
122 0, /* int p_errno */
123 NULL, /* int *p_h_errnop */
124 0, /* int p_h_errno */
125 NULL, /* char * p_in_sighandler */
126 0, /* char p_sigwaiting */
127 PTHREAD_START_ARGS_INITIALIZER(__pthread_manager),
128 /* struct pthread_start_args p_start_args */
129 {NULL}, /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
130 {NULL}, /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
131 0, /* int p_userstack */
132 NULL, /* void * p_guardaddr */
133 0, /* size_t p_guardsize */
134 1, /* Always index 1 */
135 0, /* int p_report_events */
136 {{{0, }}, 0, NULL}, /* td_eventbuf_t p_eventbuf */
137 ATOMIC_INITIALIZER, /* struct pthread_atomic p_resume_count */
138 0, /* char p_woken_by_cancel */
139 NULL, /* struct pthread_extricate_if *p_extricate */
140 NULL, /* pthread_readlock_info *p_readlock_list; */
141 NULL, /* pthread_readlock_info *p_readlock_free; */
142 0 /* int p_untracked_readlock_count; */
145 /* Pointer to the main thread (the father of the thread manager thread) */
146 /* Originally, this is the initial thread, but this changes after fork() */
148 pthread_descr __pthread_main_thread = &__pthread_initial_thread;
150 /* Limit between the stack of the initial thread (above) and the
151 stacks of other threads (below). Aligned on a STACK_SIZE boundary. */
153 char *__pthread_initial_thread_bos = NULL;
155 /* File descriptor for sending requests to the thread manager. */
156 /* Initially -1, meaning that the thread manager is not running. */
158 int __pthread_manager_request = -1;
160 /* Other end of the pipe for sending requests to the thread manager. */
162 int __pthread_manager_reader;
164 /* Limits of the thread manager stack */
166 char *__pthread_manager_thread_bos = NULL;
167 char *__pthread_manager_thread_tos = NULL;
169 /* For process-wide exit() */
171 int __pthread_exit_requested = 0;
172 int __pthread_exit_code = 0;
174 #if !__ASSUME_REALTIME_SIGNALS
175 /* Pointers that select new or old suspend/resume functions
176 based on availability of rt signals. */
178 void (*__pthread_restart)(pthread_descr) = __pthread_restart_old;
179 void (*__pthread_suspend)(pthread_descr) = __pthread_suspend_old;
180 int (*__pthread_timedsuspend)(pthread_descr, const struct timespec *) = __pthread_timedsuspend_old;
181 #endif /* __ASSUME_REALTIME_SIGNALS */
183 /* Communicate relevant LinuxThreads constants to gdb */
185 const int __pthread_threads_max = PTHREAD_THREADS_MAX;
186 const int __pthread_sizeof_handle = sizeof(struct pthread_handle_struct);
187 const int __pthread_offsetof_descr = offsetof(struct pthread_handle_struct,
188 h_descr);
189 const int __pthread_offsetof_pid = offsetof(struct _pthread_descr_struct,
190 p_pid);
191 const int __linuxthread_pthread_sizeof_descr
192 = sizeof(struct _pthread_descr_struct);
194 /* These variables are used by the setup code. */
195 extern int _errno;
196 extern int _h_errno;
198 /* Forward declarations */
200 static void pthread_exit_process(int retcode, void *arg);
201 static void pthread_handle_sigcancel(int sig);
202 static void pthread_handle_sigrestart(int sig);
203 static void pthread_handle_sigdebug(int sig);
205 /* Signal numbers used for the communication.
206 In these variables we keep track of the used variables. If the
207 platform does not support any real-time signals we will define the
208 values to some unreasonable value which will signal failing of all
209 the functions below. */
210 #ifndef __SIGRTMIN
211 static int current_rtmin = -1;
212 static int current_rtmax = -1;
213 int __pthread_sig_restart = SIGUSR1;
214 int __pthread_sig_cancel = SIGUSR2;
215 int __pthread_sig_debug = 0;
216 #else
217 static int current_rtmin;
218 static int current_rtmax;
220 #if __SIGRTMAX - __SIGRTMIN >= 3
221 int __pthread_sig_restart = __SIGRTMIN;
222 int __pthread_sig_cancel = __SIGRTMIN + 1;
223 int __pthread_sig_debug = __SIGRTMIN + 2;
224 #else
225 int __pthread_sig_restart = SIGUSR1;
226 int __pthread_sig_cancel = SIGUSR2;
227 int __pthread_sig_debug = 0;
228 #endif
230 static int rtsigs_initialized;
232 #include "testrtsig.h"
234 static void
235 init_rtsigs (void)
237 #if !__ASSUME_REALTIME_SIGNALS
238 if (!kernel_has_rtsig ())
240 current_rtmin = -1;
241 current_rtmax = -1;
242 # if __SIGRTMAX - __SIGRTMIN >= 3
243 __pthread_sig_restart = SIGUSR1;
244 __pthread_sig_cancel = SIGUSR2;
245 __pthread_sig_debug = 0;
246 # endif
248 else
249 #endif /* __ASSUME_REALTIME_SIGNALS */
251 #if __SIGRTMAX - __SIGRTMIN >= 3
252 current_rtmin = __SIGRTMIN + 3;
253 # if !__ASSUME_REALTIME_SIGNALS
254 __pthread_restart = __pthread_restart_new;
255 __pthread_suspend = __pthread_wait_for_restart_signal;
256 __pthread_timedsuspend = __pthread_timedsuspend_new;
257 # endif /* __ASSUME_REALTIME_SIGNALS */
258 #else
259 current_rtmin = __SIGRTMIN;
260 #endif
262 current_rtmax = __SIGRTMAX;
265 rtsigs_initialized = 1;
267 #endif
269 /* Return number of available real-time signal with highest priority. */
271 __libc_current_sigrtmin (void)
273 #ifdef __SIGRTMIN
274 if (!rtsigs_initialized)
275 init_rtsigs ();
276 #endif
277 return current_rtmin;
280 /* Return number of available real-time signal with lowest priority. */
282 __libc_current_sigrtmax (void)
284 #ifdef __SIGRTMIN
285 if (!rtsigs_initialized)
286 init_rtsigs ();
287 #endif
288 return current_rtmax;
291 /* Allocate real-time signal with highest/lowest available
292 priority. Please note that we don't use a lock since we assume
293 this function to be called at program start. */
295 __libc_allocate_rtsig (int high)
297 #ifndef __SIGRTMIN
298 return -1;
299 #else
300 if (!rtsigs_initialized)
301 init_rtsigs ();
302 if (current_rtmin == -1 || current_rtmin > current_rtmax)
303 /* We don't have anymore signal available. */
304 return -1;
306 return high ? current_rtmin++ : current_rtmax--;
307 #endif
310 /* Initialize the pthread library.
311 Initialization is split in two functions:
312 - a constructor function that blocks the __pthread_sig_restart signal
313 (must do this very early, since the program could capture the signal
314 mask with e.g. sigsetjmp before creating the first thread);
315 - a regular function called from pthread_create when needed. */
317 static void pthread_initialize(void) __attribute__((constructor));
319 extern void *__dso_handle __attribute__ ((weak));
322 /* Do some minimal initialization which has to be done during the
323 startup of the C library. */
324 void
325 __pthread_initialize_minimal(void)
327 /* The errno/h_errno variable of the main thread are the global ones. */
328 __pthread_initial_thread.p_errnop = &_errno;
329 __pthread_initial_thread.p_h_errnop = &_h_errno;
330 /* If we have special thread_self processing, initialize that for the
331 main thread now. */
332 #ifdef INIT_THREAD_SELF
333 INIT_THREAD_SELF(&__pthread_initial_thread, 0);
334 #endif
338 static void pthread_initialize(void)
340 struct sigaction sa;
341 sigset_t mask;
342 struct rlimit limit;
343 int max_stack;
345 /* If already done (e.g. by a constructor called earlier!), bail out */
346 if (__pthread_initial_thread_bos != NULL) return;
347 #ifdef TEST_FOR_COMPARE_AND_SWAP
348 /* Test if compare-and-swap is available */
349 __pthread_has_cas = compare_and_swap_is_available();
350 #endif
351 /* For the initial stack, reserve at least STACK_SIZE bytes of stack
352 below the current stack address, and align that on a
353 STACK_SIZE boundary. */
354 __pthread_initial_thread_bos =
355 (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
356 /* Update the descriptor for the initial thread. */
357 __pthread_initial_thread.p_pid = __getpid();
358 /* Play with the stack size limit to make sure that no stack ever grows
359 beyond STACK_SIZE minus one page (to act as a guard page). */
360 getrlimit(RLIMIT_STACK, &limit);
361 max_stack = STACK_SIZE - __getpagesize();
362 if (limit.rlim_cur > max_stack) {
363 limit.rlim_cur = max_stack;
364 setrlimit(RLIMIT_STACK, &limit);
366 /* Likewise for the resolver state _res. */
367 __pthread_initial_thread.p_resp = &_res;
368 #ifdef __SIGRTMIN
369 /* Initialize real-time signals. */
370 init_rtsigs ();
371 #endif
372 /* Setup signal handlers for the initial thread.
373 Since signal handlers are shared between threads, these settings
374 will be inherited by all other threads. */
375 sa.sa_handler = pthread_handle_sigrestart;
376 sigemptyset(&sa.sa_mask);
377 sa.sa_flags = 0;
378 __sigaction(__pthread_sig_restart, &sa, NULL);
379 sa.sa_handler = pthread_handle_sigcancel;
380 // sa.sa_flags = 0;
381 __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 __sigaction(__pthread_sig_debug, &sa, NULL);
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 /* Register an exit function to kill all other threads. */
393 /* Do it early so that user-registered atexit functions are called
394 before pthread_exit_process. */
395 if (&__dso_handle != NULL)
396 /* The cast is a bit unclean. The function expects two arguments but
397 we can only pass one. Fortunately this is not a problem since the
398 second argument of `pthread_exit_process' is simply ignored. */
399 __cxa_atexit((void (*) (void *)) pthread_exit_process, NULL, __dso_handle);
400 else
401 __on_exit (pthread_exit_process, NULL);
404 void __pthread_initialize(void)
406 pthread_initialize();
409 int __pthread_initialize_manager(void)
411 int manager_pipe[2];
412 int pid;
413 struct pthread_request request;
415 /* If basic initialization not done yet (e.g. we're called from a
416 constructor run before our constructor), do it now */
417 if (__pthread_initial_thread_bos == NULL) pthread_initialize();
418 /* Setup stack for thread manager */
419 __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
420 if (__pthread_manager_thread_bos == NULL) return -1;
421 __pthread_manager_thread_tos =
422 __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;
423 /* Setup pipe to communicate with thread manager */
424 if (pipe(manager_pipe) == -1) {
425 free(__pthread_manager_thread_bos);
426 return -1;
428 /* Start the thread manager */
429 pid = 0;
430 if (__pthread_initial_thread.p_report_events)
432 /* It's a bit more complicated. We have to report the creation of
433 the manager thread. */
434 int idx = __td_eventword (TD_CREATE);
435 uint32_t mask = __td_eventmask (TD_CREATE);
437 if ((mask & (__pthread_threads_events.event_bits[idx]
438 | __pthread_initial_thread.p_eventbuf.eventmask.event_bits[idx]))
439 != 0)
441 pid = __clone(__pthread_manager_event,
442 (void **) __pthread_manager_thread_tos,
443 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
444 (void *)(long)manager_pipe[0]);
446 if (pid != -1)
448 /* Now fill in the information about the new thread in
449 the newly created thread's data structure. We cannot let
450 the new thread do this since we don't know whether it was
451 already scheduled when we send the event. */
452 __pthread_manager_thread.p_eventbuf.eventdata =
453 &__pthread_manager_thread;
454 __pthread_manager_thread.p_eventbuf.eventnum = TD_CREATE;
455 __pthread_last_event = &__pthread_manager_thread;
456 __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
457 __pthread_manager_thread.p_pid = pid;
459 /* Now call the function which signals the event. */
460 __linuxthreads_create_event ();
462 /* Now restart the thread. */
463 __pthread_spin_unlock(__pthread_manager_thread.p_lock);
468 if (pid == 0)
469 pid = __clone(__pthread_manager, (void **) __pthread_manager_thread_tos,
470 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
471 (void *)(long)manager_pipe[0]);
472 if (pid == -1) {
473 free(__pthread_manager_thread_bos);
474 __libc_close(manager_pipe[0]);
475 __libc_close(manager_pipe[1]);
476 return -1;
478 __pthread_manager_request = manager_pipe[1]; /* writing end */
479 __pthread_manager_reader = manager_pipe[0]; /* reading end */
480 __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
481 __pthread_manager_thread.p_pid = pid;
482 /* Make gdb aware of new thread manager */
483 if (__pthread_threads_debug && __pthread_sig_debug > 0)
485 raise(__pthread_sig_debug);
486 /* We suspend ourself and gdb will wake us up when it is
487 ready to handle us. */
488 __pthread_wait_for_restart_signal(thread_self());
490 /* Synchronize debugging of the thread manager */
491 request.req_kind = REQ_DEBUG;
492 __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
493 return 0;
496 /* Thread creation */
498 int __pthread_create_2_1(pthread_t *thread, const pthread_attr_t *attr,
499 void * (*start_routine)(void *), void *arg)
501 pthread_descr self = thread_self();
502 struct pthread_request request;
503 if (__pthread_manager_request < 0) {
504 if (__pthread_initialize_manager() < 0) return EAGAIN;
506 request.req_thread = self;
507 request.req_kind = REQ_CREATE;
508 request.req_args.create.attr = attr;
509 request.req_args.create.fn = start_routine;
510 request.req_args.create.arg = arg;
511 sigprocmask(SIG_SETMASK, (const sigset_t *) NULL,
512 &request.req_args.create.mask);
513 __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
514 suspend(self);
515 if (THREAD_GETMEM(self, p_retcode) == 0)
516 *thread = (pthread_t) THREAD_GETMEM(self, p_retval);
517 return THREAD_GETMEM(self, p_retcode);
520 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
522 #if SHLIB_COMPAT (libpthread, GLIBC_2_0, GLIBC_2_1)
524 int __pthread_create_2_0(pthread_t *thread, const pthread_attr_t *attr,
525 void * (*start_routine)(void *), void *arg)
527 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
528 the old size and access to the new members might crash the program.
529 We convert the struct now. */
530 pthread_attr_t new_attr;
532 if (attr != NULL)
534 size_t ps = __getpagesize ();
536 memcpy (&new_attr, attr,
537 (size_t) &(((pthread_attr_t*)NULL)->__guardsize));
538 new_attr.__guardsize = ps;
539 new_attr.__stackaddr_set = 0;
540 new_attr.__stackaddr = NULL;
541 new_attr.__stacksize = STACK_SIZE - ps;
542 attr = &new_attr;
544 return __pthread_create_2_1 (thread, attr, start_routine, arg);
546 compat_symbol (libpthread, __pthread_create_2_0, pthread_create, GLIBC_2_0);
547 #endif
549 /* Simple operations on thread identifiers */
551 pthread_t pthread_self(void)
553 pthread_descr self = thread_self();
554 return THREAD_GETMEM(self, p_tid);
557 int pthread_equal(pthread_t thread1, pthread_t thread2)
559 return thread1 == thread2;
562 /* Helper function for thread_self in the case of user-provided stacks */
564 #ifndef THREAD_SELF
566 pthread_descr __pthread_find_self()
568 char * sp = CURRENT_STACK_FRAME;
569 pthread_handle h;
571 /* __pthread_handles[0] is the initial thread, __pthread_handles[1] is
572 the manager threads handled specially in thread_self(), so start at 2 */
573 h = __pthread_handles + 2;
574 while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;
575 return h->h_descr;
578 #endif
580 /* Thread scheduling */
582 int pthread_setschedparam(pthread_t thread, int policy,
583 const struct sched_param *param)
585 pthread_handle handle = thread_handle(thread);
586 pthread_descr th;
588 __pthread_lock(&handle->h_lock, NULL);
589 if (invalid_handle(handle, thread)) {
590 __pthread_spin_unlock(&handle->h_lock);
591 return ESRCH;
593 th = handle->h_descr;
594 if (__sched_setscheduler(th->p_pid, policy, param) == -1) {
595 __pthread_spin_unlock(&handle->h_lock);
596 return errno;
598 th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
599 __pthread_spin_unlock(&handle->h_lock);
600 if (__pthread_manager_request >= 0)
601 __pthread_manager_adjust_prio(th->p_priority);
602 return 0;
605 int pthread_getschedparam(pthread_t thread, int *policy,
606 struct sched_param *param)
608 pthread_handle handle = thread_handle(thread);
609 int pid, pol;
611 __pthread_lock(&handle->h_lock, NULL);
612 if (invalid_handle(handle, thread)) {
613 __pthread_spin_unlock(&handle->h_lock);
614 return ESRCH;
616 pid = handle->h_descr->p_pid;
617 __pthread_spin_unlock(&handle->h_lock);
618 pol = __sched_getscheduler(pid);
619 if (pol == -1) return errno;
620 if (__sched_getparam(pid, param) == -1) return errno;
621 *policy = pol;
622 return 0;
625 int __pthread_yield ()
627 /* For now this is equivalent with the POSIX call. */
628 return sched_yield ();
630 weak_alias (__pthread_yield, pthread_yield)
632 /* Process-wide exit() request */
634 static void pthread_exit_process(int retcode, void *arg)
636 struct pthread_request request;
637 pthread_descr self = thread_self();
639 if (__pthread_manager_request >= 0) {
640 request.req_thread = self;
641 request.req_kind = REQ_PROCESS_EXIT;
642 request.req_args.exit.code = retcode;
643 __libc_write(__pthread_manager_request,
644 (char *) &request, sizeof(request));
645 suspend(self);
646 /* Main thread should accumulate times for thread manager and its
647 children, so that timings for main thread account for all threads. */
648 if (self == __pthread_main_thread)
649 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
653 /* The handler for the RESTART signal just records the signal received
654 in the thread descriptor, and optionally performs a siglongjmp
655 (for pthread_cond_timedwait). */
657 static void pthread_handle_sigrestart(int sig)
659 pthread_descr self = thread_self();
660 THREAD_SETMEM(self, p_signal, sig);
661 if (THREAD_GETMEM(self, p_signal_jmp) != NULL)
662 siglongjmp(*THREAD_GETMEM(self, p_signal_jmp), 1);
665 /* The handler for the CANCEL signal checks for cancellation
666 (in asynchronous mode), for process-wide exit and exec requests.
667 For the thread manager thread, redirect the signal to
668 __pthread_manager_sighandler. */
670 static void pthread_handle_sigcancel(int sig)
672 pthread_descr self = thread_self();
673 sigjmp_buf * jmpbuf;
675 if (self == &__pthread_manager_thread)
677 __pthread_manager_sighandler(sig);
678 return;
680 if (__pthread_exit_requested) {
681 /* Main thread should accumulate times for thread manager and its
682 children, so that timings for main thread account for all threads. */
683 if (self == __pthread_main_thread)
684 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
685 _exit(__pthread_exit_code);
687 if (THREAD_GETMEM(self, p_canceled)
688 && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
689 if (THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
690 pthread_exit(PTHREAD_CANCELED);
691 jmpbuf = THREAD_GETMEM(self, p_cancel_jmp);
692 if (jmpbuf != NULL) {
693 THREAD_SETMEM(self, p_cancel_jmp, NULL);
694 siglongjmp(*jmpbuf, 1);
699 /* Handler for the DEBUG signal.
700 The debugging strategy is as follows:
701 On reception of a REQ_DEBUG request (sent by new threads created to
702 the thread manager under debugging mode), the thread manager throws
703 __pthread_sig_debug to itself. The debugger (if active) intercepts
704 this signal, takes into account new threads and continue execution
705 of the thread manager by propagating the signal because it doesn't
706 know what it is specifically done for. In the current implementation,
707 the thread manager simply discards it. */
709 static void pthread_handle_sigdebug(int sig)
711 /* Nothing */
714 /* Reset the state of the thread machinery after a fork().
715 Close the pipe used for requests and set the main thread to the forked
716 thread.
717 Notice that we can't free the stack segments, as the forked thread
718 may hold pointers into them. */
720 void __pthread_reset_main_thread()
722 pthread_descr self = thread_self();
724 if (__pthread_manager_request != -1) {
725 /* Free the thread manager stack */
726 free(__pthread_manager_thread_bos);
727 __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
728 /* Close the two ends of the pipe */
729 __libc_close(__pthread_manager_request);
730 __libc_close(__pthread_manager_reader);
731 __pthread_manager_request = __pthread_manager_reader = -1;
734 /* Update the pid of the main thread */
735 THREAD_SETMEM(self, p_pid, __getpid());
736 /* Make the forked thread the main thread */
737 __pthread_main_thread = self;
738 THREAD_SETMEM(self, p_nextlive, self);
739 THREAD_SETMEM(self, p_prevlive, self);
740 /* Now this thread modifies the global variables. */
741 THREAD_SETMEM(self, p_errnop, &_errno);
742 THREAD_SETMEM(self, p_h_errnop, &_h_errno);
743 THREAD_SETMEM(self, p_resp, &_res);
746 /* Process-wide exec() request */
748 void __pthread_kill_other_threads_np(void)
750 struct sigaction sa;
751 /* Terminate all other threads and thread manager */
752 pthread_exit_process(0, NULL);
753 /* Make current thread the main thread in case the calling thread
754 changes its mind, does not exec(), and creates new threads instead. */
755 __pthread_reset_main_thread();
757 /* Reset the signal handlers behaviour for the signals the
758 implementation uses since this would be passed to the new
759 process. */
760 sigemptyset(&sa.sa_mask);
761 sa.sa_flags = 0;
762 sa.sa_handler = SIG_DFL;
763 __sigaction(__pthread_sig_restart, &sa, NULL);
764 __sigaction(__pthread_sig_cancel, &sa, NULL);
765 if (__pthread_sig_debug > 0)
766 __sigaction(__pthread_sig_debug, &sa, NULL);
768 weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
770 /* Concurrency symbol level. */
771 static int current_level;
773 int __pthread_setconcurrency(int level)
775 /* We don't do anything unless we have found a useful interpretation. */
776 current_level = level;
777 return 0;
779 weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
781 int __pthread_getconcurrency(void)
783 return current_level;
785 weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
787 void __pthread_set_own_extricate_if(pthread_descr self, pthread_extricate_if *peif)
789 __pthread_lock(self->p_lock, self);
790 THREAD_SETMEM(self, p_extricate, peif);
791 __pthread_spin_unlock(self->p_lock);
794 /* Primitives for controlling thread execution */
796 void __pthread_wait_for_restart_signal(pthread_descr self)
798 sigset_t mask;
800 sigprocmask(SIG_SETMASK, NULL, &mask); /* Get current signal mask */
801 sigdelset(&mask, __pthread_sig_restart); /* Unblock the restart signal */
802 do {
803 self->p_signal = 0;
804 sigsuspend(&mask); /* Wait for signal */
805 } while (self->p_signal !=__pthread_sig_restart );
808 #if !__ASSUME_REALTIME_SIGNALS
809 /* The _old variants are for 2.0 and early 2.1 kernels which don't have RT
810 signals.
811 On these kernels, we use SIGUSR1 and SIGUSR2 for restart and cancellation.
812 Since the restart signal does not queue, we use an atomic counter to create
813 queuing semantics. This is needed to resolve a rare race condition in
814 pthread_cond_timedwait_relative. */
816 void __pthread_restart_old(pthread_descr th)
818 if (atomic_increment(&th->p_resume_count) == -1)
819 kill(th->p_pid, __pthread_sig_restart);
822 void __pthread_suspend_old(pthread_descr self)
824 if (atomic_decrement(&self->p_resume_count) <= 0)
825 __pthread_wait_for_restart_signal(self);
829 __pthread_timedsuspend_old(pthread_descr self, const struct timespec *abstime)
831 sigset_t unblock, initial_mask;
832 int was_signalled = 0;
833 sigjmp_buf jmpbuf;
835 if (atomic_decrement(&self->p_resume_count) == 0) {
836 /* Set up a longjmp handler for the restart signal, unblock
837 the signal and sleep. */
839 if (sigsetjmp(jmpbuf, 1) == 0) {
840 THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
841 THREAD_SETMEM(self, p_signal, 0);
842 /* Unblock the restart signal */
843 sigemptyset(&unblock);
844 sigaddset(&unblock, __pthread_sig_restart);
845 sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
847 while (1) {
848 struct timeval now;
849 struct timespec reltime;
851 /* Compute a time offset relative to now. */
852 __gettimeofday (&now, NULL);
853 reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
854 reltime.tv_sec = abstime->tv_sec - now.tv_sec;
855 if (reltime.tv_nsec < 0) {
856 reltime.tv_nsec += 1000000000;
857 reltime.tv_sec -= 1;
860 /* Sleep for the required duration. If woken by a signal,
861 resume waiting as required by Single Unix Specification. */
862 if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
863 break;
866 /* Block the restart signal again */
867 sigprocmask(SIG_SETMASK, &initial_mask, NULL);
868 was_signalled = 0;
869 } else {
870 was_signalled = 1;
872 THREAD_SETMEM(self, p_signal_jmp, NULL);
875 /* Now was_signalled is true if we exited the above code
876 due to the delivery of a restart signal. In that case,
877 we know we have been dequeued and resumed and that the
878 resume count is balanced. Otherwise, there are some
879 cases to consider. First, try to bump up the resume count
880 back to zero. If it goes to 1, it means restart() was
881 invoked on this thread. The signal must be consumed
882 and the count bumped down and everything is cool. We
883 can return a 1 to the caller.
884 Otherwise, no restart was delivered yet, so a potential
885 race exists; we return a 0 to the caller which must deal
886 with this race in an appropriate way; for example by
887 atomically removing the thread from consideration for a
888 wakeup---if such a thing fails, it means a restart is
889 being delivered. */
891 if (!was_signalled) {
892 if (atomic_increment(&self->p_resume_count) != -1) {
893 __pthread_wait_for_restart_signal(self);
894 atomic_decrement(&self->p_resume_count); /* should be zero now! */
895 /* woke spontaneously and consumed restart signal */
896 return 1;
898 /* woke spontaneously but did not consume restart---caller must resolve */
899 return 0;
901 /* woken due to restart signal */
902 return 1;
904 #endif /* __ASSUME_REALTIME_SIGNALS */
906 void __pthread_restart_new(pthread_descr th)
908 kill(th->p_pid, __pthread_sig_restart);
911 /* There is no __pthread_suspend_new because it would just
912 be a wasteful wrapper for __pthread_wait_for_restart_signal */
915 __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime)
917 sigset_t unblock, initial_mask;
918 int was_signalled = 0;
919 sigjmp_buf jmpbuf;
921 if (sigsetjmp(jmpbuf, 1) == 0) {
922 THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
923 THREAD_SETMEM(self, p_signal, 0);
924 /* Unblock the restart signal */
925 sigemptyset(&unblock);
926 sigaddset(&unblock, __pthread_sig_restart);
927 sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
929 while (1) {
930 struct timeval now;
931 struct timespec reltime;
933 /* Compute a time offset relative to now. */
934 __gettimeofday (&now, NULL);
935 reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
936 reltime.tv_sec = abstime->tv_sec - now.tv_sec;
937 if (reltime.tv_nsec < 0) {
938 reltime.tv_nsec += 1000000000;
939 reltime.tv_sec -= 1;
942 /* Sleep for the required duration. If woken by a signal,
943 resume waiting as required by Single Unix Specification. */
944 if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
945 break;
948 /* Block the restart signal again */
949 sigprocmask(SIG_SETMASK, &initial_mask, NULL);
950 was_signalled = 0;
951 } else {
952 was_signalled = 1;
954 THREAD_SETMEM(self, p_signal_jmp, NULL);
956 /* Now was_signalled is true if we exited the above code
957 due to the delivery of a restart signal. In that case,
958 everything is cool. We have been removed from whatever
959 we were waiting on by the other thread, and consumed its signal.
961 Otherwise we this thread woke up spontaneously, or due to a signal other
962 than restart. This is an ambiguous case that must be resolved by
963 the caller; the thread is still eligible for a restart wakeup
964 so there is a race. */
966 return was_signalled;
970 /* Debugging aid */
972 #ifdef DEBUG
973 #include <stdarg.h>
975 void __pthread_message(char * fmt, ...)
977 char buffer[1024];
978 va_list args;
979 sprintf(buffer, "%05d : ", __getpid());
980 va_start(args, fmt);
981 vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
982 va_end(args);
983 __libc_write(2, buffer, strlen(buffer));
986 #endif
989 #ifndef SHARED
990 /* We need a hook to force the cancelation wrappers to be linked in when
991 static libpthread is used. */
992 extern const int __pthread_provide_wrappers;
993 static const int *const __pthread_require_wrappers =
994 &__pthread_provide_wrappers;
995 #endif