Update.
[glibc.git] / linuxthreads / pthread.c
blob2700a29fb16f761be06b573eed91e54af847f470
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;
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;
167 char *__pthread_manager_thread_tos;
169 /* For process-wide exit() */
171 int __pthread_exit_requested;
172 int __pthread_exit_code;
174 /* Nozero if the machine has more than one processor. */
175 int __pthread_smp_kernel;
178 #if !__ASSUME_REALTIME_SIGNALS
179 /* Pointers that select new or old suspend/resume functions
180 based on availability of rt signals. */
182 void (*__pthread_restart)(pthread_descr) = __pthread_restart_old;
183 void (*__pthread_suspend)(pthread_descr) = __pthread_suspend_old;
184 int (*__pthread_timedsuspend)(pthread_descr, const struct timespec *) = __pthread_timedsuspend_old;
185 #endif /* __ASSUME_REALTIME_SIGNALS */
187 /* Communicate relevant LinuxThreads constants to gdb */
189 const int __pthread_threads_max = PTHREAD_THREADS_MAX;
190 const int __pthread_sizeof_handle = sizeof(struct pthread_handle_struct);
191 const int __pthread_offsetof_descr = offsetof(struct pthread_handle_struct,
192 h_descr);
193 const int __pthread_offsetof_pid = offsetof(struct _pthread_descr_struct,
194 p_pid);
195 const int __linuxthread_pthread_sizeof_descr
196 = sizeof(struct _pthread_descr_struct);
198 /* These variables are used by the setup code. */
199 extern int _errno;
200 extern int _h_errno;
202 /* Forward declarations */
204 static void pthread_exit_process(int retcode, void *arg);
205 static void pthread_handle_sigcancel(int sig);
206 static void pthread_handle_sigrestart(int sig);
207 static void pthread_handle_sigdebug(int sig);
209 /* Signal numbers used for the communication.
210 In these variables we keep track of the used variables. If the
211 platform does not support any real-time signals we will define the
212 values to some unreasonable value which will signal failing of all
213 the functions below. */
214 #ifndef __SIGRTMIN
215 static int current_rtmin = -1;
216 static int current_rtmax = -1;
217 int __pthread_sig_restart = SIGUSR1;
218 int __pthread_sig_cancel = SIGUSR2;
219 int __pthread_sig_debug;
220 #else
221 static int current_rtmin;
222 static int current_rtmax;
224 #if __SIGRTMAX - __SIGRTMIN >= 3
225 int __pthread_sig_restart = __SIGRTMIN;
226 int __pthread_sig_cancel = __SIGRTMIN + 1;
227 int __pthread_sig_debug = __SIGRTMIN + 2;
228 #else
229 int __pthread_sig_restart = SIGUSR1;
230 int __pthread_sig_cancel = SIGUSR2;
231 int __pthread_sig_debug;
232 #endif
234 static int rtsigs_initialized;
236 #include "testrtsig.h"
238 static void
239 init_rtsigs (void)
241 #if !__ASSUME_REALTIME_SIGNALS
242 if (!kernel_has_rtsig ())
244 current_rtmin = -1;
245 current_rtmax = -1;
246 # if __SIGRTMAX - __SIGRTMIN >= 3
247 __pthread_sig_restart = SIGUSR1;
248 __pthread_sig_cancel = SIGUSR2;
249 __pthread_sig_debug = 0;
250 # endif
252 else
253 #endif /* __ASSUME_REALTIME_SIGNALS */
255 #if __SIGRTMAX - __SIGRTMIN >= 3
256 current_rtmin = __SIGRTMIN + 3;
257 # if !__ASSUME_REALTIME_SIGNALS
258 __pthread_restart = __pthread_restart_new;
259 __pthread_suspend = __pthread_wait_for_restart_signal;
260 __pthread_timedsuspend = __pthread_timedsuspend_new;
261 # endif /* __ASSUME_REALTIME_SIGNALS */
262 #else
263 current_rtmin = __SIGRTMIN;
264 #endif
266 current_rtmax = __SIGRTMAX;
269 rtsigs_initialized = 1;
271 #endif
273 /* Return number of available real-time signal with highest priority. */
275 __libc_current_sigrtmin (void)
277 #ifdef __SIGRTMIN
278 if (!rtsigs_initialized)
279 init_rtsigs ();
280 #endif
281 return current_rtmin;
284 /* Return number of available real-time signal with lowest priority. */
286 __libc_current_sigrtmax (void)
288 #ifdef __SIGRTMIN
289 if (!rtsigs_initialized)
290 init_rtsigs ();
291 #endif
292 return current_rtmax;
295 /* Allocate real-time signal with highest/lowest available
296 priority. Please note that we don't use a lock since we assume
297 this function to be called at program start. */
299 __libc_allocate_rtsig (int high)
301 #ifndef __SIGRTMIN
302 return -1;
303 #else
304 if (!rtsigs_initialized)
305 init_rtsigs ();
306 if (current_rtmin == -1 || current_rtmin > current_rtmax)
307 /* We don't have anymore signal available. */
308 return -1;
310 return high ? current_rtmin++ : current_rtmax--;
311 #endif
314 /* Initialize the pthread library.
315 Initialization is split in two functions:
316 - a constructor function that blocks the __pthread_sig_restart signal
317 (must do this very early, since the program could capture the signal
318 mask with e.g. sigsetjmp before creating the first thread);
319 - a regular function called from pthread_create when needed. */
321 static void pthread_initialize(void) __attribute__((constructor));
323 extern void *__dso_handle __attribute__ ((weak));
326 /* Do some minimal initialization which has to be done during the
327 startup of the C library. */
328 void
329 __pthread_initialize_minimal(void)
331 /* The errno/h_errno variable of the main thread are the global ones. */
332 __pthread_initial_thread.p_errnop = &_errno;
333 __pthread_initial_thread.p_h_errnop = &_h_errno;
334 /* If we have special thread_self processing, initialize that for the
335 main thread now. */
336 #ifdef INIT_THREAD_SELF
337 INIT_THREAD_SELF(&__pthread_initial_thread, 0);
338 #endif
342 static void pthread_initialize(void)
344 struct sigaction sa;
345 sigset_t mask;
346 struct rlimit limit;
347 int max_stack;
349 /* If already done (e.g. by a constructor called earlier!), bail out */
350 if (__pthread_initial_thread_bos != NULL) return;
351 #ifdef TEST_FOR_COMPARE_AND_SWAP
352 /* Test if compare-and-swap is available */
353 __pthread_has_cas = compare_and_swap_is_available();
354 #endif
355 /* For the initial stack, reserve at least STACK_SIZE bytes of stack
356 below the current stack address, and align that on a
357 STACK_SIZE boundary. */
358 __pthread_initial_thread_bos =
359 (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
360 /* Update the descriptor for the initial thread. */
361 __pthread_initial_thread.p_pid = __getpid();
362 /* Play with the stack size limit to make sure that no stack ever grows
363 beyond STACK_SIZE minus one page (to act as a guard page). */
364 getrlimit(RLIMIT_STACK, &limit);
365 max_stack = STACK_SIZE - __getpagesize();
366 if (limit.rlim_cur > max_stack) {
367 limit.rlim_cur = max_stack;
368 setrlimit(RLIMIT_STACK, &limit);
370 /* Likewise for the resolver state _res. */
371 __pthread_initial_thread.p_resp = &_res;
372 #ifdef __SIGRTMIN
373 /* Initialize real-time signals. */
374 init_rtsigs ();
375 #endif
376 /* Setup signal handlers for the initial thread.
377 Since signal handlers are shared between threads, these settings
378 will be inherited by all other threads. */
379 sa.sa_handler = pthread_handle_sigrestart;
380 sigemptyset(&sa.sa_mask);
381 sa.sa_flags = 0;
382 __libc_sigaction(__pthread_sig_restart, &sa, NULL);
383 sa.sa_handler = pthread_handle_sigcancel;
384 // sa.sa_flags = 0;
385 __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
386 if (__pthread_sig_debug > 0) {
387 sa.sa_handler = pthread_handle_sigdebug;
388 sigemptyset(&sa.sa_mask);
389 // sa.sa_flags = 0;
390 __libc_sigaction(__pthread_sig_debug, &sa, NULL);
392 /* Initially, block __pthread_sig_restart. Will be unblocked on demand. */
393 sigemptyset(&mask);
394 sigaddset(&mask, __pthread_sig_restart);
395 sigprocmask(SIG_BLOCK, &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_exit_process. */
399 if (&__dso_handle != NULL)
400 /* The cast is a bit unclean. The function expects two arguments but
401 we can only pass one. Fortunately this is not a problem since the
402 second argument of `pthread_exit_process' is simply ignored. */
403 __cxa_atexit((void (*) (void *)) pthread_exit_process, NULL, __dso_handle);
404 else
405 __on_exit (pthread_exit_process, NULL);
406 /* How many processors. */
407 __pthread_smp_kernel = sysconf (_SC_NPROCESSORS_ONLN) > 1;
410 void __pthread_initialize(void)
412 pthread_initialize();
415 int __pthread_initialize_manager(void)
417 int manager_pipe[2];
418 int pid;
419 struct pthread_request request;
421 /* If basic initialization not done yet (e.g. we're called from a
422 constructor run before our constructor), do it now */
423 if (__pthread_initial_thread_bos == NULL) pthread_initialize();
424 /* Setup stack for thread manager */
425 __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
426 if (__pthread_manager_thread_bos == NULL) return -1;
427 __pthread_manager_thread_tos =
428 __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;
429 /* Setup pipe to communicate with thread manager */
430 if (pipe(manager_pipe) == -1) {
431 free(__pthread_manager_thread_bos);
432 return -1;
434 /* Start the thread manager */
435 pid = 0;
436 if (__pthread_initial_thread.p_report_events)
438 /* It's a bit more complicated. We have to report the creation of
439 the manager thread. */
440 int idx = __td_eventword (TD_CREATE);
441 uint32_t mask = __td_eventmask (TD_CREATE);
443 if ((mask & (__pthread_threads_events.event_bits[idx]
444 | __pthread_initial_thread.p_eventbuf.eventmask.event_bits[idx]))
445 != 0)
447 pid = __clone(__pthread_manager_event,
448 (void **) __pthread_manager_thread_tos,
449 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
450 (void *)(long)manager_pipe[0]);
452 if (pid != -1)
454 /* Now fill in the information about the new thread in
455 the newly created thread's data structure. We cannot let
456 the new thread do this since we don't know whether it was
457 already scheduled when we send the event. */
458 __pthread_manager_thread.p_eventbuf.eventdata =
459 &__pthread_manager_thread;
460 __pthread_manager_thread.p_eventbuf.eventnum = TD_CREATE;
461 __pthread_last_event = &__pthread_manager_thread;
462 __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
463 __pthread_manager_thread.p_pid = pid;
465 /* Now call the function which signals the event. */
466 __linuxthreads_create_event ();
468 /* Now restart the thread. */
469 __pthread_unlock(__pthread_manager_thread.p_lock);
474 if (pid == 0)
475 pid = __clone(__pthread_manager, (void **) __pthread_manager_thread_tos,
476 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
477 (void *)(long)manager_pipe[0]);
478 if (pid == -1) {
479 free(__pthread_manager_thread_bos);
480 __libc_close(manager_pipe[0]);
481 __libc_close(manager_pipe[1]);
482 return -1;
484 __pthread_manager_request = manager_pipe[1]; /* writing end */
485 __pthread_manager_reader = manager_pipe[0]; /* reading end */
486 __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
487 __pthread_manager_thread.p_pid = pid;
488 /* Make gdb aware of new thread manager */
489 if (__pthread_threads_debug && __pthread_sig_debug > 0)
491 raise(__pthread_sig_debug);
492 /* We suspend ourself and gdb will wake us up when it is
493 ready to handle us. */
494 __pthread_wait_for_restart_signal(thread_self());
496 /* Synchronize debugging of the thread manager */
497 request.req_kind = REQ_DEBUG;
498 __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
499 return 0;
502 /* Thread creation */
504 int __pthread_create_2_1(pthread_t *thread, const pthread_attr_t *attr,
505 void * (*start_routine)(void *), void *arg)
507 pthread_descr self = thread_self();
508 struct pthread_request request;
509 int retval;
510 if (__pthread_manager_request < 0) {
511 if (__pthread_initialize_manager() < 0) return EAGAIN;
513 request.req_thread = self;
514 request.req_kind = REQ_CREATE;
515 request.req_args.create.attr = attr;
516 request.req_args.create.fn = start_routine;
517 request.req_args.create.arg = arg;
518 sigprocmask(SIG_SETMASK, (const sigset_t *) NULL,
519 &request.req_args.create.mask);
520 __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
521 suspend(self);
522 retval = THREAD_GETMEM(self, p_retcode);
523 if (retval == 0)
524 *thread = (pthread_t) THREAD_GETMEM(self, p_retval);
525 return retval;
528 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
530 #if SHLIB_COMPAT (libpthread, GLIBC_2_0, GLIBC_2_1)
532 int __pthread_create_2_0(pthread_t *thread, const pthread_attr_t *attr,
533 void * (*start_routine)(void *), void *arg)
535 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
536 the old size and access to the new members might crash the program.
537 We convert the struct now. */
538 pthread_attr_t new_attr;
540 if (attr != NULL)
542 size_t ps = __getpagesize ();
544 memcpy (&new_attr, attr,
545 (size_t) &(((pthread_attr_t*)NULL)->__guardsize));
546 new_attr.__guardsize = ps;
547 new_attr.__stackaddr_set = 0;
548 new_attr.__stackaddr = NULL;
549 new_attr.__stacksize = STACK_SIZE - ps;
550 attr = &new_attr;
552 return __pthread_create_2_1 (thread, attr, start_routine, arg);
554 compat_symbol (libpthread, __pthread_create_2_0, pthread_create, GLIBC_2_0);
555 #endif
557 /* Simple operations on thread identifiers */
559 pthread_t pthread_self(void)
561 pthread_descr self = thread_self();
562 return THREAD_GETMEM(self, p_tid);
565 int pthread_equal(pthread_t thread1, pthread_t thread2)
567 return thread1 == thread2;
570 /* Helper function for thread_self in the case of user-provided stacks */
572 #ifndef THREAD_SELF
574 pthread_descr __pthread_find_self()
576 char * sp = CURRENT_STACK_FRAME;
577 pthread_handle h;
579 /* __pthread_handles[0] is the initial thread, __pthread_handles[1] is
580 the manager threads handled specially in thread_self(), so start at 2 */
581 h = __pthread_handles + 2;
582 while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;
583 return h->h_descr;
586 #endif
588 /* Thread scheduling */
590 int pthread_setschedparam(pthread_t thread, int policy,
591 const struct sched_param *param)
593 pthread_handle handle = thread_handle(thread);
594 pthread_descr th;
596 __pthread_lock(&handle->h_lock, NULL);
597 if (invalid_handle(handle, thread)) {
598 __pthread_unlock(&handle->h_lock);
599 return ESRCH;
601 th = handle->h_descr;
602 if (__sched_setscheduler(th->p_pid, policy, param) == -1) {
603 __pthread_unlock(&handle->h_lock);
604 return errno;
606 th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
607 __pthread_unlock(&handle->h_lock);
608 if (__pthread_manager_request >= 0)
609 __pthread_manager_adjust_prio(th->p_priority);
610 return 0;
613 int pthread_getschedparam(pthread_t thread, int *policy,
614 struct sched_param *param)
616 pthread_handle handle = thread_handle(thread);
617 int pid, pol;
619 __pthread_lock(&handle->h_lock, NULL);
620 if (invalid_handle(handle, thread)) {
621 __pthread_unlock(&handle->h_lock);
622 return ESRCH;
624 pid = handle->h_descr->p_pid;
625 __pthread_unlock(&handle->h_lock);
626 pol = __sched_getscheduler(pid);
627 if (pol == -1) return errno;
628 if (__sched_getparam(pid, param) == -1) return errno;
629 *policy = pol;
630 return 0;
633 int __pthread_yield ()
635 /* For now this is equivalent with the POSIX call. */
636 return sched_yield ();
638 weak_alias (__pthread_yield, pthread_yield)
640 /* Process-wide exit() request */
642 static void pthread_exit_process(int retcode, void *arg)
644 struct pthread_request request;
645 pthread_descr self = thread_self();
647 if (__pthread_manager_request >= 0) {
648 request.req_thread = self;
649 request.req_kind = REQ_PROCESS_EXIT;
650 request.req_args.exit.code = retcode;
651 __libc_write(__pthread_manager_request,
652 (char *) &request, sizeof(request));
653 suspend(self);
654 /* Main thread should accumulate times for thread manager and its
655 children, so that timings for main thread account for all threads. */
656 if (self == __pthread_main_thread)
657 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
661 /* The handler for the RESTART signal just records the signal received
662 in the thread descriptor, and optionally performs a siglongjmp
663 (for pthread_cond_timedwait). */
665 static void pthread_handle_sigrestart(int sig)
667 pthread_descr self = thread_self();
668 THREAD_SETMEM(self, p_signal, sig);
669 if (THREAD_GETMEM(self, p_signal_jmp) != NULL)
670 siglongjmp(*THREAD_GETMEM(self, p_signal_jmp), 1);
673 /* The handler for the CANCEL signal checks for cancellation
674 (in asynchronous mode), for process-wide exit and exec requests.
675 For the thread manager thread, redirect the signal to
676 __pthread_manager_sighandler. */
678 static void pthread_handle_sigcancel(int sig)
680 pthread_descr self = thread_self();
681 sigjmp_buf * jmpbuf;
683 if (self == &__pthread_manager_thread)
685 __pthread_manager_sighandler(sig);
686 return;
688 if (__pthread_exit_requested) {
689 /* Main thread should accumulate times for thread manager and its
690 children, so that timings for main thread account for all threads. */
691 if (self == __pthread_main_thread)
692 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
693 _exit(__pthread_exit_code);
695 if (THREAD_GETMEM(self, p_canceled)
696 && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
697 if (THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
698 pthread_exit(PTHREAD_CANCELED);
699 jmpbuf = THREAD_GETMEM(self, p_cancel_jmp);
700 if (jmpbuf != NULL) {
701 THREAD_SETMEM(self, p_cancel_jmp, NULL);
702 siglongjmp(*jmpbuf, 1);
707 /* Handler for the DEBUG signal.
708 The debugging strategy is as follows:
709 On reception of a REQ_DEBUG request (sent by new threads created to
710 the thread manager under debugging mode), the thread manager throws
711 __pthread_sig_debug to itself. The debugger (if active) intercepts
712 this signal, takes into account new threads and continue execution
713 of the thread manager by propagating the signal because it doesn't
714 know what it is specifically done for. In the current implementation,
715 the thread manager simply discards it. */
717 static void pthread_handle_sigdebug(int sig)
719 /* Nothing */
722 /* Reset the state of the thread machinery after a fork().
723 Close the pipe used for requests and set the main thread to the forked
724 thread.
725 Notice that we can't free the stack segments, as the forked thread
726 may hold pointers into them. */
728 void __pthread_reset_main_thread()
730 pthread_descr self = thread_self();
732 if (__pthread_manager_request != -1) {
733 /* Free the thread manager stack */
734 free(__pthread_manager_thread_bos);
735 __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
736 /* Close the two ends of the pipe */
737 __libc_close(__pthread_manager_request);
738 __libc_close(__pthread_manager_reader);
739 __pthread_manager_request = __pthread_manager_reader = -1;
742 /* Update the pid of the main thread */
743 THREAD_SETMEM(self, p_pid, __getpid());
744 /* Make the forked thread the main thread */
745 __pthread_main_thread = self;
746 THREAD_SETMEM(self, p_nextlive, self);
747 THREAD_SETMEM(self, p_prevlive, self);
748 /* Now this thread modifies the global variables. */
749 THREAD_SETMEM(self, p_errnop, &_errno);
750 THREAD_SETMEM(self, p_h_errnop, &_h_errno);
751 THREAD_SETMEM(self, p_resp, &_res);
754 /* Process-wide exec() request */
756 void __pthread_kill_other_threads_np(void)
758 struct sigaction sa;
759 /* Terminate all other threads and thread manager */
760 pthread_exit_process(0, NULL);
761 /* Make current thread the main thread in case the calling thread
762 changes its mind, does not exec(), and creates new threads instead. */
763 __pthread_reset_main_thread();
765 /* Reset the signal handlers behaviour for the signals the
766 implementation uses since this would be passed to the new
767 process. */
768 sigemptyset(&sa.sa_mask);
769 sa.sa_flags = 0;
770 sa.sa_handler = SIG_DFL;
771 __libc_sigaction(__pthread_sig_restart, &sa, NULL);
772 __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
773 if (__pthread_sig_debug > 0)
774 __libc_sigaction(__pthread_sig_debug, &sa, NULL);
776 weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
778 /* Concurrency symbol level. */
779 static int current_level;
781 int __pthread_setconcurrency(int level)
783 /* We don't do anything unless we have found a useful interpretation. */
784 current_level = level;
785 return 0;
787 weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
789 int __pthread_getconcurrency(void)
791 return current_level;
793 weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
795 void __pthread_set_own_extricate_if(pthread_descr self, pthread_extricate_if *peif)
797 __pthread_lock(self->p_lock, self);
798 THREAD_SETMEM(self, p_extricate, peif);
799 __pthread_unlock(self->p_lock);
802 /* Primitives for controlling thread execution */
804 void __pthread_wait_for_restart_signal(pthread_descr self)
806 sigset_t mask;
808 sigprocmask(SIG_SETMASK, NULL, &mask); /* Get current signal mask */
809 sigdelset(&mask, __pthread_sig_restart); /* Unblock the restart signal */
810 do {
811 self->p_signal = 0;
812 sigsuspend(&mask); /* Wait for signal */
813 } while (self->p_signal !=__pthread_sig_restart );
816 #if !__ASSUME_REALTIME_SIGNALS
817 /* The _old variants are for 2.0 and early 2.1 kernels which don't have RT
818 signals.
819 On these kernels, we use SIGUSR1 and SIGUSR2 for restart and cancellation.
820 Since the restart signal does not queue, we use an atomic counter to create
821 queuing semantics. This is needed to resolve a rare race condition in
822 pthread_cond_timedwait_relative. */
824 void __pthread_restart_old(pthread_descr th)
826 if (atomic_increment(&th->p_resume_count) == -1)
827 kill(th->p_pid, __pthread_sig_restart);
830 void __pthread_suspend_old(pthread_descr self)
832 if (atomic_decrement(&self->p_resume_count) <= 0)
833 __pthread_wait_for_restart_signal(self);
837 __pthread_timedsuspend_old(pthread_descr self, const struct timespec *abstime)
839 sigset_t unblock, initial_mask;
840 int was_signalled = 0;
841 sigjmp_buf jmpbuf;
843 if (atomic_decrement(&self->p_resume_count) == 0) {
844 /* Set up a longjmp handler for the restart signal, unblock
845 the signal and sleep. */
847 if (sigsetjmp(jmpbuf, 1) == 0) {
848 THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
849 THREAD_SETMEM(self, p_signal, 0);
850 /* Unblock the restart signal */
851 sigemptyset(&unblock);
852 sigaddset(&unblock, __pthread_sig_restart);
853 sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
855 while (1) {
856 struct timeval now;
857 struct timespec reltime;
859 /* Compute a time offset relative to now. */
860 __gettimeofday (&now, NULL);
861 reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
862 reltime.tv_sec = abstime->tv_sec - now.tv_sec;
863 if (reltime.tv_nsec < 0) {
864 reltime.tv_nsec += 1000000000;
865 reltime.tv_sec -= 1;
868 /* Sleep for the required duration. If woken by a signal,
869 resume waiting as required by Single Unix Specification. */
870 if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
871 break;
874 /* Block the restart signal again */
875 sigprocmask(SIG_SETMASK, &initial_mask, NULL);
876 was_signalled = 0;
877 } else {
878 was_signalled = 1;
880 THREAD_SETMEM(self, p_signal_jmp, NULL);
883 /* Now was_signalled is true if we exited the above code
884 due to the delivery of a restart signal. In that case,
885 we know we have been dequeued and resumed and that the
886 resume count is balanced. Otherwise, there are some
887 cases to consider. First, try to bump up the resume count
888 back to zero. If it goes to 1, it means restart() was
889 invoked on this thread. The signal must be consumed
890 and the count bumped down and everything is cool. We
891 can return a 1 to the caller.
892 Otherwise, no restart was delivered yet, so a potential
893 race exists; we return a 0 to the caller which must deal
894 with this race in an appropriate way; for example by
895 atomically removing the thread from consideration for a
896 wakeup---if such a thing fails, it means a restart is
897 being delivered. */
899 if (!was_signalled) {
900 if (atomic_increment(&self->p_resume_count) != -1) {
901 __pthread_wait_for_restart_signal(self);
902 atomic_decrement(&self->p_resume_count); /* should be zero now! */
903 /* woke spontaneously and consumed restart signal */
904 return 1;
906 /* woke spontaneously but did not consume restart---caller must resolve */
907 return 0;
909 /* woken due to restart signal */
910 return 1;
912 #endif /* __ASSUME_REALTIME_SIGNALS */
914 void __pthread_restart_new(pthread_descr th)
916 kill(th->p_pid, __pthread_sig_restart);
919 /* There is no __pthread_suspend_new because it would just
920 be a wasteful wrapper for __pthread_wait_for_restart_signal */
923 __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime)
925 sigset_t unblock, initial_mask;
926 int was_signalled = 0;
927 sigjmp_buf jmpbuf;
929 if (sigsetjmp(jmpbuf, 1) == 0) {
930 THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
931 THREAD_SETMEM(self, p_signal, 0);
932 /* Unblock the restart signal */
933 sigemptyset(&unblock);
934 sigaddset(&unblock, __pthread_sig_restart);
935 sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
937 while (1) {
938 struct timeval now;
939 struct timespec reltime;
941 /* Compute a time offset relative to now. */
942 __gettimeofday (&now, NULL);
943 reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
944 reltime.tv_sec = abstime->tv_sec - now.tv_sec;
945 if (reltime.tv_nsec < 0) {
946 reltime.tv_nsec += 1000000000;
947 reltime.tv_sec -= 1;
950 /* Sleep for the required duration. If woken by a signal,
951 resume waiting as required by Single Unix Specification. */
952 if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
953 break;
956 /* Block the restart signal again */
957 sigprocmask(SIG_SETMASK, &initial_mask, NULL);
958 was_signalled = 0;
959 } else {
960 was_signalled = 1;
962 THREAD_SETMEM(self, p_signal_jmp, NULL);
964 /* Now was_signalled is true if we exited the above code
965 due to the delivery of a restart signal. In that case,
966 everything is cool. We have been removed from whatever
967 we were waiting on by the other thread, and consumed its signal.
969 Otherwise we this thread woke up spontaneously, or due to a signal other
970 than restart. This is an ambiguous case that must be resolved by
971 the caller; the thread is still eligible for a restart wakeup
972 so there is a race. */
974 return was_signalled;
978 /* Debugging aid */
980 #ifdef DEBUG
981 #include <stdarg.h>
983 void __pthread_message(char * fmt, ...)
985 char buffer[1024];
986 va_list args;
987 sprintf(buffer, "%05d : ", __getpid());
988 va_start(args, fmt);
989 vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
990 va_end(args);
991 __libc_write(2, buffer, strlen(buffer));
994 #endif
997 #ifndef SHARED
998 /* We need a hook to force the cancelation wrappers to be linked in when
999 static libpthread is used. */
1000 extern const int __pthread_provide_wrappers;
1001 static const int *const __pthread_require_wrappers =
1002 &__pthread_provide_wrappers;
1003 #endif