Update.
[glibc.git] / linuxthreads / pthread.c
bloba7511f7eeebf25fa4b47f22505814bf0dfe84adc
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 "pthread.h"
26 #include "internals.h"
27 #include "spinlock.h"
28 #include "restart.h"
30 /* Descriptor of the initial thread */
32 struct _pthread_descr_struct __pthread_initial_thread = {
33 &__pthread_initial_thread, /* pthread_descr p_nextlive */
34 &__pthread_initial_thread, /* pthread_descr p_prevlive */
35 NULL, /* pthread_descr p_nextwaiting */
36 PTHREAD_THREADS_MAX, /* pthread_t p_tid */
37 0, /* int p_pid */
38 0, /* int p_priority */
39 &__pthread_handles[0].h_lock, /* struct _pthread_fastlock * p_lock */
40 0, /* int p_signal */
41 NULL, /* sigjmp_buf * p_signal_buf */
42 NULL, /* sigjmp_buf * p_cancel_buf */
43 0, /* char p_terminated */
44 0, /* char p_detached */
45 0, /* char p_exited */
46 NULL, /* void * p_retval */
47 0, /* int p_retval */
48 NULL, /* pthread_descr p_joining */
49 NULL, /* struct _pthread_cleanup_buffer * p_cleanup */
50 0, /* char p_cancelstate */
51 0, /* char p_canceltype */
52 0, /* char p_canceled */
53 NULL, /* int *p_errnop */
54 0, /* int p_errno */
55 NULL, /* int *p_h_errnop */
56 0, /* int p_h_errno */
57 NULL, /* char * p_in_sighandler */
58 0, /* char p_sigwaiting */
59 PTHREAD_START_ARGS_INITIALIZER, /* struct pthread_start_args p_start_args */
60 {NULL} /* void * p_specific[PTHREAD_KEYS_MAX] */
63 /* Descriptor of the manager thread; none of this is used but the error
64 variables, the p_pid and p_priority fields,
65 and the address for identification. */
67 struct _pthread_descr_struct __pthread_manager_thread = {
68 NULL, /* pthread_descr p_nextlive */
69 NULL, /* pthread_descr p_prevlive */
70 NULL, /* pthread_descr p_nextwaiting */
71 0, /* int p_tid */
72 0, /* int p_pid */
73 0, /* int p_priority */
74 NULL, /* struct _pthread_fastlock * p_lock */
75 0, /* int p_signal */
76 NULL, /* sigjmp_buf * p_signal_buf */
77 NULL, /* sigjmp_buf * p_cancel_buf */
78 0, /* char p_terminated */
79 0, /* char p_detached */
80 0, /* char p_exited */
81 NULL, /* void * p_retval */
82 0, /* int p_retval */
83 NULL, /* pthread_descr p_joining */
84 NULL, /* struct _pthread_cleanup_buffer * p_cleanup */
85 0, /* char p_cancelstate */
86 0, /* char p_canceltype */
87 0, /* char p_canceled */
88 NULL, /* int *p_errnop */
89 0, /* int p_errno */
90 NULL, /* int *p_h_errnop */
91 0, /* int p_h_errno */
92 NULL, /* char * p_in_sighandler */
93 0, /* char p_sigwaiting */
94 PTHREAD_START_ARGS_INITIALIZER, /* struct pthread_start_args p_start_args */
95 {NULL} /* void * p_specific[PTHREAD_KEYS_MAX] */
98 /* Pointer to the main thread (the father of the thread manager thread) */
99 /* Originally, this is the initial thread, but this changes after fork() */
101 pthread_descr __pthread_main_thread = &__pthread_initial_thread;
103 /* Limit between the stack of the initial thread (above) and the
104 stacks of other threads (below). Aligned on a STACK_SIZE boundary. */
106 char *__pthread_initial_thread_bos = NULL;
108 /* File descriptor for sending requests to the thread manager. */
109 /* Initially -1, meaning that the thread manager is not running. */
111 int __pthread_manager_request = -1;
113 /* Other end of the pipe for sending requests to the thread manager. */
115 int __pthread_manager_reader;
117 /* Limits of the thread manager stack */
119 char *__pthread_manager_thread_bos = NULL;
120 char *__pthread_manager_thread_tos = NULL;
122 /* For process-wide exit() */
124 int __pthread_exit_requested = 0;
125 int __pthread_exit_code = 0;
127 /* Communicate relevant LinuxThreads constants to gdb */
129 const int __pthread_threads_max = PTHREAD_THREADS_MAX;
130 const int __pthread_sizeof_handle = sizeof(struct pthread_handle_struct);
131 const int __pthread_offsetof_descr = offsetof(struct pthread_handle_struct,
132 h_descr);
133 const int __pthread_offsetof_pid = offsetof(struct _pthread_descr_struct,
134 p_pid);
136 /* Signal numbers used for the communication. */
137 int __pthread_sig_restart;
138 int __pthread_sig_cancel;
140 /* These variables are used by the setup code. */
141 extern int _errno;
142 extern int _h_errno;
144 /* Forward declarations */
146 static void pthread_exit_process(int retcode, void *arg);
147 static void pthread_handle_sigcancel(int sig);
148 static void pthread_handle_sigrestart(int sig);
150 /* Initialize the pthread library.
151 Initialization is split in two functions:
152 - a constructor function that blocks the PTHREAD_SIG_RESTART signal
153 (must do this very early, since the program could capture the signal
154 mask with e.g. sigsetjmp before creating the first thread);
155 - a regular function called from pthread_create when needed. */
157 static void pthread_initialize(void) __attribute__((constructor));
159 static void pthread_initialize(void)
161 struct sigaction sa;
162 sigset_t mask;
164 /* If already done (e.g. by a constructor called earlier!), bail out */
165 if (__pthread_initial_thread_bos != NULL) return;
166 #ifdef TEST_FOR_COMPARE_AND_SWAP
167 /* Test if compare-and-swap is available */
168 __pthread_has_cas = compare_and_swap_is_available();
169 #endif
170 /* For the initial stack, reserve at least STACK_SIZE bytes of stack
171 below the current stack address, and align that on a
172 STACK_SIZE boundary. */
173 __pthread_initial_thread_bos =
174 (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
175 /* Update the descriptor for the initial thread. */
176 __pthread_initial_thread.p_pid = __getpid();
177 /* If we have special thread_self processing, initialize that for the
178 main thread now. */
179 #ifdef INIT_THREAD_SELF
180 INIT_THREAD_SELF(&__pthread_initial_thread);
181 #endif
182 /* The errno/h_errno variable of the main thread are the global ones. */
183 __pthread_initial_thread.p_errnop = &_errno;
184 __pthread_initial_thread.p_h_errnop = &_h_errno;
185 #ifdef SIGRTMIN
186 /* Allocate the signals used. */
187 __pthread_sig_restart = __libc_allocate_rtsig (1);
188 __pthread_sig_cancel = __libc_allocate_rtsig (1);
189 if (__pthread_sig_restart < 0 || __pthread_sig_cancel < 0)
191 /* The kernel does not support real-time signals. Use as before
192 the available signals in the fixed set. */
193 __pthread_sig_restart = SIGUSR1;
194 __pthread_sig_cancel = SIGUSR2;
196 #endif
197 /* Setup signal handlers for the initial thread.
198 Since signal handlers are shared between threads, these settings
199 will be inherited by all other threads. */
200 sa.sa_handler = pthread_handle_sigrestart;
201 sigemptyset(&sa.sa_mask);
202 sa.sa_flags = SA_RESTART; /* does not matter for regular threads, but
203 better for the thread manager */
204 __sigaction(PTHREAD_SIG_RESTART, &sa, NULL);
205 sa.sa_handler = pthread_handle_sigcancel;
206 sa.sa_flags = 0;
207 __sigaction(PTHREAD_SIG_CANCEL, &sa, NULL);
209 /* Initially, block PTHREAD_SIG_RESTART. Will be unblocked on demand. */
210 sigemptyset(&mask);
211 sigaddset(&mask, PTHREAD_SIG_RESTART);
212 sigprocmask(SIG_BLOCK, &mask, NULL);
213 /* Register an exit function to kill all other threads. */
214 /* Do it early so that user-registered atexit functions are called
215 before pthread_exit_process. */
216 __on_exit(pthread_exit_process, NULL);
219 void __pthread_initialize(void)
221 pthread_initialize();
224 int __pthread_initialize_manager(void)
226 int manager_pipe[2];
227 int pid;
228 struct pthread_request request;
230 /* If basic initialization not done yet (e.g. we're called from a
231 constructor run before our constructor), do it now */
232 if (__pthread_initial_thread_bos == NULL) pthread_initialize();
233 /* Setup stack for thread manager */
234 __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
235 if (__pthread_manager_thread_bos == NULL) return -1;
236 __pthread_manager_thread_tos =
237 __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;
238 /* Setup pipe to communicate with thread manager */
239 if (pipe(manager_pipe) == -1) {
240 free(__pthread_manager_thread_bos);
241 return -1;
243 /* Start the thread manager */
244 pid = __clone(__pthread_manager, (void **) __pthread_manager_thread_tos,
245 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
246 (void *)(long)manager_pipe[0]);
247 if (pid == -1) {
248 free(__pthread_manager_thread_bos);
249 __libc_close(manager_pipe[0]);
250 __libc_close(manager_pipe[1]);
251 return -1;
253 __pthread_manager_request = manager_pipe[1]; /* writing end */
254 __pthread_manager_reader = manager_pipe[0]; /* reading end */
255 __pthread_manager_thread.p_pid = pid;
256 /* Make gdb aware of new thread manager */
257 if (__pthread_threads_debug) raise(PTHREAD_SIG_CANCEL);
258 /* Synchronize debugging of the thread manager */
259 request.req_kind = REQ_DEBUG;
260 __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
261 return 0;
264 /* Thread creation */
266 int __pthread_create_2_1(pthread_t *thread, const pthread_attr_t *attr,
267 void * (*start_routine)(void *), void *arg)
269 pthread_descr self = thread_self();
270 struct pthread_request request;
271 if (__pthread_manager_request < 0) {
272 if (__pthread_initialize_manager() < 0) return EAGAIN;
274 request.req_thread = self;
275 request.req_kind = REQ_CREATE;
276 request.req_args.create.attr = attr;
277 request.req_args.create.fn = start_routine;
278 request.req_args.create.arg = arg;
279 sigprocmask(SIG_SETMASK, (const sigset_t *) NULL,
280 &request.req_args.create.mask);
281 __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
282 suspend(self);
283 if (self->p_retcode == 0) *thread = (pthread_t) self->p_retval;
284 return self->p_retcode;
287 #if defined HAVE_ELF && defined PIC && defined DO_VERSIONING
288 default_symbol_version (__pthread_create_2_1, pthread_create, GLIBC_2.1);
290 int __pthread_create_2_0(pthread_t *thread, const pthread_attr_t *attr,
291 void * (*start_routine)(void *), void *arg)
293 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
294 the old size and access to the new members might crash the program.
295 We convert the struct now. */
296 pthread_attr_t new_attr;
298 if (attr != NULL)
300 size_t ps = __getpagesize ();
302 memcpy (&new_attr, attr, (size_t) &(((pthread_attr_t*)NULL)->guardsize));
303 new_attr.guardsize = ps;
304 new_attr.stackaddr_set = 0;
305 new_attr.stackaddr = NULL;
306 new_attr.stacksize = STACK_SIZE - ps;
307 attr = &new_attr;
309 return __pthread_create_2_1 (thread, attr, start_routine, arg);
311 symbol_version (__pthread_create_2_0, pthread_create, GLIBC_2.0);
312 #else
313 strong_alias (__pthread_create_2_1, pthread_create)
314 #endif
316 /* Simple operations on thread identifiers */
318 pthread_t pthread_self(void)
320 pthread_descr self = thread_self();
321 return self->p_tid;
324 int pthread_equal(pthread_t thread1, pthread_t thread2)
326 return thread1 == thread2;
329 /* Helper function for thread_self in the case of user-provided stacks */
331 #ifndef THREAD_SELF
333 pthread_descr __pthread_find_self()
335 char * sp = CURRENT_STACK_FRAME;
336 pthread_handle h;
338 /* __pthread_handles[0] is the initial thread, handled specially in
339 thread_self(), so start at 1 */
340 h = __pthread_handles + 1;
341 while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;
342 return h->h_descr;
345 #endif
347 /* Thread scheduling */
349 int pthread_setschedparam(pthread_t thread, int policy,
350 const struct sched_param *param)
352 pthread_handle handle = thread_handle(thread);
353 pthread_descr th;
355 __pthread_lock(&handle->h_lock);
356 if (invalid_handle(handle, thread)) {
357 __pthread_unlock(&handle->h_lock);
358 return ESRCH;
360 th = handle->h_descr;
361 if (__sched_setscheduler(th->p_pid, policy, param) == -1) {
362 __pthread_unlock(&handle->h_lock);
363 return errno;
365 th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
366 __pthread_unlock(&handle->h_lock);
367 if (__pthread_manager_request >= 0)
368 __pthread_manager_adjust_prio(th->p_priority);
369 return 0;
372 int pthread_getschedparam(pthread_t thread, int *policy,
373 struct sched_param *param)
375 pthread_handle handle = thread_handle(thread);
376 int pid, pol;
378 __pthread_lock(&handle->h_lock);
379 if (invalid_handle(handle, thread)) {
380 __pthread_unlock(&handle->h_lock);
381 return ESRCH;
383 pid = handle->h_descr->p_pid;
384 __pthread_unlock(&handle->h_lock);
385 pol = __sched_getscheduler(pid);
386 if (pol == -1) return errno;
387 if (__sched_getparam(pid, param) == -1) return errno;
388 *policy = pol;
389 return 0;
392 /* Process-wide exit() request */
394 static void pthread_exit_process(int retcode, void *arg)
396 struct pthread_request request;
397 pthread_descr self = thread_self();
399 if (__pthread_manager_request >= 0) {
400 request.req_thread = self;
401 request.req_kind = REQ_PROCESS_EXIT;
402 request.req_args.exit.code = retcode;
403 __libc_write(__pthread_manager_request,
404 (char *) &request, sizeof(request));
405 suspend(self);
406 /* Main thread should accumulate times for thread manager and its
407 children, so that timings for main thread account for all threads. */
408 if (self == __pthread_main_thread)
409 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
413 /* The handler for the RESTART signal just records the signal received
414 in the thread descriptor, and optionally performs a siglongjmp
415 (for pthread_cond_timedwait).
416 For the thread manager thread, redirect the signal to
417 __pthread_manager_sighandler. */
419 static void pthread_handle_sigrestart(int sig)
421 pthread_descr self = thread_self();
422 if (self == &__pthread_manager_thread) {
423 __pthread_manager_sighandler(sig);
424 } else {
425 self->p_signal = sig;
426 if (self->p_signal_jmp != NULL) siglongjmp(*self->p_signal_jmp, 1);
430 /* The handler for the CANCEL signal checks for cancellation
431 (in asynchronous mode), for process-wide exit and exec requests.
432 For the thread manager thread, we ignore the signal.
433 The debugging strategy is as follows:
434 On reception of a REQ_DEBUG request (sent by new threads created to
435 the thread manager under debugging mode), the thread manager throws
436 PTHREAD_SIG_CANCEL to itself. The debugger (if active) intercepts
437 this signal, takes into account new threads and continue execution
438 of the thread manager by propagating the signal because it doesn't
439 know what it is specifically done for. In the current implementation,
440 the thread manager simply discards it. */
442 static void pthread_handle_sigcancel(int sig)
444 pthread_descr self = thread_self();
445 sigjmp_buf * jmpbuf;
447 if (self == &__pthread_manager_thread)
448 return;
449 if (__pthread_exit_requested) {
450 /* Main thread should accumulate times for thread manager and its
451 children, so that timings for main thread account for all threads. */
452 if (self == __pthread_main_thread)
453 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
454 _exit(__pthread_exit_code);
456 if (self->p_canceled && self->p_cancelstate == PTHREAD_CANCEL_ENABLE) {
457 if (self->p_canceltype == PTHREAD_CANCEL_ASYNCHRONOUS)
458 pthread_exit(PTHREAD_CANCELED);
459 jmpbuf = self->p_cancel_jmp;
460 if (jmpbuf != NULL) {
461 self->p_cancel_jmp = NULL;
462 siglongjmp(*jmpbuf, 1);
467 /* Reset the state of the thread machinery after a fork().
468 Close the pipe used for requests and set the main thread to the forked
469 thread.
470 Notice that we can't free the stack segments, as the forked thread
471 may hold pointers into them. */
473 void __pthread_reset_main_thread()
475 pthread_descr self = thread_self();
477 if (__pthread_manager_request != -1) {
478 /* Free the thread manager stack */
479 free(__pthread_manager_thread_bos);
480 __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
481 /* Close the two ends of the pipe */
482 __libc_close(__pthread_manager_request);
483 __libc_close(__pthread_manager_reader);
484 __pthread_manager_request = __pthread_manager_reader = -1;
486 /* Update the pid of the main thread */
487 self->p_pid = __getpid();
488 /* Make the forked thread the main thread */
489 __pthread_main_thread = self;
490 self->p_nextlive = self;
491 self->p_prevlive = self;
492 /* Now this thread modifies the global variables. */
493 self->p_errnop = &_errno;
494 self->p_h_errnop = &_h_errno;
497 /* Process-wide exec() request */
499 void __pthread_kill_other_threads_np(void)
501 /* Terminate all other threads and thread manager */
502 pthread_exit_process(0, NULL);
503 /* Make current thread the main thread in case the calling thread
504 changes its mind, does not exec(), and creates new threads instead. */
505 __pthread_reset_main_thread();
507 weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
509 /* Concurrency symbol level. */
510 static int current_level;
512 int __pthread_setconcurrency(int level)
514 /* We don't do anything unless we have found a useful interpretation. */
515 current_level = level;
516 return 0;
518 weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
520 int __pthread_getconcurrency(void)
522 return current_level;
524 weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
526 /* Debugging aid */
528 #ifdef DEBUG
529 #include <stdarg.h>
531 void __pthread_message(char * fmt, ...)
533 char buffer[1024];
534 va_list args;
535 sprintf(buffer, "%05d : ", __getpid());
536 va_start(args, fmt);
537 vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
538 va_end(args);
539 __libc_write(2, buffer, strlen(buffer));
542 #endif
545 #ifndef PIC
546 /* We need a hook to force the cancelation wrappers to be linked in when
547 static libpthread is used. */
548 extern const int __pthread_provide_wrappers;
549 static const int *const __pthread_require_wrappers =
550 &__pthread_provide_wrappers;
551 #endif