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