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