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 */
25 #include <sys/resource.h>
26 #include <sys/sysctl.h>
27 #include <shlib-compat.h>
29 #include "internals.h"
33 /* We need the global/static resolver state here. */
37 extern struct __res_state _res;
40 #if __ASSUME_REALTIME_SIGNALS && !defined __SIGRTMIN
41 # error "This must not happen; new kernel assumed but old headers"
44 /* These variables are used by the setup code. */
48 /* Descriptor of the initial thread */
50 struct _pthread_descr_struct __pthread_initial_thread = {
53 &__pthread_initial_thread /* pthread_descr self */
56 &__pthread_initial_thread, /* pthread_descr p_nextlive */
57 &__pthread_initial_thread, /* pthread_descr p_prevlive */
58 NULL, /* pthread_descr p_nextwaiting */
59 NULL, /* pthread_descr p_nextlock */
60 PTHREAD_THREADS_MAX, /* pthread_t p_tid */
62 0, /* int p_priority */
63 &__pthread_handles[0].h_lock, /* struct _pthread_fastlock * p_lock */
65 NULL, /* sigjmp_buf * p_signal_buf */
66 NULL, /* sigjmp_buf * p_cancel_buf */
67 0, /* char p_terminated */
68 0, /* char p_detached */
69 0, /* char p_exited */
70 NULL, /* void * p_retval */
72 NULL, /* pthread_descr p_joining */
73 NULL, /* struct _pthread_cleanup_buffer * p_cleanup */
74 0, /* char p_cancelstate */
75 0, /* char p_canceltype */
76 0, /* char p_canceled */
77 &_errno, /* int *p_errnop */
79 &_h_errno, /* int *p_h_errnop */
80 0, /* int p_h_errno */
81 NULL, /* char * p_in_sighandler */
82 0, /* char p_sigwaiting */
83 PTHREAD_START_ARGS_INITIALIZER(NULL),
84 /* 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 1, /* int p_userstack */
88 NULL, /* void * p_guardaddr */
89 0, /* size_t p_guardsize */
90 0, /* Always index 0 */
91 0, /* int p_report_events */
92 {{{0, }}, 0, NULL}, /* td_eventbuf_t p_eventbuf */
93 ATOMIC_INITIALIZER, /* struct pthread_atomic p_resume_count */
94 0, /* char p_woken_by_cancel */
95 0, /* char p_condvar_avail */
96 0, /* char p_sem_avail */
97 NULL, /* struct pthread_extricate_if *p_extricate */
98 NULL, /* pthread_readlock_info *p_readlock_list; */
99 NULL, /* pthread_readlock_info *p_readlock_free; */
100 0 /* int p_untracked_readlock_count; */
103 /* Descriptor of the manager thread; none of this is used but the error
104 variables, the p_pid and p_priority fields,
105 and the address for identification. */
107 struct _pthread_descr_struct __pthread_manager_thread = {
110 &__pthread_manager_thread /* pthread_descr self */
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(__pthread_manager),
141 /* struct pthread_start_args p_start_args */
142 {NULL}, /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
143 {NULL}, /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
144 0, /* int p_userstack */
145 NULL, /* void * p_guardaddr */
146 0, /* size_t p_guardsize */
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; */
160 /* Pointer to the main thread (the father of the thread manager thread) */
161 /* Originally, this is the initial thread, but this changes after fork() */
163 pthread_descr __pthread_main_thread = &__pthread_initial_thread;
165 /* Limit between the stack of the initial thread (above) and the
166 stacks of other threads (below). Aligned on a STACK_SIZE boundary. */
168 char *__pthread_initial_thread_bos;
170 /* File descriptor for sending requests to the thread manager. */
171 /* Initially -1, meaning that the thread manager is not running. */
173 int __pthread_manager_request = -1;
175 /* Other end of the pipe for sending requests to the thread manager. */
177 int __pthread_manager_reader;
179 /* Limits of the thread manager stack */
181 char *__pthread_manager_thread_bos;
182 char *__pthread_manager_thread_tos;
184 /* For process-wide exit() */
186 int __pthread_exit_requested;
187 int __pthread_exit_code;
189 /* Maximum stack size. */
190 size_t __pthread_max_stacksize;
192 /* Nozero if the machine has more than one processor. */
193 int __pthread_smp_kernel;
196 #if !__ASSUME_REALTIME_SIGNALS
197 /* Pointers that select new or old suspend/resume functions
198 based on availability of rt signals. */
200 void (*__pthread_restart)(pthread_descr) = __pthread_restart_old;
201 void (*__pthread_suspend)(pthread_descr) = __pthread_suspend_old;
202 int (*__pthread_timedsuspend)(pthread_descr, const struct timespec *) = __pthread_timedsuspend_old;
203 #endif /* __ASSUME_REALTIME_SIGNALS */
205 /* Communicate relevant LinuxThreads constants to gdb */
207 const int __pthread_threads_max = PTHREAD_THREADS_MAX;
208 const int __pthread_sizeof_handle = sizeof(struct pthread_handle_struct);
209 const int __pthread_offsetof_descr = offsetof(struct pthread_handle_struct,
211 const int __pthread_offsetof_pid = offsetof(struct _pthread_descr_struct,
213 const int __linuxthread_pthread_sizeof_descr
214 = sizeof(struct _pthread_descr_struct);
216 /* Forward declarations */
218 static void pthread_exit_process(int retcode, void *arg);
219 static void pthread_handle_sigcancel(int sig);
220 static void pthread_handle_sigrestart(int sig);
221 static void pthread_handle_sigdebug(int sig);
223 /* Signal numbers used for the communication.
224 In these variables we keep track of the used variables. If the
225 platform does not support any real-time signals we will define the
226 values to some unreasonable value which will signal failing of all
227 the functions below. */
229 static int current_rtmin = -1;
230 static int current_rtmax = -1;
231 int __pthread_sig_restart = SIGUSR1;
232 int __pthread_sig_cancel = SIGUSR2;
233 int __pthread_sig_debug;
235 static int current_rtmin;
236 static int current_rtmax;
238 #if __SIGRTMAX - __SIGRTMIN >= 3
239 int __pthread_sig_restart = __SIGRTMIN;
240 int __pthread_sig_cancel = __SIGRTMIN + 1;
241 int __pthread_sig_debug = __SIGRTMIN + 2;
243 int __pthread_sig_restart = SIGUSR1;
244 int __pthread_sig_cancel = SIGUSR2;
245 int __pthread_sig_debug;
248 static int rtsigs_initialized;
250 #include "testrtsig.h"
255 #if !__ASSUME_REALTIME_SIGNALS
256 if (__builtin_expect (!kernel_has_rtsig (), 0))
260 # if __SIGRTMAX - __SIGRTMIN >= 3
261 __pthread_sig_restart = SIGUSR1;
262 __pthread_sig_cancel = SIGUSR2;
263 __pthread_sig_debug = 0;
267 #endif /* __ASSUME_REALTIME_SIGNALS */
269 #if __SIGRTMAX - __SIGRTMIN >= 3
270 current_rtmin = __SIGRTMIN + 3;
271 # if !__ASSUME_REALTIME_SIGNALS
272 __pthread_restart = __pthread_restart_new;
273 __pthread_suspend = __pthread_wait_for_restart_signal;
274 __pthread_timedsuspend = __pthread_timedsuspend_new;
275 # endif /* __ASSUME_REALTIME_SIGNALS */
277 current_rtmin = __SIGRTMIN;
280 current_rtmax = __SIGRTMAX;
283 rtsigs_initialized = 1;
287 /* Return number of available real-time signal with highest priority. */
289 __libc_current_sigrtmin (void)
292 if (__builtin_expect (!rtsigs_initialized, 0))
295 return current_rtmin;
298 /* Return number of available real-time signal with lowest priority. */
300 __libc_current_sigrtmax (void)
303 if (__builtin_expect (!rtsigs_initialized, 0))
306 return current_rtmax;
309 /* Allocate real-time signal with highest/lowest available
310 priority. Please note that we don't use a lock since we assume
311 this function to be called at program start. */
313 __libc_allocate_rtsig (int high)
318 if (__builtin_expect (!rtsigs_initialized, 0))
320 if (__builtin_expect (current_rtmin == -1, 0)
321 || __builtin_expect (current_rtmin > current_rtmax, 0))
322 /* We don't have anymore signal available. */
325 return high ? current_rtmin++ : current_rtmax--;
329 /* The function we use to get the kernel revision. */
330 extern int __sysctl (int *name, int nlen, void *oldval, size_t *oldlenp,
331 void *newval, size_t newlen);
333 /* Test whether the machine has more than one processor. This is not the
334 best test but good enough. More complicated tests would require `malloc'
335 which is not available at that time. */
339 static const int sysctl_args[] = { CTL_KERN, KERN_VERSION };
341 size_t reslen = sizeof (buf);
343 /* Try reading the number using `sysctl' first. */
344 if (__sysctl ((int *) sysctl_args,
345 sizeof (sysctl_args) / sizeof (sysctl_args[0]),
346 buf, &reslen, NULL, 0) < 0)
348 /*This was not successful. Now try reading the /proc filesystem. */
349 int fd = __open ("/proc/sys/kernel/version", O_RDONLY);
350 if (__builtin_expect (fd, 0) == -1
351 || (reslen = __read (fd, buf, sizeof (buf))) <= 0)
352 /* This also didn't work. We give up and say it's a UP machine. */
358 return strstr (buf, "SMP") != NULL;
362 /* Initialize the pthread library.
363 Initialization is split in two functions:
364 - a constructor function that blocks the __pthread_sig_restart signal
365 (must do this very early, since the program could capture the signal
366 mask with e.g. sigsetjmp before creating the first thread);
367 - a regular function called from pthread_create when needed. */
369 static void pthread_initialize(void) __attribute__((constructor));
371 extern void *__dso_handle __attribute__ ((weak));
374 /* Do some minimal initialization which has to be done during the
375 startup of the C library. */
377 __pthread_initialize_minimal(void)
379 /* If we have special thread_self processing, initialize that for the
381 #ifdef INIT_THREAD_SELF
382 INIT_THREAD_SELF(&__pthread_initial_thread, 0);
387 static void pthread_initialize(void)
392 /* If already done (e.g. by a constructor called earlier!), bail out */
393 if (__pthread_initial_thread_bos != NULL) return;
394 #ifdef TEST_FOR_COMPARE_AND_SWAP
395 /* Test if compare-and-swap is available */
396 __pthread_has_cas = compare_and_swap_is_available();
398 /* For the initial stack, reserve at least STACK_SIZE bytes of stack
399 below the current stack address, and align that on a
400 STACK_SIZE boundary. */
401 __pthread_initial_thread_bos =
402 (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
403 /* Update the descriptor for the initial thread. */
404 __pthread_initial_thread.p_pid = __getpid();
405 /* Likewise for the resolver state _res. */
406 __pthread_initial_thread.p_resp = &_res;
408 /* Initialize real-time signals. */
411 /* Setup signal handlers for the initial thread.
412 Since signal handlers are shared between threads, these settings
413 will be inherited by all other threads. */
414 sa.sa_handler = pthread_handle_sigrestart;
415 sigemptyset(&sa.sa_mask);
417 __libc_sigaction(__pthread_sig_restart, &sa, NULL);
418 sa.sa_handler = pthread_handle_sigcancel;
420 __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
421 if (__pthread_sig_debug > 0) {
422 sa.sa_handler = pthread_handle_sigdebug;
423 sigemptyset(&sa.sa_mask);
425 __libc_sigaction(__pthread_sig_debug, &sa, NULL);
427 /* Initially, block __pthread_sig_restart. Will be unblocked on demand. */
429 sigaddset(&mask, __pthread_sig_restart);
430 sigprocmask(SIG_BLOCK, &mask, NULL);
431 /* Register an exit function to kill all other threads. */
432 /* Do it early so that user-registered atexit functions are called
433 before pthread_exit_process. */
434 if (__builtin_expect (&__dso_handle != NULL, 1))
435 /* The cast is a bit unclean. The function expects two arguments but
436 we can only pass one. Fortunately this is not a problem since the
437 second argument of `pthread_exit_process' is simply ignored. */
438 __cxa_atexit((void (*) (void *)) pthread_exit_process, NULL, __dso_handle);
440 __on_exit (pthread_exit_process, NULL);
441 /* How many processors. */
442 __pthread_smp_kernel = is_smp_system ();
445 void __pthread_initialize(void)
447 pthread_initialize();
450 int __pthread_initialize_manager(void)
454 struct pthread_request request;
458 getrlimit(RLIMIT_STACK, &limit);
459 #ifdef FLOATING_STACKS
460 if (limit.rlim_cur == RLIM_INFINITY)
461 limit.rlim_cur = ARCH_STACK_MAX_SIZE;
462 # ifdef NEED_SEPARATE_REGISTER_STACK
463 max_stack = limit.rlim_cur / 2;
465 max_stack = limit.rlim_cur;
468 __pthread_max_stacksize = max_stack;
470 /* Play with the stack size limit to make sure that no stack ever grows
471 beyond STACK_SIZE minus one page (to act as a guard page). */
472 # ifdef NEED_SEPARATE_REGISTER_STACK
473 /* STACK_SIZE bytes hold both the main stack and register backing
474 store. The rlimit value applies to each individually. */
475 max_stack = STACK_SIZE/2 - __getpagesize ();
477 max_stack = STACK_SIZE - __getpagesize();
479 if (limit.rlim_cur > max_stack) {
480 limit.rlim_cur = max_stack;
481 setrlimit(RLIMIT_STACK, &limit);
484 /* If basic initialization not done yet (e.g. we're called from a
485 constructor run before our constructor), do it now */
486 if (__pthread_initial_thread_bos == NULL) pthread_initialize();
487 /* Setup stack for thread manager */
488 __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
489 if (__pthread_manager_thread_bos == NULL) return -1;
490 __pthread_manager_thread_tos =
491 __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;
492 /* Setup pipe to communicate with thread manager */
493 if (pipe(manager_pipe) == -1) {
494 free(__pthread_manager_thread_bos);
497 /* Start the thread manager */
499 if (__builtin_expect (__pthread_initial_thread.p_report_events, 0))
501 /* It's a bit more complicated. We have to report the creation of
502 the manager thread. */
503 int idx = __td_eventword (TD_CREATE);
504 uint32_t mask = __td_eventmask (TD_CREATE);
506 if ((mask & (__pthread_threads_events.event_bits[idx]
507 | __pthread_initial_thread.p_eventbuf.eventmask.event_bits[idx]))
510 __pthread_lock(__pthread_manager_thread.p_lock, NULL);
512 #ifdef NEED_SEPARATE_REGISTER_STACK
513 pid = __clone2(__pthread_manager_event,
514 (void **) __pthread_manager_thread_bos,
515 THREAD_MANAGER_STACK_SIZE,
516 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
517 (void *)(long)manager_pipe[0]);
519 pid = __clone(__pthread_manager_event,
520 (void **) __pthread_manager_thread_tos,
521 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
522 (void *)(long)manager_pipe[0]);
527 /* Now fill in the information about the new thread in
528 the newly created thread's data structure. We cannot let
529 the new thread do this since we don't know whether it was
530 already scheduled when we send the event. */
531 __pthread_manager_thread.p_eventbuf.eventdata =
532 &__pthread_manager_thread;
533 __pthread_manager_thread.p_eventbuf.eventnum = TD_CREATE;
534 __pthread_last_event = &__pthread_manager_thread;
535 __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
536 __pthread_manager_thread.p_pid = pid;
538 /* Now call the function which signals the event. */
539 __linuxthreads_create_event ();
542 /* Now restart the thread. */
543 __pthread_unlock(__pthread_manager_thread.p_lock);
547 if (__builtin_expect (pid, 0) == 0)
549 #ifdef NEED_SEPARATE_REGISTER_STACK
550 pid = __clone2(__pthread_manager, (void **) __pthread_manager_thread_bos,
551 THREAD_MANAGER_STACK_SIZE,
552 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
553 (void *)(long)manager_pipe[0]);
555 pid = __clone(__pthread_manager, (void **) __pthread_manager_thread_tos,
556 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
557 (void *)(long)manager_pipe[0]);
560 if (__builtin_expect (pid, 0) == -1) {
561 free(__pthread_manager_thread_bos);
562 __libc_close(manager_pipe[0]);
563 __libc_close(manager_pipe[1]);
566 __pthread_manager_request = manager_pipe[1]; /* writing end */
567 __pthread_manager_reader = manager_pipe[0]; /* reading end */
568 __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
569 __pthread_manager_thread.p_pid = pid;
570 /* Make gdb aware of new thread manager */
571 if (__builtin_expect (__pthread_threads_debug, 0) && __pthread_sig_debug > 0)
573 raise(__pthread_sig_debug);
574 /* We suspend ourself and gdb will wake us up when it is
575 ready to handle us. */
576 __pthread_wait_for_restart_signal(thread_self());
578 /* Synchronize debugging of the thread manager */
579 request.req_kind = REQ_DEBUG;
580 __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
584 /* Thread creation */
586 int __pthread_create_2_1(pthread_t *thread, const pthread_attr_t *attr,
587 void * (*start_routine)(void *), void *arg)
589 pthread_descr self = thread_self();
590 struct pthread_request request;
592 if (__builtin_expect (__pthread_manager_request, 0) < 0) {
593 if (__pthread_initialize_manager() < 0) return EAGAIN;
595 request.req_thread = self;
596 request.req_kind = REQ_CREATE;
597 request.req_args.create.attr = attr;
598 request.req_args.create.fn = start_routine;
599 request.req_args.create.arg = arg;
600 sigprocmask(SIG_SETMASK, (const sigset_t *) NULL,
601 &request.req_args.create.mask);
602 __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
604 retval = THREAD_GETMEM(self, p_retcode);
605 if (__builtin_expect (retval, 0) == 0)
606 *thread = (pthread_t) THREAD_GETMEM(self, p_retval);
610 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
612 #if SHLIB_COMPAT (libpthread, GLIBC_2_0, GLIBC_2_1)
614 int __pthread_create_2_0(pthread_t *thread, const pthread_attr_t *attr,
615 void * (*start_routine)(void *), void *arg)
617 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
618 the old size and access to the new members might crash the program.
619 We convert the struct now. */
620 pthread_attr_t new_attr;
624 size_t ps = __getpagesize ();
626 memcpy (&new_attr, attr,
627 (size_t) &(((pthread_attr_t*)NULL)->__guardsize));
628 new_attr.__guardsize = ps;
629 new_attr.__stackaddr_set = 0;
630 new_attr.__stackaddr = NULL;
631 new_attr.__stacksize = STACK_SIZE - ps;
634 return __pthread_create_2_1 (thread, attr, start_routine, arg);
636 compat_symbol (libpthread, __pthread_create_2_0, pthread_create, GLIBC_2_0);
639 /* Simple operations on thread identifiers */
641 pthread_t pthread_self(void)
643 pthread_descr self = thread_self();
644 return THREAD_GETMEM(self, p_tid);
647 int pthread_equal(pthread_t thread1, pthread_t thread2)
649 return thread1 == thread2;
652 /* Helper function for thread_self in the case of user-provided stacks */
656 pthread_descr __pthread_find_self()
658 char * sp = CURRENT_STACK_FRAME;
661 /* __pthread_handles[0] is the initial thread, __pthread_handles[1] is
662 the manager threads handled specially in thread_self(), so start at 2 */
663 h = __pthread_handles + 2;
664 while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;
670 /* Thread scheduling */
672 int pthread_setschedparam(pthread_t thread, int policy,
673 const struct sched_param *param)
675 pthread_handle handle = thread_handle(thread);
678 __pthread_lock(&handle->h_lock, NULL);
679 if (__builtin_expect (invalid_handle(handle, thread), 0)) {
680 __pthread_unlock(&handle->h_lock);
683 th = handle->h_descr;
684 if (__builtin_expect (__sched_setscheduler(th->p_pid, policy, param) == -1,
686 __pthread_unlock(&handle->h_lock);
689 th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
690 __pthread_unlock(&handle->h_lock);
691 if (__pthread_manager_request >= 0)
692 __pthread_manager_adjust_prio(th->p_priority);
696 int pthread_getschedparam(pthread_t thread, int *policy,
697 struct sched_param *param)
699 pthread_handle handle = thread_handle(thread);
702 __pthread_lock(&handle->h_lock, NULL);
703 if (__builtin_expect (invalid_handle(handle, thread), 0)) {
704 __pthread_unlock(&handle->h_lock);
707 pid = handle->h_descr->p_pid;
708 __pthread_unlock(&handle->h_lock);
709 pol = __sched_getscheduler(pid);
710 if (__builtin_expect (pol, 0) == -1) return errno;
711 if (__sched_getparam(pid, param) == -1) return errno;
716 int __pthread_yield ()
718 /* For now this is equivalent with the POSIX call. */
719 return sched_yield ();
721 weak_alias (__pthread_yield, pthread_yield)
723 /* Process-wide exit() request */
725 static void pthread_exit_process(int retcode, void *arg)
727 struct pthread_request request;
728 pthread_descr self = thread_self();
730 if (__builtin_expect (__pthread_manager_request, 0) >= 0) {
731 request.req_thread = self;
732 request.req_kind = REQ_PROCESS_EXIT;
733 request.req_args.exit.code = retcode;
734 __libc_write(__pthread_manager_request,
735 (char *) &request, sizeof(request));
737 /* Main thread should accumulate times for thread manager and its
738 children, so that timings for main thread account for all threads. */
739 if (self == __pthread_main_thread)
740 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
744 /* The handler for the RESTART signal just records the signal received
745 in the thread descriptor, and optionally performs a siglongjmp
746 (for pthread_cond_timedwait). */
748 static void pthread_handle_sigrestart(int sig)
750 pthread_descr self = thread_self();
751 THREAD_SETMEM(self, p_signal, sig);
752 if (THREAD_GETMEM(self, p_signal_jmp) != NULL)
753 siglongjmp(*THREAD_GETMEM(self, p_signal_jmp), 1);
756 /* The handler for the CANCEL signal checks for cancellation
757 (in asynchronous mode), for process-wide exit and exec requests.
758 For the thread manager thread, redirect the signal to
759 __pthread_manager_sighandler. */
761 static void pthread_handle_sigcancel(int sig)
763 pthread_descr self = thread_self();
766 if (self == &__pthread_manager_thread)
768 __pthread_manager_sighandler(sig);
771 if (__builtin_expect (__pthread_exit_requested, 0)) {
772 /* Main thread should accumulate times for thread manager and its
773 children, so that timings for main thread account for all threads. */
774 if (self == __pthread_main_thread)
775 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
776 _exit(__pthread_exit_code);
778 if (__builtin_expect (THREAD_GETMEM(self, p_canceled), 0)
779 && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
780 if (THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
781 pthread_exit(PTHREAD_CANCELED);
782 jmpbuf = THREAD_GETMEM(self, p_cancel_jmp);
783 if (jmpbuf != NULL) {
784 THREAD_SETMEM(self, p_cancel_jmp, NULL);
785 siglongjmp(*jmpbuf, 1);
790 /* Handler for the DEBUG signal.
791 The debugging strategy is as follows:
792 On reception of a REQ_DEBUG request (sent by new threads created to
793 the thread manager under debugging mode), the thread manager throws
794 __pthread_sig_debug to itself. The debugger (if active) intercepts
795 this signal, takes into account new threads and continue execution
796 of the thread manager by propagating the signal because it doesn't
797 know what it is specifically done for. In the current implementation,
798 the thread manager simply discards it. */
800 static void pthread_handle_sigdebug(int sig)
805 /* Reset the state of the thread machinery after a fork().
806 Close the pipe used for requests and set the main thread to the forked
808 Notice that we can't free the stack segments, as the forked thread
809 may hold pointers into them. */
811 void __pthread_reset_main_thread()
813 pthread_descr self = thread_self();
816 if (__pthread_manager_request != -1) {
817 /* Free the thread manager stack */
818 free(__pthread_manager_thread_bos);
819 __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
820 /* Close the two ends of the pipe */
821 __libc_close(__pthread_manager_request);
822 __libc_close(__pthread_manager_reader);
823 __pthread_manager_request = __pthread_manager_reader = -1;
826 /* Update the pid of the main thread */
827 THREAD_SETMEM(self, p_pid, __getpid());
828 /* Make the forked thread the main thread */
829 __pthread_main_thread = self;
830 THREAD_SETMEM(self, p_nextlive, self);
831 THREAD_SETMEM(self, p_prevlive, self);
832 /* Now this thread modifies the global variables. */
833 THREAD_SETMEM(self, p_errnop, &_errno);
834 THREAD_SETMEM(self, p_h_errnop, &_h_errno);
835 THREAD_SETMEM(self, p_resp, &_res);
837 if (getrlimit (RLIMIT_STACK, &limit) == 0
838 && limit.rlim_cur != limit.rlim_max) {
839 limit.rlim_cur = limit.rlim_max;
840 setrlimit (STACK_SIZE, &limit);
844 /* Process-wide exec() request */
846 void __pthread_kill_other_threads_np(void)
849 /* Terminate all other threads and thread manager */
850 pthread_exit_process(0, NULL);
851 /* Make current thread the main thread in case the calling thread
852 changes its mind, does not exec(), and creates new threads instead. */
853 __pthread_reset_main_thread();
855 /* Reset the signal handlers behaviour for the signals the
856 implementation uses since this would be passed to the new
858 sigemptyset(&sa.sa_mask);
860 sa.sa_handler = SIG_DFL;
861 __libc_sigaction(__pthread_sig_restart, &sa, NULL);
862 __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
863 if (__pthread_sig_debug > 0)
864 __libc_sigaction(__pthread_sig_debug, &sa, NULL);
866 weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
868 /* Concurrency symbol level. */
869 static int current_level;
871 int __pthread_setconcurrency(int level)
873 /* We don't do anything unless we have found a useful interpretation. */
874 current_level = level;
877 weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
879 int __pthread_getconcurrency(void)
881 return current_level;
883 weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
885 /* Primitives for controlling thread execution */
887 void __pthread_wait_for_restart_signal(pthread_descr self)
891 sigprocmask(SIG_SETMASK, NULL, &mask); /* Get current signal mask */
892 sigdelset(&mask, __pthread_sig_restart); /* Unblock the restart signal */
893 THREAD_SETMEM(self, p_signal, 0);
895 sigsuspend(&mask); /* Wait for signal */
896 } while (THREAD_GETMEM(self, p_signal) !=__pthread_sig_restart);
899 #if !__ASSUME_REALTIME_SIGNALS
900 /* The _old variants are for 2.0 and early 2.1 kernels which don't have RT
902 On these kernels, we use SIGUSR1 and SIGUSR2 for restart and cancellation.
903 Since the restart signal does not queue, we use an atomic counter to create
904 queuing semantics. This is needed to resolve a rare race condition in
905 pthread_cond_timedwait_relative. */
907 void __pthread_restart_old(pthread_descr th)
909 if (atomic_increment(&th->p_resume_count) == -1)
910 kill(th->p_pid, __pthread_sig_restart);
913 void __pthread_suspend_old(pthread_descr self)
915 if (atomic_decrement(&self->p_resume_count) <= 0)
916 __pthread_wait_for_restart_signal(self);
920 __pthread_timedsuspend_old(pthread_descr self, const struct timespec *abstime)
922 sigset_t unblock, initial_mask;
923 int was_signalled = 0;
926 if (atomic_decrement(&self->p_resume_count) == 0) {
927 /* Set up a longjmp handler for the restart signal, unblock
928 the signal and sleep. */
930 if (sigsetjmp(jmpbuf, 1) == 0) {
931 THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
932 THREAD_SETMEM(self, p_signal, 0);
933 /* Unblock the restart signal */
934 sigemptyset(&unblock);
935 sigaddset(&unblock, __pthread_sig_restart);
936 sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
940 struct timespec reltime;
942 /* Compute a time offset relative to now. */
943 __gettimeofday (&now, NULL);
944 reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
945 reltime.tv_sec = abstime->tv_sec - now.tv_sec;
946 if (reltime.tv_nsec < 0) {
947 reltime.tv_nsec += 1000000000;
951 /* Sleep for the required duration. If woken by a signal,
952 resume waiting as required by Single Unix Specification. */
953 if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
957 /* Block the restart signal again */
958 sigprocmask(SIG_SETMASK, &initial_mask, NULL);
963 THREAD_SETMEM(self, p_signal_jmp, NULL);
966 /* Now was_signalled is true if we exited the above code
967 due to the delivery of a restart signal. In that case,
968 we know we have been dequeued and resumed and that the
969 resume count is balanced. Otherwise, there are some
970 cases to consider. First, try to bump up the resume count
971 back to zero. If it goes to 1, it means restart() was
972 invoked on this thread. The signal must be consumed
973 and the count bumped down and everything is cool. We
974 can return a 1 to the caller.
975 Otherwise, no restart was delivered yet, so a potential
976 race exists; we return a 0 to the caller which must deal
977 with this race in an appropriate way; for example by
978 atomically removing the thread from consideration for a
979 wakeup---if such a thing fails, it means a restart is
982 if (!was_signalled) {
983 if (atomic_increment(&self->p_resume_count) != -1) {
984 __pthread_wait_for_restart_signal(self);
985 atomic_decrement(&self->p_resume_count); /* should be zero now! */
986 /* woke spontaneously and consumed restart signal */
989 /* woke spontaneously but did not consume restart---caller must resolve */
992 /* woken due to restart signal */
995 #endif /* __ASSUME_REALTIME_SIGNALS */
997 void __pthread_restart_new(pthread_descr th)
999 kill(th->p_pid, __pthread_sig_restart);
1002 /* There is no __pthread_suspend_new because it would just
1003 be a wasteful wrapper for __pthread_wait_for_restart_signal */
1006 __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime)
1008 sigset_t unblock, initial_mask;
1009 int was_signalled = 0;
1012 if (sigsetjmp(jmpbuf, 1) == 0) {
1013 THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
1014 THREAD_SETMEM(self, p_signal, 0);
1015 /* Unblock the restart signal */
1016 sigemptyset(&unblock);
1017 sigaddset(&unblock, __pthread_sig_restart);
1018 sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
1022 struct timespec reltime;
1024 /* Compute a time offset relative to now. */
1025 __gettimeofday (&now, NULL);
1026 reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
1027 reltime.tv_sec = abstime->tv_sec - now.tv_sec;
1028 if (reltime.tv_nsec < 0) {
1029 reltime.tv_nsec += 1000000000;
1030 reltime.tv_sec -= 1;
1033 /* Sleep for the required duration. If woken by a signal,
1034 resume waiting as required by Single Unix Specification. */
1035 if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
1039 /* Block the restart signal again */
1040 sigprocmask(SIG_SETMASK, &initial_mask, NULL);
1045 THREAD_SETMEM(self, p_signal_jmp, NULL);
1047 /* Now was_signalled is true if we exited the above code
1048 due to the delivery of a restart signal. In that case,
1049 everything is cool. We have been removed from whatever
1050 we were waiting on by the other thread, and consumed its signal.
1052 Otherwise we this thread woke up spontaneously, or due to a signal other
1053 than restart. This is an ambiguous case that must be resolved by
1054 the caller; the thread is still eligible for a restart wakeup
1055 so there is a race. */
1057 return was_signalled;
1066 void __pthread_message(char * fmt, ...)
1070 sprintf(buffer, "%05d : ", __getpid());
1071 va_start(args, fmt);
1072 vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
1074 __libc_write(2, buffer, strlen(buffer));
1081 /* We need a hook to force the cancelation wrappers to be linked in when
1082 static libpthread is used. */
1083 extern const int __pthread_provide_wrappers;
1084 static const int *const __pthread_require_wrappers =
1085 &__pthread_provide_wrappers;