kern_thread.c revision 216314
1/*-
2 * Copyright (C) 2001 Julian Elischer <julian@freebsd.org>.
3 *  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice(s), this list of conditions and the following disclaimer as
10 *    the first lines of this file unmodified other than the possible
11 *    addition of one or more copyright notices.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice(s), this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
26 * DAMAGE.
27 */
28
29#include "opt_witness.h"
30#include "opt_hwpmc_hooks.h"
31
32#include <sys/cdefs.h>
33__FBSDID("$FreeBSD: head/sys/kern/kern_thread.c 216314 2010-12-09 05:16:20Z davidxu $");
34
35#include <sys/param.h>
36#include <sys/systm.h>
37#include <sys/kernel.h>
38#include <sys/lock.h>
39#include <sys/mutex.h>
40#include <sys/proc.h>
41#include <sys/resourcevar.h>
42#include <sys/smp.h>
43#include <sys/sysctl.h>
44#include <sys/sched.h>
45#include <sys/sleepqueue.h>
46#include <sys/selinfo.h>
47#include <sys/turnstile.h>
48#include <sys/ktr.h>
49#include <sys/rwlock.h>
50#include <sys/umtx.h>
51#include <sys/cpuset.h>
52#ifdef	HWPMC_HOOKS
53#include <sys/pmckern.h>
54#endif
55
56#include <security/audit/audit.h>
57
58#include <vm/vm.h>
59#include <vm/vm_extern.h>
60#include <vm/uma.h>
61#include <sys/eventhandler.h>
62
63/*
64 * thread related storage.
65 */
66static uma_zone_t thread_zone;
67
68SYSCTL_NODE(_kern, OID_AUTO, threads, CTLFLAG_RW, 0, "thread allocation");
69
70int max_threads_per_proc = 1500;
71SYSCTL_INT(_kern_threads, OID_AUTO, max_threads_per_proc, CTLFLAG_RW,
72	&max_threads_per_proc, 0, "Limit on threads per proc");
73
74int max_threads_hits;
75SYSCTL_INT(_kern_threads, OID_AUTO, max_threads_hits, CTLFLAG_RD,
76	&max_threads_hits, 0, "");
77
78TAILQ_HEAD(, thread) zombie_threads = TAILQ_HEAD_INITIALIZER(zombie_threads);
79static struct mtx zombie_lock;
80MTX_SYSINIT(zombie_lock, &zombie_lock, "zombie lock", MTX_SPIN);
81
82static void thread_zombie(struct thread *);
83
84#define TID_BUFFER_SIZE	1024
85
86struct mtx tid_lock;
87static struct unrhdr *tid_unrhdr;
88static lwpid_t tid_buffer[TID_BUFFER_SIZE];
89static int tid_head, tid_tail;
90static MALLOC_DEFINE(M_TIDHASH, "tidhash", "thread hash");
91
92struct	tidhashhead *tidhashtbl;
93u_long	tidhash;
94struct	rwlock tidhash_lock;
95
96static lwpid_t
97tid_alloc(void)
98{
99	lwpid_t	tid;
100
101	tid = alloc_unr(tid_unrhdr);
102	if (tid != -1)
103		return (tid);
104	mtx_lock(&tid_lock);
105	if (tid_head == tid_tail) {
106		mtx_unlock(&tid_lock);
107		return (-1);
108	}
109	tid = tid_buffer[tid_head++];
110	tid_head %= TID_BUFFER_SIZE;
111	mtx_unlock(&tid_lock);
112	return (tid);
113}
114
115static void
116tid_free(lwpid_t tid)
117{
118	lwpid_t tmp_tid = -1;
119
120	mtx_lock(&tid_lock);
121	if ((tid_tail + 1) % TID_BUFFER_SIZE == tid_head) {
122		tmp_tid = tid_buffer[tid_head++];
123		tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
124	}
125	tid_buffer[tid_tail++] = tid;
126	tid_tail %= TID_BUFFER_SIZE;
127	mtx_unlock(&tid_lock);
128	if (tmp_tid != -1)
129		free_unr(tid_unrhdr, tmp_tid);
130}
131
132/*
133 * Prepare a thread for use.
134 */
135static int
136thread_ctor(void *mem, int size, void *arg, int flags)
137{
138	struct thread	*td;
139
140	td = (struct thread *)mem;
141	td->td_state = TDS_INACTIVE;
142	td->td_oncpu = NOCPU;
143
144	td->td_tid = tid_alloc();
145
146	/*
147	 * Note that td_critnest begins life as 1 because the thread is not
148	 * running and is thereby implicitly waiting to be on the receiving
149	 * end of a context switch.
150	 */
151	td->td_critnest = 1;
152	td->td_lend_user_pri = PRI_MAX;
153	EVENTHANDLER_INVOKE(thread_ctor, td);
154#ifdef AUDIT
155	audit_thread_alloc(td);
156#endif
157	umtx_thread_alloc(td);
158	return (0);
159}
160
161/*
162 * Reclaim a thread after use.
163 */
164static void
165thread_dtor(void *mem, int size, void *arg)
166{
167	struct thread *td;
168
169	td = (struct thread *)mem;
170
171#ifdef INVARIANTS
172	/* Verify that this thread is in a safe state to free. */
173	switch (td->td_state) {
174	case TDS_INHIBITED:
175	case TDS_RUNNING:
176	case TDS_CAN_RUN:
177	case TDS_RUNQ:
178		/*
179		 * We must never unlink a thread that is in one of
180		 * these states, because it is currently active.
181		 */
182		panic("bad state for thread unlinking");
183		/* NOTREACHED */
184	case TDS_INACTIVE:
185		break;
186	default:
187		panic("bad thread state");
188		/* NOTREACHED */
189	}
190#endif
191#ifdef AUDIT
192	audit_thread_free(td);
193#endif
194	/* Free all OSD associated to this thread. */
195	osd_thread_exit(td);
196
197	EVENTHANDLER_INVOKE(thread_dtor, td);
198	tid_free(td->td_tid);
199}
200
201/*
202 * Initialize type-stable parts of a thread (when newly created).
203 */
204static int
205thread_init(void *mem, int size, int flags)
206{
207	struct thread *td;
208
209	td = (struct thread *)mem;
210
211	td->td_sleepqueue = sleepq_alloc();
212	td->td_turnstile = turnstile_alloc();
213	EVENTHANDLER_INVOKE(thread_init, td);
214	td->td_sched = (struct td_sched *)&td[1];
215	umtx_thread_init(td);
216	td->td_kstack = 0;
217	return (0);
218}
219
220/*
221 * Tear down type-stable parts of a thread (just before being discarded).
222 */
223static void
224thread_fini(void *mem, int size)
225{
226	struct thread *td;
227
228	td = (struct thread *)mem;
229	EVENTHANDLER_INVOKE(thread_fini, td);
230	turnstile_free(td->td_turnstile);
231	sleepq_free(td->td_sleepqueue);
232	umtx_thread_fini(td);
233	seltdfini(td);
234}
235
236/*
237 * For a newly created process,
238 * link up all the structures and its initial threads etc.
239 * called from:
240 * {arch}/{arch}/machdep.c   ia64_init(), init386() etc.
241 * proc_dtor() (should go away)
242 * proc_init()
243 */
244void
245proc_linkup0(struct proc *p, struct thread *td)
246{
247	TAILQ_INIT(&p->p_threads);	     /* all threads in proc */
248	proc_linkup(p, td);
249}
250
251void
252proc_linkup(struct proc *p, struct thread *td)
253{
254
255	sigqueue_init(&p->p_sigqueue, p);
256	p->p_ksi = ksiginfo_alloc(1);
257	if (p->p_ksi != NULL) {
258		/* XXX p_ksi may be null if ksiginfo zone is not ready */
259		p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
260	}
261	LIST_INIT(&p->p_mqnotifier);
262	p->p_numthreads = 0;
263	thread_link(td, p);
264}
265
266/*
267 * Initialize global thread allocation resources.
268 */
269void
270threadinit(void)
271{
272
273	mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
274	/* leave one number for thread0 */
275	tid_unrhdr = new_unrhdr(PID_MAX + 2, INT_MAX, &tid_lock);
276
277	thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
278	    thread_ctor, thread_dtor, thread_init, thread_fini,
279	    16 - 1, 0);
280	tidhashtbl = hashinit(maxproc / 2, M_TIDHASH, &tidhash);
281	rw_init(&tidhash_lock, "tidhash");
282}
283
284/*
285 * Place an unused thread on the zombie list.
286 * Use the slpq as that must be unused by now.
287 */
288void
289thread_zombie(struct thread *td)
290{
291	mtx_lock_spin(&zombie_lock);
292	TAILQ_INSERT_HEAD(&zombie_threads, td, td_slpq);
293	mtx_unlock_spin(&zombie_lock);
294}
295
296/*
297 * Release a thread that has exited after cpu_throw().
298 */
299void
300thread_stash(struct thread *td)
301{
302	atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
303	thread_zombie(td);
304}
305
306/*
307 * Reap zombie resources.
308 */
309void
310thread_reap(void)
311{
312	struct thread *td_first, *td_next;
313
314	/*
315	 * Don't even bother to lock if none at this instant,
316	 * we really don't care about the next instant..
317	 */
318	if (!TAILQ_EMPTY(&zombie_threads)) {
319		mtx_lock_spin(&zombie_lock);
320		td_first = TAILQ_FIRST(&zombie_threads);
321		if (td_first)
322			TAILQ_INIT(&zombie_threads);
323		mtx_unlock_spin(&zombie_lock);
324		while (td_first) {
325			td_next = TAILQ_NEXT(td_first, td_slpq);
326			if (td_first->td_ucred)
327				crfree(td_first->td_ucred);
328			thread_free(td_first);
329			td_first = td_next;
330		}
331	}
332}
333
334/*
335 * Allocate a thread.
336 */
337struct thread *
338thread_alloc(int pages)
339{
340	struct thread *td;
341
342	thread_reap(); /* check if any zombies to get */
343
344	td = (struct thread *)uma_zalloc(thread_zone, M_WAITOK);
345	KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
346	if (!vm_thread_new(td, pages)) {
347		uma_zfree(thread_zone, td);
348		return (NULL);
349	}
350	cpu_thread_alloc(td);
351	return (td);
352}
353
354int
355thread_alloc_stack(struct thread *td, int pages)
356{
357
358	KASSERT(td->td_kstack == 0,
359	    ("thread_alloc_stack called on a thread with kstack"));
360	if (!vm_thread_new(td, pages))
361		return (0);
362	cpu_thread_alloc(td);
363	return (1);
364}
365
366/*
367 * Deallocate a thread.
368 */
369void
370thread_free(struct thread *td)
371{
372
373	lock_profile_thread_exit(td);
374	if (td->td_cpuset)
375		cpuset_rel(td->td_cpuset);
376	td->td_cpuset = NULL;
377	cpu_thread_free(td);
378	if (td->td_kstack != 0)
379		vm_thread_dispose(td);
380	uma_zfree(thread_zone, td);
381}
382
383/*
384 * Discard the current thread and exit from its context.
385 * Always called with scheduler locked.
386 *
387 * Because we can't free a thread while we're operating under its context,
388 * push the current thread into our CPU's deadthread holder. This means
389 * we needn't worry about someone else grabbing our context before we
390 * do a cpu_throw().
391 */
392void
393thread_exit(void)
394{
395	uint64_t new_switchtime;
396	struct thread *td;
397	struct thread *td2;
398	struct proc *p;
399	int wakeup_swapper;
400
401	td = curthread;
402	p = td->td_proc;
403
404	PROC_SLOCK_ASSERT(p, MA_OWNED);
405	mtx_assert(&Giant, MA_NOTOWNED);
406
407	PROC_LOCK_ASSERT(p, MA_OWNED);
408	KASSERT(p != NULL, ("thread exiting without a process"));
409	CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
410	    (long)p->p_pid, td->td_name);
411	KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
412
413#ifdef AUDIT
414	AUDIT_SYSCALL_EXIT(0, td);
415#endif
416	umtx_thread_exit(td);
417	/*
418	 * drop FPU & debug register state storage, or any other
419	 * architecture specific resources that
420	 * would not be on a new untouched process.
421	 */
422	cpu_thread_exit(td);	/* XXXSMP */
423
424	/* Do the same timestamp bookkeeping that mi_switch() would do. */
425	new_switchtime = cpu_ticks();
426	p->p_rux.rux_runtime += (new_switchtime - PCPU_GET(switchtime));
427	PCPU_SET(switchtime, new_switchtime);
428	PCPU_SET(switchticks, ticks);
429	PCPU_INC(cnt.v_swtch);
430	/* Save our resource usage in our process. */
431	td->td_ru.ru_nvcsw++;
432	rucollect(&p->p_ru, &td->td_ru);
433	/*
434	 * The last thread is left attached to the process
435	 * So that the whole bundle gets recycled. Skip
436	 * all this stuff if we never had threads.
437	 * EXIT clears all sign of other threads when
438	 * it goes to single threading, so the last thread always
439	 * takes the short path.
440	 */
441	if (p->p_flag & P_HADTHREADS) {
442		if (p->p_numthreads > 1) {
443			thread_unlink(td);
444			td2 = FIRST_THREAD_IN_PROC(p);
445			sched_exit_thread(td2, td);
446
447			/*
448			 * The test below is NOT true if we are the
449			 * sole exiting thread. P_STOPPED_SINGLE is unset
450			 * in exit1() after it is the only survivor.
451			 */
452			if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
453				if (p->p_numthreads == p->p_suspcount) {
454					thread_lock(p->p_singlethread);
455					wakeup_swapper = thread_unsuspend_one(
456						p->p_singlethread);
457					thread_unlock(p->p_singlethread);
458					if (wakeup_swapper)
459						kick_proc0();
460				}
461			}
462
463			atomic_add_int(&td->td_proc->p_exitthreads, 1);
464			PCPU_SET(deadthread, td);
465		} else {
466			/*
467			 * The last thread is exiting.. but not through exit()
468			 */
469			panic ("thread_exit: Last thread exiting on its own");
470		}
471	}
472#ifdef	HWPMC_HOOKS
473	/*
474	 * If this thread is part of a process that is being tracked by hwpmc(4),
475	 * inform the module of the thread's impending exit.
476	 */
477	if (PMC_PROC_IS_USING_PMCS(td->td_proc))
478		PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
479#endif
480	PROC_UNLOCK(p);
481	ruxagg(p, td);
482	thread_lock(td);
483	PROC_SUNLOCK(p);
484	td->td_state = TDS_INACTIVE;
485#ifdef WITNESS
486	witness_thread_exit(td);
487#endif
488	CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
489	sched_throw(td);
490	panic("I'm a teapot!");
491	/* NOTREACHED */
492}
493
494/*
495 * Do any thread specific cleanups that may be needed in wait()
496 * called with Giant, proc and schedlock not held.
497 */
498void
499thread_wait(struct proc *p)
500{
501	struct thread *td;
502
503	mtx_assert(&Giant, MA_NOTOWNED);
504	KASSERT((p->p_numthreads == 1), ("Multiple threads in wait1()"));
505	td = FIRST_THREAD_IN_PROC(p);
506	/* Lock the last thread so we spin until it exits cpu_throw(). */
507	thread_lock(td);
508	thread_unlock(td);
509	/* Wait for any remaining threads to exit cpu_throw(). */
510	while (p->p_exitthreads)
511		sched_relinquish(curthread);
512	lock_profile_thread_exit(td);
513	cpuset_rel(td->td_cpuset);
514	td->td_cpuset = NULL;
515	cpu_thread_clean(td);
516	crfree(td->td_ucred);
517	thread_reap();	/* check for zombie threads etc. */
518}
519
520/*
521 * Link a thread to a process.
522 * set up anything that needs to be initialized for it to
523 * be used by the process.
524 */
525void
526thread_link(struct thread *td, struct proc *p)
527{
528
529	/*
530	 * XXX This can't be enabled because it's called for proc0 before
531	 * its lock has been created.
532	 * PROC_LOCK_ASSERT(p, MA_OWNED);
533	 */
534	td->td_state    = TDS_INACTIVE;
535	td->td_proc     = p;
536	td->td_flags    = TDF_INMEM;
537
538	LIST_INIT(&td->td_contested);
539	LIST_INIT(&td->td_lprof[0]);
540	LIST_INIT(&td->td_lprof[1]);
541	sigqueue_init(&td->td_sigqueue, p);
542	callout_init(&td->td_slpcallout, CALLOUT_MPSAFE);
543	TAILQ_INSERT_HEAD(&p->p_threads, td, td_plist);
544	p->p_numthreads++;
545}
546
547/*
548 * Convert a process with one thread to an unthreaded process.
549 */
550void
551thread_unthread(struct thread *td)
552{
553	struct proc *p = td->td_proc;
554
555	KASSERT((p->p_numthreads == 1), ("Unthreading with >1 threads"));
556	p->p_flag &= ~P_HADTHREADS;
557}
558
559/*
560 * Called from:
561 *  thread_exit()
562 */
563void
564thread_unlink(struct thread *td)
565{
566	struct proc *p = td->td_proc;
567
568	PROC_LOCK_ASSERT(p, MA_OWNED);
569	TAILQ_REMOVE(&p->p_threads, td, td_plist);
570	p->p_numthreads--;
571	/* could clear a few other things here */
572	/* Must  NOT clear links to proc! */
573}
574
575static int
576calc_remaining(struct proc *p, int mode)
577{
578	int remaining;
579
580	if (mode == SINGLE_EXIT)
581		remaining = p->p_numthreads;
582	else if (mode == SINGLE_BOUNDARY)
583		remaining = p->p_numthreads - p->p_boundary_count;
584	else if (mode == SINGLE_NO_EXIT)
585		remaining = p->p_numthreads - p->p_suspcount;
586	else
587		panic("calc_remaining: wrong mode %d", mode);
588	return (remaining);
589}
590
591/*
592 * Enforce single-threading.
593 *
594 * Returns 1 if the caller must abort (another thread is waiting to
595 * exit the process or similar). Process is locked!
596 * Returns 0 when you are successfully the only thread running.
597 * A process has successfully single threaded in the suspend mode when
598 * There are no threads in user mode. Threads in the kernel must be
599 * allowed to continue until they get to the user boundary. They may even
600 * copy out their return values and data before suspending. They may however be
601 * accelerated in reaching the user boundary as we will wake up
602 * any sleeping threads that are interruptable. (PCATCH).
603 */
604int
605thread_single(int mode)
606{
607	struct thread *td;
608	struct thread *td2;
609	struct proc *p;
610	int remaining, wakeup_swapper;
611
612	td = curthread;
613	p = td->td_proc;
614	mtx_assert(&Giant, MA_NOTOWNED);
615	PROC_LOCK_ASSERT(p, MA_OWNED);
616	KASSERT((td != NULL), ("curthread is NULL"));
617
618	if ((p->p_flag & P_HADTHREADS) == 0)
619		return (0);
620
621	/* Is someone already single threading? */
622	if (p->p_singlethread != NULL && p->p_singlethread != td)
623		return (1);
624
625	if (mode == SINGLE_EXIT) {
626		p->p_flag |= P_SINGLE_EXIT;
627		p->p_flag &= ~P_SINGLE_BOUNDARY;
628	} else {
629		p->p_flag &= ~P_SINGLE_EXIT;
630		if (mode == SINGLE_BOUNDARY)
631			p->p_flag |= P_SINGLE_BOUNDARY;
632		else
633			p->p_flag &= ~P_SINGLE_BOUNDARY;
634	}
635	p->p_flag |= P_STOPPED_SINGLE;
636	PROC_SLOCK(p);
637	p->p_singlethread = td;
638	remaining = calc_remaining(p, mode);
639	while (remaining != 1) {
640		if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
641			goto stopme;
642		wakeup_swapper = 0;
643		FOREACH_THREAD_IN_PROC(p, td2) {
644			if (td2 == td)
645				continue;
646			thread_lock(td2);
647			td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
648			if (TD_IS_INHIBITED(td2)) {
649				switch (mode) {
650				case SINGLE_EXIT:
651					if (TD_IS_SUSPENDED(td2))
652						wakeup_swapper |=
653						    thread_unsuspend_one(td2);
654					if (TD_ON_SLEEPQ(td2) &&
655					    (td2->td_flags & TDF_SINTR))
656						wakeup_swapper |=
657						    sleepq_abort(td2, EINTR);
658					break;
659				case SINGLE_BOUNDARY:
660					if (TD_IS_SUSPENDED(td2) &&
661					    !(td2->td_flags & TDF_BOUNDARY))
662						wakeup_swapper |=
663						    thread_unsuspend_one(td2);
664					if (TD_ON_SLEEPQ(td2) &&
665					    (td2->td_flags & TDF_SINTR))
666						wakeup_swapper |=
667						    sleepq_abort(td2, ERESTART);
668					break;
669				case SINGLE_NO_EXIT:
670					if (TD_IS_SUSPENDED(td2) &&
671					    !(td2->td_flags & TDF_BOUNDARY))
672						wakeup_swapper |=
673						    thread_unsuspend_one(td2);
674					if (TD_ON_SLEEPQ(td2) &&
675					    (td2->td_flags & TDF_SINTR))
676						wakeup_swapper |=
677						    sleepq_abort(td2, ERESTART);
678					break;
679				default:
680					break;
681				}
682			}
683#ifdef SMP
684			else if (TD_IS_RUNNING(td2) && td != td2) {
685				forward_signal(td2);
686			}
687#endif
688			thread_unlock(td2);
689		}
690		if (wakeup_swapper)
691			kick_proc0();
692		remaining = calc_remaining(p, mode);
693
694		/*
695		 * Maybe we suspended some threads.. was it enough?
696		 */
697		if (remaining == 1)
698			break;
699
700stopme:
701		/*
702		 * Wake us up when everyone else has suspended.
703		 * In the mean time we suspend as well.
704		 */
705		thread_suspend_switch(td);
706		remaining = calc_remaining(p, mode);
707	}
708	if (mode == SINGLE_EXIT) {
709		/*
710		 * We have gotten rid of all the other threads and we
711		 * are about to either exit or exec. In either case,
712		 * we try our utmost  to revert to being a non-threaded
713		 * process.
714		 */
715		p->p_singlethread = NULL;
716		p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT);
717		thread_unthread(td);
718	}
719	PROC_SUNLOCK(p);
720	return (0);
721}
722
723/*
724 * Called in from locations that can safely check to see
725 * whether we have to suspend or at least throttle for a
726 * single-thread event (e.g. fork).
727 *
728 * Such locations include userret().
729 * If the "return_instead" argument is non zero, the thread must be able to
730 * accept 0 (caller may continue), or 1 (caller must abort) as a result.
731 *
732 * The 'return_instead' argument tells the function if it may do a
733 * thread_exit() or suspend, or whether the caller must abort and back
734 * out instead.
735 *
736 * If the thread that set the single_threading request has set the
737 * P_SINGLE_EXIT bit in the process flags then this call will never return
738 * if 'return_instead' is false, but will exit.
739 *
740 * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
741 *---------------+--------------------+---------------------
742 *       0       | returns 0          |   returns 0 or 1
743 *               | when ST ends       |   immediatly
744 *---------------+--------------------+---------------------
745 *       1       | thread exits       |   returns 1
746 *               |                    |  immediatly
747 * 0 = thread_exit() or suspension ok,
748 * other = return error instead of stopping the thread.
749 *
750 * While a full suspension is under effect, even a single threading
751 * thread would be suspended if it made this call (but it shouldn't).
752 * This call should only be made from places where
753 * thread_exit() would be safe as that may be the outcome unless
754 * return_instead is set.
755 */
756int
757thread_suspend_check(int return_instead)
758{
759	struct thread *td;
760	struct proc *p;
761	int wakeup_swapper;
762
763	td = curthread;
764	p = td->td_proc;
765	mtx_assert(&Giant, MA_NOTOWNED);
766	PROC_LOCK_ASSERT(p, MA_OWNED);
767	while (P_SHOULDSTOP(p) ||
768	      ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_SUSPEND))) {
769		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
770			KASSERT(p->p_singlethread != NULL,
771			    ("singlethread not set"));
772			/*
773			 * The only suspension in action is a
774			 * single-threading. Single threader need not stop.
775			 * XXX Should be safe to access unlocked
776			 * as it can only be set to be true by us.
777			 */
778			if (p->p_singlethread == td)
779				return (0);	/* Exempt from stopping. */
780		}
781		if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
782			return (EINTR);
783
784		/* Should we goto user boundary if we didn't come from there? */
785		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
786		    (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
787			return (ERESTART);
788
789		/*
790		 * If the process is waiting for us to exit,
791		 * this thread should just suicide.
792		 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
793		 */
794		if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
795			PROC_UNLOCK(p);
796			tidhash_remove(td);
797			PROC_LOCK(p);
798			tdsigcleanup(td);
799			PROC_SLOCK(p);
800			thread_stopped(p);
801			thread_exit();
802		}
803
804		PROC_SLOCK(p);
805		thread_stopped(p);
806		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
807			if (p->p_numthreads == p->p_suspcount + 1) {
808				thread_lock(p->p_singlethread);
809				wakeup_swapper =
810				    thread_unsuspend_one(p->p_singlethread);
811				thread_unlock(p->p_singlethread);
812				if (wakeup_swapper)
813					kick_proc0();
814			}
815		}
816		PROC_UNLOCK(p);
817		thread_lock(td);
818		/*
819		 * When a thread suspends, it just
820		 * gets taken off all queues.
821		 */
822		thread_suspend_one(td);
823		if (return_instead == 0) {
824			p->p_boundary_count++;
825			td->td_flags |= TDF_BOUNDARY;
826		}
827		PROC_SUNLOCK(p);
828		mi_switch(SW_INVOL | SWT_SUSPEND, NULL);
829		if (return_instead == 0)
830			td->td_flags &= ~TDF_BOUNDARY;
831		thread_unlock(td);
832		PROC_LOCK(p);
833		if (return_instead == 0)
834			p->p_boundary_count--;
835	}
836	return (0);
837}
838
839void
840thread_suspend_switch(struct thread *td)
841{
842	struct proc *p;
843
844	p = td->td_proc;
845	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
846	PROC_LOCK_ASSERT(p, MA_OWNED);
847	PROC_SLOCK_ASSERT(p, MA_OWNED);
848	/*
849	 * We implement thread_suspend_one in stages here to avoid
850	 * dropping the proc lock while the thread lock is owned.
851	 */
852	thread_stopped(p);
853	p->p_suspcount++;
854	PROC_UNLOCK(p);
855	thread_lock(td);
856	td->td_flags &= ~TDF_NEEDSUSPCHK;
857	TD_SET_SUSPENDED(td);
858	sched_sleep(td, 0);
859	PROC_SUNLOCK(p);
860	DROP_GIANT();
861	mi_switch(SW_VOL | SWT_SUSPEND, NULL);
862	thread_unlock(td);
863	PICKUP_GIANT();
864	PROC_LOCK(p);
865	PROC_SLOCK(p);
866}
867
868void
869thread_suspend_one(struct thread *td)
870{
871	struct proc *p = td->td_proc;
872
873	PROC_SLOCK_ASSERT(p, MA_OWNED);
874	THREAD_LOCK_ASSERT(td, MA_OWNED);
875	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
876	p->p_suspcount++;
877	td->td_flags &= ~TDF_NEEDSUSPCHK;
878	TD_SET_SUSPENDED(td);
879	sched_sleep(td, 0);
880}
881
882int
883thread_unsuspend_one(struct thread *td)
884{
885	struct proc *p = td->td_proc;
886
887	PROC_SLOCK_ASSERT(p, MA_OWNED);
888	THREAD_LOCK_ASSERT(td, MA_OWNED);
889	KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
890	TD_CLR_SUSPENDED(td);
891	p->p_suspcount--;
892	return (setrunnable(td));
893}
894
895/*
896 * Allow all threads blocked by single threading to continue running.
897 */
898void
899thread_unsuspend(struct proc *p)
900{
901	struct thread *td;
902	int wakeup_swapper;
903
904	PROC_LOCK_ASSERT(p, MA_OWNED);
905	PROC_SLOCK_ASSERT(p, MA_OWNED);
906	wakeup_swapper = 0;
907	if (!P_SHOULDSTOP(p)) {
908                FOREACH_THREAD_IN_PROC(p, td) {
909			thread_lock(td);
910			if (TD_IS_SUSPENDED(td)) {
911				wakeup_swapper |= thread_unsuspend_one(td);
912			}
913			thread_unlock(td);
914		}
915	} else if ((P_SHOULDSTOP(p) == P_STOPPED_SINGLE) &&
916	    (p->p_numthreads == p->p_suspcount)) {
917		/*
918		 * Stopping everything also did the job for the single
919		 * threading request. Now we've downgraded to single-threaded,
920		 * let it continue.
921		 */
922		thread_lock(p->p_singlethread);
923		wakeup_swapper = thread_unsuspend_one(p->p_singlethread);
924		thread_unlock(p->p_singlethread);
925	}
926	if (wakeup_swapper)
927		kick_proc0();
928}
929
930/*
931 * End the single threading mode..
932 */
933void
934thread_single_end(void)
935{
936	struct thread *td;
937	struct proc *p;
938	int wakeup_swapper;
939
940	td = curthread;
941	p = td->td_proc;
942	PROC_LOCK_ASSERT(p, MA_OWNED);
943	p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY);
944	PROC_SLOCK(p);
945	p->p_singlethread = NULL;
946	wakeup_swapper = 0;
947	/*
948	 * If there are other threads they may now run,
949	 * unless of course there is a blanket 'stop order'
950	 * on the process. The single threader must be allowed
951	 * to continue however as this is a bad place to stop.
952	 */
953	if ((p->p_numthreads != 1) && (!P_SHOULDSTOP(p))) {
954                FOREACH_THREAD_IN_PROC(p, td) {
955			thread_lock(td);
956			if (TD_IS_SUSPENDED(td)) {
957				wakeup_swapper |= thread_unsuspend_one(td);
958			}
959			thread_unlock(td);
960		}
961	}
962	PROC_SUNLOCK(p);
963	if (wakeup_swapper)
964		kick_proc0();
965}
966
967struct thread *
968thread_find(struct proc *p, lwpid_t tid)
969{
970	struct thread *td;
971
972	PROC_LOCK_ASSERT(p, MA_OWNED);
973	FOREACH_THREAD_IN_PROC(p, td) {
974		if (td->td_tid == tid)
975			break;
976	}
977	return (td);
978}
979
980/* Locate a thread by number; return with proc lock held. */
981struct thread *
982tdfind(lwpid_t tid, pid_t pid)
983{
984#define RUN_THRESH	16
985	struct thread *td;
986	int run = 0;
987
988	rw_rlock(&tidhash_lock);
989	LIST_FOREACH(td, TIDHASH(tid), td_hash) {
990		if (td->td_tid == tid) {
991			if (pid != -1 && td->td_proc->p_pid != pid) {
992				td = NULL;
993				break;
994			}
995			if (td->td_proc->p_state == PRS_NEW) {
996				td = NULL;
997				break;
998			}
999			if (run > RUN_THRESH) {
1000				if (rw_try_upgrade(&tidhash_lock)) {
1001					LIST_REMOVE(td, td_hash);
1002					LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1003						td, td_hash);
1004					PROC_LOCK(td->td_proc);
1005					rw_wunlock(&tidhash_lock);
1006					return (td);
1007				}
1008			}
1009			PROC_LOCK(td->td_proc);
1010			break;
1011		}
1012		run++;
1013	}
1014	rw_runlock(&tidhash_lock);
1015	return (td);
1016}
1017
1018void
1019tidhash_add(struct thread *td)
1020{
1021	rw_wlock(&tidhash_lock);
1022	LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1023	rw_wunlock(&tidhash_lock);
1024}
1025
1026void
1027tidhash_remove(struct thread *td)
1028{
1029	rw_wlock(&tidhash_lock);
1030	LIST_REMOVE(td, td_hash);
1031	rw_wunlock(&tidhash_lock);
1032}
1033