xref: /freebsd/sys/kern/kern_thread.c (revision acd9f5172513664905cfd3e9768490fcf4e03aa9)
19454b2d8SWarner Losh /*-
244990b8cSJulian Elischer  * Copyright (C) 2001 Julian Elischer <julian@freebsd.org>.
344990b8cSJulian Elischer  *  All rights reserved.
444990b8cSJulian Elischer  *
544990b8cSJulian Elischer  * Redistribution and use in source and binary forms, with or without
644990b8cSJulian Elischer  * modification, are permitted provided that the following conditions
744990b8cSJulian Elischer  * are met:
844990b8cSJulian Elischer  * 1. Redistributions of source code must retain the above copyright
944990b8cSJulian Elischer  *    notice(s), this list of conditions and the following disclaimer as
1044990b8cSJulian Elischer  *    the first lines of this file unmodified other than the possible
1144990b8cSJulian Elischer  *    addition of one or more copyright notices.
1244990b8cSJulian Elischer  * 2. Redistributions in binary form must reproduce the above copyright
1344990b8cSJulian Elischer  *    notice(s), this list of conditions and the following disclaimer in the
1444990b8cSJulian Elischer  *    documentation and/or other materials provided with the distribution.
1544990b8cSJulian Elischer  *
1644990b8cSJulian Elischer  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
1744990b8cSJulian Elischer  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1844990b8cSJulian Elischer  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1944990b8cSJulian Elischer  * DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
2044990b8cSJulian Elischer  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
2144990b8cSJulian Elischer  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2244990b8cSJulian Elischer  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2344990b8cSJulian Elischer  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2444990b8cSJulian Elischer  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2544990b8cSJulian Elischer  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
2644990b8cSJulian Elischer  * DAMAGE.
2744990b8cSJulian Elischer  */
2844990b8cSJulian Elischer 
293d06b4b3SAttilio Rao #include "opt_witness.h"
3016d95d4fSJoseph Koshy #include "opt_hwpmc_hooks.h"
313d06b4b3SAttilio Rao 
32677b542eSDavid E. O'Brien #include <sys/cdefs.h>
33677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
34677b542eSDavid E. O'Brien 
3544990b8cSJulian Elischer #include <sys/param.h>
3644990b8cSJulian Elischer #include <sys/systm.h>
3744990b8cSJulian Elischer #include <sys/kernel.h>
3844990b8cSJulian Elischer #include <sys/lock.h>
3944990b8cSJulian Elischer #include <sys/mutex.h>
4044990b8cSJulian Elischer #include <sys/proc.h>
418f0e9130SKonstantin Belousov #include <sys/rangelock.h>
42e170bfdaSDavid Xu #include <sys/resourcevar.h>
43b3e9e682SRyan Stone #include <sys/sdt.h>
4494e0a4cdSJulian Elischer #include <sys/smp.h>
45de028f5aSJeff Roberson #include <sys/sched.h>
4644f3b092SJohn Baldwin #include <sys/sleepqueue.h>
47ace8398dSJeff Roberson #include <sys/selinfo.h>
48d1e7a4a5SJohn Baldwin #include <sys/syscallsubr.h>
4991d1786fSDmitry Chagin #include <sys/sysent.h>
50961a7b24SJohn Baldwin #include <sys/turnstile.h>
5144990b8cSJulian Elischer #include <sys/ktr.h>
52cf7d9a8cSDavid Xu #include <sys/rwlock.h>
53bc8e6d81SDavid Xu #include <sys/umtx.h>
549ed01c32SGleb Smirnoff #include <sys/vmmeter.h>
55d7f687fcSJeff Roberson #include <sys/cpuset.h>
5616d95d4fSJoseph Koshy #ifdef	HWPMC_HOOKS
5716d95d4fSJoseph Koshy #include <sys/pmckern.h>
5816d95d4fSJoseph Koshy #endif
5944990b8cSJulian Elischer 
60911b84b0SRobert Watson #include <security/audit/audit.h>
61911b84b0SRobert Watson 
6244990b8cSJulian Elischer #include <vm/vm.h>
6349a2507bSAlan Cox #include <vm/vm_extern.h>
6444990b8cSJulian Elischer #include <vm/uma.h>
656520495aSAdrian Chadd #include <vm/vm_domain.h>
66b209f889SRandall Stewart #include <sys/eventhandler.h>
6702fb42b0SPeter Wemm 
68*acd9f517SKonstantin Belousov /*
69*acd9f517SKonstantin Belousov  * Asserts below verify the stability of struct thread and struct proc
70*acd9f517SKonstantin Belousov  * layout, as exposed by KBI to modules.  On head, the KBI is allowed
71*acd9f517SKonstantin Belousov  * to drift, change to the structures must be accompanied by the
72*acd9f517SKonstantin Belousov  * assert update.
73*acd9f517SKonstantin Belousov  *
74*acd9f517SKonstantin Belousov  * On the stable branches after KBI freeze, conditions must not be
75*acd9f517SKonstantin Belousov  * violated.  Typically new fields are moved to the end of the
76*acd9f517SKonstantin Belousov  * structures.
77*acd9f517SKonstantin Belousov  */
78*acd9f517SKonstantin Belousov #ifdef __amd64__
79*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct thread, td_flags) == 0xf4,
80*acd9f517SKonstantin Belousov     "struct thread KBI td_flags");
81*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct thread, td_pflags) == 0xfc,
82*acd9f517SKonstantin Belousov     "struct thread KBI td_pflags");
83*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct thread, td_frame) == 0x410,
84*acd9f517SKonstantin Belousov     "struct thread KBI td_frame");
85*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct thread, td_emuldata) == 0x4b8,
86*acd9f517SKonstantin Belousov     "struct thread KBI td_emuldata");
87*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_flag) == 0xb0,
88*acd9f517SKonstantin Belousov     "struct proc KBI p_flag");
89*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_pid) == 0xbc,
90*acd9f517SKonstantin Belousov     "struct proc KBI p_pid");
91*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_filemon) == 0x3d0,
92*acd9f517SKonstantin Belousov     "struct proc KBI p_filemon");
93*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_comm) == 0x3e0,
94*acd9f517SKonstantin Belousov     "struct proc KBI p_comm");
95*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_emuldata) == 0x4b8,
96*acd9f517SKonstantin Belousov     "struct proc KBI p_emuldata");
97*acd9f517SKonstantin Belousov #endif
98*acd9f517SKonstantin Belousov #ifdef __i386__
99*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct thread, td_flags) == 0x9c,
100*acd9f517SKonstantin Belousov     "struct thread KBI td_flags");
101*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct thread, td_pflags) == 0xa4,
102*acd9f517SKonstantin Belousov     "struct thread KBI td_pflags");
103*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct thread, td_frame) == 0x2c8,
104*acd9f517SKonstantin Belousov     "struct thread KBI td_frame");
105*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct thread, td_emuldata) == 0x314,
106*acd9f517SKonstantin Belousov     "struct thread KBI td_emuldata");
107*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_flag) == 0x68,
108*acd9f517SKonstantin Belousov     "struct proc KBI p_flag");
109*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_pid) == 0x74,
110*acd9f517SKonstantin Belousov     "struct proc KBI p_pid");
111*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_filemon) == 0x27c,
112*acd9f517SKonstantin Belousov     "struct proc KBI p_filemon");
113*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_comm) == 0x288,
114*acd9f517SKonstantin Belousov     "struct proc KBI p_comm");
115*acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_emuldata) == 0x314,
116*acd9f517SKonstantin Belousov     "struct proc KBI p_emuldata");
117*acd9f517SKonstantin Belousov #endif
118*acd9f517SKonstantin Belousov 
119b3e9e682SRyan Stone SDT_PROVIDER_DECLARE(proc);
120d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(proc, , , lwp__exit);
121b3e9e682SRyan Stone 
1228460a577SJohn Birrell /*
1238460a577SJohn Birrell  * thread related storage.
1248460a577SJohn Birrell  */
12544990b8cSJulian Elischer static uma_zone_t thread_zone;
12644990b8cSJulian Elischer 
1275215b187SJeff Roberson TAILQ_HEAD(, thread) zombie_threads = TAILQ_HEAD_INITIALIZER(zombie_threads);
128c8790f5dSAttilio Rao static struct mtx zombie_lock;
129a54e85fdSJeff Roberson MTX_SYSINIT(zombie_lock, &zombie_lock, "zombie lock", MTX_SPIN);
13044990b8cSJulian Elischer 
131ff8fbcffSJeff Roberson static void thread_zombie(struct thread *);
13284cdea97SKonstantin Belousov static int thread_unsuspend_one(struct thread *td, struct proc *p,
13384cdea97SKonstantin Belousov     bool boundary);
134ff8fbcffSJeff Roberson 
135ec6ea5e8SDavid Xu #define TID_BUFFER_SIZE	1024
136ec6ea5e8SDavid Xu 
137fdcac928SMarcel Moolenaar struct mtx tid_lock;
1381ea7a6f8SPoul-Henning Kamp static struct unrhdr *tid_unrhdr;
139ec6ea5e8SDavid Xu static lwpid_t tid_buffer[TID_BUFFER_SIZE];
140ec6ea5e8SDavid Xu static int tid_head, tid_tail;
141cf7d9a8cSDavid Xu static MALLOC_DEFINE(M_TIDHASH, "tidhash", "thread hash");
142cf7d9a8cSDavid Xu 
143cf7d9a8cSDavid Xu struct	tidhashhead *tidhashtbl;
144cf7d9a8cSDavid Xu u_long	tidhash;
145cf7d9a8cSDavid Xu struct	rwlock tidhash_lock;
146cf7d9a8cSDavid Xu 
147ec6ea5e8SDavid Xu static lwpid_t
148ec6ea5e8SDavid Xu tid_alloc(void)
149ec6ea5e8SDavid Xu {
150ec6ea5e8SDavid Xu 	lwpid_t	tid;
151ec6ea5e8SDavid Xu 
152ec6ea5e8SDavid Xu 	tid = alloc_unr(tid_unrhdr);
153ec6ea5e8SDavid Xu 	if (tid != -1)
154ec6ea5e8SDavid Xu 		return (tid);
155ec6ea5e8SDavid Xu 	mtx_lock(&tid_lock);
156ec6ea5e8SDavid Xu 	if (tid_head == tid_tail) {
157ec6ea5e8SDavid Xu 		mtx_unlock(&tid_lock);
158ec6ea5e8SDavid Xu 		return (-1);
159ec6ea5e8SDavid Xu 	}
16094cb3545SKonstantin Belousov 	tid = tid_buffer[tid_head];
16194cb3545SKonstantin Belousov 	tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
162ec6ea5e8SDavid Xu 	mtx_unlock(&tid_lock);
163ec6ea5e8SDavid Xu 	return (tid);
164ec6ea5e8SDavid Xu }
165ec6ea5e8SDavid Xu 
166ec6ea5e8SDavid Xu static void
167ec6ea5e8SDavid Xu tid_free(lwpid_t tid)
168ec6ea5e8SDavid Xu {
169ec6ea5e8SDavid Xu 	lwpid_t tmp_tid = -1;
170ec6ea5e8SDavid Xu 
171ec6ea5e8SDavid Xu 	mtx_lock(&tid_lock);
172ec6ea5e8SDavid Xu 	if ((tid_tail + 1) % TID_BUFFER_SIZE == tid_head) {
17394cb3545SKonstantin Belousov 		tmp_tid = tid_buffer[tid_head];
17494cb3545SKonstantin Belousov 		tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
175ec6ea5e8SDavid Xu 	}
17694cb3545SKonstantin Belousov 	tid_buffer[tid_tail] = tid;
17794cb3545SKonstantin Belousov 	tid_tail = (tid_tail + 1) % TID_BUFFER_SIZE;
178ec6ea5e8SDavid Xu 	mtx_unlock(&tid_lock);
179ec6ea5e8SDavid Xu 	if (tmp_tid != -1)
180ec6ea5e8SDavid Xu 		free_unr(tid_unrhdr, tmp_tid);
181ec6ea5e8SDavid Xu }
182ec6ea5e8SDavid Xu 
183fdcac928SMarcel Moolenaar /*
184696058c3SJulian Elischer  * Prepare a thread for use.
18544990b8cSJulian Elischer  */
186b23f72e9SBrian Feldman static int
187b23f72e9SBrian Feldman thread_ctor(void *mem, int size, void *arg, int flags)
18844990b8cSJulian Elischer {
18944990b8cSJulian Elischer 	struct thread	*td;
19044990b8cSJulian Elischer 
19144990b8cSJulian Elischer 	td = (struct thread *)mem;
19271fad9fdSJulian Elischer 	td->td_state = TDS_INACTIVE;
193060563ecSJulian Elischer 	td->td_oncpu = NOCPU;
1946c27c603SJuli Mallett 
195ec6ea5e8SDavid Xu 	td->td_tid = tid_alloc();
196773eff9dSPoul-Henning Kamp 
1976c27c603SJuli Mallett 	/*
1986c27c603SJuli Mallett 	 * Note that td_critnest begins life as 1 because the thread is not
1996c27c603SJuli Mallett 	 * running and is thereby implicitly waiting to be on the receiving
200a54e85fdSJeff Roberson 	 * end of a context switch.
2016c27c603SJuli Mallett 	 */
202139b7550SJohn Baldwin 	td->td_critnest = 1;
203acbe332aSDavid Xu 	td->td_lend_user_pri = PRI_MAX;
204b209f889SRandall Stewart 	EVENTHANDLER_INVOKE(thread_ctor, td);
205911b84b0SRobert Watson #ifdef AUDIT
206911b84b0SRobert Watson 	audit_thread_alloc(td);
207911b84b0SRobert Watson #endif
208d10183d9SDavid Xu 	umtx_thread_alloc(td);
209b23f72e9SBrian Feldman 	return (0);
21044990b8cSJulian Elischer }
21144990b8cSJulian Elischer 
21244990b8cSJulian Elischer /*
21344990b8cSJulian Elischer  * Reclaim a thread after use.
21444990b8cSJulian Elischer  */
21544990b8cSJulian Elischer static void
21644990b8cSJulian Elischer thread_dtor(void *mem, int size, void *arg)
21744990b8cSJulian Elischer {
21844990b8cSJulian Elischer 	struct thread *td;
21944990b8cSJulian Elischer 
22044990b8cSJulian Elischer 	td = (struct thread *)mem;
22144990b8cSJulian Elischer 
22244990b8cSJulian Elischer #ifdef INVARIANTS
22344990b8cSJulian Elischer 	/* Verify that this thread is in a safe state to free. */
22444990b8cSJulian Elischer 	switch (td->td_state) {
22571fad9fdSJulian Elischer 	case TDS_INHIBITED:
22671fad9fdSJulian Elischer 	case TDS_RUNNING:
22771fad9fdSJulian Elischer 	case TDS_CAN_RUN:
22844990b8cSJulian Elischer 	case TDS_RUNQ:
22944990b8cSJulian Elischer 		/*
23044990b8cSJulian Elischer 		 * We must never unlink a thread that is in one of
23144990b8cSJulian Elischer 		 * these states, because it is currently active.
23244990b8cSJulian Elischer 		 */
23344990b8cSJulian Elischer 		panic("bad state for thread unlinking");
23444990b8cSJulian Elischer 		/* NOTREACHED */
23571fad9fdSJulian Elischer 	case TDS_INACTIVE:
23644990b8cSJulian Elischer 		break;
23744990b8cSJulian Elischer 	default:
23844990b8cSJulian Elischer 		panic("bad thread state");
23944990b8cSJulian Elischer 		/* NOTREACHED */
24044990b8cSJulian Elischer 	}
24144990b8cSJulian Elischer #endif
2426e8525ceSRobert Watson #ifdef AUDIT
2436e8525ceSRobert Watson 	audit_thread_free(td);
2446e8525ceSRobert Watson #endif
2451ba4a712SPawel Jakub Dawidek 	/* Free all OSD associated to this thread. */
2461ba4a712SPawel Jakub Dawidek 	osd_thread_exit(td);
247aca4bb91SKonstantin Belousov 	td_softdep_cleanup(td);
248aca4bb91SKonstantin Belousov 	MPASS(td->td_su == NULL);
2491ba4a712SPawel Jakub Dawidek 
250b209f889SRandall Stewart 	EVENTHANDLER_INVOKE(thread_dtor, td);
251ec6ea5e8SDavid Xu 	tid_free(td->td_tid);
25244990b8cSJulian Elischer }
25344990b8cSJulian Elischer 
25444990b8cSJulian Elischer /*
25544990b8cSJulian Elischer  * Initialize type-stable parts of a thread (when newly created).
25644990b8cSJulian Elischer  */
257b23f72e9SBrian Feldman static int
258b23f72e9SBrian Feldman thread_init(void *mem, int size, int flags)
25944990b8cSJulian Elischer {
26044990b8cSJulian Elischer 	struct thread *td;
26144990b8cSJulian Elischer 
26244990b8cSJulian Elischer 	td = (struct thread *)mem;
263247aba24SMarcel Moolenaar 
26444f3b092SJohn Baldwin 	td->td_sleepqueue = sleepq_alloc();
265961a7b24SJohn Baldwin 	td->td_turnstile = turnstile_alloc();
2668f0e9130SKonstantin Belousov 	td->td_rlqe = NULL;
267b209f889SRandall Stewart 	EVENTHANDLER_INVOKE(thread_init, td);
268d10183d9SDavid Xu 	umtx_thread_init(td);
26989b57fcfSKonstantin Belousov 	td->td_kstack = 0;
270ad8b1d85SKonstantin Belousov 	td->td_sel = NULL;
271b23f72e9SBrian Feldman 	return (0);
27244990b8cSJulian Elischer }
27344990b8cSJulian Elischer 
27444990b8cSJulian Elischer /*
27544990b8cSJulian Elischer  * Tear down type-stable parts of a thread (just before being discarded).
27644990b8cSJulian Elischer  */
27744990b8cSJulian Elischer static void
27844990b8cSJulian Elischer thread_fini(void *mem, int size)
27944990b8cSJulian Elischer {
28044990b8cSJulian Elischer 	struct thread *td;
28144990b8cSJulian Elischer 
28244990b8cSJulian Elischer 	td = (struct thread *)mem;
283b209f889SRandall Stewart 	EVENTHANDLER_INVOKE(thread_fini, td);
2848f0e9130SKonstantin Belousov 	rlqentry_free(td->td_rlqe);
285961a7b24SJohn Baldwin 	turnstile_free(td->td_turnstile);
28644f3b092SJohn Baldwin 	sleepq_free(td->td_sleepqueue);
287d10183d9SDavid Xu 	umtx_thread_fini(td);
288ace8398dSJeff Roberson 	seltdfini(td);
28944990b8cSJulian Elischer }
2905215b187SJeff Roberson 
2915c8329edSJulian Elischer /*
2925215b187SJeff Roberson  * For a newly created process,
2935215b187SJeff Roberson  * link up all the structures and its initial threads etc.
294ed062c8dSJulian Elischer  * called from:
295e7d939bdSMarcel Moolenaar  * {arch}/{arch}/machdep.c   {arch}_init(), init386() etc.
296ed062c8dSJulian Elischer  * proc_dtor() (should go away)
297ed062c8dSJulian Elischer  * proc_init()
2985c8329edSJulian Elischer  */
2995c8329edSJulian Elischer void
30089b57fcfSKonstantin Belousov proc_linkup0(struct proc *p, struct thread *td)
30189b57fcfSKonstantin Belousov {
30289b57fcfSKonstantin Belousov 	TAILQ_INIT(&p->p_threads);	     /* all threads in proc */
30389b57fcfSKonstantin Belousov 	proc_linkup(p, td);
30489b57fcfSKonstantin Belousov }
30589b57fcfSKonstantin Belousov 
30689b57fcfSKonstantin Belousov void
3078460a577SJohn Birrell proc_linkup(struct proc *p, struct thread *td)
3085c8329edSJulian Elischer {
309a54e85fdSJeff Roberson 
3109104847fSDavid Xu 	sigqueue_init(&p->p_sigqueue, p);
311ebceaf6dSDavid Xu 	p->p_ksi = ksiginfo_alloc(1);
312ebceaf6dSDavid Xu 	if (p->p_ksi != NULL) {
3135c474517SDavid Xu 		/* XXX p_ksi may be null if ksiginfo zone is not ready */
314ebceaf6dSDavid Xu 		p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
315ebceaf6dSDavid Xu 	}
316b2f92ef9SDavid Xu 	LIST_INIT(&p->p_mqnotifier);
3175c8329edSJulian Elischer 	p->p_numthreads = 0;
3188460a577SJohn Birrell 	thread_link(td, p);
3195c8329edSJulian Elischer }
3205c8329edSJulian Elischer 
3215c8329edSJulian Elischer /*
32244990b8cSJulian Elischer  * Initialize global thread allocation resources.
32344990b8cSJulian Elischer  */
32444990b8cSJulian Elischer void
32544990b8cSJulian Elischer threadinit(void)
32644990b8cSJulian Elischer {
32744990b8cSJulian Elischer 
3281ea7a6f8SPoul-Henning Kamp 	mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
32902c6fc21SKonstantin Belousov 
33002c6fc21SKonstantin Belousov 	/*
331abce621cSKonstantin Belousov 	 * pid_max cannot be greater than PID_MAX.
33202c6fc21SKonstantin Belousov 	 * leave one number for thread0.
33302c6fc21SKonstantin Belousov 	 */
3346829a5c5SJulian Elischer 	tid_unrhdr = new_unrhdr(PID_MAX + 2, INT_MAX, &tid_lock);
3351ea7a6f8SPoul-Henning Kamp 
336de028f5aSJeff Roberson 	thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
33744990b8cSJulian Elischer 	    thread_ctor, thread_dtor, thread_init, thread_fini,
338f743ea96SMateusz Guzik 	    32 - 1, UMA_ZONE_NOFREE);
339cf7d9a8cSDavid Xu 	tidhashtbl = hashinit(maxproc / 2, M_TIDHASH, &tidhash);
340cf7d9a8cSDavid Xu 	rw_init(&tidhash_lock, "tidhash");
34144990b8cSJulian Elischer }
34244990b8cSJulian Elischer 
34344990b8cSJulian Elischer /*
344ff8fbcffSJeff Roberson  * Place an unused thread on the zombie list.
345ad1e7d28SJulian Elischer  * Use the slpq as that must be unused by now.
34644990b8cSJulian Elischer  */
34744990b8cSJulian Elischer void
348ff8fbcffSJeff Roberson thread_zombie(struct thread *td)
34944990b8cSJulian Elischer {
350a54e85fdSJeff Roberson 	mtx_lock_spin(&zombie_lock);
351ad1e7d28SJulian Elischer 	TAILQ_INSERT_HEAD(&zombie_threads, td, td_slpq);
352a54e85fdSJeff Roberson 	mtx_unlock_spin(&zombie_lock);
35344990b8cSJulian Elischer }
35444990b8cSJulian Elischer 
3555c8329edSJulian Elischer /*
356ff8fbcffSJeff Roberson  * Release a thread that has exited after cpu_throw().
357ff8fbcffSJeff Roberson  */
358ff8fbcffSJeff Roberson void
359ff8fbcffSJeff Roberson thread_stash(struct thread *td)
360ff8fbcffSJeff Roberson {
361ff8fbcffSJeff Roberson 	atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
362ff8fbcffSJeff Roberson 	thread_zombie(td);
363ff8fbcffSJeff Roberson }
364ff8fbcffSJeff Roberson 
365ff8fbcffSJeff Roberson /*
3666617724cSJeff Roberson  * Reap zombie resources.
36744990b8cSJulian Elischer  */
36844990b8cSJulian Elischer void
36944990b8cSJulian Elischer thread_reap(void)
37044990b8cSJulian Elischer {
3715c8329edSJulian Elischer 	struct thread *td_first, *td_next;
37244990b8cSJulian Elischer 
37344990b8cSJulian Elischer 	/*
3745215b187SJeff Roberson 	 * Don't even bother to lock if none at this instant,
3752d19b736SKonstantin Belousov 	 * we really don't care about the next instant.
37644990b8cSJulian Elischer 	 */
3778460a577SJohn Birrell 	if (!TAILQ_EMPTY(&zombie_threads)) {
378a54e85fdSJeff Roberson 		mtx_lock_spin(&zombie_lock);
3795c8329edSJulian Elischer 		td_first = TAILQ_FIRST(&zombie_threads);
3805c8329edSJulian Elischer 		if (td_first)
3815c8329edSJulian Elischer 			TAILQ_INIT(&zombie_threads);
382a54e85fdSJeff Roberson 		mtx_unlock_spin(&zombie_lock);
3835c8329edSJulian Elischer 		while (td_first) {
384ad1e7d28SJulian Elischer 			td_next = TAILQ_NEXT(td_first, td_slpq);
3854ea6a9a2SMateusz Guzik 			thread_cow_free(td_first);
3865c8329edSJulian Elischer 			thread_free(td_first);
3875c8329edSJulian Elischer 			td_first = td_next;
38844990b8cSJulian Elischer 		}
38944990b8cSJulian Elischer 	}
390ed062c8dSJulian Elischer }
39144990b8cSJulian Elischer 
3924f0db5e0SJulian Elischer /*
39344990b8cSJulian Elischer  * Allocate a thread.
39444990b8cSJulian Elischer  */
39544990b8cSJulian Elischer struct thread *
3968a945d10SKonstantin Belousov thread_alloc(int pages)
39744990b8cSJulian Elischer {
39889b57fcfSKonstantin Belousov 	struct thread *td;
3998460a577SJohn Birrell 
40044990b8cSJulian Elischer 	thread_reap(); /* check if any zombies to get */
40189b57fcfSKonstantin Belousov 
40289b57fcfSKonstantin Belousov 	td = (struct thread *)uma_zalloc(thread_zone, M_WAITOK);
40389b57fcfSKonstantin Belousov 	KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
4048a945d10SKonstantin Belousov 	if (!vm_thread_new(td, pages)) {
40589b57fcfSKonstantin Belousov 		uma_zfree(thread_zone, td);
40689b57fcfSKonstantin Belousov 		return (NULL);
40789b57fcfSKonstantin Belousov 	}
4080c3967e7SMarcel Moolenaar 	cpu_thread_alloc(td);
4096520495aSAdrian Chadd 	vm_domain_policy_init(&td->td_vm_dom_policy);
41089b57fcfSKonstantin Belousov 	return (td);
41144990b8cSJulian Elischer }
41244990b8cSJulian Elischer 
4138a945d10SKonstantin Belousov int
4148a945d10SKonstantin Belousov thread_alloc_stack(struct thread *td, int pages)
4158a945d10SKonstantin Belousov {
4168a945d10SKonstantin Belousov 
4178a945d10SKonstantin Belousov 	KASSERT(td->td_kstack == 0,
4188a945d10SKonstantin Belousov 	    ("thread_alloc_stack called on a thread with kstack"));
4198a945d10SKonstantin Belousov 	if (!vm_thread_new(td, pages))
4208a945d10SKonstantin Belousov 		return (0);
4218a945d10SKonstantin Belousov 	cpu_thread_alloc(td);
4228a945d10SKonstantin Belousov 	return (1);
4238a945d10SKonstantin Belousov }
4244f0db5e0SJulian Elischer 
4254f0db5e0SJulian Elischer /*
42644990b8cSJulian Elischer  * Deallocate a thread.
42744990b8cSJulian Elischer  */
42844990b8cSJulian Elischer void
42944990b8cSJulian Elischer thread_free(struct thread *td)
43044990b8cSJulian Elischer {
4312e6b8de4SJeff Roberson 
4322e6b8de4SJeff Roberson 	lock_profile_thread_exit(td);
43345aea8deSJeff Roberson 	if (td->td_cpuset)
434d7f687fcSJeff Roberson 		cpuset_rel(td->td_cpuset);
435d7f687fcSJeff Roberson 	td->td_cpuset = NULL;
4360c3967e7SMarcel Moolenaar 	cpu_thread_free(td);
43789b57fcfSKonstantin Belousov 	if (td->td_kstack != 0)
43889b57fcfSKonstantin Belousov 		vm_thread_dispose(td);
4396520495aSAdrian Chadd 	vm_domain_policy_cleanup(&td->td_vm_dom_policy);
4402d19b736SKonstantin Belousov 	callout_drain(&td->td_slpcallout);
44144990b8cSJulian Elischer 	uma_zfree(thread_zone, td);
44244990b8cSJulian Elischer }
44344990b8cSJulian Elischer 
4444ea6a9a2SMateusz Guzik void
4454ea6a9a2SMateusz Guzik thread_cow_get_proc(struct thread *newtd, struct proc *p)
4464ea6a9a2SMateusz Guzik {
4474ea6a9a2SMateusz Guzik 
4484ea6a9a2SMateusz Guzik 	PROC_LOCK_ASSERT(p, MA_OWNED);
4494ea6a9a2SMateusz Guzik 	newtd->td_ucred = crhold(p->p_ucred);
450f6f6d240SMateusz Guzik 	newtd->td_limit = lim_hold(p->p_limit);
4514ea6a9a2SMateusz Guzik 	newtd->td_cowgen = p->p_cowgen;
4524ea6a9a2SMateusz Guzik }
4534ea6a9a2SMateusz Guzik 
4544ea6a9a2SMateusz Guzik void
4554ea6a9a2SMateusz Guzik thread_cow_get(struct thread *newtd, struct thread *td)
4564ea6a9a2SMateusz Guzik {
4574ea6a9a2SMateusz Guzik 
4584ea6a9a2SMateusz Guzik 	newtd->td_ucred = crhold(td->td_ucred);
459f6f6d240SMateusz Guzik 	newtd->td_limit = lim_hold(td->td_limit);
4604ea6a9a2SMateusz Guzik 	newtd->td_cowgen = td->td_cowgen;
4614ea6a9a2SMateusz Guzik }
4624ea6a9a2SMateusz Guzik 
4634ea6a9a2SMateusz Guzik void
4644ea6a9a2SMateusz Guzik thread_cow_free(struct thread *td)
4654ea6a9a2SMateusz Guzik {
4664ea6a9a2SMateusz Guzik 
467cd672ca6SMateusz Guzik 	if (td->td_ucred != NULL)
4684ea6a9a2SMateusz Guzik 		crfree(td->td_ucred);
469cd672ca6SMateusz Guzik 	if (td->td_limit != NULL)
470f6f6d240SMateusz Guzik 		lim_free(td->td_limit);
4714ea6a9a2SMateusz Guzik }
4724ea6a9a2SMateusz Guzik 
4734ea6a9a2SMateusz Guzik void
4744ea6a9a2SMateusz Guzik thread_cow_update(struct thread *td)
4754ea6a9a2SMateusz Guzik {
4764ea6a9a2SMateusz Guzik 	struct proc *p;
477cd672ca6SMateusz Guzik 	struct ucred *oldcred;
478cd672ca6SMateusz Guzik 	struct plimit *oldlimit;
4794ea6a9a2SMateusz Guzik 
4804ea6a9a2SMateusz Guzik 	p = td->td_proc;
481cd672ca6SMateusz Guzik 	oldcred = NULL;
482cd672ca6SMateusz Guzik 	oldlimit = NULL;
4834ea6a9a2SMateusz Guzik 	PROC_LOCK(p);
484cd672ca6SMateusz Guzik 	if (td->td_ucred != p->p_ucred) {
485cd672ca6SMateusz Guzik 		oldcred = td->td_ucred;
486cd672ca6SMateusz Guzik 		td->td_ucred = crhold(p->p_ucred);
487cd672ca6SMateusz Guzik 	}
488cd672ca6SMateusz Guzik 	if (td->td_limit != p->p_limit) {
489cd672ca6SMateusz Guzik 		oldlimit = td->td_limit;
490cd672ca6SMateusz Guzik 		td->td_limit = lim_hold(p->p_limit);
491cd672ca6SMateusz Guzik 	}
4924ea6a9a2SMateusz Guzik 	td->td_cowgen = p->p_cowgen;
4934ea6a9a2SMateusz Guzik 	PROC_UNLOCK(p);
494cd672ca6SMateusz Guzik 	if (oldcred != NULL)
495cd672ca6SMateusz Guzik 		crfree(oldcred);
496cd672ca6SMateusz Guzik 	if (oldlimit != NULL)
497cd672ca6SMateusz Guzik 		lim_free(oldlimit);
4984ea6a9a2SMateusz Guzik }
4994ea6a9a2SMateusz Guzik 
50044990b8cSJulian Elischer /*
50144990b8cSJulian Elischer  * Discard the current thread and exit from its context.
50294e0a4cdSJulian Elischer  * Always called with scheduler locked.
50344990b8cSJulian Elischer  *
50444990b8cSJulian Elischer  * Because we can't free a thread while we're operating under its context,
505696058c3SJulian Elischer  * push the current thread into our CPU's deadthread holder. This means
506696058c3SJulian Elischer  * we needn't worry about someone else grabbing our context before we
5076617724cSJeff Roberson  * do a cpu_throw().
50844990b8cSJulian Elischer  */
50944990b8cSJulian Elischer void
51044990b8cSJulian Elischer thread_exit(void)
51144990b8cSJulian Elischer {
5127e3a96eaSJohn Baldwin 	uint64_t runtime, new_switchtime;
51344990b8cSJulian Elischer 	struct thread *td;
5141c4bcd05SJeff Roberson 	struct thread *td2;
51544990b8cSJulian Elischer 	struct proc *p;
5167847a9daSJohn Baldwin 	int wakeup_swapper;
51744990b8cSJulian Elischer 
51844990b8cSJulian Elischer 	td = curthread;
51944990b8cSJulian Elischer 	p = td->td_proc;
52044990b8cSJulian Elischer 
521a54e85fdSJeff Roberson 	PROC_SLOCK_ASSERT(p, MA_OWNED);
522ed062c8dSJulian Elischer 	mtx_assert(&Giant, MA_NOTOWNED);
523a54e85fdSJeff Roberson 
52444990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
525ed062c8dSJulian Elischer 	KASSERT(p != NULL, ("thread exiting without a process"));
526cc701b73SRobert Watson 	CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
527e01eafefSJulian Elischer 	    (long)p->p_pid, td->td_name);
5286c9271a9SAndriy Gapon 	SDT_PROBE0(proc, , , lwp__exit);
5299104847fSDavid Xu 	KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
53044990b8cSJulian Elischer 
53189964dd2SRobert Watson #ifdef AUDIT
53289964dd2SRobert Watson 	AUDIT_SYSCALL_EXIT(0, td);
53389964dd2SRobert Watson #endif
534ed062c8dSJulian Elischer 	/*
535ed062c8dSJulian Elischer 	 * drop FPU & debug register state storage, or any other
536ed062c8dSJulian Elischer 	 * architecture specific resources that
537ed062c8dSJulian Elischer 	 * would not be on a new untouched process.
538ed062c8dSJulian Elischer 	 */
539bd07998eSKonstantin Belousov 	cpu_thread_exit(td);
54044990b8cSJulian Elischer 
541ed062c8dSJulian Elischer 	/*
5421faf202eSJulian Elischer 	 * The last thread is left attached to the process
5431faf202eSJulian Elischer 	 * So that the whole bundle gets recycled. Skip
544ed062c8dSJulian Elischer 	 * all this stuff if we never had threads.
545ed062c8dSJulian Elischer 	 * EXIT clears all sign of other threads when
546ed062c8dSJulian Elischer 	 * it goes to single threading, so the last thread always
547ed062c8dSJulian Elischer 	 * takes the short path.
5481faf202eSJulian Elischer 	 */
549ed062c8dSJulian Elischer 	if (p->p_flag & P_HADTHREADS) {
5501faf202eSJulian Elischer 		if (p->p_numthreads > 1) {
551fd229b5bSKonstantin Belousov 			atomic_add_int(&td->td_proc->p_exitthreads, 1);
552d3a0bd78SJulian Elischer 			thread_unlink(td);
5531c4bcd05SJeff Roberson 			td2 = FIRST_THREAD_IN_PROC(p);
5541c4bcd05SJeff Roberson 			sched_exit_thread(td2, td);
555ed062c8dSJulian Elischer 
556ed062c8dSJulian Elischer 			/*
55744990b8cSJulian Elischer 			 * The test below is NOT true if we are the
5589182554aSKonstantin Belousov 			 * sole exiting thread. P_STOPPED_SINGLE is unset
55944990b8cSJulian Elischer 			 * in exit1() after it is the only survivor.
56044990b8cSJulian Elischer 			 */
5611279572aSDavid Xu 			if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
56244990b8cSJulian Elischer 				if (p->p_numthreads == p->p_suspcount) {
563a54e85fdSJeff Roberson 					thread_lock(p->p_singlethread);
5647847a9daSJohn Baldwin 					wakeup_swapper = thread_unsuspend_one(
56584cdea97SKonstantin Belousov 						p->p_singlethread, p, false);
566a54e85fdSJeff Roberson 					thread_unlock(p->p_singlethread);
5677847a9daSJohn Baldwin 					if (wakeup_swapper)
5687847a9daSJohn Baldwin 						kick_proc0();
56944990b8cSJulian Elischer 				}
57044990b8cSJulian Elischer 			}
57148bfcdddSJulian Elischer 
572696058c3SJulian Elischer 			PCPU_SET(deadthread, td);
5731faf202eSJulian Elischer 		} else {
574ed062c8dSJulian Elischer 			/*
575ed062c8dSJulian Elischer 			 * The last thread is exiting.. but not through exit()
576ed062c8dSJulian Elischer 			 */
577ed062c8dSJulian Elischer 			panic ("thread_exit: Last thread exiting on its own");
578ed062c8dSJulian Elischer 		}
5791faf202eSJulian Elischer 	}
58016d95d4fSJoseph Koshy #ifdef	HWPMC_HOOKS
58116d95d4fSJoseph Koshy 	/*
58216d95d4fSJoseph Koshy 	 * If this thread is part of a process that is being tracked by hwpmc(4),
58316d95d4fSJoseph Koshy 	 * inform the module of the thread's impending exit.
58416d95d4fSJoseph Koshy 	 */
58516d95d4fSJoseph Koshy 	if (PMC_PROC_IS_USING_PMCS(td->td_proc))
58616d95d4fSJoseph Koshy 		PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
58716d95d4fSJoseph Koshy #endif
588a54e85fdSJeff Roberson 	PROC_UNLOCK(p);
5895c7bebf9SKonstantin Belousov 	PROC_STATLOCK(p);
5905c7bebf9SKonstantin Belousov 	thread_lock(td);
5915c7bebf9SKonstantin Belousov 	PROC_SUNLOCK(p);
5927e3a96eaSJohn Baldwin 
5937e3a96eaSJohn Baldwin 	/* Do the same timestamp bookkeeping that mi_switch() would do. */
5947e3a96eaSJohn Baldwin 	new_switchtime = cpu_ticks();
5957e3a96eaSJohn Baldwin 	runtime = new_switchtime - PCPU_GET(switchtime);
5967e3a96eaSJohn Baldwin 	td->td_runtime += runtime;
5977e3a96eaSJohn Baldwin 	td->td_incruntime += runtime;
5987e3a96eaSJohn Baldwin 	PCPU_SET(switchtime, new_switchtime);
5997e3a96eaSJohn Baldwin 	PCPU_SET(switchticks, ticks);
60083c9dea1SGleb Smirnoff 	VM_CNT_INC(v_swtch);
6017e3a96eaSJohn Baldwin 
6027e3a96eaSJohn Baldwin 	/* Save our resource usage in our process. */
6037e3a96eaSJohn Baldwin 	td->td_ru.ru_nvcsw++;
60441fd9c63SKonstantin Belousov 	ruxagg(p, td);
6057e3a96eaSJohn Baldwin 	rucollect(&p->p_ru, &td->td_ru);
6065c7bebf9SKonstantin Belousov 	PROC_STATUNLOCK(p);
6077e3a96eaSJohn Baldwin 
608dcc9954eSJulian Elischer 	td->td_state = TDS_INACTIVE;
6093d06b4b3SAttilio Rao #ifdef WITNESS
6103d06b4b3SAttilio Rao 	witness_thread_exit(td);
6113d06b4b3SAttilio Rao #endif
612732d9528SJulian Elischer 	CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
613a54e85fdSJeff Roberson 	sched_throw(td);
614cc66ebe2SPeter Wemm 	panic("I'm a teapot!");
61544990b8cSJulian Elischer 	/* NOTREACHED */
61644990b8cSJulian Elischer }
61744990b8cSJulian Elischer 
61844990b8cSJulian Elischer /*
619696058c3SJulian Elischer  * Do any thread specific cleanups that may be needed in wait()
62037814395SPeter Wemm  * called with Giant, proc and schedlock not held.
621696058c3SJulian Elischer  */
622696058c3SJulian Elischer void
623696058c3SJulian Elischer thread_wait(struct proc *p)
624696058c3SJulian Elischer {
625696058c3SJulian Elischer 	struct thread *td;
626696058c3SJulian Elischer 
62737814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
628624bf9e1SKonstantin Belousov 	KASSERT(p->p_numthreads == 1, ("multiple threads in thread_wait()"));
629624bf9e1SKonstantin Belousov 	KASSERT(p->p_exitthreads == 0, ("p_exitthreads leaking"));
630ff8fbcffSJeff Roberson 	td = FIRST_THREAD_IN_PROC(p);
631ff8fbcffSJeff Roberson 	/* Lock the last thread so we spin until it exits cpu_throw(). */
632ff8fbcffSJeff Roberson 	thread_lock(td);
633ff8fbcffSJeff Roberson 	thread_unlock(td);
6342e6b8de4SJeff Roberson 	lock_profile_thread_exit(td);
635d7f687fcSJeff Roberson 	cpuset_rel(td->td_cpuset);
636d7f687fcSJeff Roberson 	td->td_cpuset = NULL;
637696058c3SJulian Elischer 	cpu_thread_clean(td);
6384ea6a9a2SMateusz Guzik 	thread_cow_free(td);
6392d19b736SKonstantin Belousov 	callout_drain(&td->td_slpcallout);
640696058c3SJulian Elischer 	thread_reap();	/* check for zombie threads etc. */
641696058c3SJulian Elischer }
642696058c3SJulian Elischer 
643696058c3SJulian Elischer /*
64444990b8cSJulian Elischer  * Link a thread to a process.
6451faf202eSJulian Elischer  * set up anything that needs to be initialized for it to
6461faf202eSJulian Elischer  * be used by the process.
64744990b8cSJulian Elischer  */
64844990b8cSJulian Elischer void
6498460a577SJohn Birrell thread_link(struct thread *td, struct proc *p)
65044990b8cSJulian Elischer {
65144990b8cSJulian Elischer 
652a54e85fdSJeff Roberson 	/*
653a54e85fdSJeff Roberson 	 * XXX This can't be enabled because it's called for proc0 before
654374ae2a3SJeff Roberson 	 * its lock has been created.
655374ae2a3SJeff Roberson 	 * PROC_LOCK_ASSERT(p, MA_OWNED);
656a54e85fdSJeff Roberson 	 */
65771fad9fdSJulian Elischer 	td->td_state    = TDS_INACTIVE;
65844990b8cSJulian Elischer 	td->td_proc     = p;
659b61ce5b0SJeff Roberson 	td->td_flags    = TDF_INMEM;
66044990b8cSJulian Elischer 
6611faf202eSJulian Elischer 	LIST_INIT(&td->td_contested);
662eea4f254SJeff Roberson 	LIST_INIT(&td->td_lprof[0]);
663eea4f254SJeff Roberson 	LIST_INIT(&td->td_lprof[1]);
6649104847fSDavid Xu 	sigqueue_init(&td->td_sigqueue, p);
665fd90e2edSJung-uk Kim 	callout_init(&td->td_slpcallout, 1);
66666d8df9dSDaniel Eischen 	TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
66744990b8cSJulian Elischer 	p->p_numthreads++;
66844990b8cSJulian Elischer }
66944990b8cSJulian Elischer 
670ed062c8dSJulian Elischer /*
671ed062c8dSJulian Elischer  * Called from:
672ed062c8dSJulian Elischer  *  thread_exit()
673ed062c8dSJulian Elischer  */
674d3a0bd78SJulian Elischer void
675d3a0bd78SJulian Elischer thread_unlink(struct thread *td)
676d3a0bd78SJulian Elischer {
677d3a0bd78SJulian Elischer 	struct proc *p = td->td_proc;
678d3a0bd78SJulian Elischer 
679374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
680d3a0bd78SJulian Elischer 	TAILQ_REMOVE(&p->p_threads, td, td_plist);
681d3a0bd78SJulian Elischer 	p->p_numthreads--;
682d3a0bd78SJulian Elischer 	/* could clear a few other things here */
6838460a577SJohn Birrell 	/* Must  NOT clear links to proc! */
6845c8329edSJulian Elischer }
6855c8329edSJulian Elischer 
68679799053SKonstantin Belousov static int
68779799053SKonstantin Belousov calc_remaining(struct proc *p, int mode)
68879799053SKonstantin Belousov {
68979799053SKonstantin Belousov 	int remaining;
69079799053SKonstantin Belousov 
6917b519077SKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
6927b519077SKonstantin Belousov 	PROC_SLOCK_ASSERT(p, MA_OWNED);
69379799053SKonstantin Belousov 	if (mode == SINGLE_EXIT)
69479799053SKonstantin Belousov 		remaining = p->p_numthreads;
69579799053SKonstantin Belousov 	else if (mode == SINGLE_BOUNDARY)
69679799053SKonstantin Belousov 		remaining = p->p_numthreads - p->p_boundary_count;
6976ddcc233SKonstantin Belousov 	else if (mode == SINGLE_NO_EXIT || mode == SINGLE_ALLPROC)
69879799053SKonstantin Belousov 		remaining = p->p_numthreads - p->p_suspcount;
69979799053SKonstantin Belousov 	else
70079799053SKonstantin Belousov 		panic("calc_remaining: wrong mode %d", mode);
70179799053SKonstantin Belousov 	return (remaining);
70279799053SKonstantin Belousov }
70379799053SKonstantin Belousov 
70407a9368aSKonstantin Belousov static int
70507a9368aSKonstantin Belousov remain_for_mode(int mode)
70607a9368aSKonstantin Belousov {
70707a9368aSKonstantin Belousov 
7086ddcc233SKonstantin Belousov 	return (mode == SINGLE_ALLPROC ? 0 : 1);
70907a9368aSKonstantin Belousov }
71007a9368aSKonstantin Belousov 
71107a9368aSKonstantin Belousov static int
71207a9368aSKonstantin Belousov weed_inhib(int mode, struct thread *td2, struct proc *p)
71307a9368aSKonstantin Belousov {
71407a9368aSKonstantin Belousov 	int wakeup_swapper;
71507a9368aSKonstantin Belousov 
71607a9368aSKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
71707a9368aSKonstantin Belousov 	PROC_SLOCK_ASSERT(p, MA_OWNED);
71807a9368aSKonstantin Belousov 	THREAD_LOCK_ASSERT(td2, MA_OWNED);
71907a9368aSKonstantin Belousov 
72007a9368aSKonstantin Belousov 	wakeup_swapper = 0;
72107a9368aSKonstantin Belousov 	switch (mode) {
72207a9368aSKonstantin Belousov 	case SINGLE_EXIT:
72307a9368aSKonstantin Belousov 		if (TD_IS_SUSPENDED(td2))
72484cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, true);
72507a9368aSKonstantin Belousov 		if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0)
72607a9368aSKonstantin Belousov 			wakeup_swapper |= sleepq_abort(td2, EINTR);
72707a9368aSKonstantin Belousov 		break;
72807a9368aSKonstantin Belousov 	case SINGLE_BOUNDARY:
72907a9368aSKonstantin Belousov 	case SINGLE_NO_EXIT:
73007a9368aSKonstantin Belousov 		if (TD_IS_SUSPENDED(td2) && (td2->td_flags & TDF_BOUNDARY) == 0)
73184cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
73207a9368aSKonstantin Belousov 		if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0)
73307a9368aSKonstantin Belousov 			wakeup_swapper |= sleepq_abort(td2, ERESTART);
734917dd390SKonstantin Belousov 		break;
7356ddcc233SKonstantin Belousov 	case SINGLE_ALLPROC:
7366ddcc233SKonstantin Belousov 		/*
7376ddcc233SKonstantin Belousov 		 * ALLPROC suspend tries to avoid spurious EINTR for
7386ddcc233SKonstantin Belousov 		 * threads sleeping interruptable, by suspending the
7396ddcc233SKonstantin Belousov 		 * thread directly, similarly to sig_suspend_threads().
7406ddcc233SKonstantin Belousov 		 * Since such sleep is not performed at the user
7416ddcc233SKonstantin Belousov 		 * boundary, TDF_BOUNDARY flag is not set, and TDF_ALLPROCSUSP
7426ddcc233SKonstantin Belousov 		 * is used to avoid immediate un-suspend.
7436ddcc233SKonstantin Belousov 		 */
7446ddcc233SKonstantin Belousov 		if (TD_IS_SUSPENDED(td2) && (td2->td_flags & (TDF_BOUNDARY |
7456ddcc233SKonstantin Belousov 		    TDF_ALLPROCSUSP)) == 0)
74684cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
7476ddcc233SKonstantin Belousov 		if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0) {
7486ddcc233SKonstantin Belousov 			if ((td2->td_flags & TDF_SBDRY) == 0) {
7496ddcc233SKonstantin Belousov 				thread_suspend_one(td2);
7506ddcc233SKonstantin Belousov 				td2->td_flags |= TDF_ALLPROCSUSP;
7516ddcc233SKonstantin Belousov 			} else {
7526ddcc233SKonstantin Belousov 				wakeup_swapper |= sleepq_abort(td2, ERESTART);
7536ddcc233SKonstantin Belousov 			}
7546ddcc233SKonstantin Belousov 		}
75507a9368aSKonstantin Belousov 		break;
75607a9368aSKonstantin Belousov 	}
75707a9368aSKonstantin Belousov 	return (wakeup_swapper);
75807a9368aSKonstantin Belousov }
75907a9368aSKonstantin Belousov 
7605215b187SJeff Roberson /*
76144990b8cSJulian Elischer  * Enforce single-threading.
76244990b8cSJulian Elischer  *
76344990b8cSJulian Elischer  * Returns 1 if the caller must abort (another thread is waiting to
76444990b8cSJulian Elischer  * exit the process or similar). Process is locked!
76544990b8cSJulian Elischer  * Returns 0 when you are successfully the only thread running.
76644990b8cSJulian Elischer  * A process has successfully single threaded in the suspend mode when
76744990b8cSJulian Elischer  * There are no threads in user mode. Threads in the kernel must be
76844990b8cSJulian Elischer  * allowed to continue until they get to the user boundary. They may even
76944990b8cSJulian Elischer  * copy out their return values and data before suspending. They may however be
770e2668f55SMaxim Konovalov  * accelerated in reaching the user boundary as we will wake up
77144990b8cSJulian Elischer  * any sleeping threads that are interruptable. (PCATCH).
77244990b8cSJulian Elischer  */
77344990b8cSJulian Elischer int
7746ddcc233SKonstantin Belousov thread_single(struct proc *p, int mode)
77544990b8cSJulian Elischer {
77644990b8cSJulian Elischer 	struct thread *td;
77744990b8cSJulian Elischer 	struct thread *td2;
778da7bbd2cSJohn Baldwin 	int remaining, wakeup_swapper;
77944990b8cSJulian Elischer 
78044990b8cSJulian Elischer 	td = curthread;
7816ddcc233SKonstantin Belousov 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
7826ddcc233SKonstantin Belousov 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
7836ddcc233SKonstantin Belousov 	    ("invalid mode %d", mode));
7846ddcc233SKonstantin Belousov 	/*
7856ddcc233SKonstantin Belousov 	 * If allowing non-ALLPROC singlethreading for non-curproc
7866ddcc233SKonstantin Belousov 	 * callers, calc_remaining() and remain_for_mode() should be
7876ddcc233SKonstantin Belousov 	 * adjusted to also account for td->td_proc != p.  For now
7886ddcc233SKonstantin Belousov 	 * this is not implemented because it is not used.
7896ddcc233SKonstantin Belousov 	 */
7906ddcc233SKonstantin Belousov 	KASSERT((mode == SINGLE_ALLPROC && td->td_proc != p) ||
7916ddcc233SKonstantin Belousov 	    (mode != SINGLE_ALLPROC && td->td_proc == p),
7926ddcc233SKonstantin Belousov 	    ("mode %d proc %p curproc %p", mode, p, td->td_proc));
79337814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
79444990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
79544990b8cSJulian Elischer 
7966ddcc233SKonstantin Belousov 	if ((p->p_flag & P_HADTHREADS) == 0 && mode != SINGLE_ALLPROC)
79744990b8cSJulian Elischer 		return (0);
79844990b8cSJulian Elischer 
799e3b9bf71SJulian Elischer 	/* Is someone already single threading? */
800906ac69dSDavid Xu 	if (p->p_singlethread != NULL && p->p_singlethread != td)
80144990b8cSJulian Elischer 		return (1);
80244990b8cSJulian Elischer 
803906ac69dSDavid Xu 	if (mode == SINGLE_EXIT) {
804906ac69dSDavid Xu 		p->p_flag |= P_SINGLE_EXIT;
805906ac69dSDavid Xu 		p->p_flag &= ~P_SINGLE_BOUNDARY;
806906ac69dSDavid Xu 	} else {
807906ac69dSDavid Xu 		p->p_flag &= ~P_SINGLE_EXIT;
808906ac69dSDavid Xu 		if (mode == SINGLE_BOUNDARY)
809906ac69dSDavid Xu 			p->p_flag |= P_SINGLE_BOUNDARY;
810906ac69dSDavid Xu 		else
811906ac69dSDavid Xu 			p->p_flag &= ~P_SINGLE_BOUNDARY;
812906ac69dSDavid Xu 	}
8136ddcc233SKonstantin Belousov 	if (mode == SINGLE_ALLPROC)
8146ddcc233SKonstantin Belousov 		p->p_flag |= P_TOTAL_STOP;
8151279572aSDavid Xu 	p->p_flag |= P_STOPPED_SINGLE;
8167b4a950aSDavid Xu 	PROC_SLOCK(p);
817112afcb2SJohn Baldwin 	p->p_singlethread = td;
81879799053SKonstantin Belousov 	remaining = calc_remaining(p, mode);
81907a9368aSKonstantin Belousov 	while (remaining != remain_for_mode(mode)) {
820bf1a3220SDavid Xu 		if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
821bf1a3220SDavid Xu 			goto stopme;
822da7bbd2cSJohn Baldwin 		wakeup_swapper = 0;
82344990b8cSJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td2) {
82444990b8cSJulian Elischer 			if (td2 == td)
82544990b8cSJulian Elischer 				continue;
826a54e85fdSJeff Roberson 			thread_lock(td2);
827b7edba77SJeff Roberson 			td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
8286ddcc233SKonstantin Belousov 			if (TD_IS_INHIBITED(td2)) {
82907a9368aSKonstantin Belousov 				wakeup_swapper |= weed_inhib(mode, td2, p);
830d8267df7SDavid Xu #ifdef SMP
8316ddcc233SKonstantin Belousov 			} else if (TD_IS_RUNNING(td2) && td != td2) {
832d8267df7SDavid Xu 				forward_signal(td2);
833d8267df7SDavid Xu #endif
8346ddcc233SKonstantin Belousov 			}
835a54e85fdSJeff Roberson 			thread_unlock(td2);
8369d102777SJulian Elischer 		}
837da7bbd2cSJohn Baldwin 		if (wakeup_swapper)
838da7bbd2cSJohn Baldwin 			kick_proc0();
83979799053SKonstantin Belousov 		remaining = calc_remaining(p, mode);
840ec008e96SDavid Xu 
8419d102777SJulian Elischer 		/*
8429d102777SJulian Elischer 		 * Maybe we suspended some threads.. was it enough?
8439d102777SJulian Elischer 		 */
84407a9368aSKonstantin Belousov 		if (remaining == remain_for_mode(mode))
8459d102777SJulian Elischer 			break;
8469d102777SJulian Elischer 
847bf1a3220SDavid Xu stopme:
84844990b8cSJulian Elischer 		/*
84944990b8cSJulian Elischer 		 * Wake us up when everyone else has suspended.
850e3b9bf71SJulian Elischer 		 * In the mean time we suspend as well.
85144990b8cSJulian Elischer 		 */
8526ddcc233SKonstantin Belousov 		thread_suspend_switch(td, p);
85379799053SKonstantin Belousov 		remaining = calc_remaining(p, mode);
85444990b8cSJulian Elischer 	}
855906ac69dSDavid Xu 	if (mode == SINGLE_EXIT) {
85691599697SJulian Elischer 		/*
8578626a0ddSKonstantin Belousov 		 * Convert the process to an unthreaded process.  The
8588626a0ddSKonstantin Belousov 		 * SINGLE_EXIT is called by exit1() or execve(), in
8598626a0ddSKonstantin Belousov 		 * both cases other threads must be retired.
86091599697SJulian Elischer 		 */
8618626a0ddSKonstantin Belousov 		KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
862ed062c8dSJulian Elischer 		p->p_singlethread = NULL;
8638626a0ddSKonstantin Belousov 		p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
864fd229b5bSKonstantin Belousov 
865fd229b5bSKonstantin Belousov 		/*
866fd229b5bSKonstantin Belousov 		 * Wait for any remaining threads to exit cpu_throw().
867fd229b5bSKonstantin Belousov 		 */
868fd229b5bSKonstantin Belousov 		while (p->p_exitthreads != 0) {
869fd229b5bSKonstantin Belousov 			PROC_SUNLOCK(p);
870fd229b5bSKonstantin Belousov 			PROC_UNLOCK(p);
871fd229b5bSKonstantin Belousov 			sched_relinquish(td);
872fd229b5bSKonstantin Belousov 			PROC_LOCK(p);
873fd229b5bSKonstantin Belousov 			PROC_SLOCK(p);
874fd229b5bSKonstantin Belousov 		}
875ac437c07SKonstantin Belousov 	} else if (mode == SINGLE_BOUNDARY) {
876ac437c07SKonstantin Belousov 		/*
877ac437c07SKonstantin Belousov 		 * Wait until all suspended threads are removed from
878ac437c07SKonstantin Belousov 		 * the processors.  The thread_suspend_check()
879ac437c07SKonstantin Belousov 		 * increments p_boundary_count while it is still
880ac437c07SKonstantin Belousov 		 * running, which makes it possible for the execve()
881ac437c07SKonstantin Belousov 		 * to destroy vmspace while our other threads are
882ac437c07SKonstantin Belousov 		 * still using the address space.
883ac437c07SKonstantin Belousov 		 *
884ac437c07SKonstantin Belousov 		 * We lock the thread, which is only allowed to
885ac437c07SKonstantin Belousov 		 * succeed after context switch code finished using
886ac437c07SKonstantin Belousov 		 * the address space.
887ac437c07SKonstantin Belousov 		 */
888ac437c07SKonstantin Belousov 		FOREACH_THREAD_IN_PROC(p, td2) {
889ac437c07SKonstantin Belousov 			if (td2 == td)
890ac437c07SKonstantin Belousov 				continue;
891ac437c07SKonstantin Belousov 			thread_lock(td2);
892ac437c07SKonstantin Belousov 			KASSERT((td2->td_flags & TDF_BOUNDARY) != 0,
893ac437c07SKonstantin Belousov 			    ("td %p not on boundary", td2));
894ac437c07SKonstantin Belousov 			KASSERT(TD_IS_SUSPENDED(td2),
895ac437c07SKonstantin Belousov 			    ("td %p is not suspended", td2));
896ac437c07SKonstantin Belousov 			thread_unlock(td2);
897ac437c07SKonstantin Belousov 		}
89891599697SJulian Elischer 	}
8997b4a950aSDavid Xu 	PROC_SUNLOCK(p);
90044990b8cSJulian Elischer 	return (0);
90144990b8cSJulian Elischer }
90244990b8cSJulian Elischer 
9038638fe7bSKonstantin Belousov bool
9048638fe7bSKonstantin Belousov thread_suspend_check_needed(void)
9058638fe7bSKonstantin Belousov {
9068638fe7bSKonstantin Belousov 	struct proc *p;
9078638fe7bSKonstantin Belousov 	struct thread *td;
9088638fe7bSKonstantin Belousov 
9098638fe7bSKonstantin Belousov 	td = curthread;
9108638fe7bSKonstantin Belousov 	p = td->td_proc;
9118638fe7bSKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
9128638fe7bSKonstantin Belousov 	return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
9138638fe7bSKonstantin Belousov 	    (td->td_dbgflags & TDB_SUSPEND) != 0));
9148638fe7bSKonstantin Belousov }
9158638fe7bSKonstantin Belousov 
91644990b8cSJulian Elischer /*
91744990b8cSJulian Elischer  * Called in from locations that can safely check to see
91844990b8cSJulian Elischer  * whether we have to suspend or at least throttle for a
91944990b8cSJulian Elischer  * single-thread event (e.g. fork).
92044990b8cSJulian Elischer  *
92144990b8cSJulian Elischer  * Such locations include userret().
92244990b8cSJulian Elischer  * If the "return_instead" argument is non zero, the thread must be able to
92344990b8cSJulian Elischer  * accept 0 (caller may continue), or 1 (caller must abort) as a result.
92444990b8cSJulian Elischer  *
92544990b8cSJulian Elischer  * The 'return_instead' argument tells the function if it may do a
92644990b8cSJulian Elischer  * thread_exit() or suspend, or whether the caller must abort and back
92744990b8cSJulian Elischer  * out instead.
92844990b8cSJulian Elischer  *
92944990b8cSJulian Elischer  * If the thread that set the single_threading request has set the
93044990b8cSJulian Elischer  * P_SINGLE_EXIT bit in the process flags then this call will never return
93144990b8cSJulian Elischer  * if 'return_instead' is false, but will exit.
93244990b8cSJulian Elischer  *
93344990b8cSJulian Elischer  * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
93444990b8cSJulian Elischer  *---------------+--------------------+---------------------
93544990b8cSJulian Elischer  *       0       | returns 0          |   returns 0 or 1
936353374b5SJohn Baldwin  *               | when ST ends       |   immediately
93744990b8cSJulian Elischer  *---------------+--------------------+---------------------
93844990b8cSJulian Elischer  *       1       | thread exits       |   returns 1
939353374b5SJohn Baldwin  *               |                    |  immediately
94044990b8cSJulian Elischer  * 0 = thread_exit() or suspension ok,
94144990b8cSJulian Elischer  * other = return error instead of stopping the thread.
94244990b8cSJulian Elischer  *
94344990b8cSJulian Elischer  * While a full suspension is under effect, even a single threading
94444990b8cSJulian Elischer  * thread would be suspended if it made this call (but it shouldn't).
94544990b8cSJulian Elischer  * This call should only be made from places where
94644990b8cSJulian Elischer  * thread_exit() would be safe as that may be the outcome unless
94744990b8cSJulian Elischer  * return_instead is set.
94844990b8cSJulian Elischer  */
94944990b8cSJulian Elischer int
95044990b8cSJulian Elischer thread_suspend_check(int return_instead)
95144990b8cSJulian Elischer {
952ecafb24bSJuli Mallett 	struct thread *td;
953ecafb24bSJuli Mallett 	struct proc *p;
95446e47c4fSKonstantin Belousov 	int wakeup_swapper;
95544990b8cSJulian Elischer 
95644990b8cSJulian Elischer 	td = curthread;
95744990b8cSJulian Elischer 	p = td->td_proc;
95837814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
95944990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
9608638fe7bSKonstantin Belousov 	while (thread_suspend_check_needed()) {
9611279572aSDavid Xu 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
96244990b8cSJulian Elischer 			KASSERT(p->p_singlethread != NULL,
96344990b8cSJulian Elischer 			    ("singlethread not set"));
96444990b8cSJulian Elischer 			/*
965e3b9bf71SJulian Elischer 			 * The only suspension in action is a
966e3b9bf71SJulian Elischer 			 * single-threading. Single threader need not stop.
967bd07998eSKonstantin Belousov 			 * It is safe to access p->p_singlethread unlocked
968bd07998eSKonstantin Belousov 			 * because it can only be set to our address by us.
96944990b8cSJulian Elischer 			 */
970e3b9bf71SJulian Elischer 			if (p->p_singlethread == td)
97144990b8cSJulian Elischer 				return (0);	/* Exempt from stopping. */
97244990b8cSJulian Elischer 		}
97345a4bfa1SDavid Xu 		if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
97494f0972bSDavid Xu 			return (EINTR);
97544990b8cSJulian Elischer 
976906ac69dSDavid Xu 		/* Should we goto user boundary if we didn't come from there? */
977906ac69dSDavid Xu 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
978906ac69dSDavid Xu 		    (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
97994f0972bSDavid Xu 			return (ERESTART);
980906ac69dSDavid Xu 
98144990b8cSJulian Elischer 		/*
9823077f938SKonstantin Belousov 		 * Ignore suspend requests if they are deferred.
983d071a6faSJohn Baldwin 		 */
9843077f938SKonstantin Belousov 		if ((td->td_flags & TDF_SBDRY) != 0) {
985d071a6faSJohn Baldwin 			KASSERT(return_instead,
986d071a6faSJohn Baldwin 			    ("TDF_SBDRY set for unsafe thread_suspend_check"));
98746e47c4fSKonstantin Belousov 			KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
98846e47c4fSKonstantin Belousov 			    (TDF_SEINTR | TDF_SERESTART),
98946e47c4fSKonstantin Belousov 			    ("both TDF_SEINTR and TDF_SERESTART"));
99046e47c4fSKonstantin Belousov 			return (TD_SBDRY_INTR(td) ? TD_SBDRY_ERRNO(td) : 0);
991d071a6faSJohn Baldwin 		}
992d071a6faSJohn Baldwin 
993d071a6faSJohn Baldwin 		/*
99444990b8cSJulian Elischer 		 * If the process is waiting for us to exit,
99544990b8cSJulian Elischer 		 * this thread should just suicide.
9961279572aSDavid Xu 		 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
99744990b8cSJulian Elischer 		 */
998cf7d9a8cSDavid Xu 		if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
999cf7d9a8cSDavid Xu 			PROC_UNLOCK(p);
100091d1786fSDmitry Chagin 
100191d1786fSDmitry Chagin 			/*
100291d1786fSDmitry Chagin 			 * Allow Linux emulation layer to do some work
100391d1786fSDmitry Chagin 			 * before thread suicide.
100491d1786fSDmitry Chagin 			 */
100591d1786fSDmitry Chagin 			if (__predict_false(p->p_sysent->sv_thread_detach != NULL))
100691d1786fSDmitry Chagin 				(p->p_sysent->sv_thread_detach)(td);
10072a339d9eSKonstantin Belousov 			umtx_thread_exit(td);
1008d1e7a4a5SJohn Baldwin 			kern_thr_exit(td);
1009d1e7a4a5SJohn Baldwin 			panic("stopped thread did not exit");
1010cf7d9a8cSDavid Xu 		}
101121ecd1e9SDavid Xu 
101221ecd1e9SDavid Xu 		PROC_SLOCK(p);
101321ecd1e9SDavid Xu 		thread_stopped(p);
1014a54e85fdSJeff Roberson 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1015a54e85fdSJeff Roberson 			if (p->p_numthreads == p->p_suspcount + 1) {
1016a54e85fdSJeff Roberson 				thread_lock(p->p_singlethread);
101784cdea97SKonstantin Belousov 				wakeup_swapper = thread_unsuspend_one(
101884cdea97SKonstantin Belousov 				    p->p_singlethread, p, false);
1019a54e85fdSJeff Roberson 				thread_unlock(p->p_singlethread);
10207847a9daSJohn Baldwin 				if (wakeup_swapper)
10217847a9daSJohn Baldwin 					kick_proc0();
1022a54e85fdSJeff Roberson 			}
1023a54e85fdSJeff Roberson 		}
10243f9be10eSDavid Xu 		PROC_UNLOCK(p);
10257b4a950aSDavid Xu 		thread_lock(td);
102644990b8cSJulian Elischer 		/*
102744990b8cSJulian Elischer 		 * When a thread suspends, it just
1028ad1e7d28SJulian Elischer 		 * gets taken off all queues.
102944990b8cSJulian Elischer 		 */
103071fad9fdSJulian Elischer 		thread_suspend_one(td);
1031906ac69dSDavid Xu 		if (return_instead == 0) {
1032906ac69dSDavid Xu 			p->p_boundary_count++;
1033906ac69dSDavid Xu 			td->td_flags |= TDF_BOUNDARY;
1034cf19bf91SJulian Elischer 		}
10357b4a950aSDavid Xu 		PROC_SUNLOCK(p);
10368df78c41SJeff Roberson 		mi_switch(SW_INVOL | SWT_SUSPEND, NULL);
1037a54e85fdSJeff Roberson 		thread_unlock(td);
103844990b8cSJulian Elischer 		PROC_LOCK(p);
103944990b8cSJulian Elischer 	}
104044990b8cSJulian Elischer 	return (0);
104144990b8cSJulian Elischer }
104244990b8cSJulian Elischer 
104335c32a76SDavid Xu void
10446ddcc233SKonstantin Belousov thread_suspend_switch(struct thread *td, struct proc *p)
1045a54e85fdSJeff Roberson {
1046a54e85fdSJeff Roberson 
1047a54e85fdSJeff Roberson 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1048a54e85fdSJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
10497b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1050a54e85fdSJeff Roberson 	/*
1051a54e85fdSJeff Roberson 	 * We implement thread_suspend_one in stages here to avoid
1052a54e85fdSJeff Roberson 	 * dropping the proc lock while the thread lock is owned.
1053a54e85fdSJeff Roberson 	 */
10546ddcc233SKonstantin Belousov 	if (p == td->td_proc) {
1055a54e85fdSJeff Roberson 		thread_stopped(p);
1056a54e85fdSJeff Roberson 		p->p_suspcount++;
10576ddcc233SKonstantin Belousov 	}
10583f9be10eSDavid Xu 	PROC_UNLOCK(p);
10597b4a950aSDavid Xu 	thread_lock(td);
1060b7edba77SJeff Roberson 	td->td_flags &= ~TDF_NEEDSUSPCHK;
1061a54e85fdSJeff Roberson 	TD_SET_SUSPENDED(td);
1062c5aa6b58SJeff Roberson 	sched_sleep(td, 0);
10637b4a950aSDavid Xu 	PROC_SUNLOCK(p);
1064a54e85fdSJeff Roberson 	DROP_GIANT();
10658df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_SUSPEND, NULL);
1066a54e85fdSJeff Roberson 	thread_unlock(td);
1067a54e85fdSJeff Roberson 	PICKUP_GIANT();
1068a54e85fdSJeff Roberson 	PROC_LOCK(p);
10697b4a950aSDavid Xu 	PROC_SLOCK(p);
1070a54e85fdSJeff Roberson }
1071a54e85fdSJeff Roberson 
1072a54e85fdSJeff Roberson void
107335c32a76SDavid Xu thread_suspend_one(struct thread *td)
107435c32a76SDavid Xu {
10756ddcc233SKonstantin Belousov 	struct proc *p;
107635c32a76SDavid Xu 
10776ddcc233SKonstantin Belousov 	p = td->td_proc;
10787b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1079a54e85fdSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1080e574e444SDavid Xu 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
108135c32a76SDavid Xu 	p->p_suspcount++;
1082b7edba77SJeff Roberson 	td->td_flags &= ~TDF_NEEDSUSPCHK;
108371fad9fdSJulian Elischer 	TD_SET_SUSPENDED(td);
1084c5aa6b58SJeff Roberson 	sched_sleep(td, 0);
108535c32a76SDavid Xu }
108635c32a76SDavid Xu 
108784cdea97SKonstantin Belousov static int
108884cdea97SKonstantin Belousov thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
108935c32a76SDavid Xu {
109035c32a76SDavid Xu 
1091a54e85fdSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1092ad1e7d28SJulian Elischer 	KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
109371fad9fdSJulian Elischer 	TD_CLR_SUSPENDED(td);
10946ddcc233SKonstantin Belousov 	td->td_flags &= ~TDF_ALLPROCSUSP;
10956ddcc233SKonstantin Belousov 	if (td->td_proc == p) {
10966ddcc233SKonstantin Belousov 		PROC_SLOCK_ASSERT(p, MA_OWNED);
109735c32a76SDavid Xu 		p->p_suspcount--;
109884cdea97SKonstantin Belousov 		if (boundary && (td->td_flags & TDF_BOUNDARY) != 0) {
109984cdea97SKonstantin Belousov 			td->td_flags &= ~TDF_BOUNDARY;
110084cdea97SKonstantin Belousov 			p->p_boundary_count--;
110184cdea97SKonstantin Belousov 		}
11026ddcc233SKonstantin Belousov 	}
11037847a9daSJohn Baldwin 	return (setrunnable(td));
110435c32a76SDavid Xu }
110535c32a76SDavid Xu 
110644990b8cSJulian Elischer /*
110744990b8cSJulian Elischer  * Allow all threads blocked by single threading to continue running.
110844990b8cSJulian Elischer  */
110944990b8cSJulian Elischer void
111044990b8cSJulian Elischer thread_unsuspend(struct proc *p)
111144990b8cSJulian Elischer {
111244990b8cSJulian Elischer 	struct thread *td;
11137847a9daSJohn Baldwin 	int wakeup_swapper;
111444990b8cSJulian Elischer 
111544990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
11167b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
11177847a9daSJohn Baldwin 	wakeup_swapper = 0;
111844990b8cSJulian Elischer 	if (!P_SHOULDSTOP(p)) {
1119ad1e7d28SJulian Elischer                 FOREACH_THREAD_IN_PROC(p, td) {
1120a54e85fdSJeff Roberson 			thread_lock(td);
1121ad1e7d28SJulian Elischer 			if (TD_IS_SUSPENDED(td)) {
112284cdea97SKonstantin Belousov 				wakeup_swapper |= thread_unsuspend_one(td, p,
112384cdea97SKonstantin Belousov 				    true);
112444990b8cSJulian Elischer 			}
1125a54e85fdSJeff Roberson 			thread_unlock(td);
1126ad1e7d28SJulian Elischer 		}
112784cdea97SKonstantin Belousov 	} else if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
112884cdea97SKonstantin Belousov 	    p->p_numthreads == p->p_suspcount) {
112944990b8cSJulian Elischer 		/*
113044990b8cSJulian Elischer 		 * Stopping everything also did the job for the single
113144990b8cSJulian Elischer 		 * threading request. Now we've downgraded to single-threaded,
113244990b8cSJulian Elischer 		 * let it continue.
113344990b8cSJulian Elischer 		 */
11346ddcc233SKonstantin Belousov 		if (p->p_singlethread->td_proc == p) {
1135a54e85fdSJeff Roberson 			thread_lock(p->p_singlethread);
11366ddcc233SKonstantin Belousov 			wakeup_swapper = thread_unsuspend_one(
113784cdea97SKonstantin Belousov 			    p->p_singlethread, p, false);
1138a54e85fdSJeff Roberson 			thread_unlock(p->p_singlethread);
113944990b8cSJulian Elischer 		}
11406ddcc233SKonstantin Belousov 	}
11417847a9daSJohn Baldwin 	if (wakeup_swapper)
11427847a9daSJohn Baldwin 		kick_proc0();
114344990b8cSJulian Elischer }
114444990b8cSJulian Elischer 
1145ed062c8dSJulian Elischer /*
1146ed062c8dSJulian Elischer  * End the single threading mode..
1147ed062c8dSJulian Elischer  */
114844990b8cSJulian Elischer void
11496ddcc233SKonstantin Belousov thread_single_end(struct proc *p, int mode)
115044990b8cSJulian Elischer {
115144990b8cSJulian Elischer 	struct thread *td;
11527847a9daSJohn Baldwin 	int wakeup_swapper;
115344990b8cSJulian Elischer 
11546ddcc233SKonstantin Belousov 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
11556ddcc233SKonstantin Belousov 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
11566ddcc233SKonstantin Belousov 	    ("invalid mode %d", mode));
115744990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
11586ddcc233SKonstantin Belousov 	KASSERT((mode == SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) != 0) ||
11596ddcc233SKonstantin Belousov 	    (mode != SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) == 0),
11606ddcc233SKonstantin Belousov 	    ("mode %d does not match P_TOTAL_STOP", mode));
116184cdea97SKonstantin Belousov 	KASSERT(mode == SINGLE_ALLPROC || p->p_singlethread == curthread,
116284cdea97SKonstantin Belousov 	    ("thread_single_end from other thread %p %p",
116384cdea97SKonstantin Belousov 	    curthread, p->p_singlethread));
116484cdea97SKonstantin Belousov 	KASSERT(mode != SINGLE_BOUNDARY ||
116584cdea97SKonstantin Belousov 	    (p->p_flag & P_SINGLE_BOUNDARY) != 0,
116684cdea97SKonstantin Belousov 	    ("mis-matched SINGLE_BOUNDARY flags %x", p->p_flag));
11676ddcc233SKonstantin Belousov 	p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY |
11686ddcc233SKonstantin Belousov 	    P_TOTAL_STOP);
11697b4a950aSDavid Xu 	PROC_SLOCK(p);
117044990b8cSJulian Elischer 	p->p_singlethread = NULL;
11717847a9daSJohn Baldwin 	wakeup_swapper = 0;
117249539972SJulian Elischer 	/*
11737847a9daSJohn Baldwin 	 * If there are other threads they may now run,
117449539972SJulian Elischer 	 * unless of course there is a blanket 'stop order'
117549539972SJulian Elischer 	 * on the process. The single threader must be allowed
117649539972SJulian Elischer 	 * to continue however as this is a bad place to stop.
117749539972SJulian Elischer 	 */
11786ddcc233SKonstantin Belousov 	if (p->p_numthreads != remain_for_mode(mode) && !P_SHOULDSTOP(p)) {
1179ad1e7d28SJulian Elischer                 FOREACH_THREAD_IN_PROC(p, td) {
1180a54e85fdSJeff Roberson 			thread_lock(td);
1181ad1e7d28SJulian Elischer 			if (TD_IS_SUSPENDED(td)) {
118284cdea97SKonstantin Belousov 				wakeup_swapper |= thread_unsuspend_one(td, p,
118384cdea97SKonstantin Belousov 				    mode == SINGLE_BOUNDARY);
118444990b8cSJulian Elischer 			}
1185a54e85fdSJeff Roberson 			thread_unlock(td);
118649539972SJulian Elischer 		}
1187ad1e7d28SJulian Elischer 	}
118884cdea97SKonstantin Belousov 	KASSERT(mode != SINGLE_BOUNDARY || p->p_boundary_count == 0,
118984cdea97SKonstantin Belousov 	    ("inconsistent boundary count %d", p->p_boundary_count));
11907b4a950aSDavid Xu 	PROC_SUNLOCK(p);
11917847a9daSJohn Baldwin 	if (wakeup_swapper)
11927847a9daSJohn Baldwin 		kick_proc0();
119349539972SJulian Elischer }
11944fc21c09SDaniel Eischen 
119544355392SDavid Xu struct thread *
119644355392SDavid Xu thread_find(struct proc *p, lwpid_t tid)
119744355392SDavid Xu {
119844355392SDavid Xu 	struct thread *td;
119944355392SDavid Xu 
120044355392SDavid Xu 	PROC_LOCK_ASSERT(p, MA_OWNED);
120144355392SDavid Xu 	FOREACH_THREAD_IN_PROC(p, td) {
120244355392SDavid Xu 		if (td->td_tid == tid)
120344355392SDavid Xu 			break;
120444355392SDavid Xu 	}
120544355392SDavid Xu 	return (td);
120644355392SDavid Xu }
1207cf7d9a8cSDavid Xu 
1208cf7d9a8cSDavid Xu /* Locate a thread by number; return with proc lock held. */
1209cf7d9a8cSDavid Xu struct thread *
1210cf7d9a8cSDavid Xu tdfind(lwpid_t tid, pid_t pid)
1211cf7d9a8cSDavid Xu {
1212cf7d9a8cSDavid Xu #define RUN_THRESH	16
1213cf7d9a8cSDavid Xu 	struct thread *td;
1214cf7d9a8cSDavid Xu 	int run = 0;
1215cf7d9a8cSDavid Xu 
1216cf7d9a8cSDavid Xu 	rw_rlock(&tidhash_lock);
1217cf7d9a8cSDavid Xu 	LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1218cf7d9a8cSDavid Xu 		if (td->td_tid == tid) {
1219cf7d9a8cSDavid Xu 			if (pid != -1 && td->td_proc->p_pid != pid) {
1220cf7d9a8cSDavid Xu 				td = NULL;
1221cf7d9a8cSDavid Xu 				break;
1222cf7d9a8cSDavid Xu 			}
12238e6fa660SJohn Baldwin 			PROC_LOCK(td->td_proc);
1224cf7d9a8cSDavid Xu 			if (td->td_proc->p_state == PRS_NEW) {
12258e6fa660SJohn Baldwin 				PROC_UNLOCK(td->td_proc);
1226cf7d9a8cSDavid Xu 				td = NULL;
1227cf7d9a8cSDavid Xu 				break;
1228cf7d9a8cSDavid Xu 			}
1229cf7d9a8cSDavid Xu 			if (run > RUN_THRESH) {
1230cf7d9a8cSDavid Xu 				if (rw_try_upgrade(&tidhash_lock)) {
1231cf7d9a8cSDavid Xu 					LIST_REMOVE(td, td_hash);
1232cf7d9a8cSDavid Xu 					LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1233cf7d9a8cSDavid Xu 						td, td_hash);
1234cf7d9a8cSDavid Xu 					rw_wunlock(&tidhash_lock);
1235cf7d9a8cSDavid Xu 					return (td);
1236cf7d9a8cSDavid Xu 				}
1237cf7d9a8cSDavid Xu 			}
1238cf7d9a8cSDavid Xu 			break;
1239cf7d9a8cSDavid Xu 		}
1240cf7d9a8cSDavid Xu 		run++;
1241cf7d9a8cSDavid Xu 	}
1242cf7d9a8cSDavid Xu 	rw_runlock(&tidhash_lock);
1243cf7d9a8cSDavid Xu 	return (td);
1244cf7d9a8cSDavid Xu }
1245cf7d9a8cSDavid Xu 
1246cf7d9a8cSDavid Xu void
1247cf7d9a8cSDavid Xu tidhash_add(struct thread *td)
1248cf7d9a8cSDavid Xu {
1249cf7d9a8cSDavid Xu 	rw_wlock(&tidhash_lock);
1250cf7d9a8cSDavid Xu 	LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1251cf7d9a8cSDavid Xu 	rw_wunlock(&tidhash_lock);
1252cf7d9a8cSDavid Xu }
1253cf7d9a8cSDavid Xu 
1254cf7d9a8cSDavid Xu void
1255cf7d9a8cSDavid Xu tidhash_remove(struct thread *td)
1256cf7d9a8cSDavid Xu {
1257cf7d9a8cSDavid Xu 	rw_wlock(&tidhash_lock);
1258cf7d9a8cSDavid Xu 	LIST_REMOVE(td, td_hash);
1259cf7d9a8cSDavid Xu 	rw_wunlock(&tidhash_lock);
1260cf7d9a8cSDavid Xu }
1261