xref: /freebsd/lib/libthr/thread/thr_init.c (revision ff4b8cb7bd488e9f1e00bf9ed08fa4b377834961)
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$
34  */
35 
36 #include "namespace.h"
37 #include <sys/types.h>
38 #include <sys/signalvar.h>
39 #include <sys/ioctl.h>
40 #include <sys/sysctl.h>
41 #include <sys/ttycom.h>
42 #include <sys/mman.h>
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <paths.h>
46 #include <pthread.h>
47 #include <pthread_np.h>
48 #include <signal.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <time.h>
52 #include <unistd.h>
53 #include "un-namespace.h"
54 
55 #include "libc_private.h"
56 #include "thr_private.h"
57 
58 char		*_usrstack;
59 struct pthread	*_thr_initial;
60 int		_thr_scope_system;
61 int		_libthr_debug;
62 int		_thread_event_mask;
63 struct pthread	*_thread_last_event;
64 pthreadlist	_thread_list = TAILQ_HEAD_INITIALIZER(_thread_list);
65 pthreadlist 	_thread_gc_list = TAILQ_HEAD_INITIALIZER(_thread_gc_list);
66 int		_thread_active_threads = 1;
67 atfork_head	_thr_atfork_list = TAILQ_HEAD_INITIALIZER(_thr_atfork_list);
68 umtx_t		_thr_atfork_lock;
69 
70 /*
71  * XXX these values should be updated from kernel at startup,
72  * but current they are same.
73  */
74 struct pthread_prio	_thr_priorities[3] = {
75 	{0,   31, 0}, /* FIF0 */
76 	{-20, 20, 0}, /* OTHER */
77 	{0,   31, 0}  /* RR */
78 };
79 
80 struct pthread_attr _pthread_attr_default = {
81 	.sched_policy = SCHED_OTHER,
82 	.sched_inherit = 0,
83 	.prio = 0,
84 	.suspend = THR_CREATE_RUNNING,
85 	.flags = PTHREAD_SCOPE_SYSTEM,
86 	.stackaddr_attr = NULL,
87 	.stacksize_attr = THR_STACK_DEFAULT,
88 	.guardsize_attr = 0
89 };
90 
91 struct pthread_mutex_attr _pthread_mutexattr_default = {
92 	.m_type = PTHREAD_MUTEX_DEFAULT,
93 	.m_protocol = PTHREAD_PRIO_NONE,
94 	.m_ceiling = 0,
95 	.m_flags = 0
96 };
97 
98 /* Default condition variable attributes: */
99 struct pthread_cond_attr _pthread_condattr_default = {
100 	.c_pshared = PTHREAD_PROCESS_PRIVATE,
101 	.c_clockid = CLOCK_REALTIME
102 };
103 
104 pid_t		_thr_pid;
105 size_t		_thr_guard_default;
106 size_t		_thr_stack_default = THR_STACK_DEFAULT;
107 size_t		_thr_stack_initial = THR_STACK_INITIAL;
108 int		_thr_page_size;
109 int		_gc_count;
110 umtx_t		_mutex_static_lock;
111 umtx_t		_cond_static_lock;
112 umtx_t		_rwlock_static_lock;
113 umtx_t		_keytable_lock;
114 umtx_t		_thr_list_lock;
115 umtx_t		_thr_event_lock;
116 
117 int	__pthread_cond_wait(pthread_cond_t *, pthread_mutex_t *);
118 int	__pthread_mutex_lock(pthread_mutex_t *);
119 int	__pthread_mutex_trylock(pthread_mutex_t *);
120 void	_thread_init_hack(void) __attribute__ ((constructor));
121 
122 static void init_private(void);
123 static void init_main_thread(struct pthread *thread);
124 
125 /*
126  * All weak references used within libc should be in this table.
127  * This is so that static libraries will work.
128  */
129 STATIC_LIB_REQUIRE(_accept);
130 STATIC_LIB_REQUIRE(_close);
131 STATIC_LIB_REQUIRE(_connect);
132 STATIC_LIB_REQUIRE(_fcntl);
133 STATIC_LIB_REQUIRE(_fsync);
134 STATIC_LIB_REQUIRE(_nanosleep);
135 STATIC_LIB_REQUIRE(_open);
136 STATIC_LIB_REQUIRE(_pthread_getspecific);
137 STATIC_LIB_REQUIRE(_pthread_key_create);
138 STATIC_LIB_REQUIRE(_pthread_key_delete);
139 STATIC_LIB_REQUIRE(_pthread_mutex_destroy);
140 STATIC_LIB_REQUIRE(_pthread_mutex_init);
141 STATIC_LIB_REQUIRE(_pthread_mutex_lock);
142 STATIC_LIB_REQUIRE(_pthread_mutex_trylock);
143 STATIC_LIB_REQUIRE(_pthread_mutex_unlock);
144 STATIC_LIB_REQUIRE(_pthread_mutexattr_init);
145 STATIC_LIB_REQUIRE(_pthread_mutexattr_destroy);
146 STATIC_LIB_REQUIRE(_pthread_mutexattr_settype);
147 STATIC_LIB_REQUIRE(_pthread_once);
148 STATIC_LIB_REQUIRE(_pthread_setspecific);
149 STATIC_LIB_REQUIRE(_read);
150 STATIC_LIB_REQUIRE(_readv);
151 STATIC_LIB_REQUIRE(_recvfrom);
152 STATIC_LIB_REQUIRE(_recvmsg);
153 STATIC_LIB_REQUIRE(_select);
154 STATIC_LIB_REQUIRE(_sendmsg);
155 STATIC_LIB_REQUIRE(_sendto);
156 STATIC_LIB_REQUIRE(_sigaction);
157 STATIC_LIB_REQUIRE(_sigprocmask);
158 STATIC_LIB_REQUIRE(_sigsuspend);
159 STATIC_LIB_REQUIRE(_socket);
160 STATIC_LIB_REQUIRE(_socketpair);
161 STATIC_LIB_REQUIRE(_thread_init_hack);
162 STATIC_LIB_REQUIRE(_wait4);
163 STATIC_LIB_REQUIRE(_write);
164 STATIC_LIB_REQUIRE(_writev);
165 
166 /*
167  * These are needed when linking statically.  All references within
168  * libgcc (and in the future libc) to these routines are weak, but
169  * if they are not (strongly) referenced by the application or other
170  * libraries, then the actual functions will not be loaded.
171  */
172 STATIC_LIB_REQUIRE(_pthread_once);
173 STATIC_LIB_REQUIRE(_pthread_key_create);
174 STATIC_LIB_REQUIRE(_pthread_key_delete);
175 STATIC_LIB_REQUIRE(_pthread_getspecific);
176 STATIC_LIB_REQUIRE(_pthread_setspecific);
177 STATIC_LIB_REQUIRE(_pthread_mutex_init);
178 STATIC_LIB_REQUIRE(_pthread_mutex_destroy);
179 STATIC_LIB_REQUIRE(_pthread_mutex_lock);
180 STATIC_LIB_REQUIRE(_pthread_mutex_trylock);
181 STATIC_LIB_REQUIRE(_pthread_mutex_unlock);
182 STATIC_LIB_REQUIRE(_pthread_create);
183 
184 /* Pull in all symbols required by libthread_db */
185 STATIC_LIB_REQUIRE(_thread_state_running);
186 
187 #define	DUAL_ENTRY(entry)	\
188 	(pthread_func_t)entry, (pthread_func_t)entry
189 
190 static pthread_func_t jmp_table[][2] = {
191 	{DUAL_ENTRY(_pthread_atfork)},	/* PJT_ATFORK */
192 	{DUAL_ENTRY(_pthread_attr_destroy)},	/* PJT_ATTR_DESTROY */
193 	{DUAL_ENTRY(_pthread_attr_getdetachstate)},	/* PJT_ATTR_GETDETACHSTATE */
194 	{DUAL_ENTRY(_pthread_attr_getguardsize)},	/* PJT_ATTR_GETGUARDSIZE */
195 	{DUAL_ENTRY(_pthread_attr_getinheritsched)},	/* PJT_ATTR_GETINHERITSCHED */
196 	{DUAL_ENTRY(_pthread_attr_getschedparam)},	/* PJT_ATTR_GETSCHEDPARAM */
197 	{DUAL_ENTRY(_pthread_attr_getschedpolicy)},	/* PJT_ATTR_GETSCHEDPOLICY */
198 	{DUAL_ENTRY(_pthread_attr_getscope)},	/* PJT_ATTR_GETSCOPE */
199 	{DUAL_ENTRY(_pthread_attr_getstackaddr)},	/* PJT_ATTR_GETSTACKADDR */
200 	{DUAL_ENTRY(_pthread_attr_getstacksize)},	/* PJT_ATTR_GETSTACKSIZE */
201 	{DUAL_ENTRY(_pthread_attr_init)},	/* PJT_ATTR_INIT */
202 	{DUAL_ENTRY(_pthread_attr_setdetachstate)},	/* PJT_ATTR_SETDETACHSTATE */
203 	{DUAL_ENTRY(_pthread_attr_setguardsize)},	/* PJT_ATTR_SETGUARDSIZE */
204 	{DUAL_ENTRY(_pthread_attr_setinheritsched)},	/* PJT_ATTR_SETINHERITSCHED */
205 	{DUAL_ENTRY(_pthread_attr_setschedparam)},	/* PJT_ATTR_SETSCHEDPARAM */
206 	{DUAL_ENTRY(_pthread_attr_setschedpolicy)},	/* PJT_ATTR_SETSCHEDPOLICY */
207 	{DUAL_ENTRY(_pthread_attr_setscope)},	/* PJT_ATTR_SETSCOPE */
208 	{DUAL_ENTRY(_pthread_attr_setstackaddr)},	/* PJT_ATTR_SETSTACKADDR */
209 	{DUAL_ENTRY(_pthread_attr_setstacksize)},	/* PJT_ATTR_SETSTACKSIZE */
210 	{DUAL_ENTRY(_pthread_cancel)},	/* PJT_CANCEL */
211 	{DUAL_ENTRY(_pthread_cleanup_pop)},	/* PJT_CLEANUP_POP */
212 	{DUAL_ENTRY(_pthread_cleanup_push)},	/* PJT_CLEANUP_PUSH */
213 	{DUAL_ENTRY(_pthread_cond_broadcast)},	/* PJT_COND_BROADCAST */
214 	{DUAL_ENTRY(_pthread_cond_destroy)},	/* PJT_COND_DESTROY */
215 	{DUAL_ENTRY(_pthread_cond_init)},	/* PJT_COND_INIT */
216 	{DUAL_ENTRY(_pthread_cond_signal)},	/* PJT_COND_SIGNAL */
217 	{DUAL_ENTRY(_pthread_cond_timedwait)},	/* PJT_COND_TIMEDWAIT */
218 	{(pthread_func_t)__pthread_cond_wait,
219 	 (pthread_func_t)_pthread_cond_wait},	/* PJT_COND_WAIT */
220 	{DUAL_ENTRY(_pthread_detach)},	/* PJT_DETACH */
221 	{DUAL_ENTRY(_pthread_equal)},	/* PJT_EQUAL */
222 	{DUAL_ENTRY(_pthread_exit)},	/* PJT_EXIT */
223 	{DUAL_ENTRY(_pthread_getspecific)},	/* PJT_GETSPECIFIC */
224 	{DUAL_ENTRY(_pthread_join)},	/* PJT_JOIN */
225 	{DUAL_ENTRY(_pthread_key_create)},	/* PJT_KEY_CREATE */
226 	{DUAL_ENTRY(_pthread_key_delete)},	/* PJT_KEY_DELETE*/
227 	{DUAL_ENTRY(_pthread_kill)},	/* PJT_KILL */
228 	{DUAL_ENTRY(_pthread_main_np)},		/* PJT_MAIN_NP */
229 	{DUAL_ENTRY(_pthread_mutexattr_destroy)}, /* PJT_MUTEXATTR_DESTROY */
230 	{DUAL_ENTRY(_pthread_mutexattr_init)},	/* PJT_MUTEXATTR_INIT */
231 	{DUAL_ENTRY(_pthread_mutexattr_settype)}, /* PJT_MUTEXATTR_SETTYPE */
232 	{DUAL_ENTRY(_pthread_mutex_destroy)},	/* PJT_MUTEX_DESTROY */
233 	{DUAL_ENTRY(_pthread_mutex_init)},	/* PJT_MUTEX_INIT */
234 	{(pthread_func_t)__pthread_mutex_lock,
235 	 (pthread_func_t)_pthread_mutex_lock},	/* PJT_MUTEX_LOCK */
236 	{(pthread_func_t)__pthread_mutex_trylock,
237 	 (pthread_func_t)_pthread_mutex_trylock},/* PJT_MUTEX_TRYLOCK */
238 	{DUAL_ENTRY(_pthread_mutex_unlock)},	/* PJT_MUTEX_UNLOCK */
239 	{DUAL_ENTRY(_pthread_once)},		/* PJT_ONCE */
240 	{DUAL_ENTRY(_pthread_rwlock_destroy)},	/* PJT_RWLOCK_DESTROY */
241 	{DUAL_ENTRY(_pthread_rwlock_init)},	/* PJT_RWLOCK_INIT */
242 	{DUAL_ENTRY(_pthread_rwlock_rdlock)},	/* PJT_RWLOCK_RDLOCK */
243 	{DUAL_ENTRY(_pthread_rwlock_tryrdlock)},/* PJT_RWLOCK_TRYRDLOCK */
244 	{DUAL_ENTRY(_pthread_rwlock_trywrlock)},/* PJT_RWLOCK_TRYWRLOCK */
245 	{DUAL_ENTRY(_pthread_rwlock_unlock)},	/* PJT_RWLOCK_UNLOCK */
246 	{DUAL_ENTRY(_pthread_rwlock_wrlock)},	/* PJT_RWLOCK_WRLOCK */
247 	{DUAL_ENTRY(_pthread_self)},		/* PJT_SELF */
248 	{DUAL_ENTRY(_pthread_setcancelstate)},	/* PJT_SETCANCELSTATE */
249 	{DUAL_ENTRY(_pthread_setcanceltype)},	/* PJT_SETCANCELTYPE */
250 	{DUAL_ENTRY(_pthread_setspecific)},	/* PJT_SETSPECIFIC */
251 	{DUAL_ENTRY(_pthread_sigmask)},		/* PJT_SIGMASK */
252 	{DUAL_ENTRY(_pthread_testcancel)}	/* PJT_TESTCANCEL */
253 };
254 
255 static int init_once = 0;
256 
257 /*
258  * For the shared version of the threads library, the above is sufficient.
259  * But for the archive version of the library, we need a little bit more.
260  * Namely, we must arrange for this particular module to be pulled in from
261  * the archive library at link time.  To accomplish that, we define and
262  * initialize a variable, "_thread_autoinit_dummy_decl".  This variable is
263  * referenced (as an extern) from libc/stdlib/exit.c. This will always
264  * create a need for this module, ensuring that it is present in the
265  * executable.
266  */
267 extern int _thread_autoinit_dummy_decl;
268 int _thread_autoinit_dummy_decl = 0;
269 
270 void
271 _thread_init_hack(void)
272 {
273 
274 	_libpthread_init(NULL);
275 }
276 
277 
278 /*
279  * Threaded process initialization.
280  *
281  * This is only called under two conditions:
282  *
283  *   1) Some thread routines have detected that the library hasn't yet
284  *      been initialized (_thr_initial == NULL && curthread == NULL), or
285  *
286  *   2) An explicit call to reinitialize after a fork (indicated
287  *      by curthread != NULL)
288  */
289 void
290 _libpthread_init(struct pthread *curthread)
291 {
292 	int fd, first = 0;
293 	sigset_t sigset, oldset;
294 
295 	/* Check if this function has already been called: */
296 	if ((_thr_initial != NULL) && (curthread == NULL))
297 		/* Only initialize the threaded application once. */
298 		return;
299 
300 	/*
301 	 * Check the size of the jump table to make sure it is preset
302 	 * with the correct number of entries.
303 	 */
304 	if (sizeof(jmp_table) != (sizeof(pthread_func_t) * PJT_MAX * 2))
305 		PANIC("Thread jump table not properly initialized");
306 	memcpy(__thr_jtable, jmp_table, sizeof(jmp_table));
307 
308 	/*
309 	 * Check for the special case of this process running as
310 	 * or in place of init as pid = 1:
311 	 */
312 	if ((_thr_pid = getpid()) == 1) {
313 		/*
314 		 * Setup a new session for this process which is
315 		 * assumed to be running as root.
316 		 */
317 		if (setsid() == -1)
318 			PANIC("Can't set session ID");
319 		if (revoke(_PATH_CONSOLE) != 0)
320 			PANIC("Can't revoke console");
321 		if ((fd = __sys_open(_PATH_CONSOLE, O_RDWR)) < 0)
322 			PANIC("Can't open console");
323 		if (setlogin("root") == -1)
324 			PANIC("Can't set login to root");
325 		if (_ioctl(fd, TIOCSCTTY, (char *) NULL) == -1)
326 			PANIC("Can't set controlling terminal");
327 	}
328 
329 	/* Initialize pthread private data. */
330 	init_private();
331 
332 	/* Set the initial thread. */
333 	if (curthread == NULL) {
334 		first = 1;
335 		/* Create and initialize the initial thread. */
336 		curthread = _thr_alloc(NULL);
337 		if (curthread == NULL)
338 			PANIC("Can't allocate initial thread");
339 		init_main_thread(curthread);
340 	}
341 	/*
342 	 * Add the thread to the thread list queue.
343 	 */
344 	THR_LIST_ADD(curthread);
345 	_thread_active_threads = 1;
346 
347 	/* Setup the thread specific data */
348 	_tcb_set(curthread->tcb);
349 
350 	if (first) {
351 		SIGFILLSET(sigset);
352 		SIGDELSET(sigset, SIGTRAP);
353 		__sys_sigprocmask(SIG_SETMASK, &sigset, &oldset);
354 		_thr_signal_init();
355 		_thr_initial = curthread;
356 		SIGDELSET(oldset, SIGCANCEL);
357 		__sys_sigprocmask(SIG_SETMASK, &oldset, NULL);
358 		if (_thread_event_mask & TD_CREATE)
359 			_thr_report_creation(curthread, curthread);
360 	}
361 }
362 
363 /*
364  * This function and pthread_create() do a lot of the same things.
365  * It'd be nice to consolidate the common stuff in one place.
366  */
367 static void
368 init_main_thread(struct pthread *thread)
369 {
370 	/* Setup the thread attributes. */
371 	thr_self(&thread->tid);
372 	thread->attr = _pthread_attr_default;
373 	/*
374 	 * Set up the thread stack.
375 	 *
376 	 * Create a red zone below the main stack.  All other stacks
377 	 * are constrained to a maximum size by the parameters
378 	 * passed to mmap(), but this stack is only limited by
379 	 * resource limits, so this stack needs an explicitly mapped
380 	 * red zone to protect the thread stack that is just beyond.
381 	 */
382 	if (mmap(_usrstack - _thr_stack_initial -
383 	    _thr_guard_default, _thr_guard_default, 0, MAP_ANON,
384 	    -1, 0) == MAP_FAILED)
385 		PANIC("Cannot allocate red zone for initial thread");
386 
387 	/*
388 	 * Mark the stack as an application supplied stack so that it
389 	 * isn't deallocated.
390 	 *
391 	 * XXX - I'm not sure it would hurt anything to deallocate
392 	 *       the main thread stack because deallocation doesn't
393 	 *       actually free() it; it just puts it in the free
394 	 *       stack queue for later reuse.
395 	 */
396 	thread->attr.stackaddr_attr = _usrstack - _thr_stack_initial;
397 	thread->attr.stacksize_attr = _thr_stack_initial;
398 	thread->attr.guardsize_attr = _thr_guard_default;
399 	thread->attr.flags |= THR_STACK_USER;
400 
401 	/*
402 	 * Write a magic value to the thread structure
403 	 * to help identify valid ones:
404 	 */
405 	thread->magic = THR_MAGIC;
406 
407 	thread->cancelflags = PTHREAD_CANCEL_ENABLE | PTHREAD_CANCEL_DEFERRED;
408 	thr_set_name(thread->tid, "initial thread");
409 
410 	/* Default the priority of the initial thread: */
411 	thread->base_priority = THR_DEF_PRIORITY;
412 	thread->active_priority = THR_DEF_PRIORITY;
413 	thread->inherited_priority = 0;
414 
415 	/* Initialize the mutex queue: */
416 	TAILQ_INIT(&thread->mutexq);
417 
418 	thread->state = PS_RUNNING;
419 
420 	/* Others cleared to zero by thr_alloc() */
421 }
422 
423 static void
424 init_private(void)
425 {
426 	size_t len;
427 	int mib[2];
428 
429 	_thr_umtx_init(&_mutex_static_lock);
430 	_thr_umtx_init(&_cond_static_lock);
431 	_thr_umtx_init(&_rwlock_static_lock);
432 	_thr_umtx_init(&_keytable_lock);
433 	_thr_umtx_init(&_thr_atfork_lock);
434 	_thr_umtx_init(&_thr_event_lock);
435 	_thr_once_init();
436 	_thr_spinlock_init();
437 	_thr_list_init();
438 
439 	/*
440 	 * Avoid reinitializing some things if they don't need to be,
441 	 * e.g. after a fork().
442 	 */
443 	if (init_once == 0) {
444 		/* Find the stack top */
445 		mib[0] = CTL_KERN;
446 		mib[1] = KERN_USRSTACK;
447 		len = sizeof (_usrstack);
448 		if (sysctl(mib, 2, &_usrstack, &len, NULL, 0) == -1)
449 			PANIC("Cannot get kern.usrstack from sysctl");
450 		_thr_page_size = getpagesize();
451 		_thr_guard_default = _thr_page_size;
452 		_pthread_attr_default.guardsize_attr = _thr_guard_default;
453 		_pthread_attr_default.stacksize_attr = _thr_stack_default;
454 
455 		TAILQ_INIT(&_thr_atfork_list);
456 #ifdef SYSTEM_SCOPE_ONLY
457 		_thr_scope_system = 1;
458 #else
459 		if (getenv("LIBPTHREAD_SYSTEM_SCOPE") != NULL)
460 			_thr_scope_system = 1;
461 		else if (getenv("LIBPTHREAD_PROCESS_SCOPE") != NULL)
462 			_thr_scope_system = -1;
463 #endif
464 	}
465 	init_once = 1;
466 }
467