2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (C) 2001 Julian Elischer <julian@freebsd.org>.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
31 #include "opt_witness.h"
32 #include "opt_hwpmc_hooks.h"
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/kernel.h>
41 #include <sys/mutex.h>
43 #include <sys/bitstring.h>
44 #include <sys/epoch.h>
45 #include <sys/rangelock.h>
46 #include <sys/resourcevar.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>
56 #include <sys/rwlock.h>
58 #include <sys/vmmeter.h>
59 #include <sys/cpuset.h>
61 #include <sys/pmckern.h>
65 #include <security/audit/audit.h>
68 #include <vm/vm_extern.h>
70 #include <sys/eventhandler.h>
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
78 * On the stable branches after KBI freeze, conditions must not be
79 * violated. Typically new fields are moved to the end of the
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");
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");
123 SDT_PROVIDER_DECLARE(proc);
124 SDT_PROBE_DEFINE(proc, , , lwp__exit);
127 * thread related storage.
129 static uma_zone_t thread_zone;
131 TAILQ_HEAD(, thread) zombie_threads = TAILQ_HEAD_INITIALIZER(zombie_threads);
132 static struct mtx zombie_lock;
133 MTX_SYSINIT(zombie_lock, &zombie_lock, "zombie lock", MTX_SPIN);
135 static void thread_zombie(struct thread *);
136 static int thread_unsuspend_one(struct thread *td, struct proc *p,
139 static struct mtx tid_lock;
140 static bitstr_t *tid_bitmap;
142 static MALLOC_DEFINE(M_TIDHASH, "tidhash", "thread hash");
144 static int maxthread;
145 SYSCTL_INT(_kern, OID_AUTO, maxthread, CTLFLAG_RDTUN,
146 &maxthread, 0, "Maximum number of threads");
150 struct tidhashhead *tidhashtbl;
152 struct rwlock tidhash_lock;
154 EVENTHANDLER_LIST_DEFINE(thread_ctor);
155 EVENTHANDLER_LIST_DEFINE(thread_dtor);
156 EVENTHANDLER_LIST_DEFINE(thread_init);
157 EVENTHANDLER_LIST_DEFINE(thread_fini);
162 static struct timeval lastfail;
164 static lwpid_t trytid;
168 if (nthreads + 1 >= maxthread - 100) {
169 if (priv_check_cred(curthread->td_ucred, PRIV_MAXPROC) != 0 ||
170 nthreads + 1 >= maxthread) {
171 mtx_unlock(&tid_lock);
172 if (ppsratecheck(&lastfail, &curfail, 1)) {
173 printf("maxthread limit exceeded by uid %u "
174 "(pid %d); consider increasing kern.maxthread\n",
175 curthread->td_ucred->cr_ruid, curproc->p_pid);
183 * It is an invariant that the bitmap is big enough to hold maxthread
184 * IDs. If we got to this point there has to be at least one free.
186 if (trytid >= maxthread)
188 bit_ffc_at(tid_bitmap, trytid, maxthread, &tid);
190 KASSERT(trytid != 0, ("unexpectedly ran out of IDs"));
192 bit_ffc_at(tid_bitmap, trytid, maxthread, &tid);
193 KASSERT(tid != -1, ("unexpectedly ran out of IDs"));
195 bit_set(tid_bitmap, tid);
197 mtx_unlock(&tid_lock);
198 return (tid + NO_PID);
202 tid_free(lwpid_t rtid)
206 KASSERT(rtid >= NO_PID,
207 ("%s: invalid tid %d\n", __func__, rtid));
210 KASSERT(bit_test(tid_bitmap, tid) != 0,
211 ("thread ID %d not allocated\n", rtid));
212 bit_clear(tid_bitmap, tid);
214 mtx_unlock(&tid_lock);
218 * Prepare a thread for use.
221 thread_ctor(void *mem, int size, void *arg, int flags)
225 td = (struct thread *)mem;
226 td->td_state = TDS_INACTIVE;
227 td->td_lastcpu = td->td_oncpu = NOCPU;
230 * Note that td_critnest begins life as 1 because the thread is not
231 * running and is thereby implicitly waiting to be on the receiving
232 * end of a context switch.
235 td->td_lend_user_pri = PRI_MAX;
237 audit_thread_alloc(td);
239 umtx_thread_alloc(td);
244 * Reclaim a thread after use.
247 thread_dtor(void *mem, int size, void *arg)
251 td = (struct thread *)mem;
254 /* Verify that this thread is in a safe state to free. */
255 switch (td->td_state) {
261 * We must never unlink a thread that is in one of
262 * these states, because it is currently active.
264 panic("bad state for thread unlinking");
269 panic("bad thread state");
274 audit_thread_free(td);
276 /* Free all OSD associated to this thread. */
278 td_softdep_cleanup(td);
279 MPASS(td->td_su == NULL);
283 * Initialize type-stable parts of a thread (when newly created).
286 thread_init(void *mem, int size, int flags)
290 td = (struct thread *)mem;
292 td->td_sleepqueue = sleepq_alloc();
293 td->td_turnstile = turnstile_alloc();
295 EVENTHANDLER_DIRECT_INVOKE(thread_init, td);
296 umtx_thread_init(td);
303 * Tear down type-stable parts of a thread (just before being discarded).
306 thread_fini(void *mem, int size)
310 td = (struct thread *)mem;
311 EVENTHANDLER_DIRECT_INVOKE(thread_fini, td);
312 rlqentry_free(td->td_rlqe);
313 turnstile_free(td->td_turnstile);
314 sleepq_free(td->td_sleepqueue);
315 umtx_thread_fini(td);
320 * For a newly created process,
321 * link up all the structures and its initial threads etc.
323 * {arch}/{arch}/machdep.c {arch}_init(), init386() etc.
324 * proc_dtor() (should go away)
328 proc_linkup0(struct proc *p, struct thread *td)
330 TAILQ_INIT(&p->p_threads); /* all threads in proc */
335 proc_linkup(struct proc *p, struct thread *td)
338 sigqueue_init(&p->p_sigqueue, p);
339 p->p_ksi = ksiginfo_alloc(1);
340 if (p->p_ksi != NULL) {
341 /* XXX p_ksi may be null if ksiginfo zone is not ready */
342 p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
344 LIST_INIT(&p->p_mqnotifier);
349 extern int max_threads_per_proc;
352 * Initialize global thread allocation resources.
361 * Place an upper limit on threads which can be allocated.
363 * Note that other factors may make the de facto limit much lower.
365 * Platform limits are somewhat arbitrary but deemed "more than good
366 * enough" for the foreseable future.
368 if (maxthread == 0) {
370 maxthread = MIN(maxproc * max_threads_per_proc, 1000000);
372 maxthread = MIN(maxproc * max_threads_per_proc, 100000);
376 mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
377 tid_bitmap = bit_alloc(maxthread, M_TIDHASH, M_WAITOK);
379 if (tid0 != THREAD0_TID)
380 panic("tid0 %d != %d\n", tid0, THREAD0_TID);
382 flags = UMA_ZONE_NOFREE;
385 * Force thread structures to be allocated from the direct map.
386 * Otherwise, superpage promotions and demotions may temporarily
387 * invalidate thread structure mappings. For most dynamically allocated
388 * structures this is not a problem, but translation faults cannot be
389 * handled without accessing curthread.
391 flags |= UMA_ZONE_CONTIG;
393 thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
394 thread_ctor, thread_dtor, thread_init, thread_fini,
396 tidhashtbl = hashinit(maxproc / 2, M_TIDHASH, &tidhash);
397 rw_init(&tidhash_lock, "tidhash");
401 * Place an unused thread on the zombie list.
402 * Use the slpq as that must be unused by now.
405 thread_zombie(struct thread *td)
407 mtx_lock_spin(&zombie_lock);
408 TAILQ_INSERT_HEAD(&zombie_threads, td, td_slpq);
409 mtx_unlock_spin(&zombie_lock);
413 * Release a thread that has exited after cpu_throw().
416 thread_stash(struct thread *td)
418 atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
423 * Reap zombie resources.
428 struct thread *td_first, *td_next;
431 * Don't even bother to lock if none at this instant,
432 * we really don't care about the next instant.
434 if (!TAILQ_EMPTY(&zombie_threads)) {
435 mtx_lock_spin(&zombie_lock);
436 td_first = TAILQ_FIRST(&zombie_threads);
438 TAILQ_INIT(&zombie_threads);
439 mtx_unlock_spin(&zombie_lock);
441 td_next = TAILQ_NEXT(td_first, td_slpq);
442 thread_cow_free(td_first);
443 thread_free(td_first);
453 thread_alloc(int pages)
458 thread_reap(); /* check if any zombies to get */
465 td = uma_zalloc(thread_zone, M_WAITOK);
466 KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
467 if (!vm_thread_new(td, pages)) {
468 uma_zfree(thread_zone, td);
473 cpu_thread_alloc(td);
474 EVENTHANDLER_DIRECT_INVOKE(thread_ctor, td);
479 thread_alloc_stack(struct thread *td, int pages)
482 KASSERT(td->td_kstack == 0,
483 ("thread_alloc_stack called on a thread with kstack"));
484 if (!vm_thread_new(td, pages))
486 cpu_thread_alloc(td);
491 * Deallocate a thread.
494 thread_free(struct thread *td)
497 EVENTHANDLER_DIRECT_INVOKE(thread_dtor, td);
498 lock_profile_thread_exit(td);
500 cpuset_rel(td->td_cpuset);
501 td->td_cpuset = NULL;
503 if (td->td_kstack != 0)
504 vm_thread_dispose(td);
505 callout_drain(&td->td_slpcallout);
506 tid_free(td->td_tid);
508 uma_zfree(thread_zone, td);
512 thread_cow_get_proc(struct thread *newtd, struct proc *p)
515 PROC_LOCK_ASSERT(p, MA_OWNED);
516 newtd->td_realucred = crcowget(p->p_ucred);
517 newtd->td_ucred = newtd->td_realucred;
518 newtd->td_limit = lim_hold(p->p_limit);
519 newtd->td_cowgen = p->p_cowgen;
523 thread_cow_get(struct thread *newtd, struct thread *td)
526 MPASS(td->td_realucred == td->td_ucred);
527 newtd->td_realucred = crcowget(td->td_realucred);
528 newtd->td_ucred = newtd->td_realucred;
529 newtd->td_limit = lim_hold(td->td_limit);
530 newtd->td_cowgen = td->td_cowgen;
534 thread_cow_free(struct thread *td)
537 if (td->td_realucred != NULL)
539 if (td->td_limit != NULL)
540 lim_free(td->td_limit);
544 thread_cow_update(struct thread *td)
547 struct ucred *oldcred;
548 struct plimit *oldlimit;
553 oldcred = crcowsync();
554 if (td->td_limit != p->p_limit) {
555 oldlimit = td->td_limit;
556 td->td_limit = lim_hold(p->p_limit);
558 td->td_cowgen = p->p_cowgen;
562 if (oldlimit != NULL)
567 * Discard the current thread and exit from its context.
568 * Always called with scheduler locked.
570 * Because we can't free a thread while we're operating under its context,
571 * push the current thread into our CPU's deadthread holder. This means
572 * we needn't worry about someone else grabbing our context before we
578 uint64_t runtime, new_switchtime;
587 PROC_SLOCK_ASSERT(p, MA_OWNED);
588 mtx_assert(&Giant, MA_NOTOWNED);
590 PROC_LOCK_ASSERT(p, MA_OWNED);
591 KASSERT(p != NULL, ("thread exiting without a process"));
592 CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
593 (long)p->p_pid, td->td_name);
594 SDT_PROBE0(proc, , , lwp__exit);
595 KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
596 MPASS(td->td_realucred == td->td_ucred);
599 * drop FPU & debug register state storage, or any other
600 * architecture specific resources that
601 * would not be on a new untouched process.
606 * The last thread is left attached to the process
607 * So that the whole bundle gets recycled. Skip
608 * all this stuff if we never had threads.
609 * EXIT clears all sign of other threads when
610 * it goes to single threading, so the last thread always
611 * takes the short path.
613 if (p->p_flag & P_HADTHREADS) {
614 if (p->p_numthreads > 1) {
615 atomic_add_int(&td->td_proc->p_exitthreads, 1);
617 td2 = FIRST_THREAD_IN_PROC(p);
618 sched_exit_thread(td2, td);
621 * The test below is NOT true if we are the
622 * sole exiting thread. P_STOPPED_SINGLE is unset
623 * in exit1() after it is the only survivor.
625 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
626 if (p->p_numthreads == p->p_suspcount) {
627 thread_lock(p->p_singlethread);
628 wakeup_swapper = thread_unsuspend_one(
629 p->p_singlethread, p, false);
635 PCPU_SET(deadthread, td);
638 * The last thread is exiting.. but not through exit()
640 panic ("thread_exit: Last thread exiting on its own");
645 * If this thread is part of a process that is being tracked by hwpmc(4),
646 * inform the module of the thread's impending exit.
648 if (PMC_PROC_IS_USING_PMCS(td->td_proc)) {
649 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
650 PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT, NULL);
651 } else if (PMC_SYSTEM_SAMPLING_ACTIVE())
652 PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT_LOG, NULL);
659 /* Do the same timestamp bookkeeping that mi_switch() would do. */
660 new_switchtime = cpu_ticks();
661 runtime = new_switchtime - PCPU_GET(switchtime);
662 td->td_runtime += runtime;
663 td->td_incruntime += runtime;
664 PCPU_SET(switchtime, new_switchtime);
665 PCPU_SET(switchticks, ticks);
668 /* Save our resource usage in our process. */
669 td->td_ru.ru_nvcsw++;
670 ruxagg_locked(p, td);
671 rucollect(&p->p_ru, &td->td_ru);
674 td->td_state = TDS_INACTIVE;
676 witness_thread_exit(td);
678 CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
680 panic("I'm a teapot!");
685 * Do any thread specific cleanups that may be needed in wait()
686 * called with Giant, proc and schedlock not held.
689 thread_wait(struct proc *p)
693 mtx_assert(&Giant, MA_NOTOWNED);
694 KASSERT(p->p_numthreads == 1, ("multiple threads in thread_wait()"));
695 KASSERT(p->p_exitthreads == 0, ("p_exitthreads leaking"));
696 td = FIRST_THREAD_IN_PROC(p);
697 /* Lock the last thread so we spin until it exits cpu_throw(). */
700 lock_profile_thread_exit(td);
701 cpuset_rel(td->td_cpuset);
702 td->td_cpuset = NULL;
703 cpu_thread_clean(td);
705 callout_drain(&td->td_slpcallout);
706 thread_reap(); /* check for zombie threads etc. */
710 * Link a thread to a process.
711 * set up anything that needs to be initialized for it to
712 * be used by the process.
715 thread_link(struct thread *td, struct proc *p)
719 * XXX This can't be enabled because it's called for proc0 before
720 * its lock has been created.
721 * PROC_LOCK_ASSERT(p, MA_OWNED);
723 td->td_state = TDS_INACTIVE;
725 td->td_flags = TDF_INMEM;
727 LIST_INIT(&td->td_contested);
728 LIST_INIT(&td->td_lprof[0]);
729 LIST_INIT(&td->td_lprof[1]);
731 SLIST_INIT(&td->td_epochs);
733 sigqueue_init(&td->td_sigqueue, p);
734 callout_init(&td->td_slpcallout, 1);
735 TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
744 thread_unlink(struct thread *td)
746 struct proc *p = td->td_proc;
748 PROC_LOCK_ASSERT(p, MA_OWNED);
750 MPASS(SLIST_EMPTY(&td->td_epochs));
753 TAILQ_REMOVE(&p->p_threads, td, td_plist);
755 /* could clear a few other things here */
756 /* Must NOT clear links to proc! */
760 calc_remaining(struct proc *p, int mode)
764 PROC_LOCK_ASSERT(p, MA_OWNED);
765 PROC_SLOCK_ASSERT(p, MA_OWNED);
766 if (mode == SINGLE_EXIT)
767 remaining = p->p_numthreads;
768 else if (mode == SINGLE_BOUNDARY)
769 remaining = p->p_numthreads - p->p_boundary_count;
770 else if (mode == SINGLE_NO_EXIT || mode == SINGLE_ALLPROC)
771 remaining = p->p_numthreads - p->p_suspcount;
773 panic("calc_remaining: wrong mode %d", mode);
778 remain_for_mode(int mode)
781 return (mode == SINGLE_ALLPROC ? 0 : 1);
785 weed_inhib(int mode, struct thread *td2, struct proc *p)
789 PROC_LOCK_ASSERT(p, MA_OWNED);
790 PROC_SLOCK_ASSERT(p, MA_OWNED);
791 THREAD_LOCK_ASSERT(td2, MA_OWNED);
796 * Since the thread lock is dropped by the scheduler we have
797 * to retry to check for races.
802 if (TD_IS_SUSPENDED(td2)) {
803 wakeup_swapper |= thread_unsuspend_one(td2, p, true);
807 if (TD_CAN_ABORT(td2)) {
808 wakeup_swapper |= sleepq_abort(td2, EINTR);
809 return (wakeup_swapper);
812 case SINGLE_BOUNDARY:
814 if (TD_IS_SUSPENDED(td2) &&
815 (td2->td_flags & TDF_BOUNDARY) == 0) {
816 wakeup_swapper |= thread_unsuspend_one(td2, p, false);
820 if (TD_CAN_ABORT(td2)) {
821 wakeup_swapper |= sleepq_abort(td2, ERESTART);
822 return (wakeup_swapper);
827 * ALLPROC suspend tries to avoid spurious EINTR for
828 * threads sleeping interruptable, by suspending the
829 * thread directly, similarly to sig_suspend_threads().
830 * Since such sleep is not performed at the user
831 * boundary, TDF_BOUNDARY flag is not set, and TDF_ALLPROCSUSP
832 * is used to avoid immediate un-suspend.
834 if (TD_IS_SUSPENDED(td2) && (td2->td_flags & (TDF_BOUNDARY |
835 TDF_ALLPROCSUSP)) == 0) {
836 wakeup_swapper |= thread_unsuspend_one(td2, p, false);
840 if (TD_CAN_ABORT(td2)) {
841 if ((td2->td_flags & TDF_SBDRY) == 0) {
842 thread_suspend_one(td2);
843 td2->td_flags |= TDF_ALLPROCSUSP;
845 wakeup_swapper |= sleepq_abort(td2, ERESTART);
846 return (wakeup_swapper);
854 return (wakeup_swapper);
858 * Enforce single-threading.
860 * Returns 1 if the caller must abort (another thread is waiting to
861 * exit the process or similar). Process is locked!
862 * Returns 0 when you are successfully the only thread running.
863 * A process has successfully single threaded in the suspend mode when
864 * There are no threads in user mode. Threads in the kernel must be
865 * allowed to continue until they get to the user boundary. They may even
866 * copy out their return values and data before suspending. They may however be
867 * accelerated in reaching the user boundary as we will wake up
868 * any sleeping threads that are interruptable. (PCATCH).
871 thread_single(struct proc *p, int mode)
875 int remaining, wakeup_swapper;
878 KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
879 mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
880 ("invalid mode %d", mode));
882 * If allowing non-ALLPROC singlethreading for non-curproc
883 * callers, calc_remaining() and remain_for_mode() should be
884 * adjusted to also account for td->td_proc != p. For now
885 * this is not implemented because it is not used.
887 KASSERT((mode == SINGLE_ALLPROC && td->td_proc != p) ||
888 (mode != SINGLE_ALLPROC && td->td_proc == p),
889 ("mode %d proc %p curproc %p", mode, p, td->td_proc));
890 mtx_assert(&Giant, MA_NOTOWNED);
891 PROC_LOCK_ASSERT(p, MA_OWNED);
893 if ((p->p_flag & P_HADTHREADS) == 0 && mode != SINGLE_ALLPROC)
896 /* Is someone already single threading? */
897 if (p->p_singlethread != NULL && p->p_singlethread != td)
900 if (mode == SINGLE_EXIT) {
901 p->p_flag |= P_SINGLE_EXIT;
902 p->p_flag &= ~P_SINGLE_BOUNDARY;
904 p->p_flag &= ~P_SINGLE_EXIT;
905 if (mode == SINGLE_BOUNDARY)
906 p->p_flag |= P_SINGLE_BOUNDARY;
908 p->p_flag &= ~P_SINGLE_BOUNDARY;
910 if (mode == SINGLE_ALLPROC)
911 p->p_flag |= P_TOTAL_STOP;
912 p->p_flag |= P_STOPPED_SINGLE;
914 p->p_singlethread = td;
915 remaining = calc_remaining(p, mode);
916 while (remaining != remain_for_mode(mode)) {
917 if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
920 FOREACH_THREAD_IN_PROC(p, td2) {
924 td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
925 if (TD_IS_INHIBITED(td2)) {
926 wakeup_swapper |= weed_inhib(mode, td2, p);
928 } else if (TD_IS_RUNNING(td2) && td != td2) {
937 remaining = calc_remaining(p, mode);
940 * Maybe we suspended some threads.. was it enough?
942 if (remaining == remain_for_mode(mode))
947 * Wake us up when everyone else has suspended.
948 * In the mean time we suspend as well.
950 thread_suspend_switch(td, p);
951 remaining = calc_remaining(p, mode);
953 if (mode == SINGLE_EXIT) {
955 * Convert the process to an unthreaded process. The
956 * SINGLE_EXIT is called by exit1() or execve(), in
957 * both cases other threads must be retired.
959 KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
960 p->p_singlethread = NULL;
961 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
964 * Wait for any remaining threads to exit cpu_throw().
966 while (p->p_exitthreads != 0) {
969 sched_relinquish(td);
973 } else if (mode == SINGLE_BOUNDARY) {
975 * Wait until all suspended threads are removed from
976 * the processors. The thread_suspend_check()
977 * increments p_boundary_count while it is still
978 * running, which makes it possible for the execve()
979 * to destroy vmspace while our other threads are
980 * still using the address space.
982 * We lock the thread, which is only allowed to
983 * succeed after context switch code finished using
986 FOREACH_THREAD_IN_PROC(p, td2) {
990 KASSERT((td2->td_flags & TDF_BOUNDARY) != 0,
991 ("td %p not on boundary", td2));
992 KASSERT(TD_IS_SUSPENDED(td2),
993 ("td %p is not suspended", td2));
1002 thread_suspend_check_needed(void)
1009 PROC_LOCK_ASSERT(p, MA_OWNED);
1010 return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
1011 (td->td_dbgflags & TDB_SUSPEND) != 0));
1015 * Called in from locations that can safely check to see
1016 * whether we have to suspend or at least throttle for a
1017 * single-thread event (e.g. fork).
1019 * Such locations include userret().
1020 * If the "return_instead" argument is non zero, the thread must be able to
1021 * accept 0 (caller may continue), or 1 (caller must abort) as a result.
1023 * The 'return_instead' argument tells the function if it may do a
1024 * thread_exit() or suspend, or whether the caller must abort and back
1027 * If the thread that set the single_threading request has set the
1028 * P_SINGLE_EXIT bit in the process flags then this call will never return
1029 * if 'return_instead' is false, but will exit.
1031 * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
1032 *---------------+--------------------+---------------------
1033 * 0 | returns 0 | returns 0 or 1
1034 * | when ST ends | immediately
1035 *---------------+--------------------+---------------------
1036 * 1 | thread exits | returns 1
1038 * 0 = thread_exit() or suspension ok,
1039 * other = return error instead of stopping the thread.
1041 * While a full suspension is under effect, even a single threading
1042 * thread would be suspended if it made this call (but it shouldn't).
1043 * This call should only be made from places where
1044 * thread_exit() would be safe as that may be the outcome unless
1045 * return_instead is set.
1048 thread_suspend_check(int return_instead)
1056 mtx_assert(&Giant, MA_NOTOWNED);
1057 PROC_LOCK_ASSERT(p, MA_OWNED);
1058 while (thread_suspend_check_needed()) {
1059 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1060 KASSERT(p->p_singlethread != NULL,
1061 ("singlethread not set"));
1063 * The only suspension in action is a
1064 * single-threading. Single threader need not stop.
1065 * It is safe to access p->p_singlethread unlocked
1066 * because it can only be set to our address by us.
1068 if (p->p_singlethread == td)
1069 return (0); /* Exempt from stopping. */
1071 if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
1074 /* Should we goto user boundary if we didn't come from there? */
1075 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1076 (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
1080 * Ignore suspend requests if they are deferred.
1082 if ((td->td_flags & TDF_SBDRY) != 0) {
1083 KASSERT(return_instead,
1084 ("TDF_SBDRY set for unsafe thread_suspend_check"));
1085 KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
1086 (TDF_SEINTR | TDF_SERESTART),
1087 ("both TDF_SEINTR and TDF_SERESTART"));
1088 return (TD_SBDRY_INTR(td) ? TD_SBDRY_ERRNO(td) : 0);
1092 * If the process is waiting for us to exit,
1093 * this thread should just suicide.
1094 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
1096 if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
1100 * Allow Linux emulation layer to do some work
1101 * before thread suicide.
1103 if (__predict_false(p->p_sysent->sv_thread_detach != NULL))
1104 (p->p_sysent->sv_thread_detach)(td);
1105 umtx_thread_exit(td);
1107 panic("stopped thread did not exit");
1112 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1113 if (p->p_numthreads == p->p_suspcount + 1) {
1114 thread_lock(p->p_singlethread);
1115 wakeup_swapper = thread_unsuspend_one(
1116 p->p_singlethread, p, false);
1124 * When a thread suspends, it just
1125 * gets taken off all queues.
1127 thread_suspend_one(td);
1128 if (return_instead == 0) {
1129 p->p_boundary_count++;
1130 td->td_flags |= TDF_BOUNDARY;
1133 mi_switch(SW_INVOL | SWT_SUSPEND);
1140 * Check for possible stops and suspensions while executing a
1141 * casueword or similar transiently failing operation.
1143 * The sleep argument controls whether the function can handle a stop
1144 * request itself or it should return ERESTART and the request is
1145 * proceed at the kernel/user boundary in ast.
1147 * Typically, when retrying due to casueword(9) failure (rv == 1), we
1148 * should handle the stop requests there, with exception of cases when
1149 * the thread owns a kernel resource, for instance busied the umtx
1150 * key, or when functions return immediately if thread_check_susp()
1151 * returned non-zero. On the other hand, retrying the whole lock
1152 * operation, we better not stop there but delegate the handling to
1155 * If the request is for thread termination P_SINGLE_EXIT, we cannot
1156 * handle it at all, and simply return EINTR.
1159 thread_check_susp(struct thread *td, bool sleep)
1165 * The check for TDF_NEEDSUSPCHK is racy, but it is enough to
1166 * eventually break the lockstep loop.
1168 if ((td->td_flags & TDF_NEEDSUSPCHK) == 0)
1173 if (p->p_flag & P_SINGLE_EXIT)
1175 else if (P_SHOULDSTOP(p) ||
1176 ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_SUSPEND)))
1177 error = sleep ? thread_suspend_check(0) : ERESTART;
1183 thread_suspend_switch(struct thread *td, struct proc *p)
1186 KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1187 PROC_LOCK_ASSERT(p, MA_OWNED);
1188 PROC_SLOCK_ASSERT(p, MA_OWNED);
1190 * We implement thread_suspend_one in stages here to avoid
1191 * dropping the proc lock while the thread lock is owned.
1193 if (p == td->td_proc) {
1199 td->td_flags &= ~TDF_NEEDSUSPCHK;
1200 TD_SET_SUSPENDED(td);
1204 mi_switch(SW_VOL | SWT_SUSPEND);
1211 thread_suspend_one(struct thread *td)
1216 PROC_SLOCK_ASSERT(p, MA_OWNED);
1217 THREAD_LOCK_ASSERT(td, MA_OWNED);
1218 KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1220 td->td_flags &= ~TDF_NEEDSUSPCHK;
1221 TD_SET_SUSPENDED(td);
1226 thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
1229 THREAD_LOCK_ASSERT(td, MA_OWNED);
1230 KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
1231 TD_CLR_SUSPENDED(td);
1232 td->td_flags &= ~TDF_ALLPROCSUSP;
1233 if (td->td_proc == p) {
1234 PROC_SLOCK_ASSERT(p, MA_OWNED);
1236 if (boundary && (td->td_flags & TDF_BOUNDARY) != 0) {
1237 td->td_flags &= ~TDF_BOUNDARY;
1238 p->p_boundary_count--;
1241 return (setrunnable(td, 0));
1245 * Allow all threads blocked by single threading to continue running.
1248 thread_unsuspend(struct proc *p)
1253 PROC_LOCK_ASSERT(p, MA_OWNED);
1254 PROC_SLOCK_ASSERT(p, MA_OWNED);
1256 if (!P_SHOULDSTOP(p)) {
1257 FOREACH_THREAD_IN_PROC(p, td) {
1259 if (TD_IS_SUSPENDED(td)) {
1260 wakeup_swapper |= thread_unsuspend_one(td, p,
1265 } else if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1266 p->p_numthreads == p->p_suspcount) {
1268 * Stopping everything also did the job for the single
1269 * threading request. Now we've downgraded to single-threaded,
1272 if (p->p_singlethread->td_proc == p) {
1273 thread_lock(p->p_singlethread);
1274 wakeup_swapper = thread_unsuspend_one(
1275 p->p_singlethread, p, false);
1283 * End the single threading mode..
1286 thread_single_end(struct proc *p, int mode)
1291 KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
1292 mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
1293 ("invalid mode %d", mode));
1294 PROC_LOCK_ASSERT(p, MA_OWNED);
1295 KASSERT((mode == SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) != 0) ||
1296 (mode != SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) == 0),
1297 ("mode %d does not match P_TOTAL_STOP", mode));
1298 KASSERT(mode == SINGLE_ALLPROC || p->p_singlethread == curthread,
1299 ("thread_single_end from other thread %p %p",
1300 curthread, p->p_singlethread));
1301 KASSERT(mode != SINGLE_BOUNDARY ||
1302 (p->p_flag & P_SINGLE_BOUNDARY) != 0,
1303 ("mis-matched SINGLE_BOUNDARY flags %x", p->p_flag));
1304 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY |
1307 p->p_singlethread = NULL;
1310 * If there are other threads they may now run,
1311 * unless of course there is a blanket 'stop order'
1312 * on the process. The single threader must be allowed
1313 * to continue however as this is a bad place to stop.
1315 if (p->p_numthreads != remain_for_mode(mode) && !P_SHOULDSTOP(p)) {
1316 FOREACH_THREAD_IN_PROC(p, td) {
1318 if (TD_IS_SUSPENDED(td)) {
1319 wakeup_swapper |= thread_unsuspend_one(td, p,
1320 mode == SINGLE_BOUNDARY);
1325 KASSERT(mode != SINGLE_BOUNDARY || p->p_boundary_count == 0,
1326 ("inconsistent boundary count %d", p->p_boundary_count));
1332 /* Locate a thread by number; return with proc lock held. */
1334 tdfind(lwpid_t tid, pid_t pid)
1336 #define RUN_THRESH 16
1341 if (td->td_tid == tid) {
1342 if (pid != -1 && td->td_proc->p_pid != pid)
1344 PROC_LOCK(td->td_proc);
1348 rw_rlock(&tidhash_lock);
1349 LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1350 if (td->td_tid == tid) {
1351 if (pid != -1 && td->td_proc->p_pid != pid) {
1355 PROC_LOCK(td->td_proc);
1356 if (td->td_proc->p_state == PRS_NEW) {
1357 PROC_UNLOCK(td->td_proc);
1361 if (run > RUN_THRESH) {
1362 if (rw_try_upgrade(&tidhash_lock)) {
1363 LIST_REMOVE(td, td_hash);
1364 LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1366 rw_wunlock(&tidhash_lock);
1374 rw_runlock(&tidhash_lock);
1379 tidhash_add(struct thread *td)
1381 rw_wlock(&tidhash_lock);
1382 LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1383 rw_wunlock(&tidhash_lock);
1387 tidhash_remove(struct thread *td)
1389 rw_wlock(&tidhash_lock);
1390 LIST_REMOVE(td, td_hash);
1391 rw_wunlock(&tidhash_lock);