xref: /freebsd/lib/libthr/thread/thr_create.c (revision 1c05a6ea6b849ff95e539c31adea887c644a6a01)
1 /*
2  * Copyright (c) 2003 Daniel M. Eischen <deischen@gdeb.com>
3  * Copyright (c) 2005, David Xu <davidxu@freebsd.org>
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 unmodified, this list of conditions, and the following
11  *    disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 #include "namespace.h"
32 #include <sys/types.h>
33 #include <sys/rtprio.h>
34 #include <sys/signalvar.h>
35 #include <errno.h>
36 #include <link.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <stddef.h>
40 #include <pthread.h>
41 #include <pthread_np.h>
42 #include "un-namespace.h"
43 
44 #include "libc_private.h"
45 #include "thr_private.h"
46 
47 static int  create_stack(struct pthread_attr *pattr);
48 static void thread_start(struct pthread *curthread);
49 
50 __weak_reference(_pthread_create, pthread_create);
51 
52 int
53 _pthread_create(pthread_t * thread, const pthread_attr_t * attr,
54 	       void *(*start_routine) (void *), void *arg)
55 {
56 	struct pthread *curthread, *new_thread;
57 	struct thr_param param;
58 	struct sched_param sched_param;
59 	struct rtprio rtp;
60 	sigset_t set, oset;
61 	cpuset_t *cpusetp;
62 	int i, cpusetsize, create_suspended, locked, old_stack_prot, ret;
63 
64 	cpusetp = NULL;
65 	ret = cpusetsize = 0;
66 	_thr_check_init();
67 
68 	/*
69 	 * Tell libc and others now they need lock to protect their data.
70 	 */
71 	if (_thr_isthreaded() == 0) {
72 		_malloc_first_thread();
73 		if (_thr_setthreaded(1))
74 			return (EAGAIN);
75 	}
76 
77 	curthread = _get_curthread();
78 	if ((new_thread = _thr_alloc(curthread)) == NULL)
79 		return (EAGAIN);
80 
81 	memset(&param, 0, sizeof(param));
82 
83 	if (attr == NULL || *attr == NULL)
84 		/* Use the default thread attributes: */
85 		new_thread->attr = _pthread_attr_default;
86 	else {
87 		new_thread->attr = *(*attr);
88 		cpusetp = new_thread->attr.cpuset;
89 		cpusetsize = new_thread->attr.cpusetsize;
90 		new_thread->attr.cpuset = NULL;
91 		new_thread->attr.cpusetsize = 0;
92 	}
93 	if (new_thread->attr.sched_inherit == PTHREAD_INHERIT_SCHED) {
94 		/* inherit scheduling contention scope */
95 		if (curthread->attr.flags & PTHREAD_SCOPE_SYSTEM)
96 			new_thread->attr.flags |= PTHREAD_SCOPE_SYSTEM;
97 		else
98 			new_thread->attr.flags &= ~PTHREAD_SCOPE_SYSTEM;
99 
100 		new_thread->attr.prio = curthread->attr.prio;
101 		new_thread->attr.sched_policy = curthread->attr.sched_policy;
102 	}
103 
104 	new_thread->tid = TID_TERMINATED;
105 
106 	old_stack_prot = _rtld_get_stack_prot();
107 	if (create_stack(&new_thread->attr) != 0) {
108 		/* Insufficient memory to create a stack: */
109 		_thr_free(curthread, new_thread);
110 		return (EAGAIN);
111 	}
112 	/*
113 	 * Write a magic value to the thread structure
114 	 * to help identify valid ones:
115 	 */
116 	new_thread->magic = THR_MAGIC;
117 	new_thread->start_routine = start_routine;
118 	new_thread->arg = arg;
119 	new_thread->cancel_enable = 1;
120 	new_thread->cancel_async = 0;
121 	/* Initialize the mutex queue: */
122 	for (i = 0; i < TMQ_NITEMS; i++)
123 		TAILQ_INIT(&new_thread->mq[i]);
124 
125 	/* Initialise hooks in the thread structure: */
126 	if (new_thread->attr.suspend == THR_CREATE_SUSPENDED) {
127 		new_thread->flags = THR_FLAGS_NEED_SUSPEND;
128 		create_suspended = 1;
129 	} else {
130 		create_suspended = 0;
131 	}
132 
133 	new_thread->state = PS_RUNNING;
134 
135 	if (new_thread->attr.flags & PTHREAD_CREATE_DETACHED)
136 		new_thread->flags |= THR_FLAGS_DETACHED;
137 
138 	/* Add the new thread. */
139 	new_thread->refcount = 1;
140 	_thr_link(curthread, new_thread);
141 
142 	/*
143 	 * Handle the race between __pthread_map_stacks_exec and
144 	 * thread linkage.
145 	 */
146 	if (old_stack_prot != _rtld_get_stack_prot())
147 		_thr_stack_fix_protection(new_thread);
148 
149 	/* Return thread pointer eariler so that new thread can use it. */
150 	(*thread) = new_thread;
151 	if (SHOULD_REPORT_EVENT(curthread, TD_CREATE) || cpusetp != NULL) {
152 		THR_THREAD_LOCK(curthread, new_thread);
153 		locked = 1;
154 	} else
155 		locked = 0;
156 	param.start_func = (void (*)(void *)) thread_start;
157 	param.arg = new_thread;
158 	param.stack_base = new_thread->attr.stackaddr_attr;
159 	param.stack_size = new_thread->attr.stacksize_attr;
160 	param.tls_base = (char *)new_thread->tcb;
161 	param.tls_size = sizeof(struct tcb);
162 	param.child_tid = &new_thread->tid;
163 	param.parent_tid = &new_thread->tid;
164 	param.flags = 0;
165 	if (new_thread->attr.flags & PTHREAD_SCOPE_SYSTEM)
166 		param.flags |= THR_SYSTEM_SCOPE;
167 	if (new_thread->attr.sched_inherit == PTHREAD_INHERIT_SCHED)
168 		param.rtp = NULL;
169 	else {
170 		sched_param.sched_priority = new_thread->attr.prio;
171 		_schedparam_to_rtp(new_thread->attr.sched_policy,
172 			&sched_param, &rtp);
173 		param.rtp = &rtp;
174 	}
175 
176 	/* Schedule the new thread. */
177 	if (create_suspended) {
178 		SIGFILLSET(set);
179 		SIGDELSET(set, SIGTRAP);
180 		__sys_sigprocmask(SIG_SETMASK, &set, &oset);
181 		new_thread->sigmask = oset;
182 		SIGDELSET(new_thread->sigmask, SIGCANCEL);
183 	}
184 
185 	ret = thr_new(&param, sizeof(param));
186 
187 	if (ret != 0) {
188 		ret = errno;
189 		/*
190 		 * Translate EPROCLIM into well-known POSIX code EAGAIN.
191 		 */
192 		if (ret == EPROCLIM)
193 			ret = EAGAIN;
194 	}
195 
196 	if (create_suspended)
197 		__sys_sigprocmask(SIG_SETMASK, &oset, NULL);
198 
199 	if (ret != 0) {
200 		if (!locked)
201 			THR_THREAD_LOCK(curthread, new_thread);
202 		new_thread->state = PS_DEAD;
203 		new_thread->tid = TID_TERMINATED;
204 		new_thread->flags |= THR_FLAGS_DETACHED;
205 		new_thread->refcount--;
206 		if (new_thread->flags & THR_FLAGS_NEED_SUSPEND) {
207 			new_thread->cycle++;
208 			_thr_umtx_wake(&new_thread->cycle, INT_MAX, 0);
209 		}
210 		_thr_try_gc(curthread, new_thread); /* thread lock released */
211 		atomic_add_int(&_thread_active_threads, -1);
212 	} else if (locked) {
213 		if (cpusetp != NULL) {
214 			if (cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID,
215 				TID(new_thread), cpusetsize, cpusetp)) {
216 				ret = errno;
217 				/* kill the new thread */
218 				new_thread->force_exit = 1;
219 				new_thread->flags |= THR_FLAGS_DETACHED;
220 				_thr_try_gc(curthread, new_thread);
221 				 /* thread lock released */
222 				goto out;
223 			}
224 		}
225 
226 		_thr_report_creation(curthread, new_thread);
227 		THR_THREAD_UNLOCK(curthread, new_thread);
228 	}
229 out:
230 	if (ret)
231 		(*thread) = 0;
232 	return (ret);
233 }
234 
235 static int
236 create_stack(struct pthread_attr *pattr)
237 {
238 	int ret;
239 
240 	/* Check if a stack was specified in the thread attributes: */
241 	if ((pattr->stackaddr_attr) != NULL) {
242 		pattr->guardsize_attr = 0;
243 		pattr->flags |= THR_STACK_USER;
244 		ret = 0;
245 	}
246 	else
247 		ret = _thr_stack_alloc(pattr);
248 	return (ret);
249 }
250 
251 static void
252 thread_start(struct pthread *curthread)
253 {
254 	sigset_t set;
255 
256 	if (curthread->attr.suspend == THR_CREATE_SUSPENDED)
257 		set = curthread->sigmask;
258 
259 	/*
260 	 * This is used as a serialization point to allow parent
261 	 * to report 'new thread' event to debugger or tweak new thread's
262 	 * attributes before the new thread does real-world work.
263 	 */
264 	THR_LOCK(curthread);
265 	THR_UNLOCK(curthread);
266 
267 	if (curthread->force_exit)
268 		_pthread_exit(PTHREAD_CANCELED);
269 
270 	if (curthread->attr.suspend == THR_CREATE_SUSPENDED) {
271 #if 0
272 		/* Done in THR_UNLOCK() */
273 		_thr_ast(curthread);
274 #endif
275 
276 		/*
277 		 * Parent thread have stored signal mask for us,
278 		 * we should restore it now.
279 		 */
280 		__sys_sigprocmask(SIG_SETMASK, &set, NULL);
281 	}
282 
283 #ifdef _PTHREAD_FORCED_UNWIND
284 	curthread->unwind_stackend = (char *)curthread->attr.stackaddr_attr +
285 		curthread->attr.stacksize_attr;
286 #endif
287 
288 	/* Run the current thread's start routine with argument: */
289 	_pthread_exit(curthread->start_routine(curthread->arg));
290 
291 	/* This point should never be reached. */
292 	PANIC("Thread has resumed after exit");
293 }
294