xref: /freebsd/sys/kern/kern_thread.c (revision f6eccf96a0ffa94ead8565145a4a845c79d74f7b)
19454b2d8SWarner Losh /*-
28a36da99SPedro F. Giffuni  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
38a36da99SPedro F. Giffuni  *
444990b8cSJulian Elischer  * Copyright (C) 2001 Julian Elischer <julian@freebsd.org>.
544990b8cSJulian Elischer  *  All rights reserved.
644990b8cSJulian Elischer  *
744990b8cSJulian Elischer  * Redistribution and use in source and binary forms, with or without
844990b8cSJulian Elischer  * modification, are permitted provided that the following conditions
944990b8cSJulian Elischer  * are met:
1044990b8cSJulian Elischer  * 1. Redistributions of source code must retain the above copyright
1144990b8cSJulian Elischer  *    notice(s), this list of conditions and the following disclaimer as
1244990b8cSJulian Elischer  *    the first lines of this file unmodified other than the possible
1344990b8cSJulian Elischer  *    addition of one or more copyright notices.
1444990b8cSJulian Elischer  * 2. Redistributions in binary form must reproduce the above copyright
1544990b8cSJulian Elischer  *    notice(s), this list of conditions and the following disclaimer in the
1644990b8cSJulian Elischer  *    documentation and/or other materials provided with the distribution.
1744990b8cSJulian Elischer  *
1844990b8cSJulian Elischer  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
1944990b8cSJulian Elischer  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
2044990b8cSJulian Elischer  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2144990b8cSJulian Elischer  * DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
2244990b8cSJulian Elischer  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
2344990b8cSJulian Elischer  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2444990b8cSJulian Elischer  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2544990b8cSJulian Elischer  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2644990b8cSJulian Elischer  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2744990b8cSJulian Elischer  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
2844990b8cSJulian Elischer  * DAMAGE.
2944990b8cSJulian Elischer  */
3044990b8cSJulian Elischer 
313d06b4b3SAttilio Rao #include "opt_witness.h"
3216d95d4fSJoseph Koshy #include "opt_hwpmc_hooks.h"
333d06b4b3SAttilio Rao 
34677b542eSDavid E. O'Brien #include <sys/cdefs.h>
35677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
36677b542eSDavid E. O'Brien 
3744990b8cSJulian Elischer #include <sys/param.h>
3844990b8cSJulian Elischer #include <sys/systm.h>
3944990b8cSJulian Elischer #include <sys/kernel.h>
4044990b8cSJulian Elischer #include <sys/lock.h>
4144990b8cSJulian Elischer #include <sys/mutex.h>
4244990b8cSJulian Elischer #include <sys/proc.h>
436febf180SGleb Smirnoff #include <sys/epoch.h>
448f0e9130SKonstantin Belousov #include <sys/rangelock.h>
45e170bfdaSDavid Xu #include <sys/resourcevar.h>
46b3e9e682SRyan Stone #include <sys/sdt.h>
4794e0a4cdSJulian Elischer #include <sys/smp.h>
48de028f5aSJeff Roberson #include <sys/sched.h>
4944f3b092SJohn Baldwin #include <sys/sleepqueue.h>
50ace8398dSJeff Roberson #include <sys/selinfo.h>
51d1e7a4a5SJohn Baldwin #include <sys/syscallsubr.h>
5291d1786fSDmitry Chagin #include <sys/sysent.h>
53961a7b24SJohn Baldwin #include <sys/turnstile.h>
5444990b8cSJulian Elischer #include <sys/ktr.h>
55cf7d9a8cSDavid Xu #include <sys/rwlock.h>
56bc8e6d81SDavid Xu #include <sys/umtx.h>
579ed01c32SGleb Smirnoff #include <sys/vmmeter.h>
58d7f687fcSJeff Roberson #include <sys/cpuset.h>
5916d95d4fSJoseph Koshy #ifdef	HWPMC_HOOKS
6016d95d4fSJoseph Koshy #include <sys/pmckern.h>
6116d95d4fSJoseph Koshy #endif
6244990b8cSJulian Elischer 
63911b84b0SRobert Watson #include <security/audit/audit.h>
64911b84b0SRobert Watson 
6544990b8cSJulian Elischer #include <vm/vm.h>
6649a2507bSAlan Cox #include <vm/vm_extern.h>
6744990b8cSJulian Elischer #include <vm/uma.h>
68b209f889SRandall Stewart #include <sys/eventhandler.h>
6902fb42b0SPeter Wemm 
70acd9f517SKonstantin Belousov /*
71acd9f517SKonstantin Belousov  * Asserts below verify the stability of struct thread and struct proc
72acd9f517SKonstantin Belousov  * layout, as exposed by KBI to modules.  On head, the KBI is allowed
73acd9f517SKonstantin Belousov  * to drift, change to the structures must be accompanied by the
74acd9f517SKonstantin Belousov  * assert update.
75acd9f517SKonstantin Belousov  *
76acd9f517SKonstantin Belousov  * On the stable branches after KBI freeze, conditions must not be
77acd9f517SKonstantin Belousov  * violated.  Typically new fields are moved to the end of the
78acd9f517SKonstantin Belousov  * structures.
79acd9f517SKonstantin Belousov  */
80acd9f517SKonstantin Belousov #ifdef __amd64__
813f289c3fSJeff Roberson _Static_assert(offsetof(struct thread, td_flags) == 0xfc,
82acd9f517SKonstantin Belousov     "struct thread KBI td_flags");
833f289c3fSJeff Roberson _Static_assert(offsetof(struct thread, td_pflags) == 0x104,
84acd9f517SKonstantin Belousov     "struct thread KBI td_pflags");
85b3c0d957SAndrew Turner _Static_assert(offsetof(struct thread, td_frame) == 0x478,
86acd9f517SKonstantin Belousov     "struct thread KBI td_frame");
871af9474bSJohn Baldwin _Static_assert(offsetof(struct thread, td_emuldata) == 0x540,
88acd9f517SKonstantin Belousov     "struct thread KBI td_emuldata");
89acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_flag) == 0xb0,
90acd9f517SKonstantin Belousov     "struct proc KBI p_flag");
91acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_pid) == 0xbc,
92acd9f517SKonstantin Belousov     "struct proc KBI p_pid");
9383bf5ec3SJohn Baldwin _Static_assert(offsetof(struct proc, p_filemon) == 0x3c8,
94acd9f517SKonstantin Belousov     "struct proc KBI p_filemon");
9583bf5ec3SJohn Baldwin _Static_assert(offsetof(struct proc, p_comm) == 0x3e0,
96acd9f517SKonstantin Belousov     "struct proc KBI p_comm");
9783bf5ec3SJohn Baldwin _Static_assert(offsetof(struct proc, p_emuldata) == 0x4c0,
98acd9f517SKonstantin Belousov     "struct proc KBI p_emuldata");
99acd9f517SKonstantin Belousov #endif
100acd9f517SKonstantin Belousov #ifdef __i386__
1013f289c3fSJeff Roberson _Static_assert(offsetof(struct thread, td_flags) == 0x98,
102acd9f517SKonstantin Belousov     "struct thread KBI td_flags");
1033f289c3fSJeff Roberson _Static_assert(offsetof(struct thread, td_pflags) == 0xa0,
104acd9f517SKonstantin Belousov     "struct thread KBI td_pflags");
1051af9474bSJohn Baldwin _Static_assert(offsetof(struct thread, td_frame) == 0x2f0,
106acd9f517SKonstantin Belousov     "struct thread KBI td_frame");
107be860eaeSAndrew Turner _Static_assert(offsetof(struct thread, td_emuldata) == 0x338,
108acd9f517SKonstantin Belousov     "struct thread KBI td_emuldata");
109acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_flag) == 0x68,
110acd9f517SKonstantin Belousov     "struct proc KBI p_flag");
111acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_pid) == 0x74,
112acd9f517SKonstantin Belousov     "struct proc KBI p_pid");
11383bf5ec3SJohn Baldwin _Static_assert(offsetof(struct proc, p_filemon) == 0x278,
114acd9f517SKonstantin Belousov     "struct proc KBI p_filemon");
11583bf5ec3SJohn Baldwin _Static_assert(offsetof(struct proc, p_comm) == 0x28c,
116acd9f517SKonstantin Belousov     "struct proc KBI p_comm");
11783bf5ec3SJohn Baldwin _Static_assert(offsetof(struct proc, p_emuldata) == 0x318,
118acd9f517SKonstantin Belousov     "struct proc KBI p_emuldata");
119acd9f517SKonstantin Belousov #endif
120acd9f517SKonstantin Belousov 
121b3e9e682SRyan Stone SDT_PROVIDER_DECLARE(proc);
122d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(proc, , , lwp__exit);
123b3e9e682SRyan Stone 
1248460a577SJohn Birrell /*
1258460a577SJohn Birrell  * thread related storage.
1268460a577SJohn Birrell  */
12744990b8cSJulian Elischer static uma_zone_t thread_zone;
12844990b8cSJulian Elischer 
1295215b187SJeff Roberson TAILQ_HEAD(, thread) zombie_threads = TAILQ_HEAD_INITIALIZER(zombie_threads);
130c8790f5dSAttilio Rao static struct mtx zombie_lock;
131a54e85fdSJeff Roberson MTX_SYSINIT(zombie_lock, &zombie_lock, "zombie lock", MTX_SPIN);
13244990b8cSJulian Elischer 
133ff8fbcffSJeff Roberson static void thread_zombie(struct thread *);
13484cdea97SKonstantin Belousov static int thread_unsuspend_one(struct thread *td, struct proc *p,
13584cdea97SKonstantin Belousov     bool boundary);
136ff8fbcffSJeff Roberson 
137ec6ea5e8SDavid Xu #define TID_BUFFER_SIZE	1024
138ec6ea5e8SDavid Xu 
139fdcac928SMarcel Moolenaar struct mtx tid_lock;
1401ea7a6f8SPoul-Henning Kamp static struct unrhdr *tid_unrhdr;
141ec6ea5e8SDavid Xu static lwpid_t tid_buffer[TID_BUFFER_SIZE];
142ec6ea5e8SDavid Xu static int tid_head, tid_tail;
143cf7d9a8cSDavid Xu static MALLOC_DEFINE(M_TIDHASH, "tidhash", "thread hash");
144cf7d9a8cSDavid Xu 
145cf7d9a8cSDavid Xu struct	tidhashhead *tidhashtbl;
146cf7d9a8cSDavid Xu u_long	tidhash;
147cf7d9a8cSDavid Xu struct	rwlock tidhash_lock;
148cf7d9a8cSDavid Xu 
1492ca45184SMatt Joras EVENTHANDLER_LIST_DEFINE(thread_ctor);
1502ca45184SMatt Joras EVENTHANDLER_LIST_DEFINE(thread_dtor);
1512ca45184SMatt Joras EVENTHANDLER_LIST_DEFINE(thread_init);
1522ca45184SMatt Joras EVENTHANDLER_LIST_DEFINE(thread_fini);
1532ca45184SMatt Joras 
154ec6ea5e8SDavid Xu static lwpid_t
155ec6ea5e8SDavid Xu tid_alloc(void)
156ec6ea5e8SDavid Xu {
157ec6ea5e8SDavid Xu 	lwpid_t	tid;
158ec6ea5e8SDavid Xu 
159ec6ea5e8SDavid Xu 	tid = alloc_unr(tid_unrhdr);
160ec6ea5e8SDavid Xu 	if (tid != -1)
161ec6ea5e8SDavid Xu 		return (tid);
162ec6ea5e8SDavid Xu 	mtx_lock(&tid_lock);
163ec6ea5e8SDavid Xu 	if (tid_head == tid_tail) {
164ec6ea5e8SDavid Xu 		mtx_unlock(&tid_lock);
165ec6ea5e8SDavid Xu 		return (-1);
166ec6ea5e8SDavid Xu 	}
16794cb3545SKonstantin Belousov 	tid = tid_buffer[tid_head];
16894cb3545SKonstantin Belousov 	tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
169ec6ea5e8SDavid Xu 	mtx_unlock(&tid_lock);
170ec6ea5e8SDavid Xu 	return (tid);
171ec6ea5e8SDavid Xu }
172ec6ea5e8SDavid Xu 
173ec6ea5e8SDavid Xu static void
174ec6ea5e8SDavid Xu tid_free(lwpid_t tid)
175ec6ea5e8SDavid Xu {
176ec6ea5e8SDavid Xu 	lwpid_t tmp_tid = -1;
177ec6ea5e8SDavid Xu 
178ec6ea5e8SDavid Xu 	mtx_lock(&tid_lock);
179ec6ea5e8SDavid Xu 	if ((tid_tail + 1) % TID_BUFFER_SIZE == tid_head) {
18094cb3545SKonstantin Belousov 		tmp_tid = tid_buffer[tid_head];
18194cb3545SKonstantin Belousov 		tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
182ec6ea5e8SDavid Xu 	}
18394cb3545SKonstantin Belousov 	tid_buffer[tid_tail] = tid;
18494cb3545SKonstantin Belousov 	tid_tail = (tid_tail + 1) % TID_BUFFER_SIZE;
185ec6ea5e8SDavid Xu 	mtx_unlock(&tid_lock);
186ec6ea5e8SDavid Xu 	if (tmp_tid != -1)
187ec6ea5e8SDavid Xu 		free_unr(tid_unrhdr, tmp_tid);
188ec6ea5e8SDavid Xu }
189ec6ea5e8SDavid Xu 
190fdcac928SMarcel Moolenaar /*
191696058c3SJulian Elischer  * Prepare a thread for use.
19244990b8cSJulian Elischer  */
193b23f72e9SBrian Feldman static int
194b23f72e9SBrian Feldman thread_ctor(void *mem, int size, void *arg, int flags)
19544990b8cSJulian Elischer {
19644990b8cSJulian Elischer 	struct thread	*td;
19744990b8cSJulian Elischer 
19844990b8cSJulian Elischer 	td = (struct thread *)mem;
19971fad9fdSJulian Elischer 	td->td_state = TDS_INACTIVE;
20094dd54b9SKonstantin Belousov 	td->td_lastcpu = td->td_oncpu = NOCPU;
2016c27c603SJuli Mallett 
202ec6ea5e8SDavid Xu 	td->td_tid = tid_alloc();
203773eff9dSPoul-Henning Kamp 
2046c27c603SJuli Mallett 	/*
2056c27c603SJuli Mallett 	 * Note that td_critnest begins life as 1 because the thread is not
2066c27c603SJuli Mallett 	 * running and is thereby implicitly waiting to be on the receiving
207a54e85fdSJeff Roberson 	 * end of a context switch.
2086c27c603SJuli Mallett 	 */
209139b7550SJohn Baldwin 	td->td_critnest = 1;
210acbe332aSDavid Xu 	td->td_lend_user_pri = PRI_MAX;
2112ca45184SMatt Joras 	EVENTHANDLER_DIRECT_INVOKE(thread_ctor, td);
212911b84b0SRobert Watson #ifdef AUDIT
213911b84b0SRobert Watson 	audit_thread_alloc(td);
214911b84b0SRobert Watson #endif
215d10183d9SDavid Xu 	umtx_thread_alloc(td);
216b23f72e9SBrian Feldman 	return (0);
21744990b8cSJulian Elischer }
21844990b8cSJulian Elischer 
21944990b8cSJulian Elischer /*
22044990b8cSJulian Elischer  * Reclaim a thread after use.
22144990b8cSJulian Elischer  */
22244990b8cSJulian Elischer static void
22344990b8cSJulian Elischer thread_dtor(void *mem, int size, void *arg)
22444990b8cSJulian Elischer {
22544990b8cSJulian Elischer 	struct thread *td;
22644990b8cSJulian Elischer 
22744990b8cSJulian Elischer 	td = (struct thread *)mem;
22844990b8cSJulian Elischer 
22944990b8cSJulian Elischer #ifdef INVARIANTS
23044990b8cSJulian Elischer 	/* Verify that this thread is in a safe state to free. */
23144990b8cSJulian Elischer 	switch (td->td_state) {
23271fad9fdSJulian Elischer 	case TDS_INHIBITED:
23371fad9fdSJulian Elischer 	case TDS_RUNNING:
23471fad9fdSJulian Elischer 	case TDS_CAN_RUN:
23544990b8cSJulian Elischer 	case TDS_RUNQ:
23644990b8cSJulian Elischer 		/*
23744990b8cSJulian Elischer 		 * We must never unlink a thread that is in one of
23844990b8cSJulian Elischer 		 * these states, because it is currently active.
23944990b8cSJulian Elischer 		 */
24044990b8cSJulian Elischer 		panic("bad state for thread unlinking");
24144990b8cSJulian Elischer 		/* NOTREACHED */
24271fad9fdSJulian Elischer 	case TDS_INACTIVE:
24344990b8cSJulian Elischer 		break;
24444990b8cSJulian Elischer 	default:
24544990b8cSJulian Elischer 		panic("bad thread state");
24644990b8cSJulian Elischer 		/* NOTREACHED */
24744990b8cSJulian Elischer 	}
24844990b8cSJulian Elischer #endif
2496e8525ceSRobert Watson #ifdef AUDIT
2506e8525ceSRobert Watson 	audit_thread_free(td);
2516e8525ceSRobert Watson #endif
2521ba4a712SPawel Jakub Dawidek 	/* Free all OSD associated to this thread. */
2531ba4a712SPawel Jakub Dawidek 	osd_thread_exit(td);
254aca4bb91SKonstantin Belousov 	td_softdep_cleanup(td);
255aca4bb91SKonstantin Belousov 	MPASS(td->td_su == NULL);
2561ba4a712SPawel Jakub Dawidek 
2572ca45184SMatt Joras 	EVENTHANDLER_DIRECT_INVOKE(thread_dtor, td);
258ec6ea5e8SDavid Xu 	tid_free(td->td_tid);
25944990b8cSJulian Elischer }
26044990b8cSJulian Elischer 
26144990b8cSJulian Elischer /*
26244990b8cSJulian Elischer  * Initialize type-stable parts of a thread (when newly created).
26344990b8cSJulian Elischer  */
264b23f72e9SBrian Feldman static int
265b23f72e9SBrian Feldman thread_init(void *mem, int size, int flags)
26644990b8cSJulian Elischer {
26744990b8cSJulian Elischer 	struct thread *td;
26844990b8cSJulian Elischer 
26944990b8cSJulian Elischer 	td = (struct thread *)mem;
270247aba24SMarcel Moolenaar 
27144f3b092SJohn Baldwin 	td->td_sleepqueue = sleepq_alloc();
272961a7b24SJohn Baldwin 	td->td_turnstile = turnstile_alloc();
2738f0e9130SKonstantin Belousov 	td->td_rlqe = NULL;
2742ca45184SMatt Joras 	EVENTHANDLER_DIRECT_INVOKE(thread_init, td);
275d10183d9SDavid Xu 	umtx_thread_init(td);
276b79aa45eSGleb Smirnoff 	epoch_thread_init(td);
27789b57fcfSKonstantin Belousov 	td->td_kstack = 0;
278ad8b1d85SKonstantin Belousov 	td->td_sel = NULL;
279b23f72e9SBrian Feldman 	return (0);
28044990b8cSJulian Elischer }
28144990b8cSJulian Elischer 
28244990b8cSJulian Elischer /*
28344990b8cSJulian Elischer  * Tear down type-stable parts of a thread (just before being discarded).
28444990b8cSJulian Elischer  */
28544990b8cSJulian Elischer static void
28644990b8cSJulian Elischer thread_fini(void *mem, int size)
28744990b8cSJulian Elischer {
28844990b8cSJulian Elischer 	struct thread *td;
28944990b8cSJulian Elischer 
29044990b8cSJulian Elischer 	td = (struct thread *)mem;
2912ca45184SMatt Joras 	EVENTHANDLER_DIRECT_INVOKE(thread_fini, td);
2928f0e9130SKonstantin Belousov 	rlqentry_free(td->td_rlqe);
293961a7b24SJohn Baldwin 	turnstile_free(td->td_turnstile);
29444f3b092SJohn Baldwin 	sleepq_free(td->td_sleepqueue);
295d10183d9SDavid Xu 	umtx_thread_fini(td);
296b79aa45eSGleb Smirnoff 	epoch_thread_fini(td);
297ace8398dSJeff Roberson 	seltdfini(td);
29844990b8cSJulian Elischer }
2995215b187SJeff Roberson 
3005c8329edSJulian Elischer /*
3015215b187SJeff Roberson  * For a newly created process,
3025215b187SJeff Roberson  * link up all the structures and its initial threads etc.
303ed062c8dSJulian Elischer  * called from:
304e7d939bdSMarcel Moolenaar  * {arch}/{arch}/machdep.c   {arch}_init(), init386() etc.
305ed062c8dSJulian Elischer  * proc_dtor() (should go away)
306ed062c8dSJulian Elischer  * proc_init()
3075c8329edSJulian Elischer  */
3085c8329edSJulian Elischer void
30989b57fcfSKonstantin Belousov proc_linkup0(struct proc *p, struct thread *td)
31089b57fcfSKonstantin Belousov {
31189b57fcfSKonstantin Belousov 	TAILQ_INIT(&p->p_threads);	     /* all threads in proc */
31289b57fcfSKonstantin Belousov 	proc_linkup(p, td);
31389b57fcfSKonstantin Belousov }
31489b57fcfSKonstantin Belousov 
31589b57fcfSKonstantin Belousov void
3168460a577SJohn Birrell proc_linkup(struct proc *p, struct thread *td)
3175c8329edSJulian Elischer {
318a54e85fdSJeff Roberson 
3199104847fSDavid Xu 	sigqueue_init(&p->p_sigqueue, p);
320ebceaf6dSDavid Xu 	p->p_ksi = ksiginfo_alloc(1);
321ebceaf6dSDavid Xu 	if (p->p_ksi != NULL) {
3225c474517SDavid Xu 		/* XXX p_ksi may be null if ksiginfo zone is not ready */
323ebceaf6dSDavid Xu 		p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
324ebceaf6dSDavid Xu 	}
325b2f92ef9SDavid Xu 	LIST_INIT(&p->p_mqnotifier);
3265c8329edSJulian Elischer 	p->p_numthreads = 0;
3278460a577SJohn Birrell 	thread_link(td, p);
3285c8329edSJulian Elischer }
3295c8329edSJulian Elischer 
3305c8329edSJulian Elischer /*
33144990b8cSJulian Elischer  * Initialize global thread allocation resources.
33244990b8cSJulian Elischer  */
33344990b8cSJulian Elischer void
33444990b8cSJulian Elischer threadinit(void)
33544990b8cSJulian Elischer {
33644990b8cSJulian Elischer 
3371ea7a6f8SPoul-Henning Kamp 	mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
33802c6fc21SKonstantin Belousov 
33902c6fc21SKonstantin Belousov 	/*
340abce621cSKonstantin Belousov 	 * pid_max cannot be greater than PID_MAX.
34102c6fc21SKonstantin Belousov 	 * leave one number for thread0.
34202c6fc21SKonstantin Belousov 	 */
3436829a5c5SJulian Elischer 	tid_unrhdr = new_unrhdr(PID_MAX + 2, INT_MAX, &tid_lock);
3441ea7a6f8SPoul-Henning Kamp 
345de028f5aSJeff Roberson 	thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
34644990b8cSJulian Elischer 	    thread_ctor, thread_dtor, thread_init, thread_fini,
347f743ea96SMateusz Guzik 	    32 - 1, UMA_ZONE_NOFREE);
348cf7d9a8cSDavid Xu 	tidhashtbl = hashinit(maxproc / 2, M_TIDHASH, &tidhash);
349cf7d9a8cSDavid Xu 	rw_init(&tidhash_lock, "tidhash");
35044990b8cSJulian Elischer }
35144990b8cSJulian Elischer 
35244990b8cSJulian Elischer /*
353ff8fbcffSJeff Roberson  * Place an unused thread on the zombie list.
354ad1e7d28SJulian Elischer  * Use the slpq as that must be unused by now.
35544990b8cSJulian Elischer  */
35644990b8cSJulian Elischer void
357ff8fbcffSJeff Roberson thread_zombie(struct thread *td)
35844990b8cSJulian Elischer {
359a54e85fdSJeff Roberson 	mtx_lock_spin(&zombie_lock);
360ad1e7d28SJulian Elischer 	TAILQ_INSERT_HEAD(&zombie_threads, td, td_slpq);
361a54e85fdSJeff Roberson 	mtx_unlock_spin(&zombie_lock);
36244990b8cSJulian Elischer }
36344990b8cSJulian Elischer 
3645c8329edSJulian Elischer /*
365ff8fbcffSJeff Roberson  * Release a thread that has exited after cpu_throw().
366ff8fbcffSJeff Roberson  */
367ff8fbcffSJeff Roberson void
368ff8fbcffSJeff Roberson thread_stash(struct thread *td)
369ff8fbcffSJeff Roberson {
370ff8fbcffSJeff Roberson 	atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
371ff8fbcffSJeff Roberson 	thread_zombie(td);
372ff8fbcffSJeff Roberson }
373ff8fbcffSJeff Roberson 
374ff8fbcffSJeff Roberson /*
3756617724cSJeff Roberson  * Reap zombie resources.
37644990b8cSJulian Elischer  */
37744990b8cSJulian Elischer void
37844990b8cSJulian Elischer thread_reap(void)
37944990b8cSJulian Elischer {
3805c8329edSJulian Elischer 	struct thread *td_first, *td_next;
38144990b8cSJulian Elischer 
38244990b8cSJulian Elischer 	/*
3835215b187SJeff Roberson 	 * Don't even bother to lock if none at this instant,
3842d19b736SKonstantin Belousov 	 * we really don't care about the next instant.
38544990b8cSJulian Elischer 	 */
3868460a577SJohn Birrell 	if (!TAILQ_EMPTY(&zombie_threads)) {
387a54e85fdSJeff Roberson 		mtx_lock_spin(&zombie_lock);
3885c8329edSJulian Elischer 		td_first = TAILQ_FIRST(&zombie_threads);
3895c8329edSJulian Elischer 		if (td_first)
3905c8329edSJulian Elischer 			TAILQ_INIT(&zombie_threads);
391a54e85fdSJeff Roberson 		mtx_unlock_spin(&zombie_lock);
3925c8329edSJulian Elischer 		while (td_first) {
393ad1e7d28SJulian Elischer 			td_next = TAILQ_NEXT(td_first, td_slpq);
3944ea6a9a2SMateusz Guzik 			thread_cow_free(td_first);
3955c8329edSJulian Elischer 			thread_free(td_first);
3965c8329edSJulian Elischer 			td_first = td_next;
39744990b8cSJulian Elischer 		}
39844990b8cSJulian Elischer 	}
399ed062c8dSJulian Elischer }
40044990b8cSJulian Elischer 
4014f0db5e0SJulian Elischer /*
40244990b8cSJulian Elischer  * Allocate a thread.
40344990b8cSJulian Elischer  */
40444990b8cSJulian Elischer struct thread *
4058a945d10SKonstantin Belousov thread_alloc(int pages)
40644990b8cSJulian Elischer {
40789b57fcfSKonstantin Belousov 	struct thread *td;
4088460a577SJohn Birrell 
40944990b8cSJulian Elischer 	thread_reap(); /* check if any zombies to get */
41089b57fcfSKonstantin Belousov 
41189b57fcfSKonstantin Belousov 	td = (struct thread *)uma_zalloc(thread_zone, M_WAITOK);
41289b57fcfSKonstantin Belousov 	KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
4138a945d10SKonstantin Belousov 	if (!vm_thread_new(td, pages)) {
41489b57fcfSKonstantin Belousov 		uma_zfree(thread_zone, td);
41589b57fcfSKonstantin Belousov 		return (NULL);
41689b57fcfSKonstantin Belousov 	}
4170c3967e7SMarcel Moolenaar 	cpu_thread_alloc(td);
41889b57fcfSKonstantin Belousov 	return (td);
41944990b8cSJulian Elischer }
42044990b8cSJulian Elischer 
4218a945d10SKonstantin Belousov int
4228a945d10SKonstantin Belousov thread_alloc_stack(struct thread *td, int pages)
4238a945d10SKonstantin Belousov {
4248a945d10SKonstantin Belousov 
4258a945d10SKonstantin Belousov 	KASSERT(td->td_kstack == 0,
4268a945d10SKonstantin Belousov 	    ("thread_alloc_stack called on a thread with kstack"));
4278a945d10SKonstantin Belousov 	if (!vm_thread_new(td, pages))
4288a945d10SKonstantin Belousov 		return (0);
4298a945d10SKonstantin Belousov 	cpu_thread_alloc(td);
4308a945d10SKonstantin Belousov 	return (1);
4318a945d10SKonstantin Belousov }
4324f0db5e0SJulian Elischer 
4334f0db5e0SJulian Elischer /*
43444990b8cSJulian Elischer  * Deallocate a thread.
43544990b8cSJulian Elischer  */
43644990b8cSJulian Elischer void
43744990b8cSJulian Elischer thread_free(struct thread *td)
43844990b8cSJulian Elischer {
4392e6b8de4SJeff Roberson 
4402e6b8de4SJeff Roberson 	lock_profile_thread_exit(td);
44145aea8deSJeff Roberson 	if (td->td_cpuset)
442d7f687fcSJeff Roberson 		cpuset_rel(td->td_cpuset);
443d7f687fcSJeff Roberson 	td->td_cpuset = NULL;
4440c3967e7SMarcel Moolenaar 	cpu_thread_free(td);
44589b57fcfSKonstantin Belousov 	if (td->td_kstack != 0)
44689b57fcfSKonstantin Belousov 		vm_thread_dispose(td);
4472d19b736SKonstantin Belousov 	callout_drain(&td->td_slpcallout);
44844990b8cSJulian Elischer 	uma_zfree(thread_zone, td);
44944990b8cSJulian Elischer }
45044990b8cSJulian Elischer 
4514ea6a9a2SMateusz Guzik void
4524ea6a9a2SMateusz Guzik thread_cow_get_proc(struct thread *newtd, struct proc *p)
4534ea6a9a2SMateusz Guzik {
4544ea6a9a2SMateusz Guzik 
4554ea6a9a2SMateusz Guzik 	PROC_LOCK_ASSERT(p, MA_OWNED);
4564ea6a9a2SMateusz Guzik 	newtd->td_ucred = crhold(p->p_ucred);
457f6f6d240SMateusz Guzik 	newtd->td_limit = lim_hold(p->p_limit);
4584ea6a9a2SMateusz Guzik 	newtd->td_cowgen = p->p_cowgen;
4594ea6a9a2SMateusz Guzik }
4604ea6a9a2SMateusz Guzik 
4614ea6a9a2SMateusz Guzik void
4624ea6a9a2SMateusz Guzik thread_cow_get(struct thread *newtd, struct thread *td)
4634ea6a9a2SMateusz Guzik {
4644ea6a9a2SMateusz Guzik 
4654ea6a9a2SMateusz Guzik 	newtd->td_ucred = crhold(td->td_ucred);
466f6f6d240SMateusz Guzik 	newtd->td_limit = lim_hold(td->td_limit);
4674ea6a9a2SMateusz Guzik 	newtd->td_cowgen = td->td_cowgen;
4684ea6a9a2SMateusz Guzik }
4694ea6a9a2SMateusz Guzik 
4704ea6a9a2SMateusz Guzik void
4714ea6a9a2SMateusz Guzik thread_cow_free(struct thread *td)
4724ea6a9a2SMateusz Guzik {
4734ea6a9a2SMateusz Guzik 
474cd672ca6SMateusz Guzik 	if (td->td_ucred != NULL)
4754ea6a9a2SMateusz Guzik 		crfree(td->td_ucred);
476cd672ca6SMateusz Guzik 	if (td->td_limit != NULL)
477f6f6d240SMateusz Guzik 		lim_free(td->td_limit);
4784ea6a9a2SMateusz Guzik }
4794ea6a9a2SMateusz Guzik 
4804ea6a9a2SMateusz Guzik void
4814ea6a9a2SMateusz Guzik thread_cow_update(struct thread *td)
4824ea6a9a2SMateusz Guzik {
4834ea6a9a2SMateusz Guzik 	struct proc *p;
484cd672ca6SMateusz Guzik 	struct ucred *oldcred;
485cd672ca6SMateusz Guzik 	struct plimit *oldlimit;
4864ea6a9a2SMateusz Guzik 
4874ea6a9a2SMateusz Guzik 	p = td->td_proc;
488cd672ca6SMateusz Guzik 	oldcred = NULL;
489cd672ca6SMateusz Guzik 	oldlimit = NULL;
4904ea6a9a2SMateusz Guzik 	PROC_LOCK(p);
491cd672ca6SMateusz Guzik 	if (td->td_ucred != p->p_ucred) {
492cd672ca6SMateusz Guzik 		oldcred = td->td_ucred;
493cd672ca6SMateusz Guzik 		td->td_ucred = crhold(p->p_ucred);
494cd672ca6SMateusz Guzik 	}
495cd672ca6SMateusz Guzik 	if (td->td_limit != p->p_limit) {
496cd672ca6SMateusz Guzik 		oldlimit = td->td_limit;
497cd672ca6SMateusz Guzik 		td->td_limit = lim_hold(p->p_limit);
498cd672ca6SMateusz Guzik 	}
4994ea6a9a2SMateusz Guzik 	td->td_cowgen = p->p_cowgen;
5004ea6a9a2SMateusz Guzik 	PROC_UNLOCK(p);
501cd672ca6SMateusz Guzik 	if (oldcred != NULL)
502cd672ca6SMateusz Guzik 		crfree(oldcred);
503cd672ca6SMateusz Guzik 	if (oldlimit != NULL)
504cd672ca6SMateusz Guzik 		lim_free(oldlimit);
5054ea6a9a2SMateusz Guzik }
5064ea6a9a2SMateusz Guzik 
50744990b8cSJulian Elischer /*
50844990b8cSJulian Elischer  * Discard the current thread and exit from its context.
50994e0a4cdSJulian Elischer  * Always called with scheduler locked.
51044990b8cSJulian Elischer  *
51144990b8cSJulian Elischer  * Because we can't free a thread while we're operating under its context,
512696058c3SJulian Elischer  * push the current thread into our CPU's deadthread holder. This means
513696058c3SJulian Elischer  * we needn't worry about someone else grabbing our context before we
5146617724cSJeff Roberson  * do a cpu_throw().
51544990b8cSJulian Elischer  */
51644990b8cSJulian Elischer void
51744990b8cSJulian Elischer thread_exit(void)
51844990b8cSJulian Elischer {
5197e3a96eaSJohn Baldwin 	uint64_t runtime, new_switchtime;
52044990b8cSJulian Elischer 	struct thread *td;
5211c4bcd05SJeff Roberson 	struct thread *td2;
52244990b8cSJulian Elischer 	struct proc *p;
5237847a9daSJohn Baldwin 	int wakeup_swapper;
52444990b8cSJulian Elischer 
52544990b8cSJulian Elischer 	td = curthread;
52644990b8cSJulian Elischer 	p = td->td_proc;
52744990b8cSJulian Elischer 
528a54e85fdSJeff Roberson 	PROC_SLOCK_ASSERT(p, MA_OWNED);
529ed062c8dSJulian Elischer 	mtx_assert(&Giant, MA_NOTOWNED);
530a54e85fdSJeff Roberson 
53144990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
532ed062c8dSJulian Elischer 	KASSERT(p != NULL, ("thread exiting without a process"));
533cc701b73SRobert Watson 	CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
534e01eafefSJulian Elischer 	    (long)p->p_pid, td->td_name);
5356c9271a9SAndriy Gapon 	SDT_PROBE0(proc, , , lwp__exit);
5369104847fSDavid Xu 	KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
53744990b8cSJulian Elischer 
538ed062c8dSJulian Elischer 	/*
539ed062c8dSJulian Elischer 	 * drop FPU & debug register state storage, or any other
540ed062c8dSJulian Elischer 	 * architecture specific resources that
541ed062c8dSJulian Elischer 	 * would not be on a new untouched process.
542ed062c8dSJulian Elischer 	 */
543bd07998eSKonstantin Belousov 	cpu_thread_exit(td);
54444990b8cSJulian Elischer 
545ed062c8dSJulian Elischer 	/*
5461faf202eSJulian Elischer 	 * The last thread is left attached to the process
5471faf202eSJulian Elischer 	 * So that the whole bundle gets recycled. Skip
548ed062c8dSJulian Elischer 	 * all this stuff if we never had threads.
549ed062c8dSJulian Elischer 	 * EXIT clears all sign of other threads when
550ed062c8dSJulian Elischer 	 * it goes to single threading, so the last thread always
551ed062c8dSJulian Elischer 	 * takes the short path.
5521faf202eSJulian Elischer 	 */
553ed062c8dSJulian Elischer 	if (p->p_flag & P_HADTHREADS) {
5541faf202eSJulian Elischer 		if (p->p_numthreads > 1) {
555fd229b5bSKonstantin Belousov 			atomic_add_int(&td->td_proc->p_exitthreads, 1);
556d3a0bd78SJulian Elischer 			thread_unlink(td);
5571c4bcd05SJeff Roberson 			td2 = FIRST_THREAD_IN_PROC(p);
5581c4bcd05SJeff Roberson 			sched_exit_thread(td2, td);
559ed062c8dSJulian Elischer 
560ed062c8dSJulian Elischer 			/*
56144990b8cSJulian Elischer 			 * The test below is NOT true if we are the
5629182554aSKonstantin Belousov 			 * sole exiting thread. P_STOPPED_SINGLE is unset
56344990b8cSJulian Elischer 			 * in exit1() after it is the only survivor.
56444990b8cSJulian Elischer 			 */
5651279572aSDavid Xu 			if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
56644990b8cSJulian Elischer 				if (p->p_numthreads == p->p_suspcount) {
567a54e85fdSJeff Roberson 					thread_lock(p->p_singlethread);
5687847a9daSJohn Baldwin 					wakeup_swapper = thread_unsuspend_one(
56984cdea97SKonstantin Belousov 						p->p_singlethread, p, false);
570a54e85fdSJeff Roberson 					thread_unlock(p->p_singlethread);
5717847a9daSJohn Baldwin 					if (wakeup_swapper)
5727847a9daSJohn Baldwin 						kick_proc0();
57344990b8cSJulian Elischer 				}
57444990b8cSJulian Elischer 			}
57548bfcdddSJulian Elischer 
576696058c3SJulian Elischer 			PCPU_SET(deadthread, td);
5771faf202eSJulian Elischer 		} else {
578ed062c8dSJulian Elischer 			/*
579ed062c8dSJulian Elischer 			 * The last thread is exiting.. but not through exit()
580ed062c8dSJulian Elischer 			 */
581ed062c8dSJulian Elischer 			panic ("thread_exit: Last thread exiting on its own");
582ed062c8dSJulian Elischer 		}
5831faf202eSJulian Elischer 	}
58416d95d4fSJoseph Koshy #ifdef	HWPMC_HOOKS
58516d95d4fSJoseph Koshy 	/*
58616d95d4fSJoseph Koshy 	 * If this thread is part of a process that is being tracked by hwpmc(4),
58716d95d4fSJoseph Koshy 	 * inform the module of the thread's impending exit.
58816d95d4fSJoseph Koshy 	 */
5896161b98cSMatt Macy 	if (PMC_PROC_IS_USING_PMCS(td->td_proc)) {
59016d95d4fSJoseph Koshy 		PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
5916161b98cSMatt Macy 		PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT, NULL);
592ebfaf69cSMatt Macy 	} else if (PMC_SYSTEM_SAMPLING_ACTIVE())
593ebfaf69cSMatt Macy 		PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT_LOG, NULL);
59416d95d4fSJoseph Koshy #endif
595a54e85fdSJeff Roberson 	PROC_UNLOCK(p);
5965c7bebf9SKonstantin Belousov 	PROC_STATLOCK(p);
5975c7bebf9SKonstantin Belousov 	thread_lock(td);
5985c7bebf9SKonstantin Belousov 	PROC_SUNLOCK(p);
5997e3a96eaSJohn Baldwin 
6007e3a96eaSJohn Baldwin 	/* Do the same timestamp bookkeeping that mi_switch() would do. */
6017e3a96eaSJohn Baldwin 	new_switchtime = cpu_ticks();
6027e3a96eaSJohn Baldwin 	runtime = new_switchtime - PCPU_GET(switchtime);
6037e3a96eaSJohn Baldwin 	td->td_runtime += runtime;
6047e3a96eaSJohn Baldwin 	td->td_incruntime += runtime;
6057e3a96eaSJohn Baldwin 	PCPU_SET(switchtime, new_switchtime);
6067e3a96eaSJohn Baldwin 	PCPU_SET(switchticks, ticks);
60783c9dea1SGleb Smirnoff 	VM_CNT_INC(v_swtch);
6087e3a96eaSJohn Baldwin 
6097e3a96eaSJohn Baldwin 	/* Save our resource usage in our process. */
6107e3a96eaSJohn Baldwin 	td->td_ru.ru_nvcsw++;
61141fd9c63SKonstantin Belousov 	ruxagg(p, td);
6127e3a96eaSJohn Baldwin 	rucollect(&p->p_ru, &td->td_ru);
6135c7bebf9SKonstantin Belousov 	PROC_STATUNLOCK(p);
6147e3a96eaSJohn Baldwin 
615dcc9954eSJulian Elischer 	td->td_state = TDS_INACTIVE;
6163d06b4b3SAttilio Rao #ifdef WITNESS
6173d06b4b3SAttilio Rao 	witness_thread_exit(td);
6183d06b4b3SAttilio Rao #endif
619732d9528SJulian Elischer 	CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
620a54e85fdSJeff Roberson 	sched_throw(td);
621cc66ebe2SPeter Wemm 	panic("I'm a teapot!");
62244990b8cSJulian Elischer 	/* NOTREACHED */
62344990b8cSJulian Elischer }
62444990b8cSJulian Elischer 
62544990b8cSJulian Elischer /*
626696058c3SJulian Elischer  * Do any thread specific cleanups that may be needed in wait()
62737814395SPeter Wemm  * called with Giant, proc and schedlock not held.
628696058c3SJulian Elischer  */
629696058c3SJulian Elischer void
630696058c3SJulian Elischer thread_wait(struct proc *p)
631696058c3SJulian Elischer {
632696058c3SJulian Elischer 	struct thread *td;
633696058c3SJulian Elischer 
63437814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
635624bf9e1SKonstantin Belousov 	KASSERT(p->p_numthreads == 1, ("multiple threads in thread_wait()"));
636624bf9e1SKonstantin Belousov 	KASSERT(p->p_exitthreads == 0, ("p_exitthreads leaking"));
637ff8fbcffSJeff Roberson 	td = FIRST_THREAD_IN_PROC(p);
638ff8fbcffSJeff Roberson 	/* Lock the last thread so we spin until it exits cpu_throw(). */
639ff8fbcffSJeff Roberson 	thread_lock(td);
640ff8fbcffSJeff Roberson 	thread_unlock(td);
6412e6b8de4SJeff Roberson 	lock_profile_thread_exit(td);
642d7f687fcSJeff Roberson 	cpuset_rel(td->td_cpuset);
643d7f687fcSJeff Roberson 	td->td_cpuset = NULL;
644696058c3SJulian Elischer 	cpu_thread_clean(td);
6454ea6a9a2SMateusz Guzik 	thread_cow_free(td);
6462d19b736SKonstantin Belousov 	callout_drain(&td->td_slpcallout);
647696058c3SJulian Elischer 	thread_reap();	/* check for zombie threads etc. */
648696058c3SJulian Elischer }
649696058c3SJulian Elischer 
650696058c3SJulian Elischer /*
65144990b8cSJulian Elischer  * Link a thread to a process.
6521faf202eSJulian Elischer  * set up anything that needs to be initialized for it to
6531faf202eSJulian Elischer  * be used by the process.
65444990b8cSJulian Elischer  */
65544990b8cSJulian Elischer void
6568460a577SJohn Birrell thread_link(struct thread *td, struct proc *p)
65744990b8cSJulian Elischer {
65844990b8cSJulian Elischer 
659a54e85fdSJeff Roberson 	/*
660a54e85fdSJeff Roberson 	 * XXX This can't be enabled because it's called for proc0 before
661374ae2a3SJeff Roberson 	 * its lock has been created.
662374ae2a3SJeff Roberson 	 * PROC_LOCK_ASSERT(p, MA_OWNED);
663a54e85fdSJeff Roberson 	 */
66471fad9fdSJulian Elischer 	td->td_state    = TDS_INACTIVE;
66544990b8cSJulian Elischer 	td->td_proc     = p;
666b61ce5b0SJeff Roberson 	td->td_flags    = TDF_INMEM;
66744990b8cSJulian Elischer 
6681faf202eSJulian Elischer 	LIST_INIT(&td->td_contested);
669eea4f254SJeff Roberson 	LIST_INIT(&td->td_lprof[0]);
670eea4f254SJeff Roberson 	LIST_INIT(&td->td_lprof[1]);
671*f6eccf96SGleb Smirnoff #ifdef EPOCH_TRACE
672dd902d01SGleb Smirnoff 	SLIST_INIT(&td->td_epochs);
673*f6eccf96SGleb Smirnoff #endif
6749104847fSDavid Xu 	sigqueue_init(&td->td_sigqueue, p);
675fd90e2edSJung-uk Kim 	callout_init(&td->td_slpcallout, 1);
67666d8df9dSDaniel Eischen 	TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
67744990b8cSJulian Elischer 	p->p_numthreads++;
67844990b8cSJulian Elischer }
67944990b8cSJulian Elischer 
680ed062c8dSJulian Elischer /*
681ed062c8dSJulian Elischer  * Called from:
682ed062c8dSJulian Elischer  *  thread_exit()
683ed062c8dSJulian Elischer  */
684d3a0bd78SJulian Elischer void
685d3a0bd78SJulian Elischer thread_unlink(struct thread *td)
686d3a0bd78SJulian Elischer {
687d3a0bd78SJulian Elischer 	struct proc *p = td->td_proc;
688d3a0bd78SJulian Elischer 
689374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
690*f6eccf96SGleb Smirnoff #ifdef EPOCH_TRACE
691dd902d01SGleb Smirnoff 	MPASS(SLIST_EMPTY(&td->td_epochs));
692*f6eccf96SGleb Smirnoff #endif
693dd902d01SGleb Smirnoff 
694d3a0bd78SJulian Elischer 	TAILQ_REMOVE(&p->p_threads, td, td_plist);
695d3a0bd78SJulian Elischer 	p->p_numthreads--;
696d3a0bd78SJulian Elischer 	/* could clear a few other things here */
6978460a577SJohn Birrell 	/* Must  NOT clear links to proc! */
6985c8329edSJulian Elischer }
6995c8329edSJulian Elischer 
70079799053SKonstantin Belousov static int
70179799053SKonstantin Belousov calc_remaining(struct proc *p, int mode)
70279799053SKonstantin Belousov {
70379799053SKonstantin Belousov 	int remaining;
70479799053SKonstantin Belousov 
7057b519077SKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
7067b519077SKonstantin Belousov 	PROC_SLOCK_ASSERT(p, MA_OWNED);
70779799053SKonstantin Belousov 	if (mode == SINGLE_EXIT)
70879799053SKonstantin Belousov 		remaining = p->p_numthreads;
70979799053SKonstantin Belousov 	else if (mode == SINGLE_BOUNDARY)
71079799053SKonstantin Belousov 		remaining = p->p_numthreads - p->p_boundary_count;
7116ddcc233SKonstantin Belousov 	else if (mode == SINGLE_NO_EXIT || mode == SINGLE_ALLPROC)
71279799053SKonstantin Belousov 		remaining = p->p_numthreads - p->p_suspcount;
71379799053SKonstantin Belousov 	else
71479799053SKonstantin Belousov 		panic("calc_remaining: wrong mode %d", mode);
71579799053SKonstantin Belousov 	return (remaining);
71679799053SKonstantin Belousov }
71779799053SKonstantin Belousov 
71807a9368aSKonstantin Belousov static int
71907a9368aSKonstantin Belousov remain_for_mode(int mode)
72007a9368aSKonstantin Belousov {
72107a9368aSKonstantin Belousov 
7226ddcc233SKonstantin Belousov 	return (mode == SINGLE_ALLPROC ? 0 : 1);
72307a9368aSKonstantin Belousov }
72407a9368aSKonstantin Belousov 
72507a9368aSKonstantin Belousov static int
72607a9368aSKonstantin Belousov weed_inhib(int mode, struct thread *td2, struct proc *p)
72707a9368aSKonstantin Belousov {
72807a9368aSKonstantin Belousov 	int wakeup_swapper;
72907a9368aSKonstantin Belousov 
73007a9368aSKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
73107a9368aSKonstantin Belousov 	PROC_SLOCK_ASSERT(p, MA_OWNED);
73207a9368aSKonstantin Belousov 	THREAD_LOCK_ASSERT(td2, MA_OWNED);
73307a9368aSKonstantin Belousov 
73407a9368aSKonstantin Belousov 	wakeup_swapper = 0;
73507a9368aSKonstantin Belousov 	switch (mode) {
73607a9368aSKonstantin Belousov 	case SINGLE_EXIT:
73707a9368aSKonstantin Belousov 		if (TD_IS_SUSPENDED(td2))
73884cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, true);
73907a9368aSKonstantin Belousov 		if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0)
74007a9368aSKonstantin Belousov 			wakeup_swapper |= sleepq_abort(td2, EINTR);
74107a9368aSKonstantin Belousov 		break;
74207a9368aSKonstantin Belousov 	case SINGLE_BOUNDARY:
74307a9368aSKonstantin Belousov 	case SINGLE_NO_EXIT:
74407a9368aSKonstantin Belousov 		if (TD_IS_SUSPENDED(td2) && (td2->td_flags & TDF_BOUNDARY) == 0)
74584cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
74607a9368aSKonstantin Belousov 		if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0)
74707a9368aSKonstantin Belousov 			wakeup_swapper |= sleepq_abort(td2, ERESTART);
748917dd390SKonstantin Belousov 		break;
7496ddcc233SKonstantin Belousov 	case SINGLE_ALLPROC:
7506ddcc233SKonstantin Belousov 		/*
7516ddcc233SKonstantin Belousov 		 * ALLPROC suspend tries to avoid spurious EINTR for
7526ddcc233SKonstantin Belousov 		 * threads sleeping interruptable, by suspending the
7536ddcc233SKonstantin Belousov 		 * thread directly, similarly to sig_suspend_threads().
7546ddcc233SKonstantin Belousov 		 * Since such sleep is not performed at the user
7556ddcc233SKonstantin Belousov 		 * boundary, TDF_BOUNDARY flag is not set, and TDF_ALLPROCSUSP
7566ddcc233SKonstantin Belousov 		 * is used to avoid immediate un-suspend.
7576ddcc233SKonstantin Belousov 		 */
7586ddcc233SKonstantin Belousov 		if (TD_IS_SUSPENDED(td2) && (td2->td_flags & (TDF_BOUNDARY |
7596ddcc233SKonstantin Belousov 		    TDF_ALLPROCSUSP)) == 0)
76084cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
7616ddcc233SKonstantin Belousov 		if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0) {
7626ddcc233SKonstantin Belousov 			if ((td2->td_flags & TDF_SBDRY) == 0) {
7636ddcc233SKonstantin Belousov 				thread_suspend_one(td2);
7646ddcc233SKonstantin Belousov 				td2->td_flags |= TDF_ALLPROCSUSP;
7656ddcc233SKonstantin Belousov 			} else {
7666ddcc233SKonstantin Belousov 				wakeup_swapper |= sleepq_abort(td2, ERESTART);
7676ddcc233SKonstantin Belousov 			}
7686ddcc233SKonstantin Belousov 		}
76907a9368aSKonstantin Belousov 		break;
77007a9368aSKonstantin Belousov 	}
77107a9368aSKonstantin Belousov 	return (wakeup_swapper);
77207a9368aSKonstantin Belousov }
77307a9368aSKonstantin Belousov 
7745215b187SJeff Roberson /*
77544990b8cSJulian Elischer  * Enforce single-threading.
77644990b8cSJulian Elischer  *
77744990b8cSJulian Elischer  * Returns 1 if the caller must abort (another thread is waiting to
77844990b8cSJulian Elischer  * exit the process or similar). Process is locked!
77944990b8cSJulian Elischer  * Returns 0 when you are successfully the only thread running.
78044990b8cSJulian Elischer  * A process has successfully single threaded in the suspend mode when
78144990b8cSJulian Elischer  * There are no threads in user mode. Threads in the kernel must be
78244990b8cSJulian Elischer  * allowed to continue until they get to the user boundary. They may even
78344990b8cSJulian Elischer  * copy out their return values and data before suspending. They may however be
784e2668f55SMaxim Konovalov  * accelerated in reaching the user boundary as we will wake up
78544990b8cSJulian Elischer  * any sleeping threads that are interruptable. (PCATCH).
78644990b8cSJulian Elischer  */
78744990b8cSJulian Elischer int
7886ddcc233SKonstantin Belousov thread_single(struct proc *p, int mode)
78944990b8cSJulian Elischer {
79044990b8cSJulian Elischer 	struct thread *td;
79144990b8cSJulian Elischer 	struct thread *td2;
792da7bbd2cSJohn Baldwin 	int remaining, wakeup_swapper;
79344990b8cSJulian Elischer 
79444990b8cSJulian Elischer 	td = curthread;
7956ddcc233SKonstantin Belousov 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
7966ddcc233SKonstantin Belousov 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
7976ddcc233SKonstantin Belousov 	    ("invalid mode %d", mode));
7986ddcc233SKonstantin Belousov 	/*
7996ddcc233SKonstantin Belousov 	 * If allowing non-ALLPROC singlethreading for non-curproc
8006ddcc233SKonstantin Belousov 	 * callers, calc_remaining() and remain_for_mode() should be
8016ddcc233SKonstantin Belousov 	 * adjusted to also account for td->td_proc != p.  For now
8026ddcc233SKonstantin Belousov 	 * this is not implemented because it is not used.
8036ddcc233SKonstantin Belousov 	 */
8046ddcc233SKonstantin Belousov 	KASSERT((mode == SINGLE_ALLPROC && td->td_proc != p) ||
8056ddcc233SKonstantin Belousov 	    (mode != SINGLE_ALLPROC && td->td_proc == p),
8066ddcc233SKonstantin Belousov 	    ("mode %d proc %p curproc %p", mode, p, td->td_proc));
80737814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
80844990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
80944990b8cSJulian Elischer 
8106ddcc233SKonstantin Belousov 	if ((p->p_flag & P_HADTHREADS) == 0 && mode != SINGLE_ALLPROC)
81144990b8cSJulian Elischer 		return (0);
81244990b8cSJulian Elischer 
813e3b9bf71SJulian Elischer 	/* Is someone already single threading? */
814906ac69dSDavid Xu 	if (p->p_singlethread != NULL && p->p_singlethread != td)
81544990b8cSJulian Elischer 		return (1);
81644990b8cSJulian Elischer 
817906ac69dSDavid Xu 	if (mode == SINGLE_EXIT) {
818906ac69dSDavid Xu 		p->p_flag |= P_SINGLE_EXIT;
819906ac69dSDavid Xu 		p->p_flag &= ~P_SINGLE_BOUNDARY;
820906ac69dSDavid Xu 	} else {
821906ac69dSDavid Xu 		p->p_flag &= ~P_SINGLE_EXIT;
822906ac69dSDavid Xu 		if (mode == SINGLE_BOUNDARY)
823906ac69dSDavid Xu 			p->p_flag |= P_SINGLE_BOUNDARY;
824906ac69dSDavid Xu 		else
825906ac69dSDavid Xu 			p->p_flag &= ~P_SINGLE_BOUNDARY;
826906ac69dSDavid Xu 	}
8276ddcc233SKonstantin Belousov 	if (mode == SINGLE_ALLPROC)
8286ddcc233SKonstantin Belousov 		p->p_flag |= P_TOTAL_STOP;
8291279572aSDavid Xu 	p->p_flag |= P_STOPPED_SINGLE;
8307b4a950aSDavid Xu 	PROC_SLOCK(p);
831112afcb2SJohn Baldwin 	p->p_singlethread = td;
83279799053SKonstantin Belousov 	remaining = calc_remaining(p, mode);
83307a9368aSKonstantin Belousov 	while (remaining != remain_for_mode(mode)) {
834bf1a3220SDavid Xu 		if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
835bf1a3220SDavid Xu 			goto stopme;
836da7bbd2cSJohn Baldwin 		wakeup_swapper = 0;
83744990b8cSJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td2) {
83844990b8cSJulian Elischer 			if (td2 == td)
83944990b8cSJulian Elischer 				continue;
840a54e85fdSJeff Roberson 			thread_lock(td2);
841b7edba77SJeff Roberson 			td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
8426ddcc233SKonstantin Belousov 			if (TD_IS_INHIBITED(td2)) {
84307a9368aSKonstantin Belousov 				wakeup_swapper |= weed_inhib(mode, td2, p);
844d8267df7SDavid Xu #ifdef SMP
8456ddcc233SKonstantin Belousov 			} else if (TD_IS_RUNNING(td2) && td != td2) {
846d8267df7SDavid Xu 				forward_signal(td2);
847d8267df7SDavid Xu #endif
8486ddcc233SKonstantin Belousov 			}
849a54e85fdSJeff Roberson 			thread_unlock(td2);
8509d102777SJulian Elischer 		}
851da7bbd2cSJohn Baldwin 		if (wakeup_swapper)
852da7bbd2cSJohn Baldwin 			kick_proc0();
85379799053SKonstantin Belousov 		remaining = calc_remaining(p, mode);
854ec008e96SDavid Xu 
8559d102777SJulian Elischer 		/*
8569d102777SJulian Elischer 		 * Maybe we suspended some threads.. was it enough?
8579d102777SJulian Elischer 		 */
85807a9368aSKonstantin Belousov 		if (remaining == remain_for_mode(mode))
8599d102777SJulian Elischer 			break;
8609d102777SJulian Elischer 
861bf1a3220SDavid Xu stopme:
86244990b8cSJulian Elischer 		/*
86344990b8cSJulian Elischer 		 * Wake us up when everyone else has suspended.
864e3b9bf71SJulian Elischer 		 * In the mean time we suspend as well.
86544990b8cSJulian Elischer 		 */
8666ddcc233SKonstantin Belousov 		thread_suspend_switch(td, p);
86779799053SKonstantin Belousov 		remaining = calc_remaining(p, mode);
86844990b8cSJulian Elischer 	}
869906ac69dSDavid Xu 	if (mode == SINGLE_EXIT) {
87091599697SJulian Elischer 		/*
8718626a0ddSKonstantin Belousov 		 * Convert the process to an unthreaded process.  The
8728626a0ddSKonstantin Belousov 		 * SINGLE_EXIT is called by exit1() or execve(), in
8738626a0ddSKonstantin Belousov 		 * both cases other threads must be retired.
87491599697SJulian Elischer 		 */
8758626a0ddSKonstantin Belousov 		KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
876ed062c8dSJulian Elischer 		p->p_singlethread = NULL;
8778626a0ddSKonstantin Belousov 		p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
878fd229b5bSKonstantin Belousov 
879fd229b5bSKonstantin Belousov 		/*
880fd229b5bSKonstantin Belousov 		 * Wait for any remaining threads to exit cpu_throw().
881fd229b5bSKonstantin Belousov 		 */
882fd229b5bSKonstantin Belousov 		while (p->p_exitthreads != 0) {
883fd229b5bSKonstantin Belousov 			PROC_SUNLOCK(p);
884fd229b5bSKonstantin Belousov 			PROC_UNLOCK(p);
885fd229b5bSKonstantin Belousov 			sched_relinquish(td);
886fd229b5bSKonstantin Belousov 			PROC_LOCK(p);
887fd229b5bSKonstantin Belousov 			PROC_SLOCK(p);
888fd229b5bSKonstantin Belousov 		}
889ac437c07SKonstantin Belousov 	} else if (mode == SINGLE_BOUNDARY) {
890ac437c07SKonstantin Belousov 		/*
891ac437c07SKonstantin Belousov 		 * Wait until all suspended threads are removed from
892ac437c07SKonstantin Belousov 		 * the processors.  The thread_suspend_check()
893ac437c07SKonstantin Belousov 		 * increments p_boundary_count while it is still
894ac437c07SKonstantin Belousov 		 * running, which makes it possible for the execve()
895ac437c07SKonstantin Belousov 		 * to destroy vmspace while our other threads are
896ac437c07SKonstantin Belousov 		 * still using the address space.
897ac437c07SKonstantin Belousov 		 *
898ac437c07SKonstantin Belousov 		 * We lock the thread, which is only allowed to
899ac437c07SKonstantin Belousov 		 * succeed after context switch code finished using
900ac437c07SKonstantin Belousov 		 * the address space.
901ac437c07SKonstantin Belousov 		 */
902ac437c07SKonstantin Belousov 		FOREACH_THREAD_IN_PROC(p, td2) {
903ac437c07SKonstantin Belousov 			if (td2 == td)
904ac437c07SKonstantin Belousov 				continue;
905ac437c07SKonstantin Belousov 			thread_lock(td2);
906ac437c07SKonstantin Belousov 			KASSERT((td2->td_flags & TDF_BOUNDARY) != 0,
907ac437c07SKonstantin Belousov 			    ("td %p not on boundary", td2));
908ac437c07SKonstantin Belousov 			KASSERT(TD_IS_SUSPENDED(td2),
909ac437c07SKonstantin Belousov 			    ("td %p is not suspended", td2));
910ac437c07SKonstantin Belousov 			thread_unlock(td2);
911ac437c07SKonstantin Belousov 		}
91291599697SJulian Elischer 	}
9137b4a950aSDavid Xu 	PROC_SUNLOCK(p);
91444990b8cSJulian Elischer 	return (0);
91544990b8cSJulian Elischer }
91644990b8cSJulian Elischer 
9178638fe7bSKonstantin Belousov bool
9188638fe7bSKonstantin Belousov thread_suspend_check_needed(void)
9198638fe7bSKonstantin Belousov {
9208638fe7bSKonstantin Belousov 	struct proc *p;
9218638fe7bSKonstantin Belousov 	struct thread *td;
9228638fe7bSKonstantin Belousov 
9238638fe7bSKonstantin Belousov 	td = curthread;
9248638fe7bSKonstantin Belousov 	p = td->td_proc;
9258638fe7bSKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
9268638fe7bSKonstantin Belousov 	return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
9278638fe7bSKonstantin Belousov 	    (td->td_dbgflags & TDB_SUSPEND) != 0));
9288638fe7bSKonstantin Belousov }
9298638fe7bSKonstantin Belousov 
93044990b8cSJulian Elischer /*
93144990b8cSJulian Elischer  * Called in from locations that can safely check to see
93244990b8cSJulian Elischer  * whether we have to suspend or at least throttle for a
93344990b8cSJulian Elischer  * single-thread event (e.g. fork).
93444990b8cSJulian Elischer  *
93544990b8cSJulian Elischer  * Such locations include userret().
93644990b8cSJulian Elischer  * If the "return_instead" argument is non zero, the thread must be able to
93744990b8cSJulian Elischer  * accept 0 (caller may continue), or 1 (caller must abort) as a result.
93844990b8cSJulian Elischer  *
93944990b8cSJulian Elischer  * The 'return_instead' argument tells the function if it may do a
94044990b8cSJulian Elischer  * thread_exit() or suspend, or whether the caller must abort and back
94144990b8cSJulian Elischer  * out instead.
94244990b8cSJulian Elischer  *
94344990b8cSJulian Elischer  * If the thread that set the single_threading request has set the
94444990b8cSJulian Elischer  * P_SINGLE_EXIT bit in the process flags then this call will never return
94544990b8cSJulian Elischer  * if 'return_instead' is false, but will exit.
94644990b8cSJulian Elischer  *
94744990b8cSJulian Elischer  * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
94844990b8cSJulian Elischer  *---------------+--------------------+---------------------
94944990b8cSJulian Elischer  *       0       | returns 0          |   returns 0 or 1
950353374b5SJohn Baldwin  *               | when ST ends       |   immediately
95144990b8cSJulian Elischer  *---------------+--------------------+---------------------
95244990b8cSJulian Elischer  *       1       | thread exits       |   returns 1
953353374b5SJohn Baldwin  *               |                    |  immediately
95444990b8cSJulian Elischer  * 0 = thread_exit() or suspension ok,
95544990b8cSJulian Elischer  * other = return error instead of stopping the thread.
95644990b8cSJulian Elischer  *
95744990b8cSJulian Elischer  * While a full suspension is under effect, even a single threading
95844990b8cSJulian Elischer  * thread would be suspended if it made this call (but it shouldn't).
95944990b8cSJulian Elischer  * This call should only be made from places where
96044990b8cSJulian Elischer  * thread_exit() would be safe as that may be the outcome unless
96144990b8cSJulian Elischer  * return_instead is set.
96244990b8cSJulian Elischer  */
96344990b8cSJulian Elischer int
96444990b8cSJulian Elischer thread_suspend_check(int return_instead)
96544990b8cSJulian Elischer {
966ecafb24bSJuli Mallett 	struct thread *td;
967ecafb24bSJuli Mallett 	struct proc *p;
96846e47c4fSKonstantin Belousov 	int wakeup_swapper;
96944990b8cSJulian Elischer 
97044990b8cSJulian Elischer 	td = curthread;
97144990b8cSJulian Elischer 	p = td->td_proc;
97237814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
97344990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
9748638fe7bSKonstantin Belousov 	while (thread_suspend_check_needed()) {
9751279572aSDavid Xu 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
97644990b8cSJulian Elischer 			KASSERT(p->p_singlethread != NULL,
97744990b8cSJulian Elischer 			    ("singlethread not set"));
97844990b8cSJulian Elischer 			/*
979e3b9bf71SJulian Elischer 			 * The only suspension in action is a
980e3b9bf71SJulian Elischer 			 * single-threading. Single threader need not stop.
981bd07998eSKonstantin Belousov 			 * It is safe to access p->p_singlethread unlocked
982bd07998eSKonstantin Belousov 			 * because it can only be set to our address by us.
98344990b8cSJulian Elischer 			 */
984e3b9bf71SJulian Elischer 			if (p->p_singlethread == td)
98544990b8cSJulian Elischer 				return (0);	/* Exempt from stopping. */
98644990b8cSJulian Elischer 		}
98745a4bfa1SDavid Xu 		if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
98894f0972bSDavid Xu 			return (EINTR);
98944990b8cSJulian Elischer 
990906ac69dSDavid Xu 		/* Should we goto user boundary if we didn't come from there? */
991906ac69dSDavid Xu 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
992906ac69dSDavid Xu 		    (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
99394f0972bSDavid Xu 			return (ERESTART);
994906ac69dSDavid Xu 
99544990b8cSJulian Elischer 		/*
9963077f938SKonstantin Belousov 		 * Ignore suspend requests if they are deferred.
997d071a6faSJohn Baldwin 		 */
9983077f938SKonstantin Belousov 		if ((td->td_flags & TDF_SBDRY) != 0) {
999d071a6faSJohn Baldwin 			KASSERT(return_instead,
1000d071a6faSJohn Baldwin 			    ("TDF_SBDRY set for unsafe thread_suspend_check"));
100146e47c4fSKonstantin Belousov 			KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
100246e47c4fSKonstantin Belousov 			    (TDF_SEINTR | TDF_SERESTART),
100346e47c4fSKonstantin Belousov 			    ("both TDF_SEINTR and TDF_SERESTART"));
100446e47c4fSKonstantin Belousov 			return (TD_SBDRY_INTR(td) ? TD_SBDRY_ERRNO(td) : 0);
1005d071a6faSJohn Baldwin 		}
1006d071a6faSJohn Baldwin 
1007d071a6faSJohn Baldwin 		/*
100844990b8cSJulian Elischer 		 * If the process is waiting for us to exit,
100944990b8cSJulian Elischer 		 * this thread should just suicide.
10101279572aSDavid Xu 		 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
101144990b8cSJulian Elischer 		 */
1012cf7d9a8cSDavid Xu 		if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
1013cf7d9a8cSDavid Xu 			PROC_UNLOCK(p);
101491d1786fSDmitry Chagin 
101591d1786fSDmitry Chagin 			/*
101691d1786fSDmitry Chagin 			 * Allow Linux emulation layer to do some work
101791d1786fSDmitry Chagin 			 * before thread suicide.
101891d1786fSDmitry Chagin 			 */
101991d1786fSDmitry Chagin 			if (__predict_false(p->p_sysent->sv_thread_detach != NULL))
102091d1786fSDmitry Chagin 				(p->p_sysent->sv_thread_detach)(td);
10212a339d9eSKonstantin Belousov 			umtx_thread_exit(td);
1022d1e7a4a5SJohn Baldwin 			kern_thr_exit(td);
1023d1e7a4a5SJohn Baldwin 			panic("stopped thread did not exit");
1024cf7d9a8cSDavid Xu 		}
102521ecd1e9SDavid Xu 
102621ecd1e9SDavid Xu 		PROC_SLOCK(p);
102721ecd1e9SDavid Xu 		thread_stopped(p);
1028a54e85fdSJeff Roberson 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1029a54e85fdSJeff Roberson 			if (p->p_numthreads == p->p_suspcount + 1) {
1030a54e85fdSJeff Roberson 				thread_lock(p->p_singlethread);
103184cdea97SKonstantin Belousov 				wakeup_swapper = thread_unsuspend_one(
103284cdea97SKonstantin Belousov 				    p->p_singlethread, p, false);
1033a54e85fdSJeff Roberson 				thread_unlock(p->p_singlethread);
10347847a9daSJohn Baldwin 				if (wakeup_swapper)
10357847a9daSJohn Baldwin 					kick_proc0();
1036a54e85fdSJeff Roberson 			}
1037a54e85fdSJeff Roberson 		}
10383f9be10eSDavid Xu 		PROC_UNLOCK(p);
10397b4a950aSDavid Xu 		thread_lock(td);
104044990b8cSJulian Elischer 		/*
104144990b8cSJulian Elischer 		 * When a thread suspends, it just
1042ad1e7d28SJulian Elischer 		 * gets taken off all queues.
104344990b8cSJulian Elischer 		 */
104471fad9fdSJulian Elischer 		thread_suspend_one(td);
1045906ac69dSDavid Xu 		if (return_instead == 0) {
1046906ac69dSDavid Xu 			p->p_boundary_count++;
1047906ac69dSDavid Xu 			td->td_flags |= TDF_BOUNDARY;
1048cf19bf91SJulian Elischer 		}
10497b4a950aSDavid Xu 		PROC_SUNLOCK(p);
10508df78c41SJeff Roberson 		mi_switch(SW_INVOL | SWT_SUSPEND, NULL);
1051a54e85fdSJeff Roberson 		thread_unlock(td);
105244990b8cSJulian Elischer 		PROC_LOCK(p);
105344990b8cSJulian Elischer 	}
105444990b8cSJulian Elischer 	return (0);
105544990b8cSJulian Elischer }
105644990b8cSJulian Elischer 
105735c32a76SDavid Xu void
10586ddcc233SKonstantin Belousov thread_suspend_switch(struct thread *td, struct proc *p)
1059a54e85fdSJeff Roberson {
1060a54e85fdSJeff Roberson 
1061a54e85fdSJeff Roberson 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1062a54e85fdSJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
10637b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1064a54e85fdSJeff Roberson 	/*
1065a54e85fdSJeff Roberson 	 * We implement thread_suspend_one in stages here to avoid
1066a54e85fdSJeff Roberson 	 * dropping the proc lock while the thread lock is owned.
1067a54e85fdSJeff Roberson 	 */
10686ddcc233SKonstantin Belousov 	if (p == td->td_proc) {
1069a54e85fdSJeff Roberson 		thread_stopped(p);
1070a54e85fdSJeff Roberson 		p->p_suspcount++;
10716ddcc233SKonstantin Belousov 	}
10723f9be10eSDavid Xu 	PROC_UNLOCK(p);
10737b4a950aSDavid Xu 	thread_lock(td);
1074b7edba77SJeff Roberson 	td->td_flags &= ~TDF_NEEDSUSPCHK;
1075a54e85fdSJeff Roberson 	TD_SET_SUSPENDED(td);
1076c5aa6b58SJeff Roberson 	sched_sleep(td, 0);
10777b4a950aSDavid Xu 	PROC_SUNLOCK(p);
1078a54e85fdSJeff Roberson 	DROP_GIANT();
10798df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_SUSPEND, NULL);
1080a54e85fdSJeff Roberson 	thread_unlock(td);
1081a54e85fdSJeff Roberson 	PICKUP_GIANT();
1082a54e85fdSJeff Roberson 	PROC_LOCK(p);
10837b4a950aSDavid Xu 	PROC_SLOCK(p);
1084a54e85fdSJeff Roberson }
1085a54e85fdSJeff Roberson 
1086a54e85fdSJeff Roberson void
108735c32a76SDavid Xu thread_suspend_one(struct thread *td)
108835c32a76SDavid Xu {
10896ddcc233SKonstantin Belousov 	struct proc *p;
109035c32a76SDavid Xu 
10916ddcc233SKonstantin Belousov 	p = td->td_proc;
10927b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1093a54e85fdSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1094e574e444SDavid Xu 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
109535c32a76SDavid Xu 	p->p_suspcount++;
1096b7edba77SJeff Roberson 	td->td_flags &= ~TDF_NEEDSUSPCHK;
109771fad9fdSJulian Elischer 	TD_SET_SUSPENDED(td);
1098c5aa6b58SJeff Roberson 	sched_sleep(td, 0);
109935c32a76SDavid Xu }
110035c32a76SDavid Xu 
110184cdea97SKonstantin Belousov static int
110284cdea97SKonstantin Belousov thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
110335c32a76SDavid Xu {
110435c32a76SDavid Xu 
1105a54e85fdSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1106ad1e7d28SJulian Elischer 	KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
110771fad9fdSJulian Elischer 	TD_CLR_SUSPENDED(td);
11086ddcc233SKonstantin Belousov 	td->td_flags &= ~TDF_ALLPROCSUSP;
11096ddcc233SKonstantin Belousov 	if (td->td_proc == p) {
11106ddcc233SKonstantin Belousov 		PROC_SLOCK_ASSERT(p, MA_OWNED);
111135c32a76SDavid Xu 		p->p_suspcount--;
111284cdea97SKonstantin Belousov 		if (boundary && (td->td_flags & TDF_BOUNDARY) != 0) {
111384cdea97SKonstantin Belousov 			td->td_flags &= ~TDF_BOUNDARY;
111484cdea97SKonstantin Belousov 			p->p_boundary_count--;
111584cdea97SKonstantin Belousov 		}
11166ddcc233SKonstantin Belousov 	}
11177847a9daSJohn Baldwin 	return (setrunnable(td));
111835c32a76SDavid Xu }
111935c32a76SDavid Xu 
112044990b8cSJulian Elischer /*
112144990b8cSJulian Elischer  * Allow all threads blocked by single threading to continue running.
112244990b8cSJulian Elischer  */
112344990b8cSJulian Elischer void
112444990b8cSJulian Elischer thread_unsuspend(struct proc *p)
112544990b8cSJulian Elischer {
112644990b8cSJulian Elischer 	struct thread *td;
11277847a9daSJohn Baldwin 	int wakeup_swapper;
112844990b8cSJulian Elischer 
112944990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
11307b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
11317847a9daSJohn Baldwin 	wakeup_swapper = 0;
113244990b8cSJulian Elischer 	if (!P_SHOULDSTOP(p)) {
1133ad1e7d28SJulian Elischer                 FOREACH_THREAD_IN_PROC(p, td) {
1134a54e85fdSJeff Roberson 			thread_lock(td);
1135ad1e7d28SJulian Elischer 			if (TD_IS_SUSPENDED(td)) {
113684cdea97SKonstantin Belousov 				wakeup_swapper |= thread_unsuspend_one(td, p,
113784cdea97SKonstantin Belousov 				    true);
113844990b8cSJulian Elischer 			}
1139a54e85fdSJeff Roberson 			thread_unlock(td);
1140ad1e7d28SJulian Elischer 		}
114184cdea97SKonstantin Belousov 	} else if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
114284cdea97SKonstantin Belousov 	    p->p_numthreads == p->p_suspcount) {
114344990b8cSJulian Elischer 		/*
114444990b8cSJulian Elischer 		 * Stopping everything also did the job for the single
114544990b8cSJulian Elischer 		 * threading request. Now we've downgraded to single-threaded,
114644990b8cSJulian Elischer 		 * let it continue.
114744990b8cSJulian Elischer 		 */
11486ddcc233SKonstantin Belousov 		if (p->p_singlethread->td_proc == p) {
1149a54e85fdSJeff Roberson 			thread_lock(p->p_singlethread);
11506ddcc233SKonstantin Belousov 			wakeup_swapper = thread_unsuspend_one(
115184cdea97SKonstantin Belousov 			    p->p_singlethread, p, false);
1152a54e85fdSJeff Roberson 			thread_unlock(p->p_singlethread);
115344990b8cSJulian Elischer 		}
11546ddcc233SKonstantin Belousov 	}
11557847a9daSJohn Baldwin 	if (wakeup_swapper)
11567847a9daSJohn Baldwin 		kick_proc0();
115744990b8cSJulian Elischer }
115844990b8cSJulian Elischer 
1159ed062c8dSJulian Elischer /*
1160ed062c8dSJulian Elischer  * End the single threading mode..
1161ed062c8dSJulian Elischer  */
116244990b8cSJulian Elischer void
11636ddcc233SKonstantin Belousov thread_single_end(struct proc *p, int mode)
116444990b8cSJulian Elischer {
116544990b8cSJulian Elischer 	struct thread *td;
11667847a9daSJohn Baldwin 	int wakeup_swapper;
116744990b8cSJulian Elischer 
11686ddcc233SKonstantin Belousov 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
11696ddcc233SKonstantin Belousov 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
11706ddcc233SKonstantin Belousov 	    ("invalid mode %d", mode));
117144990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
11726ddcc233SKonstantin Belousov 	KASSERT((mode == SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) != 0) ||
11736ddcc233SKonstantin Belousov 	    (mode != SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) == 0),
11746ddcc233SKonstantin Belousov 	    ("mode %d does not match P_TOTAL_STOP", mode));
117584cdea97SKonstantin Belousov 	KASSERT(mode == SINGLE_ALLPROC || p->p_singlethread == curthread,
117684cdea97SKonstantin Belousov 	    ("thread_single_end from other thread %p %p",
117784cdea97SKonstantin Belousov 	    curthread, p->p_singlethread));
117884cdea97SKonstantin Belousov 	KASSERT(mode != SINGLE_BOUNDARY ||
117984cdea97SKonstantin Belousov 	    (p->p_flag & P_SINGLE_BOUNDARY) != 0,
118084cdea97SKonstantin Belousov 	    ("mis-matched SINGLE_BOUNDARY flags %x", p->p_flag));
11816ddcc233SKonstantin Belousov 	p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY |
11826ddcc233SKonstantin Belousov 	    P_TOTAL_STOP);
11837b4a950aSDavid Xu 	PROC_SLOCK(p);
118444990b8cSJulian Elischer 	p->p_singlethread = NULL;
11857847a9daSJohn Baldwin 	wakeup_swapper = 0;
118649539972SJulian Elischer 	/*
11877847a9daSJohn Baldwin 	 * If there are other threads they may now run,
118849539972SJulian Elischer 	 * unless of course there is a blanket 'stop order'
118949539972SJulian Elischer 	 * on the process. The single threader must be allowed
119049539972SJulian Elischer 	 * to continue however as this is a bad place to stop.
119149539972SJulian Elischer 	 */
11926ddcc233SKonstantin Belousov 	if (p->p_numthreads != remain_for_mode(mode) && !P_SHOULDSTOP(p)) {
1193ad1e7d28SJulian Elischer                 FOREACH_THREAD_IN_PROC(p, td) {
1194a54e85fdSJeff Roberson 			thread_lock(td);
1195ad1e7d28SJulian Elischer 			if (TD_IS_SUSPENDED(td)) {
119684cdea97SKonstantin Belousov 				wakeup_swapper |= thread_unsuspend_one(td, p,
119784cdea97SKonstantin Belousov 				    mode == SINGLE_BOUNDARY);
119844990b8cSJulian Elischer 			}
1199a54e85fdSJeff Roberson 			thread_unlock(td);
120049539972SJulian Elischer 		}
1201ad1e7d28SJulian Elischer 	}
120284cdea97SKonstantin Belousov 	KASSERT(mode != SINGLE_BOUNDARY || p->p_boundary_count == 0,
120384cdea97SKonstantin Belousov 	    ("inconsistent boundary count %d", p->p_boundary_count));
12047b4a950aSDavid Xu 	PROC_SUNLOCK(p);
12057847a9daSJohn Baldwin 	if (wakeup_swapper)
12067847a9daSJohn Baldwin 		kick_proc0();
120749539972SJulian Elischer }
12084fc21c09SDaniel Eischen 
120944355392SDavid Xu struct thread *
121044355392SDavid Xu thread_find(struct proc *p, lwpid_t tid)
121144355392SDavid Xu {
121244355392SDavid Xu 	struct thread *td;
121344355392SDavid Xu 
121444355392SDavid Xu 	PROC_LOCK_ASSERT(p, MA_OWNED);
121544355392SDavid Xu 	FOREACH_THREAD_IN_PROC(p, td) {
121644355392SDavid Xu 		if (td->td_tid == tid)
121744355392SDavid Xu 			break;
121844355392SDavid Xu 	}
121944355392SDavid Xu 	return (td);
122044355392SDavid Xu }
1221cf7d9a8cSDavid Xu 
1222cf7d9a8cSDavid Xu /* Locate a thread by number; return with proc lock held. */
1223cf7d9a8cSDavid Xu struct thread *
1224cf7d9a8cSDavid Xu tdfind(lwpid_t tid, pid_t pid)
1225cf7d9a8cSDavid Xu {
1226cf7d9a8cSDavid Xu #define RUN_THRESH	16
1227cf7d9a8cSDavid Xu 	struct thread *td;
1228cf7d9a8cSDavid Xu 	int run = 0;
1229cf7d9a8cSDavid Xu 
1230cf7d9a8cSDavid Xu 	rw_rlock(&tidhash_lock);
1231cf7d9a8cSDavid Xu 	LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1232cf7d9a8cSDavid Xu 		if (td->td_tid == tid) {
1233cf7d9a8cSDavid Xu 			if (pid != -1 && td->td_proc->p_pid != pid) {
1234cf7d9a8cSDavid Xu 				td = NULL;
1235cf7d9a8cSDavid Xu 				break;
1236cf7d9a8cSDavid Xu 			}
12378e6fa660SJohn Baldwin 			PROC_LOCK(td->td_proc);
1238cf7d9a8cSDavid Xu 			if (td->td_proc->p_state == PRS_NEW) {
12398e6fa660SJohn Baldwin 				PROC_UNLOCK(td->td_proc);
1240cf7d9a8cSDavid Xu 				td = NULL;
1241cf7d9a8cSDavid Xu 				break;
1242cf7d9a8cSDavid Xu 			}
1243cf7d9a8cSDavid Xu 			if (run > RUN_THRESH) {
1244cf7d9a8cSDavid Xu 				if (rw_try_upgrade(&tidhash_lock)) {
1245cf7d9a8cSDavid Xu 					LIST_REMOVE(td, td_hash);
1246cf7d9a8cSDavid Xu 					LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1247cf7d9a8cSDavid Xu 						td, td_hash);
1248cf7d9a8cSDavid Xu 					rw_wunlock(&tidhash_lock);
1249cf7d9a8cSDavid Xu 					return (td);
1250cf7d9a8cSDavid Xu 				}
1251cf7d9a8cSDavid Xu 			}
1252cf7d9a8cSDavid Xu 			break;
1253cf7d9a8cSDavid Xu 		}
1254cf7d9a8cSDavid Xu 		run++;
1255cf7d9a8cSDavid Xu 	}
1256cf7d9a8cSDavid Xu 	rw_runlock(&tidhash_lock);
1257cf7d9a8cSDavid Xu 	return (td);
1258cf7d9a8cSDavid Xu }
1259cf7d9a8cSDavid Xu 
1260cf7d9a8cSDavid Xu void
1261cf7d9a8cSDavid Xu tidhash_add(struct thread *td)
1262cf7d9a8cSDavid Xu {
1263cf7d9a8cSDavid Xu 	rw_wlock(&tidhash_lock);
1264cf7d9a8cSDavid Xu 	LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1265cf7d9a8cSDavid Xu 	rw_wunlock(&tidhash_lock);
1266cf7d9a8cSDavid Xu }
1267cf7d9a8cSDavid Xu 
1268cf7d9a8cSDavid Xu void
1269cf7d9a8cSDavid Xu tidhash_remove(struct thread *td)
1270cf7d9a8cSDavid Xu {
1271cf7d9a8cSDavid Xu 	rw_wlock(&tidhash_lock);
1272cf7d9a8cSDavid Xu 	LIST_REMOVE(td, td_hash);
1273cf7d9a8cSDavid Xu 	rw_wunlock(&tidhash_lock);
1274cf7d9a8cSDavid Xu }
1275