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