thr_init.c revision 115080
1/* 2 * Copyright (c) 2003 Daniel M. Eischen <deischen@freebsd.org> 3 * Copyright (c) 1995-1998 John Birrell <jb@cimlogic.com.au> 4 * All rights reserved. 5 * 6 * Redistribution and use in source and binary forms, with or without 7 * modification, are permitted provided that the following conditions 8 * are met: 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. All advertising materials mentioning features or use of this software 15 * must display the following acknowledgement: 16 * This product includes software developed by John Birrell. 17 * 4. Neither the name of the author nor the names of any co-contributors 18 * may be used to endorse or promote products derived from this software 19 * without specific prior written permission. 20 * 21 * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND 22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 * 33 * $FreeBSD: head/lib/libkse/thread/thr_init.c 115080 2003-05-16 19:58:30Z deischen $ 34 */ 35 36/* Allocate space for global thread variables here: */ 37#define GLOBAL_PTHREAD_PRIVATE 38 39#include "namespace.h" 40#include <sys/param.h> 41#include <sys/types.h> 42#include <machine/reg.h> 43 44#include <sys/ioctl.h> 45#include <sys/mount.h> 46#include <sys/uio.h> 47#include <sys/socket.h> 48#include <sys/event.h> 49#include <sys/stat.h> 50#include <sys/sysctl.h> 51#include <sys/time.h> 52#include <sys/ttycom.h> 53#include <sys/wait.h> 54#include <sys/mman.h> 55#include <dirent.h> 56#include <errno.h> 57#include <fcntl.h> 58#include <paths.h> 59#include <pthread.h> 60#include <pthread_np.h> 61#include <signal.h> 62#include <stdio.h> 63#include <stdlib.h> 64#include <string.h> 65#include <unistd.h> 66#include "un-namespace.h" 67 68#include "libc_private.h" 69#include "thr_private.h" 70#include "ksd.h" 71 72int __pthread_cond_wait(pthread_cond_t *, pthread_mutex_t *); 73int __pthread_mutex_lock(pthread_mutex_t *); 74int __pthread_mutex_trylock(pthread_mutex_t *); 75void _thread_init_hack(void); 76 77static void init_private(void); 78static void init_main_thread(struct pthread *thread); 79 80/* 81 * All weak references used within libc should be in this table. 82 * This is so that static libraries will work. 83 */ 84static void *references[] = { 85 &_accept, 86 &_bind, 87 &_close, 88 &_connect, 89 &_dup, 90 &_dup2, 91 &_execve, 92 &_fcntl, 93 &_flock, 94 &_flockfile, 95 &_fstat, 96 &_fstatfs, 97 &_fsync, 98 &_funlockfile, 99 &_getdirentries, 100 &_getlogin, 101 &_getpeername, 102 &_getsockname, 103 &_getsockopt, 104 &_ioctl, 105 &_kevent, 106 &_listen, 107 &_nanosleep, 108 &_open, 109 &_pthread_getspecific, 110 &_pthread_key_create, 111 &_pthread_key_delete, 112 &_pthread_mutex_destroy, 113 &_pthread_mutex_init, 114 &_pthread_mutex_lock, 115 &_pthread_mutex_trylock, 116 &_pthread_mutex_unlock, 117 &_pthread_mutexattr_init, 118 &_pthread_mutexattr_destroy, 119 &_pthread_mutexattr_settype, 120 &_pthread_once, 121 &_pthread_setspecific, 122 &_read, 123 &_readv, 124 &_recvfrom, 125 &_recvmsg, 126 &_select, 127 &_sendmsg, 128 &_sendto, 129 &_setsockopt, 130 &_sigaction, 131 &_sigprocmask, 132 &_sigsuspend, 133 &_socket, 134 &_socketpair, 135 &_thread_init_hack, 136 &_wait4, 137 &_write, 138 &_writev 139}; 140 141/* 142 * These are needed when linking statically. All references within 143 * libgcc (and in the future libc) to these routines are weak, but 144 * if they are not (strongly) referenced by the application or other 145 * libraries, then the actual functions will not be loaded. 146 */ 147static void *libgcc_references[] = { 148 &_pthread_once, 149 &_pthread_key_create, 150 &_pthread_key_delete, 151 &_pthread_getspecific, 152 &_pthread_setspecific, 153 &_pthread_mutex_init, 154 &_pthread_mutex_destroy, 155 &_pthread_mutex_lock, 156 &_pthread_mutex_trylock, 157 &_pthread_mutex_unlock 158}; 159 160#define DUAL_ENTRY(entry) \ 161 (pthread_func_t)entry, (pthread_func_t)entry 162 163static pthread_func_t jmp_table[][2] = { 164 {DUAL_ENTRY(_pthread_cond_broadcast)}, /* PJT_COND_BROADCAST */ 165 {DUAL_ENTRY(_pthread_cond_destroy)}, /* PJT_COND_DESTROY */ 166 {DUAL_ENTRY(_pthread_cond_init)}, /* PJT_COND_INIT */ 167 {DUAL_ENTRY(_pthread_cond_signal)}, /* PJT_COND_SIGNAL */ 168 {(pthread_func_t)__pthread_cond_wait, 169 (pthread_func_t)_pthread_cond_wait}, /* PJT_COND_WAIT */ 170 {DUAL_ENTRY(_pthread_getspecific)}, /* PJT_GETSPECIFIC */ 171 {DUAL_ENTRY(_pthread_key_create)}, /* PJT_KEY_CREATE */ 172 {DUAL_ENTRY(_pthread_key_delete)}, /* PJT_KEY_DELETE*/ 173 {DUAL_ENTRY(_pthread_main_np)}, /* PJT_MAIN_NP */ 174 {DUAL_ENTRY(_pthread_mutex_destroy)}, /* PJT_MUTEX_DESTROY */ 175 {DUAL_ENTRY(_pthread_mutex_init)}, /* PJT_MUTEX_INIT */ 176 {(pthread_func_t)__pthread_mutex_lock, 177 (pthread_func_t)_pthread_mutex_lock}, /* PJT_MUTEX_LOCK */ 178 {(pthread_func_t)__pthread_mutex_trylock, 179 (pthread_func_t)_pthread_mutex_trylock},/* PJT_MUTEX_TRYLOCK */ 180 {DUAL_ENTRY(_pthread_mutex_unlock)}, /* PJT_MUTEX_UNLOCK */ 181 {DUAL_ENTRY(_pthread_mutexattr_destroy)}, /* PJT_MUTEXATTR_DESTROY */ 182 {DUAL_ENTRY(_pthread_mutexattr_init)}, /* PJT_MUTEXATTR_INIT */ 183 {DUAL_ENTRY(_pthread_mutexattr_settype)}, /* PJT_MUTEXATTR_SETTYPE */ 184 {DUAL_ENTRY(_pthread_once)}, /* PJT_ONCE */ 185 {DUAL_ENTRY(_pthread_rwlock_destroy)}, /* PJT_RWLOCK_DESTROY */ 186 {DUAL_ENTRY(_pthread_rwlock_init)}, /* PJT_RWLOCK_INIT */ 187 {DUAL_ENTRY(_pthread_rwlock_rdlock)}, /* PJT_RWLOCK_RDLOCK */ 188 {DUAL_ENTRY(_pthread_rwlock_tryrdlock)},/* PJT_RWLOCK_TRYRDLOCK */ 189 {DUAL_ENTRY(_pthread_rwlock_trywrlock)},/* PJT_RWLOCK_TRYWRLOCK */ 190 {DUAL_ENTRY(_pthread_rwlock_unlock)}, /* PJT_RWLOCK_UNLOCK */ 191 {DUAL_ENTRY(_pthread_rwlock_wrlock)}, /* PJT_RWLOCK_WRLOCK */ 192 {DUAL_ENTRY(_pthread_self)}, /* PJT_SELF */ 193 {DUAL_ENTRY(_pthread_setspecific)}, /* PJT_SETSPECIFIC */ 194 {DUAL_ENTRY(_pthread_sigmask)} /* PJT_SIGMASK */ 195}; 196 197static int init_once = 0; 198 199/* 200 * Threaded process initialization. 201 * 202 * This is only called under two conditions: 203 * 204 * 1) Some thread routines have detected that the library hasn't yet 205 * been initialized (_thr_initial == NULL && curthread == NULL), or 206 * 207 * 2) An explicit call to reinitialize after a fork (indicated 208 * by curthread != NULL) 209 */ 210void 211_libpthread_init(struct pthread *curthread) 212{ 213 int fd; 214 215 /* Check if this function has already been called: */ 216 if ((_thr_initial != NULL) && (curthread == NULL)) 217 /* Only initialize the threaded application once. */ 218 return; 219 220 /* 221 * Make gcc quiescent about {,libgcc_}references not being 222 * referenced: 223 */ 224 if ((references[0] == NULL) || (libgcc_references[0] == NULL)) 225 PANIC("Failed loading mandatory references in _thread_init"); 226 227 /* 228 * Check the size of the jump table to make sure it is preset 229 * with the correct number of entries. 230 */ 231 if (sizeof(jmp_table) != (sizeof(pthread_func_t) * PJT_MAX * 2)) 232 PANIC("Thread jump table not properly initialized"); 233 memcpy(__thr_jtable, jmp_table, sizeof(jmp_table)); 234 235 /* 236 * Check for the special case of this process running as 237 * or in place of init as pid = 1: 238 */ 239 if ((_thr_pid = getpid()) == 1) { 240 /* 241 * Setup a new session for this process which is 242 * assumed to be running as root. 243 */ 244 if (setsid() == -1) 245 PANIC("Can't set session ID"); 246 if (revoke(_PATH_CONSOLE) != 0) 247 PANIC("Can't revoke console"); 248 if ((fd = __sys_open(_PATH_CONSOLE, O_RDWR)) < 0) 249 PANIC("Can't open console"); 250 if (setlogin("root") == -1) 251 PANIC("Can't set login to root"); 252 if (__sys_ioctl(fd, TIOCSCTTY, (char *) NULL) == -1) 253 PANIC("Can't set controlling terminal"); 254 } 255 256 /* Initialize pthread private data. */ 257 init_private(); 258 _kse_init(); 259 260 /* Initialize the initial kse and kseg. */ 261 _kse_initial = _kse_alloc(NULL); 262 if (_kse_initial == NULL) 263 PANIC("Can't allocate initial kse."); 264 _kse_initial->k_kseg = _kseg_alloc(NULL); 265 if (_kse_initial->k_kseg == NULL) 266 PANIC("Can't allocate initial kseg."); 267 _kse_initial->k_schedq = &_kse_initial->k_kseg->kg_schedq; 268 269 TAILQ_INSERT_TAIL(&_kse_initial->k_kseg->kg_kseq, _kse_initial, k_kgqe); 270 _kse_initial->k_kseg->kg_ksecount = 1; 271 272 /* Set the initial thread. */ 273 if (curthread == NULL) { 274 /* Create and initialize the initial thread. */ 275 curthread = _thr_alloc(NULL); 276 if (curthread == NULL) 277 PANIC("Can't allocate initial thread"); 278 _thr_initial = curthread; 279 init_main_thread(curthread); 280 } else { 281 /* 282 * The initial thread is the current thread. It is 283 * assumed that the current thread is already initialized 284 * because it is left over from a fork(). 285 */ 286 _thr_initial = curthread; 287 } 288 _kse_initial->k_kseg->kg_threadcount = 0; 289 _thr_initial->kse = _kse_initial; 290 _thr_initial->kseg = _kse_initial->k_kseg; 291 _thr_initial->active = 1; 292 293 /* 294 * Add the thread to the thread list and to the KSEG's thread 295 * queue. 296 */ 297 THR_LIST_ADD(_thr_initial); 298 KSEG_THRQ_ADD(_kse_initial->k_kseg, _thr_initial); 299 300 /* Setup the KSE/thread specific data for the current KSE/thread. */ 301 if (_ksd_setprivate(&_thr_initial->kse->k_ksd) != 0) 302 PANIC("Can't set initial KSE specific data"); 303 _set_curkse(_thr_initial->kse); 304 _thr_initial->kse->k_curthread = _thr_initial; 305 _thr_initial->kse->k_flags |= KF_INITIALIZED; 306 _kse_initial->k_curthread = _thr_initial; 307} 308 309/* 310 * This function and pthread_create() do a lot of the same things. 311 * It'd be nice to consolidate the common stuff in one place. 312 */ 313static void 314init_main_thread(struct pthread *thread) 315{ 316 void *p; 317 int i; 318 319 /* Zero the initial thread structure. */ 320 p = thread->alloc_addr; 321 memset(thread, 0, sizeof(struct pthread)); 322 thread->alloc_addr = p; 323 324 /* Setup the thread attributes. */ 325 thread->attr = _pthread_attr_default; 326 327 /* 328 * Set up the thread stack. 329 * 330 * Create a red zone below the main stack. All other stacks 331 * are constrained to a maximum size by the parameters 332 * passed to mmap(), but this stack is only limited by 333 * resource limits, so this stack needs an explicitly mapped 334 * red zone to protect the thread stack that is just beyond. 335 */ 336 if (mmap((void *)_usrstack - THR_STACK_INITIAL - 337 _thr_guard_default, _thr_guard_default, 0, MAP_ANON, 338 -1, 0) == MAP_FAILED) 339 PANIC("Cannot allocate red zone for initial thread"); 340 341 /* 342 * Mark the stack as an application supplied stack so that it 343 * isn't deallocated. 344 * 345 * XXX - I'm not sure it would hurt anything to deallocate 346 * the main thread stack because deallocation doesn't 347 * actually free() it; it just puts it in the free 348 * stack queue for later reuse. 349 */ 350 thread->attr.stackaddr_attr = (void *)_usrstack - THR_STACK_INITIAL; 351 thread->attr.stacksize_attr = THR_STACK_INITIAL; 352 thread->attr.guardsize_attr = _thr_guard_default; 353 thread->attr.flags |= THR_STACK_USER; 354 355 /* 356 * Write a magic value to the thread structure 357 * to help identify valid ones: 358 */ 359 thread->magic = THR_MAGIC; 360 361 thread->slice_usec = -1; 362 thread->cancelflags = PTHREAD_CANCEL_ENABLE | PTHREAD_CANCEL_DEFERRED; 363 thread->name = strdup("initial thread"); 364 365 /* Initialize the thread for signals: */ 366 sigemptyset(&thread->sigmask); 367 368 /* 369 * Set up the thread mailbox. The threads saved context 370 * is also in the mailbox. 371 */ 372 thread->tmbx.tm_udata = thread; 373 thread->tmbx.tm_context.uc_sigmask = thread->sigmask; 374 thread->tmbx.tm_context.uc_stack.ss_size = thread->attr.stacksize_attr; 375 thread->tmbx.tm_context.uc_stack.ss_sp = thread->attr.stackaddr_attr; 376 377 /* Default the priority of the initial thread: */ 378 thread->base_priority = THR_DEFAULT_PRIORITY; 379 thread->active_priority = THR_DEFAULT_PRIORITY; 380 thread->inherited_priority = 0; 381 382 /* Initialize the mutex queue: */ 383 TAILQ_INIT(&thread->mutexq); 384 385 /* Initialize thread locking. */ 386 if (_lock_init(&thread->lock, LCK_ADAPTIVE, 387 _thr_lock_wait, _thr_lock_wakeup) != 0) 388 PANIC("Cannot initialize initial thread lock"); 389 for (i = 0; i < MAX_THR_LOCKLEVEL; i++) { 390 _lockuser_init(&thread->lockusers[i], (void *)thread); 391 _LCK_SET_PRIVATE2(&thread->lockusers[i], (void *)thread); 392 } 393 394 /* Initialize hooks in the thread structure: */ 395 thread->specific = NULL; 396 thread->cleanup = NULL; 397 thread->flags = 0; 398 thread->continuation = NULL; 399 400 thread->state = PS_RUNNING; 401 thread->uniqueid = 0; 402} 403 404static void 405init_private(void) 406{ 407 struct clockinfo clockinfo; 408 struct sigaction act; 409 size_t len; 410 int mib[2]; 411 int i; 412 413 /* 414 * Avoid reinitializing some things if they don't need to be, 415 * e.g. after a fork(). 416 */ 417 if (init_once == 0) { 418 /* Find the stack top */ 419 mib[0] = CTL_KERN; 420 mib[1] = KERN_USRSTACK; 421 len = sizeof (_usrstack); 422 if (sysctl(mib, 2, &_usrstack, &len, NULL, 0) == -1) 423 PANIC("Cannot get kern.usrstack from sysctl"); 424 425 /* 426 * Create a red zone below the main stack. All other 427 * stacks are constrained to a maximum size by the 428 * parameters passed to mmap(), but this stack is only 429 * limited by resource limits, so this stack needs an 430 * explicitly mapped red zone to protect the thread stack 431 * that is just beyond. 432 */ 433 if (mmap((void *)_usrstack - THR_STACK_INITIAL - 434 _thr_guard_default, _thr_guard_default, 435 0, MAP_ANON, -1, 0) == MAP_FAILED) 436 PANIC("Cannot allocate red zone for initial thread"); 437 438 /* Get the kernel clockrate: */ 439 mib[0] = CTL_KERN; 440 mib[1] = KERN_CLOCKRATE; 441 len = sizeof (struct clockinfo); 442 if (sysctl(mib, 2, &clockinfo, &len, NULL, 0) == 0) 443 _clock_res_usec = clockinfo.tick; 444 else 445 _clock_res_usec = CLOCK_RES_USEC; 446 447 _thr_page_size = getpagesize(); 448 _thr_guard_default = _thr_page_size; 449 450 init_once = 1; /* Don't do this again. */ 451 } else { 452 /* 453 * Destroy the locks before creating them. We don't 454 * know what state they are in so it is better to just 455 * recreate them. 456 */ 457 _lock_destroy(&_thread_signal_lock); 458 _lock_destroy(&_mutex_static_lock); 459 _lock_destroy(&_rwlock_static_lock); 460 _lock_destroy(&_keytable_lock); 461 } 462 463 464 /* Initialize everything else. */ 465 TAILQ_INIT(&_thread_list); 466 TAILQ_INIT(&_thread_gc_list); 467 468 /* Enter a loop to get the existing signal status: */ 469 for (i = 1; i < NSIG; i++) { 470 /* Check for signals which cannot be trapped: */ 471 if (i == SIGKILL || i == SIGSTOP) { 472 } 473 474 /* Get the signal handler details: */ 475 else if (__sys_sigaction(i, NULL, 476 &_thread_sigact[i - 1]) != 0) { 477 /* 478 * Abort this process if signal 479 * initialisation fails: 480 */ 481 PANIC("Cannot read signal handler info"); 482 } 483 484 /* Initialize the SIG_DFL dummy handler count. */ 485 _thread_dfl_count[i] = 0; 486 } 487 488 /* 489 * Install the signal handler for SIGINFO. It isn't 490 * really needed, but it is nice to have for debugging 491 * purposes. 492 */ 493 if (__sys_sigaction(SIGINFO, &act, NULL) != 0) { 494 /* 495 * Abort this process if signal initialisation fails: 496 */ 497 PANIC("Cannot initialize signal handler"); 498 } 499 _thread_sigact[SIGINFO - 1].sa_flags = SA_SIGINFO | SA_RESTART; 500 501 /* 502 * Initialize the lock for temporary installation of signal 503 * handlers (to support sigwait() semantics) and for the 504 * process signal mask and pending signal sets. 505 */ 506 if (_lock_init(&_thread_signal_lock, LCK_ADAPTIVE, 507 _kse_lock_wait, _kse_lock_wakeup) != 0) 508 PANIC("Cannot initialize _thread_signal_lock"); 509 if (_lock_init(&_mutex_static_lock, LCK_ADAPTIVE, 510 _thr_lock_wait, _thr_lock_wakeup) != 0) 511 PANIC("Cannot initialize mutex static init lock"); 512 if (_lock_init(&_rwlock_static_lock, LCK_ADAPTIVE, 513 _thr_lock_wait, _thr_lock_wakeup) != 0) 514 PANIC("Cannot initialize rwlock static init lock"); 515 if (_lock_init(&_keytable_lock, LCK_ADAPTIVE, 516 _thr_lock_wait, _thr_lock_wakeup) != 0) 517 PANIC("Cannot initialize thread specific keytable lock"); 518 519 /* Clear pending signals and get the process signal mask. */ 520 sigemptyset(&_thr_proc_sigpending); 521 __sys_sigprocmask(SIG_SETMASK, NULL, &_thr_proc_sigmask); 522 523 /* 524 * _thread_list_lock and _kse_count are initialized 525 * by _kse_init() 526 */ 527} 528