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