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