xref: /freebsd/sys/kern/kern_thr.c (revision c27f7d6b9cf6d4ab01cb3d0972726c14e0aca146)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2003, Jeffrey Roberson <jeff@freebsd.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice unmodified, this list of conditions, and the following
12  *    disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include "opt_posix.h"
30 #include "opt_hwpmc_hooks.h"
31 
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
34 #include <sys/limits.h>
35 #include <sys/lock.h>
36 #include <sys/mutex.h>
37 #include <sys/priv.h>
38 #include <sys/proc.h>
39 #include <sys/posix4.h>
40 #include <sys/ptrace.h>
41 #include <sys/racct.h>
42 #include <sys/resourcevar.h>
43 #include <sys/rtprio.h>
44 #include <sys/rwlock.h>
45 #include <sys/sched.h>
46 #include <sys/sysctl.h>
47 #include <sys/smp.h>
48 #include <sys/syscallsubr.h>
49 #include <sys/sysent.h>
50 #include <sys/sysproto.h>
51 #include <sys/signalvar.h>
52 #include <sys/sysctl.h>
53 #include <sys/thr.h>
54 #include <sys/ucontext.h>
55 #include <sys/umtxvar.h>
56 #ifdef	HWPMC_HOOKS
57 #include <sys/pmckern.h>
58 #endif
59 
60 #include <machine/frame.h>
61 
62 #include <security/audit/audit.h>
63 
64 static SYSCTL_NODE(_kern, OID_AUTO, threads, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
65     "thread allocation");
66 
67 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 	int error;
149 
150 	/*
151 	 * Here we copy out tid to two places, one for child and one
152 	 * for parent, because pthread can create a detached thread,
153 	 * if parent wants to safely access child tid, it has to provide
154 	 * its storage, because child thread may exit quickly and
155 	 * memory is freed before parent thread can access it.
156 	 */
157 	param = thunk;
158 	if ((param->child_tid != NULL &&
159 	    suword_lwpid(param->child_tid, td->td_tid)) ||
160 	    (param->parent_tid != NULL &&
161 	    suword_lwpid(param->parent_tid, td->td_tid)))
162 		return (EFAULT);
163 
164 	/* Set up our machine context. */
165 	stack.ss_sp = param->stack_base;
166 	stack.ss_size = param->stack_size;
167 	/* Set upcall address to user thread entry function. */
168 	error = cpu_set_upcall(td, param->start_func, param->arg, &stack);
169 	if (error != 0)
170 		return (error);
171 	/* Setup user TLS address and TLS pointer register. */
172 	return (cpu_set_user_tls(td, param->tls_base, param->flags));
173 }
174 
175 int
176 kern_thr_new(struct thread *td, struct thr_param *param)
177 {
178 	struct rtprio rtp, *rtpp;
179 	int error;
180 
181 	if ((param->flags & ~(THR_SUSPENDED | THR_SYSTEM_SCOPE |
182 	    THR_C_RUNTIME)) != 0)
183 		return (EINVAL);
184 	rtpp = NULL;
185 	if (param->rtp != 0) {
186 		error = copyin(param->rtp, &rtp, sizeof(struct rtprio));
187 		if (error)
188 			return (error);
189 		rtpp = &rtp;
190 	}
191 	return (thread_create(td, rtpp, thr_new_initthr, param));
192 }
193 
194 int
195 thread_create(struct thread *td, struct rtprio *rtp,
196     int (*initialize_thread)(struct thread *, void *), void *thunk)
197 {
198 	struct thread *newtd;
199 	struct proc *p;
200 	int error;
201 
202 	p = td->td_proc;
203 
204 	if (rtp != NULL) {
205 		switch(rtp->type) {
206 		case RTP_PRIO_REALTIME:
207 		case RTP_PRIO_FIFO:
208 			/* Only root can set scheduler policy */
209 			if (priv_check(td, PRIV_SCHED_SETPOLICY) != 0)
210 				return (EPERM);
211 			if (rtp->prio > RTP_PRIO_MAX)
212 				return (EINVAL);
213 			break;
214 		case RTP_PRIO_NORMAL:
215 			rtp->prio = 0;
216 			break;
217 		default:
218 			return (EINVAL);
219 		}
220 	}
221 
222 #ifdef RACCT
223 	if (racct_enable) {
224 		PROC_LOCK(p);
225 		error = racct_add(p, RACCT_NTHR, 1);
226 		PROC_UNLOCK(p);
227 		if (error != 0)
228 			return (EPROCLIM);
229 	}
230 #endif
231 
232 	/* Initialize our td */
233 	error = kern_thr_alloc(p, 0, &newtd);
234 	if (error)
235 		goto fail;
236 
237 	bzero(&newtd->td_startzero,
238 	    __rangeof(struct thread, td_startzero, td_endzero));
239 	bcopy(&td->td_startcopy, &newtd->td_startcopy,
240 	    __rangeof(struct thread, td_startcopy, td_endcopy));
241 	newtd->td_proc = td->td_proc;
242 	newtd->td_rb_list = newtd->td_rbp_list = newtd->td_rb_inact = 0;
243 	thread_cow_get(newtd, td);
244 
245 	cpu_copy_thread(newtd, td);
246 
247 	error = initialize_thread(newtd, thunk);
248 	if (error != 0) {
249 		thread_cow_free(newtd);
250 		thread_free(newtd);
251 		goto fail;
252 	}
253 
254 	PROC_LOCK(p);
255 	p->p_flag |= P_HADTHREADS;
256 	thread_link(newtd, p);
257 	bcopy(p->p_comm, newtd->td_name, sizeof(newtd->td_name));
258 	thread_lock(td);
259 	/* let the scheduler know about these things. */
260 	sched_fork_thread(td, newtd);
261 	thread_unlock(td);
262 	if (P_SHOULDSTOP(p))
263 		ast_sched(newtd, TDA_SUSPEND);
264 	if (p->p_ptevents & PTRACE_LWP)
265 		newtd->td_dbgflags |= TDB_BORN;
266 
267 	PROC_UNLOCK(p);
268 #ifdef	HWPMC_HOOKS
269 	if (PMC_PROC_IS_USING_PMCS(p))
270 		PMC_CALL_HOOK(newtd, PMC_FN_THR_CREATE, NULL);
271 	else if (PMC_SYSTEM_SAMPLING_ACTIVE())
272 		PMC_CALL_HOOK_UNLOCKED(newtd, PMC_FN_THR_CREATE_LOG, NULL);
273 #endif
274 
275 	tidhash_add(newtd);
276 
277 	/* ignore timesharing class */
278 	if (rtp != NULL && !(td->td_pri_class == PRI_TIMESHARE &&
279 	    rtp->type == RTP_PRIO_NORMAL))
280 		rtp_to_pri(rtp, newtd);
281 
282 	thread_lock(newtd);
283 	TD_SET_CAN_RUN(newtd);
284 	sched_add(newtd, SRQ_BORING);
285 
286 	return (0);
287 
288 fail:
289 #ifdef RACCT
290 	if (racct_enable) {
291 		PROC_LOCK(p);
292 		racct_sub(p, RACCT_NTHR, 1);
293 		PROC_UNLOCK(p);
294 	}
295 #endif
296 	return (error);
297 }
298 
299 int
300 sys_thr_self(struct thread *td, struct thr_self_args *uap)
301     /* long *id */
302 {
303 	int error;
304 
305 	error = suword_lwpid(uap->id, (unsigned)td->td_tid);
306 	if (error == -1)
307 		return (EFAULT);
308 	return (0);
309 }
310 
311 int
312 sys_thr_exit(struct thread *td, struct thr_exit_args *uap)
313     /* long *state */
314 {
315 
316 	umtx_thread_exit(td);
317 
318 	/* Signal userland that it can free the stack. */
319 	if ((void *)uap->state != NULL) {
320 		(void)suword_lwpid(uap->state, 1);
321 		(void)kern_umtx_wake(td, uap->state, INT_MAX, 0);
322 	}
323 
324 	return (kern_thr_exit(td));
325 }
326 
327 int
328 kern_thr_exit(struct thread *td)
329 {
330 	struct proc *p;
331 
332 	p = td->td_proc;
333 
334 	/*
335 	 * If all of the threads in a process call this routine to
336 	 * exit (e.g. all threads call pthread_exit()), exactly one
337 	 * thread should return to the caller to terminate the process
338 	 * instead of the thread.
339 	 *
340 	 * Checking p_numthreads alone is not sufficient since threads
341 	 * might be committed to terminating while the PROC_LOCK is
342 	 * dropped in either ptracestop() or while removing this thread
343 	 * from the tidhash.  Instead, the p_pendingexits field holds
344 	 * the count of threads in either of those states and a thread
345 	 * is considered the "last" thread if all of the other threads
346 	 * in a process are already terminating.
347 	 */
348 	PROC_LOCK(p);
349 	if (p->p_numthreads == p->p_pendingexits + 1) {
350 		/*
351 		 * Ignore attempts to shut down last thread in the
352 		 * proc.  This will actually call _exit(2) in the
353 		 * usermode trampoline when it returns.
354 		 */
355 		PROC_UNLOCK(p);
356 		return (0);
357 	}
358 
359 	if (p->p_sysent->sv_ontdexit != NULL)
360 		p->p_sysent->sv_ontdexit(td);
361 
362 	td->td_dbgflags |= TDB_EXIT;
363 	if (p->p_ptevents & PTRACE_LWP) {
364 		p->p_pendingexits++;
365 		ptracestop(td, SIGTRAP, NULL);
366 		p->p_pendingexits--;
367 	}
368 	tidhash_remove(td);
369 
370 	/*
371 	 * The check above should prevent all other threads from this
372 	 * process from exiting while the PROC_LOCK is dropped, so
373 	 * there must be at least one other thread other than the
374 	 * current thread.
375 	 */
376 	KASSERT(p->p_numthreads > 1, ("too few threads"));
377 	racct_sub(p, RACCT_NTHR, 1);
378 	tdsigcleanup(td);
379 
380 #ifdef AUDIT
381 	AUDIT_SYSCALL_EXIT(0, td);
382 #endif
383 
384 	PROC_SLOCK(p);
385 	thread_stopped(p);
386 	thread_exit();
387 	/* NOTREACHED */
388 }
389 
390 int
391 sys_thr_kill(struct thread *td, struct thr_kill_args *uap)
392     /* long id, int sig */
393 {
394 	ksiginfo_t ksi;
395 	struct thread *ttd;
396 	struct proc *p;
397 	int error;
398 
399 	p = td->td_proc;
400 	ksiginfo_init(&ksi);
401 	ksi.ksi_signo = uap->sig;
402 	ksi.ksi_code = SI_LWP;
403 	ksi.ksi_pid = p->p_pid;
404 	ksi.ksi_uid = td->td_ucred->cr_ruid;
405 	if (uap->id == -1) {
406 		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
407 			error = EINVAL;
408 		} else {
409 			error = ESRCH;
410 			PROC_LOCK(p);
411 			FOREACH_THREAD_IN_PROC(p, ttd) {
412 				if (ttd != td) {
413 					error = 0;
414 					if (uap->sig == 0)
415 						break;
416 					tdksignal(ttd, uap->sig, &ksi);
417 				}
418 			}
419 			PROC_UNLOCK(p);
420 		}
421 	} else {
422 		error = 0;
423 		ttd = tdfind((lwpid_t)uap->id, p->p_pid);
424 		if (ttd == NULL)
425 			return (ESRCH);
426 		if (uap->sig == 0)
427 			;
428 		else if (!_SIG_VALID(uap->sig))
429 			error = EINVAL;
430 		else
431 			tdksignal(ttd, uap->sig, &ksi);
432 		PROC_UNLOCK(ttd->td_proc);
433 	}
434 	return (error);
435 }
436 
437 int
438 sys_thr_kill2(struct thread *td, struct thr_kill2_args *uap)
439     /* pid_t pid, long id, int sig */
440 {
441 	ksiginfo_t ksi;
442 	struct thread *ttd;
443 	struct proc *p;
444 	int error;
445 
446 	AUDIT_ARG_SIGNUM(uap->sig);
447 
448 	ksiginfo_init(&ksi);
449 	ksi.ksi_signo = uap->sig;
450 	ksi.ksi_code = SI_LWP;
451 	ksi.ksi_pid = td->td_proc->p_pid;
452 	ksi.ksi_uid = td->td_ucred->cr_ruid;
453 	if (uap->id == -1) {
454 		if ((p = pfind(uap->pid)) == NULL)
455 			return (ESRCH);
456 		AUDIT_ARG_PROCESS(p);
457 		error = p_cansignal(td, p, uap->sig);
458 		if (error) {
459 			PROC_UNLOCK(p);
460 			return (error);
461 		}
462 		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
463 			error = EINVAL;
464 		} else {
465 			error = ESRCH;
466 			FOREACH_THREAD_IN_PROC(p, ttd) {
467 				if (ttd != td) {
468 					error = 0;
469 					if (uap->sig == 0)
470 						break;
471 					tdksignal(ttd, uap->sig, &ksi);
472 				}
473 			}
474 		}
475 		PROC_UNLOCK(p);
476 	} else {
477 		ttd = tdfind((lwpid_t)uap->id, uap->pid);
478 		if (ttd == NULL)
479 			return (ESRCH);
480 		p = ttd->td_proc;
481 		AUDIT_ARG_PROCESS(p);
482 		error = p_cansignal(td, p, uap->sig);
483 		if (uap->sig == 0)
484 			;
485 		else if (!_SIG_VALID(uap->sig))
486 			error = EINVAL;
487 		else
488 			tdksignal(ttd, uap->sig, &ksi);
489 		PROC_UNLOCK(p);
490 	}
491 	return (error);
492 }
493 
494 int
495 sys_thr_suspend(struct thread *td, struct thr_suspend_args *uap)
496 	/* const struct timespec *timeout */
497 {
498 	struct timespec ts, *tsp;
499 	int error;
500 
501 	tsp = NULL;
502 	if (uap->timeout != NULL) {
503 		error = umtx_copyin_timeout(uap->timeout, &ts);
504 		if (error != 0)
505 			return (error);
506 		tsp = &ts;
507 	}
508 
509 	return (kern_thr_suspend(td, tsp));
510 }
511 
512 int
513 kern_thr_suspend(struct thread *td, struct timespec *tsp)
514 {
515 	struct proc *p = td->td_proc;
516 	struct timeval tv;
517 	int error = 0;
518 	int timo = 0;
519 
520 	if (td->td_pflags & TDP_WAKEUP) {
521 		td->td_pflags &= ~TDP_WAKEUP;
522 		return (0);
523 	}
524 
525 	if (tsp != NULL) {
526 		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
527 			error = EWOULDBLOCK;
528 		else {
529 			TIMESPEC_TO_TIMEVAL(&tv, tsp);
530 			timo = tvtohz(&tv);
531 		}
532 	}
533 
534 	PROC_LOCK(p);
535 	if (error == 0 && (td->td_flags & TDF_THRWAKEUP) == 0)
536 		error = msleep((void *)td, &p->p_mtx,
537 			 PCATCH, "lthr", timo);
538 
539 	if (td->td_flags & TDF_THRWAKEUP) {
540 		thread_lock(td);
541 		td->td_flags &= ~TDF_THRWAKEUP;
542 		thread_unlock(td);
543 		PROC_UNLOCK(p);
544 		return (0);
545 	}
546 	PROC_UNLOCK(p);
547 	if (error == EWOULDBLOCK)
548 		error = ETIMEDOUT;
549 	else if (error == ERESTART) {
550 		if (timo != 0)
551 			error = EINTR;
552 	}
553 	return (error);
554 }
555 
556 int
557 sys_thr_wake(struct thread *td, struct thr_wake_args *uap)
558 	/* long id */
559 {
560 	struct proc *p;
561 	struct thread *ttd;
562 
563 	if (uap->id == td->td_tid) {
564 		td->td_pflags |= TDP_WAKEUP;
565 		return (0);
566 	}
567 
568 	p = td->td_proc;
569 	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
570 	if (ttd == NULL)
571 		return (ESRCH);
572 	thread_lock(ttd);
573 	ttd->td_flags |= TDF_THRWAKEUP;
574 	thread_unlock(ttd);
575 	wakeup((void *)ttd);
576 	PROC_UNLOCK(p);
577 	return (0);
578 }
579 
580 int
581 sys_thr_set_name(struct thread *td, struct thr_set_name_args *uap)
582 {
583 	struct proc *p;
584 	char name[MAXCOMLEN + 1];
585 	struct thread *ttd;
586 	int error;
587 
588 	error = 0;
589 	name[0] = '\0';
590 	if (uap->name != NULL) {
591 		error = copyinstr(uap->name, name, sizeof(name), NULL);
592 		if (error == ENAMETOOLONG) {
593 			error = copyin(uap->name, name, sizeof(name) - 1);
594 			name[sizeof(name) - 1] = '\0';
595 		}
596 		if (error)
597 			return (error);
598 	}
599 	p = td->td_proc;
600 	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
601 	if (ttd == NULL)
602 		return (ESRCH);
603 	strcpy(ttd->td_name, name);
604 #ifdef HWPMC_HOOKS
605 	if (PMC_PROC_IS_USING_PMCS(p) || PMC_SYSTEM_SAMPLING_ACTIVE())
606 		PMC_CALL_HOOK_UNLOCKED(ttd, PMC_FN_THR_CREATE_LOG, NULL);
607 #endif
608 #ifdef KTR
609 	sched_clear_tdname(ttd);
610 #endif
611 	PROC_UNLOCK(p);
612 	return (error);
613 }
614 
615 int
616 kern_thr_alloc(struct proc *p, int pages, struct thread **ntd)
617 {
618 
619 	/* Have race condition but it is cheap. */
620 	if (p->p_numthreads >= max_threads_per_proc) {
621 		++max_threads_hits;
622 		return (EPROCLIM);
623 	}
624 
625 	*ntd = thread_alloc(pages);
626 	if (*ntd == NULL)
627 		return (ENOMEM);
628 
629 	return (0);
630 }
631