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