xref: /freebsd/sys/kern/kern_thread.c (revision 353374b525ffdd9f7702eeda9369e3abbcbd45b6)
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"
30b3e9e682SRyan Stone #include "opt_kdtrace.h"
3116d95d4fSJoseph Koshy #include "opt_hwpmc_hooks.h"
323d06b4b3SAttilio Rao 
33677b542eSDavid E. O'Brien #include <sys/cdefs.h>
34677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
35677b542eSDavid E. O'Brien 
3644990b8cSJulian Elischer #include <sys/param.h>
3744990b8cSJulian Elischer #include <sys/systm.h>
3844990b8cSJulian Elischer #include <sys/kernel.h>
3944990b8cSJulian Elischer #include <sys/lock.h>
4044990b8cSJulian Elischer #include <sys/mutex.h>
4144990b8cSJulian Elischer #include <sys/proc.h>
428f0e9130SKonstantin Belousov #include <sys/rangelock.h>
43e170bfdaSDavid Xu #include <sys/resourcevar.h>
44b3e9e682SRyan Stone #include <sys/sdt.h>
4594e0a4cdSJulian Elischer #include <sys/smp.h>
46de028f5aSJeff Roberson #include <sys/sched.h>
4744f3b092SJohn Baldwin #include <sys/sleepqueue.h>
48ace8398dSJeff Roberson #include <sys/selinfo.h>
49961a7b24SJohn Baldwin #include <sys/turnstile.h>
5044990b8cSJulian Elischer #include <sys/ktr.h>
51cf7d9a8cSDavid Xu #include <sys/rwlock.h>
52bc8e6d81SDavid Xu #include <sys/umtx.h>
53d7f687fcSJeff Roberson #include <sys/cpuset.h>
5416d95d4fSJoseph Koshy #ifdef	HWPMC_HOOKS
5516d95d4fSJoseph Koshy #include <sys/pmckern.h>
5616d95d4fSJoseph Koshy #endif
5744990b8cSJulian Elischer 
58911b84b0SRobert Watson #include <security/audit/audit.h>
59911b84b0SRobert Watson 
6044990b8cSJulian Elischer #include <vm/vm.h>
6149a2507bSAlan Cox #include <vm/vm_extern.h>
6244990b8cSJulian Elischer #include <vm/uma.h>
63b209f889SRandall Stewart #include <sys/eventhandler.h>
6402fb42b0SPeter Wemm 
65b3e9e682SRyan Stone SDT_PROVIDER_DECLARE(proc);
66b3e9e682SRyan Stone SDT_PROBE_DEFINE(proc, , , lwp_exit, lwp-exit);
67b3e9e682SRyan Stone 
68b3e9e682SRyan Stone 
698460a577SJohn Birrell /*
708460a577SJohn Birrell  * thread related storage.
718460a577SJohn Birrell  */
7244990b8cSJulian Elischer static uma_zone_t thread_zone;
7344990b8cSJulian Elischer 
745215b187SJeff Roberson TAILQ_HEAD(, thread) zombie_threads = TAILQ_HEAD_INITIALIZER(zombie_threads);
75c8790f5dSAttilio Rao static struct mtx zombie_lock;
76a54e85fdSJeff Roberson MTX_SYSINIT(zombie_lock, &zombie_lock, "zombie lock", MTX_SPIN);
7744990b8cSJulian Elischer 
78ff8fbcffSJeff Roberson static void thread_zombie(struct thread *);
79ff8fbcffSJeff Roberson 
80ec6ea5e8SDavid Xu #define TID_BUFFER_SIZE	1024
81ec6ea5e8SDavid Xu 
82fdcac928SMarcel Moolenaar struct mtx tid_lock;
831ea7a6f8SPoul-Henning Kamp static struct unrhdr *tid_unrhdr;
84ec6ea5e8SDavid Xu static lwpid_t tid_buffer[TID_BUFFER_SIZE];
85ec6ea5e8SDavid Xu static int tid_head, tid_tail;
86cf7d9a8cSDavid Xu static MALLOC_DEFINE(M_TIDHASH, "tidhash", "thread hash");
87cf7d9a8cSDavid Xu 
88cf7d9a8cSDavid Xu struct	tidhashhead *tidhashtbl;
89cf7d9a8cSDavid Xu u_long	tidhash;
90cf7d9a8cSDavid Xu struct	rwlock tidhash_lock;
91cf7d9a8cSDavid Xu 
92ec6ea5e8SDavid Xu static lwpid_t
93ec6ea5e8SDavid Xu tid_alloc(void)
94ec6ea5e8SDavid Xu {
95ec6ea5e8SDavid Xu 	lwpid_t	tid;
96ec6ea5e8SDavid Xu 
97ec6ea5e8SDavid Xu 	tid = alloc_unr(tid_unrhdr);
98ec6ea5e8SDavid Xu 	if (tid != -1)
99ec6ea5e8SDavid Xu 		return (tid);
100ec6ea5e8SDavid Xu 	mtx_lock(&tid_lock);
101ec6ea5e8SDavid Xu 	if (tid_head == tid_tail) {
102ec6ea5e8SDavid Xu 		mtx_unlock(&tid_lock);
103ec6ea5e8SDavid Xu 		return (-1);
104ec6ea5e8SDavid Xu 	}
10594cb3545SKonstantin Belousov 	tid = tid_buffer[tid_head];
10694cb3545SKonstantin Belousov 	tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
107ec6ea5e8SDavid Xu 	mtx_unlock(&tid_lock);
108ec6ea5e8SDavid Xu 	return (tid);
109ec6ea5e8SDavid Xu }
110ec6ea5e8SDavid Xu 
111ec6ea5e8SDavid Xu static void
112ec6ea5e8SDavid Xu tid_free(lwpid_t tid)
113ec6ea5e8SDavid Xu {
114ec6ea5e8SDavid Xu 	lwpid_t tmp_tid = -1;
115ec6ea5e8SDavid Xu 
116ec6ea5e8SDavid Xu 	mtx_lock(&tid_lock);
117ec6ea5e8SDavid Xu 	if ((tid_tail + 1) % TID_BUFFER_SIZE == tid_head) {
11894cb3545SKonstantin Belousov 		tmp_tid = tid_buffer[tid_head];
11994cb3545SKonstantin Belousov 		tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
120ec6ea5e8SDavid Xu 	}
12194cb3545SKonstantin Belousov 	tid_buffer[tid_tail] = tid;
12294cb3545SKonstantin Belousov 	tid_tail = (tid_tail + 1) % TID_BUFFER_SIZE;
123ec6ea5e8SDavid Xu 	mtx_unlock(&tid_lock);
124ec6ea5e8SDavid Xu 	if (tmp_tid != -1)
125ec6ea5e8SDavid Xu 		free_unr(tid_unrhdr, tmp_tid);
126ec6ea5e8SDavid Xu }
127ec6ea5e8SDavid Xu 
128fdcac928SMarcel Moolenaar /*
129696058c3SJulian Elischer  * Prepare a thread for use.
13044990b8cSJulian Elischer  */
131b23f72e9SBrian Feldman static int
132b23f72e9SBrian Feldman thread_ctor(void *mem, int size, void *arg, int flags)
13344990b8cSJulian Elischer {
13444990b8cSJulian Elischer 	struct thread	*td;
13544990b8cSJulian Elischer 
13644990b8cSJulian Elischer 	td = (struct thread *)mem;
13771fad9fdSJulian Elischer 	td->td_state = TDS_INACTIVE;
138060563ecSJulian Elischer 	td->td_oncpu = NOCPU;
1396c27c603SJuli Mallett 
140ec6ea5e8SDavid Xu 	td->td_tid = tid_alloc();
141773eff9dSPoul-Henning Kamp 
1426c27c603SJuli Mallett 	/*
1436c27c603SJuli Mallett 	 * Note that td_critnest begins life as 1 because the thread is not
1446c27c603SJuli Mallett 	 * running and is thereby implicitly waiting to be on the receiving
145a54e85fdSJeff Roberson 	 * end of a context switch.
1466c27c603SJuli Mallett 	 */
147139b7550SJohn Baldwin 	td->td_critnest = 1;
148acbe332aSDavid Xu 	td->td_lend_user_pri = PRI_MAX;
149b209f889SRandall Stewart 	EVENTHANDLER_INVOKE(thread_ctor, td);
150911b84b0SRobert Watson #ifdef AUDIT
151911b84b0SRobert Watson 	audit_thread_alloc(td);
152911b84b0SRobert Watson #endif
153d10183d9SDavid Xu 	umtx_thread_alloc(td);
154b23f72e9SBrian Feldman 	return (0);
15544990b8cSJulian Elischer }
15644990b8cSJulian Elischer 
15744990b8cSJulian Elischer /*
15844990b8cSJulian Elischer  * Reclaim a thread after use.
15944990b8cSJulian Elischer  */
16044990b8cSJulian Elischer static void
16144990b8cSJulian Elischer thread_dtor(void *mem, int size, void *arg)
16244990b8cSJulian Elischer {
16344990b8cSJulian Elischer 	struct thread *td;
16444990b8cSJulian Elischer 
16544990b8cSJulian Elischer 	td = (struct thread *)mem;
16644990b8cSJulian Elischer 
16744990b8cSJulian Elischer #ifdef INVARIANTS
16844990b8cSJulian Elischer 	/* Verify that this thread is in a safe state to free. */
16944990b8cSJulian Elischer 	switch (td->td_state) {
17071fad9fdSJulian Elischer 	case TDS_INHIBITED:
17171fad9fdSJulian Elischer 	case TDS_RUNNING:
17271fad9fdSJulian Elischer 	case TDS_CAN_RUN:
17344990b8cSJulian Elischer 	case TDS_RUNQ:
17444990b8cSJulian Elischer 		/*
17544990b8cSJulian Elischer 		 * We must never unlink a thread that is in one of
17644990b8cSJulian Elischer 		 * these states, because it is currently active.
17744990b8cSJulian Elischer 		 */
17844990b8cSJulian Elischer 		panic("bad state for thread unlinking");
17944990b8cSJulian Elischer 		/* NOTREACHED */
18071fad9fdSJulian Elischer 	case TDS_INACTIVE:
18144990b8cSJulian Elischer 		break;
18244990b8cSJulian Elischer 	default:
18344990b8cSJulian Elischer 		panic("bad thread state");
18444990b8cSJulian Elischer 		/* NOTREACHED */
18544990b8cSJulian Elischer 	}
18644990b8cSJulian Elischer #endif
1876e8525ceSRobert Watson #ifdef AUDIT
1886e8525ceSRobert Watson 	audit_thread_free(td);
1896e8525ceSRobert Watson #endif
1901ba4a712SPawel Jakub Dawidek 	/* Free all OSD associated to this thread. */
1911ba4a712SPawel Jakub Dawidek 	osd_thread_exit(td);
1921ba4a712SPawel Jakub Dawidek 
193b209f889SRandall Stewart 	EVENTHANDLER_INVOKE(thread_dtor, td);
194ec6ea5e8SDavid Xu 	tid_free(td->td_tid);
19544990b8cSJulian Elischer }
19644990b8cSJulian Elischer 
19744990b8cSJulian Elischer /*
19844990b8cSJulian Elischer  * Initialize type-stable parts of a thread (when newly created).
19944990b8cSJulian Elischer  */
200b23f72e9SBrian Feldman static int
201b23f72e9SBrian Feldman thread_init(void *mem, int size, int flags)
20244990b8cSJulian Elischer {
20344990b8cSJulian Elischer 	struct thread *td;
20444990b8cSJulian Elischer 
20544990b8cSJulian Elischer 	td = (struct thread *)mem;
206247aba24SMarcel Moolenaar 
20744f3b092SJohn Baldwin 	td->td_sleepqueue = sleepq_alloc();
208961a7b24SJohn Baldwin 	td->td_turnstile = turnstile_alloc();
2098f0e9130SKonstantin Belousov 	td->td_rlqe = NULL;
210b209f889SRandall Stewart 	EVENTHANDLER_INVOKE(thread_init, td);
211de028f5aSJeff Roberson 	td->td_sched = (struct td_sched *)&td[1];
212d10183d9SDavid Xu 	umtx_thread_init(td);
21389b57fcfSKonstantin Belousov 	td->td_kstack = 0;
214b23f72e9SBrian Feldman 	return (0);
21544990b8cSJulian Elischer }
21644990b8cSJulian Elischer 
21744990b8cSJulian Elischer /*
21844990b8cSJulian Elischer  * Tear down type-stable parts of a thread (just before being discarded).
21944990b8cSJulian Elischer  */
22044990b8cSJulian Elischer static void
22144990b8cSJulian Elischer thread_fini(void *mem, int size)
22244990b8cSJulian Elischer {
22344990b8cSJulian Elischer 	struct thread *td;
22444990b8cSJulian Elischer 
22544990b8cSJulian Elischer 	td = (struct thread *)mem;
226b209f889SRandall Stewart 	EVENTHANDLER_INVOKE(thread_fini, td);
2278f0e9130SKonstantin Belousov 	rlqentry_free(td->td_rlqe);
228961a7b24SJohn Baldwin 	turnstile_free(td->td_turnstile);
22944f3b092SJohn Baldwin 	sleepq_free(td->td_sleepqueue);
230d10183d9SDavid Xu 	umtx_thread_fini(td);
231ace8398dSJeff Roberson 	seltdfini(td);
23244990b8cSJulian Elischer }
2335215b187SJeff Roberson 
2345c8329edSJulian Elischer /*
2355215b187SJeff Roberson  * For a newly created process,
2365215b187SJeff Roberson  * link up all the structures and its initial threads etc.
237ed062c8dSJulian Elischer  * called from:
238ed062c8dSJulian Elischer  * {arch}/{arch}/machdep.c   ia64_init(), init386() etc.
239ed062c8dSJulian Elischer  * proc_dtor() (should go away)
240ed062c8dSJulian Elischer  * proc_init()
2415c8329edSJulian Elischer  */
2425c8329edSJulian Elischer void
24389b57fcfSKonstantin Belousov proc_linkup0(struct proc *p, struct thread *td)
24489b57fcfSKonstantin Belousov {
24589b57fcfSKonstantin Belousov 	TAILQ_INIT(&p->p_threads);	     /* all threads in proc */
24689b57fcfSKonstantin Belousov 	proc_linkup(p, td);
24789b57fcfSKonstantin Belousov }
24889b57fcfSKonstantin Belousov 
24989b57fcfSKonstantin Belousov void
2508460a577SJohn Birrell proc_linkup(struct proc *p, struct thread *td)
2515c8329edSJulian Elischer {
252a54e85fdSJeff Roberson 
2539104847fSDavid Xu 	sigqueue_init(&p->p_sigqueue, p);
254ebceaf6dSDavid Xu 	p->p_ksi = ksiginfo_alloc(1);
255ebceaf6dSDavid Xu 	if (p->p_ksi != NULL) {
2565c474517SDavid Xu 		/* XXX p_ksi may be null if ksiginfo zone is not ready */
257ebceaf6dSDavid Xu 		p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
258ebceaf6dSDavid Xu 	}
259b2f92ef9SDavid Xu 	LIST_INIT(&p->p_mqnotifier);
2605c8329edSJulian Elischer 	p->p_numthreads = 0;
2618460a577SJohn Birrell 	thread_link(td, p);
2625c8329edSJulian Elischer }
2635c8329edSJulian Elischer 
2645c8329edSJulian Elischer /*
26544990b8cSJulian Elischer  * Initialize global thread allocation resources.
26644990b8cSJulian Elischer  */
26744990b8cSJulian Elischer void
26844990b8cSJulian Elischer threadinit(void)
26944990b8cSJulian Elischer {
27044990b8cSJulian Elischer 
2711ea7a6f8SPoul-Henning Kamp 	mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
27202c6fc21SKonstantin Belousov 
27302c6fc21SKonstantin Belousov 	/*
274abce621cSKonstantin Belousov 	 * pid_max cannot be greater than PID_MAX.
27502c6fc21SKonstantin Belousov 	 * leave one number for thread0.
27602c6fc21SKonstantin Belousov 	 */
2776829a5c5SJulian Elischer 	tid_unrhdr = new_unrhdr(PID_MAX + 2, INT_MAX, &tid_lock);
2781ea7a6f8SPoul-Henning Kamp 
279de028f5aSJeff Roberson 	thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
28044990b8cSJulian Elischer 	    thread_ctor, thread_dtor, thread_init, thread_fini,
2814649e92bSJohn Baldwin 	    16 - 1, 0);
282cf7d9a8cSDavid Xu 	tidhashtbl = hashinit(maxproc / 2, M_TIDHASH, &tidhash);
283cf7d9a8cSDavid Xu 	rw_init(&tidhash_lock, "tidhash");
28444990b8cSJulian Elischer }
28544990b8cSJulian Elischer 
28644990b8cSJulian Elischer /*
287ff8fbcffSJeff Roberson  * Place an unused thread on the zombie list.
288ad1e7d28SJulian Elischer  * Use the slpq as that must be unused by now.
28944990b8cSJulian Elischer  */
29044990b8cSJulian Elischer void
291ff8fbcffSJeff Roberson thread_zombie(struct thread *td)
29244990b8cSJulian Elischer {
293a54e85fdSJeff Roberson 	mtx_lock_spin(&zombie_lock);
294ad1e7d28SJulian Elischer 	TAILQ_INSERT_HEAD(&zombie_threads, td, td_slpq);
295a54e85fdSJeff Roberson 	mtx_unlock_spin(&zombie_lock);
29644990b8cSJulian Elischer }
29744990b8cSJulian Elischer 
2985c8329edSJulian Elischer /*
299ff8fbcffSJeff Roberson  * Release a thread that has exited after cpu_throw().
300ff8fbcffSJeff Roberson  */
301ff8fbcffSJeff Roberson void
302ff8fbcffSJeff Roberson thread_stash(struct thread *td)
303ff8fbcffSJeff Roberson {
304ff8fbcffSJeff Roberson 	atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
305ff8fbcffSJeff Roberson 	thread_zombie(td);
306ff8fbcffSJeff Roberson }
307ff8fbcffSJeff Roberson 
308ff8fbcffSJeff Roberson /*
3096617724cSJeff Roberson  * Reap zombie resources.
31044990b8cSJulian Elischer  */
31144990b8cSJulian Elischer void
31244990b8cSJulian Elischer thread_reap(void)
31344990b8cSJulian Elischer {
3145c8329edSJulian Elischer 	struct thread *td_first, *td_next;
31544990b8cSJulian Elischer 
31644990b8cSJulian Elischer 	/*
3175215b187SJeff Roberson 	 * Don't even bother to lock if none at this instant,
3185215b187SJeff Roberson 	 * we really don't care about the next instant..
31944990b8cSJulian Elischer 	 */
3208460a577SJohn Birrell 	if (!TAILQ_EMPTY(&zombie_threads)) {
321a54e85fdSJeff Roberson 		mtx_lock_spin(&zombie_lock);
3225c8329edSJulian Elischer 		td_first = TAILQ_FIRST(&zombie_threads);
3235c8329edSJulian Elischer 		if (td_first)
3245c8329edSJulian Elischer 			TAILQ_INIT(&zombie_threads);
325a54e85fdSJeff Roberson 		mtx_unlock_spin(&zombie_lock);
3265c8329edSJulian Elischer 		while (td_first) {
327ad1e7d28SJulian Elischer 			td_next = TAILQ_NEXT(td_first, td_slpq);
3285215b187SJeff Roberson 			if (td_first->td_ucred)
3295215b187SJeff Roberson 				crfree(td_first->td_ucred);
3305c8329edSJulian Elischer 			thread_free(td_first);
3315c8329edSJulian Elischer 			td_first = td_next;
33244990b8cSJulian Elischer 		}
33344990b8cSJulian Elischer 	}
334ed062c8dSJulian Elischer }
33544990b8cSJulian Elischer 
3364f0db5e0SJulian Elischer /*
33744990b8cSJulian Elischer  * Allocate a thread.
33844990b8cSJulian Elischer  */
33944990b8cSJulian Elischer struct thread *
3408a945d10SKonstantin Belousov thread_alloc(int pages)
34144990b8cSJulian Elischer {
34289b57fcfSKonstantin Belousov 	struct thread *td;
3438460a577SJohn Birrell 
34444990b8cSJulian Elischer 	thread_reap(); /* check if any zombies to get */
34589b57fcfSKonstantin Belousov 
34689b57fcfSKonstantin Belousov 	td = (struct thread *)uma_zalloc(thread_zone, M_WAITOK);
34789b57fcfSKonstantin Belousov 	KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
3488a945d10SKonstantin Belousov 	if (!vm_thread_new(td, pages)) {
34989b57fcfSKonstantin Belousov 		uma_zfree(thread_zone, td);
35089b57fcfSKonstantin Belousov 		return (NULL);
35189b57fcfSKonstantin Belousov 	}
3520c3967e7SMarcel Moolenaar 	cpu_thread_alloc(td);
35389b57fcfSKonstantin Belousov 	return (td);
35444990b8cSJulian Elischer }
35544990b8cSJulian Elischer 
3568a945d10SKonstantin Belousov int
3578a945d10SKonstantin Belousov thread_alloc_stack(struct thread *td, int pages)
3588a945d10SKonstantin Belousov {
3598a945d10SKonstantin Belousov 
3608a945d10SKonstantin Belousov 	KASSERT(td->td_kstack == 0,
3618a945d10SKonstantin Belousov 	    ("thread_alloc_stack called on a thread with kstack"));
3628a945d10SKonstantin Belousov 	if (!vm_thread_new(td, pages))
3638a945d10SKonstantin Belousov 		return (0);
3648a945d10SKonstantin Belousov 	cpu_thread_alloc(td);
3658a945d10SKonstantin Belousov 	return (1);
3668a945d10SKonstantin Belousov }
3674f0db5e0SJulian Elischer 
3684f0db5e0SJulian Elischer /*
36944990b8cSJulian Elischer  * Deallocate a thread.
37044990b8cSJulian Elischer  */
37144990b8cSJulian Elischer void
37244990b8cSJulian Elischer thread_free(struct thread *td)
37344990b8cSJulian Elischer {
3742e6b8de4SJeff Roberson 
3752e6b8de4SJeff Roberson 	lock_profile_thread_exit(td);
37645aea8deSJeff Roberson 	if (td->td_cpuset)
377d7f687fcSJeff Roberson 		cpuset_rel(td->td_cpuset);
378d7f687fcSJeff Roberson 	td->td_cpuset = NULL;
3790c3967e7SMarcel Moolenaar 	cpu_thread_free(td);
38089b57fcfSKonstantin Belousov 	if (td->td_kstack != 0)
38189b57fcfSKonstantin Belousov 		vm_thread_dispose(td);
38244990b8cSJulian Elischer 	uma_zfree(thread_zone, td);
38344990b8cSJulian Elischer }
38444990b8cSJulian Elischer 
38544990b8cSJulian Elischer /*
38644990b8cSJulian Elischer  * Discard the current thread and exit from its context.
38794e0a4cdSJulian Elischer  * Always called with scheduler locked.
38844990b8cSJulian Elischer  *
38944990b8cSJulian Elischer  * Because we can't free a thread while we're operating under its context,
390696058c3SJulian Elischer  * push the current thread into our CPU's deadthread holder. This means
391696058c3SJulian Elischer  * we needn't worry about someone else grabbing our context before we
3926617724cSJeff Roberson  * do a cpu_throw().
39344990b8cSJulian Elischer  */
39444990b8cSJulian Elischer void
39544990b8cSJulian Elischer thread_exit(void)
39644990b8cSJulian Elischer {
3977e3a96eaSJohn Baldwin 	uint64_t runtime, new_switchtime;
39844990b8cSJulian Elischer 	struct thread *td;
3991c4bcd05SJeff Roberson 	struct thread *td2;
40044990b8cSJulian Elischer 	struct proc *p;
4017847a9daSJohn Baldwin 	int wakeup_swapper;
40244990b8cSJulian Elischer 
40344990b8cSJulian Elischer 	td = curthread;
40444990b8cSJulian Elischer 	p = td->td_proc;
40544990b8cSJulian Elischer 
406a54e85fdSJeff Roberson 	PROC_SLOCK_ASSERT(p, MA_OWNED);
407ed062c8dSJulian Elischer 	mtx_assert(&Giant, MA_NOTOWNED);
408a54e85fdSJeff Roberson 
40944990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
410ed062c8dSJulian Elischer 	KASSERT(p != NULL, ("thread exiting without a process"));
411cc701b73SRobert Watson 	CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
412e01eafefSJulian Elischer 	    (long)p->p_pid, td->td_name);
4139104847fSDavid Xu 	KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
41444990b8cSJulian Elischer 
41589964dd2SRobert Watson #ifdef AUDIT
41689964dd2SRobert Watson 	AUDIT_SYSCALL_EXIT(0, td);
41789964dd2SRobert Watson #endif
418d10183d9SDavid Xu 	umtx_thread_exit(td);
419ed062c8dSJulian Elischer 	/*
420ed062c8dSJulian Elischer 	 * drop FPU & debug register state storage, or any other
421ed062c8dSJulian Elischer 	 * architecture specific resources that
422ed062c8dSJulian Elischer 	 * would not be on a new untouched process.
423ed062c8dSJulian Elischer 	 */
42444990b8cSJulian Elischer 	cpu_thread_exit(td);	/* XXXSMP */
42544990b8cSJulian Elischer 
426ed062c8dSJulian Elischer 	/*
4271faf202eSJulian Elischer 	 * The last thread is left attached to the process
4281faf202eSJulian Elischer 	 * So that the whole bundle gets recycled. Skip
429ed062c8dSJulian Elischer 	 * all this stuff if we never had threads.
430ed062c8dSJulian Elischer 	 * EXIT clears all sign of other threads when
431ed062c8dSJulian Elischer 	 * it goes to single threading, so the last thread always
432ed062c8dSJulian Elischer 	 * takes the short path.
4331faf202eSJulian Elischer 	 */
434ed062c8dSJulian Elischer 	if (p->p_flag & P_HADTHREADS) {
4351faf202eSJulian Elischer 		if (p->p_numthreads > 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 
456ff8fbcffSJeff Roberson 			atomic_add_int(&td->td_proc->p_exitthreads, 1);
457696058c3SJulian Elischer 			PCPU_SET(deadthread, td);
4581faf202eSJulian Elischer 		} else {
459ed062c8dSJulian Elischer 			/*
460ed062c8dSJulian Elischer 			 * The last thread is exiting.. but not through exit()
461ed062c8dSJulian Elischer 			 */
462ed062c8dSJulian Elischer 			panic ("thread_exit: Last thread exiting on its own");
463ed062c8dSJulian Elischer 		}
4641faf202eSJulian Elischer 	}
46516d95d4fSJoseph Koshy #ifdef	HWPMC_HOOKS
46616d95d4fSJoseph Koshy 	/*
46716d95d4fSJoseph Koshy 	 * If this thread is part of a process that is being tracked by hwpmc(4),
46816d95d4fSJoseph Koshy 	 * inform the module of the thread's impending exit.
46916d95d4fSJoseph Koshy 	 */
47016d95d4fSJoseph Koshy 	if (PMC_PROC_IS_USING_PMCS(td->td_proc))
47116d95d4fSJoseph Koshy 		PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
47216d95d4fSJoseph Koshy #endif
473a54e85fdSJeff Roberson 	PROC_UNLOCK(p);
4747e3a96eaSJohn Baldwin 
4757e3a96eaSJohn Baldwin 	/* Do the same timestamp bookkeeping that mi_switch() would do. */
4767e3a96eaSJohn Baldwin 	new_switchtime = cpu_ticks();
4777e3a96eaSJohn Baldwin 	runtime = new_switchtime - PCPU_GET(switchtime);
4787e3a96eaSJohn Baldwin 	td->td_runtime += runtime;
4797e3a96eaSJohn Baldwin 	td->td_incruntime += runtime;
4807e3a96eaSJohn Baldwin 	PCPU_SET(switchtime, new_switchtime);
4817e3a96eaSJohn Baldwin 	PCPU_SET(switchticks, ticks);
4827e3a96eaSJohn Baldwin 	PCPU_INC(cnt.v_swtch);
4837e3a96eaSJohn Baldwin 
4847e3a96eaSJohn Baldwin 	/* Save our resource usage in our process. */
4857e3a96eaSJohn Baldwin 	td->td_ru.ru_nvcsw++;
48641fd9c63SKonstantin Belousov 	ruxagg(p, td);
4877e3a96eaSJohn Baldwin 	rucollect(&p->p_ru, &td->td_ru);
4887e3a96eaSJohn Baldwin 
489a54e85fdSJeff Roberson 	thread_lock(td);
490a54e85fdSJeff Roberson 	PROC_SUNLOCK(p);
491dcc9954eSJulian Elischer 	td->td_state = TDS_INACTIVE;
4923d06b4b3SAttilio Rao #ifdef WITNESS
4933d06b4b3SAttilio Rao 	witness_thread_exit(td);
4943d06b4b3SAttilio Rao #endif
495732d9528SJulian Elischer 	CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
496a54e85fdSJeff Roberson 	sched_throw(td);
497cc66ebe2SPeter Wemm 	panic("I'm a teapot!");
49844990b8cSJulian Elischer 	/* NOTREACHED */
49944990b8cSJulian Elischer }
50044990b8cSJulian Elischer 
50144990b8cSJulian Elischer /*
502696058c3SJulian Elischer  * Do any thread specific cleanups that may be needed in wait()
50337814395SPeter Wemm  * called with Giant, proc and schedlock not held.
504696058c3SJulian Elischer  */
505696058c3SJulian Elischer void
506696058c3SJulian Elischer thread_wait(struct proc *p)
507696058c3SJulian Elischer {
508696058c3SJulian Elischer 	struct thread *td;
509696058c3SJulian Elischer 
51037814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
51185495c72SJens Schweikhardt 	KASSERT((p->p_numthreads == 1), ("Multiple threads in wait1()"));
512ff8fbcffSJeff Roberson 	td = FIRST_THREAD_IN_PROC(p);
513ff8fbcffSJeff Roberson 	/* Lock the last thread so we spin until it exits cpu_throw(). */
514ff8fbcffSJeff Roberson 	thread_lock(td);
515ff8fbcffSJeff Roberson 	thread_unlock(td);
516ff8fbcffSJeff Roberson 	/* Wait for any remaining threads to exit cpu_throw(). */
517ff8fbcffSJeff Roberson 	while (p->p_exitthreads)
518ff8fbcffSJeff Roberson 		sched_relinquish(curthread);
5192e6b8de4SJeff Roberson 	lock_profile_thread_exit(td);
520d7f687fcSJeff Roberson 	cpuset_rel(td->td_cpuset);
521d7f687fcSJeff Roberson 	td->td_cpuset = NULL;
522696058c3SJulian Elischer 	cpu_thread_clean(td);
523ed062c8dSJulian Elischer 	crfree(td->td_ucred);
524696058c3SJulian Elischer 	thread_reap();	/* check for zombie threads etc. */
525696058c3SJulian Elischer }
526696058c3SJulian Elischer 
527696058c3SJulian Elischer /*
52844990b8cSJulian Elischer  * Link a thread to a process.
5291faf202eSJulian Elischer  * set up anything that needs to be initialized for it to
5301faf202eSJulian Elischer  * be used by the process.
53144990b8cSJulian Elischer  */
53244990b8cSJulian Elischer void
5338460a577SJohn Birrell thread_link(struct thread *td, struct proc *p)
53444990b8cSJulian Elischer {
53544990b8cSJulian Elischer 
536a54e85fdSJeff Roberson 	/*
537a54e85fdSJeff Roberson 	 * XXX This can't be enabled because it's called for proc0 before
538374ae2a3SJeff Roberson 	 * its lock has been created.
539374ae2a3SJeff Roberson 	 * PROC_LOCK_ASSERT(p, MA_OWNED);
540a54e85fdSJeff Roberson 	 */
54171fad9fdSJulian Elischer 	td->td_state    = TDS_INACTIVE;
54244990b8cSJulian Elischer 	td->td_proc     = p;
543b61ce5b0SJeff Roberson 	td->td_flags    = TDF_INMEM;
54444990b8cSJulian Elischer 
5451faf202eSJulian Elischer 	LIST_INIT(&td->td_contested);
546eea4f254SJeff Roberson 	LIST_INIT(&td->td_lprof[0]);
547eea4f254SJeff Roberson 	LIST_INIT(&td->td_lprof[1]);
5489104847fSDavid Xu 	sigqueue_init(&td->td_sigqueue, p);
549c06eb4e2SSam Leffler 	callout_init(&td->td_slpcallout, CALLOUT_MPSAFE);
55044990b8cSJulian Elischer 	TAILQ_INSERT_HEAD(&p->p_threads, td, td_plist);
55144990b8cSJulian Elischer 	p->p_numthreads++;
55244990b8cSJulian Elischer }
55344990b8cSJulian Elischer 
554ed062c8dSJulian Elischer /*
555e5bedcefSJulian Elischer  * Convert a process with one thread to an unthreaded process.
556e5bedcefSJulian Elischer  */
557e5bedcefSJulian Elischer void
558e5bedcefSJulian Elischer thread_unthread(struct thread *td)
559e5bedcefSJulian Elischer {
560e5bedcefSJulian Elischer 	struct proc *p = td->td_proc;
561e5bedcefSJulian Elischer 
562e5bedcefSJulian Elischer 	KASSERT((p->p_numthreads == 1), ("Unthreading with >1 threads"));
5638460a577SJohn Birrell 	p->p_flag &= ~P_HADTHREADS;
564e5bedcefSJulian Elischer }
565e5bedcefSJulian Elischer 
566e5bedcefSJulian Elischer /*
567ed062c8dSJulian Elischer  * Called from:
568ed062c8dSJulian Elischer  *  thread_exit()
569ed062c8dSJulian Elischer  */
570d3a0bd78SJulian Elischer void
571d3a0bd78SJulian Elischer thread_unlink(struct thread *td)
572d3a0bd78SJulian Elischer {
573d3a0bd78SJulian Elischer 	struct proc *p = td->td_proc;
574d3a0bd78SJulian Elischer 
575374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
576d3a0bd78SJulian Elischer 	TAILQ_REMOVE(&p->p_threads, td, td_plist);
577d3a0bd78SJulian Elischer 	p->p_numthreads--;
578d3a0bd78SJulian Elischer 	/* could clear a few other things here */
5798460a577SJohn Birrell 	/* Must  NOT clear links to proc! */
5805c8329edSJulian Elischer }
5815c8329edSJulian Elischer 
58279799053SKonstantin Belousov static int
58379799053SKonstantin Belousov calc_remaining(struct proc *p, int mode)
58479799053SKonstantin Belousov {
58579799053SKonstantin Belousov 	int remaining;
58679799053SKonstantin Belousov 
5877b519077SKonstantin Belousov 	PROC_LOCK_ASSERT(p, MA_OWNED);
5887b519077SKonstantin Belousov 	PROC_SLOCK_ASSERT(p, MA_OWNED);
58979799053SKonstantin Belousov 	if (mode == SINGLE_EXIT)
59079799053SKonstantin Belousov 		remaining = p->p_numthreads;
59179799053SKonstantin Belousov 	else if (mode == SINGLE_BOUNDARY)
59279799053SKonstantin Belousov 		remaining = p->p_numthreads - p->p_boundary_count;
59379799053SKonstantin Belousov 	else if (mode == SINGLE_NO_EXIT)
59479799053SKonstantin Belousov 		remaining = p->p_numthreads - p->p_suspcount;
59579799053SKonstantin Belousov 	else
59679799053SKonstantin Belousov 		panic("calc_remaining: wrong mode %d", mode);
59779799053SKonstantin Belousov 	return (remaining);
59879799053SKonstantin Belousov }
59979799053SKonstantin Belousov 
6005215b187SJeff Roberson /*
60144990b8cSJulian Elischer  * Enforce single-threading.
60244990b8cSJulian Elischer  *
60344990b8cSJulian Elischer  * Returns 1 if the caller must abort (another thread is waiting to
60444990b8cSJulian Elischer  * exit the process or similar). Process is locked!
60544990b8cSJulian Elischer  * Returns 0 when you are successfully the only thread running.
60644990b8cSJulian Elischer  * A process has successfully single threaded in the suspend mode when
60744990b8cSJulian Elischer  * There are no threads in user mode. Threads in the kernel must be
60844990b8cSJulian Elischer  * allowed to continue until they get to the user boundary. They may even
60944990b8cSJulian Elischer  * copy out their return values and data before suspending. They may however be
610e2668f55SMaxim Konovalov  * accelerated in reaching the user boundary as we will wake up
61144990b8cSJulian Elischer  * any sleeping threads that are interruptable. (PCATCH).
61244990b8cSJulian Elischer  */
61344990b8cSJulian Elischer int
614906ac69dSDavid Xu thread_single(int mode)
61544990b8cSJulian Elischer {
61644990b8cSJulian Elischer 	struct thread *td;
61744990b8cSJulian Elischer 	struct thread *td2;
61844990b8cSJulian Elischer 	struct proc *p;
619da7bbd2cSJohn Baldwin 	int remaining, wakeup_swapper;
62044990b8cSJulian Elischer 
62144990b8cSJulian Elischer 	td = curthread;
62244990b8cSJulian Elischer 	p = td->td_proc;
62337814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
62444990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
62544990b8cSJulian Elischer 
626ed062c8dSJulian Elischer 	if ((p->p_flag & P_HADTHREADS) == 0)
62744990b8cSJulian Elischer 		return (0);
62844990b8cSJulian Elischer 
629e3b9bf71SJulian Elischer 	/* Is someone already single threading? */
630906ac69dSDavid Xu 	if (p->p_singlethread != NULL && p->p_singlethread != td)
63144990b8cSJulian Elischer 		return (1);
63244990b8cSJulian Elischer 
633906ac69dSDavid Xu 	if (mode == SINGLE_EXIT) {
634906ac69dSDavid Xu 		p->p_flag |= P_SINGLE_EXIT;
635906ac69dSDavid Xu 		p->p_flag &= ~P_SINGLE_BOUNDARY;
636906ac69dSDavid Xu 	} else {
637906ac69dSDavid Xu 		p->p_flag &= ~P_SINGLE_EXIT;
638906ac69dSDavid Xu 		if (mode == SINGLE_BOUNDARY)
639906ac69dSDavid Xu 			p->p_flag |= P_SINGLE_BOUNDARY;
640906ac69dSDavid Xu 		else
641906ac69dSDavid Xu 			p->p_flag &= ~P_SINGLE_BOUNDARY;
642906ac69dSDavid Xu 	}
6431279572aSDavid Xu 	p->p_flag |= P_STOPPED_SINGLE;
6447b4a950aSDavid Xu 	PROC_SLOCK(p);
645112afcb2SJohn Baldwin 	p->p_singlethread = td;
64679799053SKonstantin Belousov 	remaining = calc_remaining(p, mode);
647ec008e96SDavid Xu 	while (remaining != 1) {
648bf1a3220SDavid Xu 		if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
649bf1a3220SDavid Xu 			goto stopme;
650da7bbd2cSJohn Baldwin 		wakeup_swapper = 0;
65144990b8cSJulian Elischer 		FOREACH_THREAD_IN_PROC(p, td2) {
65244990b8cSJulian Elischer 			if (td2 == td)
65344990b8cSJulian Elischer 				continue;
654a54e85fdSJeff Roberson 			thread_lock(td2);
655b7edba77SJeff Roberson 			td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
65671fad9fdSJulian Elischer 			if (TD_IS_INHIBITED(td2)) {
657906ac69dSDavid Xu 				switch (mode) {
658906ac69dSDavid Xu 				case SINGLE_EXIT:
659906ac69dSDavid Xu 					if (TD_IS_SUSPENDED(td2))
6607847a9daSJohn Baldwin 						wakeup_swapper |=
66171fad9fdSJulian Elischer 						    thread_unsuspend_one(td2);
66233862f40SDavid Xu 					if (TD_ON_SLEEPQ(td2) &&
663906ac69dSDavid Xu 					    (td2->td_flags & TDF_SINTR))
6647847a9daSJohn Baldwin 						wakeup_swapper |=
66594f0972bSDavid Xu 						    sleepq_abort(td2, EINTR);
666906ac69dSDavid Xu 					break;
667906ac69dSDavid Xu 				case SINGLE_BOUNDARY:
668ffdc5a34SDavid Xu 					if (TD_IS_SUSPENDED(td2) &&
669ffdc5a34SDavid Xu 					    !(td2->td_flags & TDF_BOUNDARY))
670ffdc5a34SDavid Xu 						wakeup_swapper |=
671ffdc5a34SDavid Xu 						    thread_unsuspend_one(td2);
672ffdc5a34SDavid Xu 					if (TD_ON_SLEEPQ(td2) &&
673ffdc5a34SDavid Xu 					    (td2->td_flags & TDF_SINTR))
674ffdc5a34SDavid Xu 						wakeup_swapper |=
675ffdc5a34SDavid Xu 						    sleepq_abort(td2, ERESTART);
676906ac69dSDavid Xu 					break;
677f33a947bSKonstantin Belousov 				case SINGLE_NO_EXIT:
678f33a947bSKonstantin Belousov 					if (TD_IS_SUSPENDED(td2) &&
679f33a947bSKonstantin Belousov 					    !(td2->td_flags & TDF_BOUNDARY))
680f33a947bSKonstantin Belousov 						wakeup_swapper |=
681f33a947bSKonstantin Belousov 						    thread_unsuspend_one(td2);
682f33a947bSKonstantin Belousov 					if (TD_ON_SLEEPQ(td2) &&
683f33a947bSKonstantin Belousov 					    (td2->td_flags & TDF_SINTR))
684f33a947bSKonstantin Belousov 						wakeup_swapper |=
685f33a947bSKonstantin Belousov 						    sleepq_abort(td2, ERESTART);
686f33a947bSKonstantin Belousov 					break;
687906ac69dSDavid Xu 				default:
688906ac69dSDavid Xu 					break;
68944990b8cSJulian Elischer 				}
69044990b8cSJulian Elischer 			}
691d8267df7SDavid Xu #ifdef SMP
692d8267df7SDavid Xu 			else if (TD_IS_RUNNING(td2) && td != td2) {
693d8267df7SDavid Xu 				forward_signal(td2);
694d8267df7SDavid Xu 			}
695d8267df7SDavid Xu #endif
696a54e85fdSJeff Roberson 			thread_unlock(td2);
6979d102777SJulian Elischer 		}
698da7bbd2cSJohn Baldwin 		if (wakeup_swapper)
699da7bbd2cSJohn Baldwin 			kick_proc0();
70079799053SKonstantin Belousov 		remaining = calc_remaining(p, mode);
701ec008e96SDavid Xu 
7029d102777SJulian Elischer 		/*
7039d102777SJulian Elischer 		 * Maybe we suspended some threads.. was it enough?
7049d102777SJulian Elischer 		 */
705ec008e96SDavid Xu 		if (remaining == 1)
7069d102777SJulian Elischer 			break;
7079d102777SJulian Elischer 
708bf1a3220SDavid Xu stopme:
70944990b8cSJulian Elischer 		/*
71044990b8cSJulian Elischer 		 * Wake us up when everyone else has suspended.
711e3b9bf71SJulian Elischer 		 * In the mean time we suspend as well.
71244990b8cSJulian Elischer 		 */
713a54e85fdSJeff Roberson 		thread_suspend_switch(td);
71479799053SKonstantin Belousov 		remaining = calc_remaining(p, mode);
71544990b8cSJulian Elischer 	}
716906ac69dSDavid Xu 	if (mode == SINGLE_EXIT) {
71791599697SJulian Elischer 		/*
71891599697SJulian Elischer 		 * We have gotten rid of all the other threads and we
71991599697SJulian Elischer 		 * are about to either exit or exec. In either case,
72091599697SJulian Elischer 		 * we try our utmost to revert to being a non-threaded
72191599697SJulian Elischer 		 * process.
72291599697SJulian Elischer 		 */
723ed062c8dSJulian Elischer 		p->p_singlethread = NULL;
72464895117SDavid Xu 		p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT);
725e5bedcefSJulian Elischer 		thread_unthread(td);
72691599697SJulian Elischer 	}
7277b4a950aSDavid Xu 	PROC_SUNLOCK(p);
72844990b8cSJulian Elischer 	return (0);
72944990b8cSJulian Elischer }
73044990b8cSJulian Elischer 
73144990b8cSJulian Elischer /*
73244990b8cSJulian Elischer  * Called in from locations that can safely check to see
73344990b8cSJulian Elischer  * whether we have to suspend or at least throttle for a
73444990b8cSJulian Elischer  * single-thread event (e.g. fork).
73544990b8cSJulian Elischer  *
73644990b8cSJulian Elischer  * Such locations include userret().
73744990b8cSJulian Elischer  * If the "return_instead" argument is non zero, the thread must be able to
73844990b8cSJulian Elischer  * accept 0 (caller may continue), or 1 (caller must abort) as a result.
73944990b8cSJulian Elischer  *
74044990b8cSJulian Elischer  * The 'return_instead' argument tells the function if it may do a
74144990b8cSJulian Elischer  * thread_exit() or suspend, or whether the caller must abort and back
74244990b8cSJulian Elischer  * out instead.
74344990b8cSJulian Elischer  *
74444990b8cSJulian Elischer  * If the thread that set the single_threading request has set the
74544990b8cSJulian Elischer  * P_SINGLE_EXIT bit in the process flags then this call will never return
74644990b8cSJulian Elischer  * if 'return_instead' is false, but will exit.
74744990b8cSJulian Elischer  *
74844990b8cSJulian Elischer  * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
74944990b8cSJulian Elischer  *---------------+--------------------+---------------------
75044990b8cSJulian Elischer  *       0       | returns 0          |   returns 0 or 1
751*353374b5SJohn Baldwin  *               | when ST ends       |   immediately
75244990b8cSJulian Elischer  *---------------+--------------------+---------------------
75344990b8cSJulian Elischer  *       1       | thread exits       |   returns 1
754*353374b5SJohn Baldwin  *               |                    |  immediately
75544990b8cSJulian Elischer  * 0 = thread_exit() or suspension ok,
75644990b8cSJulian Elischer  * other = return error instead of stopping the thread.
75744990b8cSJulian Elischer  *
75844990b8cSJulian Elischer  * While a full suspension is under effect, even a single threading
75944990b8cSJulian Elischer  * thread would be suspended if it made this call (but it shouldn't).
76044990b8cSJulian Elischer  * This call should only be made from places where
76144990b8cSJulian Elischer  * thread_exit() would be safe as that may be the outcome unless
76244990b8cSJulian Elischer  * return_instead is set.
76344990b8cSJulian Elischer  */
76444990b8cSJulian Elischer int
76544990b8cSJulian Elischer thread_suspend_check(int return_instead)
76644990b8cSJulian Elischer {
767ecafb24bSJuli Mallett 	struct thread *td;
768ecafb24bSJuli Mallett 	struct proc *p;
7697847a9daSJohn Baldwin 	int wakeup_swapper;
77044990b8cSJulian Elischer 
77144990b8cSJulian Elischer 	td = curthread;
77244990b8cSJulian Elischer 	p = td->td_proc;
77337814395SPeter Wemm 	mtx_assert(&Giant, MA_NOTOWNED);
77444990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
775cbf4e354SDavid Xu 	while (P_SHOULDSTOP(p) ||
776904c5ec4SDavid Xu 	      ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_SUSPEND))) {
7771279572aSDavid Xu 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
77844990b8cSJulian Elischer 			KASSERT(p->p_singlethread != NULL,
77944990b8cSJulian Elischer 			    ("singlethread not set"));
78044990b8cSJulian Elischer 			/*
781e3b9bf71SJulian Elischer 			 * The only suspension in action is a
782e3b9bf71SJulian Elischer 			 * single-threading. Single threader need not stop.
783b6d5995eSJulian Elischer 			 * XXX Should be safe to access unlocked
784b6d5995eSJulian Elischer 			 * as it can only be set to be true by us.
78544990b8cSJulian Elischer 			 */
786e3b9bf71SJulian Elischer 			if (p->p_singlethread == td)
78744990b8cSJulian Elischer 				return (0);	/* Exempt from stopping. */
78844990b8cSJulian Elischer 		}
78945a4bfa1SDavid Xu 		if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
79094f0972bSDavid Xu 			return (EINTR);
79144990b8cSJulian Elischer 
792906ac69dSDavid Xu 		/* Should we goto user boundary if we didn't come from there? */
793906ac69dSDavid Xu 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
794906ac69dSDavid Xu 		    (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
79594f0972bSDavid Xu 			return (ERESTART);
796906ac69dSDavid Xu 
79744990b8cSJulian Elischer 		/*
79844990b8cSJulian Elischer 		 * If the process is waiting for us to exit,
79944990b8cSJulian Elischer 		 * this thread should just suicide.
8001279572aSDavid Xu 		 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
80144990b8cSJulian Elischer 		 */
802cf7d9a8cSDavid Xu 		if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
803cf7d9a8cSDavid Xu 			PROC_UNLOCK(p);
804cf7d9a8cSDavid Xu 			tidhash_remove(td);
805cf7d9a8cSDavid Xu 			PROC_LOCK(p);
80621ecd1e9SDavid Xu 			tdsigcleanup(td);
807cf7d9a8cSDavid Xu 			PROC_SLOCK(p);
80821ecd1e9SDavid Xu 			thread_stopped(p);
80944990b8cSJulian Elischer 			thread_exit();
810cf7d9a8cSDavid Xu 		}
81121ecd1e9SDavid Xu 
81221ecd1e9SDavid Xu 		PROC_SLOCK(p);
81321ecd1e9SDavid Xu 		thread_stopped(p);
814a54e85fdSJeff Roberson 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
815a54e85fdSJeff Roberson 			if (p->p_numthreads == p->p_suspcount + 1) {
816a54e85fdSJeff Roberson 				thread_lock(p->p_singlethread);
8177847a9daSJohn Baldwin 				wakeup_swapper =
818a54e85fdSJeff Roberson 				    thread_unsuspend_one(p->p_singlethread);
819a54e85fdSJeff Roberson 				thread_unlock(p->p_singlethread);
8207847a9daSJohn Baldwin 				if (wakeup_swapper)
8217847a9daSJohn Baldwin 					kick_proc0();
822a54e85fdSJeff Roberson 			}
823a54e85fdSJeff Roberson 		}
8243f9be10eSDavid Xu 		PROC_UNLOCK(p);
8257b4a950aSDavid Xu 		thread_lock(td);
82644990b8cSJulian Elischer 		/*
82744990b8cSJulian Elischer 		 * When a thread suspends, it just
828ad1e7d28SJulian Elischer 		 * gets taken off all queues.
82944990b8cSJulian Elischer 		 */
83071fad9fdSJulian Elischer 		thread_suspend_one(td);
831906ac69dSDavid Xu 		if (return_instead == 0) {
832906ac69dSDavid Xu 			p->p_boundary_count++;
833906ac69dSDavid Xu 			td->td_flags |= TDF_BOUNDARY;
834cf19bf91SJulian Elischer 		}
8357b4a950aSDavid Xu 		PROC_SUNLOCK(p);
8368df78c41SJeff Roberson 		mi_switch(SW_INVOL | SWT_SUSPEND, NULL);
837a54e85fdSJeff Roberson 		if (return_instead == 0)
838906ac69dSDavid Xu 			td->td_flags &= ~TDF_BOUNDARY;
839a54e85fdSJeff Roberson 		thread_unlock(td);
84044990b8cSJulian Elischer 		PROC_LOCK(p);
8417b519077SKonstantin Belousov 		if (return_instead == 0) {
8427b519077SKonstantin Belousov 			PROC_SLOCK(p);
843a54e85fdSJeff Roberson 			p->p_boundary_count--;
8447b519077SKonstantin Belousov 			PROC_SUNLOCK(p);
8457b519077SKonstantin Belousov 		}
84644990b8cSJulian Elischer 	}
84744990b8cSJulian Elischer 	return (0);
84844990b8cSJulian Elischer }
84944990b8cSJulian Elischer 
85035c32a76SDavid Xu void
851a54e85fdSJeff Roberson thread_suspend_switch(struct thread *td)
852a54e85fdSJeff Roberson {
853a54e85fdSJeff Roberson 	struct proc *p;
854a54e85fdSJeff Roberson 
855a54e85fdSJeff Roberson 	p = td->td_proc;
856a54e85fdSJeff Roberson 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
857a54e85fdSJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
8587b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
859a54e85fdSJeff Roberson 	/*
860a54e85fdSJeff Roberson 	 * We implement thread_suspend_one in stages here to avoid
861a54e85fdSJeff Roberson 	 * dropping the proc lock while the thread lock is owned.
862a54e85fdSJeff Roberson 	 */
863a54e85fdSJeff Roberson 	thread_stopped(p);
864a54e85fdSJeff Roberson 	p->p_suspcount++;
8653f9be10eSDavid Xu 	PROC_UNLOCK(p);
8667b4a950aSDavid Xu 	thread_lock(td);
867b7edba77SJeff Roberson 	td->td_flags &= ~TDF_NEEDSUSPCHK;
868a54e85fdSJeff Roberson 	TD_SET_SUSPENDED(td);
869c5aa6b58SJeff Roberson 	sched_sleep(td, 0);
8707b4a950aSDavid Xu 	PROC_SUNLOCK(p);
871a54e85fdSJeff Roberson 	DROP_GIANT();
8728df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_SUSPEND, NULL);
873a54e85fdSJeff Roberson 	thread_unlock(td);
874a54e85fdSJeff Roberson 	PICKUP_GIANT();
875a54e85fdSJeff Roberson 	PROC_LOCK(p);
8767b4a950aSDavid Xu 	PROC_SLOCK(p);
877a54e85fdSJeff Roberson }
878a54e85fdSJeff Roberson 
879a54e85fdSJeff Roberson void
88035c32a76SDavid Xu thread_suspend_one(struct thread *td)
88135c32a76SDavid Xu {
88235c32a76SDavid Xu 	struct proc *p = td->td_proc;
88335c32a76SDavid Xu 
8847b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
885a54e85fdSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
886e574e444SDavid Xu 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
88735c32a76SDavid Xu 	p->p_suspcount++;
888b7edba77SJeff Roberson 	td->td_flags &= ~TDF_NEEDSUSPCHK;
88971fad9fdSJulian Elischer 	TD_SET_SUSPENDED(td);
890c5aa6b58SJeff Roberson 	sched_sleep(td, 0);
89135c32a76SDavid Xu }
89235c32a76SDavid Xu 
8937847a9daSJohn Baldwin int
89435c32a76SDavid Xu thread_unsuspend_one(struct thread *td)
89535c32a76SDavid Xu {
89635c32a76SDavid Xu 	struct proc *p = td->td_proc;
89735c32a76SDavid Xu 
8987b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
899a54e85fdSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
900ad1e7d28SJulian Elischer 	KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
90171fad9fdSJulian Elischer 	TD_CLR_SUSPENDED(td);
90235c32a76SDavid Xu 	p->p_suspcount--;
9037847a9daSJohn Baldwin 	return (setrunnable(td));
90435c32a76SDavid Xu }
90535c32a76SDavid Xu 
90644990b8cSJulian Elischer /*
90744990b8cSJulian Elischer  * Allow all threads blocked by single threading to continue running.
90844990b8cSJulian Elischer  */
90944990b8cSJulian Elischer void
91044990b8cSJulian Elischer thread_unsuspend(struct proc *p)
91144990b8cSJulian Elischer {
91244990b8cSJulian Elischer 	struct thread *td;
9137847a9daSJohn Baldwin 	int wakeup_swapper;
91444990b8cSJulian Elischer 
91544990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
9167b4a950aSDavid Xu 	PROC_SLOCK_ASSERT(p, MA_OWNED);
9177847a9daSJohn Baldwin 	wakeup_swapper = 0;
91844990b8cSJulian Elischer 	if (!P_SHOULDSTOP(p)) {
919ad1e7d28SJulian Elischer                 FOREACH_THREAD_IN_PROC(p, td) {
920a54e85fdSJeff Roberson 			thread_lock(td);
921ad1e7d28SJulian Elischer 			if (TD_IS_SUSPENDED(td)) {
9227847a9daSJohn Baldwin 				wakeup_swapper |= thread_unsuspend_one(td);
92344990b8cSJulian Elischer 			}
924a54e85fdSJeff Roberson 			thread_unlock(td);
925ad1e7d28SJulian Elischer 		}
9261279572aSDavid Xu 	} else if ((P_SHOULDSTOP(p) == P_STOPPED_SINGLE) &&
92744990b8cSJulian Elischer 	    (p->p_numthreads == p->p_suspcount)) {
92844990b8cSJulian Elischer 		/*
92944990b8cSJulian Elischer 		 * Stopping everything also did the job for the single
93044990b8cSJulian Elischer 		 * threading request. Now we've downgraded to single-threaded,
93144990b8cSJulian Elischer 		 * let it continue.
93244990b8cSJulian Elischer 		 */
933a54e85fdSJeff Roberson 		thread_lock(p->p_singlethread);
9347847a9daSJohn Baldwin 		wakeup_swapper = thread_unsuspend_one(p->p_singlethread);
935a54e85fdSJeff Roberson 		thread_unlock(p->p_singlethread);
93644990b8cSJulian Elischer 	}
9377847a9daSJohn Baldwin 	if (wakeup_swapper)
9387847a9daSJohn Baldwin 		kick_proc0();
93944990b8cSJulian Elischer }
94044990b8cSJulian Elischer 
941ed062c8dSJulian Elischer /*
942ed062c8dSJulian Elischer  * End the single threading mode..
943ed062c8dSJulian Elischer  */
94444990b8cSJulian Elischer void
94544990b8cSJulian Elischer thread_single_end(void)
94644990b8cSJulian Elischer {
94744990b8cSJulian Elischer 	struct thread *td;
94844990b8cSJulian Elischer 	struct proc *p;
9497847a9daSJohn Baldwin 	int wakeup_swapper;
95044990b8cSJulian Elischer 
95144990b8cSJulian Elischer 	td = curthread;
95244990b8cSJulian Elischer 	p = td->td_proc;
95344990b8cSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
954906ac69dSDavid Xu 	p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY);
9557b4a950aSDavid Xu 	PROC_SLOCK(p);
95644990b8cSJulian Elischer 	p->p_singlethread = NULL;
9577847a9daSJohn Baldwin 	wakeup_swapper = 0;
95849539972SJulian Elischer 	/*
9597847a9daSJohn Baldwin 	 * If there are other threads they may now run,
96049539972SJulian Elischer 	 * unless of course there is a blanket 'stop order'
96149539972SJulian Elischer 	 * on the process. The single threader must be allowed
96249539972SJulian Elischer 	 * to continue however as this is a bad place to stop.
96349539972SJulian Elischer 	 */
96449539972SJulian Elischer 	if ((p->p_numthreads != 1) && (!P_SHOULDSTOP(p))) {
965ad1e7d28SJulian Elischer                 FOREACH_THREAD_IN_PROC(p, td) {
966a54e85fdSJeff Roberson 			thread_lock(td);
967ad1e7d28SJulian Elischer 			if (TD_IS_SUSPENDED(td)) {
9687847a9daSJohn Baldwin 				wakeup_swapper |= thread_unsuspend_one(td);
96944990b8cSJulian Elischer 			}
970a54e85fdSJeff Roberson 			thread_unlock(td);
97149539972SJulian Elischer 		}
972ad1e7d28SJulian Elischer 	}
9737b4a950aSDavid Xu 	PROC_SUNLOCK(p);
9747847a9daSJohn Baldwin 	if (wakeup_swapper)
9757847a9daSJohn Baldwin 		kick_proc0();
97649539972SJulian Elischer }
9774fc21c09SDaniel Eischen 
97844355392SDavid Xu struct thread *
97944355392SDavid Xu thread_find(struct proc *p, lwpid_t tid)
98044355392SDavid Xu {
98144355392SDavid Xu 	struct thread *td;
98244355392SDavid Xu 
98344355392SDavid Xu 	PROC_LOCK_ASSERT(p, MA_OWNED);
98444355392SDavid Xu 	FOREACH_THREAD_IN_PROC(p, td) {
98544355392SDavid Xu 		if (td->td_tid == tid)
98644355392SDavid Xu 			break;
98744355392SDavid Xu 	}
98844355392SDavid Xu 	return (td);
98944355392SDavid Xu }
990cf7d9a8cSDavid Xu 
991cf7d9a8cSDavid Xu /* Locate a thread by number; return with proc lock held. */
992cf7d9a8cSDavid Xu struct thread *
993cf7d9a8cSDavid Xu tdfind(lwpid_t tid, pid_t pid)
994cf7d9a8cSDavid Xu {
995cf7d9a8cSDavid Xu #define RUN_THRESH	16
996cf7d9a8cSDavid Xu 	struct thread *td;
997cf7d9a8cSDavid Xu 	int run = 0;
998cf7d9a8cSDavid Xu 
999cf7d9a8cSDavid Xu 	rw_rlock(&tidhash_lock);
1000cf7d9a8cSDavid Xu 	LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1001cf7d9a8cSDavid Xu 		if (td->td_tid == tid) {
1002cf7d9a8cSDavid Xu 			if (pid != -1 && td->td_proc->p_pid != pid) {
1003cf7d9a8cSDavid Xu 				td = NULL;
1004cf7d9a8cSDavid Xu 				break;
1005cf7d9a8cSDavid Xu 			}
10068e6fa660SJohn Baldwin 			PROC_LOCK(td->td_proc);
1007cf7d9a8cSDavid Xu 			if (td->td_proc->p_state == PRS_NEW) {
10088e6fa660SJohn Baldwin 				PROC_UNLOCK(td->td_proc);
1009cf7d9a8cSDavid Xu 				td = NULL;
1010cf7d9a8cSDavid Xu 				break;
1011cf7d9a8cSDavid Xu 			}
1012cf7d9a8cSDavid Xu 			if (run > RUN_THRESH) {
1013cf7d9a8cSDavid Xu 				if (rw_try_upgrade(&tidhash_lock)) {
1014cf7d9a8cSDavid Xu 					LIST_REMOVE(td, td_hash);
1015cf7d9a8cSDavid Xu 					LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1016cf7d9a8cSDavid Xu 						td, td_hash);
1017cf7d9a8cSDavid Xu 					rw_wunlock(&tidhash_lock);
1018cf7d9a8cSDavid Xu 					return (td);
1019cf7d9a8cSDavid Xu 				}
1020cf7d9a8cSDavid Xu 			}
1021cf7d9a8cSDavid Xu 			break;
1022cf7d9a8cSDavid Xu 		}
1023cf7d9a8cSDavid Xu 		run++;
1024cf7d9a8cSDavid Xu 	}
1025cf7d9a8cSDavid Xu 	rw_runlock(&tidhash_lock);
1026cf7d9a8cSDavid Xu 	return (td);
1027cf7d9a8cSDavid Xu }
1028cf7d9a8cSDavid Xu 
1029cf7d9a8cSDavid Xu void
1030cf7d9a8cSDavid Xu tidhash_add(struct thread *td)
1031cf7d9a8cSDavid Xu {
1032cf7d9a8cSDavid Xu 	rw_wlock(&tidhash_lock);
1033cf7d9a8cSDavid Xu 	LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1034cf7d9a8cSDavid Xu 	rw_wunlock(&tidhash_lock);
1035cf7d9a8cSDavid Xu }
1036cf7d9a8cSDavid Xu 
1037cf7d9a8cSDavid Xu void
1038cf7d9a8cSDavid Xu tidhash_remove(struct thread *td)
1039cf7d9a8cSDavid Xu {
1040cf7d9a8cSDavid Xu 	rw_wlock(&tidhash_lock);
1041cf7d9a8cSDavid Xu 	LIST_REMOVE(td, td_hash);
1042cf7d9a8cSDavid Xu 	rw_wunlock(&tidhash_lock);
1043cf7d9a8cSDavid Xu }
1044