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