xref: /freebsd/sys/kern/kern_thr.c (revision acd3428b7d3e94cef0e1881c868cb4b131d4ff41)
1 /*-
2  * Copyright (c) 2003, Jeffrey Roberson <jeff@freebsd.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice unmodified, this list of conditions, and the following
10  *    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  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_compat.h"
31 #include "opt_posix.h"
32 #include <sys/param.h>
33 #include <sys/kernel.h>
34 #include <sys/lock.h>
35 #include <sys/mutex.h>
36 #include <sys/priv.h>
37 #include <sys/proc.h>
38 #include <sys/resourcevar.h>
39 #include <sys/sched.h>
40 #include <sys/sysctl.h>
41 #include <sys/smp.h>
42 #include <sys/sysent.h>
43 #include <sys/systm.h>
44 #include <sys/sysproto.h>
45 #include <sys/signalvar.h>
46 #include <sys/ucontext.h>
47 #include <sys/thr.h>
48 #include <sys/rtprio.h>
49 #include <posix4/sched.h>
50 #include <posix4/posix4.h>
51 #include <sys/umtx.h>
52 #include <sys/limits.h>
53 
54 #include <machine/frame.h>
55 
56 #ifdef COMPAT_IA32
57 
58 extern struct sysentvec ia32_freebsd_sysvec;
59 
60 static inline int
61 suword_lwpid(void *addr, lwpid_t lwpid)
62 {
63 	int error;
64 
65 	if (curproc->p_sysent != &ia32_freebsd_sysvec)
66 		error = suword(addr, lwpid);
67 	else
68 		error = suword32(addr, lwpid);
69 	return (error);
70 }
71 
72 #else
73 #define suword_lwpid	suword
74 #endif
75 
76 extern int max_threads_per_proc;
77 
78 static int create_thread(struct thread *td, mcontext_t *ctx,
79 			 void (*start_func)(void *), void *arg,
80 			 char *stack_base, size_t stack_size,
81 			 char *tls_base,
82 			 long *child_tid, long *parent_tid,
83 			 int flags, struct rtprio *rtp);
84 
85 /*
86  * System call interface.
87  */
88 int
89 thr_create(struct thread *td, struct thr_create_args *uap)
90     /* ucontext_t *ctx, long *id, int flags */
91 {
92 	ucontext_t ctx;
93 	int error;
94 
95 	if ((error = copyin(uap->ctx, &ctx, sizeof(ctx))))
96 		return (error);
97 
98 	error = create_thread(td, &ctx.uc_mcontext, NULL, NULL,
99 		NULL, 0, NULL, uap->id, NULL, uap->flags, NULL);
100 	return (error);
101 }
102 
103 int
104 thr_new(struct thread *td, struct thr_new_args *uap)
105     /* struct thr_param * */
106 {
107 	struct thr_param param;
108 	int error;
109 
110 	if (uap->param_size < 0 || uap->param_size > sizeof(param))
111 		return (EINVAL);
112 	bzero(&param, sizeof(param));
113 	if ((error = copyin(uap->param, &param, uap->param_size)))
114 		return (error);
115 	return (kern_thr_new(td, &param));
116 }
117 
118 int
119 kern_thr_new(struct thread *td, struct thr_param *param)
120 {
121 	struct rtprio rtp, *rtpp;
122 	int error;
123 
124 	rtpp = NULL;
125 	if (param->rtp != 0) {
126 		error = copyin(param->rtp, &rtp, sizeof(struct rtprio));
127 		rtpp = &rtp;
128 	}
129 	error = create_thread(td, NULL, param->start_func, param->arg,
130 		param->stack_base, param->stack_size, param->tls_base,
131 		param->child_tid, param->parent_tid, param->flags,
132 		rtpp);
133 	return (error);
134 }
135 
136 static int
137 create_thread(struct thread *td, mcontext_t *ctx,
138 	    void (*start_func)(void *), void *arg,
139 	    char *stack_base, size_t stack_size,
140 	    char *tls_base,
141 	    long *child_tid, long *parent_tid,
142 	    int flags, struct rtprio *rtp)
143 {
144 	stack_t stack;
145 	struct thread *newtd;
146 #ifdef KSE
147 	struct ksegrp *kg, *newkg;
148 #endif
149 	struct proc *p;
150 	long id;
151 	int error;
152 
153 	error = 0;
154 	p = td->td_proc;
155 #ifdef KSE
156 	kg = td->td_ksegrp;
157 #endif
158 
159 	/* Have race condition but it is cheap. */
160 	if (p->p_numthreads >= max_threads_per_proc)
161 		return (EPROCLIM);
162 
163 	if (rtp != NULL) {
164 		switch(rtp->type) {
165 		case RTP_PRIO_REALTIME:
166 		case RTP_PRIO_FIFO:
167 			/* Only root can set scheduler policy */
168 			if (priv_check(td, PRIV_SCHED_SETPOLICY) != 0)
169 				return (EPERM);
170 			if (rtp->prio > RTP_PRIO_MAX)
171 				return (EINVAL);
172 			break;
173 		case RTP_PRIO_NORMAL:
174 			rtp->prio = 0;
175 			break;
176 		default:
177 			return (EINVAL);
178 		}
179 	}
180 
181 	/* Initialize our td and new ksegrp.. */
182 	newtd = thread_alloc();
183 
184 	/*
185 	 * Try the copyout as soon as we allocate the td so we don't
186 	 * have to tear things down in a failure case below.
187 	 * Here we copy out tid to two places, one for child and one
188 	 * for parent, because pthread can create a detached thread,
189 	 * if parent wants to safely access child tid, it has to provide
190 	 * its storage, because child thread may exit quickly and
191 	 * memory is freed before parent thread can access it.
192 	 */
193 	id = newtd->td_tid;
194 	if ((child_tid != NULL &&
195 	    suword_lwpid(child_tid, newtd->td_tid)) ||
196 	    (parent_tid != NULL &&
197 	    suword_lwpid(parent_tid, newtd->td_tid))) {
198 		thread_free(newtd);
199 		return (EFAULT);
200 	}
201 
202 	bzero(&newtd->td_startzero,
203 	    __rangeof(struct thread, td_startzero, td_endzero));
204 	bcopy(&td->td_startcopy, &newtd->td_startcopy,
205 	    __rangeof(struct thread, td_startcopy, td_endcopy));
206 	newtd->td_proc = td->td_proc;
207 	newtd->td_ucred = crhold(td->td_ucred);
208 
209 	cpu_set_upcall(newtd, td);
210 
211 	if (ctx != NULL) { /* old way to set user context */
212 		error = set_mcontext(newtd, ctx);
213 		if (error != 0) {
214 			thread_free(newtd);
215 			crfree(td->td_ucred);
216 			return (error);
217 		}
218 	} else {
219 		/* Set up our machine context. */
220 		stack.ss_sp = stack_base;
221 		stack.ss_size = stack_size;
222 		/* Set upcall address to user thread entry function. */
223 		cpu_set_upcall_kse(newtd, start_func, arg, &stack);
224 		/* Setup user TLS address and TLS pointer register. */
225 		error = cpu_set_user_tls(newtd, tls_base);
226 		if (error != 0) {
227 			thread_free(newtd);
228 			crfree(td->td_ucred);
229 			return (error);
230 		}
231 	}
232 
233 #ifdef KSE
234 	newkg = ksegrp_alloc();
235 	bzero(&newkg->kg_startzero,
236 	    __rangeof(struct ksegrp, kg_startzero, kg_endzero));
237 	bcopy(&kg->kg_startcopy, &newkg->kg_startcopy,
238 	    __rangeof(struct ksegrp, kg_startcopy, kg_endcopy));
239 	sched_init_concurrency(newkg);
240 	PROC_LOCK(td->td_proc);
241 	td->td_proc->p_flag |= P_HADTHREADS;
242 	newtd->td_sigmask = td->td_sigmask;
243 	mtx_lock_spin(&sched_lock);
244 	ksegrp_link(newkg, p);
245 	thread_link(newtd, newkg);
246 	PROC_UNLOCK(p);
247 #else
248     PROC_LOCK(td->td_proc);
249 	td->td_proc->p_flag |= P_HADTHREADS;
250 	newtd->td_sigmask = td->td_sigmask;
251 	mtx_lock_spin(&sched_lock);
252 	thread_link(newtd, p);
253 	PROC_UNLOCK(p);
254 #endif
255 
256 #ifdef KSE
257 	/* let the scheduler know about these things. */
258 	sched_fork_ksegrp(td, newkg);
259 	sched_fork_thread(td, newtd);
260 	if (rtp != NULL) {
261 		if (!(kg->kg_pri_class == PRI_TIMESHARE &&
262 		      rtp->type == RTP_PRIO_NORMAL)) {
263 			rtp_to_pri(rtp, newkg);
264 			sched_prio(newtd, newkg->kg_user_pri);
265 		} /* ignore timesharing class */
266 	}
267 #else
268 	sched_fork(td, newtd);
269 	if (rtp != NULL) {
270 		if (!(td->td_pri_class == PRI_TIMESHARE &&
271 		      rtp->type == RTP_PRIO_NORMAL)) {
272 			rtp_to_pri(rtp, newtd);
273 			sched_prio(newtd, newtd->td_user_pri);
274 		} /* ignore timesharing class */
275 	}
276 #endif
277 	TD_SET_CAN_RUN(newtd);
278 	/* if ((flags & THR_SUSPENDED) == 0) */
279 		setrunqueue(newtd, SRQ_BORING);
280 	mtx_unlock_spin(&sched_lock);
281 
282 	return (error);
283 }
284 
285 int
286 thr_self(struct thread *td, struct thr_self_args *uap)
287     /* long *id */
288 {
289 	int error;
290 
291 	error = suword_lwpid(uap->id, (unsigned)td->td_tid);
292 	if (error == -1)
293 		return (EFAULT);
294 	return (0);
295 }
296 
297 int
298 thr_exit(struct thread *td, struct thr_exit_args *uap)
299     /* long *state */
300 {
301 	struct proc *p;
302 
303 	p = td->td_proc;
304 
305 	/* Signal userland that it can free the stack. */
306 	if ((void *)uap->state != NULL) {
307 		suword_lwpid(uap->state, 1);
308 		kern_umtx_wake(td, uap->state, INT_MAX);
309 	}
310 
311 	PROC_LOCK(p);
312 	sigqueue_flush(&td->td_sigqueue);
313 	mtx_lock_spin(&sched_lock);
314 
315 	/*
316 	 * Shutting down last thread in the proc.  This will actually
317 	 * call exit() in the trampoline when it returns.
318 	 */
319 	if (p->p_numthreads != 1) {
320 		thread_stopped(p);
321 		thread_exit();
322 		/* NOTREACHED */
323 	}
324 	mtx_unlock_spin(&sched_lock);
325 	PROC_UNLOCK(p);
326 	return (0);
327 }
328 
329 int
330 thr_kill(struct thread *td, struct thr_kill_args *uap)
331     /* long id, int sig */
332 {
333 	struct thread *ttd;
334 	struct proc *p;
335 	int error;
336 
337 	p = td->td_proc;
338 	error = 0;
339 	PROC_LOCK(p);
340 	if (uap->id == -1) {
341 		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
342 			error = EINVAL;
343 		} else {
344 			error = ESRCH;
345 			FOREACH_THREAD_IN_PROC(p, ttd) {
346 				if (ttd != td) {
347 					error = 0;
348 					if (uap->sig == 0)
349 						break;
350 					tdsignal(p, ttd, uap->sig, NULL);
351 				}
352 			}
353 		}
354 	} else {
355 		if (uap->id != td->td_tid)
356 			ttd = thread_find(p, uap->id);
357 		else
358 			ttd = td;
359 		if (ttd == NULL)
360 			error = ESRCH;
361 		else if (uap->sig == 0)
362 			;
363 		else if (!_SIG_VALID(uap->sig))
364 			error = EINVAL;
365 		else
366 			tdsignal(p, ttd, uap->sig, NULL);
367 	}
368 	PROC_UNLOCK(p);
369 	return (error);
370 }
371 
372 int
373 thr_suspend(struct thread *td, struct thr_suspend_args *uap)
374 	/* const struct timespec *timeout */
375 {
376 	struct timespec ts, *tsp;
377 	int error;
378 
379 	error = 0;
380 	tsp = NULL;
381 	if (uap->timeout != NULL) {
382 		error = copyin((const void *)uap->timeout, (void *)&ts,
383 		    sizeof(struct timespec));
384 		if (error != 0)
385 			return (error);
386 		tsp = &ts;
387 	}
388 
389 	return (kern_thr_suspend(td, tsp));
390 }
391 
392 int
393 kern_thr_suspend(struct thread *td, struct timespec *tsp)
394 {
395 	struct timeval tv;
396 	int error = 0, hz = 0;
397 
398 	if (tsp != NULL) {
399 		if (tsp->tv_nsec < 0 || tsp->tv_nsec > 1000000000)
400 			return (EINVAL);
401 		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
402 			return (ETIMEDOUT);
403 		TIMESPEC_TO_TIMEVAL(&tv, tsp);
404 		hz = tvtohz(&tv);
405 	}
406 	PROC_LOCK(td->td_proc);
407 	if ((td->td_flags & TDF_THRWAKEUP) == 0)
408 		error = msleep((void *)td, &td->td_proc->p_mtx, PCATCH, "lthr",
409 		    hz);
410 	if (td->td_flags & TDF_THRWAKEUP) {
411 		mtx_lock_spin(&sched_lock);
412 		td->td_flags &= ~TDF_THRWAKEUP;
413 		mtx_unlock_spin(&sched_lock);
414 		PROC_UNLOCK(td->td_proc);
415 		return (0);
416 	}
417 	PROC_UNLOCK(td->td_proc);
418 	if (error == EWOULDBLOCK)
419 		error = ETIMEDOUT;
420 	else if (error == ERESTART) {
421 		if (hz != 0)
422 			error = EINTR;
423 	}
424 	return (error);
425 }
426 
427 int
428 thr_wake(struct thread *td, struct thr_wake_args *uap)
429 	/* long id */
430 {
431 	struct proc *p;
432 	struct thread *ttd;
433 
434 	p = td->td_proc;
435 	PROC_LOCK(p);
436 	ttd = thread_find(p, uap->id);
437 	if (ttd == NULL) {
438 		PROC_UNLOCK(p);
439 		return (ESRCH);
440 	}
441 	mtx_lock_spin(&sched_lock);
442 	ttd->td_flags |= TDF_THRWAKEUP;
443 	mtx_unlock_spin(&sched_lock);
444 	wakeup((void *)ttd);
445 	PROC_UNLOCK(p);
446 	return (0);
447 }
448 
449 int
450 thr_set_name(struct thread *td, struct thr_set_name_args *uap)
451 {
452 	struct proc *p = td->td_proc;
453 	char name[MAXCOMLEN + 1];
454 	struct thread *ttd;
455 	int error;
456 
457 	error = 0;
458 	name[0] = '\0';
459 	if (uap->name != NULL) {
460 		error = copyinstr(uap->name, name, sizeof(name),
461 			NULL);
462 		if (error)
463 			return (error);
464 	}
465 	PROC_LOCK(p);
466 	if (uap->id == td->td_tid)
467 		ttd = td;
468 	else
469 		ttd = thread_find(p, uap->id);
470 	if (ttd != NULL)
471 		strcpy(ttd->td_name, name);
472 	else
473 		error = ESRCH;
474 	PROC_UNLOCK(p);
475 	return (error);
476 }
477