xref: /freebsd/sys/kern/kern_thread.c (revision d7d962ead0b6e5e8a39202d0590022082bf5bfb6)
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) == 0x110,
91     "struct thread KBI td_pflags");
92 _Static_assert(offsetof(struct thread, td_frame) == 0x4a8,
93     "struct thread KBI td_frame");
94 _Static_assert(offsetof(struct thread, td_emuldata) == 0x6b0,
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) == 0x3b8,
101     "struct proc KBI p_filemon");
102 _Static_assert(offsetof(struct proc, p_comm) == 0x3d0,
103     "struct proc KBI p_comm");
104 _Static_assert(offsetof(struct proc, p_emuldata) == 0x4b8,
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) == 0xa4,
111     "struct thread KBI td_pflags");
112 _Static_assert(offsetof(struct thread, td_frame) == 0x308,
113     "struct thread KBI td_frame");
114 _Static_assert(offsetof(struct thread, td_emuldata) == 0x34c,
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) == 0x268,
121     "struct proc KBI p_filemon");
122 _Static_assert(offsetof(struct proc, p_comm) == 0x27c,
123     "struct proc KBI p_comm");
124 _Static_assert(offsetof(struct proc, p_emuldata) == 0x308,
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 	td_softdep_cleanup(td);
410 	MPASS(td->td_su == NULL);
411 	seltdfini(td);
412 }
413 
414 /*
415  * Initialize type-stable parts of a thread (when newly created).
416  */
417 static int
418 thread_init(void *mem, int size, int flags)
419 {
420 	struct thread *td;
421 
422 	td = (struct thread *)mem;
423 
424 	td->td_allocdomain = vm_phys_domain(vtophys(td));
425 	td->td_sleepqueue = sleepq_alloc();
426 	td->td_turnstile = turnstile_alloc();
427 	td->td_rlqe = NULL;
428 	EVENTHANDLER_DIRECT_INVOKE(thread_init, td);
429 	umtx_thread_init(td);
430 	td->td_kstack = 0;
431 	td->td_sel = NULL;
432 	return (0);
433 }
434 
435 /*
436  * Tear down type-stable parts of a thread (just before being discarded).
437  */
438 static void
439 thread_fini(void *mem, int size)
440 {
441 	struct thread *td;
442 
443 	td = (struct thread *)mem;
444 	EVENTHANDLER_DIRECT_INVOKE(thread_fini, td);
445 	rlqentry_free(td->td_rlqe);
446 	turnstile_free(td->td_turnstile);
447 	sleepq_free(td->td_sleepqueue);
448 	umtx_thread_fini(td);
449 	MPASS(td->td_sel == NULL);
450 }
451 
452 /*
453  * For a newly created process,
454  * link up all the structures and its initial threads etc.
455  * called from:
456  * {arch}/{arch}/machdep.c   {arch}_init(), init386() etc.
457  * proc_dtor() (should go away)
458  * proc_init()
459  */
460 void
461 proc_linkup0(struct proc *p, struct thread *td)
462 {
463 	TAILQ_INIT(&p->p_threads);	     /* all threads in proc */
464 	proc_linkup(p, td);
465 }
466 
467 void
468 proc_linkup(struct proc *p, struct thread *td)
469 {
470 
471 	sigqueue_init(&p->p_sigqueue, p);
472 	p->p_ksi = ksiginfo_alloc(1);
473 	if (p->p_ksi != NULL) {
474 		/* XXX p_ksi may be null if ksiginfo zone is not ready */
475 		p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
476 	}
477 	LIST_INIT(&p->p_mqnotifier);
478 	p->p_numthreads = 0;
479 	thread_link(td, p);
480 }
481 
482 extern int max_threads_per_proc;
483 
484 /*
485  * Initialize global thread allocation resources.
486  */
487 void
488 threadinit(void)
489 {
490 	u_long i;
491 	lwpid_t tid0;
492 	uint32_t flags;
493 
494 	/*
495 	 * Place an upper limit on threads which can be allocated.
496 	 *
497 	 * Note that other factors may make the de facto limit much lower.
498 	 *
499 	 * Platform limits are somewhat arbitrary but deemed "more than good
500 	 * enough" for the foreseable future.
501 	 */
502 	if (maxthread == 0) {
503 #ifdef _LP64
504 		maxthread = MIN(maxproc * max_threads_per_proc, 1000000);
505 #else
506 		maxthread = MIN(maxproc * max_threads_per_proc, 100000);
507 #endif
508 	}
509 
510 	mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
511 	tid_bitmap = bit_alloc(maxthread, M_TIDHASH, M_WAITOK);
512 	/*
513 	 * Handle thread0.
514 	 */
515 	thread_count_inc();
516 	tid0 = tid_alloc();
517 	if (tid0 != THREAD0_TID)
518 		panic("tid0 %d != %d\n", tid0, THREAD0_TID);
519 
520 	flags = UMA_ZONE_NOFREE;
521 #ifdef __aarch64__
522 	/*
523 	 * Force thread structures to be allocated from the direct map.
524 	 * Otherwise, superpage promotions and demotions may temporarily
525 	 * invalidate thread structure mappings.  For most dynamically allocated
526 	 * structures this is not a problem, but translation faults cannot be
527 	 * handled without accessing curthread.
528 	 */
529 	flags |= UMA_ZONE_CONTIG;
530 #endif
531 	thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
532 	    thread_ctor, thread_dtor, thread_init, thread_fini,
533 	    32 - 1, flags);
534 	tidhashtbl = hashinit(maxproc / 2, M_TIDHASH, &tidhash);
535 	tidhashlock = (tidhash + 1) / 64;
536 	if (tidhashlock > 0)
537 		tidhashlock--;
538 	tidhashtbl_lock = malloc(sizeof(*tidhashtbl_lock) * (tidhashlock + 1),
539 	    M_TIDHASH, M_WAITOK | M_ZERO);
540 	for (i = 0; i < tidhashlock + 1; i++)
541 		rw_init(&tidhashtbl_lock[i], "tidhash");
542 
543 	TASK_INIT(&thread_reap_task, 0, thread_reap_task_cb, NULL);
544 	callout_init(&thread_reap_callout, 1);
545 	callout_reset(&thread_reap_callout, 5 * hz,
546 	    thread_reap_callout_cb, NULL);
547 }
548 
549 /*
550  * Place an unused thread on the zombie list.
551  */
552 void
553 thread_zombie(struct thread *td)
554 {
555 	struct thread_domain_data *tdd;
556 	struct thread *ztd;
557 
558 	tdd = &thread_domain_data[td->td_allocdomain];
559 	ztd = atomic_load_ptr(&tdd->tdd_zombies);
560 	for (;;) {
561 		td->td_zombie = ztd;
562 		if (atomic_fcmpset_rel_ptr((uintptr_t *)&tdd->tdd_zombies,
563 		    (uintptr_t *)&ztd, (uintptr_t)td))
564 			break;
565 		continue;
566 	}
567 }
568 
569 /*
570  * Release a thread that has exited after cpu_throw().
571  */
572 void
573 thread_stash(struct thread *td)
574 {
575 	atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
576 	thread_zombie(td);
577 }
578 
579 /*
580  * Reap zombies from passed domain.
581  */
582 static void
583 thread_reap_domain(struct thread_domain_data *tdd)
584 {
585 	struct thread *itd, *ntd;
586 	struct tidbatch tidbatch;
587 	struct credbatch credbatch;
588 	int tdcount;
589 	struct plimit *lim;
590 	int limcount;
591 
592 	/*
593 	 * Reading upfront is pessimal if followed by concurrent atomic_swap,
594 	 * but most of the time the list is empty.
595 	 */
596 	if (tdd->tdd_zombies == NULL)
597 		return;
598 
599 	itd = (struct thread *)atomic_swap_ptr((uintptr_t *)&tdd->tdd_zombies,
600 	    (uintptr_t)NULL);
601 	if (itd == NULL)
602 		return;
603 
604 	/*
605 	 * Multiple CPUs can get here, the race is fine as ticks is only
606 	 * advisory.
607 	 */
608 	tdd->tdd_reapticks = ticks;
609 
610 	tidbatch_prep(&tidbatch);
611 	credbatch_prep(&credbatch);
612 	tdcount = 0;
613 	lim = NULL;
614 	limcount = 0;
615 
616 	while (itd != NULL) {
617 		ntd = itd->td_zombie;
618 		EVENTHANDLER_DIRECT_INVOKE(thread_dtor, itd);
619 		tidbatch_add(&tidbatch, itd);
620 		credbatch_add(&credbatch, itd);
621 		MPASS(itd->td_limit != NULL);
622 		if (lim != itd->td_limit) {
623 			if (limcount != 0) {
624 				lim_freen(lim, limcount);
625 				limcount = 0;
626 			}
627 		}
628 		lim = itd->td_limit;
629 		limcount++;
630 		thread_free_batched(itd);
631 		tidbatch_process(&tidbatch);
632 		credbatch_process(&credbatch);
633 		tdcount++;
634 		if (tdcount == 32) {
635 			thread_count_sub(tdcount);
636 			tdcount = 0;
637 		}
638 		itd = ntd;
639 	}
640 
641 	tidbatch_final(&tidbatch);
642 	credbatch_final(&credbatch);
643 	if (tdcount != 0) {
644 		thread_count_sub(tdcount);
645 	}
646 	MPASS(limcount != 0);
647 	lim_freen(lim, limcount);
648 }
649 
650 /*
651  * Reap zombies from all domains.
652  */
653 static void
654 thread_reap_all(void)
655 {
656 	struct thread_domain_data *tdd;
657 	int i, domain;
658 
659 	domain = PCPU_GET(domain);
660 	for (i = 0; i < vm_ndomains; i++) {
661 		tdd = &thread_domain_data[(i + domain) % vm_ndomains];
662 		thread_reap_domain(tdd);
663 	}
664 }
665 
666 /*
667  * Reap zombies from local domain.
668  */
669 static void
670 thread_reap(void)
671 {
672 	struct thread_domain_data *tdd;
673 	int domain;
674 
675 	domain = PCPU_GET(domain);
676 	tdd = &thread_domain_data[domain];
677 
678 	thread_reap_domain(tdd);
679 }
680 
681 static void
682 thread_reap_task_cb(void *arg __unused, int pending __unused)
683 {
684 
685 	thread_reap_all();
686 }
687 
688 static void
689 thread_reap_callout_cb(void *arg __unused)
690 {
691 	struct thread_domain_data *tdd;
692 	int i, cticks, lticks;
693 	bool wantreap;
694 
695 	wantreap = false;
696 	cticks = atomic_load_int(&ticks);
697 	for (i = 0; i < vm_ndomains; i++) {
698 		tdd = &thread_domain_data[i];
699 		lticks = tdd->tdd_reapticks;
700 		if (tdd->tdd_zombies != NULL &&
701 		    (u_int)(cticks - lticks) > 5 * hz) {
702 			wantreap = true;
703 			break;
704 		}
705 	}
706 
707 	if (wantreap)
708 		taskqueue_enqueue(taskqueue_thread, &thread_reap_task);
709 	callout_reset(&thread_reap_callout, 5 * hz,
710 	    thread_reap_callout_cb, NULL);
711 }
712 
713 /*
714  * Calling this function guarantees that any thread that exited before
715  * the call is reaped when the function returns.  By 'exited' we mean
716  * a thread removed from the process linkage with thread_unlink().
717  * Practically this means that caller must lock/unlock corresponding
718  * process lock before the call, to synchronize with thread_exit().
719  */
720 void
721 thread_reap_barrier(void)
722 {
723 	struct task *t;
724 
725 	/*
726 	 * First do context switches to each CPU to ensure that all
727 	 * PCPU pc_deadthreads are moved to zombie list.
728 	 */
729 	quiesce_all_cpus("", PDROP);
730 
731 	/*
732 	 * Second, fire the task in the same thread as normal
733 	 * thread_reap() is done, to serialize reaping.
734 	 */
735 	t = malloc(sizeof(*t), M_TEMP, M_WAITOK);
736 	TASK_INIT(t, 0, thread_reap_task_cb, t);
737 	taskqueue_enqueue(taskqueue_thread, t);
738 	taskqueue_drain(taskqueue_thread, t);
739 	free(t, M_TEMP);
740 }
741 
742 /*
743  * Allocate a thread.
744  */
745 struct thread *
746 thread_alloc(int pages)
747 {
748 	struct thread *td;
749 	lwpid_t tid;
750 
751 	if (!thread_count_inc()) {
752 		return (NULL);
753 	}
754 
755 	tid = tid_alloc();
756 	td = uma_zalloc(thread_zone, M_WAITOK);
757 	KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
758 	if (!vm_thread_new(td, pages)) {
759 		uma_zfree(thread_zone, td);
760 		tid_free(tid);
761 		thread_count_dec();
762 		return (NULL);
763 	}
764 	td->td_tid = tid;
765 	kmsan_thread_alloc(td);
766 	cpu_thread_alloc(td);
767 	EVENTHANDLER_DIRECT_INVOKE(thread_ctor, td);
768 	return (td);
769 }
770 
771 int
772 thread_alloc_stack(struct thread *td, int pages)
773 {
774 
775 	KASSERT(td->td_kstack == 0,
776 	    ("thread_alloc_stack called on a thread with kstack"));
777 	if (!vm_thread_new(td, pages))
778 		return (0);
779 	cpu_thread_alloc(td);
780 	return (1);
781 }
782 
783 /*
784  * Deallocate a thread.
785  */
786 static void
787 thread_free_batched(struct thread *td)
788 {
789 
790 	lock_profile_thread_exit(td);
791 	if (td->td_cpuset)
792 		cpuset_rel(td->td_cpuset);
793 	td->td_cpuset = NULL;
794 	cpu_thread_free(td);
795 	if (td->td_kstack != 0)
796 		vm_thread_dispose(td);
797 	callout_drain(&td->td_slpcallout);
798 	/*
799 	 * Freeing handled by the caller.
800 	 */
801 	td->td_tid = -1;
802 	kmsan_thread_free(td);
803 	uma_zfree(thread_zone, td);
804 }
805 
806 void
807 thread_free(struct thread *td)
808 {
809 	lwpid_t tid;
810 
811 	EVENTHANDLER_DIRECT_INVOKE(thread_dtor, td);
812 	tid = td->td_tid;
813 	thread_free_batched(td);
814 	tid_free(tid);
815 	thread_count_dec();
816 }
817 
818 void
819 thread_cow_get_proc(struct thread *newtd, struct proc *p)
820 {
821 
822 	PROC_LOCK_ASSERT(p, MA_OWNED);
823 	newtd->td_realucred = crcowget(p->p_ucred);
824 	newtd->td_ucred = newtd->td_realucred;
825 	newtd->td_limit = lim_hold(p->p_limit);
826 	newtd->td_cowgen = p->p_cowgen;
827 }
828 
829 void
830 thread_cow_get(struct thread *newtd, struct thread *td)
831 {
832 
833 	MPASS(td->td_realucred == td->td_ucred);
834 	newtd->td_realucred = crcowget(td->td_realucred);
835 	newtd->td_ucred = newtd->td_realucred;
836 	newtd->td_limit = lim_hold(td->td_limit);
837 	newtd->td_cowgen = td->td_cowgen;
838 }
839 
840 void
841 thread_cow_free(struct thread *td)
842 {
843 
844 	if (td->td_realucred != NULL)
845 		crcowfree(td);
846 	if (td->td_limit != NULL)
847 		lim_free(td->td_limit);
848 }
849 
850 void
851 thread_cow_update(struct thread *td)
852 {
853 	struct proc *p;
854 	struct ucred *oldcred;
855 	struct plimit *oldlimit;
856 
857 	p = td->td_proc;
858 	oldlimit = NULL;
859 	PROC_LOCK(p);
860 	oldcred = crcowsync();
861 	if (td->td_limit != p->p_limit) {
862 		oldlimit = td->td_limit;
863 		td->td_limit = lim_hold(p->p_limit);
864 	}
865 	td->td_cowgen = p->p_cowgen;
866 	PROC_UNLOCK(p);
867 	if (oldcred != NULL)
868 		crfree(oldcred);
869 	if (oldlimit != NULL)
870 		lim_free(oldlimit);
871 }
872 
873 /*
874  * Discard the current thread and exit from its context.
875  * Always called with scheduler locked.
876  *
877  * Because we can't free a thread while we're operating under its context,
878  * push the current thread into our CPU's deadthread holder. This means
879  * we needn't worry about someone else grabbing our context before we
880  * do a cpu_throw().
881  */
882 void
883 thread_exit(void)
884 {
885 	uint64_t runtime, new_switchtime;
886 	struct thread *td;
887 	struct thread *td2;
888 	struct proc *p;
889 	int wakeup_swapper;
890 
891 	td = curthread;
892 	p = td->td_proc;
893 
894 	PROC_SLOCK_ASSERT(p, MA_OWNED);
895 	mtx_assert(&Giant, MA_NOTOWNED);
896 
897 	PROC_LOCK_ASSERT(p, MA_OWNED);
898 	KASSERT(p != NULL, ("thread exiting without a process"));
899 	CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
900 	    (long)p->p_pid, td->td_name);
901 	SDT_PROBE0(proc, , , lwp__exit);
902 	KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
903 	MPASS(td->td_realucred == td->td_ucred);
904 
905 	/*
906 	 * drop FPU & debug register state storage, or any other
907 	 * architecture specific resources that
908 	 * would not be on a new untouched process.
909 	 */
910 	cpu_thread_exit(td);
911 
912 	/*
913 	 * The last thread is left attached to the process
914 	 * So that the whole bundle gets recycled. Skip
915 	 * all this stuff if we never had threads.
916 	 * EXIT clears all sign of other threads when
917 	 * it goes to single threading, so the last thread always
918 	 * takes the short path.
919 	 */
920 	if (p->p_flag & P_HADTHREADS) {
921 		if (p->p_numthreads > 1) {
922 			atomic_add_int(&td->td_proc->p_exitthreads, 1);
923 			thread_unlink(td);
924 			td2 = FIRST_THREAD_IN_PROC(p);
925 			sched_exit_thread(td2, td);
926 
927 			/*
928 			 * The test below is NOT true if we are the
929 			 * sole exiting thread. P_STOPPED_SINGLE is unset
930 			 * in exit1() after it is the only survivor.
931 			 */
932 			if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
933 				if (p->p_numthreads == p->p_suspcount) {
934 					thread_lock(p->p_singlethread);
935 					wakeup_swapper = thread_unsuspend_one(
936 						p->p_singlethread, p, false);
937 					if (wakeup_swapper)
938 						kick_proc0();
939 				}
940 			}
941 
942 			PCPU_SET(deadthread, td);
943 		} else {
944 			/*
945 			 * The last thread is exiting.. but not through exit()
946 			 */
947 			panic ("thread_exit: Last thread exiting on its own");
948 		}
949 	}
950 #ifdef	HWPMC_HOOKS
951 	/*
952 	 * If this thread is part of a process that is being tracked by hwpmc(4),
953 	 * inform the module of the thread's impending exit.
954 	 */
955 	if (PMC_PROC_IS_USING_PMCS(td->td_proc)) {
956 		PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
957 		PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT, NULL);
958 	} else if (PMC_SYSTEM_SAMPLING_ACTIVE())
959 		PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT_LOG, NULL);
960 #endif
961 	PROC_UNLOCK(p);
962 	PROC_STATLOCK(p);
963 	thread_lock(td);
964 	PROC_SUNLOCK(p);
965 
966 	/* Do the same timestamp bookkeeping that mi_switch() would do. */
967 	new_switchtime = cpu_ticks();
968 	runtime = new_switchtime - PCPU_GET(switchtime);
969 	td->td_runtime += runtime;
970 	td->td_incruntime += runtime;
971 	PCPU_SET(switchtime, new_switchtime);
972 	PCPU_SET(switchticks, ticks);
973 	VM_CNT_INC(v_swtch);
974 
975 	/* Save our resource usage in our process. */
976 	td->td_ru.ru_nvcsw++;
977 	ruxagg_locked(p, td);
978 	rucollect(&p->p_ru, &td->td_ru);
979 	PROC_STATUNLOCK(p);
980 
981 	TD_SET_STATE(td, TDS_INACTIVE);
982 #ifdef WITNESS
983 	witness_thread_exit(td);
984 #endif
985 	CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
986 	sched_throw(td);
987 	panic("I'm a teapot!");
988 	/* NOTREACHED */
989 }
990 
991 /*
992  * Do any thread specific cleanups that may be needed in wait()
993  * called with Giant, proc and schedlock not held.
994  */
995 void
996 thread_wait(struct proc *p)
997 {
998 	struct thread *td;
999 
1000 	mtx_assert(&Giant, MA_NOTOWNED);
1001 	KASSERT(p->p_numthreads == 1, ("multiple threads in thread_wait()"));
1002 	KASSERT(p->p_exitthreads == 0, ("p_exitthreads leaking"));
1003 	td = FIRST_THREAD_IN_PROC(p);
1004 	/* Lock the last thread so we spin until it exits cpu_throw(). */
1005 	thread_lock(td);
1006 	thread_unlock(td);
1007 	lock_profile_thread_exit(td);
1008 	cpuset_rel(td->td_cpuset);
1009 	td->td_cpuset = NULL;
1010 	cpu_thread_clean(td);
1011 	thread_cow_free(td);
1012 	callout_drain(&td->td_slpcallout);
1013 	thread_reap();	/* check for zombie threads etc. */
1014 }
1015 
1016 /*
1017  * Link a thread to a process.
1018  * set up anything that needs to be initialized for it to
1019  * be used by the process.
1020  */
1021 void
1022 thread_link(struct thread *td, struct proc *p)
1023 {
1024 
1025 	/*
1026 	 * XXX This can't be enabled because it's called for proc0 before
1027 	 * its lock has been created.
1028 	 * PROC_LOCK_ASSERT(p, MA_OWNED);
1029 	 */
1030 	TD_SET_STATE(td, TDS_INACTIVE);
1031 	td->td_proc     = p;
1032 	td->td_flags    = TDF_INMEM;
1033 
1034 	LIST_INIT(&td->td_contested);
1035 	LIST_INIT(&td->td_lprof[0]);
1036 	LIST_INIT(&td->td_lprof[1]);
1037 #ifdef EPOCH_TRACE
1038 	SLIST_INIT(&td->td_epochs);
1039 #endif
1040 	sigqueue_init(&td->td_sigqueue, p);
1041 	callout_init(&td->td_slpcallout, 1);
1042 	TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
1043 	p->p_numthreads++;
1044 }
1045 
1046 /*
1047  * Called from:
1048  *  thread_exit()
1049  */
1050 void
1051 thread_unlink(struct thread *td)
1052 {
1053 	struct proc *p = td->td_proc;
1054 
1055 	PROC_LOCK_ASSERT(p, MA_OWNED);
1056 #ifdef EPOCH_TRACE
1057 	MPASS(SLIST_EMPTY(&td->td_epochs));
1058 #endif
1059 
1060 	TAILQ_REMOVE(&p->p_threads, td, td_plist);
1061 	p->p_numthreads--;
1062 	/* could clear a few other things here */
1063 	/* Must  NOT clear links to proc! */
1064 }
1065 
1066 static int
1067 calc_remaining(struct proc *p, int mode)
1068 {
1069 	int remaining;
1070 
1071 	PROC_LOCK_ASSERT(p, MA_OWNED);
1072 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1073 	if (mode == SINGLE_EXIT)
1074 		remaining = p->p_numthreads;
1075 	else if (mode == SINGLE_BOUNDARY)
1076 		remaining = p->p_numthreads - p->p_boundary_count;
1077 	else if (mode == SINGLE_NO_EXIT || mode == SINGLE_ALLPROC)
1078 		remaining = p->p_numthreads - p->p_suspcount;
1079 	else
1080 		panic("calc_remaining: wrong mode %d", mode);
1081 	return (remaining);
1082 }
1083 
1084 static int
1085 remain_for_mode(int mode)
1086 {
1087 
1088 	return (mode == SINGLE_ALLPROC ? 0 : 1);
1089 }
1090 
1091 static int
1092 weed_inhib(int mode, struct thread *td2, struct proc *p)
1093 {
1094 	int wakeup_swapper;
1095 
1096 	PROC_LOCK_ASSERT(p, MA_OWNED);
1097 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1098 	THREAD_LOCK_ASSERT(td2, MA_OWNED);
1099 
1100 	wakeup_swapper = 0;
1101 
1102 	/*
1103 	 * Since the thread lock is dropped by the scheduler we have
1104 	 * to retry to check for races.
1105 	 */
1106 restart:
1107 	switch (mode) {
1108 	case SINGLE_EXIT:
1109 		if (TD_IS_SUSPENDED(td2)) {
1110 			wakeup_swapper |= thread_unsuspend_one(td2, p, true);
1111 			thread_lock(td2);
1112 			goto restart;
1113 		}
1114 		if (TD_CAN_ABORT(td2)) {
1115 			wakeup_swapper |= sleepq_abort(td2, EINTR);
1116 			return (wakeup_swapper);
1117 		}
1118 		break;
1119 	case SINGLE_BOUNDARY:
1120 	case SINGLE_NO_EXIT:
1121 		if (TD_IS_SUSPENDED(td2) &&
1122 		    (td2->td_flags & TDF_BOUNDARY) == 0) {
1123 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
1124 			thread_lock(td2);
1125 			goto restart;
1126 		}
1127 		if (TD_CAN_ABORT(td2)) {
1128 			wakeup_swapper |= sleepq_abort(td2, ERESTART);
1129 			return (wakeup_swapper);
1130 		}
1131 		break;
1132 	case SINGLE_ALLPROC:
1133 		/*
1134 		 * ALLPROC suspend tries to avoid spurious EINTR for
1135 		 * threads sleeping interruptable, by suspending the
1136 		 * thread directly, similarly to sig_suspend_threads().
1137 		 * Since such sleep is not performed at the user
1138 		 * boundary, TDF_BOUNDARY flag is not set, and TDF_ALLPROCSUSP
1139 		 * is used to avoid immediate un-suspend.
1140 		 */
1141 		if (TD_IS_SUSPENDED(td2) && (td2->td_flags & (TDF_BOUNDARY |
1142 		    TDF_ALLPROCSUSP)) == 0) {
1143 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
1144 			thread_lock(td2);
1145 			goto restart;
1146 		}
1147 		if (TD_CAN_ABORT(td2)) {
1148 			if ((td2->td_flags & TDF_SBDRY) == 0) {
1149 				thread_suspend_one(td2);
1150 				td2->td_flags |= TDF_ALLPROCSUSP;
1151 			} else {
1152 				wakeup_swapper |= sleepq_abort(td2, ERESTART);
1153 				return (wakeup_swapper);
1154 			}
1155 		}
1156 		break;
1157 	default:
1158 		break;
1159 	}
1160 	thread_unlock(td2);
1161 	return (wakeup_swapper);
1162 }
1163 
1164 /*
1165  * Enforce single-threading.
1166  *
1167  * Returns 1 if the caller must abort (another thread is waiting to
1168  * exit the process or similar). Process is locked!
1169  * Returns 0 when you are successfully the only thread running.
1170  * A process has successfully single threaded in the suspend mode when
1171  * There are no threads in user mode. Threads in the kernel must be
1172  * allowed to continue until they get to the user boundary. They may even
1173  * copy out their return values and data before suspending. They may however be
1174  * accelerated in reaching the user boundary as we will wake up
1175  * any sleeping threads that are interruptable. (PCATCH).
1176  */
1177 int
1178 thread_single(struct proc *p, int mode)
1179 {
1180 	struct thread *td;
1181 	struct thread *td2;
1182 	int remaining, wakeup_swapper;
1183 
1184 	td = curthread;
1185 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
1186 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
1187 	    ("invalid mode %d", mode));
1188 	/*
1189 	 * If allowing non-ALLPROC singlethreading for non-curproc
1190 	 * callers, calc_remaining() and remain_for_mode() should be
1191 	 * adjusted to also account for td->td_proc != p.  For now
1192 	 * this is not implemented because it is not used.
1193 	 */
1194 	KASSERT((mode == SINGLE_ALLPROC && td->td_proc != p) ||
1195 	    (mode != SINGLE_ALLPROC && td->td_proc == p),
1196 	    ("mode %d proc %p curproc %p", mode, p, td->td_proc));
1197 	mtx_assert(&Giant, MA_NOTOWNED);
1198 	PROC_LOCK_ASSERT(p, MA_OWNED);
1199 
1200 	if ((p->p_flag & P_HADTHREADS) == 0 && mode != SINGLE_ALLPROC)
1201 		return (0);
1202 
1203 	/* Is someone already single threading? */
1204 	if (p->p_singlethread != NULL && p->p_singlethread != td)
1205 		return (1);
1206 
1207 	if (mode == SINGLE_EXIT) {
1208 		p->p_flag |= P_SINGLE_EXIT;
1209 		p->p_flag &= ~P_SINGLE_BOUNDARY;
1210 	} else {
1211 		p->p_flag &= ~P_SINGLE_EXIT;
1212 		if (mode == SINGLE_BOUNDARY)
1213 			p->p_flag |= P_SINGLE_BOUNDARY;
1214 		else
1215 			p->p_flag &= ~P_SINGLE_BOUNDARY;
1216 	}
1217 	if (mode == SINGLE_ALLPROC)
1218 		p->p_flag |= P_TOTAL_STOP;
1219 	p->p_flag |= P_STOPPED_SINGLE;
1220 	PROC_SLOCK(p);
1221 	p->p_singlethread = td;
1222 	remaining = calc_remaining(p, mode);
1223 	while (remaining != remain_for_mode(mode)) {
1224 		if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
1225 			goto stopme;
1226 		wakeup_swapper = 0;
1227 		FOREACH_THREAD_IN_PROC(p, td2) {
1228 			if (td2 == td)
1229 				continue;
1230 			thread_lock(td2);
1231 			td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
1232 			if (TD_IS_INHIBITED(td2)) {
1233 				wakeup_swapper |= weed_inhib(mode, td2, p);
1234 #ifdef SMP
1235 			} else if (TD_IS_RUNNING(td2) && td != td2) {
1236 				forward_signal(td2);
1237 				thread_unlock(td2);
1238 #endif
1239 			} else
1240 				thread_unlock(td2);
1241 		}
1242 		if (wakeup_swapper)
1243 			kick_proc0();
1244 		remaining = calc_remaining(p, mode);
1245 
1246 		/*
1247 		 * Maybe we suspended some threads.. was it enough?
1248 		 */
1249 		if (remaining == remain_for_mode(mode))
1250 			break;
1251 
1252 stopme:
1253 		/*
1254 		 * Wake us up when everyone else has suspended.
1255 		 * In the mean time we suspend as well.
1256 		 */
1257 		thread_suspend_switch(td, p);
1258 		remaining = calc_remaining(p, mode);
1259 	}
1260 	if (mode == SINGLE_EXIT) {
1261 		/*
1262 		 * Convert the process to an unthreaded process.  The
1263 		 * SINGLE_EXIT is called by exit1() or execve(), in
1264 		 * both cases other threads must be retired.
1265 		 */
1266 		KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
1267 		p->p_singlethread = NULL;
1268 		p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
1269 
1270 		/*
1271 		 * Wait for any remaining threads to exit cpu_throw().
1272 		 */
1273 		while (p->p_exitthreads != 0) {
1274 			PROC_SUNLOCK(p);
1275 			PROC_UNLOCK(p);
1276 			sched_relinquish(td);
1277 			PROC_LOCK(p);
1278 			PROC_SLOCK(p);
1279 		}
1280 	} else if (mode == SINGLE_BOUNDARY) {
1281 		/*
1282 		 * Wait until all suspended threads are removed from
1283 		 * the processors.  The thread_suspend_check()
1284 		 * increments p_boundary_count while it is still
1285 		 * running, which makes it possible for the execve()
1286 		 * to destroy vmspace while our other threads are
1287 		 * still using the address space.
1288 		 *
1289 		 * We lock the thread, which is only allowed to
1290 		 * succeed after context switch code finished using
1291 		 * the address space.
1292 		 */
1293 		FOREACH_THREAD_IN_PROC(p, td2) {
1294 			if (td2 == td)
1295 				continue;
1296 			thread_lock(td2);
1297 			KASSERT((td2->td_flags & TDF_BOUNDARY) != 0,
1298 			    ("td %p not on boundary", td2));
1299 			KASSERT(TD_IS_SUSPENDED(td2),
1300 			    ("td %p is not suspended", td2));
1301 			thread_unlock(td2);
1302 		}
1303 	}
1304 	PROC_SUNLOCK(p);
1305 	return (0);
1306 }
1307 
1308 bool
1309 thread_suspend_check_needed(void)
1310 {
1311 	struct proc *p;
1312 	struct thread *td;
1313 
1314 	td = curthread;
1315 	p = td->td_proc;
1316 	PROC_LOCK_ASSERT(p, MA_OWNED);
1317 	return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
1318 	    (td->td_dbgflags & TDB_SUSPEND) != 0));
1319 }
1320 
1321 /*
1322  * Called in from locations that can safely check to see
1323  * whether we have to suspend or at least throttle for a
1324  * single-thread event (e.g. fork).
1325  *
1326  * Such locations include userret().
1327  * If the "return_instead" argument is non zero, the thread must be able to
1328  * accept 0 (caller may continue), or 1 (caller must abort) as a result.
1329  *
1330  * The 'return_instead' argument tells the function if it may do a
1331  * thread_exit() or suspend, or whether the caller must abort and back
1332  * out instead.
1333  *
1334  * If the thread that set the single_threading request has set the
1335  * P_SINGLE_EXIT bit in the process flags then this call will never return
1336  * if 'return_instead' is false, but will exit.
1337  *
1338  * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
1339  *---------------+--------------------+---------------------
1340  *       0       | returns 0          |   returns 0 or 1
1341  *               | when ST ends       |   immediately
1342  *---------------+--------------------+---------------------
1343  *       1       | thread exits       |   returns 1
1344  *               |                    |  immediately
1345  * 0 = thread_exit() or suspension ok,
1346  * other = return error instead of stopping the thread.
1347  *
1348  * While a full suspension is under effect, even a single threading
1349  * thread would be suspended if it made this call (but it shouldn't).
1350  * This call should only be made from places where
1351  * thread_exit() would be safe as that may be the outcome unless
1352  * return_instead is set.
1353  */
1354 int
1355 thread_suspend_check(int return_instead)
1356 {
1357 	struct thread *td;
1358 	struct proc *p;
1359 	int wakeup_swapper;
1360 
1361 	td = curthread;
1362 	p = td->td_proc;
1363 	mtx_assert(&Giant, MA_NOTOWNED);
1364 	PROC_LOCK_ASSERT(p, MA_OWNED);
1365 	while (thread_suspend_check_needed()) {
1366 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1367 			KASSERT(p->p_singlethread != NULL,
1368 			    ("singlethread not set"));
1369 			/*
1370 			 * The only suspension in action is a
1371 			 * single-threading. Single threader need not stop.
1372 			 * It is safe to access p->p_singlethread unlocked
1373 			 * because it can only be set to our address by us.
1374 			 */
1375 			if (p->p_singlethread == td)
1376 				return (0);	/* Exempt from stopping. */
1377 		}
1378 		if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
1379 			return (EINTR);
1380 
1381 		/* Should we goto user boundary if we didn't come from there? */
1382 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1383 		    (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
1384 			return (ERESTART);
1385 
1386 		/*
1387 		 * Ignore suspend requests if they are deferred.
1388 		 */
1389 		if ((td->td_flags & TDF_SBDRY) != 0) {
1390 			KASSERT(return_instead,
1391 			    ("TDF_SBDRY set for unsafe thread_suspend_check"));
1392 			KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
1393 			    (TDF_SEINTR | TDF_SERESTART),
1394 			    ("both TDF_SEINTR and TDF_SERESTART"));
1395 			return (TD_SBDRY_INTR(td) ? TD_SBDRY_ERRNO(td) : 0);
1396 		}
1397 
1398 		/*
1399 		 * If the process is waiting for us to exit,
1400 		 * this thread should just suicide.
1401 		 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
1402 		 */
1403 		if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
1404 			PROC_UNLOCK(p);
1405 
1406 			/*
1407 			 * Allow Linux emulation layer to do some work
1408 			 * before thread suicide.
1409 			 */
1410 			if (__predict_false(p->p_sysent->sv_thread_detach != NULL))
1411 				(p->p_sysent->sv_thread_detach)(td);
1412 			umtx_thread_exit(td);
1413 			kern_thr_exit(td);
1414 			panic("stopped thread did not exit");
1415 		}
1416 
1417 		PROC_SLOCK(p);
1418 		thread_stopped(p);
1419 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1420 			if (p->p_numthreads == p->p_suspcount + 1) {
1421 				thread_lock(p->p_singlethread);
1422 				wakeup_swapper = thread_unsuspend_one(
1423 				    p->p_singlethread, p, false);
1424 				if (wakeup_swapper)
1425 					kick_proc0();
1426 			}
1427 		}
1428 		PROC_UNLOCK(p);
1429 		thread_lock(td);
1430 		/*
1431 		 * When a thread suspends, it just
1432 		 * gets taken off all queues.
1433 		 */
1434 		thread_suspend_one(td);
1435 		if (return_instead == 0) {
1436 			p->p_boundary_count++;
1437 			td->td_flags |= TDF_BOUNDARY;
1438 		}
1439 		PROC_SUNLOCK(p);
1440 		mi_switch(SW_INVOL | SWT_SUSPEND);
1441 		PROC_LOCK(p);
1442 	}
1443 	return (0);
1444 }
1445 
1446 /*
1447  * Check for possible stops and suspensions while executing a
1448  * casueword or similar transiently failing operation.
1449  *
1450  * The sleep argument controls whether the function can handle a stop
1451  * request itself or it should return ERESTART and the request is
1452  * proceed at the kernel/user boundary in ast.
1453  *
1454  * Typically, when retrying due to casueword(9) failure (rv == 1), we
1455  * should handle the stop requests there, with exception of cases when
1456  * the thread owns a kernel resource, for instance busied the umtx
1457  * key, or when functions return immediately if thread_check_susp()
1458  * returned non-zero.  On the other hand, retrying the whole lock
1459  * operation, we better not stop there but delegate the handling to
1460  * ast.
1461  *
1462  * If the request is for thread termination P_SINGLE_EXIT, we cannot
1463  * handle it at all, and simply return EINTR.
1464  */
1465 int
1466 thread_check_susp(struct thread *td, bool sleep)
1467 {
1468 	struct proc *p;
1469 	int error;
1470 
1471 	/*
1472 	 * The check for TDF_NEEDSUSPCHK is racy, but it is enough to
1473 	 * eventually break the lockstep loop.
1474 	 */
1475 	if ((td->td_flags & TDF_NEEDSUSPCHK) == 0)
1476 		return (0);
1477 	error = 0;
1478 	p = td->td_proc;
1479 	PROC_LOCK(p);
1480 	if (p->p_flag & P_SINGLE_EXIT)
1481 		error = EINTR;
1482 	else if (P_SHOULDSTOP(p) ||
1483 	    ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_SUSPEND)))
1484 		error = sleep ? thread_suspend_check(0) : ERESTART;
1485 	PROC_UNLOCK(p);
1486 	return (error);
1487 }
1488 
1489 void
1490 thread_suspend_switch(struct thread *td, struct proc *p)
1491 {
1492 
1493 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1494 	PROC_LOCK_ASSERT(p, MA_OWNED);
1495 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1496 	/*
1497 	 * We implement thread_suspend_one in stages here to avoid
1498 	 * dropping the proc lock while the thread lock is owned.
1499 	 */
1500 	if (p == td->td_proc) {
1501 		thread_stopped(p);
1502 		p->p_suspcount++;
1503 	}
1504 	PROC_UNLOCK(p);
1505 	thread_lock(td);
1506 	td->td_flags &= ~TDF_NEEDSUSPCHK;
1507 	TD_SET_SUSPENDED(td);
1508 	sched_sleep(td, 0);
1509 	PROC_SUNLOCK(p);
1510 	DROP_GIANT();
1511 	mi_switch(SW_VOL | SWT_SUSPEND);
1512 	PICKUP_GIANT();
1513 	PROC_LOCK(p);
1514 	PROC_SLOCK(p);
1515 }
1516 
1517 void
1518 thread_suspend_one(struct thread *td)
1519 {
1520 	struct proc *p;
1521 
1522 	p = td->td_proc;
1523 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1524 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1525 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1526 	p->p_suspcount++;
1527 	td->td_flags &= ~TDF_NEEDSUSPCHK;
1528 	TD_SET_SUSPENDED(td);
1529 	sched_sleep(td, 0);
1530 }
1531 
1532 static int
1533 thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
1534 {
1535 
1536 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1537 	KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
1538 	TD_CLR_SUSPENDED(td);
1539 	td->td_flags &= ~TDF_ALLPROCSUSP;
1540 	if (td->td_proc == p) {
1541 		PROC_SLOCK_ASSERT(p, MA_OWNED);
1542 		p->p_suspcount--;
1543 		if (boundary && (td->td_flags & TDF_BOUNDARY) != 0) {
1544 			td->td_flags &= ~TDF_BOUNDARY;
1545 			p->p_boundary_count--;
1546 		}
1547 	}
1548 	return (setrunnable(td, 0));
1549 }
1550 
1551 void
1552 thread_run_flash(struct thread *td)
1553 {
1554 	struct proc *p;
1555 
1556 	p = td->td_proc;
1557 	PROC_LOCK_ASSERT(p, MA_OWNED);
1558 
1559 	if (TD_ON_SLEEPQ(td))
1560 		sleepq_remove_nested(td);
1561 	else
1562 		thread_lock(td);
1563 
1564 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1565 	KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
1566 
1567 	TD_CLR_SUSPENDED(td);
1568 	PROC_SLOCK(p);
1569 	MPASS(p->p_suspcount > 0);
1570 	p->p_suspcount--;
1571 	PROC_SUNLOCK(p);
1572 	if (setrunnable(td, 0))
1573 		kick_proc0();
1574 }
1575 
1576 /*
1577  * Allow all threads blocked by single threading to continue running.
1578  */
1579 void
1580 thread_unsuspend(struct proc *p)
1581 {
1582 	struct thread *td;
1583 	int wakeup_swapper;
1584 
1585 	PROC_LOCK_ASSERT(p, MA_OWNED);
1586 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1587 	wakeup_swapper = 0;
1588 	if (!P_SHOULDSTOP(p)) {
1589                 FOREACH_THREAD_IN_PROC(p, td) {
1590 			thread_lock(td);
1591 			if (TD_IS_SUSPENDED(td)) {
1592 				wakeup_swapper |= thread_unsuspend_one(td, p,
1593 				    true);
1594 			} else
1595 				thread_unlock(td);
1596 		}
1597 	} else if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1598 	    p->p_numthreads == p->p_suspcount) {
1599 		/*
1600 		 * Stopping everything also did the job for the single
1601 		 * threading request. Now we've downgraded to single-threaded,
1602 		 * let it continue.
1603 		 */
1604 		if (p->p_singlethread->td_proc == p) {
1605 			thread_lock(p->p_singlethread);
1606 			wakeup_swapper = thread_unsuspend_one(
1607 			    p->p_singlethread, p, false);
1608 		}
1609 	}
1610 	if (wakeup_swapper)
1611 		kick_proc0();
1612 }
1613 
1614 /*
1615  * End the single threading mode..
1616  */
1617 void
1618 thread_single_end(struct proc *p, int mode)
1619 {
1620 	struct thread *td;
1621 	int wakeup_swapper;
1622 
1623 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
1624 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
1625 	    ("invalid mode %d", mode));
1626 	PROC_LOCK_ASSERT(p, MA_OWNED);
1627 	KASSERT((mode == SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) != 0) ||
1628 	    (mode != SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) == 0),
1629 	    ("mode %d does not match P_TOTAL_STOP", mode));
1630 	KASSERT(mode == SINGLE_ALLPROC || p->p_singlethread == curthread,
1631 	    ("thread_single_end from other thread %p %p",
1632 	    curthread, p->p_singlethread));
1633 	KASSERT(mode != SINGLE_BOUNDARY ||
1634 	    (p->p_flag & P_SINGLE_BOUNDARY) != 0,
1635 	    ("mis-matched SINGLE_BOUNDARY flags %x", p->p_flag));
1636 	p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY |
1637 	    P_TOTAL_STOP);
1638 	PROC_SLOCK(p);
1639 	p->p_singlethread = NULL;
1640 	wakeup_swapper = 0;
1641 	/*
1642 	 * If there are other threads they may now run,
1643 	 * unless of course there is a blanket 'stop order'
1644 	 * on the process. The single threader must be allowed
1645 	 * to continue however as this is a bad place to stop.
1646 	 */
1647 	if (p->p_numthreads != remain_for_mode(mode) && !P_SHOULDSTOP(p)) {
1648                 FOREACH_THREAD_IN_PROC(p, td) {
1649 			thread_lock(td);
1650 			if (TD_IS_SUSPENDED(td)) {
1651 				wakeup_swapper |= thread_unsuspend_one(td, p,
1652 				    mode == SINGLE_BOUNDARY);
1653 			} else
1654 				thread_unlock(td);
1655 		}
1656 	}
1657 	KASSERT(mode != SINGLE_BOUNDARY || p->p_boundary_count == 0,
1658 	    ("inconsistent boundary count %d", p->p_boundary_count));
1659 	PROC_SUNLOCK(p);
1660 	if (wakeup_swapper)
1661 		kick_proc0();
1662 }
1663 
1664 /*
1665  * Locate a thread by number and return with proc lock held.
1666  *
1667  * thread exit establishes proc -> tidhash lock ordering, but lookup
1668  * takes tidhash first and needs to return locked proc.
1669  *
1670  * The problem is worked around by relying on type-safety of both
1671  * structures and doing the work in 2 steps:
1672  * - tidhash-locked lookup which saves both thread and proc pointers
1673  * - proc-locked verification that the found thread still matches
1674  */
1675 static bool
1676 tdfind_hash(lwpid_t tid, pid_t pid, struct proc **pp, struct thread **tdp)
1677 {
1678 #define RUN_THRESH	16
1679 	struct proc *p;
1680 	struct thread *td;
1681 	int run;
1682 	bool locked;
1683 
1684 	run = 0;
1685 	rw_rlock(TIDHASHLOCK(tid));
1686 	locked = true;
1687 	LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1688 		if (td->td_tid != tid) {
1689 			run++;
1690 			continue;
1691 		}
1692 		p = td->td_proc;
1693 		if (pid != -1 && p->p_pid != pid) {
1694 			td = NULL;
1695 			break;
1696 		}
1697 		if (run > RUN_THRESH) {
1698 			if (rw_try_upgrade(TIDHASHLOCK(tid))) {
1699 				LIST_REMOVE(td, td_hash);
1700 				LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1701 					td, td_hash);
1702 				rw_wunlock(TIDHASHLOCK(tid));
1703 				locked = false;
1704 				break;
1705 			}
1706 		}
1707 		break;
1708 	}
1709 	if (locked)
1710 		rw_runlock(TIDHASHLOCK(tid));
1711 	if (td == NULL)
1712 		return (false);
1713 	*pp = p;
1714 	*tdp = td;
1715 	return (true);
1716 }
1717 
1718 struct thread *
1719 tdfind(lwpid_t tid, pid_t pid)
1720 {
1721 	struct proc *p;
1722 	struct thread *td;
1723 
1724 	td = curthread;
1725 	if (td->td_tid == tid) {
1726 		if (pid != -1 && td->td_proc->p_pid != pid)
1727 			return (NULL);
1728 		PROC_LOCK(td->td_proc);
1729 		return (td);
1730 	}
1731 
1732 	for (;;) {
1733 		if (!tdfind_hash(tid, pid, &p, &td))
1734 			return (NULL);
1735 		PROC_LOCK(p);
1736 		if (td->td_tid != tid) {
1737 			PROC_UNLOCK(p);
1738 			continue;
1739 		}
1740 		if (td->td_proc != p) {
1741 			PROC_UNLOCK(p);
1742 			continue;
1743 		}
1744 		if (p->p_state == PRS_NEW) {
1745 			PROC_UNLOCK(p);
1746 			return (NULL);
1747 		}
1748 		return (td);
1749 	}
1750 }
1751 
1752 void
1753 tidhash_add(struct thread *td)
1754 {
1755 	rw_wlock(TIDHASHLOCK(td->td_tid));
1756 	LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1757 	rw_wunlock(TIDHASHLOCK(td->td_tid));
1758 }
1759 
1760 void
1761 tidhash_remove(struct thread *td)
1762 {
1763 
1764 	rw_wlock(TIDHASHLOCK(td->td_tid));
1765 	LIST_REMOVE(td, td_hash);
1766 	rw_wunlock(TIDHASHLOCK(td->td_tid));
1767 }
1768