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