* sysdeps/unix/sysv/linux/net/if_arp.h (ARPHRD_RAWHDLC): Added.
[glibc.git] / linuxthreads / pthread.c
blob479531b5a42ce8ac1803e7fa2b33943f7b7c0e69
2 /* Linuxthreads - a simple clone()-based implementation of Posix */
3 /* threads for Linux. */
4 /* Copyright (C) 1996 Xavier Leroy (Xavier.Leroy@inria.fr) */
5 /* */
6 /* This program is free software; you can redistribute it and/or */
7 /* modify it under the terms of the GNU Library General Public License */
8 /* as published by the Free Software Foundation; either version 2 */
9 /* of the License, or (at your option) any later version. */
10 /* */
11 /* This program is distributed in the hope that it will be useful, */
12 /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
13 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
14 /* GNU Library General Public License for more details. */
16 /* Thread creation, initialization, and basic low-level routines */
18 #include <errno.h>
19 #include <stddef.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <fcntl.h>
25 #include <sys/wait.h>
26 #include <sys/resource.h>
27 #include <sys/sysctl.h>
28 #include <shlib-compat.h>
29 #include "pthread.h"
30 #include "internals.h"
31 #include "spinlock.h"
32 #include "restart.h"
34 /* We need the global/static resolver state here. */
35 #include <resolv.h>
36 #undef _res
38 extern struct __res_state _res;
40 /* Sanity check. */
41 #if __ASSUME_REALTIME_SIGNALS && !defined __SIGRTMIN
42 # error "This must not happen; new kernel assumed but old headers"
43 #endif
45 /* These variables are used by the setup code. */
46 extern int _errno;
47 extern int _h_errno;
49 /* Descriptor of the initial thread */
51 struct _pthread_descr_struct __pthread_initial_thread = {
54 &__pthread_initial_thread /* pthread_descr self */
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 */
62 0, /* int p_pid */
63 0, /* int p_priority */
64 &__pthread_handles[0].h_lock, /* struct _pthread_fastlock * p_lock */
65 0, /* int p_signal */
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 */
72 0, /* int 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 */
79 0, /* int p_errno */
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(NULL),
85 /* struct pthread_start_args p_start_args */
86 {NULL}, /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
87 {NULL}, /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
88 1, /* int p_userstack */
89 NULL, /* void * p_guardaddr */
90 0, /* size_t p_guardsize */
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; */
104 /* Descriptor of the manager thread; none of this is used but the error
105 variables, the p_pid and p_priority fields,
106 and the address for identification. */
108 struct _pthread_descr_struct __pthread_manager_thread = {
111 &__pthread_manager_thread /* pthread_descr self */
114 NULL, /* pthread_descr p_nextlive */
115 NULL, /* pthread_descr p_prevlive */
116 NULL, /* pthread_descr p_nextwaiting */
117 NULL, /* pthread_descr p_nextlock */
118 0, /* int p_tid */
119 0, /* int p_pid */
120 0, /* int p_priority */
121 &__pthread_handles[1].h_lock, /* struct _pthread_fastlock * p_lock */
122 0, /* int p_signal */
123 NULL, /* sigjmp_buf * p_signal_buf */
124 NULL, /* sigjmp_buf * p_cancel_buf */
125 0, /* char p_terminated */
126 0, /* char p_detached */
127 0, /* char p_exited */
128 NULL, /* void * p_retval */
129 0, /* int p_retval */
130 NULL, /* pthread_descr p_joining */
131 NULL, /* struct _pthread_cleanup_buffer * p_cleanup */
132 0, /* char p_cancelstate */
133 0, /* char p_canceltype */
134 0, /* char p_canceled */
135 &__pthread_manager_thread.p_errno, /* int *p_errnop */
136 0, /* int p_errno */
137 NULL, /* int *p_h_errnop */
138 0, /* int p_h_errno */
139 NULL, /* char * p_in_sighandler */
140 0, /* char p_sigwaiting */
141 PTHREAD_START_ARGS_INITIALIZER(__pthread_manager),
142 /* struct pthread_start_args p_start_args */
143 {NULL}, /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
144 {NULL}, /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
145 0, /* int p_userstack */
146 NULL, /* void * p_guardaddr */
147 0, /* size_t p_guardsize */
148 1, /* Always index 1 */
149 0, /* int p_report_events */
150 {{{0, }}, 0, NULL}, /* td_eventbuf_t p_eventbuf */
151 __ATOMIC_INITIALIZER, /* struct pthread_atomic p_resume_count */
152 0, /* char p_woken_by_cancel */
153 0, /* char p_condvar_avail */
154 0, /* char p_sem_avail */
155 NULL, /* struct pthread_extricate_if *p_extricate */
156 NULL, /* pthread_readlock_info *p_readlock_list; */
157 NULL, /* pthread_readlock_info *p_readlock_free; */
158 0 /* int p_untracked_readlock_count; */
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;
171 /* File descriptor for sending requests to the thread manager. */
172 /* Initially -1, meaning that the thread manager is not running. */
174 int __pthread_manager_request = -1;
176 /* Other end of the pipe for sending requests to the thread manager. */
178 int __pthread_manager_reader;
180 /* Limits of the thread manager stack */
182 char *__pthread_manager_thread_bos;
183 char *__pthread_manager_thread_tos;
185 /* For process-wide exit() */
187 int __pthread_exit_requested;
188 int __pthread_exit_code;
190 /* Maximum stack size. */
191 size_t __pthread_max_stacksize;
193 /* Nozero if the machine has more than one processor. */
194 int __pthread_smp_kernel;
197 #if !__ASSUME_REALTIME_SIGNALS
198 /* Pointers that select new or old suspend/resume functions
199 based on availability of rt signals. */
201 void (*__pthread_restart)(pthread_descr) = __pthread_restart_old;
202 void (*__pthread_suspend)(pthread_descr) = __pthread_suspend_old;
203 int (*__pthread_timedsuspend)(pthread_descr, const struct timespec *) = __pthread_timedsuspend_old;
204 #endif /* __ASSUME_REALTIME_SIGNALS */
206 /* Communicate relevant LinuxThreads constants to gdb */
208 const int __pthread_threads_max = PTHREAD_THREADS_MAX;
209 const int __pthread_sizeof_handle = sizeof(struct pthread_handle_struct);
210 const int __pthread_offsetof_descr = offsetof(struct pthread_handle_struct,
211 h_descr);
212 const int __pthread_offsetof_pid = offsetof(struct _pthread_descr_struct,
213 p_pid);
214 const int __linuxthread_pthread_sizeof_descr
215 = sizeof(struct _pthread_descr_struct);
217 /* Forward declarations */
219 static void pthread_onexit_process(int retcode, void *arg);
220 #ifndef HAVE_Z_NODELETE
221 static void pthread_atexit_process(void *arg, int retcode);
222 static void pthread_atexit_retcode(void *arg, int retcode);
223 #endif
224 static void pthread_handle_sigcancel(int sig);
225 static void pthread_handle_sigrestart(int sig);
226 static void pthread_handle_sigdebug(int sig);
228 /* Signal numbers used for the communication.
229 In these variables we keep track of the used variables. If the
230 platform does not support any real-time signals we will define the
231 values to some unreasonable value which will signal failing of all
232 the functions below. */
233 #ifndef __SIGRTMIN
234 static int current_rtmin = -1;
235 static int current_rtmax = -1;
236 int __pthread_sig_restart = SIGUSR1;
237 int __pthread_sig_cancel = SIGUSR2;
238 int __pthread_sig_debug;
239 #else
240 static int current_rtmin;
241 static int current_rtmax;
243 #if __SIGRTMAX - __SIGRTMIN >= 3
244 int __pthread_sig_restart = __SIGRTMIN;
245 int __pthread_sig_cancel = __SIGRTMIN + 1;
246 int __pthread_sig_debug = __SIGRTMIN + 2;
247 #else
248 int __pthread_sig_restart = SIGUSR1;
249 int __pthread_sig_cancel = SIGUSR2;
250 int __pthread_sig_debug;
251 #endif
253 static int rtsigs_initialized;
255 #if !__ASSUME_REALTIME_SIGNALS
256 # include "testrtsig.h"
257 #endif
259 static void
260 init_rtsigs (void)
262 #if !__ASSUME_REALTIME_SIGNALS
263 if (__builtin_expect (!kernel_has_rtsig (), 0))
265 current_rtmin = -1;
266 current_rtmax = -1;
267 # if __SIGRTMAX - __SIGRTMIN >= 3
268 __pthread_sig_restart = SIGUSR1;
269 __pthread_sig_cancel = SIGUSR2;
270 __pthread_sig_debug = 0;
271 # endif
273 else
274 #endif /* __ASSUME_REALTIME_SIGNALS */
276 #if __SIGRTMAX - __SIGRTMIN >= 3
277 current_rtmin = __SIGRTMIN + 3;
278 # if !__ASSUME_REALTIME_SIGNALS
279 __pthread_restart = __pthread_restart_new;
280 __pthread_suspend = __pthread_wait_for_restart_signal;
281 __pthread_timedsuspend = __pthread_timedsuspend_new;
282 # endif /* __ASSUME_REALTIME_SIGNALS */
283 #else
284 current_rtmin = __SIGRTMIN;
285 #endif
287 current_rtmax = __SIGRTMAX;
290 rtsigs_initialized = 1;
292 #endif
294 /* Return number of available real-time signal with highest priority. */
296 __libc_current_sigrtmin (void)
298 #ifdef __SIGRTMIN
299 if (__builtin_expect (!rtsigs_initialized, 0))
300 init_rtsigs ();
301 #endif
302 return current_rtmin;
305 /* Return number of available real-time signal with lowest priority. */
307 __libc_current_sigrtmax (void)
309 #ifdef __SIGRTMIN
310 if (__builtin_expect (!rtsigs_initialized, 0))
311 init_rtsigs ();
312 #endif
313 return current_rtmax;
316 /* Allocate real-time signal with highest/lowest available
317 priority. Please note that we don't use a lock since we assume
318 this function to be called at program start. */
320 __libc_allocate_rtsig (int high)
322 #ifndef __SIGRTMIN
323 return -1;
324 #else
325 if (__builtin_expect (!rtsigs_initialized, 0))
326 init_rtsigs ();
327 if (__builtin_expect (current_rtmin == -1, 0)
328 || __builtin_expect (current_rtmin > current_rtmax, 0))
329 /* We don't have anymore signal available. */
330 return -1;
332 return high ? current_rtmin++ : current_rtmax--;
333 #endif
336 /* The function we use to get the kernel revision. */
337 extern int __sysctl (int *name, int nlen, void *oldval, size_t *oldlenp,
338 void *newval, size_t newlen);
340 /* Test whether the machine has more than one processor. This is not the
341 best test but good enough. More complicated tests would require `malloc'
342 which is not available at that time. */
343 static int
344 is_smp_system (void)
346 static const int sysctl_args[] = { CTL_KERN, KERN_VERSION };
347 char buf[512];
348 size_t reslen = sizeof (buf);
350 /* Try reading the number using `sysctl' first. */
351 if (__sysctl ((int *) sysctl_args,
352 sizeof (sysctl_args) / sizeof (sysctl_args[0]),
353 buf, &reslen, NULL, 0) < 0)
355 /* This was not successful. Now try reading the /proc filesystem. */
356 int fd = __open ("/proc/sys/kernel/version", O_RDONLY);
357 if (__builtin_expect (fd, 0) == -1
358 || (reslen = __read (fd, buf, sizeof (buf))) <= 0)
359 /* This also didn't work. We give up and say it's a UP machine. */
360 buf[0] = '\0';
362 __close (fd);
365 return strstr (buf, "SMP") != NULL;
369 /* Initialize the pthread library.
370 Initialization is split in two functions:
371 - a constructor function that blocks the __pthread_sig_restart signal
372 (must do this very early, since the program could capture the signal
373 mask with e.g. sigsetjmp before creating the first thread);
374 - a regular function called from pthread_create when needed. */
376 static void pthread_initialize(void) __attribute__((constructor));
378 #ifndef HAVE_Z_NODELETE
379 extern void *__dso_handle __attribute__ ((weak));
380 #endif
383 /* Do some minimal initialization which has to be done during the
384 startup of the C library. */
385 void
386 __pthread_initialize_minimal(void)
388 /* If we have special thread_self processing, initialize that for the
389 main thread now. */
390 #ifdef INIT_THREAD_SELF
391 INIT_THREAD_SELF(&__pthread_initial_thread, 0);
392 #endif
396 static void pthread_initialize(void)
398 struct sigaction sa;
399 sigset_t mask;
401 /* If already done (e.g. by a constructor called earlier!), bail out */
402 if (__pthread_initial_thread_bos != NULL) return;
403 #ifdef TEST_FOR_COMPARE_AND_SWAP
404 /* Test if compare-and-swap is available */
405 __pthread_has_cas = compare_and_swap_is_available();
406 #endif
407 /* For the initial stack, reserve at least STACK_SIZE bytes of stack
408 below the current stack address, and align that on a
409 STACK_SIZE boundary. */
410 __pthread_initial_thread_bos =
411 (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
412 /* Update the descriptor for the initial thread. */
413 __pthread_initial_thread.p_pid = __getpid();
414 /* Likewise for the resolver state _res. */
415 __pthread_initial_thread.p_resp = &_res;
416 #ifdef __SIGRTMIN
417 /* Initialize real-time signals. */
418 init_rtsigs ();
419 #endif
420 /* Setup signal handlers for the initial thread.
421 Since signal handlers are shared between threads, these settings
422 will be inherited by all other threads. */
423 sa.sa_handler = pthread_handle_sigrestart;
424 sigemptyset(&sa.sa_mask);
425 sa.sa_flags = 0;
426 __libc_sigaction(__pthread_sig_restart, &sa, NULL);
427 sa.sa_handler = pthread_handle_sigcancel;
428 // sa.sa_flags = 0;
429 __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
430 if (__pthread_sig_debug > 0) {
431 sa.sa_handler = pthread_handle_sigdebug;
432 sigemptyset(&sa.sa_mask);
433 // sa.sa_flags = 0;
434 __libc_sigaction(__pthread_sig_debug, &sa, NULL);
436 /* Initially, block __pthread_sig_restart. Will be unblocked on demand. */
437 sigemptyset(&mask);
438 sigaddset(&mask, __pthread_sig_restart);
439 sigprocmask(SIG_BLOCK, &mask, NULL);
440 /* Register an exit function to kill all other threads. */
441 /* Do it early so that user-registered atexit functions are called
442 before pthread_*exit_process. */
443 #ifndef HAVE_Z_NODELETE
444 if (__builtin_expect (&__dso_handle != NULL, 1))
445 __cxa_atexit ((void (*) (void *)) pthread_atexit_process, NULL,
446 __dso_handle);
447 else
448 #endif
449 __on_exit (pthread_onexit_process, NULL);
450 /* How many processors. */
451 __pthread_smp_kernel = is_smp_system ();
454 void __pthread_initialize(void)
456 pthread_initialize();
459 void __pthread_init_max_stacksize(void)
461 struct rlimit limit;
462 size_t max_stack;
464 getrlimit(RLIMIT_STACK, &limit);
465 #ifdef FLOATING_STACKS
466 if (limit.rlim_cur == RLIM_INFINITY)
467 limit.rlim_cur = ARCH_STACK_MAX_SIZE;
468 # ifdef NEED_SEPARATE_REGISTER_STACK
469 max_stack = limit.rlim_cur / 2;
470 # else
471 max_stack = limit.rlim_cur;
472 # endif
473 #else
474 /* Play with the stack size limit to make sure that no stack ever grows
475 beyond STACK_SIZE minus one page (to act as a guard page). */
476 # ifdef NEED_SEPARATE_REGISTER_STACK
477 /* STACK_SIZE bytes hold both the main stack and register backing
478 store. The rlimit value applies to each individually. */
479 max_stack = STACK_SIZE/2 - __getpagesize ();
480 # else
481 max_stack = STACK_SIZE - __getpagesize();
482 # endif
483 if (limit.rlim_cur > max_stack) {
484 limit.rlim_cur = max_stack;
485 setrlimit(RLIMIT_STACK, &limit);
487 #endif
488 __pthread_max_stacksize = max_stack;
491 int __pthread_initialize_manager(void)
493 int manager_pipe[2];
494 int pid;
495 struct pthread_request request;
497 #ifndef HAVE_Z_NODELETE
498 if (__builtin_expect (&__dso_handle != NULL, 1))
499 __cxa_atexit ((void (*) (void *)) pthread_atexit_retcode, NULL,
500 __dso_handle);
501 #endif
503 if (__pthread_max_stacksize == 0)
504 __pthread_init_max_stacksize ();
505 /* If basic initialization not done yet (e.g. we're called from a
506 constructor run before our constructor), do it now */
507 if (__pthread_initial_thread_bos == NULL) pthread_initialize();
508 /* Setup stack for thread manager */
509 __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
510 if (__pthread_manager_thread_bos == NULL) return -1;
511 __pthread_manager_thread_tos =
512 __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;
513 /* Setup pipe to communicate with thread manager */
514 if (pipe(manager_pipe) == -1) {
515 free(__pthread_manager_thread_bos);
516 return -1;
518 /* Start the thread manager */
519 pid = 0;
520 if (__builtin_expect (__pthread_initial_thread.p_report_events, 0))
522 /* It's a bit more complicated. We have to report the creation of
523 the manager thread. */
524 int idx = __td_eventword (TD_CREATE);
525 uint32_t mask = __td_eventmask (TD_CREATE);
527 if ((mask & (__pthread_threads_events.event_bits[idx]
528 | __pthread_initial_thread.p_eventbuf.eventmask.event_bits[idx]))
529 != 0)
531 __pthread_lock(__pthread_manager_thread.p_lock, NULL);
533 #ifdef NEED_SEPARATE_REGISTER_STACK
534 pid = __clone2(__pthread_manager_event,
535 (void **) __pthread_manager_thread_bos,
536 THREAD_MANAGER_STACK_SIZE,
537 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
538 (void *)(long)manager_pipe[0]);
539 #else
540 pid = __clone(__pthread_manager_event,
541 (void **) __pthread_manager_thread_tos,
542 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
543 (void *)(long)manager_pipe[0]);
544 #endif
546 if (pid != -1)
548 /* Now fill in the information about the new thread in
549 the newly created thread's data structure. We cannot let
550 the new thread do this since we don't know whether it was
551 already scheduled when we send the event. */
552 __pthread_manager_thread.p_eventbuf.eventdata =
553 &__pthread_manager_thread;
554 __pthread_manager_thread.p_eventbuf.eventnum = TD_CREATE;
555 __pthread_last_event = &__pthread_manager_thread;
556 __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
557 __pthread_manager_thread.p_pid = pid;
559 /* Now call the function which signals the event. */
560 __linuxthreads_create_event ();
563 /* Now restart the thread. */
564 __pthread_unlock(__pthread_manager_thread.p_lock);
568 if (__builtin_expect (pid, 0) == 0)
570 #ifdef NEED_SEPARATE_REGISTER_STACK
571 pid = __clone2(__pthread_manager, (void **) __pthread_manager_thread_bos,
572 THREAD_MANAGER_STACK_SIZE,
573 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
574 (void *)(long)manager_pipe[0]);
575 #else
576 pid = __clone(__pthread_manager, (void **) __pthread_manager_thread_tos,
577 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
578 (void *)(long)manager_pipe[0]);
579 #endif
581 if (__builtin_expect (pid, 0) == -1) {
582 free(__pthread_manager_thread_bos);
583 __libc_close(manager_pipe[0]);
584 __libc_close(manager_pipe[1]);
585 return -1;
587 __pthread_manager_request = manager_pipe[1]; /* writing end */
588 __pthread_manager_reader = manager_pipe[0]; /* reading end */
589 __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
590 __pthread_manager_thread.p_pid = pid;
591 /* Make gdb aware of new thread manager */
592 if (__builtin_expect (__pthread_threads_debug, 0) && __pthread_sig_debug > 0)
594 raise(__pthread_sig_debug);
595 /* We suspend ourself and gdb will wake us up when it is
596 ready to handle us. */
597 __pthread_wait_for_restart_signal(thread_self());
599 /* Synchronize debugging of the thread manager */
600 request.req_kind = REQ_DEBUG;
601 __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
602 return 0;
605 /* Thread creation */
607 int __pthread_create_2_1(pthread_t *thread, const pthread_attr_t *attr,
608 void * (*start_routine)(void *), void *arg)
610 pthread_descr self = thread_self();
611 struct pthread_request request;
612 int retval;
613 if (__builtin_expect (__pthread_manager_request, 0) < 0) {
614 if (__pthread_initialize_manager() < 0) return EAGAIN;
616 request.req_thread = self;
617 request.req_kind = REQ_CREATE;
618 request.req_args.create.attr = attr;
619 request.req_args.create.fn = start_routine;
620 request.req_args.create.arg = arg;
621 sigprocmask(SIG_SETMASK, (const sigset_t *) NULL,
622 &request.req_args.create.mask);
623 __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
624 suspend(self);
625 retval = THREAD_GETMEM(self, p_retcode);
626 if (__builtin_expect (retval, 0) == 0)
627 *thread = (pthread_t) THREAD_GETMEM(self, p_retval);
628 return retval;
631 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
633 #if SHLIB_COMPAT (libpthread, GLIBC_2_0, GLIBC_2_1)
635 int __pthread_create_2_0(pthread_t *thread, const pthread_attr_t *attr,
636 void * (*start_routine)(void *), void *arg)
638 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
639 the old size and access to the new members might crash the program.
640 We convert the struct now. */
641 pthread_attr_t new_attr;
643 if (attr != NULL)
645 size_t ps = __getpagesize ();
647 memcpy (&new_attr, attr,
648 (size_t) &(((pthread_attr_t*)NULL)->__guardsize));
649 new_attr.__guardsize = ps;
650 new_attr.__stackaddr_set = 0;
651 new_attr.__stackaddr = NULL;
652 new_attr.__stacksize = STACK_SIZE - ps;
653 attr = &new_attr;
655 return __pthread_create_2_1 (thread, attr, start_routine, arg);
657 compat_symbol (libpthread, __pthread_create_2_0, pthread_create, GLIBC_2_0);
658 #endif
660 /* Simple operations on thread identifiers */
662 pthread_t pthread_self(void)
664 pthread_descr self = thread_self();
665 return THREAD_GETMEM(self, p_tid);
668 int pthread_equal(pthread_t thread1, pthread_t thread2)
670 return thread1 == thread2;
673 /* Helper function for thread_self in the case of user-provided stacks */
675 #ifndef THREAD_SELF
677 pthread_descr __pthread_find_self()
679 char * sp = CURRENT_STACK_FRAME;
680 pthread_handle h;
682 /* __pthread_handles[0] is the initial thread, __pthread_handles[1] is
683 the manager threads handled specially in thread_self(), so start at 2 */
684 h = __pthread_handles + 2;
685 while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;
686 return h->h_descr;
689 #endif
691 /* Thread scheduling */
693 int pthread_setschedparam(pthread_t thread, int policy,
694 const struct sched_param *param)
696 pthread_handle handle = thread_handle(thread);
697 pthread_descr th;
699 __pthread_lock(&handle->h_lock, NULL);
700 if (__builtin_expect (invalid_handle(handle, thread), 0)) {
701 __pthread_unlock(&handle->h_lock);
702 return ESRCH;
704 th = handle->h_descr;
705 if (__builtin_expect (__sched_setscheduler(th->p_pid, policy, param) == -1,
706 0)) {
707 __pthread_unlock(&handle->h_lock);
708 return errno;
710 th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
711 __pthread_unlock(&handle->h_lock);
712 if (__pthread_manager_request >= 0)
713 __pthread_manager_adjust_prio(th->p_priority);
714 return 0;
717 int pthread_getschedparam(pthread_t thread, int *policy,
718 struct sched_param *param)
720 pthread_handle handle = thread_handle(thread);
721 int pid, pol;
723 __pthread_lock(&handle->h_lock, NULL);
724 if (__builtin_expect (invalid_handle(handle, thread), 0)) {
725 __pthread_unlock(&handle->h_lock);
726 return ESRCH;
728 pid = handle->h_descr->p_pid;
729 __pthread_unlock(&handle->h_lock);
730 pol = __sched_getscheduler(pid);
731 if (__builtin_expect (pol, 0) == -1) return errno;
732 if (__sched_getparam(pid, param) == -1) return errno;
733 *policy = pol;
734 return 0;
737 int __pthread_yield ()
739 /* For now this is equivalent with the POSIX call. */
740 return sched_yield ();
742 weak_alias (__pthread_yield, pthread_yield)
744 /* Process-wide exit() request */
746 static void pthread_onexit_process(int retcode, void *arg)
748 if (__builtin_expect (__pthread_manager_request, 0) >= 0) {
749 struct pthread_request request;
750 pthread_descr self = thread_self();
752 request.req_thread = self;
753 request.req_kind = REQ_PROCESS_EXIT;
754 request.req_args.exit.code = retcode;
755 __libc_write(__pthread_manager_request,
756 (char *) &request, sizeof(request));
757 suspend(self);
758 /* Main thread should accumulate times for thread manager and its
759 children, so that timings for main thread account for all threads. */
760 if (self == __pthread_main_thread)
762 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
763 free (__pthread_manager_thread_bos);
764 __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
769 #ifndef HAVE_Z_NODELETE
770 static int __pthread_atexit_retcode;
772 static void pthread_atexit_process(void *arg, int retcode)
774 pthread_onexit_process (retcode ?: __pthread_atexit_retcode, arg);
777 static void pthread_atexit_retcode(void *arg, int retcode)
779 __pthread_atexit_retcode = retcode;
781 #endif
783 /* The handler for the RESTART signal just records the signal received
784 in the thread descriptor, and optionally performs a siglongjmp
785 (for pthread_cond_timedwait). */
787 static void pthread_handle_sigrestart(int sig)
789 pthread_descr self = thread_self();
790 THREAD_SETMEM(self, p_signal, sig);
791 if (THREAD_GETMEM(self, p_signal_jmp) != NULL)
792 siglongjmp(*THREAD_GETMEM(self, p_signal_jmp), 1);
795 /* The handler for the CANCEL signal checks for cancellation
796 (in asynchronous mode), for process-wide exit and exec requests.
797 For the thread manager thread, redirect the signal to
798 __pthread_manager_sighandler. */
800 static void pthread_handle_sigcancel(int sig)
802 pthread_descr self = thread_self();
803 sigjmp_buf * jmpbuf;
805 if (self == &__pthread_manager_thread)
807 __pthread_manager_sighandler(sig);
808 return;
810 if (__builtin_expect (__pthread_exit_requested, 0)) {
811 /* Main thread should accumulate times for thread manager and its
812 children, so that timings for main thread account for all threads. */
813 if (self == __pthread_main_thread)
814 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
815 _exit(__pthread_exit_code);
817 if (__builtin_expect (THREAD_GETMEM(self, p_canceled), 0)
818 && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
819 if (THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
820 pthread_exit(PTHREAD_CANCELED);
821 jmpbuf = THREAD_GETMEM(self, p_cancel_jmp);
822 if (jmpbuf != NULL) {
823 THREAD_SETMEM(self, p_cancel_jmp, NULL);
824 siglongjmp(*jmpbuf, 1);
829 /* Handler for the DEBUG signal.
830 The debugging strategy is as follows:
831 On reception of a REQ_DEBUG request (sent by new threads created to
832 the thread manager under debugging mode), the thread manager throws
833 __pthread_sig_debug to itself. The debugger (if active) intercepts
834 this signal, takes into account new threads and continue execution
835 of the thread manager by propagating the signal because it doesn't
836 know what it is specifically done for. In the current implementation,
837 the thread manager simply discards it. */
839 static void pthread_handle_sigdebug(int sig)
841 /* Nothing */
844 /* Reset the state of the thread machinery after a fork().
845 Close the pipe used for requests and set the main thread to the forked
846 thread.
847 Notice that we can't free the stack segments, as the forked thread
848 may hold pointers into them. */
850 void __pthread_reset_main_thread()
852 pthread_descr self = thread_self();
853 struct rlimit limit;
855 if (__pthread_manager_request != -1) {
856 /* Free the thread manager stack */
857 free(__pthread_manager_thread_bos);
858 __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
859 /* Close the two ends of the pipe */
860 __libc_close(__pthread_manager_request);
861 __libc_close(__pthread_manager_reader);
862 __pthread_manager_request = __pthread_manager_reader = -1;
865 /* Update the pid of the main thread */
866 THREAD_SETMEM(self, p_pid, __getpid());
867 /* Make the forked thread the main thread */
868 __pthread_main_thread = self;
869 THREAD_SETMEM(self, p_nextlive, self);
870 THREAD_SETMEM(self, p_prevlive, self);
871 /* Now this thread modifies the global variables. */
872 THREAD_SETMEM(self, p_errnop, &_errno);
873 THREAD_SETMEM(self, p_h_errnop, &_h_errno);
874 THREAD_SETMEM(self, p_resp, &_res);
876 if (getrlimit (RLIMIT_STACK, &limit) == 0
877 && limit.rlim_cur != limit.rlim_max) {
878 limit.rlim_cur = limit.rlim_max;
879 setrlimit (STACK_SIZE, &limit);
883 /* Process-wide exec() request */
885 void __pthread_kill_other_threads_np(void)
887 struct sigaction sa;
888 /* Terminate all other threads and thread manager */
889 pthread_onexit_process(0, NULL);
890 /* Make current thread the main thread in case the calling thread
891 changes its mind, does not exec(), and creates new threads instead. */
892 __pthread_reset_main_thread();
894 /* Reset the signal handlers behaviour for the signals the
895 implementation uses since this would be passed to the new
896 process. */
897 sigemptyset(&sa.sa_mask);
898 sa.sa_flags = 0;
899 sa.sa_handler = SIG_DFL;
900 __libc_sigaction(__pthread_sig_restart, &sa, NULL);
901 __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
902 if (__pthread_sig_debug > 0)
903 __libc_sigaction(__pthread_sig_debug, &sa, NULL);
905 weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
907 /* Concurrency symbol level. */
908 static int current_level;
910 int __pthread_setconcurrency(int level)
912 /* We don't do anything unless we have found a useful interpretation. */
913 current_level = level;
914 return 0;
916 weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
918 int __pthread_getconcurrency(void)
920 return current_level;
922 weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
924 /* Primitives for controlling thread execution */
926 void __pthread_wait_for_restart_signal(pthread_descr self)
928 sigset_t mask;
930 sigprocmask(SIG_SETMASK, NULL, &mask); /* Get current signal mask */
931 sigdelset(&mask, __pthread_sig_restart); /* Unblock the restart signal */
932 THREAD_SETMEM(self, p_signal, 0);
933 do {
934 sigsuspend(&mask); /* Wait for signal */
935 } while (THREAD_GETMEM(self, p_signal) !=__pthread_sig_restart);
938 #if !__ASSUME_REALTIME_SIGNALS
939 /* The _old variants are for 2.0 and early 2.1 kernels which don't have RT
940 signals.
941 On these kernels, we use SIGUSR1 and SIGUSR2 for restart and cancellation.
942 Since the restart signal does not queue, we use an atomic counter to create
943 queuing semantics. This is needed to resolve a rare race condition in
944 pthread_cond_timedwait_relative. */
946 void __pthread_restart_old(pthread_descr th)
948 if (atomic_increment(&th->p_resume_count) == -1)
949 kill(th->p_pid, __pthread_sig_restart);
952 void __pthread_suspend_old(pthread_descr self)
954 if (atomic_decrement(&self->p_resume_count) <= 0)
955 __pthread_wait_for_restart_signal(self);
959 __pthread_timedsuspend_old(pthread_descr self, const struct timespec *abstime)
961 sigset_t unblock, initial_mask;
962 int was_signalled = 0;
963 sigjmp_buf jmpbuf;
965 if (atomic_decrement(&self->p_resume_count) == 0) {
966 /* Set up a longjmp handler for the restart signal, unblock
967 the signal and sleep. */
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);
977 while (1) {
978 struct timeval now;
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;
987 reltime.tv_sec -= 1;
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)
993 break;
996 /* Block the restart signal again */
997 sigprocmask(SIG_SETMASK, &initial_mask, NULL);
998 was_signalled = 0;
999 } else {
1000 was_signalled = 1;
1002 THREAD_SETMEM(self, p_signal_jmp, NULL);
1005 /* Now was_signalled is true if we exited the above code
1006 due to the delivery of a restart signal. In that case,
1007 we know we have been dequeued and resumed and that the
1008 resume count is balanced. Otherwise, there are some
1009 cases to consider. First, try to bump up the resume count
1010 back to zero. If it goes to 1, it means restart() was
1011 invoked on this thread. The signal must be consumed
1012 and the count bumped down and everything is cool. We
1013 can return a 1 to the caller.
1014 Otherwise, no restart was delivered yet, so a potential
1015 race exists; we return a 0 to the caller which must deal
1016 with this race in an appropriate way; for example by
1017 atomically removing the thread from consideration for a
1018 wakeup---if such a thing fails, it means a restart is
1019 being delivered. */
1021 if (!was_signalled) {
1022 if (atomic_increment(&self->p_resume_count) != -1) {
1023 __pthread_wait_for_restart_signal(self);
1024 atomic_decrement(&self->p_resume_count); /* should be zero now! */
1025 /* woke spontaneously and consumed restart signal */
1026 return 1;
1028 /* woke spontaneously but did not consume restart---caller must resolve */
1029 return 0;
1031 /* woken due to restart signal */
1032 return 1;
1034 #endif /* __ASSUME_REALTIME_SIGNALS */
1036 void __pthread_restart_new(pthread_descr th)
1038 kill(th->p_pid, __pthread_sig_restart);
1041 /* There is no __pthread_suspend_new because it would just
1042 be a wasteful wrapper for __pthread_wait_for_restart_signal */
1045 __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime)
1047 sigset_t unblock, initial_mask;
1048 int was_signalled = 0;
1049 sigjmp_buf jmpbuf;
1051 if (sigsetjmp(jmpbuf, 1) == 0) {
1052 THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
1053 THREAD_SETMEM(self, p_signal, 0);
1054 /* Unblock the restart signal */
1055 sigemptyset(&unblock);
1056 sigaddset(&unblock, __pthread_sig_restart);
1057 sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
1059 while (1) {
1060 struct timeval now;
1061 struct timespec reltime;
1063 /* Compute a time offset relative to now. */
1064 __gettimeofday (&now, NULL);
1065 reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
1066 reltime.tv_sec = abstime->tv_sec - now.tv_sec;
1067 if (reltime.tv_nsec < 0) {
1068 reltime.tv_nsec += 1000000000;
1069 reltime.tv_sec -= 1;
1072 /* Sleep for the required duration. If woken by a signal,
1073 resume waiting as required by Single Unix Specification. */
1074 if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
1075 break;
1078 /* Block the restart signal again */
1079 sigprocmask(SIG_SETMASK, &initial_mask, NULL);
1080 was_signalled = 0;
1081 } else {
1082 was_signalled = 1;
1084 THREAD_SETMEM(self, p_signal_jmp, NULL);
1086 /* Now was_signalled is true if we exited the above code
1087 due to the delivery of a restart signal. In that case,
1088 everything is cool. We have been removed from whatever
1089 we were waiting on by the other thread, and consumed its signal.
1091 Otherwise we this thread woke up spontaneously, or due to a signal other
1092 than restart. This is an ambiguous case that must be resolved by
1093 the caller; the thread is still eligible for a restart wakeup
1094 so there is a race. */
1096 return was_signalled;
1100 /* Debugging aid */
1102 #ifdef DEBUG
1103 #include <stdarg.h>
1105 void __pthread_message(char * fmt, ...)
1107 char buffer[1024];
1108 va_list args;
1109 sprintf(buffer, "%05d : ", __getpid());
1110 va_start(args, fmt);
1111 vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
1112 va_end(args);
1113 __libc_write(2, buffer, strlen(buffer));
1116 #endif
1119 #ifndef SHARED
1120 /* We need a hook to force the cancelation wrappers to be linked in when
1121 static libpthread is used. */
1122 extern const int __pthread_provide_wrappers;
1123 static const int *const __pthread_require_wrappers =
1124 &__pthread_provide_wrappers;
1125 #endif