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