xref: /freebsd/sys/kern/kern_thread.c (revision 8638fe7bea3efc18bf04517d1993c8dfa448e571)
19454b2d8SWarner Losh /*-
244990b8cSJulian Elischer  * Copyright (C) 2001 Julian Elischer <julian@freebsd.org>.
344990b8cSJulian Elischer  *  All rights reserved.
444990b8cSJulian Elischer  *
544990b8cSJulian Elischer  * Redistribution and use in source and binary forms, with or without
644990b8cSJulian Elischer  * modification, are permitted provided that the following conditions
744990b8cSJulian Elischer  * are met:
844990b8cSJulian Elischer  * 1. Redistributions of source code must retain the above copyright
944990b8cSJulian Elischer  *    notice(s), this list of conditions and the following disclaimer as
1044990b8cSJulian Elischer  *    the first lines of this file unmodified other than the possible
1144990b8cSJulian Elischer  *    addition of one or more copyright notices.
1244990b8cSJulian Elischer  * 2. Redistributions in binary form must reproduce the above copyright
1344990b8cSJulian Elischer  *    notice(s), this list of conditions and the following disclaimer in the
1444990b8cSJulian Elischer  *    documentation and/or other materials provided with the distribution.
1544990b8cSJulian Elischer  *
1644990b8cSJulian Elischer  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
1744990b8cSJulian Elischer  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1844990b8cSJulian Elischer  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1944990b8cSJulian Elischer  * DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
2044990b8cSJulian Elischer  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
2144990b8cSJulian Elischer  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2244990b8cSJulian Elischer  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2344990b8cSJulian Elischer  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2444990b8cSJulian Elischer  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2544990b8cSJulian Elischer  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
2644990b8cSJulian Elischer  * DAMAGE.
2744990b8cSJulian Elischer  */
2844990b8cSJulian Elischer 
293d06b4b3SAttilio Rao #include "opt_witness.h"
3016d95d4fSJoseph Koshy #include "opt_hwpmc_hooks.h"
313d06b4b3SAttilio Rao 
32677b542eSDavid E. O'Brien #include <sys/cdefs.h>
33677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
34677b542eSDavid E. O'Brien 
3544990b8cSJulian Elischer #include <sys/param.h>
3644990b8cSJulian Elischer #include <sys/systm.h>
3744990b8cSJulian Elischer #include <sys/kernel.h>
3844990b8cSJulian Elischer #include <sys/lock.h>
3944990b8cSJulian Elischer #include <sys/mutex.h>
4044990b8cSJulian Elischer #include <sys/proc.h>
418f0e9130SKonstantin Belousov #include <sys/rangelock.h>
42e170bfdaSDavid Xu #include <sys/resourcevar.h>
43b3e9e682SRyan Stone #include <sys/sdt.h>
4494e0a4cdSJulian Elischer #include <sys/smp.h>
45de028f5aSJeff Roberson #include <sys/sched.h>
4644f3b092SJohn Baldwin #include <sys/sleepqueue.h>
47ace8398dSJeff Roberson #include <sys/selinfo.h>
48961a7b24SJohn Baldwin #include <sys/turnstile.h>
4944990b8cSJulian Elischer #include <sys/ktr.h>
50cf7d9a8cSDavid Xu #include <sys/rwlock.h>
51bc8e6d81SDavid Xu #include <sys/umtx.h>
52d7f687fcSJeff Roberson #include <sys/cpuset.h>
5316d95d4fSJoseph Koshy #ifdef	HWPMC_HOOKS
5416d95d4fSJoseph Koshy #include <sys/pmckern.h>
5516d95d4fSJoseph Koshy #endif
5644990b8cSJulian Elischer 
57911b84b0SRobert Watson #include <security/audit/audit.h>
58911b84b0SRobert Watson 
5944990b8cSJulian Elischer #include <vm/vm.h>
6049a2507bSAlan Cox #include <vm/vm_extern.h>
6144990b8cSJulian Elischer #include <vm/uma.h>
62b209f889SRandall Stewart #include <sys/eventhandler.h>
6302fb42b0SPeter Wemm 
64b3e9e682SRyan Stone SDT_PROVIDER_DECLARE(proc);
65d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(proc, , , lwp__exit);
66b3e9e682SRyan Stone 
67b3e9e682SRyan Stone 
688460a577SJohn Birrell /*
698460a577SJohn Birrell  * thread related storage.
708460a577SJohn Birrell  */
7144990b8cSJulian Elischer static uma_zone_t thread_zone;
7244990b8cSJulian Elischer 
735215b187SJeff Roberson TAILQ_HEAD(, thread) zombie_threads = TAILQ_HEAD_INITIALIZER(zombie_threads);
74c8790f5dSAttilio Rao static struct mtx zombie_lock;
75a54e85fdSJeff Roberson MTX_SYSINIT(zombie_lock, &zombie_lock, "zombie lock", MTX_SPIN);
7644990b8cSJulian Elischer 
77ff8fbcffSJeff Roberson static void thread_zombie(struct thread *);
78ff8fbcffSJeff Roberson 
79ec6ea5e8SDavid Xu #define TID_BUFFER_SIZE	1024
80ec6ea5e8SDavid Xu 
81fdcac928SMarcel Moolenaar struct mtx tid_lock;
821ea7a6f8SPoul-Henning Kamp static struct unrhdr *tid_unrhdr;
83ec6ea5e8SDavid Xu static lwpid_t tid_buffer[TID_BUFFER_SIZE];
84ec6ea5e8SDavid Xu static int tid_head, tid_tail;
85cf7d9a8cSDavid Xu static MALLOC_DEFINE(M_TIDHASH, "tidhash", "thread hash");
86cf7d9a8cSDavid Xu 
87cf7d9a8cSDavid Xu struct	tidhashhead *tidhashtbl;
88cf7d9a8cSDavid Xu u_long	tidhash;
89cf7d9a8cSDavid Xu struct	rwlock tidhash_lock;
90cf7d9a8cSDavid Xu 
91ec6ea5e8SDavid Xu static lwpid_t
92ec6ea5e8SDavid Xu tid_alloc(void)
93ec6ea5e8SDavid Xu {
94ec6ea5e8SDavid Xu 	lwpid_t	tid;
95ec6ea5e8SDavid Xu 
96ec6ea5e8SDavid Xu 	tid = alloc_unr(tid_unrhdr);
97ec6ea5e8SDavid Xu 	if (tid != -1)
98ec6ea5e8SDavid Xu 		return (tid);
99ec6ea5e8SDavid Xu 	mtx_lock(&tid_lock);
100ec6ea5e8SDavid Xu 	if (tid_head == tid_tail) {
101ec6ea5e8SDavid Xu 		mtx_unlock(&tid_lock);
102ec6ea5e8SDavid Xu 		return (-1);
103ec6ea5e8SDavid Xu 	}
10494cb3545SKonstantin Belousov 	tid = tid_buffer[tid_head];
10594cb3545SKonstantin Belousov 	tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
106ec6ea5e8SDavid Xu 	mtx_unlock(&tid_lock);
107ec6ea5e8SDavid Xu 	return (tid);
108ec6ea5e8SDavid Xu }
109ec6ea5e8SDavid Xu 
110ec6ea5e8SDavid Xu static void
111ec6ea5e8SDavid Xu tid_free(lwpid_t tid)
112ec6ea5e8SDavid Xu {
113ec6ea5e8SDavid Xu 	lwpid_t tmp_tid = -1;
114ec6ea5e8SDavid Xu 
115ec6ea5e8SDavid Xu 	mtx_lock(&tid_lock);
116ec6ea5e8SDavid Xu 	if ((tid_tail + 1) % TID_BUFFER_SIZE == tid_head) {
11794cb3545SKonstantin Belousov 		tmp_tid = tid_buffer[tid_head];
11894cb3545SKonstantin Belousov 		tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
119ec6ea5e8SDavid Xu 	}
12094cb3545SKonstantin Belousov 	tid_buffer[tid_tail] = tid;
12194cb3545SKonstantin Belousov 	tid_tail = (tid_tail + 1) % TID_BUFFER_SIZE;
122ec6ea5e8SDavid Xu 	mtx_unlock(&tid_lock);
123ec6ea5e8SDavid Xu 	if (tmp_tid != -1)
124ec6ea5e8SDavid Xu 		free_unr(tid_unrhdr, tmp_tid);
125ec6ea5e8SDavid Xu }
126ec6ea5e8SDavid Xu 
127fdcac928SMarcel Moolenaar /*
128696058c3SJulian Elischer  * Prepare a thread for use.
12944990b8cSJulian Elischer  */
130b23f72e9SBrian Feldman static int
131b23f72e9SBrian Feldman thread_ctor(void *mem, int size, void *arg, int flags)
13244990b8cSJulian Elischer {
13344990b8cSJulian Elischer 	struct thread	*td;
13444990b8cSJulian Elischer 
13544990b8cSJulian Elischer 	td = (struct thread *)mem;
13671fad9fdSJulian Elischer 	td->td_state = TDS_INACTIVE;
137060563ecSJulian Elischer 	td->td_oncpu = NOCPU;
1386c27c603SJuli Mallett 
139ec6ea5e8SDavid Xu 	td->td_tid = tid_alloc();
140773eff9dSPoul-Henning Kamp 
1416c27c603SJuli Mallett 	/*
1426c27c603SJuli Mallett 	 * Note that td_critnest begins life as 1 because the thread is not
1436c27c603SJuli Mallett 	 * running and is thereby implicitly waiting to be on the receiving
144a54e85fdSJeff Roberson 	 * end of a context switch.
1456c27c603SJuli Mallett 	 */
146139b7550SJohn Baldwin 	td->td_critnest = 1;
147acbe332aSDavid Xu 	td->td_lend_user_pri = PRI_MAX;
148b209f889SRandall Stewart 	EVENTHANDLER_INVOKE(thread_ctor, td);
149911b84b0SRobert Watson #ifdef AUDIT
150911b84b0SRobert Watson 	audit_thread_alloc(td);
151911b84b0SRobert Watson #endif
152d10183d9SDavid Xu 	umtx_thread_alloc(td);
153b23f72e9SBrian Feldman 	return (0);
15444990b8cSJulian Elischer }
15544990b8cSJulian Elischer 
15644990b8cSJulian Elischer /*
15744990b8cSJulian Elischer  * Reclaim a thread after use.
15844990b8cSJulian Elischer  */
15944990b8cSJulian Elischer static void
16044990b8cSJulian Elischer thread_dtor(void *mem, int size, void *arg)
16144990b8cSJulian Elischer {
16244990b8cSJulian Elischer 	struct thread *td;
16344990b8cSJulian Elischer 
16444990b8cSJulian Elischer 	td = (struct thread *)mem;
16544990b8cSJulian Elischer 
16644990b8cSJulian Elischer #ifdef INVARIANTS
16744990b8cSJulian Elischer 	/* Verify that this thread is in a safe state to free. */
16844990b8cSJulian Elischer 	switch (td->td_state) {
16971fad9fdSJulian Elischer 	case TDS_INHIBITED:
17071fad9fdSJulian Elischer 	case TDS_RUNNING:
17171fad9fdSJulian Elischer 	case TDS_CAN_RUN:
17244990b8cSJulian Elischer 	case TDS_RUNQ:
17344990b8cSJulian Elischer 		/*
17444990b8cSJulian Elischer 		 * We must never unlink a thread that is in one of
17544990b8cSJulian Elischer 		 * these states, because it is currently active.
17644990b8cSJulian Elischer 		 */
17744990b8cSJulian Elischer 		panic("bad state for thread unlinking");
17844990b8cSJulian Elischer 		/* NOTREACHED */
17971fad9fdSJulian Elischer 	case TDS_INACTIVE:
18044990b8cSJulian Elischer 		break;
18144990b8cSJulian Elischer 	default:
18244990b8cSJulian Elischer 		panic("bad thread state");
18344990b8cSJulian Elischer 		/* NOTREACHED */
18444990b8cSJulian Elischer 	}
18544990b8cSJulian Elischer #endif
1866e8525ceSRobert Watson #ifdef AUDIT
1876e8525ceSRobert Watson 	audit_thread_free(td);
1886e8525ceSRobert Watson #endif
1891ba4a712SPawel Jakub Dawidek 	/* Free all OSD associated to this thread. */
1901ba4a712SPawel Jakub Dawidek 	osd_thread_exit(td);
1911ba4a712SPawel Jakub Dawidek 
192b209f889SRandall Stewart 	EVENTHANDLER_INVOKE(thread_dtor, td);
193ec6ea5e8SDavid Xu 	tid_free(td->td_tid);
19444990b8cSJulian Elischer }
19544990b8cSJulian Elischer 
19644990b8cSJulian Elischer /*
19744990b8cSJulian Elischer  * Initialize type-stable parts of a thread (when newly created).
19844990b8cSJulian Elischer  */
199b23f72e9SBrian Feldman static int
200b23f72e9SBrian Feldman thread_init(void *mem, int size, int flags)
20144990b8cSJulian Elischer {
20244990b8cSJulian Elischer 	struct thread *td;
20344990b8cSJulian Elischer 
20444990b8cSJulian Elischer 	td = (struct thread *)mem;
205247aba24SMarcel Moolenaar 
20644f3b092SJohn Baldwin 	td->td_sleepqueue = sleepq_alloc();
207961a7b24SJohn Baldwin 	td->td_turnstile = turnstile_alloc();
2088f0e9130SKonstantin Belousov 	td->td_rlqe = NULL;
209b209f889SRandall Stewart 	EVENTHANDLER_INVOKE(thread_init, td);
210de028f5aSJeff Roberson 	td->td_sched = (struct td_sched *)&td[1];
211d10183d9SDavid Xu 	umtx_thread_init(td);
21289b57fcfSKonstantin Belousov 	td->td_kstack = 0;
213b23f72e9SBrian Feldman 	return (0);
21444990b8cSJulian Elischer }
21544990b8cSJulian Elischer 
21644990b8cSJulian Elischer /*
21744990b8cSJulian Elischer  * Tear down type-stable parts of a thread (just before being discarded).
21844990b8cSJulian Elischer  */
21944990b8cSJulian Elischer static void
22044990b8cSJulian Elischer thread_fini(void *mem, int size)
22144990b8cSJulian Elischer {
22244990b8cSJulian Elischer 	struct thread *td;
22344990b8cSJulian Elischer 
22444990b8cSJulian Elischer 	td = (struct thread *)mem;
225b209f889SRandall Stewart 	EVENTHANDLER_INVOKE(thread_fini, td);
2268f0e9130SKonstantin Belousov 	rlqentry_free(td->td_rlqe);
227961a7b24SJohn Baldwin 	turnstile_free(td->td_turnstile);
22844f3b092SJohn Baldwin 	sleepq_free(td->td_sleepqueue);
229d10183d9SDavid Xu 	umtx_thread_fini(td);
230ace8398dSJeff Roberson 	seltdfini(td);
23144990b8cSJulian Elischer }
2325215b187SJeff Roberson 
2335c8329edSJulian Elischer /*
2345215b187SJeff Roberson  * For a newly created process,
2355215b187SJeff Roberson  * link up all the structures and its initial threads etc.
236ed062c8dSJulian Elischer  * called from:
237e7d939bdSMarcel Moolenaar  * {arch}/{arch}/machdep.c   {arch}_init(), init386() etc.
238ed062c8dSJulian Elischer  * proc_dtor() (should go away)
239ed062c8dSJulian Elischer  * proc_init()
2405c8329edSJulian Elischer  */
2415c8329edSJulian Elischer void
24289b57fcfSKonstantin Belousov proc_linkup0(struct proc *p, struct thread *td)
24389b57fcfSKonstantin Belousov {
24489b57fcfSKonstantin Belousov 	TAILQ_INIT(&p->p_threads);	     /* all threads in proc */
24589b57fcfSKonstantin Belousov 	proc_linkup(p, td);
24689b57fcfSKonstantin Belousov }
24789b57fcfSKonstantin Belousov 
24889b57fcfSKonstantin Belousov void
2498460a577SJohn Birrell proc_linkup(struct proc *p, struct thread *td)
2505c8329edSJulian Elischer {
251a54e85fdSJeff Roberson 
2529104847fSDavid Xu 	sigqueue_init(&p->p_sigqueue, p);
253ebceaf6dSDavid Xu 	p->p_ksi = ksiginfo_alloc(1);
254ebceaf6dSDavid Xu 	if (p->p_ksi != NULL) {
2555c474517SDavid Xu 		/* XXX p_ksi may be null if ksiginfo zone is not ready */
256ebceaf6dSDavid Xu 		p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
257ebceaf6dSDavid Xu 	}
258b2f92ef9SDavid Xu 	LIST_INIT(&p->p_mqnotifier);
2595c8329edSJulian Elischer 	p->p_numthreads = 0;
2608460a577SJohn Birrell 	thread_link(td, p);
2615c8329edSJulian Elischer }
2625c8329edSJulian Elischer 
2635c8329edSJulian Elischer /*
26444990b8cSJulian Elischer  * Initialize global thread allocation resources.
26544990b8cSJulian Elischer  */
26644990b8cSJulian Elischer void
26744990b8cSJulian Elischer threadinit(void)
26844990b8cSJulian Elischer {
26944990b8cSJulian Elischer 
2701ea7a6f8SPoul-Henning Kamp 	mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
27102c6fc21SKonstantin Belousov 
27202c6fc21SKonstantin Belousov 	/*
273abce621cSKonstantin Belousov 	 * pid_max cannot be greater than PID_MAX.
27402c6fc21SKonstantin Belousov 	 * leave one number for thread0.
27502c6fc21SKonstantin Belousov 	 */
2766829a5c5SJulian Elischer 	tid_unrhdr = new_unrhdr(PID_MAX + 2, INT_MAX, &tid_lock);
2771ea7a6f8SPoul-Henning Kamp 
278de028f5aSJeff Roberson 	thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
27944990b8cSJulian Elischer 	    thread_ctor, thread_dtor, thread_init, thread_fini,
2804649e92bSJohn Baldwin 	    16 - 1, 0);
281cf7d9a8cSDavid Xu 	tidhashtbl = hashinit(maxproc / 2, M_TIDHASH, &tidhash);
282cf7d9a8cSDavid Xu 	rw_init(&tidhash_lock, "tidhash");
28344990b8cSJulian Elischer }
28444990b8cSJulian Elischer 
28544990b8cSJulian Elischer /*
286ff8fbcffSJeff Roberson  * Place an unused thread on the zombie list.
287ad1e7d28SJulian Elischer  * Use the slpq as that must be unused by now.
28844990b8cSJulian Elischer  */
28944990b8cSJulian Elischer void
290ff8fbcffSJeff Roberson thread_zombie(struct thread *td)
29144990b8cSJulian Elischer {
292a54e85fdSJeff Roberson 	mtx_lock_spin(&zombie_lock);
293ad1e7d28SJulian Elischer 	TAILQ_INSERT_HEAD(&zombie_threads, td, td_slpq);
294a54e85fdSJeff Roberson 	mtx_unlock_spin(&zombie_lock);
29544990b8cSJulian Elischer }
29644990b8cSJulian Elischer 
2975c8329edSJulian Elischer /*
298ff8fbcffSJeff Roberson  * Release a thread that has exited after cpu_throw().
299ff8fbcffSJeff Roberson  */
300ff8fbcffSJeff Roberson void
301ff8fbcffSJeff Roberson thread_stash(struct thread *td)
302ff8fbcffSJeff Roberson {
303ff8fbcffSJeff Roberson 	atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
304ff8fbcffSJeff Roberson 	thread_zombie(td);
305ff8fbcffSJeff Roberson }
306ff8fbcffSJeff Roberson 
307ff8fbcffSJeff Roberson /*
3086617724cSJeff Roberson  * Reap zombie resources.
30944990b8cSJulian Elischer  */
31044990b8cSJulian Elischer void
31144990b8cSJulian Elischer thread_reap(void)
31244990b8cSJulian Elischer {
3135c8329edSJulian Elischer 	struct thread *td_first, *td_next;
31444990b8cSJulian Elischer 
31544990b8cSJulian Elischer 	/*
3165215b187SJeff Roberson 	 * Don't even bother to lock if none at this instant,
3175215b187SJeff Roberson 	 * we really don't care about the next instant..
31844990b8cSJulian Elischer 	 */
3198460a577SJohn Birrell 	if (!TAILQ_EMPTY(&zombie_threads)) {
320a54e85fdSJeff Roberson 		mtx_lock_spin(&zombie_lock);
3215c8329edSJulian Elischer 		td_first = TAILQ_FIRST(&zombie_threads);
3225c8329edSJulian Elischer 		if (td_first)
3235c8329edSJulian Elischer 			TAILQ_INIT(&zombie_threads);
324a54e85fdSJeff Roberson 		mtx_unlock_spin(&zombie_lock);
3255c8329edSJulian Elischer 		while (td_first) {
326ad1e7d28SJulian Elischer 			td_next = TAILQ_NEXT(td_first, td_slpq);
3275215b187SJeff Roberson 			if (td_first->td_ucred)
3285215b187SJeff Roberson 				crfree(td_first->td_ucred);
3295c8329edSJulian Elischer 			thread_free(td_first);
3305c8329edSJulian Elischer 			td_first = td_next;
33144990b8cSJulian Elischer 		}
33244990b8cSJulian Elischer 	}
333ed062c8dSJulian Elischer }
33444990b8cSJulian Elischer 
3354f0db5e0SJulian Elischer /*
33644990b8cSJulian Elischer  * Allocate a thread.
33744990b8cSJulian Elischer  */
33844990b8cSJulian Elischer struct thread *
3398a945d10SKonstantin Belousov thread_alloc(int pages)
34044990b8cSJulian Elischer {
34189b57fcfSKonstantin Belousov 	struct thread *td;
3428460a577SJohn Birrell 
34344990b8cSJulian Elischer 	thread_reap(); /* check if any zombies to get */
34489b57fcfSKonstantin Belousov 
34589b57fcfSKonstantin Belousov 	td = (struct thread *)uma_zalloc(thread_zone, M_WAITOK);
34689b57fcfSKonstantin Belousov 	KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
3478a945d10SKonstantin Belousov 	if (!vm_thread_new(td, pages)) {
34889b57fcfSKonstantin Belousov 		uma_zfree(thread_zone, td);
34989b57fcfSKonstantin Belousov 		return (NULL);
35089b57fcfSKonstantin Belousov 	}
3510c3967e7SMarcel Moolenaar 	cpu_thread_alloc(td);
35289b57fcfSKonstantin Belousov 	return (td);
35344990b8cSJulian Elischer }
35444990b8cSJulian Elischer 
3558a945d10SKonstantin Belousov int
3568a945d10SKonstantin Belousov thread_alloc_stack(struct thread *td, int pages)
3578a945d10SKonstantin Belousov {
3588a945d10SKonstantin Belousov 
3598a945d10SKonstantin Belousov 	KASSERT(td->td_kstack == 0,
3608a945d10SKonstantin Belousov 	    ("thread_alloc_stack called on a thread with kstack"));
3618a945d10SKonstantin Belousov 	if (!vm_thread_new(td, pages))
3628a945d10SKonstantin Belousov 		return (0);
3638a945d10SKonstantin Belousov 	cpu_thread_alloc(td);
3648a945d10SKonstantin Belousov 	return (1);
3658a945d10SKonstantin Belousov }
3664f0db5e0SJulian Elischer 
3674f0db5e0SJulian Elischer /*
36844990b8cSJulian Elischer  * Deallocate a thread.
36944990b8cSJulian Elischer  */
37044990b8cSJulian Elischer void
37144990b8cSJulian Elischer thread_free(struct thread *td)
37244990b8cSJulian Elischer {
3732e6b8de4SJeff Roberson 
3742e6b8de4SJeff Roberson 	lock_profile_thread_exit(td);
37545aea8deSJeff Roberson 	if (td->td_cpuset)
376d7f687fcSJeff Roberson 		cpuset_rel(td->td_cpuset);
377d7f687fcSJeff Roberson 	td->td_cpuset = NULL;
3780c3967e7SMarcel Moolenaar 	cpu_thread_free(td);
37989b57fcfSKonstantin Belousov 	if (td->td_kstack != 0)
38089b57fcfSKonstantin Belousov 		vm_thread_dispose(td);
38144990b8cSJulian Elischer 	uma_zfree(thread_zone, td);
38244990b8cSJulian Elischer }
38344990b8cSJulian Elischer 
38444990b8cSJulian Elischer /*
38544990b8cSJulian Elischer  * Discard the current thread and exit from its context.
38694e0a4cdSJulian Elischer  * Always called with scheduler locked.
38744990b8cSJulian Elischer  *
38844990b8cSJulian Elischer  * Because we can't free a thread while we're operating under its context,
389696058c3SJulian Elischer  * push the current thread into our CPU's deadthread holder. This means
390696058c3SJulian Elischer  * we needn't worry about someone else grabbing our context before we
3916617724cSJeff Roberson  * do a cpu_throw().
39244990b8cSJulian Elischer  */
39344990b8cSJulian Elischer void
39444990b8cSJulian Elischer thread_exit(void)
39544990b8cSJulian Elischer {
3967e3a96eaSJohn Baldwin 	uint64_t runtime, new_switchtime;
39744990b8cSJulian Elischer 	struct thread *td;
3981c4bcd05SJeff Roberson 	struct thread *td2;
39944990b8cSJulian Elischer 	struct proc *p;
4007847a9daSJohn Baldwin 	int wakeup_swapper;
40144990b8cSJulian Elischer 
40244990b8cSJulian Elischer 	td = curthread;
40344990b8cSJulian Elischer 	p = td->td_proc;
40444990b8cSJulian Elischer 
405a54e85fdSJeff Roberson 	PROC_SLOCK_ASSERT(p, MA_OWNED);
406ed062c8dSJulian Elischer 	mtx_assert(&Giant, MA_NOTOWNED);
407a54e85fdSJeff Roberson 
40844990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
409ed062c8dSJulian Elischer 	KASSERT(p != NULL, ("thread exiting without a process"));
410cc701b73SRobert Watson 	CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
411e01eafefSJulian Elischer 	    (long)p->p_pid, td->td_name);
4129104847fSDavid Xu 	KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
41344990b8cSJulian Elischer 
41489964dd2SRobert Watson #ifdef AUDIT
41589964dd2SRobert Watson 	AUDIT_SYSCALL_EXIT(0, td);
41689964dd2SRobert Watson #endif
417d10183d9SDavid Xu 	umtx_thread_exit(td);
418ed062c8dSJulian Elischer 	/*
419ed062c8dSJulian Elischer 	 * drop FPU & debug register state storage, or any other
420ed062c8dSJulian Elischer 	 * architecture specific resources that
421ed062c8dSJulian Elischer 	 * would not be on a new untouched process.
422ed062c8dSJulian Elischer 	 */
42344990b8cSJulian Elischer 	cpu_thread_exit(td);	/* XXXSMP */
42444990b8cSJulian Elischer 
425ed062c8dSJulian Elischer 	/*
4261faf202eSJulian Elischer 	 * The last thread is left attached to the process
4271faf202eSJulian Elischer 	 * So that the whole bundle gets recycled. Skip
428ed062c8dSJulian Elischer 	 * all this stuff if we never had threads.
429ed062c8dSJulian Elischer 	 * EXIT clears all sign of other threads when
430ed062c8dSJulian Elischer 	 * it goes to single threading, so the last thread always
431ed062c8dSJulian Elischer 	 * takes the short path.
4321faf202eSJulian Elischer 	 */
433ed062c8dSJulian Elischer 	if (p->p_flag & P_HADTHREADS) {
4341faf202eSJulian Elischer 		if (p->p_numthreads > 1) {
435fd229b5bSKonstantin Belousov 			atomic_add_int(&td->td_proc->p_exitthreads, 1);
436d3a0bd78SJulian Elischer 			thread_unlink(td);
4371c4bcd05SJeff Roberson 			td2 = FIRST_THREAD_IN_PROC(p);
4381c4bcd05SJeff Roberson 			sched_exit_thread(td2, td);
439ed062c8dSJulian Elischer 
440ed062c8dSJulian Elischer 			/*
44144990b8cSJulian Elischer 			 * The test below is NOT true if we are the
4429182554aSKonstantin Belousov 			 * sole exiting thread. P_STOPPED_SINGLE is unset
44344990b8cSJulian Elischer 			 * in exit1() after it is the only survivor.
44444990b8cSJulian Elischer 			 */
4451279572aSDavid Xu 			if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
44644990b8cSJulian Elischer 				if (p->p_numthreads == p->p_suspcount) {
447a54e85fdSJeff Roberson 					thread_lock(p->p_singlethread);
4487847a9daSJohn Baldwin 					wakeup_swapper = thread_unsuspend_one(
4497847a9daSJohn Baldwin 						p->p_singlethread);
450a54e85fdSJeff Roberson 					thread_unlock(p->p_singlethread);
4517847a9daSJohn Baldwin 					if (wakeup_swapper)
4527847a9daSJohn Baldwin 						kick_proc0();
45344990b8cSJulian Elischer 				}
45444990b8cSJulian Elischer 			}
45548bfcdddSJulian Elischer 
456696058c3SJulian Elischer 			PCPU_SET(deadthread, td);
4571faf202eSJulian Elischer 		} else {
458ed062c8dSJulian Elischer 			/*
459ed062c8dSJulian Elischer 			 * The last thread is exiting.. but not through exit()
460ed062c8dSJulian Elischer 			 */
461ed062c8dSJulian Elischer 			panic ("thread_exit: Last thread exiting on its own");
462ed062c8dSJulian Elischer 		}
4631faf202eSJulian Elischer 	}
46416d95d4fSJoseph Koshy #ifdef	HWPMC_HOOKS
46516d95d4fSJoseph Koshy 	/*
46616d95d4fSJoseph Koshy 	 * If this thread is part of a process that is being tracked by hwpmc(4),
46716d95d4fSJoseph Koshy 	 * inform the module of the thread's impending exit.
46816d95d4fSJoseph Koshy 	 */
46916d95d4fSJoseph Koshy 	if (PMC_PROC_IS_USING_PMCS(td->td_proc))
47016d95d4fSJoseph Koshy 		PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
47116d95d4fSJoseph Koshy #endif
472a54e85fdSJeff Roberson 	PROC_UNLOCK(p);
4735c7bebf9SKonstantin Belousov 	PROC_STATLOCK(p);
4745c7bebf9SKonstantin Belousov 	thread_lock(td);
4755c7bebf9SKonstantin Belousov 	PROC_SUNLOCK(p);
4767e3a96eaSJohn Baldwin 
4777e3a96eaSJohn Baldwin 	/* Do the same timestamp bookkeeping that mi_switch() would do. */
4787e3a96eaSJohn Baldwin 	new_switchtime = cpu_ticks();
4797e3a96eaSJohn Baldwin 	runtime = new_switchtime - PCPU_GET(switchtime);
4807e3a96eaSJohn Baldwin 	td->td_runtime += runtime;
4817e3a96eaSJohn Baldwin 	td->td_incruntime += runtime;
4827e3a96eaSJohn Baldwin 	PCPU_SET(switchtime, new_switchtime);
4837e3a96eaSJohn Baldwin 	PCPU_SET(switchticks, ticks);
4847e3a96eaSJohn Baldwin 	PCPU_INC(cnt.v_swtch);
4857e3a96eaSJohn Baldwin 
4867e3a96eaSJohn Baldwin 	/* Save our resource usage in our process. */
4877e3a96eaSJohn Baldwin 	td->td_ru.ru_nvcsw++;
48841fd9c63SKonstantin Belousov 	ruxagg(p, td);
4897e3a96eaSJohn Baldwin 	rucollect(&p->p_ru, &td->td_ru);
4905c7bebf9SKonstantin Belousov 	PROC_STATUNLOCK(p);
4917e3a96eaSJohn Baldwin 
492dcc9954eSJulian Elischer 	td->td_state = TDS_INACTIVE;
4933d06b4b3SAttilio Rao #ifdef WITNESS
4943d06b4b3SAttilio Rao 	witness_thread_exit(td);
4953d06b4b3SAttilio Rao #endif
496732d9528SJulian Elischer 	CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
497a54e85fdSJeff Roberson 	sched_throw(td);
498cc66ebe2SPeter Wemm 	panic("I'm a teapot!");
49944990b8cSJulian Elischer 	/* NOTREACHED */
50044990b8cSJulian Elischer }
50144990b8cSJulian Elischer 
50244990b8cSJulian Elischer /*
503696058c3SJulian Elischer  * Do any thread specific cleanups that may be needed in wait()
50437814395SPeter Wemm  * called with Giant, proc and schedlock not held.
505696058c3SJulian Elischer  */
506696058c3SJulian Elischer void
507696058c3SJulian Elischer thread_wait(struct proc *p)
508696058c3SJulian Elischer {
509696058c3SJulian Elischer 	struct thread *td;
510696058c3SJulian Elischer 
51137814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
512624bf9e1SKonstantin Belousov 	KASSERT(p->p_numthreads == 1, ("multiple threads in thread_wait()"));
513624bf9e1SKonstantin Belousov 	KASSERT(p->p_exitthreads == 0, ("p_exitthreads leaking"));
514ff8fbcffSJeff Roberson 	td = FIRST_THREAD_IN_PROC(p);
515ff8fbcffSJeff Roberson 	/* Lock the last thread so we spin until it exits cpu_throw(). */
516ff8fbcffSJeff Roberson 	thread_lock(td);
517ff8fbcffSJeff Roberson 	thread_unlock(td);
5182e6b8de4SJeff Roberson 	lock_profile_thread_exit(td);
519d7f687fcSJeff Roberson 	cpuset_rel(td->td_cpuset);
520d7f687fcSJeff Roberson 	td->td_cpuset = NULL;
521696058c3SJulian Elischer 	cpu_thread_clean(td);
522ed062c8dSJulian Elischer 	crfree(td->td_ucred);
523696058c3SJulian Elischer 	thread_reap();	/* check for zombie threads etc. */
524696058c3SJulian Elischer }
525696058c3SJulian Elischer 
526696058c3SJulian Elischer /*
52744990b8cSJulian Elischer  * Link a thread to a process.
5281faf202eSJulian Elischer  * set up anything that needs to be initialized for it to
5291faf202eSJulian Elischer  * be used by the process.
53044990b8cSJulian Elischer  */
53144990b8cSJulian Elischer void
5328460a577SJohn Birrell thread_link(struct thread *td, struct proc *p)
53344990b8cSJulian Elischer {
53444990b8cSJulian Elischer 
535a54e85fdSJeff Roberson 	/*
536a54e85fdSJeff Roberson 	 * XXX This can't be enabled because it's called for proc0 before
537374ae2a3SJeff Roberson 	 * its lock has been created.
538374ae2a3SJeff Roberson 	 * PROC_LOCK_ASSERT(p, MA_OWNED);
539a54e85fdSJeff Roberson 	 */
54071fad9fdSJulian Elischer 	td->td_state    = TDS_INACTIVE;
54144990b8cSJulian Elischer 	td->td_proc     = p;
542b61ce5b0SJeff Roberson 	td->td_flags    = TDF_INMEM;
54344990b8cSJulian Elischer 
5441faf202eSJulian Elischer 	LIST_INIT(&td->td_contested);
545eea4f254SJeff Roberson 	LIST_INIT(&td->td_lprof[0]);
546eea4f254SJeff Roberson 	LIST_INIT(&td->td_lprof[1]);
5479104847fSDavid Xu 	sigqueue_init(&td->td_sigqueue, p);
548c06eb4e2SSam Leffler 	callout_init(&td->td_slpcallout, CALLOUT_MPSAFE);
54966d8df9dSDaniel Eischen 	TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
55044990b8cSJulian Elischer 	p->p_numthreads++;
55144990b8cSJulian Elischer }
55244990b8cSJulian Elischer 
553ed062c8dSJulian Elischer /*
554ed062c8dSJulian Elischer  * Called from:
555ed062c8dSJulian Elischer  *  thread_exit()
556ed062c8dSJulian Elischer  */
557d3a0bd78SJulian Elischer void
558d3a0bd78SJulian Elischer thread_unlink(struct thread *td)
559d3a0bd78SJulian Elischer {
560d3a0bd78SJulian Elischer 	struct proc *p = td->td_proc;
561d3a0bd78SJulian Elischer 
562374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
563d3a0bd78SJulian Elischer 	TAILQ_REMOVE(&p->p_threads, td, td_plist);
564d3a0bd78SJulian Elischer 	p->p_numthreads--;
565d3a0bd78SJulian Elischer 	/* could clear a few other things here */
5668460a577SJohn Birrell 	/* Must  NOT clear links to proc! */
5675c8329edSJulian Elischer }
5685c8329edSJulian Elischer 
56979799053SKonstantin Belousov static int
57079799053SKonstantin Belousov calc_remaining(struct proc *p, int mode)
57179799053SKonstantin Belousov {
57279799053SKonstantin Belousov 	int remaining;
57379799053SKonstantin Belousov 
5747b519077SKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
5757b519077SKonstantin Belousov 	PROC_SLOCK_ASSERT(p, MA_OWNED);
57679799053SKonstantin Belousov 	if (mode == SINGLE_EXIT)
57779799053SKonstantin Belousov 		remaining = p->p_numthreads;
57879799053SKonstantin Belousov 	else if (mode == SINGLE_BOUNDARY)
57979799053SKonstantin Belousov 		remaining = p->p_numthreads - p->p_boundary_count;
58079799053SKonstantin Belousov 	else if (mode == SINGLE_NO_EXIT)
58179799053SKonstantin Belousov 		remaining = p->p_numthreads - p->p_suspcount;
58279799053SKonstantin Belousov 	else
58379799053SKonstantin Belousov 		panic("calc_remaining: wrong mode %d", mode);
58479799053SKonstantin Belousov 	return (remaining);
58579799053SKonstantin Belousov }
58679799053SKonstantin Belousov 
5875215b187SJeff Roberson /*
58844990b8cSJulian Elischer  * Enforce single-threading.
58944990b8cSJulian Elischer  *
59044990b8cSJulian Elischer  * Returns 1 if the caller must abort (another thread is waiting to
59144990b8cSJulian Elischer  * exit the process or similar). Process is locked!
59244990b8cSJulian Elischer  * Returns 0 when you are successfully the only thread running.
59344990b8cSJulian Elischer  * A process has successfully single threaded in the suspend mode when
59444990b8cSJulian Elischer  * There are no threads in user mode. Threads in the kernel must be
59544990b8cSJulian Elischer  * allowed to continue until they get to the user boundary. They may even
59644990b8cSJulian Elischer  * copy out their return values and data before suspending. They may however be
597e2668f55SMaxim Konovalov  * accelerated in reaching the user boundary as we will wake up
59844990b8cSJulian Elischer  * any sleeping threads that are interruptable. (PCATCH).
59944990b8cSJulian Elischer  */
60044990b8cSJulian Elischer int
601906ac69dSDavid Xu thread_single(int mode)
60244990b8cSJulian Elischer {
60344990b8cSJulian Elischer 	struct thread *td;
60444990b8cSJulian Elischer 	struct thread *td2;
60544990b8cSJulian Elischer 	struct proc *p;
606da7bbd2cSJohn Baldwin 	int remaining, wakeup_swapper;
60744990b8cSJulian Elischer 
60844990b8cSJulian Elischer 	td = curthread;
60944990b8cSJulian Elischer 	p = td->td_proc;
61037814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
61144990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
61244990b8cSJulian Elischer 
613ed062c8dSJulian Elischer 	if ((p->p_flag & P_HADTHREADS) == 0)
61444990b8cSJulian Elischer 		return (0);
61544990b8cSJulian Elischer 
616e3b9bf71SJulian Elischer 	/* Is someone already single threading? */
617906ac69dSDavid Xu 	if (p->p_singlethread != NULL && p->p_singlethread != td)
61844990b8cSJulian Elischer 		return (1);
61944990b8cSJulian Elischer 
620906ac69dSDavid Xu 	if (mode == SINGLE_EXIT) {
621906ac69dSDavid Xu 		p->p_flag |= P_SINGLE_EXIT;
622906ac69dSDavid Xu 		p->p_flag &= ~P_SINGLE_BOUNDARY;
623906ac69dSDavid Xu 	} else {
624906ac69dSDavid Xu 		p->p_flag &= ~P_SINGLE_EXIT;
625906ac69dSDavid Xu 		if (mode == SINGLE_BOUNDARY)
626906ac69dSDavid Xu 			p->p_flag |= P_SINGLE_BOUNDARY;
627906ac69dSDavid Xu 		else
628906ac69dSDavid Xu 			p->p_flag &= ~P_SINGLE_BOUNDARY;
629906ac69dSDavid Xu 	}
6301279572aSDavid Xu 	p->p_flag |= P_STOPPED_SINGLE;
6317b4a950aSDavid Xu 	PROC_SLOCK(p);
632112afcb2SJohn Baldwin 	p->p_singlethread = td;
63379799053SKonstantin Belousov 	remaining = calc_remaining(p, mode);
634ec008e96SDavid Xu 	while (remaining != 1) {
635bf1a3220SDavid Xu 		if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
636bf1a3220SDavid Xu 			goto stopme;
637da7bbd2cSJohn Baldwin 		wakeup_swapper = 0;
63844990b8cSJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td2) {
63944990b8cSJulian Elischer 			if (td2 == td)
64044990b8cSJulian Elischer 				continue;
641a54e85fdSJeff Roberson 			thread_lock(td2);
642b7edba77SJeff Roberson 			td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
64371fad9fdSJulian Elischer 			if (TD_IS_INHIBITED(td2)) {
644906ac69dSDavid Xu 				switch (mode) {
645906ac69dSDavid Xu 				case SINGLE_EXIT:
646906ac69dSDavid Xu 					if (TD_IS_SUSPENDED(td2))
6477847a9daSJohn Baldwin 						wakeup_swapper |=
64871fad9fdSJulian Elischer 						    thread_unsuspend_one(td2);
64933862f40SDavid Xu 					if (TD_ON_SLEEPQ(td2) &&
650906ac69dSDavid Xu 					    (td2->td_flags & TDF_SINTR))
6517847a9daSJohn Baldwin 						wakeup_swapper |=
65294f0972bSDavid Xu 						    sleepq_abort(td2, EINTR);
653906ac69dSDavid Xu 					break;
654906ac69dSDavid Xu 				case SINGLE_BOUNDARY:
655ffdc5a34SDavid Xu 					if (TD_IS_SUSPENDED(td2) &&
656ffdc5a34SDavid Xu 					    !(td2->td_flags & TDF_BOUNDARY))
657ffdc5a34SDavid Xu 						wakeup_swapper |=
658ffdc5a34SDavid Xu 						    thread_unsuspend_one(td2);
659ffdc5a34SDavid Xu 					if (TD_ON_SLEEPQ(td2) &&
660ffdc5a34SDavid Xu 					    (td2->td_flags & TDF_SINTR))
661ffdc5a34SDavid Xu 						wakeup_swapper |=
662ffdc5a34SDavid Xu 						    sleepq_abort(td2, ERESTART);
663906ac69dSDavid Xu 					break;
664f33a947bSKonstantin Belousov 				case SINGLE_NO_EXIT:
665f33a947bSKonstantin Belousov 					if (TD_IS_SUSPENDED(td2) &&
666f33a947bSKonstantin Belousov 					    !(td2->td_flags & TDF_BOUNDARY))
667f33a947bSKonstantin Belousov 						wakeup_swapper |=
668f33a947bSKonstantin Belousov 						    thread_unsuspend_one(td2);
669f33a947bSKonstantin Belousov 					if (TD_ON_SLEEPQ(td2) &&
670f33a947bSKonstantin Belousov 					    (td2->td_flags & TDF_SINTR))
671f33a947bSKonstantin Belousov 						wakeup_swapper |=
672f33a947bSKonstantin Belousov 						    sleepq_abort(td2, ERESTART);
673f33a947bSKonstantin Belousov 					break;
674906ac69dSDavid Xu 				default:
675906ac69dSDavid Xu 					break;
67644990b8cSJulian Elischer 				}
67744990b8cSJulian Elischer 			}
678d8267df7SDavid Xu #ifdef SMP
679d8267df7SDavid Xu 			else if (TD_IS_RUNNING(td2) && td != td2) {
680d8267df7SDavid Xu 				forward_signal(td2);
681d8267df7SDavid Xu 			}
682d8267df7SDavid Xu #endif
683a54e85fdSJeff Roberson 			thread_unlock(td2);
6849d102777SJulian Elischer 		}
685da7bbd2cSJohn Baldwin 		if (wakeup_swapper)
686da7bbd2cSJohn Baldwin 			kick_proc0();
68779799053SKonstantin Belousov 		remaining = calc_remaining(p, mode);
688ec008e96SDavid Xu 
6899d102777SJulian Elischer 		/*
6909d102777SJulian Elischer 		 * Maybe we suspended some threads.. was it enough?
6919d102777SJulian Elischer 		 */
692ec008e96SDavid Xu 		if (remaining == 1)
6939d102777SJulian Elischer 			break;
6949d102777SJulian Elischer 
695bf1a3220SDavid Xu stopme:
69644990b8cSJulian Elischer 		/*
69744990b8cSJulian Elischer 		 * Wake us up when everyone else has suspended.
698e3b9bf71SJulian Elischer 		 * In the mean time we suspend as well.
69944990b8cSJulian Elischer 		 */
700a54e85fdSJeff Roberson 		thread_suspend_switch(td);
70179799053SKonstantin Belousov 		remaining = calc_remaining(p, mode);
70244990b8cSJulian Elischer 	}
703906ac69dSDavid Xu 	if (mode == SINGLE_EXIT) {
70491599697SJulian Elischer 		/*
7058626a0ddSKonstantin Belousov 		 * Convert the process to an unthreaded process.  The
7068626a0ddSKonstantin Belousov 		 * SINGLE_EXIT is called by exit1() or execve(), in
7078626a0ddSKonstantin Belousov 		 * both cases other threads must be retired.
70891599697SJulian Elischer 		 */
7098626a0ddSKonstantin Belousov 		KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
710ed062c8dSJulian Elischer 		p->p_singlethread = NULL;
7118626a0ddSKonstantin Belousov 		p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
712fd229b5bSKonstantin Belousov 
713fd229b5bSKonstantin Belousov 		/*
714fd229b5bSKonstantin Belousov 		 * Wait for any remaining threads to exit cpu_throw().
715fd229b5bSKonstantin Belousov 		 */
716fd229b5bSKonstantin Belousov 		while (p->p_exitthreads != 0) {
717fd229b5bSKonstantin Belousov 			PROC_SUNLOCK(p);
718fd229b5bSKonstantin Belousov 			PROC_UNLOCK(p);
719fd229b5bSKonstantin Belousov 			sched_relinquish(td);
720fd229b5bSKonstantin Belousov 			PROC_LOCK(p);
721fd229b5bSKonstantin Belousov 			PROC_SLOCK(p);
722fd229b5bSKonstantin Belousov 		}
72391599697SJulian Elischer 	}
7247b4a950aSDavid Xu 	PROC_SUNLOCK(p);
72544990b8cSJulian Elischer 	return (0);
72644990b8cSJulian Elischer }
72744990b8cSJulian Elischer 
728*8638fe7bSKonstantin Belousov bool
729*8638fe7bSKonstantin Belousov thread_suspend_check_needed(void)
730*8638fe7bSKonstantin Belousov {
731*8638fe7bSKonstantin Belousov 	struct proc *p;
732*8638fe7bSKonstantin Belousov 	struct thread *td;
733*8638fe7bSKonstantin Belousov 
734*8638fe7bSKonstantin Belousov 	td = curthread;
735*8638fe7bSKonstantin Belousov 	p = td->td_proc;
736*8638fe7bSKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
737*8638fe7bSKonstantin Belousov 	return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
738*8638fe7bSKonstantin Belousov 	    (td->td_dbgflags & TDB_SUSPEND) != 0));
739*8638fe7bSKonstantin Belousov }
740*8638fe7bSKonstantin Belousov 
74144990b8cSJulian Elischer /*
74244990b8cSJulian Elischer  * Called in from locations that can safely check to see
74344990b8cSJulian Elischer  * whether we have to suspend or at least throttle for a
74444990b8cSJulian Elischer  * single-thread event (e.g. fork).
74544990b8cSJulian Elischer  *
74644990b8cSJulian Elischer  * Such locations include userret().
74744990b8cSJulian Elischer  * If the "return_instead" argument is non zero, the thread must be able to
74844990b8cSJulian Elischer  * accept 0 (caller may continue), or 1 (caller must abort) as a result.
74944990b8cSJulian Elischer  *
75044990b8cSJulian Elischer  * The 'return_instead' argument tells the function if it may do a
75144990b8cSJulian Elischer  * thread_exit() or suspend, or whether the caller must abort and back
75244990b8cSJulian Elischer  * out instead.
75344990b8cSJulian Elischer  *
75444990b8cSJulian Elischer  * If the thread that set the single_threading request has set the
75544990b8cSJulian Elischer  * P_SINGLE_EXIT bit in the process flags then this call will never return
75644990b8cSJulian Elischer  * if 'return_instead' is false, but will exit.
75744990b8cSJulian Elischer  *
75844990b8cSJulian Elischer  * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
75944990b8cSJulian Elischer  *---------------+--------------------+---------------------
76044990b8cSJulian Elischer  *       0       | returns 0          |   returns 0 or 1
761353374b5SJohn Baldwin  *               | when ST ends       |   immediately
76244990b8cSJulian Elischer  *---------------+--------------------+---------------------
76344990b8cSJulian Elischer  *       1       | thread exits       |   returns 1
764353374b5SJohn Baldwin  *               |                    |  immediately
76544990b8cSJulian Elischer  * 0 = thread_exit() or suspension ok,
76644990b8cSJulian Elischer  * other = return error instead of stopping the thread.
76744990b8cSJulian Elischer  *
76844990b8cSJulian Elischer  * While a full suspension is under effect, even a single threading
76944990b8cSJulian Elischer  * thread would be suspended if it made this call (but it shouldn't).
77044990b8cSJulian Elischer  * This call should only be made from places where
77144990b8cSJulian Elischer  * thread_exit() would be safe as that may be the outcome unless
77244990b8cSJulian Elischer  * return_instead is set.
77344990b8cSJulian Elischer  */
77444990b8cSJulian Elischer int
77544990b8cSJulian Elischer thread_suspend_check(int return_instead)
77644990b8cSJulian Elischer {
777ecafb24bSJuli Mallett 	struct thread *td;
778ecafb24bSJuli Mallett 	struct proc *p;
7797847a9daSJohn Baldwin 	int wakeup_swapper;
78044990b8cSJulian Elischer 
78144990b8cSJulian Elischer 	td = curthread;
78244990b8cSJulian Elischer 	p = td->td_proc;
78337814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
78444990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
785*8638fe7bSKonstantin Belousov 	while (thread_suspend_check_needed()) {
7861279572aSDavid Xu 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
78744990b8cSJulian Elischer 			KASSERT(p->p_singlethread != NULL,
78844990b8cSJulian Elischer 			    ("singlethread not set"));
78944990b8cSJulian Elischer 			/*
790e3b9bf71SJulian Elischer 			 * The only suspension in action is a
791e3b9bf71SJulian Elischer 			 * single-threading. Single threader need not stop.
792b6d5995eSJulian Elischer 			 * XXX Should be safe to access unlocked
793b6d5995eSJulian Elischer 			 * as it can only be set to be true by us.
79444990b8cSJulian Elischer 			 */
795e3b9bf71SJulian Elischer 			if (p->p_singlethread == td)
79644990b8cSJulian Elischer 				return (0);	/* Exempt from stopping. */
79744990b8cSJulian Elischer 		}
79845a4bfa1SDavid Xu 		if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
79994f0972bSDavid Xu 			return (EINTR);
80044990b8cSJulian Elischer 
801906ac69dSDavid Xu 		/* Should we goto user boundary if we didn't come from there? */
802906ac69dSDavid Xu 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
803906ac69dSDavid Xu 		    (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
80494f0972bSDavid Xu 			return (ERESTART);
805906ac69dSDavid Xu 
80644990b8cSJulian Elischer 		/*
807d071a6faSJohn Baldwin 		 * Ignore suspend requests for stop signals if they
808d071a6faSJohn Baldwin 		 * are deferred.
809d071a6faSJohn Baldwin 		 */
810d071a6faSJohn Baldwin 		if (P_SHOULDSTOP(p) == P_STOPPED_SIG &&
811d071a6faSJohn Baldwin 		    td->td_flags & TDF_SBDRY) {
812d071a6faSJohn Baldwin 			KASSERT(return_instead,
813d071a6faSJohn Baldwin 			    ("TDF_SBDRY set for unsafe thread_suspend_check"));
814d071a6faSJohn Baldwin 			return (0);
815d071a6faSJohn Baldwin 		}
816d071a6faSJohn Baldwin 
817d071a6faSJohn Baldwin 		/*
81844990b8cSJulian Elischer 		 * If the process is waiting for us to exit,
81944990b8cSJulian Elischer 		 * this thread should just suicide.
8201279572aSDavid Xu 		 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
82144990b8cSJulian Elischer 		 */
822cf7d9a8cSDavid Xu 		if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
823cf7d9a8cSDavid Xu 			PROC_UNLOCK(p);
824cf7d9a8cSDavid Xu 			tidhash_remove(td);
825cf7d9a8cSDavid Xu 			PROC_LOCK(p);
82621ecd1e9SDavid Xu 			tdsigcleanup(td);
827cf7d9a8cSDavid Xu 			PROC_SLOCK(p);
82821ecd1e9SDavid Xu 			thread_stopped(p);
82944990b8cSJulian Elischer 			thread_exit();
830cf7d9a8cSDavid Xu 		}
83121ecd1e9SDavid Xu 
83221ecd1e9SDavid Xu 		PROC_SLOCK(p);
83321ecd1e9SDavid Xu 		thread_stopped(p);
834a54e85fdSJeff Roberson 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
835a54e85fdSJeff Roberson 			if (p->p_numthreads == p->p_suspcount + 1) {
836a54e85fdSJeff Roberson 				thread_lock(p->p_singlethread);
8377847a9daSJohn Baldwin 				wakeup_swapper =
838a54e85fdSJeff Roberson 				    thread_unsuspend_one(p->p_singlethread);
839a54e85fdSJeff Roberson 				thread_unlock(p->p_singlethread);
8407847a9daSJohn Baldwin 				if (wakeup_swapper)
8417847a9daSJohn Baldwin 					kick_proc0();
842a54e85fdSJeff Roberson 			}
843a54e85fdSJeff Roberson 		}
8443f9be10eSDavid Xu 		PROC_UNLOCK(p);
8457b4a950aSDavid Xu 		thread_lock(td);
84644990b8cSJulian Elischer 		/*
84744990b8cSJulian Elischer 		 * When a thread suspends, it just
848ad1e7d28SJulian Elischer 		 * gets taken off all queues.
84944990b8cSJulian Elischer 		 */
85071fad9fdSJulian Elischer 		thread_suspend_one(td);
851906ac69dSDavid Xu 		if (return_instead == 0) {
852906ac69dSDavid Xu 			p->p_boundary_count++;
853906ac69dSDavid Xu 			td->td_flags |= TDF_BOUNDARY;
854cf19bf91SJulian Elischer 		}
8557b4a950aSDavid Xu 		PROC_SUNLOCK(p);
8568df78c41SJeff Roberson 		mi_switch(SW_INVOL | SWT_SUSPEND, NULL);
857a54e85fdSJeff Roberson 		if (return_instead == 0)
858906ac69dSDavid Xu 			td->td_flags &= ~TDF_BOUNDARY;
859a54e85fdSJeff Roberson 		thread_unlock(td);
86044990b8cSJulian Elischer 		PROC_LOCK(p);
8617b519077SKonstantin Belousov 		if (return_instead == 0) {
8627b519077SKonstantin Belousov 			PROC_SLOCK(p);
863a54e85fdSJeff Roberson 			p->p_boundary_count--;
8647b519077SKonstantin Belousov 			PROC_SUNLOCK(p);
8657b519077SKonstantin Belousov 		}
86644990b8cSJulian Elischer 	}
86744990b8cSJulian Elischer 	return (0);
86844990b8cSJulian Elischer }
86944990b8cSJulian Elischer 
87035c32a76SDavid Xu void
871a54e85fdSJeff Roberson thread_suspend_switch(struct thread *td)
872a54e85fdSJeff Roberson {
873a54e85fdSJeff Roberson 	struct proc *p;
874a54e85fdSJeff Roberson 
875a54e85fdSJeff Roberson 	p = td->td_proc;
876a54e85fdSJeff Roberson 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
877a54e85fdSJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
8787b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
879a54e85fdSJeff Roberson 	/*
880a54e85fdSJeff Roberson 	 * We implement thread_suspend_one in stages here to avoid
881a54e85fdSJeff Roberson 	 * dropping the proc lock while the thread lock is owned.
882a54e85fdSJeff Roberson 	 */
883a54e85fdSJeff Roberson 	thread_stopped(p);
884a54e85fdSJeff Roberson 	p->p_suspcount++;
8853f9be10eSDavid Xu 	PROC_UNLOCK(p);
8867b4a950aSDavid Xu 	thread_lock(td);
887b7edba77SJeff Roberson 	td->td_flags &= ~TDF_NEEDSUSPCHK;
888a54e85fdSJeff Roberson 	TD_SET_SUSPENDED(td);
889c5aa6b58SJeff Roberson 	sched_sleep(td, 0);
8907b4a950aSDavid Xu 	PROC_SUNLOCK(p);
891a54e85fdSJeff Roberson 	DROP_GIANT();
8928df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_SUSPEND, NULL);
893a54e85fdSJeff Roberson 	thread_unlock(td);
894a54e85fdSJeff Roberson 	PICKUP_GIANT();
895a54e85fdSJeff Roberson 	PROC_LOCK(p);
8967b4a950aSDavid Xu 	PROC_SLOCK(p);
897a54e85fdSJeff Roberson }
898a54e85fdSJeff Roberson 
899a54e85fdSJeff Roberson void
90035c32a76SDavid Xu thread_suspend_one(struct thread *td)
90135c32a76SDavid Xu {
90235c32a76SDavid Xu 	struct proc *p = td->td_proc;
90335c32a76SDavid Xu 
9047b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
905a54e85fdSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
906e574e444SDavid Xu 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
90735c32a76SDavid Xu 	p->p_suspcount++;
908b7edba77SJeff Roberson 	td->td_flags &= ~TDF_NEEDSUSPCHK;
90971fad9fdSJulian Elischer 	TD_SET_SUSPENDED(td);
910c5aa6b58SJeff Roberson 	sched_sleep(td, 0);
91135c32a76SDavid Xu }
91235c32a76SDavid Xu 
9137847a9daSJohn Baldwin int
91435c32a76SDavid Xu thread_unsuspend_one(struct thread *td)
91535c32a76SDavid Xu {
91635c32a76SDavid Xu 	struct proc *p = td->td_proc;
91735c32a76SDavid Xu 
9187b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
919a54e85fdSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
920ad1e7d28SJulian Elischer 	KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
92171fad9fdSJulian Elischer 	TD_CLR_SUSPENDED(td);
92235c32a76SDavid Xu 	p->p_suspcount--;
9237847a9daSJohn Baldwin 	return (setrunnable(td));
92435c32a76SDavid Xu }
92535c32a76SDavid Xu 
92644990b8cSJulian Elischer /*
92744990b8cSJulian Elischer  * Allow all threads blocked by single threading to continue running.
92844990b8cSJulian Elischer  */
92944990b8cSJulian Elischer void
93044990b8cSJulian Elischer thread_unsuspend(struct proc *p)
93144990b8cSJulian Elischer {
93244990b8cSJulian Elischer 	struct thread *td;
9337847a9daSJohn Baldwin 	int wakeup_swapper;
93444990b8cSJulian Elischer 
93544990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
9367b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
9377847a9daSJohn Baldwin 	wakeup_swapper = 0;
93844990b8cSJulian Elischer 	if (!P_SHOULDSTOP(p)) {
939ad1e7d28SJulian Elischer                 FOREACH_THREAD_IN_PROC(p, td) {
940a54e85fdSJeff Roberson 			thread_lock(td);
941ad1e7d28SJulian Elischer 			if (TD_IS_SUSPENDED(td)) {
9427847a9daSJohn Baldwin 				wakeup_swapper |= thread_unsuspend_one(td);
94344990b8cSJulian Elischer 			}
944a54e85fdSJeff Roberson 			thread_unlock(td);
945ad1e7d28SJulian Elischer 		}
9461279572aSDavid Xu 	} else if ((P_SHOULDSTOP(p) == P_STOPPED_SINGLE) &&
94744990b8cSJulian Elischer 	    (p->p_numthreads == p->p_suspcount)) {
94844990b8cSJulian Elischer 		/*
94944990b8cSJulian Elischer 		 * Stopping everything also did the job for the single
95044990b8cSJulian Elischer 		 * threading request. Now we've downgraded to single-threaded,
95144990b8cSJulian Elischer 		 * let it continue.
95244990b8cSJulian Elischer 		 */
953a54e85fdSJeff Roberson 		thread_lock(p->p_singlethread);
9547847a9daSJohn Baldwin 		wakeup_swapper = thread_unsuspend_one(p->p_singlethread);
955a54e85fdSJeff Roberson 		thread_unlock(p->p_singlethread);
95644990b8cSJulian Elischer 	}
9577847a9daSJohn Baldwin 	if (wakeup_swapper)
9587847a9daSJohn Baldwin 		kick_proc0();
95944990b8cSJulian Elischer }
96044990b8cSJulian Elischer 
961ed062c8dSJulian Elischer /*
962ed062c8dSJulian Elischer  * End the single threading mode..
963ed062c8dSJulian Elischer  */
96444990b8cSJulian Elischer void
96544990b8cSJulian Elischer thread_single_end(void)
96644990b8cSJulian Elischer {
96744990b8cSJulian Elischer 	struct thread *td;
96844990b8cSJulian Elischer 	struct proc *p;
9697847a9daSJohn Baldwin 	int wakeup_swapper;
97044990b8cSJulian Elischer 
97144990b8cSJulian Elischer 	td = curthread;
97244990b8cSJulian Elischer 	p = td->td_proc;
97344990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
974906ac69dSDavid Xu 	p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY);
9757b4a950aSDavid Xu 	PROC_SLOCK(p);
97644990b8cSJulian Elischer 	p->p_singlethread = NULL;
9777847a9daSJohn Baldwin 	wakeup_swapper = 0;
97849539972SJulian Elischer 	/*
9797847a9daSJohn Baldwin 	 * If there are other threads they may now run,
98049539972SJulian Elischer 	 * unless of course there is a blanket 'stop order'
98149539972SJulian Elischer 	 * on the process. The single threader must be allowed
98249539972SJulian Elischer 	 * to continue however as this is a bad place to stop.
98349539972SJulian Elischer 	 */
98449539972SJulian Elischer 	if ((p->p_numthreads != 1) && (!P_SHOULDSTOP(p))) {
985ad1e7d28SJulian Elischer                 FOREACH_THREAD_IN_PROC(p, td) {
986a54e85fdSJeff Roberson 			thread_lock(td);
987ad1e7d28SJulian Elischer 			if (TD_IS_SUSPENDED(td)) {
9887847a9daSJohn Baldwin 				wakeup_swapper |= thread_unsuspend_one(td);
98944990b8cSJulian Elischer 			}
990a54e85fdSJeff Roberson 			thread_unlock(td);
99149539972SJulian Elischer 		}
992ad1e7d28SJulian Elischer 	}
9937b4a950aSDavid Xu 	PROC_SUNLOCK(p);
9947847a9daSJohn Baldwin 	if (wakeup_swapper)
9957847a9daSJohn Baldwin 		kick_proc0();
99649539972SJulian Elischer }
9974fc21c09SDaniel Eischen 
99844355392SDavid Xu struct thread *
99944355392SDavid Xu thread_find(struct proc *p, lwpid_t tid)
100044355392SDavid Xu {
100144355392SDavid Xu 	struct thread *td;
100244355392SDavid Xu 
100344355392SDavid Xu 	PROC_LOCK_ASSERT(p, MA_OWNED);
100444355392SDavid Xu 	FOREACH_THREAD_IN_PROC(p, td) {
100544355392SDavid Xu 		if (td->td_tid == tid)
100644355392SDavid Xu 			break;
100744355392SDavid Xu 	}
100844355392SDavid Xu 	return (td);
100944355392SDavid Xu }
1010cf7d9a8cSDavid Xu 
1011cf7d9a8cSDavid Xu /* Locate a thread by number; return with proc lock held. */
1012cf7d9a8cSDavid Xu struct thread *
1013cf7d9a8cSDavid Xu tdfind(lwpid_t tid, pid_t pid)
1014cf7d9a8cSDavid Xu {
1015cf7d9a8cSDavid Xu #define RUN_THRESH	16
1016cf7d9a8cSDavid Xu 	struct thread *td;
1017cf7d9a8cSDavid Xu 	int run = 0;
1018cf7d9a8cSDavid Xu 
1019cf7d9a8cSDavid Xu 	rw_rlock(&tidhash_lock);
1020cf7d9a8cSDavid Xu 	LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1021cf7d9a8cSDavid Xu 		if (td->td_tid == tid) {
1022cf7d9a8cSDavid Xu 			if (pid != -1 && td->td_proc->p_pid != pid) {
1023cf7d9a8cSDavid Xu 				td = NULL;
1024cf7d9a8cSDavid Xu 				break;
1025cf7d9a8cSDavid Xu 			}
10268e6fa660SJohn Baldwin 			PROC_LOCK(td->td_proc);
1027cf7d9a8cSDavid Xu 			if (td->td_proc->p_state == PRS_NEW) {
10288e6fa660SJohn Baldwin 				PROC_UNLOCK(td->td_proc);
1029cf7d9a8cSDavid Xu 				td = NULL;
1030cf7d9a8cSDavid Xu 				break;
1031cf7d9a8cSDavid Xu 			}
1032cf7d9a8cSDavid Xu 			if (run > RUN_THRESH) {
1033cf7d9a8cSDavid Xu 				if (rw_try_upgrade(&tidhash_lock)) {
1034cf7d9a8cSDavid Xu 					LIST_REMOVE(td, td_hash);
1035cf7d9a8cSDavid Xu 					LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1036cf7d9a8cSDavid Xu 						td, td_hash);
1037cf7d9a8cSDavid Xu 					rw_wunlock(&tidhash_lock);
1038cf7d9a8cSDavid Xu 					return (td);
1039cf7d9a8cSDavid Xu 				}
1040cf7d9a8cSDavid Xu 			}
1041cf7d9a8cSDavid Xu 			break;
1042cf7d9a8cSDavid Xu 		}
1043cf7d9a8cSDavid Xu 		run++;
1044cf7d9a8cSDavid Xu 	}
1045cf7d9a8cSDavid Xu 	rw_runlock(&tidhash_lock);
1046cf7d9a8cSDavid Xu 	return (td);
1047cf7d9a8cSDavid Xu }
1048cf7d9a8cSDavid Xu 
1049cf7d9a8cSDavid Xu void
1050cf7d9a8cSDavid Xu tidhash_add(struct thread *td)
1051cf7d9a8cSDavid Xu {
1052cf7d9a8cSDavid Xu 	rw_wlock(&tidhash_lock);
1053cf7d9a8cSDavid Xu 	LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1054cf7d9a8cSDavid Xu 	rw_wunlock(&tidhash_lock);
1055cf7d9a8cSDavid Xu }
1056cf7d9a8cSDavid Xu 
1057cf7d9a8cSDavid Xu void
1058cf7d9a8cSDavid Xu tidhash_remove(struct thread *td)
1059cf7d9a8cSDavid Xu {
1060cf7d9a8cSDavid Xu 	rw_wlock(&tidhash_lock);
1061cf7d9a8cSDavid Xu 	LIST_REMOVE(td, td_hash);
1062cf7d9a8cSDavid Xu 	rw_wunlock(&tidhash_lock);
1063cf7d9a8cSDavid Xu }
1064