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