thr_init.c revision 90431
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 90431 2002-02-09 19:58:41Z deischen $
33 */
34
35/* Allocate space for global thread variables here: */
36#define GLOBAL_PTHREAD_PRIVATE
37
38#include "namespace.h"
39#include <sys/param.h>
40#include <sys/types.h>
41#include <machine/reg.h>
42
43#include <sys/ioctl.h>
44#include <sys/mount.h>
45#include <sys/uio.h>
46#include <sys/socket.h>
47#include <sys/event.h>
48#include <sys/stat.h>
49#include <sys/sysctl.h>
50#include <sys/time.h>
51#include <sys/ttycom.h>
52#include <sys/user.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 <poll.h>
60#include <pthread.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 "pthread_private.h"
69
70/*
71 * All weak references used within libc should be in this table.
72 * This will is so that static libraries will work.
73 */
74static void *references[] = {
75	&_accept,
76	&_bind,
77	&_close,
78	&_connect,
79	&_dup,
80	&_dup2,
81	&_execve,
82	&_fcntl,
83	&_flock,
84	&_flockfile,
85	&_fstat,
86	&_fstatfs,
87	&_fsync,
88	&_funlockfile,
89	&_getdirentries,
90	&_getlogin,
91	&_getpeername,
92	&_getsockname,
93	&_getsockopt,
94	&_ioctl,
95	&_kevent,
96	&_listen,
97	&_nanosleep,
98	&_open,
99	&_pthread_getspecific,
100	&_pthread_key_create,
101	&_pthread_key_delete,
102	&_pthread_mutex_destroy,
103	&_pthread_mutex_init,
104	&_pthread_mutex_lock,
105	&_pthread_mutex_trylock,
106	&_pthread_mutex_unlock,
107	&_pthread_mutexattr_init,
108	&_pthread_mutexattr_destroy,
109	&_pthread_mutexattr_settype,
110	&_pthread_once,
111	&_pthread_setspecific,
112	&_read,
113	&_readv,
114	&_recvfrom,
115	&_recvmsg,
116	&_select,
117	&_sendmsg,
118	&_sendto,
119	&_setsockopt,
120	&_sigaction,
121	&_sigprocmask,
122	&_sigsuspend,
123	&_socket,
124	&_socketpair,
125	&_wait4,
126	&_write,
127	&_writev
128};
129
130/*
131 * These are needed when linking statically.  All references within
132 * libgcc (and in the future libc) to these routines are weak, but
133 * if they are not (strongly) referenced by the application or other
134 * libraries, then the actual functions will not be loaded.
135 */
136static void *libgcc_references[] = {
137	&_pthread_once,
138	&_pthread_key_create,
139	&_pthread_key_delete,
140	&_pthread_getspecific,
141	&_pthread_setspecific,
142	&_pthread_mutex_init,
143	&_pthread_mutex_destroy,
144	&_pthread_mutex_lock,
145	&_pthread_mutex_trylock,
146	&_pthread_mutex_unlock
147};
148
149
150/*
151 * Threaded process initialization
152 */
153void
154_thread_init(void)
155{
156	int		fd;
157	int             flags;
158	int             i;
159	size_t		len;
160	int		mib[2];
161	struct clockinfo clockinfo;
162	struct sigaction act;
163
164	/* Check if this function has already been called: */
165	if (_thread_initial)
166		/* Only initialise the threaded application once. */
167		return;
168
169	/*
170	 * Make gcc quiescent about {,libgcc_}references not being
171	 * referenced:
172	 */
173	if ((references[0] == NULL) || (libgcc_references[0] == NULL))
174		PANIC("Failed loading mandatory references in _thread_init");
175
176	/*
177	 * Check for the special case of this process running as
178	 * or in place of init as pid = 1:
179	 */
180	if (getpid() == 1) {
181		/*
182		 * Setup a new session for this process which is
183		 * assumed to be running as root.
184		 */
185		if (setsid() == -1)
186			PANIC("Can't set session ID");
187		if (revoke(_PATH_CONSOLE) != 0)
188			PANIC("Can't revoke console");
189		if ((fd = __sys_open(_PATH_CONSOLE, O_RDWR)) < 0)
190			PANIC("Can't open console");
191		if (setlogin("root") == -1)
192			PANIC("Can't set login to root");
193		if (__sys_ioctl(fd,TIOCSCTTY, (char *) NULL) == -1)
194			PANIC("Can't set controlling terminal");
195		if (__sys_dup2(fd,0) == -1 ||
196		    __sys_dup2(fd,1) == -1 ||
197		    __sys_dup2(fd,2) == -1)
198			PANIC("Can't dup2");
199	}
200
201	/* Get the standard I/O flags before messing with them : */
202	for (i = 0; i < 3; i++)
203		if (((_pthread_stdio_flags[i] =
204		    __sys_fcntl(i,F_GETFL, NULL)) == -1) &&
205		    (errno != EBADF))
206			PANIC("Cannot get stdio flags");
207
208	/*
209	 * Create a pipe that is written to by the signal handler to prevent
210	 * signals being missed in calls to _select:
211	 */
212	if (__sys_pipe(_thread_kern_pipe) != 0) {
213		/* Cannot create pipe, so abort: */
214		PANIC("Cannot create kernel pipe");
215	}
216	/* Get the flags for the read pipe: */
217	else if ((flags = __sys_fcntl(_thread_kern_pipe[0], F_GETFL, NULL)) == -1) {
218		/* Abort this application: */
219		PANIC("Cannot get kernel read pipe flags");
220	}
221	/* Make the read pipe non-blocking: */
222	else if (__sys_fcntl(_thread_kern_pipe[0], F_SETFL, flags | O_NONBLOCK) == -1) {
223		/* Abort this application: */
224		PANIC("Cannot make kernel read pipe non-blocking");
225	}
226	/* Get the flags for the write pipe: */
227	else if ((flags = __sys_fcntl(_thread_kern_pipe[1], F_GETFL, NULL)) == -1) {
228		/* Abort this application: */
229		PANIC("Cannot get kernel write pipe flags");
230	}
231	/* Make the write pipe non-blocking: */
232	else if (__sys_fcntl(_thread_kern_pipe[1], F_SETFL, flags | O_NONBLOCK) == -1) {
233		/* Abort this application: */
234		PANIC("Cannot get kernel write pipe flags");
235	}
236	/* Allocate and initialize the ready queue: */
237	else if (_pq_alloc(&_readyq, PTHREAD_MIN_PRIORITY, PTHREAD_LAST_PRIORITY) != 0) {
238		/* Abort this application: */
239		PANIC("Cannot allocate priority ready queue.");
240	}
241	/* Allocate memory for the thread structure of the initial thread: */
242	else if ((_thread_initial = (pthread_t) malloc(sizeof(struct pthread))) == NULL) {
243		/*
244		 * Insufficient memory to initialise this application, so
245		 * abort:
246		 */
247		PANIC("Cannot allocate memory for initial thread");
248	}
249	/* Allocate memory for the scheduler stack: */
250	else if ((_thread_kern_sched_stack = malloc(SCHED_STACK_SIZE)) == NULL)
251		PANIC("Failed to allocate stack for scheduler");
252	else {
253		/* Zero the global kernel thread structure: */
254		memset(&_thread_kern_thread, 0, sizeof(struct pthread));
255		_thread_kern_thread.flags = PTHREAD_FLAGS_PRIVATE;
256		memset(_thread_initial, 0, sizeof(struct pthread));
257
258		/* Initialize the waiting and work queues: */
259		TAILQ_INIT(&_waitingq);
260		TAILQ_INIT(&_workq);
261
262		/* Initialize the scheduling switch hook routine: */
263		_sched_switch_hook = NULL;
264
265		/* Give this thread default attributes: */
266		memcpy((void *) &_thread_initial->attr, &pthread_attr_default,
267		    sizeof(struct pthread_attr));
268
269		/* Find the stack top */
270		mib[0] = CTL_KERN;
271		mib[1] = KERN_USRSTACK;
272		len = sizeof (_usrstack);
273		if (sysctl(mib, 2, &_usrstack, &len, NULL, 0) == -1)
274			_usrstack = (void *)USRSTACK;
275		/*
276		 * Create a red zone below the main stack.  All other stacks are
277		 * constrained to a maximum size by the paramters passed to
278		 * mmap(), but this stack is only limited by resource limits, so
279		 * this stack needs an explicitly mapped red zone to protect the
280		 * thread stack that is just beyond.
281		 */
282		if (mmap(_usrstack - PTHREAD_STACK_INITIAL -
283		    PTHREAD_GUARD_DEFAULT, PTHREAD_GUARD_DEFAULT, 0, MAP_ANON,
284		    -1, 0) == MAP_FAILED)
285			PANIC("Cannot allocate red zone for initial thread");
286
287		/* Set the main thread stack pointer. */
288		_thread_initial->stack = _usrstack - PTHREAD_STACK_INITIAL;
289
290		/* Set the stack attributes: */
291		_thread_initial->attr.stackaddr_attr = _thread_initial->stack;
292		_thread_initial->attr.stacksize_attr = PTHREAD_STACK_INITIAL;
293
294		/* Setup the context for the scheduler: */
295		_setjmp(_thread_kern_sched_jb);
296		SET_STACK_JB(_thread_kern_sched_jb, _thread_kern_sched_stack +
297		    SCHED_STACK_SIZE - sizeof(double));
298		SET_RETURN_ADDR_JB(_thread_kern_sched_jb, _thread_kern_scheduler);
299
300		/*
301		 * Write a magic value to the thread structure
302		 * to help identify valid ones:
303		 */
304		_thread_initial->magic = PTHREAD_MAGIC;
305
306		/* Set the initial cancel state */
307		_thread_initial->cancelflags = PTHREAD_CANCEL_ENABLE |
308		    PTHREAD_CANCEL_DEFERRED;
309
310		/* Default the priority of the initial thread: */
311		_thread_initial->base_priority = PTHREAD_DEFAULT_PRIORITY;
312		_thread_initial->active_priority = PTHREAD_DEFAULT_PRIORITY;
313		_thread_initial->inherited_priority = 0;
314
315		/* Initialise the state of the initial thread: */
316		_thread_initial->state = PS_RUNNING;
317
318		/* Set the name of the thread: */
319		_thread_initial->name = strdup("_thread_initial");
320
321		/* Initialize joiner to NULL (no joiner): */
322		_thread_initial->joiner = NULL;
323
324		/* Initialize the owned mutex queue and count: */
325		TAILQ_INIT(&(_thread_initial->mutexq));
326		_thread_initial->priority_mutex_count = 0;
327
328		/* Initialize the global scheduling time: */
329		_sched_ticks = 0;
330		gettimeofday((struct timeval *) &_sched_tod, NULL);
331
332		/* Initialize last active: */
333		_thread_initial->last_active = (long) _sched_ticks;
334
335		/* Initialize the initial context: */
336		_thread_initial->curframe = NULL;
337
338		/* Initialise the rest of the fields: */
339		_thread_initial->poll_data.nfds = 0;
340		_thread_initial->poll_data.fds = NULL;
341		_thread_initial->sig_defer_count = 0;
342		_thread_initial->yield_on_sig_undefer = 0;
343		_thread_initial->specific_data = NULL;
344		_thread_initial->cleanup = NULL;
345		_thread_initial->flags = 0;
346		_thread_initial->error = 0;
347		TAILQ_INIT(&_thread_list);
348		TAILQ_INSERT_HEAD(&_thread_list, _thread_initial, tle);
349		_set_curthread(_thread_initial);
350
351		/* Initialise the global signal action structure: */
352		sigfillset(&act.sa_mask);
353		act.sa_handler = (void (*) ()) _thread_sig_handler;
354		act.sa_flags = SA_SIGINFO | SA_ONSTACK;
355
356		/* Clear pending signals for the process: */
357		sigemptyset(&_process_sigpending);
358
359		/* Clear the signal queue: */
360		memset(_thread_sigq, 0, sizeof(_thread_sigq));
361
362		/* Enter a loop to get the existing signal status: */
363		for (i = 1; i < NSIG; i++) {
364			/* Check for signals which cannot be trapped: */
365			if (i == SIGKILL || i == SIGSTOP) {
366			}
367
368			/* Get the signal handler details: */
369			else if (__sys_sigaction(i, NULL,
370			    &_thread_sigact[i - 1]) != 0) {
371				/*
372				 * Abort this process if signal
373				 * initialisation fails:
374				 */
375				PANIC("Cannot read signal handler info");
376			}
377
378			/* Initialize the SIG_DFL dummy handler count. */
379			_thread_dfl_count[i] = 0;
380		}
381
382		/*
383		 * Install the signal handler for the most important
384		 * signals that the user-thread kernel needs. Actually
385		 * SIGINFO isn't really needed, but it is nice to have.
386		 */
387		if (__sys_sigaction(_SCHED_SIGNAL, &act, NULL) != 0 ||
388		    __sys_sigaction(SIGINFO,       &act, NULL) != 0 ||
389		    __sys_sigaction(SIGCHLD,       &act, NULL) != 0) {
390			/*
391			 * Abort this process if signal initialisation fails:
392			 */
393			PANIC("Cannot initialise signal handler");
394		}
395		_thread_sigact[_SCHED_SIGNAL - 1].sa_flags = SA_SIGINFO;
396		_thread_sigact[SIGINFO - 1].sa_flags = SA_SIGINFO;
397		_thread_sigact[SIGCHLD - 1].sa_flags = SA_SIGINFO;
398
399		/* Get the process signal mask: */
400		__sys_sigprocmask(SIG_SETMASK, NULL, &_process_sigmask);
401
402		/* Get the kernel clockrate: */
403		mib[0] = CTL_KERN;
404		mib[1] = KERN_CLOCKRATE;
405		len = sizeof (struct clockinfo);
406		if (sysctl(mib, 2, &clockinfo, &len, NULL, 0) == 0)
407			_clock_res_usec = clockinfo.tick > CLOCK_RES_USEC_MIN ?
408			    clockinfo.tick : CLOCK_RES_USEC_MIN;
409
410		/* Get the table size: */
411		if ((_thread_dtablesize = getdtablesize()) < 0) {
412			/*
413			 * Cannot get the system defined table size, so abort
414			 * this process.
415			 */
416			PANIC("Cannot get dtablesize");
417		}
418		/* Allocate memory for the file descriptor table: */
419		if ((_thread_fd_table = (struct fd_table_entry **) malloc(sizeof(struct fd_table_entry *) * _thread_dtablesize)) == NULL) {
420			/* Avoid accesses to file descriptor table on exit: */
421			_thread_dtablesize = 0;
422
423			/*
424			 * Cannot allocate memory for the file descriptor
425			 * table, so abort this process.
426			 */
427			PANIC("Cannot allocate memory for file descriptor table");
428		}
429		/* Allocate memory for the pollfd table: */
430		if ((_thread_pfd_table = (struct pollfd *) malloc(sizeof(struct pollfd) * _thread_dtablesize)) == NULL) {
431			/*
432			 * Cannot allocate memory for the file descriptor
433			 * table, so abort this process.
434			 */
435			PANIC("Cannot allocate memory for pollfd table");
436		} else {
437			/*
438			 * Enter a loop to initialise the file descriptor
439			 * table:
440			 */
441			for (i = 0; i < _thread_dtablesize; i++) {
442				/* Initialise the file descriptor table: */
443				_thread_fd_table[i] = NULL;
444			}
445
446			/* Initialize stdio file descriptor table entries: */
447			for (i = 0; i < 3; i++) {
448				if ((_thread_fd_table_init(i) != 0) &&
449				    (errno != EBADF))
450					PANIC("Cannot initialize stdio file "
451					    "descriptor table entry");
452			}
453		}
454	}
455
456	/* Initialise the garbage collector mutex and condition variable. */
457	if (_pthread_mutex_init(&_gc_mutex,NULL) != 0 ||
458	    pthread_cond_init(&_gc_cond,NULL) != 0)
459		PANIC("Failed to initialise garbage collector mutex or condvar");
460}
461
462/*
463 * Special start up code for NetBSD/Alpha
464 */
465#if	defined(__NetBSD__) && defined(__alpha__)
466int
467main(int argc, char *argv[], char *env);
468
469int
470_thread_main(int argc, char *argv[], char *env)
471{
472	_thread_init();
473	return (main(argc, argv, env));
474}
475#endif
476