xref: /freebsd/sys/kern/kern_thread.c (revision a4e5e0106ac7145f56eb39a691e302cabb4635be)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (C) 2001 Julian Elischer <julian@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(s), this list of conditions and the following disclaimer as
12  *    the first lines of this file unmodified other than the possible
13  *    addition of one or more copyright notices.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice(s), this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
28  * DAMAGE.
29  */
30 
31 #include "opt_witness.h"
32 #include "opt_hwpmc_hooks.h"
33 
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
37 #include <sys/lock.h>
38 #include <sys/msan.h>
39 #include <sys/mutex.h>
40 #include <sys/proc.h>
41 #include <sys/bitstring.h>
42 #include <sys/epoch.h>
43 #include <sys/rangelock.h>
44 #include <sys/resourcevar.h>
45 #include <sys/sdt.h>
46 #include <sys/smp.h>
47 #include <sys/sched.h>
48 #include <sys/sleepqueue.h>
49 #include <sys/selinfo.h>
50 #include <sys/syscallsubr.h>
51 #include <sys/dtrace_bsd.h>
52 #include <sys/sysent.h>
53 #include <sys/turnstile.h>
54 #include <sys/taskqueue.h>
55 #include <sys/ktr.h>
56 #include <sys/rwlock.h>
57 #include <sys/umtxvar.h>
58 #include <sys/vmmeter.h>
59 #include <sys/cpuset.h>
60 #ifdef	HWPMC_HOOKS
61 #include <sys/pmckern.h>
62 #endif
63 #include <sys/priv.h>
64 
65 #include <security/audit/audit.h>
66 
67 #include <vm/pmap.h>
68 #include <vm/vm.h>
69 #include <vm/vm_extern.h>
70 #include <vm/uma.h>
71 #include <vm/vm_phys.h>
72 #include <sys/eventhandler.h>
73 
74 /*
75  * Asserts below verify the stability of struct thread and struct proc
76  * layout, as exposed by KBI to modules.  On head, the KBI is allowed
77  * to drift, change to the structures must be accompanied by the
78  * assert update.
79  *
80  * On the stable branches after KBI freeze, conditions must not be
81  * violated.  Typically new fields are moved to the end of the
82  * structures.
83  */
84 #ifdef __amd64__
85 _Static_assert(offsetof(struct thread, td_flags) == 0x108,
86     "struct thread KBI td_flags");
87 _Static_assert(offsetof(struct thread, td_pflags) == 0x114,
88     "struct thread KBI td_pflags");
89 _Static_assert(offsetof(struct thread, td_frame) == 0x4b8,
90     "struct thread KBI td_frame");
91 _Static_assert(offsetof(struct thread, td_emuldata) == 0x6c0,
92     "struct thread KBI td_emuldata");
93 _Static_assert(offsetof(struct proc, p_flag) == 0xb8,
94     "struct proc KBI p_flag");
95 _Static_assert(offsetof(struct proc, p_pid) == 0xc4,
96     "struct proc KBI p_pid");
97 _Static_assert(offsetof(struct proc, p_filemon) == 0x3c8,
98     "struct proc KBI p_filemon");
99 _Static_assert(offsetof(struct proc, p_comm) == 0x3e0,
100     "struct proc KBI p_comm");
101 _Static_assert(offsetof(struct proc, p_emuldata) == 0x4d0,
102     "struct proc KBI p_emuldata");
103 #endif
104 #ifdef __i386__
105 _Static_assert(offsetof(struct thread, td_flags) == 0x9c,
106     "struct thread KBI td_flags");
107 _Static_assert(offsetof(struct thread, td_pflags) == 0xa8,
108     "struct thread KBI td_pflags");
109 _Static_assert(offsetof(struct thread, td_frame) == 0x318,
110     "struct thread KBI td_frame");
111 _Static_assert(offsetof(struct thread, td_emuldata) == 0x35c,
112     "struct thread KBI td_emuldata");
113 _Static_assert(offsetof(struct proc, p_flag) == 0x6c,
114     "struct proc KBI p_flag");
115 _Static_assert(offsetof(struct proc, p_pid) == 0x78,
116     "struct proc KBI p_pid");
117 _Static_assert(offsetof(struct proc, p_filemon) == 0x270,
118     "struct proc KBI p_filemon");
119 _Static_assert(offsetof(struct proc, p_comm) == 0x284,
120     "struct proc KBI p_comm");
121 _Static_assert(offsetof(struct proc, p_emuldata) == 0x318,
122     "struct proc KBI p_emuldata");
123 #endif
124 
125 SDT_PROVIDER_DECLARE(proc);
126 SDT_PROBE_DEFINE(proc, , , lwp__exit);
127 
128 /*
129  * thread related storage.
130  */
131 static uma_zone_t thread_zone;
132 
133 struct thread_domain_data {
134 	struct thread	*tdd_zombies;
135 	int		tdd_reapticks;
136 } __aligned(CACHE_LINE_SIZE);
137 
138 static struct thread_domain_data thread_domain_data[MAXMEMDOM];
139 
140 static struct task	thread_reap_task;
141 static struct callout  	thread_reap_callout;
142 
143 static void thread_zombie(struct thread *);
144 static void thread_reap(void);
145 static void thread_reap_all(void);
146 static void thread_reap_task_cb(void *, int);
147 static void thread_reap_callout_cb(void *);
148 static int thread_unsuspend_one(struct thread *td, struct proc *p,
149     bool boundary);
150 static void thread_free_batched(struct thread *td);
151 
152 static __exclusive_cache_line struct mtx tid_lock;
153 static bitstr_t *tid_bitmap;
154 
155 static MALLOC_DEFINE(M_TIDHASH, "tidhash", "thread hash");
156 
157 static int maxthread;
158 SYSCTL_INT(_kern, OID_AUTO, maxthread, CTLFLAG_RDTUN,
159     &maxthread, 0, "Maximum number of threads");
160 
161 static __exclusive_cache_line int nthreads;
162 
163 static LIST_HEAD(tidhashhead, thread) *tidhashtbl;
164 static u_long	tidhash;
165 static u_long	tidhashlock;
166 static struct	rwlock *tidhashtbl_lock;
167 #define	TIDHASH(tid)		(&tidhashtbl[(tid) & tidhash])
168 #define	TIDHASHLOCK(tid)	(&tidhashtbl_lock[(tid) & tidhashlock])
169 
170 EVENTHANDLER_LIST_DEFINE(thread_ctor);
171 EVENTHANDLER_LIST_DEFINE(thread_dtor);
172 EVENTHANDLER_LIST_DEFINE(thread_init);
173 EVENTHANDLER_LIST_DEFINE(thread_fini);
174 
175 static bool
176 thread_count_inc_try(void)
177 {
178 	int nthreads_new;
179 
180 	nthreads_new = atomic_fetchadd_int(&nthreads, 1) + 1;
181 	if (nthreads_new >= maxthread - 100) {
182 		if (priv_check_cred(curthread->td_ucred, PRIV_MAXPROC) != 0 ||
183 		    nthreads_new >= maxthread) {
184 			atomic_subtract_int(&nthreads, 1);
185 			return (false);
186 		}
187 	}
188 	return (true);
189 }
190 
191 static bool
192 thread_count_inc(void)
193 {
194 	static struct timeval lastfail;
195 	static int curfail;
196 
197 	thread_reap();
198 	if (thread_count_inc_try()) {
199 		return (true);
200 	}
201 
202 	thread_reap_all();
203 	if (thread_count_inc_try()) {
204 		return (true);
205 	}
206 
207 	if (ppsratecheck(&lastfail, &curfail, 1)) {
208 		printf("maxthread limit exceeded by uid %u "
209 		    "(pid %d); consider increasing kern.maxthread\n",
210 		    curthread->td_ucred->cr_ruid, curproc->p_pid);
211 	}
212 	return (false);
213 }
214 
215 static void
216 thread_count_sub(int n)
217 {
218 
219 	atomic_subtract_int(&nthreads, n);
220 }
221 
222 static void
223 thread_count_dec(void)
224 {
225 
226 	thread_count_sub(1);
227 }
228 
229 static lwpid_t
230 tid_alloc(void)
231 {
232 	static lwpid_t trytid;
233 	lwpid_t tid;
234 
235 	mtx_lock(&tid_lock);
236 	/*
237 	 * It is an invariant that the bitmap is big enough to hold maxthread
238 	 * IDs. If we got to this point there has to be at least one free.
239 	 */
240 	if (trytid >= maxthread)
241 		trytid = 0;
242 	bit_ffc_at(tid_bitmap, trytid, maxthread, &tid);
243 	if (tid == -1) {
244 		KASSERT(trytid != 0, ("unexpectedly ran out of IDs"));
245 		trytid = 0;
246 		bit_ffc_at(tid_bitmap, trytid, maxthread, &tid);
247 		KASSERT(tid != -1, ("unexpectedly ran out of IDs"));
248 	}
249 	bit_set(tid_bitmap, tid);
250 	trytid = tid + 1;
251 	mtx_unlock(&tid_lock);
252 	return (tid + NO_PID);
253 }
254 
255 static void
256 tid_free_locked(lwpid_t rtid)
257 {
258 	lwpid_t tid;
259 
260 	mtx_assert(&tid_lock, MA_OWNED);
261 	KASSERT(rtid >= NO_PID,
262 	    ("%s: invalid tid %d\n", __func__, rtid));
263 	tid = rtid - NO_PID;
264 	KASSERT(bit_test(tid_bitmap, tid) != 0,
265 	    ("thread ID %d not allocated\n", rtid));
266 	bit_clear(tid_bitmap, tid);
267 }
268 
269 static void
270 tid_free(lwpid_t rtid)
271 {
272 
273 	mtx_lock(&tid_lock);
274 	tid_free_locked(rtid);
275 	mtx_unlock(&tid_lock);
276 }
277 
278 static void
279 tid_free_batch(lwpid_t *batch, int n)
280 {
281 	int i;
282 
283 	mtx_lock(&tid_lock);
284 	for (i = 0; i < n; i++) {
285 		tid_free_locked(batch[i]);
286 	}
287 	mtx_unlock(&tid_lock);
288 }
289 
290 /*
291  * Batching for thread reapping.
292  */
293 struct tidbatch {
294 	lwpid_t tab[16];
295 	int n;
296 };
297 
298 static void
299 tidbatch_prep(struct tidbatch *tb)
300 {
301 
302 	tb->n = 0;
303 }
304 
305 static void
306 tidbatch_add(struct tidbatch *tb, struct thread *td)
307 {
308 
309 	KASSERT(tb->n < nitems(tb->tab),
310 	    ("%s: count too high %d", __func__, tb->n));
311 	tb->tab[tb->n] = td->td_tid;
312 	tb->n++;
313 }
314 
315 static void
316 tidbatch_process(struct tidbatch *tb)
317 {
318 
319 	KASSERT(tb->n <= nitems(tb->tab),
320 	    ("%s: count too high %d", __func__, tb->n));
321 	if (tb->n == nitems(tb->tab)) {
322 		tid_free_batch(tb->tab, tb->n);
323 		tb->n = 0;
324 	}
325 }
326 
327 static void
328 tidbatch_final(struct tidbatch *tb)
329 {
330 
331 	KASSERT(tb->n <= nitems(tb->tab),
332 	    ("%s: count too high %d", __func__, tb->n));
333 	if (tb->n != 0) {
334 		tid_free_batch(tb->tab, tb->n);
335 	}
336 }
337 
338 /*
339  * Batching thread count free, for consistency
340  */
341 struct tdcountbatch {
342 	int n;
343 };
344 
345 static void
346 tdcountbatch_prep(struct tdcountbatch *tb)
347 {
348 
349 	tb->n = 0;
350 }
351 
352 static void
353 tdcountbatch_add(struct tdcountbatch *tb, struct thread *td __unused)
354 {
355 
356 	tb->n++;
357 }
358 
359 static void
360 tdcountbatch_process(struct tdcountbatch *tb)
361 {
362 
363 	if (tb->n == 32) {
364 		thread_count_sub(tb->n);
365 		tb->n = 0;
366 	}
367 }
368 
369 static void
370 tdcountbatch_final(struct tdcountbatch *tb)
371 {
372 
373 	if (tb->n != 0) {
374 		thread_count_sub(tb->n);
375 	}
376 }
377 
378 /*
379  * Prepare a thread for use.
380  */
381 static int
382 thread_ctor(void *mem, int size, void *arg, int flags)
383 {
384 	struct thread	*td;
385 
386 	td = (struct thread *)mem;
387 	TD_SET_STATE(td, TDS_INACTIVE);
388 	td->td_lastcpu = td->td_oncpu = NOCPU;
389 
390 	/*
391 	 * Note that td_critnest begins life as 1 because the thread is not
392 	 * running and is thereby implicitly waiting to be on the receiving
393 	 * end of a context switch.
394 	 */
395 	td->td_critnest = 1;
396 	td->td_lend_user_pri = PRI_MAX;
397 #ifdef AUDIT
398 	audit_thread_alloc(td);
399 #endif
400 #ifdef KDTRACE_HOOKS
401 	kdtrace_thread_ctor(td);
402 #endif
403 	umtx_thread_alloc(td);
404 	MPASS(td->td_sel == NULL);
405 	return (0);
406 }
407 
408 /*
409  * Reclaim a thread after use.
410  */
411 static void
412 thread_dtor(void *mem, int size, void *arg)
413 {
414 	struct thread *td;
415 
416 	td = (struct thread *)mem;
417 
418 #ifdef INVARIANTS
419 	/* Verify that this thread is in a safe state to free. */
420 	switch (TD_GET_STATE(td)) {
421 	case TDS_INHIBITED:
422 	case TDS_RUNNING:
423 	case TDS_CAN_RUN:
424 	case TDS_RUNQ:
425 		/*
426 		 * We must never unlink a thread that is in one of
427 		 * these states, because it is currently active.
428 		 */
429 		panic("bad state for thread unlinking");
430 		/* NOTREACHED */
431 	case TDS_INACTIVE:
432 		break;
433 	default:
434 		panic("bad thread state");
435 		/* NOTREACHED */
436 	}
437 #endif
438 #ifdef AUDIT
439 	audit_thread_free(td);
440 #endif
441 #ifdef KDTRACE_HOOKS
442 	kdtrace_thread_dtor(td);
443 #endif
444 	/* Free all OSD associated to this thread. */
445 	osd_thread_exit(td);
446 	ast_kclear(td);
447 	seltdfini(td);
448 }
449 
450 /*
451  * Initialize type-stable parts of a thread (when newly created).
452  */
453 static int
454 thread_init(void *mem, int size, int flags)
455 {
456 	struct thread *td;
457 
458 	td = (struct thread *)mem;
459 
460 	td->td_allocdomain = vm_phys_domain(vtophys(td));
461 	td->td_sleepqueue = sleepq_alloc();
462 	td->td_turnstile = turnstile_alloc();
463 	td->td_rlqe = NULL;
464 	EVENTHANDLER_DIRECT_INVOKE(thread_init, td);
465 	umtx_thread_init(td);
466 	td->td_kstack = 0;
467 	td->td_sel = NULL;
468 	return (0);
469 }
470 
471 /*
472  * Tear down type-stable parts of a thread (just before being discarded).
473  */
474 static void
475 thread_fini(void *mem, int size)
476 {
477 	struct thread *td;
478 
479 	td = (struct thread *)mem;
480 	EVENTHANDLER_DIRECT_INVOKE(thread_fini, td);
481 	rlqentry_free(td->td_rlqe);
482 	turnstile_free(td->td_turnstile);
483 	sleepq_free(td->td_sleepqueue);
484 	umtx_thread_fini(td);
485 	MPASS(td->td_sel == NULL);
486 }
487 
488 /*
489  * For a newly created process,
490  * link up all the structures and its initial threads etc.
491  * called from:
492  * {arch}/{arch}/machdep.c   {arch}_init(), init386() etc.
493  * proc_dtor() (should go away)
494  * proc_init()
495  */
496 void
497 proc_linkup0(struct proc *p, struct thread *td)
498 {
499 	TAILQ_INIT(&p->p_threads);	     /* all threads in proc */
500 	proc_linkup(p, td);
501 }
502 
503 void
504 proc_linkup(struct proc *p, struct thread *td)
505 {
506 
507 	sigqueue_init(&p->p_sigqueue, p);
508 	p->p_ksi = ksiginfo_alloc(M_WAITOK);
509 	if (p->p_ksi != NULL) {
510 		/* XXX p_ksi may be null if ksiginfo zone is not ready */
511 		p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
512 	}
513 	LIST_INIT(&p->p_mqnotifier);
514 	p->p_numthreads = 0;
515 	thread_link(td, p);
516 }
517 
518 static void
519 ast_suspend(struct thread *td, int tda __unused)
520 {
521 	struct proc *p;
522 
523 	p = td->td_proc;
524 	/*
525 	 * We need to check to see if we have to exit or wait due to a
526 	 * single threading requirement or some other STOP condition.
527 	 */
528 	PROC_LOCK(p);
529 	thread_suspend_check(0);
530 	PROC_UNLOCK(p);
531 }
532 
533 extern int max_threads_per_proc;
534 
535 /*
536  * Initialize global thread allocation resources.
537  */
538 void
539 threadinit(void)
540 {
541 	u_long i;
542 	lwpid_t tid0;
543 
544 	/*
545 	 * Place an upper limit on threads which can be allocated.
546 	 *
547 	 * Note that other factors may make the de facto limit much lower.
548 	 *
549 	 * Platform limits are somewhat arbitrary but deemed "more than good
550 	 * enough" for the foreseable future.
551 	 */
552 	if (maxthread == 0) {
553 #ifdef _LP64
554 		maxthread = MIN(maxproc * max_threads_per_proc, 1000000);
555 #else
556 		maxthread = MIN(maxproc * max_threads_per_proc, 100000);
557 #endif
558 	}
559 
560 	mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
561 	tid_bitmap = bit_alloc(maxthread, M_TIDHASH, M_WAITOK);
562 	/*
563 	 * Handle thread0.
564 	 */
565 	thread_count_inc();
566 	tid0 = tid_alloc();
567 	if (tid0 != THREAD0_TID)
568 		panic("tid0 %d != %d\n", tid0, THREAD0_TID);
569 
570 	/*
571 	 * Thread structures are specially aligned so that (at least) the
572 	 * 5 lower bits of a pointer to 'struct thead' must be 0.  These bits
573 	 * are used by synchronization primitives to store flags in pointers to
574 	 * such structures.
575 	 */
576 	thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
577 	    thread_ctor, thread_dtor, thread_init, thread_fini,
578 	    UMA_ALIGN_CACHE_AND_MASK(32 - 1), UMA_ZONE_NOFREE);
579 	tidhashtbl = hashinit(maxproc / 2, M_TIDHASH, &tidhash);
580 	tidhashlock = (tidhash + 1) / 64;
581 	if (tidhashlock > 0)
582 		tidhashlock--;
583 	tidhashtbl_lock = malloc(sizeof(*tidhashtbl_lock) * (tidhashlock + 1),
584 	    M_TIDHASH, M_WAITOK | M_ZERO);
585 	for (i = 0; i < tidhashlock + 1; i++)
586 		rw_init(&tidhashtbl_lock[i], "tidhash");
587 
588 	TASK_INIT(&thread_reap_task, 0, thread_reap_task_cb, NULL);
589 	callout_init(&thread_reap_callout, 1);
590 	callout_reset(&thread_reap_callout, 5 * hz,
591 	    thread_reap_callout_cb, NULL);
592 	ast_register(TDA_SUSPEND, ASTR_ASTF_REQUIRED, 0, ast_suspend);
593 }
594 
595 /*
596  * Place an unused thread on the zombie list.
597  */
598 void
599 thread_zombie(struct thread *td)
600 {
601 	struct thread_domain_data *tdd;
602 	struct thread *ztd;
603 
604 	tdd = &thread_domain_data[td->td_allocdomain];
605 	ztd = atomic_load_ptr(&tdd->tdd_zombies);
606 	for (;;) {
607 		td->td_zombie = ztd;
608 		if (atomic_fcmpset_rel_ptr((uintptr_t *)&tdd->tdd_zombies,
609 		    (uintptr_t *)&ztd, (uintptr_t)td))
610 			break;
611 		continue;
612 	}
613 }
614 
615 /*
616  * Release a thread that has exited after cpu_throw().
617  */
618 void
619 thread_stash(struct thread *td)
620 {
621 	atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
622 	thread_zombie(td);
623 }
624 
625 /*
626  * Reap zombies from passed domain.
627  */
628 static void
629 thread_reap_domain(struct thread_domain_data *tdd)
630 {
631 	struct thread *itd, *ntd;
632 	struct tidbatch tidbatch;
633 	struct credbatch credbatch;
634 	struct limbatch limbatch;
635 	struct tdcountbatch tdcountbatch;
636 
637 	/*
638 	 * Reading upfront is pessimal if followed by concurrent atomic_swap,
639 	 * but most of the time the list is empty.
640 	 */
641 	if (tdd->tdd_zombies == NULL)
642 		return;
643 
644 	itd = (struct thread *)atomic_swap_ptr((uintptr_t *)&tdd->tdd_zombies,
645 	    (uintptr_t)NULL);
646 	if (itd == NULL)
647 		return;
648 
649 	/*
650 	 * Multiple CPUs can get here, the race is fine as ticks is only
651 	 * advisory.
652 	 */
653 	tdd->tdd_reapticks = ticks;
654 
655 	tidbatch_prep(&tidbatch);
656 	credbatch_prep(&credbatch);
657 	limbatch_prep(&limbatch);
658 	tdcountbatch_prep(&tdcountbatch);
659 
660 	while (itd != NULL) {
661 		ntd = itd->td_zombie;
662 		EVENTHANDLER_DIRECT_INVOKE(thread_dtor, itd);
663 
664 		tidbatch_add(&tidbatch, itd);
665 		credbatch_add(&credbatch, itd);
666 		limbatch_add(&limbatch, itd);
667 		tdcountbatch_add(&tdcountbatch, itd);
668 
669 		thread_free_batched(itd);
670 
671 		tidbatch_process(&tidbatch);
672 		credbatch_process(&credbatch);
673 		limbatch_process(&limbatch);
674 		tdcountbatch_process(&tdcountbatch);
675 
676 		itd = ntd;
677 	}
678 
679 	tidbatch_final(&tidbatch);
680 	credbatch_final(&credbatch);
681 	limbatch_final(&limbatch);
682 	tdcountbatch_final(&tdcountbatch);
683 }
684 
685 /*
686  * Reap zombies from all domains.
687  */
688 static void
689 thread_reap_all(void)
690 {
691 	struct thread_domain_data *tdd;
692 	int i, domain;
693 
694 	domain = PCPU_GET(domain);
695 	for (i = 0; i < vm_ndomains; i++) {
696 		tdd = &thread_domain_data[(i + domain) % vm_ndomains];
697 		thread_reap_domain(tdd);
698 	}
699 }
700 
701 /*
702  * Reap zombies from local domain.
703  */
704 static void
705 thread_reap(void)
706 {
707 	struct thread_domain_data *tdd;
708 	int domain;
709 
710 	domain = PCPU_GET(domain);
711 	tdd = &thread_domain_data[domain];
712 
713 	thread_reap_domain(tdd);
714 }
715 
716 static void
717 thread_reap_task_cb(void *arg __unused, int pending __unused)
718 {
719 
720 	thread_reap_all();
721 }
722 
723 static void
724 thread_reap_callout_cb(void *arg __unused)
725 {
726 	struct thread_domain_data *tdd;
727 	int i, cticks, lticks;
728 	bool wantreap;
729 
730 	wantreap = false;
731 	cticks = atomic_load_int(&ticks);
732 	for (i = 0; i < vm_ndomains; i++) {
733 		tdd = &thread_domain_data[i];
734 		lticks = tdd->tdd_reapticks;
735 		if (tdd->tdd_zombies != NULL &&
736 		    (u_int)(cticks - lticks) > 5 * hz) {
737 			wantreap = true;
738 			break;
739 		}
740 	}
741 
742 	if (wantreap)
743 		taskqueue_enqueue(taskqueue_thread, &thread_reap_task);
744 	callout_reset(&thread_reap_callout, 5 * hz,
745 	    thread_reap_callout_cb, NULL);
746 }
747 
748 /*
749  * Calling this function guarantees that any thread that exited before
750  * the call is reaped when the function returns.  By 'exited' we mean
751  * a thread removed from the process linkage with thread_unlink().
752  * Practically this means that caller must lock/unlock corresponding
753  * process lock before the call, to synchronize with thread_exit().
754  */
755 void
756 thread_reap_barrier(void)
757 {
758 	struct task *t;
759 
760 	/*
761 	 * First do context switches to each CPU to ensure that all
762 	 * PCPU pc_deadthreads are moved to zombie list.
763 	 */
764 	quiesce_all_cpus("", PDROP);
765 
766 	/*
767 	 * Second, fire the task in the same thread as normal
768 	 * thread_reap() is done, to serialize reaping.
769 	 */
770 	t = malloc(sizeof(*t), M_TEMP, M_WAITOK);
771 	TASK_INIT(t, 0, thread_reap_task_cb, t);
772 	taskqueue_enqueue(taskqueue_thread, t);
773 	taskqueue_drain(taskqueue_thread, t);
774 	free(t, M_TEMP);
775 }
776 
777 /*
778  * Allocate a thread.
779  */
780 struct thread *
781 thread_alloc(int pages)
782 {
783 	struct thread *td;
784 	lwpid_t tid;
785 
786 	if (!thread_count_inc()) {
787 		return (NULL);
788 	}
789 
790 	tid = tid_alloc();
791 	td = uma_zalloc(thread_zone, M_WAITOK);
792 	KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
793 	if (!vm_thread_new(td, pages)) {
794 		uma_zfree(thread_zone, td);
795 		tid_free(tid);
796 		thread_count_dec();
797 		return (NULL);
798 	}
799 	td->td_tid = tid;
800 	bzero(&td->td_sa.args, sizeof(td->td_sa.args));
801 	kmsan_thread_alloc(td);
802 	cpu_thread_alloc(td);
803 	EVENTHANDLER_DIRECT_INVOKE(thread_ctor, td);
804 	return (td);
805 }
806 
807 int
808 thread_alloc_stack(struct thread *td, int pages)
809 {
810 
811 	KASSERT(td->td_kstack == 0,
812 	    ("thread_alloc_stack called on a thread with kstack"));
813 	if (!vm_thread_new(td, pages))
814 		return (0);
815 	cpu_thread_alloc(td);
816 	return (1);
817 }
818 
819 /*
820  * Deallocate a thread.
821  */
822 static void
823 thread_free_batched(struct thread *td)
824 {
825 
826 	lock_profile_thread_exit(td);
827 	if (td->td_cpuset)
828 		cpuset_rel(td->td_cpuset);
829 	td->td_cpuset = NULL;
830 	cpu_thread_free(td);
831 	if (td->td_kstack != 0)
832 		vm_thread_dispose(td);
833 	callout_drain(&td->td_slpcallout);
834 	/*
835 	 * Freeing handled by the caller.
836 	 */
837 	td->td_tid = -1;
838 	kmsan_thread_free(td);
839 	uma_zfree(thread_zone, td);
840 }
841 
842 void
843 thread_free(struct thread *td)
844 {
845 	lwpid_t tid;
846 
847 	EVENTHANDLER_DIRECT_INVOKE(thread_dtor, td);
848 	tid = td->td_tid;
849 	thread_free_batched(td);
850 	tid_free(tid);
851 	thread_count_dec();
852 }
853 
854 void
855 thread_cow_get_proc(struct thread *newtd, struct proc *p)
856 {
857 
858 	PROC_LOCK_ASSERT(p, MA_OWNED);
859 	newtd->td_realucred = crcowget(p->p_ucred);
860 	newtd->td_ucred = newtd->td_realucred;
861 	newtd->td_limit = lim_hold(p->p_limit);
862 	newtd->td_cowgen = p->p_cowgen;
863 }
864 
865 void
866 thread_cow_get(struct thread *newtd, struct thread *td)
867 {
868 
869 	MPASS(td->td_realucred == td->td_ucred);
870 	newtd->td_realucred = crcowget(td->td_realucred);
871 	newtd->td_ucred = newtd->td_realucred;
872 	newtd->td_limit = lim_hold(td->td_limit);
873 	newtd->td_cowgen = td->td_cowgen;
874 }
875 
876 void
877 thread_cow_free(struct thread *td)
878 {
879 
880 	if (td->td_realucred != NULL)
881 		crcowfree(td);
882 	if (td->td_limit != NULL)
883 		lim_free(td->td_limit);
884 }
885 
886 void
887 thread_cow_update(struct thread *td)
888 {
889 	struct proc *p;
890 	struct ucred *oldcred;
891 	struct plimit *oldlimit;
892 
893 	p = td->td_proc;
894 	PROC_LOCK(p);
895 	oldcred = crcowsync();
896 	oldlimit = lim_cowsync();
897 	td->td_cowgen = p->p_cowgen;
898 	PROC_UNLOCK(p);
899 	if (oldcred != NULL)
900 		crfree(oldcred);
901 	if (oldlimit != NULL)
902 		lim_free(oldlimit);
903 }
904 
905 void
906 thread_cow_synced(struct thread *td)
907 {
908 	struct proc *p;
909 
910 	p = td->td_proc;
911 	PROC_LOCK_ASSERT(p, MA_OWNED);
912 	MPASS(td->td_cowgen != p->p_cowgen);
913 	MPASS(td->td_ucred == p->p_ucred);
914 	MPASS(td->td_limit == p->p_limit);
915 	td->td_cowgen = p->p_cowgen;
916 }
917 
918 /*
919  * Discard the current thread and exit from its context.
920  * Always called with scheduler locked.
921  *
922  * Because we can't free a thread while we're operating under its context,
923  * push the current thread into our CPU's deadthread holder. This means
924  * we needn't worry about someone else grabbing our context before we
925  * do a cpu_throw().
926  */
927 void
928 thread_exit(void)
929 {
930 	uint64_t runtime, new_switchtime;
931 	struct thread *td;
932 	struct thread *td2;
933 	struct proc *p;
934 	int wakeup_swapper;
935 
936 	td = curthread;
937 	p = td->td_proc;
938 
939 	PROC_SLOCK_ASSERT(p, MA_OWNED);
940 	mtx_assert(&Giant, MA_NOTOWNED);
941 
942 	PROC_LOCK_ASSERT(p, MA_OWNED);
943 	KASSERT(p != NULL, ("thread exiting without a process"));
944 	CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
945 	    (long)p->p_pid, td->td_name);
946 	SDT_PROBE0(proc, , , lwp__exit);
947 	KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
948 	MPASS(td->td_realucred == td->td_ucred);
949 
950 	/*
951 	 * drop FPU & debug register state storage, or any other
952 	 * architecture specific resources that
953 	 * would not be on a new untouched process.
954 	 */
955 	cpu_thread_exit(td);
956 
957 	/*
958 	 * The last thread is left attached to the process
959 	 * So that the whole bundle gets recycled. Skip
960 	 * all this stuff if we never had threads.
961 	 * EXIT clears all sign of other threads when
962 	 * it goes to single threading, so the last thread always
963 	 * takes the short path.
964 	 */
965 	if (p->p_flag & P_HADTHREADS) {
966 		if (p->p_numthreads > 1) {
967 			atomic_add_int(&td->td_proc->p_exitthreads, 1);
968 			thread_unlink(td);
969 			td2 = FIRST_THREAD_IN_PROC(p);
970 			sched_exit_thread(td2, td);
971 
972 			/*
973 			 * The test below is NOT true if we are the
974 			 * sole exiting thread. P_STOPPED_SINGLE is unset
975 			 * in exit1() after it is the only survivor.
976 			 */
977 			if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
978 				if (p->p_numthreads == p->p_suspcount) {
979 					thread_lock(p->p_singlethread);
980 					wakeup_swapper = thread_unsuspend_one(
981 						p->p_singlethread, p, false);
982 					if (wakeup_swapper)
983 						kick_proc0();
984 				}
985 			}
986 
987 			PCPU_SET(deadthread, td);
988 		} else {
989 			/*
990 			 * The last thread is exiting.. but not through exit()
991 			 */
992 			panic ("thread_exit: Last thread exiting on its own");
993 		}
994 	}
995 #ifdef	HWPMC_HOOKS
996 	/*
997 	 * If this thread is part of a process that is being tracked by hwpmc(4),
998 	 * inform the module of the thread's impending exit.
999 	 */
1000 	if (PMC_PROC_IS_USING_PMCS(td->td_proc)) {
1001 		PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1002 		PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT, NULL);
1003 	} else if (PMC_SYSTEM_SAMPLING_ACTIVE())
1004 		PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT_LOG, NULL);
1005 #endif
1006 	PROC_UNLOCK(p);
1007 	PROC_STATLOCK(p);
1008 	thread_lock(td);
1009 	PROC_SUNLOCK(p);
1010 
1011 	/* Do the same timestamp bookkeeping that mi_switch() would do. */
1012 	new_switchtime = cpu_ticks();
1013 	runtime = new_switchtime - PCPU_GET(switchtime);
1014 	td->td_runtime += runtime;
1015 	td->td_incruntime += runtime;
1016 	PCPU_SET(switchtime, new_switchtime);
1017 	PCPU_SET(switchticks, ticks);
1018 	VM_CNT_INC(v_swtch);
1019 
1020 	/* Save our resource usage in our process. */
1021 	td->td_ru.ru_nvcsw++;
1022 	ruxagg_locked(p, td);
1023 	rucollect(&p->p_ru, &td->td_ru);
1024 	PROC_STATUNLOCK(p);
1025 
1026 	TD_SET_STATE(td, TDS_INACTIVE);
1027 #ifdef WITNESS
1028 	witness_thread_exit(td);
1029 #endif
1030 	CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
1031 	sched_throw(td);
1032 	panic("I'm a teapot!");
1033 	/* NOTREACHED */
1034 }
1035 
1036 /*
1037  * Do any thread specific cleanups that may be needed in wait()
1038  * called with Giant, proc and schedlock not held.
1039  */
1040 void
1041 thread_wait(struct proc *p)
1042 {
1043 	struct thread *td;
1044 
1045 	mtx_assert(&Giant, MA_NOTOWNED);
1046 	KASSERT(p->p_numthreads == 1, ("multiple threads in thread_wait()"));
1047 	KASSERT(p->p_exitthreads == 0, ("p_exitthreads leaking"));
1048 	td = FIRST_THREAD_IN_PROC(p);
1049 	/* Lock the last thread so we spin until it exits cpu_throw(). */
1050 	thread_lock(td);
1051 	thread_unlock(td);
1052 	lock_profile_thread_exit(td);
1053 	cpuset_rel(td->td_cpuset);
1054 	td->td_cpuset = NULL;
1055 	cpu_thread_clean(td);
1056 	thread_cow_free(td);
1057 	callout_drain(&td->td_slpcallout);
1058 	thread_reap();	/* check for zombie threads etc. */
1059 }
1060 
1061 /*
1062  * Link a thread to a process.
1063  * set up anything that needs to be initialized for it to
1064  * be used by the process.
1065  */
1066 void
1067 thread_link(struct thread *td, struct proc *p)
1068 {
1069 
1070 	/*
1071 	 * XXX This can't be enabled because it's called for proc0 before
1072 	 * its lock has been created.
1073 	 * PROC_LOCK_ASSERT(p, MA_OWNED);
1074 	 */
1075 	TD_SET_STATE(td, TDS_INACTIVE);
1076 	td->td_proc     = p;
1077 	td->td_flags    = TDF_INMEM;
1078 
1079 	LIST_INIT(&td->td_contested);
1080 	LIST_INIT(&td->td_lprof[0]);
1081 	LIST_INIT(&td->td_lprof[1]);
1082 #ifdef EPOCH_TRACE
1083 	SLIST_INIT(&td->td_epochs);
1084 #endif
1085 	sigqueue_init(&td->td_sigqueue, p);
1086 	callout_init(&td->td_slpcallout, 1);
1087 	TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
1088 	p->p_numthreads++;
1089 }
1090 
1091 /*
1092  * Called from:
1093  *  thread_exit()
1094  */
1095 void
1096 thread_unlink(struct thread *td)
1097 {
1098 	struct proc *p = td->td_proc;
1099 
1100 	PROC_LOCK_ASSERT(p, MA_OWNED);
1101 #ifdef EPOCH_TRACE
1102 	MPASS(SLIST_EMPTY(&td->td_epochs));
1103 #endif
1104 
1105 	TAILQ_REMOVE(&p->p_threads, td, td_plist);
1106 	p->p_numthreads--;
1107 	/* could clear a few other things here */
1108 	/* Must  NOT clear links to proc! */
1109 }
1110 
1111 static int
1112 calc_remaining(struct proc *p, int mode)
1113 {
1114 	int remaining;
1115 
1116 	PROC_LOCK_ASSERT(p, MA_OWNED);
1117 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1118 	if (mode == SINGLE_EXIT)
1119 		remaining = p->p_numthreads;
1120 	else if (mode == SINGLE_BOUNDARY)
1121 		remaining = p->p_numthreads - p->p_boundary_count;
1122 	else if (mode == SINGLE_NO_EXIT || mode == SINGLE_ALLPROC)
1123 		remaining = p->p_numthreads - p->p_suspcount;
1124 	else
1125 		panic("calc_remaining: wrong mode %d", mode);
1126 	return (remaining);
1127 }
1128 
1129 static int
1130 remain_for_mode(int mode)
1131 {
1132 
1133 	return (mode == SINGLE_ALLPROC ? 0 : 1);
1134 }
1135 
1136 static int
1137 weed_inhib(int mode, struct thread *td2, struct proc *p)
1138 {
1139 	int wakeup_swapper;
1140 
1141 	PROC_LOCK_ASSERT(p, MA_OWNED);
1142 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1143 	THREAD_LOCK_ASSERT(td2, MA_OWNED);
1144 
1145 	wakeup_swapper = 0;
1146 
1147 	/*
1148 	 * Since the thread lock is dropped by the scheduler we have
1149 	 * to retry to check for races.
1150 	 */
1151 restart:
1152 	switch (mode) {
1153 	case SINGLE_EXIT:
1154 		if (TD_IS_SUSPENDED(td2)) {
1155 			wakeup_swapper |= thread_unsuspend_one(td2, p, true);
1156 			thread_lock(td2);
1157 			goto restart;
1158 		}
1159 		if (TD_CAN_ABORT(td2)) {
1160 			wakeup_swapper |= sleepq_abort(td2, EINTR);
1161 			return (wakeup_swapper);
1162 		}
1163 		break;
1164 	case SINGLE_BOUNDARY:
1165 	case SINGLE_NO_EXIT:
1166 		if (TD_IS_SUSPENDED(td2) &&
1167 		    (td2->td_flags & TDF_BOUNDARY) == 0) {
1168 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
1169 			thread_lock(td2);
1170 			goto restart;
1171 		}
1172 		if (TD_CAN_ABORT(td2)) {
1173 			wakeup_swapper |= sleepq_abort(td2, ERESTART);
1174 			return (wakeup_swapper);
1175 		}
1176 		break;
1177 	case SINGLE_ALLPROC:
1178 		/*
1179 		 * ALLPROC suspend tries to avoid spurious EINTR for
1180 		 * threads sleeping interruptable, by suspending the
1181 		 * thread directly, similarly to sig_suspend_threads().
1182 		 * Since such sleep is not neccessary performed at the user
1183 		 * boundary, TDF_ALLPROCSUSP is used to avoid immediate
1184 		 * un-suspend.
1185 		 */
1186 		if (TD_IS_SUSPENDED(td2) &&
1187 		    (td2->td_flags & TDF_ALLPROCSUSP) == 0) {
1188 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
1189 			thread_lock(td2);
1190 			goto restart;
1191 		}
1192 		if (TD_CAN_ABORT(td2)) {
1193 			td2->td_flags |= TDF_ALLPROCSUSP;
1194 			wakeup_swapper |= sleepq_abort(td2, ERESTART);
1195 			return (wakeup_swapper);
1196 		}
1197 		break;
1198 	default:
1199 		break;
1200 	}
1201 	thread_unlock(td2);
1202 	return (wakeup_swapper);
1203 }
1204 
1205 /*
1206  * Enforce single-threading.
1207  *
1208  * Returns 1 if the caller must abort (another thread is waiting to
1209  * exit the process or similar). Process is locked!
1210  * Returns 0 when you are successfully the only thread running.
1211  * A process has successfully single threaded in the suspend mode when
1212  * There are no threads in user mode. Threads in the kernel must be
1213  * allowed to continue until they get to the user boundary. They may even
1214  * copy out their return values and data before suspending. They may however be
1215  * accelerated in reaching the user boundary as we will wake up
1216  * any sleeping threads that are interruptable. (PCATCH).
1217  */
1218 int
1219 thread_single(struct proc *p, int mode)
1220 {
1221 	struct thread *td;
1222 	struct thread *td2;
1223 	int remaining, wakeup_swapper;
1224 
1225 	td = curthread;
1226 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
1227 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
1228 	    ("invalid mode %d", mode));
1229 	/*
1230 	 * If allowing non-ALLPROC singlethreading for non-curproc
1231 	 * callers, calc_remaining() and remain_for_mode() should be
1232 	 * adjusted to also account for td->td_proc != p.  For now
1233 	 * this is not implemented because it is not used.
1234 	 */
1235 	KASSERT((mode == SINGLE_ALLPROC && td->td_proc != p) ||
1236 	    (mode != SINGLE_ALLPROC && td->td_proc == p),
1237 	    ("mode %d proc %p curproc %p", mode, p, td->td_proc));
1238 	mtx_assert(&Giant, MA_NOTOWNED);
1239 	PROC_LOCK_ASSERT(p, MA_OWNED);
1240 
1241 	/*
1242 	 * Is someone already single threading?
1243 	 * Or may be singlethreading is not needed at all.
1244 	 */
1245 	if (mode == SINGLE_ALLPROC) {
1246 		while ((p->p_flag & P_STOPPED_SINGLE) != 0) {
1247 			if ((p->p_flag2 & P2_WEXIT) != 0)
1248 				return (1);
1249 			msleep(&p->p_flag, &p->p_mtx, PCATCH, "thrsgl", 0);
1250 		}
1251 	} else if ((p->p_flag & P_HADTHREADS) == 0)
1252 		return (0);
1253 	if (p->p_singlethread != NULL && p->p_singlethread != td)
1254 		return (1);
1255 
1256 	if (mode == SINGLE_EXIT) {
1257 		p->p_flag |= P_SINGLE_EXIT;
1258 		p->p_flag &= ~P_SINGLE_BOUNDARY;
1259 	} else {
1260 		p->p_flag &= ~P_SINGLE_EXIT;
1261 		if (mode == SINGLE_BOUNDARY)
1262 			p->p_flag |= P_SINGLE_BOUNDARY;
1263 		else
1264 			p->p_flag &= ~P_SINGLE_BOUNDARY;
1265 	}
1266 	if (mode == SINGLE_ALLPROC)
1267 		p->p_flag |= P_TOTAL_STOP;
1268 	p->p_flag |= P_STOPPED_SINGLE;
1269 	PROC_SLOCK(p);
1270 	p->p_singlethread = td;
1271 	remaining = calc_remaining(p, mode);
1272 	while (remaining != remain_for_mode(mode)) {
1273 		if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
1274 			goto stopme;
1275 		wakeup_swapper = 0;
1276 		FOREACH_THREAD_IN_PROC(p, td2) {
1277 			if (td2 == td)
1278 				continue;
1279 			thread_lock(td2);
1280 			ast_sched_locked(td2, TDA_SUSPEND);
1281 			if (TD_IS_INHIBITED(td2)) {
1282 				wakeup_swapper |= weed_inhib(mode, td2, p);
1283 #ifdef SMP
1284 			} else if (TD_IS_RUNNING(td2)) {
1285 				forward_signal(td2);
1286 				thread_unlock(td2);
1287 #endif
1288 			} else
1289 				thread_unlock(td2);
1290 		}
1291 		if (wakeup_swapper)
1292 			kick_proc0();
1293 		remaining = calc_remaining(p, mode);
1294 
1295 		/*
1296 		 * Maybe we suspended some threads.. was it enough?
1297 		 */
1298 		if (remaining == remain_for_mode(mode))
1299 			break;
1300 
1301 stopme:
1302 		/*
1303 		 * Wake us up when everyone else has suspended.
1304 		 * In the mean time we suspend as well.
1305 		 */
1306 		thread_suspend_switch(td, p);
1307 		remaining = calc_remaining(p, mode);
1308 	}
1309 	if (mode == SINGLE_EXIT) {
1310 		/*
1311 		 * Convert the process to an unthreaded process.  The
1312 		 * SINGLE_EXIT is called by exit1() or execve(), in
1313 		 * both cases other threads must be retired.
1314 		 */
1315 		KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
1316 		p->p_singlethread = NULL;
1317 		p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
1318 
1319 		/*
1320 		 * Wait for any remaining threads to exit cpu_throw().
1321 		 */
1322 		while (p->p_exitthreads != 0) {
1323 			PROC_SUNLOCK(p);
1324 			PROC_UNLOCK(p);
1325 			sched_relinquish(td);
1326 			PROC_LOCK(p);
1327 			PROC_SLOCK(p);
1328 		}
1329 	} else if (mode == SINGLE_BOUNDARY) {
1330 		/*
1331 		 * Wait until all suspended threads are removed from
1332 		 * the processors.  The thread_suspend_check()
1333 		 * increments p_boundary_count while it is still
1334 		 * running, which makes it possible for the execve()
1335 		 * to destroy vmspace while our other threads are
1336 		 * still using the address space.
1337 		 *
1338 		 * We lock the thread, which is only allowed to
1339 		 * succeed after context switch code finished using
1340 		 * the address space.
1341 		 */
1342 		FOREACH_THREAD_IN_PROC(p, td2) {
1343 			if (td2 == td)
1344 				continue;
1345 			thread_lock(td2);
1346 			KASSERT((td2->td_flags & TDF_BOUNDARY) != 0,
1347 			    ("td %p not on boundary", td2));
1348 			KASSERT(TD_IS_SUSPENDED(td2),
1349 			    ("td %p is not suspended", td2));
1350 			thread_unlock(td2);
1351 		}
1352 	}
1353 	PROC_SUNLOCK(p);
1354 	return (0);
1355 }
1356 
1357 bool
1358 thread_suspend_check_needed(void)
1359 {
1360 	struct proc *p;
1361 	struct thread *td;
1362 
1363 	td = curthread;
1364 	p = td->td_proc;
1365 	PROC_LOCK_ASSERT(p, MA_OWNED);
1366 	return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
1367 	    (td->td_dbgflags & TDB_SUSPEND) != 0));
1368 }
1369 
1370 /*
1371  * Called in from locations that can safely check to see
1372  * whether we have to suspend or at least throttle for a
1373  * single-thread event (e.g. fork).
1374  *
1375  * Such locations include userret().
1376  * If the "return_instead" argument is non zero, the thread must be able to
1377  * accept 0 (caller may continue), or 1 (caller must abort) as a result.
1378  *
1379  * The 'return_instead' argument tells the function if it may do a
1380  * thread_exit() or suspend, or whether the caller must abort and back
1381  * out instead.
1382  *
1383  * If the thread that set the single_threading request has set the
1384  * P_SINGLE_EXIT bit in the process flags then this call will never return
1385  * if 'return_instead' is false, but will exit.
1386  *
1387  * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
1388  *---------------+--------------------+---------------------
1389  *       0       | returns 0          |   returns 0 or 1
1390  *               | when ST ends       |   immediately
1391  *---------------+--------------------+---------------------
1392  *       1       | thread exits       |   returns 1
1393  *               |                    |  immediately
1394  * 0 = thread_exit() or suspension ok,
1395  * other = return error instead of stopping the thread.
1396  *
1397  * While a full suspension is under effect, even a single threading
1398  * thread would be suspended if it made this call (but it shouldn't).
1399  * This call should only be made from places where
1400  * thread_exit() would be safe as that may be the outcome unless
1401  * return_instead is set.
1402  */
1403 int
1404 thread_suspend_check(int return_instead)
1405 {
1406 	struct thread *td;
1407 	struct proc *p;
1408 	int wakeup_swapper;
1409 
1410 	td = curthread;
1411 	p = td->td_proc;
1412 	mtx_assert(&Giant, MA_NOTOWNED);
1413 	PROC_LOCK_ASSERT(p, MA_OWNED);
1414 	while (thread_suspend_check_needed()) {
1415 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1416 			KASSERT(p->p_singlethread != NULL,
1417 			    ("singlethread not set"));
1418 			/*
1419 			 * The only suspension in action is a
1420 			 * single-threading. Single threader need not stop.
1421 			 * It is safe to access p->p_singlethread unlocked
1422 			 * because it can only be set to our address by us.
1423 			 */
1424 			if (p->p_singlethread == td)
1425 				return (0);	/* Exempt from stopping. */
1426 		}
1427 		if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
1428 			return (EINTR);
1429 
1430 		/* Should we goto user boundary if we didn't come from there? */
1431 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1432 		    (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
1433 			return (ERESTART);
1434 
1435 		/*
1436 		 * Ignore suspend requests if they are deferred.
1437 		 */
1438 		if ((td->td_flags & TDF_SBDRY) != 0) {
1439 			KASSERT(return_instead,
1440 			    ("TDF_SBDRY set for unsafe thread_suspend_check"));
1441 			KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
1442 			    (TDF_SEINTR | TDF_SERESTART),
1443 			    ("both TDF_SEINTR and TDF_SERESTART"));
1444 			return (TD_SBDRY_INTR(td) ? TD_SBDRY_ERRNO(td) : 0);
1445 		}
1446 
1447 		/*
1448 		 * If the process is waiting for us to exit,
1449 		 * this thread should just suicide.
1450 		 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
1451 		 */
1452 		if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
1453 			PROC_UNLOCK(p);
1454 
1455 			/*
1456 			 * Allow Linux emulation layer to do some work
1457 			 * before thread suicide.
1458 			 */
1459 			if (__predict_false(p->p_sysent->sv_thread_detach != NULL))
1460 				(p->p_sysent->sv_thread_detach)(td);
1461 			umtx_thread_exit(td);
1462 			kern_thr_exit(td);
1463 			panic("stopped thread did not exit");
1464 		}
1465 
1466 		PROC_SLOCK(p);
1467 		thread_stopped(p);
1468 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1469 			if (p->p_numthreads == p->p_suspcount + 1) {
1470 				thread_lock(p->p_singlethread);
1471 				wakeup_swapper = thread_unsuspend_one(
1472 				    p->p_singlethread, p, false);
1473 				if (wakeup_swapper)
1474 					kick_proc0();
1475 			}
1476 		}
1477 		PROC_UNLOCK(p);
1478 		thread_lock(td);
1479 		/*
1480 		 * When a thread suspends, it just
1481 		 * gets taken off all queues.
1482 		 */
1483 		thread_suspend_one(td);
1484 		if (return_instead == 0) {
1485 			p->p_boundary_count++;
1486 			td->td_flags |= TDF_BOUNDARY;
1487 		}
1488 		PROC_SUNLOCK(p);
1489 		mi_switch(SW_INVOL | SWT_SUSPEND);
1490 		PROC_LOCK(p);
1491 	}
1492 	return (0);
1493 }
1494 
1495 /*
1496  * Check for possible stops and suspensions while executing a
1497  * casueword or similar transiently failing operation.
1498  *
1499  * The sleep argument controls whether the function can handle a stop
1500  * request itself or it should return ERESTART and the request is
1501  * proceed at the kernel/user boundary in ast.
1502  *
1503  * Typically, when retrying due to casueword(9) failure (rv == 1), we
1504  * should handle the stop requests there, with exception of cases when
1505  * the thread owns a kernel resource, for instance busied the umtx
1506  * key, or when functions return immediately if thread_check_susp()
1507  * returned non-zero.  On the other hand, retrying the whole lock
1508  * operation, we better not stop there but delegate the handling to
1509  * ast.
1510  *
1511  * If the request is for thread termination P_SINGLE_EXIT, we cannot
1512  * handle it at all, and simply return EINTR.
1513  */
1514 int
1515 thread_check_susp(struct thread *td, bool sleep)
1516 {
1517 	struct proc *p;
1518 	int error;
1519 
1520 	/*
1521 	 * The check for TDA_SUSPEND is racy, but it is enough to
1522 	 * eventually break the lockstep loop.
1523 	 */
1524 	if (!td_ast_pending(td, TDA_SUSPEND))
1525 		return (0);
1526 	error = 0;
1527 	p = td->td_proc;
1528 	PROC_LOCK(p);
1529 	if (p->p_flag & P_SINGLE_EXIT)
1530 		error = EINTR;
1531 	else if (P_SHOULDSTOP(p) ||
1532 	    ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_SUSPEND)))
1533 		error = sleep ? thread_suspend_check(0) : ERESTART;
1534 	PROC_UNLOCK(p);
1535 	return (error);
1536 }
1537 
1538 void
1539 thread_suspend_switch(struct thread *td, struct proc *p)
1540 {
1541 
1542 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1543 	PROC_LOCK_ASSERT(p, MA_OWNED);
1544 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1545 	/*
1546 	 * We implement thread_suspend_one in stages here to avoid
1547 	 * dropping the proc lock while the thread lock is owned.
1548 	 */
1549 	if (p == td->td_proc) {
1550 		thread_stopped(p);
1551 		p->p_suspcount++;
1552 	}
1553 	PROC_UNLOCK(p);
1554 	thread_lock(td);
1555 	ast_unsched_locked(td, TDA_SUSPEND);
1556 	TD_SET_SUSPENDED(td);
1557 	sched_sleep(td, 0);
1558 	PROC_SUNLOCK(p);
1559 	DROP_GIANT();
1560 	mi_switch(SW_VOL | SWT_SUSPEND);
1561 	PICKUP_GIANT();
1562 	PROC_LOCK(p);
1563 	PROC_SLOCK(p);
1564 }
1565 
1566 void
1567 thread_suspend_one(struct thread *td)
1568 {
1569 	struct proc *p;
1570 
1571 	p = td->td_proc;
1572 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1573 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1574 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1575 	p->p_suspcount++;
1576 	ast_unsched_locked(td, TDA_SUSPEND);
1577 	TD_SET_SUSPENDED(td);
1578 	sched_sleep(td, 0);
1579 }
1580 
1581 static int
1582 thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
1583 {
1584 
1585 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1586 	KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
1587 	TD_CLR_SUSPENDED(td);
1588 	td->td_flags &= ~TDF_ALLPROCSUSP;
1589 	if (td->td_proc == p) {
1590 		PROC_SLOCK_ASSERT(p, MA_OWNED);
1591 		p->p_suspcount--;
1592 		if (boundary && (td->td_flags & TDF_BOUNDARY) != 0) {
1593 			td->td_flags &= ~TDF_BOUNDARY;
1594 			p->p_boundary_count--;
1595 		}
1596 	}
1597 	return (setrunnable(td, 0));
1598 }
1599 
1600 void
1601 thread_run_flash(struct thread *td)
1602 {
1603 	struct proc *p;
1604 
1605 	p = td->td_proc;
1606 	PROC_LOCK_ASSERT(p, MA_OWNED);
1607 
1608 	if (TD_ON_SLEEPQ(td))
1609 		sleepq_remove_nested(td);
1610 	else
1611 		thread_lock(td);
1612 
1613 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1614 	KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
1615 
1616 	TD_CLR_SUSPENDED(td);
1617 	PROC_SLOCK(p);
1618 	MPASS(p->p_suspcount > 0);
1619 	p->p_suspcount--;
1620 	PROC_SUNLOCK(p);
1621 	if (setrunnable(td, 0))
1622 		kick_proc0();
1623 }
1624 
1625 /*
1626  * Allow all threads blocked by single threading to continue running.
1627  */
1628 void
1629 thread_unsuspend(struct proc *p)
1630 {
1631 	struct thread *td;
1632 	int wakeup_swapper;
1633 
1634 	PROC_LOCK_ASSERT(p, MA_OWNED);
1635 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1636 	wakeup_swapper = 0;
1637 	if (!P_SHOULDSTOP(p)) {
1638                 FOREACH_THREAD_IN_PROC(p, td) {
1639 			thread_lock(td);
1640 			if (TD_IS_SUSPENDED(td))
1641 				wakeup_swapper |= thread_unsuspend_one(td, p,
1642 				    true);
1643 			else
1644 				thread_unlock(td);
1645 		}
1646 	} else if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1647 	    p->p_numthreads == p->p_suspcount) {
1648 		/*
1649 		 * Stopping everything also did the job for the single
1650 		 * threading request. Now we've downgraded to single-threaded,
1651 		 * let it continue.
1652 		 */
1653 		if (p->p_singlethread->td_proc == p) {
1654 			thread_lock(p->p_singlethread);
1655 			wakeup_swapper = thread_unsuspend_one(
1656 			    p->p_singlethread, p, false);
1657 		}
1658 	}
1659 	if (wakeup_swapper)
1660 		kick_proc0();
1661 }
1662 
1663 /*
1664  * End the single threading mode..
1665  */
1666 void
1667 thread_single_end(struct proc *p, int mode)
1668 {
1669 	struct thread *td;
1670 	int wakeup_swapper;
1671 
1672 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
1673 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
1674 	    ("invalid mode %d", mode));
1675 	PROC_LOCK_ASSERT(p, MA_OWNED);
1676 	KASSERT((mode == SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) != 0) ||
1677 	    (mode != SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) == 0),
1678 	    ("mode %d does not match P_TOTAL_STOP", mode));
1679 	KASSERT(mode == SINGLE_ALLPROC || p->p_singlethread == curthread,
1680 	    ("thread_single_end from other thread %p %p",
1681 	    curthread, p->p_singlethread));
1682 	KASSERT(mode != SINGLE_BOUNDARY ||
1683 	    (p->p_flag & P_SINGLE_BOUNDARY) != 0,
1684 	    ("mis-matched SINGLE_BOUNDARY flags %x", p->p_flag));
1685 	p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY |
1686 	    P_TOTAL_STOP);
1687 	PROC_SLOCK(p);
1688 	p->p_singlethread = NULL;
1689 	wakeup_swapper = 0;
1690 	/*
1691 	 * If there are other threads they may now run,
1692 	 * unless of course there is a blanket 'stop order'
1693 	 * on the process. The single threader must be allowed
1694 	 * to continue however as this is a bad place to stop.
1695 	 */
1696 	if (p->p_numthreads != remain_for_mode(mode) && !P_SHOULDSTOP(p)) {
1697                 FOREACH_THREAD_IN_PROC(p, td) {
1698 			thread_lock(td);
1699 			if (TD_IS_SUSPENDED(td)) {
1700 				wakeup_swapper |= thread_unsuspend_one(td, p,
1701 				    true);
1702 			} else
1703 				thread_unlock(td);
1704 		}
1705 	}
1706 	KASSERT(mode != SINGLE_BOUNDARY || p->p_boundary_count == 0,
1707 	    ("inconsistent boundary count %d", p->p_boundary_count));
1708 	PROC_SUNLOCK(p);
1709 	if (wakeup_swapper)
1710 		kick_proc0();
1711 	wakeup(&p->p_flag);
1712 }
1713 
1714 /*
1715  * Locate a thread by number and return with proc lock held.
1716  *
1717  * thread exit establishes proc -> tidhash lock ordering, but lookup
1718  * takes tidhash first and needs to return locked proc.
1719  *
1720  * The problem is worked around by relying on type-safety of both
1721  * structures and doing the work in 2 steps:
1722  * - tidhash-locked lookup which saves both thread and proc pointers
1723  * - proc-locked verification that the found thread still matches
1724  */
1725 static bool
1726 tdfind_hash(lwpid_t tid, pid_t pid, struct proc **pp, struct thread **tdp)
1727 {
1728 #define RUN_THRESH	16
1729 	struct proc *p;
1730 	struct thread *td;
1731 	int run;
1732 	bool locked;
1733 
1734 	run = 0;
1735 	rw_rlock(TIDHASHLOCK(tid));
1736 	locked = true;
1737 	LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1738 		if (td->td_tid != tid) {
1739 			run++;
1740 			continue;
1741 		}
1742 		p = td->td_proc;
1743 		if (pid != -1 && p->p_pid != pid) {
1744 			td = NULL;
1745 			break;
1746 		}
1747 		if (run > RUN_THRESH) {
1748 			if (rw_try_upgrade(TIDHASHLOCK(tid))) {
1749 				LIST_REMOVE(td, td_hash);
1750 				LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1751 					td, td_hash);
1752 				rw_wunlock(TIDHASHLOCK(tid));
1753 				locked = false;
1754 				break;
1755 			}
1756 		}
1757 		break;
1758 	}
1759 	if (locked)
1760 		rw_runlock(TIDHASHLOCK(tid));
1761 	if (td == NULL)
1762 		return (false);
1763 	*pp = p;
1764 	*tdp = td;
1765 	return (true);
1766 }
1767 
1768 struct thread *
1769 tdfind(lwpid_t tid, pid_t pid)
1770 {
1771 	struct proc *p;
1772 	struct thread *td;
1773 
1774 	td = curthread;
1775 	if (td->td_tid == tid) {
1776 		if (pid != -1 && td->td_proc->p_pid != pid)
1777 			return (NULL);
1778 		PROC_LOCK(td->td_proc);
1779 		return (td);
1780 	}
1781 
1782 	for (;;) {
1783 		if (!tdfind_hash(tid, pid, &p, &td))
1784 			return (NULL);
1785 		PROC_LOCK(p);
1786 		if (td->td_tid != tid) {
1787 			PROC_UNLOCK(p);
1788 			continue;
1789 		}
1790 		if (td->td_proc != p) {
1791 			PROC_UNLOCK(p);
1792 			continue;
1793 		}
1794 		if (p->p_state == PRS_NEW) {
1795 			PROC_UNLOCK(p);
1796 			return (NULL);
1797 		}
1798 		return (td);
1799 	}
1800 }
1801 
1802 void
1803 tidhash_add(struct thread *td)
1804 {
1805 	rw_wlock(TIDHASHLOCK(td->td_tid));
1806 	LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1807 	rw_wunlock(TIDHASHLOCK(td->td_tid));
1808 }
1809 
1810 void
1811 tidhash_remove(struct thread *td)
1812 {
1813 
1814 	rw_wlock(TIDHASHLOCK(td->td_tid));
1815 	LIST_REMOVE(td, td_hash);
1816 	rw_wunlock(TIDHASHLOCK(td->td_tid));
1817 }
1818