1 /* Linuxthreads - a simple clone()-based implementation of Posix */
2 /* threads for Linux. */
3 /* Copyright (C) 1996 Xavier Leroy (Xavier.Leroy@inria.fr) */
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. */
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 */
21 #include <netdb.h> /* for h_errno */
29 #include <sys/resource.h>
31 #include "internals.h"
34 #include "debug.h" /* added to linuxthreads -StS */
37 /* Mods for uClibc: Some includes */
39 #include <sys/types.h>
40 #include <sys/syscall.h>
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);
49 /* These variables are used by the setup code. */
54 /* Descriptor of the initial thread */
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 */
63 0, /* int p_priority */
64 &__pthread_handles[0].h_lock, /* struct _pthread_fastlock * p_lock */
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 */
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 */
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__
104 &__global_locale_data, /* __locale_t locale; */
105 #endif /* __UCLIBC_HAS_XLOCALE__ */
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 */
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 */
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__
160 &__global_locale_data, /* __locale_t locale; */
161 #endif /* __UCLIBC_HAS_XLOCALE__ */
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() */
167 pthread_descr __pthread_main_thread = &__pthread_initial_thread;
169 /* Limit between the stack of the initial thread (above) and the
170 stacks of other threads (below). Aligned on a STACK_SIZE boundary. */
172 char *__pthread_initial_thread_bos = NULL;
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 */
178 #ifndef __ARCH_HAS_MMU__
179 char *__pthread_initial_thread_tos = NULL;
180 #endif /* __ARCH_HAS_MMU__ */
182 /* File descriptor for sending requests to the thread manager. */
183 /* Initially -1, meaning that the thread manager is not running. */
185 int __pthread_manager_request = -1;
187 /* Other end of the pipe for sending requests to the thread manager. */
189 int __pthread_manager_reader;
191 /* Limits of the thread manager stack */
193 char *__pthread_manager_thread_bos = NULL;
194 char *__pthread_manager_thread_tos = NULL;
196 /* For process-wide exit() */
198 int __pthread_exit_requested = 0;
199 int __pthread_exit_code = 0;
201 /* Communicate relevant LinuxThreads constants to gdb */
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,
208 const int __linuxthreads_pthread_sizeof_descr
209 = sizeof(struct _pthread_descr_struct);
211 const int __linuxthreads_initial_report_events;
213 const char __linuxthreads_version[] = VERSION;
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);
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;
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;
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;
256 /* Return number of available real-time signal with highest priority. */
257 int __libc_current_sigrtmin (void)
259 return current_rtmin;
262 /* Return number of available real-time signal with lowest priority. */
263 int __libc_current_sigrtmax (void)
265 return current_rtmax;
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)
273 if (current_rtmin == -1 || current_rtmin > current_rtmax)
274 /* We don't have anymore signal available. */
276 return high ? current_rtmin++ : current_rtmax--;
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. */
287 static void pthread_initialize(void) __attribute__((constructor));
289 /* Do some minimal initialization which has to be done during the
290 startup of the C library. */
291 void __pthread_initialize_minimal(void)
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);
301 static void pthread_initialize(void)
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();
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
323 #ifdef INIT_THREAD_SELF
324 INIT_THREAD_SELF(&__pthread_initial_thread, 0);
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;
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__ */
335 { /* uClibc-specific stdio initialization for threads. */
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;
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). */
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);
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
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__ */
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);
377 __libc_sigaction(__pthread_sig_restart, &sa, NULL);
378 sa.sa_handler = pthread_handle_sigcancel;
379 sigaddset(&sa.sa_mask, __pthread_sig_restart);
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);
386 __libc_sigaction(__pthread_sig_debug, &sa, NULL);
388 /* Initially, block __pthread_sig_restart. Will be unblocked on demand. */
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);
402 void __pthread_initialize(void)
404 pthread_initialize();
407 int __pthread_initialize_manager(void)
412 struct pthread_request request;
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;
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);
429 PDEBUG("initial stack: estimate bos=%p, tos=%p\n",
430 __pthread_initial_thread_bos, __pthread_initial_thread_tos);
433 /* Setup pipe to communicate with thread manager */
434 if (pipe(manager_pipe) == -1) {
435 free(__pthread_manager_thread_bos);
438 /* Start the thread manager */
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);
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;
451 if (__builtin_expect (report_events, 0))
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);
458 if ((mask & (__pthread_threads_events.event_bits[idx]
459 | __pthread_initial_thread.p_eventbuf.eventmask.event_bits[idx]))
463 __pthread_lock(__pthread_manager_thread.p_lock, NULL);
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]);
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;
483 /* Now call the function which signals the event. */
484 __linuxthreads_create_event ();
486 /* Now restart the thread. */
487 __pthread_unlock(__pthread_manager_thread.p_lock);
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]);
497 free(__pthread_manager_thread_bos);
498 __libc_close(manager_pipe[0]);
499 __libc_close(manager_pipe[1]);
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;
507 /* Make gdb aware of new thread manager */
508 if (__pthread_threads_debug && __pthread_sig_debug > 0)
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());
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)));
523 /* Thread creation */
525 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
526 void * (*start_routine)(void *), void *arg)
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;
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");
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);
551 /* Simple operations on thread identifiers */
553 pthread_t pthread_self(void)
555 pthread_descr self = thread_self();
556 return THREAD_GETMEM(self, p_tid);
559 int pthread_equal(pthread_t thread1, pthread_t thread2)
561 return thread1 == thread2;
564 /* Helper function for thread_self in the case of user-provided stacks */
568 pthread_descr __pthread_find_self()
570 char * sp = CURRENT_STACK_FRAME;
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++;
579 if (h->h_descr == NULL) {
580 printf("*** %s ERROR descriptor is NULL!!!!! ***\n\n", __FUNCTION__);
589 static pthread_descr thread_self_stack(void)
591 char *sp = CURRENT_STACK_FRAME;
594 if (sp >= __pthread_manager_thread_bos && sp < __pthread_manager_thread_tos)
595 return manager_thread;
596 h = __pthread_handles + 2;
598 while (h->h_descr == NULL
599 || ! (sp <= (char *) h->h_descr->p_stackaddr && sp >= h->h_bottom))
602 while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom))
610 /* Thread scheduling */
612 int pthread_setschedparam(pthread_t thread, int policy,
613 const struct sched_param *param)
615 pthread_handle handle = thread_handle(thread);
618 __pthread_lock(&handle->h_lock, NULL);
619 if (invalid_handle(handle, thread)) {
620 __pthread_unlock(&handle->h_lock);
623 th = handle->h_descr;
624 if (sched_setscheduler(th->p_pid, policy, param) == -1) {
625 __pthread_unlock(&handle->h_lock);
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);
635 int pthread_getschedparam(pthread_t thread, int *policy,
636 struct sched_param *param)
638 pthread_handle handle = thread_handle(thread);
641 __pthread_lock(&handle->h_lock, NULL);
642 if (invalid_handle(handle, thread)) {
643 __pthread_unlock(&handle->h_lock);
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;
655 /* Process-wide exit() request */
657 static void pthread_onexit_process(int retcode, void *arg)
659 struct pthread_request request;
660 pthread_descr self = thread_self();
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)));
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;
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). */
684 static void pthread_handle_sigrestart(int sig)
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);
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. */
697 static void pthread_handle_sigcancel(int sig)
699 pthread_descr self = thread_self();
703 if (self == &__pthread_manager_thread)
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
710 pthread_descr real_self = thread_self_stack();
711 if (real_self == &__pthread_manager_thread)
713 __pthread_manager_sighandler(sig);
716 /* Oops, thread_self() isn't working yet.. */
718 # ifdef INIT_THREAD_SELF
719 INIT_THREAD_SELF(self, self->p_nr);
722 __pthread_manager_sighandler(sig);
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) {
731 waitpid(__pthread_manager_thread->p_pid, NULL, __WCLONE);
733 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
736 _exit(__pthread_exit_code);
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);
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. */
760 static void pthread_handle_sigdebug(int sig)
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
768 Notice that we can't free the stack segments, as the forked thread
769 may hold pointers into them. */
771 void __pthread_reset_main_thread()
773 pthread_descr self = thread_self();
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;
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);
796 /* Process-wide exec() request */
798 void __pthread_kill_other_threads_np(void)
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
809 sigemptyset(&sa.sa_mask);
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);
817 weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
819 /* Concurrency symbol level. */
820 static int current_level;
822 int __pthread_setconcurrency(int level)
824 /* We don't do anything unless we have found a useful interpretation. */
825 current_level = level;
828 weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
830 int __pthread_getconcurrency(void)
832 return current_level;
834 weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
837 /* Primitives for controlling thread execution */
839 void __pthread_wait_for_restart_signal(pthread_descr self)
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);
847 sigsuspend(&mask); /* Wait for signal */
848 } while (THREAD_GETMEM(self, p_signal) !=__pthread_sig_restart);
850 READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
853 #ifndef __NR_rt_sigaction
854 /* The _old variants are for 2.0 and early 2.1 kernels which don't have RT
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. */
861 void __pthread_restart_old(pthread_descr th)
863 if (atomic_increment(&th->p_resume_count) == -1)
864 kill(th->p_pid, __pthread_sig_restart);
867 void __pthread_suspend_old(pthread_descr self)
869 if (atomic_decrement(&self->p_resume_count) <= 0)
870 __pthread_wait_for_restart_signal(self);
874 __pthread_timedsuspend_old(pthread_descr self, const struct timespec *abstime)
876 sigset_t unblock, initial_mask;
877 int was_signalled = 0;
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. */
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);
894 struct timespec reltime;
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;
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)
911 /* Block the restart signal again */
912 sigprocmask(SIG_SETMASK, &initial_mask, NULL);
917 THREAD_SETMEM(self, p_signal_jmp, NULL);
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
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 */
943 /* woke spontaneously but did not consume restart---caller must resolve */
946 /* woken due to restart signal */
949 #endif /* __NR_rt_sigaction */
952 #ifdef __NR_rt_sigaction
953 void __pthread_restart_new(pthread_descr th)
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);
963 int __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime)
965 sigset_t unblock, initial_mask;
966 int was_signalled = 0;
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);
979 struct timespec reltime;
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;
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)
996 /* Block the restart signal again */
997 sigprocmask(SIG_SETMASK, &initial_mask, NULL);
1002 THREAD_SETMEM(self, p_signal_jmp, NULL);
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.
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. */
1014 READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
1015 return was_signalled;
1024 void __pthread_message(char * fmt, ...)
1028 sprintf(buffer, "%05d : ", __getpid());
1029 va_start(args, fmt);
1030 vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
1032 TEMP_FAILURE_RETRY(__libc_write(2, buffer, strlen(buffer)));
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;