xref: /dflybsd-src/lib/libthread_xu/thread/thr_init.c (revision d9bb5dfdc3905237fb704584b71c9e0a9627656c)
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 
34 #include "namespace.h"
35 #include <sys/param.h>
36 #include <sys/signalvar.h>
37 #include <sys/ioctl.h>
38 #include <sys/sysctl.h>
39 #include <sys/time.h>
40 #include <sys/ttycom.h>
41 #include <sys/mman.h>
42 #include <stdio.h>
43 #include <fcntl.h>
44 #include <paths.h>
45 #include <pthread.h>
46 #include <signal.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <unistd.h>
50 #include "un-namespace.h"
51 
52 #include "libc_private.h"
53 #include "thr_private.h"
54 
55 /* Default thread attributes: */
56 struct pthread_attr _pthread_attr_default = {
57 	.sched_policy = SCHED_OTHER,
58 	.sched_inherit = 0,
59 	.prio = THR_DEFAULT_PRIORITY,
60 	.suspend = THR_CREATE_RUNNING,
61 	.flags = PTHREAD_SCOPE_SYSTEM,
62 	.stackaddr_attr = NULL,
63 	.stacksize_attr = THR_STACK_DEFAULT,
64 	.guardsize_attr = 0
65 };
66 
67 /* Default mutex attributes: */
68 struct pthread_mutex_attr _pthread_mutexattr_default = {
69 	.m_type = PTHREAD_MUTEX_DEFAULT,
70 	.m_protocol = PTHREAD_PRIO_NONE,
71 	.m_ceiling = 0,
72 	.m_flags = 0
73 };
74 
75 /* Default condition variable attributes: */
76 struct pthread_cond_attr _pthread_condattr_default = {
77 	.c_pshared = PTHREAD_PROCESS_PRIVATE,
78 	.c_clockid = CLOCK_REALTIME
79 };
80 
81 /* thr_attr.c */
82 STATIC_LIB_REQUIRE(_pthread_attr_init);
83 /* thr_barrier.c */
84 STATIC_LIB_REQUIRE(_pthread_barrier_init);
85 /* thr_barrierattr.c */
86 STATIC_LIB_REQUIRE(_pthread_barrierattr_init);
87 /* thr_cancel.c */
88 STATIC_LIB_REQUIRE(_pthread_cancel);
89 /* thr_clean.c */
90 STATIC_LIB_REQUIRE(_pthread_cleanup_push);
91 /* thr_concurrency.c */
92 STATIC_LIB_REQUIRE(_pthread_getconcurrency);
93 STATIC_LIB_REQUIRE(_pthread_setconcurrency);
94 /* thr_cond.c */
95 STATIC_LIB_REQUIRE(_pthread_cond_init);
96 /* thr_condattr.c */
97 STATIC_LIB_REQUIRE(_pthread_condattr_init);
98 /* thr_create.c */
99 STATIC_LIB_REQUIRE(_pthread_create);
100 /* thr_detach.c */
101 STATIC_LIB_REQUIRE(_pthread_detach);
102 /* thr_equal.c */
103 STATIC_LIB_REQUIRE(_pthread_equal);
104 /* thr_exit.c */
105 STATIC_LIB_REQUIRE(_pthread_exit);
106 /* thr_fork.c */
107 STATIC_LIB_REQUIRE(_pthread_atfork);
108 STATIC_LIB_REQUIRE(_fork);
109 /* thr_affinity.c */
110 STATIC_LIB_REQUIRE(_pthread_getaffinity_np);
111 /* thr_getcpuclockid.c */
112 STATIC_LIB_REQUIRE(_pthread_getcpuclockid);
113 /* thr_getprio.c */
114 STATIC_LIB_REQUIRE(_pthread_getprio);
115 /* thr_getschedparam.c */
116 STATIC_LIB_REQUIRE(_pthread_getschedparam);
117 /* thr_getthreadid_np.c */
118 STATIC_LIB_REQUIRE(_pthread_getthreadid_np);
119 /* thr_info.c */
120 STATIC_LIB_REQUIRE(_pthread_set_name_np);
121 /* thr_init.c */
122 STATIC_LIB_REQUIRE(_pthread_init_early);
123 /* thr_join.c */
124 STATIC_LIB_REQUIRE(_pthread_join);
125 /* thr_kill.c */
126 STATIC_LIB_REQUIRE(_pthread_kill);
127 /* thr_main_np.c */
128 STATIC_LIB_REQUIRE(_pthread_main_np);
129 /* thr_multi_np.c */
130 STATIC_LIB_REQUIRE(_pthread_multi_np);
131 /* thr_mutex.c */
132 STATIC_LIB_REQUIRE(_pthread_mutex_init);
133 /* thr_mutex_prioceiling.c */
134 STATIC_LIB_REQUIRE(_pthread_mutexattr_getprioceiling);
135 /* thr_mutex_protocol.c */
136 STATIC_LIB_REQUIRE(_pthread_mutexattr_getprotocol);
137 /* thr_mutexattr.c */
138 STATIC_LIB_REQUIRE(_pthread_mutexattr_init);
139 /* thr_once.c */
140 STATIC_LIB_REQUIRE(_pthread_once);
141 /* thr_pspinlock.c */
142 STATIC_LIB_REQUIRE(_pthread_spin_init);
143 /* thr_resume_np.c */
144 STATIC_LIB_REQUIRE(_pthread_resume_np);
145 /* thr_rwlock.c */
146 STATIC_LIB_REQUIRE(_pthread_rwlock_init);
147 /* thr_rwlockattr.c */
148 STATIC_LIB_REQUIRE(_pthread_rwlockattr_init);
149 /* thr_self.c */
150 STATIC_LIB_REQUIRE(_pthread_self);
151 /* thr_sem.c */
152 STATIC_LIB_REQUIRE(_sem_init);
153 /* thr_affinity.c */
154 STATIC_LIB_REQUIRE(_pthread_setaffinity_np);
155 /* thr_setprio.c */
156 STATIC_LIB_REQUIRE(_pthread_setprio);
157 /* thr_setschedparam.c */
158 STATIC_LIB_REQUIRE(_pthread_setschedparam);
159 /* thr_sig.c */
160 STATIC_LIB_REQUIRE(_sigwait);
161 /* thr_single_np.c */
162 STATIC_LIB_REQUIRE(_pthread_single_np);
163 /* thr_spec.c */
164 STATIC_LIB_REQUIRE(_pthread_key_create);
165 /* thr_spinlock.c */
166 STATIC_LIB_REQUIRE(_spinlock);
167 /* thr_suspend_np.c */
168 STATIC_LIB_REQUIRE(_pthread_suspend_np);
169 /* thr_switch_np.c */
170 STATIC_LIB_REQUIRE(_pthread_switch_add_np);
171 /* thr_symbols.c */
172 STATIC_LIB_REQUIRE(_thread_state_running);
173 /* thr_syscalls.c */
174 STATIC_LIB_REQUIRE(__wait4);
175 /* thr_yield.c */
176 STATIC_LIB_REQUIRE(_pthread_yield);
177 
178 char		*_usrstack;
179 struct pthread	*_thr_initial;
180 static void	*_thr_main_redzone;
181 
182 pid_t		_thr_pid;
183 size_t		_thr_guard_default;
184 size_t		_thr_stack_default =	THR_STACK_DEFAULT;
185 size_t		_thr_stack_initial =	THR_STACK_INITIAL;
186 int		_thr_page_size;
187 
188 static void	init_private(void);
189 static void	_libpthread_uninit(void);
190 static void	init_main_thread(struct pthread *thread);
191 
192 void	_thread_init(void) __attribute__ ((constructor));
193 void
194 _thread_init(void)
195 {
196 	_libpthread_init(NULL);
197 	_libc_thr_init();
198 }
199 
200 void	_thread_uninit(void) __attribute__ ((destructor));
201 void
202 _thread_uninit(void)
203 {
204 	_libpthread_uninit();
205 }
206 
207 /*
208  * This function is used by libc to initialise libpthread
209  * early during dynamic linking.
210  */
211 void _pthread_init_early(void);
212 void
213 _pthread_init_early(void)
214 {
215 	_libpthread_init(NULL);
216 }
217 
218 /*
219  * Threaded process initialization.
220  *
221  * This is only called under two conditions:
222  *
223  *   1) Some thread routines have detected that the library hasn't yet
224  *      been initialized (_thr_initial == NULL && curthread == NULL), or
225  *
226  *   2) An explicit call to reinitialize after a fork (indicated
227  *      by curthread != NULL)
228  */
229 void
230 _libpthread_init(struct pthread *curthread)
231 {
232 	int fd, first = 0;
233 	sigset_t sigset, oldset;
234 
235 	/* Check if this function has already been called: */
236 	if ((_thr_initial != NULL) && (curthread == NULL))
237 		/* Only initialize the threaded application once. */
238 		return;
239 
240 	/*
241 	 * Check for the special case of this process running as
242 	 * or in place of init as pid = 1:
243 	 */
244 	if ((_thr_pid = getpid()) == 1) {
245 		/*
246 		 * Setup a new session for this process which is
247 		 * assumed to be running as root.
248 		 */
249 		if (setsid() == -1)
250 			PANIC("Can't set session ID");
251 		if (revoke(_PATH_CONSOLE) != 0)
252 			PANIC("Can't revoke console");
253 		if ((fd = __sys_open(_PATH_CONSOLE, O_RDWR)) < 0)
254 			PANIC("Can't open console");
255 		if (setlogin("root") == -1)
256 			PANIC("Can't set login to root");
257 		if (__sys_ioctl(fd, TIOCSCTTY, NULL) == -1)
258 			PANIC("Can't set controlling terminal");
259 	}
260 
261 	/* Initialize pthread private data. */
262 	init_private();
263 
264 	/* Set the initial thread. */
265 	if (curthread == NULL) {
266 		first = 1;
267 		/* Create and initialize the initial thread. */
268 		curthread = _thr_alloc(NULL);
269 		if (curthread == NULL)
270 			PANIC("Can't allocate initial thread");
271 		init_main_thread(curthread);
272 	}
273 	/*
274 	 * Add the thread to the thread list queue.
275 	 */
276 	THR_LIST_ADD(curthread);
277 	_thread_active_threads = 1;
278 
279 	/* Setup the thread specific data */
280 	tls_set_tcb(curthread->tcb);
281 
282 	if (first) {
283 		SIGFILLSET(sigset);
284 		__sys_sigprocmask(SIG_SETMASK, &sigset, &oldset);
285 		_thr_signal_init();
286 		_thr_initial = curthread;
287 		SIGDELSET(oldset, SIGCANCEL);
288 		__sys_sigprocmask(SIG_SETMASK, &oldset, NULL);
289 		if (td_eventismember(&_thread_event_mask, TD_CREATE))
290 			_thr_report_creation(curthread, curthread);
291 		_thr_rtld_init();
292 		_thr_malloc_init();
293 		_thr_sem_init();
294 	}
295 }
296 
297 static void
298 _libpthread_uninit(void)
299 {
300 	if (_thr_initial == NULL)
301 		return;
302 	if (_thr_main_redzone && _thr_main_redzone != MAP_FAILED) {
303 		munmap(_thr_main_redzone, _thr_guard_default);
304 		_thr_main_redzone = NULL;
305 	}
306 	_thr_stack_cleanup();
307 }
308 
309 /*
310  * This function and pthread_create() do a lot of the same things.
311  * It'd be nice to consolidate the common stuff in one place.
312  */
313 static void
314 init_main_thread(struct pthread *thread)
315 {
316 	/* Setup the thread attributes. */
317 	thread->tid = _thr_get_tid();
318 	thread->attr = _pthread_attr_default;
319 	/*
320 	 * Set up the thread stack.
321 	 *
322 	 * Create a red zone below the main stack.  All other stacks
323 	 * are constrained to a maximum size by the parameters
324 	 * passed to mmap(), but this stack is only limited by
325 	 * resource limits, so this stack needs an explicitly mapped
326 	 * red zone to protect the thread stack that is just beyond.
327 	 */
328 	_thr_main_redzone = mmap(_usrstack - _thr_stack_initial -
329 				 _thr_guard_default, _thr_guard_default,
330 				 0, MAP_ANON | MAP_TRYFIXED, -1, 0);
331 	if (_thr_main_redzone == MAP_FAILED) {
332 		PANIC("Cannot allocate red zone for initial thread");
333 	}
334 
335 	/*
336 	 * Mark the stack as an application supplied stack so that it
337 	 * isn't deallocated.
338 	 *
339 	 * XXX - I'm not sure it would hurt anything to deallocate
340 	 *       the main thread stack because deallocation doesn't
341 	 *       actually free() it; it just puts it in the free
342 	 *       stack queue for later reuse.
343 	 */
344 	thread->attr.stackaddr_attr = _usrstack - _thr_stack_initial;
345 	thread->attr.stacksize_attr = _thr_stack_initial;
346 	thread->attr.guardsize_attr = _thr_guard_default;
347 	thread->attr.flags |= THR_STACK_USER;
348 
349 	/*
350 	 * Write a magic value to the thread structure
351 	 * to help identify valid ones:
352 	 */
353 	thread->magic = THR_MAGIC;
354 
355 	thread->cancelflags = PTHREAD_CANCEL_ENABLE | PTHREAD_CANCEL_DEFERRED;
356 	thread->name = __malloc(16);
357 	snprintf(thread->name, 16, "initial thread");
358 
359 	/* Default the priority of the initial thread: */
360 	thread->base_priority = THR_DEFAULT_PRIORITY;
361 	thread->active_priority = THR_DEFAULT_PRIORITY;
362 	thread->inherited_priority = 0;
363 
364 	/* Initialize the mutex queue: */
365 	TAILQ_INIT(&thread->mutexq);
366 
367 	thread->state = PS_RUNNING;
368 	thread->uniqueid = 0;
369 
370 	/* Others cleared to zero by thr_alloc() */
371 }
372 
373 static void
374 init_private(void)
375 {
376 	static int init_once = 0;
377 	size_t len;
378 	int mib[2];
379 
380 	/*
381 	 * Avoid reinitializing some things if they don't need to be,
382 	 * e.g. after a fork().
383 	 *
384 	 * NOTE: _thr_atfork_*list must remain intact after a fork.
385 	 */
386 	if (init_once == 0) {
387 		/* Find the stack top */
388 		mib[0] = CTL_KERN;
389 		mib[1] = KERN_USRSTACK;
390 		len = sizeof (_usrstack);
391 		if (sysctl(mib, 2, &_usrstack, &len, NULL, 0) == -1)
392 			PANIC("Cannot get kern.usrstack from sysctl");
393 		_thr_page_size = getpagesize();
394 		_thr_guard_default = _thr_page_size;
395 		_pthread_attr_default.guardsize_attr = _thr_guard_default;
396 		TAILQ_INIT(&_thr_atfork_list);
397 		TAILQ_INIT(&_thr_atfork_kern_list);
398 		init_once = 1;
399 	}
400 
401 	_thr_umtx_init(&_mutex_static_lock);
402 	_thr_umtx_init(&_cond_static_lock);
403 	_thr_umtx_init(&_rwlock_static_lock);
404 	_thr_umtx_init(&_keytable_lock);
405 	_thr_umtx_init(&_thr_atfork_lock);
406 	_thr_umtx_init(&_thr_event_lock);
407 	_thr_spinlock_init();
408 	_thr_list_init();
409 }
410 
411 __strong_reference(_pthread_init_early, pthread_init_early);
412