xref: /freebsd/sys/kern/kern_thread.c (revision 755341df4fe0fbf704d9dc8a3193a8a5de8f887a)
19454b2d8SWarner Losh /*-
28a36da99SPedro F. Giffuni  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
38a36da99SPedro F. Giffuni  *
444990b8cSJulian Elischer  * Copyright (C) 2001 Julian Elischer <julian@freebsd.org>.
544990b8cSJulian Elischer  *  All rights reserved.
644990b8cSJulian Elischer  *
744990b8cSJulian Elischer  * Redistribution and use in source and binary forms, with or without
844990b8cSJulian Elischer  * modification, are permitted provided that the following conditions
944990b8cSJulian Elischer  * are met:
1044990b8cSJulian Elischer  * 1. Redistributions of source code must retain the above copyright
1144990b8cSJulian Elischer  *    notice(s), this list of conditions and the following disclaimer as
1244990b8cSJulian Elischer  *    the first lines of this file unmodified other than the possible
1344990b8cSJulian Elischer  *    addition of one or more copyright notices.
1444990b8cSJulian Elischer  * 2. Redistributions in binary form must reproduce the above copyright
1544990b8cSJulian Elischer  *    notice(s), this list of conditions and the following disclaimer in the
1644990b8cSJulian Elischer  *    documentation and/or other materials provided with the distribution.
1744990b8cSJulian Elischer  *
1844990b8cSJulian Elischer  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
1944990b8cSJulian Elischer  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2044990b8cSJulian Elischer  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2144990b8cSJulian Elischer  * DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
2244990b8cSJulian Elischer  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
2344990b8cSJulian Elischer  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2444990b8cSJulian Elischer  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2544990b8cSJulian Elischer  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2644990b8cSJulian Elischer  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2744990b8cSJulian Elischer  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
2844990b8cSJulian Elischer  * DAMAGE.
2944990b8cSJulian Elischer  */
3044990b8cSJulian Elischer 
313d06b4b3SAttilio Rao #include "opt_witness.h"
3216d95d4fSJoseph Koshy #include "opt_hwpmc_hooks.h"
333d06b4b3SAttilio Rao 
34677b542eSDavid E. O'Brien #include <sys/cdefs.h>
35677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
36677b542eSDavid E. O'Brien 
3744990b8cSJulian Elischer #include <sys/param.h>
3844990b8cSJulian Elischer #include <sys/systm.h>
3944990b8cSJulian Elischer #include <sys/kernel.h>
4044990b8cSJulian Elischer #include <sys/lock.h>
4144990b8cSJulian Elischer #include <sys/mutex.h>
4244990b8cSJulian Elischer #include <sys/proc.h>
4335bb59edSMateusz Guzik #include <sys/bitstring.h>
446febf180SGleb Smirnoff #include <sys/epoch.h>
458f0e9130SKonstantin Belousov #include <sys/rangelock.h>
46e170bfdaSDavid Xu #include <sys/resourcevar.h>
47b3e9e682SRyan Stone #include <sys/sdt.h>
4894e0a4cdSJulian Elischer #include <sys/smp.h>
49de028f5aSJeff Roberson #include <sys/sched.h>
5044f3b092SJohn Baldwin #include <sys/sleepqueue.h>
51ace8398dSJeff Roberson #include <sys/selinfo.h>
52d1e7a4a5SJohn Baldwin #include <sys/syscallsubr.h>
5391d1786fSDmitry Chagin #include <sys/sysent.h>
54961a7b24SJohn Baldwin #include <sys/turnstile.h>
5544990b8cSJulian Elischer #include <sys/ktr.h>
56cf7d9a8cSDavid Xu #include <sys/rwlock.h>
57bc8e6d81SDavid Xu #include <sys/umtx.h>
589ed01c32SGleb Smirnoff #include <sys/vmmeter.h>
59d7f687fcSJeff Roberson #include <sys/cpuset.h>
6016d95d4fSJoseph Koshy #ifdef	HWPMC_HOOKS
6116d95d4fSJoseph Koshy #include <sys/pmckern.h>
6216d95d4fSJoseph Koshy #endif
631bd3cf5dSMateusz Guzik #include <sys/priv.h>
6444990b8cSJulian Elischer 
65911b84b0SRobert Watson #include <security/audit/audit.h>
66911b84b0SRobert Watson 
6744990b8cSJulian Elischer #include <vm/vm.h>
6849a2507bSAlan Cox #include <vm/vm_extern.h>
6944990b8cSJulian Elischer #include <vm/uma.h>
70b209f889SRandall Stewart #include <sys/eventhandler.h>
7102fb42b0SPeter Wemm 
72acd9f517SKonstantin Belousov /*
73acd9f517SKonstantin Belousov  * Asserts below verify the stability of struct thread and struct proc
74acd9f517SKonstantin Belousov  * layout, as exposed by KBI to modules.  On head, the KBI is allowed
75acd9f517SKonstantin Belousov  * to drift, change to the structures must be accompanied by the
76acd9f517SKonstantin Belousov  * assert update.
77acd9f517SKonstantin Belousov  *
78acd9f517SKonstantin Belousov  * On the stable branches after KBI freeze, conditions must not be
79acd9f517SKonstantin Belousov  * violated.  Typically new fields are moved to the end of the
80acd9f517SKonstantin Belousov  * structures.
81acd9f517SKonstantin Belousov  */
82acd9f517SKonstantin Belousov #ifdef __amd64__
833f289c3fSJeff Roberson _Static_assert(offsetof(struct thread, td_flags) == 0xfc,
84acd9f517SKonstantin Belousov     "struct thread KBI td_flags");
853f289c3fSJeff Roberson _Static_assert(offsetof(struct thread, td_pflags) == 0x104,
86acd9f517SKonstantin Belousov     "struct thread KBI td_pflags");
871e2521ffSEdward Tomasz Napierala _Static_assert(offsetof(struct thread, td_frame) == 0x4a0,
88acd9f517SKonstantin Belousov     "struct thread KBI td_frame");
891724c563SMateusz Guzik _Static_assert(offsetof(struct thread, td_emuldata) == 0x6b0,
90acd9f517SKonstantin Belousov     "struct thread KBI td_emuldata");
91acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_flag) == 0xb0,
92acd9f517SKonstantin Belousov     "struct proc KBI p_flag");
93acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_pid) == 0xbc,
94acd9f517SKonstantin Belousov     "struct proc KBI p_pid");
958de97f39SRick Macklem _Static_assert(offsetof(struct proc, p_filemon) == 0x3b8,
96acd9f517SKonstantin Belousov     "struct proc KBI p_filemon");
978de97f39SRick Macklem _Static_assert(offsetof(struct proc, p_comm) == 0x3d0,
98acd9f517SKonstantin Belousov     "struct proc KBI p_comm");
998de97f39SRick Macklem _Static_assert(offsetof(struct proc, p_emuldata) == 0x4b0,
100acd9f517SKonstantin Belousov     "struct proc KBI p_emuldata");
101acd9f517SKonstantin Belousov #endif
102acd9f517SKonstantin Belousov #ifdef __i386__
1033f289c3fSJeff Roberson _Static_assert(offsetof(struct thread, td_flags) == 0x98,
104acd9f517SKonstantin Belousov     "struct thread KBI td_flags");
1053f289c3fSJeff Roberson _Static_assert(offsetof(struct thread, td_pflags) == 0xa0,
106acd9f517SKonstantin Belousov     "struct thread KBI td_pflags");
1071e2521ffSEdward Tomasz Napierala _Static_assert(offsetof(struct thread, td_frame) == 0x300,
108acd9f517SKonstantin Belousov     "struct thread KBI td_frame");
1091e2521ffSEdward Tomasz Napierala _Static_assert(offsetof(struct thread, td_emuldata) == 0x344,
110acd9f517SKonstantin Belousov     "struct thread KBI td_emuldata");
111acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_flag) == 0x68,
112acd9f517SKonstantin Belousov     "struct proc KBI p_flag");
113acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_pid) == 0x74,
114acd9f517SKonstantin Belousov     "struct proc KBI p_pid");
1158de97f39SRick Macklem _Static_assert(offsetof(struct proc, p_filemon) == 0x268,
116acd9f517SKonstantin Belousov     "struct proc KBI p_filemon");
1178de97f39SRick Macklem _Static_assert(offsetof(struct proc, p_comm) == 0x27c,
118acd9f517SKonstantin Belousov     "struct proc KBI p_comm");
1198de97f39SRick Macklem _Static_assert(offsetof(struct proc, p_emuldata) == 0x308,
120acd9f517SKonstantin Belousov     "struct proc KBI p_emuldata");
121acd9f517SKonstantin Belousov #endif
122acd9f517SKonstantin Belousov 
123b3e9e682SRyan Stone SDT_PROVIDER_DECLARE(proc);
124d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(proc, , , lwp__exit);
125b3e9e682SRyan Stone 
1268460a577SJohn Birrell /*
1278460a577SJohn Birrell  * thread related storage.
1288460a577SJohn Birrell  */
12944990b8cSJulian Elischer static uma_zone_t thread_zone;
13044990b8cSJulian Elischer 
131c5315f51SMateusz Guzik static __exclusive_cache_line struct thread *thread_zombies;
13244990b8cSJulian Elischer 
133ff8fbcffSJeff Roberson static void thread_zombie(struct thread *);
13484cdea97SKonstantin Belousov static int thread_unsuspend_one(struct thread *td, struct proc *p,
13584cdea97SKonstantin Belousov     bool boundary);
136*755341dfSMateusz Guzik static void thread_free_batched(struct thread *td);
137ff8fbcffSJeff Roberson 
138934e7e5eSMateusz Guzik static struct mtx tid_lock;
139934e7e5eSMateusz Guzik static bitstr_t *tid_bitmap;
14035bb59edSMateusz Guzik 
141cf7d9a8cSDavid Xu static MALLOC_DEFINE(M_TIDHASH, "tidhash", "thread hash");
142cf7d9a8cSDavid Xu 
1431bd3cf5dSMateusz Guzik static int maxthread;
1441bd3cf5dSMateusz Guzik SYSCTL_INT(_kern, OID_AUTO, maxthread, CTLFLAG_RDTUN,
1451bd3cf5dSMateusz Guzik     &maxthread, 0, "Maximum number of threads");
1461bd3cf5dSMateusz Guzik 
1471bd3cf5dSMateusz Guzik static int nthreads;
1481bd3cf5dSMateusz Guzik 
149aae3547bSMateusz Guzik static LIST_HEAD(tidhashhead, thread) *tidhashtbl;
150aae3547bSMateusz Guzik static u_long	tidhash;
15126007fe3SMateusz Guzik static u_long	tidhashlock;
15226007fe3SMateusz Guzik static struct	rwlock *tidhashtbl_lock;
153aae3547bSMateusz Guzik #define	TIDHASH(tid)		(&tidhashtbl[(tid) & tidhash])
15426007fe3SMateusz Guzik #define	TIDHASHLOCK(tid)	(&tidhashtbl_lock[(tid) & tidhashlock])
155cf7d9a8cSDavid Xu 
1562ca45184SMatt Joras EVENTHANDLER_LIST_DEFINE(thread_ctor);
1572ca45184SMatt Joras EVENTHANDLER_LIST_DEFINE(thread_dtor);
1582ca45184SMatt Joras EVENTHANDLER_LIST_DEFINE(thread_init);
1592ca45184SMatt Joras EVENTHANDLER_LIST_DEFINE(thread_fini);
1602ca45184SMatt Joras 
161ec6ea5e8SDavid Xu static lwpid_t
162ec6ea5e8SDavid Xu tid_alloc(void)
163ec6ea5e8SDavid Xu {
1641bd3cf5dSMateusz Guzik 	static struct timeval lastfail;
1651bd3cf5dSMateusz Guzik 	static int curfail;
16635bb59edSMateusz Guzik 	static lwpid_t trytid;
167ec6ea5e8SDavid Xu 	lwpid_t tid;
168ec6ea5e8SDavid Xu 
16935bb59edSMateusz Guzik 	mtx_lock(&tid_lock);
17035bb59edSMateusz Guzik 	if (nthreads + 1 >= maxthread - 100) {
1711bd3cf5dSMateusz Guzik 		if (priv_check_cred(curthread->td_ucred, PRIV_MAXPROC) != 0 ||
17235bb59edSMateusz Guzik 		    nthreads + 1 >= maxthread) {
17335bb59edSMateusz Guzik 			mtx_unlock(&tid_lock);
1741bd3cf5dSMateusz Guzik 			if (ppsratecheck(&lastfail, &curfail, 1)) {
1751bd3cf5dSMateusz Guzik 				printf("maxthread limit exceeded by uid %u "
1761bd3cf5dSMateusz Guzik 				"(pid %d); consider increasing kern.maxthread\n",
1771bd3cf5dSMateusz Guzik 				curthread->td_ucred->cr_ruid, curproc->p_pid);
1781bd3cf5dSMateusz Guzik 			}
1791bd3cf5dSMateusz Guzik 			return (-1);
1801bd3cf5dSMateusz Guzik 		}
1811bd3cf5dSMateusz Guzik 	}
1821bd3cf5dSMateusz Guzik 
18335bb59edSMateusz Guzik 	nthreads++;
18435bb59edSMateusz Guzik 	/*
18535bb59edSMateusz Guzik 	 * It is an invariant that the bitmap is big enough to hold maxthread
18635bb59edSMateusz Guzik 	 * IDs. If we got to this point there has to be at least one free.
18735bb59edSMateusz Guzik 	 */
18835bb59edSMateusz Guzik 	if (trytid >= maxthread)
18935bb59edSMateusz Guzik 		trytid = 0;
19035bb59edSMateusz Guzik 	bit_ffc_at(tid_bitmap, trytid, maxthread, &tid);
19135bb59edSMateusz Guzik 	if (tid == -1) {
19235bb59edSMateusz Guzik 		KASSERT(trytid != 0, ("unexpectedly ran out of IDs"));
19335bb59edSMateusz Guzik 		trytid = 0;
19435bb59edSMateusz Guzik 		bit_ffc_at(tid_bitmap, trytid, maxthread, &tid);
19535bb59edSMateusz Guzik 		KASSERT(tid != -1, ("unexpectedly ran out of IDs"));
196ec6ea5e8SDavid Xu 	}
19735bb59edSMateusz Guzik 	bit_set(tid_bitmap, tid);
198934e7e5eSMateusz Guzik 	trytid = tid + 1;
199ec6ea5e8SDavid Xu 	mtx_unlock(&tid_lock);
20035bb59edSMateusz Guzik 	return (tid + NO_PID);
201ec6ea5e8SDavid Xu }
202ec6ea5e8SDavid Xu 
203ec6ea5e8SDavid Xu static void
204*755341dfSMateusz Guzik tid_free_locked(lwpid_t rtid)
205ec6ea5e8SDavid Xu {
20635bb59edSMateusz Guzik 	lwpid_t tid;
207ec6ea5e8SDavid Xu 
208*755341dfSMateusz Guzik 	mtx_assert(&tid_lock, MA_OWNED);
20935bb59edSMateusz Guzik 	KASSERT(rtid >= NO_PID,
21035bb59edSMateusz Guzik 	    ("%s: invalid tid %d\n", __func__, rtid));
21135bb59edSMateusz Guzik 	tid = rtid - NO_PID;
21235bb59edSMateusz Guzik 	KASSERT(bit_test(tid_bitmap, tid) != 0,
21335bb59edSMateusz Guzik 	    ("thread ID %d not allocated\n", rtid));
21435bb59edSMateusz Guzik 	bit_clear(tid_bitmap, tid);
21535bb59edSMateusz Guzik 	nthreads--;
216*755341dfSMateusz Guzik }
217*755341dfSMateusz Guzik 
218*755341dfSMateusz Guzik static void
219*755341dfSMateusz Guzik tid_free(lwpid_t rtid)
220*755341dfSMateusz Guzik {
221*755341dfSMateusz Guzik 
222*755341dfSMateusz Guzik 	mtx_lock(&tid_lock);
223*755341dfSMateusz Guzik 	tid_free_locked(rtid);
224*755341dfSMateusz Guzik 	mtx_unlock(&tid_lock);
225*755341dfSMateusz Guzik }
226*755341dfSMateusz Guzik 
227*755341dfSMateusz Guzik static void
228*755341dfSMateusz Guzik tid_free_batch(lwpid_t *batch, int n)
229*755341dfSMateusz Guzik {
230*755341dfSMateusz Guzik 	int i;
231*755341dfSMateusz Guzik 
232*755341dfSMateusz Guzik 	mtx_lock(&tid_lock);
233*755341dfSMateusz Guzik 	for (i = 0; i < n; i++) {
234*755341dfSMateusz Guzik 		tid_free_locked(batch[i]);
235*755341dfSMateusz Guzik 	}
236ec6ea5e8SDavid Xu 	mtx_unlock(&tid_lock);
237ec6ea5e8SDavid Xu }
238ec6ea5e8SDavid Xu 
239fdcac928SMarcel Moolenaar /*
240696058c3SJulian Elischer  * Prepare a thread for use.
24144990b8cSJulian Elischer  */
242b23f72e9SBrian Feldman static int
243b23f72e9SBrian Feldman thread_ctor(void *mem, int size, void *arg, int flags)
24444990b8cSJulian Elischer {
24544990b8cSJulian Elischer 	struct thread	*td;
24644990b8cSJulian Elischer 
24744990b8cSJulian Elischer 	td = (struct thread *)mem;
24871fad9fdSJulian Elischer 	td->td_state = TDS_INACTIVE;
24994dd54b9SKonstantin Belousov 	td->td_lastcpu = td->td_oncpu = NOCPU;
2506c27c603SJuli Mallett 
2516c27c603SJuli Mallett 	/*
2526c27c603SJuli Mallett 	 * Note that td_critnest begins life as 1 because the thread is not
2536c27c603SJuli Mallett 	 * running and is thereby implicitly waiting to be on the receiving
254a54e85fdSJeff Roberson 	 * end of a context switch.
2556c27c603SJuli Mallett 	 */
256139b7550SJohn Baldwin 	td->td_critnest = 1;
257acbe332aSDavid Xu 	td->td_lend_user_pri = PRI_MAX;
258911b84b0SRobert Watson #ifdef AUDIT
259911b84b0SRobert Watson 	audit_thread_alloc(td);
260911b84b0SRobert Watson #endif
261d10183d9SDavid Xu 	umtx_thread_alloc(td);
262b23f72e9SBrian Feldman 	return (0);
26344990b8cSJulian Elischer }
26444990b8cSJulian Elischer 
26544990b8cSJulian Elischer /*
26644990b8cSJulian Elischer  * Reclaim a thread after use.
26744990b8cSJulian Elischer  */
26844990b8cSJulian Elischer static void
26944990b8cSJulian Elischer thread_dtor(void *mem, int size, void *arg)
27044990b8cSJulian Elischer {
27144990b8cSJulian Elischer 	struct thread *td;
27244990b8cSJulian Elischer 
27344990b8cSJulian Elischer 	td = (struct thread *)mem;
27444990b8cSJulian Elischer 
27544990b8cSJulian Elischer #ifdef INVARIANTS
27644990b8cSJulian Elischer 	/* Verify that this thread is in a safe state to free. */
27744990b8cSJulian Elischer 	switch (td->td_state) {
27871fad9fdSJulian Elischer 	case TDS_INHIBITED:
27971fad9fdSJulian Elischer 	case TDS_RUNNING:
28071fad9fdSJulian Elischer 	case TDS_CAN_RUN:
28144990b8cSJulian Elischer 	case TDS_RUNQ:
28244990b8cSJulian Elischer 		/*
28344990b8cSJulian Elischer 		 * We must never unlink a thread that is in one of
28444990b8cSJulian Elischer 		 * these states, because it is currently active.
28544990b8cSJulian Elischer 		 */
28644990b8cSJulian Elischer 		panic("bad state for thread unlinking");
28744990b8cSJulian Elischer 		/* NOTREACHED */
28871fad9fdSJulian Elischer 	case TDS_INACTIVE:
28944990b8cSJulian Elischer 		break;
29044990b8cSJulian Elischer 	default:
29144990b8cSJulian Elischer 		panic("bad thread state");
29244990b8cSJulian Elischer 		/* NOTREACHED */
29344990b8cSJulian Elischer 	}
29444990b8cSJulian Elischer #endif
2956e8525ceSRobert Watson #ifdef AUDIT
2966e8525ceSRobert Watson 	audit_thread_free(td);
2976e8525ceSRobert Watson #endif
2981ba4a712SPawel Jakub Dawidek 	/* Free all OSD associated to this thread. */
2991ba4a712SPawel Jakub Dawidek 	osd_thread_exit(td);
300aca4bb91SKonstantin Belousov 	td_softdep_cleanup(td);
301aca4bb91SKonstantin Belousov 	MPASS(td->td_su == NULL);
30244990b8cSJulian Elischer }
30344990b8cSJulian Elischer 
30444990b8cSJulian Elischer /*
30544990b8cSJulian Elischer  * Initialize type-stable parts of a thread (when newly created).
30644990b8cSJulian Elischer  */
307b23f72e9SBrian Feldman static int
308b23f72e9SBrian Feldman thread_init(void *mem, int size, int flags)
30944990b8cSJulian Elischer {
31044990b8cSJulian Elischer 	struct thread *td;
31144990b8cSJulian Elischer 
31244990b8cSJulian Elischer 	td = (struct thread *)mem;
313247aba24SMarcel Moolenaar 
31444f3b092SJohn Baldwin 	td->td_sleepqueue = sleepq_alloc();
315961a7b24SJohn Baldwin 	td->td_turnstile = turnstile_alloc();
3168f0e9130SKonstantin Belousov 	td->td_rlqe = NULL;
3172ca45184SMatt Joras 	EVENTHANDLER_DIRECT_INVOKE(thread_init, td);
318d10183d9SDavid Xu 	umtx_thread_init(td);
31989b57fcfSKonstantin Belousov 	td->td_kstack = 0;
320ad8b1d85SKonstantin Belousov 	td->td_sel = NULL;
321b23f72e9SBrian Feldman 	return (0);
32244990b8cSJulian Elischer }
32344990b8cSJulian Elischer 
32444990b8cSJulian Elischer /*
32544990b8cSJulian Elischer  * Tear down type-stable parts of a thread (just before being discarded).
32644990b8cSJulian Elischer  */
32744990b8cSJulian Elischer static void
32844990b8cSJulian Elischer thread_fini(void *mem, int size)
32944990b8cSJulian Elischer {
33044990b8cSJulian Elischer 	struct thread *td;
33144990b8cSJulian Elischer 
33244990b8cSJulian Elischer 	td = (struct thread *)mem;
3332ca45184SMatt Joras 	EVENTHANDLER_DIRECT_INVOKE(thread_fini, td);
3348f0e9130SKonstantin Belousov 	rlqentry_free(td->td_rlqe);
335961a7b24SJohn Baldwin 	turnstile_free(td->td_turnstile);
33644f3b092SJohn Baldwin 	sleepq_free(td->td_sleepqueue);
337d10183d9SDavid Xu 	umtx_thread_fini(td);
338ace8398dSJeff Roberson 	seltdfini(td);
33944990b8cSJulian Elischer }
3405215b187SJeff Roberson 
3415c8329edSJulian Elischer /*
3425215b187SJeff Roberson  * For a newly created process,
3435215b187SJeff Roberson  * link up all the structures and its initial threads etc.
344ed062c8dSJulian Elischer  * called from:
345e7d939bdSMarcel Moolenaar  * {arch}/{arch}/machdep.c   {arch}_init(), init386() etc.
346ed062c8dSJulian Elischer  * proc_dtor() (should go away)
347ed062c8dSJulian Elischer  * proc_init()
3485c8329edSJulian Elischer  */
3495c8329edSJulian Elischer void
35089b57fcfSKonstantin Belousov proc_linkup0(struct proc *p, struct thread *td)
35189b57fcfSKonstantin Belousov {
35289b57fcfSKonstantin Belousov 	TAILQ_INIT(&p->p_threads);	     /* all threads in proc */
35389b57fcfSKonstantin Belousov 	proc_linkup(p, td);
35489b57fcfSKonstantin Belousov }
35589b57fcfSKonstantin Belousov 
35689b57fcfSKonstantin Belousov void
3578460a577SJohn Birrell proc_linkup(struct proc *p, struct thread *td)
3585c8329edSJulian Elischer {
359a54e85fdSJeff Roberson 
3609104847fSDavid Xu 	sigqueue_init(&p->p_sigqueue, p);
361ebceaf6dSDavid Xu 	p->p_ksi = ksiginfo_alloc(1);
362ebceaf6dSDavid Xu 	if (p->p_ksi != NULL) {
3635c474517SDavid Xu 		/* XXX p_ksi may be null if ksiginfo zone is not ready */
364ebceaf6dSDavid Xu 		p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
365ebceaf6dSDavid Xu 	}
366b2f92ef9SDavid Xu 	LIST_INIT(&p->p_mqnotifier);
3675c8329edSJulian Elischer 	p->p_numthreads = 0;
3688460a577SJohn Birrell 	thread_link(td, p);
3695c8329edSJulian Elischer }
3705c8329edSJulian Elischer 
3711bd3cf5dSMateusz Guzik extern int max_threads_per_proc;
3721bd3cf5dSMateusz Guzik 
3735c8329edSJulian Elischer /*
37444990b8cSJulian Elischer  * Initialize global thread allocation resources.
37544990b8cSJulian Elischer  */
37644990b8cSJulian Elischer void
37744990b8cSJulian Elischer threadinit(void)
37844990b8cSJulian Elischer {
37926007fe3SMateusz Guzik 	u_long i;
380cf31cadeSMateusz Guzik 	lwpid_t tid0;
3815aa5420fSMark Johnston 	uint32_t flags;
38244990b8cSJulian Elischer 
3831bd3cf5dSMateusz Guzik 	/*
3841bd3cf5dSMateusz Guzik 	 * Place an upper limit on threads which can be allocated.
3851bd3cf5dSMateusz Guzik 	 *
3861bd3cf5dSMateusz Guzik 	 * Note that other factors may make the de facto limit much lower.
3871bd3cf5dSMateusz Guzik 	 *
3881bd3cf5dSMateusz Guzik 	 * Platform limits are somewhat arbitrary but deemed "more than good
3891bd3cf5dSMateusz Guzik 	 * enough" for the foreseable future.
3901bd3cf5dSMateusz Guzik 	 */
3911bd3cf5dSMateusz Guzik 	if (maxthread == 0) {
3921bd3cf5dSMateusz Guzik #ifdef _LP64
3931bd3cf5dSMateusz Guzik 		maxthread = MIN(maxproc * max_threads_per_proc, 1000000);
3941bd3cf5dSMateusz Guzik #else
3951bd3cf5dSMateusz Guzik 		maxthread = MIN(maxproc * max_threads_per_proc, 100000);
3961bd3cf5dSMateusz Guzik #endif
3971bd3cf5dSMateusz Guzik 	}
3981bd3cf5dSMateusz Guzik 
3991ea7a6f8SPoul-Henning Kamp 	mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
40035bb59edSMateusz Guzik 	tid_bitmap = bit_alloc(maxthread, M_TIDHASH, M_WAITOK);
401cf31cadeSMateusz Guzik 	tid0 = tid_alloc();
402cf31cadeSMateusz Guzik 	if (tid0 != THREAD0_TID)
403cf31cadeSMateusz Guzik 		panic("tid0 %d != %d\n", tid0, THREAD0_TID);
4041ea7a6f8SPoul-Henning Kamp 
4055aa5420fSMark Johnston 	flags = UMA_ZONE_NOFREE;
4065aa5420fSMark Johnston #ifdef __aarch64__
4075aa5420fSMark Johnston 	/*
4085aa5420fSMark Johnston 	 * Force thread structures to be allocated from the direct map.
4095aa5420fSMark Johnston 	 * Otherwise, superpage promotions and demotions may temporarily
4105aa5420fSMark Johnston 	 * invalidate thread structure mappings.  For most dynamically allocated
4115aa5420fSMark Johnston 	 * structures this is not a problem, but translation faults cannot be
4125aa5420fSMark Johnston 	 * handled without accessing curthread.
4135aa5420fSMark Johnston 	 */
4145aa5420fSMark Johnston 	flags |= UMA_ZONE_CONTIG;
4155aa5420fSMark Johnston #endif
416de028f5aSJeff Roberson 	thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
41744990b8cSJulian Elischer 	    thread_ctor, thread_dtor, thread_init, thread_fini,
4185aa5420fSMark Johnston 	    32 - 1, flags);
419cf7d9a8cSDavid Xu 	tidhashtbl = hashinit(maxproc / 2, M_TIDHASH, &tidhash);
42026007fe3SMateusz Guzik 	tidhashlock = (tidhash + 1) / 64;
42126007fe3SMateusz Guzik 	if (tidhashlock > 0)
42226007fe3SMateusz Guzik 		tidhashlock--;
42326007fe3SMateusz Guzik 	tidhashtbl_lock = malloc(sizeof(*tidhashtbl_lock) * (tidhashlock + 1),
42426007fe3SMateusz Guzik 	    M_TIDHASH, M_WAITOK | M_ZERO);
42526007fe3SMateusz Guzik 	for (i = 0; i < tidhashlock + 1; i++)
42626007fe3SMateusz Guzik 		rw_init(&tidhashtbl_lock[i], "tidhash");
42744990b8cSJulian Elischer }
42844990b8cSJulian Elischer 
42944990b8cSJulian Elischer /*
430ff8fbcffSJeff Roberson  * Place an unused thread on the zombie list.
43144990b8cSJulian Elischer  */
43244990b8cSJulian Elischer void
433ff8fbcffSJeff Roberson thread_zombie(struct thread *td)
43444990b8cSJulian Elischer {
435c5315f51SMateusz Guzik 	struct thread *ztd;
436c5315f51SMateusz Guzik 
437c5315f51SMateusz Guzik 	ztd = atomic_load_ptr(&thread_zombies);
438c5315f51SMateusz Guzik 	for (;;) {
439c5315f51SMateusz Guzik 		td->td_zombie = ztd;
440c5315f51SMateusz Guzik 		if (atomic_fcmpset_rel_ptr((uintptr_t *)&thread_zombies,
441c5315f51SMateusz Guzik 		    (uintptr_t *)&ztd, (uintptr_t)td))
442c5315f51SMateusz Guzik 			break;
443c5315f51SMateusz Guzik 		continue;
444c5315f51SMateusz Guzik 	}
44544990b8cSJulian Elischer }
44644990b8cSJulian Elischer 
4475c8329edSJulian Elischer /*
448ff8fbcffSJeff Roberson  * Release a thread that has exited after cpu_throw().
449ff8fbcffSJeff Roberson  */
450ff8fbcffSJeff Roberson void
451ff8fbcffSJeff Roberson thread_stash(struct thread *td)
452ff8fbcffSJeff Roberson {
453ff8fbcffSJeff Roberson 	atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
454ff8fbcffSJeff Roberson 	thread_zombie(td);
455ff8fbcffSJeff Roberson }
456ff8fbcffSJeff Roberson 
457ff8fbcffSJeff Roberson /*
458c5315f51SMateusz Guzik  * Reap zombie threads.
45944990b8cSJulian Elischer  */
46044990b8cSJulian Elischer void
46144990b8cSJulian Elischer thread_reap(void)
46244990b8cSJulian Elischer {
463c5315f51SMateusz Guzik 	struct thread *itd, *ntd;
464*755341dfSMateusz Guzik 	lwpid_t tidbatch[16];
465*755341dfSMateusz Guzik 	int tidbatchn;
46644990b8cSJulian Elischer 
46744990b8cSJulian Elischer 	/*
468c5315f51SMateusz Guzik 	 * Reading upfront is pessimal if followed by concurrent atomic_swap,
469c5315f51SMateusz Guzik 	 * but most of the time the list is empty.
47044990b8cSJulian Elischer 	 */
471c5315f51SMateusz Guzik 	if (thread_zombies == NULL)
472c5315f51SMateusz Guzik 		return;
473c5315f51SMateusz Guzik 
474c5315f51SMateusz Guzik 	itd = (struct thread *)atomic_swap_ptr((uintptr_t *)&thread_zombies,
475c5315f51SMateusz Guzik 	    (uintptr_t)NULL);
476*755341dfSMateusz Guzik 	tidbatchn = 0;
477c5315f51SMateusz Guzik 	while (itd != NULL) {
478c5315f51SMateusz Guzik 		ntd = itd->td_zombie;
479*755341dfSMateusz Guzik 		tidbatch[tidbatchn] = itd->td_tid;
480*755341dfSMateusz Guzik 		tidbatchn++;
481c5315f51SMateusz Guzik 		thread_cow_free(itd);
482*755341dfSMateusz Guzik 		thread_free_batched(itd);
483*755341dfSMateusz Guzik 		if (tidbatchn == nitems(tidbatch)) {
484*755341dfSMateusz Guzik 			tid_free_batch(tidbatch, tidbatchn);
485*755341dfSMateusz Guzik 			tidbatchn = 0;
486*755341dfSMateusz Guzik 		}
487c5315f51SMateusz Guzik 		itd = ntd;
48844990b8cSJulian Elischer 	}
489*755341dfSMateusz Guzik 
490*755341dfSMateusz Guzik 	if (tidbatchn != 0) {
491*755341dfSMateusz Guzik 		tid_free_batch(tidbatch, tidbatchn);
492*755341dfSMateusz Guzik 	}
493ed062c8dSJulian Elischer }
49444990b8cSJulian Elischer 
4954f0db5e0SJulian Elischer /*
49644990b8cSJulian Elischer  * Allocate a thread.
49744990b8cSJulian Elischer  */
49844990b8cSJulian Elischer struct thread *
4998a945d10SKonstantin Belousov thread_alloc(int pages)
50044990b8cSJulian Elischer {
50189b57fcfSKonstantin Belousov 	struct thread *td;
5021bd3cf5dSMateusz Guzik 	lwpid_t tid;
5038460a577SJohn Birrell 
50444990b8cSJulian Elischer 	thread_reap(); /* check if any zombies to get */
50589b57fcfSKonstantin Belousov 
5061bd3cf5dSMateusz Guzik 	tid = tid_alloc();
5071bd3cf5dSMateusz Guzik 	if (tid == -1) {
5081bd3cf5dSMateusz Guzik 		return (NULL);
5091bd3cf5dSMateusz Guzik 	}
5101bd3cf5dSMateusz Guzik 
5111bd3cf5dSMateusz Guzik 	td = uma_zalloc(thread_zone, M_WAITOK);
51289b57fcfSKonstantin Belousov 	KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
5138a945d10SKonstantin Belousov 	if (!vm_thread_new(td, pages)) {
51489b57fcfSKonstantin Belousov 		uma_zfree(thread_zone, td);
5151bd3cf5dSMateusz Guzik 		tid_free(tid);
51689b57fcfSKonstantin Belousov 		return (NULL);
51789b57fcfSKonstantin Belousov 	}
5181bd3cf5dSMateusz Guzik 	td->td_tid = tid;
5190c3967e7SMarcel Moolenaar 	cpu_thread_alloc(td);
5201bd3cf5dSMateusz Guzik 	EVENTHANDLER_DIRECT_INVOKE(thread_ctor, td);
52189b57fcfSKonstantin Belousov 	return (td);
52244990b8cSJulian Elischer }
52344990b8cSJulian Elischer 
5248a945d10SKonstantin Belousov int
5258a945d10SKonstantin Belousov thread_alloc_stack(struct thread *td, int pages)
5268a945d10SKonstantin Belousov {
5278a945d10SKonstantin Belousov 
5288a945d10SKonstantin Belousov 	KASSERT(td->td_kstack == 0,
5298a945d10SKonstantin Belousov 	    ("thread_alloc_stack called on a thread with kstack"));
5308a945d10SKonstantin Belousov 	if (!vm_thread_new(td, pages))
5318a945d10SKonstantin Belousov 		return (0);
5328a945d10SKonstantin Belousov 	cpu_thread_alloc(td);
5338a945d10SKonstantin Belousov 	return (1);
5348a945d10SKonstantin Belousov }
5354f0db5e0SJulian Elischer 
5364f0db5e0SJulian Elischer /*
53744990b8cSJulian Elischer  * Deallocate a thread.
53844990b8cSJulian Elischer  */
539*755341dfSMateusz Guzik static void
540*755341dfSMateusz Guzik thread_free_batched(struct thread *td)
54144990b8cSJulian Elischer {
5422e6b8de4SJeff Roberson 
5431bd3cf5dSMateusz Guzik 	EVENTHANDLER_DIRECT_INVOKE(thread_dtor, td);
5442e6b8de4SJeff Roberson 	lock_profile_thread_exit(td);
54545aea8deSJeff Roberson 	if (td->td_cpuset)
546d7f687fcSJeff Roberson 		cpuset_rel(td->td_cpuset);
547d7f687fcSJeff Roberson 	td->td_cpuset = NULL;
5480c3967e7SMarcel Moolenaar 	cpu_thread_free(td);
54989b57fcfSKonstantin Belousov 	if (td->td_kstack != 0)
55089b57fcfSKonstantin Belousov 		vm_thread_dispose(td);
5512d19b736SKonstantin Belousov 	callout_drain(&td->td_slpcallout);
552*755341dfSMateusz Guzik 	/*
553*755341dfSMateusz Guzik 	 * Freeing handled by the caller.
554*755341dfSMateusz Guzik 	 */
5551bd3cf5dSMateusz Guzik 	td->td_tid = -1;
55644990b8cSJulian Elischer 	uma_zfree(thread_zone, td);
55744990b8cSJulian Elischer }
55844990b8cSJulian Elischer 
5594ea6a9a2SMateusz Guzik void
560*755341dfSMateusz Guzik thread_free(struct thread *td)
561*755341dfSMateusz Guzik {
562*755341dfSMateusz Guzik 	lwpid_t tid;
563*755341dfSMateusz Guzik 
564*755341dfSMateusz Guzik 	tid = td->td_tid;
565*755341dfSMateusz Guzik 	thread_free_batched(td);
566*755341dfSMateusz Guzik 	tid_free(tid);
567*755341dfSMateusz Guzik }
568*755341dfSMateusz Guzik 
569*755341dfSMateusz Guzik void
5704ea6a9a2SMateusz Guzik thread_cow_get_proc(struct thread *newtd, struct proc *p)
5714ea6a9a2SMateusz Guzik {
5724ea6a9a2SMateusz Guzik 
5734ea6a9a2SMateusz Guzik 	PROC_LOCK_ASSERT(p, MA_OWNED);
5741724c563SMateusz Guzik 	newtd->td_realucred = crcowget(p->p_ucred);
5751724c563SMateusz Guzik 	newtd->td_ucred = newtd->td_realucred;
576f6f6d240SMateusz Guzik 	newtd->td_limit = lim_hold(p->p_limit);
5774ea6a9a2SMateusz Guzik 	newtd->td_cowgen = p->p_cowgen;
5784ea6a9a2SMateusz Guzik }
5794ea6a9a2SMateusz Guzik 
5804ea6a9a2SMateusz Guzik void
5814ea6a9a2SMateusz Guzik thread_cow_get(struct thread *newtd, struct thread *td)
5824ea6a9a2SMateusz Guzik {
5834ea6a9a2SMateusz Guzik 
5841724c563SMateusz Guzik 	MPASS(td->td_realucred == td->td_ucred);
5851724c563SMateusz Guzik 	newtd->td_realucred = crcowget(td->td_realucred);
5861724c563SMateusz Guzik 	newtd->td_ucred = newtd->td_realucred;
587f6f6d240SMateusz Guzik 	newtd->td_limit = lim_hold(td->td_limit);
5884ea6a9a2SMateusz Guzik 	newtd->td_cowgen = td->td_cowgen;
5894ea6a9a2SMateusz Guzik }
5904ea6a9a2SMateusz Guzik 
5914ea6a9a2SMateusz Guzik void
5924ea6a9a2SMateusz Guzik thread_cow_free(struct thread *td)
5934ea6a9a2SMateusz Guzik {
5944ea6a9a2SMateusz Guzik 
5951724c563SMateusz Guzik 	if (td->td_realucred != NULL)
5961724c563SMateusz Guzik 		crcowfree(td);
597cd672ca6SMateusz Guzik 	if (td->td_limit != NULL)
598f6f6d240SMateusz Guzik 		lim_free(td->td_limit);
5994ea6a9a2SMateusz Guzik }
6004ea6a9a2SMateusz Guzik 
6014ea6a9a2SMateusz Guzik void
6024ea6a9a2SMateusz Guzik thread_cow_update(struct thread *td)
6034ea6a9a2SMateusz Guzik {
6044ea6a9a2SMateusz Guzik 	struct proc *p;
605cd672ca6SMateusz Guzik 	struct ucred *oldcred;
606cd672ca6SMateusz Guzik 	struct plimit *oldlimit;
6074ea6a9a2SMateusz Guzik 
6084ea6a9a2SMateusz Guzik 	p = td->td_proc;
609cd672ca6SMateusz Guzik 	oldlimit = NULL;
6104ea6a9a2SMateusz Guzik 	PROC_LOCK(p);
6111724c563SMateusz Guzik 	oldcred = crcowsync();
612cd672ca6SMateusz Guzik 	if (td->td_limit != p->p_limit) {
613cd672ca6SMateusz Guzik 		oldlimit = td->td_limit;
614cd672ca6SMateusz Guzik 		td->td_limit = lim_hold(p->p_limit);
615cd672ca6SMateusz Guzik 	}
6164ea6a9a2SMateusz Guzik 	td->td_cowgen = p->p_cowgen;
6174ea6a9a2SMateusz Guzik 	PROC_UNLOCK(p);
618cd672ca6SMateusz Guzik 	if (oldcred != NULL)
619cd672ca6SMateusz Guzik 		crfree(oldcred);
620cd672ca6SMateusz Guzik 	if (oldlimit != NULL)
621cd672ca6SMateusz Guzik 		lim_free(oldlimit);
6224ea6a9a2SMateusz Guzik }
6234ea6a9a2SMateusz Guzik 
62444990b8cSJulian Elischer /*
62544990b8cSJulian Elischer  * Discard the current thread and exit from its context.
62694e0a4cdSJulian Elischer  * Always called with scheduler locked.
62744990b8cSJulian Elischer  *
62844990b8cSJulian Elischer  * Because we can't free a thread while we're operating under its context,
629696058c3SJulian Elischer  * push the current thread into our CPU's deadthread holder. This means
630696058c3SJulian Elischer  * we needn't worry about someone else grabbing our context before we
6316617724cSJeff Roberson  * do a cpu_throw().
63244990b8cSJulian Elischer  */
63344990b8cSJulian Elischer void
63444990b8cSJulian Elischer thread_exit(void)
63544990b8cSJulian Elischer {
6367e3a96eaSJohn Baldwin 	uint64_t runtime, new_switchtime;
63744990b8cSJulian Elischer 	struct thread *td;
6381c4bcd05SJeff Roberson 	struct thread *td2;
63944990b8cSJulian Elischer 	struct proc *p;
6407847a9daSJohn Baldwin 	int wakeup_swapper;
64144990b8cSJulian Elischer 
64244990b8cSJulian Elischer 	td = curthread;
64344990b8cSJulian Elischer 	p = td->td_proc;
64444990b8cSJulian Elischer 
645a54e85fdSJeff Roberson 	PROC_SLOCK_ASSERT(p, MA_OWNED);
646ed062c8dSJulian Elischer 	mtx_assert(&Giant, MA_NOTOWNED);
647a54e85fdSJeff Roberson 
64844990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
649ed062c8dSJulian Elischer 	KASSERT(p != NULL, ("thread exiting without a process"));
650cc701b73SRobert Watson 	CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
651e01eafefSJulian Elischer 	    (long)p->p_pid, td->td_name);
6526c9271a9SAndriy Gapon 	SDT_PROBE0(proc, , , lwp__exit);
6539104847fSDavid Xu 	KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
654936c24faSMateusz Guzik 	MPASS(td->td_realucred == td->td_ucred);
65544990b8cSJulian Elischer 
656ed062c8dSJulian Elischer 	/*
657ed062c8dSJulian Elischer 	 * drop FPU & debug register state storage, or any other
658ed062c8dSJulian Elischer 	 * architecture specific resources that
659ed062c8dSJulian Elischer 	 * would not be on a new untouched process.
660ed062c8dSJulian Elischer 	 */
661bd07998eSKonstantin Belousov 	cpu_thread_exit(td);
66244990b8cSJulian Elischer 
663ed062c8dSJulian Elischer 	/*
6641faf202eSJulian Elischer 	 * The last thread is left attached to the process
6651faf202eSJulian Elischer 	 * So that the whole bundle gets recycled. Skip
666ed062c8dSJulian Elischer 	 * all this stuff if we never had threads.
667ed062c8dSJulian Elischer 	 * EXIT clears all sign of other threads when
668ed062c8dSJulian Elischer 	 * it goes to single threading, so the last thread always
669ed062c8dSJulian Elischer 	 * takes the short path.
6701faf202eSJulian Elischer 	 */
671ed062c8dSJulian Elischer 	if (p->p_flag & P_HADTHREADS) {
6721faf202eSJulian Elischer 		if (p->p_numthreads > 1) {
673fd229b5bSKonstantin Belousov 			atomic_add_int(&td->td_proc->p_exitthreads, 1);
674d3a0bd78SJulian Elischer 			thread_unlink(td);
6751c4bcd05SJeff Roberson 			td2 = FIRST_THREAD_IN_PROC(p);
6761c4bcd05SJeff Roberson 			sched_exit_thread(td2, td);
677ed062c8dSJulian Elischer 
678ed062c8dSJulian Elischer 			/*
67944990b8cSJulian Elischer 			 * The test below is NOT true if we are the
6809182554aSKonstantin Belousov 			 * sole exiting thread. P_STOPPED_SINGLE is unset
68144990b8cSJulian Elischer 			 * in exit1() after it is the only survivor.
68244990b8cSJulian Elischer 			 */
6831279572aSDavid Xu 			if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
68444990b8cSJulian Elischer 				if (p->p_numthreads == p->p_suspcount) {
685a54e85fdSJeff Roberson 					thread_lock(p->p_singlethread);
6867847a9daSJohn Baldwin 					wakeup_swapper = thread_unsuspend_one(
68784cdea97SKonstantin Belousov 						p->p_singlethread, p, false);
6887847a9daSJohn Baldwin 					if (wakeup_swapper)
6897847a9daSJohn Baldwin 						kick_proc0();
69044990b8cSJulian Elischer 				}
69144990b8cSJulian Elischer 			}
69248bfcdddSJulian Elischer 
693696058c3SJulian Elischer 			PCPU_SET(deadthread, td);
6941faf202eSJulian Elischer 		} else {
695ed062c8dSJulian Elischer 			/*
696ed062c8dSJulian Elischer 			 * The last thread is exiting.. but not through exit()
697ed062c8dSJulian Elischer 			 */
698ed062c8dSJulian Elischer 			panic ("thread_exit: Last thread exiting on its own");
699ed062c8dSJulian Elischer 		}
7001faf202eSJulian Elischer 	}
70116d95d4fSJoseph Koshy #ifdef	HWPMC_HOOKS
70216d95d4fSJoseph Koshy 	/*
70316d95d4fSJoseph Koshy 	 * If this thread is part of a process that is being tracked by hwpmc(4),
70416d95d4fSJoseph Koshy 	 * inform the module of the thread's impending exit.
70516d95d4fSJoseph Koshy 	 */
7066161b98cSMatt Macy 	if (PMC_PROC_IS_USING_PMCS(td->td_proc)) {
70716d95d4fSJoseph Koshy 		PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
7086161b98cSMatt Macy 		PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT, NULL);
709ebfaf69cSMatt Macy 	} else if (PMC_SYSTEM_SAMPLING_ACTIVE())
710ebfaf69cSMatt Macy 		PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT_LOG, NULL);
71116d95d4fSJoseph Koshy #endif
712a54e85fdSJeff Roberson 	PROC_UNLOCK(p);
7135c7bebf9SKonstantin Belousov 	PROC_STATLOCK(p);
7145c7bebf9SKonstantin Belousov 	thread_lock(td);
7155c7bebf9SKonstantin Belousov 	PROC_SUNLOCK(p);
7167e3a96eaSJohn Baldwin 
7177e3a96eaSJohn Baldwin 	/* Do the same timestamp bookkeeping that mi_switch() would do. */
7187e3a96eaSJohn Baldwin 	new_switchtime = cpu_ticks();
7197e3a96eaSJohn Baldwin 	runtime = new_switchtime - PCPU_GET(switchtime);
7207e3a96eaSJohn Baldwin 	td->td_runtime += runtime;
7217e3a96eaSJohn Baldwin 	td->td_incruntime += runtime;
7227e3a96eaSJohn Baldwin 	PCPU_SET(switchtime, new_switchtime);
7237e3a96eaSJohn Baldwin 	PCPU_SET(switchticks, ticks);
72483c9dea1SGleb Smirnoff 	VM_CNT_INC(v_swtch);
7257e3a96eaSJohn Baldwin 
7267e3a96eaSJohn Baldwin 	/* Save our resource usage in our process. */
7277e3a96eaSJohn Baldwin 	td->td_ru.ru_nvcsw++;
72861a74c5cSJeff Roberson 	ruxagg_locked(p, td);
7297e3a96eaSJohn Baldwin 	rucollect(&p->p_ru, &td->td_ru);
7305c7bebf9SKonstantin Belousov 	PROC_STATUNLOCK(p);
7317e3a96eaSJohn Baldwin 
732dcc9954eSJulian Elischer 	td->td_state = TDS_INACTIVE;
7333d06b4b3SAttilio Rao #ifdef WITNESS
7343d06b4b3SAttilio Rao 	witness_thread_exit(td);
7353d06b4b3SAttilio Rao #endif
736732d9528SJulian Elischer 	CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
737a54e85fdSJeff Roberson 	sched_throw(td);
738cc66ebe2SPeter Wemm 	panic("I'm a teapot!");
73944990b8cSJulian Elischer 	/* NOTREACHED */
74044990b8cSJulian Elischer }
74144990b8cSJulian Elischer 
74244990b8cSJulian Elischer /*
743696058c3SJulian Elischer  * Do any thread specific cleanups that may be needed in wait()
74437814395SPeter Wemm  * called with Giant, proc and schedlock not held.
745696058c3SJulian Elischer  */
746696058c3SJulian Elischer void
747696058c3SJulian Elischer thread_wait(struct proc *p)
748696058c3SJulian Elischer {
749696058c3SJulian Elischer 	struct thread *td;
750696058c3SJulian Elischer 
75137814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
752624bf9e1SKonstantin Belousov 	KASSERT(p->p_numthreads == 1, ("multiple threads in thread_wait()"));
753624bf9e1SKonstantin Belousov 	KASSERT(p->p_exitthreads == 0, ("p_exitthreads leaking"));
754ff8fbcffSJeff Roberson 	td = FIRST_THREAD_IN_PROC(p);
755ff8fbcffSJeff Roberson 	/* Lock the last thread so we spin until it exits cpu_throw(). */
756ff8fbcffSJeff Roberson 	thread_lock(td);
757ff8fbcffSJeff Roberson 	thread_unlock(td);
7582e6b8de4SJeff Roberson 	lock_profile_thread_exit(td);
759d7f687fcSJeff Roberson 	cpuset_rel(td->td_cpuset);
760d7f687fcSJeff Roberson 	td->td_cpuset = NULL;
761696058c3SJulian Elischer 	cpu_thread_clean(td);
7624ea6a9a2SMateusz Guzik 	thread_cow_free(td);
7632d19b736SKonstantin Belousov 	callout_drain(&td->td_slpcallout);
764696058c3SJulian Elischer 	thread_reap();	/* check for zombie threads etc. */
765696058c3SJulian Elischer }
766696058c3SJulian Elischer 
767696058c3SJulian Elischer /*
76844990b8cSJulian Elischer  * Link a thread to a process.
7691faf202eSJulian Elischer  * set up anything that needs to be initialized for it to
7701faf202eSJulian Elischer  * be used by the process.
77144990b8cSJulian Elischer  */
77244990b8cSJulian Elischer void
7738460a577SJohn Birrell thread_link(struct thread *td, struct proc *p)
77444990b8cSJulian Elischer {
77544990b8cSJulian Elischer 
776a54e85fdSJeff Roberson 	/*
777a54e85fdSJeff Roberson 	 * XXX This can't be enabled because it's called for proc0 before
778374ae2a3SJeff Roberson 	 * its lock has been created.
779374ae2a3SJeff Roberson 	 * PROC_LOCK_ASSERT(p, MA_OWNED);
780a54e85fdSJeff Roberson 	 */
78171fad9fdSJulian Elischer 	td->td_state    = TDS_INACTIVE;
78244990b8cSJulian Elischer 	td->td_proc     = p;
783b61ce5b0SJeff Roberson 	td->td_flags    = TDF_INMEM;
78444990b8cSJulian Elischer 
7851faf202eSJulian Elischer 	LIST_INIT(&td->td_contested);
786eea4f254SJeff Roberson 	LIST_INIT(&td->td_lprof[0]);
787eea4f254SJeff Roberson 	LIST_INIT(&td->td_lprof[1]);
788f6eccf96SGleb Smirnoff #ifdef EPOCH_TRACE
789dd902d01SGleb Smirnoff 	SLIST_INIT(&td->td_epochs);
790f6eccf96SGleb Smirnoff #endif
7919104847fSDavid Xu 	sigqueue_init(&td->td_sigqueue, p);
792fd90e2edSJung-uk Kim 	callout_init(&td->td_slpcallout, 1);
79366d8df9dSDaniel Eischen 	TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
79444990b8cSJulian Elischer 	p->p_numthreads++;
79544990b8cSJulian Elischer }
79644990b8cSJulian Elischer 
797ed062c8dSJulian Elischer /*
798ed062c8dSJulian Elischer  * Called from:
799ed062c8dSJulian Elischer  *  thread_exit()
800ed062c8dSJulian Elischer  */
801d3a0bd78SJulian Elischer void
802d3a0bd78SJulian Elischer thread_unlink(struct thread *td)
803d3a0bd78SJulian Elischer {
804d3a0bd78SJulian Elischer 	struct proc *p = td->td_proc;
805d3a0bd78SJulian Elischer 
806374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
807f6eccf96SGleb Smirnoff #ifdef EPOCH_TRACE
808dd902d01SGleb Smirnoff 	MPASS(SLIST_EMPTY(&td->td_epochs));
809f6eccf96SGleb Smirnoff #endif
810dd902d01SGleb Smirnoff 
811d3a0bd78SJulian Elischer 	TAILQ_REMOVE(&p->p_threads, td, td_plist);
812d3a0bd78SJulian Elischer 	p->p_numthreads--;
813d3a0bd78SJulian Elischer 	/* could clear a few other things here */
8148460a577SJohn Birrell 	/* Must  NOT clear links to proc! */
8155c8329edSJulian Elischer }
8165c8329edSJulian Elischer 
81779799053SKonstantin Belousov static int
81879799053SKonstantin Belousov calc_remaining(struct proc *p, int mode)
81979799053SKonstantin Belousov {
82079799053SKonstantin Belousov 	int remaining;
82179799053SKonstantin Belousov 
8227b519077SKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
8237b519077SKonstantin Belousov 	PROC_SLOCK_ASSERT(p, MA_OWNED);
82479799053SKonstantin Belousov 	if (mode == SINGLE_EXIT)
82579799053SKonstantin Belousov 		remaining = p->p_numthreads;
82679799053SKonstantin Belousov 	else if (mode == SINGLE_BOUNDARY)
82779799053SKonstantin Belousov 		remaining = p->p_numthreads - p->p_boundary_count;
8286ddcc233SKonstantin Belousov 	else if (mode == SINGLE_NO_EXIT || mode == SINGLE_ALLPROC)
82979799053SKonstantin Belousov 		remaining = p->p_numthreads - p->p_suspcount;
83079799053SKonstantin Belousov 	else
83179799053SKonstantin Belousov 		panic("calc_remaining: wrong mode %d", mode);
83279799053SKonstantin Belousov 	return (remaining);
83379799053SKonstantin Belousov }
83479799053SKonstantin Belousov 
83507a9368aSKonstantin Belousov static int
83607a9368aSKonstantin Belousov remain_for_mode(int mode)
83707a9368aSKonstantin Belousov {
83807a9368aSKonstantin Belousov 
8396ddcc233SKonstantin Belousov 	return (mode == SINGLE_ALLPROC ? 0 : 1);
84007a9368aSKonstantin Belousov }
84107a9368aSKonstantin Belousov 
84207a9368aSKonstantin Belousov static int
84307a9368aSKonstantin Belousov weed_inhib(int mode, struct thread *td2, struct proc *p)
84407a9368aSKonstantin Belousov {
84507a9368aSKonstantin Belousov 	int wakeup_swapper;
84607a9368aSKonstantin Belousov 
84707a9368aSKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
84807a9368aSKonstantin Belousov 	PROC_SLOCK_ASSERT(p, MA_OWNED);
84907a9368aSKonstantin Belousov 	THREAD_LOCK_ASSERT(td2, MA_OWNED);
85007a9368aSKonstantin Belousov 
85107a9368aSKonstantin Belousov 	wakeup_swapper = 0;
85261a74c5cSJeff Roberson 
85361a74c5cSJeff Roberson 	/*
85461a74c5cSJeff Roberson 	 * Since the thread lock is dropped by the scheduler we have
85561a74c5cSJeff Roberson 	 * to retry to check for races.
85661a74c5cSJeff Roberson 	 */
85761a74c5cSJeff Roberson restart:
85807a9368aSKonstantin Belousov 	switch (mode) {
85907a9368aSKonstantin Belousov 	case SINGLE_EXIT:
86061a74c5cSJeff Roberson 		if (TD_IS_SUSPENDED(td2)) {
86184cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, true);
86261a74c5cSJeff Roberson 			thread_lock(td2);
86361a74c5cSJeff Roberson 			goto restart;
86461a74c5cSJeff Roberson 		}
86561a74c5cSJeff Roberson 		if (TD_CAN_ABORT(td2)) {
86607a9368aSKonstantin Belousov 			wakeup_swapper |= sleepq_abort(td2, EINTR);
86761a74c5cSJeff Roberson 			return (wakeup_swapper);
86861a74c5cSJeff Roberson 		}
86907a9368aSKonstantin Belousov 		break;
87007a9368aSKonstantin Belousov 	case SINGLE_BOUNDARY:
87107a9368aSKonstantin Belousov 	case SINGLE_NO_EXIT:
87261a74c5cSJeff Roberson 		if (TD_IS_SUSPENDED(td2) &&
87361a74c5cSJeff Roberson 		    (td2->td_flags & TDF_BOUNDARY) == 0) {
87484cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
87561a74c5cSJeff Roberson 			thread_lock(td2);
87661a74c5cSJeff Roberson 			goto restart;
87761a74c5cSJeff Roberson 		}
87861a74c5cSJeff Roberson 		if (TD_CAN_ABORT(td2)) {
87907a9368aSKonstantin Belousov 			wakeup_swapper |= sleepq_abort(td2, ERESTART);
88061a74c5cSJeff Roberson 			return (wakeup_swapper);
88161a74c5cSJeff Roberson 		}
882917dd390SKonstantin Belousov 		break;
8836ddcc233SKonstantin Belousov 	case SINGLE_ALLPROC:
8846ddcc233SKonstantin Belousov 		/*
8856ddcc233SKonstantin Belousov 		 * ALLPROC suspend tries to avoid spurious EINTR for
8866ddcc233SKonstantin Belousov 		 * threads sleeping interruptable, by suspending the
8876ddcc233SKonstantin Belousov 		 * thread directly, similarly to sig_suspend_threads().
8886ddcc233SKonstantin Belousov 		 * Since such sleep is not performed at the user
8896ddcc233SKonstantin Belousov 		 * boundary, TDF_BOUNDARY flag is not set, and TDF_ALLPROCSUSP
8906ddcc233SKonstantin Belousov 		 * is used to avoid immediate un-suspend.
8916ddcc233SKonstantin Belousov 		 */
8926ddcc233SKonstantin Belousov 		if (TD_IS_SUSPENDED(td2) && (td2->td_flags & (TDF_BOUNDARY |
89361a74c5cSJeff Roberson 		    TDF_ALLPROCSUSP)) == 0) {
89484cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
89561a74c5cSJeff Roberson 			thread_lock(td2);
89661a74c5cSJeff Roberson 			goto restart;
89761a74c5cSJeff Roberson 		}
89861a74c5cSJeff Roberson 		if (TD_CAN_ABORT(td2)) {
8996ddcc233SKonstantin Belousov 			if ((td2->td_flags & TDF_SBDRY) == 0) {
9006ddcc233SKonstantin Belousov 				thread_suspend_one(td2);
9016ddcc233SKonstantin Belousov 				td2->td_flags |= TDF_ALLPROCSUSP;
9026ddcc233SKonstantin Belousov 			} else {
9036ddcc233SKonstantin Belousov 				wakeup_swapper |= sleepq_abort(td2, ERESTART);
90461a74c5cSJeff Roberson 				return (wakeup_swapper);
9056ddcc233SKonstantin Belousov 			}
9066ddcc233SKonstantin Belousov 		}
90707a9368aSKonstantin Belousov 		break;
90861a74c5cSJeff Roberson 	default:
90961a74c5cSJeff Roberson 		break;
91007a9368aSKonstantin Belousov 	}
91161a74c5cSJeff Roberson 	thread_unlock(td2);
91207a9368aSKonstantin Belousov 	return (wakeup_swapper);
91307a9368aSKonstantin Belousov }
91407a9368aSKonstantin Belousov 
9155215b187SJeff Roberson /*
91644990b8cSJulian Elischer  * Enforce single-threading.
91744990b8cSJulian Elischer  *
91844990b8cSJulian Elischer  * Returns 1 if the caller must abort (another thread is waiting to
91944990b8cSJulian Elischer  * exit the process or similar). Process is locked!
92044990b8cSJulian Elischer  * Returns 0 when you are successfully the only thread running.
92144990b8cSJulian Elischer  * A process has successfully single threaded in the suspend mode when
92244990b8cSJulian Elischer  * There are no threads in user mode. Threads in the kernel must be
92344990b8cSJulian Elischer  * allowed to continue until they get to the user boundary. They may even
92444990b8cSJulian Elischer  * copy out their return values and data before suspending. They may however be
925e2668f55SMaxim Konovalov  * accelerated in reaching the user boundary as we will wake up
92644990b8cSJulian Elischer  * any sleeping threads that are interruptable. (PCATCH).
92744990b8cSJulian Elischer  */
92844990b8cSJulian Elischer int
9296ddcc233SKonstantin Belousov thread_single(struct proc *p, int mode)
93044990b8cSJulian Elischer {
93144990b8cSJulian Elischer 	struct thread *td;
93244990b8cSJulian Elischer 	struct thread *td2;
933da7bbd2cSJohn Baldwin 	int remaining, wakeup_swapper;
93444990b8cSJulian Elischer 
93544990b8cSJulian Elischer 	td = curthread;
9366ddcc233SKonstantin Belousov 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
9376ddcc233SKonstantin Belousov 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
9386ddcc233SKonstantin Belousov 	    ("invalid mode %d", mode));
9396ddcc233SKonstantin Belousov 	/*
9406ddcc233SKonstantin Belousov 	 * If allowing non-ALLPROC singlethreading for non-curproc
9416ddcc233SKonstantin Belousov 	 * callers, calc_remaining() and remain_for_mode() should be
9426ddcc233SKonstantin Belousov 	 * adjusted to also account for td->td_proc != p.  For now
9436ddcc233SKonstantin Belousov 	 * this is not implemented because it is not used.
9446ddcc233SKonstantin Belousov 	 */
9456ddcc233SKonstantin Belousov 	KASSERT((mode == SINGLE_ALLPROC && td->td_proc != p) ||
9466ddcc233SKonstantin Belousov 	    (mode != SINGLE_ALLPROC && td->td_proc == p),
9476ddcc233SKonstantin Belousov 	    ("mode %d proc %p curproc %p", mode, p, td->td_proc));
94837814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
94944990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
95044990b8cSJulian Elischer 
9516ddcc233SKonstantin Belousov 	if ((p->p_flag & P_HADTHREADS) == 0 && mode != SINGLE_ALLPROC)
95244990b8cSJulian Elischer 		return (0);
95344990b8cSJulian Elischer 
954e3b9bf71SJulian Elischer 	/* Is someone already single threading? */
955906ac69dSDavid Xu 	if (p->p_singlethread != NULL && p->p_singlethread != td)
95644990b8cSJulian Elischer 		return (1);
95744990b8cSJulian Elischer 
958906ac69dSDavid Xu 	if (mode == SINGLE_EXIT) {
959906ac69dSDavid Xu 		p->p_flag |= P_SINGLE_EXIT;
960906ac69dSDavid Xu 		p->p_flag &= ~P_SINGLE_BOUNDARY;
961906ac69dSDavid Xu 	} else {
962906ac69dSDavid Xu 		p->p_flag &= ~P_SINGLE_EXIT;
963906ac69dSDavid Xu 		if (mode == SINGLE_BOUNDARY)
964906ac69dSDavid Xu 			p->p_flag |= P_SINGLE_BOUNDARY;
965906ac69dSDavid Xu 		else
966906ac69dSDavid Xu 			p->p_flag &= ~P_SINGLE_BOUNDARY;
967906ac69dSDavid Xu 	}
9686ddcc233SKonstantin Belousov 	if (mode == SINGLE_ALLPROC)
9696ddcc233SKonstantin Belousov 		p->p_flag |= P_TOTAL_STOP;
9701279572aSDavid Xu 	p->p_flag |= P_STOPPED_SINGLE;
9717b4a950aSDavid Xu 	PROC_SLOCK(p);
972112afcb2SJohn Baldwin 	p->p_singlethread = td;
97379799053SKonstantin Belousov 	remaining = calc_remaining(p, mode);
97407a9368aSKonstantin Belousov 	while (remaining != remain_for_mode(mode)) {
975bf1a3220SDavid Xu 		if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
976bf1a3220SDavid Xu 			goto stopme;
977da7bbd2cSJohn Baldwin 		wakeup_swapper = 0;
97844990b8cSJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td2) {
97944990b8cSJulian Elischer 			if (td2 == td)
98044990b8cSJulian Elischer 				continue;
981a54e85fdSJeff Roberson 			thread_lock(td2);
982b7edba77SJeff Roberson 			td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
9836ddcc233SKonstantin Belousov 			if (TD_IS_INHIBITED(td2)) {
98407a9368aSKonstantin Belousov 				wakeup_swapper |= weed_inhib(mode, td2, p);
985d8267df7SDavid Xu #ifdef SMP
9866ddcc233SKonstantin Belousov 			} else if (TD_IS_RUNNING(td2) && td != td2) {
987d8267df7SDavid Xu 				forward_signal(td2);
98861a74c5cSJeff Roberson 				thread_unlock(td2);
989d8267df7SDavid Xu #endif
99061a74c5cSJeff Roberson 			} else
991a54e85fdSJeff Roberson 				thread_unlock(td2);
9929d102777SJulian Elischer 		}
993da7bbd2cSJohn Baldwin 		if (wakeup_swapper)
994da7bbd2cSJohn Baldwin 			kick_proc0();
99579799053SKonstantin Belousov 		remaining = calc_remaining(p, mode);
996ec008e96SDavid Xu 
9979d102777SJulian Elischer 		/*
9989d102777SJulian Elischer 		 * Maybe we suspended some threads.. was it enough?
9999d102777SJulian Elischer 		 */
100007a9368aSKonstantin Belousov 		if (remaining == remain_for_mode(mode))
10019d102777SJulian Elischer 			break;
10029d102777SJulian Elischer 
1003bf1a3220SDavid Xu stopme:
100444990b8cSJulian Elischer 		/*
100544990b8cSJulian Elischer 		 * Wake us up when everyone else has suspended.
1006e3b9bf71SJulian Elischer 		 * In the mean time we suspend as well.
100744990b8cSJulian Elischer 		 */
10086ddcc233SKonstantin Belousov 		thread_suspend_switch(td, p);
100979799053SKonstantin Belousov 		remaining = calc_remaining(p, mode);
101044990b8cSJulian Elischer 	}
1011906ac69dSDavid Xu 	if (mode == SINGLE_EXIT) {
101291599697SJulian Elischer 		/*
10138626a0ddSKonstantin Belousov 		 * Convert the process to an unthreaded process.  The
10148626a0ddSKonstantin Belousov 		 * SINGLE_EXIT is called by exit1() or execve(), in
10158626a0ddSKonstantin Belousov 		 * both cases other threads must be retired.
101691599697SJulian Elischer 		 */
10178626a0ddSKonstantin Belousov 		KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
1018ed062c8dSJulian Elischer 		p->p_singlethread = NULL;
10198626a0ddSKonstantin Belousov 		p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
1020fd229b5bSKonstantin Belousov 
1021fd229b5bSKonstantin Belousov 		/*
1022fd229b5bSKonstantin Belousov 		 * Wait for any remaining threads to exit cpu_throw().
1023fd229b5bSKonstantin Belousov 		 */
1024fd229b5bSKonstantin Belousov 		while (p->p_exitthreads != 0) {
1025fd229b5bSKonstantin Belousov 			PROC_SUNLOCK(p);
1026fd229b5bSKonstantin Belousov 			PROC_UNLOCK(p);
1027fd229b5bSKonstantin Belousov 			sched_relinquish(td);
1028fd229b5bSKonstantin Belousov 			PROC_LOCK(p);
1029fd229b5bSKonstantin Belousov 			PROC_SLOCK(p);
1030fd229b5bSKonstantin Belousov 		}
1031ac437c07SKonstantin Belousov 	} else if (mode == SINGLE_BOUNDARY) {
1032ac437c07SKonstantin Belousov 		/*
1033ac437c07SKonstantin Belousov 		 * Wait until all suspended threads are removed from
1034ac437c07SKonstantin Belousov 		 * the processors.  The thread_suspend_check()
1035ac437c07SKonstantin Belousov 		 * increments p_boundary_count while it is still
1036ac437c07SKonstantin Belousov 		 * running, which makes it possible for the execve()
1037ac437c07SKonstantin Belousov 		 * to destroy vmspace while our other threads are
1038ac437c07SKonstantin Belousov 		 * still using the address space.
1039ac437c07SKonstantin Belousov 		 *
1040ac437c07SKonstantin Belousov 		 * We lock the thread, which is only allowed to
1041ac437c07SKonstantin Belousov 		 * succeed after context switch code finished using
1042ac437c07SKonstantin Belousov 		 * the address space.
1043ac437c07SKonstantin Belousov 		 */
1044ac437c07SKonstantin Belousov 		FOREACH_THREAD_IN_PROC(p, td2) {
1045ac437c07SKonstantin Belousov 			if (td2 == td)
1046ac437c07SKonstantin Belousov 				continue;
1047ac437c07SKonstantin Belousov 			thread_lock(td2);
1048ac437c07SKonstantin Belousov 			KASSERT((td2->td_flags & TDF_BOUNDARY) != 0,
1049ac437c07SKonstantin Belousov 			    ("td %p not on boundary", td2));
1050ac437c07SKonstantin Belousov 			KASSERT(TD_IS_SUSPENDED(td2),
1051ac437c07SKonstantin Belousov 			    ("td %p is not suspended", td2));
1052ac437c07SKonstantin Belousov 			thread_unlock(td2);
1053ac437c07SKonstantin Belousov 		}
105491599697SJulian Elischer 	}
10557b4a950aSDavid Xu 	PROC_SUNLOCK(p);
105644990b8cSJulian Elischer 	return (0);
105744990b8cSJulian Elischer }
105844990b8cSJulian Elischer 
10598638fe7bSKonstantin Belousov bool
10608638fe7bSKonstantin Belousov thread_suspend_check_needed(void)
10618638fe7bSKonstantin Belousov {
10628638fe7bSKonstantin Belousov 	struct proc *p;
10638638fe7bSKonstantin Belousov 	struct thread *td;
10648638fe7bSKonstantin Belousov 
10658638fe7bSKonstantin Belousov 	td = curthread;
10668638fe7bSKonstantin Belousov 	p = td->td_proc;
10678638fe7bSKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
10688638fe7bSKonstantin Belousov 	return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
10698638fe7bSKonstantin Belousov 	    (td->td_dbgflags & TDB_SUSPEND) != 0));
10708638fe7bSKonstantin Belousov }
10718638fe7bSKonstantin Belousov 
107244990b8cSJulian Elischer /*
107344990b8cSJulian Elischer  * Called in from locations that can safely check to see
107444990b8cSJulian Elischer  * whether we have to suspend or at least throttle for a
107544990b8cSJulian Elischer  * single-thread event (e.g. fork).
107644990b8cSJulian Elischer  *
107744990b8cSJulian Elischer  * Such locations include userret().
107844990b8cSJulian Elischer  * If the "return_instead" argument is non zero, the thread must be able to
107944990b8cSJulian Elischer  * accept 0 (caller may continue), or 1 (caller must abort) as a result.
108044990b8cSJulian Elischer  *
108144990b8cSJulian Elischer  * The 'return_instead' argument tells the function if it may do a
108244990b8cSJulian Elischer  * thread_exit() or suspend, or whether the caller must abort and back
108344990b8cSJulian Elischer  * out instead.
108444990b8cSJulian Elischer  *
108544990b8cSJulian Elischer  * If the thread that set the single_threading request has set the
108644990b8cSJulian Elischer  * P_SINGLE_EXIT bit in the process flags then this call will never return
108744990b8cSJulian Elischer  * if 'return_instead' is false, but will exit.
108844990b8cSJulian Elischer  *
108944990b8cSJulian Elischer  * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
109044990b8cSJulian Elischer  *---------------+--------------------+---------------------
109144990b8cSJulian Elischer  *       0       | returns 0          |   returns 0 or 1
1092353374b5SJohn Baldwin  *               | when ST ends       |   immediately
109344990b8cSJulian Elischer  *---------------+--------------------+---------------------
109444990b8cSJulian Elischer  *       1       | thread exits       |   returns 1
1095353374b5SJohn Baldwin  *               |                    |  immediately
109644990b8cSJulian Elischer  * 0 = thread_exit() or suspension ok,
109744990b8cSJulian Elischer  * other = return error instead of stopping the thread.
109844990b8cSJulian Elischer  *
109944990b8cSJulian Elischer  * While a full suspension is under effect, even a single threading
110044990b8cSJulian Elischer  * thread would be suspended if it made this call (but it shouldn't).
110144990b8cSJulian Elischer  * This call should only be made from places where
110244990b8cSJulian Elischer  * thread_exit() would be safe as that may be the outcome unless
110344990b8cSJulian Elischer  * return_instead is set.
110444990b8cSJulian Elischer  */
110544990b8cSJulian Elischer int
110644990b8cSJulian Elischer thread_suspend_check(int return_instead)
110744990b8cSJulian Elischer {
1108ecafb24bSJuli Mallett 	struct thread *td;
1109ecafb24bSJuli Mallett 	struct proc *p;
111046e47c4fSKonstantin Belousov 	int wakeup_swapper;
111144990b8cSJulian Elischer 
111244990b8cSJulian Elischer 	td = curthread;
111344990b8cSJulian Elischer 	p = td->td_proc;
111437814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
111544990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
11168638fe7bSKonstantin Belousov 	while (thread_suspend_check_needed()) {
11171279572aSDavid Xu 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
111844990b8cSJulian Elischer 			KASSERT(p->p_singlethread != NULL,
111944990b8cSJulian Elischer 			    ("singlethread not set"));
112044990b8cSJulian Elischer 			/*
1121e3b9bf71SJulian Elischer 			 * The only suspension in action is a
1122e3b9bf71SJulian Elischer 			 * single-threading. Single threader need not stop.
1123bd07998eSKonstantin Belousov 			 * It is safe to access p->p_singlethread unlocked
1124bd07998eSKonstantin Belousov 			 * because it can only be set to our address by us.
112544990b8cSJulian Elischer 			 */
1126e3b9bf71SJulian Elischer 			if (p->p_singlethread == td)
112744990b8cSJulian Elischer 				return (0);	/* Exempt from stopping. */
112844990b8cSJulian Elischer 		}
112945a4bfa1SDavid Xu 		if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
113094f0972bSDavid Xu 			return (EINTR);
113144990b8cSJulian Elischer 
1132906ac69dSDavid Xu 		/* Should we goto user boundary if we didn't come from there? */
1133906ac69dSDavid Xu 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1134906ac69dSDavid Xu 		    (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
113594f0972bSDavid Xu 			return (ERESTART);
1136906ac69dSDavid Xu 
113744990b8cSJulian Elischer 		/*
11383077f938SKonstantin Belousov 		 * Ignore suspend requests if they are deferred.
1139d071a6faSJohn Baldwin 		 */
11403077f938SKonstantin Belousov 		if ((td->td_flags & TDF_SBDRY) != 0) {
1141d071a6faSJohn Baldwin 			KASSERT(return_instead,
1142d071a6faSJohn Baldwin 			    ("TDF_SBDRY set for unsafe thread_suspend_check"));
114346e47c4fSKonstantin Belousov 			KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
114446e47c4fSKonstantin Belousov 			    (TDF_SEINTR | TDF_SERESTART),
114546e47c4fSKonstantin Belousov 			    ("both TDF_SEINTR and TDF_SERESTART"));
114646e47c4fSKonstantin Belousov 			return (TD_SBDRY_INTR(td) ? TD_SBDRY_ERRNO(td) : 0);
1147d071a6faSJohn Baldwin 		}
1148d071a6faSJohn Baldwin 
1149d071a6faSJohn Baldwin 		/*
115044990b8cSJulian Elischer 		 * If the process is waiting for us to exit,
115144990b8cSJulian Elischer 		 * this thread should just suicide.
11521279572aSDavid Xu 		 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
115344990b8cSJulian Elischer 		 */
1154cf7d9a8cSDavid Xu 		if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
1155cf7d9a8cSDavid Xu 			PROC_UNLOCK(p);
115691d1786fSDmitry Chagin 
115791d1786fSDmitry Chagin 			/*
115891d1786fSDmitry Chagin 			 * Allow Linux emulation layer to do some work
115991d1786fSDmitry Chagin 			 * before thread suicide.
116091d1786fSDmitry Chagin 			 */
116191d1786fSDmitry Chagin 			if (__predict_false(p->p_sysent->sv_thread_detach != NULL))
116291d1786fSDmitry Chagin 				(p->p_sysent->sv_thread_detach)(td);
11632a339d9eSKonstantin Belousov 			umtx_thread_exit(td);
1164d1e7a4a5SJohn Baldwin 			kern_thr_exit(td);
1165d1e7a4a5SJohn Baldwin 			panic("stopped thread did not exit");
1166cf7d9a8cSDavid Xu 		}
116721ecd1e9SDavid Xu 
116821ecd1e9SDavid Xu 		PROC_SLOCK(p);
116921ecd1e9SDavid Xu 		thread_stopped(p);
1170a54e85fdSJeff Roberson 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1171a54e85fdSJeff Roberson 			if (p->p_numthreads == p->p_suspcount + 1) {
1172a54e85fdSJeff Roberson 				thread_lock(p->p_singlethread);
117384cdea97SKonstantin Belousov 				wakeup_swapper = thread_unsuspend_one(
117484cdea97SKonstantin Belousov 				    p->p_singlethread, p, false);
11757847a9daSJohn Baldwin 				if (wakeup_swapper)
11767847a9daSJohn Baldwin 					kick_proc0();
1177a54e85fdSJeff Roberson 			}
1178a54e85fdSJeff Roberson 		}
11793f9be10eSDavid Xu 		PROC_UNLOCK(p);
11807b4a950aSDavid Xu 		thread_lock(td);
118144990b8cSJulian Elischer 		/*
118244990b8cSJulian Elischer 		 * When a thread suspends, it just
1183ad1e7d28SJulian Elischer 		 * gets taken off all queues.
118444990b8cSJulian Elischer 		 */
118571fad9fdSJulian Elischer 		thread_suspend_one(td);
1186906ac69dSDavid Xu 		if (return_instead == 0) {
1187906ac69dSDavid Xu 			p->p_boundary_count++;
1188906ac69dSDavid Xu 			td->td_flags |= TDF_BOUNDARY;
1189cf19bf91SJulian Elischer 		}
11907b4a950aSDavid Xu 		PROC_SUNLOCK(p);
1191686bcb5cSJeff Roberson 		mi_switch(SW_INVOL | SWT_SUSPEND);
119244990b8cSJulian Elischer 		PROC_LOCK(p);
119344990b8cSJulian Elischer 	}
119444990b8cSJulian Elischer 	return (0);
119544990b8cSJulian Elischer }
119644990b8cSJulian Elischer 
1197478ca4b0SKonstantin Belousov /*
1198478ca4b0SKonstantin Belousov  * Check for possible stops and suspensions while executing a
1199478ca4b0SKonstantin Belousov  * casueword or similar transiently failing operation.
1200478ca4b0SKonstantin Belousov  *
1201478ca4b0SKonstantin Belousov  * The sleep argument controls whether the function can handle a stop
1202478ca4b0SKonstantin Belousov  * request itself or it should return ERESTART and the request is
1203478ca4b0SKonstantin Belousov  * proceed at the kernel/user boundary in ast.
1204478ca4b0SKonstantin Belousov  *
1205478ca4b0SKonstantin Belousov  * Typically, when retrying due to casueword(9) failure (rv == 1), we
1206478ca4b0SKonstantin Belousov  * should handle the stop requests there, with exception of cases when
1207478ca4b0SKonstantin Belousov  * the thread owns a kernel resource, for instance busied the umtx
1208300b525dSKonstantin Belousov  * key, or when functions return immediately if thread_check_susp()
1209478ca4b0SKonstantin Belousov  * returned non-zero.  On the other hand, retrying the whole lock
1210478ca4b0SKonstantin Belousov  * operation, we better not stop there but delegate the handling to
1211478ca4b0SKonstantin Belousov  * ast.
1212478ca4b0SKonstantin Belousov  *
1213478ca4b0SKonstantin Belousov  * If the request is for thread termination P_SINGLE_EXIT, we cannot
1214478ca4b0SKonstantin Belousov  * handle it at all, and simply return EINTR.
1215478ca4b0SKonstantin Belousov  */
1216478ca4b0SKonstantin Belousov int
1217478ca4b0SKonstantin Belousov thread_check_susp(struct thread *td, bool sleep)
1218478ca4b0SKonstantin Belousov {
1219478ca4b0SKonstantin Belousov 	struct proc *p;
1220478ca4b0SKonstantin Belousov 	int error;
1221478ca4b0SKonstantin Belousov 
1222478ca4b0SKonstantin Belousov 	/*
1223478ca4b0SKonstantin Belousov 	 * The check for TDF_NEEDSUSPCHK is racy, but it is enough to
1224478ca4b0SKonstantin Belousov 	 * eventually break the lockstep loop.
1225478ca4b0SKonstantin Belousov 	 */
1226478ca4b0SKonstantin Belousov 	if ((td->td_flags & TDF_NEEDSUSPCHK) == 0)
1227478ca4b0SKonstantin Belousov 		return (0);
1228478ca4b0SKonstantin Belousov 	error = 0;
1229478ca4b0SKonstantin Belousov 	p = td->td_proc;
1230478ca4b0SKonstantin Belousov 	PROC_LOCK(p);
1231478ca4b0SKonstantin Belousov 	if (p->p_flag & P_SINGLE_EXIT)
1232478ca4b0SKonstantin Belousov 		error = EINTR;
1233478ca4b0SKonstantin Belousov 	else if (P_SHOULDSTOP(p) ||
1234478ca4b0SKonstantin Belousov 	    ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_SUSPEND)))
1235478ca4b0SKonstantin Belousov 		error = sleep ? thread_suspend_check(0) : ERESTART;
1236478ca4b0SKonstantin Belousov 	PROC_UNLOCK(p);
1237478ca4b0SKonstantin Belousov 	return (error);
1238478ca4b0SKonstantin Belousov }
1239478ca4b0SKonstantin Belousov 
124035c32a76SDavid Xu void
12416ddcc233SKonstantin Belousov thread_suspend_switch(struct thread *td, struct proc *p)
1242a54e85fdSJeff Roberson {
1243a54e85fdSJeff Roberson 
1244a54e85fdSJeff Roberson 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1245a54e85fdSJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
12467b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1247a54e85fdSJeff Roberson 	/*
1248a54e85fdSJeff Roberson 	 * We implement thread_suspend_one in stages here to avoid
1249a54e85fdSJeff Roberson 	 * dropping the proc lock while the thread lock is owned.
1250a54e85fdSJeff Roberson 	 */
12516ddcc233SKonstantin Belousov 	if (p == td->td_proc) {
1252a54e85fdSJeff Roberson 		thread_stopped(p);
1253a54e85fdSJeff Roberson 		p->p_suspcount++;
12546ddcc233SKonstantin Belousov 	}
12553f9be10eSDavid Xu 	PROC_UNLOCK(p);
12567b4a950aSDavid Xu 	thread_lock(td);
1257b7edba77SJeff Roberson 	td->td_flags &= ~TDF_NEEDSUSPCHK;
1258a54e85fdSJeff Roberson 	TD_SET_SUSPENDED(td);
1259c5aa6b58SJeff Roberson 	sched_sleep(td, 0);
12607b4a950aSDavid Xu 	PROC_SUNLOCK(p);
1261a54e85fdSJeff Roberson 	DROP_GIANT();
1262686bcb5cSJeff Roberson 	mi_switch(SW_VOL | SWT_SUSPEND);
1263a54e85fdSJeff Roberson 	PICKUP_GIANT();
1264a54e85fdSJeff Roberson 	PROC_LOCK(p);
12657b4a950aSDavid Xu 	PROC_SLOCK(p);
1266a54e85fdSJeff Roberson }
1267a54e85fdSJeff Roberson 
1268a54e85fdSJeff Roberson void
126935c32a76SDavid Xu thread_suspend_one(struct thread *td)
127035c32a76SDavid Xu {
12716ddcc233SKonstantin Belousov 	struct proc *p;
127235c32a76SDavid Xu 
12736ddcc233SKonstantin Belousov 	p = td->td_proc;
12747b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1275a54e85fdSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1276e574e444SDavid Xu 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
127735c32a76SDavid Xu 	p->p_suspcount++;
1278b7edba77SJeff Roberson 	td->td_flags &= ~TDF_NEEDSUSPCHK;
127971fad9fdSJulian Elischer 	TD_SET_SUSPENDED(td);
1280c5aa6b58SJeff Roberson 	sched_sleep(td, 0);
128135c32a76SDavid Xu }
128235c32a76SDavid Xu 
128384cdea97SKonstantin Belousov static int
128484cdea97SKonstantin Belousov thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
128535c32a76SDavid Xu {
128635c32a76SDavid Xu 
1287a54e85fdSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1288ad1e7d28SJulian Elischer 	KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
128971fad9fdSJulian Elischer 	TD_CLR_SUSPENDED(td);
12906ddcc233SKonstantin Belousov 	td->td_flags &= ~TDF_ALLPROCSUSP;
12916ddcc233SKonstantin Belousov 	if (td->td_proc == p) {
12926ddcc233SKonstantin Belousov 		PROC_SLOCK_ASSERT(p, MA_OWNED);
129335c32a76SDavid Xu 		p->p_suspcount--;
129484cdea97SKonstantin Belousov 		if (boundary && (td->td_flags & TDF_BOUNDARY) != 0) {
129584cdea97SKonstantin Belousov 			td->td_flags &= ~TDF_BOUNDARY;
129684cdea97SKonstantin Belousov 			p->p_boundary_count--;
129784cdea97SKonstantin Belousov 		}
12986ddcc233SKonstantin Belousov 	}
129961a74c5cSJeff Roberson 	return (setrunnable(td, 0));
130035c32a76SDavid Xu }
130135c32a76SDavid Xu 
130244990b8cSJulian Elischer /*
130344990b8cSJulian Elischer  * Allow all threads blocked by single threading to continue running.
130444990b8cSJulian Elischer  */
130544990b8cSJulian Elischer void
130644990b8cSJulian Elischer thread_unsuspend(struct proc *p)
130744990b8cSJulian Elischer {
130844990b8cSJulian Elischer 	struct thread *td;
13097847a9daSJohn Baldwin 	int wakeup_swapper;
131044990b8cSJulian Elischer 
131144990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
13127b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
13137847a9daSJohn Baldwin 	wakeup_swapper = 0;
131444990b8cSJulian Elischer 	if (!P_SHOULDSTOP(p)) {
1315ad1e7d28SJulian Elischer                 FOREACH_THREAD_IN_PROC(p, td) {
1316a54e85fdSJeff Roberson 			thread_lock(td);
1317ad1e7d28SJulian Elischer 			if (TD_IS_SUSPENDED(td)) {
131884cdea97SKonstantin Belousov 				wakeup_swapper |= thread_unsuspend_one(td, p,
131984cdea97SKonstantin Belousov 				    true);
132061a74c5cSJeff Roberson 			} else
1321a54e85fdSJeff Roberson 				thread_unlock(td);
1322ad1e7d28SJulian Elischer 		}
132384cdea97SKonstantin Belousov 	} else if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
132484cdea97SKonstantin Belousov 	    p->p_numthreads == p->p_suspcount) {
132544990b8cSJulian Elischer 		/*
132644990b8cSJulian Elischer 		 * Stopping everything also did the job for the single
132744990b8cSJulian Elischer 		 * threading request. Now we've downgraded to single-threaded,
132844990b8cSJulian Elischer 		 * let it continue.
132944990b8cSJulian Elischer 		 */
13306ddcc233SKonstantin Belousov 		if (p->p_singlethread->td_proc == p) {
1331a54e85fdSJeff Roberson 			thread_lock(p->p_singlethread);
13326ddcc233SKonstantin Belousov 			wakeup_swapper = thread_unsuspend_one(
133384cdea97SKonstantin Belousov 			    p->p_singlethread, p, false);
133444990b8cSJulian Elischer 		}
13356ddcc233SKonstantin Belousov 	}
13367847a9daSJohn Baldwin 	if (wakeup_swapper)
13377847a9daSJohn Baldwin 		kick_proc0();
133844990b8cSJulian Elischer }
133944990b8cSJulian Elischer 
1340ed062c8dSJulian Elischer /*
1341ed062c8dSJulian Elischer  * End the single threading mode..
1342ed062c8dSJulian Elischer  */
134344990b8cSJulian Elischer void
13446ddcc233SKonstantin Belousov thread_single_end(struct proc *p, int mode)
134544990b8cSJulian Elischer {
134644990b8cSJulian Elischer 	struct thread *td;
13477847a9daSJohn Baldwin 	int wakeup_swapper;
134844990b8cSJulian Elischer 
13496ddcc233SKonstantin Belousov 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
13506ddcc233SKonstantin Belousov 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
13516ddcc233SKonstantin Belousov 	    ("invalid mode %d", mode));
135244990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
13536ddcc233SKonstantin Belousov 	KASSERT((mode == SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) != 0) ||
13546ddcc233SKonstantin Belousov 	    (mode != SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) == 0),
13556ddcc233SKonstantin Belousov 	    ("mode %d does not match P_TOTAL_STOP", mode));
135684cdea97SKonstantin Belousov 	KASSERT(mode == SINGLE_ALLPROC || p->p_singlethread == curthread,
135784cdea97SKonstantin Belousov 	    ("thread_single_end from other thread %p %p",
135884cdea97SKonstantin Belousov 	    curthread, p->p_singlethread));
135984cdea97SKonstantin Belousov 	KASSERT(mode != SINGLE_BOUNDARY ||
136084cdea97SKonstantin Belousov 	    (p->p_flag & P_SINGLE_BOUNDARY) != 0,
136184cdea97SKonstantin Belousov 	    ("mis-matched SINGLE_BOUNDARY flags %x", p->p_flag));
13626ddcc233SKonstantin Belousov 	p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY |
13636ddcc233SKonstantin Belousov 	    P_TOTAL_STOP);
13647b4a950aSDavid Xu 	PROC_SLOCK(p);
136544990b8cSJulian Elischer 	p->p_singlethread = NULL;
13667847a9daSJohn Baldwin 	wakeup_swapper = 0;
136749539972SJulian Elischer 	/*
13687847a9daSJohn Baldwin 	 * If there are other threads they may now run,
136949539972SJulian Elischer 	 * unless of course there is a blanket 'stop order'
137049539972SJulian Elischer 	 * on the process. The single threader must be allowed
137149539972SJulian Elischer 	 * to continue however as this is a bad place to stop.
137249539972SJulian Elischer 	 */
13736ddcc233SKonstantin Belousov 	if (p->p_numthreads != remain_for_mode(mode) && !P_SHOULDSTOP(p)) {
1374ad1e7d28SJulian Elischer                 FOREACH_THREAD_IN_PROC(p, td) {
1375a54e85fdSJeff Roberson 			thread_lock(td);
1376ad1e7d28SJulian Elischer 			if (TD_IS_SUSPENDED(td)) {
137784cdea97SKonstantin Belousov 				wakeup_swapper |= thread_unsuspend_one(td, p,
137884cdea97SKonstantin Belousov 				    mode == SINGLE_BOUNDARY);
137961a74c5cSJeff Roberson 			} else
1380a54e85fdSJeff Roberson 				thread_unlock(td);
138149539972SJulian Elischer 		}
1382ad1e7d28SJulian Elischer 	}
138384cdea97SKonstantin Belousov 	KASSERT(mode != SINGLE_BOUNDARY || p->p_boundary_count == 0,
138484cdea97SKonstantin Belousov 	    ("inconsistent boundary count %d", p->p_boundary_count));
13857b4a950aSDavid Xu 	PROC_SUNLOCK(p);
13867847a9daSJohn Baldwin 	if (wakeup_swapper)
13877847a9daSJohn Baldwin 		kick_proc0();
138849539972SJulian Elischer }
13894fc21c09SDaniel Eischen 
1390aae3547bSMateusz Guzik /*
1391aae3547bSMateusz Guzik  * Locate a thread by number and return with proc lock held.
1392aae3547bSMateusz Guzik  *
1393aae3547bSMateusz Guzik  * thread exit establishes proc -> tidhash lock ordering, but lookup
1394aae3547bSMateusz Guzik  * takes tidhash first and needs to return locked proc.
1395aae3547bSMateusz Guzik  *
1396aae3547bSMateusz Guzik  * The problem is worked around by relying on type-safety of both
1397aae3547bSMateusz Guzik  * structures and doing the work in 2 steps:
1398aae3547bSMateusz Guzik  * - tidhash-locked lookup which saves both thread and proc pointers
1399aae3547bSMateusz Guzik  * - proc-locked verification that the found thread still matches
1400aae3547bSMateusz Guzik  */
1401aae3547bSMateusz Guzik static bool
1402aae3547bSMateusz Guzik tdfind_hash(lwpid_t tid, pid_t pid, struct proc **pp, struct thread **tdp)
1403cf7d9a8cSDavid Xu {
1404cf7d9a8cSDavid Xu #define RUN_THRESH	16
1405aae3547bSMateusz Guzik 	struct proc *p;
1406cf7d9a8cSDavid Xu 	struct thread *td;
1407aae3547bSMateusz Guzik 	int run;
1408aae3547bSMateusz Guzik 	bool locked;
1409cf7d9a8cSDavid Xu 
1410aae3547bSMateusz Guzik 	run = 0;
141126007fe3SMateusz Guzik 	rw_rlock(TIDHASHLOCK(tid));
1412aae3547bSMateusz Guzik 	locked = true;
1413cf7d9a8cSDavid Xu 	LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1414aae3547bSMateusz Guzik 		if (td->td_tid != tid) {
1415aae3547bSMateusz Guzik 			run++;
1416aae3547bSMateusz Guzik 			continue;
1417cf7d9a8cSDavid Xu 		}
1418aae3547bSMateusz Guzik 		p = td->td_proc;
1419aae3547bSMateusz Guzik 		if (pid != -1 && p->p_pid != pid) {
1420cf7d9a8cSDavid Xu 			td = NULL;
1421cf7d9a8cSDavid Xu 			break;
1422cf7d9a8cSDavid Xu 		}
1423cf7d9a8cSDavid Xu 		if (run > RUN_THRESH) {
142426007fe3SMateusz Guzik 			if (rw_try_upgrade(TIDHASHLOCK(tid))) {
1425cf7d9a8cSDavid Xu 				LIST_REMOVE(td, td_hash);
1426cf7d9a8cSDavid Xu 				LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1427cf7d9a8cSDavid Xu 					td, td_hash);
142826007fe3SMateusz Guzik 				rw_wunlock(TIDHASHLOCK(tid));
1429aae3547bSMateusz Guzik 				locked = false;
1430aae3547bSMateusz Guzik 				break;
1431cf7d9a8cSDavid Xu 			}
1432cf7d9a8cSDavid Xu 		}
1433cf7d9a8cSDavid Xu 		break;
1434cf7d9a8cSDavid Xu 	}
1435aae3547bSMateusz Guzik 	if (locked)
143626007fe3SMateusz Guzik 		rw_runlock(TIDHASHLOCK(tid));
1437aae3547bSMateusz Guzik 	if (td == NULL)
1438aae3547bSMateusz Guzik 		return (false);
1439aae3547bSMateusz Guzik 	*pp = p;
1440aae3547bSMateusz Guzik 	*tdp = td;
1441aae3547bSMateusz Guzik 	return (true);
1442aae3547bSMateusz Guzik }
1443aae3547bSMateusz Guzik 
1444aae3547bSMateusz Guzik struct thread *
1445aae3547bSMateusz Guzik tdfind(lwpid_t tid, pid_t pid)
1446aae3547bSMateusz Guzik {
1447aae3547bSMateusz Guzik 	struct proc *p;
1448aae3547bSMateusz Guzik 	struct thread *td;
1449aae3547bSMateusz Guzik 
1450aae3547bSMateusz Guzik 	td = curthread;
1451aae3547bSMateusz Guzik 	if (td->td_tid == tid) {
1452aae3547bSMateusz Guzik 		if (pid != -1 && td->td_proc->p_pid != pid)
1453aae3547bSMateusz Guzik 			return (NULL);
1454aae3547bSMateusz Guzik 		PROC_LOCK(td->td_proc);
1455cf7d9a8cSDavid Xu 		return (td);
1456cf7d9a8cSDavid Xu 	}
1457cf7d9a8cSDavid Xu 
1458aae3547bSMateusz Guzik 	for (;;) {
1459aae3547bSMateusz Guzik 		if (!tdfind_hash(tid, pid, &p, &td))
1460aae3547bSMateusz Guzik 			return (NULL);
1461aae3547bSMateusz Guzik 		PROC_LOCK(p);
1462aae3547bSMateusz Guzik 		if (td->td_tid != tid) {
1463aae3547bSMateusz Guzik 			PROC_UNLOCK(p);
1464aae3547bSMateusz Guzik 			continue;
1465aae3547bSMateusz Guzik 		}
1466aae3547bSMateusz Guzik 		if (td->td_proc != p) {
1467aae3547bSMateusz Guzik 			PROC_UNLOCK(p);
1468aae3547bSMateusz Guzik 			continue;
1469aae3547bSMateusz Guzik 		}
1470aae3547bSMateusz Guzik 		if (p->p_state == PRS_NEW) {
1471aae3547bSMateusz Guzik 			PROC_UNLOCK(p);
1472aae3547bSMateusz Guzik 			return (NULL);
1473aae3547bSMateusz Guzik 		}
1474aae3547bSMateusz Guzik 		return (td);
1475aae3547bSMateusz Guzik 	}
1476aae3547bSMateusz Guzik }
1477aae3547bSMateusz Guzik 
1478cf7d9a8cSDavid Xu void
1479cf7d9a8cSDavid Xu tidhash_add(struct thread *td)
1480cf7d9a8cSDavid Xu {
148126007fe3SMateusz Guzik 	rw_wlock(TIDHASHLOCK(td->td_tid));
1482cf7d9a8cSDavid Xu 	LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
148326007fe3SMateusz Guzik 	rw_wunlock(TIDHASHLOCK(td->td_tid));
1484cf7d9a8cSDavid Xu }
1485cf7d9a8cSDavid Xu 
1486cf7d9a8cSDavid Xu void
1487cf7d9a8cSDavid Xu tidhash_remove(struct thread *td)
1488cf7d9a8cSDavid Xu {
148926007fe3SMateusz Guzik 
149026007fe3SMateusz Guzik 	rw_wlock(TIDHASHLOCK(td->td_tid));
1491cf7d9a8cSDavid Xu 	LIST_REMOVE(td, td_hash);
149226007fe3SMateusz Guzik 	rw_wunlock(TIDHASHLOCK(td->td_tid));
1493cf7d9a8cSDavid Xu }
1494