xref: /freebsd/lib/libthr/thread/thr_init.c (revision c69db88340f9a7659ab4faa7fd328a3fb858b72e)
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$
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 <pthread.h>
60 #include <signal.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <unistd.h>
65 #include "un-namespace.h"
66 
67 #include "thr_private.h"
68 
69 /*
70  * Early implementations of sigtimedwait interpreted the signal
71  * set incorrectly.
72  */
73 #define SIGTIMEDWAIT_SET_IS_INVERTED(osreldate) \
74     ((500100 <= (osreldate) && (osreldate) <= 500113) || \
75     (osreldate) == 501000 || (osreldate) == 501100)
76 
77 extern void _thread_init_hack(void);
78 
79 /*
80  * All weak references used within libc should be in this table.
81  * This will is so that static libraries will work.
82  *
83  * XXXTHR - Check this list.
84  */
85 static void *references[] = {
86 	&_thread_init_hack,
87 	&_thread_init,
88 	&_accept,
89 	&_bind,
90 	&_close,
91 	&_connect,
92 	&_dup,
93 	&_dup2,
94 	&_execve,
95 	&_fcntl,
96 	&_flock,
97 	&_flockfile,
98 	&_fstat,
99 	&_fstatfs,
100 	&_fsync,
101 	&_funlockfile,
102 	&_getdirentries,
103 	&_getlogin,
104 	&_getpeername,
105 	&_getsockname,
106 	&_getsockopt,
107 	&_ioctl,
108 	&_kevent,
109 	&_listen,
110 	&_nanosleep,
111 	&_open,
112 	&_pthread_getspecific,
113 	&_pthread_key_create,
114 	&_pthread_key_delete,
115 	&_pthread_mutex_destroy,
116 	&_pthread_mutex_init,
117 	&_pthread_mutex_lock,
118 	&_pthread_mutex_trylock,
119 	&_pthread_mutex_unlock,
120 	&_pthread_mutexattr_init,
121 	&_pthread_mutexattr_destroy,
122 	&_pthread_mutexattr_settype,
123 	&_pthread_once,
124 	&_pthread_setspecific,
125 	&_read,
126 	&_readv,
127 	&_recvfrom,
128 	&_recvmsg,
129 	&_select,
130 	&_sendmsg,
131 	&_sendto,
132 	&_setsockopt,
133 	&_sigaction,
134 	&_sigprocmask,
135 	&_sigsuspend,
136 	&_socket,
137 	&_socketpair,
138 	&_wait4,
139 	&_write,
140 	&_writev
141 };
142 
143 /*
144  * These are needed when linking statically.  All references within
145  * libgcc (and in the future libc) to these routines are weak, but
146  * if they are not (strongly) referenced by the application or other
147  * libraries, then the actual functions will not be loaded.
148  */
149 static void *libgcc_references[] = {
150 	&_thread_init_hack,
151 	&_thread_init,
152 	&_pthread_once,
153 	&_pthread_key_create,
154 	&_pthread_key_delete,
155 	&_pthread_getspecific,
156 	&_pthread_setspecific,
157 	&_pthread_mutex_init,
158 	&_pthread_mutex_destroy,
159 	&_pthread_mutex_lock,
160 	&_pthread_mutex_trylock,
161 	&_pthread_mutex_unlock
162 };
163 
164 int _pthread_guard_default;
165 int _pthread_page_size;
166 
167 /*
168  * Threaded process initialization
169  */
170 void
171 _thread_init(void)
172 {
173 	struct pthread	*pthread;
174 	int		fd;
175 	int             i;
176 	size_t		len;
177 	int		mib[2];
178 	sigset_t	set;
179 	int		osreldate;
180 	int		error;
181 
182 	struct clockinfo clockinfo;
183 	struct sigaction act;
184 
185 	/* Check if this function has already been called: */
186 	if (_thread_initial)
187 		/* Only initialise the threaded application once. */
188 		return;
189 
190 	_pthread_page_size = getpagesize();
191 	_pthread_guard_default = getpagesize();
192 
193 	pthread_attr_default.guardsize_attr = _pthread_guard_default;
194 
195 
196 	/*
197 	 * Make gcc quiescent about {,libgcc_}references not being
198 	 * referenced:
199 	 */
200 	if ((references[0] == NULL) || (libgcc_references[0] == NULL))
201 		PANIC("Failed loading mandatory references in _thread_init");
202 
203 	/*
204 	 * Check for the special case of this process running as
205 	 * or in place of init as pid = 1:
206 	 */
207 	if (getpid() == 1) {
208 		/*
209 		 * Setup a new session for this process which is
210 		 * assumed to be running as root.
211 		 */
212 		if (setsid() == -1)
213 			PANIC("Can't set session ID");
214 		if (revoke(_PATH_CONSOLE) != 0)
215 			PANIC("Can't revoke console");
216 		if ((fd = __sys_open(_PATH_CONSOLE, O_RDWR)) < 0)
217 			PANIC("Can't open console");
218 		if (setlogin("root") == -1)
219 			PANIC("Can't set login to root");
220 		if (__sys_ioctl(fd, TIOCSCTTY, (char *) NULL) == -1)
221 			PANIC("Can't set controlling terminal");
222 		if (__sys_dup2(fd, 0) == -1 ||
223 		    __sys_dup2(fd, 1) == -1 ||
224 		    __sys_dup2(fd, 2) == -1)
225 			PANIC("Can't dup2");
226 	}
227 
228 	/* Allocate memory for the thread structure of the initial thread: */
229 	if ((pthread = (pthread_t) malloc(sizeof(struct pthread))) == NULL) {
230 		/*
231 		 * Insufficient memory to initialise this application, so
232 		 * abort:
233 		 */
234 		PANIC("Cannot allocate memory for initial thread");
235 	}
236 	/* Zero the initial thread structure: */
237 	memset(pthread, 0, sizeof(struct pthread));
238 
239 	_thread_initial = pthread;
240 	pthread->arch_id = _set_curthread(NULL, pthread, &error);
241 
242 	/* Get our thread id. */
243 	thr_self(&pthread->thr_id);
244 
245 	/* Give this thread default attributes: */
246 	memcpy((void *) &pthread->attr, &pthread_attr_default,
247 	    sizeof(struct pthread_attr));
248 
249 	/* Find the stack top */
250 	mib[0] = CTL_KERN;
251 	mib[1] = KERN_USRSTACK;
252 	len = sizeof (_usrstack);
253 	if (sysctl(mib, 2, &_usrstack, &len, NULL, 0) == -1)
254 		_usrstack = (void *)USRSTACK;
255 	/*
256 	 * Create a red zone below the main stack.  All other stacks are
257 	 * constrained to a maximum size by the paramters passed to
258 	 * mmap(), but this stack is only limited by resource limits, so
259 	 * this stack needs an explicitly mapped red zone to protect the
260 	 * thread stack that is just beyond.
261 	 */
262 	if (mmap(_usrstack - PTHREAD_STACK_INITIAL -
263 	    _pthread_guard_default, _pthread_guard_default, 0,
264 	    MAP_ANON, -1, 0) == MAP_FAILED)
265 		PANIC("Cannot allocate red zone for initial thread");
266 
267 	/* Set the main thread stack pointer. */
268 	pthread->stack = _usrstack - PTHREAD_STACK_INITIAL;
269 
270 	/* Set the stack attributes. */
271 	pthread->attr.stackaddr_attr = pthread->stack;
272 	pthread->attr.stacksize_attr = PTHREAD_STACK_INITIAL;
273 
274 	/*
275 	 * Write a magic value to the thread structure
276 	 * to help identify valid ones:
277 	 */
278 	pthread->magic = PTHREAD_MAGIC;
279 
280 	/* Set the initial cancel state */
281 	pthread->cancelflags = PTHREAD_CANCEL_ENABLE | PTHREAD_CANCEL_DEFERRED;
282 
283 	/* Setup the context for initial thread. */
284 	getcontext(&pthread->ctx);
285 	pthread->ctx.uc_stack.ss_sp = pthread->stack;
286 	pthread->ctx.uc_stack.ss_size = PTHREAD_STACK_INITIAL;
287 
288 	/* Default the priority of the initial thread: */
289 	pthread->base_priority = PTHREAD_DEFAULT_PRIORITY;
290 	pthread->active_priority = PTHREAD_DEFAULT_PRIORITY;
291 	pthread->inherited_priority = 0;
292 
293 	/* Initialise the state of the initial thread: */
294 	pthread->state = PS_RUNNING;
295 
296 	/* Set the name of the thread: */
297 	pthread->name = strdup("_thread_initial");
298 
299 	/* Initialize joiner to NULL (no joiner): */
300 	pthread->joiner = NULL;
301 
302 	/* Initialize the owned mutex queue and count: */
303 	TAILQ_INIT(&(pthread->mutexq));
304 	pthread->priority_mutex_count = 0;
305 
306 	/* Initialise the rest of the fields: */
307 	pthread->specific = NULL;
308 	pthread->cleanup = NULL;
309 	pthread->flags = 0;
310 	pthread->error = 0;
311 	TAILQ_INIT(&_thread_list);
312 	TAILQ_INSERT_HEAD(&_thread_list, pthread, tle);
313 
314 	/* Enter a loop to get the existing signal status: */
315 	for (i = 1; i < NSIG; i++) {
316 		/* Check for signals which cannot be trapped. */
317 		if (i == SIGKILL || i == SIGSTOP)
318 			continue;
319 
320 		/* Get the signal handler details. */
321 		if (__sys_sigaction(i, NULL,
322 		    &_thread_sigact[i - 1]) != 0)
323 			PANIC("Cannot read signal handler info");
324 	}
325 	act.sa_sigaction = _thread_sig_wrapper;
326 	act.sa_flags = SA_SIGINFO;
327 	SIGFILLSET(act.sa_mask);
328 
329 	if (__sys_sigaction(SIGTHR, &act, NULL))
330 		PANIC("Cannot set SIGTHR handler.\n");
331 
332 	SIGEMPTYSET(set);
333 	SIGADDSET(set, SIGTHR);
334 	__sys_sigprocmask(SIG_BLOCK, &set, 0);
335 
336 	/*
337 	 * Precompute the signal set used by _thread_suspend to wait
338 	 * for SIGTHR.
339 	 */
340 	mib[0] = CTL_KERN;
341 	mib[1] = KERN_OSRELDATE;
342 	len = sizeof(osreldate);
343 	if (sysctl(mib, 2, &osreldate, &len, NULL, 0) == 0 &&
344 	    SIGTIMEDWAIT_SET_IS_INVERTED(osreldate)) {
345 		/* Kernel bug requires an inverted signal set. */
346 		SIGFILLSET(_thread_suspend_sigset);
347 		SIGDELSET(_thread_suspend_sigset, SIGTHR);
348 	} else {
349 		SIGEMPTYSET(_thread_suspend_sigset);
350 		SIGADDSET(_thread_suspend_sigset, SIGTHR);
351 	}
352 #ifdef _PTHREADS_INVARIANTS
353 	SIGADDSET(_thread_suspend_sigset, SIGALRM);
354 #endif
355 
356 	/* Get the kernel clockrate: */
357 	mib[0] = CTL_KERN;
358 	mib[1] = KERN_CLOCKRATE;
359 	len = sizeof (struct clockinfo);
360 	if (sysctl(mib, 2, &clockinfo, &len, NULL, 0) == 0)
361 		_clock_res_usec = clockinfo.tick > CLOCK_RES_USEC_MIN ?
362 		    clockinfo.tick : CLOCK_RES_USEC_MIN;
363 
364 	/* Initialise the garbage collector mutex and condition variable. */
365 	if (_pthread_mutex_init(&dead_list_lock,NULL) != 0 ||
366 	    _pthread_cond_init(&_gc_cond,NULL) != 0)
367 		PANIC("Failed to initialise garbage collector mutex or condvar");
368 }
369 
370 /*
371  * Special start up code for NetBSD/Alpha
372  */
373 #if	defined(__NetBSD__) && defined(__alpha__)
374 int
375 main(int argc, char *argv[], char *env);
376 
377 int
378 _thread_main(int argc, char *argv[], char *env)
379 {
380 	_thread_init();
381 	return (main(argc, argv, env));
382 }
383 #endif
384