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