1 /* Linuxthreads - a simple clone()-based implementation of Posix */
2 /* threads for Linux. */
3 /* Copyright (C) 1996 Xavier Leroy (Xavier.Leroy@inria.fr) */
5 /* This program is free software; you can redistribute it and/or */
6 /* modify it under the terms of the GNU Library General Public License */
7 /* as published by the Free Software Foundation; either version 2 */
8 /* of the License, or (at your option) any later version. */
10 /* This program is distributed in the hope that it will be useful, */
11 /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
12 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
13 /* GNU Library General Public License for more details. */
15 /* Thread creation, initialization, and basic low-level routines */
25 #include "internals.h"
29 /* Descriptor of the initial thread */
31 struct _pthread_descr_struct __pthread_initial_thread = {
32 &__pthread_initial_thread, /* pthread_descr p_nextlive */
33 &__pthread_initial_thread, /* pthread_descr p_prevlive */
34 NULL, /* pthread_descr p_nextwaiting */
35 PTHREAD_THREADS_MAX, /* pthread_t p_tid */
37 0, /* int p_priority */
38 &__pthread_handles[0].h_lock, /* struct _pthread_fastlock * p_lock */
40 NULL, /* sigjmp_buf * p_signal_buf */
41 NULL, /* sigjmp_buf * p_cancel_buf */
42 0, /* char p_terminated */
43 0, /* char p_detached */
44 0, /* char p_exited */
45 NULL, /* void * p_retval */
47 NULL, /* pthread_descr p_joining */
48 NULL, /* struct _pthread_cleanup_buffer * p_cleanup */
49 0, /* char p_cancelstate */
50 0, /* char p_canceltype */
51 0, /* char p_canceled */
52 NULL, /* int *p_errnop */
54 NULL, /* int *p_h_errnop */
55 0, /* int p_h_errno */
56 NULL, /* char * p_in_sighandler */
57 0, /* char p_sigwaiting */
58 PTHREAD_START_ARGS_INITIALIZER, /* struct pthread_start_args p_start_args */
59 {NULL} /* void * p_specific[PTHREAD_KEYS_MAX] */
62 /* Descriptor of the manager thread; none of this is used but the error
63 variables, the p_pid and p_priority fields,
64 and the address for identification. */
66 struct _pthread_descr_struct __pthread_manager_thread = {
67 NULL, /* pthread_descr p_nextlive */
68 NULL, /* pthread_descr p_prevlive */
69 NULL, /* pthread_descr p_nextwaiting */
72 0, /* int p_priority */
73 NULL, /* struct _pthread_fastlock * p_lock */
75 NULL, /* sigjmp_buf * p_signal_buf */
76 NULL, /* sigjmp_buf * p_cancel_buf */
77 0, /* char p_terminated */
78 0, /* char p_detached */
79 0, /* char p_exited */
80 NULL, /* void * p_retval */
82 NULL, /* pthread_descr p_joining */
83 NULL, /* struct _pthread_cleanup_buffer * p_cleanup */
84 0, /* char p_cancelstate */
85 0, /* char p_canceltype */
86 0, /* char p_canceled */
87 NULL, /* int *p_errnop */
89 NULL, /* int *p_h_errnop */
90 0, /* int p_h_errno */
91 NULL, /* char * p_in_sighandler */
92 0, /* char p_sigwaiting */
93 PTHREAD_START_ARGS_INITIALIZER, /* struct pthread_start_args p_start_args */
94 {NULL} /* void * p_specific[PTHREAD_KEYS_MAX] */
97 /* Pointer to the main thread (the father of the thread manager thread) */
98 /* Originally, this is the initial thread, but this changes after fork() */
100 pthread_descr __pthread_main_thread = &__pthread_initial_thread;
102 /* Limit between the stack of the initial thread (above) and the
103 stacks of other threads (below). Aligned on a STACK_SIZE boundary. */
105 char *__pthread_initial_thread_bos = NULL;
107 /* File descriptor for sending requests to the thread manager. */
108 /* Initially -1, meaning that the thread manager is not running. */
110 int __pthread_manager_request = -1;
112 /* Other end of the pipe for sending requests to the thread manager. */
114 int __pthread_manager_reader;
116 /* Limits of the thread manager stack */
118 char *__pthread_manager_thread_bos = NULL;
119 char *__pthread_manager_thread_tos = NULL;
121 /* For process-wide exit() */
123 int __pthread_exit_requested = 0;
124 int __pthread_exit_code = 0;
126 /* Communicate relevant LinuxThreads constants to gdb */
128 const int __pthread_threads_max = PTHREAD_THREADS_MAX;
129 const int __pthread_sizeof_handle = sizeof(struct pthread_handle_struct);
130 const int __pthread_offsetof_descr = offsetof(struct pthread_handle_struct,
132 const int __pthread_offsetof_pid = offsetof(struct _pthread_descr_struct,
135 /* Signal numbers used for the communication. */
136 int __pthread_sig_restart;
137 int __pthread_sig_cancel;
139 /* These variables are used by the setup code. */
143 /* Forward declarations */
145 static void pthread_exit_process(int retcode, void *arg);
146 static void pthread_handle_sigcancel(int sig);
147 static void pthread_handle_sigrestart(int sig);
149 /* Initialize the pthread library.
150 Initialization is split in two functions:
151 - a constructor function that blocks the PTHREAD_SIG_RESTART signal
152 (must do this very early, since the program could capture the signal
153 mask with e.g. sigsetjmp before creating the first thread);
154 - a regular function called from pthread_create when needed. */
156 static void pthread_initialize(void) __attribute__((constructor));
158 static void pthread_initialize(void)
163 /* If already done (e.g. by a constructor called earlier!), bail out */
164 if (__pthread_initial_thread_bos != NULL) return;
165 #ifdef TEST_FOR_COMPARE_AND_SWAP
166 /* Test if compare-and-swap is available */
167 __pthread_has_cas = compare_and_swap_is_available();
169 /* For the initial stack, reserve at least STACK_SIZE bytes of stack
170 below the current stack address, and align that on a
171 STACK_SIZE boundary. */
172 __pthread_initial_thread_bos =
173 (char *)(((long)CURRENT_STACK_FRAME - 2 * STACK_SIZE) & ~(STACK_SIZE - 1));
174 /* Update the descriptor for the initial thread. */
175 __pthread_initial_thread.p_pid = __getpid();
176 /* If we have special thread_self processing, initialize that for the
178 #ifdef INIT_THREAD_SELF
179 INIT_THREAD_SELF(&__pthread_initial_thread);
181 /* The errno/h_errno variable of the main thread are the global ones. */
182 __pthread_initial_thread.p_errnop = &_errno;
183 __pthread_initial_thread.p_h_errnop = &_h_errno;
185 /* Allocate the signals used. */
186 __pthread_sig_restart = __libc_allocate_rtsig (1);
187 __pthread_sig_cancel = __libc_allocate_rtsig (1);
188 if (__pthread_sig_restart < 0 || __pthread_sig_cancel < 0)
190 /* The kernel does not support real-time signals. Use as before
191 the available signals in the fixed set. */
192 __pthread_sig_restart = SIGUSR1;
193 __pthread_sig_cancel = SIGUSR2;
196 /* Setup signal handlers for the initial thread.
197 Since signal handlers are shared between threads, these settings
198 will be inherited by all other threads. */
199 sa.sa_handler = pthread_handle_sigrestart;
200 sigemptyset(&sa.sa_mask);
201 sa.sa_flags = SA_RESTART; /* does not matter for regular threads, but
202 better for the thread manager */
203 __sigaction(PTHREAD_SIG_RESTART, &sa, NULL);
204 sa.sa_handler = pthread_handle_sigcancel;
206 __sigaction(PTHREAD_SIG_CANCEL, &sa, NULL);
208 /* Initially, block PTHREAD_SIG_RESTART. Will be unblocked on demand. */
210 sigaddset(&mask, PTHREAD_SIG_RESTART);
211 sigprocmask(SIG_BLOCK, &mask, NULL);
212 /* Register an exit function to kill all other threads. */
213 /* Do it early so that user-registered atexit functions are called
214 before pthread_exit_process. */
215 __on_exit(pthread_exit_process, NULL);
218 void __pthread_initialize(void)
220 pthread_initialize();
223 int __pthread_initialize_manager(void)
227 struct pthread_request request;
229 /* If basic initialization not done yet (e.g. we're called from a
230 constructor run before our constructor), do it now */
231 if (__pthread_initial_thread_bos == NULL) pthread_initialize();
232 /* Setup stack for thread manager */
233 __pthread_manager_thread_bos = malloc(THREAD_MANAGER_STACK_SIZE);
234 if (__pthread_manager_thread_bos == NULL) return -1;
235 __pthread_manager_thread_tos =
236 __pthread_manager_thread_bos + THREAD_MANAGER_STACK_SIZE;
237 /* Setup pipe to communicate with thread manager */
238 if (pipe(manager_pipe) == -1) {
239 free(__pthread_manager_thread_bos);
242 /* Start the thread manager */
243 pid = __clone(__pthread_manager, (void **) __pthread_manager_thread_tos,
244 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND,
245 (void *)(long)manager_pipe[0]);
247 free(__pthread_manager_thread_bos);
248 __libc_close(manager_pipe[0]);
249 __libc_close(manager_pipe[1]);
252 __pthread_manager_request = manager_pipe[1]; /* writing end */
253 __pthread_manager_reader = manager_pipe[0]; /* reading end */
254 __pthread_manager_thread.p_pid = pid;
255 /* Make gdb aware of new thread manager */
256 if (__pthread_threads_debug) raise(PTHREAD_SIG_CANCEL);
257 /* Synchronize debugging of the thread manager */
258 request.req_kind = REQ_DEBUG;
259 __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
263 /* Thread creation */
265 int __pthread_create_2_1(pthread_t *thread, const pthread_attr_t *attr,
266 void * (*start_routine)(void *), void *arg)
268 pthread_descr self = thread_self();
269 struct pthread_request request;
270 if (__pthread_manager_request < 0) {
271 if (__pthread_initialize_manager() < 0) return EAGAIN;
273 request.req_thread = self;
274 request.req_kind = REQ_CREATE;
275 request.req_args.create.attr = attr;
276 request.req_args.create.fn = start_routine;
277 request.req_args.create.arg = arg;
278 sigprocmask(SIG_SETMASK, (const sigset_t *) NULL,
279 &request.req_args.create.mask);
280 __libc_write(__pthread_manager_request, (char *) &request, sizeof(request));
282 if (self->p_retcode == 0) *thread = (pthread_t) self->p_retval;
283 return self->p_retcode;
286 #if defined HAVE_ELF && defined PIC && defined DO_VERSIONING
287 default_symbol_version (__pthread_create_2_1, pthread_create, GLIBC_2.1);
289 int __pthread_create_2_0(pthread_t *thread, const pthread_attr_t *attr,
290 void * (*start_routine)(void *), void *arg)
292 /* The ATTR attribute is not really of type `pthread_attr_t *'. It has
293 the old size and access to the new members might crash the program.
294 We convert the struct now. */
295 pthread_attr_t new_attr;
299 size_t ps = __getpagesize ();
301 memcpy (&new_attr, attr, (size_t) &(((pthread_attr_t*)NULL)->guardsize));
302 new_attr.guardsize = ps;
303 new_attr.stackaddr_set = 0;
304 new_attr.stackaddr = NULL;
305 new_attr.stacksize = STACK_SIZE - ps;
308 return __pthread_create_2_1 (thread, attr, start_routine, arg);
310 symbol_version (__pthread_create_2_0, pthread_create, GLIBC_2.0);
312 strong_alias (__pthread_create_2_1, pthread_create)
315 /* Simple operations on thread identifiers */
317 pthread_t pthread_self(void)
319 pthread_descr self = thread_self();
323 int pthread_equal(pthread_t thread1, pthread_t thread2)
325 return thread1 == thread2;
328 /* Helper function for thread_self in the case of user-provided stacks */
332 pthread_descr __pthread_find_self()
334 char * sp = CURRENT_STACK_FRAME;
337 /* __pthread_handles[0] is the initial thread, handled specially in
338 thread_self(), so start at 1 */
339 h = __pthread_handles + 1;
340 while (! (sp <= (char *) h->h_descr && sp >= h->h_bottom)) h++;
346 /* Thread scheduling */
348 int pthread_setschedparam(pthread_t thread, int policy,
349 const struct sched_param *param)
351 pthread_handle handle = thread_handle(thread);
354 __pthread_lock(&handle->h_lock);
355 if (invalid_handle(handle, thread)) {
356 __pthread_unlock(&handle->h_lock);
359 th = handle->h_descr;
360 if (__sched_setscheduler(th->p_pid, policy, param) == -1) {
361 __pthread_unlock(&handle->h_lock);
364 th->p_priority = policy == SCHED_OTHER ? 0 : param->sched_priority;
365 __pthread_unlock(&handle->h_lock);
366 if (__pthread_manager_request >= 0)
367 __pthread_manager_adjust_prio(th->p_priority);
371 int pthread_getschedparam(pthread_t thread, int *policy,
372 struct sched_param *param)
374 pthread_handle handle = thread_handle(thread);
377 __pthread_lock(&handle->h_lock);
378 if (invalid_handle(handle, thread)) {
379 __pthread_unlock(&handle->h_lock);
382 pid = handle->h_descr->p_pid;
383 __pthread_unlock(&handle->h_lock);
384 pol = __sched_getscheduler(pid);
385 if (pol == -1) return errno;
386 if (__sched_getparam(pid, param) == -1) return errno;
391 /* Process-wide exit() request */
393 static void pthread_exit_process(int retcode, void *arg)
395 struct pthread_request request;
396 pthread_descr self = thread_self();
398 if (__pthread_manager_request >= 0) {
399 request.req_thread = self;
400 request.req_kind = REQ_PROCESS_EXIT;
401 request.req_args.exit.code = retcode;
402 __libc_write(__pthread_manager_request,
403 (char *) &request, sizeof(request));
405 /* Main thread should accumulate times for thread manager and its
406 children, so that timings for main thread account for all threads. */
407 if (self == __pthread_main_thread)
408 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
412 /* The handler for the RESTART signal just records the signal received
413 in the thread descriptor, and optionally performs a siglongjmp
414 (for pthread_cond_timedwait).
415 For the thread manager thread, redirect the signal to
416 __pthread_manager_sighandler. */
418 static void pthread_handle_sigrestart(int sig)
420 pthread_descr self = thread_self();
421 if (self == &__pthread_manager_thread) {
422 __pthread_manager_sighandler(sig);
424 self->p_signal = sig;
425 if (self->p_signal_jmp != NULL) siglongjmp(*self->p_signal_jmp, 1);
429 /* The handler for the CANCEL signal checks for cancellation
430 (in asynchronous mode), for process-wide exit and exec requests.
431 For the thread manager thread, we ignore the signal.
432 The debugging strategy is as follows:
433 On reception of a REQ_DEBUG request (sent by new threads created to
434 the thread manager under debugging mode), the thread manager throws
435 PTHREAD_SIG_CANCEL to itself. The debugger (if active) intercepts
436 this signal, takes into account new threads and continue execution
437 of the thread manager by propagating the signal because it doesn't
438 know what it is specifically done for. In the current implementation,
439 the thread manager simply discards it. */
441 static void pthread_handle_sigcancel(int sig)
443 pthread_descr self = thread_self();
446 if (self == &__pthread_manager_thread)
448 if (__pthread_exit_requested) {
449 /* Main thread should accumulate times for thread manager and its
450 children, so that timings for main thread account for all threads. */
451 if (self == __pthread_main_thread)
452 waitpid(__pthread_manager_thread.p_pid, NULL, __WCLONE);
453 _exit(__pthread_exit_code);
455 if (self->p_canceled && self->p_cancelstate == PTHREAD_CANCEL_ENABLE) {
456 if (self->p_canceltype == PTHREAD_CANCEL_ASYNCHRONOUS)
457 pthread_exit(PTHREAD_CANCELED);
458 jmpbuf = self->p_cancel_jmp;
459 if (jmpbuf != NULL) {
460 self->p_cancel_jmp = NULL;
461 siglongjmp(*jmpbuf, 1);
466 /* Reset the state of the thread machinery after a fork().
467 Close the pipe used for requests and set the main thread to the forked
469 Notice that we can't free the stack segments, as the forked thread
470 may hold pointers into them. */
472 void __pthread_reset_main_thread()
474 pthread_descr self = thread_self();
476 if (__pthread_manager_request != -1) {
477 /* Free the thread manager stack */
478 free(__pthread_manager_thread_bos);
479 __pthread_manager_thread_bos = __pthread_manager_thread_tos = NULL;
480 /* Close the two ends of the pipe */
481 __libc_close(__pthread_manager_request);
482 __libc_close(__pthread_manager_reader);
483 __pthread_manager_request = __pthread_manager_reader = -1;
485 /* Update the pid of the main thread */
486 self->p_pid = __getpid();
487 /* Make the forked thread the main thread */
488 __pthread_main_thread = self;
489 self->p_nextlive = self;
490 self->p_prevlive = self;
491 /* Now this thread modifies the global variables. */
492 self->p_errnop = &_errno;
493 self->p_h_errnop = &_h_errno;
496 /* Process-wide exec() request */
498 void __pthread_kill_other_threads_np(void)
500 /* Terminate all other threads and thread manager */
501 pthread_exit_process(0, NULL);
502 /* Make current thread the main thread in case the calling thread
503 changes its mind, does not exec(), and creates new threads instead. */
504 __pthread_reset_main_thread();
506 weak_alias (__pthread_kill_other_threads_np, pthread_kill_other_threads_np)
508 /* Concurrency symbol level. */
509 static int current_level;
511 int __pthread_setconcurrency(int level)
513 /* We don't do anything unless we have found a useful interpretation. */
514 current_level = level;
517 weak_alias (__pthread_setconcurrency, pthread_setconcurrency)
519 int __pthread_getconcurrency(void)
521 return current_level;
523 weak_alias (__pthread_getconcurrency, pthread_getconcurrency)
530 void __pthread_message(char * fmt, ...)
534 sprintf(buffer, "%05d : ", __getpid());
536 vsnprintf(buffer + 8, sizeof(buffer) - 8, fmt, args);
538 __libc_write(2, buffer, strlen(buffer));
545 /* We need a hook to force the cancelation wrappers to be linked in when
546 static libpthread is used. */
547 extern const int __pthread_provide_wrappers;
548 static const int *const __pthread_require_wrappers =
549 &__pthread_provide_wrappers;