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 */
20 #include <netdb.h> /* for h_errno */
28 #include <sys/resource.h>
30 #include "internals.h"
33 #include "debug.h" /* added to linuxthreads -StS */
36 /* Mods for uClibc: Some includes */
38 #include <sys/types.h>
39 #include <sys/syscall.h>
41 /* mods for uClibc: __libc_sigaction is not in any standard headers */
42 extern __typeof(sigaction) __libc_sigaction;
43 libpthread_hidden_proto(waitpid)
44 libpthread_hidden_proto(raise)
46 /* These variables are used by the setup code. */
51 /* Descriptor of the initial thread */
53 struct _pthread_descr_struct __pthread_initial_thread = {
54 &__pthread_initial_thread, /* pthread_descr p_nextlive */
55 &__pthread_initial_thread, /* pthread_descr p_prevlive */
56 NULL, /* pthread_descr p_nextwaiting */
57 NULL, /* pthread_descr p_nextlock */
58 PTHREAD_THREADS_MAX, /* pthread_t p_tid */
60 0, /* int p_priority */
61 &__pthread_handles[0].h_lock, /* struct _pthread_fastlock * p_lock */
63 NULL, /* sigjmp_buf * p_signal_buf */
64 NULL, /* sigjmp_buf * p_cancel_buf */
65 0, /* char p_terminated */
66 0, /* char p_detached */
67 0, /* char p_exited */
68 NULL, /* void * p_retval */
70 NULL, /* pthread_descr p_joining */
71 NULL, /* struct _pthread_cleanup_buffer * p_cleanup */
72 0, /* char p_cancelstate */
73 0, /* char p_canceltype */
74 0, /* char p_canceled */
75 &_errno, /* int *p_errnop */
77 &_h_errno, /* int *p_h_errnop */
78 0, /* int p_h_errno */
79 NULL, /* char * p_in_sighandler */
80 0, /* char p_sigwaiting */
81 PTHREAD_START_ARGS_INITIALIZER, /* struct pthread_start_args p_start_args */
82 {NULL}, /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
83 {NULL}, /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
84 0, /* int p_userstack */
85 NULL, /* void * p_guardaddr */
86 0, /* size_t p_guardsize */
87 &__pthread_initial_thread, /* pthread_descr p_self */
88 0, /* Always index 0 */
89 0, /* int p_report_events */
90 {{{0, }}, 0, NULL}, /* td_eventbuf_t p_eventbuf */
91 __ATOMIC_INITIALIZER, /* struct pthread_atomic p_resume_count */
92 0, /* char p_woken_by_cancel */
93 0, /* char p_condvar_avail */
94 0, /* char p_sem_avail */
95 NULL, /* struct pthread_extricate_if *p_extricate */
96 NULL, /* pthread_readlock_info *p_readlock_list; */
97 NULL, /* pthread_readlock_info *p_readlock_free; */
98 0 /* int p_untracked_readlock_count; */
99 #ifdef __UCLIBC_HAS_XLOCALE__
101 &__global_locale_data, /* __locale_t locale; */
102 #endif /* __UCLIBC_HAS_XLOCALE__ */
105 /* Descriptor of the manager thread; none of this is used but the error
106 variables, the p_pid and p_priority fields,
107 and the address for identification. */
108 #define manager_thread (&__pthread_manager_thread)
109 struct _pthread_descr_struct __pthread_manager_thread = {
110 NULL, /* pthread_descr p_nextlive */
111 NULL, /* pthread_descr p_prevlive */
112 NULL, /* pthread_descr p_nextwaiting */
113 NULL, /* pthread_descr p_nextlock */
116 0, /* int p_priority */
117 &__pthread_handles[1].h_lock, /* struct _pthread_fastlock * p_lock */
118 0, /* int p_signal */
119 NULL, /* sigjmp_buf * p_signal_buf */
120 NULL, /* sigjmp_buf * p_cancel_buf */
121 0, /* char p_terminated */
122 0, /* char p_detached */
123 0, /* char p_exited */
124 NULL, /* void * p_retval */
125 0, /* int p_retval */
126 NULL, /* pthread_descr p_joining */
127 NULL, /* struct _pthread_cleanup_buffer * p_cleanup */
128 0, /* char p_cancelstate */
129 0, /* char p_canceltype */
130 0, /* char p_canceled */
131 &__pthread_manager_thread.p_errno, /* int *p_errnop */
133 NULL, /* int *p_h_errnop */
134 0, /* int p_h_errno */
135 NULL, /* char * p_in_sighandler */
136 0, /* char p_sigwaiting */
137 PTHREAD_START_ARGS_INITIALIZER, /* struct pthread_start_args p_start_args */
138 {NULL}, /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
139 {NULL}, /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
140 0, /* int p_userstack */
141 NULL, /* void * p_guardaddr */
142 0, /* size_t p_guardsize */
143 &__pthread_manager_thread, /* pthread_descr p_self */
144 1, /* Always index 1 */
145 0, /* int p_report_events */
146 {{{0, }}, 0, NULL}, /* td_eventbuf_t p_eventbuf */
147 __ATOMIC_INITIALIZER, /* struct pthread_atomic p_resume_count */
148 0, /* char p_woken_by_cancel */
149 0, /* char p_condvar_avail */
150 0, /* char p_sem_avail */
151 NULL, /* struct pthread_extricate_if *p_extricate */
152 NULL, /* pthread_readlock_info *p_readlock_list; */
153 NULL, /* pthread_readlock_info *p_readlock_free; */
154 0 /* int p_untracked_readlock_count; */
155 #ifdef __UCLIBC_HAS_XLOCALE__
157 &__global_locale_data, /* __locale_t locale; */
158 #endif /* __UCLIBC_HAS_XLOCALE__ */
161 /* Pointer to the main thread (the father of the thread manager thread) */
162 /* Originally, this is the initial thread, but this changes after fork() */
164 pthread_descr __pthread_main_thread = &__pthread_initial_thread;
166 /* Limit between the stack of the initial thread (above) and the
167 stacks of other threads (below). Aligned on a STACK_SIZE boundary. */
169 char *__pthread_initial_thread_bos = NULL;
171 /* For non-MMU systems also remember to stack top of the initial thread.
172 * This is adapted when other stacks are malloc'ed since we don't know
173 * the bounds a-priori. -StS */
175 #ifndef __ARCH_HAS_MMU__
176 char *__pthread_initial_thread_tos = NULL;
177 #endif /* __ARCH_HAS_MMU__ */
179 /* File descriptor for sending requests to the thread manager. */
180 /* Initially -1, meaning that the thread manager is not running. */
182 int __pthread_manager_request = -1;
184 /* Other end of the pipe for sending requests to the thread manager. */
186 int __pthread_manager_reader;
188 /* Limits of the thread manager stack */
190 char *__pthread_manager_thread_bos = NULL;
191 char *__pthread_manager_thread_tos = NULL;
193 /* For process-wide exit() */
195 int __pthread_exit_requested = 0;
196 int __pthread_exit_code = 0;
198 /* Communicate relevant LinuxThreads constants to gdb */
200 const int __pthread_threads_max = PTHREAD_THREADS_MAX;
201 const int __pthread_sizeof_handle = sizeof(struct pthread_handle_struct);
202 const int __pthread_offsetof_descr = offsetof(struct pthread_handle_struct, h_descr);
203 const int __pthread_offsetof_pid = offsetof(struct _pthread_descr_struct,
205 const int __linuxthreads_pthread_sizeof_descr
206 = sizeof(struct _pthread_descr_struct);
208 const int __linuxthreads_initial_report_events;
210 const char __linuxthreads_version[] = VERSION;
212 /* Forward declarations */
213 static void pthread_onexit_process(int retcode, void *arg);
214 static void pthread_handle_sigcancel(int sig);
215 static void pthread_handle_sigrestart(int sig);
216 static void pthread_handle_sigdebug(int sig);
217 int __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime);
219 /* Signal numbers used for the communication.
220 In these variables we keep track of the used variables. If the
221 platform does not support any real-time signals we will define the
222 values to some unreasonable value which will signal failing of all
223 the functions below. */
224 #ifndef __NR_rt_sigaction
225 static int current_rtmin = -1;
226 static int current_rtmax = -1;
227 int __pthread_sig_restart = SIGUSR1;
228 int __pthread_sig_cancel = SIGUSR2;
229 int __pthread_sig_debug;
232 #if __SIGRTMAX - __SIGRTMIN >= 3
233 static int current_rtmin = __SIGRTMIN + 3;
234 static int current_rtmax = __SIGRTMAX;
235 int __pthread_sig_restart = __SIGRTMIN;
236 int __pthread_sig_cancel = __SIGRTMIN + 1;
237 int __pthread_sig_debug = __SIGRTMIN + 2;
238 void (*__pthread_restart)(pthread_descr) = __pthread_restart_new;
239 void (*__pthread_suspend)(pthread_descr) = __pthread_wait_for_restart_signal;
240 int (*__pthread_timedsuspend)(pthread_descr, const struct timespec *) = __pthread_timedsuspend_new;
242 static int current_rtmin = __SIGRTMIN;
243 static int current_rtmax = __SIGRTMAX;
244 int __pthread_sig_restart = SIGUSR1;
245 int __pthread_sig_cancel = SIGUSR2;
246 int __pthread_sig_debug;
247 void (*__pthread_restart)(pthread_descr) = __pthread_restart_old;
248 void (*__pthread_suspend)(pthread_descr) = __pthread_suspend_old;
249 int (*__pthread_timedsuspend)(pthread_descr, const struct timespec *) = __pthread_timedsuspend_old;
253 /* Return number of available real-time signal with highest priority. */
254 int __libc_current_sigrtmin (void)
256 return current_rtmin;
259 /* Return number of available real-time signal with lowest priority. */
260 int __libc_current_sigrtmax (void)
262 return current_rtmax;
265 /* Allocate real-time signal with highest/lowest available
266 priority. Please note that we don't use a lock since we assume
267 this function to be called at program start. */
268 int __libc_allocate_rtsig (int high);
269 int __libc_allocate_rtsig (int high)
271 if (current_rtmin == -1 || current_rtmin > current_rtmax)
272 /* We don't have anymore signal available. */
274 return high ? current_rtmin++ : current_rtmax--;
278 /* Initialize the pthread library.
279 Initialization is split in two functions:
280 - a constructor function that blocks the __pthread_sig_restart signal
281 (must do this very early, since the program could capture the signal
282 mask with e.g. sigsetjmp before creating the first thread);
283 - a regular function called from pthread_create when needed. */
285 static void pthread_initialize(void) __attribute__((constructor));
287 struct pthread_functions __pthread_functions =
289 #if !(USE_TLS && HAVE___THREAD)
290 .ptr_pthread_internal_tsd_set = __pthread_internal_tsd_set,
291 .ptr_pthread_internal_tsd_get = __pthread_internal_tsd_get,
292 .ptr_pthread_internal_tsd_address = __pthread_internal_tsd_address,
295 .ptr_pthread_fork = __pthread_fork,
297 .ptr_pthread_attr_destroy = pthread_attr_destroy,
298 .ptr_pthread_attr_init = pthread_attr_init,
299 .ptr_pthread_attr_getdetachstate = pthread_attr_getdetachstate,
300 .ptr_pthread_attr_setdetachstate = pthread_attr_setdetachstate,
301 .ptr_pthread_attr_getinheritsched = pthread_attr_getinheritsched,
302 .ptr_pthread_attr_setinheritsched = pthread_attr_setinheritsched,
303 .ptr_pthread_attr_getschedparam = pthread_attr_getschedparam,
304 .ptr_pthread_attr_setschedparam = pthread_attr_setschedparam,
305 .ptr_pthread_attr_getschedpolicy = pthread_attr_getschedpolicy,
306 .ptr_pthread_attr_setschedpolicy = pthread_attr_setschedpolicy,
307 .ptr_pthread_attr_getscope = pthread_attr_getscope,
308 .ptr_pthread_attr_setscope = pthread_attr_setscope,
309 .ptr_pthread_condattr_destroy = pthread_condattr_destroy,
310 .ptr_pthread_condattr_init = pthread_condattr_init,
311 .ptr_pthread_cond_broadcast = pthread_cond_broadcast,
312 .ptr_pthread_cond_destroy = pthread_cond_destroy,
313 .ptr_pthread_cond_init = pthread_cond_init,
314 .ptr_pthread_cond_signal = pthread_cond_signal,
315 .ptr_pthread_cond_wait = pthread_cond_wait,
316 .ptr_pthread_cond_timedwait = pthread_cond_timedwait,
317 .ptr_pthread_equal = pthread_equal,
318 .ptr___pthread_exit = pthread_exit,
319 .ptr_pthread_getschedparam = pthread_getschedparam,
320 .ptr_pthread_setschedparam = pthread_setschedparam,
321 .ptr_pthread_mutex_destroy = __pthread_mutex_destroy,
322 .ptr_pthread_mutex_init = __pthread_mutex_init,
323 .ptr_pthread_mutex_lock = __pthread_mutex_lock,
324 .ptr_pthread_mutex_trylock = __pthread_mutex_trylock,
325 .ptr_pthread_mutex_unlock = __pthread_mutex_unlock,
326 .ptr_pthread_self = pthread_self,
327 .ptr_pthread_setcancelstate = pthread_setcancelstate,
328 .ptr_pthread_setcanceltype = pthread_setcanceltype,
330 .ptr_pthread_do_exit = pthread_do_exit,
331 .ptr_pthread_thread_self = pthread_thread_self,
332 .ptr_pthread_cleanup_upto = pthread_cleanup_upto,
333 .ptr_pthread_sigaction = pthread_sigaction,
334 .ptr_pthread_sigwait = pthread_sigwait,
335 .ptr_pthread_raise = pthread_raise,
336 .ptr__pthread_cleanup_push = _pthread_cleanup_push,
337 .ptr__pthread_cleanup_pop = _pthread_cleanup_pop
341 # define ptr_pthread_functions &__pthread_functions
343 # define ptr_pthread_functions NULL
346 static int *__libc_multiple_threads_ptr;
348 /* Do some minimal initialization which has to be done during the
349 startup of the C library. */
350 void __pthread_initialize_minimal(void)
352 /* If we have special thread_self processing, initialize
353 * that for the main thread now. */
354 #ifdef INIT_THREAD_SELF
355 INIT_THREAD_SELF(&__pthread_initial_thread, 0);
358 __libc_multiple_threads_ptr = __libc_pthread_init (ptr_pthread_functions);
362 static void pthread_initialize(void)
366 #ifdef __ARCH_HAS_MMU__
371 /* If already done (e.g. by a constructor called earlier!), bail out */
372 if (__pthread_initial_thread_bos != NULL) return;
373 #ifdef TEST_FOR_COMPARE_AND_SWAP
374 /* Test if compare-and-swap is available */
375 __pthread_has_cas = compare_and_swap_is_available();
377 /* For the initial stack, reserve at least STACK_SIZE bytes of stack
378 below the current stack address, and align that on a
379 STACK_SIZE boundary. */
380 __pthread_initial_thread_bos =
381 (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
382 /* Update the descriptor for the initial thread. */
383 __pthread_initial_thread.p_pid = getpid();
384 /* If we have special thread_self processing, initialize that for the
386 #ifdef INIT_THREAD_SELF
387 INIT_THREAD_SELF(&__pthread_initial_thread, 0);
389 /* The errno/h_errno variable of the main thread are the global ones. */
390 __pthread_initial_thread.p_errnop = &_errno;
391 __pthread_initial_thread.p_h_errnop = &_h_errno;
393 #ifdef __UCLIBC_HAS_XLOCALE__
394 /* The locale of the main thread is the current locale in use. */
395 __pthread_initial_thread.locale = __curlocale_var;
396 #endif /* __UCLIBC_HAS_XLOCALE__ */
398 { /* uClibc-specific stdio initialization for threads. */
401 _stdio_user_locking = 0; /* 2 if threading not initialized */
402 for (fp = _stdio_openlist; fp != NULL; fp = fp->__nextopen) {
403 if (fp->__user_locking != 1) {
404 fp->__user_locking = 0;
409 /* Play with the stack size limit to make sure that no stack ever grows
410 beyond STACK_SIZE minus two pages (one page for the thread descriptor
411 immediately beyond, and one page to act as a guard page). */
413 #ifdef __ARCH_HAS_MMU__
414 /* We cannot allocate a huge chunk of memory to mmap all thread stacks later
415 * on a non-MMU system. Thus, we don't need the rlimit either. -StS */
416 getrlimit(RLIMIT_STACK, &limit);
417 max_stack = STACK_SIZE - 2 * getpagesize();
418 if (limit.rlim_cur > max_stack) {
419 limit.rlim_cur = max_stack;
420 setrlimit(RLIMIT_STACK, &limit);
423 /* For non-MMU assume __pthread_initial_thread_tos at upper page boundary, and
424 * __pthread_initial_thread_bos at address 0. These bounds are refined as we
425 * malloc other stack frames such that they don't overlap. -StS
427 __pthread_initial_thread_tos =
428 (char *)(((long)CURRENT_STACK_FRAME + getpagesize()) & ~(getpagesize() - 1));
429 __pthread_initial_thread_bos = (char *) 1; /* set it non-zero so we know we have been here */
430 PDEBUG("initial thread stack bounds: bos=%p, tos=%p\n",
431 __pthread_initial_thread_bos, __pthread_initial_thread_tos);
432 #endif /* __ARCH_HAS_MMU__ */
434 /* Setup signal handlers for the initial thread.
435 Since signal handlers are shared between threads, these settings
436 will be inherited by all other threads. */
437 sa.sa_handler = pthread_handle_sigrestart;
438 sigemptyset(&sa.sa_mask);
440 __libc_sigaction(__pthread_sig_restart, &sa, NULL);
441 sa.sa_handler = pthread_handle_sigcancel;
442 sigaddset(&sa.sa_mask, __pthread_sig_restart);
444 __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
445 if (__pthread_sig_debug > 0) {
446 sa.sa_handler = pthread_handle_sigdebug;
447 sigemptyset(&sa.sa_mask);
449 __libc_sigaction(__pthread_sig_debug, &sa, NULL);
451 /* Initially, block __pthread_sig_restart. Will be unblocked on demand. */
453 sigaddset(&mask, __pthread_sig_restart);
454 sigprocmask(SIG_BLOCK, &mask, NULL);
455 /* And unblock __pthread_sig_cancel if it has been blocked. */
456 sigdelset(&mask, __pthread_sig_restart);
457 sigaddset(&mask, __pthread_sig_cancel);
458 sigprocmask(SIG_UNBLOCK, &mask, NULL);
459 /* Register an exit function to kill all other threads. */
460 /* Do it early so that user-registered atexit functions are called
461 before pthread_onexit_process. */
462 on_exit(pthread_onexit_process, NULL);
465 void __pthread_initialize(void);
466 void __pthread_initialize(void)
468 pthread_initialize();
471 int __pthread_initialize_manager(void)
476 struct pthread_request request;
478 *__libc_multiple_threads_ptr = 1;
480 /* If basic initialization not done yet (e.g. we're called from a
481 constructor run before our constructor), do it now */
482 if (__pthread_initial_thread_bos == NULL) pthread_initialize();
483 /* Setup stack for thread manager */
484 __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
485 if (__pthread_manager_thread_bos == NULL) return -1;
486 __pthread_manager_thread_tos =
487 __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;
489 /* On non-MMU systems we make sure that the initial thread bounds don't overlap
490 * with the manager stack frame */
491 NOMMU_INITIAL_THREAD_BOUNDS(__pthread_manager_thread_tos,__pthread_manager_thread_bos);
492 PDEBUG("manager stack: size=%d, bos=%p, tos=%p\n", THREAD_MANAGER_STACK_SIZE,
493 __pthread_manager_thread_bos, __pthread_manager_thread_tos);
495 PDEBUG("initial stack: estimate bos=%p, tos=%p\n",
496 __pthread_initial_thread_bos, __pthread_initial_thread_tos);
499 /* Setup pipe to communicate with thread manager */
500 if (pipe(manager_pipe) == -1) {
501 free(__pthread_manager_thread_bos);
504 /* Start the thread manager */
507 if (__linuxthreads_initial_report_events != 0)
508 THREAD_SETMEM (((pthread_descr) NULL), p_report_events,
509 __linuxthreads_initial_report_events);
510 report_events = THREAD_GETMEM (((pthread_descr) NULL), p_report_events);
512 if (__linuxthreads_initial_report_events != 0)
513 __pthread_initial_thread.p_report_events
514 = __linuxthreads_initial_report_events;
515 report_events = __pthread_initial_thread.p_report_events;
517 if (__builtin_expect (report_events, 0))
519 /* It's a bit more complicated. We have to report the creation of
520 the manager thread. */
521 int idx = __td_eventword (TD_CREATE);
522 uint32_t mask = __td_eventmask (TD_CREATE);
524 if ((mask & (__pthread_threads_events.event_bits[idx]
525 | __pthread_initial_thread.p_eventbuf.eventmask.event_bits[idx]))
529 __pthread_lock(__pthread_manager_thread.p_lock, NULL);
531 pid = clone(__pthread_manager_event,
532 (void **) __pthread_manager_thread_tos,
533 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
534 (void *)(long)manager_pipe[0]);
538 /* Now fill in the information about the new thread in
539 the newly created thread's data structure. We cannot let
540 the new thread do this since we don't know whether it was
541 already scheduled when we send the event. */
542 __pthread_manager_thread.p_eventbuf.eventdata =
543 &__pthread_manager_thread;
544 __pthread_manager_thread.p_eventbuf.eventnum = TD_CREATE;
545 __pthread_last_event = &__pthread_manager_thread;
546 __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
547 __pthread_manager_thread.p_pid = pid;
549 /* Now call the function which signals the event. */
550 __linuxthreads_create_event ();
552 /* Now restart the thread. */
553 __pthread_unlock(__pthread_manager_thread.p_lock);
558 pid = clone(__pthread_manager, (void **) __pthread_manager_thread_tos,
559 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
560 (void *)(long)manager_pipe[0]);
563 free(__pthread_manager_thread_bos);
564 __libc_close(manager_pipe[0]);
565 __libc_close(manager_pipe[1]);
568 __pthread_manager_request = manager_pipe[1]; /* writing end */
569 __pthread_manager_reader = manager_pipe[0]; /* reading end */
570 __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
571 __pthread_manager_thread.p_pid = pid;
573 /* Make gdb aware of new thread manager */
574 if (__pthread_threads_debug && __pthread_sig_debug > 0)
576 raise(__pthread_sig_debug);
577 /* We suspend ourself and gdb will wake us up when it is
578 ready to handle us. */
579 __pthread_wait_for_restart_signal(thread_self());
581 /* Synchronize debugging of the thread manager */
582 PDEBUG("send REQ_DEBUG to manager thread\n");
583 request.req_kind = REQ_DEBUG;
584 TEMP_FAILURE_RETRY(__libc_write(__pthread_manager_request,
585 (char *) &request, sizeof(request)));
589 /* Thread creation */
591 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
592 void * (*start_routine)(void *), void *arg)
594 pthread_descr self = thread_self();
595 struct pthread_request request;
596 if (__pthread_manager_request < 0) {
597 if (__pthread_initialize_manager() < 0) return EAGAIN;
599 request.req_thread = self;
600 request.req_kind = REQ_CREATE;
601 request.req_args.create.attr = attr;
602 request.req_args.create.fn = start_routine;
603 request.req_args.create.arg = arg;
604 sigprocmask(SIG_SETMASK, (const sigset_t *) NULL,
605 &request.req_args.create.mask);
606 PDEBUG("write REQ_CREATE to manager thread\n");
607 TEMP_FAILURE_RETRY(__libc_write(__pthread_manager_request,
608 (char *) &request, sizeof(request)));
609 PDEBUG("before suspend(self)\n");
611 PDEBUG("after suspend(self)\n");
612 if (THREAD_GETMEM(self, p_retcode) == 0)
613 *thread = (pthread_t) THREAD_GETMEM(self, p_retval);
614 return THREAD_GETMEM(self, p_retcode);
617 /* Simple operations on thread identifiers */
619 pthread_t pthread_self(void)
621 pthread_descr self = thread_self();
622 return THREAD_GETMEM(self, p_tid);
625 int pthread_equal(pthread_t thread1, pthread_t thread2)
627 return thread1 == thread2;
630 /* Helper function for thread_self in the case of user-provided stacks */
634 pthread_descr __pthread_find_self()
636 char * sp = CURRENT_STACK_FRAME;
639 /* __pthread_handles[0] is the initial thread, __pthread_handles[1] is
640 the manager threads handled specially in thread_self(), so start at 2 */
641 h = __pthread_handles + 2;
642 while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;
645 if (h->h_descr == NULL) {
646 printf("*** %s ERROR descriptor is NULL!!!!! ***\n\n", __FUNCTION__);
655 static pthread_descr thread_self_stack(void)
657 char *sp = CURRENT_STACK_FRAME;
660 if (sp >= __pthread_manager_thread_bos && sp < __pthread_manager_thread_tos)
661 return manager_thread;
662 h = __pthread_handles + 2;
664 while (h->h_descr == NULL
665 || ! (sp <= (char *) h->h_descr->p_stackaddr && sp >= h->h_bottom))
668 while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom))
676 /* Thread scheduling */
678 int pthread_setschedparam(pthread_t thread, int policy,
679 const struct sched_param *param)
681 pthread_handle handle = thread_handle(thread);
684 __pthread_lock(&handle->h_lock, NULL);
685 if (invalid_handle(handle, thread)) {
686 __pthread_unlock(&handle->h_lock);
689 th = handle->h_descr;
690 if (sched_setscheduler(th->p_pid, policy, param) == -1) {
691 __pthread_unlock(&handle->h_lock);
694 th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
695 __pthread_unlock(&handle->h_lock);
696 if (__pthread_manager_request >= 0)
697 __pthread_manager_adjust_prio(th->p_priority);
701 int pthread_getschedparam(pthread_t thread, int *policy,
702 struct sched_param *param)
704 pthread_handle handle = thread_handle(thread);
707 __pthread_lock(&handle->h_lock, NULL);
708 if (invalid_handle(handle, thread)) {
709 __pthread_unlock(&handle->h_lock);
712 pid = handle->h_descr->p_pid;
713 __pthread_unlock(&handle->h_lock);
714 pol = sched_getscheduler(pid);
715 if (pol == -1) return errno;
716 if (sched_getparam(pid, param) == -1) return errno;
721 /* Process-wide exit() request */
723 static void pthread_onexit_process(int retcode, void *arg attribute_unused)
725 struct pthread_request request;
726 pthread_descr self = thread_self();
728 if (__pthread_manager_request >= 0) {
729 request.req_thread = self;
730 request.req_kind = REQ_PROCESS_EXIT;
731 request.req_args.exit.code = retcode;
732 TEMP_FAILURE_RETRY(__libc_write(__pthread_manager_request,
733 (char *) &request, sizeof(request)));
735 /* Main thread should accumulate times for thread manager and its
736 children, so that timings for main thread account for all threads. */
737 if (self == __pthread_main_thread) {
738 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
739 /* Since all threads have been asynchronously terminated
740 * (possibly holding locks), free cannot be used any more. */
741 __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
746 /* The handler for the RESTART signal just records the signal received
747 in the thread descriptor, and optionally performs a siglongjmp
748 (for pthread_cond_timedwait). */
750 static void pthread_handle_sigrestart(int sig)
752 pthread_descr self = thread_self();
753 THREAD_SETMEM(self, p_signal, sig);
754 if (THREAD_GETMEM(self, p_signal_jmp) != NULL)
755 siglongjmp(*THREAD_GETMEM(self, p_signal_jmp), 1);
758 /* The handler for the CANCEL signal checks for cancellation
759 (in asynchronous mode), for process-wide exit and exec requests.
760 For the thread manager thread, redirect the signal to
761 __pthread_manager_sighandler. */
763 static void pthread_handle_sigcancel(int sig)
765 pthread_descr self = thread_self();
769 if (self == &__pthread_manager_thread)
772 /* A new thread might get a cancel signal before it is fully
773 initialized, so that the thread register might still point to the
774 manager thread. Double check that this is really the manager
776 pthread_descr real_self = thread_self_stack();
777 if (real_self == &__pthread_manager_thread)
779 __pthread_manager_sighandler(sig);
782 /* Oops, thread_self() isn't working yet.. */
784 # ifdef INIT_THREAD_SELF
785 INIT_THREAD_SELF(self, self->p_nr);
788 __pthread_manager_sighandler(sig);
792 if (__builtin_expect (__pthread_exit_requested, 0)) {
793 /* Main thread should accumulate times for thread manager and its
794 children, so that timings for main thread account for all threads. */
795 if (self == __pthread_main_thread) {
797 waitpid(__pthread_manager_thread->p_pid, NULL, __WCLONE);
799 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
802 _exit(__pthread_exit_code);
804 if (__builtin_expect (THREAD_GETMEM(self, p_canceled), 0)
805 && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
806 if (THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
807 pthread_exit(PTHREAD_CANCELED);
808 jmpbuf = THREAD_GETMEM(self, p_cancel_jmp);
809 if (jmpbuf != NULL) {
810 THREAD_SETMEM(self, p_cancel_jmp, NULL);
811 siglongjmp(*jmpbuf, 1);
816 /* Handler for the DEBUG signal.
817 The debugging strategy is as follows:
818 On reception of a REQ_DEBUG request (sent by new threads created to
819 the thread manager under debugging mode), the thread manager throws
820 __pthread_sig_debug to itself. The debugger (if active) intercepts
821 this signal, takes into account new threads and continue execution
822 of the thread manager by propagating the signal because it doesn't
823 know what it is specifically done for. In the current implementation,
824 the thread manager simply discards it. */
826 static void pthread_handle_sigdebug(int sig attribute_unused)
831 /* Reset the state of the thread machinery after a fork().
832 Close the pipe used for requests and set the main thread to the forked
834 Notice that we can't free the stack segments, as the forked thread
835 may hold pointers into them. */
837 void __pthread_reset_main_thread()
839 pthread_descr self = thread_self();
841 if (__pthread_manager_request != -1) {
842 /* Free the thread manager stack */
843 free(__pthread_manager_thread_bos);
844 __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
845 /* Close the two ends of the pipe */
846 __libc_close(__pthread_manager_request);
847 __libc_close(__pthread_manager_reader);
848 __pthread_manager_request = __pthread_manager_reader = -1;
851 /* Update the pid of the main thread */
852 THREAD_SETMEM(self, p_pid, getpid());
853 /* Make the forked thread the main thread */
854 __pthread_main_thread = self;
855 THREAD_SETMEM(self, p_nextlive, self);
856 THREAD_SETMEM(self, p_prevlive, self);
857 /* Now this thread modifies the global variables. */
858 THREAD_SETMEM(self, p_errnop, &_errno);
859 THREAD_SETMEM(self, p_h_errnop, &_h_errno);
862 /* Process-wide exec() request */
864 void __pthread_kill_other_threads_np(void)
867 /* Terminate all other threads and thread manager */
868 pthread_onexit_process(0, NULL);
869 /* Make current thread the main thread in case the calling thread
870 changes its mind, does not exec(), and creates new threads instead. */
871 __pthread_reset_main_thread();
872 /* Reset the signal handlers behaviour for the signals the
873 implementation uses since this would be passed to the new
875 sigemptyset(&sa.sa_mask);
877 sa.sa_handler = SIG_DFL;
878 __libc_sigaction(__pthread_sig_restart, &sa, NULL);
879 __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
880 if (__pthread_sig_debug > 0)
881 __libc_sigaction(__pthread_sig_debug, &sa, NULL);
883 weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
885 /* Concurrency symbol level. */
886 static int current_level;
888 int __pthread_setconcurrency(int level)
890 /* We don't do anything unless we have found a useful interpretation. */
891 current_level = level;
894 weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
896 int __pthread_getconcurrency(void)
898 return current_level;
900 weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
903 /* Primitives for controlling thread execution */
905 void __pthread_wait_for_restart_signal(pthread_descr self)
909 sigprocmask(SIG_SETMASK, NULL, &mask); /* Get current signal mask */
910 sigdelset(&mask, __pthread_sig_restart); /* Unblock the restart signal */
911 THREAD_SETMEM(self, p_signal, 0);
913 sigsuspend(&mask); /* Wait for signal */
914 } while (THREAD_GETMEM(self, p_signal) !=__pthread_sig_restart);
916 READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
919 #ifndef __NR_rt_sigaction
920 /* The _old variants are for 2.0 and early 2.1 kernels which don't have RT
922 On these kernels, we use SIGUSR1 and SIGUSR2 for restart and cancellation.
923 Since the restart signal does not queue, we use an atomic counter to create
924 queuing semantics. This is needed to resolve a rare race condition in
925 pthread_cond_timedwait_relative. */
927 void __pthread_restart_old(pthread_descr th)
929 if (atomic_increment(&th->p_resume_count) == -1)
930 kill(th->p_pid, __pthread_sig_restart);
933 void __pthread_suspend_old(pthread_descr self)
935 if (atomic_decrement(&self->p_resume_count) <= 0)
936 __pthread_wait_for_restart_signal(self);
940 __pthread_timedsuspend_old(pthread_descr self, const struct timespec *abstime)
942 sigset_t unblock, initial_mask;
943 int was_signalled = 0;
946 if (atomic_decrement(&self->p_resume_count) == 0) {
947 /* Set up a longjmp handler for the restart signal, unblock
948 the signal and sleep. */
950 if (sigsetjmp(jmpbuf, 1) == 0) {
951 THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
952 THREAD_SETMEM(self, p_signal, 0);
953 /* Unblock the restart signal */
954 sigemptyset(&unblock);
955 sigaddset(&unblock, __pthread_sig_restart);
956 sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
960 struct timespec reltime;
962 /* Compute a time offset relative to now. */
963 gettimeofday (&now, NULL);
964 reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
965 reltime.tv_sec = abstime->tv_sec - now.tv_sec;
966 if (reltime.tv_nsec < 0) {
967 reltime.tv_nsec += 1000000000;
971 /* Sleep for the required duration. If woken by a signal,
972 resume waiting as required by Single Unix Specification. */
973 if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
977 /* Block the restart signal again */
978 sigprocmask(SIG_SETMASK, &initial_mask, NULL);
983 THREAD_SETMEM(self, p_signal_jmp, NULL);
986 /* Now was_signalled is true if we exited the above code
987 due to the delivery of a restart signal. In that case,
988 we know we have been dequeued and resumed and that the
989 resume count is balanced. Otherwise, there are some
990 cases to consider. First, try to bump up the resume count
991 back to zero. If it goes to 1, it means restart() was
992 invoked on this thread. The signal must be consumed
993 and the count bumped down and everything is cool. We
994 can return a 1 to the caller.
995 Otherwise, no restart was delivered yet, so a potential
996 race exists; we return a 0 to the caller which must deal
997 with this race in an appropriate way; for example by
998 atomically removing the thread from consideration for a
999 wakeup---if such a thing fails, it means a restart is
1002 if (!was_signalled) {
1003 if (atomic_increment(&self->p_resume_count) != -1) {
1004 __pthread_wait_for_restart_signal(self);
1005 atomic_decrement(&self->p_resume_count); /* should be zero now! */
1006 /* woke spontaneously and consumed restart signal */
1009 /* woke spontaneously but did not consume restart---caller must resolve */
1012 /* woken due to restart signal */
1015 #endif /* __NR_rt_sigaction */
1018 #ifdef __NR_rt_sigaction
1019 void __pthread_restart_new(pthread_descr th)
1021 /* The barrier is proabably not needed, in which case it still documents
1022 our assumptions. The intent is to commit previous writes to shared
1023 memory so the woken thread will have a consistent view. Complementary
1024 read barriers are present to the suspend functions. */
1025 WRITE_MEMORY_BARRIER();
1026 kill(th->p_pid, __pthread_sig_restart);
1029 int __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime)
1031 sigset_t unblock, initial_mask;
1032 int was_signalled = 0;
1035 if (sigsetjmp(jmpbuf, 1) == 0) {
1036 THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
1037 THREAD_SETMEM(self, p_signal, 0);
1038 /* Unblock the restart signal */
1039 sigemptyset(&unblock);
1040 sigaddset(&unblock, __pthread_sig_restart);
1041 sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
1045 struct timespec reltime;
1047 /* Compute a time offset relative to now. */
1048 gettimeofday (&now, NULL);
1049 reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
1050 reltime.tv_sec = abstime->tv_sec - now.tv_sec;
1051 if (reltime.tv_nsec < 0) {
1052 reltime.tv_nsec += 1000000000;
1053 reltime.tv_sec -= 1;
1056 /* Sleep for the required duration. If woken by a signal,
1057 resume waiting as required by Single Unix Specification. */
1058 if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
1062 /* Block the restart signal again */
1063 sigprocmask(SIG_SETMASK, &initial_mask, NULL);
1068 THREAD_SETMEM(self, p_signal_jmp, NULL);
1070 /* Now was_signalled is true if we exited the above code
1071 due to the delivery of a restart signal. In that case,
1072 everything is cool. We have been removed from whatever
1073 we were waiting on by the other thread, and consumed its signal.
1075 Otherwise we this thread woke up spontaneously, or due to a signal other
1076 than restart. This is an ambiguous case that must be resolved by
1077 the caller; the thread is still eligible for a restart wakeup
1078 so there is a race. */
1080 READ_MEMORY_BARRIER(); /* See comment in __pthread_restart_new */
1081 return was_signalled;
1090 void __pthread_message(char * fmt, ...)
1094 sprintf(buffer, "%05d : ", getpid());
1095 va_start(args, fmt);
1096 vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
1098 TEMP_FAILURE_RETRY(__libc_write(2, buffer, strlen(buffer)));
1105 /* We need a hook to force the cancelation wrappers to be linked in when
1106 static libpthread is used. */
1107 extern const int __pthread_provide_wrappers;
1108 static const int *const __pthread_require_wrappers =
1109 &__pthread_provide_wrappers;