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/rangelock.h>
44 #include <sys/resourcevar.h>
47 #include <sys/sched.h>
48 #include <sys/sleepqueue.h>
49 #include <sys/selinfo.h>
50 #include <sys/syscallsubr.h>
51 #include <sys/sysent.h>
52 #include <sys/turnstile.h>
54 #include <sys/rwlock.h>
56 #include <sys/vmmeter.h>
57 #include <sys/cpuset.h>
59 #include <sys/pmckern.h>
62 #include <security/audit/audit.h>
65 #include <vm/vm_extern.h>
67 #include <sys/eventhandler.h>
70 * Asserts below verify the stability of struct thread and struct proc
71 * layout, as exposed by KBI to modules. On head, the KBI is allowed
72 * to drift, change to the structures must be accompanied by the
75 * On the stable branches after KBI freeze, conditions must not be
76 * violated. Typically new fields are moved to the end of the
80 _Static_assert(offsetof(struct thread, td_flags) == 0xfc,
81 "struct thread KBI td_flags");
82 _Static_assert(offsetof(struct thread, td_pflags) == 0x104,
83 "struct thread KBI td_pflags");
84 _Static_assert(offsetof(struct thread, td_frame) == 0x470,
85 "struct thread KBI td_frame");
86 _Static_assert(offsetof(struct thread, td_emuldata) == 0x518,
87 "struct thread KBI td_emuldata");
88 _Static_assert(offsetof(struct proc, p_flag) == 0xb0,
89 "struct proc KBI p_flag");
90 _Static_assert(offsetof(struct proc, p_pid) == 0xbc,
91 "struct proc KBI p_pid");
92 _Static_assert(offsetof(struct proc, p_filemon) == 0x3d0,
93 "struct proc KBI p_filemon");
94 _Static_assert(offsetof(struct proc, p_comm) == 0x3e4,
95 "struct proc KBI p_comm");
96 _Static_assert(offsetof(struct proc, p_emuldata) == 0x4b8,
97 "struct proc KBI p_emuldata");
100 _Static_assert(offsetof(struct thread, td_flags) == 0x98,
101 "struct thread KBI td_flags");
102 _Static_assert(offsetof(struct thread, td_pflags) == 0xa0,
103 "struct thread KBI td_pflags");
104 _Static_assert(offsetof(struct thread, td_frame) == 0x2e8,
105 "struct thread KBI td_frame");
106 _Static_assert(offsetof(struct thread, td_emuldata) == 0x334,
107 "struct thread KBI td_emuldata");
108 _Static_assert(offsetof(struct proc, p_flag) == 0x68,
109 "struct proc KBI p_flag");
110 _Static_assert(offsetof(struct proc, p_pid) == 0x74,
111 "struct proc KBI p_pid");
112 _Static_assert(offsetof(struct proc, p_filemon) == 0x27c,
113 "struct proc KBI p_filemon");
114 _Static_assert(offsetof(struct proc, p_comm) == 0x28c,
115 "struct proc KBI p_comm");
116 _Static_assert(offsetof(struct proc, p_emuldata) == 0x318,
117 "struct proc KBI p_emuldata");
120 SDT_PROVIDER_DECLARE(proc);
121 SDT_PROBE_DEFINE(proc, , , lwp__exit);
124 * thread related storage.
126 static uma_zone_t thread_zone;
128 TAILQ_HEAD(, thread) zombie_threads = TAILQ_HEAD_INITIALIZER(zombie_threads);
129 static struct mtx zombie_lock;
130 MTX_SYSINIT(zombie_lock, &zombie_lock, "zombie lock", MTX_SPIN);
132 static void thread_zombie(struct thread *);
133 static int thread_unsuspend_one(struct thread *td, struct proc *p,
136 #define TID_BUFFER_SIZE 1024
139 static struct unrhdr *tid_unrhdr;
140 static lwpid_t tid_buffer[TID_BUFFER_SIZE];
141 static int tid_head, tid_tail;
142 static MALLOC_DEFINE(M_TIDHASH, "tidhash", "thread hash");
144 struct tidhashhead *tidhashtbl;
146 struct rwlock tidhash_lock;
148 EVENTHANDLER_LIST_DEFINE(thread_ctor);
149 EVENTHANDLER_LIST_DEFINE(thread_dtor);
150 EVENTHANDLER_LIST_DEFINE(thread_init);
151 EVENTHANDLER_LIST_DEFINE(thread_fini);
158 tid = alloc_unr(tid_unrhdr);
162 if (tid_head == tid_tail) {
163 mtx_unlock(&tid_lock);
166 tid = tid_buffer[tid_head];
167 tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
168 mtx_unlock(&tid_lock);
173 tid_free(lwpid_t tid)
175 lwpid_t tmp_tid = -1;
178 if ((tid_tail + 1) % TID_BUFFER_SIZE == tid_head) {
179 tmp_tid = tid_buffer[tid_head];
180 tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
182 tid_buffer[tid_tail] = tid;
183 tid_tail = (tid_tail + 1) % TID_BUFFER_SIZE;
184 mtx_unlock(&tid_lock);
186 free_unr(tid_unrhdr, tmp_tid);
190 * Prepare a thread for use.
193 thread_ctor(void *mem, int size, void *arg, int flags)
197 td = (struct thread *)mem;
198 td->td_state = TDS_INACTIVE;
199 td->td_oncpu = NOCPU;
201 td->td_tid = tid_alloc();
204 * Note that td_critnest begins life as 1 because the thread is not
205 * running and is thereby implicitly waiting to be on the receiving
206 * end of a context switch.
209 td->td_lend_user_pri = PRI_MAX;
210 EVENTHANDLER_DIRECT_INVOKE(thread_ctor, td);
212 audit_thread_alloc(td);
214 umtx_thread_alloc(td);
219 * Reclaim a thread after use.
222 thread_dtor(void *mem, int size, void *arg)
226 td = (struct thread *)mem;
229 /* Verify that this thread is in a safe state to free. */
230 switch (td->td_state) {
236 * We must never unlink a thread that is in one of
237 * these states, because it is currently active.
239 panic("bad state for thread unlinking");
244 panic("bad thread state");
249 audit_thread_free(td);
251 /* Free all OSD associated to this thread. */
253 td_softdep_cleanup(td);
254 MPASS(td->td_su == NULL);
256 EVENTHANDLER_DIRECT_INVOKE(thread_dtor, td);
257 tid_free(td->td_tid);
261 * Initialize type-stable parts of a thread (when newly created).
264 thread_init(void *mem, int size, int flags)
268 td = (struct thread *)mem;
270 td->td_sleepqueue = sleepq_alloc();
271 td->td_turnstile = turnstile_alloc();
273 EVENTHANDLER_DIRECT_INVOKE(thread_init, td);
274 umtx_thread_init(td);
281 * Tear down type-stable parts of a thread (just before being discarded).
284 thread_fini(void *mem, int size)
288 td = (struct thread *)mem;
289 EVENTHANDLER_DIRECT_INVOKE(thread_fini, td);
290 rlqentry_free(td->td_rlqe);
291 turnstile_free(td->td_turnstile);
292 sleepq_free(td->td_sleepqueue);
293 umtx_thread_fini(td);
298 * For a newly created process,
299 * link up all the structures and its initial threads etc.
301 * {arch}/{arch}/machdep.c {arch}_init(), init386() etc.
302 * proc_dtor() (should go away)
306 proc_linkup0(struct proc *p, struct thread *td)
308 TAILQ_INIT(&p->p_threads); /* all threads in proc */
313 proc_linkup(struct proc *p, struct thread *td)
316 sigqueue_init(&p->p_sigqueue, p);
317 p->p_ksi = ksiginfo_alloc(1);
318 if (p->p_ksi != NULL) {
319 /* XXX p_ksi may be null if ksiginfo zone is not ready */
320 p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
322 LIST_INIT(&p->p_mqnotifier);
328 * Initialize global thread allocation resources.
334 mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
337 * pid_max cannot be greater than PID_MAX.
338 * leave one number for thread0.
340 tid_unrhdr = new_unrhdr(PID_MAX + 2, INT_MAX, &tid_lock);
342 thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
343 thread_ctor, thread_dtor, thread_init, thread_fini,
344 32 - 1, UMA_ZONE_NOFREE);
345 tidhashtbl = hashinit(maxproc / 2, M_TIDHASH, &tidhash);
346 rw_init(&tidhash_lock, "tidhash");
350 * Place an unused thread on the zombie list.
351 * Use the slpq as that must be unused by now.
354 thread_zombie(struct thread *td)
356 mtx_lock_spin(&zombie_lock);
357 TAILQ_INSERT_HEAD(&zombie_threads, td, td_slpq);
358 mtx_unlock_spin(&zombie_lock);
362 * Release a thread that has exited after cpu_throw().
365 thread_stash(struct thread *td)
367 atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
372 * Reap zombie resources.
377 struct thread *td_first, *td_next;
380 * Don't even bother to lock if none at this instant,
381 * we really don't care about the next instant.
383 if (!TAILQ_EMPTY(&zombie_threads)) {
384 mtx_lock_spin(&zombie_lock);
385 td_first = TAILQ_FIRST(&zombie_threads);
387 TAILQ_INIT(&zombie_threads);
388 mtx_unlock_spin(&zombie_lock);
390 td_next = TAILQ_NEXT(td_first, td_slpq);
391 thread_cow_free(td_first);
392 thread_free(td_first);
402 thread_alloc(int pages)
406 thread_reap(); /* check if any zombies to get */
408 td = (struct thread *)uma_zalloc(thread_zone, M_WAITOK);
409 KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
410 if (!vm_thread_new(td, pages)) {
411 uma_zfree(thread_zone, td);
414 cpu_thread_alloc(td);
419 thread_alloc_stack(struct thread *td, int pages)
422 KASSERT(td->td_kstack == 0,
423 ("thread_alloc_stack called on a thread with kstack"));
424 if (!vm_thread_new(td, pages))
426 cpu_thread_alloc(td);
431 * Deallocate a thread.
434 thread_free(struct thread *td)
437 lock_profile_thread_exit(td);
439 cpuset_rel(td->td_cpuset);
440 td->td_cpuset = NULL;
442 if (td->td_kstack != 0)
443 vm_thread_dispose(td);
444 callout_drain(&td->td_slpcallout);
445 uma_zfree(thread_zone, td);
449 thread_cow_get_proc(struct thread *newtd, struct proc *p)
452 PROC_LOCK_ASSERT(p, MA_OWNED);
453 newtd->td_ucred = crhold(p->p_ucred);
454 newtd->td_limit = lim_hold(p->p_limit);
455 newtd->td_cowgen = p->p_cowgen;
459 thread_cow_get(struct thread *newtd, struct thread *td)
462 newtd->td_ucred = crhold(td->td_ucred);
463 newtd->td_limit = lim_hold(td->td_limit);
464 newtd->td_cowgen = td->td_cowgen;
468 thread_cow_free(struct thread *td)
471 if (td->td_ucred != NULL)
472 crfree(td->td_ucred);
473 if (td->td_limit != NULL)
474 lim_free(td->td_limit);
478 thread_cow_update(struct thread *td)
481 struct ucred *oldcred;
482 struct plimit *oldlimit;
488 if (td->td_ucred != p->p_ucred) {
489 oldcred = td->td_ucred;
490 td->td_ucred = crhold(p->p_ucred);
492 if (td->td_limit != p->p_limit) {
493 oldlimit = td->td_limit;
494 td->td_limit = lim_hold(p->p_limit);
496 td->td_cowgen = p->p_cowgen;
500 if (oldlimit != NULL)
505 * Discard the current thread and exit from its context.
506 * Always called with scheduler locked.
508 * Because we can't free a thread while we're operating under its context,
509 * push the current thread into our CPU's deadthread holder. This means
510 * we needn't worry about someone else grabbing our context before we
516 uint64_t runtime, new_switchtime;
525 PROC_SLOCK_ASSERT(p, MA_OWNED);
526 mtx_assert(&Giant, MA_NOTOWNED);
528 PROC_LOCK_ASSERT(p, MA_OWNED);
529 KASSERT(p != NULL, ("thread exiting without a process"));
530 CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
531 (long)p->p_pid, td->td_name);
532 SDT_PROBE0(proc, , , lwp__exit);
533 KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
536 AUDIT_SYSCALL_EXIT(0, td);
539 * drop FPU & debug register state storage, or any other
540 * architecture specific resources that
541 * would not be on a new untouched process.
546 * The last thread is left attached to the process
547 * So that the whole bundle gets recycled. Skip
548 * all this stuff if we never had threads.
549 * EXIT clears all sign of other threads when
550 * it goes to single threading, so the last thread always
551 * takes the short path.
553 if (p->p_flag & P_HADTHREADS) {
554 if (p->p_numthreads > 1) {
555 atomic_add_int(&td->td_proc->p_exitthreads, 1);
557 td2 = FIRST_THREAD_IN_PROC(p);
558 sched_exit_thread(td2, td);
561 * The test below is NOT true if we are the
562 * sole exiting thread. P_STOPPED_SINGLE is unset
563 * in exit1() after it is the only survivor.
565 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
566 if (p->p_numthreads == p->p_suspcount) {
567 thread_lock(p->p_singlethread);
568 wakeup_swapper = thread_unsuspend_one(
569 p->p_singlethread, p, false);
570 thread_unlock(p->p_singlethread);
576 PCPU_SET(deadthread, td);
579 * The last thread is exiting.. but not through exit()
581 panic ("thread_exit: Last thread exiting on its own");
586 * If this thread is part of a process that is being tracked by hwpmc(4),
587 * inform the module of the thread's impending exit.
589 if (PMC_PROC_IS_USING_PMCS(td->td_proc)) {
590 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
591 PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT, NULL);
599 /* Do the same timestamp bookkeeping that mi_switch() would do. */
600 new_switchtime = cpu_ticks();
601 runtime = new_switchtime - PCPU_GET(switchtime);
602 td->td_runtime += runtime;
603 td->td_incruntime += runtime;
604 PCPU_SET(switchtime, new_switchtime);
605 PCPU_SET(switchticks, ticks);
608 /* Save our resource usage in our process. */
609 td->td_ru.ru_nvcsw++;
611 rucollect(&p->p_ru, &td->td_ru);
614 td->td_state = TDS_INACTIVE;
616 witness_thread_exit(td);
618 CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
620 panic("I'm a teapot!");
625 * Do any thread specific cleanups that may be needed in wait()
626 * called with Giant, proc and schedlock not held.
629 thread_wait(struct proc *p)
633 mtx_assert(&Giant, MA_NOTOWNED);
634 KASSERT(p->p_numthreads == 1, ("multiple threads in thread_wait()"));
635 KASSERT(p->p_exitthreads == 0, ("p_exitthreads leaking"));
636 td = FIRST_THREAD_IN_PROC(p);
637 /* Lock the last thread so we spin until it exits cpu_throw(). */
640 lock_profile_thread_exit(td);
641 cpuset_rel(td->td_cpuset);
642 td->td_cpuset = NULL;
643 cpu_thread_clean(td);
645 callout_drain(&td->td_slpcallout);
646 thread_reap(); /* check for zombie threads etc. */
650 * Link a thread to a process.
651 * set up anything that needs to be initialized for it to
652 * be used by the process.
655 thread_link(struct thread *td, struct proc *p)
659 * XXX This can't be enabled because it's called for proc0 before
660 * its lock has been created.
661 * PROC_LOCK_ASSERT(p, MA_OWNED);
663 td->td_state = TDS_INACTIVE;
665 td->td_flags = TDF_INMEM;
667 LIST_INIT(&td->td_contested);
668 LIST_INIT(&td->td_lprof[0]);
669 LIST_INIT(&td->td_lprof[1]);
670 sigqueue_init(&td->td_sigqueue, p);
671 callout_init(&td->td_slpcallout, 1);
672 TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
681 thread_unlink(struct thread *td)
683 struct proc *p = td->td_proc;
685 PROC_LOCK_ASSERT(p, MA_OWNED);
686 TAILQ_REMOVE(&p->p_threads, td, td_plist);
688 /* could clear a few other things here */
689 /* Must NOT clear links to proc! */
693 calc_remaining(struct proc *p, int mode)
697 PROC_LOCK_ASSERT(p, MA_OWNED);
698 PROC_SLOCK_ASSERT(p, MA_OWNED);
699 if (mode == SINGLE_EXIT)
700 remaining = p->p_numthreads;
701 else if (mode == SINGLE_BOUNDARY)
702 remaining = p->p_numthreads - p->p_boundary_count;
703 else if (mode == SINGLE_NO_EXIT || mode == SINGLE_ALLPROC)
704 remaining = p->p_numthreads - p->p_suspcount;
706 panic("calc_remaining: wrong mode %d", mode);
711 remain_for_mode(int mode)
714 return (mode == SINGLE_ALLPROC ? 0 : 1);
718 weed_inhib(int mode, struct thread *td2, struct proc *p)
722 PROC_LOCK_ASSERT(p, MA_OWNED);
723 PROC_SLOCK_ASSERT(p, MA_OWNED);
724 THREAD_LOCK_ASSERT(td2, MA_OWNED);
729 if (TD_IS_SUSPENDED(td2))
730 wakeup_swapper |= thread_unsuspend_one(td2, p, true);
731 if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0)
732 wakeup_swapper |= sleepq_abort(td2, EINTR);
734 case SINGLE_BOUNDARY:
736 if (TD_IS_SUSPENDED(td2) && (td2->td_flags & TDF_BOUNDARY) == 0)
737 wakeup_swapper |= thread_unsuspend_one(td2, p, false);
738 if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0)
739 wakeup_swapper |= sleepq_abort(td2, ERESTART);
743 * ALLPROC suspend tries to avoid spurious EINTR for
744 * threads sleeping interruptable, by suspending the
745 * thread directly, similarly to sig_suspend_threads().
746 * Since such sleep is not performed at the user
747 * boundary, TDF_BOUNDARY flag is not set, and TDF_ALLPROCSUSP
748 * is used to avoid immediate un-suspend.
750 if (TD_IS_SUSPENDED(td2) && (td2->td_flags & (TDF_BOUNDARY |
751 TDF_ALLPROCSUSP)) == 0)
752 wakeup_swapper |= thread_unsuspend_one(td2, p, false);
753 if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0) {
754 if ((td2->td_flags & TDF_SBDRY) == 0) {
755 thread_suspend_one(td2);
756 td2->td_flags |= TDF_ALLPROCSUSP;
758 wakeup_swapper |= sleepq_abort(td2, ERESTART);
763 return (wakeup_swapper);
767 * Enforce single-threading.
769 * Returns 1 if the caller must abort (another thread is waiting to
770 * exit the process or similar). Process is locked!
771 * Returns 0 when you are successfully the only thread running.
772 * A process has successfully single threaded in the suspend mode when
773 * There are no threads in user mode. Threads in the kernel must be
774 * allowed to continue until they get to the user boundary. They may even
775 * copy out their return values and data before suspending. They may however be
776 * accelerated in reaching the user boundary as we will wake up
777 * any sleeping threads that are interruptable. (PCATCH).
780 thread_single(struct proc *p, int mode)
784 int remaining, wakeup_swapper;
787 KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
788 mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
789 ("invalid mode %d", mode));
791 * If allowing non-ALLPROC singlethreading for non-curproc
792 * callers, calc_remaining() and remain_for_mode() should be
793 * adjusted to also account for td->td_proc != p. For now
794 * this is not implemented because it is not used.
796 KASSERT((mode == SINGLE_ALLPROC && td->td_proc != p) ||
797 (mode != SINGLE_ALLPROC && td->td_proc == p),
798 ("mode %d proc %p curproc %p", mode, p, td->td_proc));
799 mtx_assert(&Giant, MA_NOTOWNED);
800 PROC_LOCK_ASSERT(p, MA_OWNED);
802 if ((p->p_flag & P_HADTHREADS) == 0 && mode != SINGLE_ALLPROC)
805 /* Is someone already single threading? */
806 if (p->p_singlethread != NULL && p->p_singlethread != td)
809 if (mode == SINGLE_EXIT) {
810 p->p_flag |= P_SINGLE_EXIT;
811 p->p_flag &= ~P_SINGLE_BOUNDARY;
813 p->p_flag &= ~P_SINGLE_EXIT;
814 if (mode == SINGLE_BOUNDARY)
815 p->p_flag |= P_SINGLE_BOUNDARY;
817 p->p_flag &= ~P_SINGLE_BOUNDARY;
819 if (mode == SINGLE_ALLPROC)
820 p->p_flag |= P_TOTAL_STOP;
821 p->p_flag |= P_STOPPED_SINGLE;
823 p->p_singlethread = td;
824 remaining = calc_remaining(p, mode);
825 while (remaining != remain_for_mode(mode)) {
826 if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
829 FOREACH_THREAD_IN_PROC(p, td2) {
833 td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
834 if (TD_IS_INHIBITED(td2)) {
835 wakeup_swapper |= weed_inhib(mode, td2, p);
837 } else if (TD_IS_RUNNING(td2) && td != td2) {
845 remaining = calc_remaining(p, mode);
848 * Maybe we suspended some threads.. was it enough?
850 if (remaining == remain_for_mode(mode))
855 * Wake us up when everyone else has suspended.
856 * In the mean time we suspend as well.
858 thread_suspend_switch(td, p);
859 remaining = calc_remaining(p, mode);
861 if (mode == SINGLE_EXIT) {
863 * Convert the process to an unthreaded process. The
864 * SINGLE_EXIT is called by exit1() or execve(), in
865 * both cases other threads must be retired.
867 KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
868 p->p_singlethread = NULL;
869 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
872 * Wait for any remaining threads to exit cpu_throw().
874 while (p->p_exitthreads != 0) {
877 sched_relinquish(td);
881 } else if (mode == SINGLE_BOUNDARY) {
883 * Wait until all suspended threads are removed from
884 * the processors. The thread_suspend_check()
885 * increments p_boundary_count while it is still
886 * running, which makes it possible for the execve()
887 * to destroy vmspace while our other threads are
888 * still using the address space.
890 * We lock the thread, which is only allowed to
891 * succeed after context switch code finished using
894 FOREACH_THREAD_IN_PROC(p, td2) {
898 KASSERT((td2->td_flags & TDF_BOUNDARY) != 0,
899 ("td %p not on boundary", td2));
900 KASSERT(TD_IS_SUSPENDED(td2),
901 ("td %p is not suspended", td2));
910 thread_suspend_check_needed(void)
917 PROC_LOCK_ASSERT(p, MA_OWNED);
918 return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
919 (td->td_dbgflags & TDB_SUSPEND) != 0));
923 * Called in from locations that can safely check to see
924 * whether we have to suspend or at least throttle for a
925 * single-thread event (e.g. fork).
927 * Such locations include userret().
928 * If the "return_instead" argument is non zero, the thread must be able to
929 * accept 0 (caller may continue), or 1 (caller must abort) as a result.
931 * The 'return_instead' argument tells the function if it may do a
932 * thread_exit() or suspend, or whether the caller must abort and back
935 * If the thread that set the single_threading request has set the
936 * P_SINGLE_EXIT bit in the process flags then this call will never return
937 * if 'return_instead' is false, but will exit.
939 * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
940 *---------------+--------------------+---------------------
941 * 0 | returns 0 | returns 0 or 1
942 * | when ST ends | immediately
943 *---------------+--------------------+---------------------
944 * 1 | thread exits | returns 1
946 * 0 = thread_exit() or suspension ok,
947 * other = return error instead of stopping the thread.
949 * While a full suspension is under effect, even a single threading
950 * thread would be suspended if it made this call (but it shouldn't).
951 * This call should only be made from places where
952 * thread_exit() would be safe as that may be the outcome unless
953 * return_instead is set.
956 thread_suspend_check(int return_instead)
964 mtx_assert(&Giant, MA_NOTOWNED);
965 PROC_LOCK_ASSERT(p, MA_OWNED);
966 while (thread_suspend_check_needed()) {
967 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
968 KASSERT(p->p_singlethread != NULL,
969 ("singlethread not set"));
971 * The only suspension in action is a
972 * single-threading. Single threader need not stop.
973 * It is safe to access p->p_singlethread unlocked
974 * because it can only be set to our address by us.
976 if (p->p_singlethread == td)
977 return (0); /* Exempt from stopping. */
979 if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
982 /* Should we goto user boundary if we didn't come from there? */
983 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
984 (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
988 * Ignore suspend requests if they are deferred.
990 if ((td->td_flags & TDF_SBDRY) != 0) {
991 KASSERT(return_instead,
992 ("TDF_SBDRY set for unsafe thread_suspend_check"));
993 KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
994 (TDF_SEINTR | TDF_SERESTART),
995 ("both TDF_SEINTR and TDF_SERESTART"));
996 return (TD_SBDRY_INTR(td) ? TD_SBDRY_ERRNO(td) : 0);
1000 * If the process is waiting for us to exit,
1001 * this thread should just suicide.
1002 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
1004 if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
1008 * Allow Linux emulation layer to do some work
1009 * before thread suicide.
1011 if (__predict_false(p->p_sysent->sv_thread_detach != NULL))
1012 (p->p_sysent->sv_thread_detach)(td);
1013 umtx_thread_exit(td);
1015 panic("stopped thread did not exit");
1020 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1021 if (p->p_numthreads == p->p_suspcount + 1) {
1022 thread_lock(p->p_singlethread);
1023 wakeup_swapper = thread_unsuspend_one(
1024 p->p_singlethread, p, false);
1025 thread_unlock(p->p_singlethread);
1033 * When a thread suspends, it just
1034 * gets taken off all queues.
1036 thread_suspend_one(td);
1037 if (return_instead == 0) {
1038 p->p_boundary_count++;
1039 td->td_flags |= TDF_BOUNDARY;
1042 mi_switch(SW_INVOL | SWT_SUSPEND, NULL);
1050 thread_suspend_switch(struct thread *td, struct proc *p)
1053 KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1054 PROC_LOCK_ASSERT(p, MA_OWNED);
1055 PROC_SLOCK_ASSERT(p, MA_OWNED);
1057 * We implement thread_suspend_one in stages here to avoid
1058 * dropping the proc lock while the thread lock is owned.
1060 if (p == td->td_proc) {
1066 td->td_flags &= ~TDF_NEEDSUSPCHK;
1067 TD_SET_SUSPENDED(td);
1071 mi_switch(SW_VOL | SWT_SUSPEND, NULL);
1079 thread_suspend_one(struct thread *td)
1084 PROC_SLOCK_ASSERT(p, MA_OWNED);
1085 THREAD_LOCK_ASSERT(td, MA_OWNED);
1086 KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1088 td->td_flags &= ~TDF_NEEDSUSPCHK;
1089 TD_SET_SUSPENDED(td);
1094 thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
1097 THREAD_LOCK_ASSERT(td, MA_OWNED);
1098 KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
1099 TD_CLR_SUSPENDED(td);
1100 td->td_flags &= ~TDF_ALLPROCSUSP;
1101 if (td->td_proc == p) {
1102 PROC_SLOCK_ASSERT(p, MA_OWNED);
1104 if (boundary && (td->td_flags & TDF_BOUNDARY) != 0) {
1105 td->td_flags &= ~TDF_BOUNDARY;
1106 p->p_boundary_count--;
1109 return (setrunnable(td));
1113 * Allow all threads blocked by single threading to continue running.
1116 thread_unsuspend(struct proc *p)
1121 PROC_LOCK_ASSERT(p, MA_OWNED);
1122 PROC_SLOCK_ASSERT(p, MA_OWNED);
1124 if (!P_SHOULDSTOP(p)) {
1125 FOREACH_THREAD_IN_PROC(p, td) {
1127 if (TD_IS_SUSPENDED(td)) {
1128 wakeup_swapper |= thread_unsuspend_one(td, p,
1133 } else if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1134 p->p_numthreads == p->p_suspcount) {
1136 * Stopping everything also did the job for the single
1137 * threading request. Now we've downgraded to single-threaded,
1140 if (p->p_singlethread->td_proc == p) {
1141 thread_lock(p->p_singlethread);
1142 wakeup_swapper = thread_unsuspend_one(
1143 p->p_singlethread, p, false);
1144 thread_unlock(p->p_singlethread);
1152 * End the single threading mode..
1155 thread_single_end(struct proc *p, int mode)
1160 KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
1161 mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
1162 ("invalid mode %d", mode));
1163 PROC_LOCK_ASSERT(p, MA_OWNED);
1164 KASSERT((mode == SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) != 0) ||
1165 (mode != SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) == 0),
1166 ("mode %d does not match P_TOTAL_STOP", mode));
1167 KASSERT(mode == SINGLE_ALLPROC || p->p_singlethread == curthread,
1168 ("thread_single_end from other thread %p %p",
1169 curthread, p->p_singlethread));
1170 KASSERT(mode != SINGLE_BOUNDARY ||
1171 (p->p_flag & P_SINGLE_BOUNDARY) != 0,
1172 ("mis-matched SINGLE_BOUNDARY flags %x", p->p_flag));
1173 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY |
1176 p->p_singlethread = NULL;
1179 * If there are other threads they may now run,
1180 * unless of course there is a blanket 'stop order'
1181 * on the process. The single threader must be allowed
1182 * to continue however as this is a bad place to stop.
1184 if (p->p_numthreads != remain_for_mode(mode) && !P_SHOULDSTOP(p)) {
1185 FOREACH_THREAD_IN_PROC(p, td) {
1187 if (TD_IS_SUSPENDED(td)) {
1188 wakeup_swapper |= thread_unsuspend_one(td, p,
1189 mode == SINGLE_BOUNDARY);
1194 KASSERT(mode != SINGLE_BOUNDARY || p->p_boundary_count == 0,
1195 ("inconsistent boundary count %d", p->p_boundary_count));
1202 thread_find(struct proc *p, lwpid_t tid)
1206 PROC_LOCK_ASSERT(p, MA_OWNED);
1207 FOREACH_THREAD_IN_PROC(p, td) {
1208 if (td->td_tid == tid)
1214 /* Locate a thread by number; return with proc lock held. */
1216 tdfind(lwpid_t tid, pid_t pid)
1218 #define RUN_THRESH 16
1222 rw_rlock(&tidhash_lock);
1223 LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1224 if (td->td_tid == tid) {
1225 if (pid != -1 && td->td_proc->p_pid != pid) {
1229 PROC_LOCK(td->td_proc);
1230 if (td->td_proc->p_state == PRS_NEW) {
1231 PROC_UNLOCK(td->td_proc);
1235 if (run > RUN_THRESH) {
1236 if (rw_try_upgrade(&tidhash_lock)) {
1237 LIST_REMOVE(td, td_hash);
1238 LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1240 rw_wunlock(&tidhash_lock);
1248 rw_runlock(&tidhash_lock);
1253 tidhash_add(struct thread *td)
1255 rw_wlock(&tidhash_lock);
1256 LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1257 rw_wunlock(&tidhash_lock);
1261 tidhash_remove(struct thread *td)
1263 rw_wlock(&tidhash_lock);
1264 LIST_REMOVE(td, td_hash);
1265 rw_wunlock(&tidhash_lock);