xref: /freebsd/sys/kern/kern_thread.c (revision dd902d015a202e4cabb8fdadd307ec9a3dc38251)
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*dd902d01SGleb Smirnoff 	SLIST_INIT(&td->td_epochs);
6729104847fSDavid Xu 	sigqueue_init(&td->td_sigqueue, p);
673fd90e2edSJung-uk Kim 	callout_init(&td->td_slpcallout, 1);
67466d8df9dSDaniel Eischen 	TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
67544990b8cSJulian Elischer 	p->p_numthreads++;
67644990b8cSJulian Elischer }
67744990b8cSJulian Elischer 
678ed062c8dSJulian Elischer /*
679ed062c8dSJulian Elischer  * Called from:
680ed062c8dSJulian Elischer  *  thread_exit()
681ed062c8dSJulian Elischer  */
682d3a0bd78SJulian Elischer void
683d3a0bd78SJulian Elischer thread_unlink(struct thread *td)
684d3a0bd78SJulian Elischer {
685d3a0bd78SJulian Elischer 	struct proc *p = td->td_proc;
686d3a0bd78SJulian Elischer 
687374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
688*dd902d01SGleb Smirnoff 	MPASS(SLIST_EMPTY(&td->td_epochs));
689*dd902d01SGleb Smirnoff 
690d3a0bd78SJulian Elischer 	TAILQ_REMOVE(&p->p_threads, td, td_plist);
691d3a0bd78SJulian Elischer 	p->p_numthreads--;
692d3a0bd78SJulian Elischer 	/* could clear a few other things here */
6938460a577SJohn Birrell 	/* Must  NOT clear links to proc! */
6945c8329edSJulian Elischer }
6955c8329edSJulian Elischer 
69679799053SKonstantin Belousov static int
69779799053SKonstantin Belousov calc_remaining(struct proc *p, int mode)
69879799053SKonstantin Belousov {
69979799053SKonstantin Belousov 	int remaining;
70079799053SKonstantin Belousov 
7017b519077SKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
7027b519077SKonstantin Belousov 	PROC_SLOCK_ASSERT(p, MA_OWNED);
70379799053SKonstantin Belousov 	if (mode == SINGLE_EXIT)
70479799053SKonstantin Belousov 		remaining = p->p_numthreads;
70579799053SKonstantin Belousov 	else if (mode == SINGLE_BOUNDARY)
70679799053SKonstantin Belousov 		remaining = p->p_numthreads - p->p_boundary_count;
7076ddcc233SKonstantin Belousov 	else if (mode == SINGLE_NO_EXIT || mode == SINGLE_ALLPROC)
70879799053SKonstantin Belousov 		remaining = p->p_numthreads - p->p_suspcount;
70979799053SKonstantin Belousov 	else
71079799053SKonstantin Belousov 		panic("calc_remaining: wrong mode %d", mode);
71179799053SKonstantin Belousov 	return (remaining);
71279799053SKonstantin Belousov }
71379799053SKonstantin Belousov 
71407a9368aSKonstantin Belousov static int
71507a9368aSKonstantin Belousov remain_for_mode(int mode)
71607a9368aSKonstantin Belousov {
71707a9368aSKonstantin Belousov 
7186ddcc233SKonstantin Belousov 	return (mode == SINGLE_ALLPROC ? 0 : 1);
71907a9368aSKonstantin Belousov }
72007a9368aSKonstantin Belousov 
72107a9368aSKonstantin Belousov static int
72207a9368aSKonstantin Belousov weed_inhib(int mode, struct thread *td2, struct proc *p)
72307a9368aSKonstantin Belousov {
72407a9368aSKonstantin Belousov 	int wakeup_swapper;
72507a9368aSKonstantin Belousov 
72607a9368aSKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
72707a9368aSKonstantin Belousov 	PROC_SLOCK_ASSERT(p, MA_OWNED);
72807a9368aSKonstantin Belousov 	THREAD_LOCK_ASSERT(td2, MA_OWNED);
72907a9368aSKonstantin Belousov 
73007a9368aSKonstantin Belousov 	wakeup_swapper = 0;
73107a9368aSKonstantin Belousov 	switch (mode) {
73207a9368aSKonstantin Belousov 	case SINGLE_EXIT:
73307a9368aSKonstantin Belousov 		if (TD_IS_SUSPENDED(td2))
73484cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, true);
73507a9368aSKonstantin Belousov 		if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0)
73607a9368aSKonstantin Belousov 			wakeup_swapper |= sleepq_abort(td2, EINTR);
73707a9368aSKonstantin Belousov 		break;
73807a9368aSKonstantin Belousov 	case SINGLE_BOUNDARY:
73907a9368aSKonstantin Belousov 	case SINGLE_NO_EXIT:
74007a9368aSKonstantin Belousov 		if (TD_IS_SUSPENDED(td2) && (td2->td_flags & TDF_BOUNDARY) == 0)
74184cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
74207a9368aSKonstantin Belousov 		if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0)
74307a9368aSKonstantin Belousov 			wakeup_swapper |= sleepq_abort(td2, ERESTART);
744917dd390SKonstantin Belousov 		break;
7456ddcc233SKonstantin Belousov 	case SINGLE_ALLPROC:
7466ddcc233SKonstantin Belousov 		/*
7476ddcc233SKonstantin Belousov 		 * ALLPROC suspend tries to avoid spurious EINTR for
7486ddcc233SKonstantin Belousov 		 * threads sleeping interruptable, by suspending the
7496ddcc233SKonstantin Belousov 		 * thread directly, similarly to sig_suspend_threads().
7506ddcc233SKonstantin Belousov 		 * Since such sleep is not performed at the user
7516ddcc233SKonstantin Belousov 		 * boundary, TDF_BOUNDARY flag is not set, and TDF_ALLPROCSUSP
7526ddcc233SKonstantin Belousov 		 * is used to avoid immediate un-suspend.
7536ddcc233SKonstantin Belousov 		 */
7546ddcc233SKonstantin Belousov 		if (TD_IS_SUSPENDED(td2) && (td2->td_flags & (TDF_BOUNDARY |
7556ddcc233SKonstantin Belousov 		    TDF_ALLPROCSUSP)) == 0)
75684cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
7576ddcc233SKonstantin Belousov 		if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0) {
7586ddcc233SKonstantin Belousov 			if ((td2->td_flags & TDF_SBDRY) == 0) {
7596ddcc233SKonstantin Belousov 				thread_suspend_one(td2);
7606ddcc233SKonstantin Belousov 				td2->td_flags |= TDF_ALLPROCSUSP;
7616ddcc233SKonstantin Belousov 			} else {
7626ddcc233SKonstantin Belousov 				wakeup_swapper |= sleepq_abort(td2, ERESTART);
7636ddcc233SKonstantin Belousov 			}
7646ddcc233SKonstantin Belousov 		}
76507a9368aSKonstantin Belousov 		break;
76607a9368aSKonstantin Belousov 	}
76707a9368aSKonstantin Belousov 	return (wakeup_swapper);
76807a9368aSKonstantin Belousov }
76907a9368aSKonstantin Belousov 
7705215b187SJeff Roberson /*
77144990b8cSJulian Elischer  * Enforce single-threading.
77244990b8cSJulian Elischer  *
77344990b8cSJulian Elischer  * Returns 1 if the caller must abort (another thread is waiting to
77444990b8cSJulian Elischer  * exit the process or similar). Process is locked!
77544990b8cSJulian Elischer  * Returns 0 when you are successfully the only thread running.
77644990b8cSJulian Elischer  * A process has successfully single threaded in the suspend mode when
77744990b8cSJulian Elischer  * There are no threads in user mode. Threads in the kernel must be
77844990b8cSJulian Elischer  * allowed to continue until they get to the user boundary. They may even
77944990b8cSJulian Elischer  * copy out their return values and data before suspending. They may however be
780e2668f55SMaxim Konovalov  * accelerated in reaching the user boundary as we will wake up
78144990b8cSJulian Elischer  * any sleeping threads that are interruptable. (PCATCH).
78244990b8cSJulian Elischer  */
78344990b8cSJulian Elischer int
7846ddcc233SKonstantin Belousov thread_single(struct proc *p, int mode)
78544990b8cSJulian Elischer {
78644990b8cSJulian Elischer 	struct thread *td;
78744990b8cSJulian Elischer 	struct thread *td2;
788da7bbd2cSJohn Baldwin 	int remaining, wakeup_swapper;
78944990b8cSJulian Elischer 
79044990b8cSJulian Elischer 	td = curthread;
7916ddcc233SKonstantin Belousov 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
7926ddcc233SKonstantin Belousov 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
7936ddcc233SKonstantin Belousov 	    ("invalid mode %d", mode));
7946ddcc233SKonstantin Belousov 	/*
7956ddcc233SKonstantin Belousov 	 * If allowing non-ALLPROC singlethreading for non-curproc
7966ddcc233SKonstantin Belousov 	 * callers, calc_remaining() and remain_for_mode() should be
7976ddcc233SKonstantin Belousov 	 * adjusted to also account for td->td_proc != p.  For now
7986ddcc233SKonstantin Belousov 	 * this is not implemented because it is not used.
7996ddcc233SKonstantin Belousov 	 */
8006ddcc233SKonstantin Belousov 	KASSERT((mode == SINGLE_ALLPROC && td->td_proc != p) ||
8016ddcc233SKonstantin Belousov 	    (mode != SINGLE_ALLPROC && td->td_proc == p),
8026ddcc233SKonstantin Belousov 	    ("mode %d proc %p curproc %p", mode, p, td->td_proc));
80337814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
80444990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
80544990b8cSJulian Elischer 
8066ddcc233SKonstantin Belousov 	if ((p->p_flag & P_HADTHREADS) == 0 && mode != SINGLE_ALLPROC)
80744990b8cSJulian Elischer 		return (0);
80844990b8cSJulian Elischer 
809e3b9bf71SJulian Elischer 	/* Is someone already single threading? */
810906ac69dSDavid Xu 	if (p->p_singlethread != NULL && p->p_singlethread != td)
81144990b8cSJulian Elischer 		return (1);
81244990b8cSJulian Elischer 
813906ac69dSDavid Xu 	if (mode == SINGLE_EXIT) {
814906ac69dSDavid Xu 		p->p_flag |= P_SINGLE_EXIT;
815906ac69dSDavid Xu 		p->p_flag &= ~P_SINGLE_BOUNDARY;
816906ac69dSDavid Xu 	} else {
817906ac69dSDavid Xu 		p->p_flag &= ~P_SINGLE_EXIT;
818906ac69dSDavid Xu 		if (mode == SINGLE_BOUNDARY)
819906ac69dSDavid Xu 			p->p_flag |= P_SINGLE_BOUNDARY;
820906ac69dSDavid Xu 		else
821906ac69dSDavid Xu 			p->p_flag &= ~P_SINGLE_BOUNDARY;
822906ac69dSDavid Xu 	}
8236ddcc233SKonstantin Belousov 	if (mode == SINGLE_ALLPROC)
8246ddcc233SKonstantin Belousov 		p->p_flag |= P_TOTAL_STOP;
8251279572aSDavid Xu 	p->p_flag |= P_STOPPED_SINGLE;
8267b4a950aSDavid Xu 	PROC_SLOCK(p);
827112afcb2SJohn Baldwin 	p->p_singlethread = td;
82879799053SKonstantin Belousov 	remaining = calc_remaining(p, mode);
82907a9368aSKonstantin Belousov 	while (remaining != remain_for_mode(mode)) {
830bf1a3220SDavid Xu 		if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
831bf1a3220SDavid Xu 			goto stopme;
832da7bbd2cSJohn Baldwin 		wakeup_swapper = 0;
83344990b8cSJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td2) {
83444990b8cSJulian Elischer 			if (td2 == td)
83544990b8cSJulian Elischer 				continue;
836a54e85fdSJeff Roberson 			thread_lock(td2);
837b7edba77SJeff Roberson 			td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
8386ddcc233SKonstantin Belousov 			if (TD_IS_INHIBITED(td2)) {
83907a9368aSKonstantin Belousov 				wakeup_swapper |= weed_inhib(mode, td2, p);
840d8267df7SDavid Xu #ifdef SMP
8416ddcc233SKonstantin Belousov 			} else if (TD_IS_RUNNING(td2) && td != td2) {
842d8267df7SDavid Xu 				forward_signal(td2);
843d8267df7SDavid Xu #endif
8446ddcc233SKonstantin Belousov 			}
845a54e85fdSJeff Roberson 			thread_unlock(td2);
8469d102777SJulian Elischer 		}
847da7bbd2cSJohn Baldwin 		if (wakeup_swapper)
848da7bbd2cSJohn Baldwin 			kick_proc0();
84979799053SKonstantin Belousov 		remaining = calc_remaining(p, mode);
850ec008e96SDavid Xu 
8519d102777SJulian Elischer 		/*
8529d102777SJulian Elischer 		 * Maybe we suspended some threads.. was it enough?
8539d102777SJulian Elischer 		 */
85407a9368aSKonstantin Belousov 		if (remaining == remain_for_mode(mode))
8559d102777SJulian Elischer 			break;
8569d102777SJulian Elischer 
857bf1a3220SDavid Xu stopme:
85844990b8cSJulian Elischer 		/*
85944990b8cSJulian Elischer 		 * Wake us up when everyone else has suspended.
860e3b9bf71SJulian Elischer 		 * In the mean time we suspend as well.
86144990b8cSJulian Elischer 		 */
8626ddcc233SKonstantin Belousov 		thread_suspend_switch(td, p);
86379799053SKonstantin Belousov 		remaining = calc_remaining(p, mode);
86444990b8cSJulian Elischer 	}
865906ac69dSDavid Xu 	if (mode == SINGLE_EXIT) {
86691599697SJulian Elischer 		/*
8678626a0ddSKonstantin Belousov 		 * Convert the process to an unthreaded process.  The
8688626a0ddSKonstantin Belousov 		 * SINGLE_EXIT is called by exit1() or execve(), in
8698626a0ddSKonstantin Belousov 		 * both cases other threads must be retired.
87091599697SJulian Elischer 		 */
8718626a0ddSKonstantin Belousov 		KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
872ed062c8dSJulian Elischer 		p->p_singlethread = NULL;
8738626a0ddSKonstantin Belousov 		p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
874fd229b5bSKonstantin Belousov 
875fd229b5bSKonstantin Belousov 		/*
876fd229b5bSKonstantin Belousov 		 * Wait for any remaining threads to exit cpu_throw().
877fd229b5bSKonstantin Belousov 		 */
878fd229b5bSKonstantin Belousov 		while (p->p_exitthreads != 0) {
879fd229b5bSKonstantin Belousov 			PROC_SUNLOCK(p);
880fd229b5bSKonstantin Belousov 			PROC_UNLOCK(p);
881fd229b5bSKonstantin Belousov 			sched_relinquish(td);
882fd229b5bSKonstantin Belousov 			PROC_LOCK(p);
883fd229b5bSKonstantin Belousov 			PROC_SLOCK(p);
884fd229b5bSKonstantin Belousov 		}
885ac437c07SKonstantin Belousov 	} else if (mode == SINGLE_BOUNDARY) {
886ac437c07SKonstantin Belousov 		/*
887ac437c07SKonstantin Belousov 		 * Wait until all suspended threads are removed from
888ac437c07SKonstantin Belousov 		 * the processors.  The thread_suspend_check()
889ac437c07SKonstantin Belousov 		 * increments p_boundary_count while it is still
890ac437c07SKonstantin Belousov 		 * running, which makes it possible for the execve()
891ac437c07SKonstantin Belousov 		 * to destroy vmspace while our other threads are
892ac437c07SKonstantin Belousov 		 * still using the address space.
893ac437c07SKonstantin Belousov 		 *
894ac437c07SKonstantin Belousov 		 * We lock the thread, which is only allowed to
895ac437c07SKonstantin Belousov 		 * succeed after context switch code finished using
896ac437c07SKonstantin Belousov 		 * the address space.
897ac437c07SKonstantin Belousov 		 */
898ac437c07SKonstantin Belousov 		FOREACH_THREAD_IN_PROC(p, td2) {
899ac437c07SKonstantin Belousov 			if (td2 == td)
900ac437c07SKonstantin Belousov 				continue;
901ac437c07SKonstantin Belousov 			thread_lock(td2);
902ac437c07SKonstantin Belousov 			KASSERT((td2->td_flags & TDF_BOUNDARY) != 0,
903ac437c07SKonstantin Belousov 			    ("td %p not on boundary", td2));
904ac437c07SKonstantin Belousov 			KASSERT(TD_IS_SUSPENDED(td2),
905ac437c07SKonstantin Belousov 			    ("td %p is not suspended", td2));
906ac437c07SKonstantin Belousov 			thread_unlock(td2);
907ac437c07SKonstantin Belousov 		}
90891599697SJulian Elischer 	}
9097b4a950aSDavid Xu 	PROC_SUNLOCK(p);
91044990b8cSJulian Elischer 	return (0);
91144990b8cSJulian Elischer }
91244990b8cSJulian Elischer 
9138638fe7bSKonstantin Belousov bool
9148638fe7bSKonstantin Belousov thread_suspend_check_needed(void)
9158638fe7bSKonstantin Belousov {
9168638fe7bSKonstantin Belousov 	struct proc *p;
9178638fe7bSKonstantin Belousov 	struct thread *td;
9188638fe7bSKonstantin Belousov 
9198638fe7bSKonstantin Belousov 	td = curthread;
9208638fe7bSKonstantin Belousov 	p = td->td_proc;
9218638fe7bSKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
9228638fe7bSKonstantin Belousov 	return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
9238638fe7bSKonstantin Belousov 	    (td->td_dbgflags & TDB_SUSPEND) != 0));
9248638fe7bSKonstantin Belousov }
9258638fe7bSKonstantin Belousov 
92644990b8cSJulian Elischer /*
92744990b8cSJulian Elischer  * Called in from locations that can safely check to see
92844990b8cSJulian Elischer  * whether we have to suspend or at least throttle for a
92944990b8cSJulian Elischer  * single-thread event (e.g. fork).
93044990b8cSJulian Elischer  *
93144990b8cSJulian Elischer  * Such locations include userret().
93244990b8cSJulian Elischer  * If the "return_instead" argument is non zero, the thread must be able to
93344990b8cSJulian Elischer  * accept 0 (caller may continue), or 1 (caller must abort) as a result.
93444990b8cSJulian Elischer  *
93544990b8cSJulian Elischer  * The 'return_instead' argument tells the function if it may do a
93644990b8cSJulian Elischer  * thread_exit() or suspend, or whether the caller must abort and back
93744990b8cSJulian Elischer  * out instead.
93844990b8cSJulian Elischer  *
93944990b8cSJulian Elischer  * If the thread that set the single_threading request has set the
94044990b8cSJulian Elischer  * P_SINGLE_EXIT bit in the process flags then this call will never return
94144990b8cSJulian Elischer  * if 'return_instead' is false, but will exit.
94244990b8cSJulian Elischer  *
94344990b8cSJulian Elischer  * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
94444990b8cSJulian Elischer  *---------------+--------------------+---------------------
94544990b8cSJulian Elischer  *       0       | returns 0          |   returns 0 or 1
946353374b5SJohn Baldwin  *               | when ST ends       |   immediately
94744990b8cSJulian Elischer  *---------------+--------------------+---------------------
94844990b8cSJulian Elischer  *       1       | thread exits       |   returns 1
949353374b5SJohn Baldwin  *               |                    |  immediately
95044990b8cSJulian Elischer  * 0 = thread_exit() or suspension ok,
95144990b8cSJulian Elischer  * other = return error instead of stopping the thread.
95244990b8cSJulian Elischer  *
95344990b8cSJulian Elischer  * While a full suspension is under effect, even a single threading
95444990b8cSJulian Elischer  * thread would be suspended if it made this call (but it shouldn't).
95544990b8cSJulian Elischer  * This call should only be made from places where
95644990b8cSJulian Elischer  * thread_exit() would be safe as that may be the outcome unless
95744990b8cSJulian Elischer  * return_instead is set.
95844990b8cSJulian Elischer  */
95944990b8cSJulian Elischer int
96044990b8cSJulian Elischer thread_suspend_check(int return_instead)
96144990b8cSJulian Elischer {
962ecafb24bSJuli Mallett 	struct thread *td;
963ecafb24bSJuli Mallett 	struct proc *p;
96446e47c4fSKonstantin Belousov 	int wakeup_swapper;
96544990b8cSJulian Elischer 
96644990b8cSJulian Elischer 	td = curthread;
96744990b8cSJulian Elischer 	p = td->td_proc;
96837814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
96944990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
9708638fe7bSKonstantin Belousov 	while (thread_suspend_check_needed()) {
9711279572aSDavid Xu 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
97244990b8cSJulian Elischer 			KASSERT(p->p_singlethread != NULL,
97344990b8cSJulian Elischer 			    ("singlethread not set"));
97444990b8cSJulian Elischer 			/*
975e3b9bf71SJulian Elischer 			 * The only suspension in action is a
976e3b9bf71SJulian Elischer 			 * single-threading. Single threader need not stop.
977bd07998eSKonstantin Belousov 			 * It is safe to access p->p_singlethread unlocked
978bd07998eSKonstantin Belousov 			 * because it can only be set to our address by us.
97944990b8cSJulian Elischer 			 */
980e3b9bf71SJulian Elischer 			if (p->p_singlethread == td)
98144990b8cSJulian Elischer 				return (0);	/* Exempt from stopping. */
98244990b8cSJulian Elischer 		}
98345a4bfa1SDavid Xu 		if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
98494f0972bSDavid Xu 			return (EINTR);
98544990b8cSJulian Elischer 
986906ac69dSDavid Xu 		/* Should we goto user boundary if we didn't come from there? */
987906ac69dSDavid Xu 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
988906ac69dSDavid Xu 		    (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
98994f0972bSDavid Xu 			return (ERESTART);
990906ac69dSDavid Xu 
99144990b8cSJulian Elischer 		/*
9923077f938SKonstantin Belousov 		 * Ignore suspend requests if they are deferred.
993d071a6faSJohn Baldwin 		 */
9943077f938SKonstantin Belousov 		if ((td->td_flags & TDF_SBDRY) != 0) {
995d071a6faSJohn Baldwin 			KASSERT(return_instead,
996d071a6faSJohn Baldwin 			    ("TDF_SBDRY set for unsafe thread_suspend_check"));
99746e47c4fSKonstantin Belousov 			KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
99846e47c4fSKonstantin Belousov 			    (TDF_SEINTR | TDF_SERESTART),
99946e47c4fSKonstantin Belousov 			    ("both TDF_SEINTR and TDF_SERESTART"));
100046e47c4fSKonstantin Belousov 			return (TD_SBDRY_INTR(td) ? TD_SBDRY_ERRNO(td) : 0);
1001d071a6faSJohn Baldwin 		}
1002d071a6faSJohn Baldwin 
1003d071a6faSJohn Baldwin 		/*
100444990b8cSJulian Elischer 		 * If the process is waiting for us to exit,
100544990b8cSJulian Elischer 		 * this thread should just suicide.
10061279572aSDavid Xu 		 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
100744990b8cSJulian Elischer 		 */
1008cf7d9a8cSDavid Xu 		if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
1009cf7d9a8cSDavid Xu 			PROC_UNLOCK(p);
101091d1786fSDmitry Chagin 
101191d1786fSDmitry Chagin 			/*
101291d1786fSDmitry Chagin 			 * Allow Linux emulation layer to do some work
101391d1786fSDmitry Chagin 			 * before thread suicide.
101491d1786fSDmitry Chagin 			 */
101591d1786fSDmitry Chagin 			if (__predict_false(p->p_sysent->sv_thread_detach != NULL))
101691d1786fSDmitry Chagin 				(p->p_sysent->sv_thread_detach)(td);
10172a339d9eSKonstantin Belousov 			umtx_thread_exit(td);
1018d1e7a4a5SJohn Baldwin 			kern_thr_exit(td);
1019d1e7a4a5SJohn Baldwin 			panic("stopped thread did not exit");
1020cf7d9a8cSDavid Xu 		}
102121ecd1e9SDavid Xu 
102221ecd1e9SDavid Xu 		PROC_SLOCK(p);
102321ecd1e9SDavid Xu 		thread_stopped(p);
1024a54e85fdSJeff Roberson 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1025a54e85fdSJeff Roberson 			if (p->p_numthreads == p->p_suspcount + 1) {
1026a54e85fdSJeff Roberson 				thread_lock(p->p_singlethread);
102784cdea97SKonstantin Belousov 				wakeup_swapper = thread_unsuspend_one(
102884cdea97SKonstantin Belousov 				    p->p_singlethread, p, false);
1029a54e85fdSJeff Roberson 				thread_unlock(p->p_singlethread);
10307847a9daSJohn Baldwin 				if (wakeup_swapper)
10317847a9daSJohn Baldwin 					kick_proc0();
1032a54e85fdSJeff Roberson 			}
1033a54e85fdSJeff Roberson 		}
10343f9be10eSDavid Xu 		PROC_UNLOCK(p);
10357b4a950aSDavid Xu 		thread_lock(td);
103644990b8cSJulian Elischer 		/*
103744990b8cSJulian Elischer 		 * When a thread suspends, it just
1038ad1e7d28SJulian Elischer 		 * gets taken off all queues.
103944990b8cSJulian Elischer 		 */
104071fad9fdSJulian Elischer 		thread_suspend_one(td);
1041906ac69dSDavid Xu 		if (return_instead == 0) {
1042906ac69dSDavid Xu 			p->p_boundary_count++;
1043906ac69dSDavid Xu 			td->td_flags |= TDF_BOUNDARY;
1044cf19bf91SJulian Elischer 		}
10457b4a950aSDavid Xu 		PROC_SUNLOCK(p);
10468df78c41SJeff Roberson 		mi_switch(SW_INVOL | SWT_SUSPEND, NULL);
1047a54e85fdSJeff Roberson 		thread_unlock(td);
104844990b8cSJulian Elischer 		PROC_LOCK(p);
104944990b8cSJulian Elischer 	}
105044990b8cSJulian Elischer 	return (0);
105144990b8cSJulian Elischer }
105244990b8cSJulian Elischer 
105335c32a76SDavid Xu void
10546ddcc233SKonstantin Belousov thread_suspend_switch(struct thread *td, struct proc *p)
1055a54e85fdSJeff Roberson {
1056a54e85fdSJeff Roberson 
1057a54e85fdSJeff Roberson 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1058a54e85fdSJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
10597b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1060a54e85fdSJeff Roberson 	/*
1061a54e85fdSJeff Roberson 	 * We implement thread_suspend_one in stages here to avoid
1062a54e85fdSJeff Roberson 	 * dropping the proc lock while the thread lock is owned.
1063a54e85fdSJeff Roberson 	 */
10646ddcc233SKonstantin Belousov 	if (p == td->td_proc) {
1065a54e85fdSJeff Roberson 		thread_stopped(p);
1066a54e85fdSJeff Roberson 		p->p_suspcount++;
10676ddcc233SKonstantin Belousov 	}
10683f9be10eSDavid Xu 	PROC_UNLOCK(p);
10697b4a950aSDavid Xu 	thread_lock(td);
1070b7edba77SJeff Roberson 	td->td_flags &= ~TDF_NEEDSUSPCHK;
1071a54e85fdSJeff Roberson 	TD_SET_SUSPENDED(td);
1072c5aa6b58SJeff Roberson 	sched_sleep(td, 0);
10737b4a950aSDavid Xu 	PROC_SUNLOCK(p);
1074a54e85fdSJeff Roberson 	DROP_GIANT();
10758df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_SUSPEND, NULL);
1076a54e85fdSJeff Roberson 	thread_unlock(td);
1077a54e85fdSJeff Roberson 	PICKUP_GIANT();
1078a54e85fdSJeff Roberson 	PROC_LOCK(p);
10797b4a950aSDavid Xu 	PROC_SLOCK(p);
1080a54e85fdSJeff Roberson }
1081a54e85fdSJeff Roberson 
1082a54e85fdSJeff Roberson void
108335c32a76SDavid Xu thread_suspend_one(struct thread *td)
108435c32a76SDavid Xu {
10856ddcc233SKonstantin Belousov 	struct proc *p;
108635c32a76SDavid Xu 
10876ddcc233SKonstantin Belousov 	p = td->td_proc;
10887b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1089a54e85fdSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1090e574e444SDavid Xu 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
109135c32a76SDavid Xu 	p->p_suspcount++;
1092b7edba77SJeff Roberson 	td->td_flags &= ~TDF_NEEDSUSPCHK;
109371fad9fdSJulian Elischer 	TD_SET_SUSPENDED(td);
1094c5aa6b58SJeff Roberson 	sched_sleep(td, 0);
109535c32a76SDavid Xu }
109635c32a76SDavid Xu 
109784cdea97SKonstantin Belousov static int
109884cdea97SKonstantin Belousov thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
109935c32a76SDavid Xu {
110035c32a76SDavid Xu 
1101a54e85fdSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1102ad1e7d28SJulian Elischer 	KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
110371fad9fdSJulian Elischer 	TD_CLR_SUSPENDED(td);
11046ddcc233SKonstantin Belousov 	td->td_flags &= ~TDF_ALLPROCSUSP;
11056ddcc233SKonstantin Belousov 	if (td->td_proc == p) {
11066ddcc233SKonstantin Belousov 		PROC_SLOCK_ASSERT(p, MA_OWNED);
110735c32a76SDavid Xu 		p->p_suspcount--;
110884cdea97SKonstantin Belousov 		if (boundary && (td->td_flags & TDF_BOUNDARY) != 0) {
110984cdea97SKonstantin Belousov 			td->td_flags &= ~TDF_BOUNDARY;
111084cdea97SKonstantin Belousov 			p->p_boundary_count--;
111184cdea97SKonstantin Belousov 		}
11126ddcc233SKonstantin Belousov 	}
11137847a9daSJohn Baldwin 	return (setrunnable(td));
111435c32a76SDavid Xu }
111535c32a76SDavid Xu 
111644990b8cSJulian Elischer /*
111744990b8cSJulian Elischer  * Allow all threads blocked by single threading to continue running.
111844990b8cSJulian Elischer  */
111944990b8cSJulian Elischer void
112044990b8cSJulian Elischer thread_unsuspend(struct proc *p)
112144990b8cSJulian Elischer {
112244990b8cSJulian Elischer 	struct thread *td;
11237847a9daSJohn Baldwin 	int wakeup_swapper;
112444990b8cSJulian Elischer 
112544990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
11267b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
11277847a9daSJohn Baldwin 	wakeup_swapper = 0;
112844990b8cSJulian Elischer 	if (!P_SHOULDSTOP(p)) {
1129ad1e7d28SJulian Elischer                 FOREACH_THREAD_IN_PROC(p, td) {
1130a54e85fdSJeff Roberson 			thread_lock(td);
1131ad1e7d28SJulian Elischer 			if (TD_IS_SUSPENDED(td)) {
113284cdea97SKonstantin Belousov 				wakeup_swapper |= thread_unsuspend_one(td, p,
113384cdea97SKonstantin Belousov 				    true);
113444990b8cSJulian Elischer 			}
1135a54e85fdSJeff Roberson 			thread_unlock(td);
1136ad1e7d28SJulian Elischer 		}
113784cdea97SKonstantin Belousov 	} else if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
113884cdea97SKonstantin Belousov 	    p->p_numthreads == p->p_suspcount) {
113944990b8cSJulian Elischer 		/*
114044990b8cSJulian Elischer 		 * Stopping everything also did the job for the single
114144990b8cSJulian Elischer 		 * threading request. Now we've downgraded to single-threaded,
114244990b8cSJulian Elischer 		 * let it continue.
114344990b8cSJulian Elischer 		 */
11446ddcc233SKonstantin Belousov 		if (p->p_singlethread->td_proc == p) {
1145a54e85fdSJeff Roberson 			thread_lock(p->p_singlethread);
11466ddcc233SKonstantin Belousov 			wakeup_swapper = thread_unsuspend_one(
114784cdea97SKonstantin Belousov 			    p->p_singlethread, p, false);
1148a54e85fdSJeff Roberson 			thread_unlock(p->p_singlethread);
114944990b8cSJulian Elischer 		}
11506ddcc233SKonstantin Belousov 	}
11517847a9daSJohn Baldwin 	if (wakeup_swapper)
11527847a9daSJohn Baldwin 		kick_proc0();
115344990b8cSJulian Elischer }
115444990b8cSJulian Elischer 
1155ed062c8dSJulian Elischer /*
1156ed062c8dSJulian Elischer  * End the single threading mode..
1157ed062c8dSJulian Elischer  */
115844990b8cSJulian Elischer void
11596ddcc233SKonstantin Belousov thread_single_end(struct proc *p, int mode)
116044990b8cSJulian Elischer {
116144990b8cSJulian Elischer 	struct thread *td;
11627847a9daSJohn Baldwin 	int wakeup_swapper;
116344990b8cSJulian Elischer 
11646ddcc233SKonstantin Belousov 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
11656ddcc233SKonstantin Belousov 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
11666ddcc233SKonstantin Belousov 	    ("invalid mode %d", mode));
116744990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
11686ddcc233SKonstantin Belousov 	KASSERT((mode == SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) != 0) ||
11696ddcc233SKonstantin Belousov 	    (mode != SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) == 0),
11706ddcc233SKonstantin Belousov 	    ("mode %d does not match P_TOTAL_STOP", mode));
117184cdea97SKonstantin Belousov 	KASSERT(mode == SINGLE_ALLPROC || p->p_singlethread == curthread,
117284cdea97SKonstantin Belousov 	    ("thread_single_end from other thread %p %p",
117384cdea97SKonstantin Belousov 	    curthread, p->p_singlethread));
117484cdea97SKonstantin Belousov 	KASSERT(mode != SINGLE_BOUNDARY ||
117584cdea97SKonstantin Belousov 	    (p->p_flag & P_SINGLE_BOUNDARY) != 0,
117684cdea97SKonstantin Belousov 	    ("mis-matched SINGLE_BOUNDARY flags %x", p->p_flag));
11776ddcc233SKonstantin Belousov 	p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY |
11786ddcc233SKonstantin Belousov 	    P_TOTAL_STOP);
11797b4a950aSDavid Xu 	PROC_SLOCK(p);
118044990b8cSJulian Elischer 	p->p_singlethread = NULL;
11817847a9daSJohn Baldwin 	wakeup_swapper = 0;
118249539972SJulian Elischer 	/*
11837847a9daSJohn Baldwin 	 * If there are other threads they may now run,
118449539972SJulian Elischer 	 * unless of course there is a blanket 'stop order'
118549539972SJulian Elischer 	 * on the process. The single threader must be allowed
118649539972SJulian Elischer 	 * to continue however as this is a bad place to stop.
118749539972SJulian Elischer 	 */
11886ddcc233SKonstantin Belousov 	if (p->p_numthreads != remain_for_mode(mode) && !P_SHOULDSTOP(p)) {
1189ad1e7d28SJulian Elischer                 FOREACH_THREAD_IN_PROC(p, td) {
1190a54e85fdSJeff Roberson 			thread_lock(td);
1191ad1e7d28SJulian Elischer 			if (TD_IS_SUSPENDED(td)) {
119284cdea97SKonstantin Belousov 				wakeup_swapper |= thread_unsuspend_one(td, p,
119384cdea97SKonstantin Belousov 				    mode == SINGLE_BOUNDARY);
119444990b8cSJulian Elischer 			}
1195a54e85fdSJeff Roberson 			thread_unlock(td);
119649539972SJulian Elischer 		}
1197ad1e7d28SJulian Elischer 	}
119884cdea97SKonstantin Belousov 	KASSERT(mode != SINGLE_BOUNDARY || p->p_boundary_count == 0,
119984cdea97SKonstantin Belousov 	    ("inconsistent boundary count %d", p->p_boundary_count));
12007b4a950aSDavid Xu 	PROC_SUNLOCK(p);
12017847a9daSJohn Baldwin 	if (wakeup_swapper)
12027847a9daSJohn Baldwin 		kick_proc0();
120349539972SJulian Elischer }
12044fc21c09SDaniel Eischen 
120544355392SDavid Xu struct thread *
120644355392SDavid Xu thread_find(struct proc *p, lwpid_t tid)
120744355392SDavid Xu {
120844355392SDavid Xu 	struct thread *td;
120944355392SDavid Xu 
121044355392SDavid Xu 	PROC_LOCK_ASSERT(p, MA_OWNED);
121144355392SDavid Xu 	FOREACH_THREAD_IN_PROC(p, td) {
121244355392SDavid Xu 		if (td->td_tid == tid)
121344355392SDavid Xu 			break;
121444355392SDavid Xu 	}
121544355392SDavid Xu 	return (td);
121644355392SDavid Xu }
1217cf7d9a8cSDavid Xu 
1218cf7d9a8cSDavid Xu /* Locate a thread by number; return with proc lock held. */
1219cf7d9a8cSDavid Xu struct thread *
1220cf7d9a8cSDavid Xu tdfind(lwpid_t tid, pid_t pid)
1221cf7d9a8cSDavid Xu {
1222cf7d9a8cSDavid Xu #define RUN_THRESH	16
1223cf7d9a8cSDavid Xu 	struct thread *td;
1224cf7d9a8cSDavid Xu 	int run = 0;
1225cf7d9a8cSDavid Xu 
1226cf7d9a8cSDavid Xu 	rw_rlock(&tidhash_lock);
1227cf7d9a8cSDavid Xu 	LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1228cf7d9a8cSDavid Xu 		if (td->td_tid == tid) {
1229cf7d9a8cSDavid Xu 			if (pid != -1 && td->td_proc->p_pid != pid) {
1230cf7d9a8cSDavid Xu 				td = NULL;
1231cf7d9a8cSDavid Xu 				break;
1232cf7d9a8cSDavid Xu 			}
12338e6fa660SJohn Baldwin 			PROC_LOCK(td->td_proc);
1234cf7d9a8cSDavid Xu 			if (td->td_proc->p_state == PRS_NEW) {
12358e6fa660SJohn Baldwin 				PROC_UNLOCK(td->td_proc);
1236cf7d9a8cSDavid Xu 				td = NULL;
1237cf7d9a8cSDavid Xu 				break;
1238cf7d9a8cSDavid Xu 			}
1239cf7d9a8cSDavid Xu 			if (run > RUN_THRESH) {
1240cf7d9a8cSDavid Xu 				if (rw_try_upgrade(&tidhash_lock)) {
1241cf7d9a8cSDavid Xu 					LIST_REMOVE(td, td_hash);
1242cf7d9a8cSDavid Xu 					LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1243cf7d9a8cSDavid Xu 						td, td_hash);
1244cf7d9a8cSDavid Xu 					rw_wunlock(&tidhash_lock);
1245cf7d9a8cSDavid Xu 					return (td);
1246cf7d9a8cSDavid Xu 				}
1247cf7d9a8cSDavid Xu 			}
1248cf7d9a8cSDavid Xu 			break;
1249cf7d9a8cSDavid Xu 		}
1250cf7d9a8cSDavid Xu 		run++;
1251cf7d9a8cSDavid Xu 	}
1252cf7d9a8cSDavid Xu 	rw_runlock(&tidhash_lock);
1253cf7d9a8cSDavid Xu 	return (td);
1254cf7d9a8cSDavid Xu }
1255cf7d9a8cSDavid Xu 
1256cf7d9a8cSDavid Xu void
1257cf7d9a8cSDavid Xu tidhash_add(struct thread *td)
1258cf7d9a8cSDavid Xu {
1259cf7d9a8cSDavid Xu 	rw_wlock(&tidhash_lock);
1260cf7d9a8cSDavid Xu 	LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1261cf7d9a8cSDavid Xu 	rw_wunlock(&tidhash_lock);
1262cf7d9a8cSDavid Xu }
1263cf7d9a8cSDavid Xu 
1264cf7d9a8cSDavid Xu void
1265cf7d9a8cSDavid Xu tidhash_remove(struct thread *td)
1266cf7d9a8cSDavid Xu {
1267cf7d9a8cSDavid Xu 	rw_wlock(&tidhash_lock);
1268cf7d9a8cSDavid Xu 	LIST_REMOVE(td, td_hash);
1269cf7d9a8cSDavid Xu 	rw_wunlock(&tidhash_lock);
1270cf7d9a8cSDavid Xu }
1271