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