xref: /freebsd/sys/kern/kern_thread.c (revision 2ca45184dcc132afd7d40dcf055c927f79fd0b73)
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 
68acd9f517SKonstantin Belousov /*
69acd9f517SKonstantin Belousov  * Asserts below verify the stability of struct thread and struct proc
70acd9f517SKonstantin Belousov  * layout, as exposed by KBI to modules.  On head, the KBI is allowed
71acd9f517SKonstantin Belousov  * to drift, change to the structures must be accompanied by the
72acd9f517SKonstantin Belousov  * assert update.
73acd9f517SKonstantin Belousov  *
74acd9f517SKonstantin Belousov  * On the stable branches after KBI freeze, conditions must not be
75acd9f517SKonstantin Belousov  * violated.  Typically new fields are moved to the end of the
76acd9f517SKonstantin Belousov  * structures.
77acd9f517SKonstantin Belousov  */
78acd9f517SKonstantin Belousov #ifdef __amd64__
79acd9f517SKonstantin Belousov _Static_assert(offsetof(struct thread, td_flags) == 0xf4,
80acd9f517SKonstantin Belousov     "struct thread KBI td_flags");
81acd9f517SKonstantin Belousov _Static_assert(offsetof(struct thread, td_pflags) == 0xfc,
82acd9f517SKonstantin Belousov     "struct thread KBI td_pflags");
832d88da2fSKonstantin Belousov _Static_assert(offsetof(struct thread, td_frame) == 0x460,
84acd9f517SKonstantin Belousov     "struct thread KBI td_frame");
852d88da2fSKonstantin Belousov _Static_assert(offsetof(struct thread, td_emuldata) == 0x508,
86acd9f517SKonstantin Belousov     "struct thread KBI td_emuldata");
87acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_flag) == 0xb0,
88acd9f517SKonstantin Belousov     "struct proc KBI p_flag");
89acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_pid) == 0xbc,
90acd9f517SKonstantin Belousov     "struct proc KBI p_pid");
91acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_filemon) == 0x3d0,
92acd9f517SKonstantin Belousov     "struct proc KBI p_filemon");
93acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_comm) == 0x3e0,
94acd9f517SKonstantin Belousov     "struct proc KBI p_comm");
95acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_emuldata) == 0x4b8,
96acd9f517SKonstantin Belousov     "struct proc KBI p_emuldata");
97acd9f517SKonstantin Belousov #endif
98acd9f517SKonstantin Belousov #ifdef __i386__
99acd9f517SKonstantin Belousov _Static_assert(offsetof(struct thread, td_flags) == 0x9c,
100acd9f517SKonstantin Belousov     "struct thread KBI td_flags");
101acd9f517SKonstantin Belousov _Static_assert(offsetof(struct thread, td_pflags) == 0xa4,
102acd9f517SKonstantin Belousov     "struct thread KBI td_pflags");
1032d88da2fSKonstantin Belousov _Static_assert(offsetof(struct thread, td_frame) == 0x2ec,
104acd9f517SKonstantin Belousov     "struct thread KBI td_frame");
1052d88da2fSKonstantin Belousov _Static_assert(offsetof(struct thread, td_emuldata) == 0x338,
106acd9f517SKonstantin Belousov     "struct thread KBI td_emuldata");
107acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_flag) == 0x68,
108acd9f517SKonstantin Belousov     "struct proc KBI p_flag");
109acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_pid) == 0x74,
110acd9f517SKonstantin Belousov     "struct proc KBI p_pid");
111acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_filemon) == 0x27c,
112acd9f517SKonstantin Belousov     "struct proc KBI p_filemon");
113acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_comm) == 0x288,
114acd9f517SKonstantin Belousov     "struct proc KBI p_comm");
115acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_emuldata) == 0x314,
116acd9f517SKonstantin Belousov     "struct proc KBI p_emuldata");
117acd9f517SKonstantin Belousov #endif
118acd9f517SKonstantin 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 
147*2ca45184SMatt Joras EVENTHANDLER_LIST_DEFINE(thread_ctor);
148*2ca45184SMatt Joras EVENTHANDLER_LIST_DEFINE(thread_dtor);
149*2ca45184SMatt Joras EVENTHANDLER_LIST_DEFINE(thread_init);
150*2ca45184SMatt Joras EVENTHANDLER_LIST_DEFINE(thread_fini);
151*2ca45184SMatt Joras 
152ec6ea5e8SDavid Xu static lwpid_t
153ec6ea5e8SDavid Xu tid_alloc(void)
154ec6ea5e8SDavid Xu {
155ec6ea5e8SDavid Xu 	lwpid_t	tid;
156ec6ea5e8SDavid Xu 
157ec6ea5e8SDavid Xu 	tid = alloc_unr(tid_unrhdr);
158ec6ea5e8SDavid Xu 	if (tid != -1)
159ec6ea5e8SDavid Xu 		return (tid);
160ec6ea5e8SDavid Xu 	mtx_lock(&tid_lock);
161ec6ea5e8SDavid Xu 	if (tid_head == tid_tail) {
162ec6ea5e8SDavid Xu 		mtx_unlock(&tid_lock);
163ec6ea5e8SDavid Xu 		return (-1);
164ec6ea5e8SDavid Xu 	}
16594cb3545SKonstantin Belousov 	tid = tid_buffer[tid_head];
16694cb3545SKonstantin Belousov 	tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
167ec6ea5e8SDavid Xu 	mtx_unlock(&tid_lock);
168ec6ea5e8SDavid Xu 	return (tid);
169ec6ea5e8SDavid Xu }
170ec6ea5e8SDavid Xu 
171ec6ea5e8SDavid Xu static void
172ec6ea5e8SDavid Xu tid_free(lwpid_t tid)
173ec6ea5e8SDavid Xu {
174ec6ea5e8SDavid Xu 	lwpid_t tmp_tid = -1;
175ec6ea5e8SDavid Xu 
176ec6ea5e8SDavid Xu 	mtx_lock(&tid_lock);
177ec6ea5e8SDavid Xu 	if ((tid_tail + 1) % TID_BUFFER_SIZE == tid_head) {
17894cb3545SKonstantin Belousov 		tmp_tid = tid_buffer[tid_head];
17994cb3545SKonstantin Belousov 		tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
180ec6ea5e8SDavid Xu 	}
18194cb3545SKonstantin Belousov 	tid_buffer[tid_tail] = tid;
18294cb3545SKonstantin Belousov 	tid_tail = (tid_tail + 1) % TID_BUFFER_SIZE;
183ec6ea5e8SDavid Xu 	mtx_unlock(&tid_lock);
184ec6ea5e8SDavid Xu 	if (tmp_tid != -1)
185ec6ea5e8SDavid Xu 		free_unr(tid_unrhdr, tmp_tid);
186ec6ea5e8SDavid Xu }
187ec6ea5e8SDavid Xu 
188fdcac928SMarcel Moolenaar /*
189696058c3SJulian Elischer  * Prepare a thread for use.
19044990b8cSJulian Elischer  */
191b23f72e9SBrian Feldman static int
192b23f72e9SBrian Feldman thread_ctor(void *mem, int size, void *arg, int flags)
19344990b8cSJulian Elischer {
19444990b8cSJulian Elischer 	struct thread	*td;
19544990b8cSJulian Elischer 
19644990b8cSJulian Elischer 	td = (struct thread *)mem;
19771fad9fdSJulian Elischer 	td->td_state = TDS_INACTIVE;
198060563ecSJulian Elischer 	td->td_oncpu = NOCPU;
1996c27c603SJuli Mallett 
200ec6ea5e8SDavid Xu 	td->td_tid = tid_alloc();
201773eff9dSPoul-Henning Kamp 
2026c27c603SJuli Mallett 	/*
2036c27c603SJuli Mallett 	 * Note that td_critnest begins life as 1 because the thread is not
2046c27c603SJuli Mallett 	 * running and is thereby implicitly waiting to be on the receiving
205a54e85fdSJeff Roberson 	 * end of a context switch.
2066c27c603SJuli Mallett 	 */
207139b7550SJohn Baldwin 	td->td_critnest = 1;
208acbe332aSDavid Xu 	td->td_lend_user_pri = PRI_MAX;
209*2ca45184SMatt Joras 	EVENTHANDLER_DIRECT_INVOKE(thread_ctor, td);
210911b84b0SRobert Watson #ifdef AUDIT
211911b84b0SRobert Watson 	audit_thread_alloc(td);
212911b84b0SRobert Watson #endif
213d10183d9SDavid Xu 	umtx_thread_alloc(td);
214b23f72e9SBrian Feldman 	return (0);
21544990b8cSJulian Elischer }
21644990b8cSJulian Elischer 
21744990b8cSJulian Elischer /*
21844990b8cSJulian Elischer  * Reclaim a thread after use.
21944990b8cSJulian Elischer  */
22044990b8cSJulian Elischer static void
22144990b8cSJulian Elischer thread_dtor(void *mem, int size, void *arg)
22244990b8cSJulian Elischer {
22344990b8cSJulian Elischer 	struct thread *td;
22444990b8cSJulian Elischer 
22544990b8cSJulian Elischer 	td = (struct thread *)mem;
22644990b8cSJulian Elischer 
22744990b8cSJulian Elischer #ifdef INVARIANTS
22844990b8cSJulian Elischer 	/* Verify that this thread is in a safe state to free. */
22944990b8cSJulian Elischer 	switch (td->td_state) {
23071fad9fdSJulian Elischer 	case TDS_INHIBITED:
23171fad9fdSJulian Elischer 	case TDS_RUNNING:
23271fad9fdSJulian Elischer 	case TDS_CAN_RUN:
23344990b8cSJulian Elischer 	case TDS_RUNQ:
23444990b8cSJulian Elischer 		/*
23544990b8cSJulian Elischer 		 * We must never unlink a thread that is in one of
23644990b8cSJulian Elischer 		 * these states, because it is currently active.
23744990b8cSJulian Elischer 		 */
23844990b8cSJulian Elischer 		panic("bad state for thread unlinking");
23944990b8cSJulian Elischer 		/* NOTREACHED */
24071fad9fdSJulian Elischer 	case TDS_INACTIVE:
24144990b8cSJulian Elischer 		break;
24244990b8cSJulian Elischer 	default:
24344990b8cSJulian Elischer 		panic("bad thread state");
24444990b8cSJulian Elischer 		/* NOTREACHED */
24544990b8cSJulian Elischer 	}
24644990b8cSJulian Elischer #endif
2476e8525ceSRobert Watson #ifdef AUDIT
2486e8525ceSRobert Watson 	audit_thread_free(td);
2496e8525ceSRobert Watson #endif
2501ba4a712SPawel Jakub Dawidek 	/* Free all OSD associated to this thread. */
2511ba4a712SPawel Jakub Dawidek 	osd_thread_exit(td);
252aca4bb91SKonstantin Belousov 	td_softdep_cleanup(td);
253aca4bb91SKonstantin Belousov 	MPASS(td->td_su == NULL);
2541ba4a712SPawel Jakub Dawidek 
255*2ca45184SMatt Joras 	EVENTHANDLER_DIRECT_INVOKE(thread_dtor, td);
256ec6ea5e8SDavid Xu 	tid_free(td->td_tid);
25744990b8cSJulian Elischer }
25844990b8cSJulian Elischer 
25944990b8cSJulian Elischer /*
26044990b8cSJulian Elischer  * Initialize type-stable parts of a thread (when newly created).
26144990b8cSJulian Elischer  */
262b23f72e9SBrian Feldman static int
263b23f72e9SBrian Feldman thread_init(void *mem, int size, int flags)
26444990b8cSJulian Elischer {
26544990b8cSJulian Elischer 	struct thread *td;
26644990b8cSJulian Elischer 
26744990b8cSJulian Elischer 	td = (struct thread *)mem;
268247aba24SMarcel Moolenaar 
26944f3b092SJohn Baldwin 	td->td_sleepqueue = sleepq_alloc();
270961a7b24SJohn Baldwin 	td->td_turnstile = turnstile_alloc();
2718f0e9130SKonstantin Belousov 	td->td_rlqe = NULL;
272*2ca45184SMatt Joras 	EVENTHANDLER_DIRECT_INVOKE(thread_init, td);
273d10183d9SDavid Xu 	umtx_thread_init(td);
27489b57fcfSKonstantin Belousov 	td->td_kstack = 0;
275ad8b1d85SKonstantin Belousov 	td->td_sel = NULL;
276b23f72e9SBrian Feldman 	return (0);
27744990b8cSJulian Elischer }
27844990b8cSJulian Elischer 
27944990b8cSJulian Elischer /*
28044990b8cSJulian Elischer  * Tear down type-stable parts of a thread (just before being discarded).
28144990b8cSJulian Elischer  */
28244990b8cSJulian Elischer static void
28344990b8cSJulian Elischer thread_fini(void *mem, int size)
28444990b8cSJulian Elischer {
28544990b8cSJulian Elischer 	struct thread *td;
28644990b8cSJulian Elischer 
28744990b8cSJulian Elischer 	td = (struct thread *)mem;
288*2ca45184SMatt Joras 	EVENTHANDLER_DIRECT_INVOKE(thread_fini, td);
2898f0e9130SKonstantin Belousov 	rlqentry_free(td->td_rlqe);
290961a7b24SJohn Baldwin 	turnstile_free(td->td_turnstile);
29144f3b092SJohn Baldwin 	sleepq_free(td->td_sleepqueue);
292d10183d9SDavid Xu 	umtx_thread_fini(td);
293ace8398dSJeff Roberson 	seltdfini(td);
29444990b8cSJulian Elischer }
2955215b187SJeff Roberson 
2965c8329edSJulian Elischer /*
2975215b187SJeff Roberson  * For a newly created process,
2985215b187SJeff Roberson  * link up all the structures and its initial threads etc.
299ed062c8dSJulian Elischer  * called from:
300e7d939bdSMarcel Moolenaar  * {arch}/{arch}/machdep.c   {arch}_init(), init386() etc.
301ed062c8dSJulian Elischer  * proc_dtor() (should go away)
302ed062c8dSJulian Elischer  * proc_init()
3035c8329edSJulian Elischer  */
3045c8329edSJulian Elischer void
30589b57fcfSKonstantin Belousov proc_linkup0(struct proc *p, struct thread *td)
30689b57fcfSKonstantin Belousov {
30789b57fcfSKonstantin Belousov 	TAILQ_INIT(&p->p_threads);	     /* all threads in proc */
30889b57fcfSKonstantin Belousov 	proc_linkup(p, td);
30989b57fcfSKonstantin Belousov }
31089b57fcfSKonstantin Belousov 
31189b57fcfSKonstantin Belousov void
3128460a577SJohn Birrell proc_linkup(struct proc *p, struct thread *td)
3135c8329edSJulian Elischer {
314a54e85fdSJeff Roberson 
3159104847fSDavid Xu 	sigqueue_init(&p->p_sigqueue, p);
316ebceaf6dSDavid Xu 	p->p_ksi = ksiginfo_alloc(1);
317ebceaf6dSDavid Xu 	if (p->p_ksi != NULL) {
3185c474517SDavid Xu 		/* XXX p_ksi may be null if ksiginfo zone is not ready */
319ebceaf6dSDavid Xu 		p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
320ebceaf6dSDavid Xu 	}
321b2f92ef9SDavid Xu 	LIST_INIT(&p->p_mqnotifier);
3225c8329edSJulian Elischer 	p->p_numthreads = 0;
3238460a577SJohn Birrell 	thread_link(td, p);
3245c8329edSJulian Elischer }
3255c8329edSJulian Elischer 
3265c8329edSJulian Elischer /*
32744990b8cSJulian Elischer  * Initialize global thread allocation resources.
32844990b8cSJulian Elischer  */
32944990b8cSJulian Elischer void
33044990b8cSJulian Elischer threadinit(void)
33144990b8cSJulian Elischer {
33244990b8cSJulian Elischer 
3331ea7a6f8SPoul-Henning Kamp 	mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
33402c6fc21SKonstantin Belousov 
33502c6fc21SKonstantin Belousov 	/*
336abce621cSKonstantin Belousov 	 * pid_max cannot be greater than PID_MAX.
33702c6fc21SKonstantin Belousov 	 * leave one number for thread0.
33802c6fc21SKonstantin Belousov 	 */
3396829a5c5SJulian Elischer 	tid_unrhdr = new_unrhdr(PID_MAX + 2, INT_MAX, &tid_lock);
3401ea7a6f8SPoul-Henning Kamp 
341de028f5aSJeff Roberson 	thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
34244990b8cSJulian Elischer 	    thread_ctor, thread_dtor, thread_init, thread_fini,
343f743ea96SMateusz Guzik 	    32 - 1, UMA_ZONE_NOFREE);
344cf7d9a8cSDavid Xu 	tidhashtbl = hashinit(maxproc / 2, M_TIDHASH, &tidhash);
345cf7d9a8cSDavid Xu 	rw_init(&tidhash_lock, "tidhash");
34644990b8cSJulian Elischer }
34744990b8cSJulian Elischer 
34844990b8cSJulian Elischer /*
349ff8fbcffSJeff Roberson  * Place an unused thread on the zombie list.
350ad1e7d28SJulian Elischer  * Use the slpq as that must be unused by now.
35144990b8cSJulian Elischer  */
35244990b8cSJulian Elischer void
353ff8fbcffSJeff Roberson thread_zombie(struct thread *td)
35444990b8cSJulian Elischer {
355a54e85fdSJeff Roberson 	mtx_lock_spin(&zombie_lock);
356ad1e7d28SJulian Elischer 	TAILQ_INSERT_HEAD(&zombie_threads, td, td_slpq);
357a54e85fdSJeff Roberson 	mtx_unlock_spin(&zombie_lock);
35844990b8cSJulian Elischer }
35944990b8cSJulian Elischer 
3605c8329edSJulian Elischer /*
361ff8fbcffSJeff Roberson  * Release a thread that has exited after cpu_throw().
362ff8fbcffSJeff Roberson  */
363ff8fbcffSJeff Roberson void
364ff8fbcffSJeff Roberson thread_stash(struct thread *td)
365ff8fbcffSJeff Roberson {
366ff8fbcffSJeff Roberson 	atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
367ff8fbcffSJeff Roberson 	thread_zombie(td);
368ff8fbcffSJeff Roberson }
369ff8fbcffSJeff Roberson 
370ff8fbcffSJeff Roberson /*
3716617724cSJeff Roberson  * Reap zombie resources.
37244990b8cSJulian Elischer  */
37344990b8cSJulian Elischer void
37444990b8cSJulian Elischer thread_reap(void)
37544990b8cSJulian Elischer {
3765c8329edSJulian Elischer 	struct thread *td_first, *td_next;
37744990b8cSJulian Elischer 
37844990b8cSJulian Elischer 	/*
3795215b187SJeff Roberson 	 * Don't even bother to lock if none at this instant,
3802d19b736SKonstantin Belousov 	 * we really don't care about the next instant.
38144990b8cSJulian Elischer 	 */
3828460a577SJohn Birrell 	if (!TAILQ_EMPTY(&zombie_threads)) {
383a54e85fdSJeff Roberson 		mtx_lock_spin(&zombie_lock);
3845c8329edSJulian Elischer 		td_first = TAILQ_FIRST(&zombie_threads);
3855c8329edSJulian Elischer 		if (td_first)
3865c8329edSJulian Elischer 			TAILQ_INIT(&zombie_threads);
387a54e85fdSJeff Roberson 		mtx_unlock_spin(&zombie_lock);
3885c8329edSJulian Elischer 		while (td_first) {
389ad1e7d28SJulian Elischer 			td_next = TAILQ_NEXT(td_first, td_slpq);
3904ea6a9a2SMateusz Guzik 			thread_cow_free(td_first);
3915c8329edSJulian Elischer 			thread_free(td_first);
3925c8329edSJulian Elischer 			td_first = td_next;
39344990b8cSJulian Elischer 		}
39444990b8cSJulian Elischer 	}
395ed062c8dSJulian Elischer }
39644990b8cSJulian Elischer 
3974f0db5e0SJulian Elischer /*
39844990b8cSJulian Elischer  * Allocate a thread.
39944990b8cSJulian Elischer  */
40044990b8cSJulian Elischer struct thread *
4018a945d10SKonstantin Belousov thread_alloc(int pages)
40244990b8cSJulian Elischer {
40389b57fcfSKonstantin Belousov 	struct thread *td;
4048460a577SJohn Birrell 
40544990b8cSJulian Elischer 	thread_reap(); /* check if any zombies to get */
40689b57fcfSKonstantin Belousov 
40789b57fcfSKonstantin Belousov 	td = (struct thread *)uma_zalloc(thread_zone, M_WAITOK);
40889b57fcfSKonstantin Belousov 	KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
4098a945d10SKonstantin Belousov 	if (!vm_thread_new(td, pages)) {
41089b57fcfSKonstantin Belousov 		uma_zfree(thread_zone, td);
41189b57fcfSKonstantin Belousov 		return (NULL);
41289b57fcfSKonstantin Belousov 	}
4130c3967e7SMarcel Moolenaar 	cpu_thread_alloc(td);
4146520495aSAdrian Chadd 	vm_domain_policy_init(&td->td_vm_dom_policy);
41589b57fcfSKonstantin Belousov 	return (td);
41644990b8cSJulian Elischer }
41744990b8cSJulian Elischer 
4188a945d10SKonstantin Belousov int
4198a945d10SKonstantin Belousov thread_alloc_stack(struct thread *td, int pages)
4208a945d10SKonstantin Belousov {
4218a945d10SKonstantin Belousov 
4228a945d10SKonstantin Belousov 	KASSERT(td->td_kstack == 0,
4238a945d10SKonstantin Belousov 	    ("thread_alloc_stack called on a thread with kstack"));
4248a945d10SKonstantin Belousov 	if (!vm_thread_new(td, pages))
4258a945d10SKonstantin Belousov 		return (0);
4268a945d10SKonstantin Belousov 	cpu_thread_alloc(td);
4278a945d10SKonstantin Belousov 	return (1);
4288a945d10SKonstantin Belousov }
4294f0db5e0SJulian Elischer 
4304f0db5e0SJulian Elischer /*
43144990b8cSJulian Elischer  * Deallocate a thread.
43244990b8cSJulian Elischer  */
43344990b8cSJulian Elischer void
43444990b8cSJulian Elischer thread_free(struct thread *td)
43544990b8cSJulian Elischer {
4362e6b8de4SJeff Roberson 
4372e6b8de4SJeff Roberson 	lock_profile_thread_exit(td);
43845aea8deSJeff Roberson 	if (td->td_cpuset)
439d7f687fcSJeff Roberson 		cpuset_rel(td->td_cpuset);
440d7f687fcSJeff Roberson 	td->td_cpuset = NULL;
4410c3967e7SMarcel Moolenaar 	cpu_thread_free(td);
44289b57fcfSKonstantin Belousov 	if (td->td_kstack != 0)
44389b57fcfSKonstantin Belousov 		vm_thread_dispose(td);
4446520495aSAdrian Chadd 	vm_domain_policy_cleanup(&td->td_vm_dom_policy);
4452d19b736SKonstantin Belousov 	callout_drain(&td->td_slpcallout);
44644990b8cSJulian Elischer 	uma_zfree(thread_zone, td);
44744990b8cSJulian Elischer }
44844990b8cSJulian Elischer 
4494ea6a9a2SMateusz Guzik void
4504ea6a9a2SMateusz Guzik thread_cow_get_proc(struct thread *newtd, struct proc *p)
4514ea6a9a2SMateusz Guzik {
4524ea6a9a2SMateusz Guzik 
4534ea6a9a2SMateusz Guzik 	PROC_LOCK_ASSERT(p, MA_OWNED);
4544ea6a9a2SMateusz Guzik 	newtd->td_ucred = crhold(p->p_ucred);
455f6f6d240SMateusz Guzik 	newtd->td_limit = lim_hold(p->p_limit);
4564ea6a9a2SMateusz Guzik 	newtd->td_cowgen = p->p_cowgen;
4574ea6a9a2SMateusz Guzik }
4584ea6a9a2SMateusz Guzik 
4594ea6a9a2SMateusz Guzik void
4604ea6a9a2SMateusz Guzik thread_cow_get(struct thread *newtd, struct thread *td)
4614ea6a9a2SMateusz Guzik {
4624ea6a9a2SMateusz Guzik 
4634ea6a9a2SMateusz Guzik 	newtd->td_ucred = crhold(td->td_ucred);
464f6f6d240SMateusz Guzik 	newtd->td_limit = lim_hold(td->td_limit);
4654ea6a9a2SMateusz Guzik 	newtd->td_cowgen = td->td_cowgen;
4664ea6a9a2SMateusz Guzik }
4674ea6a9a2SMateusz Guzik 
4684ea6a9a2SMateusz Guzik void
4694ea6a9a2SMateusz Guzik thread_cow_free(struct thread *td)
4704ea6a9a2SMateusz Guzik {
4714ea6a9a2SMateusz Guzik 
472cd672ca6SMateusz Guzik 	if (td->td_ucred != NULL)
4734ea6a9a2SMateusz Guzik 		crfree(td->td_ucred);
474cd672ca6SMateusz Guzik 	if (td->td_limit != NULL)
475f6f6d240SMateusz Guzik 		lim_free(td->td_limit);
4764ea6a9a2SMateusz Guzik }
4774ea6a9a2SMateusz Guzik 
4784ea6a9a2SMateusz Guzik void
4794ea6a9a2SMateusz Guzik thread_cow_update(struct thread *td)
4804ea6a9a2SMateusz Guzik {
4814ea6a9a2SMateusz Guzik 	struct proc *p;
482cd672ca6SMateusz Guzik 	struct ucred *oldcred;
483cd672ca6SMateusz Guzik 	struct plimit *oldlimit;
4844ea6a9a2SMateusz Guzik 
4854ea6a9a2SMateusz Guzik 	p = td->td_proc;
486cd672ca6SMateusz Guzik 	oldcred = NULL;
487cd672ca6SMateusz Guzik 	oldlimit = NULL;
4884ea6a9a2SMateusz Guzik 	PROC_LOCK(p);
489cd672ca6SMateusz Guzik 	if (td->td_ucred != p->p_ucred) {
490cd672ca6SMateusz Guzik 		oldcred = td->td_ucred;
491cd672ca6SMateusz Guzik 		td->td_ucred = crhold(p->p_ucred);
492cd672ca6SMateusz Guzik 	}
493cd672ca6SMateusz Guzik 	if (td->td_limit != p->p_limit) {
494cd672ca6SMateusz Guzik 		oldlimit = td->td_limit;
495cd672ca6SMateusz Guzik 		td->td_limit = lim_hold(p->p_limit);
496cd672ca6SMateusz Guzik 	}
4974ea6a9a2SMateusz Guzik 	td->td_cowgen = p->p_cowgen;
4984ea6a9a2SMateusz Guzik 	PROC_UNLOCK(p);
499cd672ca6SMateusz Guzik 	if (oldcred != NULL)
500cd672ca6SMateusz Guzik 		crfree(oldcred);
501cd672ca6SMateusz Guzik 	if (oldlimit != NULL)
502cd672ca6SMateusz Guzik 		lim_free(oldlimit);
5034ea6a9a2SMateusz Guzik }
5044ea6a9a2SMateusz Guzik 
50544990b8cSJulian Elischer /*
50644990b8cSJulian Elischer  * Discard the current thread and exit from its context.
50794e0a4cdSJulian Elischer  * Always called with scheduler locked.
50844990b8cSJulian Elischer  *
50944990b8cSJulian Elischer  * Because we can't free a thread while we're operating under its context,
510696058c3SJulian Elischer  * push the current thread into our CPU's deadthread holder. This means
511696058c3SJulian Elischer  * we needn't worry about someone else grabbing our context before we
5126617724cSJeff Roberson  * do a cpu_throw().
51344990b8cSJulian Elischer  */
51444990b8cSJulian Elischer void
51544990b8cSJulian Elischer thread_exit(void)
51644990b8cSJulian Elischer {
5177e3a96eaSJohn Baldwin 	uint64_t runtime, new_switchtime;
51844990b8cSJulian Elischer 	struct thread *td;
5191c4bcd05SJeff Roberson 	struct thread *td2;
52044990b8cSJulian Elischer 	struct proc *p;
5217847a9daSJohn Baldwin 	int wakeup_swapper;
52244990b8cSJulian Elischer 
52344990b8cSJulian Elischer 	td = curthread;
52444990b8cSJulian Elischer 	p = td->td_proc;
52544990b8cSJulian Elischer 
526a54e85fdSJeff Roberson 	PROC_SLOCK_ASSERT(p, MA_OWNED);
527ed062c8dSJulian Elischer 	mtx_assert(&Giant, MA_NOTOWNED);
528a54e85fdSJeff Roberson 
52944990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
530ed062c8dSJulian Elischer 	KASSERT(p != NULL, ("thread exiting without a process"));
531cc701b73SRobert Watson 	CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
532e01eafefSJulian Elischer 	    (long)p->p_pid, td->td_name);
5336c9271a9SAndriy Gapon 	SDT_PROBE0(proc, , , lwp__exit);
5349104847fSDavid Xu 	KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
53544990b8cSJulian Elischer 
53689964dd2SRobert Watson #ifdef AUDIT
53789964dd2SRobert Watson 	AUDIT_SYSCALL_EXIT(0, td);
53889964dd2SRobert Watson #endif
539ed062c8dSJulian Elischer 	/*
540ed062c8dSJulian Elischer 	 * drop FPU & debug register state storage, or any other
541ed062c8dSJulian Elischer 	 * architecture specific resources that
542ed062c8dSJulian Elischer 	 * would not be on a new untouched process.
543ed062c8dSJulian Elischer 	 */
544bd07998eSKonstantin Belousov 	cpu_thread_exit(td);
54544990b8cSJulian Elischer 
546ed062c8dSJulian Elischer 	/*
5471faf202eSJulian Elischer 	 * The last thread is left attached to the process
5481faf202eSJulian Elischer 	 * So that the whole bundle gets recycled. Skip
549ed062c8dSJulian Elischer 	 * all this stuff if we never had threads.
550ed062c8dSJulian Elischer 	 * EXIT clears all sign of other threads when
551ed062c8dSJulian Elischer 	 * it goes to single threading, so the last thread always
552ed062c8dSJulian Elischer 	 * takes the short path.
5531faf202eSJulian Elischer 	 */
554ed062c8dSJulian Elischer 	if (p->p_flag & P_HADTHREADS) {
5551faf202eSJulian Elischer 		if (p->p_numthreads > 1) {
556fd229b5bSKonstantin Belousov 			atomic_add_int(&td->td_proc->p_exitthreads, 1);
557d3a0bd78SJulian Elischer 			thread_unlink(td);
5581c4bcd05SJeff Roberson 			td2 = FIRST_THREAD_IN_PROC(p);
5591c4bcd05SJeff Roberson 			sched_exit_thread(td2, td);
560ed062c8dSJulian Elischer 
561ed062c8dSJulian Elischer 			/*
56244990b8cSJulian Elischer 			 * The test below is NOT true if we are the
5639182554aSKonstantin Belousov 			 * sole exiting thread. P_STOPPED_SINGLE is unset
56444990b8cSJulian Elischer 			 * in exit1() after it is the only survivor.
56544990b8cSJulian Elischer 			 */
5661279572aSDavid Xu 			if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
56744990b8cSJulian Elischer 				if (p->p_numthreads == p->p_suspcount) {
568a54e85fdSJeff Roberson 					thread_lock(p->p_singlethread);
5697847a9daSJohn Baldwin 					wakeup_swapper = thread_unsuspend_one(
57084cdea97SKonstantin Belousov 						p->p_singlethread, p, false);
571a54e85fdSJeff Roberson 					thread_unlock(p->p_singlethread);
5727847a9daSJohn Baldwin 					if (wakeup_swapper)
5737847a9daSJohn Baldwin 						kick_proc0();
57444990b8cSJulian Elischer 				}
57544990b8cSJulian Elischer 			}
57648bfcdddSJulian Elischer 
577696058c3SJulian Elischer 			PCPU_SET(deadthread, td);
5781faf202eSJulian Elischer 		} else {
579ed062c8dSJulian Elischer 			/*
580ed062c8dSJulian Elischer 			 * The last thread is exiting.. but not through exit()
581ed062c8dSJulian Elischer 			 */
582ed062c8dSJulian Elischer 			panic ("thread_exit: Last thread exiting on its own");
583ed062c8dSJulian Elischer 		}
5841faf202eSJulian Elischer 	}
58516d95d4fSJoseph Koshy #ifdef	HWPMC_HOOKS
58616d95d4fSJoseph Koshy 	/*
58716d95d4fSJoseph Koshy 	 * If this thread is part of a process that is being tracked by hwpmc(4),
58816d95d4fSJoseph Koshy 	 * inform the module of the thread's impending exit.
58916d95d4fSJoseph Koshy 	 */
59016d95d4fSJoseph Koshy 	if (PMC_PROC_IS_USING_PMCS(td->td_proc))
59116d95d4fSJoseph Koshy 		PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
59216d95d4fSJoseph Koshy #endif
593a54e85fdSJeff Roberson 	PROC_UNLOCK(p);
5945c7bebf9SKonstantin Belousov 	PROC_STATLOCK(p);
5955c7bebf9SKonstantin Belousov 	thread_lock(td);
5965c7bebf9SKonstantin Belousov 	PROC_SUNLOCK(p);
5977e3a96eaSJohn Baldwin 
5987e3a96eaSJohn Baldwin 	/* Do the same timestamp bookkeeping that mi_switch() would do. */
5997e3a96eaSJohn Baldwin 	new_switchtime = cpu_ticks();
6007e3a96eaSJohn Baldwin 	runtime = new_switchtime - PCPU_GET(switchtime);
6017e3a96eaSJohn Baldwin 	td->td_runtime += runtime;
6027e3a96eaSJohn Baldwin 	td->td_incruntime += runtime;
6037e3a96eaSJohn Baldwin 	PCPU_SET(switchtime, new_switchtime);
6047e3a96eaSJohn Baldwin 	PCPU_SET(switchticks, ticks);
60583c9dea1SGleb Smirnoff 	VM_CNT_INC(v_swtch);
6067e3a96eaSJohn Baldwin 
6077e3a96eaSJohn Baldwin 	/* Save our resource usage in our process. */
6087e3a96eaSJohn Baldwin 	td->td_ru.ru_nvcsw++;
60941fd9c63SKonstantin Belousov 	ruxagg(p, td);
6107e3a96eaSJohn Baldwin 	rucollect(&p->p_ru, &td->td_ru);
6115c7bebf9SKonstantin Belousov 	PROC_STATUNLOCK(p);
6127e3a96eaSJohn Baldwin 
613dcc9954eSJulian Elischer 	td->td_state = TDS_INACTIVE;
6143d06b4b3SAttilio Rao #ifdef WITNESS
6153d06b4b3SAttilio Rao 	witness_thread_exit(td);
6163d06b4b3SAttilio Rao #endif
617732d9528SJulian Elischer 	CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
618a54e85fdSJeff Roberson 	sched_throw(td);
619cc66ebe2SPeter Wemm 	panic("I'm a teapot!");
62044990b8cSJulian Elischer 	/* NOTREACHED */
62144990b8cSJulian Elischer }
62244990b8cSJulian Elischer 
62344990b8cSJulian Elischer /*
624696058c3SJulian Elischer  * Do any thread specific cleanups that may be needed in wait()
62537814395SPeter Wemm  * called with Giant, proc and schedlock not held.
626696058c3SJulian Elischer  */
627696058c3SJulian Elischer void
628696058c3SJulian Elischer thread_wait(struct proc *p)
629696058c3SJulian Elischer {
630696058c3SJulian Elischer 	struct thread *td;
631696058c3SJulian Elischer 
63237814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
633624bf9e1SKonstantin Belousov 	KASSERT(p->p_numthreads == 1, ("multiple threads in thread_wait()"));
634624bf9e1SKonstantin Belousov 	KASSERT(p->p_exitthreads == 0, ("p_exitthreads leaking"));
635ff8fbcffSJeff Roberson 	td = FIRST_THREAD_IN_PROC(p);
636ff8fbcffSJeff Roberson 	/* Lock the last thread so we spin until it exits cpu_throw(). */
637ff8fbcffSJeff Roberson 	thread_lock(td);
638ff8fbcffSJeff Roberson 	thread_unlock(td);
6392e6b8de4SJeff Roberson 	lock_profile_thread_exit(td);
640d7f687fcSJeff Roberson 	cpuset_rel(td->td_cpuset);
641d7f687fcSJeff Roberson 	td->td_cpuset = NULL;
642696058c3SJulian Elischer 	cpu_thread_clean(td);
6434ea6a9a2SMateusz Guzik 	thread_cow_free(td);
6442d19b736SKonstantin Belousov 	callout_drain(&td->td_slpcallout);
645696058c3SJulian Elischer 	thread_reap();	/* check for zombie threads etc. */
646696058c3SJulian Elischer }
647696058c3SJulian Elischer 
648696058c3SJulian Elischer /*
64944990b8cSJulian Elischer  * Link a thread to a process.
6501faf202eSJulian Elischer  * set up anything that needs to be initialized for it to
6511faf202eSJulian Elischer  * be used by the process.
65244990b8cSJulian Elischer  */
65344990b8cSJulian Elischer void
6548460a577SJohn Birrell thread_link(struct thread *td, struct proc *p)
65544990b8cSJulian Elischer {
65644990b8cSJulian Elischer 
657a54e85fdSJeff Roberson 	/*
658a54e85fdSJeff Roberson 	 * XXX This can't be enabled because it's called for proc0 before
659374ae2a3SJeff Roberson 	 * its lock has been created.
660374ae2a3SJeff Roberson 	 * PROC_LOCK_ASSERT(p, MA_OWNED);
661a54e85fdSJeff Roberson 	 */
66271fad9fdSJulian Elischer 	td->td_state    = TDS_INACTIVE;
66344990b8cSJulian Elischer 	td->td_proc     = p;
664b61ce5b0SJeff Roberson 	td->td_flags    = TDF_INMEM;
66544990b8cSJulian Elischer 
6661faf202eSJulian Elischer 	LIST_INIT(&td->td_contested);
667eea4f254SJeff Roberson 	LIST_INIT(&td->td_lprof[0]);
668eea4f254SJeff Roberson 	LIST_INIT(&td->td_lprof[1]);
6699104847fSDavid Xu 	sigqueue_init(&td->td_sigqueue, p);
670fd90e2edSJung-uk Kim 	callout_init(&td->td_slpcallout, 1);
67166d8df9dSDaniel Eischen 	TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
67244990b8cSJulian Elischer 	p->p_numthreads++;
67344990b8cSJulian Elischer }
67444990b8cSJulian Elischer 
675ed062c8dSJulian Elischer /*
676ed062c8dSJulian Elischer  * Called from:
677ed062c8dSJulian Elischer  *  thread_exit()
678ed062c8dSJulian Elischer  */
679d3a0bd78SJulian Elischer void
680d3a0bd78SJulian Elischer thread_unlink(struct thread *td)
681d3a0bd78SJulian Elischer {
682d3a0bd78SJulian Elischer 	struct proc *p = td->td_proc;
683d3a0bd78SJulian Elischer 
684374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
685d3a0bd78SJulian Elischer 	TAILQ_REMOVE(&p->p_threads, td, td_plist);
686d3a0bd78SJulian Elischer 	p->p_numthreads--;
687d3a0bd78SJulian Elischer 	/* could clear a few other things here */
6888460a577SJohn Birrell 	/* Must  NOT clear links to proc! */
6895c8329edSJulian Elischer }
6905c8329edSJulian Elischer 
69179799053SKonstantin Belousov static int
69279799053SKonstantin Belousov calc_remaining(struct proc *p, int mode)
69379799053SKonstantin Belousov {
69479799053SKonstantin Belousov 	int remaining;
69579799053SKonstantin Belousov 
6967b519077SKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
6977b519077SKonstantin Belousov 	PROC_SLOCK_ASSERT(p, MA_OWNED);
69879799053SKonstantin Belousov 	if (mode == SINGLE_EXIT)
69979799053SKonstantin Belousov 		remaining = p->p_numthreads;
70079799053SKonstantin Belousov 	else if (mode == SINGLE_BOUNDARY)
70179799053SKonstantin Belousov 		remaining = p->p_numthreads - p->p_boundary_count;
7026ddcc233SKonstantin Belousov 	else if (mode == SINGLE_NO_EXIT || mode == SINGLE_ALLPROC)
70379799053SKonstantin Belousov 		remaining = p->p_numthreads - p->p_suspcount;
70479799053SKonstantin Belousov 	else
70579799053SKonstantin Belousov 		panic("calc_remaining: wrong mode %d", mode);
70679799053SKonstantin Belousov 	return (remaining);
70779799053SKonstantin Belousov }
70879799053SKonstantin Belousov 
70907a9368aSKonstantin Belousov static int
71007a9368aSKonstantin Belousov remain_for_mode(int mode)
71107a9368aSKonstantin Belousov {
71207a9368aSKonstantin Belousov 
7136ddcc233SKonstantin Belousov 	return (mode == SINGLE_ALLPROC ? 0 : 1);
71407a9368aSKonstantin Belousov }
71507a9368aSKonstantin Belousov 
71607a9368aSKonstantin Belousov static int
71707a9368aSKonstantin Belousov weed_inhib(int mode, struct thread *td2, struct proc *p)
71807a9368aSKonstantin Belousov {
71907a9368aSKonstantin Belousov 	int wakeup_swapper;
72007a9368aSKonstantin Belousov 
72107a9368aSKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
72207a9368aSKonstantin Belousov 	PROC_SLOCK_ASSERT(p, MA_OWNED);
72307a9368aSKonstantin Belousov 	THREAD_LOCK_ASSERT(td2, MA_OWNED);
72407a9368aSKonstantin Belousov 
72507a9368aSKonstantin Belousov 	wakeup_swapper = 0;
72607a9368aSKonstantin Belousov 	switch (mode) {
72707a9368aSKonstantin Belousov 	case SINGLE_EXIT:
72807a9368aSKonstantin Belousov 		if (TD_IS_SUSPENDED(td2))
72984cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, true);
73007a9368aSKonstantin Belousov 		if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0)
73107a9368aSKonstantin Belousov 			wakeup_swapper |= sleepq_abort(td2, EINTR);
73207a9368aSKonstantin Belousov 		break;
73307a9368aSKonstantin Belousov 	case SINGLE_BOUNDARY:
73407a9368aSKonstantin Belousov 	case SINGLE_NO_EXIT:
73507a9368aSKonstantin Belousov 		if (TD_IS_SUSPENDED(td2) && (td2->td_flags & TDF_BOUNDARY) == 0)
73684cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
73707a9368aSKonstantin Belousov 		if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0)
73807a9368aSKonstantin Belousov 			wakeup_swapper |= sleepq_abort(td2, ERESTART);
739917dd390SKonstantin Belousov 		break;
7406ddcc233SKonstantin Belousov 	case SINGLE_ALLPROC:
7416ddcc233SKonstantin Belousov 		/*
7426ddcc233SKonstantin Belousov 		 * ALLPROC suspend tries to avoid spurious EINTR for
7436ddcc233SKonstantin Belousov 		 * threads sleeping interruptable, by suspending the
7446ddcc233SKonstantin Belousov 		 * thread directly, similarly to sig_suspend_threads().
7456ddcc233SKonstantin Belousov 		 * Since such sleep is not performed at the user
7466ddcc233SKonstantin Belousov 		 * boundary, TDF_BOUNDARY flag is not set, and TDF_ALLPROCSUSP
7476ddcc233SKonstantin Belousov 		 * is used to avoid immediate un-suspend.
7486ddcc233SKonstantin Belousov 		 */
7496ddcc233SKonstantin Belousov 		if (TD_IS_SUSPENDED(td2) && (td2->td_flags & (TDF_BOUNDARY |
7506ddcc233SKonstantin Belousov 		    TDF_ALLPROCSUSP)) == 0)
75184cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
7526ddcc233SKonstantin Belousov 		if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0) {
7536ddcc233SKonstantin Belousov 			if ((td2->td_flags & TDF_SBDRY) == 0) {
7546ddcc233SKonstantin Belousov 				thread_suspend_one(td2);
7556ddcc233SKonstantin Belousov 				td2->td_flags |= TDF_ALLPROCSUSP;
7566ddcc233SKonstantin Belousov 			} else {
7576ddcc233SKonstantin Belousov 				wakeup_swapper |= sleepq_abort(td2, ERESTART);
7586ddcc233SKonstantin Belousov 			}
7596ddcc233SKonstantin Belousov 		}
76007a9368aSKonstantin Belousov 		break;
76107a9368aSKonstantin Belousov 	}
76207a9368aSKonstantin Belousov 	return (wakeup_swapper);
76307a9368aSKonstantin Belousov }
76407a9368aSKonstantin Belousov 
7655215b187SJeff Roberson /*
76644990b8cSJulian Elischer  * Enforce single-threading.
76744990b8cSJulian Elischer  *
76844990b8cSJulian Elischer  * Returns 1 if the caller must abort (another thread is waiting to
76944990b8cSJulian Elischer  * exit the process or similar). Process is locked!
77044990b8cSJulian Elischer  * Returns 0 when you are successfully the only thread running.
77144990b8cSJulian Elischer  * A process has successfully single threaded in the suspend mode when
77244990b8cSJulian Elischer  * There are no threads in user mode. Threads in the kernel must be
77344990b8cSJulian Elischer  * allowed to continue until they get to the user boundary. They may even
77444990b8cSJulian Elischer  * copy out their return values and data before suspending. They may however be
775e2668f55SMaxim Konovalov  * accelerated in reaching the user boundary as we will wake up
77644990b8cSJulian Elischer  * any sleeping threads that are interruptable. (PCATCH).
77744990b8cSJulian Elischer  */
77844990b8cSJulian Elischer int
7796ddcc233SKonstantin Belousov thread_single(struct proc *p, int mode)
78044990b8cSJulian Elischer {
78144990b8cSJulian Elischer 	struct thread *td;
78244990b8cSJulian Elischer 	struct thread *td2;
783da7bbd2cSJohn Baldwin 	int remaining, wakeup_swapper;
78444990b8cSJulian Elischer 
78544990b8cSJulian Elischer 	td = curthread;
7866ddcc233SKonstantin Belousov 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
7876ddcc233SKonstantin Belousov 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
7886ddcc233SKonstantin Belousov 	    ("invalid mode %d", mode));
7896ddcc233SKonstantin Belousov 	/*
7906ddcc233SKonstantin Belousov 	 * If allowing non-ALLPROC singlethreading for non-curproc
7916ddcc233SKonstantin Belousov 	 * callers, calc_remaining() and remain_for_mode() should be
7926ddcc233SKonstantin Belousov 	 * adjusted to also account for td->td_proc != p.  For now
7936ddcc233SKonstantin Belousov 	 * this is not implemented because it is not used.
7946ddcc233SKonstantin Belousov 	 */
7956ddcc233SKonstantin Belousov 	KASSERT((mode == SINGLE_ALLPROC && td->td_proc != p) ||
7966ddcc233SKonstantin Belousov 	    (mode != SINGLE_ALLPROC && td->td_proc == p),
7976ddcc233SKonstantin Belousov 	    ("mode %d proc %p curproc %p", mode, p, td->td_proc));
79837814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
79944990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
80044990b8cSJulian Elischer 
8016ddcc233SKonstantin Belousov 	if ((p->p_flag & P_HADTHREADS) == 0 && mode != SINGLE_ALLPROC)
80244990b8cSJulian Elischer 		return (0);
80344990b8cSJulian Elischer 
804e3b9bf71SJulian Elischer 	/* Is someone already single threading? */
805906ac69dSDavid Xu 	if (p->p_singlethread != NULL && p->p_singlethread != td)
80644990b8cSJulian Elischer 		return (1);
80744990b8cSJulian Elischer 
808906ac69dSDavid Xu 	if (mode == SINGLE_EXIT) {
809906ac69dSDavid Xu 		p->p_flag |= P_SINGLE_EXIT;
810906ac69dSDavid Xu 		p->p_flag &= ~P_SINGLE_BOUNDARY;
811906ac69dSDavid Xu 	} else {
812906ac69dSDavid Xu 		p->p_flag &= ~P_SINGLE_EXIT;
813906ac69dSDavid Xu 		if (mode == SINGLE_BOUNDARY)
814906ac69dSDavid Xu 			p->p_flag |= P_SINGLE_BOUNDARY;
815906ac69dSDavid Xu 		else
816906ac69dSDavid Xu 			p->p_flag &= ~P_SINGLE_BOUNDARY;
817906ac69dSDavid Xu 	}
8186ddcc233SKonstantin Belousov 	if (mode == SINGLE_ALLPROC)
8196ddcc233SKonstantin Belousov 		p->p_flag |= P_TOTAL_STOP;
8201279572aSDavid Xu 	p->p_flag |= P_STOPPED_SINGLE;
8217b4a950aSDavid Xu 	PROC_SLOCK(p);
822112afcb2SJohn Baldwin 	p->p_singlethread = td;
82379799053SKonstantin Belousov 	remaining = calc_remaining(p, mode);
82407a9368aSKonstantin Belousov 	while (remaining != remain_for_mode(mode)) {
825bf1a3220SDavid Xu 		if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
826bf1a3220SDavid Xu 			goto stopme;
827da7bbd2cSJohn Baldwin 		wakeup_swapper = 0;
82844990b8cSJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td2) {
82944990b8cSJulian Elischer 			if (td2 == td)
83044990b8cSJulian Elischer 				continue;
831a54e85fdSJeff Roberson 			thread_lock(td2);
832b7edba77SJeff Roberson 			td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
8336ddcc233SKonstantin Belousov 			if (TD_IS_INHIBITED(td2)) {
83407a9368aSKonstantin Belousov 				wakeup_swapper |= weed_inhib(mode, td2, p);
835d8267df7SDavid Xu #ifdef SMP
8366ddcc233SKonstantin Belousov 			} else if (TD_IS_RUNNING(td2) && td != td2) {
837d8267df7SDavid Xu 				forward_signal(td2);
838d8267df7SDavid Xu #endif
8396ddcc233SKonstantin Belousov 			}
840a54e85fdSJeff Roberson 			thread_unlock(td2);
8419d102777SJulian Elischer 		}
842da7bbd2cSJohn Baldwin 		if (wakeup_swapper)
843da7bbd2cSJohn Baldwin 			kick_proc0();
84479799053SKonstantin Belousov 		remaining = calc_remaining(p, mode);
845ec008e96SDavid Xu 
8469d102777SJulian Elischer 		/*
8479d102777SJulian Elischer 		 * Maybe we suspended some threads.. was it enough?
8489d102777SJulian Elischer 		 */
84907a9368aSKonstantin Belousov 		if (remaining == remain_for_mode(mode))
8509d102777SJulian Elischer 			break;
8519d102777SJulian Elischer 
852bf1a3220SDavid Xu stopme:
85344990b8cSJulian Elischer 		/*
85444990b8cSJulian Elischer 		 * Wake us up when everyone else has suspended.
855e3b9bf71SJulian Elischer 		 * In the mean time we suspend as well.
85644990b8cSJulian Elischer 		 */
8576ddcc233SKonstantin Belousov 		thread_suspend_switch(td, p);
85879799053SKonstantin Belousov 		remaining = calc_remaining(p, mode);
85944990b8cSJulian Elischer 	}
860906ac69dSDavid Xu 	if (mode == SINGLE_EXIT) {
86191599697SJulian Elischer 		/*
8628626a0ddSKonstantin Belousov 		 * Convert the process to an unthreaded process.  The
8638626a0ddSKonstantin Belousov 		 * SINGLE_EXIT is called by exit1() or execve(), in
8648626a0ddSKonstantin Belousov 		 * both cases other threads must be retired.
86591599697SJulian Elischer 		 */
8668626a0ddSKonstantin Belousov 		KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
867ed062c8dSJulian Elischer 		p->p_singlethread = NULL;
8688626a0ddSKonstantin Belousov 		p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
869fd229b5bSKonstantin Belousov 
870fd229b5bSKonstantin Belousov 		/*
871fd229b5bSKonstantin Belousov 		 * Wait for any remaining threads to exit cpu_throw().
872fd229b5bSKonstantin Belousov 		 */
873fd229b5bSKonstantin Belousov 		while (p->p_exitthreads != 0) {
874fd229b5bSKonstantin Belousov 			PROC_SUNLOCK(p);
875fd229b5bSKonstantin Belousov 			PROC_UNLOCK(p);
876fd229b5bSKonstantin Belousov 			sched_relinquish(td);
877fd229b5bSKonstantin Belousov 			PROC_LOCK(p);
878fd229b5bSKonstantin Belousov 			PROC_SLOCK(p);
879fd229b5bSKonstantin Belousov 		}
880ac437c07SKonstantin Belousov 	} else if (mode == SINGLE_BOUNDARY) {
881ac437c07SKonstantin Belousov 		/*
882ac437c07SKonstantin Belousov 		 * Wait until all suspended threads are removed from
883ac437c07SKonstantin Belousov 		 * the processors.  The thread_suspend_check()
884ac437c07SKonstantin Belousov 		 * increments p_boundary_count while it is still
885ac437c07SKonstantin Belousov 		 * running, which makes it possible for the execve()
886ac437c07SKonstantin Belousov 		 * to destroy vmspace while our other threads are
887ac437c07SKonstantin Belousov 		 * still using the address space.
888ac437c07SKonstantin Belousov 		 *
889ac437c07SKonstantin Belousov 		 * We lock the thread, which is only allowed to
890ac437c07SKonstantin Belousov 		 * succeed after context switch code finished using
891ac437c07SKonstantin Belousov 		 * the address space.
892ac437c07SKonstantin Belousov 		 */
893ac437c07SKonstantin Belousov 		FOREACH_THREAD_IN_PROC(p, td2) {
894ac437c07SKonstantin Belousov 			if (td2 == td)
895ac437c07SKonstantin Belousov 				continue;
896ac437c07SKonstantin Belousov 			thread_lock(td2);
897ac437c07SKonstantin Belousov 			KASSERT((td2->td_flags & TDF_BOUNDARY) != 0,
898ac437c07SKonstantin Belousov 			    ("td %p not on boundary", td2));
899ac437c07SKonstantin Belousov 			KASSERT(TD_IS_SUSPENDED(td2),
900ac437c07SKonstantin Belousov 			    ("td %p is not suspended", td2));
901ac437c07SKonstantin Belousov 			thread_unlock(td2);
902ac437c07SKonstantin Belousov 		}
90391599697SJulian Elischer 	}
9047b4a950aSDavid Xu 	PROC_SUNLOCK(p);
90544990b8cSJulian Elischer 	return (0);
90644990b8cSJulian Elischer }
90744990b8cSJulian Elischer 
9088638fe7bSKonstantin Belousov bool
9098638fe7bSKonstantin Belousov thread_suspend_check_needed(void)
9108638fe7bSKonstantin Belousov {
9118638fe7bSKonstantin Belousov 	struct proc *p;
9128638fe7bSKonstantin Belousov 	struct thread *td;
9138638fe7bSKonstantin Belousov 
9148638fe7bSKonstantin Belousov 	td = curthread;
9158638fe7bSKonstantin Belousov 	p = td->td_proc;
9168638fe7bSKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
9178638fe7bSKonstantin Belousov 	return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
9188638fe7bSKonstantin Belousov 	    (td->td_dbgflags & TDB_SUSPEND) != 0));
9198638fe7bSKonstantin Belousov }
9208638fe7bSKonstantin Belousov 
92144990b8cSJulian Elischer /*
92244990b8cSJulian Elischer  * Called in from locations that can safely check to see
92344990b8cSJulian Elischer  * whether we have to suspend or at least throttle for a
92444990b8cSJulian Elischer  * single-thread event (e.g. fork).
92544990b8cSJulian Elischer  *
92644990b8cSJulian Elischer  * Such locations include userret().
92744990b8cSJulian Elischer  * If the "return_instead" argument is non zero, the thread must be able to
92844990b8cSJulian Elischer  * accept 0 (caller may continue), or 1 (caller must abort) as a result.
92944990b8cSJulian Elischer  *
93044990b8cSJulian Elischer  * The 'return_instead' argument tells the function if it may do a
93144990b8cSJulian Elischer  * thread_exit() or suspend, or whether the caller must abort and back
93244990b8cSJulian Elischer  * out instead.
93344990b8cSJulian Elischer  *
93444990b8cSJulian Elischer  * If the thread that set the single_threading request has set the
93544990b8cSJulian Elischer  * P_SINGLE_EXIT bit in the process flags then this call will never return
93644990b8cSJulian Elischer  * if 'return_instead' is false, but will exit.
93744990b8cSJulian Elischer  *
93844990b8cSJulian Elischer  * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
93944990b8cSJulian Elischer  *---------------+--------------------+---------------------
94044990b8cSJulian Elischer  *       0       | returns 0          |   returns 0 or 1
941353374b5SJohn Baldwin  *               | when ST ends       |   immediately
94244990b8cSJulian Elischer  *---------------+--------------------+---------------------
94344990b8cSJulian Elischer  *       1       | thread exits       |   returns 1
944353374b5SJohn Baldwin  *               |                    |  immediately
94544990b8cSJulian Elischer  * 0 = thread_exit() or suspension ok,
94644990b8cSJulian Elischer  * other = return error instead of stopping the thread.
94744990b8cSJulian Elischer  *
94844990b8cSJulian Elischer  * While a full suspension is under effect, even a single threading
94944990b8cSJulian Elischer  * thread would be suspended if it made this call (but it shouldn't).
95044990b8cSJulian Elischer  * This call should only be made from places where
95144990b8cSJulian Elischer  * thread_exit() would be safe as that may be the outcome unless
95244990b8cSJulian Elischer  * return_instead is set.
95344990b8cSJulian Elischer  */
95444990b8cSJulian Elischer int
95544990b8cSJulian Elischer thread_suspend_check(int return_instead)
95644990b8cSJulian Elischer {
957ecafb24bSJuli Mallett 	struct thread *td;
958ecafb24bSJuli Mallett 	struct proc *p;
95946e47c4fSKonstantin Belousov 	int wakeup_swapper;
96044990b8cSJulian Elischer 
96144990b8cSJulian Elischer 	td = curthread;
96244990b8cSJulian Elischer 	p = td->td_proc;
96337814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
96444990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
9658638fe7bSKonstantin Belousov 	while (thread_suspend_check_needed()) {
9661279572aSDavid Xu 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
96744990b8cSJulian Elischer 			KASSERT(p->p_singlethread != NULL,
96844990b8cSJulian Elischer 			    ("singlethread not set"));
96944990b8cSJulian Elischer 			/*
970e3b9bf71SJulian Elischer 			 * The only suspension in action is a
971e3b9bf71SJulian Elischer 			 * single-threading. Single threader need not stop.
972bd07998eSKonstantin Belousov 			 * It is safe to access p->p_singlethread unlocked
973bd07998eSKonstantin Belousov 			 * because it can only be set to our address by us.
97444990b8cSJulian Elischer 			 */
975e3b9bf71SJulian Elischer 			if (p->p_singlethread == td)
97644990b8cSJulian Elischer 				return (0);	/* Exempt from stopping. */
97744990b8cSJulian Elischer 		}
97845a4bfa1SDavid Xu 		if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
97994f0972bSDavid Xu 			return (EINTR);
98044990b8cSJulian Elischer 
981906ac69dSDavid Xu 		/* Should we goto user boundary if we didn't come from there? */
982906ac69dSDavid Xu 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
983906ac69dSDavid Xu 		    (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
98494f0972bSDavid Xu 			return (ERESTART);
985906ac69dSDavid Xu 
98644990b8cSJulian Elischer 		/*
9873077f938SKonstantin Belousov 		 * Ignore suspend requests if they are deferred.
988d071a6faSJohn Baldwin 		 */
9893077f938SKonstantin Belousov 		if ((td->td_flags & TDF_SBDRY) != 0) {
990d071a6faSJohn Baldwin 			KASSERT(return_instead,
991d071a6faSJohn Baldwin 			    ("TDF_SBDRY set for unsafe thread_suspend_check"));
99246e47c4fSKonstantin Belousov 			KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
99346e47c4fSKonstantin Belousov 			    (TDF_SEINTR | TDF_SERESTART),
99446e47c4fSKonstantin Belousov 			    ("both TDF_SEINTR and TDF_SERESTART"));
99546e47c4fSKonstantin Belousov 			return (TD_SBDRY_INTR(td) ? TD_SBDRY_ERRNO(td) : 0);
996d071a6faSJohn Baldwin 		}
997d071a6faSJohn Baldwin 
998d071a6faSJohn Baldwin 		/*
99944990b8cSJulian Elischer 		 * If the process is waiting for us to exit,
100044990b8cSJulian Elischer 		 * this thread should just suicide.
10011279572aSDavid Xu 		 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
100244990b8cSJulian Elischer 		 */
1003cf7d9a8cSDavid Xu 		if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
1004cf7d9a8cSDavid Xu 			PROC_UNLOCK(p);
100591d1786fSDmitry Chagin 
100691d1786fSDmitry Chagin 			/*
100791d1786fSDmitry Chagin 			 * Allow Linux emulation layer to do some work
100891d1786fSDmitry Chagin 			 * before thread suicide.
100991d1786fSDmitry Chagin 			 */
101091d1786fSDmitry Chagin 			if (__predict_false(p->p_sysent->sv_thread_detach != NULL))
101191d1786fSDmitry Chagin 				(p->p_sysent->sv_thread_detach)(td);
10122a339d9eSKonstantin Belousov 			umtx_thread_exit(td);
1013d1e7a4a5SJohn Baldwin 			kern_thr_exit(td);
1014d1e7a4a5SJohn Baldwin 			panic("stopped thread did not exit");
1015cf7d9a8cSDavid Xu 		}
101621ecd1e9SDavid Xu 
101721ecd1e9SDavid Xu 		PROC_SLOCK(p);
101821ecd1e9SDavid Xu 		thread_stopped(p);
1019a54e85fdSJeff Roberson 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1020a54e85fdSJeff Roberson 			if (p->p_numthreads == p->p_suspcount + 1) {
1021a54e85fdSJeff Roberson 				thread_lock(p->p_singlethread);
102284cdea97SKonstantin Belousov 				wakeup_swapper = thread_unsuspend_one(
102384cdea97SKonstantin Belousov 				    p->p_singlethread, p, false);
1024a54e85fdSJeff Roberson 				thread_unlock(p->p_singlethread);
10257847a9daSJohn Baldwin 				if (wakeup_swapper)
10267847a9daSJohn Baldwin 					kick_proc0();
1027a54e85fdSJeff Roberson 			}
1028a54e85fdSJeff Roberson 		}
10293f9be10eSDavid Xu 		PROC_UNLOCK(p);
10307b4a950aSDavid Xu 		thread_lock(td);
103144990b8cSJulian Elischer 		/*
103244990b8cSJulian Elischer 		 * When a thread suspends, it just
1033ad1e7d28SJulian Elischer 		 * gets taken off all queues.
103444990b8cSJulian Elischer 		 */
103571fad9fdSJulian Elischer 		thread_suspend_one(td);
1036906ac69dSDavid Xu 		if (return_instead == 0) {
1037906ac69dSDavid Xu 			p->p_boundary_count++;
1038906ac69dSDavid Xu 			td->td_flags |= TDF_BOUNDARY;
1039cf19bf91SJulian Elischer 		}
10407b4a950aSDavid Xu 		PROC_SUNLOCK(p);
10418df78c41SJeff Roberson 		mi_switch(SW_INVOL | SWT_SUSPEND, NULL);
1042a54e85fdSJeff Roberson 		thread_unlock(td);
104344990b8cSJulian Elischer 		PROC_LOCK(p);
104444990b8cSJulian Elischer 	}
104544990b8cSJulian Elischer 	return (0);
104644990b8cSJulian Elischer }
104744990b8cSJulian Elischer 
104835c32a76SDavid Xu void
10496ddcc233SKonstantin Belousov thread_suspend_switch(struct thread *td, struct proc *p)
1050a54e85fdSJeff Roberson {
1051a54e85fdSJeff Roberson 
1052a54e85fdSJeff Roberson 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1053a54e85fdSJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
10547b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1055a54e85fdSJeff Roberson 	/*
1056a54e85fdSJeff Roberson 	 * We implement thread_suspend_one in stages here to avoid
1057a54e85fdSJeff Roberson 	 * dropping the proc lock while the thread lock is owned.
1058a54e85fdSJeff Roberson 	 */
10596ddcc233SKonstantin Belousov 	if (p == td->td_proc) {
1060a54e85fdSJeff Roberson 		thread_stopped(p);
1061a54e85fdSJeff Roberson 		p->p_suspcount++;
10626ddcc233SKonstantin Belousov 	}
10633f9be10eSDavid Xu 	PROC_UNLOCK(p);
10647b4a950aSDavid Xu 	thread_lock(td);
1065b7edba77SJeff Roberson 	td->td_flags &= ~TDF_NEEDSUSPCHK;
1066a54e85fdSJeff Roberson 	TD_SET_SUSPENDED(td);
1067c5aa6b58SJeff Roberson 	sched_sleep(td, 0);
10687b4a950aSDavid Xu 	PROC_SUNLOCK(p);
1069a54e85fdSJeff Roberson 	DROP_GIANT();
10708df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_SUSPEND, NULL);
1071a54e85fdSJeff Roberson 	thread_unlock(td);
1072a54e85fdSJeff Roberson 	PICKUP_GIANT();
1073a54e85fdSJeff Roberson 	PROC_LOCK(p);
10747b4a950aSDavid Xu 	PROC_SLOCK(p);
1075a54e85fdSJeff Roberson }
1076a54e85fdSJeff Roberson 
1077a54e85fdSJeff Roberson void
107835c32a76SDavid Xu thread_suspend_one(struct thread *td)
107935c32a76SDavid Xu {
10806ddcc233SKonstantin Belousov 	struct proc *p;
108135c32a76SDavid Xu 
10826ddcc233SKonstantin Belousov 	p = td->td_proc;
10837b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1084a54e85fdSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1085e574e444SDavid Xu 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
108635c32a76SDavid Xu 	p->p_suspcount++;
1087b7edba77SJeff Roberson 	td->td_flags &= ~TDF_NEEDSUSPCHK;
108871fad9fdSJulian Elischer 	TD_SET_SUSPENDED(td);
1089c5aa6b58SJeff Roberson 	sched_sleep(td, 0);
109035c32a76SDavid Xu }
109135c32a76SDavid Xu 
109284cdea97SKonstantin Belousov static int
109384cdea97SKonstantin Belousov thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
109435c32a76SDavid Xu {
109535c32a76SDavid Xu 
1096a54e85fdSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1097ad1e7d28SJulian Elischer 	KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
109871fad9fdSJulian Elischer 	TD_CLR_SUSPENDED(td);
10996ddcc233SKonstantin Belousov 	td->td_flags &= ~TDF_ALLPROCSUSP;
11006ddcc233SKonstantin Belousov 	if (td->td_proc == p) {
11016ddcc233SKonstantin Belousov 		PROC_SLOCK_ASSERT(p, MA_OWNED);
110235c32a76SDavid Xu 		p->p_suspcount--;
110384cdea97SKonstantin Belousov 		if (boundary && (td->td_flags & TDF_BOUNDARY) != 0) {
110484cdea97SKonstantin Belousov 			td->td_flags &= ~TDF_BOUNDARY;
110584cdea97SKonstantin Belousov 			p->p_boundary_count--;
110684cdea97SKonstantin Belousov 		}
11076ddcc233SKonstantin Belousov 	}
11087847a9daSJohn Baldwin 	return (setrunnable(td));
110935c32a76SDavid Xu }
111035c32a76SDavid Xu 
111144990b8cSJulian Elischer /*
111244990b8cSJulian Elischer  * Allow all threads blocked by single threading to continue running.
111344990b8cSJulian Elischer  */
111444990b8cSJulian Elischer void
111544990b8cSJulian Elischer thread_unsuspend(struct proc *p)
111644990b8cSJulian Elischer {
111744990b8cSJulian Elischer 	struct thread *td;
11187847a9daSJohn Baldwin 	int wakeup_swapper;
111944990b8cSJulian Elischer 
112044990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
11217b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
11227847a9daSJohn Baldwin 	wakeup_swapper = 0;
112344990b8cSJulian Elischer 	if (!P_SHOULDSTOP(p)) {
1124ad1e7d28SJulian Elischer                 FOREACH_THREAD_IN_PROC(p, td) {
1125a54e85fdSJeff Roberson 			thread_lock(td);
1126ad1e7d28SJulian Elischer 			if (TD_IS_SUSPENDED(td)) {
112784cdea97SKonstantin Belousov 				wakeup_swapper |= thread_unsuspend_one(td, p,
112884cdea97SKonstantin Belousov 				    true);
112944990b8cSJulian Elischer 			}
1130a54e85fdSJeff Roberson 			thread_unlock(td);
1131ad1e7d28SJulian Elischer 		}
113284cdea97SKonstantin Belousov 	} else if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
113384cdea97SKonstantin Belousov 	    p->p_numthreads == p->p_suspcount) {
113444990b8cSJulian Elischer 		/*
113544990b8cSJulian Elischer 		 * Stopping everything also did the job for the single
113644990b8cSJulian Elischer 		 * threading request. Now we've downgraded to single-threaded,
113744990b8cSJulian Elischer 		 * let it continue.
113844990b8cSJulian Elischer 		 */
11396ddcc233SKonstantin Belousov 		if (p->p_singlethread->td_proc == p) {
1140a54e85fdSJeff Roberson 			thread_lock(p->p_singlethread);
11416ddcc233SKonstantin Belousov 			wakeup_swapper = thread_unsuspend_one(
114284cdea97SKonstantin Belousov 			    p->p_singlethread, p, false);
1143a54e85fdSJeff Roberson 			thread_unlock(p->p_singlethread);
114444990b8cSJulian Elischer 		}
11456ddcc233SKonstantin Belousov 	}
11467847a9daSJohn Baldwin 	if (wakeup_swapper)
11477847a9daSJohn Baldwin 		kick_proc0();
114844990b8cSJulian Elischer }
114944990b8cSJulian Elischer 
1150ed062c8dSJulian Elischer /*
1151ed062c8dSJulian Elischer  * End the single threading mode..
1152ed062c8dSJulian Elischer  */
115344990b8cSJulian Elischer void
11546ddcc233SKonstantin Belousov thread_single_end(struct proc *p, int mode)
115544990b8cSJulian Elischer {
115644990b8cSJulian Elischer 	struct thread *td;
11577847a9daSJohn Baldwin 	int wakeup_swapper;
115844990b8cSJulian Elischer 
11596ddcc233SKonstantin Belousov 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
11606ddcc233SKonstantin Belousov 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
11616ddcc233SKonstantin Belousov 	    ("invalid mode %d", mode));
116244990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
11636ddcc233SKonstantin Belousov 	KASSERT((mode == SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) != 0) ||
11646ddcc233SKonstantin Belousov 	    (mode != SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) == 0),
11656ddcc233SKonstantin Belousov 	    ("mode %d does not match P_TOTAL_STOP", mode));
116684cdea97SKonstantin Belousov 	KASSERT(mode == SINGLE_ALLPROC || p->p_singlethread == curthread,
116784cdea97SKonstantin Belousov 	    ("thread_single_end from other thread %p %p",
116884cdea97SKonstantin Belousov 	    curthread, p->p_singlethread));
116984cdea97SKonstantin Belousov 	KASSERT(mode != SINGLE_BOUNDARY ||
117084cdea97SKonstantin Belousov 	    (p->p_flag & P_SINGLE_BOUNDARY) != 0,
117184cdea97SKonstantin Belousov 	    ("mis-matched SINGLE_BOUNDARY flags %x", p->p_flag));
11726ddcc233SKonstantin Belousov 	p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY |
11736ddcc233SKonstantin Belousov 	    P_TOTAL_STOP);
11747b4a950aSDavid Xu 	PROC_SLOCK(p);
117544990b8cSJulian Elischer 	p->p_singlethread = NULL;
11767847a9daSJohn Baldwin 	wakeup_swapper = 0;
117749539972SJulian Elischer 	/*
11787847a9daSJohn Baldwin 	 * If there are other threads they may now run,
117949539972SJulian Elischer 	 * unless of course there is a blanket 'stop order'
118049539972SJulian Elischer 	 * on the process. The single threader must be allowed
118149539972SJulian Elischer 	 * to continue however as this is a bad place to stop.
118249539972SJulian Elischer 	 */
11836ddcc233SKonstantin Belousov 	if (p->p_numthreads != remain_for_mode(mode) && !P_SHOULDSTOP(p)) {
1184ad1e7d28SJulian Elischer                 FOREACH_THREAD_IN_PROC(p, td) {
1185a54e85fdSJeff Roberson 			thread_lock(td);
1186ad1e7d28SJulian Elischer 			if (TD_IS_SUSPENDED(td)) {
118784cdea97SKonstantin Belousov 				wakeup_swapper |= thread_unsuspend_one(td, p,
118884cdea97SKonstantin Belousov 				    mode == SINGLE_BOUNDARY);
118944990b8cSJulian Elischer 			}
1190a54e85fdSJeff Roberson 			thread_unlock(td);
119149539972SJulian Elischer 		}
1192ad1e7d28SJulian Elischer 	}
119384cdea97SKonstantin Belousov 	KASSERT(mode != SINGLE_BOUNDARY || p->p_boundary_count == 0,
119484cdea97SKonstantin Belousov 	    ("inconsistent boundary count %d", p->p_boundary_count));
11957b4a950aSDavid Xu 	PROC_SUNLOCK(p);
11967847a9daSJohn Baldwin 	if (wakeup_swapper)
11977847a9daSJohn Baldwin 		kick_proc0();
119849539972SJulian Elischer }
11994fc21c09SDaniel Eischen 
120044355392SDavid Xu struct thread *
120144355392SDavid Xu thread_find(struct proc *p, lwpid_t tid)
120244355392SDavid Xu {
120344355392SDavid Xu 	struct thread *td;
120444355392SDavid Xu 
120544355392SDavid Xu 	PROC_LOCK_ASSERT(p, MA_OWNED);
120644355392SDavid Xu 	FOREACH_THREAD_IN_PROC(p, td) {
120744355392SDavid Xu 		if (td->td_tid == tid)
120844355392SDavid Xu 			break;
120944355392SDavid Xu 	}
121044355392SDavid Xu 	return (td);
121144355392SDavid Xu }
1212cf7d9a8cSDavid Xu 
1213cf7d9a8cSDavid Xu /* Locate a thread by number; return with proc lock held. */
1214cf7d9a8cSDavid Xu struct thread *
1215cf7d9a8cSDavid Xu tdfind(lwpid_t tid, pid_t pid)
1216cf7d9a8cSDavid Xu {
1217cf7d9a8cSDavid Xu #define RUN_THRESH	16
1218cf7d9a8cSDavid Xu 	struct thread *td;
1219cf7d9a8cSDavid Xu 	int run = 0;
1220cf7d9a8cSDavid Xu 
1221cf7d9a8cSDavid Xu 	rw_rlock(&tidhash_lock);
1222cf7d9a8cSDavid Xu 	LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1223cf7d9a8cSDavid Xu 		if (td->td_tid == tid) {
1224cf7d9a8cSDavid Xu 			if (pid != -1 && td->td_proc->p_pid != pid) {
1225cf7d9a8cSDavid Xu 				td = NULL;
1226cf7d9a8cSDavid Xu 				break;
1227cf7d9a8cSDavid Xu 			}
12288e6fa660SJohn Baldwin 			PROC_LOCK(td->td_proc);
1229cf7d9a8cSDavid Xu 			if (td->td_proc->p_state == PRS_NEW) {
12308e6fa660SJohn Baldwin 				PROC_UNLOCK(td->td_proc);
1231cf7d9a8cSDavid Xu 				td = NULL;
1232cf7d9a8cSDavid Xu 				break;
1233cf7d9a8cSDavid Xu 			}
1234cf7d9a8cSDavid Xu 			if (run > RUN_THRESH) {
1235cf7d9a8cSDavid Xu 				if (rw_try_upgrade(&tidhash_lock)) {
1236cf7d9a8cSDavid Xu 					LIST_REMOVE(td, td_hash);
1237cf7d9a8cSDavid Xu 					LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1238cf7d9a8cSDavid Xu 						td, td_hash);
1239cf7d9a8cSDavid Xu 					rw_wunlock(&tidhash_lock);
1240cf7d9a8cSDavid Xu 					return (td);
1241cf7d9a8cSDavid Xu 				}
1242cf7d9a8cSDavid Xu 			}
1243cf7d9a8cSDavid Xu 			break;
1244cf7d9a8cSDavid Xu 		}
1245cf7d9a8cSDavid Xu 		run++;
1246cf7d9a8cSDavid Xu 	}
1247cf7d9a8cSDavid Xu 	rw_runlock(&tidhash_lock);
1248cf7d9a8cSDavid Xu 	return (td);
1249cf7d9a8cSDavid Xu }
1250cf7d9a8cSDavid Xu 
1251cf7d9a8cSDavid Xu void
1252cf7d9a8cSDavid Xu tidhash_add(struct thread *td)
1253cf7d9a8cSDavid Xu {
1254cf7d9a8cSDavid Xu 	rw_wlock(&tidhash_lock);
1255cf7d9a8cSDavid Xu 	LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1256cf7d9a8cSDavid Xu 	rw_wunlock(&tidhash_lock);
1257cf7d9a8cSDavid Xu }
1258cf7d9a8cSDavid Xu 
1259cf7d9a8cSDavid Xu void
1260cf7d9a8cSDavid Xu tidhash_remove(struct thread *td)
1261cf7d9a8cSDavid Xu {
1262cf7d9a8cSDavid Xu 	rw_wlock(&tidhash_lock);
1263cf7d9a8cSDavid Xu 	LIST_REMOVE(td, td_hash);
1264cf7d9a8cSDavid Xu 	rw_wunlock(&tidhash_lock);
1265cf7d9a8cSDavid Xu }
1266