Update.
[glibc.git] / linuxthreads / pthread.c
blob551086f84b1e24d7cb6a3dc4fcb035e494a579af
1 /* Linuxthreads - a simple clone()-based implementation of Posix */
2 /* threads for Linux. */
3 /* Copyright (C) 1996 Xavier Leroy (Xavier.Leroy@inria.fr) */
4 /* */
5 /* This program is free software; you can redistribute it and/or */
6 /* modify it under the terms of the GNU Library General Public License */
7 /* as published by the Free Software Foundation; either version 2 */
8 /* of the License, or (at your option) any later version. */
9 /* */
10 /* This program is distributed in the hope that it will be useful, */
11 /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
12 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
13 /* GNU Library General Public License for more details. */
15 /* Thread creation, initialization, and basic low-level routines */
17 #include <errno.h>
18 #include <stddef.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include <fcntl.h>
24 #include <sys/wait.h>
25 #include <sys/resource.h>
26 #include <sys/sysctl.h>
27 #include <shlib-compat.h>
28 #include "pthread.h"
29 #include "internals.h"
30 #include "spinlock.h"
31 #include "restart.h"
33 /* Sanity check. */
34 #if __ASSUME_REALTIME_SIGNALS && !defined __SIGRTMIN
35 # error "This must not happen; new kernel assumed but old headers"
36 #endif
38 /* Descriptor of the initial thread */
40 struct _pthread_descr_struct __pthread_initial_thread = {
43 &__pthread_initial_thread /* pthread_descr self */
46 &__pthread_initial_thread, /* pthread_descr p_nextlive */
47 &__pthread_initial_thread, /* pthread_descr p_prevlive */
48 NULL, /* pthread_descr p_nextwaiting */
49 NULL, /* pthread_descr p_nextlock */
50 PTHREAD_THREADS_MAX, /* pthread_t p_tid */
51 0, /* int p_pid */
52 0, /* int p_priority */
53 &__pthread_handles[0].h_lock, /* struct _pthread_fastlock * p_lock */
54 0, /* int p_signal */
55 NULL, /* sigjmp_buf * p_signal_buf */
56 NULL, /* sigjmp_buf * p_cancel_buf */
57 0, /* char p_terminated */
58 0, /* char p_detached */
59 0, /* char p_exited */
60 NULL, /* void * p_retval */
61 0, /* int p_retval */
62 NULL, /* pthread_descr p_joining */
63 NULL, /* struct _pthread_cleanup_buffer * p_cleanup */
64 0, /* char p_cancelstate */
65 0, /* char p_canceltype */
66 0, /* char p_canceled */
67 NULL, /* int *p_errnop */
68 0, /* int p_errno */
69 NULL, /* int *p_h_errnop */
70 0, /* int p_h_errno */
71 NULL, /* char * p_in_sighandler */
72 0, /* char p_sigwaiting */
73 PTHREAD_START_ARGS_INITIALIZER(NULL),
74 /* struct pthread_start_args p_start_args */
75 {NULL}, /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
76 {NULL}, /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
77 0, /* int p_userstack */
78 NULL, /* void * p_guardaddr */
79 0, /* size_t p_guardsize */
80 0, /* Always index 0 */
81 0, /* int p_report_events */
82 {{{0, }}, 0, NULL}, /* td_eventbuf_t p_eventbuf */
83 ATOMIC_INITIALIZER, /* struct pthread_atomic p_resume_count */
84 0, /* char p_woken_by_cancel */
85 NULL, /* struct pthread_extricate_if *p_extricate */
86 NULL, /* pthread_readlock_info *p_readlock_list; */
87 NULL, /* pthread_readlock_info *p_readlock_free; */
88 0 /* int p_untracked_readlock_count; */
91 /* Descriptor of the manager thread; none of this is used but the error
92 variables, the p_pid and p_priority fields,
93 and the address for identification. */
95 struct _pthread_descr_struct __pthread_manager_thread = {
98 &__pthread_manager_thread /* pthread_descr self */
101 NULL, /* pthread_descr p_nextlive */
102 NULL, /* pthread_descr p_prevlive */
103 NULL, /* pthread_descr p_nextwaiting */
104 NULL, /* pthread_descr p_nextlock */
105 0, /* int p_tid */
106 0, /* int p_pid */
107 0, /* int p_priority */
108 &__pthread_handles[1].h_lock, /* struct _pthread_fastlock * p_lock */
109 0, /* int p_signal */
110 NULL, /* sigjmp_buf * p_signal_buf */
111 NULL, /* sigjmp_buf * p_cancel_buf */
112 0, /* char p_terminated */
113 0, /* char p_detached */
114 0, /* char p_exited */
115 NULL, /* void * p_retval */
116 0, /* int p_retval */
117 NULL, /* pthread_descr p_joining */
118 NULL, /* struct _pthread_cleanup_buffer * p_cleanup */
119 0, /* char p_cancelstate */
120 0, /* char p_canceltype */
121 0, /* char p_canceled */
122 &__pthread_manager_thread.p_errno, /* int *p_errnop */
123 0, /* int p_errno */
124 NULL, /* int *p_h_errnop */
125 0, /* int p_h_errno */
126 NULL, /* char * p_in_sighandler */
127 0, /* char p_sigwaiting */
128 PTHREAD_START_ARGS_INITIALIZER(__pthread_manager),
129 /* struct pthread_start_args p_start_args */
130 {NULL}, /* void ** p_specific[PTHREAD_KEY_1STLEVEL_SIZE] */
131 {NULL}, /* void * p_libc_specific[_LIBC_TSD_KEY_N] */
132 0, /* int p_userstack */
133 NULL, /* void * p_guardaddr */
134 0, /* size_t p_guardsize */
135 1, /* Always index 1 */
136 0, /* int p_report_events */
137 {{{0, }}, 0, NULL}, /* td_eventbuf_t p_eventbuf */
138 ATOMIC_INITIALIZER, /* struct pthread_atomic p_resume_count */
139 0, /* char p_woken_by_cancel */
140 NULL, /* struct pthread_extricate_if *p_extricate */
141 NULL, /* pthread_readlock_info *p_readlock_list; */
142 NULL, /* pthread_readlock_info *p_readlock_free; */
143 0 /* int p_untracked_readlock_count; */
146 /* Pointer to the main thread (the father of the thread manager thread) */
147 /* Originally, this is the initial thread, but this changes after fork() */
149 pthread_descr __pthread_main_thread = &__pthread_initial_thread;
151 /* Limit between the stack of the initial thread (above) and the
152 stacks of other threads (below). Aligned on a STACK_SIZE boundary. */
154 char *__pthread_initial_thread_bos;
156 /* File descriptor for sending requests to the thread manager. */
157 /* Initially -1, meaning that the thread manager is not running. */
159 int __pthread_manager_request = -1;
161 /* Other end of the pipe for sending requests to the thread manager. */
163 int __pthread_manager_reader;
165 /* Limits of the thread manager stack */
167 char *__pthread_manager_thread_bos;
168 char *__pthread_manager_thread_tos;
170 /* For process-wide exit() */
172 int __pthread_exit_requested;
173 int __pthread_exit_code;
175 /* Nozero if the machine has more than one processor. */
176 int __pthread_smp_kernel;
179 #if !__ASSUME_REALTIME_SIGNALS
180 /* Pointers that select new or old suspend/resume functions
181 based on availability of rt signals. */
183 void (*__pthread_restart)(pthread_descr) = __pthread_restart_old;
184 void (*__pthread_suspend)(pthread_descr) = __pthread_suspend_old;
185 int (*__pthread_timedsuspend)(pthread_descr, const struct timespec *) = __pthread_timedsuspend_old;
186 #endif /* __ASSUME_REALTIME_SIGNALS */
188 /* Communicate relevant LinuxThreads constants to gdb */
190 const int __pthread_threads_max = PTHREAD_THREADS_MAX;
191 const int __pthread_sizeof_handle = sizeof(struct pthread_handle_struct);
192 const int __pthread_offsetof_descr = offsetof(struct pthread_handle_struct,
193 h_descr);
194 const int __pthread_offsetof_pid = offsetof(struct _pthread_descr_struct,
195 p_pid);
196 const int __linuxthread_pthread_sizeof_descr
197 = sizeof(struct _pthread_descr_struct);
199 /* These variables are used by the setup code. */
200 extern int _errno;
201 extern int _h_errno;
203 /* Forward declarations */
205 static void pthread_exit_process(int retcode, void *arg);
206 static void pthread_handle_sigcancel(int sig);
207 static void pthread_handle_sigrestart(int sig);
208 static void pthread_handle_sigdebug(int sig);
210 /* Signal numbers used for the communication.
211 In these variables we keep track of the used variables. If the
212 platform does not support any real-time signals we will define the
213 values to some unreasonable value which will signal failing of all
214 the functions below. */
215 #ifndef __SIGRTMIN
216 static int current_rtmin = -1;
217 static int current_rtmax = -1;
218 int __pthread_sig_restart = SIGUSR1;
219 int __pthread_sig_cancel = SIGUSR2;
220 int __pthread_sig_debug;
221 #else
222 static int current_rtmin;
223 static int current_rtmax;
225 #if __SIGRTMAX - __SIGRTMIN >= 3
226 int __pthread_sig_restart = __SIGRTMIN;
227 int __pthread_sig_cancel = __SIGRTMIN + 1;
228 int __pthread_sig_debug = __SIGRTMIN + 2;
229 #else
230 int __pthread_sig_restart = SIGUSR1;
231 int __pthread_sig_cancel = SIGUSR2;
232 int __pthread_sig_debug;
233 #endif
235 static int rtsigs_initialized;
237 #include "testrtsig.h"
239 static void
240 init_rtsigs (void)
242 #if !__ASSUME_REALTIME_SIGNALS
243 if (!kernel_has_rtsig ())
245 current_rtmin = -1;
246 current_rtmax = -1;
247 # if __SIGRTMAX - __SIGRTMIN >= 3
248 __pthread_sig_restart = SIGUSR1;
249 __pthread_sig_cancel = SIGUSR2;
250 __pthread_sig_debug = 0;
251 # endif
253 else
254 #endif /* __ASSUME_REALTIME_SIGNALS */
256 #if __SIGRTMAX - __SIGRTMIN >= 3
257 current_rtmin = __SIGRTMIN + 3;
258 # if !__ASSUME_REALTIME_SIGNALS
259 __pthread_restart = __pthread_restart_new;
260 __pthread_suspend = __pthread_wait_for_restart_signal;
261 __pthread_timedsuspend = __pthread_timedsuspend_new;
262 # endif /* __ASSUME_REALTIME_SIGNALS */
263 #else
264 current_rtmin = __SIGRTMIN;
265 #endif
267 current_rtmax = __SIGRTMAX;
270 rtsigs_initialized = 1;
272 #endif
274 /* Return number of available real-time signal with highest priority. */
276 __libc_current_sigrtmin (void)
278 #ifdef __SIGRTMIN
279 if (!rtsigs_initialized)
280 init_rtsigs ();
281 #endif
282 return current_rtmin;
285 /* Return number of available real-time signal with lowest priority. */
287 __libc_current_sigrtmax (void)
289 #ifdef __SIGRTMIN
290 if (!rtsigs_initialized)
291 init_rtsigs ();
292 #endif
293 return current_rtmax;
296 /* Allocate real-time signal with highest/lowest available
297 priority. Please note that we don't use a lock since we assume
298 this function to be called at program start. */
300 __libc_allocate_rtsig (int high)
302 #ifndef __SIGRTMIN
303 return -1;
304 #else
305 if (!rtsigs_initialized)
306 init_rtsigs ();
307 if (current_rtmin == -1 || current_rtmin > current_rtmax)
308 /* We don't have anymore signal available. */
309 return -1;
311 return high ? current_rtmin++ : current_rtmax--;
312 #endif
315 /* The function we use to get the kernel revision. */
316 extern int __sysctl (int *name, int nlen, void *oldval, size_t *oldlenp,
317 void *newval, size_t newlen);
319 /* Test whether the machine has more than one processor. This is not the
320 best test but good enough. More complicated tests would require `malloc'
321 which is not available at that time. */
322 static int
323 is_smp_system (void)
325 static const int sysctl_args[] = { CTL_KERN, KERN_VERSION };
326 char buf[512];
327 size_t reslen = sizeof (buf);
329 /* Try reading the number using `sysctl' first. */
330 if (__sysctl ((int *) sysctl_args,
331 sizeof (sysctl_args) / sizeof (sysctl_args[0]),
332 buf, &reslen, NULL, 0) < 0)
334 /*This was not successful. Now try reading the /proc filesystem. */
335 int fd = __open ("/proc/sys/kernel/version", O_RDONLY);
336 if (fd == -1
337 || (reslen = __read (fd, buf, sizeof (buf))) <= 0)
338 /* This also didn't work. We give up and say it's a UP machine. */
339 buf[0] = '\0';
341 __close (fd);
344 return strstr (buf, "SMP") != NULL;
348 /* Initialize the pthread library.
349 Initialization is split in two functions:
350 - a constructor function that blocks the __pthread_sig_restart signal
351 (must do this very early, since the program could capture the signal
352 mask with e.g. sigsetjmp before creating the first thread);
353 - a regular function called from pthread_create when needed. */
355 static void pthread_initialize(void) __attribute__((constructor));
357 extern void *__dso_handle __attribute__ ((weak));
360 /* Do some minimal initialization which has to be done during the
361 startup of the C library. */
362 void
363 __pthread_initialize_minimal(void)
365 /* The errno/h_errno variable of the main thread are the global ones. */
366 __pthread_initial_thread.p_errnop = &_errno;
367 __pthread_initial_thread.p_h_errnop = &_h_errno;
368 /* If we have special thread_self processing, initialize that for the
369 main thread now. */
370 #ifdef INIT_THREAD_SELF
371 INIT_THREAD_SELF(&__pthread_initial_thread, 0);
372 #endif
376 static void pthread_initialize(void)
378 struct sigaction sa;
379 sigset_t mask;
380 struct rlimit limit;
381 int max_stack;
383 /* If already done (e.g. by a constructor called earlier!), bail out */
384 if (__pthread_initial_thread_bos != NULL) return;
385 #ifdef TEST_FOR_COMPARE_AND_SWAP
386 /* Test if compare-and-swap is available */
387 __pthread_has_cas = compare_and_swap_is_available();
388 #endif
389 /* For the initial stack, reserve at least STACK_SIZE bytes of stack
390 below the current stack address, and align that on a
391 STACK_SIZE boundary. */
392 __pthread_initial_thread_bos =
393 (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
394 /* Update the descriptor for the initial thread. */
395 __pthread_initial_thread.p_pid = __getpid();
396 /* Play with the stack size limit to make sure that no stack ever grows
397 beyond STACK_SIZE minus one page (to act as a guard page). */
398 getrlimit(RLIMIT_STACK, &limit);
399 #ifdef NEED_SEPARATE_REGISTER_STACK
400 /* STACK_SIZE bytes hold both the main stack and register backing
401 store. The rlimit value applies to each individually. */
402 max_stack = STACK_SIZE/2 - __getpagesize();
403 #else
404 max_stack = STACK_SIZE - __getpagesize();
405 #endif
406 if (limit.rlim_cur > max_stack) {
407 limit.rlim_cur = max_stack;
408 setrlimit(RLIMIT_STACK, &limit);
410 /* Likewise for the resolver state _res. */
411 __pthread_initial_thread.p_resp = &_res;
412 #ifdef __SIGRTMIN
413 /* Initialize real-time signals. */
414 init_rtsigs ();
415 #endif
416 /* Setup signal handlers for the initial thread.
417 Since signal handlers are shared between threads, these settings
418 will be inherited by all other threads. */
419 sa.sa_handler = pthread_handle_sigrestart;
420 sigemptyset(&sa.sa_mask);
421 sa.sa_flags = 0;
422 __libc_sigaction(__pthread_sig_restart, &sa, NULL);
423 sa.sa_handler = pthread_handle_sigcancel;
424 // sa.sa_flags = 0;
425 __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
426 if (__pthread_sig_debug > 0) {
427 sa.sa_handler = pthread_handle_sigdebug;
428 sigemptyset(&sa.sa_mask);
429 // sa.sa_flags = 0;
430 __libc_sigaction(__pthread_sig_debug, &sa, NULL);
432 /* Initially, block __pthread_sig_restart. Will be unblocked on demand. */
433 sigemptyset(&mask);
434 sigaddset(&mask, __pthread_sig_restart);
435 sigprocmask(SIG_BLOCK, &mask, NULL);
436 /* Register an exit function to kill all other threads. */
437 /* Do it early so that user-registered atexit functions are called
438 before pthread_exit_process. */
439 if (&__dso_handle != NULL)
440 /* The cast is a bit unclean. The function expects two arguments but
441 we can only pass one. Fortunately this is not a problem since the
442 second argument of `pthread_exit_process' is simply ignored. */
443 __cxa_atexit((void (*) (void *)) pthread_exit_process, NULL, __dso_handle);
444 else
445 __on_exit (pthread_exit_process, NULL);
446 /* How many processors. */
447 __pthread_smp_kernel = is_smp_system ();
450 void __pthread_initialize(void)
452 pthread_initialize();
455 int __pthread_initialize_manager(void)
457 int manager_pipe[2];
458 int pid;
459 struct pthread_request request;
461 /* If basic initialization not done yet (e.g. we're called from a
462 constructor run before our constructor), do it now */
463 if (__pthread_initial_thread_bos == NULL) pthread_initialize();
464 /* Setup stack for thread manager */
465 __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
466 if (__pthread_manager_thread_bos == NULL) return -1;
467 __pthread_manager_thread_tos =
468 __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;
469 /* Setup pipe to communicate with thread manager */
470 if (pipe(manager_pipe) == -1) {
471 free(__pthread_manager_thread_bos);
472 return -1;
474 /* Start the thread manager */
475 pid = 0;
476 if (__pthread_initial_thread.p_report_events)
478 /* It's a bit more complicated. We have to report the creation of
479 the manager thread. */
480 int idx = __td_eventword (TD_CREATE);
481 uint32_t mask = __td_eventmask (TD_CREATE);
483 if ((mask & (__pthread_threads_events.event_bits[idx]
484 | __pthread_initial_thread.p_eventbuf.eventmask.event_bits[idx]))
485 != 0)
487 __pthread_lock(__pthread_manager_thread.p_lock, NULL);
489 #ifdef NEED_SEPARATE_REGISTER_STACK
490 pid = __clone2(__pthread_manager_event,
491 (void **) __pthread_manager_thread_bos,
492 THREAD_MANAGER_STACK_SIZE,
493 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
494 (void *)(long)manager_pipe[0]);
495 #else
496 pid = __clone(__pthread_manager_event,
497 (void **) __pthread_manager_thread_tos,
498 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
499 (void *)(long)manager_pipe[0]);
500 #endif
502 if (pid != -1)
504 /* Now fill in the information about the new thread in
505 the newly created thread's data structure. We cannot let
506 the new thread do this since we don't know whether it was
507 already scheduled when we send the event. */
508 __pthread_manager_thread.p_eventbuf.eventdata =
509 &__pthread_manager_thread;
510 __pthread_manager_thread.p_eventbuf.eventnum = TD_CREATE;
511 __pthread_last_event = &__pthread_manager_thread;
512 __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
513 __pthread_manager_thread.p_pid = pid;
515 /* Now call the function which signals the event. */
516 __linuxthreads_create_event ();
519 /* Now restart the thread. */
520 __pthread_unlock(__pthread_manager_thread.p_lock);
524 if (pid == 0)
526 #ifdef NEED_SEPARATE_REGISTER_STACK
527 pid = __clone2(__pthread_manager, (void **) __pthread_manager_thread_bos,
528 THREAD_MANAGER_STACK_SIZE,
529 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
530 (void *)(long)manager_pipe[0]);
531 #else
532 pid = __clone(__pthread_manager, (void **) __pthread_manager_thread_tos,
533 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
534 (void *)(long)manager_pipe[0]);
535 #endif
537 if (pid == -1) {
538 free(__pthread_manager_thread_bos);
539 __libc_close(manager_pipe[0]);
540 __libc_close(manager_pipe[1]);
541 return -1;
543 __pthread_manager_request = manager_pipe[1]; /* writing end */
544 __pthread_manager_reader = manager_pipe[0]; /* reading end */
545 __pthread_manager_thread.p_tid = 2* PTHREAD_THREADS_MAX + 1;
546 __pthread_manager_thread.p_pid = pid;
547 /* Make gdb aware of new thread manager */
548 if (__pthread_threads_debug && __pthread_sig_debug > 0)
550 raise(__pthread_sig_debug);
551 /* We suspend ourself and gdb will wake us up when it is
552 ready to handle us. */
553 __pthread_wait_for_restart_signal(thread_self());
555 /* Synchronize debugging of the thread manager */
556 request.req_kind = REQ_DEBUG;
557 __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
558 return 0;
561 /* Thread creation */
563 int __pthread_create_2_1(pthread_t *thread, const pthread_attr_t *attr,
564 void * (*start_routine)(void *), void *arg)
566 pthread_descr self = thread_self();
567 struct pthread_request request;
568 int retval;
569 if (__pthread_manager_request < 0) {
570 if (__pthread_initialize_manager() < 0) return EAGAIN;
572 request.req_thread = self;
573 request.req_kind = REQ_CREATE;
574 request.req_args.create.attr = attr;
575 request.req_args.create.fn = start_routine;
576 request.req_args.create.arg = arg;
577 sigprocmask(SIG_SETMASK, (const sigset_t *) NULL,
578 &request.req_args.create.mask);
579 __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
580 suspend(self);
581 retval = THREAD_GETMEM(self, p_retcode);
582 if (retval == 0)
583 *thread = (pthread_t) THREAD_GETMEM(self, p_retval);
584 return retval;
587 versioned_symbol (libpthread, __pthread_create_2_1, pthread_create, GLIBC_2_1);
589 #if SHLIB_COMPAT (libpthread, GLIBC_2_0, GLIBC_2_1)
591 int __pthread_create_2_0(pthread_t *thread, const pthread_attr_t *attr,
592 void * (*start_routine)(void *), void *arg)
594 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
595 the old size and access to the new members might crash the program.
596 We convert the struct now. */
597 pthread_attr_t new_attr;
599 if (attr != NULL)
601 size_t ps = __getpagesize ();
603 memcpy (&new_attr, attr,
604 (size_t) &(((pthread_attr_t*)NULL)->__guardsize));
605 new_attr.__guardsize = ps;
606 new_attr.__stackaddr_set = 0;
607 new_attr.__stackaddr = NULL;
608 new_attr.__stacksize = STACK_SIZE - ps;
609 attr = &new_attr;
611 return __pthread_create_2_1 (thread, attr, start_routine, arg);
613 compat_symbol (libpthread, __pthread_create_2_0, pthread_create, GLIBC_2_0);
614 #endif
616 /* Simple operations on thread identifiers */
618 pthread_t pthread_self(void)
620 pthread_descr self = thread_self();
621 return THREAD_GETMEM(self, p_tid);
624 int pthread_equal(pthread_t thread1, pthread_t thread2)
626 return thread1 == thread2;
629 /* Helper function for thread_self in the case of user-provided stacks */
631 #ifndef THREAD_SELF
633 pthread_descr __pthread_find_self()
635 char * sp = CURRENT_STACK_FRAME;
636 pthread_handle h;
638 /* __pthread_handles[0] is the initial thread, __pthread_handles[1] is
639 the manager threads handled specially in thread_self(), so start at 2 */
640 h = __pthread_handles + 2;
641 while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;
642 return h->h_descr;
645 #endif
647 /* Thread scheduling */
649 int pthread_setschedparam(pthread_t thread, int policy,
650 const struct sched_param *param)
652 pthread_handle handle = thread_handle(thread);
653 pthread_descr th;
655 __pthread_lock(&handle->h_lock, NULL);
656 if (invalid_handle(handle, thread)) {
657 __pthread_unlock(&handle->h_lock);
658 return ESRCH;
660 th = handle->h_descr;
661 if (__sched_setscheduler(th->p_pid, policy, param) == -1) {
662 __pthread_unlock(&handle->h_lock);
663 return errno;
665 th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
666 __pthread_unlock(&handle->h_lock);
667 if (__pthread_manager_request >= 0)
668 __pthread_manager_adjust_prio(th->p_priority);
669 return 0;
672 int pthread_getschedparam(pthread_t thread, int *policy,
673 struct sched_param *param)
675 pthread_handle handle = thread_handle(thread);
676 int pid, pol;
678 __pthread_lock(&handle->h_lock, NULL);
679 if (invalid_handle(handle, thread)) {
680 __pthread_unlock(&handle->h_lock);
681 return ESRCH;
683 pid = handle->h_descr->p_pid;
684 __pthread_unlock(&handle->h_lock);
685 pol = __sched_getscheduler(pid);
686 if (pol == -1) return errno;
687 if (__sched_getparam(pid, param) == -1) return errno;
688 *policy = pol;
689 return 0;
692 int __pthread_yield ()
694 /* For now this is equivalent with the POSIX call. */
695 return sched_yield ();
697 weak_alias (__pthread_yield, pthread_yield)
699 /* Process-wide exit() request */
701 static void pthread_exit_process(int retcode, void *arg)
703 struct pthread_request request;
704 pthread_descr self = thread_self();
706 if (__pthread_manager_request >= 0) {
707 request.req_thread = self;
708 request.req_kind = REQ_PROCESS_EXIT;
709 request.req_args.exit.code = retcode;
710 __libc_write(__pthread_manager_request,
711 (char *) &request, sizeof(request));
712 suspend(self);
713 /* Main thread should accumulate times for thread manager and its
714 children, so that timings for main thread account for all threads. */
715 if (self == __pthread_main_thread)
716 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
720 /* The handler for the RESTART signal just records the signal received
721 in the thread descriptor, and optionally performs a siglongjmp
722 (for pthread_cond_timedwait). */
724 static void pthread_handle_sigrestart(int sig)
726 pthread_descr self = thread_self();
727 THREAD_SETMEM(self, p_signal, sig);
728 if (THREAD_GETMEM(self, p_signal_jmp) != NULL)
729 siglongjmp(*THREAD_GETMEM(self, p_signal_jmp), 1);
732 /* The handler for the CANCEL signal checks for cancellation
733 (in asynchronous mode), for process-wide exit and exec requests.
734 For the thread manager thread, redirect the signal to
735 __pthread_manager_sighandler. */
737 static void pthread_handle_sigcancel(int sig)
739 pthread_descr self = thread_self();
740 sigjmp_buf * jmpbuf;
742 if (self == &__pthread_manager_thread)
744 __pthread_manager_sighandler(sig);
745 return;
747 if (__pthread_exit_requested) {
748 /* Main thread should accumulate times for thread manager and its
749 children, so that timings for main thread account for all threads. */
750 if (self == __pthread_main_thread)
751 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
752 _exit(__pthread_exit_code);
754 if (THREAD_GETMEM(self, p_canceled)
755 && THREAD_GETMEM(self, p_cancelstate) == PTHREAD_CANCEL_ENABLE) {
756 if (THREAD_GETMEM(self, p_canceltype) == PTHREAD_CANCEL_ASYNCHRONOUS)
757 pthread_exit(PTHREAD_CANCELED);
758 jmpbuf = THREAD_GETMEM(self, p_cancel_jmp);
759 if (jmpbuf != NULL) {
760 THREAD_SETMEM(self, p_cancel_jmp, NULL);
761 siglongjmp(*jmpbuf, 1);
766 /* Handler for the DEBUG signal.
767 The debugging strategy is as follows:
768 On reception of a REQ_DEBUG request (sent by new threads created to
769 the thread manager under debugging mode), the thread manager throws
770 __pthread_sig_debug to itself. The debugger (if active) intercepts
771 this signal, takes into account new threads and continue execution
772 of the thread manager by propagating the signal because it doesn't
773 know what it is specifically done for. In the current implementation,
774 the thread manager simply discards it. */
776 static void pthread_handle_sigdebug(int sig)
778 /* Nothing */
781 /* Reset the state of the thread machinery after a fork().
782 Close the pipe used for requests and set the main thread to the forked
783 thread.
784 Notice that we can't free the stack segments, as the forked thread
785 may hold pointers into them. */
787 void __pthread_reset_main_thread()
789 pthread_descr self = thread_self();
791 if (__pthread_manager_request != -1) {
792 /* Free the thread manager stack */
793 free(__pthread_manager_thread_bos);
794 __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
795 /* Close the two ends of the pipe */
796 __libc_close(__pthread_manager_request);
797 __libc_close(__pthread_manager_reader);
798 __pthread_manager_request = __pthread_manager_reader = -1;
801 /* Update the pid of the main thread */
802 THREAD_SETMEM(self, p_pid, __getpid());
803 /* Make the forked thread the main thread */
804 __pthread_main_thread = self;
805 THREAD_SETMEM(self, p_nextlive, self);
806 THREAD_SETMEM(self, p_prevlive, self);
807 /* Now this thread modifies the global variables. */
808 THREAD_SETMEM(self, p_errnop, &_errno);
809 THREAD_SETMEM(self, p_h_errnop, &_h_errno);
810 THREAD_SETMEM(self, p_resp, &_res);
813 /* Process-wide exec() request */
815 void __pthread_kill_other_threads_np(void)
817 struct sigaction sa;
818 /* Terminate all other threads and thread manager */
819 pthread_exit_process(0, NULL);
820 /* Make current thread the main thread in case the calling thread
821 changes its mind, does not exec(), and creates new threads instead. */
822 __pthread_reset_main_thread();
824 /* Reset the signal handlers behaviour for the signals the
825 implementation uses since this would be passed to the new
826 process. */
827 sigemptyset(&sa.sa_mask);
828 sa.sa_flags = 0;
829 sa.sa_handler = SIG_DFL;
830 __libc_sigaction(__pthread_sig_restart, &sa, NULL);
831 __libc_sigaction(__pthread_sig_cancel, &sa, NULL);
832 if (__pthread_sig_debug > 0)
833 __libc_sigaction(__pthread_sig_debug, &sa, NULL);
835 weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
837 /* Concurrency symbol level. */
838 static int current_level;
840 int __pthread_setconcurrency(int level)
842 /* We don't do anything unless we have found a useful interpretation. */
843 current_level = level;
844 return 0;
846 weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
848 int __pthread_getconcurrency(void)
850 return current_level;
852 weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
854 void __pthread_set_own_extricate_if(pthread_descr self, pthread_extricate_if *peif)
856 __pthread_lock(self->p_lock, self);
857 THREAD_SETMEM(self, p_extricate, peif);
858 __pthread_unlock(self->p_lock);
861 /* Primitives for controlling thread execution */
863 void __pthread_wait_for_restart_signal(pthread_descr self)
865 sigset_t mask;
867 sigprocmask(SIG_SETMASK, NULL, &mask); /* Get current signal mask */
868 sigdelset(&mask, __pthread_sig_restart); /* Unblock the restart signal */
869 do {
870 self->p_signal = 0;
871 sigsuspend(&mask); /* Wait for signal */
872 } while (self->p_signal !=__pthread_sig_restart );
875 #if !__ASSUME_REALTIME_SIGNALS
876 /* The _old variants are for 2.0 and early 2.1 kernels which don't have RT
877 signals.
878 On these kernels, we use SIGUSR1 and SIGUSR2 for restart and cancellation.
879 Since the restart signal does not queue, we use an atomic counter to create
880 queuing semantics. This is needed to resolve a rare race condition in
881 pthread_cond_timedwait_relative. */
883 void __pthread_restart_old(pthread_descr th)
885 if (atomic_increment(&th->p_resume_count) == -1)
886 kill(th->p_pid, __pthread_sig_restart);
889 void __pthread_suspend_old(pthread_descr self)
891 if (atomic_decrement(&self->p_resume_count) <= 0)
892 __pthread_wait_for_restart_signal(self);
896 __pthread_timedsuspend_old(pthread_descr self, const struct timespec *abstime)
898 sigset_t unblock, initial_mask;
899 int was_signalled = 0;
900 sigjmp_buf jmpbuf;
902 if (atomic_decrement(&self->p_resume_count) == 0) {
903 /* Set up a longjmp handler for the restart signal, unblock
904 the signal and sleep. */
906 if (sigsetjmp(jmpbuf, 1) == 0) {
907 THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
908 THREAD_SETMEM(self, p_signal, 0);
909 /* Unblock the restart signal */
910 sigemptyset(&unblock);
911 sigaddset(&unblock, __pthread_sig_restart);
912 sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
914 while (1) {
915 struct timeval now;
916 struct timespec reltime;
918 /* Compute a time offset relative to now. */
919 __gettimeofday (&now, NULL);
920 reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
921 reltime.tv_sec = abstime->tv_sec - now.tv_sec;
922 if (reltime.tv_nsec < 0) {
923 reltime.tv_nsec += 1000000000;
924 reltime.tv_sec -= 1;
927 /* Sleep for the required duration. If woken by a signal,
928 resume waiting as required by Single Unix Specification. */
929 if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
930 break;
933 /* Block the restart signal again */
934 sigprocmask(SIG_SETMASK, &initial_mask, NULL);
935 was_signalled = 0;
936 } else {
937 was_signalled = 1;
939 THREAD_SETMEM(self, p_signal_jmp, NULL);
942 /* Now was_signalled is true if we exited the above code
943 due to the delivery of a restart signal. In that case,
944 we know we have been dequeued and resumed and that the
945 resume count is balanced. Otherwise, there are some
946 cases to consider. First, try to bump up the resume count
947 back to zero. If it goes to 1, it means restart() was
948 invoked on this thread. The signal must be consumed
949 and the count bumped down and everything is cool. We
950 can return a 1 to the caller.
951 Otherwise, no restart was delivered yet, so a potential
952 race exists; we return a 0 to the caller which must deal
953 with this race in an appropriate way; for example by
954 atomically removing the thread from consideration for a
955 wakeup---if such a thing fails, it means a restart is
956 being delivered. */
958 if (!was_signalled) {
959 if (atomic_increment(&self->p_resume_count) != -1) {
960 __pthread_wait_for_restart_signal(self);
961 atomic_decrement(&self->p_resume_count); /* should be zero now! */
962 /* woke spontaneously and consumed restart signal */
963 return 1;
965 /* woke spontaneously but did not consume restart---caller must resolve */
966 return 0;
968 /* woken due to restart signal */
969 return 1;
971 #endif /* __ASSUME_REALTIME_SIGNALS */
973 void __pthread_restart_new(pthread_descr th)
975 kill(th->p_pid, __pthread_sig_restart);
978 /* There is no __pthread_suspend_new because it would just
979 be a wasteful wrapper for __pthread_wait_for_restart_signal */
982 __pthread_timedsuspend_new(pthread_descr self, const struct timespec *abstime)
984 sigset_t unblock, initial_mask;
985 int was_signalled = 0;
986 sigjmp_buf jmpbuf;
988 if (sigsetjmp(jmpbuf, 1) == 0) {
989 THREAD_SETMEM(self, p_signal_jmp, &jmpbuf);
990 THREAD_SETMEM(self, p_signal, 0);
991 /* Unblock the restart signal */
992 sigemptyset(&unblock);
993 sigaddset(&unblock, __pthread_sig_restart);
994 sigprocmask(SIG_UNBLOCK, &unblock, &initial_mask);
996 while (1) {
997 struct timeval now;
998 struct timespec reltime;
1000 /* Compute a time offset relative to now. */
1001 __gettimeofday (&now, NULL);
1002 reltime.tv_nsec = abstime->tv_nsec - now.tv_usec * 1000;
1003 reltime.tv_sec = abstime->tv_sec - now.tv_sec;
1004 if (reltime.tv_nsec < 0) {
1005 reltime.tv_nsec += 1000000000;
1006 reltime.tv_sec -= 1;
1009 /* Sleep for the required duration. If woken by a signal,
1010 resume waiting as required by Single Unix Specification. */
1011 if (reltime.tv_sec < 0 || __libc_nanosleep(&reltime, NULL) == 0)
1012 break;
1015 /* Block the restart signal again */
1016 sigprocmask(SIG_SETMASK, &initial_mask, NULL);
1017 was_signalled = 0;
1018 } else {
1019 was_signalled = 1;
1021 THREAD_SETMEM(self, p_signal_jmp, NULL);
1023 /* Now was_signalled is true if we exited the above code
1024 due to the delivery of a restart signal. In that case,
1025 everything is cool. We have been removed from whatever
1026 we were waiting on by the other thread, and consumed its signal.
1028 Otherwise we this thread woke up spontaneously, or due to a signal other
1029 than restart. This is an ambiguous case that must be resolved by
1030 the caller; the thread is still eligible for a restart wakeup
1031 so there is a race. */
1033 return was_signalled;
1037 /* Debugging aid */
1039 #ifdef DEBUG
1040 #include <stdarg.h>
1042 void __pthread_message(char * fmt, ...)
1044 char buffer[1024];
1045 va_list args;
1046 sprintf(buffer, "%05d : ", __getpid());
1047 va_start(args, fmt);
1048 vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
1049 va_end(args);
1050 __libc_write(2, buffer, strlen(buffer));
1053 #endif
1056 #ifndef SHARED
1057 /* We need a hook to force the cancelation wrappers to be linked in when
1058 static libpthread is used. */
1059 extern const int __pthread_provide_wrappers;
1060 static const int *const __pthread_require_wrappers =
1061 &__pthread_provide_wrappers;
1062 #endif