2 * Copyright (C) 2001 Julian Elischer <julian@freebsd.org>.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice(s), this list of conditions and the following disclaimer as
10 * the first lines of this file unmodified other than the possible
11 * addition of one or more copyright notices.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice(s), this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
29 #include "opt_witness.h"
30 #include "opt_hwpmc_hooks.h"
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
39 #include <sys/mutex.h>
41 #include <sys/rangelock.h>
42 #include <sys/resourcevar.h>
45 #include <sys/sched.h>
46 #include <sys/sleepqueue.h>
47 #include <sys/selinfo.h>
48 #include <sys/syscallsubr.h>
49 #include <sys/sysent.h>
50 #include <sys/turnstile.h>
52 #include <sys/rwlock.h>
54 #include <sys/vmmeter.h>
55 #include <sys/cpuset.h>
57 #include <sys/pmckern.h>
60 #include <security/audit/audit.h>
63 #include <vm/vm_extern.h>
65 #include <vm/vm_domain.h>
66 #include <sys/eventhandler.h>
69 * Asserts below verify the stability of struct thread and struct proc
70 * layout, as exposed by KBI to modules. On head, the KBI is allowed
71 * to drift, change to the structures must be accompanied by the
74 * On the stable branches after KBI freeze, conditions must not be
75 * violated. Typically new fields are moved to the end of the
79 _Static_assert(offsetof(struct thread, td_flags) == 0xf4,
80 "struct thread KBI td_flags");
81 _Static_assert(offsetof(struct thread, td_pflags) == 0xfc,
82 "struct thread KBI td_pflags");
83 _Static_assert(offsetof(struct thread, td_frame) == 0x410,
84 "struct thread KBI td_frame");
85 _Static_assert(offsetof(struct thread, td_emuldata) == 0x4b8,
86 "struct thread KBI td_emuldata");
87 _Static_assert(offsetof(struct proc, p_flag) == 0xb0,
88 "struct proc KBI p_flag");
89 _Static_assert(offsetof(struct proc, p_pid) == 0xbc,
90 "struct proc KBI p_pid");
91 _Static_assert(offsetof(struct proc, p_filemon) == 0x3d0,
92 "struct proc KBI p_filemon");
93 _Static_assert(offsetof(struct proc, p_comm) == 0x3e0,
94 "struct proc KBI p_comm");
95 _Static_assert(offsetof(struct proc, p_emuldata) == 0x4b8,
96 "struct proc KBI p_emuldata");
99 _Static_assert(offsetof(struct thread, td_flags) == 0x9c,
100 "struct thread KBI td_flags");
101 _Static_assert(offsetof(struct thread, td_pflags) == 0xa4,
102 "struct thread KBI td_pflags");
103 _Static_assert(offsetof(struct thread, td_frame) == 0x2c8,
104 "struct thread KBI td_frame");
105 _Static_assert(offsetof(struct thread, td_emuldata) == 0x314,
106 "struct thread KBI td_emuldata");
107 _Static_assert(offsetof(struct proc, p_flag) == 0x68,
108 "struct proc KBI p_flag");
109 _Static_assert(offsetof(struct proc, p_pid) == 0x74,
110 "struct proc KBI p_pid");
111 _Static_assert(offsetof(struct proc, p_filemon) == 0x27c,
112 "struct proc KBI p_filemon");
113 _Static_assert(offsetof(struct proc, p_comm) == 0x288,
114 "struct proc KBI p_comm");
115 _Static_assert(offsetof(struct proc, p_emuldata) == 0x314,
116 "struct proc KBI p_emuldata");
119 SDT_PROVIDER_DECLARE(proc);
120 SDT_PROBE_DEFINE(proc, , , lwp__exit);
123 * thread related storage.
125 static uma_zone_t thread_zone;
127 TAILQ_HEAD(, thread) zombie_threads = TAILQ_HEAD_INITIALIZER(zombie_threads);
128 static struct mtx zombie_lock;
129 MTX_SYSINIT(zombie_lock, &zombie_lock, "zombie lock", MTX_SPIN);
131 static void thread_zombie(struct thread *);
132 static int thread_unsuspend_one(struct thread *td, struct proc *p,
135 #define TID_BUFFER_SIZE 1024
138 static struct unrhdr *tid_unrhdr;
139 static lwpid_t tid_buffer[TID_BUFFER_SIZE];
140 static int tid_head, tid_tail;
141 static MALLOC_DEFINE(M_TIDHASH, "tidhash", "thread hash");
143 struct tidhashhead *tidhashtbl;
145 struct rwlock tidhash_lock;
152 tid = alloc_unr(tid_unrhdr);
156 if (tid_head == tid_tail) {
157 mtx_unlock(&tid_lock);
160 tid = tid_buffer[tid_head];
161 tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
162 mtx_unlock(&tid_lock);
167 tid_free(lwpid_t tid)
169 lwpid_t tmp_tid = -1;
172 if ((tid_tail + 1) % TID_BUFFER_SIZE == tid_head) {
173 tmp_tid = tid_buffer[tid_head];
174 tid_head = (tid_head + 1) % TID_BUFFER_SIZE;
176 tid_buffer[tid_tail] = tid;
177 tid_tail = (tid_tail + 1) % TID_BUFFER_SIZE;
178 mtx_unlock(&tid_lock);
180 free_unr(tid_unrhdr, tmp_tid);
184 * Prepare a thread for use.
187 thread_ctor(void *mem, int size, void *arg, int flags)
191 td = (struct thread *)mem;
192 td->td_state = TDS_INACTIVE;
193 td->td_oncpu = NOCPU;
195 td->td_tid = tid_alloc();
198 * Note that td_critnest begins life as 1 because the thread is not
199 * running and is thereby implicitly waiting to be on the receiving
200 * end of a context switch.
203 td->td_lend_user_pri = PRI_MAX;
204 EVENTHANDLER_INVOKE(thread_ctor, td);
206 audit_thread_alloc(td);
208 umtx_thread_alloc(td);
213 * Reclaim a thread after use.
216 thread_dtor(void *mem, int size, void *arg)
220 td = (struct thread *)mem;
223 /* Verify that this thread is in a safe state to free. */
224 switch (td->td_state) {
230 * We must never unlink a thread that is in one of
231 * these states, because it is currently active.
233 panic("bad state for thread unlinking");
238 panic("bad thread state");
243 audit_thread_free(td);
245 /* Free all OSD associated to this thread. */
247 td_softdep_cleanup(td);
248 MPASS(td->td_su == NULL);
250 EVENTHANDLER_INVOKE(thread_dtor, td);
251 tid_free(td->td_tid);
255 * Initialize type-stable parts of a thread (when newly created).
258 thread_init(void *mem, int size, int flags)
262 td = (struct thread *)mem;
264 td->td_sleepqueue = sleepq_alloc();
265 td->td_turnstile = turnstile_alloc();
267 EVENTHANDLER_INVOKE(thread_init, td);
268 umtx_thread_init(td);
275 * Tear down type-stable parts of a thread (just before being discarded).
278 thread_fini(void *mem, int size)
282 td = (struct thread *)mem;
283 EVENTHANDLER_INVOKE(thread_fini, td);
284 rlqentry_free(td->td_rlqe);
285 turnstile_free(td->td_turnstile);
286 sleepq_free(td->td_sleepqueue);
287 umtx_thread_fini(td);
292 * For a newly created process,
293 * link up all the structures and its initial threads etc.
295 * {arch}/{arch}/machdep.c {arch}_init(), init386() etc.
296 * proc_dtor() (should go away)
300 proc_linkup0(struct proc *p, struct thread *td)
302 TAILQ_INIT(&p->p_threads); /* all threads in proc */
307 proc_linkup(struct proc *p, struct thread *td)
310 sigqueue_init(&p->p_sigqueue, p);
311 p->p_ksi = ksiginfo_alloc(1);
312 if (p->p_ksi != NULL) {
313 /* XXX p_ksi may be null if ksiginfo zone is not ready */
314 p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
316 LIST_INIT(&p->p_mqnotifier);
322 * Initialize global thread allocation resources.
328 mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
331 * pid_max cannot be greater than PID_MAX.
332 * leave one number for thread0.
334 tid_unrhdr = new_unrhdr(PID_MAX + 2, INT_MAX, &tid_lock);
336 thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
337 thread_ctor, thread_dtor, thread_init, thread_fini,
338 32 - 1, UMA_ZONE_NOFREE);
339 tidhashtbl = hashinit(maxproc / 2, M_TIDHASH, &tidhash);
340 rw_init(&tidhash_lock, "tidhash");
344 * Place an unused thread on the zombie list.
345 * Use the slpq as that must be unused by now.
348 thread_zombie(struct thread *td)
350 mtx_lock_spin(&zombie_lock);
351 TAILQ_INSERT_HEAD(&zombie_threads, td, td_slpq);
352 mtx_unlock_spin(&zombie_lock);
356 * Release a thread that has exited after cpu_throw().
359 thread_stash(struct thread *td)
361 atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
366 * Reap zombie resources.
371 struct thread *td_first, *td_next;
374 * Don't even bother to lock if none at this instant,
375 * we really don't care about the next instant.
377 if (!TAILQ_EMPTY(&zombie_threads)) {
378 mtx_lock_spin(&zombie_lock);
379 td_first = TAILQ_FIRST(&zombie_threads);
381 TAILQ_INIT(&zombie_threads);
382 mtx_unlock_spin(&zombie_lock);
384 td_next = TAILQ_NEXT(td_first, td_slpq);
385 thread_cow_free(td_first);
386 thread_free(td_first);
396 thread_alloc(int pages)
400 thread_reap(); /* check if any zombies to get */
402 td = (struct thread *)uma_zalloc(thread_zone, M_WAITOK);
403 KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
404 if (!vm_thread_new(td, pages)) {
405 uma_zfree(thread_zone, td);
408 cpu_thread_alloc(td);
409 vm_domain_policy_init(&td->td_vm_dom_policy);
414 thread_alloc_stack(struct thread *td, int pages)
417 KASSERT(td->td_kstack == 0,
418 ("thread_alloc_stack called on a thread with kstack"));
419 if (!vm_thread_new(td, pages))
421 cpu_thread_alloc(td);
426 * Deallocate a thread.
429 thread_free(struct thread *td)
432 lock_profile_thread_exit(td);
434 cpuset_rel(td->td_cpuset);
435 td->td_cpuset = NULL;
437 if (td->td_kstack != 0)
438 vm_thread_dispose(td);
439 vm_domain_policy_cleanup(&td->td_vm_dom_policy);
440 callout_drain(&td->td_slpcallout);
441 uma_zfree(thread_zone, td);
445 thread_cow_get_proc(struct thread *newtd, struct proc *p)
448 PROC_LOCK_ASSERT(p, MA_OWNED);
449 newtd->td_ucred = crhold(p->p_ucred);
450 newtd->td_limit = lim_hold(p->p_limit);
451 newtd->td_cowgen = p->p_cowgen;
455 thread_cow_get(struct thread *newtd, struct thread *td)
458 newtd->td_ucred = crhold(td->td_ucred);
459 newtd->td_limit = lim_hold(td->td_limit);
460 newtd->td_cowgen = td->td_cowgen;
464 thread_cow_free(struct thread *td)
467 if (td->td_ucred != NULL)
468 crfree(td->td_ucred);
469 if (td->td_limit != NULL)
470 lim_free(td->td_limit);
474 thread_cow_update(struct thread *td)
477 struct ucred *oldcred;
478 struct plimit *oldlimit;
484 if (td->td_ucred != p->p_ucred) {
485 oldcred = td->td_ucred;
486 td->td_ucred = crhold(p->p_ucred);
488 if (td->td_limit != p->p_limit) {
489 oldlimit = td->td_limit;
490 td->td_limit = lim_hold(p->p_limit);
492 td->td_cowgen = p->p_cowgen;
496 if (oldlimit != NULL)
501 * Discard the current thread and exit from its context.
502 * Always called with scheduler locked.
504 * Because we can't free a thread while we're operating under its context,
505 * push the current thread into our CPU's deadthread holder. This means
506 * we needn't worry about someone else grabbing our context before we
512 uint64_t runtime, new_switchtime;
521 PROC_SLOCK_ASSERT(p, MA_OWNED);
522 mtx_assert(&Giant, MA_NOTOWNED);
524 PROC_LOCK_ASSERT(p, MA_OWNED);
525 KASSERT(p != NULL, ("thread exiting without a process"));
526 CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
527 (long)p->p_pid, td->td_name);
528 SDT_PROBE0(proc, , , lwp__exit);
529 KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
532 AUDIT_SYSCALL_EXIT(0, td);
535 * drop FPU & debug register state storage, or any other
536 * architecture specific resources that
537 * would not be on a new untouched process.
542 * The last thread is left attached to the process
543 * So that the whole bundle gets recycled. Skip
544 * all this stuff if we never had threads.
545 * EXIT clears all sign of other threads when
546 * it goes to single threading, so the last thread always
547 * takes the short path.
549 if (p->p_flag & P_HADTHREADS) {
550 if (p->p_numthreads > 1) {
551 atomic_add_int(&td->td_proc->p_exitthreads, 1);
553 td2 = FIRST_THREAD_IN_PROC(p);
554 sched_exit_thread(td2, td);
557 * The test below is NOT true if we are the
558 * sole exiting thread. P_STOPPED_SINGLE is unset
559 * in exit1() after it is the only survivor.
561 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
562 if (p->p_numthreads == p->p_suspcount) {
563 thread_lock(p->p_singlethread);
564 wakeup_swapper = thread_unsuspend_one(
565 p->p_singlethread, p, false);
566 thread_unlock(p->p_singlethread);
572 PCPU_SET(deadthread, td);
575 * The last thread is exiting.. but not through exit()
577 panic ("thread_exit: Last thread exiting on its own");
582 * If this thread is part of a process that is being tracked by hwpmc(4),
583 * inform the module of the thread's impending exit.
585 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
586 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
593 /* Do the same timestamp bookkeeping that mi_switch() would do. */
594 new_switchtime = cpu_ticks();
595 runtime = new_switchtime - PCPU_GET(switchtime);
596 td->td_runtime += runtime;
597 td->td_incruntime += runtime;
598 PCPU_SET(switchtime, new_switchtime);
599 PCPU_SET(switchticks, ticks);
602 /* Save our resource usage in our process. */
603 td->td_ru.ru_nvcsw++;
605 rucollect(&p->p_ru, &td->td_ru);
608 td->td_state = TDS_INACTIVE;
610 witness_thread_exit(td);
612 CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
614 panic("I'm a teapot!");
619 * Do any thread specific cleanups that may be needed in wait()
620 * called with Giant, proc and schedlock not held.
623 thread_wait(struct proc *p)
627 mtx_assert(&Giant, MA_NOTOWNED);
628 KASSERT(p->p_numthreads == 1, ("multiple threads in thread_wait()"));
629 KASSERT(p->p_exitthreads == 0, ("p_exitthreads leaking"));
630 td = FIRST_THREAD_IN_PROC(p);
631 /* Lock the last thread so we spin until it exits cpu_throw(). */
634 lock_profile_thread_exit(td);
635 cpuset_rel(td->td_cpuset);
636 td->td_cpuset = NULL;
637 cpu_thread_clean(td);
639 callout_drain(&td->td_slpcallout);
640 thread_reap(); /* check for zombie threads etc. */
644 * Link a thread to a process.
645 * set up anything that needs to be initialized for it to
646 * be used by the process.
649 thread_link(struct thread *td, struct proc *p)
653 * XXX This can't be enabled because it's called for proc0 before
654 * its lock has been created.
655 * PROC_LOCK_ASSERT(p, MA_OWNED);
657 td->td_state = TDS_INACTIVE;
659 td->td_flags = TDF_INMEM;
661 LIST_INIT(&td->td_contested);
662 LIST_INIT(&td->td_lprof[0]);
663 LIST_INIT(&td->td_lprof[1]);
664 sigqueue_init(&td->td_sigqueue, p);
665 callout_init(&td->td_slpcallout, 1);
666 TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
675 thread_unlink(struct thread *td)
677 struct proc *p = td->td_proc;
679 PROC_LOCK_ASSERT(p, MA_OWNED);
680 TAILQ_REMOVE(&p->p_threads, td, td_plist);
682 /* could clear a few other things here */
683 /* Must NOT clear links to proc! */
687 calc_remaining(struct proc *p, int mode)
691 PROC_LOCK_ASSERT(p, MA_OWNED);
692 PROC_SLOCK_ASSERT(p, MA_OWNED);
693 if (mode == SINGLE_EXIT)
694 remaining = p->p_numthreads;
695 else if (mode == SINGLE_BOUNDARY)
696 remaining = p->p_numthreads - p->p_boundary_count;
697 else if (mode == SINGLE_NO_EXIT || mode == SINGLE_ALLPROC)
698 remaining = p->p_numthreads - p->p_suspcount;
700 panic("calc_remaining: wrong mode %d", mode);
705 remain_for_mode(int mode)
708 return (mode == SINGLE_ALLPROC ? 0 : 1);
712 weed_inhib(int mode, struct thread *td2, struct proc *p)
716 PROC_LOCK_ASSERT(p, MA_OWNED);
717 PROC_SLOCK_ASSERT(p, MA_OWNED);
718 THREAD_LOCK_ASSERT(td2, MA_OWNED);
723 if (TD_IS_SUSPENDED(td2))
724 wakeup_swapper |= thread_unsuspend_one(td2, p, true);
725 if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0)
726 wakeup_swapper |= sleepq_abort(td2, EINTR);
728 case SINGLE_BOUNDARY:
730 if (TD_IS_SUSPENDED(td2) && (td2->td_flags & TDF_BOUNDARY) == 0)
731 wakeup_swapper |= thread_unsuspend_one(td2, p, false);
732 if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0)
733 wakeup_swapper |= sleepq_abort(td2, ERESTART);
737 * ALLPROC suspend tries to avoid spurious EINTR for
738 * threads sleeping interruptable, by suspending the
739 * thread directly, similarly to sig_suspend_threads().
740 * Since such sleep is not performed at the user
741 * boundary, TDF_BOUNDARY flag is not set, and TDF_ALLPROCSUSP
742 * is used to avoid immediate un-suspend.
744 if (TD_IS_SUSPENDED(td2) && (td2->td_flags & (TDF_BOUNDARY |
745 TDF_ALLPROCSUSP)) == 0)
746 wakeup_swapper |= thread_unsuspend_one(td2, p, false);
747 if (TD_ON_SLEEPQ(td2) && (td2->td_flags & TDF_SINTR) != 0) {
748 if ((td2->td_flags & TDF_SBDRY) == 0) {
749 thread_suspend_one(td2);
750 td2->td_flags |= TDF_ALLPROCSUSP;
752 wakeup_swapper |= sleepq_abort(td2, ERESTART);
757 return (wakeup_swapper);
761 * Enforce single-threading.
763 * Returns 1 if the caller must abort (another thread is waiting to
764 * exit the process or similar). Process is locked!
765 * Returns 0 when you are successfully the only thread running.
766 * A process has successfully single threaded in the suspend mode when
767 * There are no threads in user mode. Threads in the kernel must be
768 * allowed to continue until they get to the user boundary. They may even
769 * copy out their return values and data before suspending. They may however be
770 * accelerated in reaching the user boundary as we will wake up
771 * any sleeping threads that are interruptable. (PCATCH).
774 thread_single(struct proc *p, int mode)
778 int remaining, wakeup_swapper;
781 KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
782 mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
783 ("invalid mode %d", mode));
785 * If allowing non-ALLPROC singlethreading for non-curproc
786 * callers, calc_remaining() and remain_for_mode() should be
787 * adjusted to also account for td->td_proc != p. For now
788 * this is not implemented because it is not used.
790 KASSERT((mode == SINGLE_ALLPROC && td->td_proc != p) ||
791 (mode != SINGLE_ALLPROC && td->td_proc == p),
792 ("mode %d proc %p curproc %p", mode, p, td->td_proc));
793 mtx_assert(&Giant, MA_NOTOWNED);
794 PROC_LOCK_ASSERT(p, MA_OWNED);
796 if ((p->p_flag & P_HADTHREADS) == 0 && mode != SINGLE_ALLPROC)
799 /* Is someone already single threading? */
800 if (p->p_singlethread != NULL && p->p_singlethread != td)
803 if (mode == SINGLE_EXIT) {
804 p->p_flag |= P_SINGLE_EXIT;
805 p->p_flag &= ~P_SINGLE_BOUNDARY;
807 p->p_flag &= ~P_SINGLE_EXIT;
808 if (mode == SINGLE_BOUNDARY)
809 p->p_flag |= P_SINGLE_BOUNDARY;
811 p->p_flag &= ~P_SINGLE_BOUNDARY;
813 if (mode == SINGLE_ALLPROC)
814 p->p_flag |= P_TOTAL_STOP;
815 p->p_flag |= P_STOPPED_SINGLE;
817 p->p_singlethread = td;
818 remaining = calc_remaining(p, mode);
819 while (remaining != remain_for_mode(mode)) {
820 if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
823 FOREACH_THREAD_IN_PROC(p, td2) {
827 td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
828 if (TD_IS_INHIBITED(td2)) {
829 wakeup_swapper |= weed_inhib(mode, td2, p);
831 } else if (TD_IS_RUNNING(td2) && td != td2) {
839 remaining = calc_remaining(p, mode);
842 * Maybe we suspended some threads.. was it enough?
844 if (remaining == remain_for_mode(mode))
849 * Wake us up when everyone else has suspended.
850 * In the mean time we suspend as well.
852 thread_suspend_switch(td, p);
853 remaining = calc_remaining(p, mode);
855 if (mode == SINGLE_EXIT) {
857 * Convert the process to an unthreaded process. The
858 * SINGLE_EXIT is called by exit1() or execve(), in
859 * both cases other threads must be retired.
861 KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
862 p->p_singlethread = NULL;
863 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
866 * Wait for any remaining threads to exit cpu_throw().
868 while (p->p_exitthreads != 0) {
871 sched_relinquish(td);
875 } else if (mode == SINGLE_BOUNDARY) {
877 * Wait until all suspended threads are removed from
878 * the processors. The thread_suspend_check()
879 * increments p_boundary_count while it is still
880 * running, which makes it possible for the execve()
881 * to destroy vmspace while our other threads are
882 * still using the address space.
884 * We lock the thread, which is only allowed to
885 * succeed after context switch code finished using
888 FOREACH_THREAD_IN_PROC(p, td2) {
892 KASSERT((td2->td_flags & TDF_BOUNDARY) != 0,
893 ("td %p not on boundary", td2));
894 KASSERT(TD_IS_SUSPENDED(td2),
895 ("td %p is not suspended", td2));
904 thread_suspend_check_needed(void)
911 PROC_LOCK_ASSERT(p, MA_OWNED);
912 return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
913 (td->td_dbgflags & TDB_SUSPEND) != 0));
917 * Called in from locations that can safely check to see
918 * whether we have to suspend or at least throttle for a
919 * single-thread event (e.g. fork).
921 * Such locations include userret().
922 * If the "return_instead" argument is non zero, the thread must be able to
923 * accept 0 (caller may continue), or 1 (caller must abort) as a result.
925 * The 'return_instead' argument tells the function if it may do a
926 * thread_exit() or suspend, or whether the caller must abort and back
929 * If the thread that set the single_threading request has set the
930 * P_SINGLE_EXIT bit in the process flags then this call will never return
931 * if 'return_instead' is false, but will exit.
933 * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
934 *---------------+--------------------+---------------------
935 * 0 | returns 0 | returns 0 or 1
936 * | when ST ends | immediately
937 *---------------+--------------------+---------------------
938 * 1 | thread exits | returns 1
940 * 0 = thread_exit() or suspension ok,
941 * other = return error instead of stopping the thread.
943 * While a full suspension is under effect, even a single threading
944 * thread would be suspended if it made this call (but it shouldn't).
945 * This call should only be made from places where
946 * thread_exit() would be safe as that may be the outcome unless
947 * return_instead is set.
950 thread_suspend_check(int return_instead)
958 mtx_assert(&Giant, MA_NOTOWNED);
959 PROC_LOCK_ASSERT(p, MA_OWNED);
960 while (thread_suspend_check_needed()) {
961 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
962 KASSERT(p->p_singlethread != NULL,
963 ("singlethread not set"));
965 * The only suspension in action is a
966 * single-threading. Single threader need not stop.
967 * It is safe to access p->p_singlethread unlocked
968 * because it can only be set to our address by us.
970 if (p->p_singlethread == td)
971 return (0); /* Exempt from stopping. */
973 if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
976 /* Should we goto user boundary if we didn't come from there? */
977 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
978 (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
982 * Ignore suspend requests if they are deferred.
984 if ((td->td_flags & TDF_SBDRY) != 0) {
985 KASSERT(return_instead,
986 ("TDF_SBDRY set for unsafe thread_suspend_check"));
987 KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
988 (TDF_SEINTR | TDF_SERESTART),
989 ("both TDF_SEINTR and TDF_SERESTART"));
990 return (TD_SBDRY_INTR(td) ? TD_SBDRY_ERRNO(td) : 0);
994 * If the process is waiting for us to exit,
995 * this thread should just suicide.
996 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
998 if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
1002 * Allow Linux emulation layer to do some work
1003 * before thread suicide.
1005 if (__predict_false(p->p_sysent->sv_thread_detach != NULL))
1006 (p->p_sysent->sv_thread_detach)(td);
1007 umtx_thread_exit(td);
1009 panic("stopped thread did not exit");
1014 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1015 if (p->p_numthreads == p->p_suspcount + 1) {
1016 thread_lock(p->p_singlethread);
1017 wakeup_swapper = thread_unsuspend_one(
1018 p->p_singlethread, p, false);
1019 thread_unlock(p->p_singlethread);
1027 * When a thread suspends, it just
1028 * gets taken off all queues.
1030 thread_suspend_one(td);
1031 if (return_instead == 0) {
1032 p->p_boundary_count++;
1033 td->td_flags |= TDF_BOUNDARY;
1036 mi_switch(SW_INVOL | SWT_SUSPEND, NULL);
1044 thread_suspend_switch(struct thread *td, struct proc *p)
1047 KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1048 PROC_LOCK_ASSERT(p, MA_OWNED);
1049 PROC_SLOCK_ASSERT(p, MA_OWNED);
1051 * We implement thread_suspend_one in stages here to avoid
1052 * dropping the proc lock while the thread lock is owned.
1054 if (p == td->td_proc) {
1060 td->td_flags &= ~TDF_NEEDSUSPCHK;
1061 TD_SET_SUSPENDED(td);
1065 mi_switch(SW_VOL | SWT_SUSPEND, NULL);
1073 thread_suspend_one(struct thread *td)
1078 PROC_SLOCK_ASSERT(p, MA_OWNED);
1079 THREAD_LOCK_ASSERT(td, MA_OWNED);
1080 KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1082 td->td_flags &= ~TDF_NEEDSUSPCHK;
1083 TD_SET_SUSPENDED(td);
1088 thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
1091 THREAD_LOCK_ASSERT(td, MA_OWNED);
1092 KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
1093 TD_CLR_SUSPENDED(td);
1094 td->td_flags &= ~TDF_ALLPROCSUSP;
1095 if (td->td_proc == p) {
1096 PROC_SLOCK_ASSERT(p, MA_OWNED);
1098 if (boundary && (td->td_flags & TDF_BOUNDARY) != 0) {
1099 td->td_flags &= ~TDF_BOUNDARY;
1100 p->p_boundary_count--;
1103 return (setrunnable(td));
1107 * Allow all threads blocked by single threading to continue running.
1110 thread_unsuspend(struct proc *p)
1115 PROC_LOCK_ASSERT(p, MA_OWNED);
1116 PROC_SLOCK_ASSERT(p, MA_OWNED);
1118 if (!P_SHOULDSTOP(p)) {
1119 FOREACH_THREAD_IN_PROC(p, td) {
1121 if (TD_IS_SUSPENDED(td)) {
1122 wakeup_swapper |= thread_unsuspend_one(td, p,
1127 } else if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1128 p->p_numthreads == p->p_suspcount) {
1130 * Stopping everything also did the job for the single
1131 * threading request. Now we've downgraded to single-threaded,
1134 if (p->p_singlethread->td_proc == p) {
1135 thread_lock(p->p_singlethread);
1136 wakeup_swapper = thread_unsuspend_one(
1137 p->p_singlethread, p, false);
1138 thread_unlock(p->p_singlethread);
1146 * End the single threading mode..
1149 thread_single_end(struct proc *p, int mode)
1154 KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
1155 mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
1156 ("invalid mode %d", mode));
1157 PROC_LOCK_ASSERT(p, MA_OWNED);
1158 KASSERT((mode == SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) != 0) ||
1159 (mode != SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) == 0),
1160 ("mode %d does not match P_TOTAL_STOP", mode));
1161 KASSERT(mode == SINGLE_ALLPROC || p->p_singlethread == curthread,
1162 ("thread_single_end from other thread %p %p",
1163 curthread, p->p_singlethread));
1164 KASSERT(mode != SINGLE_BOUNDARY ||
1165 (p->p_flag & P_SINGLE_BOUNDARY) != 0,
1166 ("mis-matched SINGLE_BOUNDARY flags %x", p->p_flag));
1167 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY |
1170 p->p_singlethread = NULL;
1173 * If there are other threads they may now run,
1174 * unless of course there is a blanket 'stop order'
1175 * on the process. The single threader must be allowed
1176 * to continue however as this is a bad place to stop.
1178 if (p->p_numthreads != remain_for_mode(mode) && !P_SHOULDSTOP(p)) {
1179 FOREACH_THREAD_IN_PROC(p, td) {
1181 if (TD_IS_SUSPENDED(td)) {
1182 wakeup_swapper |= thread_unsuspend_one(td, p,
1183 mode == SINGLE_BOUNDARY);
1188 KASSERT(mode != SINGLE_BOUNDARY || p->p_boundary_count == 0,
1189 ("inconsistent boundary count %d", p->p_boundary_count));
1196 thread_find(struct proc *p, lwpid_t tid)
1200 PROC_LOCK_ASSERT(p, MA_OWNED);
1201 FOREACH_THREAD_IN_PROC(p, td) {
1202 if (td->td_tid == tid)
1208 /* Locate a thread by number; return with proc lock held. */
1210 tdfind(lwpid_t tid, pid_t pid)
1212 #define RUN_THRESH 16
1216 rw_rlock(&tidhash_lock);
1217 LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1218 if (td->td_tid == tid) {
1219 if (pid != -1 && td->td_proc->p_pid != pid) {
1223 PROC_LOCK(td->td_proc);
1224 if (td->td_proc->p_state == PRS_NEW) {
1225 PROC_UNLOCK(td->td_proc);
1229 if (run > RUN_THRESH) {
1230 if (rw_try_upgrade(&tidhash_lock)) {
1231 LIST_REMOVE(td, td_hash);
1232 LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1234 rw_wunlock(&tidhash_lock);
1242 rw_runlock(&tidhash_lock);
1247 tidhash_add(struct thread *td)
1249 rw_wlock(&tidhash_lock);
1250 LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1251 rw_wunlock(&tidhash_lock);
1255 tidhash_remove(struct thread *td)
1257 rw_wlock(&tidhash_lock);
1258 LIST_REMOVE(td, td_hash);
1259 rw_wunlock(&tidhash_lock);