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