xref: /freebsd/sys/kern/kern_thread.c (revision f9fd7337f63698f33239c58c07bf430198235a22)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (C) 2001 Julian Elischer <julian@freebsd.org>.
5  *  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice(s), this list of conditions and the following disclaimer as
12  *    the first lines of this file unmodified other than the possible
13  *    addition of one or more copyright notices.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice(s), this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
28  * DAMAGE.
29  */
30 
31 #include "opt_witness.h"
32 #include "opt_hwpmc_hooks.h"
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
40 #include <sys/lock.h>
41 #include <sys/mutex.h>
42 #include <sys/proc.h>
43 #include <sys/bitstring.h>
44 #include <sys/epoch.h>
45 #include <sys/rangelock.h>
46 #include <sys/resourcevar.h>
47 #include <sys/sdt.h>
48 #include <sys/smp.h>
49 #include <sys/sched.h>
50 #include <sys/sleepqueue.h>
51 #include <sys/selinfo.h>
52 #include <sys/syscallsubr.h>
53 #include <sys/sysent.h>
54 #include <sys/turnstile.h>
55 #include <sys/ktr.h>
56 #include <sys/rwlock.h>
57 #include <sys/umtx.h>
58 #include <sys/vmmeter.h>
59 #include <sys/cpuset.h>
60 #ifdef	HWPMC_HOOKS
61 #include <sys/pmckern.h>
62 #endif
63 #include <sys/priv.h>
64 
65 #include <security/audit/audit.h>
66 
67 #include <vm/vm.h>
68 #include <vm/vm_extern.h>
69 #include <vm/uma.h>
70 #include <sys/eventhandler.h>
71 
72 /*
73  * Asserts below verify the stability of struct thread and struct proc
74  * layout, as exposed by KBI to modules.  On head, the KBI is allowed
75  * to drift, change to the structures must be accompanied by the
76  * assert update.
77  *
78  * On the stable branches after KBI freeze, conditions must not be
79  * violated.  Typically new fields are moved to the end of the
80  * structures.
81  */
82 #ifdef __amd64__
83 _Static_assert(offsetof(struct thread, td_flags) == 0xfc,
84     "struct thread KBI td_flags");
85 _Static_assert(offsetof(struct thread, td_pflags) == 0x104,
86     "struct thread KBI td_pflags");
87 _Static_assert(offsetof(struct thread, td_frame) == 0x4a0,
88     "struct thread KBI td_frame");
89 _Static_assert(offsetof(struct thread, td_emuldata) == 0x6b0,
90     "struct thread KBI td_emuldata");
91 _Static_assert(offsetof(struct proc, p_flag) == 0xb0,
92     "struct proc KBI p_flag");
93 _Static_assert(offsetof(struct proc, p_pid) == 0xbc,
94     "struct proc KBI p_pid");
95 _Static_assert(offsetof(struct proc, p_filemon) == 0x3b8,
96     "struct proc KBI p_filemon");
97 _Static_assert(offsetof(struct proc, p_comm) == 0x3d0,
98     "struct proc KBI p_comm");
99 _Static_assert(offsetof(struct proc, p_emuldata) == 0x4b0,
100     "struct proc KBI p_emuldata");
101 #endif
102 #ifdef __i386__
103 _Static_assert(offsetof(struct thread, td_flags) == 0x98,
104     "struct thread KBI td_flags");
105 _Static_assert(offsetof(struct thread, td_pflags) == 0xa0,
106     "struct thread KBI td_pflags");
107 _Static_assert(offsetof(struct thread, td_frame) == 0x300,
108     "struct thread KBI td_frame");
109 _Static_assert(offsetof(struct thread, td_emuldata) == 0x344,
110     "struct thread KBI td_emuldata");
111 _Static_assert(offsetof(struct proc, p_flag) == 0x68,
112     "struct proc KBI p_flag");
113 _Static_assert(offsetof(struct proc, p_pid) == 0x74,
114     "struct proc KBI p_pid");
115 _Static_assert(offsetof(struct proc, p_filemon) == 0x268,
116     "struct proc KBI p_filemon");
117 _Static_assert(offsetof(struct proc, p_comm) == 0x27c,
118     "struct proc KBI p_comm");
119 _Static_assert(offsetof(struct proc, p_emuldata) == 0x308,
120     "struct proc KBI p_emuldata");
121 #endif
122 
123 SDT_PROVIDER_DECLARE(proc);
124 SDT_PROBE_DEFINE(proc, , , lwp__exit);
125 
126 /*
127  * thread related storage.
128  */
129 static uma_zone_t thread_zone;
130 
131 TAILQ_HEAD(, thread) zombie_threads = TAILQ_HEAD_INITIALIZER(zombie_threads);
132 static struct mtx zombie_lock;
133 MTX_SYSINIT(zombie_lock, &zombie_lock, "zombie lock", MTX_SPIN);
134 
135 static void thread_zombie(struct thread *);
136 static int thread_unsuspend_one(struct thread *td, struct proc *p,
137     bool boundary);
138 
139 static struct mtx tid_lock;
140 static bitstr_t *tid_bitmap;
141 
142 static MALLOC_DEFINE(M_TIDHASH, "tidhash", "thread hash");
143 
144 static int maxthread;
145 SYSCTL_INT(_kern, OID_AUTO, maxthread, CTLFLAG_RDTUN,
146     &maxthread, 0, "Maximum number of threads");
147 
148 static int nthreads;
149 
150 struct	tidhashhead *tidhashtbl;
151 u_long	tidhash;
152 struct	rwlock tidhash_lock;
153 
154 EVENTHANDLER_LIST_DEFINE(thread_ctor);
155 EVENTHANDLER_LIST_DEFINE(thread_dtor);
156 EVENTHANDLER_LIST_DEFINE(thread_init);
157 EVENTHANDLER_LIST_DEFINE(thread_fini);
158 
159 static lwpid_t
160 tid_alloc(void)
161 {
162 	static struct timeval lastfail;
163 	static int curfail;
164 	static lwpid_t trytid;
165 	lwpid_t tid;
166 
167 	mtx_lock(&tid_lock);
168 	if (nthreads + 1 >= maxthread - 100) {
169 		if (priv_check_cred(curthread->td_ucred, PRIV_MAXPROC) != 0 ||
170 		    nthreads + 1 >= maxthread) {
171 			mtx_unlock(&tid_lock);
172 			if (ppsratecheck(&lastfail, &curfail, 1)) {
173 				printf("maxthread limit exceeded by uid %u "
174 				"(pid %d); consider increasing kern.maxthread\n",
175 				curthread->td_ucred->cr_ruid, curproc->p_pid);
176 			}
177 			return (-1);
178 		}
179 	}
180 
181 	nthreads++;
182 	/*
183 	 * It is an invariant that the bitmap is big enough to hold maxthread
184 	 * IDs. If we got to this point there has to be at least one free.
185 	 */
186 	if (trytid >= maxthread)
187 		trytid = 0;
188 	bit_ffc_at(tid_bitmap, trytid, maxthread, &tid);
189 	if (tid == -1) {
190 		KASSERT(trytid != 0, ("unexpectedly ran out of IDs"));
191 		trytid = 0;
192 		bit_ffc_at(tid_bitmap, trytid, maxthread, &tid);
193 		KASSERT(tid != -1, ("unexpectedly ran out of IDs"));
194 	}
195 	bit_set(tid_bitmap, tid);
196 	trytid = tid + 1;
197 	mtx_unlock(&tid_lock);
198 	return (tid + NO_PID);
199 }
200 
201 static void
202 tid_free(lwpid_t rtid)
203 {
204 	lwpid_t tid;
205 
206 	KASSERT(rtid >= NO_PID,
207 	    ("%s: invalid tid %d\n", __func__, rtid));
208 	tid = rtid - NO_PID;
209 	mtx_lock(&tid_lock);
210 	KASSERT(bit_test(tid_bitmap, tid) != 0,
211 	    ("thread ID %d not allocated\n", rtid));
212 	bit_clear(tid_bitmap, tid);
213 	nthreads--;
214 	mtx_unlock(&tid_lock);
215 }
216 
217 /*
218  * Prepare a thread for use.
219  */
220 static int
221 thread_ctor(void *mem, int size, void *arg, int flags)
222 {
223 	struct thread	*td;
224 
225 	td = (struct thread *)mem;
226 	td->td_state = TDS_INACTIVE;
227 	td->td_lastcpu = td->td_oncpu = NOCPU;
228 
229 	/*
230 	 * Note that td_critnest begins life as 1 because the thread is not
231 	 * running and is thereby implicitly waiting to be on the receiving
232 	 * end of a context switch.
233 	 */
234 	td->td_critnest = 1;
235 	td->td_lend_user_pri = PRI_MAX;
236 #ifdef AUDIT
237 	audit_thread_alloc(td);
238 #endif
239 	umtx_thread_alloc(td);
240 	return (0);
241 }
242 
243 /*
244  * Reclaim a thread after use.
245  */
246 static void
247 thread_dtor(void *mem, int size, void *arg)
248 {
249 	struct thread *td;
250 
251 	td = (struct thread *)mem;
252 
253 #ifdef INVARIANTS
254 	/* Verify that this thread is in a safe state to free. */
255 	switch (td->td_state) {
256 	case TDS_INHIBITED:
257 	case TDS_RUNNING:
258 	case TDS_CAN_RUN:
259 	case TDS_RUNQ:
260 		/*
261 		 * We must never unlink a thread that is in one of
262 		 * these states, because it is currently active.
263 		 */
264 		panic("bad state for thread unlinking");
265 		/* NOTREACHED */
266 	case TDS_INACTIVE:
267 		break;
268 	default:
269 		panic("bad thread state");
270 		/* NOTREACHED */
271 	}
272 #endif
273 #ifdef AUDIT
274 	audit_thread_free(td);
275 #endif
276 	/* Free all OSD associated to this thread. */
277 	osd_thread_exit(td);
278 	td_softdep_cleanup(td);
279 	MPASS(td->td_su == NULL);
280 }
281 
282 /*
283  * Initialize type-stable parts of a thread (when newly created).
284  */
285 static int
286 thread_init(void *mem, int size, int flags)
287 {
288 	struct thread *td;
289 
290 	td = (struct thread *)mem;
291 
292 	td->td_sleepqueue = sleepq_alloc();
293 	td->td_turnstile = turnstile_alloc();
294 	td->td_rlqe = NULL;
295 	EVENTHANDLER_DIRECT_INVOKE(thread_init, td);
296 	umtx_thread_init(td);
297 	td->td_kstack = 0;
298 	td->td_sel = NULL;
299 	return (0);
300 }
301 
302 /*
303  * Tear down type-stable parts of a thread (just before being discarded).
304  */
305 static void
306 thread_fini(void *mem, int size)
307 {
308 	struct thread *td;
309 
310 	td = (struct thread *)mem;
311 	EVENTHANDLER_DIRECT_INVOKE(thread_fini, td);
312 	rlqentry_free(td->td_rlqe);
313 	turnstile_free(td->td_turnstile);
314 	sleepq_free(td->td_sleepqueue);
315 	umtx_thread_fini(td);
316 	seltdfini(td);
317 }
318 
319 /*
320  * For a newly created process,
321  * link up all the structures and its initial threads etc.
322  * called from:
323  * {arch}/{arch}/machdep.c   {arch}_init(), init386() etc.
324  * proc_dtor() (should go away)
325  * proc_init()
326  */
327 void
328 proc_linkup0(struct proc *p, struct thread *td)
329 {
330 	TAILQ_INIT(&p->p_threads);	     /* all threads in proc */
331 	proc_linkup(p, td);
332 }
333 
334 void
335 proc_linkup(struct proc *p, struct thread *td)
336 {
337 
338 	sigqueue_init(&p->p_sigqueue, p);
339 	p->p_ksi = ksiginfo_alloc(1);
340 	if (p->p_ksi != NULL) {
341 		/* XXX p_ksi may be null if ksiginfo zone is not ready */
342 		p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
343 	}
344 	LIST_INIT(&p->p_mqnotifier);
345 	p->p_numthreads = 0;
346 	thread_link(td, p);
347 }
348 
349 extern int max_threads_per_proc;
350 
351 /*
352  * Initialize global thread allocation resources.
353  */
354 void
355 threadinit(void)
356 {
357 	uint32_t flags;
358 
359 	/*
360 	 * Place an upper limit on threads which can be allocated.
361 	 *
362 	 * Note that other factors may make the de facto limit much lower.
363 	 *
364 	 * Platform limits are somewhat arbitrary but deemed "more than good
365 	 * enough" for the foreseable future.
366 	 */
367 	if (maxthread == 0) {
368 #ifdef _LP64
369 		maxthread = MIN(maxproc * max_threads_per_proc, 1000000);
370 #else
371 		maxthread = MIN(maxproc * max_threads_per_proc, 100000);
372 #endif
373 	}
374 
375 	mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
376 	tid_bitmap = bit_alloc(maxthread, M_TIDHASH, M_WAITOK);
377 
378 	flags = UMA_ZONE_NOFREE;
379 #ifdef __aarch64__
380 	/*
381 	 * Force thread structures to be allocated from the direct map.
382 	 * Otherwise, superpage promotions and demotions may temporarily
383 	 * invalidate thread structure mappings.  For most dynamically allocated
384 	 * structures this is not a problem, but translation faults cannot be
385 	 * handled without accessing curthread.
386 	 */
387 	flags |= UMA_ZONE_CONTIG;
388 #endif
389 	thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
390 	    thread_ctor, thread_dtor, thread_init, thread_fini,
391 	    32 - 1, flags);
392 	tidhashtbl = hashinit(maxproc / 2, M_TIDHASH, &tidhash);
393 	rw_init(&tidhash_lock, "tidhash");
394 }
395 
396 /*
397  * Place an unused thread on the zombie list.
398  * Use the slpq as that must be unused by now.
399  */
400 void
401 thread_zombie(struct thread *td)
402 {
403 	mtx_lock_spin(&zombie_lock);
404 	TAILQ_INSERT_HEAD(&zombie_threads, td, td_slpq);
405 	mtx_unlock_spin(&zombie_lock);
406 }
407 
408 /*
409  * Release a thread that has exited after cpu_throw().
410  */
411 void
412 thread_stash(struct thread *td)
413 {
414 	atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
415 	thread_zombie(td);
416 }
417 
418 /*
419  * Reap zombie resources.
420  */
421 void
422 thread_reap(void)
423 {
424 	struct thread *td_first, *td_next;
425 
426 	/*
427 	 * Don't even bother to lock if none at this instant,
428 	 * we really don't care about the next instant.
429 	 */
430 	if (!TAILQ_EMPTY(&zombie_threads)) {
431 		mtx_lock_spin(&zombie_lock);
432 		td_first = TAILQ_FIRST(&zombie_threads);
433 		if (td_first)
434 			TAILQ_INIT(&zombie_threads);
435 		mtx_unlock_spin(&zombie_lock);
436 		while (td_first) {
437 			td_next = TAILQ_NEXT(td_first, td_slpq);
438 			thread_cow_free(td_first);
439 			thread_free(td_first);
440 			td_first = td_next;
441 		}
442 	}
443 }
444 
445 /*
446  * Allocate a thread.
447  */
448 struct thread *
449 thread_alloc(int pages)
450 {
451 	struct thread *td;
452 	lwpid_t tid;
453 
454 	thread_reap(); /* check if any zombies to get */
455 
456 	tid = tid_alloc();
457 	if (tid == -1) {
458 		return (NULL);
459 	}
460 
461 	td = uma_zalloc(thread_zone, M_WAITOK);
462 	KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
463 	if (!vm_thread_new(td, pages)) {
464 		uma_zfree(thread_zone, td);
465 		tid_free(tid);
466 		return (NULL);
467 	}
468 	td->td_tid = tid;
469 	cpu_thread_alloc(td);
470 	EVENTHANDLER_DIRECT_INVOKE(thread_ctor, td);
471 	return (td);
472 }
473 
474 int
475 thread_alloc_stack(struct thread *td, int pages)
476 {
477 
478 	KASSERT(td->td_kstack == 0,
479 	    ("thread_alloc_stack called on a thread with kstack"));
480 	if (!vm_thread_new(td, pages))
481 		return (0);
482 	cpu_thread_alloc(td);
483 	return (1);
484 }
485 
486 /*
487  * Deallocate a thread.
488  */
489 void
490 thread_free(struct thread *td)
491 {
492 
493 	EVENTHANDLER_DIRECT_INVOKE(thread_dtor, td);
494 	lock_profile_thread_exit(td);
495 	if (td->td_cpuset)
496 		cpuset_rel(td->td_cpuset);
497 	td->td_cpuset = NULL;
498 	cpu_thread_free(td);
499 	if (td->td_kstack != 0)
500 		vm_thread_dispose(td);
501 	callout_drain(&td->td_slpcallout);
502 	tid_free(td->td_tid);
503 	td->td_tid = -1;
504 	uma_zfree(thread_zone, td);
505 }
506 
507 void
508 thread_cow_get_proc(struct thread *newtd, struct proc *p)
509 {
510 
511 	PROC_LOCK_ASSERT(p, MA_OWNED);
512 	newtd->td_realucred = crcowget(p->p_ucred);
513 	newtd->td_ucred = newtd->td_realucred;
514 	newtd->td_limit = lim_hold(p->p_limit);
515 	newtd->td_cowgen = p->p_cowgen;
516 }
517 
518 void
519 thread_cow_get(struct thread *newtd, struct thread *td)
520 {
521 
522 	MPASS(td->td_realucred == td->td_ucred);
523 	newtd->td_realucred = crcowget(td->td_realucred);
524 	newtd->td_ucred = newtd->td_realucred;
525 	newtd->td_limit = lim_hold(td->td_limit);
526 	newtd->td_cowgen = td->td_cowgen;
527 }
528 
529 void
530 thread_cow_free(struct thread *td)
531 {
532 
533 	if (td->td_realucred != NULL)
534 		crcowfree(td);
535 	if (td->td_limit != NULL)
536 		lim_free(td->td_limit);
537 }
538 
539 void
540 thread_cow_update(struct thread *td)
541 {
542 	struct proc *p;
543 	struct ucred *oldcred;
544 	struct plimit *oldlimit;
545 
546 	p = td->td_proc;
547 	oldlimit = NULL;
548 	PROC_LOCK(p);
549 	oldcred = crcowsync();
550 	if (td->td_limit != p->p_limit) {
551 		oldlimit = td->td_limit;
552 		td->td_limit = lim_hold(p->p_limit);
553 	}
554 	td->td_cowgen = p->p_cowgen;
555 	PROC_UNLOCK(p);
556 	if (oldcred != NULL)
557 		crfree(oldcred);
558 	if (oldlimit != NULL)
559 		lim_free(oldlimit);
560 }
561 
562 /*
563  * Discard the current thread and exit from its context.
564  * Always called with scheduler locked.
565  *
566  * Because we can't free a thread while we're operating under its context,
567  * push the current thread into our CPU's deadthread holder. This means
568  * we needn't worry about someone else grabbing our context before we
569  * do a cpu_throw().
570  */
571 void
572 thread_exit(void)
573 {
574 	uint64_t runtime, new_switchtime;
575 	struct thread *td;
576 	struct thread *td2;
577 	struct proc *p;
578 	int wakeup_swapper;
579 
580 	td = curthread;
581 	p = td->td_proc;
582 
583 	PROC_SLOCK_ASSERT(p, MA_OWNED);
584 	mtx_assert(&Giant, MA_NOTOWNED);
585 
586 	PROC_LOCK_ASSERT(p, MA_OWNED);
587 	KASSERT(p != NULL, ("thread exiting without a process"));
588 	CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
589 	    (long)p->p_pid, td->td_name);
590 	SDT_PROBE0(proc, , , lwp__exit);
591 	KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
592 	MPASS(td->td_realucred == td->td_ucred);
593 
594 	/*
595 	 * drop FPU & debug register state storage, or any other
596 	 * architecture specific resources that
597 	 * would not be on a new untouched process.
598 	 */
599 	cpu_thread_exit(td);
600 
601 	/*
602 	 * The last thread is left attached to the process
603 	 * So that the whole bundle gets recycled. Skip
604 	 * all this stuff if we never had threads.
605 	 * EXIT clears all sign of other threads when
606 	 * it goes to single threading, so the last thread always
607 	 * takes the short path.
608 	 */
609 	if (p->p_flag & P_HADTHREADS) {
610 		if (p->p_numthreads > 1) {
611 			atomic_add_int(&td->td_proc->p_exitthreads, 1);
612 			thread_unlink(td);
613 			td2 = FIRST_THREAD_IN_PROC(p);
614 			sched_exit_thread(td2, td);
615 
616 			/*
617 			 * The test below is NOT true if we are the
618 			 * sole exiting thread. P_STOPPED_SINGLE is unset
619 			 * in exit1() after it is the only survivor.
620 			 */
621 			if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
622 				if (p->p_numthreads == p->p_suspcount) {
623 					thread_lock(p->p_singlethread);
624 					wakeup_swapper = thread_unsuspend_one(
625 						p->p_singlethread, p, false);
626 					if (wakeup_swapper)
627 						kick_proc0();
628 				}
629 			}
630 
631 			PCPU_SET(deadthread, td);
632 		} else {
633 			/*
634 			 * The last thread is exiting.. but not through exit()
635 			 */
636 			panic ("thread_exit: Last thread exiting on its own");
637 		}
638 	}
639 #ifdef	HWPMC_HOOKS
640 	/*
641 	 * If this thread is part of a process that is being tracked by hwpmc(4),
642 	 * inform the module of the thread's impending exit.
643 	 */
644 	if (PMC_PROC_IS_USING_PMCS(td->td_proc)) {
645 		PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
646 		PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT, NULL);
647 	} else if (PMC_SYSTEM_SAMPLING_ACTIVE())
648 		PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT_LOG, NULL);
649 #endif
650 	PROC_UNLOCK(p);
651 	PROC_STATLOCK(p);
652 	thread_lock(td);
653 	PROC_SUNLOCK(p);
654 
655 	/* Do the same timestamp bookkeeping that mi_switch() would do. */
656 	new_switchtime = cpu_ticks();
657 	runtime = new_switchtime - PCPU_GET(switchtime);
658 	td->td_runtime += runtime;
659 	td->td_incruntime += runtime;
660 	PCPU_SET(switchtime, new_switchtime);
661 	PCPU_SET(switchticks, ticks);
662 	VM_CNT_INC(v_swtch);
663 
664 	/* Save our resource usage in our process. */
665 	td->td_ru.ru_nvcsw++;
666 	ruxagg_locked(p, td);
667 	rucollect(&p->p_ru, &td->td_ru);
668 	PROC_STATUNLOCK(p);
669 
670 	td->td_state = TDS_INACTIVE;
671 #ifdef WITNESS
672 	witness_thread_exit(td);
673 #endif
674 	CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
675 	sched_throw(td);
676 	panic("I'm a teapot!");
677 	/* NOTREACHED */
678 }
679 
680 /*
681  * Do any thread specific cleanups that may be needed in wait()
682  * called with Giant, proc and schedlock not held.
683  */
684 void
685 thread_wait(struct proc *p)
686 {
687 	struct thread *td;
688 
689 	mtx_assert(&Giant, MA_NOTOWNED);
690 	KASSERT(p->p_numthreads == 1, ("multiple threads in thread_wait()"));
691 	KASSERT(p->p_exitthreads == 0, ("p_exitthreads leaking"));
692 	td = FIRST_THREAD_IN_PROC(p);
693 	/* Lock the last thread so we spin until it exits cpu_throw(). */
694 	thread_lock(td);
695 	thread_unlock(td);
696 	lock_profile_thread_exit(td);
697 	cpuset_rel(td->td_cpuset);
698 	td->td_cpuset = NULL;
699 	cpu_thread_clean(td);
700 	thread_cow_free(td);
701 	callout_drain(&td->td_slpcallout);
702 	thread_reap();	/* check for zombie threads etc. */
703 }
704 
705 /*
706  * Link a thread to a process.
707  * set up anything that needs to be initialized for it to
708  * be used by the process.
709  */
710 void
711 thread_link(struct thread *td, struct proc *p)
712 {
713 
714 	/*
715 	 * XXX This can't be enabled because it's called for proc0 before
716 	 * its lock has been created.
717 	 * PROC_LOCK_ASSERT(p, MA_OWNED);
718 	 */
719 	td->td_state    = TDS_INACTIVE;
720 	td->td_proc     = p;
721 	td->td_flags    = TDF_INMEM;
722 
723 	LIST_INIT(&td->td_contested);
724 	LIST_INIT(&td->td_lprof[0]);
725 	LIST_INIT(&td->td_lprof[1]);
726 #ifdef EPOCH_TRACE
727 	SLIST_INIT(&td->td_epochs);
728 #endif
729 	sigqueue_init(&td->td_sigqueue, p);
730 	callout_init(&td->td_slpcallout, 1);
731 	TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
732 	p->p_numthreads++;
733 }
734 
735 /*
736  * Called from:
737  *  thread_exit()
738  */
739 void
740 thread_unlink(struct thread *td)
741 {
742 	struct proc *p = td->td_proc;
743 
744 	PROC_LOCK_ASSERT(p, MA_OWNED);
745 #ifdef EPOCH_TRACE
746 	MPASS(SLIST_EMPTY(&td->td_epochs));
747 #endif
748 
749 	TAILQ_REMOVE(&p->p_threads, td, td_plist);
750 	p->p_numthreads--;
751 	/* could clear a few other things here */
752 	/* Must  NOT clear links to proc! */
753 }
754 
755 static int
756 calc_remaining(struct proc *p, int mode)
757 {
758 	int remaining;
759 
760 	PROC_LOCK_ASSERT(p, MA_OWNED);
761 	PROC_SLOCK_ASSERT(p, MA_OWNED);
762 	if (mode == SINGLE_EXIT)
763 		remaining = p->p_numthreads;
764 	else if (mode == SINGLE_BOUNDARY)
765 		remaining = p->p_numthreads - p->p_boundary_count;
766 	else if (mode == SINGLE_NO_EXIT || mode == SINGLE_ALLPROC)
767 		remaining = p->p_numthreads - p->p_suspcount;
768 	else
769 		panic("calc_remaining: wrong mode %d", mode);
770 	return (remaining);
771 }
772 
773 static int
774 remain_for_mode(int mode)
775 {
776 
777 	return (mode == SINGLE_ALLPROC ? 0 : 1);
778 }
779 
780 static int
781 weed_inhib(int mode, struct thread *td2, struct proc *p)
782 {
783 	int wakeup_swapper;
784 
785 	PROC_LOCK_ASSERT(p, MA_OWNED);
786 	PROC_SLOCK_ASSERT(p, MA_OWNED);
787 	THREAD_LOCK_ASSERT(td2, MA_OWNED);
788 
789 	wakeup_swapper = 0;
790 
791 	/*
792 	 * Since the thread lock is dropped by the scheduler we have
793 	 * to retry to check for races.
794 	 */
795 restart:
796 	switch (mode) {
797 	case SINGLE_EXIT:
798 		if (TD_IS_SUSPENDED(td2)) {
799 			wakeup_swapper |= thread_unsuspend_one(td2, p, true);
800 			thread_lock(td2);
801 			goto restart;
802 		}
803 		if (TD_CAN_ABORT(td2)) {
804 			wakeup_swapper |= sleepq_abort(td2, EINTR);
805 			return (wakeup_swapper);
806 		}
807 		break;
808 	case SINGLE_BOUNDARY:
809 	case SINGLE_NO_EXIT:
810 		if (TD_IS_SUSPENDED(td2) &&
811 		    (td2->td_flags & TDF_BOUNDARY) == 0) {
812 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
813 			thread_lock(td2);
814 			goto restart;
815 		}
816 		if (TD_CAN_ABORT(td2)) {
817 			wakeup_swapper |= sleepq_abort(td2, ERESTART);
818 			return (wakeup_swapper);
819 		}
820 		break;
821 	case SINGLE_ALLPROC:
822 		/*
823 		 * ALLPROC suspend tries to avoid spurious EINTR for
824 		 * threads sleeping interruptable, by suspending the
825 		 * thread directly, similarly to sig_suspend_threads().
826 		 * Since such sleep is not performed at the user
827 		 * boundary, TDF_BOUNDARY flag is not set, and TDF_ALLPROCSUSP
828 		 * is used to avoid immediate un-suspend.
829 		 */
830 		if (TD_IS_SUSPENDED(td2) && (td2->td_flags & (TDF_BOUNDARY |
831 		    TDF_ALLPROCSUSP)) == 0) {
832 			wakeup_swapper |= thread_unsuspend_one(td2, p, false);
833 			thread_lock(td2);
834 			goto restart;
835 		}
836 		if (TD_CAN_ABORT(td2)) {
837 			if ((td2->td_flags & TDF_SBDRY) == 0) {
838 				thread_suspend_one(td2);
839 				td2->td_flags |= TDF_ALLPROCSUSP;
840 			} else {
841 				wakeup_swapper |= sleepq_abort(td2, ERESTART);
842 				return (wakeup_swapper);
843 			}
844 		}
845 		break;
846 	default:
847 		break;
848 	}
849 	thread_unlock(td2);
850 	return (wakeup_swapper);
851 }
852 
853 /*
854  * Enforce single-threading.
855  *
856  * Returns 1 if the caller must abort (another thread is waiting to
857  * exit the process or similar). Process is locked!
858  * Returns 0 when you are successfully the only thread running.
859  * A process has successfully single threaded in the suspend mode when
860  * There are no threads in user mode. Threads in the kernel must be
861  * allowed to continue until they get to the user boundary. They may even
862  * copy out their return values and data before suspending. They may however be
863  * accelerated in reaching the user boundary as we will wake up
864  * any sleeping threads that are interruptable. (PCATCH).
865  */
866 int
867 thread_single(struct proc *p, int mode)
868 {
869 	struct thread *td;
870 	struct thread *td2;
871 	int remaining, wakeup_swapper;
872 
873 	td = curthread;
874 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
875 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
876 	    ("invalid mode %d", mode));
877 	/*
878 	 * If allowing non-ALLPROC singlethreading for non-curproc
879 	 * callers, calc_remaining() and remain_for_mode() should be
880 	 * adjusted to also account for td->td_proc != p.  For now
881 	 * this is not implemented because it is not used.
882 	 */
883 	KASSERT((mode == SINGLE_ALLPROC && td->td_proc != p) ||
884 	    (mode != SINGLE_ALLPROC && td->td_proc == p),
885 	    ("mode %d proc %p curproc %p", mode, p, td->td_proc));
886 	mtx_assert(&Giant, MA_NOTOWNED);
887 	PROC_LOCK_ASSERT(p, MA_OWNED);
888 
889 	if ((p->p_flag & P_HADTHREADS) == 0 && mode != SINGLE_ALLPROC)
890 		return (0);
891 
892 	/* Is someone already single threading? */
893 	if (p->p_singlethread != NULL && p->p_singlethread != td)
894 		return (1);
895 
896 	if (mode == SINGLE_EXIT) {
897 		p->p_flag |= P_SINGLE_EXIT;
898 		p->p_flag &= ~P_SINGLE_BOUNDARY;
899 	} else {
900 		p->p_flag &= ~P_SINGLE_EXIT;
901 		if (mode == SINGLE_BOUNDARY)
902 			p->p_flag |= P_SINGLE_BOUNDARY;
903 		else
904 			p->p_flag &= ~P_SINGLE_BOUNDARY;
905 	}
906 	if (mode == SINGLE_ALLPROC)
907 		p->p_flag |= P_TOTAL_STOP;
908 	p->p_flag |= P_STOPPED_SINGLE;
909 	PROC_SLOCK(p);
910 	p->p_singlethread = td;
911 	remaining = calc_remaining(p, mode);
912 	while (remaining != remain_for_mode(mode)) {
913 		if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
914 			goto stopme;
915 		wakeup_swapper = 0;
916 		FOREACH_THREAD_IN_PROC(p, td2) {
917 			if (td2 == td)
918 				continue;
919 			thread_lock(td2);
920 			td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
921 			if (TD_IS_INHIBITED(td2)) {
922 				wakeup_swapper |= weed_inhib(mode, td2, p);
923 #ifdef SMP
924 			} else if (TD_IS_RUNNING(td2) && td != td2) {
925 				forward_signal(td2);
926 				thread_unlock(td2);
927 #endif
928 			} else
929 				thread_unlock(td2);
930 		}
931 		if (wakeup_swapper)
932 			kick_proc0();
933 		remaining = calc_remaining(p, mode);
934 
935 		/*
936 		 * Maybe we suspended some threads.. was it enough?
937 		 */
938 		if (remaining == remain_for_mode(mode))
939 			break;
940 
941 stopme:
942 		/*
943 		 * Wake us up when everyone else has suspended.
944 		 * In the mean time we suspend as well.
945 		 */
946 		thread_suspend_switch(td, p);
947 		remaining = calc_remaining(p, mode);
948 	}
949 	if (mode == SINGLE_EXIT) {
950 		/*
951 		 * Convert the process to an unthreaded process.  The
952 		 * SINGLE_EXIT is called by exit1() or execve(), in
953 		 * both cases other threads must be retired.
954 		 */
955 		KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
956 		p->p_singlethread = NULL;
957 		p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
958 
959 		/*
960 		 * Wait for any remaining threads to exit cpu_throw().
961 		 */
962 		while (p->p_exitthreads != 0) {
963 			PROC_SUNLOCK(p);
964 			PROC_UNLOCK(p);
965 			sched_relinquish(td);
966 			PROC_LOCK(p);
967 			PROC_SLOCK(p);
968 		}
969 	} else if (mode == SINGLE_BOUNDARY) {
970 		/*
971 		 * Wait until all suspended threads are removed from
972 		 * the processors.  The thread_suspend_check()
973 		 * increments p_boundary_count while it is still
974 		 * running, which makes it possible for the execve()
975 		 * to destroy vmspace while our other threads are
976 		 * still using the address space.
977 		 *
978 		 * We lock the thread, which is only allowed to
979 		 * succeed after context switch code finished using
980 		 * the address space.
981 		 */
982 		FOREACH_THREAD_IN_PROC(p, td2) {
983 			if (td2 == td)
984 				continue;
985 			thread_lock(td2);
986 			KASSERT((td2->td_flags & TDF_BOUNDARY) != 0,
987 			    ("td %p not on boundary", td2));
988 			KASSERT(TD_IS_SUSPENDED(td2),
989 			    ("td %p is not suspended", td2));
990 			thread_unlock(td2);
991 		}
992 	}
993 	PROC_SUNLOCK(p);
994 	return (0);
995 }
996 
997 bool
998 thread_suspend_check_needed(void)
999 {
1000 	struct proc *p;
1001 	struct thread *td;
1002 
1003 	td = curthread;
1004 	p = td->td_proc;
1005 	PROC_LOCK_ASSERT(p, MA_OWNED);
1006 	return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
1007 	    (td->td_dbgflags & TDB_SUSPEND) != 0));
1008 }
1009 
1010 /*
1011  * Called in from locations that can safely check to see
1012  * whether we have to suspend or at least throttle for a
1013  * single-thread event (e.g. fork).
1014  *
1015  * Such locations include userret().
1016  * If the "return_instead" argument is non zero, the thread must be able to
1017  * accept 0 (caller may continue), or 1 (caller must abort) as a result.
1018  *
1019  * The 'return_instead' argument tells the function if it may do a
1020  * thread_exit() or suspend, or whether the caller must abort and back
1021  * out instead.
1022  *
1023  * If the thread that set the single_threading request has set the
1024  * P_SINGLE_EXIT bit in the process flags then this call will never return
1025  * if 'return_instead' is false, but will exit.
1026  *
1027  * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
1028  *---------------+--------------------+---------------------
1029  *       0       | returns 0          |   returns 0 or 1
1030  *               | when ST ends       |   immediately
1031  *---------------+--------------------+---------------------
1032  *       1       | thread exits       |   returns 1
1033  *               |                    |  immediately
1034  * 0 = thread_exit() or suspension ok,
1035  * other = return error instead of stopping the thread.
1036  *
1037  * While a full suspension is under effect, even a single threading
1038  * thread would be suspended if it made this call (but it shouldn't).
1039  * This call should only be made from places where
1040  * thread_exit() would be safe as that may be the outcome unless
1041  * return_instead is set.
1042  */
1043 int
1044 thread_suspend_check(int return_instead)
1045 {
1046 	struct thread *td;
1047 	struct proc *p;
1048 	int wakeup_swapper;
1049 
1050 	td = curthread;
1051 	p = td->td_proc;
1052 	mtx_assert(&Giant, MA_NOTOWNED);
1053 	PROC_LOCK_ASSERT(p, MA_OWNED);
1054 	while (thread_suspend_check_needed()) {
1055 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1056 			KASSERT(p->p_singlethread != NULL,
1057 			    ("singlethread not set"));
1058 			/*
1059 			 * The only suspension in action is a
1060 			 * single-threading. Single threader need not stop.
1061 			 * It is safe to access p->p_singlethread unlocked
1062 			 * because it can only be set to our address by us.
1063 			 */
1064 			if (p->p_singlethread == td)
1065 				return (0);	/* Exempt from stopping. */
1066 		}
1067 		if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
1068 			return (EINTR);
1069 
1070 		/* Should we goto user boundary if we didn't come from there? */
1071 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1072 		    (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
1073 			return (ERESTART);
1074 
1075 		/*
1076 		 * Ignore suspend requests if they are deferred.
1077 		 */
1078 		if ((td->td_flags & TDF_SBDRY) != 0) {
1079 			KASSERT(return_instead,
1080 			    ("TDF_SBDRY set for unsafe thread_suspend_check"));
1081 			KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
1082 			    (TDF_SEINTR | TDF_SERESTART),
1083 			    ("both TDF_SEINTR and TDF_SERESTART"));
1084 			return (TD_SBDRY_INTR(td) ? TD_SBDRY_ERRNO(td) : 0);
1085 		}
1086 
1087 		/*
1088 		 * If the process is waiting for us to exit,
1089 		 * this thread should just suicide.
1090 		 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
1091 		 */
1092 		if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
1093 			PROC_UNLOCK(p);
1094 
1095 			/*
1096 			 * Allow Linux emulation layer to do some work
1097 			 * before thread suicide.
1098 			 */
1099 			if (__predict_false(p->p_sysent->sv_thread_detach != NULL))
1100 				(p->p_sysent->sv_thread_detach)(td);
1101 			umtx_thread_exit(td);
1102 			kern_thr_exit(td);
1103 			panic("stopped thread did not exit");
1104 		}
1105 
1106 		PROC_SLOCK(p);
1107 		thread_stopped(p);
1108 		if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1109 			if (p->p_numthreads == p->p_suspcount + 1) {
1110 				thread_lock(p->p_singlethread);
1111 				wakeup_swapper = thread_unsuspend_one(
1112 				    p->p_singlethread, p, false);
1113 				if (wakeup_swapper)
1114 					kick_proc0();
1115 			}
1116 		}
1117 		PROC_UNLOCK(p);
1118 		thread_lock(td);
1119 		/*
1120 		 * When a thread suspends, it just
1121 		 * gets taken off all queues.
1122 		 */
1123 		thread_suspend_one(td);
1124 		if (return_instead == 0) {
1125 			p->p_boundary_count++;
1126 			td->td_flags |= TDF_BOUNDARY;
1127 		}
1128 		PROC_SUNLOCK(p);
1129 		mi_switch(SW_INVOL | SWT_SUSPEND);
1130 		PROC_LOCK(p);
1131 	}
1132 	return (0);
1133 }
1134 
1135 /*
1136  * Check for possible stops and suspensions while executing a
1137  * casueword or similar transiently failing operation.
1138  *
1139  * The sleep argument controls whether the function can handle a stop
1140  * request itself or it should return ERESTART and the request is
1141  * proceed at the kernel/user boundary in ast.
1142  *
1143  * Typically, when retrying due to casueword(9) failure (rv == 1), we
1144  * should handle the stop requests there, with exception of cases when
1145  * the thread owns a kernel resource, for instance busied the umtx
1146  * key, or when functions return immediately if thread_check_susp()
1147  * returned non-zero.  On the other hand, retrying the whole lock
1148  * operation, we better not stop there but delegate the handling to
1149  * ast.
1150  *
1151  * If the request is for thread termination P_SINGLE_EXIT, we cannot
1152  * handle it at all, and simply return EINTR.
1153  */
1154 int
1155 thread_check_susp(struct thread *td, bool sleep)
1156 {
1157 	struct proc *p;
1158 	int error;
1159 
1160 	/*
1161 	 * The check for TDF_NEEDSUSPCHK is racy, but it is enough to
1162 	 * eventually break the lockstep loop.
1163 	 */
1164 	if ((td->td_flags & TDF_NEEDSUSPCHK) == 0)
1165 		return (0);
1166 	error = 0;
1167 	p = td->td_proc;
1168 	PROC_LOCK(p);
1169 	if (p->p_flag & P_SINGLE_EXIT)
1170 		error = EINTR;
1171 	else if (P_SHOULDSTOP(p) ||
1172 	    ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_SUSPEND)))
1173 		error = sleep ? thread_suspend_check(0) : ERESTART;
1174 	PROC_UNLOCK(p);
1175 	return (error);
1176 }
1177 
1178 void
1179 thread_suspend_switch(struct thread *td, struct proc *p)
1180 {
1181 
1182 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1183 	PROC_LOCK_ASSERT(p, MA_OWNED);
1184 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1185 	/*
1186 	 * We implement thread_suspend_one in stages here to avoid
1187 	 * dropping the proc lock while the thread lock is owned.
1188 	 */
1189 	if (p == td->td_proc) {
1190 		thread_stopped(p);
1191 		p->p_suspcount++;
1192 	}
1193 	PROC_UNLOCK(p);
1194 	thread_lock(td);
1195 	td->td_flags &= ~TDF_NEEDSUSPCHK;
1196 	TD_SET_SUSPENDED(td);
1197 	sched_sleep(td, 0);
1198 	PROC_SUNLOCK(p);
1199 	DROP_GIANT();
1200 	mi_switch(SW_VOL | SWT_SUSPEND);
1201 	PICKUP_GIANT();
1202 	PROC_LOCK(p);
1203 	PROC_SLOCK(p);
1204 }
1205 
1206 void
1207 thread_suspend_one(struct thread *td)
1208 {
1209 	struct proc *p;
1210 
1211 	p = td->td_proc;
1212 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1213 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1214 	KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1215 	p->p_suspcount++;
1216 	td->td_flags &= ~TDF_NEEDSUSPCHK;
1217 	TD_SET_SUSPENDED(td);
1218 	sched_sleep(td, 0);
1219 }
1220 
1221 static int
1222 thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
1223 {
1224 
1225 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1226 	KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
1227 	TD_CLR_SUSPENDED(td);
1228 	td->td_flags &= ~TDF_ALLPROCSUSP;
1229 	if (td->td_proc == p) {
1230 		PROC_SLOCK_ASSERT(p, MA_OWNED);
1231 		p->p_suspcount--;
1232 		if (boundary && (td->td_flags & TDF_BOUNDARY) != 0) {
1233 			td->td_flags &= ~TDF_BOUNDARY;
1234 			p->p_boundary_count--;
1235 		}
1236 	}
1237 	return (setrunnable(td, 0));
1238 }
1239 
1240 /*
1241  * Allow all threads blocked by single threading to continue running.
1242  */
1243 void
1244 thread_unsuspend(struct proc *p)
1245 {
1246 	struct thread *td;
1247 	int wakeup_swapper;
1248 
1249 	PROC_LOCK_ASSERT(p, MA_OWNED);
1250 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1251 	wakeup_swapper = 0;
1252 	if (!P_SHOULDSTOP(p)) {
1253                 FOREACH_THREAD_IN_PROC(p, td) {
1254 			thread_lock(td);
1255 			if (TD_IS_SUSPENDED(td)) {
1256 				wakeup_swapper |= thread_unsuspend_one(td, p,
1257 				    true);
1258 			} else
1259 				thread_unlock(td);
1260 		}
1261 	} else if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1262 	    p->p_numthreads == p->p_suspcount) {
1263 		/*
1264 		 * Stopping everything also did the job for the single
1265 		 * threading request. Now we've downgraded to single-threaded,
1266 		 * let it continue.
1267 		 */
1268 		if (p->p_singlethread->td_proc == p) {
1269 			thread_lock(p->p_singlethread);
1270 			wakeup_swapper = thread_unsuspend_one(
1271 			    p->p_singlethread, p, false);
1272 		}
1273 	}
1274 	if (wakeup_swapper)
1275 		kick_proc0();
1276 }
1277 
1278 /*
1279  * End the single threading mode..
1280  */
1281 void
1282 thread_single_end(struct proc *p, int mode)
1283 {
1284 	struct thread *td;
1285 	int wakeup_swapper;
1286 
1287 	KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
1288 	    mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
1289 	    ("invalid mode %d", mode));
1290 	PROC_LOCK_ASSERT(p, MA_OWNED);
1291 	KASSERT((mode == SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) != 0) ||
1292 	    (mode != SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) == 0),
1293 	    ("mode %d does not match P_TOTAL_STOP", mode));
1294 	KASSERT(mode == SINGLE_ALLPROC || p->p_singlethread == curthread,
1295 	    ("thread_single_end from other thread %p %p",
1296 	    curthread, p->p_singlethread));
1297 	KASSERT(mode != SINGLE_BOUNDARY ||
1298 	    (p->p_flag & P_SINGLE_BOUNDARY) != 0,
1299 	    ("mis-matched SINGLE_BOUNDARY flags %x", p->p_flag));
1300 	p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY |
1301 	    P_TOTAL_STOP);
1302 	PROC_SLOCK(p);
1303 	p->p_singlethread = NULL;
1304 	wakeup_swapper = 0;
1305 	/*
1306 	 * If there are other threads they may now run,
1307 	 * unless of course there is a blanket 'stop order'
1308 	 * on the process. The single threader must be allowed
1309 	 * to continue however as this is a bad place to stop.
1310 	 */
1311 	if (p->p_numthreads != remain_for_mode(mode) && !P_SHOULDSTOP(p)) {
1312                 FOREACH_THREAD_IN_PROC(p, td) {
1313 			thread_lock(td);
1314 			if (TD_IS_SUSPENDED(td)) {
1315 				wakeup_swapper |= thread_unsuspend_one(td, p,
1316 				    mode == SINGLE_BOUNDARY);
1317 			} else
1318 				thread_unlock(td);
1319 		}
1320 	}
1321 	KASSERT(mode != SINGLE_BOUNDARY || p->p_boundary_count == 0,
1322 	    ("inconsistent boundary count %d", p->p_boundary_count));
1323 	PROC_SUNLOCK(p);
1324 	if (wakeup_swapper)
1325 		kick_proc0();
1326 }
1327 
1328 /* Locate a thread by number; return with proc lock held. */
1329 struct thread *
1330 tdfind(lwpid_t tid, pid_t pid)
1331 {
1332 #define RUN_THRESH	16
1333 	struct thread *td;
1334 	int run = 0;
1335 
1336 	td = curthread;
1337 	if (td->td_tid == tid) {
1338 		if (pid != -1 && td->td_proc->p_pid != pid)
1339 			return (NULL);
1340 		PROC_LOCK(td->td_proc);
1341 		return (td);
1342 	}
1343 
1344 	rw_rlock(&tidhash_lock);
1345 	LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1346 		if (td->td_tid == tid) {
1347 			if (pid != -1 && td->td_proc->p_pid != pid) {
1348 				td = NULL;
1349 				break;
1350 			}
1351 			PROC_LOCK(td->td_proc);
1352 			if (td->td_proc->p_state == PRS_NEW) {
1353 				PROC_UNLOCK(td->td_proc);
1354 				td = NULL;
1355 				break;
1356 			}
1357 			if (run > RUN_THRESH) {
1358 				if (rw_try_upgrade(&tidhash_lock)) {
1359 					LIST_REMOVE(td, td_hash);
1360 					LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1361 						td, td_hash);
1362 					rw_wunlock(&tidhash_lock);
1363 					return (td);
1364 				}
1365 			}
1366 			break;
1367 		}
1368 		run++;
1369 	}
1370 	rw_runlock(&tidhash_lock);
1371 	return (td);
1372 }
1373 
1374 void
1375 tidhash_add(struct thread *td)
1376 {
1377 	rw_wlock(&tidhash_lock);
1378 	LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1379 	rw_wunlock(&tidhash_lock);
1380 }
1381 
1382 void
1383 tidhash_remove(struct thread *td)
1384 {
1385 	rw_wlock(&tidhash_lock);
1386 	LIST_REMOVE(td, td_hash);
1387 	rw_wunlock(&tidhash_lock);
1388 }
1389