xref: /freebsd/sys/kern/kern_thr.c (revision 5e3190f700637fcfc1a52daeaa4a031fdd2557c7)
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 
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 	cpu_set_upcall(td, param->start_func, param->arg, &stack);
169 	/* Setup user TLS address and TLS pointer register. */
170 	return (cpu_set_user_tls(td, param->tls_base));
171 }
172 
173 int
174 kern_thr_new(struct thread *td, struct thr_param *param)
175 {
176 	struct rtprio rtp, *rtpp;
177 	int error;
178 
179 	rtpp = NULL;
180 	if (param->rtp != 0) {
181 		error = copyin(param->rtp, &rtp, sizeof(struct rtprio));
182 		if (error)
183 			return (error);
184 		rtpp = &rtp;
185 	}
186 	return (thread_create(td, rtpp, thr_new_initthr, param));
187 }
188 
189 int
190 thread_create(struct thread *td, struct rtprio *rtp,
191     int (*initialize_thread)(struct thread *, void *), void *thunk)
192 {
193 	struct thread *newtd;
194 	struct proc *p;
195 	int error;
196 
197 	p = td->td_proc;
198 
199 	if (rtp != NULL) {
200 		switch(rtp->type) {
201 		case RTP_PRIO_REALTIME:
202 		case RTP_PRIO_FIFO:
203 			/* Only root can set scheduler policy */
204 			if (priv_check(td, PRIV_SCHED_SETPOLICY) != 0)
205 				return (EPERM);
206 			if (rtp->prio > RTP_PRIO_MAX)
207 				return (EINVAL);
208 			break;
209 		case RTP_PRIO_NORMAL:
210 			rtp->prio = 0;
211 			break;
212 		default:
213 			return (EINVAL);
214 		}
215 	}
216 
217 #ifdef RACCT
218 	if (racct_enable) {
219 		PROC_LOCK(p);
220 		error = racct_add(p, RACCT_NTHR, 1);
221 		PROC_UNLOCK(p);
222 		if (error != 0)
223 			return (EPROCLIM);
224 	}
225 #endif
226 
227 	/* Initialize our td */
228 	error = kern_thr_alloc(p, 0, &newtd);
229 	if (error)
230 		goto fail;
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 	newtd->td_rb_list = newtd->td_rbp_list = newtd->td_rb_inact = 0;
238 	thread_cow_get(newtd, td);
239 
240 	cpu_copy_thread(newtd, td);
241 
242 	error = initialize_thread(newtd, thunk);
243 	if (error != 0) {
244 		thread_cow_free(newtd);
245 		thread_free(newtd);
246 		goto fail;
247 	}
248 
249 	PROC_LOCK(p);
250 	p->p_flag |= P_HADTHREADS;
251 	thread_link(newtd, p);
252 	bcopy(p->p_comm, newtd->td_name, sizeof(newtd->td_name));
253 	thread_lock(td);
254 	/* let the scheduler know about these things. */
255 	sched_fork_thread(td, newtd);
256 	thread_unlock(td);
257 	if (P_SHOULDSTOP(p))
258 		ast_sched(newtd, TDA_SUSPEND);
259 	if (p->p_ptevents & PTRACE_LWP)
260 		newtd->td_dbgflags |= TDB_BORN;
261 
262 	PROC_UNLOCK(p);
263 #ifdef	HWPMC_HOOKS
264 	if (PMC_PROC_IS_USING_PMCS(p))
265 		PMC_CALL_HOOK(newtd, PMC_FN_THR_CREATE, NULL);
266 	else if (PMC_SYSTEM_SAMPLING_ACTIVE())
267 		PMC_CALL_HOOK_UNLOCKED(newtd, PMC_FN_THR_CREATE_LOG, NULL);
268 #endif
269 
270 	tidhash_add(newtd);
271 
272 	/* ignore timesharing class */
273 	if (rtp != NULL && !(td->td_pri_class == PRI_TIMESHARE &&
274 	    rtp->type == RTP_PRIO_NORMAL))
275 		rtp_to_pri(rtp, newtd);
276 
277 	thread_lock(newtd);
278 	TD_SET_CAN_RUN(newtd);
279 	sched_add(newtd, SRQ_BORING);
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 
311 	umtx_thread_exit(td);
312 
313 	/* Signal userland that it can free the stack. */
314 	if ((void *)uap->state != NULL) {
315 		suword_lwpid(uap->state, 1);
316 		kern_umtx_wake(td, uap->state, INT_MAX, 0);
317 	}
318 
319 	return (kern_thr_exit(td));
320 }
321 
322 int
323 kern_thr_exit(struct thread *td)
324 {
325 	struct proc *p;
326 
327 	p = td->td_proc;
328 
329 	/*
330 	 * If all of the threads in a process call this routine to
331 	 * exit (e.g. all threads call pthread_exit()), exactly one
332 	 * thread should return to the caller to terminate the process
333 	 * instead of the thread.
334 	 *
335 	 * Checking p_numthreads alone is not sufficient since threads
336 	 * might be committed to terminating while the PROC_LOCK is
337 	 * dropped in either ptracestop() or while removing this thread
338 	 * from the tidhash.  Instead, the p_pendingexits field holds
339 	 * the count of threads in either of those states and a thread
340 	 * is considered the "last" thread if all of the other threads
341 	 * in a process are already terminating.
342 	 */
343 	PROC_LOCK(p);
344 	if (p->p_numthreads == p->p_pendingexits + 1) {
345 		/*
346 		 * Ignore attempts to shut down last thread in the
347 		 * proc.  This will actually call _exit(2) in the
348 		 * usermode trampoline when it returns.
349 		 */
350 		PROC_UNLOCK(p);
351 		return (0);
352 	}
353 
354 	if (p->p_sysent->sv_ontdexit != NULL)
355 		p->p_sysent->sv_ontdexit(td);
356 
357 	td->td_dbgflags |= TDB_EXIT;
358 	if (p->p_ptevents & PTRACE_LWP) {
359 		p->p_pendingexits++;
360 		ptracestop(td, SIGTRAP, NULL);
361 		p->p_pendingexits--;
362 	}
363 	tidhash_remove(td);
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 
375 #ifdef AUDIT
376 	AUDIT_SYSCALL_EXIT(0, td);
377 #endif
378 
379 	PROC_SLOCK(p);
380 	thread_stopped(p);
381 	thread_exit();
382 	/* NOTREACHED */
383 }
384 
385 int
386 sys_thr_kill(struct thread *td, struct thr_kill_args *uap)
387     /* long id, int sig */
388 {
389 	ksiginfo_t ksi;
390 	struct thread *ttd;
391 	struct proc *p;
392 	int error;
393 
394 	p = td->td_proc;
395 	ksiginfo_init(&ksi);
396 	ksi.ksi_signo = uap->sig;
397 	ksi.ksi_code = SI_LWP;
398 	ksi.ksi_pid = p->p_pid;
399 	ksi.ksi_uid = td->td_ucred->cr_ruid;
400 	if (uap->id == -1) {
401 		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
402 			error = EINVAL;
403 		} else {
404 			error = ESRCH;
405 			PROC_LOCK(p);
406 			FOREACH_THREAD_IN_PROC(p, ttd) {
407 				if (ttd != td) {
408 					error = 0;
409 					if (uap->sig == 0)
410 						break;
411 					tdksignal(ttd, uap->sig, &ksi);
412 				}
413 			}
414 			PROC_UNLOCK(p);
415 		}
416 	} else {
417 		error = 0;
418 		ttd = tdfind((lwpid_t)uap->id, p->p_pid);
419 		if (ttd == NULL)
420 			return (ESRCH);
421 		if (uap->sig == 0)
422 			;
423 		else if (!_SIG_VALID(uap->sig))
424 			error = EINVAL;
425 		else
426 			tdksignal(ttd, uap->sig, &ksi);
427 		PROC_UNLOCK(ttd->td_proc);
428 	}
429 	return (error);
430 }
431 
432 int
433 sys_thr_kill2(struct thread *td, struct thr_kill2_args *uap)
434     /* pid_t pid, long id, int sig */
435 {
436 	ksiginfo_t ksi;
437 	struct thread *ttd;
438 	struct proc *p;
439 	int error;
440 
441 	AUDIT_ARG_SIGNUM(uap->sig);
442 
443 	ksiginfo_init(&ksi);
444 	ksi.ksi_signo = uap->sig;
445 	ksi.ksi_code = SI_LWP;
446 	ksi.ksi_pid = td->td_proc->p_pid;
447 	ksi.ksi_uid = td->td_ucred->cr_ruid;
448 	if (uap->id == -1) {
449 		if ((p = pfind(uap->pid)) == NULL)
450 			return (ESRCH);
451 		AUDIT_ARG_PROCESS(p);
452 		error = p_cansignal(td, p, uap->sig);
453 		if (error) {
454 			PROC_UNLOCK(p);
455 			return (error);
456 		}
457 		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
458 			error = EINVAL;
459 		} else {
460 			error = ESRCH;
461 			FOREACH_THREAD_IN_PROC(p, ttd) {
462 				if (ttd != td) {
463 					error = 0;
464 					if (uap->sig == 0)
465 						break;
466 					tdksignal(ttd, uap->sig, &ksi);
467 				}
468 			}
469 		}
470 		PROC_UNLOCK(p);
471 	} else {
472 		ttd = tdfind((lwpid_t)uap->id, uap->pid);
473 		if (ttd == NULL)
474 			return (ESRCH);
475 		p = ttd->td_proc;
476 		AUDIT_ARG_PROCESS(p);
477 		error = p_cansignal(td, p, uap->sig);
478 		if (uap->sig == 0)
479 			;
480 		else if (!_SIG_VALID(uap->sig))
481 			error = EINVAL;
482 		else
483 			tdksignal(ttd, uap->sig, &ksi);
484 		PROC_UNLOCK(p);
485 	}
486 	return (error);
487 }
488 
489 int
490 sys_thr_suspend(struct thread *td, struct thr_suspend_args *uap)
491 	/* const struct timespec *timeout */
492 {
493 	struct timespec ts, *tsp;
494 	int error;
495 
496 	tsp = NULL;
497 	if (uap->timeout != NULL) {
498 		error = umtx_copyin_timeout(uap->timeout, &ts);
499 		if (error != 0)
500 			return (error);
501 		tsp = &ts;
502 	}
503 
504 	return (kern_thr_suspend(td, tsp));
505 }
506 
507 int
508 kern_thr_suspend(struct thread *td, struct timespec *tsp)
509 {
510 	struct proc *p = td->td_proc;
511 	struct timeval tv;
512 	int error = 0;
513 	int timo = 0;
514 
515 	if (td->td_pflags & TDP_WAKEUP) {
516 		td->td_pflags &= ~TDP_WAKEUP;
517 		return (0);
518 	}
519 
520 	if (tsp != NULL) {
521 		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
522 			error = EWOULDBLOCK;
523 		else {
524 			TIMESPEC_TO_TIMEVAL(&tv, tsp);
525 			timo = tvtohz(&tv);
526 		}
527 	}
528 
529 	PROC_LOCK(p);
530 	if (error == 0 && (td->td_flags & TDF_THRWAKEUP) == 0)
531 		error = msleep((void *)td, &p->p_mtx,
532 			 PCATCH, "lthr", timo);
533 
534 	if (td->td_flags & TDF_THRWAKEUP) {
535 		thread_lock(td);
536 		td->td_flags &= ~TDF_THRWAKEUP;
537 		thread_unlock(td);
538 		PROC_UNLOCK(p);
539 		return (0);
540 	}
541 	PROC_UNLOCK(p);
542 	if (error == EWOULDBLOCK)
543 		error = ETIMEDOUT;
544 	else if (error == ERESTART) {
545 		if (timo != 0)
546 			error = EINTR;
547 	}
548 	return (error);
549 }
550 
551 int
552 sys_thr_wake(struct thread *td, struct thr_wake_args *uap)
553 	/* long id */
554 {
555 	struct proc *p;
556 	struct thread *ttd;
557 
558 	if (uap->id == td->td_tid) {
559 		td->td_pflags |= TDP_WAKEUP;
560 		return (0);
561 	}
562 
563 	p = td->td_proc;
564 	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
565 	if (ttd == NULL)
566 		return (ESRCH);
567 	thread_lock(ttd);
568 	ttd->td_flags |= TDF_THRWAKEUP;
569 	thread_unlock(ttd);
570 	wakeup((void *)ttd);
571 	PROC_UNLOCK(p);
572 	return (0);
573 }
574 
575 int
576 sys_thr_set_name(struct thread *td, struct thr_set_name_args *uap)
577 {
578 	struct proc *p;
579 	char name[MAXCOMLEN + 1];
580 	struct thread *ttd;
581 	int error;
582 
583 	error = 0;
584 	name[0] = '\0';
585 	if (uap->name != NULL) {
586 		error = copyinstr(uap->name, name, sizeof(name), NULL);
587 		if (error == ENAMETOOLONG) {
588 			error = copyin(uap->name, name, sizeof(name) - 1);
589 			name[sizeof(name) - 1] = '\0';
590 		}
591 		if (error)
592 			return (error);
593 	}
594 	p = td->td_proc;
595 	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
596 	if (ttd == NULL)
597 		return (ESRCH);
598 	strcpy(ttd->td_name, name);
599 #ifdef HWPMC_HOOKS
600 	if (PMC_PROC_IS_USING_PMCS(p) || PMC_SYSTEM_SAMPLING_ACTIVE())
601 		PMC_CALL_HOOK_UNLOCKED(ttd, PMC_FN_THR_CREATE_LOG, NULL);
602 #endif
603 #ifdef KTR
604 	sched_clear_tdname(ttd);
605 #endif
606 	PROC_UNLOCK(p);
607 	return (error);
608 }
609 
610 int
611 kern_thr_alloc(struct proc *p, int pages, struct thread **ntd)
612 {
613 
614 	/* Have race condition but it is cheap. */
615 	if (p->p_numthreads >= max_threads_per_proc) {
616 		++max_threads_hits;
617 		return (EPROCLIM);
618 	}
619 
620 	*ntd = thread_alloc(pages);
621 	if (*ntd == NULL)
622 		return (ENOMEM);
623 
624 	return (0);
625 }
626