thr_init.c revision 80021
121308Sache/*
221308Sache * Copyright (c) 1995-1998 John Birrell <jb@cimlogic.com.au>
321308Sache * All rights reserved.
421308Sache *
521308Sache * Redistribution and use in source and binary forms, with or without
621308Sache * modification, are permitted provided that the following conditions
7119610Sache * are met:
8119610Sache * 1. Redistributions of source code must retain the above copyright
9119610Sache *    notice, this list of conditions and the following disclaimer.
10119610Sache * 2. Redistributions in binary form must reproduce the above copyright
11119610Sache *    notice, this list of conditions and the following disclaimer in the
12119610Sache *    documentation and/or other materials provided with the distribution.
13119610Sache * 3. All advertising materials mentioning features or use of this software
14119610Sache *    must display the following acknowledgement:
15119610Sache *	This product includes software developed by John Birrell.
16119610Sache * 4. Neither the name of the author nor the names of any co-contributors
17119610Sache *    may be used to endorse or promote products derived from this software
18119610Sache *    without specific prior written permission.
19119610Sache *
20119610Sache * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND
21119610Sache * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22119610Sache * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23119610Sache * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24119610Sache * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25119610Sache * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26119610Sache * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2726497Sache * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2826497Sache * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2926497Sache * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3026497Sache * SUCH DAMAGE.
3121308Sache *
3221308Sache * $FreeBSD: head/lib/libkse/thread/thr_init.c 80021 2001-07-20 04:23:11Z jasone $
3321308Sache */
34157184Sache
35157184Sache/* Allocate space for global thread variables here: */
36157184Sache#define GLOBAL_PTHREAD_PRIVATE
37157184Sache
38157184Sache#include "namespace.h"
39157184Sache#include <sys/param.h>
4058310Sache#include <sys/lock.h>
4158310Sache#include <sys/mutex.h>
4258310Sache#include <sys/types.h>
4358310Sache#include <machine/reg.h>
4458310Sache
4558310Sache#include <sys/ioctl.h>
4658310Sache#include <sys/mount.h>
4758310Sache#include <sys/uio.h>
4835486Sache#include <sys/socket.h>
4935486Sache#include <sys/event.h>
5021308Sache#include <sys/stat.h>
5121308Sache#include <sys/sysctl.h>
5235486Sache#include <sys/time.h>
5335486Sache#include <sys/ttycom.h>
5421308Sache#include <sys/user.h>
5535486Sache#include <sys/wait.h>
5635486Sache#include <sys/mman.h>
5735486Sache#include <dirent.h>
5835486Sache#include <errno.h>
5921308Sache#include <fcntl.h>
6021308Sache#include <paths.h>
6121308Sache#include <poll.h>
6221308Sache#include <pthread.h>
6321308Sache#include <signal.h>
6421308Sache#include <stdio.h>
6521308Sache#include <stdlib.h>
6621308Sache#include <string.h>
6721308Sache#include <unistd.h>
6821308Sache#include "un-namespace.h"
6921308Sache
7021308Sache#include "pthread_private.h"
7121308Sache
7221308Sache/*
7321308Sache * All weak references used within libc should be in this table.
7421308Sache * This will is so that static libraries will work.
7521308Sache */
7621308Sachestatic void *references[] = {
7721308Sache	&_accept,
7821308Sache	&_bind,
7921308Sache	&_close,
8035486Sache	&_connect,
8121308Sache	&_dup,
8235486Sache	&_dup2,
8335486Sache	&_execve,
8421308Sache	&_fcntl,
8521308Sache	&_flock,
8621308Sache	&_flockfile,
8735486Sache	&_fstat,
8821308Sache	&_fstatfs,
8921308Sache	&_fsync,
9021308Sache	&_funlockfile,
9121308Sache	&_getdirentries,
9235486Sache	&_getlogin,
9321308Sache	&_getpeername,
94	&_getsockname,
95	&_getsockopt,
96	&_ioctl,
97	&_kevent,
98	&_listen,
99	&_nanosleep,
100	&_open,
101	&_pthread_getspecific,
102	&_pthread_key_create,
103	&_pthread_key_delete,
104	&_pthread_mutex_destroy,
105	&_pthread_mutex_init,
106	&_pthread_mutex_lock,
107	&_pthread_mutex_trylock,
108	&_pthread_mutex_unlock,
109	&_pthread_mutexattr_init,
110	&_pthread_mutexattr_destroy,
111	&_pthread_mutexattr_settype,
112	&_pthread_once,
113	&_pthread_setspecific,
114	&_read,
115	&_readv,
116	&_recvfrom,
117	&_recvmsg,
118	&_select,
119	&_sendmsg,
120	&_sendto,
121	&_setsockopt,
122	&_sigaction,
123	&_sigprocmask,
124	&_sigsuspend,
125	&_socket,
126	&_socketpair,
127	&_wait4,
128	&_write,
129	&_writev
130};
131
132/*
133 * These are needed when linking statically.  All references within
134 * libgcc (and in the future libc) to these routines are weak, but
135 * if they are not (strongly) referenced by the application or other
136 * libraries, then the actual functions will not be loaded.
137 */
138static void *libgcc_references[] = {
139	&_pthread_once,
140	&_pthread_key_create,
141	&_pthread_key_delete,
142	&_pthread_getspecific,
143	&_pthread_setspecific,
144	&_pthread_mutex_init,
145	&_pthread_mutex_destroy,
146	&_pthread_mutex_lock,
147	&_pthread_mutex_trylock,
148	&_pthread_mutex_unlock
149};
150
151
152/*
153 * Threaded process initialization
154 */
155void
156_thread_init(void)
157{
158	int		fd;
159	int             flags;
160	int             i;
161	size_t		len;
162	int		mib[2];
163	struct clockinfo clockinfo;
164	struct sigaction act;
165
166	/* Check if this function has already been called: */
167	if (_thread_initial)
168		/* Only initialise the threaded application once. */
169		return;
170
171	/*
172	 * Make gcc quiescent about {,libgcc_}references not being
173	 * referenced:
174	 */
175	if ((references[0] == NULL) || (libgcc_references[0] == NULL))
176		PANIC("Failed loading mandatory references in _thread_init");
177
178	/*
179	 * Check for the special case of this process running as
180	 * or in place of init as pid = 1:
181	 */
182	if (getpid() == 1) {
183		/*
184		 * Setup a new session for this process which is
185		 * assumed to be running as root.
186		 */
187		if (setsid() == -1)
188			PANIC("Can't set session ID");
189		if (revoke(_PATH_CONSOLE) != 0)
190			PANIC("Can't revoke console");
191		if ((fd = __sys_open(_PATH_CONSOLE, O_RDWR)) < 0)
192			PANIC("Can't open console");
193		if (setlogin("root") == -1)
194			PANIC("Can't set login to root");
195		if (__sys_ioctl(fd,TIOCSCTTY, (char *) NULL) == -1)
196			PANIC("Can't set controlling terminal");
197		if (__sys_dup2(fd,0) == -1 ||
198		    __sys_dup2(fd,1) == -1 ||
199		    __sys_dup2(fd,2) == -1)
200			PANIC("Can't dup2");
201	}
202
203	/* Get the standard I/O flags before messing with them : */
204	for (i = 0; i < 3; i++)
205		if (((_pthread_stdio_flags[i] =
206		    __sys_fcntl(i,F_GETFL, NULL)) == -1) &&
207		    (errno != EBADF))
208			PANIC("Cannot get stdio flags");
209
210	/*
211	 * Create a pipe that is written to by the signal handler to prevent
212	 * signals being missed in calls to _select:
213	 */
214	if (__sys_pipe(_thread_kern_pipe) != 0) {
215		/* Cannot create pipe, so abort: */
216		PANIC("Cannot create kernel pipe");
217	}
218	/* Get the flags for the read pipe: */
219	else if ((flags = __sys_fcntl(_thread_kern_pipe[0], F_GETFL, NULL)) == -1) {
220		/* Abort this application: */
221		PANIC("Cannot get kernel read pipe flags");
222	}
223	/* Make the read pipe non-blocking: */
224	else if (__sys_fcntl(_thread_kern_pipe[0], F_SETFL, flags | O_NONBLOCK) == -1) {
225		/* Abort this application: */
226		PANIC("Cannot make kernel read pipe non-blocking");
227	}
228	/* Get the flags for the write pipe: */
229	else if ((flags = __sys_fcntl(_thread_kern_pipe[1], F_GETFL, NULL)) == -1) {
230		/* Abort this application: */
231		PANIC("Cannot get kernel write pipe flags");
232	}
233	/* Make the write pipe non-blocking: */
234	else if (__sys_fcntl(_thread_kern_pipe[1], F_SETFL, flags | O_NONBLOCK) == -1) {
235		/* Abort this application: */
236		PANIC("Cannot get kernel write pipe flags");
237	}
238	/* Allocate and initialize the ready queue: */
239	else if (_pq_alloc(&_readyq, PTHREAD_MIN_PRIORITY, PTHREAD_LAST_PRIORITY) != 0) {
240		/* Abort this application: */
241		PANIC("Cannot allocate priority ready queue.");
242	}
243	/* Allocate memory for the thread structure of the initial thread: */
244	else if ((_thread_initial = (pthread_t) malloc(sizeof(struct pthread))) == NULL) {
245		/*
246		 * Insufficient memory to initialise this application, so
247		 * abort:
248		 */
249		PANIC("Cannot allocate memory for initial thread");
250	}
251	/* Allocate memory for the scheduler stack: */
252	else if ((_thread_kern_sched_stack = malloc(SCHED_STACK_SIZE)) == NULL)
253		PANIC("Failed to allocate stack for scheduler");
254	else {
255		/* Zero the global kernel thread structure: */
256		memset(&_thread_kern_thread, 0, sizeof(struct pthread));
257		_thread_kern_thread.flags = PTHREAD_FLAGS_PRIVATE;
258		memset(_thread_initial, 0, sizeof(struct pthread));
259
260		/* Initialize the waiting and work queues: */
261		TAILQ_INIT(&_waitingq);
262		TAILQ_INIT(&_workq);
263
264		/* Initialize the scheduling switch hook routine: */
265		_sched_switch_hook = NULL;
266
267		/* Give this thread default attributes: */
268		memcpy((void *) &_thread_initial->attr, &pthread_attr_default,
269		    sizeof(struct pthread_attr));
270
271		/*
272		 * Create a red zone below the main stack.  All other stacks are
273		 * constrained to a maximum size by the paramters passed to
274		 * mmap(), but this stack is only limited by resource limits, so
275		 * this stack needs an explicitly mapped red zone to protect the
276		 * thread stack that is just beyond.
277		 */
278		if (mmap((void *) USRSTACK - PTHREAD_STACK_INITIAL -
279		    PTHREAD_GUARD_DEFAULT, PTHREAD_GUARD_DEFAULT, 0, MAP_ANON,
280		    -1, 0) == MAP_FAILED)
281			PANIC("Cannot allocate red zone for initial thread");
282
283		/* Set the main thread stack pointer. */
284		_thread_initial->stack = (void *) USRSTACK -
285		    PTHREAD_STACK_INITIAL;
286
287		/* Set the stack attributes: */
288		_thread_initial->attr.stackaddr_attr = _thread_initial->stack;
289		_thread_initial->attr.stacksize_attr = PTHREAD_STACK_INITIAL;
290
291		/* Setup the context for the scheduler: */
292		_setjmp(_thread_kern_sched_jb);
293		SET_STACK_JB(_thread_kern_sched_jb, _thread_kern_sched_stack +
294		    SCHED_STACK_SIZE - sizeof(double));
295		SET_RETURN_ADDR_JB(_thread_kern_sched_jb, _thread_kern_scheduler);
296
297		/*
298		 * Write a magic value to the thread structure
299		 * to help identify valid ones:
300		 */
301		_thread_initial->magic = PTHREAD_MAGIC;
302
303		/* Set the initial cancel state */
304		_thread_initial->cancelflags = PTHREAD_CANCEL_ENABLE |
305		    PTHREAD_CANCEL_DEFERRED;
306
307		/* Default the priority of the initial thread: */
308		_thread_initial->base_priority = PTHREAD_DEFAULT_PRIORITY;
309		_thread_initial->active_priority = PTHREAD_DEFAULT_PRIORITY;
310		_thread_initial->inherited_priority = 0;
311
312		/* Initialise the state of the initial thread: */
313		_thread_initial->state = PS_RUNNING;
314
315		/* Set the name of the thread: */
316		_thread_initial->name = strdup("_thread_initial");
317
318		/* Initialize joiner to NULL (no joiner): */
319		_thread_initial->joiner = NULL;
320
321		/* Initialize the owned mutex queue and count: */
322		TAILQ_INIT(&(_thread_initial->mutexq));
323		_thread_initial->priority_mutex_count = 0;
324
325		/* Initialize the global scheduling time: */
326		_sched_ticks = 0;
327		gettimeofday((struct timeval *) &_sched_tod, NULL);
328
329		/* Initialize last active: */
330		_thread_initial->last_active = (long) _sched_ticks;
331
332		/* Initialize the initial context: */
333		_thread_initial->curframe = NULL;
334		_thread_initial->ctxtype = CTX_JB_NOSIG;
335
336		/* Initialise the rest of the fields: */
337		_thread_initial->poll_data.nfds = 0;
338		_thread_initial->poll_data.fds = NULL;
339		_thread_initial->sig_defer_count = 0;
340		_thread_initial->yield_on_sig_undefer = 0;
341		_thread_initial->specific_data = NULL;
342		_thread_initial->cleanup = NULL;
343		_thread_initial->flags = 0;
344		_thread_initial->error = 0;
345		TAILQ_INIT(&_thread_list);
346		TAILQ_INSERT_HEAD(&_thread_list, _thread_initial, tle);
347		_set_curthread(_thread_initial);
348
349		/* Initialise the global signal action structure: */
350		sigfillset(&act.sa_mask);
351		act.sa_handler = (void (*) ()) _thread_sig_handler;
352		act.sa_flags = SA_SIGINFO | SA_ONSTACK;
353
354		/* Clear pending signals for the process: */
355		sigemptyset(&_process_sigpending);
356
357		/* Clear the signal queue: */
358		memset(_thread_sigq, 0, sizeof(_thread_sigq));
359
360		/*
361		 * Create and install an alternate signal stack of
362		 * the recommended size:
363		 */
364		_thread_sigstack.ss_sp = malloc(SIGSTKSZ);
365		_thread_sigstack.ss_size = SIGSTKSZ;
366		_thread_sigstack.ss_flags = 0;
367		if ((_thread_sigstack.ss_sp == NULL) ||
368		    (__sys_sigaltstack(&_thread_sigstack, NULL) != 0))
369			PANIC("Unable to install alternate signal stack");
370
371		/* Enter a loop to get the existing signal status: */
372		for (i = 1; i < NSIG; i++) {
373			/* Check for signals which cannot be trapped: */
374			if (i == SIGKILL || i == SIGSTOP) {
375			}
376
377			/* Get the signal handler details: */
378			else if (__sys_sigaction(i, NULL,
379			    &_thread_sigact[i - 1]) != 0) {
380				/*
381				 * Abort this process if signal
382				 * initialisation fails:
383				 */
384				PANIC("Cannot read signal handler info");
385			}
386
387			/* Initialize the SIG_DFL dummy handler count. */
388			_thread_dfl_count[i] = 0;
389		}
390
391		/*
392		 * Install the signal handler for the most important
393		 * signals that the user-thread kernel needs. Actually
394		 * SIGINFO isn't really needed, but it is nice to have.
395		 */
396		if (__sys_sigaction(_SCHED_SIGNAL, &act, NULL) != 0 ||
397		    __sys_sigaction(SIGINFO,       &act, NULL) != 0 ||
398		    __sys_sigaction(SIGCHLD,       &act, NULL) != 0) {
399			/*
400			 * Abort this process if signal initialisation fails:
401			 */
402			PANIC("Cannot initialise signal handler");
403		}
404		_thread_sigact[_SCHED_SIGNAL - 1].sa_flags = SA_SIGINFO;
405		_thread_sigact[SIGINFO - 1].sa_flags = SA_SIGINFO;
406		_thread_sigact[SIGCHLD - 1].sa_flags = SA_SIGINFO;
407
408		/* Get the process signal mask: */
409		__sys_sigprocmask(SIG_SETMASK, NULL, &_process_sigmask);
410
411		/* Get the kernel clockrate: */
412		mib[0] = CTL_KERN;
413		mib[1] = KERN_CLOCKRATE;
414		len = sizeof (struct clockinfo);
415		if (sysctl(mib, 2, &clockinfo, &len, NULL, 0) == 0)
416			_clock_res_usec = clockinfo.tick > CLOCK_RES_USEC_MIN ?
417			    clockinfo.tick : CLOCK_RES_USEC_MIN;
418
419		/* Get the table size: */
420		if ((_thread_dtablesize = getdtablesize()) < 0) {
421			/*
422			 * Cannot get the system defined table size, so abort
423			 * this process.
424			 */
425			PANIC("Cannot get dtablesize");
426		}
427		/* Allocate memory for the file descriptor table: */
428		if ((_thread_fd_table = (struct fd_table_entry **) malloc(sizeof(struct fd_table_entry *) * _thread_dtablesize)) == NULL) {
429			/* Avoid accesses to file descriptor table on exit: */
430			_thread_dtablesize = 0;
431
432			/*
433			 * Cannot allocate memory for the file descriptor
434			 * table, so abort this process.
435			 */
436			PANIC("Cannot allocate memory for file descriptor table");
437		}
438		/* Allocate memory for the pollfd table: */
439		if ((_thread_pfd_table = (struct pollfd *) malloc(sizeof(struct pollfd) * _thread_dtablesize)) == NULL) {
440			/*
441			 * Cannot allocate memory for the file descriptor
442			 * table, so abort this process.
443			 */
444			PANIC("Cannot allocate memory for pollfd table");
445		} else {
446			/*
447			 * Enter a loop to initialise the file descriptor
448			 * table:
449			 */
450			for (i = 0; i < _thread_dtablesize; i++) {
451				/* Initialise the file descriptor table: */
452				_thread_fd_table[i] = NULL;
453			}
454
455			/* Initialize stdio file descriptor table entries: */
456			for (i = 0; i < 3; i++) {
457				if ((_thread_fd_table_init(i) != 0) &&
458				    (errno != EBADF))
459					PANIC("Cannot initialize stdio file "
460					    "descriptor table entry");
461			}
462		}
463	}
464
465	/* Initialise the garbage collector mutex and condition variable. */
466	if (_pthread_mutex_init(&_gc_mutex,NULL) != 0 ||
467	    pthread_cond_init(&_gc_cond,NULL) != 0)
468		PANIC("Failed to initialise garbage collector mutex or condvar");
469}
470
471/*
472 * Special start up code for NetBSD/Alpha
473 */
474#if	defined(__NetBSD__) && defined(__alpha__)
475int
476main(int argc, char *argv[], char *env);
477
478int
479_thread_main(int argc, char *argv[], char *env)
480{
481	_thread_init();
482	return (main(argc, argv, env));
483}
484#endif
485