xref: /freebsd/lib/libthr/thread/thr_init.c (revision 8ca4df3299628bad609cb74ee2f76671e07b4788)
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/wait.h>
53 #include <sys/mman.h>
54 #include <dirent.h>
55 #include <errno.h>
56 #include <fcntl.h>
57 #include <paths.h>
58 #include <pthread.h>
59 #include <signal.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #include <unistd.h>
64 #include "un-namespace.h"
65 
66 #include "thr_private.h"
67 
68 extern void _thread_init_hack(void);
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  *
74  * XXXTHR - Check this list.
75  */
76 static void *references[] = {
77 	&_thread_init_hack,
78 	&_thread_init,
79 	&_accept,
80 	&_bind,
81 	&_close,
82 	&_connect,
83 	&_dup,
84 	&_dup2,
85 	&_execve,
86 	&_fcntl,
87 	&_flock,
88 	&_flockfile,
89 	&_fstat,
90 	&_fstatfs,
91 	&_fsync,
92 	&_funlockfile,
93 	&_getdirentries,
94 	&_getlogin,
95 	&_getpeername,
96 	&_getsockname,
97 	&_getsockopt,
98 	&_ioctl,
99 	&_kevent,
100 	&_listen,
101 	&_nanosleep,
102 	&_open,
103 	&_pthread_getspecific,
104 	&_pthread_key_create,
105 	&_pthread_key_delete,
106 	&_pthread_mutex_destroy,
107 	&_pthread_mutex_init,
108 	&_pthread_mutex_lock,
109 	&_pthread_mutex_trylock,
110 	&_pthread_mutex_unlock,
111 	&_pthread_mutexattr_init,
112 	&_pthread_mutexattr_destroy,
113 	&_pthread_mutexattr_settype,
114 	&_pthread_once,
115 	&_pthread_setspecific,
116 	&_read,
117 	&_readv,
118 	&_recvfrom,
119 	&_recvmsg,
120 	&_select,
121 	&_sendmsg,
122 	&_sendto,
123 	&_setsockopt,
124 	&_sigaction,
125 	&_sigprocmask,
126 	&_sigsuspend,
127 	&_socket,
128 	&_socketpair,
129 	&_wait4,
130 	&_write,
131 	&_writev
132 };
133 
134 /*
135  * These are needed when linking statically.  All references within
136  * libgcc (and in the future libc) to these routines are weak, but
137  * if they are not (strongly) referenced by the application or other
138  * libraries, then the actual functions will not be loaded.
139  */
140 static void *libgcc_references[] = {
141 	&_thread_init_hack,
142 	&_thread_init,
143 	&_pthread_once,
144 	&_pthread_key_create,
145 	&_pthread_key_delete,
146 	&_pthread_getspecific,
147 	&_pthread_setspecific,
148 	&_pthread_mutex_init,
149 	&_pthread_mutex_destroy,
150 	&_pthread_mutex_lock,
151 	&_pthread_mutex_trylock,
152 	&_pthread_mutex_unlock
153 };
154 
155 int _pthread_guard_default;
156 int _pthread_page_size;
157 int _pthread_stack_default;
158 int _pthread_stack_initial;
159 
160 /*
161  * Initialize the current thread.
162  */
163 void
164 init_td_common(struct pthread *td, struct pthread_attr *attrp, int reinit)
165 {
166 	/*
167 	 * Some parts of a pthread are initialized only once.
168 	 */
169 	if (!reinit) {
170 		memset(td, 0, sizeof(struct pthread));
171 		td->cancelmode = M_DEFERRED;
172 		td->cancelstate = M_DEFERRED;
173 		td->cancellation = CS_NULL;
174 		memcpy(&td->attr, attrp, sizeof(struct pthread_attr));
175 		td->magic = PTHREAD_MAGIC;
176 		TAILQ_INIT(&td->mutexq);
177 		td->base_priority = PTHREAD_DEFAULT_PRIORITY;
178 		td->active_priority = PTHREAD_DEFAULT_PRIORITY;
179 		td->inherited_priority = PTHREAD_MIN_PRIORITY;
180 	} else {
181 		memset(&td->join_status, 0, sizeof(struct join_status));
182 	}
183 	td->joiner = NULL;
184 	td->error = 0;
185 	td->flags = 0;
186 }
187 
188 /*
189  * Initialize the active and dead threads list. Any threads in the active
190  * list will be removed and the thread td * will be marked as the
191  * initial thread and inserted in the list as the only thread. Any threads
192  * in the dead threads list will also be removed.
193  */
194 void
195 init_tdlist(struct pthread *td, int reinit)
196 {
197 	struct pthread *tdTemp, *tdTemp2;
198 
199 	_thread_initial = td;
200 	td->name = strdup("_thread_initial");
201 
202 	/*
203 	 * If this is not the first initialization, remove any entries
204 	 * that may be in the list and deallocate their memory. Also
205 	 * destroy any global pthread primitives (they will be recreated).
206 	 */
207 	if (reinit) {
208 		TAILQ_FOREACH_SAFE(tdTemp, &_thread_list, tle, tdTemp2) {
209 			if (tdTemp != NULL && tdTemp != td) {
210 				TAILQ_REMOVE(&_thread_list, tdTemp, tle);
211 				free(tdTemp);
212 			}
213 		}
214 		TAILQ_FOREACH_SAFE(tdTemp, &_dead_list, dle, tdTemp2) {
215 			if (tdTemp != NULL) {
216 				TAILQ_REMOVE(&_dead_list, tdTemp, dle);
217 				free(tdTemp);
218 			}
219 		}
220 		_pthread_mutex_destroy(&dead_list_lock);
221 	} else {
222 		TAILQ_INIT(&_thread_list);
223 		TAILQ_INIT(&_dead_list);
224 
225 		/* Insert this thread as the first thread in the active list */
226 		TAILQ_INSERT_HEAD(&_thread_list, td, tle);
227 	}
228 
229 	/*
230 	 * Initialize the active thread list lock and the
231 	 * dead threads list lock.
232 	 */
233 	memset(&thread_list_lock, 0, sizeof(spinlock_t));
234 	if (_pthread_mutex_init(&dead_list_lock,NULL) != 0)
235 		PANIC("Failed to initialize garbage collector primitives");
236 }
237 
238 /*
239  * Threaded process initialization
240  */
241 void
242 _thread_init(void)
243 {
244 	struct pthread	*pthread;
245 	int		fd;
246 	size_t		len;
247 	int		mib[2];
248 	int		error;
249 
250 	/* Check if this function has already been called: */
251 	if (_thread_initial)
252 		/* Only initialise the threaded application once. */
253 		return;
254 
255 	_pthread_page_size = getpagesize();
256 	_pthread_guard_default = getpagesize();
257 	if (sizeof(void *) == 8) {
258 		_pthread_stack_default = PTHREAD_STACK64_DEFAULT;
259 		_pthread_stack_initial = PTHREAD_STACK64_INITIAL;
260 	}
261 	else {
262 		_pthread_stack_default = PTHREAD_STACK32_DEFAULT;
263 		_pthread_stack_initial = PTHREAD_STACK32_INITIAL;
264 	}
265 
266 	pthread_attr_default.guardsize_attr = _pthread_guard_default;
267 	pthread_attr_default.stacksize_attr = _pthread_stack_default;
268 
269 	/*
270 	 * Make gcc quiescent about {,libgcc_}references not being
271 	 * referenced:
272 	 */
273 	if ((references[0] == NULL) || (libgcc_references[0] == NULL))
274 		PANIC("Failed loading mandatory references in _thread_init");
275 
276 	/*
277 	 * Check for the special case of this process running as
278 	 * or in place of init as pid = 1:
279 	 */
280 	if (getpid() == 1) {
281 		/*
282 		 * Setup a new session for this process which is
283 		 * assumed to be running as root.
284 		 */
285 		if (setsid() == -1)
286 			PANIC("Can't set session ID");
287 		if (revoke(_PATH_CONSOLE) != 0)
288 			PANIC("Can't revoke console");
289 		if ((fd = __sys_open(_PATH_CONSOLE, O_RDWR)) < 0)
290 			PANIC("Can't open console");
291 		if (setlogin("root") == -1)
292 			PANIC("Can't set login to root");
293 		if (__sys_ioctl(fd, TIOCSCTTY, (char *) NULL) == -1)
294 			PANIC("Can't set controlling terminal");
295 		if (__sys_dup2(fd, 0) == -1 ||
296 		    __sys_dup2(fd, 1) == -1 ||
297 		    __sys_dup2(fd, 2) == -1)
298 			PANIC("Can't dup2");
299 	}
300 
301 	/* Allocate memory for the thread structure of the initial thread: */
302 	if ((pthread = (pthread_t) malloc(sizeof(struct pthread))) == NULL) {
303 		/*
304 		 * Insufficient memory to initialise this application, so
305 		 * abort:
306 		 */
307 		PANIC("Cannot allocate memory for initial thread");
308 	}
309 
310 	init_tdlist(pthread, 0);
311 	init_td_common(pthread, &pthread_attr_default, 0);
312 	pthread->arch_id = _set_curthread(NULL, pthread, &error);
313 
314 	/* Get our thread id. */
315 	thr_self(&pthread->thr_id);
316 
317 	/* Find the stack top */
318 	mib[0] = CTL_KERN;
319 	mib[1] = KERN_USRSTACK;
320 	len = sizeof (_usrstack);
321 	if (sysctl(mib, 2, &_usrstack, &len, NULL, 0) == -1)
322 		_usrstack = (void *)USRSTACK;
323 	/*
324 	 * Create a red zone below the main stack.  All other stacks are
325 	 * constrained to a maximum size by the paramters passed to
326 	 * mmap(), but this stack is only limited by resource limits, so
327 	 * this stack needs an explicitly mapped red zone to protect the
328 	 * thread stack that is just beyond.
329 	 */
330 	if (mmap(_usrstack - _pthread_stack_initial -
331 	    _pthread_guard_default, _pthread_guard_default, 0,
332 	    MAP_ANON, -1, 0) == MAP_FAILED)
333 		PANIC("Cannot allocate red zone for initial thread");
334 
335 	/* Set the main thread stack pointer. */
336 	pthread->stack = _usrstack - _pthread_stack_initial;
337 
338 	/* Set the stack attributes. */
339 	pthread->attr.stackaddr_attr = pthread->stack;
340 	pthread->attr.stacksize_attr = _pthread_stack_initial;
341 
342 	/* Setup the context for initial thread. */
343 	getcontext(&pthread->ctx);
344 	pthread->ctx.uc_stack.ss_sp = pthread->stack;
345 	pthread->ctx.uc_stack.ss_size = _pthread_stack_initial;
346 
347 	/* Initialize the atfork list and mutex */
348 	TAILQ_INIT(&_atfork_list);
349 	_pthread_mutex_init(&_atfork_mutex, NULL);
350 }
351 
352 /*
353  * Special start up code for NetBSD/Alpha
354  */
355 #if	defined(__NetBSD__) && defined(__alpha__)
356 int
357 main(int argc, char *argv[], char *env);
358 
359 int
360 _thread_main(int argc, char *argv[], char *env)
361 {
362 	_thread_init();
363 	return (main(argc, argv, env));
364 }
365 #endif
366