xref: /dflybsd-src/lib/libthread_xu/thread/thr_init.c (revision 23c32883e759b0ea42fdaff39e661bd1a12e3b9f)
1 /*
2  * Copyright (c) 2003 Daniel M. Eischen <deischen@freebsd.org>
3  * Copyright (c) 1995-1998 John Birrell <jb@cimlogic.com.au>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgement:
16  *	This product includes software developed by John Birrell.
17  * 4. Neither the name of the author nor the names of any co-contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * $FreeBSD: src/lib/libpthread/thread/thr_init.c,v 1.66 2004/08/21 11:49:19 davidxu Exp $
34  * $DragonFly: src/lib/libthread_xu/thread/thr_init.c,v 1.2 2005/02/21 13:47:21 davidxu Exp $
35  */
36 
37 /* Allocate space for global thread variables here: */
38 #define GLOBAL_PTHREAD_PRIVATE
39 
40 #include "namespace.h"
41 #include <sys/param.h>
42 #include <sys/types.h>
43 #include <sys/signalvar.h>
44 #include <machine/reg.h>
45 
46 #include <sys/ioctl.h>
47 #include <sys/mount.h>
48 #include <sys/uio.h>
49 #include <sys/socket.h>
50 #include <sys/event.h>
51 #include <sys/stat.h>
52 #include <sys/sysctl.h>
53 #include <sys/time.h>
54 #include <sys/ttycom.h>
55 #include <sys/wait.h>
56 #include <sys/mman.h>
57 #include <dirent.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <paths.h>
61 #include <pthread.h>
62 #include <pthread_np.h>
63 #include <signal.h>
64 #include <stdio.h>
65 #include <stdlib.h>
66 #include <string.h>
67 #include <unistd.h>
68 #include "un-namespace.h"
69 
70 #include "libc_private.h"
71 #include "thr_private.h"
72 
73 extern int _thread_state_running;
74 
75 int	__pthread_cond_wait(pthread_cond_t *, pthread_mutex_t *);
76 int	__pthread_mutex_lock(pthread_mutex_t *);
77 int	__pthread_mutex_trylock(pthread_mutex_t *);
78 
79 void	_thread_init(void) __attribute__ ((constructor));
80 
81 static void init_private(void);
82 static void init_main_thread(struct pthread *thread);
83 
84 /*
85  * All weak references used within libc should be in this table.
86  * This is so that static libraries will work.
87  */
88 static void *references[] = {
89 	&_accept,
90 	&_bind,
91 	&_close,
92 	&_connect,
93 	&_dup,
94 	&_dup2,
95 	&_execve,
96 	&_fcntl,
97 	&_flock,
98 	&_flockfile,
99 	&_fstat,
100 	&_fstatfs,
101 	&_fsync,
102 	&_funlockfile,
103 	&_getdirentries,
104 	&_getlogin,
105 	&_getpeername,
106 	&_getsockname,
107 	&_getsockopt,
108 	&_ioctl,
109 	&_kevent,
110 	&_listen,
111 	&_nanosleep,
112 	&_open,
113 	&_pthread_getspecific,
114 	&_pthread_key_create,
115 	&_pthread_key_delete,
116 	&_pthread_mutex_destroy,
117 	&_pthread_mutex_init,
118 	&_pthread_mutex_lock,
119 	&_pthread_mutex_trylock,
120 	&_pthread_mutex_unlock,
121 	&_pthread_mutexattr_init,
122 	&_pthread_mutexattr_destroy,
123 	&_pthread_mutexattr_settype,
124 	&_pthread_once,
125 	&_pthread_setspecific,
126 	&_read,
127 	&_readv,
128 	&_recvfrom,
129 	&_recvmsg,
130 	&_select,
131 	&_sendmsg,
132 	&_sendto,
133 	&_setsockopt,
134 	&_sigaction,
135 	&_sigprocmask,
136 	&_sigsuspend,
137 	&_socket,
138 	&_socketpair,
139 	&_thread_init,
140 	&_wait4,
141 	&_write,
142 	&_writev
143 };
144 
145 /*
146  * These are needed when linking statically.  All references within
147  * libgcc (and in the future libc) to these routines are weak, but
148  * if they are not (strongly) referenced by the application or other
149  * libraries, then the actual functions will not be loaded.
150  */
151 static void *libgcc_references[] = {
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 	&_pthread_cond_init,
163 	&_pthread_cond_destroy,
164 	&_pthread_cond_wait,
165 	&_pthread_cond_timedwait,
166 	&_pthread_cond_signal,
167 	&_pthread_cond_broadcast
168 };
169 
170 #if 0
171 #define	DUAL_ENTRY(entry)	\
172 	(pthread_func_t)entry, (pthread_func_t)entry
173 
174 static pthread_func_t jmp_table[][2] = {
175 	{DUAL_ENTRY(_pthread_cond_broadcast)},	/* PJT_COND_BROADCAST */
176 	{DUAL_ENTRY(_pthread_cond_destroy)},	/* PJT_COND_DESTROY */
177 	{DUAL_ENTRY(_pthread_cond_init)},	/* PJT_COND_INIT */
178 	{DUAL_ENTRY(_pthread_cond_signal)},	/* PJT_COND_SIGNAL */
179 	{(pthread_func_t)__pthread_cond_wait,
180 	 (pthread_func_t)_pthread_cond_wait},	/* PJT_COND_WAIT */
181 	{DUAL_ENTRY(_pthread_getspecific)},	/* PJT_GETSPECIFIC */
182 	{DUAL_ENTRY(_pthread_key_create)},	/* PJT_KEY_CREATE */
183 	{DUAL_ENTRY(_pthread_key_delete)},	/* PJT_KEY_DELETE*/
184 	{DUAL_ENTRY(_pthread_main_np)},		/* PJT_MAIN_NP */
185 	{DUAL_ENTRY(_pthread_mutex_destroy)},	/* PJT_MUTEX_DESTROY */
186 	{DUAL_ENTRY(_pthread_mutex_init)},	/* PJT_MUTEX_INIT */
187 	{(pthread_func_t)__pthread_mutex_lock,
188 	 (pthread_func_t)_pthread_mutex_lock},	/* PJT_MUTEX_LOCK */
189 	{(pthread_func_t)__pthread_mutex_trylock,
190 	 (pthread_func_t)_pthread_mutex_trylock},/* PJT_MUTEX_TRYLOCK */
191 	{DUAL_ENTRY(_pthread_mutex_unlock)},	/* PJT_MUTEX_UNLOCK */
192 	{DUAL_ENTRY(_pthread_mutexattr_destroy)}, /* PJT_MUTEXATTR_DESTROY */
193 	{DUAL_ENTRY(_pthread_mutexattr_init)},	/* PJT_MUTEXATTR_INIT */
194 	{DUAL_ENTRY(_pthread_mutexattr_settype)}, /* PJT_MUTEXATTR_SETTYPE */
195 	{DUAL_ENTRY(_pthread_once)},		/* PJT_ONCE */
196 	{DUAL_ENTRY(_pthread_rwlock_destroy)},	/* PJT_RWLOCK_DESTROY */
197 	{DUAL_ENTRY(_pthread_rwlock_init)},	/* PJT_RWLOCK_INIT */
198 	{DUAL_ENTRY(_pthread_rwlock_rdlock)},	/* PJT_RWLOCK_RDLOCK */
199 	{DUAL_ENTRY(_pthread_rwlock_tryrdlock)},/* PJT_RWLOCK_TRYRDLOCK */
200 	{DUAL_ENTRY(_pthread_rwlock_trywrlock)},/* PJT_RWLOCK_TRYWRLOCK */
201 	{DUAL_ENTRY(_pthread_rwlock_unlock)},	/* PJT_RWLOCK_UNLOCK */
202 	{DUAL_ENTRY(_pthread_rwlock_wrlock)},	/* PJT_RWLOCK_WRLOCK */
203 	{DUAL_ENTRY(_pthread_self)},		/* PJT_SELF */
204 	{DUAL_ENTRY(_pthread_setspecific)},	/* PJT_SETSPECIFIC */
205 	{DUAL_ENTRY(_pthread_sigmask)}		/* PJT_SIGMASK */
206 };
207 #endif
208 
209 static int	init_once = 0;
210 
211 /*
212  * Threaded process initialization.
213  *
214  * This is only called under two conditions:
215  *
216  *   1) Some thread routines have detected that the library hasn't yet
217  *      been initialized (_thr_initial == NULL && curthread == NULL), or
218  *
219  *   2) An explicit call to reinitialize after a fork (indicated
220  *      by curthread != NULL)
221  */
222 void
223 _libpthread_init(struct pthread *curthread)
224 {
225 	int fd, first = 0;
226 	sigset_t sigset, oldset;
227 
228 	/* Check if this function has already been called: */
229 	if ((_thr_initial != NULL) && (curthread == NULL))
230 		/* Only initialize the threaded application once. */
231 		return;
232 
233 	/*
234 	 * Make gcc quiescent about {,libgcc_}references not being
235 	 * referenced:
236 	 */
237 	if ((references[0] == NULL) || (libgcc_references[0] == NULL))
238 		PANIC("Failed loading mandatory references in _thread_init");
239 
240 	/* Pull debug symbols in for static binary */
241 	_thread_state_running = PS_RUNNING;
242 
243 #if 0
244 	/*
245 	 * Check the size of the jump table to make sure it is preset
246 	 * with the correct number of entries.
247 	 */
248 	if (sizeof(jmp_table) != (sizeof(pthread_func_t) * PJT_MAX * 2))
249 		PANIC("Thread jump table not properly initialized");
250 	memcpy(__thr_jtable, jmp_table, sizeof(jmp_table));
251 #endif
252 	/*
253 	 * Check for the special case of this process running as
254 	 * or in place of init as pid = 1:
255 	 */
256 	if ((_thr_pid = getpid()) == 1) {
257 		/*
258 		 * Setup a new session for this process which is
259 		 * assumed to be running as root.
260 		 */
261 		if (setsid() == -1)
262 			PANIC("Can't set session ID");
263 		if (revoke(_PATH_CONSOLE) != 0)
264 			PANIC("Can't revoke console");
265 		if ((fd = __sys_open(_PATH_CONSOLE, O_RDWR)) < 0)
266 			PANIC("Can't open console");
267 		if (setlogin("root") == -1)
268 			PANIC("Can't set login to root");
269 		if (__sys_ioctl(fd, TIOCSCTTY, (char *) NULL) == -1)
270 			PANIC("Can't set controlling terminal");
271 	}
272 
273 	/* Initialize pthread private data. */
274 	init_private();
275 
276 	/* Set the initial thread. */
277 	if (curthread == NULL) {
278 		first = 1;
279 		/* Create and initialize the initial thread. */
280 		curthread = _thr_alloc(NULL);
281 		if (curthread == NULL)
282 			PANIC("Can't allocate initial thread");
283 		init_main_thread(curthread);
284 	}
285 	/*
286 	 * Add the thread to the thread list queue.
287 	 */
288 	THR_LIST_ADD(curthread);
289 	_thread_active_threads = 1;
290 
291 	/* Setup the thread specific data */
292 	_tcb_set(curthread->tcb);
293 
294 	if (first) {
295 		SIGFILLSET(sigset);
296 		__sys_sigprocmask(SIG_SETMASK, &sigset, &oldset);
297 		_thr_signal_init();
298 		_thr_initial = curthread;
299 		SIGDELSET(oldset, SIGCANCEL);
300 		__sys_sigprocmask(SIG_SETMASK, &oldset, NULL);
301 	}
302 }
303 
304 /*
305  * This function and pthread_create() do a lot of the same things.
306  * It'd be nice to consolidate the common stuff in one place.
307  */
308 static void
309 init_main_thread(struct pthread *thread)
310 {
311 	/* Setup the thread attributes. */
312 	thread->tid = _thr_get_tid();
313 	thread->attr = _pthread_attr_default;
314 	/*
315 	 * Set up the thread stack.
316 	 *
317 	 * Create a red zone below the main stack.  All other stacks
318 	 * are constrained to a maximum size by the parameters
319 	 * passed to mmap(), but this stack is only limited by
320 	 * resource limits, so this stack needs an explicitly mapped
321 	 * red zone to protect the thread stack that is just beyond.
322 	 */
323 	if (mmap((void *)_usrstack - _thr_stack_initial -
324 	    _thr_guard_default, _thr_guard_default, 0, MAP_ANON,
325 	    -1, 0) == MAP_FAILED)
326 		PANIC("Cannot allocate red zone for initial thread");
327 
328 	/*
329 	 * Mark the stack as an application supplied stack so that it
330 	 * isn't deallocated.
331 	 *
332 	 * XXX - I'm not sure it would hurt anything to deallocate
333 	 *       the main thread stack because deallocation doesn't
334 	 *       actually free() it; it just puts it in the free
335 	 *       stack queue for later reuse.
336 	 */
337 	thread->attr.stackaddr_attr = (void *)_usrstack - _thr_stack_initial;
338 	thread->attr.stacksize_attr = _thr_stack_initial;
339 	thread->attr.guardsize_attr = _thr_guard_default;
340 	thread->attr.flags |= THR_STACK_USER;
341 
342 	/*
343 	 * Write a magic value to the thread structure
344 	 * to help identify valid ones:
345 	 */
346 	thread->magic = THR_MAGIC;
347 
348 	thread->cancelflags = PTHREAD_CANCEL_ENABLE | PTHREAD_CANCEL_DEFERRED;
349 	thread->name = strdup("initial thread");
350 
351 	/* Default the priority of the initial thread: */
352 	thread->base_priority = THR_DEFAULT_PRIORITY;
353 	thread->active_priority = THR_DEFAULT_PRIORITY;
354 	thread->inherited_priority = 0;
355 
356 	/* Initialize the mutex queue: */
357 	TAILQ_INIT(&thread->mutexq);
358 	TAILQ_INIT(&thread->pri_mutexq);
359 
360 	thread->state = PS_RUNNING;
361 	thread->uniqueid = 0;
362 
363 	/* Others cleared to zero by thr_alloc() */
364 }
365 
366 static void
367 init_private(void)
368 {
369 	size_t len;
370 	int mib[2];
371 
372 	_thr_umtx_init(&_mutex_static_lock);
373 	_thr_umtx_init(&_cond_static_lock);
374 	_thr_umtx_init(&_rwlock_static_lock);
375 	_thr_umtx_init(&_keytable_lock);
376 	_thr_umtx_init(&_thr_atfork_lock);
377 	_thr_spinlock_init();
378 	_thr_list_init();
379 
380 	/*
381 	 * Avoid reinitializing some things if they don't need to be,
382 	 * e.g. after a fork().
383 	 */
384 	if (init_once == 0) {
385 		/* Find the stack top */
386 		mib[0] = CTL_KERN;
387 		mib[1] = KERN_USRSTACK;
388 		len = sizeof (_usrstack);
389 		if (sysctl(mib, 2, &_usrstack, &len, NULL, 0) == -1)
390 			PANIC("Cannot get kern.usrstack from sysctl");
391 		_thr_page_size = getpagesize();
392 		_thr_guard_default = _thr_page_size;
393 	 	_pthread_attr_default.guardsize_attr = _thr_guard_default;
394 
395 		TAILQ_INIT(&_thr_atfork_list);
396 #ifdef SYSTEM_SCOPE_ONLY
397 		_thread_scope_system = 1;
398 #else
399 		if (getenv("LIBPTHREAD_SYSTEM_SCOPE") != NULL)
400 			_thread_scope_system = 1;
401 		else if (getenv("LIBPTHREAD_PROCESS_SCOPE") != NULL)
402 			_thread_scope_system = -1;
403 #endif
404 	}
405 	init_once = 1;
406 }
407 
408 void
409 _thread_init(void)
410 {
411 	_libpthread_init(NULL);
412 }
413 
414 extern int _thread_autoinit_dummy_decl;
415 int _thread_autoinit_dummy_decl = 0;
416