thr_init.c revision 48140
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 * $Id: uthread_init.c,v 1.11 1999/06/20 08:28:28 jb Exp $
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/sysctl.h>
46#include <sys/time.h>
47#include <sys/ttycom.h>
48#ifdef _THREAD_SAFE
49#include <machine/reg.h>
50#include <pthread.h>
51#include "pthread_private.h"
52
53#ifdef GCC_2_8_MADE_THREAD_AWARE
54typedef void *** (*dynamic_handler_allocator)();
55extern void __set_dynamic_handler_allocator(dynamic_handler_allocator);
56
57static pthread_key_t except_head_key;
58
59typedef struct {
60  void **__dynamic_handler_chain;
61  void *top_elt[2];
62} except_struct;
63
64static void ***dynamic_allocator_handler_fn()
65{
66	except_struct *dh = (except_struct *)pthread_getspecific(except_head_key);
67
68	if(dh == NULL) {
69		dh = (except_struct *)malloc( sizeof(except_struct) );
70		memset(dh, '\0', sizeof(except_struct));
71		dh->__dynamic_handler_chain= dh->top_elt;
72		pthread_setspecific(except_head_key, (void *)dh);
73	}
74	return &dh->__dynamic_handler_chain;
75}
76#endif /* GCC_2_8_MADE_THREAD_AWARE */
77
78/*
79 * Threaded process initialization
80 */
81void
82_thread_init(void)
83{
84	int		fd;
85	int             flags;
86	int             i;
87	size_t		len;
88	int		mib[2];
89	struct clockinfo clockinfo;
90	struct sigaction act;
91
92	/* Check if this function has already been called: */
93	if (_thread_initial)
94		/* Only initialise the threaded application once. */
95		return;
96
97	/*
98	 * Check for the special case of this process running as
99	 * or in place of init as pid = 1:
100	 */
101	if (getpid() == 1) {
102		/*
103		 * Setup a new session for this process which is
104		 * assumed to be running as root.
105		 */
106    		if (setsid() == -1)
107			PANIC("Can't set session ID");
108    		if (revoke(_PATH_CONSOLE) != 0)
109			PANIC("Can't revoke console");
110    		if ((fd = _thread_sys_open(_PATH_CONSOLE, O_RDWR)) < 0)
111			PANIC("Can't open console");
112    		if (setlogin("root") == -1)
113			PANIC("Can't set login to root");
114    		if (_thread_sys_ioctl(fd,TIOCSCTTY, (char *) NULL) == -1)
115			PANIC("Can't set controlling terminal");
116    		if (_thread_sys_dup2(fd,0) == -1 ||
117    		    _thread_sys_dup2(fd,1) == -1 ||
118    		    _thread_sys_dup2(fd,2) == -1)
119			PANIC("Can't dup2");
120	}
121
122	/* Get the standard I/O flags before messing with them : */
123	for (i = 0; i < 3; i++)
124		if ((_pthread_stdio_flags[i] =
125		    _thread_sys_fcntl(i,F_GETFL, NULL)) == -1)
126			PANIC("Cannot get stdio flags");
127
128	/*
129	 * Create a pipe that is written to by the signal handler to prevent
130	 * signals being missed in calls to _select:
131	 */
132	if (_thread_sys_pipe(_thread_kern_pipe) != 0) {
133		/* Cannot create pipe, so abort: */
134		PANIC("Cannot create kernel pipe");
135	}
136	/* Get the flags for the read pipe: */
137	else if ((flags = _thread_sys_fcntl(_thread_kern_pipe[0], F_GETFL, NULL)) == -1) {
138		/* Abort this application: */
139		PANIC("Cannot get kernel read pipe flags");
140	}
141	/* Make the read pipe non-blocking: */
142	else if (_thread_sys_fcntl(_thread_kern_pipe[0], F_SETFL, flags | O_NONBLOCK) == -1) {
143		/* Abort this application: */
144		PANIC("Cannot make kernel read pipe non-blocking");
145	}
146	/* Get the flags for the write pipe: */
147	else if ((flags = _thread_sys_fcntl(_thread_kern_pipe[1], F_GETFL, NULL)) == -1) {
148		/* Abort this application: */
149		PANIC("Cannot get kernel write pipe flags");
150	}
151	/* Make the write pipe non-blocking: */
152	else if (_thread_sys_fcntl(_thread_kern_pipe[1], F_SETFL, flags | O_NONBLOCK) == -1) {
153		/* Abort this application: */
154		PANIC("Cannot get kernel write pipe flags");
155	}
156	/* Allocate and initialize the ready queue: */
157	else if (_pq_alloc(&_readyq, PTHREAD_MIN_PRIORITY, PTHREAD_MAX_PRIORITY) != 0) {
158		/* Abort this application: */
159		PANIC("Cannot allocate priority ready queue.");
160	}
161	/* Allocate memory for the thread structure of the initial thread: */
162	else if ((_thread_initial = (pthread_t) malloc(sizeof(struct pthread))) == NULL) {
163		/*
164		 * Insufficient memory to initialise this application, so
165		 * abort:
166		 */
167		PANIC("Cannot allocate memory for initial thread");
168	} else {
169		/* Zero the global kernel thread structure: */
170		memset(&_thread_kern_thread, 0, sizeof(struct pthread));
171		_thread_kern_thread.flags = PTHREAD_FLAGS_PRIVATE;
172		memset(_thread_initial, 0, sizeof(struct pthread));
173
174		/* Initialize the waiting and work queues: */
175		TAILQ_INIT(&_waitingq);
176		TAILQ_INIT(&_workq);
177
178		/* Initialize the scheduling switch hook routine: */
179		_sched_switch_hook = NULL;
180
181		/*
182		 * Write a magic value to the thread structure
183		 * to help identify valid ones:
184		 */
185		_thread_initial->magic = PTHREAD_MAGIC;
186
187		/* Default the priority of the initial thread: */
188		_thread_initial->base_priority = PTHREAD_DEFAULT_PRIORITY;
189		_thread_initial->active_priority = PTHREAD_DEFAULT_PRIORITY;
190		_thread_initial->inherited_priority = 0;
191
192		/* Initialise the state of the initial thread: */
193		_thread_initial->state = PS_RUNNING;
194
195		/* Initialise the queue: */
196		TAILQ_INIT(&(_thread_initial->join_queue));
197
198		/* Initialize the owned mutex queue and count: */
199		TAILQ_INIT(&(_thread_initial->mutexq));
200		_thread_initial->priority_mutex_count = 0;
201
202		/* Initialise the rest of the fields: */
203		_thread_initial->poll_data.nfds = 0;
204		_thread_initial->poll_data.fds = NULL;
205		_thread_initial->sig_defer_count = 0;
206		_thread_initial->yield_on_sig_undefer = 0;
207		_thread_initial->specific_data = NULL;
208		_thread_initial->cleanup = NULL;
209		_thread_initial->flags = 0;
210		_thread_initial->error = 0;
211		TAILQ_INIT(&_thread_list);
212		TAILQ_INSERT_HEAD(&_thread_list, _thread_initial, tle);
213		_thread_run = _thread_initial;
214
215		/* Initialise the global signal action structure: */
216		sigfillset(&act.sa_mask);
217		act.sa_handler = (void (*) ()) _thread_sig_handler;
218		act.sa_flags = 0;
219
220		/* Initialize signal handling: */
221		_thread_sig_init();
222
223		/* Enter a loop to get the existing signal status: */
224		for (i = 1; i < NSIG; i++) {
225			/* Check for signals which cannot be trapped: */
226			if (i == SIGKILL || i == SIGSTOP) {
227			}
228
229			/* Get the signal handler details: */
230			else if (_thread_sys_sigaction(i, NULL,
231			    &_thread_sigact[i - 1]) != 0) {
232				/*
233				 * Abort this process if signal
234				 * initialisation fails:
235				 */
236				PANIC("Cannot read signal handler info");
237			}
238		}
239
240		/*
241		 * Install the signal handler for the most important
242		 * signals that the user-thread kernel needs. Actually
243		 * SIGINFO isn't really needed, but it is nice to have.
244		 */
245		if (_thread_sys_sigaction(_SCHED_SIGNAL, &act, NULL) != 0 ||
246		    _thread_sys_sigaction(SIGINFO,       &act, NULL) != 0 ||
247		    _thread_sys_sigaction(SIGCHLD,       &act, NULL) != 0) {
248			/*
249			 * Abort this process if signal initialisation fails:
250			 */
251			PANIC("Cannot initialise signal handler");
252		}
253
254		/* Get the kernel clockrate: */
255		mib[0] = CTL_KERN;
256		mib[1] = KERN_CLOCKRATE;
257		len = sizeof (struct clockinfo);
258		if (sysctl(mib, 2, &clockinfo, &len, NULL, 0) == 0)
259			_clock_res_nsec = clockinfo.tick * 1000;
260
261		/* Get the table size: */
262		if ((_thread_dtablesize = getdtablesize()) < 0) {
263			/*
264			 * Cannot get the system defined table size, so abort
265			 * this process.
266			 */
267			PANIC("Cannot get dtablesize");
268		}
269		/* Allocate memory for the file descriptor table: */
270		if ((_thread_fd_table = (struct fd_table_entry **) malloc(sizeof(struct fd_table_entry *) * _thread_dtablesize)) == NULL) {
271			/*
272			 * Cannot allocate memory for the file descriptor
273			 * table, so abort this process.
274			 */
275			PANIC("Cannot allocate memory for file descriptor table");
276		}
277		/* Allocate memory for the pollfd table: */
278		if ((_thread_pfd_table = (struct pollfd *) malloc(sizeof(struct pollfd) * _thread_dtablesize)) == NULL) {
279			/*
280			 * Cannot allocate memory for the file descriptor
281			 * table, so abort this process.
282			 */
283			PANIC("Cannot allocate memory for pollfd table");
284		} else {
285			/*
286			 * Enter a loop to initialise the file descriptor
287			 * table:
288			 */
289			for (i = 0; i < _thread_dtablesize; i++) {
290				/* Initialise the file descriptor table: */
291				_thread_fd_table[i] = NULL;
292			}
293
294			/* Initialize stdio file descriptor table entries: */
295			if ((_thread_fd_table_init(0) != 0) ||
296			    (_thread_fd_table_init(1) != 0) ||
297			    (_thread_fd_table_init(2) != 0)) {
298				PANIC("Cannot initialize stdio file descriptor "
299				    "table entries");
300			}
301		}
302	}
303
304#ifdef GCC_2_8_MADE_THREAD_AWARE
305	/* Create the thread-specific data for the exception linked list. */
306	if(pthread_key_create(&except_head_key, NULL) != 0)
307        	PANIC("Failed to create thread specific execption head");
308
309	/* Setup the gcc exception handler per thread. */
310	__set_dynamic_handler_allocator( dynamic_allocator_handler_fn );
311#endif /* GCC_2_8_MADE_THREAD_AWARE */
312
313	/* Initialise the garbage collector mutex and condition variable. */
314	if (pthread_mutex_init(&_gc_mutex,NULL) != 0 ||
315	    pthread_cond_init(&_gc_cond,NULL) != 0)
316		PANIC("Failed to initialise garbage collector mutex or condvar");
317
318	gettimeofday(&kern_inc_prio_time, NULL);
319
320	return;
321}
322
323/*
324 * Special start up code for NetBSD/Alpha
325 */
326#if	defined(__NetBSD__) && defined(__alpha__)
327int
328main(int argc, char *argv[], char *env);
329
330int
331_thread_main(int argc, char *argv[], char *env)
332{
333	_thread_init();
334	return (main(argc, argv, env));
335}
336#endif
337#else
338/*
339 * A stub for non-threaded programs.
340 */
341void
342_thread_init(void)
343{
344}
345#endif
346