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