xref: /freebsd/sys/kern/kern_thread.c (revision b75b03116f6137e570f5f158ac66831ecf90954e)
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/smp.h>
39 #include <sys/sysctl.h>
40 #include <sys/sched.h>
41 #include <sys/sleepqueue.h>
42 #include <sys/turnstile.h>
43 #include <sys/ktr.h>
44 #include <sys/umtx.h>
45 
46 #include <vm/vm.h>
47 #include <vm/vm_extern.h>
48 #include <vm/uma.h>
49 
50 /*
51  * KSEGRP related storage.
52  */
53 static uma_zone_t ksegrp_zone;
54 static uma_zone_t thread_zone;
55 
56 /* DEBUG ONLY */
57 SYSCTL_NODE(_kern, OID_AUTO, threads, CTLFLAG_RW, 0, "thread allocation");
58 static int thread_debug = 0;
59 SYSCTL_INT(_kern_threads, OID_AUTO, debug, CTLFLAG_RW,
60 	&thread_debug, 0, "thread debug");
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_groups_per_proc = 1500;
67 SYSCTL_INT(_kern_threads, OID_AUTO, max_groups_per_proc, CTLFLAG_RW,
68 	&max_groups_per_proc, 0, "Limit on thread groups per proc");
69 
70 int max_threads_hits;
71 SYSCTL_INT(_kern_threads, OID_AUTO, max_threads_hits, CTLFLAG_RD,
72 	&max_threads_hits, 0, "");
73 
74 int virtual_cpu;
75 
76 TAILQ_HEAD(, thread) zombie_threads = TAILQ_HEAD_INITIALIZER(zombie_threads);
77 TAILQ_HEAD(, ksegrp) zombie_ksegrps = TAILQ_HEAD_INITIALIZER(zombie_ksegrps);
78 struct mtx kse_zombie_lock;
79 MTX_SYSINIT(kse_zombie_lock, &kse_zombie_lock, "kse zombie lock", MTX_SPIN);
80 
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 
106 struct mtx tid_lock;
107 static struct unrhdr *tid_unrhdr;
108 
109 /*
110  * Prepare a thread for use.
111  */
112 static int
113 thread_ctor(void *mem, int size, void *arg, int flags)
114 {
115 	struct thread	*td;
116 
117 	td = (struct thread *)mem;
118 	td->td_state = TDS_INACTIVE;
119 	td->td_oncpu = NOCPU;
120 
121 	td->td_tid = alloc_unr(tid_unrhdr);
122 
123 	/*
124 	 * Note that td_critnest begins life as 1 because the thread is not
125 	 * running and is thereby implicitly waiting to be on the receiving
126 	 * end of a context switch.  A context switch must occur inside a
127 	 * critical section, and in fact, includes hand-off of the sched_lock.
128 	 * After a context switch to a newly created thread, it will release
129 	 * sched_lock for the first time, and its td_critnest will hit 0 for
130 	 * the first time.  This happens on the far end of a context switch,
131 	 * and when it context switches away from itself, it will in fact go
132 	 * back into a critical section, and hand off the sched lock to the
133 	 * next thread.
134 	 */
135 	td->td_critnest = 1;
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 
170 	free_unr(tid_unrhdr, td->td_tid);
171 	sched_newthread(td);
172 }
173 
174 /*
175  * Initialize type-stable parts of a thread (when newly created).
176  */
177 static int
178 thread_init(void *mem, int size, int flags)
179 {
180 	struct thread *td;
181 
182 	td = (struct thread *)mem;
183 
184 	vm_thread_new(td, 0);
185 	cpu_thread_setup(td);
186 	td->td_sleepqueue = sleepq_alloc();
187 	td->td_turnstile = turnstile_alloc();
188 	td->td_umtxq = umtxq_alloc();
189 	td->td_sched = (struct td_sched *)&td[1];
190 	sched_newthread(td);
191 	return (0);
192 }
193 
194 /*
195  * Tear down type-stable parts of a thread (just before being discarded).
196  */
197 static void
198 thread_fini(void *mem, int size)
199 {
200 	struct thread *td;
201 
202 	td = (struct thread *)mem;
203 	turnstile_free(td->td_turnstile);
204 	sleepq_free(td->td_sleepqueue);
205 	umtxq_free(td->td_umtxq);
206 	vm_thread_dispose(td);
207 }
208 
209 /*
210  * Initialize type-stable parts of a ksegrp (when newly created).
211  */
212 static int
213 ksegrp_ctor(void *mem, int size, void *arg, int flags)
214 {
215 	struct ksegrp	*kg;
216 
217 	kg = (struct ksegrp *)mem;
218 	bzero(mem, size);
219 	kg->kg_sched = (struct kg_sched *)&kg[1];
220 	return (0);
221 }
222 
223 void
224 ksegrp_link(struct ksegrp *kg, struct proc *p)
225 {
226 
227 	TAILQ_INIT(&kg->kg_threads);
228 	TAILQ_INIT(&kg->kg_runq);	/* links with td_runq */
229 	TAILQ_INIT(&kg->kg_upcalls);	/* all upcall structure in ksegrp */
230 	kg->kg_proc = p;
231 	/*
232 	 * the following counters are in the -zero- section
233 	 * and may not need clearing
234 	 */
235 	kg->kg_numthreads = 0;
236 	kg->kg_numupcalls = 0;
237 	/* link it in now that it's consistent */
238 	p->p_numksegrps++;
239 	TAILQ_INSERT_HEAD(&p->p_ksegrps, kg, kg_ksegrp);
240 }
241 
242 /*
243  * Called from:
244  *   thread-exit()
245  */
246 void
247 ksegrp_unlink(struct ksegrp *kg)
248 {
249 	struct proc *p;
250 
251 	mtx_assert(&sched_lock, MA_OWNED);
252 	KASSERT((kg->kg_numthreads == 0), ("ksegrp_unlink: residual threads"));
253 	KASSERT((kg->kg_numupcalls == 0), ("ksegrp_unlink: residual upcalls"));
254 
255 	p = kg->kg_proc;
256 	TAILQ_REMOVE(&p->p_ksegrps, kg, kg_ksegrp);
257 	p->p_numksegrps--;
258 	/*
259 	 * Aggregate stats from the KSE
260 	 */
261 }
262 
263 /*
264  * For a newly created process,
265  * link up all the structures and its initial threads etc.
266  * called from:
267  * {arch}/{arch}/machdep.c   ia64_init(), init386() etc.
268  * proc_dtor() (should go away)
269  * proc_init()
270  */
271 void
272 proc_linkup(struct proc *p, struct ksegrp *kg, struct thread *td)
273 {
274 
275 	TAILQ_INIT(&p->p_ksegrps);	     /* all ksegrps in proc */
276 	TAILQ_INIT(&p->p_threads);	     /* all threads in proc */
277 	TAILQ_INIT(&p->p_suspended);	     /* Threads suspended */
278 	p->p_numksegrps = 0;
279 	p->p_numthreads = 0;
280 
281 	ksegrp_link(kg, p);
282 	thread_link(td, kg);
283 }
284 
285 /*
286  * Initialize global thread allocation resources.
287  */
288 void
289 threadinit(void)
290 {
291 
292 	mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
293 	tid_unrhdr = new_unrhdr(PID_MAX + 1, INT_MAX, &tid_lock);
294 
295 	thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
296 	    thread_ctor, thread_dtor, thread_init, thread_fini,
297 	    UMA_ALIGN_CACHE, 0);
298 	ksegrp_zone = uma_zcreate("KSEGRP", sched_sizeof_ksegrp(),
299 	    ksegrp_ctor, NULL, NULL, NULL,
300 	    UMA_ALIGN_CACHE, 0);
301 	kseinit();	/* set up kse specific stuff  e.g. upcall zone*/
302 }
303 
304 /*
305  * Stash an embarasingly extra thread into the zombie thread queue.
306  */
307 void
308 thread_stash(struct thread *td)
309 {
310 	mtx_lock_spin(&kse_zombie_lock);
311 	TAILQ_INSERT_HEAD(&zombie_threads, td, td_runq);
312 	mtx_unlock_spin(&kse_zombie_lock);
313 }
314 
315 /*
316  * Stash an embarasingly extra ksegrp into the zombie ksegrp queue.
317  */
318 void
319 ksegrp_stash(struct ksegrp *kg)
320 {
321 	mtx_lock_spin(&kse_zombie_lock);
322 	TAILQ_INSERT_HEAD(&zombie_ksegrps, kg, kg_ksegrp);
323 	mtx_unlock_spin(&kse_zombie_lock);
324 }
325 
326 /*
327  * Reap zombie kse resource.
328  */
329 void
330 thread_reap(void)
331 {
332 	struct thread *td_first, *td_next;
333 	struct ksegrp *kg_first, * kg_next;
334 
335 	/*
336 	 * Don't even bother to lock if none at this instant,
337 	 * we really don't care about the next instant..
338 	 */
339 	if ((!TAILQ_EMPTY(&zombie_threads))
340 	    || (!TAILQ_EMPTY(&zombie_ksegrps))) {
341 		mtx_lock_spin(&kse_zombie_lock);
342 		td_first = TAILQ_FIRST(&zombie_threads);
343 		kg_first = TAILQ_FIRST(&zombie_ksegrps);
344 		if (td_first)
345 			TAILQ_INIT(&zombie_threads);
346 		if (kg_first)
347 			TAILQ_INIT(&zombie_ksegrps);
348 		mtx_unlock_spin(&kse_zombie_lock);
349 		while (td_first) {
350 			td_next = TAILQ_NEXT(td_first, td_runq);
351 			if (td_first->td_ucred)
352 				crfree(td_first->td_ucred);
353 			thread_free(td_first);
354 			td_first = td_next;
355 		}
356 		while (kg_first) {
357 			kg_next = TAILQ_NEXT(kg_first, kg_ksegrp);
358 			ksegrp_free(kg_first);
359 			kg_first = kg_next;
360 		}
361 		/*
362 		 * there will always be a thread on the list if one of these
363 		 * is there.
364 		 */
365 		kse_GC();
366 	}
367 }
368 
369 /*
370  * Allocate a ksegrp.
371  */
372 struct ksegrp *
373 ksegrp_alloc(void)
374 {
375 	return (uma_zalloc(ksegrp_zone, M_WAITOK));
376 }
377 
378 /*
379  * Allocate a thread.
380  */
381 struct thread *
382 thread_alloc(void)
383 {
384 	thread_reap(); /* check if any zombies to get */
385 	return (uma_zalloc(thread_zone, M_WAITOK));
386 }
387 
388 /*
389  * Deallocate a ksegrp.
390  */
391 void
392 ksegrp_free(struct ksegrp *td)
393 {
394 	uma_zfree(ksegrp_zone, td);
395 }
396 
397 /*
398  * Deallocate a thread.
399  */
400 void
401 thread_free(struct thread *td)
402 {
403 
404 	cpu_thread_clean(td);
405 	uma_zfree(thread_zone, td);
406 }
407 
408 /*
409  * Discard the current thread and exit from its context.
410  * Always called with scheduler locked.
411  *
412  * Because we can't free a thread while we're operating under its context,
413  * push the current thread into our CPU's deadthread holder. This means
414  * we needn't worry about someone else grabbing our context before we
415  * do a cpu_throw().  This may not be needed now as we are under schedlock.
416  * Maybe we can just do a thread_stash() as thr_exit1 does.
417  */
418 /*  XXX
419  * libthr expects its thread exit to return for the last
420  * thread, meaning that the program is back to non-threaded
421  * mode I guess. Because we do this (cpu_throw) unconditionally
422  * here, they have their own version of it. (thr_exit1())
423  * that doesn't do it all if this was the last thread.
424  * It is also called from thread_suspend_check().
425  * Of course in the end, they end up coming here through exit1
426  * anyhow..  After fixing 'thr' to play by the rules we should be able
427  * to merge these two functions together.
428  *
429  * called from:
430  * exit1()
431  * kse_exit()
432  * thr_exit()
433  * thread_user_enter()
434  * thread_userret()
435  * thread_suspend_check()
436  */
437 void
438 thread_exit(void)
439 {
440 	struct thread *td;
441 	struct proc *p;
442 	struct ksegrp	*kg;
443 
444 	td = curthread;
445 	kg = td->td_ksegrp;
446 	p = td->td_proc;
447 
448 	mtx_assert(&sched_lock, MA_OWNED);
449 	mtx_assert(&Giant, MA_NOTOWNED);
450 	PROC_LOCK_ASSERT(p, MA_OWNED);
451 	KASSERT(p != NULL, ("thread exiting without a process"));
452 	KASSERT(kg != NULL, ("thread exiting without a kse group"));
453 	CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
454 	    (long)p->p_pid, p->p_comm);
455 
456 	if (td->td_standin != NULL) {
457 		/*
458 		 * Note that we don't need to free the cred here as it
459 		 * is done in thread_reap().
460 		 */
461 		thread_stash(td->td_standin);
462 		td->td_standin = NULL;
463 	}
464 
465 	/*
466 	 * drop FPU & debug register state storage, or any other
467 	 * architecture specific resources that
468 	 * would not be on a new untouched process.
469 	 */
470 	cpu_thread_exit(td);	/* XXXSMP */
471 
472 	/*
473 	 * The thread is exiting. scheduler can release its stuff
474 	 * and collect stats etc.
475 	 */
476 	sched_thread_exit(td);
477 
478 	/*
479 	 * The last thread is left attached to the process
480 	 * So that the whole bundle gets recycled. Skip
481 	 * all this stuff if we never had threads.
482 	 * EXIT clears all sign of other threads when
483 	 * it goes to single threading, so the last thread always
484 	 * takes the short path.
485 	 */
486 	if (p->p_flag & P_HADTHREADS) {
487 		if (p->p_numthreads > 1) {
488 			thread_unlink(td);
489 
490 			/* XXX first arg not used in 4BSD or ULE */
491 			sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
492 
493 			/*
494 			 * as we are exiting there is room for another
495 			 * to be created.
496 			 */
497 			if (p->p_maxthrwaits)
498 				wakeup(&p->p_numthreads);
499 
500 			/*
501 			 * The test below is NOT true if we are the
502 			 * sole exiting thread. P_STOPPED_SNGL is unset
503 			 * in exit1() after it is the only survivor.
504 			 */
505 			if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
506 				if (p->p_numthreads == p->p_suspcount) {
507 					thread_unsuspend_one(p->p_singlethread);
508 				}
509 			}
510 
511 			/*
512 			 * Because each upcall structure has an owner thread,
513 			 * owner thread exits only when process is in exiting
514 			 * state, so upcall to userland is no longer needed,
515 			 * deleting upcall structure is safe here.
516 			 * So when all threads in a group is exited, all upcalls
517 			 * in the group should be automatically freed.
518 			 *  XXXKSE This is a KSE thing and should be exported
519 			 * there somehow.
520 			 */
521 			upcall_remove(td);
522 
523 			/*
524 			 * If the thread we unlinked above was the last one,
525 			 * then this ksegrp should go away too.
526 			 */
527 			if (kg->kg_numthreads == 0) {
528 				/*
529 				 * let the scheduler know about this in case
530 				 * it needs to recover stats or resources.
531 				 * Theoretically we could let
532 				 * sched_exit_ksegrp()  do the equivalent of
533 				 * setting the concurrency to 0
534 				 * but don't do it yet to avoid changing
535 				 * the existing scheduler code until we
536 				 * are ready.
537 				 * We supply a random other ksegrp
538 				 * as the recipient of any built up
539 				 * cpu usage etc. (If the scheduler wants it).
540 				 * XXXKSE
541 				 * This is probably not fair so think of
542  				 * a better answer.
543 				 */
544 				sched_exit_ksegrp(FIRST_KSEGRP_IN_PROC(p), td);
545 				sched_set_concurrency(kg, 0); /* XXX TEMP */
546 				ksegrp_unlink(kg);
547 				ksegrp_stash(kg);
548 			}
549 			PROC_UNLOCK(p);
550 			td->td_ksegrp	= NULL;
551 			PCPU_SET(deadthread, td);
552 		} else {
553 			/*
554 			 * The last thread is exiting.. but not through exit()
555 			 * what should we do?
556 			 * Theoretically this can't happen
557  			 * exit1() - clears threading flags before coming here
558  			 * kse_exit() - treats last thread specially
559  			 * thr_exit() - treats last thread specially
560  			 * thread_user_enter() - only if more exist
561  			 * thread_userret() - only if more exist
562  			 * thread_suspend_check() - only if more exist
563 			 */
564 			panic ("thread_exit: Last thread exiting on its own");
565 		}
566 	} else {
567 		/*
568 		 * non threaded process comes here.
569 		 * This includes an EX threaded process that is coming
570 		 * here via exit1(). (exit1 dethreads the proc first).
571 		 */
572 		PROC_UNLOCK(p);
573 	}
574 	td->td_state = TDS_INACTIVE;
575 	CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
576 	cpu_throw(td, choosethread());
577 	panic("I'm a teapot!");
578 	/* NOTREACHED */
579 }
580 
581 /*
582  * Do any thread specific cleanups that may be needed in wait()
583  * called with Giant, proc and schedlock not held.
584  */
585 void
586 thread_wait(struct proc *p)
587 {
588 	struct thread *td;
589 
590 	mtx_assert(&Giant, MA_NOTOWNED);
591 	KASSERT((p->p_numthreads == 1), ("Multiple threads in wait1()"));
592 	KASSERT((p->p_numksegrps == 1), ("Multiple ksegrps in wait1()"));
593 	FOREACH_THREAD_IN_PROC(p, td) {
594 		if (td->td_standin != NULL) {
595 			if (td->td_standin->td_ucred != NULL) {
596 				crfree(td->td_standin->td_ucred);
597 				td->td_standin->td_ucred = NULL;
598 			}
599 			thread_free(td->td_standin);
600 			td->td_standin = NULL;
601 		}
602 		cpu_thread_clean(td);
603 		crfree(td->td_ucred);
604 	}
605 	thread_reap();	/* check for zombie threads etc. */
606 }
607 
608 /*
609  * Link a thread to a process.
610  * set up anything that needs to be initialized for it to
611  * be used by the process.
612  *
613  * Note that we do not link to the proc's ucred here.
614  * The thread is linked as if running but no KSE assigned.
615  * Called from:
616  *  proc_linkup()
617  *  thread_schedule_upcall()
618  *  thr_create()
619  */
620 void
621 thread_link(struct thread *td, struct ksegrp *kg)
622 {
623 	struct proc *p;
624 
625 	p = kg->kg_proc;
626 	td->td_state    = TDS_INACTIVE;
627 	td->td_proc     = p;
628 	td->td_ksegrp   = kg;
629 	td->td_flags    = 0;
630 	td->td_kflags	= 0;
631 
632 	LIST_INIT(&td->td_contested);
633 	callout_init(&td->td_slpcallout, CALLOUT_MPSAFE);
634 	TAILQ_INSERT_HEAD(&p->p_threads, td, td_plist);
635 	TAILQ_INSERT_HEAD(&kg->kg_threads, td, td_kglist);
636 	p->p_numthreads++;
637 	kg->kg_numthreads++;
638 }
639 
640 /*
641  * Convert a process with one thread to an unthreaded process.
642  * Called from:
643  *  thread_single(exit)  (called from execve and exit)
644  *  kse_exit()		XXX may need cleaning up wrt KSE stuff
645  */
646 void
647 thread_unthread(struct thread *td)
648 {
649 	struct proc *p = td->td_proc;
650 
651 	KASSERT((p->p_numthreads == 1), ("Unthreading with >1 threads"));
652 	upcall_remove(td);
653 	p->p_flag &= ~(P_SA|P_HADTHREADS);
654 	td->td_mailbox = NULL;
655 	td->td_pflags &= ~(TDP_SA | TDP_CAN_UNBIND);
656 	if (td->td_standin != NULL) {
657 		thread_stash(td->td_standin);
658 		td->td_standin = NULL;
659 	}
660 	sched_set_concurrency(td->td_ksegrp, 1);
661 }
662 
663 /*
664  * Called from:
665  *  thread_exit()
666  */
667 void
668 thread_unlink(struct thread *td)
669 {
670 	struct proc *p = td->td_proc;
671 	struct ksegrp *kg = td->td_ksegrp;
672 
673 	mtx_assert(&sched_lock, MA_OWNED);
674 	TAILQ_REMOVE(&p->p_threads, td, td_plist);
675 	p->p_numthreads--;
676 	TAILQ_REMOVE(&kg->kg_threads, td, td_kglist);
677 	kg->kg_numthreads--;
678 	/* could clear a few other things here */
679 	/* Must  NOT clear links to proc and ksegrp! */
680 }
681 
682 /*
683  * Enforce single-threading.
684  *
685  * Returns 1 if the caller must abort (another thread is waiting to
686  * exit the process or similar). Process is locked!
687  * Returns 0 when you are successfully the only thread running.
688  * A process has successfully single threaded in the suspend mode when
689  * There are no threads in user mode. Threads in the kernel must be
690  * allowed to continue until they get to the user boundary. They may even
691  * copy out their return values and data before suspending. They may however be
692  * accellerated in reaching the user boundary as we will wake up
693  * any sleeping threads that are interruptable. (PCATCH).
694  */
695 int
696 thread_single(int mode)
697 {
698 	struct thread *td;
699 	struct thread *td2;
700 	struct proc *p;
701 	int remaining;
702 
703 	td = curthread;
704 	p = td->td_proc;
705 	mtx_assert(&Giant, MA_NOTOWNED);
706 	PROC_LOCK_ASSERT(p, MA_OWNED);
707 	KASSERT((td != NULL), ("curthread is NULL"));
708 
709 	if ((p->p_flag & P_HADTHREADS) == 0)
710 		return (0);
711 
712 	/* Is someone already single threading? */
713 	if (p->p_singlethread != NULL && p->p_singlethread != td)
714 		return (1);
715 
716 	if (mode == SINGLE_EXIT) {
717 		p->p_flag |= P_SINGLE_EXIT;
718 		p->p_flag &= ~P_SINGLE_BOUNDARY;
719 	} else {
720 		p->p_flag &= ~P_SINGLE_EXIT;
721 		if (mode == SINGLE_BOUNDARY)
722 			p->p_flag |= P_SINGLE_BOUNDARY;
723 		else
724 			p->p_flag &= ~P_SINGLE_BOUNDARY;
725 	}
726 	p->p_flag |= P_STOPPED_SINGLE;
727 	mtx_lock_spin(&sched_lock);
728 	p->p_singlethread = td;
729 	if (mode == SINGLE_EXIT)
730 		remaining = p->p_numthreads;
731 	else if (mode == SINGLE_BOUNDARY)
732 		remaining = p->p_numthreads - p->p_boundary_count;
733 	else
734 		remaining = p->p_numthreads - p->p_suspcount;
735 	while (remaining != 1) {
736 		FOREACH_THREAD_IN_PROC(p, td2) {
737 			if (td2 == td)
738 				continue;
739 			td2->td_flags |= TDF_ASTPENDING;
740 			if (TD_IS_INHIBITED(td2)) {
741 				switch (mode) {
742 				case SINGLE_EXIT:
743 					if (td->td_flags & TDF_DBSUSPEND)
744 						td->td_flags &= ~TDF_DBSUSPEND;
745 					if (TD_IS_SUSPENDED(td2))
746 						thread_unsuspend_one(td2);
747 					if (TD_ON_SLEEPQ(td2) &&
748 					    (td2->td_flags & TDF_SINTR))
749 						sleepq_abort(td2);
750 					break;
751 				case SINGLE_BOUNDARY:
752 					if (TD_IS_SUSPENDED(td2) &&
753 					    !(td2->td_flags & TDF_BOUNDARY))
754 						thread_unsuspend_one(td2);
755 					if (TD_ON_SLEEPQ(td2) &&
756 					    (td2->td_flags & TDF_SINTR))
757 						sleepq_abort(td2);
758 					break;
759 				default:
760 					if (TD_IS_SUSPENDED(td2))
761 						continue;
762 					/*
763 					 * maybe other inhibitted states too?
764 					 */
765 					if ((td2->td_flags & TDF_SINTR) &&
766 					    (td2->td_inhibitors &
767 					    (TDI_SLEEPING | TDI_SWAPPED)))
768 						thread_suspend_one(td2);
769 					break;
770 				}
771 			}
772 		}
773 		if (mode == SINGLE_EXIT)
774 			remaining = p->p_numthreads;
775 		else if (mode == SINGLE_BOUNDARY)
776 			remaining = p->p_numthreads - p->p_boundary_count;
777 		else
778 			remaining = p->p_numthreads - p->p_suspcount;
779 
780 		/*
781 		 * Maybe we suspended some threads.. was it enough?
782 		 */
783 		if (remaining == 1)
784 			break;
785 
786 		/*
787 		 * Wake us up when everyone else has suspended.
788 		 * In the mean time we suspend as well.
789 		 */
790 		thread_suspend_one(td);
791 		PROC_UNLOCK(p);
792 		mi_switch(SW_VOL, NULL);
793 		mtx_unlock_spin(&sched_lock);
794 		PROC_LOCK(p);
795 		mtx_lock_spin(&sched_lock);
796 		if (mode == SINGLE_EXIT)
797 			remaining = p->p_numthreads;
798 		else if (mode == SINGLE_BOUNDARY)
799 			remaining = p->p_numthreads - p->p_boundary_count;
800 		else
801 			remaining = p->p_numthreads - p->p_suspcount;
802 	}
803 	if (mode == SINGLE_EXIT) {
804 		/*
805 		 * We have gotten rid of all the other threads and we
806 		 * are about to either exit or exec. In either case,
807 		 * we try our utmost  to revert to being a non-threaded
808 		 * process.
809 		 */
810 		p->p_singlethread = NULL;
811 		p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT);
812 		thread_unthread(td);
813 	}
814 	mtx_unlock_spin(&sched_lock);
815 	return (0);
816 }
817 
818 /*
819  * Called in from locations that can safely check to see
820  * whether we have to suspend or at least throttle for a
821  * single-thread event (e.g. fork).
822  *
823  * Such locations include userret().
824  * If the "return_instead" argument is non zero, the thread must be able to
825  * accept 0 (caller may continue), or 1 (caller must abort) as a result.
826  *
827  * The 'return_instead' argument tells the function if it may do a
828  * thread_exit() or suspend, or whether the caller must abort and back
829  * out instead.
830  *
831  * If the thread that set the single_threading request has set the
832  * P_SINGLE_EXIT bit in the process flags then this call will never return
833  * if 'return_instead' is false, but will exit.
834  *
835  * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
836  *---------------+--------------------+---------------------
837  *       0       | returns 0          |   returns 0 or 1
838  *               | when ST ends       |   immediatly
839  *---------------+--------------------+---------------------
840  *       1       | thread exits       |   returns 1
841  *               |                    |  immediatly
842  * 0 = thread_exit() or suspension ok,
843  * other = return error instead of stopping the thread.
844  *
845  * While a full suspension is under effect, even a single threading
846  * thread would be suspended if it made this call (but it shouldn't).
847  * This call should only be made from places where
848  * thread_exit() would be safe as that may be the outcome unless
849  * return_instead is set.
850  */
851 int
852 thread_suspend_check(int return_instead)
853 {
854 	struct thread *td;
855 	struct proc *p;
856 
857 	td = curthread;
858 	p = td->td_proc;
859 	mtx_assert(&Giant, MA_NOTOWNED);
860 	PROC_LOCK_ASSERT(p, MA_OWNED);
861 	while (P_SHOULDSTOP(p) ||
862 	      ((p->p_flag & P_TRACED) && (td->td_flags & TDF_DBSUSPEND))) {
863 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
864 			KASSERT(p->p_singlethread != NULL,
865 			    ("singlethread not set"));
866 			/*
867 			 * The only suspension in action is a
868 			 * single-threading. Single threader need not stop.
869 			 * XXX Should be safe to access unlocked
870 			 * as it can only be set to be true by us.
871 			 */
872 			if (p->p_singlethread == td)
873 				return (0);	/* Exempt from stopping. */
874 		}
875 		if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
876 			return (1);
877 
878 		/* Should we goto user boundary if we didn't come from there? */
879 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
880 		    (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
881 			return (1);
882 
883 		mtx_lock_spin(&sched_lock);
884 		thread_stopped(p);
885 		/*
886 		 * If the process is waiting for us to exit,
887 		 * this thread should just suicide.
888 		 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
889 		 */
890 		if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td))
891 			thread_exit();
892 
893 		/*
894 		 * When a thread suspends, it just
895 		 * moves to the processes's suspend queue
896 		 * and stays there.
897 		 */
898 		thread_suspend_one(td);
899 		if (return_instead == 0) {
900 			p->p_boundary_count++;
901 			td->td_flags |= TDF_BOUNDARY;
902 		}
903 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
904 			if (p->p_numthreads == p->p_suspcount)
905 				thread_unsuspend_one(p->p_singlethread);
906 		}
907 		PROC_UNLOCK(p);
908 		mi_switch(SW_INVOL, NULL);
909 		if (return_instead == 0) {
910 			p->p_boundary_count--;
911 			td->td_flags &= ~TDF_BOUNDARY;
912 		}
913 		mtx_unlock_spin(&sched_lock);
914 		PROC_LOCK(p);
915 	}
916 	return (0);
917 }
918 
919 void
920 thread_suspend_one(struct thread *td)
921 {
922 	struct proc *p = td->td_proc;
923 
924 	mtx_assert(&sched_lock, MA_OWNED);
925 	PROC_LOCK_ASSERT(p, MA_OWNED);
926 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
927 	p->p_suspcount++;
928 	TD_SET_SUSPENDED(td);
929 	TAILQ_INSERT_TAIL(&p->p_suspended, td, td_runq);
930 	/*
931 	 * Hack: If we are suspending but are on the sleep queue
932 	 * then we are in msleep or the cv equivalent. We
933 	 * want to look like we have two Inhibitors.
934 	 * May already be set.. doesn't matter.
935 	 */
936 	if (TD_ON_SLEEPQ(td))
937 		TD_SET_SLEEPING(td);
938 }
939 
940 void
941 thread_unsuspend_one(struct thread *td)
942 {
943 	struct proc *p = td->td_proc;
944 
945 	mtx_assert(&sched_lock, MA_OWNED);
946 	PROC_LOCK_ASSERT(p, MA_OWNED);
947 	TAILQ_REMOVE(&p->p_suspended, td, td_runq);
948 	TD_CLR_SUSPENDED(td);
949 	p->p_suspcount--;
950 	setrunnable(td);
951 }
952 
953 /*
954  * Allow all threads blocked by single threading to continue running.
955  */
956 void
957 thread_unsuspend(struct proc *p)
958 {
959 	struct thread *td;
960 
961 	mtx_assert(&sched_lock, MA_OWNED);
962 	PROC_LOCK_ASSERT(p, MA_OWNED);
963 	if (!P_SHOULDSTOP(p)) {
964 		while ((td = TAILQ_FIRST(&p->p_suspended))) {
965 			thread_unsuspend_one(td);
966 		}
967 	} else if ((P_SHOULDSTOP(p) == P_STOPPED_SINGLE) &&
968 	    (p->p_numthreads == p->p_suspcount)) {
969 		/*
970 		 * Stopping everything also did the job for the single
971 		 * threading request. Now we've downgraded to single-threaded,
972 		 * let it continue.
973 		 */
974 		thread_unsuspend_one(p->p_singlethread);
975 	}
976 }
977 
978 /*
979  * End the single threading mode..
980  */
981 void
982 thread_single_end(void)
983 {
984 	struct thread *td;
985 	struct proc *p;
986 
987 	td = curthread;
988 	p = td->td_proc;
989 	PROC_LOCK_ASSERT(p, MA_OWNED);
990 	p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY);
991 	mtx_lock_spin(&sched_lock);
992 	p->p_singlethread = NULL;
993 	/*
994 	 * If there are other threads they mey now run,
995 	 * unless of course there is a blanket 'stop order'
996 	 * on the process. The single threader must be allowed
997 	 * to continue however as this is a bad place to stop.
998 	 */
999 	if ((p->p_numthreads != 1) && (!P_SHOULDSTOP(p))) {
1000 		while ((td = TAILQ_FIRST(&p->p_suspended))) {
1001 			thread_unsuspend_one(td);
1002 		}
1003 	}
1004 	mtx_unlock_spin(&sched_lock);
1005 }
1006 
1007 /*
1008  * Called before going into an interruptible sleep to see if we have been
1009  * interrupted or requested to exit.
1010  */
1011 int
1012 thread_sleep_check(struct thread *td)
1013 {
1014 	struct proc *p;
1015 
1016 	p = td->td_proc;
1017 	mtx_assert(&sched_lock, MA_OWNED);
1018 	if (p->p_flag & P_HADTHREADS) {
1019 		if (p->p_singlethread != td) {
1020 			if (p->p_flag & P_SINGLE_EXIT)
1021 				return (EINTR);
1022 			if (p->p_flag & P_SINGLE_BOUNDARY)
1023 				return (ERESTART);
1024 		}
1025 		if (td->td_flags & TDF_INTERRUPT)
1026 			return (td->td_intrval);
1027 	}
1028 	return (0);
1029 }
1030