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
35 /* Allocate space for global thread variables here: */
36 #define GLOBAL_PTHREAD_PRIVATE
38 #include "namespace.h"
39 #include <sys/param.h>
40 #include <sys/types.h>
41 #include <machine/reg.h>
43 #include <sys/ioctl.h>
44 #include <sys/mount.h>
46 #include <sys/socket.h>
47 #include <sys/event.h>
49 #include <sys/sysctl.h>
51 #include <sys/ttycom.h>
60 #include <pthread_np.h>
66 #include "un-namespace.h"
68 #include "libc_private.h"
69 #include "pthread_private.h"
71 int __pthread_cond_wait(pthread_cond_t *, pthread_mutex_t *);
72 int __pthread_mutex_lock(pthread_mutex_t *);
73 int __pthread_mutex_trylock(pthread_mutex_t *);
76 * All weak references used within libc should be in this table.
77 * This allows static libraries to work.
79 static void *references[] = {
104 &_pthread_cond_destroy,
106 &_pthread_cond_signal,
108 &_pthread_getspecific,
109 &_pthread_key_create,
110 &_pthread_key_delete,
111 &_pthread_mutex_destroy,
112 &_pthread_mutex_init,
113 &_pthread_mutex_lock,
114 &_pthread_mutex_trylock,
115 &_pthread_mutex_unlock,
116 &_pthread_mutexattr_init,
117 &_pthread_mutexattr_destroy,
118 &_pthread_mutexattr_settype,
120 &_pthread_setspecific,
140 * These are needed when linking statically. All references within
141 * libgcc (and libc) to these routines are weak, but if they are not
142 * (strongly) referenced by the application or other libraries, then
143 * the actual functions will not be loaded.
145 static void *libgcc_references[] = {
147 &_pthread_key_create,
148 &_pthread_key_delete,
149 &_pthread_getspecific,
150 &_pthread_setspecific,
151 &_pthread_mutex_init,
152 &_pthread_mutex_destroy,
153 &_pthread_mutex_lock,
154 &_pthread_mutex_trylock,
155 &_pthread_mutex_unlock
158 #define DUAL_ENTRY(entry) \
159 (pthread_func_t)entry, (pthread_func_t)entry
161 static pthread_func_t jmp_table[][2] = {
162 {DUAL_ENTRY(_pthread_cond_broadcast)}, /* PJT_COND_BROADCAST */
163 {DUAL_ENTRY(_pthread_cond_destroy)}, /* PJT_COND_DESTROY */
164 {DUAL_ENTRY(_pthread_cond_init)}, /* PJT_COND_INIT */
165 {DUAL_ENTRY(_pthread_cond_signal)}, /* PJT_COND_SIGNAL */
166 {(pthread_func_t)__pthread_cond_wait,
167 (pthread_func_t)_pthread_cond_wait}, /* PJT_COND_WAIT */
168 {DUAL_ENTRY(_pthread_getspecific)}, /* PJT_GETSPECIFIC */
169 {DUAL_ENTRY(_pthread_key_create)}, /* PJT_KEY_CREATE */
170 {DUAL_ENTRY(_pthread_key_delete)}, /* PJT_KEY_DELETE*/
171 {DUAL_ENTRY(_pthread_main_np)}, /* PJT_MAIN_NP */
172 {DUAL_ENTRY(_pthread_mutex_destroy)}, /* PJT_MUTEX_DESTROY */
173 {DUAL_ENTRY(_pthread_mutex_init)}, /* PJT_MUTEX_INIT */
174 {(pthread_func_t)__pthread_mutex_lock,
175 (pthread_func_t)_pthread_mutex_lock}, /* PJT_MUTEX_LOCK */
176 {(pthread_func_t)__pthread_mutex_trylock,
177 (pthread_func_t)_pthread_mutex_trylock},/* PJT_MUTEX_TRYLOCK */
178 {DUAL_ENTRY(_pthread_mutex_unlock)}, /* PJT_MUTEX_UNLOCK */
179 {DUAL_ENTRY(_pthread_mutexattr_destroy)}, /* PJT_MUTEXATTR_DESTROY */
180 {DUAL_ENTRY(_pthread_mutexattr_init)}, /* PJT_MUTEXATTR_INIT */
181 {DUAL_ENTRY(_pthread_mutexattr_settype)}, /* PJT_MUTEXATTR_SETTYPE */
182 {DUAL_ENTRY(_pthread_once)}, /* PJT_ONCE */
183 {DUAL_ENTRY(_pthread_rwlock_destroy)}, /* PJT_RWLOCK_DESTROY */
184 {DUAL_ENTRY(_pthread_rwlock_init)}, /* PJT_RWLOCK_INIT */
185 {DUAL_ENTRY(_pthread_rwlock_rdlock)}, /* PJT_RWLOCK_RDLOCK */
186 {DUAL_ENTRY(_pthread_rwlock_tryrdlock)},/* PJT_RWLOCK_TRYRDLOCK */
187 {DUAL_ENTRY(_pthread_rwlock_trywrlock)},/* PJT_RWLOCK_TRYWRLOCK */
188 {DUAL_ENTRY(_pthread_rwlock_unlock)}, /* PJT_RWLOCK_UNLOCK */
189 {DUAL_ENTRY(_pthread_rwlock_wrlock)}, /* PJT_RWLOCK_WRLOCK */
190 {DUAL_ENTRY(_pthread_self)}, /* PJT_SELF */
191 {DUAL_ENTRY(_pthread_setspecific)}, /* PJT_SETSPECIFIC */
192 {DUAL_ENTRY(_pthread_sigmask)} /* PJT_SIGMASK */
195 int _pthread_guard_default;
196 int _pthread_page_size;
197 int _pthread_stack_default;
198 int _pthread_stack_initial;
201 * Threaded process initialization
211 int sched_stack_size; /* Size of scheduler stack. */
212 #if !defined(__ia64__)
216 struct clockinfo clockinfo;
217 struct sigaction act;
220 /* Check if this function has already been called: */
222 /* Only initialise the threaded application once. */
225 _pthread_page_size = getpagesize();;
226 _pthread_guard_default = _pthread_page_size;
227 sched_stack_size = 4 * _pthread_page_size;
228 if (sizeof(void *) == 8) {
229 _pthread_stack_default = PTHREAD_STACK64_DEFAULT;
230 _pthread_stack_initial = PTHREAD_STACK64_INITIAL;
233 _pthread_stack_default = PTHREAD_STACK32_DEFAULT;
234 _pthread_stack_initial = PTHREAD_STACK32_INITIAL;
237 _pthread_attr_default.guardsize_attr = _pthread_guard_default;
238 _pthread_attr_default.stacksize_attr = _pthread_stack_default;
241 * Make gcc quiescent about {,libgcc_}references not being
244 if ((references[0] == NULL) || (libgcc_references[0] == NULL))
245 PANIC("Failed loading mandatory references in _thread_init");
248 * Check the size of the jump table to make sure it is preset
249 * with the correct number of entries.
251 if (sizeof(jmp_table) != (sizeof(pthread_func_t) * PJT_MAX * 2))
252 PANIC("Thread jump table not properly initialized");
253 memcpy(__thr_jtable, jmp_table, sizeof(jmp_table));
256 * Check for the special case of this process running as
257 * or in place of init as pid = 1:
261 * Setup a new session for this process which is
262 * assumed to be running as root.
265 PANIC("Can't set session ID");
266 if (revoke(_PATH_CONSOLE) != 0)
267 PANIC("Can't revoke console");
268 if ((fd = __sys_open(_PATH_CONSOLE, O_RDWR)) < 0)
269 PANIC("Can't open console");
270 if (setlogin("root") == -1)
271 PANIC("Can't set login to root");
272 if (__sys_ioctl(fd, TIOCSCTTY, (char *) NULL) == -1)
273 PANIC("Can't set controlling terminal");
274 if (__sys_dup2(fd, 0) == -1 ||
275 __sys_dup2(fd, 1) == -1 ||
276 __sys_dup2(fd, 2) == -1)
280 /* Get the standard I/O flags before messing with them : */
281 for (i = 0; i < 3; i++) {
282 if (((_pthread_stdio_flags[i] =
283 __sys_fcntl(i, F_GETFL, NULL)) == -1) &&
285 PANIC("Cannot get stdio flags");
289 * Create a pipe that is written to by the signal handler to prevent
290 * signals being missed in calls to _select:
292 if (__sys_pipe(_thread_kern_pipe) != 0) {
293 /* Cannot create pipe, so abort: */
294 PANIC("Cannot create kernel pipe");
298 * Make sure the pipe does not get in the way of stdio:
300 for (i = 0; i < 2; i++) {
301 if (_thread_kern_pipe[i] < 3) {
302 fd = __sys_fcntl(_thread_kern_pipe[i], F_DUPFD, 3);
304 PANIC("Cannot create kernel pipe");
305 __sys_close(_thread_kern_pipe[i]);
306 _thread_kern_pipe[i] = fd;
309 /* Get the flags for the read pipe: */
310 if ((flags = __sys_fcntl(_thread_kern_pipe[0], F_GETFL, NULL)) == -1) {
311 /* Abort this application: */
312 PANIC("Cannot get kernel read pipe flags");
314 /* Make the read pipe non-blocking: */
315 else if (__sys_fcntl(_thread_kern_pipe[0], F_SETFL, flags | O_NONBLOCK) == -1) {
316 /* Abort this application: */
317 PANIC("Cannot make kernel read pipe non-blocking");
319 /* Get the flags for the write pipe: */
320 else if ((flags = __sys_fcntl(_thread_kern_pipe[1], F_GETFL, NULL)) == -1) {
321 /* Abort this application: */
322 PANIC("Cannot get kernel write pipe flags");
324 /* Make the write pipe non-blocking: */
325 else if (__sys_fcntl(_thread_kern_pipe[1], F_SETFL, flags | O_NONBLOCK) == -1) {
326 /* Abort this application: */
327 PANIC("Cannot get kernel write pipe flags");
329 /* Allocate and initialize the ready queue: */
330 else if (_pq_alloc(&_readyq, PTHREAD_MIN_PRIORITY, PTHREAD_LAST_PRIORITY) != 0) {
331 /* Abort this application: */
332 PANIC("Cannot allocate priority ready queue.");
334 /* Allocate memory for the thread structure of the initial thread: */
335 else if ((_thread_initial = (pthread_t) malloc(sizeof(struct pthread))) == NULL) {
337 * Insufficient memory to initialise this application, so
340 PANIC("Cannot allocate memory for initial thread");
342 /* Allocate memory for the scheduler stack: */
343 else if ((_thread_kern_sched_stack = malloc(sched_stack_size)) == NULL)
344 PANIC("Failed to allocate stack for scheduler");
346 /* Zero the global kernel thread structure: */
347 memset(&_thread_kern_thread, 0, sizeof(struct pthread));
348 _thread_kern_thread.flags = PTHREAD_FLAGS_PRIVATE;
349 memset(_thread_initial, 0, sizeof(struct pthread));
351 /* Initialize the waiting and work queues: */
352 TAILQ_INIT(&_waitingq);
355 /* Initialize the scheduling switch hook routine: */
356 _sched_switch_hook = NULL;
358 /* Give this thread default attributes: */
359 memcpy((void *) &_thread_initial->attr, &_pthread_attr_default,
360 sizeof(struct pthread_attr));
362 /* Find the stack top */
364 mib[1] = KERN_USRSTACK;
365 len = sizeof (_usrstack);
366 if (sysctl(mib, 2, &_usrstack, &len, NULL, 0) == -1)
367 _usrstack = (void *)USRSTACK;
369 * Create a red zone below the main stack. All other stacks are
370 * constrained to a maximum size by the paramters passed to
371 * mmap(), but this stack is only limited by resource limits, so
372 * this stack needs an explicitly mapped red zone to protect the
373 * thread stack that is just beyond.
375 if (mmap(_usrstack - _pthread_stack_initial -
376 _pthread_guard_default, _pthread_guard_default, 0,
377 MAP_ANON, -1, 0) == MAP_FAILED)
378 PANIC("Cannot allocate red zone for initial thread");
380 /* Set the main thread stack pointer. */
381 _thread_initial->stack = _usrstack - _pthread_stack_initial;
383 /* Set the stack attributes: */
384 _thread_initial->attr.stackaddr_attr = _thread_initial->stack;
385 _thread_initial->attr.stacksize_attr = _pthread_stack_initial;
387 /* Setup the context for the scheduler: */
388 _setjmp(_thread_kern_sched_jb);
389 #if !defined(__ia64__)
390 stackp = (long)_thread_kern_sched_stack + sched_stack_size - sizeof(double);
391 #if defined(__amd64__)
394 SET_STACK_JB(_thread_kern_sched_jb, stackp);
396 SET_STACK_JB(_thread_kern_sched_jb, _thread_kern_sched_stack,
399 SET_RETURN_ADDR_JB(_thread_kern_sched_jb, _thread_kern_scheduler);
402 * Write a magic value to the thread structure
403 * to help identify valid ones:
405 _thread_initial->magic = PTHREAD_MAGIC;
407 /* Set the initial cancel state */
408 _thread_initial->cancelflags = PTHREAD_CANCEL_ENABLE |
409 PTHREAD_CANCEL_DEFERRED;
411 /* Default the priority of the initial thread: */
412 _thread_initial->base_priority = PTHREAD_DEFAULT_PRIORITY;
413 _thread_initial->active_priority = PTHREAD_DEFAULT_PRIORITY;
414 _thread_initial->inherited_priority = 0;
416 /* Initialise the state of the initial thread: */
417 _thread_initial->state = PS_RUNNING;
419 /* Set the name of the thread: */
420 _thread_initial->name = strdup("_thread_initial");
422 /* Initialize joiner to NULL (no joiner): */
423 _thread_initial->joiner = NULL;
425 /* Initialize the owned mutex queue and count: */
426 TAILQ_INIT(&(_thread_initial->mutexq));
427 _thread_initial->priority_mutex_count = 0;
429 /* Initialize the global scheduling time: */
431 gettimeofday((struct timeval *) &_sched_tod, NULL);
433 /* Initialize last active: */
434 _thread_initial->last_active = (long) _sched_ticks;
436 /* Initialize the initial context: */
437 _thread_initial->curframe = NULL;
439 /* Initialise the rest of the fields: */
440 _thread_initial->poll_data.nfds = 0;
441 _thread_initial->poll_data.fds = NULL;
442 _thread_initial->sig_defer_count = 0;
443 _thread_initial->yield_on_sig_undefer = 0;
444 _thread_initial->specific = NULL;
445 _thread_initial->cleanup = NULL;
446 _thread_initial->flags = 0;
447 _thread_initial->error = 0;
448 TAILQ_INIT(&_thread_list);
449 TAILQ_INSERT_HEAD(&_thread_list, _thread_initial, tle);
450 _set_curthread(_thread_initial);
451 TAILQ_INIT(&_atfork_list);
452 _pthread_mutex_init(&_atfork_mutex, NULL);
454 /* Initialise the global signal action structure: */
455 sigfillset(&act.sa_mask);
456 act.sa_handler = (void (*) ()) _thread_sig_handler;
457 act.sa_flags = SA_SIGINFO | SA_RESTART;
459 /* Clear pending signals for the process: */
460 sigemptyset(&_process_sigpending);
462 /* Clear the signal queue: */
463 memset(_thread_sigq, 0, sizeof(_thread_sigq));
465 /* Enter a loop to get the existing signal status: */
466 for (i = 1; i < NSIG; i++) {
467 /* Check for signals which cannot be trapped: */
468 if (i == SIGKILL || i == SIGSTOP) {
471 /* Get the signal handler details: */
472 else if (__sys_sigaction(i, NULL,
473 &_thread_sigact[i - 1]) != 0) {
475 * Abort this process if signal
476 * initialisation fails:
478 PANIC("Cannot read signal handler info");
481 /* Initialize the SIG_DFL dummy handler count. */
482 _thread_dfl_count[i] = 0;
486 * Install the signal handler for the most important
487 * signals that the user-thread kernel needs. Actually
488 * SIGINFO isn't really needed, but it is nice to have.
490 if (__sys_sigaction(_SCHED_SIGNAL, &act, NULL) != 0 ||
491 __sys_sigaction(SIGINFO, &act, NULL) != 0 ||
492 __sys_sigaction(SIGCHLD, &act, NULL) != 0) {
494 * Abort this process if signal initialisation fails:
496 PANIC("Cannot initialise signal handler");
498 _thread_sigact[_SCHED_SIGNAL - 1].sa_flags = SA_SIGINFO;
499 _thread_sigact[SIGINFO - 1].sa_flags = SA_SIGINFO;
500 _thread_sigact[SIGCHLD - 1].sa_flags = SA_SIGINFO;
502 /* Get the process signal mask: */
503 __sys_sigprocmask(SIG_SETMASK, NULL, &_process_sigmask);
505 /* Get the kernel clockrate: */
507 mib[1] = KERN_CLOCKRATE;
508 len = sizeof (struct clockinfo);
509 if (sysctl(mib, 2, &clockinfo, &len, NULL, 0) == 0)
510 _clock_res_usec = clockinfo.tick > CLOCK_RES_USEC_MIN ?
511 clockinfo.tick : CLOCK_RES_USEC_MIN;
513 /* Get the table size: */
514 if ((_thread_dtablesize = getdtablesize()) < 0) {
516 * Cannot get the system defined table size, so abort
519 PANIC("Cannot get dtablesize");
521 /* Allocate memory for the file descriptor table: */
522 if ((_thread_fd_table = (struct fd_table_entry **) malloc(sizeof(struct fd_table_entry *) * _thread_dtablesize)) == NULL) {
523 /* Avoid accesses to file descriptor table on exit: */
524 _thread_dtablesize = 0;
527 * Cannot allocate memory for the file descriptor
528 * table, so abort this process.
530 PANIC("Cannot allocate memory for file descriptor table");
532 /* Allocate memory for the pollfd table: */
533 if ((_thread_pfd_table = (struct pollfd *) malloc(sizeof(struct pollfd) * _thread_dtablesize)) == NULL) {
535 * Cannot allocate memory for the file descriptor
536 * table, so abort this process.
538 PANIC("Cannot allocate memory for pollfd table");
541 * Enter a loop to initialise the file descriptor
544 for (i = 0; i < _thread_dtablesize; i++) {
545 /* Initialise the file descriptor table: */
546 _thread_fd_table[i] = NULL;
549 /* Initialize stdio file descriptor table entries: */
550 for (i = 0; i < 3; i++) {
551 if ((_thread_fd_table_init(i) != 0) &&
553 PANIC("Cannot initialize stdio file "
554 "descriptor table entry");
559 /* Initialise the garbage collector mutex and condition variable. */
560 if (_pthread_mutex_init(&_gc_mutex,NULL) != 0 ||
561 _pthread_cond_init(&_gc_cond,NULL) != 0)
562 PANIC("Failed to initialise garbage collector mutex or condvar");
567 * Special start up code for NetBSD/Alpha
569 #if defined(__NetBSD__) && defined(__alpha__)
571 main(int argc, char *argv[], char *env);
574 _thread_main(int argc, char *argv[], char *env)
577 return (main(argc, argv, env));