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/epoch.h>
44 #include <sys/rangelock.h>
45 #include <sys/resourcevar.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>
55 #include <sys/rwlock.h>
57 #include <sys/vmmeter.h>
58 #include <sys/cpuset.h>
60 #include <sys/pmckern.h>
63 #include <security/audit/audit.h>
66 #include <vm/vm_extern.h>
68 #include <sys/eventhandler.h>
71 * Asserts below verify the stability of struct thread and struct proc
72 * layout, as exposed by KBI to modules. On head, the KBI is allowed
73 * to drift, change to the structures must be accompanied by the
76 * On the stable branches after KBI freeze, conditions must not be
77 * violated. Typically new fields are moved to the end of the
81 _Static_assert(offsetof(struct thread, td_flags) == 0xfc,
82 "struct thread KBI td_flags");
83 _Static_assert(offsetof(struct thread, td_pflags) == 0x104,
84 "struct thread KBI td_pflags");
85 _Static_assert(offsetof(struct thread, td_frame) == 0x4a8,
86 "struct thread KBI td_frame");
87 _Static_assert(offsetof(struct thread, td_emuldata) == 0x6b0,
88 "struct thread KBI td_emuldata");
89 _Static_assert(offsetof(struct proc, p_flag) == 0xb0,
90 "struct proc KBI p_flag");
91 _Static_assert(offsetof(struct proc, p_pid) == 0xbc,
92 "struct proc KBI p_pid");
93 _Static_assert(offsetof(struct proc, p_filemon) == 0x3b8,
94 "struct proc KBI p_filemon");
95 _Static_assert(offsetof(struct proc, p_comm) == 0x3d0,
96 "struct proc KBI p_comm");
97 _Static_assert(offsetof(struct proc, p_emuldata) == 0x4b0,
98 "struct proc KBI p_emuldata");
101 _Static_assert(offsetof(struct thread, td_flags) == 0x98,
102 "struct thread KBI td_flags");
103 _Static_assert(offsetof(struct thread, td_pflags) == 0xa0,
104 "struct thread KBI td_pflags");
105 _Static_assert(offsetof(struct thread, td_frame) == 0x304,
106 "struct thread KBI td_frame");
107 _Static_assert(offsetof(struct thread, td_emuldata) == 0x348,
108 "struct thread KBI td_emuldata");
109 _Static_assert(offsetof(struct proc, p_flag) == 0x68,
110 "struct proc KBI p_flag");
111 _Static_assert(offsetof(struct proc, p_pid) == 0x74,
112 "struct proc KBI p_pid");
113 _Static_assert(offsetof(struct proc, p_filemon) == 0x268,
114 "struct proc KBI p_filemon");
115 _Static_assert(offsetof(struct proc, p_comm) == 0x27c,
116 "struct proc KBI p_comm");
117 _Static_assert(offsetof(struct proc, p_emuldata) == 0x308,
118 "struct proc KBI p_emuldata");
121 SDT_PROVIDER_DECLARE(proc);
122 SDT_PROBE_DEFINE(proc, , , lwp__exit);
125 * thread related storage.
127 static uma_zone_t thread_zone;
129 TAILQ_HEAD(, thread) zombie_threads = TAILQ_HEAD_INITIALIZER(zombie_threads);
130 static struct mtx zombie_lock;
131 MTX_SYSINIT(zombie_lock, &zombie_lock, "zombie lock", MTX_SPIN);
133 static void thread_zombie(struct thread *);
134 static int thread_unsuspend_one(struct thread *td, struct proc *p,
137 #define TID_BUFFER_SIZE 1024
140 static struct unrhdr *tid_unrhdr;
141 static lwpid_t tid_buffer[TID_BUFFER_SIZE];
142 static int tid_head, tid_tail;
143 static MALLOC_DEFINE(M_TIDHASH, "tidhash", "thread hash");
145 struct tidhashhead *tidhashtbl;
147 struct rwlock tidhash_lock;
149 EVENTHANDLER_LIST_DEFINE(thread_ctor);
150 EVENTHANDLER_LIST_DEFINE(thread_dtor);
151 EVENTHANDLER_LIST_DEFINE(thread_init);
152 EVENTHANDLER_LIST_DEFINE(thread_fini);
159 tid = alloc_unr(tid_unrhdr);
163 if (tid_head == tid_tail) {
164 mtx_unlock(&tid_lock);
167 tid = tid_buffer[tid_head];
168 tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
169 mtx_unlock(&tid_lock);
174 tid_free(lwpid_t tid)
176 lwpid_t tmp_tid = -1;
179 if ((tid_tail + 1) % TID_BUFFER_SIZE == tid_head) {
180 tmp_tid = tid_buffer[tid_head];
181 tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
183 tid_buffer[tid_tail] = tid;
184 tid_tail = (tid_tail + 1) % TID_BUFFER_SIZE;
185 mtx_unlock(&tid_lock);
187 free_unr(tid_unrhdr, tmp_tid);
191 * Prepare a thread for use.
194 thread_ctor(void *mem, int size, void *arg, int flags)
198 td = (struct thread *)mem;
199 td->td_state = TDS_INACTIVE;
200 td->td_lastcpu = td->td_oncpu = NOCPU;
202 td->td_tid = tid_alloc();
205 * Note that td_critnest begins life as 1 because the thread is not
206 * running and is thereby implicitly waiting to be on the receiving
207 * end of a context switch.
210 td->td_lend_user_pri = PRI_MAX;
211 EVENTHANDLER_DIRECT_INVOKE(thread_ctor, td);
213 audit_thread_alloc(td);
215 umtx_thread_alloc(td);
220 * Reclaim a thread after use.
223 thread_dtor(void *mem, int size, void *arg)
227 td = (struct thread *)mem;
230 /* Verify that this thread is in a safe state to free. */
231 switch (td->td_state) {
237 * We must never unlink a thread that is in one of
238 * these states, because it is currently active.
240 panic("bad state for thread unlinking");
245 panic("bad thread state");
250 audit_thread_free(td);
252 /* Free all OSD associated to this thread. */
254 td_softdep_cleanup(td);
255 MPASS(td->td_su == NULL);
257 EVENTHANDLER_DIRECT_INVOKE(thread_dtor, td);
258 tid_free(td->td_tid);
262 * Initialize type-stable parts of a thread (when newly created).
265 thread_init(void *mem, int size, int flags)
269 td = (struct thread *)mem;
271 td->td_sleepqueue = sleepq_alloc();
272 td->td_turnstile = turnstile_alloc();
274 EVENTHANDLER_DIRECT_INVOKE(thread_init, td);
275 umtx_thread_init(td);
282 * Tear down type-stable parts of a thread (just before being discarded).
285 thread_fini(void *mem, int size)
289 td = (struct thread *)mem;
290 EVENTHANDLER_DIRECT_INVOKE(thread_fini, td);
291 rlqentry_free(td->td_rlqe);
292 turnstile_free(td->td_turnstile);
293 sleepq_free(td->td_sleepqueue);
294 umtx_thread_fini(td);
299 * For a newly created process,
300 * link up all the structures and its initial threads etc.
302 * {arch}/{arch}/machdep.c {arch}_init(), init386() etc.
303 * proc_dtor() (should go away)
307 proc_linkup0(struct proc *p, struct thread *td)
309 TAILQ_INIT(&p->p_threads); /* all threads in proc */
314 proc_linkup(struct proc *p, struct thread *td)
317 sigqueue_init(&p->p_sigqueue, p);
318 p->p_ksi = ksiginfo_alloc(1);
319 if (p->p_ksi != NULL) {
320 /* XXX p_ksi may be null if ksiginfo zone is not ready */
321 p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
323 LIST_INIT(&p->p_mqnotifier);
329 * Initialize global thread allocation resources.
336 mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
339 * pid_max cannot be greater than PID_MAX.
340 * leave one number for thread0.
342 tid_unrhdr = new_unrhdr(PID_MAX + 2, INT_MAX, &tid_lock);
344 flags = UMA_ZONE_NOFREE;
347 * Force thread structures to be allocated from the direct map.
348 * Otherwise, superpage promotions and demotions may temporarily
349 * invalidate thread structure mappings. For most dynamically allocated
350 * structures this is not a problem, but translation faults cannot be
351 * handled without accessing curthread.
353 flags |= UMA_ZONE_CONTIG;
355 thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
356 thread_ctor, thread_dtor, thread_init, thread_fini,
358 tidhashtbl = hashinit(maxproc / 2, M_TIDHASH, &tidhash);
359 rw_init(&tidhash_lock, "tidhash");
363 * Place an unused thread on the zombie list.
364 * Use the slpq as that must be unused by now.
367 thread_zombie(struct thread *td)
369 mtx_lock_spin(&zombie_lock);
370 TAILQ_INSERT_HEAD(&zombie_threads, td, td_slpq);
371 mtx_unlock_spin(&zombie_lock);
375 * Release a thread that has exited after cpu_throw().
378 thread_stash(struct thread *td)
380 atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
385 * Reap zombie resources.
390 struct thread *td_first, *td_next;
393 * Don't even bother to lock if none at this instant,
394 * we really don't care about the next instant.
396 if (!TAILQ_EMPTY(&zombie_threads)) {
397 mtx_lock_spin(&zombie_lock);
398 td_first = TAILQ_FIRST(&zombie_threads);
400 TAILQ_INIT(&zombie_threads);
401 mtx_unlock_spin(&zombie_lock);
403 td_next = TAILQ_NEXT(td_first, td_slpq);
404 thread_cow_free(td_first);
405 thread_free(td_first);
415 thread_alloc(int pages)
419 thread_reap(); /* check if any zombies to get */
421 td = (struct thread *)uma_zalloc(thread_zone, M_WAITOK);
422 KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
423 if (!vm_thread_new(td, pages)) {
424 uma_zfree(thread_zone, td);
427 cpu_thread_alloc(td);
432 thread_alloc_stack(struct thread *td, int pages)
435 KASSERT(td->td_kstack == 0,
436 ("thread_alloc_stack called on a thread with kstack"));
437 if (!vm_thread_new(td, pages))
439 cpu_thread_alloc(td);
444 * Deallocate a thread.
447 thread_free(struct thread *td)
450 lock_profile_thread_exit(td);
452 cpuset_rel(td->td_cpuset);
453 td->td_cpuset = NULL;
455 if (td->td_kstack != 0)
456 vm_thread_dispose(td);
457 callout_drain(&td->td_slpcallout);
458 uma_zfree(thread_zone, td);
462 thread_cow_get_proc(struct thread *newtd, struct proc *p)
465 PROC_LOCK_ASSERT(p, MA_OWNED);
466 newtd->td_realucred = crcowget(p->p_ucred);
467 newtd->td_ucred = newtd->td_realucred;
468 newtd->td_limit = lim_hold(p->p_limit);
469 newtd->td_cowgen = p->p_cowgen;
473 thread_cow_get(struct thread *newtd, struct thread *td)
476 MPASS(td->td_realucred == td->td_ucred);
477 newtd->td_realucred = crcowget(td->td_realucred);
478 newtd->td_ucred = newtd->td_realucred;
479 newtd->td_limit = lim_hold(td->td_limit);
480 newtd->td_cowgen = td->td_cowgen;
484 thread_cow_free(struct thread *td)
487 if (td->td_realucred != NULL)
489 if (td->td_limit != NULL)
490 lim_free(td->td_limit);
494 thread_cow_update(struct thread *td)
497 struct ucred *oldcred;
498 struct plimit *oldlimit;
503 oldcred = crcowsync();
504 if (td->td_limit != p->p_limit) {
505 oldlimit = td->td_limit;
506 td->td_limit = lim_hold(p->p_limit);
508 td->td_cowgen = p->p_cowgen;
512 if (oldlimit != NULL)
517 * Discard the current thread and exit from its context.
518 * Always called with scheduler locked.
520 * Because we can't free a thread while we're operating under its context,
521 * push the current thread into our CPU's deadthread holder. This means
522 * we needn't worry about someone else grabbing our context before we
528 uint64_t runtime, new_switchtime;
537 PROC_SLOCK_ASSERT(p, MA_OWNED);
538 mtx_assert(&Giant, MA_NOTOWNED);
540 PROC_LOCK_ASSERT(p, MA_OWNED);
541 KASSERT(p != NULL, ("thread exiting without a process"));
542 CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
543 (long)p->p_pid, td->td_name);
544 SDT_PROBE0(proc, , , lwp__exit);
545 KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
546 MPASS(td->td_realucred == td->td_ucred);
549 * drop FPU & debug register state storage, or any other
550 * architecture specific resources that
551 * would not be on a new untouched process.
556 * The last thread is left attached to the process
557 * So that the whole bundle gets recycled. Skip
558 * all this stuff if we never had threads.
559 * EXIT clears all sign of other threads when
560 * it goes to single threading, so the last thread always
561 * takes the short path.
563 if (p->p_flag & P_HADTHREADS) {
564 if (p->p_numthreads > 1) {
565 atomic_add_int(&td->td_proc->p_exitthreads, 1);
567 td2 = FIRST_THREAD_IN_PROC(p);
568 sched_exit_thread(td2, td);
571 * The test below is NOT true if we are the
572 * sole exiting thread. P_STOPPED_SINGLE is unset
573 * in exit1() after it is the only survivor.
575 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
576 if (p->p_numthreads == p->p_suspcount) {
577 thread_lock(p->p_singlethread);
578 wakeup_swapper = thread_unsuspend_one(
579 p->p_singlethread, p, false);
585 PCPU_SET(deadthread, td);
588 * The last thread is exiting.. but not through exit()
590 panic ("thread_exit: Last thread exiting on its own");
595 * If this thread is part of a process that is being tracked by hwpmc(4),
596 * inform the module of the thread's impending exit.
598 if (PMC_PROC_IS_USING_PMCS(td->td_proc)) {
599 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
600 PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT, NULL);
601 } else if (PMC_SYSTEM_SAMPLING_ACTIVE())
602 PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT_LOG, NULL);
609 /* Do the same timestamp bookkeeping that mi_switch() would do. */
610 new_switchtime = cpu_ticks();
611 runtime = new_switchtime - PCPU_GET(switchtime);
612 td->td_runtime += runtime;
613 td->td_incruntime += runtime;
614 PCPU_SET(switchtime, new_switchtime);
615 PCPU_SET(switchticks, ticks);
618 /* Save our resource usage in our process. */
619 td->td_ru.ru_nvcsw++;
620 ruxagg_locked(p, td);
621 rucollect(&p->p_ru, &td->td_ru);
624 td->td_state = TDS_INACTIVE;
626 witness_thread_exit(td);
628 CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
630 panic("I'm a teapot!");
635 * Do any thread specific cleanups that may be needed in wait()
636 * called with Giant, proc and schedlock not held.
639 thread_wait(struct proc *p)
643 mtx_assert(&Giant, MA_NOTOWNED);
644 KASSERT(p->p_numthreads == 1, ("multiple threads in thread_wait()"));
645 KASSERT(p->p_exitthreads == 0, ("p_exitthreads leaking"));
646 td = FIRST_THREAD_IN_PROC(p);
647 /* Lock the last thread so we spin until it exits cpu_throw(). */
650 lock_profile_thread_exit(td);
651 cpuset_rel(td->td_cpuset);
652 td->td_cpuset = NULL;
653 cpu_thread_clean(td);
655 callout_drain(&td->td_slpcallout);
656 thread_reap(); /* check for zombie threads etc. */
660 * Link a thread to a process.
661 * set up anything that needs to be initialized for it to
662 * be used by the process.
665 thread_link(struct thread *td, struct proc *p)
669 * XXX This can't be enabled because it's called for proc0 before
670 * its lock has been created.
671 * PROC_LOCK_ASSERT(p, MA_OWNED);
673 td->td_state = TDS_INACTIVE;
675 td->td_flags = TDF_INMEM;
677 LIST_INIT(&td->td_contested);
678 LIST_INIT(&td->td_lprof[0]);
679 LIST_INIT(&td->td_lprof[1]);
681 SLIST_INIT(&td->td_epochs);
683 sigqueue_init(&td->td_sigqueue, p);
684 callout_init(&td->td_slpcallout, 1);
685 TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
694 thread_unlink(struct thread *td)
696 struct proc *p = td->td_proc;
698 PROC_LOCK_ASSERT(p, MA_OWNED);
700 MPASS(SLIST_EMPTY(&td->td_epochs));
703 TAILQ_REMOVE(&p->p_threads, td, td_plist);
705 /* could clear a few other things here */
706 /* Must NOT clear links to proc! */
710 calc_remaining(struct proc *p, int mode)
714 PROC_LOCK_ASSERT(p, MA_OWNED);
715 PROC_SLOCK_ASSERT(p, MA_OWNED);
716 if (mode == SINGLE_EXIT)
717 remaining = p->p_numthreads;
718 else if (mode == SINGLE_BOUNDARY)
719 remaining = p->p_numthreads - p->p_boundary_count;
720 else if (mode == SINGLE_NO_EXIT || mode == SINGLE_ALLPROC)
721 remaining = p->p_numthreads - p->p_suspcount;
723 panic("calc_remaining: wrong mode %d", mode);
728 remain_for_mode(int mode)
731 return (mode == SINGLE_ALLPROC ? 0 : 1);
735 weed_inhib(int mode, struct thread *td2, struct proc *p)
739 PROC_LOCK_ASSERT(p, MA_OWNED);
740 PROC_SLOCK_ASSERT(p, MA_OWNED);
741 THREAD_LOCK_ASSERT(td2, MA_OWNED);
746 * Since the thread lock is dropped by the scheduler we have
747 * to retry to check for races.
752 if (TD_IS_SUSPENDED(td2)) {
753 wakeup_swapper |= thread_unsuspend_one(td2, p, true);
757 if (TD_CAN_ABORT(td2)) {
758 wakeup_swapper |= sleepq_abort(td2, EINTR);
759 return (wakeup_swapper);
762 case SINGLE_BOUNDARY:
764 if (TD_IS_SUSPENDED(td2) &&
765 (td2->td_flags & TDF_BOUNDARY) == 0) {
766 wakeup_swapper |= thread_unsuspend_one(td2, p, false);
770 if (TD_CAN_ABORT(td2)) {
771 wakeup_swapper |= sleepq_abort(td2, ERESTART);
772 return (wakeup_swapper);
777 * ALLPROC suspend tries to avoid spurious EINTR for
778 * threads sleeping interruptable, by suspending the
779 * thread directly, similarly to sig_suspend_threads().
780 * Since such sleep is not performed at the user
781 * boundary, TDF_BOUNDARY flag is not set, and TDF_ALLPROCSUSP
782 * is used to avoid immediate un-suspend.
784 if (TD_IS_SUSPENDED(td2) && (td2->td_flags & (TDF_BOUNDARY |
785 TDF_ALLPROCSUSP)) == 0) {
786 wakeup_swapper |= thread_unsuspend_one(td2, p, false);
790 if (TD_CAN_ABORT(td2)) {
791 if ((td2->td_flags & TDF_SBDRY) == 0) {
792 thread_suspend_one(td2);
793 td2->td_flags |= TDF_ALLPROCSUSP;
795 wakeup_swapper |= sleepq_abort(td2, ERESTART);
796 return (wakeup_swapper);
804 return (wakeup_swapper);
808 * Enforce single-threading.
810 * Returns 1 if the caller must abort (another thread is waiting to
811 * exit the process or similar). Process is locked!
812 * Returns 0 when you are successfully the only thread running.
813 * A process has successfully single threaded in the suspend mode when
814 * There are no threads in user mode. Threads in the kernel must be
815 * allowed to continue until they get to the user boundary. They may even
816 * copy out their return values and data before suspending. They may however be
817 * accelerated in reaching the user boundary as we will wake up
818 * any sleeping threads that are interruptable. (PCATCH).
821 thread_single(struct proc *p, int mode)
825 int remaining, wakeup_swapper;
828 KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
829 mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
830 ("invalid mode %d", mode));
832 * If allowing non-ALLPROC singlethreading for non-curproc
833 * callers, calc_remaining() and remain_for_mode() should be
834 * adjusted to also account for td->td_proc != p. For now
835 * this is not implemented because it is not used.
837 KASSERT((mode == SINGLE_ALLPROC && td->td_proc != p) ||
838 (mode != SINGLE_ALLPROC && td->td_proc == p),
839 ("mode %d proc %p curproc %p", mode, p, td->td_proc));
840 mtx_assert(&Giant, MA_NOTOWNED);
841 PROC_LOCK_ASSERT(p, MA_OWNED);
843 if ((p->p_flag & P_HADTHREADS) == 0 && mode != SINGLE_ALLPROC)
846 /* Is someone already single threading? */
847 if (p->p_singlethread != NULL && p->p_singlethread != td)
850 if (mode == SINGLE_EXIT) {
851 p->p_flag |= P_SINGLE_EXIT;
852 p->p_flag &= ~P_SINGLE_BOUNDARY;
854 p->p_flag &= ~P_SINGLE_EXIT;
855 if (mode == SINGLE_BOUNDARY)
856 p->p_flag |= P_SINGLE_BOUNDARY;
858 p->p_flag &= ~P_SINGLE_BOUNDARY;
860 if (mode == SINGLE_ALLPROC)
861 p->p_flag |= P_TOTAL_STOP;
862 p->p_flag |= P_STOPPED_SINGLE;
864 p->p_singlethread = td;
865 remaining = calc_remaining(p, mode);
866 while (remaining != remain_for_mode(mode)) {
867 if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
870 FOREACH_THREAD_IN_PROC(p, td2) {
874 td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
875 if (TD_IS_INHIBITED(td2)) {
876 wakeup_swapper |= weed_inhib(mode, td2, p);
878 } else if (TD_IS_RUNNING(td2) && td != td2) {
887 remaining = calc_remaining(p, mode);
890 * Maybe we suspended some threads.. was it enough?
892 if (remaining == remain_for_mode(mode))
897 * Wake us up when everyone else has suspended.
898 * In the mean time we suspend as well.
900 thread_suspend_switch(td, p);
901 remaining = calc_remaining(p, mode);
903 if (mode == SINGLE_EXIT) {
905 * Convert the process to an unthreaded process. The
906 * SINGLE_EXIT is called by exit1() or execve(), in
907 * both cases other threads must be retired.
909 KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
910 p->p_singlethread = NULL;
911 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
914 * Wait for any remaining threads to exit cpu_throw().
916 while (p->p_exitthreads != 0) {
919 sched_relinquish(td);
923 } else if (mode == SINGLE_BOUNDARY) {
925 * Wait until all suspended threads are removed from
926 * the processors. The thread_suspend_check()
927 * increments p_boundary_count while it is still
928 * running, which makes it possible for the execve()
929 * to destroy vmspace while our other threads are
930 * still using the address space.
932 * We lock the thread, which is only allowed to
933 * succeed after context switch code finished using
936 FOREACH_THREAD_IN_PROC(p, td2) {
940 KASSERT((td2->td_flags & TDF_BOUNDARY) != 0,
941 ("td %p not on boundary", td2));
942 KASSERT(TD_IS_SUSPENDED(td2),
943 ("td %p is not suspended", td2));
952 thread_suspend_check_needed(void)
959 PROC_LOCK_ASSERT(p, MA_OWNED);
960 return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
961 (td->td_dbgflags & TDB_SUSPEND) != 0));
965 * Called in from locations that can safely check to see
966 * whether we have to suspend or at least throttle for a
967 * single-thread event (e.g. fork).
969 * Such locations include userret().
970 * If the "return_instead" argument is non zero, the thread must be able to
971 * accept 0 (caller may continue), or 1 (caller must abort) as a result.
973 * The 'return_instead' argument tells the function if it may do a
974 * thread_exit() or suspend, or whether the caller must abort and back
977 * If the thread that set the single_threading request has set the
978 * P_SINGLE_EXIT bit in the process flags then this call will never return
979 * if 'return_instead' is false, but will exit.
981 * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
982 *---------------+--------------------+---------------------
983 * 0 | returns 0 | returns 0 or 1
984 * | when ST ends | immediately
985 *---------------+--------------------+---------------------
986 * 1 | thread exits | returns 1
988 * 0 = thread_exit() or suspension ok,
989 * other = return error instead of stopping the thread.
991 * While a full suspension is under effect, even a single threading
992 * thread would be suspended if it made this call (but it shouldn't).
993 * This call should only be made from places where
994 * thread_exit() would be safe as that may be the outcome unless
995 * return_instead is set.
998 thread_suspend_check(int return_instead)
1006 mtx_assert(&Giant, MA_NOTOWNED);
1007 PROC_LOCK_ASSERT(p, MA_OWNED);
1008 while (thread_suspend_check_needed()) {
1009 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1010 KASSERT(p->p_singlethread != NULL,
1011 ("singlethread not set"));
1013 * The only suspension in action is a
1014 * single-threading. Single threader need not stop.
1015 * It is safe to access p->p_singlethread unlocked
1016 * because it can only be set to our address by us.
1018 if (p->p_singlethread == td)
1019 return (0); /* Exempt from stopping. */
1021 if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
1024 /* Should we goto user boundary if we didn't come from there? */
1025 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1026 (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
1030 * Ignore suspend requests if they are deferred.
1032 if ((td->td_flags & TDF_SBDRY) != 0) {
1033 KASSERT(return_instead,
1034 ("TDF_SBDRY set for unsafe thread_suspend_check"));
1035 KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
1036 (TDF_SEINTR | TDF_SERESTART),
1037 ("both TDF_SEINTR and TDF_SERESTART"));
1038 return (TD_SBDRY_INTR(td) ? TD_SBDRY_ERRNO(td) : 0);
1042 * If the process is waiting for us to exit,
1043 * this thread should just suicide.
1044 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
1046 if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
1050 * Allow Linux emulation layer to do some work
1051 * before thread suicide.
1053 if (__predict_false(p->p_sysent->sv_thread_detach != NULL))
1054 (p->p_sysent->sv_thread_detach)(td);
1055 umtx_thread_exit(td);
1057 panic("stopped thread did not exit");
1062 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1063 if (p->p_numthreads == p->p_suspcount + 1) {
1064 thread_lock(p->p_singlethread);
1065 wakeup_swapper = thread_unsuspend_one(
1066 p->p_singlethread, p, false);
1074 * When a thread suspends, it just
1075 * gets taken off all queues.
1077 thread_suspend_one(td);
1078 if (return_instead == 0) {
1079 p->p_boundary_count++;
1080 td->td_flags |= TDF_BOUNDARY;
1083 mi_switch(SW_INVOL | SWT_SUSPEND);
1090 * Check for possible stops and suspensions while executing a
1091 * casueword or similar transiently failing operation.
1093 * The sleep argument controls whether the function can handle a stop
1094 * request itself or it should return ERESTART and the request is
1095 * proceed at the kernel/user boundary in ast.
1097 * Typically, when retrying due to casueword(9) failure (rv == 1), we
1098 * should handle the stop requests there, with exception of cases when
1099 * the thread owns a kernel resource, for instance busied the umtx
1100 * key, or when functions return immediately if thread_check_susp()
1101 * returned non-zero. On the other hand, retrying the whole lock
1102 * operation, we better not stop there but delegate the handling to
1105 * If the request is for thread termination P_SINGLE_EXIT, we cannot
1106 * handle it at all, and simply return EINTR.
1109 thread_check_susp(struct thread *td, bool sleep)
1115 * The check for TDF_NEEDSUSPCHK is racy, but it is enough to
1116 * eventually break the lockstep loop.
1118 if ((td->td_flags & TDF_NEEDSUSPCHK) == 0)
1123 if (p->p_flag & P_SINGLE_EXIT)
1125 else if (P_SHOULDSTOP(p) ||
1126 ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_SUSPEND)))
1127 error = sleep ? thread_suspend_check(0) : ERESTART;
1133 thread_suspend_switch(struct thread *td, struct proc *p)
1136 KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1137 PROC_LOCK_ASSERT(p, MA_OWNED);
1138 PROC_SLOCK_ASSERT(p, MA_OWNED);
1140 * We implement thread_suspend_one in stages here to avoid
1141 * dropping the proc lock while the thread lock is owned.
1143 if (p == td->td_proc) {
1149 td->td_flags &= ~TDF_NEEDSUSPCHK;
1150 TD_SET_SUSPENDED(td);
1154 mi_switch(SW_VOL | SWT_SUSPEND);
1161 thread_suspend_one(struct thread *td)
1166 PROC_SLOCK_ASSERT(p, MA_OWNED);
1167 THREAD_LOCK_ASSERT(td, MA_OWNED);
1168 KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1170 td->td_flags &= ~TDF_NEEDSUSPCHK;
1171 TD_SET_SUSPENDED(td);
1176 thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
1179 THREAD_LOCK_ASSERT(td, MA_OWNED);
1180 KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
1181 TD_CLR_SUSPENDED(td);
1182 td->td_flags &= ~TDF_ALLPROCSUSP;
1183 if (td->td_proc == p) {
1184 PROC_SLOCK_ASSERT(p, MA_OWNED);
1186 if (boundary && (td->td_flags & TDF_BOUNDARY) != 0) {
1187 td->td_flags &= ~TDF_BOUNDARY;
1188 p->p_boundary_count--;
1191 return (setrunnable(td, 0));
1195 * Allow all threads blocked by single threading to continue running.
1198 thread_unsuspend(struct proc *p)
1203 PROC_LOCK_ASSERT(p, MA_OWNED);
1204 PROC_SLOCK_ASSERT(p, MA_OWNED);
1206 if (!P_SHOULDSTOP(p)) {
1207 FOREACH_THREAD_IN_PROC(p, td) {
1209 if (TD_IS_SUSPENDED(td)) {
1210 wakeup_swapper |= thread_unsuspend_one(td, p,
1215 } else if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1216 p->p_numthreads == p->p_suspcount) {
1218 * Stopping everything also did the job for the single
1219 * threading request. Now we've downgraded to single-threaded,
1222 if (p->p_singlethread->td_proc == p) {
1223 thread_lock(p->p_singlethread);
1224 wakeup_swapper = thread_unsuspend_one(
1225 p->p_singlethread, p, false);
1233 * End the single threading mode..
1236 thread_single_end(struct proc *p, int mode)
1241 KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
1242 mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
1243 ("invalid mode %d", mode));
1244 PROC_LOCK_ASSERT(p, MA_OWNED);
1245 KASSERT((mode == SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) != 0) ||
1246 (mode != SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) == 0),
1247 ("mode %d does not match P_TOTAL_STOP", mode));
1248 KASSERT(mode == SINGLE_ALLPROC || p->p_singlethread == curthread,
1249 ("thread_single_end from other thread %p %p",
1250 curthread, p->p_singlethread));
1251 KASSERT(mode != SINGLE_BOUNDARY ||
1252 (p->p_flag & P_SINGLE_BOUNDARY) != 0,
1253 ("mis-matched SINGLE_BOUNDARY flags %x", p->p_flag));
1254 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY |
1257 p->p_singlethread = NULL;
1260 * If there are other threads they may now run,
1261 * unless of course there is a blanket 'stop order'
1262 * on the process. The single threader must be allowed
1263 * to continue however as this is a bad place to stop.
1265 if (p->p_numthreads != remain_for_mode(mode) && !P_SHOULDSTOP(p)) {
1266 FOREACH_THREAD_IN_PROC(p, td) {
1268 if (TD_IS_SUSPENDED(td)) {
1269 wakeup_swapper |= thread_unsuspend_one(td, p,
1270 mode == SINGLE_BOUNDARY);
1275 KASSERT(mode != SINGLE_BOUNDARY || p->p_boundary_count == 0,
1276 ("inconsistent boundary count %d", p->p_boundary_count));
1283 thread_find(struct proc *p, lwpid_t tid)
1287 PROC_LOCK_ASSERT(p, MA_OWNED);
1288 FOREACH_THREAD_IN_PROC(p, td) {
1289 if (td->td_tid == tid)
1295 /* Locate a thread by number; return with proc lock held. */
1297 tdfind(lwpid_t tid, pid_t pid)
1299 #define RUN_THRESH 16
1304 if (td->td_tid == tid) {
1305 if (pid != -1 && td->td_proc->p_pid != pid)
1307 PROC_LOCK(td->td_proc);
1311 rw_rlock(&tidhash_lock);
1312 LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1313 if (td->td_tid == tid) {
1314 if (pid != -1 && td->td_proc->p_pid != pid) {
1318 PROC_LOCK(td->td_proc);
1319 if (td->td_proc->p_state == PRS_NEW) {
1320 PROC_UNLOCK(td->td_proc);
1324 if (run > RUN_THRESH) {
1325 if (rw_try_upgrade(&tidhash_lock)) {
1326 LIST_REMOVE(td, td_hash);
1327 LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1329 rw_wunlock(&tidhash_lock);
1337 rw_runlock(&tidhash_lock);
1342 tidhash_add(struct thread *td)
1344 rw_wlock(&tidhash_lock);
1345 LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1346 rw_wunlock(&tidhash_lock);
1350 tidhash_remove(struct thread *td)
1352 rw_wlock(&tidhash_lock);
1353 LIST_REMOVE(td, td_hash);
1354 rw_wunlock(&tidhash_lock);