xref: /freebsd/sys/kern/kern_thread.c (revision 94dd54b9a2d98bcd5bce7fbc106fd195aa5be389)
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");
85ed9e8bc4SKonstantin Belousov _Static_assert(offsetof(struct thread, td_frame) == 0x470,
86acd9f517SKonstantin Belousov     "struct thread KBI td_frame");
871565fb29SKonstantin Belousov _Static_assert(offsetof(struct thread, td_emuldata) == 0x528,
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");
93acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_filemon) == 0x3d0,
94acd9f517SKonstantin Belousov     "struct proc KBI p_filemon");
95f5cf7589SKonstantin Belousov _Static_assert(offsetof(struct proc, p_comm) == 0x3e8,
96acd9f517SKonstantin Belousov     "struct proc KBI p_comm");
97f5cf7589SKonstantin Belousov _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");
105ed9e8bc4SKonstantin Belousov _Static_assert(offsetof(struct thread, td_frame) == 0x2e8,
106acd9f517SKonstantin Belousov     "struct thread KBI td_frame");
107ed9e8bc4SKonstantin Belousov _Static_assert(offsetof(struct thread, td_emuldata) == 0x334,
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");
113acd9f517SKonstantin Belousov _Static_assert(offsetof(struct proc, p_filemon) == 0x27c,
114acd9f517SKonstantin Belousov     "struct proc KBI p_filemon");
115f5cf7589SKonstantin Belousov _Static_assert(offsetof(struct proc, p_comm) == 0x290,
116acd9f517SKonstantin Belousov     "struct proc KBI p_comm");
117f5cf7589SKonstantin Belousov _Static_assert(offsetof(struct proc, p_emuldata) == 0x31c,
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;
200*94dd54b9SKonstantin 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]);
6719104847fSDavid Xu 	sigqueue_init(&td->td_sigqueue, p);
672fd90e2edSJung-uk Kim 	callout_init(&td->td_slpcallout, 1);
67366d8df9dSDaniel Eischen 	TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
67444990b8cSJulian Elischer 	p->p_numthreads++;
67544990b8cSJulian Elischer }
67644990b8cSJulian Elischer 
677ed062c8dSJulian Elischer /*
678ed062c8dSJulian Elischer  * Called from:
679ed062c8dSJulian Elischer  *  thread_exit()
680ed062c8dSJulian Elischer  */
681d3a0bd78SJulian Elischer void
682d3a0bd78SJulian Elischer thread_unlink(struct thread *td)
683d3a0bd78SJulian Elischer {
684d3a0bd78SJulian Elischer 	struct proc *p = td->td_proc;
685d3a0bd78SJulian Elischer 
686374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
687d3a0bd78SJulian Elischer 	TAILQ_REMOVE(&p->p_threads, td, td_plist);
688d3a0bd78SJulian Elischer 	p->p_numthreads--;
689d3a0bd78SJulian Elischer 	/* could clear a few other things here */
6908460a577SJohn Birrell 	/* Must  NOT clear links to proc! */
6915c8329edSJulian Elischer }
6925c8329edSJulian Elischer 
69379799053SKonstantin Belousov static int
69479799053SKonstantin Belousov calc_remaining(struct proc *p, int mode)
69579799053SKonstantin Belousov {
69679799053SKonstantin Belousov 	int remaining;
69779799053SKonstantin Belousov 
6987b519077SKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
6997b519077SKonstantin Belousov 	PROC_SLOCK_ASSERT(p, MA_OWNED);
70079799053SKonstantin Belousov 	if (mode == SINGLE_EXIT)
70179799053SKonstantin Belousov 		remaining = p->p_numthreads;
70279799053SKonstantin Belousov 	else if (mode == SINGLE_BOUNDARY)
70379799053SKonstantin Belousov 		remaining = p->p_numthreads - p->p_boundary_count;
7046ddcc233SKonstantin Belousov 	else if (mode == SINGLE_NO_EXIT || mode == SINGLE_ALLPROC)
70579799053SKonstantin Belousov 		remaining = p->p_numthreads - p->p_suspcount;
70679799053SKonstantin Belousov 	else
70779799053SKonstantin Belousov 		panic("calc_remaining: wrong mode %d", mode);
70879799053SKonstantin Belousov 	return (remaining);
70979799053SKonstantin Belousov }
71079799053SKonstantin Belousov 
71107a9368aSKonstantin Belousov static int
71207a9368aSKonstantin Belousov remain_for_mode(int mode)
71307a9368aSKonstantin Belousov {
71407a9368aSKonstantin Belousov 
7156ddcc233SKonstantin Belousov 	return (mode == SINGLE_ALLPROC ? 0 : 1);
71607a9368aSKonstantin Belousov }
71707a9368aSKonstantin Belousov 
71807a9368aSKonstantin Belousov static int
71907a9368aSKonstantin Belousov weed_inhib(int mode, struct thread *td2, struct proc *p)
72007a9368aSKonstantin Belousov {
72107a9368aSKonstantin Belousov 	int wakeup_swapper;
72207a9368aSKonstantin Belousov 
72307a9368aSKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
72407a9368aSKonstantin Belousov 	PROC_SLOCK_ASSERT(p, MA_OWNED);
72507a9368aSKonstantin Belousov 	THREAD_LOCK_ASSERT(td2, MA_OWNED);
72607a9368aSKonstantin Belousov 
72707a9368aSKonstantin Belousov 	wakeup_swapper = 0;
72807a9368aSKonstantin Belousov 	switch (mode) {
72907a9368aSKonstantin Belousov 	case SINGLE_EXIT:
73007a9368aSKonstantin Belousov 		if (TD_IS_SUSPENDED(td2))
73184cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, true);
73207a9368aSKonstantin Belousov 		if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0)
73307a9368aSKonstantin Belousov 			wakeup_swapper |= sleepq_abort(td2, EINTR);
73407a9368aSKonstantin Belousov 		break;
73507a9368aSKonstantin Belousov 	case SINGLE_BOUNDARY:
73607a9368aSKonstantin Belousov 	case SINGLE_NO_EXIT:
73707a9368aSKonstantin Belousov 		if (TD_IS_SUSPENDED(td2) && (td2->td_flags & TDF_BOUNDARY) == 0)
73884cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
73907a9368aSKonstantin Belousov 		if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0)
74007a9368aSKonstantin Belousov 			wakeup_swapper |= sleepq_abort(td2, ERESTART);
741917dd390SKonstantin Belousov 		break;
7426ddcc233SKonstantin Belousov 	case SINGLE_ALLPROC:
7436ddcc233SKonstantin Belousov 		/*
7446ddcc233SKonstantin Belousov 		 * ALLPROC suspend tries to avoid spurious EINTR for
7456ddcc233SKonstantin Belousov 		 * threads sleeping interruptable, by suspending the
7466ddcc233SKonstantin Belousov 		 * thread directly, similarly to sig_suspend_threads().
7476ddcc233SKonstantin Belousov 		 * Since such sleep is not performed at the user
7486ddcc233SKonstantin Belousov 		 * boundary, TDF_BOUNDARY flag is not set, and TDF_ALLPROCSUSP
7496ddcc233SKonstantin Belousov 		 * is used to avoid immediate un-suspend.
7506ddcc233SKonstantin Belousov 		 */
7516ddcc233SKonstantin Belousov 		if (TD_IS_SUSPENDED(td2) && (td2->td_flags & (TDF_BOUNDARY |
7526ddcc233SKonstantin Belousov 		    TDF_ALLPROCSUSP)) == 0)
75384cdea97SKonstantin Belousov 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
7546ddcc233SKonstantin Belousov 		if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0) {
7556ddcc233SKonstantin Belousov 			if ((td2->td_flags & TDF_SBDRY) == 0) {
7566ddcc233SKonstantin Belousov 				thread_suspend_one(td2);
7576ddcc233SKonstantin Belousov 				td2->td_flags |= TDF_ALLPROCSUSP;
7586ddcc233SKonstantin Belousov 			} else {
7596ddcc233SKonstantin Belousov 				wakeup_swapper |= sleepq_abort(td2, ERESTART);
7606ddcc233SKonstantin Belousov 			}
7616ddcc233SKonstantin Belousov 		}
76207a9368aSKonstantin Belousov 		break;
76307a9368aSKonstantin Belousov 	}
76407a9368aSKonstantin Belousov 	return (wakeup_swapper);
76507a9368aSKonstantin Belousov }
76607a9368aSKonstantin Belousov 
7675215b187SJeff Roberson /*
76844990b8cSJulian Elischer  * Enforce single-threading.
76944990b8cSJulian Elischer  *
77044990b8cSJulian Elischer  * Returns 1 if the caller must abort (another thread is waiting to
77144990b8cSJulian Elischer  * exit the process or similar). Process is locked!
77244990b8cSJulian Elischer  * Returns 0 when you are successfully the only thread running.
77344990b8cSJulian Elischer  * A process has successfully single threaded in the suspend mode when
77444990b8cSJulian Elischer  * There are no threads in user mode. Threads in the kernel must be
77544990b8cSJulian Elischer  * allowed to continue until they get to the user boundary. They may even
77644990b8cSJulian Elischer  * copy out their return values and data before suspending. They may however be
777e2668f55SMaxim Konovalov  * accelerated in reaching the user boundary as we will wake up
77844990b8cSJulian Elischer  * any sleeping threads that are interruptable. (PCATCH).
77944990b8cSJulian Elischer  */
78044990b8cSJulian Elischer int
7816ddcc233SKonstantin Belousov thread_single(struct proc *p, int mode)
78244990b8cSJulian Elischer {
78344990b8cSJulian Elischer 	struct thread *td;
78444990b8cSJulian Elischer 	struct thread *td2;
785da7bbd2cSJohn Baldwin 	int remaining, wakeup_swapper;
78644990b8cSJulian Elischer 
78744990b8cSJulian Elischer 	td = curthread;
7886ddcc233SKonstantin Belousov 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
7896ddcc233SKonstantin Belousov 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
7906ddcc233SKonstantin Belousov 	    ("invalid mode %d", mode));
7916ddcc233SKonstantin Belousov 	/*
7926ddcc233SKonstantin Belousov 	 * If allowing non-ALLPROC singlethreading for non-curproc
7936ddcc233SKonstantin Belousov 	 * callers, calc_remaining() and remain_for_mode() should be
7946ddcc233SKonstantin Belousov 	 * adjusted to also account for td->td_proc != p.  For now
7956ddcc233SKonstantin Belousov 	 * this is not implemented because it is not used.
7966ddcc233SKonstantin Belousov 	 */
7976ddcc233SKonstantin Belousov 	KASSERT((mode == SINGLE_ALLPROC && td->td_proc != p) ||
7986ddcc233SKonstantin Belousov 	    (mode != SINGLE_ALLPROC && td->td_proc == p),
7996ddcc233SKonstantin Belousov 	    ("mode %d proc %p curproc %p", mode, p, td->td_proc));
80037814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
80144990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
80244990b8cSJulian Elischer 
8036ddcc233SKonstantin Belousov 	if ((p->p_flag & P_HADTHREADS) == 0 && mode != SINGLE_ALLPROC)
80444990b8cSJulian Elischer 		return (0);
80544990b8cSJulian Elischer 
806e3b9bf71SJulian Elischer 	/* Is someone already single threading? */
807906ac69dSDavid Xu 	if (p->p_singlethread != NULL && p->p_singlethread != td)
80844990b8cSJulian Elischer 		return (1);
80944990b8cSJulian Elischer 
810906ac69dSDavid Xu 	if (mode == SINGLE_EXIT) {
811906ac69dSDavid Xu 		p->p_flag |= P_SINGLE_EXIT;
812906ac69dSDavid Xu 		p->p_flag &= ~P_SINGLE_BOUNDARY;
813906ac69dSDavid Xu 	} else {
814906ac69dSDavid Xu 		p->p_flag &= ~P_SINGLE_EXIT;
815906ac69dSDavid Xu 		if (mode == SINGLE_BOUNDARY)
816906ac69dSDavid Xu 			p->p_flag |= P_SINGLE_BOUNDARY;
817906ac69dSDavid Xu 		else
818906ac69dSDavid Xu 			p->p_flag &= ~P_SINGLE_BOUNDARY;
819906ac69dSDavid Xu 	}
8206ddcc233SKonstantin Belousov 	if (mode == SINGLE_ALLPROC)
8216ddcc233SKonstantin Belousov 		p->p_flag |= P_TOTAL_STOP;
8221279572aSDavid Xu 	p->p_flag |= P_STOPPED_SINGLE;
8237b4a950aSDavid Xu 	PROC_SLOCK(p);
824112afcb2SJohn Baldwin 	p->p_singlethread = td;
82579799053SKonstantin Belousov 	remaining = calc_remaining(p, mode);
82607a9368aSKonstantin Belousov 	while (remaining != remain_for_mode(mode)) {
827bf1a3220SDavid Xu 		if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
828bf1a3220SDavid Xu 			goto stopme;
829da7bbd2cSJohn Baldwin 		wakeup_swapper = 0;
83044990b8cSJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td2) {
83144990b8cSJulian Elischer 			if (td2 == td)
83244990b8cSJulian Elischer 				continue;
833a54e85fdSJeff Roberson 			thread_lock(td2);
834b7edba77SJeff Roberson 			td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
8356ddcc233SKonstantin Belousov 			if (TD_IS_INHIBITED(td2)) {
83607a9368aSKonstantin Belousov 				wakeup_swapper |= weed_inhib(mode, td2, p);
837d8267df7SDavid Xu #ifdef SMP
8386ddcc233SKonstantin Belousov 			} else if (TD_IS_RUNNING(td2) && td != td2) {
839d8267df7SDavid Xu 				forward_signal(td2);
840d8267df7SDavid Xu #endif
8416ddcc233SKonstantin Belousov 			}
842a54e85fdSJeff Roberson 			thread_unlock(td2);
8439d102777SJulian Elischer 		}
844da7bbd2cSJohn Baldwin 		if (wakeup_swapper)
845da7bbd2cSJohn Baldwin 			kick_proc0();
84679799053SKonstantin Belousov 		remaining = calc_remaining(p, mode);
847ec008e96SDavid Xu 
8489d102777SJulian Elischer 		/*
8499d102777SJulian Elischer 		 * Maybe we suspended some threads.. was it enough?
8509d102777SJulian Elischer 		 */
85107a9368aSKonstantin Belousov 		if (remaining == remain_for_mode(mode))
8529d102777SJulian Elischer 			break;
8539d102777SJulian Elischer 
854bf1a3220SDavid Xu stopme:
85544990b8cSJulian Elischer 		/*
85644990b8cSJulian Elischer 		 * Wake us up when everyone else has suspended.
857e3b9bf71SJulian Elischer 		 * In the mean time we suspend as well.
85844990b8cSJulian Elischer 		 */
8596ddcc233SKonstantin Belousov 		thread_suspend_switch(td, p);
86079799053SKonstantin Belousov 		remaining = calc_remaining(p, mode);
86144990b8cSJulian Elischer 	}
862906ac69dSDavid Xu 	if (mode == SINGLE_EXIT) {
86391599697SJulian Elischer 		/*
8648626a0ddSKonstantin Belousov 		 * Convert the process to an unthreaded process.  The
8658626a0ddSKonstantin Belousov 		 * SINGLE_EXIT is called by exit1() or execve(), in
8668626a0ddSKonstantin Belousov 		 * both cases other threads must be retired.
86791599697SJulian Elischer 		 */
8688626a0ddSKonstantin Belousov 		KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
869ed062c8dSJulian Elischer 		p->p_singlethread = NULL;
8708626a0ddSKonstantin Belousov 		p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
871fd229b5bSKonstantin Belousov 
872fd229b5bSKonstantin Belousov 		/*
873fd229b5bSKonstantin Belousov 		 * Wait for any remaining threads to exit cpu_throw().
874fd229b5bSKonstantin Belousov 		 */
875fd229b5bSKonstantin Belousov 		while (p->p_exitthreads != 0) {
876fd229b5bSKonstantin Belousov 			PROC_SUNLOCK(p);
877fd229b5bSKonstantin Belousov 			PROC_UNLOCK(p);
878fd229b5bSKonstantin Belousov 			sched_relinquish(td);
879fd229b5bSKonstantin Belousov 			PROC_LOCK(p);
880fd229b5bSKonstantin Belousov 			PROC_SLOCK(p);
881fd229b5bSKonstantin Belousov 		}
882ac437c07SKonstantin Belousov 	} else if (mode == SINGLE_BOUNDARY) {
883ac437c07SKonstantin Belousov 		/*
884ac437c07SKonstantin Belousov 		 * Wait until all suspended threads are removed from
885ac437c07SKonstantin Belousov 		 * the processors.  The thread_suspend_check()
886ac437c07SKonstantin Belousov 		 * increments p_boundary_count while it is still
887ac437c07SKonstantin Belousov 		 * running, which makes it possible for the execve()
888ac437c07SKonstantin Belousov 		 * to destroy vmspace while our other threads are
889ac437c07SKonstantin Belousov 		 * still using the address space.
890ac437c07SKonstantin Belousov 		 *
891ac437c07SKonstantin Belousov 		 * We lock the thread, which is only allowed to
892ac437c07SKonstantin Belousov 		 * succeed after context switch code finished using
893ac437c07SKonstantin Belousov 		 * the address space.
894ac437c07SKonstantin Belousov 		 */
895ac437c07SKonstantin Belousov 		FOREACH_THREAD_IN_PROC(p, td2) {
896ac437c07SKonstantin Belousov 			if (td2 == td)
897ac437c07SKonstantin Belousov 				continue;
898ac437c07SKonstantin Belousov 			thread_lock(td2);
899ac437c07SKonstantin Belousov 			KASSERT((td2->td_flags & TDF_BOUNDARY) != 0,
900ac437c07SKonstantin Belousov 			    ("td %p not on boundary", td2));
901ac437c07SKonstantin Belousov 			KASSERT(TD_IS_SUSPENDED(td2),
902ac437c07SKonstantin Belousov 			    ("td %p is not suspended", td2));
903ac437c07SKonstantin Belousov 			thread_unlock(td2);
904ac437c07SKonstantin Belousov 		}
90591599697SJulian Elischer 	}
9067b4a950aSDavid Xu 	PROC_SUNLOCK(p);
90744990b8cSJulian Elischer 	return (0);
90844990b8cSJulian Elischer }
90944990b8cSJulian Elischer 
9108638fe7bSKonstantin Belousov bool
9118638fe7bSKonstantin Belousov thread_suspend_check_needed(void)
9128638fe7bSKonstantin Belousov {
9138638fe7bSKonstantin Belousov 	struct proc *p;
9148638fe7bSKonstantin Belousov 	struct thread *td;
9158638fe7bSKonstantin Belousov 
9168638fe7bSKonstantin Belousov 	td = curthread;
9178638fe7bSKonstantin Belousov 	p = td->td_proc;
9188638fe7bSKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
9198638fe7bSKonstantin Belousov 	return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
9208638fe7bSKonstantin Belousov 	    (td->td_dbgflags & TDB_SUSPEND) != 0));
9218638fe7bSKonstantin Belousov }
9228638fe7bSKonstantin Belousov 
92344990b8cSJulian Elischer /*
92444990b8cSJulian Elischer  * Called in from locations that can safely check to see
92544990b8cSJulian Elischer  * whether we have to suspend or at least throttle for a
92644990b8cSJulian Elischer  * single-thread event (e.g. fork).
92744990b8cSJulian Elischer  *
92844990b8cSJulian Elischer  * Such locations include userret().
92944990b8cSJulian Elischer  * If the "return_instead" argument is non zero, the thread must be able to
93044990b8cSJulian Elischer  * accept 0 (caller may continue), or 1 (caller must abort) as a result.
93144990b8cSJulian Elischer  *
93244990b8cSJulian Elischer  * The 'return_instead' argument tells the function if it may do a
93344990b8cSJulian Elischer  * thread_exit() or suspend, or whether the caller must abort and back
93444990b8cSJulian Elischer  * out instead.
93544990b8cSJulian Elischer  *
93644990b8cSJulian Elischer  * If the thread that set the single_threading request has set the
93744990b8cSJulian Elischer  * P_SINGLE_EXIT bit in the process flags then this call will never return
93844990b8cSJulian Elischer  * if 'return_instead' is false, but will exit.
93944990b8cSJulian Elischer  *
94044990b8cSJulian Elischer  * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
94144990b8cSJulian Elischer  *---------------+--------------------+---------------------
94244990b8cSJulian Elischer  *       0       | returns 0          |   returns 0 or 1
943353374b5SJohn Baldwin  *               | when ST ends       |   immediately
94444990b8cSJulian Elischer  *---------------+--------------------+---------------------
94544990b8cSJulian Elischer  *       1       | thread exits       |   returns 1
946353374b5SJohn Baldwin  *               |                    |  immediately
94744990b8cSJulian Elischer  * 0 = thread_exit() or suspension ok,
94844990b8cSJulian Elischer  * other = return error instead of stopping the thread.
94944990b8cSJulian Elischer  *
95044990b8cSJulian Elischer  * While a full suspension is under effect, even a single threading
95144990b8cSJulian Elischer  * thread would be suspended if it made this call (but it shouldn't).
95244990b8cSJulian Elischer  * This call should only be made from places where
95344990b8cSJulian Elischer  * thread_exit() would be safe as that may be the outcome unless
95444990b8cSJulian Elischer  * return_instead is set.
95544990b8cSJulian Elischer  */
95644990b8cSJulian Elischer int
95744990b8cSJulian Elischer thread_suspend_check(int return_instead)
95844990b8cSJulian Elischer {
959ecafb24bSJuli Mallett 	struct thread *td;
960ecafb24bSJuli Mallett 	struct proc *p;
96146e47c4fSKonstantin Belousov 	int wakeup_swapper;
96244990b8cSJulian Elischer 
96344990b8cSJulian Elischer 	td = curthread;
96444990b8cSJulian Elischer 	p = td->td_proc;
96537814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
96644990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
9678638fe7bSKonstantin Belousov 	while (thread_suspend_check_needed()) {
9681279572aSDavid Xu 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
96944990b8cSJulian Elischer 			KASSERT(p->p_singlethread != NULL,
97044990b8cSJulian Elischer 			    ("singlethread not set"));
97144990b8cSJulian Elischer 			/*
972e3b9bf71SJulian Elischer 			 * The only suspension in action is a
973e3b9bf71SJulian Elischer 			 * single-threading. Single threader need not stop.
974bd07998eSKonstantin Belousov 			 * It is safe to access p->p_singlethread unlocked
975bd07998eSKonstantin Belousov 			 * because it can only be set to our address by us.
97644990b8cSJulian Elischer 			 */
977e3b9bf71SJulian Elischer 			if (p->p_singlethread == td)
97844990b8cSJulian Elischer 				return (0);	/* Exempt from stopping. */
97944990b8cSJulian Elischer 		}
98045a4bfa1SDavid Xu 		if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
98194f0972bSDavid Xu 			return (EINTR);
98244990b8cSJulian Elischer 
983906ac69dSDavid Xu 		/* Should we goto user boundary if we didn't come from there? */
984906ac69dSDavid Xu 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
985906ac69dSDavid Xu 		    (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
98694f0972bSDavid Xu 			return (ERESTART);
987906ac69dSDavid Xu 
98844990b8cSJulian Elischer 		/*
9893077f938SKonstantin Belousov 		 * Ignore suspend requests if they are deferred.
990d071a6faSJohn Baldwin 		 */
9913077f938SKonstantin Belousov 		if ((td->td_flags & TDF_SBDRY) != 0) {
992d071a6faSJohn Baldwin 			KASSERT(return_instead,
993d071a6faSJohn Baldwin 			    ("TDF_SBDRY set for unsafe thread_suspend_check"));
99446e47c4fSKonstantin Belousov 			KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
99546e47c4fSKonstantin Belousov 			    (TDF_SEINTR | TDF_SERESTART),
99646e47c4fSKonstantin Belousov 			    ("both TDF_SEINTR and TDF_SERESTART"));
99746e47c4fSKonstantin Belousov 			return (TD_SBDRY_INTR(td) ? TD_SBDRY_ERRNO(td) : 0);
998d071a6faSJohn Baldwin 		}
999d071a6faSJohn Baldwin 
1000d071a6faSJohn Baldwin 		/*
100144990b8cSJulian Elischer 		 * If the process is waiting for us to exit,
100244990b8cSJulian Elischer 		 * this thread should just suicide.
10031279572aSDavid Xu 		 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
100444990b8cSJulian Elischer 		 */
1005cf7d9a8cSDavid Xu 		if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
1006cf7d9a8cSDavid Xu 			PROC_UNLOCK(p);
100791d1786fSDmitry Chagin 
100891d1786fSDmitry Chagin 			/*
100991d1786fSDmitry Chagin 			 * Allow Linux emulation layer to do some work
101091d1786fSDmitry Chagin 			 * before thread suicide.
101191d1786fSDmitry Chagin 			 */
101291d1786fSDmitry Chagin 			if (__predict_false(p->p_sysent->sv_thread_detach != NULL))
101391d1786fSDmitry Chagin 				(p->p_sysent->sv_thread_detach)(td);
10142a339d9eSKonstantin Belousov 			umtx_thread_exit(td);
1015d1e7a4a5SJohn Baldwin 			kern_thr_exit(td);
1016d1e7a4a5SJohn Baldwin 			panic("stopped thread did not exit");
1017cf7d9a8cSDavid Xu 		}
101821ecd1e9SDavid Xu 
101921ecd1e9SDavid Xu 		PROC_SLOCK(p);
102021ecd1e9SDavid Xu 		thread_stopped(p);
1021a54e85fdSJeff Roberson 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1022a54e85fdSJeff Roberson 			if (p->p_numthreads == p->p_suspcount + 1) {
1023a54e85fdSJeff Roberson 				thread_lock(p->p_singlethread);
102484cdea97SKonstantin Belousov 				wakeup_swapper = thread_unsuspend_one(
102584cdea97SKonstantin Belousov 				    p->p_singlethread, p, false);
1026a54e85fdSJeff Roberson 				thread_unlock(p->p_singlethread);
10277847a9daSJohn Baldwin 				if (wakeup_swapper)
10287847a9daSJohn Baldwin 					kick_proc0();
1029a54e85fdSJeff Roberson 			}
1030a54e85fdSJeff Roberson 		}
10313f9be10eSDavid Xu 		PROC_UNLOCK(p);
10327b4a950aSDavid Xu 		thread_lock(td);
103344990b8cSJulian Elischer 		/*
103444990b8cSJulian Elischer 		 * When a thread suspends, it just
1035ad1e7d28SJulian Elischer 		 * gets taken off all queues.
103644990b8cSJulian Elischer 		 */
103771fad9fdSJulian Elischer 		thread_suspend_one(td);
1038906ac69dSDavid Xu 		if (return_instead == 0) {
1039906ac69dSDavid Xu 			p->p_boundary_count++;
1040906ac69dSDavid Xu 			td->td_flags |= TDF_BOUNDARY;
1041cf19bf91SJulian Elischer 		}
10427b4a950aSDavid Xu 		PROC_SUNLOCK(p);
10438df78c41SJeff Roberson 		mi_switch(SW_INVOL | SWT_SUSPEND, NULL);
1044a54e85fdSJeff Roberson 		thread_unlock(td);
104544990b8cSJulian Elischer 		PROC_LOCK(p);
104644990b8cSJulian Elischer 	}
104744990b8cSJulian Elischer 	return (0);
104844990b8cSJulian Elischer }
104944990b8cSJulian Elischer 
105035c32a76SDavid Xu void
10516ddcc233SKonstantin Belousov thread_suspend_switch(struct thread *td, struct proc *p)
1052a54e85fdSJeff Roberson {
1053a54e85fdSJeff Roberson 
1054a54e85fdSJeff Roberson 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1055a54e85fdSJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
10567b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1057a54e85fdSJeff Roberson 	/*
1058a54e85fdSJeff Roberson 	 * We implement thread_suspend_one in stages here to avoid
1059a54e85fdSJeff Roberson 	 * dropping the proc lock while the thread lock is owned.
1060a54e85fdSJeff Roberson 	 */
10616ddcc233SKonstantin Belousov 	if (p == td->td_proc) {
1062a54e85fdSJeff Roberson 		thread_stopped(p);
1063a54e85fdSJeff Roberson 		p->p_suspcount++;
10646ddcc233SKonstantin Belousov 	}
10653f9be10eSDavid Xu 	PROC_UNLOCK(p);
10667b4a950aSDavid Xu 	thread_lock(td);
1067b7edba77SJeff Roberson 	td->td_flags &= ~TDF_NEEDSUSPCHK;
1068a54e85fdSJeff Roberson 	TD_SET_SUSPENDED(td);
1069c5aa6b58SJeff Roberson 	sched_sleep(td, 0);
10707b4a950aSDavid Xu 	PROC_SUNLOCK(p);
1071a54e85fdSJeff Roberson 	DROP_GIANT();
10728df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_SUSPEND, NULL);
1073a54e85fdSJeff Roberson 	thread_unlock(td);
1074a54e85fdSJeff Roberson 	PICKUP_GIANT();
1075a54e85fdSJeff Roberson 	PROC_LOCK(p);
10767b4a950aSDavid Xu 	PROC_SLOCK(p);
1077a54e85fdSJeff Roberson }
1078a54e85fdSJeff Roberson 
1079a54e85fdSJeff Roberson void
108035c32a76SDavid Xu thread_suspend_one(struct thread *td)
108135c32a76SDavid Xu {
10826ddcc233SKonstantin Belousov 	struct proc *p;
108335c32a76SDavid Xu 
10846ddcc233SKonstantin Belousov 	p = td->td_proc;
10857b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1086a54e85fdSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1087e574e444SDavid Xu 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
108835c32a76SDavid Xu 	p->p_suspcount++;
1089b7edba77SJeff Roberson 	td->td_flags &= ~TDF_NEEDSUSPCHK;
109071fad9fdSJulian Elischer 	TD_SET_SUSPENDED(td);
1091c5aa6b58SJeff Roberson 	sched_sleep(td, 0);
109235c32a76SDavid Xu }
109335c32a76SDavid Xu 
109484cdea97SKonstantin Belousov static int
109584cdea97SKonstantin Belousov thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
109635c32a76SDavid Xu {
109735c32a76SDavid Xu 
1098a54e85fdSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1099ad1e7d28SJulian Elischer 	KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
110071fad9fdSJulian Elischer 	TD_CLR_SUSPENDED(td);
11016ddcc233SKonstantin Belousov 	td->td_flags &= ~TDF_ALLPROCSUSP;
11026ddcc233SKonstantin Belousov 	if (td->td_proc == p) {
11036ddcc233SKonstantin Belousov 		PROC_SLOCK_ASSERT(p, MA_OWNED);
110435c32a76SDavid Xu 		p->p_suspcount--;
110584cdea97SKonstantin Belousov 		if (boundary && (td->td_flags & TDF_BOUNDARY) != 0) {
110684cdea97SKonstantin Belousov 			td->td_flags &= ~TDF_BOUNDARY;
110784cdea97SKonstantin Belousov 			p->p_boundary_count--;
110884cdea97SKonstantin Belousov 		}
11096ddcc233SKonstantin Belousov 	}
11107847a9daSJohn Baldwin 	return (setrunnable(td));
111135c32a76SDavid Xu }
111235c32a76SDavid Xu 
111344990b8cSJulian Elischer /*
111444990b8cSJulian Elischer  * Allow all threads blocked by single threading to continue running.
111544990b8cSJulian Elischer  */
111644990b8cSJulian Elischer void
111744990b8cSJulian Elischer thread_unsuspend(struct proc *p)
111844990b8cSJulian Elischer {
111944990b8cSJulian Elischer 	struct thread *td;
11207847a9daSJohn Baldwin 	int wakeup_swapper;
112144990b8cSJulian Elischer 
112244990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
11237b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
11247847a9daSJohn Baldwin 	wakeup_swapper = 0;
112544990b8cSJulian Elischer 	if (!P_SHOULDSTOP(p)) {
1126ad1e7d28SJulian Elischer                 FOREACH_THREAD_IN_PROC(p, td) {
1127a54e85fdSJeff Roberson 			thread_lock(td);
1128ad1e7d28SJulian Elischer 			if (TD_IS_SUSPENDED(td)) {
112984cdea97SKonstantin Belousov 				wakeup_swapper |= thread_unsuspend_one(td, p,
113084cdea97SKonstantin Belousov 				    true);
113144990b8cSJulian Elischer 			}
1132a54e85fdSJeff Roberson 			thread_unlock(td);
1133ad1e7d28SJulian Elischer 		}
113484cdea97SKonstantin Belousov 	} else if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
113584cdea97SKonstantin Belousov 	    p->p_numthreads == p->p_suspcount) {
113644990b8cSJulian Elischer 		/*
113744990b8cSJulian Elischer 		 * Stopping everything also did the job for the single
113844990b8cSJulian Elischer 		 * threading request. Now we've downgraded to single-threaded,
113944990b8cSJulian Elischer 		 * let it continue.
114044990b8cSJulian Elischer 		 */
11416ddcc233SKonstantin Belousov 		if (p->p_singlethread->td_proc == p) {
1142a54e85fdSJeff Roberson 			thread_lock(p->p_singlethread);
11436ddcc233SKonstantin Belousov 			wakeup_swapper = thread_unsuspend_one(
114484cdea97SKonstantin Belousov 			    p->p_singlethread, p, false);
1145a54e85fdSJeff Roberson 			thread_unlock(p->p_singlethread);
114644990b8cSJulian Elischer 		}
11476ddcc233SKonstantin Belousov 	}
11487847a9daSJohn Baldwin 	if (wakeup_swapper)
11497847a9daSJohn Baldwin 		kick_proc0();
115044990b8cSJulian Elischer }
115144990b8cSJulian Elischer 
1152ed062c8dSJulian Elischer /*
1153ed062c8dSJulian Elischer  * End the single threading mode..
1154ed062c8dSJulian Elischer  */
115544990b8cSJulian Elischer void
11566ddcc233SKonstantin Belousov thread_single_end(struct proc *p, int mode)
115744990b8cSJulian Elischer {
115844990b8cSJulian Elischer 	struct thread *td;
11597847a9daSJohn Baldwin 	int wakeup_swapper;
116044990b8cSJulian Elischer 
11616ddcc233SKonstantin Belousov 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
11626ddcc233SKonstantin Belousov 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
11636ddcc233SKonstantin Belousov 	    ("invalid mode %d", mode));
116444990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
11656ddcc233SKonstantin Belousov 	KASSERT((mode == SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) != 0) ||
11666ddcc233SKonstantin Belousov 	    (mode != SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) == 0),
11676ddcc233SKonstantin Belousov 	    ("mode %d does not match P_TOTAL_STOP", mode));
116884cdea97SKonstantin Belousov 	KASSERT(mode == SINGLE_ALLPROC || p->p_singlethread == curthread,
116984cdea97SKonstantin Belousov 	    ("thread_single_end from other thread %p %p",
117084cdea97SKonstantin Belousov 	    curthread, p->p_singlethread));
117184cdea97SKonstantin Belousov 	KASSERT(mode != SINGLE_BOUNDARY ||
117284cdea97SKonstantin Belousov 	    (p->p_flag & P_SINGLE_BOUNDARY) != 0,
117384cdea97SKonstantin Belousov 	    ("mis-matched SINGLE_BOUNDARY flags %x", p->p_flag));
11746ddcc233SKonstantin Belousov 	p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY |
11756ddcc233SKonstantin Belousov 	    P_TOTAL_STOP);
11767b4a950aSDavid Xu 	PROC_SLOCK(p);
117744990b8cSJulian Elischer 	p->p_singlethread = NULL;
11787847a9daSJohn Baldwin 	wakeup_swapper = 0;
117949539972SJulian Elischer 	/*
11807847a9daSJohn Baldwin 	 * If there are other threads they may now run,
118149539972SJulian Elischer 	 * unless of course there is a blanket 'stop order'
118249539972SJulian Elischer 	 * on the process. The single threader must be allowed
118349539972SJulian Elischer 	 * to continue however as this is a bad place to stop.
118449539972SJulian Elischer 	 */
11856ddcc233SKonstantin Belousov 	if (p->p_numthreads != remain_for_mode(mode) && !P_SHOULDSTOP(p)) {
1186ad1e7d28SJulian Elischer                 FOREACH_THREAD_IN_PROC(p, td) {
1187a54e85fdSJeff Roberson 			thread_lock(td);
1188ad1e7d28SJulian Elischer 			if (TD_IS_SUSPENDED(td)) {
118984cdea97SKonstantin Belousov 				wakeup_swapper |= thread_unsuspend_one(td, p,
119084cdea97SKonstantin Belousov 				    mode == SINGLE_BOUNDARY);
119144990b8cSJulian Elischer 			}
1192a54e85fdSJeff Roberson 			thread_unlock(td);
119349539972SJulian Elischer 		}
1194ad1e7d28SJulian Elischer 	}
119584cdea97SKonstantin Belousov 	KASSERT(mode != SINGLE_BOUNDARY || p->p_boundary_count == 0,
119684cdea97SKonstantin Belousov 	    ("inconsistent boundary count %d", p->p_boundary_count));
11977b4a950aSDavid Xu 	PROC_SUNLOCK(p);
11987847a9daSJohn Baldwin 	if (wakeup_swapper)
11997847a9daSJohn Baldwin 		kick_proc0();
120049539972SJulian Elischer }
12014fc21c09SDaniel Eischen 
120244355392SDavid Xu struct thread *
120344355392SDavid Xu thread_find(struct proc *p, lwpid_t tid)
120444355392SDavid Xu {
120544355392SDavid Xu 	struct thread *td;
120644355392SDavid Xu 
120744355392SDavid Xu 	PROC_LOCK_ASSERT(p, MA_OWNED);
120844355392SDavid Xu 	FOREACH_THREAD_IN_PROC(p, td) {
120944355392SDavid Xu 		if (td->td_tid == tid)
121044355392SDavid Xu 			break;
121144355392SDavid Xu 	}
121244355392SDavid Xu 	return (td);
121344355392SDavid Xu }
1214cf7d9a8cSDavid Xu 
1215cf7d9a8cSDavid Xu /* Locate a thread by number; return with proc lock held. */
1216cf7d9a8cSDavid Xu struct thread *
1217cf7d9a8cSDavid Xu tdfind(lwpid_t tid, pid_t pid)
1218cf7d9a8cSDavid Xu {
1219cf7d9a8cSDavid Xu #define RUN_THRESH	16
1220cf7d9a8cSDavid Xu 	struct thread *td;
1221cf7d9a8cSDavid Xu 	int run = 0;
1222cf7d9a8cSDavid Xu 
1223cf7d9a8cSDavid Xu 	rw_rlock(&tidhash_lock);
1224cf7d9a8cSDavid Xu 	LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1225cf7d9a8cSDavid Xu 		if (td->td_tid == tid) {
1226cf7d9a8cSDavid Xu 			if (pid != -1 && td->td_proc->p_pid != pid) {
1227cf7d9a8cSDavid Xu 				td = NULL;
1228cf7d9a8cSDavid Xu 				break;
1229cf7d9a8cSDavid Xu 			}
12308e6fa660SJohn Baldwin 			PROC_LOCK(td->td_proc);
1231cf7d9a8cSDavid Xu 			if (td->td_proc->p_state == PRS_NEW) {
12328e6fa660SJohn Baldwin 				PROC_UNLOCK(td->td_proc);
1233cf7d9a8cSDavid Xu 				td = NULL;
1234cf7d9a8cSDavid Xu 				break;
1235cf7d9a8cSDavid Xu 			}
1236cf7d9a8cSDavid Xu 			if (run > RUN_THRESH) {
1237cf7d9a8cSDavid Xu 				if (rw_try_upgrade(&tidhash_lock)) {
1238cf7d9a8cSDavid Xu 					LIST_REMOVE(td, td_hash);
1239cf7d9a8cSDavid Xu 					LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1240cf7d9a8cSDavid Xu 						td, td_hash);
1241cf7d9a8cSDavid Xu 					rw_wunlock(&tidhash_lock);
1242cf7d9a8cSDavid Xu 					return (td);
1243cf7d9a8cSDavid Xu 				}
1244cf7d9a8cSDavid Xu 			}
1245cf7d9a8cSDavid Xu 			break;
1246cf7d9a8cSDavid Xu 		}
1247cf7d9a8cSDavid Xu 		run++;
1248cf7d9a8cSDavid Xu 	}
1249cf7d9a8cSDavid Xu 	rw_runlock(&tidhash_lock);
1250cf7d9a8cSDavid Xu 	return (td);
1251cf7d9a8cSDavid Xu }
1252cf7d9a8cSDavid Xu 
1253cf7d9a8cSDavid Xu void
1254cf7d9a8cSDavid Xu tidhash_add(struct thread *td)
1255cf7d9a8cSDavid Xu {
1256cf7d9a8cSDavid Xu 	rw_wlock(&tidhash_lock);
1257cf7d9a8cSDavid Xu 	LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1258cf7d9a8cSDavid Xu 	rw_wunlock(&tidhash_lock);
1259cf7d9a8cSDavid Xu }
1260cf7d9a8cSDavid Xu 
1261cf7d9a8cSDavid Xu void
1262cf7d9a8cSDavid Xu tidhash_remove(struct thread *td)
1263cf7d9a8cSDavid Xu {
1264cf7d9a8cSDavid Xu 	rw_wlock(&tidhash_lock);
1265cf7d9a8cSDavid Xu 	LIST_REMOVE(td, td_hash);
1266cf7d9a8cSDavid Xu 	rw_wunlock(&tidhash_lock);
1267cf7d9a8cSDavid Xu }
1268