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