kern_thread.c revision 111207
199026Sjulian/*
299026Sjulian * Copyright (C) 2001 Julian Elischer <julian@freebsd.org>.
399026Sjulian *  All rights reserved.
499026Sjulian *
599026Sjulian * Redistribution and use in source and binary forms, with or without
699026Sjulian * modification, are permitted provided that the following conditions
799026Sjulian * are met:
899026Sjulian * 1. Redistributions of source code must retain the above copyright
999026Sjulian *    notice(s), this list of conditions and the following disclaimer as
1099026Sjulian *    the first lines of this file unmodified other than the possible
1199026Sjulian *    addition of one or more copyright notices.
1299026Sjulian * 2. Redistributions in binary form must reproduce the above copyright
1399026Sjulian *    notice(s), this list of conditions and the following disclaimer in the
1499026Sjulian *    documentation and/or other materials provided with the distribution.
1599026Sjulian *
1699026Sjulian * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
1799026Sjulian * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1899026Sjulian * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1999026Sjulian * DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
2099026Sjulian * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
2199026Sjulian * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2299026Sjulian * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2399026Sjulian * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2499026Sjulian * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2599026Sjulian * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
2699026Sjulian * DAMAGE.
2799026Sjulian *
2899026Sjulian * $FreeBSD: head/sys/kern/kern_thread.c 111207 2003-02-21 07:11:38Z davidxu $
2999026Sjulian */
3099026Sjulian
3199026Sjulian#include <sys/param.h>
3299026Sjulian#include <sys/systm.h>
3399026Sjulian#include <sys/kernel.h>
3499026Sjulian#include <sys/lock.h>
3599026Sjulian#include <sys/malloc.h>
3699026Sjulian#include <sys/mutex.h>
3799026Sjulian#include <sys/proc.h>
38107029Sjulian#include <sys/smp.h>
3999026Sjulian#include <sys/sysctl.h>
40105854Sjulian#include <sys/sysproto.h>
4199026Sjulian#include <sys/filedesc.h>
42107126Sjeff#include <sys/sched.h>
4399026Sjulian#include <sys/signalvar.h>
4499026Sjulian#include <sys/sx.h>
45107126Sjeff#include <sys/tty.h>
4699026Sjulian#include <sys/user.h>
4799026Sjulian#include <sys/jail.h>
4899026Sjulian#include <sys/kse.h>
4999026Sjulian#include <sys/ktr.h>
50103410Smini#include <sys/ucontext.h>
5199026Sjulian
5299026Sjulian#include <vm/vm.h>
5399026Sjulian#include <vm/vm_object.h>
5499026Sjulian#include <vm/pmap.h>
5599026Sjulian#include <vm/uma.h>
5699026Sjulian#include <vm/vm_map.h>
5799026Sjulian
58100273Speter#include <machine/frame.h>
59100273Speter
6099026Sjulian/*
61103367Sjulian * KSEGRP related storage.
6299026Sjulian */
63103367Sjulianstatic uma_zone_t ksegrp_zone;
64103367Sjulianstatic uma_zone_t kse_zone;
6599026Sjulianstatic uma_zone_t thread_zone;
66111028Sjeffstatic uma_zone_t upcall_zone;
6799026Sjulian
68103367Sjulian/* DEBUG ONLY */
6999026SjulianSYSCTL_NODE(_kern, OID_AUTO, threads, CTLFLAG_RW, 0, "thread allocation");
70107719Sjulianstatic int thread_debug = 0;
71107719SjulianSYSCTL_INT(_kern_threads, OID_AUTO, debug, CTLFLAG_RW,
72107719Sjulian	&thread_debug, 0, "thread debug");
7399026Sjulian
74107006Sdavidxustatic int max_threads_per_proc = 30;
75107006SdavidxuSYSCTL_INT(_kern_threads, OID_AUTO, max_threads_per_proc, CTLFLAG_RW,
76103367Sjulian	&max_threads_per_proc, 0, "Limit on threads per proc");
77103367Sjulian
78107006Sdavidxustatic int max_groups_per_proc = 5;
79107006SdavidxuSYSCTL_INT(_kern_threads, OID_AUTO, max_groups_per_proc, CTLFLAG_RW,
80107006Sdavidxu	&max_groups_per_proc, 0, "Limit on thread groups per proc");
81107006Sdavidxu
82111115Sdavidxustatic int max_threads_hits;
83111115SdavidxuSYSCTL_INT(_kern_threads, OID_AUTO, max_threads_hits, CTLFLAG_RD,
84111115Sdavidxu	&max_threads_hits, 0, "");
85111115Sdavidxu
86111028Sjeffstatic int virtual_cpu;
87111028Sjeff
8899026Sjulian#define RANGEOF(type, start, end) (offsetof(type, end) - offsetof(type, start))
8999026Sjulian
90111028SjeffTAILQ_HEAD(, thread) zombie_threads = TAILQ_HEAD_INITIALIZER(zombie_threads);
91105854SjulianTAILQ_HEAD(, kse) zombie_kses = TAILQ_HEAD_INITIALIZER(zombie_kses);
92105854SjulianTAILQ_HEAD(, ksegrp) zombie_ksegrps = TAILQ_HEAD_INITIALIZER(zombie_ksegrps);
93111028SjeffTAILQ_HEAD(, kse_upcall) zombie_upcalls =
94111028Sjeff	TAILQ_HEAD_INITIALIZER(zombie_upcalls);
95111028Sjeffstruct mtx kse_zombie_lock;
96111028SjeffMTX_SYSINIT(kse_zombie_lock, &kse_zombie_lock, "kse zombie lock", MTX_SPIN);
9799026Sjulian
98107719Sjulianstatic void kse_purge(struct proc *p, struct thread *td);
99111028Sjeffstatic void kse_purge_group(struct thread *td);
100111028Sjeffstatic int thread_update_usr_ticks(struct thread *td);
101111028Sjeffstatic int thread_update_sys_ticks(struct thread *td);
102111028Sjeffstatic void thread_alloc_spare(struct thread *td, struct thread *spare);
103105854Sjulian
104111028Sjeffstatic int
105111028Sjeffsysctl_kse_virtual_cpu(SYSCTL_HANDLER_ARGS)
106111028Sjeff{
107111028Sjeff	int error, new_val;
108111028Sjeff	int def_val;
109111028Sjeff
110111028Sjeff#ifdef SMP
111111028Sjeff	def_val = mp_ncpus;
112111028Sjeff#else
113111028Sjeff	def_val = 1;
114111028Sjeff#endif
115111028Sjeff	if (virtual_cpu == 0)
116111028Sjeff		new_val = def_val;
117111028Sjeff	else
118111028Sjeff		new_val = virtual_cpu;
119111028Sjeff	error = sysctl_handle_int(oidp, &new_val, 0, req);
120111028Sjeff        if (error != 0 || req->newptr == NULL)
121111028Sjeff		return (error);
122111028Sjeff	if (new_val < 0)
123111028Sjeff		return (EINVAL);
124111028Sjeff	virtual_cpu = new_val;
125111028Sjeff	return (0);
126111028Sjeff}
127111028Sjeff
128111028Sjeff/* DEBUG ONLY */
129111028SjeffSYSCTL_PROC(_kern_threads, OID_AUTO, virtual_cpu, CTLTYPE_INT|CTLFLAG_RW,
130111028Sjeff	0, sizeof(virtual_cpu), sysctl_kse_virtual_cpu, "I",
131111028Sjeff	"debug virtual cpus");
132111028Sjeff
13399026Sjulian/*
134107719Sjulian * Prepare a thread for use.
13599026Sjulian */
13699026Sjulianstatic void
13799026Sjulianthread_ctor(void *mem, int size, void *arg)
13899026Sjulian{
13999026Sjulian	struct thread	*td;
14099026Sjulian
14199026Sjulian	td = (struct thread *)mem;
142103216Sjulian	td->td_state = TDS_INACTIVE;
14399026Sjulian}
14499026Sjulian
14599026Sjulian/*
14699026Sjulian * Reclaim a thread after use.
14799026Sjulian */
14899026Sjulianstatic void
14999026Sjulianthread_dtor(void *mem, int size, void *arg)
15099026Sjulian{
15199026Sjulian	struct thread	*td;
15299026Sjulian
15399026Sjulian	td = (struct thread *)mem;
15499026Sjulian
15599026Sjulian#ifdef INVARIANTS
15699026Sjulian	/* Verify that this thread is in a safe state to free. */
15799026Sjulian	switch (td->td_state) {
158103216Sjulian	case TDS_INHIBITED:
159103216Sjulian	case TDS_RUNNING:
160103216Sjulian	case TDS_CAN_RUN:
16199026Sjulian	case TDS_RUNQ:
16299026Sjulian		/*
16399026Sjulian		 * We must never unlink a thread that is in one of
16499026Sjulian		 * these states, because it is currently active.
16599026Sjulian		 */
16699026Sjulian		panic("bad state for thread unlinking");
16799026Sjulian		/* NOTREACHED */
168103216Sjulian	case TDS_INACTIVE:
16999026Sjulian		break;
17099026Sjulian	default:
17199026Sjulian		panic("bad thread state");
17299026Sjulian		/* NOTREACHED */
17399026Sjulian	}
17499026Sjulian#endif
17599026Sjulian}
17699026Sjulian
17799026Sjulian/*
17899026Sjulian * Initialize type-stable parts of a thread (when newly created).
17999026Sjulian */
18099026Sjulianstatic void
18199026Sjulianthread_init(void *mem, int size)
18299026Sjulian{
18399026Sjulian	struct thread	*td;
18499026Sjulian
18599026Sjulian	td = (struct thread *)mem;
186103312Sjulian	mtx_lock(&Giant);
187104354Sscottl	pmap_new_thread(td, 0);
188103312Sjulian	mtx_unlock(&Giant);
18999026Sjulian	cpu_thread_setup(td);
190107126Sjeff	td->td_sched = (struct td_sched *)&td[1];
19199026Sjulian}
19299026Sjulian
19399026Sjulian/*
19499026Sjulian * Tear down type-stable parts of a thread (just before being discarded).
19599026Sjulian */
19699026Sjulianstatic void
19799026Sjulianthread_fini(void *mem, int size)
19899026Sjulian{
19999026Sjulian	struct thread	*td;
20099026Sjulian
20199026Sjulian	td = (struct thread *)mem;
20299026Sjulian	pmap_dispose_thread(td);
20399026Sjulian}
204111028Sjeff
205107126Sjeff/*
206107126Sjeff * Initialize type-stable parts of a kse (when newly created).
207107126Sjeff */
208107126Sjeffstatic void
209107126Sjeffkse_init(void *mem, int size)
210107126Sjeff{
211107126Sjeff	struct kse	*ke;
21299026Sjulian
213107126Sjeff	ke = (struct kse *)mem;
214107126Sjeff	ke->ke_sched = (struct ke_sched *)&ke[1];
215107126Sjeff}
216111028Sjeff
217107126Sjeff/*
218107126Sjeff * Initialize type-stable parts of a ksegrp (when newly created).
219107126Sjeff */
220107126Sjeffstatic void
221107126Sjeffksegrp_init(void *mem, int size)
222107126Sjeff{
223107126Sjeff	struct ksegrp	*kg;
224107126Sjeff
225107126Sjeff	kg = (struct ksegrp *)mem;
226107126Sjeff	kg->kg_sched = (struct kg_sched *)&kg[1];
227107126Sjeff}
228107126Sjeff
229105854Sjulian/*
230111028Sjeff * KSE is linked into kse group.
231105854Sjulian */
232105854Sjulianvoid
233105854Sjuliankse_link(struct kse *ke, struct ksegrp *kg)
234105854Sjulian{
235105854Sjulian	struct proc *p = kg->kg_proc;
236105854Sjulian
237105854Sjulian	TAILQ_INSERT_HEAD(&kg->kg_kseq, ke, ke_kglist);
238105854Sjulian	kg->kg_kses++;
239111028Sjeff	ke->ke_state	= KES_UNQUEUED;
240105854Sjulian	ke->ke_proc	= p;
241105854Sjulian	ke->ke_ksegrp	= kg;
242105854Sjulian	ke->ke_thread	= NULL;
243111028Sjeff	ke->ke_oncpu	= NOCPU;
244111028Sjeff	ke->ke_flags	= 0;
245105854Sjulian}
246105854Sjulian
247105854Sjulianvoid
248105854Sjuliankse_unlink(struct kse *ke)
249105854Sjulian{
250105854Sjulian	struct ksegrp *kg;
251105854Sjulian
252105854Sjulian	mtx_assert(&sched_lock, MA_OWNED);
253105854Sjulian	kg = ke->ke_ksegrp;
254105854Sjulian	TAILQ_REMOVE(&kg->kg_kseq, ke, ke_kglist);
255111028Sjeff	if (ke->ke_state == KES_IDLE) {
256111028Sjeff		TAILQ_REMOVE(&kg->kg_iq, ke, ke_kgrlist);
257111028Sjeff		kg->kg_idle_kses--;
258105854Sjulian	}
259111028Sjeff	if (--kg->kg_kses == 0)
260111028Sjeff		ksegrp_unlink(kg);
261105854Sjulian	/*
262105854Sjulian	 * Aggregate stats from the KSE
263105854Sjulian	 */
264105854Sjulian	kse_stash(ke);
265105854Sjulian}
266105854Sjulian
267105854Sjulianvoid
268105854Sjulianksegrp_link(struct ksegrp *kg, struct proc *p)
269105854Sjulian{
270105854Sjulian
271105854Sjulian	TAILQ_INIT(&kg->kg_threads);
272105854Sjulian	TAILQ_INIT(&kg->kg_runq);	/* links with td_runq */
273105854Sjulian	TAILQ_INIT(&kg->kg_slpq);	/* links with td_runq */
274105854Sjulian	TAILQ_INIT(&kg->kg_kseq);	/* all kses in ksegrp */
275111028Sjeff	TAILQ_INIT(&kg->kg_iq);		/* all idle kses in ksegrp */
276111028Sjeff	TAILQ_INIT(&kg->kg_upcalls);	/* all upcall structure in ksegrp */
277111028Sjeff	kg->kg_proc = p;
278111028Sjeff	/*
279111028Sjeff	 * the following counters are in the -zero- section
280111028Sjeff	 * and may not need clearing
281111028Sjeff	 */
282105854Sjulian	kg->kg_numthreads = 0;
283111028Sjeff	kg->kg_runnable   = 0;
284111028Sjeff	kg->kg_kses       = 0;
285111028Sjeff	kg->kg_runq_kses  = 0; /* XXXKSE change name */
286111028Sjeff	kg->kg_idle_kses  = 0;
287111028Sjeff	kg->kg_numupcalls = 0;
288111028Sjeff	/* link it in now that it's consistent */
289105854Sjulian	p->p_numksegrps++;
290105854Sjulian	TAILQ_INSERT_HEAD(&p->p_ksegrps, kg, kg_ksegrp);
291105854Sjulian}
292105854Sjulian
293105854Sjulianvoid
294105854Sjulianksegrp_unlink(struct ksegrp *kg)
295105854Sjulian{
296105854Sjulian	struct proc *p;
297105854Sjulian
298105854Sjulian	mtx_assert(&sched_lock, MA_OWNED);
299111028Sjeff	KASSERT((kg->kg_numthreads == 0), ("ksegrp_unlink: residual threads"));
300111028Sjeff	KASSERT((kg->kg_kses == 0), ("ksegrp_unlink: residual kses"));
301111028Sjeff	KASSERT((kg->kg_numupcalls == 0), ("ksegrp_unlink: residual upcalls"));
302111028Sjeff
303105854Sjulian	p = kg->kg_proc;
304105854Sjulian	TAILQ_REMOVE(&p->p_ksegrps, kg, kg_ksegrp);
305105854Sjulian	p->p_numksegrps--;
306105854Sjulian	/*
307105854Sjulian	 * Aggregate stats from the KSE
308105854Sjulian	 */
309105854Sjulian	ksegrp_stash(kg);
310105854Sjulian}
311105854Sjulian
312111028Sjeffstruct kse_upcall *
313111028Sjeffupcall_alloc(void)
314111028Sjeff{
315111028Sjeff	struct kse_upcall *ku;
316111028Sjeff
317111125Sdavidxu	ku = uma_zalloc(upcall_zone, M_WAITOK);
318111028Sjeff	bzero(ku, sizeof(*ku));
319111028Sjeff	return (ku);
320111028Sjeff}
321111028Sjeff
322111028Sjeffvoid
323111028Sjeffupcall_free(struct kse_upcall *ku)
324111028Sjeff{
325111028Sjeff
326111028Sjeff	uma_zfree(upcall_zone, ku);
327111028Sjeff}
328111028Sjeff
329111028Sjeffvoid
330111028Sjeffupcall_link(struct kse_upcall *ku, struct ksegrp *kg)
331111028Sjeff{
332111028Sjeff
333111028Sjeff	mtx_assert(&sched_lock, MA_OWNED);
334111028Sjeff	TAILQ_INSERT_TAIL(&kg->kg_upcalls, ku, ku_link);
335111028Sjeff	ku->ku_ksegrp = kg;
336111028Sjeff	kg->kg_numupcalls++;
337111028Sjeff}
338111028Sjeff
339111028Sjeffvoid
340111028Sjeffupcall_unlink(struct kse_upcall *ku)
341111028Sjeff{
342111028Sjeff	struct ksegrp *kg = ku->ku_ksegrp;
343111028Sjeff
344111028Sjeff	mtx_assert(&sched_lock, MA_OWNED);
345111028Sjeff	KASSERT(ku->ku_owner == NULL, ("%s: have owner", __func__));
346111028Sjeff	TAILQ_REMOVE(&kg->kg_upcalls, ku, ku_link);
347111028Sjeff	kg->kg_numupcalls--;
348111028Sjeff	upcall_stash(ku);
349111028Sjeff}
350111028Sjeff
351111028Sjeffvoid
352111028Sjeffupcall_remove(struct thread *td)
353111028Sjeff{
354111028Sjeff
355111028Sjeff	if (td->td_upcall) {
356111028Sjeff		td->td_upcall->ku_owner = NULL;
357111028Sjeff		upcall_unlink(td->td_upcall);
358111028Sjeff		td->td_upcall = 0;
359111028Sjeff	}
360111028Sjeff}
361111028Sjeff
36299026Sjulian/*
363111028Sjeff * For a newly created process,
364111028Sjeff * link up all the structures and its initial threads etc.
365105854Sjulian */
366105854Sjulianvoid
367105854Sjulianproc_linkup(struct proc *p, struct ksegrp *kg,
368111028Sjeff	    struct kse *ke, struct thread *td)
369105854Sjulian{
370105854Sjulian
371105854Sjulian	TAILQ_INIT(&p->p_ksegrps);	     /* all ksegrps in proc */
372105854Sjulian	TAILQ_INIT(&p->p_threads);	     /* all threads in proc */
373105854Sjulian	TAILQ_INIT(&p->p_suspended);	     /* Threads suspended */
374105854Sjulian	p->p_numksegrps = 0;
375105854Sjulian	p->p_numthreads = 0;
376105854Sjulian
377105854Sjulian	ksegrp_link(kg, p);
378105854Sjulian	kse_link(ke, kg);
379105854Sjulian	thread_link(td, kg);
380105854Sjulian}
381105854Sjulian
382111028Sjeff/*
383111028Sjeffstruct kse_thr_interrupt_args {
384111028Sjeff	struct kse_thr_mailbox * tmbx;
385111028Sjeff};
386111028Sjeff*/
387105854Sjulianint
388105854Sjuliankse_thr_interrupt(struct thread *td, struct kse_thr_interrupt_args *uap)
389105854Sjulian{
390106180Sdavidxu	struct proc *p;
391106180Sdavidxu	struct thread *td2;
392105854Sjulian
393106242Sdavidxu	p = td->td_proc;
394111028Sjeff	if (!(p->p_flag & P_KSES) || (uap->tmbx == NULL))
395106242Sdavidxu		return (EINVAL);
396106180Sdavidxu	mtx_lock_spin(&sched_lock);
397106180Sdavidxu	FOREACH_THREAD_IN_PROC(p, td2) {
398106180Sdavidxu		if (td2->td_mailbox == uap->tmbx) {
399106180Sdavidxu			td2->td_flags |= TDF_INTERRUPT;
400106180Sdavidxu			if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR)) {
401106180Sdavidxu				if (td2->td_flags & TDF_CVWAITQ)
402106180Sdavidxu					cv_abort(td2);
403106180Sdavidxu				else
404106180Sdavidxu					abortsleep(td2);
405111028Sjeff			}
406106180Sdavidxu			mtx_unlock_spin(&sched_lock);
407106182Sdavidxu			return (0);
408106180Sdavidxu		}
409106180Sdavidxu	}
410106180Sdavidxu	mtx_unlock_spin(&sched_lock);
411106182Sdavidxu	return (ESRCH);
412105854Sjulian}
413105854Sjulian
414111028Sjeff/*
415111028Sjeffstruct kse_exit_args {
416111028Sjeff	register_t dummy;
417111028Sjeff};
418111028Sjeff*/
419105854Sjulianint
420105854Sjuliankse_exit(struct thread *td, struct kse_exit_args *uap)
421105854Sjulian{
422105854Sjulian	struct proc *p;
423105854Sjulian	struct ksegrp *kg;
424108640Sdavidxu	struct kse *ke;
425105854Sjulian
426105854Sjulian	p = td->td_proc;
427111028Sjeff	/*
428111028Sjeff	 * Only UTS can call the syscall and current group
429111028Sjeff	 * should be a threaded group.
430111028Sjeff	 */
431111028Sjeff	if ((td->td_mailbox != NULL) || (td->td_ksegrp->kg_numupcalls == 0))
432106182Sdavidxu		return (EINVAL);
433111028Sjeff	KASSERT((td->td_upcall != NULL), ("%s: not own an upcall", __func__));
434111028Sjeff
435105854Sjulian	kg = td->td_ksegrp;
436111028Sjeff	/* Serialize removing upcall */
437105854Sjulian	PROC_LOCK(p);
438105854Sjulian	mtx_lock_spin(&sched_lock);
439111028Sjeff	if ((kg->kg_numupcalls == 1) && (kg->kg_numthreads > 1)) {
440105854Sjulian		mtx_unlock_spin(&sched_lock);
441105854Sjulian		PROC_UNLOCK(p);
442105854Sjulian		return (EDEADLK);
443105854Sjulian	}
444108640Sdavidxu	ke = td->td_kse;
445111028Sjeff	upcall_remove(td);
446108640Sdavidxu	if (p->p_numthreads == 1) {
447111028Sjeff		kse_purge(p, td);
448105854Sjulian		p->p_flag &= ~P_KSES;
449105854Sjulian		mtx_unlock_spin(&sched_lock);
450105854Sjulian		PROC_UNLOCK(p);
451105854Sjulian	} else {
452111028Sjeff		if (kg->kg_numthreads == 1) { /* Shutdown a group */
453111028Sjeff			kse_purge_group(td);
454111028Sjeff			ke->ke_flags |= KEF_EXIT;
455111028Sjeff		}
456105854Sjulian		thread_exit();
457105854Sjulian		/* NOTREACHED */
458105854Sjulian	}
459106182Sdavidxu	return (0);
460105854Sjulian}
461105854Sjulian
462107719Sjulian/*
463108338Sjulian * Either becomes an upcall or waits for an awakening event and
464111028Sjeff * then becomes an upcall. Only error cases return.
465107719Sjulian */
466111028Sjeff/*
467111028Sjeffstruct kse_release_args {
468111169Sdavidxu	struct timespec *timeout;
469111028Sjeff};
470111028Sjeff*/
471105854Sjulianint
472111028Sjeffkse_release(struct thread *td, struct kse_release_args *uap)
473105854Sjulian{
474105854Sjulian	struct proc *p;
475107719Sjulian	struct ksegrp *kg;
476111169Sdavidxu	struct timespec ts, ts2, ts3, timeout;
477111169Sdavidxu	struct timeval tv;
478111169Sdavidxu	int error;
479105854Sjulian
480105854Sjulian	p = td->td_proc;
481107719Sjulian	kg = td->td_ksegrp;
482106903Sdavidxu	/*
483111028Sjeff	 * Only UTS can call the syscall and current group
484111028Sjeff	 * should be a threaded group.
485111028Sjeff	 */
486111028Sjeff	if ((td->td_mailbox != NULL) || (td->td_ksegrp->kg_numupcalls == 0))
487107719Sjulian		return (EINVAL);
488111028Sjeff	KASSERT((td->td_upcall != NULL), ("%s: not own an upcall", __func__));
489111169Sdavidxu	if (uap->timeout != NULL) {
490111169Sdavidxu		if ((error = copyin(uap->timeout, &timeout, sizeof(timeout))))
491111169Sdavidxu			return (error);
492111169Sdavidxu		getnanouptime(&ts);
493111169Sdavidxu		timespecadd(&ts, &timeout);
494111169Sdavidxu		TIMESPEC_TO_TIMEVAL(&tv, &timeout);
495111169Sdavidxu	}
496108613Sjulian	mtx_lock_spin(&sched_lock);
497108338Sjulian	/* Change OURSELF to become an upcall. */
498111028Sjeff	td->td_flags = TDF_UPCALLING;
499111042Sdavidxu	if (p->p_sflag & PS_NEEDSIGCHK)
500111042Sdavidxu		td->td_flags |= TDF_ASTPENDING;
501111169Sdavidxu	mtx_unlock_spin(&sched_lock);
502111169Sdavidxu	PROC_LOCK(p);
503111169Sdavidxu	while ((td->td_upcall->ku_flags & KUF_DOUPCALL) == 0 &&
504111169Sdavidxu	       (kg->kg_completed == NULL)) {
505111028Sjeff		kg->kg_upsleeps++;
506111169Sdavidxu		error = msleep(&kg->kg_completed, &p->p_mtx, PPAUSE|PCATCH,
507111169Sdavidxu			"kse_rel", (uap->timeout ? tvtohz(&tv) : 0));
508111028Sjeff		kg->kg_upsleeps--;
509110190Sjulian		PROC_UNLOCK(p);
510111169Sdavidxu		if (uap->timeout == NULL || error != EWOULDBLOCK)
511111169Sdavidxu			return (0);
512111169Sdavidxu		getnanouptime(&ts2);
513111169Sdavidxu		if (timespeccmp(&ts2, &ts, >=))
514111169Sdavidxu			return (0);
515111169Sdavidxu		ts3 = ts;
516111169Sdavidxu		timespecsub(&ts3, &ts2);
517111169Sdavidxu		TIMESPEC_TO_TIMEVAL(&tv, &ts3);
518111169Sdavidxu		PROC_LOCK(p);
519105854Sjulian	}
520111169Sdavidxu	PROC_UNLOCK(p);
521107719Sjulian	return (0);
522105854Sjulian}
523105854Sjulian
524105854Sjulian/* struct kse_wakeup_args {
525105854Sjulian	struct kse_mailbox *mbx;
526105854Sjulian}; */
527105854Sjulianint
528105854Sjuliankse_wakeup(struct thread *td, struct kse_wakeup_args *uap)
529105854Sjulian{
530105854Sjulian	struct proc *p;
531105854Sjulian	struct ksegrp *kg;
532111028Sjeff	struct kse_upcall *ku;
533108338Sjulian	struct thread *td2;
534105854Sjulian
535105854Sjulian	p = td->td_proc;
536108338Sjulian	td2 = NULL;
537111028Sjeff	ku = NULL;
538105854Sjulian	/* KSE-enabled processes only, please. */
539105854Sjulian	if (!(p->p_flag & P_KSES))
540111028Sjeff		return (EINVAL);
541111207Sdavidxu	if ((td->td_ksegrp->kg_numupcalls != 0) && (td->td_mailbox == NULL)) {
542111207Sdavidxu		KASSERT((td->td_upcall != NULL), ("%s: not own an upcall", __func__));
543111207Sdavidxu		if (td->td_upcall->ku_mailbox == uap->mbx)
544111207Sdavidxu			return (0);
545111207Sdavidxu	}
546111028Sjeff	PROC_LOCK(p);
547108613Sjulian	mtx_lock_spin(&sched_lock);
548105854Sjulian	if (uap->mbx) {
549105854Sjulian		FOREACH_KSEGRP_IN_PROC(p, kg) {
550111028Sjeff			FOREACH_UPCALL_IN_GROUP(kg, ku) {
551111207Sdavidxu				if (ku->ku_mailbox == uap->mbx)
552111028Sjeff					break;
553108613Sjulian			}
554111028Sjeff			if (ku)
555108338Sjulian				break;
556105854Sjulian		}
557105854Sjulian	} else {
558105854Sjulian		kg = td->td_ksegrp;
559111028Sjeff		if (kg->kg_upsleeps) {
560111028Sjeff			wakeup_one(&kg->kg_completed);
561111028Sjeff			mtx_unlock_spin(&sched_lock);
562111028Sjeff			PROC_UNLOCK(p);
563111028Sjeff			return (0);
564108338Sjulian		}
565111028Sjeff		ku = TAILQ_FIRST(&kg->kg_upcalls);
566105854Sjulian	}
567111028Sjeff	if (ku) {
568111028Sjeff		if ((td2 = ku->ku_owner) == NULL) {
569111028Sjeff			panic("%s: no owner", __func__);
570111028Sjeff		} else if (TD_ON_SLEEPQ(td2) &&
571111028Sjeff		           (td2->td_wchan == &kg->kg_completed)) {
572111028Sjeff			abortsleep(td2);
573111028Sjeff		} else {
574111028Sjeff			ku->ku_flags |= KUF_DOUPCALL;
575108613Sjulian		}
576105854Sjulian		mtx_unlock_spin(&sched_lock);
577111028Sjeff		PROC_UNLOCK(p);
578108338Sjulian		return (0);
579108613Sjulian	}
580105854Sjulian	mtx_unlock_spin(&sched_lock);
581111028Sjeff	PROC_UNLOCK(p);
582108338Sjulian	return (ESRCH);
583105854Sjulian}
584105854Sjulian
585105854Sjulian/*
586105854Sjulian * No new KSEG: first call: use current KSE, don't schedule an upcall
587111028Sjeff * All other situations, do allocate max new KSEs and schedule an upcall.
588105854Sjulian */
589105854Sjulian/* struct kse_create_args {
590105854Sjulian	struct kse_mailbox *mbx;
591105854Sjulian	int newgroup;
592105854Sjulian}; */
593105854Sjulianint
594105854Sjuliankse_create(struct thread *td, struct kse_create_args *uap)
595105854Sjulian{
596105854Sjulian	struct kse *newke;
597105854Sjulian	struct ksegrp *newkg;
598105854Sjulian	struct ksegrp *kg;
599105854Sjulian	struct proc *p;
600105854Sjulian	struct kse_mailbox mbx;
601111028Sjeff	struct kse_upcall *newku;
602111028Sjeff	int err, ncpus;
603105854Sjulian
604105854Sjulian	p = td->td_proc;
605105854Sjulian	if ((err = copyin(uap->mbx, &mbx, sizeof(mbx))))
606105854Sjulian		return (err);
607105854Sjulian
608111028Sjeff	/* Too bad, why hasn't kernel always a cpu counter !? */
609111028Sjeff#ifdef SMP
610111028Sjeff	ncpus = mp_ncpus;
611111028Sjeff#else
612111028Sjeff	ncpus = 1;
613111028Sjeff#endif
614111028Sjeff	if (thread_debug && virtual_cpu != 0)
615111028Sjeff		ncpus = virtual_cpu;
616111028Sjeff
617111028Sjeff	/* Easier to just set it than to test and set */
618111028Sjeff	p->p_flag |= P_KSES;
619105854Sjulian	kg = td->td_ksegrp;
620105854Sjulian	if (uap->newgroup) {
621111028Sjeff		/* Have race condition but it is cheap */
622107006Sdavidxu		if (p->p_numksegrps >= max_groups_per_proc)
623107006Sdavidxu			return (EPROCLIM);
624105854Sjulian		/*
625105854Sjulian		 * If we want a new KSEGRP it doesn't matter whether
626105854Sjulian		 * we have already fired up KSE mode before or not.
627111028Sjeff		 * We put the process in KSE mode and create a new KSEGRP.
628105854Sjulian		 */
629105854Sjulian		newkg = ksegrp_alloc();
630105854Sjulian		bzero(&newkg->kg_startzero, RANGEOF(struct ksegrp,
631111028Sjeff		      kg_startzero, kg_endzero));
632105854Sjulian		bcopy(&kg->kg_startcopy, &newkg->kg_startcopy,
633105854Sjulian		      RANGEOF(struct ksegrp, kg_startcopy, kg_endcopy));
634111028Sjeff		mtx_lock_spin(&sched_lock);
635111028Sjeff		ksegrp_link(newkg, p);
636111028Sjeff		if (p->p_numksegrps >= max_groups_per_proc) {
637111028Sjeff			ksegrp_unlink(newkg);
638111028Sjeff			mtx_unlock_spin(&sched_lock);
639111028Sjeff			return (EPROCLIM);
640111028Sjeff		}
641111028Sjeff		mtx_unlock_spin(&sched_lock);
642105854Sjulian	} else {
643111028Sjeff		newkg = kg;
644111028Sjeff	}
645111028Sjeff
646111028Sjeff	/*
647111028Sjeff	 * Creating upcalls more than number of physical cpu does
648111028Sjeff	 * not help performance.
649111028Sjeff	 */
650111028Sjeff	if (newkg->kg_numupcalls >= ncpus)
651111028Sjeff		return (EPROCLIM);
652111028Sjeff
653111028Sjeff	if (newkg->kg_numupcalls == 0) {
654111028Sjeff		/*
655111028Sjeff		 * Initialize KSE group, optimized for MP.
656111028Sjeff		 * Create KSEs as many as physical cpus, this increases
657111028Sjeff		 * concurrent even if userland is not MP safe and can only run
658111028Sjeff		 * on single CPU (for early version of libpthread, it is true).
659111028Sjeff		 * In ideal world, every physical cpu should execute a thread.
660111028Sjeff		 * If there is enough KSEs, threads in kernel can be
661111028Sjeff		 * executed parallel on different cpus with full speed,
662111028Sjeff		 * Concurrent in kernel shouldn't be restricted by number of
663111028Sjeff		 * upcalls userland provides.
664111028Sjeff		 * Adding more upcall structures only increases concurrent
665111028Sjeff		 * in userland.
666111028Sjeff		 * Highest performance configuration is:
667111028Sjeff		 * N kses = N upcalls = N phyiscal cpus
668105854Sjulian		 */
669111028Sjeff		while (newkg->kg_kses < ncpus) {
670105854Sjulian			newke = kse_alloc();
671111028Sjeff			bzero(&newke->ke_startzero, RANGEOF(struct kse,
672111028Sjeff			      ke_startzero, ke_endzero));
673105854Sjulian#if 0
674111028Sjeff			mtx_lock_spin(&sched_lock);
675111028Sjeff			bcopy(&ke->ke_startcopy, &newke->ke_startcopy,
676111028Sjeff			      RANGEOF(struct kse, ke_startcopy, ke_endcopy));
677111028Sjeff			mtx_unlock_spin(&sched_lock);
678105854Sjulian#endif
679111028Sjeff			mtx_lock_spin(&sched_lock);
680111028Sjeff			kse_link(newke, newkg);
681111028Sjeff			/* Add engine */
682111028Sjeff			kse_reassign(newke);
683111028Sjeff			mtx_unlock_spin(&sched_lock);
684105854Sjulian		}
685111028Sjeff	}
686111028Sjeff	newku = upcall_alloc();
687111028Sjeff	newku->ku_mailbox = uap->mbx;
688111028Sjeff	newku->ku_func = mbx.km_func;
689111028Sjeff	bcopy(&mbx.km_stack, &newku->ku_stack, sizeof(stack_t));
690111028Sjeff
691111028Sjeff	/* For the first call this may not have been set */
692111028Sjeff	if (td->td_standin == NULL)
693111028Sjeff		thread_alloc_spare(td, NULL);
694111028Sjeff
695111028Sjeff	mtx_lock_spin(&sched_lock);
696111028Sjeff	if (newkg->kg_numupcalls >= ncpus) {
697111028Sjeff		upcall_free(newku);
698105854Sjulian		mtx_unlock_spin(&sched_lock);
699111028Sjeff		return (EPROCLIM);
700111028Sjeff	}
701111028Sjeff	upcall_link(newku, newkg);
702111028Sjeff
703111028Sjeff	/*
704111028Sjeff	 * Each upcall structure has an owner thread, find which
705111028Sjeff	 * one owns it.
706111028Sjeff	 */
707111028Sjeff	if (uap->newgroup) {
708111028Sjeff		/*
709111028Sjeff		 * Because new ksegrp hasn't thread,
710111028Sjeff		 * create an initial upcall thread to own it.
711111028Sjeff		 */
712111028Sjeff		thread_schedule_upcall(td, newku);
713105854Sjulian	} else {
714105854Sjulian		/*
715111028Sjeff		 * If current thread hasn't an upcall structure,
716111028Sjeff		 * just assign the upcall to it.
717105854Sjulian		 */
718111028Sjeff		if (td->td_upcall == NULL) {
719111028Sjeff			newku->ku_owner = td;
720111028Sjeff			td->td_upcall = newku;
721111028Sjeff		} else {
722111028Sjeff			/*
723111028Sjeff			 * Create a new upcall thread to own it.
724111028Sjeff			 */
725111028Sjeff			thread_schedule_upcall(td, newku);
726111028Sjeff		}
727105854Sjulian	}
728111028Sjeff	mtx_unlock_spin(&sched_lock);
729105854Sjulian	return (0);
730105854Sjulian}
731105854Sjulian
732105854Sjulian/*
733103410Smini * Fill a ucontext_t with a thread's context information.
734103410Smini *
735103410Smini * This is an analogue to getcontext(3).
736103410Smini */
737103410Sminivoid
738103410Sminithread_getcontext(struct thread *td, ucontext_t *uc)
739103410Smini{
740103410Smini
741103464Speter/*
742103464Speter * XXX this is declared in a MD include file, i386/include/ucontext.h but
743103464Speter * is used in MI code.
744103464Speter */
745103463Speter#ifdef __i386__
746103410Smini	get_mcontext(td, &uc->uc_mcontext);
747103463Speter#endif
748103410Smini	uc->uc_sigmask = td->td_proc->p_sigmask;
749103410Smini}
750103410Smini
751103410Smini/*
752103410Smini * Set a thread's context from a ucontext_t.
753103410Smini *
754103410Smini * This is an analogue to setcontext(3).
755103410Smini */
756103410Sminiint
757103410Sminithread_setcontext(struct thread *td, ucontext_t *uc)
758103410Smini{
759103410Smini	int ret;
760103410Smini
761103464Speter/*
762103464Speter * XXX this is declared in a MD include file, i386/include/ucontext.h but
763103464Speter * is used in MI code.
764103464Speter */
765103463Speter#ifdef __i386__
766103410Smini	ret = set_mcontext(td, &uc->uc_mcontext);
767103463Speter#else
768103463Speter	ret = ENOSYS;
769103463Speter#endif
770103410Smini	if (ret == 0) {
771103410Smini		SIG_CANTMASK(uc->uc_sigmask);
772103410Smini		PROC_LOCK(td->td_proc);
773103410Smini		td->td_proc->p_sigmask = uc->uc_sigmask;
774103410Smini		PROC_UNLOCK(td->td_proc);
775103410Smini	}
776103410Smini	return (ret);
777103410Smini}
778103410Smini
779103410Smini/*
78099026Sjulian * Initialize global thread allocation resources.
78199026Sjulian */
78299026Sjulianvoid
78399026Sjulianthreadinit(void)
78499026Sjulian{
78599026Sjulian
786104437Speter#ifndef __ia64__
787107126Sjeff	thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
78899026Sjulian	    thread_ctor, thread_dtor, thread_init, thread_fini,
78999026Sjulian	    UMA_ALIGN_CACHE, 0);
790104437Speter#else
791104437Speter	/*
792104437Speter	 * XXX the ia64 kstack allocator is really lame and is at the mercy
793104437Speter	 * of contigmallloc().  This hackery is to pre-construct a whole
794104437Speter	 * pile of thread structures with associated kernel stacks early
795104437Speter	 * in the system startup while contigmalloc() still works. Once we
796104437Speter	 * have them, keep them.  Sigh.
797104437Speter	 */
798107126Sjeff	thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
799104437Speter	    thread_ctor, thread_dtor, thread_init, thread_fini,
800104437Speter	    UMA_ALIGN_CACHE, UMA_ZONE_NOFREE);
801104437Speter	uma_prealloc(thread_zone, 512);		/* XXX arbitary */
802104437Speter#endif
803107126Sjeff	ksegrp_zone = uma_zcreate("KSEGRP", sched_sizeof_ksegrp(),
804107126Sjeff	    NULL, NULL, ksegrp_init, NULL,
805103367Sjulian	    UMA_ALIGN_CACHE, 0);
806107126Sjeff	kse_zone = uma_zcreate("KSE", sched_sizeof_kse(),
807107126Sjeff	    NULL, NULL, kse_init, NULL,
808103367Sjulian	    UMA_ALIGN_CACHE, 0);
809111028Sjeff	upcall_zone = uma_zcreate("UPCALL", sizeof(struct kse_upcall),
810111028Sjeff	    NULL, NULL, NULL, NULL, UMA_ALIGN_CACHE, 0);
81199026Sjulian}
81299026Sjulian
81399026Sjulian/*
814103002Sjulian * Stash an embarasingly extra thread into the zombie thread queue.
81599026Sjulian */
81699026Sjulianvoid
81799026Sjulianthread_stash(struct thread *td)
81899026Sjulian{
819111028Sjeff	mtx_lock_spin(&kse_zombie_lock);
82099026Sjulian	TAILQ_INSERT_HEAD(&zombie_threads, td, td_runq);
821111028Sjeff	mtx_unlock_spin(&kse_zombie_lock);
82299026Sjulian}
82399026Sjulian
824103410Smini/*
825105854Sjulian * Stash an embarasingly extra kse into the zombie kse queue.
826105854Sjulian */
827105854Sjulianvoid
828105854Sjuliankse_stash(struct kse *ke)
829105854Sjulian{
830111028Sjeff	mtx_lock_spin(&kse_zombie_lock);
831105854Sjulian	TAILQ_INSERT_HEAD(&zombie_kses, ke, ke_procq);
832111028Sjeff	mtx_unlock_spin(&kse_zombie_lock);
833105854Sjulian}
834105854Sjulian
835105854Sjulian/*
836111028Sjeff * Stash an embarasingly extra upcall into the zombie upcall queue.
837111028Sjeff */
838111028Sjeff
839111028Sjeffvoid
840111028Sjeffupcall_stash(struct kse_upcall *ku)
841111028Sjeff{
842111028Sjeff	mtx_lock_spin(&kse_zombie_lock);
843111028Sjeff	TAILQ_INSERT_HEAD(&zombie_upcalls, ku, ku_link);
844111028Sjeff	mtx_unlock_spin(&kse_zombie_lock);
845111028Sjeff}
846111028Sjeff
847111028Sjeff/*
848105854Sjulian * Stash an embarasingly extra ksegrp into the zombie ksegrp queue.
849105854Sjulian */
850105854Sjulianvoid
851105854Sjulianksegrp_stash(struct ksegrp *kg)
852105854Sjulian{
853111028Sjeff	mtx_lock_spin(&kse_zombie_lock);
854105854Sjulian	TAILQ_INSERT_HEAD(&zombie_ksegrps, kg, kg_ksegrp);
855111028Sjeff	mtx_unlock_spin(&kse_zombie_lock);
856105854Sjulian}
857105854Sjulian
858105854Sjulian/*
859111028Sjeff * Reap zombie kse resource.
86099026Sjulian */
86199026Sjulianvoid
86299026Sjulianthread_reap(void)
86399026Sjulian{
864105854Sjulian	struct thread *td_first, *td_next;
865105854Sjulian	struct kse *ke_first, *ke_next;
866105854Sjulian	struct ksegrp *kg_first, * kg_next;
867111028Sjeff	struct kse_upcall *ku_first, *ku_next;
86899026Sjulian
86999026Sjulian	/*
870111028Sjeff	 * Don't even bother to lock if none at this instant,
871111028Sjeff	 * we really don't care about the next instant..
87299026Sjulian	 */
873105854Sjulian	if ((!TAILQ_EMPTY(&zombie_threads))
874105854Sjulian	    || (!TAILQ_EMPTY(&zombie_kses))
875111028Sjeff	    || (!TAILQ_EMPTY(&zombie_ksegrps))
876111028Sjeff	    || (!TAILQ_EMPTY(&zombie_upcalls))) {
877111028Sjeff		mtx_lock_spin(&kse_zombie_lock);
878105854Sjulian		td_first = TAILQ_FIRST(&zombie_threads);
879105854Sjulian		ke_first = TAILQ_FIRST(&zombie_kses);
880105854Sjulian		kg_first = TAILQ_FIRST(&zombie_ksegrps);
881111028Sjeff		ku_first = TAILQ_FIRST(&zombie_upcalls);
882105854Sjulian		if (td_first)
883105854Sjulian			TAILQ_INIT(&zombie_threads);
884105854Sjulian		if (ke_first)
885105854Sjulian			TAILQ_INIT(&zombie_kses);
886105854Sjulian		if (kg_first)
887105854Sjulian			TAILQ_INIT(&zombie_ksegrps);
888111028Sjeff		if (ku_first)
889111028Sjeff			TAILQ_INIT(&zombie_upcalls);
890111028Sjeff		mtx_unlock_spin(&kse_zombie_lock);
891105854Sjulian		while (td_first) {
892105854Sjulian			td_next = TAILQ_NEXT(td_first, td_runq);
893111028Sjeff			if (td_first->td_ucred)
894111028Sjeff				crfree(td_first->td_ucred);
895105854Sjulian			thread_free(td_first);
896105854Sjulian			td_first = td_next;
89799026Sjulian		}
898105854Sjulian		while (ke_first) {
899105854Sjulian			ke_next = TAILQ_NEXT(ke_first, ke_procq);
900105854Sjulian			kse_free(ke_first);
901105854Sjulian			ke_first = ke_next;
902105854Sjulian		}
903105854Sjulian		while (kg_first) {
904105854Sjulian			kg_next = TAILQ_NEXT(kg_first, kg_ksegrp);
905105854Sjulian			ksegrp_free(kg_first);
906105854Sjulian			kg_first = kg_next;
907105854Sjulian		}
908111028Sjeff		while (ku_first) {
909111028Sjeff			ku_next = TAILQ_NEXT(ku_first, ku_link);
910111028Sjeff			upcall_free(ku_first);
911111028Sjeff			ku_first = ku_next;
912111028Sjeff		}
91399026Sjulian	}
91499026Sjulian}
91599026Sjulian
91699026Sjulian/*
917103367Sjulian * Allocate a ksegrp.
918103367Sjulian */
919103367Sjulianstruct ksegrp *
920103367Sjulianksegrp_alloc(void)
921103367Sjulian{
922111119Simp	return (uma_zalloc(ksegrp_zone, M_WAITOK));
923103367Sjulian}
924103367Sjulian
925103367Sjulian/*
926103367Sjulian * Allocate a kse.
927103367Sjulian */
928103367Sjulianstruct kse *
929103367Sjuliankse_alloc(void)
930103367Sjulian{
931111119Simp	return (uma_zalloc(kse_zone, M_WAITOK));
932103367Sjulian}
933103367Sjulian
934103367Sjulian/*
93599026Sjulian * Allocate a thread.
93699026Sjulian */
93799026Sjulianstruct thread *
93899026Sjulianthread_alloc(void)
93999026Sjulian{
94099026Sjulian	thread_reap(); /* check if any zombies to get */
941111119Simp	return (uma_zalloc(thread_zone, M_WAITOK));
94299026Sjulian}
94399026Sjulian
94499026Sjulian/*
945103367Sjulian * Deallocate a ksegrp.
946103367Sjulian */
947103367Sjulianvoid
948103367Sjulianksegrp_free(struct ksegrp *td)
949103367Sjulian{
950103367Sjulian	uma_zfree(ksegrp_zone, td);
951103367Sjulian}
952103367Sjulian
953103367Sjulian/*
954103367Sjulian * Deallocate a kse.
955103367Sjulian */
956103367Sjulianvoid
957103367Sjuliankse_free(struct kse *td)
958103367Sjulian{
959103367Sjulian	uma_zfree(kse_zone, td);
960103367Sjulian}
961103367Sjulian
962103367Sjulian/*
96399026Sjulian * Deallocate a thread.
96499026Sjulian */
96599026Sjulianvoid
96699026Sjulianthread_free(struct thread *td)
96799026Sjulian{
968107719Sjulian
969107719Sjulian	cpu_thread_clean(td);
97099026Sjulian	uma_zfree(thread_zone, td);
97199026Sjulian}
97299026Sjulian
97399026Sjulian/*
97499026Sjulian * Store the thread context in the UTS's mailbox.
975104031Sjulian * then add the mailbox at the head of a list we are building in user space.
976104031Sjulian * The list is anchored in the ksegrp structure.
97799026Sjulian */
97899026Sjulianint
97999026Sjulianthread_export_context(struct thread *td)
98099026Sjulian{
981104503Sjmallett	struct proc *p;
982104031Sjulian	struct ksegrp *kg;
983104031Sjulian	uintptr_t mbx;
984104031Sjulian	void *addr;
985111028Sjeff	int error,temp;
986103410Smini	ucontext_t uc;
98799026Sjulian
988104503Sjmallett	p = td->td_proc;
989104503Sjmallett	kg = td->td_ksegrp;
990104503Sjmallett
991104031Sjulian	/* Export the user/machine context. */
992111028Sjeff	addr = (void *)(&td->td_mailbox->tm_context);
993104031Sjulian	error = copyin(addr, &uc, sizeof(ucontext_t));
994108338Sjulian	if (error)
995108338Sjulian		goto bad;
996104031Sjulian
997108338Sjulian	thread_getcontext(td, &uc);
998108338Sjulian	error = copyout(&uc, addr, sizeof(ucontext_t));
999108338Sjulian	if (error)
1000108338Sjulian		goto bad;
1001108338Sjulian
1002111028Sjeff	/* Exports clock ticks in kernel mode */
1003111028Sjeff	addr = (caddr_t)(&td->td_mailbox->tm_sticks);
1004111028Sjeff	temp = fuword(addr) + td->td_usticks;
1005111028Sjeff	if (suword(addr, temp))
1006111028Sjeff		goto bad;
1007111028Sjeff
1008111028Sjeff	/* Get address in latest mbox of list pointer */
1009104031Sjulian	addr = (void *)(&td->td_mailbox->tm_next);
1010104031Sjulian	/*
1011104031Sjulian	 * Put the saved address of the previous first
1012104031Sjulian	 * entry into this one
1013104031Sjulian	 */
1014104031Sjulian	for (;;) {
1015104031Sjulian		mbx = (uintptr_t)kg->kg_completed;
1016104031Sjulian		if (suword(addr, mbx)) {
1017108338Sjulian			error = EFAULT;
1018107034Sdavidxu			goto bad;
1019104031Sjulian		}
1020104126Sjulian		PROC_LOCK(p);
1021104031Sjulian		if (mbx == (uintptr_t)kg->kg_completed) {
1022104031Sjulian			kg->kg_completed = td->td_mailbox;
1023111028Sjeff			/*
1024111028Sjeff			 * The thread context may be taken away by
1025111028Sjeff			 * other upcall threads when we unlock
1026111028Sjeff			 * process lock. it's no longer valid to
1027111028Sjeff			 * use it again in any other places.
1028111028Sjeff			 */
1029111028Sjeff			td->td_mailbox = NULL;
1030104126Sjulian			PROC_UNLOCK(p);
1031104031Sjulian			break;
1032104031Sjulian		}
1033104126Sjulian		PROC_UNLOCK(p);
1034104031Sjulian	}
1035111028Sjeff	td->td_usticks = 0;
1036104031Sjulian	return (0);
1037107034Sdavidxu
1038107034Sdavidxubad:
1039107034Sdavidxu	PROC_LOCK(p);
1040107034Sdavidxu	psignal(p, SIGSEGV);
1041107034Sdavidxu	PROC_UNLOCK(p);
1042111028Sjeff	/* The mailbox is bad, don't use it */
1043111028Sjeff	td->td_mailbox = NULL;
1044111028Sjeff	td->td_usticks = 0;
1045108338Sjulian	return (error);
1046104031Sjulian}
104799026Sjulian
1048104031Sjulian/*
1049104031Sjulian * Take the list of completed mailboxes for this KSEGRP and put them on this
1050111028Sjeff * upcall's mailbox as it's the next one going up.
1051104031Sjulian */
1052104031Sjulianstatic int
1053111028Sjeffthread_link_mboxes(struct ksegrp *kg, struct kse_upcall *ku)
1054104031Sjulian{
1055104126Sjulian	struct proc *p = kg->kg_proc;
1056104031Sjulian	void *addr;
1057104031Sjulian	uintptr_t mbx;
1058104031Sjulian
1059111028Sjeff	addr = (void *)(&ku->ku_mailbox->km_completed);
1060104031Sjulian	for (;;) {
1061104031Sjulian		mbx = (uintptr_t)kg->kg_completed;
1062104031Sjulian		if (suword(addr, mbx)) {
1063104126Sjulian			PROC_LOCK(p);
1064104126Sjulian			psignal(p, SIGSEGV);
1065104126Sjulian			PROC_UNLOCK(p);
1066104031Sjulian			return (EFAULT);
1067104031Sjulian		}
1068104031Sjulian		/* XXXKSE could use atomic CMPXCH here */
1069104126Sjulian		PROC_LOCK(p);
1070104031Sjulian		if (mbx == (uintptr_t)kg->kg_completed) {
1071104031Sjulian			kg->kg_completed = NULL;
1072104126Sjulian			PROC_UNLOCK(p);
1073104031Sjulian			break;
1074104031Sjulian		}
1075104126Sjulian		PROC_UNLOCK(p);
107699026Sjulian	}
1077104031Sjulian	return (0);
107899026Sjulian}
107999026Sjulian
108099026Sjulian/*
1081107034Sdavidxu * This function should be called at statclock interrupt time
1082107034Sdavidxu */
1083107034Sdavidxuint
1084111028Sjeffthread_statclock(int user)
1085107034Sdavidxu{
1086107034Sdavidxu	struct thread *td = curthread;
1087107034Sdavidxu
1088111028Sjeff	if (td->td_ksegrp->kg_numupcalls == 0)
1089111028Sjeff		return (-1);
1090107034Sdavidxu	if (user) {
1091107034Sdavidxu		/* Current always do via ast() */
1092111032Sjulian		td->td_flags |= (TDF_USTATCLOCK|TDF_ASTPENDING);
1093111028Sjeff		td->td_uuticks++;
1094107034Sdavidxu	} else {
1095107034Sdavidxu		if (td->td_mailbox != NULL)
1096111028Sjeff			td->td_usticks++;
1097111028Sjeff		else {
1098111028Sjeff			/* XXXKSE
1099111028Sjeff		 	 * We will call thread_user_enter() for every
1100111028Sjeff			 * kernel entry in future, so if the thread mailbox
1101111028Sjeff			 * is NULL, it must be a UTS kernel, don't account
1102111028Sjeff			 * clock ticks for it.
1103111028Sjeff			 */
1104111028Sjeff		}
1105107034Sdavidxu	}
1106111028Sjeff	return (0);
1107107034Sdavidxu}
1108107034Sdavidxu
1109111028Sjeff/*
1110111028Sjeff * Export user mode state clock ticks
1111111028Sjeff */
1112107034Sdavidxustatic int
1113111028Sjeffthread_update_usr_ticks(struct thread *td)
1114107034Sdavidxu{
1115107034Sdavidxu	struct proc *p = td->td_proc;
1116107034Sdavidxu	struct kse_thr_mailbox *tmbx;
1117111028Sjeff	struct kse_upcall *ku;
1118107034Sdavidxu	caddr_t addr;
1119111028Sjeff	uint uticks;
1120107034Sdavidxu
1121111028Sjeff	if ((ku = td->td_upcall) == NULL)
1122111028Sjeff		return (-1);
1123111028Sjeff
1124111028Sjeff	tmbx = (void *)fuword((void *)&ku->ku_mailbox->km_curthread);
1125107034Sdavidxu	if ((tmbx == NULL) || (tmbx == (void *)-1))
1126111028Sjeff		return (-1);
1127111028Sjeff	uticks = td->td_uuticks;
1128111028Sjeff	td->td_uuticks = 0;
1129107034Sdavidxu	if (uticks) {
1130111028Sjeff		addr = (caddr_t)&tmbx->tm_uticks;
1131107034Sdavidxu		uticks += fuword(addr);
1132111028Sjeff		if (suword(addr, uticks)) {
1133111028Sjeff			PROC_LOCK(p);
1134111028Sjeff			psignal(p, SIGSEGV);
1135111028Sjeff			PROC_UNLOCK(p);
1136111028Sjeff			return (-2);
1137111028Sjeff		}
1138107034Sdavidxu	}
1139111028Sjeff	return (0);
1140111028Sjeff}
1141111028Sjeff
1142111028Sjeff/*
1143111028Sjeff * Export kernel mode state clock ticks
1144111028Sjeff */
1145111028Sjeff
1146111028Sjeffstatic int
1147111028Sjeffthread_update_sys_ticks(struct thread *td)
1148111028Sjeff{
1149111028Sjeff	struct proc *p = td->td_proc;
1150111028Sjeff	caddr_t addr;
1151111028Sjeff	int sticks;
1152111028Sjeff
1153111028Sjeff	if (td->td_mailbox == NULL)
1154111028Sjeff		return (-1);
1155111028Sjeff	if (td->td_usticks == 0)
1156111028Sjeff		return (0);
1157111028Sjeff	addr = (caddr_t)&td->td_mailbox->tm_sticks;
1158111028Sjeff	sticks = fuword(addr);
1159111028Sjeff	sticks += td->td_usticks;
1160111028Sjeff	td->td_usticks = 0;
1161111028Sjeff	if (suword(addr, sticks)) {
1162111028Sjeff		PROC_LOCK(p);
1163111028Sjeff		psignal(p, SIGSEGV);
1164111028Sjeff		PROC_UNLOCK(p);
1165111028Sjeff		return (-2);
1166107034Sdavidxu	}
1167111028Sjeff	return (0);
1168107034Sdavidxu}
1169107034Sdavidxu
1170107034Sdavidxu/*
117199026Sjulian * Discard the current thread and exit from its context.
117299026Sjulian *
117399026Sjulian * Because we can't free a thread while we're operating under its context,
1174107719Sjulian * push the current thread into our CPU's deadthread holder. This means
1175107719Sjulian * we needn't worry about someone else grabbing our context before we
1176107719Sjulian * do a cpu_throw().
117799026Sjulian */
117899026Sjulianvoid
117999026Sjulianthread_exit(void)
118099026Sjulian{
118199026Sjulian	struct thread *td;
118299026Sjulian	struct kse *ke;
118399026Sjulian	struct proc *p;
118499026Sjulian	struct ksegrp	*kg;
118599026Sjulian
118699026Sjulian	td = curthread;
118799026Sjulian	kg = td->td_ksegrp;
118899026Sjulian	p = td->td_proc;
118999026Sjulian	ke = td->td_kse;
119099026Sjulian
119199026Sjulian	mtx_assert(&sched_lock, MA_OWNED);
1192102581Sjulian	KASSERT(p != NULL, ("thread exiting without a process"));
1193102581Sjulian	KASSERT(ke != NULL, ("thread exiting without a kse"));
1194102581Sjulian	KASSERT(kg != NULL, ("thread exiting without a kse group"));
119599026Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
119699026Sjulian	CTR1(KTR_PROC, "thread_exit: thread %p", td);
119799026Sjulian	KASSERT(!mtx_owned(&Giant), ("dying thread owns giant"));
119899026Sjulian
1199104695Sjulian	if (td->td_standin != NULL) {
1200104695Sjulian		thread_stash(td->td_standin);
1201104695Sjulian		td->td_standin = NULL;
1202104695Sjulian	}
1203104695Sjulian
120499026Sjulian	cpu_thread_exit(td);	/* XXXSMP */
120599026Sjulian
1206102581Sjulian	/*
1207103002Sjulian	 * The last thread is left attached to the process
1208103002Sjulian	 * So that the whole bundle gets recycled. Skip
1209103002Sjulian	 * all this stuff.
1210102581Sjulian	 */
1211103002Sjulian	if (p->p_numthreads > 1) {
1212105854Sjulian		/*
1213105854Sjulian		 * Unlink this thread from its proc and the kseg.
1214105854Sjulian		 * In keeping with the other structs we probably should
1215105854Sjulian		 * have a thread_unlink() that does some of this but it
1216105854Sjulian		 * would only be called from here (I think) so it would
1217105854Sjulian		 * be a waste. (might be useful for proc_fini() as well.)
1218105854Sjulian 		 */
1219103002Sjulian		TAILQ_REMOVE(&p->p_threads, td, td_plist);
1220103002Sjulian		p->p_numthreads--;
1221103002Sjulian		TAILQ_REMOVE(&kg->kg_threads, td, td_kglist);
1222103002Sjulian		kg->kg_numthreads--;
1223111115Sdavidxu		if (p->p_maxthrwaits)
1224111115Sdavidxu			wakeup(&p->p_numthreads);
1225103002Sjulian		/*
1226103002Sjulian		 * The test below is NOT true if we are the
1227103002Sjulian		 * sole exiting thread. P_STOPPED_SNGL is unset
1228103002Sjulian		 * in exit1() after it is the only survivor.
1229103002Sjulian		 */
1230103002Sjulian		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1231103002Sjulian			if (p->p_numthreads == p->p_suspcount) {
1232103216Sjulian				thread_unsuspend_one(p->p_singlethread);
1233103002Sjulian			}
123499026Sjulian		}
1235104695Sjulian
1236111028Sjeff		/*
1237111028Sjeff		 * Because each upcall structure has an owner thread,
1238111028Sjeff		 * owner thread exits only when process is in exiting
1239111028Sjeff		 * state, so upcall to userland is no longer needed,
1240111028Sjeff		 * deleting upcall structure is safe here.
1241111028Sjeff		 * So when all threads in a group is exited, all upcalls
1242111028Sjeff		 * in the group should be automatically freed.
1243111028Sjeff		 */
1244111028Sjeff		if (td->td_upcall)
1245111028Sjeff			upcall_remove(td);
1246111028Sjeff
1247104695Sjulian		ke->ke_state = KES_UNQUEUED;
1248111028Sjeff		ke->ke_thread = NULL;
1249104695Sjulian		/*
1250108338Sjulian		 * Decide what to do with the KSE attached to this thread.
1251104695Sjulian		 */
1252111028Sjeff		if (ke->ke_flags & KEF_EXIT)
1253105854Sjulian			kse_unlink(ke);
1254111028Sjeff		else
1255105854Sjulian			kse_reassign(ke);
1256105854Sjulian		PROC_UNLOCK(p);
1257111028Sjeff		td->td_kse	= NULL;
1258105854Sjulian		td->td_state	= TDS_INACTIVE;
1259105854Sjulian		td->td_proc	= NULL;
1260105854Sjulian		td->td_ksegrp	= NULL;
1261105854Sjulian		td->td_last_kse	= NULL;
1262107719Sjulian		PCPU_SET(deadthread, td);
1263103002Sjulian	} else {
1264103002Sjulian		PROC_UNLOCK(p);
126599026Sjulian	}
126699026Sjulian	cpu_throw();
126799026Sjulian	/* NOTREACHED */
126899026Sjulian}
126999026Sjulian
1270107719Sjulian/*
1271107719Sjulian * Do any thread specific cleanups that may be needed in wait()
1272107719Sjulian * called with Giant held, proc and schedlock not held.
1273107719Sjulian */
1274107719Sjulianvoid
1275107719Sjulianthread_wait(struct proc *p)
1276107719Sjulian{
1277107719Sjulian	struct thread *td;
1278107719Sjulian
1279107719Sjulian	KASSERT((p->p_numthreads == 1), ("Muliple threads in wait1()"));
1280107719Sjulian	KASSERT((p->p_numksegrps == 1), ("Muliple ksegrps in wait1()"));
1281107719Sjulian	FOREACH_THREAD_IN_PROC(p, td) {
1282107719Sjulian		if (td->td_standin != NULL) {
1283107719Sjulian			thread_free(td->td_standin);
1284107719Sjulian			td->td_standin = NULL;
1285107719Sjulian		}
1286107719Sjulian		cpu_thread_clean(td);
1287107719Sjulian	}
1288107719Sjulian	thread_reap();	/* check for zombie threads etc. */
1289107719Sjulian}
1290107719Sjulian
129199026Sjulian/*
129299026Sjulian * Link a thread to a process.
1293103002Sjulian * set up anything that needs to be initialized for it to
1294103002Sjulian * be used by the process.
129599026Sjulian *
129699026Sjulian * Note that we do not link to the proc's ucred here.
129799026Sjulian * The thread is linked as if running but no KSE assigned.
129899026Sjulian */
129999026Sjulianvoid
130099026Sjulianthread_link(struct thread *td, struct ksegrp *kg)
130199026Sjulian{
130299026Sjulian	struct proc *p;
130399026Sjulian
130499026Sjulian	p = kg->kg_proc;
1305111028Sjeff	td->td_state    = TDS_INACTIVE;
1306111028Sjeff	td->td_proc     = p;
1307111028Sjeff	td->td_ksegrp   = kg;
1308111028Sjeff	td->td_last_kse = NULL;
1309111028Sjeff	td->td_flags    = 0;
1310111028Sjeff	td->td_kse      = NULL;
131199026Sjulian
1312103002Sjulian	LIST_INIT(&td->td_contested);
1313103002Sjulian	callout_init(&td->td_slpcallout, 1);
131499026Sjulian	TAILQ_INSERT_HEAD(&p->p_threads, td, td_plist);
131599026Sjulian	TAILQ_INSERT_HEAD(&kg->kg_threads, td, td_kglist);
131699026Sjulian	p->p_numthreads++;
131799026Sjulian	kg->kg_numthreads++;
131899026Sjulian}
131999026Sjulian
1320111028Sjeff/*
1321111028Sjeff * Purge a ksegrp resource. When a ksegrp is preparing to
1322111028Sjeff * exit, it calls this function.
1323111028Sjeff */
1324105854Sjulianvoid
1325111028Sjeffkse_purge_group(struct thread *td)
1326111028Sjeff{
1327111028Sjeff	struct ksegrp *kg;
1328111028Sjeff	struct kse *ke;
1329111028Sjeff
1330111028Sjeff	kg = td->td_ksegrp;
1331111028Sjeff 	KASSERT(kg->kg_numthreads == 1, ("%s: bad thread number", __func__));
1332111028Sjeff	while ((ke = TAILQ_FIRST(&kg->kg_iq)) != NULL) {
1333111028Sjeff		KASSERT(ke->ke_state == KES_IDLE,
1334111028Sjeff			("%s: wrong idle KSE state", __func__));
1335111028Sjeff		kse_unlink(ke);
1336111028Sjeff	}
1337111028Sjeff	KASSERT((kg->kg_kses == 1),
1338111028Sjeff		("%s: ksegrp still has %d KSEs", __func__, kg->kg_kses));
1339111028Sjeff	KASSERT((kg->kg_numupcalls == 0),
1340111028Sjeff	        ("%s: ksegrp still has %d upcall datas",
1341111028Sjeff		__func__, kg->kg_numupcalls));
1342111028Sjeff}
1343111028Sjeff
1344111028Sjeff/*
1345111028Sjeff * Purge a process's KSE resource. When a process is preparing to
1346111028Sjeff * exit, it calls kse_purge to release any extra KSE resources in
1347111028Sjeff * the process.
1348111028Sjeff */
1349111028Sjeffvoid
1350105854Sjuliankse_purge(struct proc *p, struct thread *td)
1351105854Sjulian{
1352105854Sjulian	struct ksegrp *kg;
1353111028Sjeff	struct kse *ke;
1354105854Sjulian
1355105854Sjulian 	KASSERT(p->p_numthreads == 1, ("bad thread number"));
1356105854Sjulian	mtx_lock_spin(&sched_lock);
1357105854Sjulian	while ((kg = TAILQ_FIRST(&p->p_ksegrps)) != NULL) {
1358105854Sjulian		TAILQ_REMOVE(&p->p_ksegrps, kg, kg_ksegrp);
1359105854Sjulian		p->p_numksegrps--;
1360111028Sjeff		/*
1361111028Sjeff		 * There is no ownership for KSE, after all threads
1362111028Sjeff		 * in the group exited, it is possible that some KSEs
1363111028Sjeff		 * were left in idle queue, gc them now.
1364111028Sjeff		 */
1365111028Sjeff		while ((ke = TAILQ_FIRST(&kg->kg_iq)) != NULL) {
1366111028Sjeff			KASSERT(ke->ke_state == KES_IDLE,
1367111028Sjeff			   ("%s: wrong idle KSE state", __func__));
1368111028Sjeff			TAILQ_REMOVE(&kg->kg_iq, ke, ke_kgrlist);
1369111028Sjeff			kg->kg_idle_kses--;
1370111028Sjeff			TAILQ_REMOVE(&kg->kg_kseq, ke, ke_kglist);
1371111028Sjeff			kg->kg_kses--;
1372111028Sjeff			kse_stash(ke);
1373111028Sjeff		}
1374105854Sjulian		KASSERT(((kg->kg_kses == 0) && (kg != td->td_ksegrp)) ||
1375111028Sjeff		        ((kg->kg_kses == 1) && (kg == td->td_ksegrp)),
1376111028Sjeff		        ("ksegrp has wrong kg_kses: %d", kg->kg_kses));
1377111028Sjeff		KASSERT((kg->kg_numupcalls == 0),
1378111028Sjeff		        ("%s: ksegrp still has %d upcall datas",
1379111028Sjeff			__func__, kg->kg_numupcalls));
1380111028Sjeff
1381111028Sjeff		if (kg != td->td_ksegrp)
1382105854Sjulian			ksegrp_stash(kg);
1383105854Sjulian	}
1384105854Sjulian	TAILQ_INSERT_HEAD(&p->p_ksegrps, td->td_ksegrp, kg_ksegrp);
1385105854Sjulian	p->p_numksegrps++;
1386105854Sjulian	mtx_unlock_spin(&sched_lock);
1387105854Sjulian}
1388105854Sjulian
1389111028Sjeff/*
1390111028Sjeff * This function is intended to be used to initialize a spare thread
1391111028Sjeff * for upcall. Initialize thread's large data area outside sched_lock
1392111028Sjeff * for thread_schedule_upcall().
1393111028Sjeff */
1394111028Sjeffvoid
1395111028Sjeffthread_alloc_spare(struct thread *td, struct thread *spare)
1396111028Sjeff{
1397111028Sjeff	if (td->td_standin)
1398111028Sjeff		return;
1399111028Sjeff	if (spare == NULL)
1400111028Sjeff		spare = thread_alloc();
1401111028Sjeff	td->td_standin = spare;
1402111028Sjeff	bzero(&spare->td_startzero,
1403111028Sjeff	    (unsigned)RANGEOF(struct thread, td_startzero, td_endzero));
1404111028Sjeff	spare->td_proc = td->td_proc;
1405111028Sjeff	/* Setup PCB and fork address */
1406111028Sjeff	cpu_set_upcall(spare, td->td_pcb);
1407111028Sjeff	/*
1408111028Sjeff	 * XXXKSE do we really need this? (default values for the
1409111028Sjeff	 * frame).
1410111028Sjeff	 */
1411111028Sjeff	bcopy(td->td_frame, spare->td_frame, sizeof(struct trapframe));
1412111028Sjeff	spare->td_ucred = crhold(td->td_ucred);
1413111028Sjeff}
1414105854Sjulian
141599026Sjulian/*
1416103410Smini * Create a thread and schedule it for upcall on the KSE given.
1417108338Sjulian * Use our thread's standin so that we don't have to allocate one.
141899026Sjulian */
141999026Sjulianstruct thread *
1420111028Sjeffthread_schedule_upcall(struct thread *td, struct kse_upcall *ku)
142199026Sjulian{
142299026Sjulian	struct thread *td2;
142399026Sjulian
142499026Sjulian	mtx_assert(&sched_lock, MA_OWNED);
1425104695Sjulian
1426104695Sjulian	/*
1427111028Sjeff	 * Schedule an upcall thread on specified kse_upcall,
1428111028Sjeff	 * the kse_upcall must be free.
1429111028Sjeff	 * td must have a spare thread.
1430104695Sjulian	 */
1431111028Sjeff	KASSERT(ku->ku_owner == NULL, ("%s: upcall has owner", __func__));
1432104695Sjulian	if ((td2 = td->td_standin) != NULL) {
1433104695Sjulian		td->td_standin = NULL;
143499026Sjulian	} else {
1435111028Sjeff		panic("no reserve thread when scheduling an upcall");
1436106182Sdavidxu		return (NULL);
143799026Sjulian	}
143899026Sjulian	CTR3(KTR_PROC, "thread_schedule_upcall: thread %p (pid %d, %s)",
1439104695Sjulian	     td2, td->td_proc->p_pid, td->td_proc->p_comm);
1440103002Sjulian	bcopy(&td->td_startcopy, &td2->td_startcopy,
1441103002Sjulian	    (unsigned) RANGEOF(struct thread, td_startcopy, td_endcopy));
1442111028Sjeff	thread_link(td2, ku->ku_ksegrp);
1443111028Sjeff	/* Let the new thread become owner of the upcall */
1444111028Sjeff	ku->ku_owner   = td2;
1445111028Sjeff	td2->td_upcall = ku;
1446111028Sjeff	td2->td_flags  = TDF_UPCALLING;
1447111041Sdavidxu	if (td->td_proc->p_sflag & PS_NEEDSIGCHK)
1448111041Sdavidxu		td2->td_flags |= TDF_ASTPENDING;
1449111028Sjeff	td2->td_kse    = NULL;
1450111028Sjeff	td2->td_state  = TDS_CAN_RUN;
1451104695Sjulian	td2->td_inhibitors = 0;
1452111028Sjeff	setrunqueue(td2);
1453104695Sjulian	return (td2);	/* bogus.. should be a void function */
145499026Sjulian}
145599026Sjulian
1456111033Sjeffvoid
1457111033Sjeffthread_signal_add(struct thread *td, int sig)
1458103410Smini{
1459111033Sjeff	struct kse_upcall *ku;
1460111033Sjeff	struct proc *p;
1461103410Smini	sigset_t ss;
1462103410Smini	int error;
1463103410Smini
1464111033Sjeff	PROC_LOCK_ASSERT(td->td_proc, MA_OWNED);
1465111033Sjeff	td = curthread;
1466111033Sjeff	ku = td->td_upcall;
1467111033Sjeff	p = td->td_proc;
1468111033Sjeff
1469103410Smini	PROC_UNLOCK(p);
1470111033Sjeff	error = copyin(&ku->ku_mailbox->km_sigscaught, &ss, sizeof(sigset_t));
1471103410Smini	if (error)
1472111033Sjeff		goto error;
1473111033Sjeff
1474103410Smini	SIGADDSET(ss, sig);
1475111033Sjeff
1476111033Sjeff	error = copyout(&ss, &ku->ku_mailbox->km_sigscaught, sizeof(sigset_t));
1477111033Sjeff	if (error)
1478111033Sjeff		goto error;
1479111033Sjeff
1480103410Smini	PROC_LOCK(p);
1481111033Sjeff	return;
1482111033Sjefferror:
1483111033Sjeff	PROC_LOCK(p);
1484111033Sjeff	sigexit(td, SIGILL);
1485111033Sjeff}
1486111033Sjeff
1487111033Sjeff
1488111033Sjeff/*
1489111033Sjeff * Schedule an upcall to notify a KSE process recieved signals.
1490111033Sjeff *
1491111033Sjeff */
1492111033Sjeffvoid
1493111033Sjeffthread_signal_upcall(struct thread *td)
1494111033Sjeff{
1495103410Smini	mtx_lock_spin(&sched_lock);
1496111033Sjeff	td->td_flags |= TDF_UPCALLING;
1497103410Smini	mtx_unlock_spin(&sched_lock);
1498111033Sjeff
1499111033Sjeff	return;
1500103410Smini}
1501103410Smini
1502103410Smini/*
1503111028Sjeff * Setup done on the thread when it enters the kernel.
1504105900Sjulian * XXXKSE Presently only for syscalls but eventually all kernel entries.
1505105900Sjulian */
1506105900Sjulianvoid
1507105900Sjulianthread_user_enter(struct proc *p, struct thread *td)
1508105900Sjulian{
1509111028Sjeff	struct ksegrp *kg;
1510111028Sjeff	struct kse_upcall *ku;
1511105900Sjulian
1512111028Sjeff	kg = td->td_ksegrp;
1513105900Sjulian	/*
1514105900Sjulian	 * First check that we shouldn't just abort.
1515105900Sjulian	 * But check if we are the single thread first!
1516105900Sjulian	 * XXX p_singlethread not locked, but should be safe.
1517105900Sjulian	 */
1518111028Sjeff	if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
1519105900Sjulian		PROC_LOCK(p);
1520105900Sjulian		mtx_lock_spin(&sched_lock);
1521105900Sjulian		thread_exit();
1522105900Sjulian		/* NOTREACHED */
1523105900Sjulian	}
1524105900Sjulian
1525105900Sjulian	/*
1526105900Sjulian	 * If we are doing a syscall in a KSE environment,
1527105900Sjulian	 * note where our mailbox is. There is always the
1528108338Sjulian	 * possibility that we could do this lazily (in kse_reassign()),
1529105900Sjulian	 * but for now do it every time.
1530105900Sjulian	 */
1531111028Sjeff	kg = td->td_ksegrp;
1532111028Sjeff	if (kg->kg_numupcalls) {
1533111028Sjeff		ku = td->td_upcall;
1534111028Sjeff		KASSERT(ku, ("%s: no upcall owned", __func__));
1535111028Sjeff		KASSERT((ku->ku_owner == td), ("%s: wrong owner", __func__));
1536105900Sjulian		td->td_mailbox =
1537111028Sjeff		    (void *)fuword((void *)&ku->ku_mailbox->km_curthread);
1538105900Sjulian		if ((td->td_mailbox == NULL) ||
1539107034Sdavidxu		    (td->td_mailbox == (void *)-1)) {
1540111028Sjeff		    	/* Don't schedule upcall when blocked */
1541111028Sjeff			td->td_mailbox = NULL;
1542107034Sdavidxu			mtx_lock_spin(&sched_lock);
1543111028Sjeff			td->td_flags &= ~TDF_CAN_UNBIND;
1544107034Sdavidxu			mtx_unlock_spin(&sched_lock);
1545105900Sjulian		} else {
1546111115Sdavidxu			if (td->td_standin == NULL)
1547111115Sdavidxu				thread_alloc_spare(td, NULL);
1548111115Sdavidxu			mtx_lock_spin(&sched_lock);
1549111115Sdavidxu			td->td_flags |= TDF_CAN_UNBIND;
1550111115Sdavidxu			mtx_unlock_spin(&sched_lock);
1551105900Sjulian		}
1552105900Sjulian	}
1553105900Sjulian}
1554105900Sjulian
1555105900Sjulian/*
1556103410Smini * The extra work we go through if we are a threaded process when we
1557103410Smini * return to userland.
1558103410Smini *
155999026Sjulian * If we are a KSE process and returning to user mode, check for
156099026Sjulian * extra work to do before we return (e.g. for more syscalls
156199026Sjulian * to complete first).  If we were in a critical section, we should
156299026Sjulian * just return to let it finish. Same if we were in the UTS (in
1563103410Smini * which case the mailbox's context's busy indicator will be set).
1564103410Smini * The only traps we suport will have set the mailbox.
1565103410Smini * We will clear it here.
156699026Sjulian */
156799026Sjulianint
1568103838Sjulianthread_userret(struct thread *td, struct trapframe *frame)
156999026Sjulian{
1570111115Sdavidxu	int error = 0, upcalls;
1571111028Sjeff	struct kse_upcall *ku;
1572111115Sdavidxu	struct ksegrp *kg, *kg2;
1573104695Sjulian	struct proc *p;
1574107060Sdavidxu	struct timespec ts;
157599026Sjulian
1576111028Sjeff	p = td->td_proc;
1577110190Sjulian	kg = td->td_ksegrp;
1578104695Sjulian
1579111028Sjeff	/* Nothing to do with non-threaded group/process */
1580111028Sjeff	if (td->td_ksegrp->kg_numupcalls == 0)
1581111028Sjeff		return (0);
1582108338Sjulian
1583103410Smini	/*
1584111028Sjeff	 * Stat clock interrupt hit in userland, it
1585111028Sjeff	 * is returning from interrupt, charge thread's
1586111028Sjeff	 * userland time for UTS.
1587103410Smini	 */
1588111028Sjeff	if (td->td_flags & TDF_USTATCLOCK) {
1589111028Sjeff		thread_update_usr_ticks(td);
1590111028Sjeff		mtx_lock_spin(&sched_lock);
1591111028Sjeff		td->td_flags &= ~TDF_USTATCLOCK;
1592111028Sjeff		mtx_unlock_spin(&sched_lock);
1593111028Sjeff	}
1594108338Sjulian
1595111028Sjeff	/*
1596111028Sjeff	 * Optimisation:
1597111028Sjeff	 * This thread has not started any upcall.
1598111028Sjeff	 * If there is no work to report other than ourself,
1599111028Sjeff	 * then it can return direct to userland.
1600111028Sjeff	 */
1601108338Sjulian	if (TD_CAN_UNBIND(td)) {
1602111028Sjeff		mtx_lock_spin(&sched_lock);
1603111028Sjeff		td->td_flags &= ~TDF_CAN_UNBIND;
1604111028Sjeff		mtx_unlock_spin(&sched_lock);
1605111028Sjeff		if ((kg->kg_completed == NULL) &&
1606111028Sjeff		    (td->td_upcall->ku_flags & KUF_DOUPCALL) == 0) {
1607111028Sjeff			thread_update_sys_ticks(td);
1608108338Sjulian			td->td_mailbox = NULL;
1609108338Sjulian			return (0);
1610108338Sjulian		}
1611104695Sjulian		error = thread_export_context(td);
1612104695Sjulian		if (error) {
1613104695Sjulian			/*
1614111028Sjeff			 * Failing to do the KSE operation just defaults
1615104695Sjulian			 * back to synchonous operation, so just return from
1616108338Sjulian			 * the syscall.
1617104695Sjulian			 */
1618111028Sjeff			return (0);
1619104695Sjulian		}
1620104695Sjulian		/*
1621111028Sjeff		 * There is something to report, and we own an upcall
1622111028Sjeff		 * strucuture, we can go to userland.
1623111028Sjeff		 * Turn ourself into an upcall thread.
1624104695Sjulian		 */
1625111028Sjeff		mtx_lock_spin(&sched_lock);
1626104695Sjulian		td->td_flags |= TDF_UPCALLING;
1627108338Sjulian		mtx_unlock_spin(&sched_lock);
1628111028Sjeff	} else if (td->td_mailbox) {
1629108338Sjulian		error = thread_export_context(td);
1630108338Sjulian		if (error) {
1631108338Sjulian			PROC_LOCK(td->td_proc);
1632108338Sjulian			mtx_lock_spin(&sched_lock);
1633108338Sjulian			/* possibly upcall with error? */
1634108338Sjulian		} else {
1635111028Sjeff			PROC_LOCK(td->td_proc);
1636111028Sjeff			mtx_lock_spin(&sched_lock);
1637108338Sjulian			/*
1638111028Sjeff			 * There are upcall threads waiting for
1639111028Sjeff			 * work to do, wake one of them up.
1640111028Sjeff			 * XXXKSE Maybe wake all of them up.
1641108338Sjulian			 */
1642111028Sjeff			if (kg->kg_upsleeps)
1643111028Sjeff				wakeup_one(&kg->kg_completed);
1644108338Sjulian		}
1645108338Sjulian		thread_exit();
1646111028Sjeff		/* NOTREACHED */
1647104695Sjulian	}
1648104695Sjulian
1649111154Sdavidxu	KASSERT(TD_CAN_UNBIND(td) == 0, ("can unbind"));
1650111154Sdavidxu
1651111154Sdavidxu	if (p->p_numthreads > max_threads_per_proc) {
1652111154Sdavidxu		max_threads_hits++;
1653111154Sdavidxu		PROC_LOCK(p);
1654111154Sdavidxu		while (p->p_numthreads > max_threads_per_proc) {
1655111154Sdavidxu			if (P_SHOULDSTOP(p))
1656111154Sdavidxu				break;
1657111154Sdavidxu			upcalls = 0;
1658111154Sdavidxu			mtx_lock_spin(&sched_lock);
1659111154Sdavidxu			FOREACH_KSEGRP_IN_PROC(p, kg2) {
1660111154Sdavidxu				if (kg2->kg_numupcalls == 0)
1661111154Sdavidxu					upcalls++;
1662111154Sdavidxu				else
1663111154Sdavidxu					upcalls += kg2->kg_numupcalls;
1664111154Sdavidxu			}
1665111154Sdavidxu			mtx_unlock_spin(&sched_lock);
1666111154Sdavidxu			if (upcalls >= max_threads_per_proc)
1667111154Sdavidxu				break;
1668111154Sdavidxu			p->p_maxthrwaits++;
1669111154Sdavidxu			msleep(&p->p_numthreads, &p->p_mtx, PPAUSE|PCATCH,
1670111154Sdavidxu			    "maxthreads", NULL);
1671111154Sdavidxu			p->p_maxthrwaits--;
1672111154Sdavidxu		}
1673111154Sdavidxu		PROC_UNLOCK(p);
1674111154Sdavidxu	}
1675111154Sdavidxu
1676108338Sjulian	if (td->td_flags & TDF_UPCALLING) {
1677111028Sjeff		ku = td->td_upcall;
1678108338Sjulian		/*
1679108338Sjulian		 * There is no more work to do and we are going to ride
1680111028Sjeff		 * this thread up to userland as an upcall.
1681108338Sjulian		 * Do the last parts of the setup needed for the upcall.
1682108338Sjulian		 */
1683108338Sjulian		CTR3(KTR_PROC, "userret: upcall thread %p (pid %d, %s)",
1684108338Sjulian		    td, td->td_proc->p_pid, td->td_proc->p_comm);
1685104695Sjulian
1686108338Sjulian		/*
1687108338Sjulian		 * Set user context to the UTS.
1688108338Sjulian		 * Will use Giant in cpu_thread_clean() because it uses
1689108338Sjulian		 * kmem_free(kernel_map, ...)
1690108338Sjulian		 */
1691111028Sjeff		cpu_set_upcall_kse(td, ku);
1692104695Sjulian
1693111028Sjeff		/*
1694111028Sjeff		 * Clear TDF_UPCALLING after set upcall context,
1695111028Sjeff		 * profiling code looks TDF_UPCALLING to avoid account
1696111028Sjeff		 * a wrong user %EIP
1697111028Sjeff		 */
1698111028Sjeff		mtx_lock_spin(&sched_lock);
1699111028Sjeff		td->td_flags &= ~TDF_UPCALLING;
1700111028Sjeff		if (ku->ku_flags & KUF_DOUPCALL)
1701111028Sjeff			ku->ku_flags &= ~KUF_DOUPCALL;
1702111028Sjeff		mtx_unlock_spin(&sched_lock);
1703111028Sjeff
1704111028Sjeff		/*
1705108338Sjulian		 * Unhook the list of completed threads.
1706108338Sjulian		 * anything that completes after this gets to
1707108338Sjulian		 * come in next time.
1708108338Sjulian		 * Put the list of completed thread mailboxes on
1709108338Sjulian		 * this KSE's mailbox.
1710108338Sjulian		 */
1711111028Sjeff		error = thread_link_mboxes(kg, ku);
1712108338Sjulian		if (error)
1713111115Sdavidxu			goto out;
171499026Sjulian
1715108338Sjulian		/*
1716108338Sjulian		 * Set state and clear the  thread mailbox pointer.
1717108338Sjulian		 * From now on we are just a bound outgoing process.
1718108338Sjulian		 * **Problem** userret is often called several times.
1719108338Sjulian		 * it would be nice if this all happenned only on the first
1720108338Sjulian		 * time through. (the scan for extra work etc.)
1721108338Sjulian		 */
1722111028Sjeff		error = suword((caddr_t)&ku->ku_mailbox->km_curthread, 0);
1723108338Sjulian		if (error)
1724111115Sdavidxu			goto out;
1725111028Sjeff
1726111028Sjeff		/* Export current system time */
1727107060Sdavidxu		nanotime(&ts);
1728111115Sdavidxu		error = copyout(&ts, (caddr_t)&ku->ku_mailbox->km_timeofday,
1729111115Sdavidxu			sizeof(ts));
1730111115Sdavidxu	}
1731111115Sdavidxu
1732111115Sdavidxuout:
1733111115Sdavidxu	if (error) {
1734111115Sdavidxu		/*
1735111129Sdavidxu		 * Things are going to be so screwed we should just kill
1736111129Sdavidxu		 * the process.
1737111115Sdavidxu		 * how do we do that?
1738111115Sdavidxu		 */
1739111115Sdavidxu		PROC_LOCK(td->td_proc);
1740111115Sdavidxu		psignal(td->td_proc, SIGSEGV);
1741111115Sdavidxu		PROC_UNLOCK(td->td_proc);
1742111115Sdavidxu	} else {
1743111115Sdavidxu		/*
1744111115Sdavidxu		 * Optimisation:
1745111115Sdavidxu		 * Ensure that we have a spare thread available,
1746111115Sdavidxu		 * for when we re-enter the kernel.
1747111115Sdavidxu		 */
1748111115Sdavidxu		if (td->td_standin == NULL)
1749111115Sdavidxu			thread_alloc_spare(td, NULL);
1750111115Sdavidxu	}
1751111115Sdavidxu
1752111028Sjeff	/*
1753111028Sjeff	 * Clear thread mailbox first, then clear system tick count.
1754111028Sjeff	 * The order is important because thread_statclock() use
1755111028Sjeff	 * mailbox pointer to see if it is an userland thread or
1756111028Sjeff	 * an UTS kernel thread.
1757111028Sjeff	 */
1758108338Sjulian	td->td_mailbox = NULL;
1759111028Sjeff	td->td_usticks = 0;
1760104695Sjulian	return (error);	/* go sync */
176199026Sjulian}
176299026Sjulian
176399026Sjulian/*
176499026Sjulian * Enforce single-threading.
176599026Sjulian *
176699026Sjulian * Returns 1 if the caller must abort (another thread is waiting to
176799026Sjulian * exit the process or similar). Process is locked!
176899026Sjulian * Returns 0 when you are successfully the only thread running.
176999026Sjulian * A process has successfully single threaded in the suspend mode when
177099026Sjulian * There are no threads in user mode. Threads in the kernel must be
177199026Sjulian * allowed to continue until they get to the user boundary. They may even
177299026Sjulian * copy out their return values and data before suspending. They may however be
177399026Sjulian * accellerated in reaching the user boundary as we will wake up
177499026Sjulian * any sleeping threads that are interruptable. (PCATCH).
177599026Sjulian */
177699026Sjulianint
177799026Sjulianthread_single(int force_exit)
177899026Sjulian{
177999026Sjulian	struct thread *td;
178099026Sjulian	struct thread *td2;
178199026Sjulian	struct proc *p;
178299026Sjulian
178399026Sjulian	td = curthread;
178499026Sjulian	p = td->td_proc;
1785107719Sjulian	mtx_assert(&Giant, MA_OWNED);
178699026Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
178799026Sjulian	KASSERT((td != NULL), ("curthread is NULL"));
178899026Sjulian
178999026Sjulian	if ((p->p_flag & P_KSES) == 0)
179099026Sjulian		return (0);
179199026Sjulian
1792100648Sjulian	/* Is someone already single threading? */
1793100648Sjulian	if (p->p_singlethread)
179499026Sjulian		return (1);
179599026Sjulian
1796108338Sjulian	if (force_exit == SINGLE_EXIT) {
179799026Sjulian		p->p_flag |= P_SINGLE_EXIT;
1798108338Sjulian	} else
179999026Sjulian		p->p_flag &= ~P_SINGLE_EXIT;
1800102950Sdavidxu	p->p_flag |= P_STOPPED_SINGLE;
180199026Sjulian	p->p_singlethread = td;
1802105911Sjulian	/* XXXKSE Which lock protects the below values? */
180399026Sjulian	while ((p->p_numthreads - p->p_suspcount) != 1) {
1804103216Sjulian		mtx_lock_spin(&sched_lock);
180599026Sjulian		FOREACH_THREAD_IN_PROC(p, td2) {
180699026Sjulian			if (td2 == td)
180799026Sjulian				continue;
1808111115Sdavidxu			td->td_flags |= TDF_ASTPENDING;
1809103216Sjulian			if (TD_IS_INHIBITED(td2)) {
1810105911Sjulian				if (force_exit == SINGLE_EXIT) {
1811105911Sjulian					if (TD_IS_SUSPENDED(td2)) {
1812103216Sjulian						thread_unsuspend_one(td2);
1813105911Sjulian					}
1814105911Sjulian					if (TD_ON_SLEEPQ(td2) &&
1815105911Sjulian					    (td2->td_flags & TDF_SINTR)) {
1816105911Sjulian						if (td2->td_flags & TDF_CVWAITQ)
1817105911Sjulian							cv_abort(td2);
1818105911Sjulian						else
1819105911Sjulian							abortsleep(td2);
1820105911Sjulian					}
1821105911Sjulian				} else {
1822105911Sjulian					if (TD_IS_SUSPENDED(td2))
1823105874Sdavidxu						continue;
1824111028Sjeff					/*
1825111028Sjeff					 * maybe other inhibitted states too?
1826111028Sjeff					 * XXXKSE Is it totally safe to
1827111028Sjeff					 * suspend a non-interruptable thread?
1828111028Sjeff					 */
1829108338Sjulian					if (td2->td_inhibitors &
1830111028Sjeff					    (TDI_SLEEPING | TDI_SWAPPED))
1831105911Sjulian						thread_suspend_one(td2);
183299026Sjulian				}
183399026Sjulian			}
183499026Sjulian		}
1835105911Sjulian		/*
1836105911Sjulian		 * Maybe we suspended some threads.. was it enough?
1837105911Sjulian		 */
1838105911Sjulian		if ((p->p_numthreads - p->p_suspcount) == 1) {
1839105911Sjulian			mtx_unlock_spin(&sched_lock);
1840105911Sjulian			break;
1841105911Sjulian		}
1842105911Sjulian
184399026Sjulian		/*
184499026Sjulian		 * Wake us up when everyone else has suspended.
1845100648Sjulian		 * In the mean time we suspend as well.
184699026Sjulian		 */
1847103216Sjulian		thread_suspend_one(td);
184899026Sjulian		mtx_unlock(&Giant);
184999026Sjulian		PROC_UNLOCK(p);
1850107719Sjulian		p->p_stats->p_ru.ru_nvcsw++;
185199026Sjulian		mi_switch();
185299026Sjulian		mtx_unlock_spin(&sched_lock);
185399026Sjulian		mtx_lock(&Giant);
185499026Sjulian		PROC_LOCK(p);
185599026Sjulian	}
1856111028Sjeff	if (force_exit == SINGLE_EXIT) {
1857111028Sjeff		if (td->td_upcall) {
1858111028Sjeff			mtx_lock_spin(&sched_lock);
1859111028Sjeff			upcall_remove(td);
1860111028Sjeff			mtx_unlock_spin(&sched_lock);
1861111028Sjeff		}
1862105854Sjulian		kse_purge(p, td);
1863111028Sjeff	}
186499026Sjulian	return (0);
186599026Sjulian}
186699026Sjulian
186799026Sjulian/*
186899026Sjulian * Called in from locations that can safely check to see
186999026Sjulian * whether we have to suspend or at least throttle for a
187099026Sjulian * single-thread event (e.g. fork).
187199026Sjulian *
187299026Sjulian * Such locations include userret().
187399026Sjulian * If the "return_instead" argument is non zero, the thread must be able to
187499026Sjulian * accept 0 (caller may continue), or 1 (caller must abort) as a result.
187599026Sjulian *
187699026Sjulian * The 'return_instead' argument tells the function if it may do a
187799026Sjulian * thread_exit() or suspend, or whether the caller must abort and back
187899026Sjulian * out instead.
187999026Sjulian *
188099026Sjulian * If the thread that set the single_threading request has set the
188199026Sjulian * P_SINGLE_EXIT bit in the process flags then this call will never return
188299026Sjulian * if 'return_instead' is false, but will exit.
188399026Sjulian *
188499026Sjulian * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
188599026Sjulian *---------------+--------------------+---------------------
188699026Sjulian *       0       | returns 0          |   returns 0 or 1
188799026Sjulian *               | when ST ends       |   immediatly
188899026Sjulian *---------------+--------------------+---------------------
188999026Sjulian *       1       | thread exits       |   returns 1
189099026Sjulian *               |                    |  immediatly
189199026Sjulian * 0 = thread_exit() or suspension ok,
189299026Sjulian * other = return error instead of stopping the thread.
189399026Sjulian *
189499026Sjulian * While a full suspension is under effect, even a single threading
189599026Sjulian * thread would be suspended if it made this call (but it shouldn't).
189699026Sjulian * This call should only be made from places where
189799026Sjulian * thread_exit() would be safe as that may be the outcome unless
189899026Sjulian * return_instead is set.
189999026Sjulian */
190099026Sjulianint
190199026Sjulianthread_suspend_check(int return_instead)
190299026Sjulian{
1903104502Sjmallett	struct thread *td;
1904104502Sjmallett	struct proc *p;
1905105854Sjulian	struct ksegrp *kg;
190699026Sjulian
190799026Sjulian	td = curthread;
190899026Sjulian	p = td->td_proc;
1909105854Sjulian	kg = td->td_ksegrp;
191099026Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
191199026Sjulian	while (P_SHOULDSTOP(p)) {
1912102950Sdavidxu		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
191399026Sjulian			KASSERT(p->p_singlethread != NULL,
191499026Sjulian			    ("singlethread not set"));
191599026Sjulian			/*
1916100648Sjulian			 * The only suspension in action is a
1917100648Sjulian			 * single-threading. Single threader need not stop.
1918100646Sjulian			 * XXX Should be safe to access unlocked
1919100646Sjulian			 * as it can only be set to be true by us.
192099026Sjulian			 */
1921100648Sjulian			if (p->p_singlethread == td)
192299026Sjulian				return (0);	/* Exempt from stopping. */
192399026Sjulian		}
1924100648Sjulian		if (return_instead)
192599026Sjulian			return (1);
192699026Sjulian
192799026Sjulian		/*
192899026Sjulian		 * If the process is waiting for us to exit,
192999026Sjulian		 * this thread should just suicide.
1930102950Sdavidxu		 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
193199026Sjulian		 */
193299026Sjulian		if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
193399026Sjulian			mtx_lock_spin(&sched_lock);
193499026Sjulian			while (mtx_owned(&Giant))
193599026Sjulian				mtx_unlock(&Giant);
193699026Sjulian			thread_exit();
193799026Sjulian		}
193899026Sjulian
193999026Sjulian		/*
194099026Sjulian		 * When a thread suspends, it just
194199026Sjulian		 * moves to the processes's suspend queue
194299026Sjulian		 * and stays there.
194399026Sjulian		 */
1944102238Sjulian		mtx_lock_spin(&sched_lock);
1945102950Sdavidxu		if ((p->p_flag & P_STOPPED_SIG) &&
1946102238Sjulian		    (p->p_suspcount+1 == p->p_numthreads)) {
1947102238Sjulian			mtx_unlock_spin(&sched_lock);
1948102238Sjulian			PROC_LOCK(p->p_pptr);
1949102238Sjulian			if ((p->p_pptr->p_procsig->ps_flag &
1950102238Sjulian				PS_NOCLDSTOP) == 0) {
1951102238Sjulian				psignal(p->p_pptr, SIGCHLD);
1952102238Sjulian			}
1953102238Sjulian			PROC_UNLOCK(p->p_pptr);
1954103055Sjulian			mtx_lock_spin(&sched_lock);
1955102238Sjulian		}
195699026Sjulian		mtx_assert(&Giant, MA_NOTOWNED);
1957103216Sjulian		thread_suspend_one(td);
195899026Sjulian		PROC_UNLOCK(p);
1959102950Sdavidxu		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1960100632Sjulian			if (p->p_numthreads == p->p_suspcount) {
1961103216Sjulian				thread_unsuspend_one(p->p_singlethread);
1962100632Sjulian			}
1963100632Sjulian		}
1964100594Sjulian		p->p_stats->p_ru.ru_nivcsw++;
196599026Sjulian		mi_switch();
196699026Sjulian		mtx_unlock_spin(&sched_lock);
196799026Sjulian		PROC_LOCK(p);
196899026Sjulian	}
196999026Sjulian	return (0);
197099026Sjulian}
197199026Sjulian
1972102898Sdavidxuvoid
1973102898Sdavidxuthread_suspend_one(struct thread *td)
1974102898Sdavidxu{
1975102898Sdavidxu	struct proc *p = td->td_proc;
1976102898Sdavidxu
1977102898Sdavidxu	mtx_assert(&sched_lock, MA_OWNED);
1978102898Sdavidxu	p->p_suspcount++;
1979103216Sjulian	TD_SET_SUSPENDED(td);
1980102898Sdavidxu	TAILQ_INSERT_TAIL(&p->p_suspended, td, td_runq);
1981103216Sjulian	/*
1982103216Sjulian	 * Hack: If we are suspending but are on the sleep queue
1983103216Sjulian	 * then we are in msleep or the cv equivalent. We
1984103216Sjulian	 * want to look like we have two Inhibitors.
1985105911Sjulian	 * May already be set.. doesn't matter.
1986103216Sjulian	 */
1987103216Sjulian	if (TD_ON_SLEEPQ(td))
1988103216Sjulian		TD_SET_SLEEPING(td);
1989102898Sdavidxu}
1990102898Sdavidxu
1991102898Sdavidxuvoid
1992102898Sdavidxuthread_unsuspend_one(struct thread *td)
1993102898Sdavidxu{
1994102898Sdavidxu	struct proc *p = td->td_proc;
1995102898Sdavidxu
1996102898Sdavidxu	mtx_assert(&sched_lock, MA_OWNED);
1997102898Sdavidxu	TAILQ_REMOVE(&p->p_suspended, td, td_runq);
1998103216Sjulian	TD_CLR_SUSPENDED(td);
1999102898Sdavidxu	p->p_suspcount--;
2000103216Sjulian	setrunnable(td);
2001102898Sdavidxu}
2002102898Sdavidxu
200399026Sjulian/*
200499026Sjulian * Allow all threads blocked by single threading to continue running.
200599026Sjulian */
200699026Sjulianvoid
200799026Sjulianthread_unsuspend(struct proc *p)
200899026Sjulian{
200999026Sjulian	struct thread *td;
201099026Sjulian
2011100646Sjulian	mtx_assert(&sched_lock, MA_OWNED);
201299026Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
201399026Sjulian	if (!P_SHOULDSTOP(p)) {
201499026Sjulian		while (( td = TAILQ_FIRST(&p->p_suspended))) {
2015102898Sdavidxu			thread_unsuspend_one(td);
201699026Sjulian		}
2017102950Sdavidxu	} else if ((P_SHOULDSTOP(p) == P_STOPPED_SINGLE) &&
201899026Sjulian	    (p->p_numthreads == p->p_suspcount)) {
201999026Sjulian		/*
202099026Sjulian		 * Stopping everything also did the job for the single
202199026Sjulian		 * threading request. Now we've downgraded to single-threaded,
202299026Sjulian		 * let it continue.
202399026Sjulian		 */
2024102898Sdavidxu		thread_unsuspend_one(p->p_singlethread);
202599026Sjulian	}
202699026Sjulian}
202799026Sjulian
202899026Sjulianvoid
202999026Sjulianthread_single_end(void)
203099026Sjulian{
203199026Sjulian	struct thread *td;
203299026Sjulian	struct proc *p;
203399026Sjulian
203499026Sjulian	td = curthread;
203599026Sjulian	p = td->td_proc;
203699026Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
2037102950Sdavidxu	p->p_flag &= ~P_STOPPED_SINGLE;
203899026Sjulian	p->p_singlethread = NULL;
2039102292Sjulian	/*
2040102292Sjulian	 * If there are other threads they mey now run,
2041102292Sjulian	 * unless of course there is a blanket 'stop order'
2042102292Sjulian	 * on the process. The single threader must be allowed
2043102292Sjulian	 * to continue however as this is a bad place to stop.
2044102292Sjulian	 */
2045102292Sjulian	if ((p->p_numthreads != 1) && (!P_SHOULDSTOP(p))) {
2046102292Sjulian		mtx_lock_spin(&sched_lock);
2047102292Sjulian		while (( td = TAILQ_FIRST(&p->p_suspended))) {
2048103216Sjulian			thread_unsuspend_one(td);
2049102292Sjulian		}
2050102292Sjulian		mtx_unlock_spin(&sched_lock);
2051102292Sjulian	}
205299026Sjulian}
205399026Sjulian
2054102292Sjulian
2055