thr_init.c revision 67097
1/* 2 * Copyright (c) 1995-1998 John Birrell <jb@cimlogic.com.au> 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. All advertising materials mentioning features or use of this software 14 * must display the following acknowledgement: 15 * This product includes software developed by John Birrell. 16 * 4. Neither the name of the author nor the names of any co-contributors 17 * may be used to endorse or promote products derived from this software 18 * without specific prior written permission. 19 * 20 * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND 21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 30 * SUCH DAMAGE. 31 * 32 * $FreeBSD: head/lib/libkse/thread/thr_init.c 67097 2000-10-13 22:12:32Z deischen $ 33 */ 34 35/* Allocate space for global thread variables here: */ 36#define GLOBAL_PTHREAD_PRIVATE 37 38#include <errno.h> 39#include <stdlib.h> 40#include <string.h> 41#include <fcntl.h> 42#include <paths.h> 43#include <poll.h> 44#include <unistd.h> 45#include <sys/ioctl.h> 46#include <sys/sysctl.h> 47#include <sys/time.h> 48#include <sys/ttycom.h> 49#include <sys/param.h> 50#include <sys/user.h> 51#include <sys/mman.h> 52#ifdef _THREAD_SAFE 53#include <machine/reg.h> 54#include <pthread.h> 55#include "pthread_private.h" 56 57#ifdef GCC_2_8_MADE_THREAD_AWARE 58typedef void *** (*dynamic_handler_allocator)(); 59extern void __set_dynamic_handler_allocator(dynamic_handler_allocator); 60 61static pthread_key_t except_head_key; 62 63typedef struct { 64 void **__dynamic_handler_chain; 65 void *top_elt[2]; 66} except_struct; 67 68static void ***dynamic_allocator_handler_fn() 69{ 70 except_struct *dh = (except_struct *)pthread_getspecific(except_head_key); 71 72 if(dh == NULL) { 73 dh = (except_struct *)malloc( sizeof(except_struct) ); 74 memset(dh, '\0', sizeof(except_struct)); 75 dh->__dynamic_handler_chain= dh->top_elt; 76 pthread_setspecific(except_head_key, (void *)dh); 77 } 78 return &dh->__dynamic_handler_chain; 79} 80#endif /* GCC_2_8_MADE_THREAD_AWARE */ 81 82/* 83 * Threaded process initialization 84 */ 85void 86_thread_init(void) 87{ 88 int fd; 89 int flags; 90 int i; 91 size_t len; 92 int mib[2]; 93 struct clockinfo clockinfo; 94 struct sigaction act; 95 struct itimerval itimer; 96 97 /* Check if this function has already been called: */ 98 if (_thread_initial) 99 /* Only initialise the threaded application once. */ 100 return; 101 102 /* 103 * Check for the special case of this process running as 104 * or in place of init as pid = 1: 105 */ 106 if (getpid() == 1) { 107 /* 108 * Setup a new session for this process which is 109 * assumed to be running as root. 110 */ 111 if (setsid() == -1) 112 PANIC("Can't set session ID"); 113 if (revoke(_PATH_CONSOLE) != 0) 114 PANIC("Can't revoke console"); 115 if ((fd = _thread_sys_open(_PATH_CONSOLE, O_RDWR)) < 0) 116 PANIC("Can't open console"); 117 if (setlogin("root") == -1) 118 PANIC("Can't set login to root"); 119 if (_thread_sys_ioctl(fd,TIOCSCTTY, (char *) NULL) == -1) 120 PANIC("Can't set controlling terminal"); 121 if (_thread_sys_dup2(fd,0) == -1 || 122 _thread_sys_dup2(fd,1) == -1 || 123 _thread_sys_dup2(fd,2) == -1) 124 PANIC("Can't dup2"); 125 } 126 127 /* Get the standard I/O flags before messing with them : */ 128 for (i = 0; i < 3; i++) 129 if (((_pthread_stdio_flags[i] = 130 _thread_sys_fcntl(i,F_GETFL, NULL)) == -1) && 131 (errno != EBADF)) 132 PANIC("Cannot get stdio flags"); 133 134 /* 135 * Create a pipe that is written to by the signal handler to prevent 136 * signals being missed in calls to _select: 137 */ 138 if (_thread_sys_pipe(_thread_kern_pipe) != 0) { 139 /* Cannot create pipe, so abort: */ 140 PANIC("Cannot create kernel pipe"); 141 } 142 /* Get the flags for the read pipe: */ 143 else if ((flags = _thread_sys_fcntl(_thread_kern_pipe[0], F_GETFL, NULL)) == -1) { 144 /* Abort this application: */ 145 PANIC("Cannot get kernel read pipe flags"); 146 } 147 /* Make the read pipe non-blocking: */ 148 else if (_thread_sys_fcntl(_thread_kern_pipe[0], F_SETFL, flags | O_NONBLOCK) == -1) { 149 /* Abort this application: */ 150 PANIC("Cannot make kernel read pipe non-blocking"); 151 } 152 /* Get the flags for the write pipe: */ 153 else if ((flags = _thread_sys_fcntl(_thread_kern_pipe[1], F_GETFL, NULL)) == -1) { 154 /* Abort this application: */ 155 PANIC("Cannot get kernel write pipe flags"); 156 } 157 /* Make the write pipe non-blocking: */ 158 else if (_thread_sys_fcntl(_thread_kern_pipe[1], F_SETFL, flags | O_NONBLOCK) == -1) { 159 /* Abort this application: */ 160 PANIC("Cannot get kernel write pipe flags"); 161 } 162 /* Allocate and initialize the ready queue: */ 163 else if (_pq_alloc(&_readyq, PTHREAD_MIN_PRIORITY, PTHREAD_LAST_PRIORITY) != 0) { 164 /* Abort this application: */ 165 PANIC("Cannot allocate priority ready queue."); 166 } 167 /* Allocate memory for the thread structure of the initial thread: */ 168 else if ((_thread_initial = (pthread_t) malloc(sizeof(struct pthread))) == NULL) { 169 /* 170 * Insufficient memory to initialise this application, so 171 * abort: 172 */ 173 PANIC("Cannot allocate memory for initial thread"); 174 } 175 /* Allocate memory for the scheduler stack: */ 176 else if ((_thread_kern_sched_stack = malloc(PAGE_SIZE * 10)) == NULL) 177 PANIC("Failed to allocate stack for scheduler"); 178 else { 179 /* Zero the global kernel thread structure: */ 180 memset(&_thread_kern_thread, 0, sizeof(struct pthread)); 181 _thread_kern_thread.flags = PTHREAD_FLAGS_PRIVATE; 182 memset(_thread_initial, 0, sizeof(struct pthread)); 183 184 /* Initialize the waiting and work queues: */ 185 TAILQ_INIT(&_waitingq); 186 TAILQ_INIT(&_workq); 187 188 /* Initialize the scheduling switch hook routine: */ 189 _sched_switch_hook = NULL; 190 191 /* Give this thread default attributes: */ 192 memcpy((void *) &_thread_initial->attr, &pthread_attr_default, 193 sizeof(struct pthread_attr)); 194 195 /* Initialize the thread stack cache: */ 196 SLIST_INIT(&_stackq); 197 198 /* 199 * Create a red zone below the main stack. All other stacks are 200 * constrained to a maximum size by the paramters passed to 201 * mmap(), but this stack is only limited by resource limits, so 202 * this stack needs an explicitly mapped red zone to protect the 203 * thread stack that is just beyond. 204 */ 205 if (mmap((void *) USRSTACK - PTHREAD_STACK_INITIAL - 206 PTHREAD_STACK_GUARD, PTHREAD_STACK_GUARD, 0, MAP_ANON, 207 -1, 0) == MAP_FAILED) 208 PANIC("Cannot allocate red zone for initial thread"); 209 210 /* Set the main thread stack pointer. */ 211 _thread_initial->stack = (void *) USRSTACK - 212 PTHREAD_STACK_INITIAL; 213 214 /* Set the stack attributes: */ 215 _thread_initial->attr.stackaddr_attr = _thread_initial->stack; 216 _thread_initial->attr.stacksize_attr = PTHREAD_STACK_INITIAL; 217 218 /* Setup the context for the scheduler: */ 219 _setjmp(_thread_kern_sched_jb); 220 SET_STACK_JB(_thread_kern_sched_jb, 221 _thread_kern_sched_stack + PAGE_SIZE*10 - sizeof(double)); 222 SET_RETURN_ADDR_JB(_thread_kern_sched_jb, _thread_kern_scheduler); 223 224 /* 225 * Write a magic value to the thread structure 226 * to help identify valid ones: 227 */ 228 _thread_initial->magic = PTHREAD_MAGIC; 229 230 /* Set the initial cancel state */ 231 _thread_initial->cancelflags = PTHREAD_CANCEL_ENABLE | 232 PTHREAD_CANCEL_DEFERRED; 233 234 /* Default the priority of the initial thread: */ 235 _thread_initial->base_priority = PTHREAD_DEFAULT_PRIORITY; 236 _thread_initial->active_priority = PTHREAD_DEFAULT_PRIORITY; 237 _thread_initial->inherited_priority = 0; 238 239 /* Initialise the state of the initial thread: */ 240 _thread_initial->state = PS_RUNNING; 241 242 /* Initialise the queue: */ 243 TAILQ_INIT(&(_thread_initial->join_queue)); 244 245 /* Initialize the owned mutex queue and count: */ 246 TAILQ_INIT(&(_thread_initial->mutexq)); 247 _thread_initial->priority_mutex_count = 0; 248 249 /* Initialize the global scheduling time: */ 250 _sched_ticks = 0; 251 gettimeofday((struct timeval *) &_sched_tod, NULL); 252 253 /* Initialize last active: */ 254 _thread_initial->last_active = (long) _sched_ticks; 255 256 /* Initialize the initial signal frame: */ 257 _thread_initial->sigframes[0] = &_thread_initial->sigframe0; 258 _thread_initial->curframe = &_thread_initial->sigframe0; 259 _thread_initial->curframe->ctxtype = CTX_JB_NOSIG; 260 /* Set the base of the stack: */ 261 _thread_initial->curframe->stackp = (unsigned long) USRSTACK; 262 263 /* Initialise the rest of the fields: */ 264 _thread_initial->poll_data.nfds = 0; 265 _thread_initial->poll_data.fds = NULL; 266 _thread_initial->sig_defer_count = 0; 267 _thread_initial->yield_on_sig_undefer = 0; 268 _thread_initial->specific_data = NULL; 269 _thread_initial->cleanup = NULL; 270 _thread_initial->flags = 0; 271 _thread_initial->error = 0; 272 TAILQ_INIT(&_thread_list); 273 TAILQ_INSERT_HEAD(&_thread_list, _thread_initial, tle); 274 _thread_run = _thread_initial; 275 276 /* Initialise the global signal action structure: */ 277 sigfillset(&act.sa_mask); 278 act.sa_handler = (void (*) ()) _thread_sig_handler; 279 act.sa_flags = SA_SIGINFO; 280 281 /* Clear pending signals for the process: */ 282 sigemptyset(&_process_sigpending); 283 284 /* Clear the signal queue: */ 285 memset(_thread_sigq, 0, sizeof(_thread_sigq)); 286 287 /* Enter a loop to get the existing signal status: */ 288 for (i = 1; i < NSIG; i++) { 289 /* Check for signals which cannot be trapped: */ 290 if (i == SIGKILL || i == SIGSTOP) { 291 } 292 293 /* Get the signal handler details: */ 294 else if (_thread_sys_sigaction(i, NULL, 295 &_thread_sigact[i - 1]) != 0) { 296 /* 297 * Abort this process if signal 298 * initialisation fails: 299 */ 300 PANIC("Cannot read signal handler info"); 301 } 302 303 /* Initialize the SIG_DFL dummy handler count. */ 304 _thread_dfl_count[i] = 0; 305 } 306 307 /* 308 * Install the signal handler for the most important 309 * signals that the user-thread kernel needs. Actually 310 * SIGINFO isn't really needed, but it is nice to have. 311 */ 312 if (_thread_sys_sigaction(_SCHED_SIGNAL, &act, NULL) != 0 || 313 _thread_sys_sigaction(SIGINFO, &act, NULL) != 0 || 314 _thread_sys_sigaction(SIGCHLD, &act, NULL) != 0) { 315 /* 316 * Abort this process if signal initialisation fails: 317 */ 318 PANIC("Cannot initialise signal handler"); 319 } 320 _thread_sigact[_SCHED_SIGNAL - 1].sa_flags = SA_SIGINFO; 321 _thread_sigact[SIGINFO - 1].sa_flags = SA_SIGINFO; 322 _thread_sigact[SIGCHLD - 1].sa_flags = SA_SIGINFO; 323 324 /* Get the process signal mask: */ 325 _thread_sys_sigprocmask(SIG_SETMASK, NULL, &_process_sigmask); 326 327 /* Get the kernel clockrate: */ 328 mib[0] = CTL_KERN; 329 mib[1] = KERN_CLOCKRATE; 330 len = sizeof (struct clockinfo); 331 if (sysctl(mib, 2, &clockinfo, &len, NULL, 0) == 0) 332 _clock_res_usec = clockinfo.tick; 333 334 /* Get the table size: */ 335 if ((_thread_dtablesize = getdtablesize()) < 0) { 336 /* 337 * Cannot get the system defined table size, so abort 338 * this process. 339 */ 340 PANIC("Cannot get dtablesize"); 341 } 342 /* Allocate memory for the file descriptor table: */ 343 if ((_thread_fd_table = (struct fd_table_entry **) malloc(sizeof(struct fd_table_entry *) * _thread_dtablesize)) == NULL) { 344 /* Avoid accesses to file descriptor table on exit: */ 345 _thread_dtablesize = 0; 346 347 /* 348 * Cannot allocate memory for the file descriptor 349 * table, so abort this process. 350 */ 351 PANIC("Cannot allocate memory for file descriptor table"); 352 } 353 /* Allocate memory for the pollfd table: */ 354 if ((_thread_pfd_table = (struct pollfd *) malloc(sizeof(struct pollfd) * _thread_dtablesize)) == NULL) { 355 /* 356 * Cannot allocate memory for the file descriptor 357 * table, so abort this process. 358 */ 359 PANIC("Cannot allocate memory for pollfd table"); 360 } else { 361 /* 362 * Enter a loop to initialise the file descriptor 363 * table: 364 */ 365 for (i = 0; i < _thread_dtablesize; i++) { 366 /* Initialise the file descriptor table: */ 367 _thread_fd_table[i] = NULL; 368 } 369 370 /* Initialize stdio file descriptor table entries: */ 371 for (i = 0; i < 3; i++) { 372 if ((_thread_fd_table_init(i) != 0) && 373 (errno != EBADF)) 374 PANIC("Cannot initialize stdio file " 375 "descriptor table entry"); 376 } 377 378 /* Install the scheduling timer: */ 379 itimer.it_interval.tv_sec = 0; 380 itimer.it_interval.tv_usec = _clock_res_usec; 381 itimer.it_value = itimer.it_interval; 382 if (setitimer(_ITIMER_SCHED_TIMER, &itimer, NULL) != 0) 383 PANIC("Cannot set interval timer"); 384 385 } 386 } 387 388#ifdef GCC_2_8_MADE_THREAD_AWARE 389 /* Create the thread-specific data for the exception linked list. */ 390 if(pthread_key_create(&except_head_key, NULL) != 0) 391 PANIC("Failed to create thread specific execption head"); 392 393 /* Setup the gcc exception handler per thread. */ 394 __set_dynamic_handler_allocator( dynamic_allocator_handler_fn ); 395#endif /* GCC_2_8_MADE_THREAD_AWARE */ 396 397 /* Initialise the garbage collector mutex and condition variable. */ 398 if (pthread_mutex_init(&_gc_mutex,NULL) != 0 || 399 pthread_cond_init(&_gc_cond,NULL) != 0) 400 PANIC("Failed to initialise garbage collector mutex or condvar"); 401} 402 403/* 404 * Special start up code for NetBSD/Alpha 405 */ 406#if defined(__NetBSD__) && defined(__alpha__) 407int 408main(int argc, char *argv[], char *env); 409 410int 411_thread_main(int argc, char *argv[], char *env) 412{ 413 _thread_init(); 414 return (main(argc, argv, env)); 415} 416#endif 417#else 418/* 419 * A stub for non-threaded programs. 420 */ 421void 422_thread_init(void) 423{ 424} 425#endif 426