2 * Copyright (c) 2003 Daniel M. Eischen <deischen@freebsd.org>
3 * Copyright (c) 1995-1998 John Birrell <jb@cimlogic.com.au>
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. Neither the name of the author nor the names of any co-contributors
15 * may be used to endorse or promote products derived from this software
16 * without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 /* Allocate space for global thread variables here: */
34 #define GLOBAL_PTHREAD_PRIVATE
36 #include "namespace.h"
37 #include <sys/param.h>
38 #include <sys/types.h>
39 #include <sys/signalvar.h>
40 #include <machine/reg.h>
42 #include <sys/ioctl.h>
43 #include <sys/mount.h>
45 #include <sys/socket.h>
46 #include <sys/event.h>
48 #include <sys/sysctl.h>
50 #include <sys/ttycom.h>
58 #include <pthread_np.h>
64 #include "un-namespace.h"
66 #include "libc_private.h"
67 #include "thr_private.h"
69 LT10_COMPAT_PRIVATE(_libkse_debug);
70 LT10_COMPAT_PRIVATE(_thread_activated);
71 LT10_COMPAT_PRIVATE(_thread_active_threads);
72 LT10_COMPAT_PRIVATE(_thread_list);
74 int __pthread_cond_wait(pthread_cond_t *, pthread_mutex_t *);
75 int __pthread_mutex_lock(pthread_mutex_t *);
76 int __pthread_mutex_trylock(pthread_mutex_t *);
77 void _thread_init_hack(void);
78 extern int _thread_state_running;
80 static void init_private(void);
81 static void init_main_thread(struct pthread *thread);
84 * All weak references used within libc should be in this table.
85 * This is so that static libraries will work.
87 static void *references[] = {
112 &_pthread_getspecific,
113 &_pthread_key_create,
114 &_pthread_key_delete,
115 &_pthread_mutex_destroy,
116 &_pthread_mutex_init,
117 &_pthread_mutex_lock,
118 &_pthread_mutex_trylock,
119 &_pthread_mutex_unlock,
120 &_pthread_mutexattr_init,
121 &_pthread_mutexattr_destroy,
122 &_pthread_mutexattr_settype,
124 &_pthread_setspecific,
145 * These are needed when linking statically. All references within
146 * libgcc (and in the future libc) to these routines are weak, but
147 * if they are not (strongly) referenced by the application or other
148 * libraries, then the actual functions will not be loaded.
150 static void *libgcc_references[] = {
152 &_pthread_key_create,
153 &_pthread_key_delete,
154 &_pthread_getspecific,
155 &_pthread_setspecific,
156 &_pthread_mutex_init,
157 &_pthread_mutex_destroy,
158 &_pthread_mutex_lock,
159 &_pthread_mutex_trylock,
160 &_pthread_mutex_unlock
163 #define DUAL_ENTRY(entry) \
164 (pthread_func_t)entry, (pthread_func_t)entry
166 static pthread_func_t jmp_table[][2] = {
167 {DUAL_ENTRY(_pthread_atfork)}, /* PJT_ATFORK */
168 {DUAL_ENTRY(_pthread_attr_destroy)}, /* PJT_ATTR_DESTROY */
169 {DUAL_ENTRY(_pthread_attr_getdetachstate)}, /* PJT_ATTR_GETDETACHSTATE */
170 {DUAL_ENTRY(_pthread_attr_getguardsize)}, /* PJT_ATTR_GETGUARDSIZE */
171 {DUAL_ENTRY(_pthread_attr_getinheritsched)}, /* PJT_ATTR_GETINHERITSCHED */
172 {DUAL_ENTRY(_pthread_attr_getschedparam)}, /* PJT_ATTR_GETSCHEDPARAM */
173 {DUAL_ENTRY(_pthread_attr_getschedpolicy)}, /* PJT_ATTR_GETSCHEDPOLICY */
174 {DUAL_ENTRY(_pthread_attr_getscope)}, /* PJT_ATTR_GETSCOPE */
175 {DUAL_ENTRY(_pthread_attr_getstackaddr)}, /* PJT_ATTR_GETSTACKADDR */
176 {DUAL_ENTRY(_pthread_attr_getstacksize)}, /* PJT_ATTR_GETSTACKSIZE */
177 {DUAL_ENTRY(_pthread_attr_init)}, /* PJT_ATTR_INIT */
178 {DUAL_ENTRY(_pthread_attr_setdetachstate)}, /* PJT_ATTR_SETDETACHSTATE */
179 {DUAL_ENTRY(_pthread_attr_setguardsize)}, /* PJT_ATTR_SETGUARDSIZE */
180 {DUAL_ENTRY(_pthread_attr_setinheritsched)}, /* PJT_ATTR_SETINHERITSCHED */
181 {DUAL_ENTRY(_pthread_attr_setschedparam)}, /* PJT_ATTR_SETSCHEDPARAM */
182 {DUAL_ENTRY(_pthread_attr_setschedpolicy)}, /* PJT_ATTR_SETSCHEDPOLICY */
183 {DUAL_ENTRY(_pthread_attr_setscope)}, /* PJT_ATTR_SETSCOPE */
184 {DUAL_ENTRY(_pthread_attr_setstackaddr)}, /* PJT_ATTR_SETSTACKADDR */
185 {DUAL_ENTRY(_pthread_attr_setstacksize)}, /* PJT_ATTR_SETSTACKSIZE */
186 {DUAL_ENTRY(_pthread_cancel)}, /* PJT_CANCEL */
187 {DUAL_ENTRY(_pthread_cleanup_pop)}, /* PJT_CLEANUP_POP */
188 {DUAL_ENTRY(_pthread_cleanup_push)}, /* PJT_CLEANUP_PUSH */
189 {DUAL_ENTRY(_pthread_cond_broadcast)}, /* PJT_COND_BROADCAST */
190 {DUAL_ENTRY(_pthread_cond_destroy)}, /* PJT_COND_DESTROY */
191 {DUAL_ENTRY(_pthread_cond_init)}, /* PJT_COND_INIT */
192 {DUAL_ENTRY(_pthread_cond_signal)}, /* PJT_COND_SIGNAL */
193 {DUAL_ENTRY(_pthread_cond_timedwait)}, /* PJT_COND_TIMEDWAIT */
194 {(pthread_func_t)__pthread_cond_wait,
195 (pthread_func_t)_pthread_cond_wait}, /* PJT_COND_WAIT */
196 {DUAL_ENTRY(_pthread_detach)}, /* PJT_DETACH */
197 {DUAL_ENTRY(_pthread_equal)}, /* PJT_EQUAL */
198 {DUAL_ENTRY(_pthread_exit)}, /* PJT_EXIT */
199 {DUAL_ENTRY(_pthread_getspecific)}, /* PJT_GETSPECIFIC */
200 {DUAL_ENTRY(_pthread_join)}, /* PJT_JOIN */
201 {DUAL_ENTRY(_pthread_key_create)}, /* PJT_KEY_CREATE */
202 {DUAL_ENTRY(_pthread_key_delete)}, /* PJT_KEY_DELETE*/
203 {DUAL_ENTRY(_pthread_kill)}, /* PJT_KILL */
204 {DUAL_ENTRY(_pthread_main_np)}, /* PJT_MAIN_NP */
205 {DUAL_ENTRY(_pthread_mutexattr_destroy)}, /* PJT_MUTEXATTR_DESTROY */
206 {DUAL_ENTRY(_pthread_mutexattr_init)}, /* PJT_MUTEXATTR_INIT */
207 {DUAL_ENTRY(_pthread_mutexattr_settype)}, /* PJT_MUTEXATTR_SETTYPE */
208 {DUAL_ENTRY(_pthread_mutex_destroy)}, /* PJT_MUTEX_DESTROY */
209 {DUAL_ENTRY(_pthread_mutex_init)}, /* PJT_MUTEX_INIT */
210 {(pthread_func_t)__pthread_mutex_lock,
211 (pthread_func_t)_pthread_mutex_lock}, /* PJT_MUTEX_LOCK */
212 {(pthread_func_t)__pthread_mutex_trylock,
213 (pthread_func_t)_pthread_mutex_trylock},/* PJT_MUTEX_TRYLOCK */
214 {DUAL_ENTRY(_pthread_mutex_unlock)}, /* PJT_MUTEX_UNLOCK */
215 {DUAL_ENTRY(_pthread_once)}, /* PJT_ONCE */
216 {DUAL_ENTRY(_pthread_rwlock_destroy)}, /* PJT_RWLOCK_DESTROY */
217 {DUAL_ENTRY(_pthread_rwlock_init)}, /* PJT_RWLOCK_INIT */
218 {DUAL_ENTRY(_pthread_rwlock_rdlock)}, /* PJT_RWLOCK_RDLOCK */
219 {DUAL_ENTRY(_pthread_rwlock_tryrdlock)},/* PJT_RWLOCK_TRYRDLOCK */
220 {DUAL_ENTRY(_pthread_rwlock_trywrlock)},/* PJT_RWLOCK_TRYWRLOCK */
221 {DUAL_ENTRY(_pthread_rwlock_unlock)}, /* PJT_RWLOCK_UNLOCK */
222 {DUAL_ENTRY(_pthread_rwlock_wrlock)}, /* PJT_RWLOCK_WRLOCK */
223 {DUAL_ENTRY(_pthread_self)}, /* PJT_SELF */
224 {DUAL_ENTRY(_pthread_setcancelstate)}, /* PJT_SETCANCELSTATE */
225 {DUAL_ENTRY(_pthread_setcanceltype)}, /* PJT_SETCANCELTYPE */
226 {DUAL_ENTRY(_pthread_setspecific)}, /* PJT_SETSPECIFIC */
227 {DUAL_ENTRY(_pthread_sigmask)}, /* PJT_SIGMASK */
228 {DUAL_ENTRY(_pthread_testcancel)} /* PJT_TESTCANCEL */
231 static int init_once = 0;
234 * Threaded process initialization.
236 * This is only called under two conditions:
238 * 1) Some thread routines have detected that the library hasn't yet
239 * been initialized (_thr_initial == NULL && curthread == NULL), or
241 * 2) An explicit call to reinitialize after a fork (indicated
242 * by curthread != NULL)
245 _libpthread_init(struct pthread *curthread)
249 /* Check if this function has already been called: */
250 if ((_thr_initial != NULL) && (curthread == NULL))
251 /* Only initialize the threaded application once. */
255 * Make gcc quiescent about {,libgcc_}references not being
258 if ((references[0] == NULL) || (libgcc_references[0] == NULL))
259 PANIC("Failed loading mandatory references in _thread_init");
261 /* Pull debug symbols in for static binary */
262 _thread_state_running = PS_RUNNING;
265 * Check the size of the jump table to make sure it is preset
266 * with the correct number of entries.
268 if (sizeof(jmp_table) != (sizeof(pthread_func_t) * PJT_MAX * 2))
269 PANIC("Thread jump table not properly initialized");
270 memcpy(__thr_jtable, jmp_table, sizeof(jmp_table));
273 * Check for the special case of this process running as
274 * or in place of init as pid = 1:
276 if ((_thr_pid = getpid()) == 1) {
278 * Setup a new session for this process which is
279 * assumed to be running as root.
282 PANIC("Can't set session ID");
283 if (revoke(_PATH_CONSOLE) != 0)
284 PANIC("Can't revoke console");
285 if ((fd = __sys_open(_PATH_CONSOLE, O_RDWR)) < 0)
286 PANIC("Can't open console");
287 if (setlogin("root") == -1)
288 PANIC("Can't set login to root");
289 if (__sys_ioctl(fd, TIOCSCTTY, (char *) NULL) == -1)
290 PANIC("Can't set controlling terminal");
293 /* Initialize pthread private data. */
297 /* Initialize the initial kse and kseg. */
298 _kse_initial = _kse_alloc(NULL, _thread_scope_system > 0);
299 if (_kse_initial == NULL)
300 PANIC("Can't allocate initial kse.");
301 _kse_initial->k_kseg = _kseg_alloc(NULL);
302 if (_kse_initial->k_kseg == NULL)
303 PANIC("Can't allocate initial kseg.");
304 _kse_initial->k_kseg->kg_flags |= KGF_SINGLE_THREAD;
305 _kse_initial->k_schedq = &_kse_initial->k_kseg->kg_schedq;
307 TAILQ_INSERT_TAIL(&_kse_initial->k_kseg->kg_kseq, _kse_initial, k_kgqe);
308 _kse_initial->k_kseg->kg_ksecount = 1;
310 /* Set the initial thread. */
311 if (curthread == NULL) {
312 /* Create and initialize the initial thread. */
313 curthread = _thr_alloc(NULL);
314 if (curthread == NULL)
315 PANIC("Can't allocate initial thread");
316 _thr_initial = curthread;
317 init_main_thread(curthread);
320 * The initial thread is the current thread. It is
321 * assumed that the current thread is already initialized
322 * because it is left over from a fork().
324 _thr_initial = curthread;
326 _kse_initial->k_kseg->kg_threadcount = 0;
327 _thr_initial->kse = _kse_initial;
328 _thr_initial->kseg = _kse_initial->k_kseg;
329 _thr_initial->active = 1;
332 * Add the thread to the thread list and to the KSEG's thread
335 THR_LIST_ADD(_thr_initial);
336 KSEG_THRQ_ADD(_kse_initial->k_kseg, _thr_initial);
338 /* Setup the KSE/thread specific data for the current KSE/thread. */
339 _thr_initial->kse->k_curthread = _thr_initial;
340 _kcb_set(_thr_initial->kse->k_kcb);
341 _tcb_set(_thr_initial->kse->k_kcb, _thr_initial->tcb);
342 _thr_initial->kse->k_flags |= KF_INITIALIZED;
345 _kse_critical_leave(&_thr_initial->tcb->tcb_tmbx);
347 * activate threaded mode as soon as possible if we are
355 * This function and pthread_create() do a lot of the same things.
356 * It'd be nice to consolidate the common stuff in one place.
359 init_main_thread(struct pthread *thread)
361 /* Setup the thread attributes. */
362 thread->attr = _pthread_attr_default;
363 thread->attr.flags |= PTHREAD_SCOPE_SYSTEM;
365 * Set up the thread stack.
367 * Create a red zone below the main stack. All other stacks
368 * are constrained to a maximum size by the parameters
369 * passed to mmap(), but this stack is only limited by
370 * resource limits, so this stack needs an explicitly mapped
371 * red zone to protect the thread stack that is just beyond.
373 if (mmap((void *)_usrstack - _thr_stack_initial -
374 _thr_guard_default, _thr_guard_default, 0, MAP_ANON,
375 -1, 0) == MAP_FAILED)
376 PANIC("Cannot allocate red zone for initial thread");
379 * Mark the stack as an application supplied stack so that it
382 * XXX - I'm not sure it would hurt anything to deallocate
383 * the main thread stack because deallocation doesn't
384 * actually free() it; it just puts it in the free
385 * stack queue for later reuse.
387 thread->attr.stackaddr_attr = (void *)_usrstack - _thr_stack_initial;
388 thread->attr.stacksize_attr = _thr_stack_initial;
389 thread->attr.guardsize_attr = _thr_guard_default;
390 thread->attr.flags |= THR_STACK_USER;
393 * Write a magic value to the thread structure
394 * to help identify valid ones:
396 thread->magic = THR_MAGIC;
398 thread->slice_usec = -1;
399 thread->cancelflags = PTHREAD_CANCEL_ENABLE | PTHREAD_CANCEL_DEFERRED;
400 thread->name = strdup("initial thread");
402 /* Initialize the thread for signals: */
403 SIGEMPTYSET(thread->sigmask);
406 * Set up the thread mailbox. The threads saved context
407 * is also in the mailbox.
409 thread->tcb->tcb_tmbx.tm_udata = thread;
410 thread->tcb->tcb_tmbx.tm_context.uc_stack.ss_size =
411 thread->attr.stacksize_attr;
412 thread->tcb->tcb_tmbx.tm_context.uc_stack.ss_sp =
413 thread->attr.stackaddr_attr;
415 /* Default the priority of the initial thread: */
416 thread->base_priority = THR_DEFAULT_PRIORITY;
417 thread->active_priority = THR_DEFAULT_PRIORITY;
418 thread->inherited_priority = 0;
420 /* Initialize the mutex queue: */
421 TAILQ_INIT(&thread->mutexq);
423 /* Initialize hooks in the thread structure: */
424 thread->specific = NULL;
425 thread->cleanup = NULL;
427 thread->sigbackout = NULL;
428 thread->continuation = NULL;
430 thread->state = PS_RUNNING;
431 thread->uniqueid = 0;
437 struct clockinfo clockinfo;
442 * Avoid reinitializing some things if they don't need to be,
443 * e.g. after a fork().
445 if (init_once == 0) {
446 /* Find the stack top */
448 mib[1] = KERN_USRSTACK;
449 len = sizeof (_usrstack);
450 if (sysctl(mib, 2, &_usrstack, &len, NULL, 0) == -1)
451 PANIC("Cannot get kern.usrstack from sysctl");
452 /* Get the kernel clockrate: */
454 mib[1] = KERN_CLOCKRATE;
455 len = sizeof (struct clockinfo);
456 if (sysctl(mib, 2, &clockinfo, &len, NULL, 0) == 0)
457 _clock_res_usec = 1000000 / clockinfo.stathz;
459 _clock_res_usec = CLOCK_RES_USEC;
461 _thr_page_size = getpagesize();
462 _thr_guard_default = _thr_page_size;
463 if (sizeof(void *) == 8) {
464 _thr_stack_default = THR_STACK64_DEFAULT;
465 _thr_stack_initial = THR_STACK64_INITIAL;
468 _thr_stack_default = THR_STACK32_DEFAULT;
469 _thr_stack_initial = THR_STACK32_INITIAL;
471 _pthread_attr_default.guardsize_attr = _thr_guard_default;
472 _pthread_attr_default.stacksize_attr = _thr_stack_default;
473 TAILQ_INIT(&_thr_atfork_list);
474 init_once = 1; /* Don't do this again. */
477 * Destroy the locks before creating them. We don't
478 * know what state they are in so it is better to just
481 _lock_destroy(&_thread_signal_lock);
482 _lock_destroy(&_mutex_static_lock);
483 _lock_destroy(&_rwlock_static_lock);
484 _lock_destroy(&_keytable_lock);
487 /* Initialize everything else. */
488 TAILQ_INIT(&_thread_list);
489 TAILQ_INIT(&_thread_gc_list);
490 _pthread_mutex_init(&_thr_atfork_mutex, NULL);
493 * Initialize the lock for temporary installation of signal
494 * handlers (to support sigwait() semantics) and for the
495 * process signal mask and pending signal sets.
497 if (_lock_init(&_thread_signal_lock, LCK_ADAPTIVE,
498 _kse_lock_wait, _kse_lock_wakeup, calloc) != 0)
499 PANIC("Cannot initialize _thread_signal_lock");
500 if (_lock_init(&_mutex_static_lock, LCK_ADAPTIVE,
501 _thr_lock_wait, _thr_lock_wakeup, calloc) != 0)
502 PANIC("Cannot initialize mutex static init lock");
503 if (_lock_init(&_rwlock_static_lock, LCK_ADAPTIVE,
504 _thr_lock_wait, _thr_lock_wakeup, calloc) != 0)
505 PANIC("Cannot initialize rwlock static init lock");
506 if (_lock_init(&_keytable_lock, LCK_ADAPTIVE,
507 _thr_lock_wait, _thr_lock_wakeup, calloc) != 0)
508 PANIC("Cannot initialize thread specific keytable lock");
509 _thr_spinlock_init();
511 /* Clear pending signals and get the process signal mask. */
512 SIGEMPTYSET(_thr_proc_sigpending);
514 /* Are we in M:N mode (default) or 1:1 mode? */
515 #ifdef SYSTEM_SCOPE_ONLY
516 _thread_scope_system = 1;
518 if (getenv("LIBPTHREAD_SYSTEM_SCOPE") != NULL)
519 _thread_scope_system = 1;
520 else if (getenv("LIBPTHREAD_PROCESS_SCOPE") != NULL)
521 _thread_scope_system = -1;
523 if (getenv("LIBPTHREAD_DEBUG") != NULL)
524 _thr_debug_flags |= DBG_INFO_DUMP;
527 * _thread_list_lock and _kse_count are initialized