2 * Copyright (c) 1995-1998 John Birrell <jb@cimlogic.com.au>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
32 * $FreeBSD: src/lib/libc_r/uthread/uthread_init.c,v 1.23.2.11 2003/02/24 23:27:32 das Exp $
33 * $DragonFly: src/lib/libc_r/uthread/uthread_init.c,v 1.2 2003/06/17 04:26:48 dillon Exp $
36 /* Allocate space for global thread variables here: */
37 #define GLOBAL_PTHREAD_PRIVATE
46 #include <sys/ioctl.h>
47 #include <sys/sysctl.h>
49 #include <sys/ttycom.h>
50 #include <sys/param.h>
53 #include <machine/reg.h>
55 #include "pthread_private.h"
58 * These are needed when linking statically. All references within
59 * libgcc (and in the future libc) to these routines are weak, but
60 * if they are not (strongly) referenced by the application or other
61 * libraries, then the actual functions will not be loaded.
63 static void *thread_references[] = {
67 &_pthread_getspecific,
68 &_pthread_setspecific,
70 &_pthread_mutex_destroy,
72 &_pthread_mutex_trylock,
73 &_pthread_mutex_unlock,
75 &_pthread_cond_destroy,
77 &_pthread_cond_timedwait,
78 &_pthread_cond_signal,
79 &_pthread_cond_broadcast
82 #ifdef GCC_2_8_MADE_THREAD_AWARE
83 typedef void *** (*dynamic_handler_allocator)();
84 extern void __set_dynamic_handler_allocator(dynamic_handler_allocator);
86 static pthread_key_t except_head_key;
89 void **__dynamic_handler_chain;
93 static void ***dynamic_allocator_handler_fn()
95 except_struct *dh = (except_struct *)pthread_getspecific(except_head_key);
98 dh = (except_struct *)malloc( sizeof(except_struct) );
99 memset(dh, '\0', sizeof(except_struct));
100 dh->__dynamic_handler_chain= dh->top_elt;
101 pthread_setspecific(except_head_key, (void *)dh);
103 return &dh->__dynamic_handler_chain;
105 #endif /* GCC_2_8_MADE_THREAD_AWARE */
108 * Threaded process initialization
118 struct clockinfo clockinfo;
119 struct sigaction act;
121 /* Check if this function has already been called: */
123 /* Only initialise the threaded application once. */
127 * Make gcc quiescent about thread_references not being
130 if (thread_references[0] == NULL)
131 PANIC("Mandatory pthread_* functions not loaded");
134 * Check for the special case of this process running as
135 * or in place of init as pid = 1:
139 * Setup a new session for this process which is
140 * assumed to be running as root.
143 PANIC("Can't set session ID");
144 if (revoke(_PATH_CONSOLE) != 0)
145 PANIC("Can't revoke console");
146 if ((fd = __sys_open(_PATH_CONSOLE, O_RDWR)) < 0)
147 PANIC("Can't open console");
148 if (setlogin("root") == -1)
149 PANIC("Can't set login to root");
150 if (__sys_ioctl(fd, TIOCSCTTY, (char *) NULL) == -1)
151 PANIC("Can't set controlling terminal");
152 if (__sys_dup2(fd, 0) == -1 ||
153 __sys_dup2(fd, 1) == -1 ||
154 __sys_dup2(fd, 2) == -1)
158 /* Get the standard I/O flags before messing with them : */
159 for (i = 0; i < 3; i++) {
160 if (((_pthread_stdio_flags[i] =
161 __sys_fcntl(i, F_GETFL, NULL)) == -1) &&
163 PANIC("Cannot get stdio flags");
167 * Create a pipe that is written to by the signal handler to prevent
168 * signals being missed in calls to _select:
170 if (__sys_pipe(_thread_kern_pipe) != 0) {
171 /* Cannot create pipe, so abort: */
172 PANIC("Cannot create kernel pipe");
176 * Make sure the pipe does not get in the way of stdio:
178 for (i = 0; i < 2; i++) {
179 if (_thread_kern_pipe[i] < 3) {
180 fd = __sys_fcntl(_thread_kern_pipe[i], F_DUPFD, 3);
182 PANIC("Cannot create kernel pipe");
183 __sys_close(_thread_kern_pipe[i]);
184 _thread_kern_pipe[i] = fd;
187 /* Get the flags for the read pipe: */
188 if ((flags = __sys_fcntl(_thread_kern_pipe[0], F_GETFL, NULL)) == -1) {
189 /* Abort this application: */
190 PANIC("Cannot get kernel read pipe flags");
192 /* Make the read pipe non-blocking: */
193 else if (__sys_fcntl(_thread_kern_pipe[0], F_SETFL, flags | O_NONBLOCK) == -1) {
194 /* Abort this application: */
195 PANIC("Cannot make kernel read pipe non-blocking");
197 /* Get the flags for the write pipe: */
198 else if ((flags = __sys_fcntl(_thread_kern_pipe[1], F_GETFL, NULL)) == -1) {
199 /* Abort this application: */
200 PANIC("Cannot get kernel write pipe flags");
202 /* Make the write pipe non-blocking: */
203 else if (__sys_fcntl(_thread_kern_pipe[1], F_SETFL, flags | O_NONBLOCK) == -1) {
204 /* Abort this application: */
205 PANIC("Cannot get kernel write pipe flags");
207 /* Allocate and initialize the ready queue: */
208 else if (_pq_alloc(&_readyq, PTHREAD_MIN_PRIORITY, PTHREAD_LAST_PRIORITY) != 0) {
209 /* Abort this application: */
210 PANIC("Cannot allocate priority ready queue.");
212 /* Allocate memory for the thread structure of the initial thread: */
213 else if ((_thread_initial = (pthread_t) malloc(sizeof(struct pthread))) == NULL) {
215 * Insufficient memory to initialise this application, so
218 PANIC("Cannot allocate memory for initial thread");
220 /* Allocate memory for the scheduler stack: */
221 else if ((_thread_kern_sched_stack = malloc(SCHED_STACK_SIZE)) == NULL)
222 PANIC("Failed to allocate stack for scheduler");
224 /* Zero the global kernel thread structure: */
225 memset(&_thread_kern_thread, 0, sizeof(struct pthread));
226 _thread_kern_thread.flags = PTHREAD_FLAGS_PRIVATE;
227 memset(_thread_initial, 0, sizeof(struct pthread));
229 /* Initialize the waiting and work queues: */
230 TAILQ_INIT(&_waitingq);
233 /* Initialize the scheduling switch hook routine: */
234 _sched_switch_hook = NULL;
236 /* Give this thread default attributes: */
237 memcpy((void *) &_thread_initial->attr, &pthread_attr_default,
238 sizeof(struct pthread_attr));
240 /* Initialize the thread stack cache: */
241 SLIST_INIT(&_stackq);
243 /* Find the stack top */
245 mib[1] = KERN_USRSTACK;
247 if (sysctl(mib, 2, &_usrstack, &len, NULL, 0) == -1)
248 _usrstack = (void *)USRSTACK;
249 _next_stack = _usrstack - PTHREAD_STACK_INITIAL -
250 PTHREAD_STACK_DEFAULT - (2 * PTHREAD_STACK_GUARD);
252 * Create a red zone below the main stack. All other stacks are
253 * constrained to a maximum size by the paramters passed to
254 * mmap(), but this stack is only limited by resource limits, so
255 * this stack needs an explicitly mapped red zone to protect the
256 * thread stack that is just beyond.
258 if (mmap(_usrstack - PTHREAD_STACK_INITIAL -
259 PTHREAD_STACK_GUARD, PTHREAD_STACK_GUARD, 0, MAP_ANON,
260 -1, 0) == MAP_FAILED)
261 PANIC("Cannot allocate red zone for initial thread");
263 /* Set the main thread stack pointer. */
264 _thread_initial->stack = _usrstack - PTHREAD_STACK_INITIAL;
266 /* Set the stack attributes: */
267 _thread_initial->attr.stackaddr_attr = _thread_initial->stack;
268 _thread_initial->attr.stacksize_attr = PTHREAD_STACK_INITIAL;
270 /* Setup the context for the scheduler: */
271 _setjmp(_thread_kern_sched_jb);
272 SET_STACK_JB(_thread_kern_sched_jb, _thread_kern_sched_stack +
273 SCHED_STACK_SIZE - sizeof(double));
274 SET_RETURN_ADDR_JB(_thread_kern_sched_jb, _thread_kern_scheduler);
277 * Write a magic value to the thread structure
278 * to help identify valid ones:
280 _thread_initial->magic = PTHREAD_MAGIC;
282 /* Set the initial cancel state */
283 _thread_initial->cancelflags = PTHREAD_CANCEL_ENABLE |
284 PTHREAD_CANCEL_DEFERRED;
286 /* Default the priority of the initial thread: */
287 _thread_initial->base_priority = PTHREAD_DEFAULT_PRIORITY;
288 _thread_initial->active_priority = PTHREAD_DEFAULT_PRIORITY;
289 _thread_initial->inherited_priority = 0;
291 /* Initialise the state of the initial thread: */
292 _thread_initial->state = PS_RUNNING;
294 /* Set the name of the thread: */
295 _thread_initial->name = strdup("_thread_initial");
297 /* Initialize joiner to NULL (no joiner): */
298 _thread_initial->joiner = NULL;
300 /* Initialize the owned mutex queue and count: */
301 TAILQ_INIT(&(_thread_initial->mutexq));
302 _thread_initial->priority_mutex_count = 0;
304 /* Initialize the global scheduling time: */
306 gettimeofday((struct timeval *) &_sched_tod, NULL);
308 /* Initialize last active: */
309 _thread_initial->last_active = (long) _sched_ticks;
311 /* Initialize the initial context: */
312 _thread_initial->curframe = NULL;
314 /* Initialise the rest of the fields: */
315 _thread_initial->poll_data.nfds = 0;
316 _thread_initial->poll_data.fds = NULL;
317 _thread_initial->sig_defer_count = 0;
318 _thread_initial->yield_on_sig_undefer = 0;
319 _thread_initial->specific_data = NULL;
320 _thread_initial->cleanup = NULL;
321 _thread_initial->flags = 0;
322 _thread_initial->error = 0;
323 TAILQ_INIT(&_thread_list);
324 TAILQ_INSERT_HEAD(&_thread_list, _thread_initial, tle);
325 _set_curthread(_thread_initial);
327 /* Initialise the global signal action structure: */
328 sigfillset(&act.sa_mask);
329 act.sa_handler = (void (*) ()) _thread_sig_handler;
330 act.sa_flags = SA_SIGINFO | SA_RESTART;
332 /* Clear pending signals for the process: */
333 sigemptyset(&_process_sigpending);
335 /* Clear the signal queue: */
336 memset(_thread_sigq, 0, sizeof(_thread_sigq));
338 /* Enter a loop to get the existing signal status: */
339 for (i = 1; i < NSIG; i++) {
340 /* Check for signals which cannot be trapped: */
341 if (i == SIGKILL || i == SIGSTOP) {
344 /* Get the signal handler details: */
345 else if (__sys_sigaction(i, NULL,
346 &_thread_sigact[i - 1]) != 0) {
348 * Abort this process if signal
349 * initialisation fails:
351 PANIC("Cannot read signal handler info");
354 /* Initialize the SIG_DFL dummy handler count. */
355 _thread_dfl_count[i] = 0;
359 * Install the signal handler for the most important
360 * signals that the user-thread kernel needs. Actually
361 * SIGINFO isn't really needed, but it is nice to have.
363 if (__sys_sigaction(_SCHED_SIGNAL, &act, NULL) != 0 ||
364 __sys_sigaction(SIGINFO, &act, NULL) != 0 ||
365 __sys_sigaction(SIGCHLD, &act, NULL) != 0) {
367 * Abort this process if signal initialisation fails:
369 PANIC("Cannot initialise signal handler");
371 _thread_sigact[_SCHED_SIGNAL - 1].sa_flags = SA_SIGINFO;
372 _thread_sigact[SIGINFO - 1].sa_flags = SA_SIGINFO;
373 _thread_sigact[SIGCHLD - 1].sa_flags = SA_SIGINFO;
375 /* Get the process signal mask: */
376 __sys_sigprocmask(SIG_SETMASK, NULL, &_process_sigmask);
378 /* Get the kernel clockrate: */
380 mib[1] = KERN_CLOCKRATE;
381 len = sizeof (struct clockinfo);
382 if (sysctl(mib, 2, &clockinfo, &len, NULL, 0) == 0)
383 _clock_res_usec = clockinfo.tick > CLOCK_RES_USEC_MIN ?
384 clockinfo.tick : CLOCK_RES_USEC_MIN;
386 /* Get the table size: */
387 if ((_thread_dtablesize = getdtablesize()) < 0) {
389 * Cannot get the system defined table size, so abort
392 PANIC("Cannot get dtablesize");
394 /* Allocate memory for the file descriptor table: */
395 if ((_thread_fd_table = (struct fd_table_entry **) malloc(sizeof(struct fd_table_entry *) * _thread_dtablesize)) == NULL) {
396 /* Avoid accesses to file descriptor table on exit: */
397 _thread_dtablesize = 0;
400 * Cannot allocate memory for the file descriptor
401 * table, so abort this process.
403 PANIC("Cannot allocate memory for file descriptor table");
405 /* Allocate memory for the pollfd table: */
406 if ((_thread_pfd_table = (struct pollfd *) malloc(sizeof(struct pollfd) * _thread_dtablesize)) == NULL) {
408 * Cannot allocate memory for the file descriptor
409 * table, so abort this process.
411 PANIC("Cannot allocate memory for pollfd table");
414 * Enter a loop to initialise the file descriptor
417 for (i = 0; i < _thread_dtablesize; i++) {
418 /* Initialise the file descriptor table: */
419 _thread_fd_table[i] = NULL;
422 /* Initialize stdio file descriptor table entries: */
423 for (i = 0; i < 3; i++) {
424 if ((_thread_fd_table_init(i) != 0) &&
426 PANIC("Cannot initialize stdio file "
427 "descriptor table entry");
432 #ifdef GCC_2_8_MADE_THREAD_AWARE
433 /* Create the thread-specific data for the exception linked list. */
434 if(pthread_key_create(&except_head_key, NULL) != 0)
435 PANIC("Failed to create thread specific execption head");
437 /* Setup the gcc exception handler per thread. */
438 __set_dynamic_handler_allocator( dynamic_allocator_handler_fn );
439 #endif /* GCC_2_8_MADE_THREAD_AWARE */
441 /* Initialise the garbage collector mutex and condition variable. */
442 if (pthread_mutex_init(&_gc_mutex,NULL) != 0 ||
443 pthread_cond_init(&_gc_cond,NULL) != 0)
444 PANIC("Failed to initialise garbage collector mutex or condvar");
448 * Special start up code for NetBSD/Alpha
450 #if defined(__NetBSD__) && defined(__alpha__)
452 main(int argc, char *argv[], char *env);
455 _thread_main(int argc, char *argv[], char *env)
458 return (main(argc, argv, env));