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