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