xref: /freebsd/sys/kern/kern_thr.c (revision bd1da0a002e9a43cfb5220835c7a42804d90dc56)
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/posix4.h>
39 #include <sys/racct.h>
40 #include <sys/resourcevar.h>
41 #include <sys/rwlock.h>
42 #include <sys/sched.h>
43 #include <sys/sysctl.h>
44 #include <sys/smp.h>
45 #include <sys/syscallsubr.h>
46 #include <sys/sysent.h>
47 #include <sys/systm.h>
48 #include <sys/sysproto.h>
49 #include <sys/signalvar.h>
50 #include <sys/sysctl.h>
51 #include <sys/ucontext.h>
52 #include <sys/thr.h>
53 #include <sys/rtprio.h>
54 #include <sys/umtx.h>
55 #include <sys/limits.h>
56 
57 #include <machine/frame.h>
58 
59 #include <security/audit/audit.h>
60 
61 static SYSCTL_NODE(_kern, OID_AUTO, threads, CTLFLAG_RW, 0,
62     "thread allocation");
63 
64 static int max_threads_per_proc = 1500;
65 SYSCTL_INT(_kern_threads, OID_AUTO, max_threads_per_proc, CTLFLAG_RW,
66     &max_threads_per_proc, 0, "Limit on threads per proc");
67 
68 static int max_threads_hits;
69 SYSCTL_INT(_kern_threads, OID_AUTO, max_threads_hits, CTLFLAG_RD,
70     &max_threads_hits, 0, "kern.threads.max_threads_per_proc hit count");
71 
72 #ifdef COMPAT_FREEBSD32
73 
74 static inline int
75 suword_lwpid(void *addr, lwpid_t lwpid)
76 {
77 	int error;
78 
79 	if (SV_CURPROC_FLAG(SV_LP64))
80 		error = suword(addr, lwpid);
81 	else
82 		error = suword32(addr, lwpid);
83 	return (error);
84 }
85 
86 #else
87 #define suword_lwpid	suword
88 #endif
89 
90 static int create_thread(struct thread *td, mcontext_t *ctx,
91 			 void (*start_func)(void *), void *arg,
92 			 char *stack_base, size_t stack_size,
93 			 char *tls_base,
94 			 long *child_tid, long *parent_tid,
95 			 int flags, struct rtprio *rtp);
96 
97 /*
98  * System call interface.
99  */
100 int
101 sys_thr_create(struct thread *td, struct thr_create_args *uap)
102     /* ucontext_t *ctx, long *id, int flags */
103 {
104 	ucontext_t ctx;
105 	int error;
106 
107 	if ((error = copyin(uap->ctx, &ctx, sizeof(ctx))))
108 		return (error);
109 
110 	error = create_thread(td, &ctx.uc_mcontext, NULL, NULL,
111 		NULL, 0, NULL, uap->id, NULL, uap->flags, NULL);
112 	return (error);
113 }
114 
115 int
116 sys_thr_new(struct thread *td, struct thr_new_args *uap)
117     /* struct thr_param * */
118 {
119 	struct thr_param param;
120 	int error;
121 
122 	if (uap->param_size < 0 || uap->param_size > sizeof(param))
123 		return (EINVAL);
124 	bzero(&param, sizeof(param));
125 	if ((error = copyin(uap->param, &param, uap->param_size)))
126 		return (error);
127 	return (kern_thr_new(td, &param));
128 }
129 
130 int
131 kern_thr_new(struct thread *td, struct thr_param *param)
132 {
133 	struct rtprio rtp, *rtpp;
134 	int error;
135 
136 	rtpp = NULL;
137 	if (param->rtp != 0) {
138 		error = copyin(param->rtp, &rtp, sizeof(struct rtprio));
139 		if (error)
140 			return (error);
141 		rtpp = &rtp;
142 	}
143 	error = create_thread(td, NULL, param->start_func, param->arg,
144 		param->stack_base, param->stack_size, param->tls_base,
145 		param->child_tid, param->parent_tid, param->flags,
146 		rtpp);
147 	return (error);
148 }
149 
150 static int
151 create_thread(struct thread *td, mcontext_t *ctx,
152 	    void (*start_func)(void *), void *arg,
153 	    char *stack_base, size_t stack_size,
154 	    char *tls_base,
155 	    long *child_tid, long *parent_tid,
156 	    int flags, struct rtprio *rtp)
157 {
158 	stack_t stack;
159 	struct thread *newtd;
160 	struct proc *p;
161 	int error;
162 
163 	p = td->td_proc;
164 
165 	/* Have race condition but it is cheap. */
166 	if (p->p_numthreads >= max_threads_per_proc) {
167 		++max_threads_hits;
168 		return (EPROCLIM);
169 	}
170 
171 	if (rtp != NULL) {
172 		switch(rtp->type) {
173 		case RTP_PRIO_REALTIME:
174 		case RTP_PRIO_FIFO:
175 			/* Only root can set scheduler policy */
176 			if (priv_check(td, PRIV_SCHED_SETPOLICY) != 0)
177 				return (EPERM);
178 			if (rtp->prio > RTP_PRIO_MAX)
179 				return (EINVAL);
180 			break;
181 		case RTP_PRIO_NORMAL:
182 			rtp->prio = 0;
183 			break;
184 		default:
185 			return (EINVAL);
186 		}
187 	}
188 
189 #ifdef RACCT
190 	if (racct_enable) {
191 		PROC_LOCK(p);
192 		error = racct_add(p, RACCT_NTHR, 1);
193 		PROC_UNLOCK(p);
194 		if (error != 0)
195 			return (EPROCLIM);
196 	}
197 #endif
198 
199 	/* Initialize our td */
200 	newtd = thread_alloc(0);
201 	if (newtd == NULL) {
202 		error = ENOMEM;
203 		goto fail;
204 	}
205 
206 	cpu_set_upcall(newtd, td);
207 
208 	/*
209 	 * Try the copyout as soon as we allocate the td so we don't
210 	 * have to tear things down in a failure case below.
211 	 * Here we copy out tid to two places, one for child and one
212 	 * for parent, because pthread can create a detached thread,
213 	 * if parent wants to safely access child tid, it has to provide
214 	 * its storage, because child thread may exit quickly and
215 	 * memory is freed before parent thread can access it.
216 	 */
217 	if ((child_tid != NULL &&
218 	    suword_lwpid(child_tid, newtd->td_tid)) ||
219 	    (parent_tid != NULL &&
220 	    suword_lwpid(parent_tid, newtd->td_tid))) {
221 		thread_free(newtd);
222 		error = EFAULT;
223 		goto fail;
224 	}
225 
226 	bzero(&newtd->td_startzero,
227 	    __rangeof(struct thread, td_startzero, td_endzero));
228 	bcopy(&td->td_startcopy, &newtd->td_startcopy,
229 	    __rangeof(struct thread, td_startcopy, td_endcopy));
230 	newtd->td_proc = td->td_proc;
231 	newtd->td_ucred = crhold(td->td_ucred);
232 
233 	if (ctx != NULL) { /* old way to set user context */
234 		error = set_mcontext(newtd, ctx);
235 		if (error != 0) {
236 			thread_free(newtd);
237 			crfree(td->td_ucred);
238 			goto fail;
239 		}
240 	} else {
241 		/* Set up our machine context. */
242 		stack.ss_sp = stack_base;
243 		stack.ss_size = stack_size;
244 		/* Set upcall address to user thread entry function. */
245 		cpu_set_upcall_kse(newtd, start_func, arg, &stack);
246 		/* Setup user TLS address and TLS pointer register. */
247 		error = cpu_set_user_tls(newtd, tls_base);
248 		if (error != 0) {
249 			thread_free(newtd);
250 			crfree(td->td_ucred);
251 			goto fail;
252 		}
253 	}
254 
255 	PROC_LOCK(p);
256 	p->p_flag |= P_HADTHREADS;
257 	thread_link(newtd, p);
258 	bcopy(p->p_comm, newtd->td_name, sizeof(newtd->td_name));
259 	thread_lock(td);
260 	/* let the scheduler know about these things. */
261 	sched_fork_thread(td, newtd);
262 	thread_unlock(td);
263 	if (P_SHOULDSTOP(p))
264 		newtd->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
265 	PROC_UNLOCK(p);
266 
267 	tidhash_add(newtd);
268 
269 	thread_lock(newtd);
270 	if (rtp != NULL) {
271 		if (!(td->td_pri_class == PRI_TIMESHARE &&
272 		      rtp->type == RTP_PRIO_NORMAL)) {
273 			rtp_to_pri(rtp, newtd);
274 			sched_prio(newtd, newtd->td_user_pri);
275 		} /* ignore timesharing class */
276 	}
277 	TD_SET_CAN_RUN(newtd);
278 	sched_add(newtd, SRQ_BORING);
279 	thread_unlock(newtd);
280 
281 	return (0);
282 
283 fail:
284 #ifdef RACCT
285 	if (racct_enable) {
286 		PROC_LOCK(p);
287 		racct_sub(p, RACCT_NTHR, 1);
288 		PROC_UNLOCK(p);
289 	}
290 #endif
291 	return (error);
292 }
293 
294 int
295 sys_thr_self(struct thread *td, struct thr_self_args *uap)
296     /* long *id */
297 {
298 	int error;
299 
300 	error = suword_lwpid(uap->id, (unsigned)td->td_tid);
301 	if (error == -1)
302 		return (EFAULT);
303 	return (0);
304 }
305 
306 int
307 sys_thr_exit(struct thread *td, struct thr_exit_args *uap)
308     /* long *state */
309 {
310 	struct proc *p;
311 
312 	p = td->td_proc;
313 
314 	/* Signal userland that it can free the stack. */
315 	if ((void *)uap->state != NULL) {
316 		suword_lwpid(uap->state, 1);
317 		kern_umtx_wake(td, uap->state, INT_MAX, 0);
318 	}
319 
320 	rw_wlock(&tidhash_lock);
321 
322 	PROC_LOCK(p);
323 
324 	if (p->p_numthreads != 1) {
325 		racct_sub(p, RACCT_NTHR, 1);
326 		LIST_REMOVE(td, td_hash);
327 		rw_wunlock(&tidhash_lock);
328 		tdsigcleanup(td);
329 		umtx_thread_exit(td);
330 		PROC_SLOCK(p);
331 		thread_stopped(p);
332 		thread_exit();
333 		/* NOTREACHED */
334 	}
335 
336 	/*
337 	 * Ignore attempts to shut down last thread in the proc.  This
338 	 * will actually call _exit(2) in the usermode trampoline when
339 	 * it returns.
340 	 */
341 	PROC_UNLOCK(p);
342 	rw_wunlock(&tidhash_lock);
343 	return (0);
344 }
345 
346 int
347 sys_thr_kill(struct thread *td, struct thr_kill_args *uap)
348     /* long id, int sig */
349 {
350 	ksiginfo_t ksi;
351 	struct thread *ttd;
352 	struct proc *p;
353 	int error;
354 
355 	p = td->td_proc;
356 	ksiginfo_init(&ksi);
357 	ksi.ksi_signo = uap->sig;
358 	ksi.ksi_code = SI_LWP;
359 	ksi.ksi_pid = p->p_pid;
360 	ksi.ksi_uid = td->td_ucred->cr_ruid;
361 	if (uap->id == -1) {
362 		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
363 			error = EINVAL;
364 		} else {
365 			error = ESRCH;
366 			PROC_LOCK(p);
367 			FOREACH_THREAD_IN_PROC(p, ttd) {
368 				if (ttd != td) {
369 					error = 0;
370 					if (uap->sig == 0)
371 						break;
372 					tdksignal(ttd, uap->sig, &ksi);
373 				}
374 			}
375 			PROC_UNLOCK(p);
376 		}
377 	} else {
378 		error = 0;
379 		ttd = tdfind((lwpid_t)uap->id, p->p_pid);
380 		if (ttd == NULL)
381 			return (ESRCH);
382 		if (uap->sig == 0)
383 			;
384 		else if (!_SIG_VALID(uap->sig))
385 			error = EINVAL;
386 		else
387 			tdksignal(ttd, uap->sig, &ksi);
388 		PROC_UNLOCK(ttd->td_proc);
389 	}
390 	return (error);
391 }
392 
393 int
394 sys_thr_kill2(struct thread *td, struct thr_kill2_args *uap)
395     /* pid_t pid, long id, int sig */
396 {
397 	ksiginfo_t ksi;
398 	struct thread *ttd;
399 	struct proc *p;
400 	int error;
401 
402 	AUDIT_ARG_SIGNUM(uap->sig);
403 
404 	ksiginfo_init(&ksi);
405 	ksi.ksi_signo = uap->sig;
406 	ksi.ksi_code = SI_LWP;
407 	ksi.ksi_pid = td->td_proc->p_pid;
408 	ksi.ksi_uid = td->td_ucred->cr_ruid;
409 	if (uap->id == -1) {
410 		if ((p = pfind(uap->pid)) == NULL)
411 			return (ESRCH);
412 		AUDIT_ARG_PROCESS(p);
413 		error = p_cansignal(td, p, uap->sig);
414 		if (error) {
415 			PROC_UNLOCK(p);
416 			return (error);
417 		}
418 		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
419 			error = EINVAL;
420 		} else {
421 			error = ESRCH;
422 			FOREACH_THREAD_IN_PROC(p, ttd) {
423 				if (ttd != td) {
424 					error = 0;
425 					if (uap->sig == 0)
426 						break;
427 					tdksignal(ttd, uap->sig, &ksi);
428 				}
429 			}
430 		}
431 		PROC_UNLOCK(p);
432 	} else {
433 		ttd = tdfind((lwpid_t)uap->id, uap->pid);
434 		if (ttd == NULL)
435 			return (ESRCH);
436 		p = ttd->td_proc;
437 		AUDIT_ARG_PROCESS(p);
438 		error = p_cansignal(td, p, uap->sig);
439 		if (uap->sig == 0)
440 			;
441 		else if (!_SIG_VALID(uap->sig))
442 			error = EINVAL;
443 		else
444 			tdksignal(ttd, uap->sig, &ksi);
445 		PROC_UNLOCK(p);
446 	}
447 	return (error);
448 }
449 
450 int
451 sys_thr_suspend(struct thread *td, struct thr_suspend_args *uap)
452 	/* const struct timespec *timeout */
453 {
454 	struct timespec ts, *tsp;
455 	int error;
456 
457 	tsp = NULL;
458 	if (uap->timeout != NULL) {
459 		error = umtx_copyin_timeout(uap->timeout, &ts);
460 		if (error != 0)
461 			return (error);
462 		tsp = &ts;
463 	}
464 
465 	return (kern_thr_suspend(td, tsp));
466 }
467 
468 int
469 kern_thr_suspend(struct thread *td, struct timespec *tsp)
470 {
471 	struct proc *p = td->td_proc;
472 	struct timeval tv;
473 	int error = 0;
474 	int timo = 0;
475 
476 	if (td->td_pflags & TDP_WAKEUP) {
477 		td->td_pflags &= ~TDP_WAKEUP;
478 		return (0);
479 	}
480 
481 	if (tsp != NULL) {
482 		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
483 			error = EWOULDBLOCK;
484 		else {
485 			TIMESPEC_TO_TIMEVAL(&tv, tsp);
486 			timo = tvtohz(&tv);
487 		}
488 	}
489 
490 	PROC_LOCK(p);
491 	if (error == 0 && (td->td_flags & TDF_THRWAKEUP) == 0)
492 		error = msleep((void *)td, &p->p_mtx,
493 			 PCATCH, "lthr", timo);
494 
495 	if (td->td_flags & TDF_THRWAKEUP) {
496 		thread_lock(td);
497 		td->td_flags &= ~TDF_THRWAKEUP;
498 		thread_unlock(td);
499 		PROC_UNLOCK(p);
500 		return (0);
501 	}
502 	PROC_UNLOCK(p);
503 	if (error == EWOULDBLOCK)
504 		error = ETIMEDOUT;
505 	else if (error == ERESTART) {
506 		if (timo != 0)
507 			error = EINTR;
508 	}
509 	return (error);
510 }
511 
512 int
513 sys_thr_wake(struct thread *td, struct thr_wake_args *uap)
514 	/* long id */
515 {
516 	struct proc *p;
517 	struct thread *ttd;
518 
519 	if (uap->id == td->td_tid) {
520 		td->td_pflags |= TDP_WAKEUP;
521 		return (0);
522 	}
523 
524 	p = td->td_proc;
525 	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
526 	if (ttd == NULL)
527 		return (ESRCH);
528 	thread_lock(ttd);
529 	ttd->td_flags |= TDF_THRWAKEUP;
530 	thread_unlock(ttd);
531 	wakeup((void *)ttd);
532 	PROC_UNLOCK(p);
533 	return (0);
534 }
535 
536 int
537 sys_thr_set_name(struct thread *td, struct thr_set_name_args *uap)
538 {
539 	struct proc *p;
540 	char name[MAXCOMLEN + 1];
541 	struct thread *ttd;
542 	int error;
543 
544 	error = 0;
545 	name[0] = '\0';
546 	if (uap->name != NULL) {
547 		error = copyinstr(uap->name, name, sizeof(name),
548 			NULL);
549 		if (error)
550 			return (error);
551 	}
552 	p = td->td_proc;
553 	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
554 	if (ttd == NULL)
555 		return (ESRCH);
556 	strcpy(ttd->td_name, name);
557 #ifdef KTR
558 	sched_clear_tdname(ttd);
559 #endif
560 	PROC_UNLOCK(p);
561 	return (error);
562 }
563