2 * SPDX-License-Identifier: BSD-2-Clause
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 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/kernel.h>
40 #include <sys/mutex.h>
42 #include <sys/bitstring.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/dtrace_bsd.h>
53 #include <sys/sysent.h>
54 #include <sys/turnstile.h>
55 #include <sys/taskqueue.h>
57 #include <sys/rwlock.h>
58 #include <sys/umtxvar.h>
59 #include <sys/vmmeter.h>
60 #include <sys/cpuset.h>
62 #include <sys/pmckern.h>
66 #include <security/audit/audit.h>
70 #include <vm/vm_extern.h>
72 #include <vm/vm_phys.h>
73 #include <sys/eventhandler.h>
76 * Asserts below verify the stability of struct thread and struct proc
77 * layout, as exposed by KBI to modules. On head, the KBI is allowed
78 * to drift, change to the structures must be accompanied by the
81 * On the stable branches after KBI freeze, conditions must not be
82 * violated. Typically new fields are moved to the end of the
86 _Static_assert(offsetof(struct thread, td_flags) == 0x108,
87 "struct thread KBI td_flags");
88 _Static_assert(offsetof(struct thread, td_pflags) == 0x114,
89 "struct thread KBI td_pflags");
90 _Static_assert(offsetof(struct thread, td_frame) == 0x4b8,
91 "struct thread KBI td_frame");
92 _Static_assert(offsetof(struct thread, td_emuldata) == 0x6c0,
93 "struct thread KBI td_emuldata");
94 _Static_assert(offsetof(struct proc, p_flag) == 0xb8,
95 "struct proc KBI p_flag");
96 _Static_assert(offsetof(struct proc, p_pid) == 0xc4,
97 "struct proc KBI p_pid");
98 _Static_assert(offsetof(struct proc, p_filemon) == 0x3c8,
99 "struct proc KBI p_filemon");
100 _Static_assert(offsetof(struct proc, p_comm) == 0x3e0,
101 "struct proc KBI p_comm");
102 _Static_assert(offsetof(struct proc, p_emuldata) == 0x4d0,
103 "struct proc KBI p_emuldata");
106 _Static_assert(offsetof(struct thread, td_flags) == 0x9c,
107 "struct thread KBI td_flags");
108 _Static_assert(offsetof(struct thread, td_pflags) == 0xa8,
109 "struct thread KBI td_pflags");
110 _Static_assert(offsetof(struct thread, td_frame) == 0x314,
111 "struct thread KBI td_frame");
112 _Static_assert(offsetof(struct thread, td_emuldata) == 0x358,
113 "struct thread KBI td_emuldata");
114 _Static_assert(offsetof(struct proc, p_flag) == 0x6c,
115 "struct proc KBI p_flag");
116 _Static_assert(offsetof(struct proc, p_pid) == 0x78,
117 "struct proc KBI p_pid");
118 _Static_assert(offsetof(struct proc, p_filemon) == 0x270,
119 "struct proc KBI p_filemon");
120 _Static_assert(offsetof(struct proc, p_comm) == 0x284,
121 "struct proc KBI p_comm");
122 _Static_assert(offsetof(struct proc, p_emuldata) == 0x318,
123 "struct proc KBI p_emuldata");
126 SDT_PROVIDER_DECLARE(proc);
127 SDT_PROBE_DEFINE(proc, , , lwp__exit);
130 * thread related storage.
132 static uma_zone_t thread_zone;
134 struct thread_domain_data {
135 struct thread *tdd_zombies;
137 } __aligned(CACHE_LINE_SIZE);
139 static struct thread_domain_data thread_domain_data[MAXMEMDOM];
141 static struct task thread_reap_task;
142 static struct callout thread_reap_callout;
144 static void thread_zombie(struct thread *);
145 static void thread_reap(void);
146 static void thread_reap_all(void);
147 static void thread_reap_task_cb(void *, int);
148 static void thread_reap_callout_cb(void *);
149 static int thread_unsuspend_one(struct thread *td, struct proc *p,
151 static void thread_free_batched(struct thread *td);
153 static __exclusive_cache_line struct mtx tid_lock;
154 static bitstr_t *tid_bitmap;
156 static MALLOC_DEFINE(M_TIDHASH, "tidhash", "thread hash");
158 static int maxthread;
159 SYSCTL_INT(_kern, OID_AUTO, maxthread, CTLFLAG_RDTUN,
160 &maxthread, 0, "Maximum number of threads");
162 static __exclusive_cache_line int nthreads;
164 static LIST_HEAD(tidhashhead, thread) *tidhashtbl;
165 static u_long tidhash;
166 static u_long tidhashlock;
167 static struct rwlock *tidhashtbl_lock;
168 #define TIDHASH(tid) (&tidhashtbl[(tid) & tidhash])
169 #define TIDHASHLOCK(tid) (&tidhashtbl_lock[(tid) & tidhashlock])
171 EVENTHANDLER_LIST_DEFINE(thread_ctor);
172 EVENTHANDLER_LIST_DEFINE(thread_dtor);
173 EVENTHANDLER_LIST_DEFINE(thread_init);
174 EVENTHANDLER_LIST_DEFINE(thread_fini);
177 thread_count_inc_try(void)
181 nthreads_new = atomic_fetchadd_int(&nthreads, 1) + 1;
182 if (nthreads_new >= maxthread - 100) {
183 if (priv_check_cred(curthread->td_ucred, PRIV_MAXPROC) != 0 ||
184 nthreads_new >= maxthread) {
185 atomic_subtract_int(&nthreads, 1);
193 thread_count_inc(void)
195 static struct timeval lastfail;
199 if (thread_count_inc_try()) {
204 if (thread_count_inc_try()) {
208 if (ppsratecheck(&lastfail, &curfail, 1)) {
209 printf("maxthread limit exceeded by uid %u "
210 "(pid %d); consider increasing kern.maxthread\n",
211 curthread->td_ucred->cr_ruid, curproc->p_pid);
217 thread_count_sub(int n)
220 atomic_subtract_int(&nthreads, n);
224 thread_count_dec(void)
233 static lwpid_t trytid;
238 * It is an invariant that the bitmap is big enough to hold maxthread
239 * IDs. If we got to this point there has to be at least one free.
241 if (trytid >= maxthread)
243 bit_ffc_at(tid_bitmap, trytid, maxthread, &tid);
245 KASSERT(trytid != 0, ("unexpectedly ran out of IDs"));
247 bit_ffc_at(tid_bitmap, trytid, maxthread, &tid);
248 KASSERT(tid != -1, ("unexpectedly ran out of IDs"));
250 bit_set(tid_bitmap, tid);
252 mtx_unlock(&tid_lock);
253 return (tid + NO_PID);
257 tid_free_locked(lwpid_t rtid)
261 mtx_assert(&tid_lock, MA_OWNED);
262 KASSERT(rtid >= NO_PID,
263 ("%s: invalid tid %d\n", __func__, rtid));
265 KASSERT(bit_test(tid_bitmap, tid) != 0,
266 ("thread ID %d not allocated\n", rtid));
267 bit_clear(tid_bitmap, tid);
271 tid_free(lwpid_t rtid)
275 tid_free_locked(rtid);
276 mtx_unlock(&tid_lock);
280 tid_free_batch(lwpid_t *batch, int n)
285 for (i = 0; i < n; i++) {
286 tid_free_locked(batch[i]);
288 mtx_unlock(&tid_lock);
292 * Batching for thread reapping.
300 tidbatch_prep(struct tidbatch *tb)
307 tidbatch_add(struct tidbatch *tb, struct thread *td)
310 KASSERT(tb->n < nitems(tb->tab),
311 ("%s: count too high %d", __func__, tb->n));
312 tb->tab[tb->n] = td->td_tid;
317 tidbatch_process(struct tidbatch *tb)
320 KASSERT(tb->n <= nitems(tb->tab),
321 ("%s: count too high %d", __func__, tb->n));
322 if (tb->n == nitems(tb->tab)) {
323 tid_free_batch(tb->tab, tb->n);
329 tidbatch_final(struct tidbatch *tb)
332 KASSERT(tb->n <= nitems(tb->tab),
333 ("%s: count too high %d", __func__, tb->n));
335 tid_free_batch(tb->tab, tb->n);
340 * Batching thread count free, for consistency
342 struct tdcountbatch {
347 tdcountbatch_prep(struct tdcountbatch *tb)
354 tdcountbatch_add(struct tdcountbatch *tb, struct thread *td __unused)
361 tdcountbatch_process(struct tdcountbatch *tb)
365 thread_count_sub(tb->n);
371 tdcountbatch_final(struct tdcountbatch *tb)
375 thread_count_sub(tb->n);
380 * Prepare a thread for use.
383 thread_ctor(void *mem, int size, void *arg, int flags)
387 td = (struct thread *)mem;
388 TD_SET_STATE(td, TDS_INACTIVE);
389 td->td_lastcpu = td->td_oncpu = NOCPU;
392 * Note that td_critnest begins life as 1 because the thread is not
393 * running and is thereby implicitly waiting to be on the receiving
394 * end of a context switch.
397 td->td_lend_user_pri = PRI_MAX;
399 audit_thread_alloc(td);
402 kdtrace_thread_ctor(td);
404 umtx_thread_alloc(td);
405 MPASS(td->td_sel == NULL);
410 * Reclaim a thread after use.
413 thread_dtor(void *mem, int size, void *arg)
417 td = (struct thread *)mem;
420 /* Verify that this thread is in a safe state to free. */
421 switch (TD_GET_STATE(td)) {
427 * We must never unlink a thread that is in one of
428 * these states, because it is currently active.
430 panic("bad state for thread unlinking");
435 panic("bad thread state");
440 audit_thread_free(td);
443 kdtrace_thread_dtor(td);
445 /* Free all OSD associated to this thread. */
452 * Initialize type-stable parts of a thread (when newly created).
455 thread_init(void *mem, int size, int flags)
459 td = (struct thread *)mem;
461 td->td_allocdomain = vm_phys_domain(vtophys(td));
462 td->td_sleepqueue = sleepq_alloc();
463 td->td_turnstile = turnstile_alloc();
465 EVENTHANDLER_DIRECT_INVOKE(thread_init, td);
466 umtx_thread_init(td);
473 * Tear down type-stable parts of a thread (just before being discarded).
476 thread_fini(void *mem, int size)
480 td = (struct thread *)mem;
481 EVENTHANDLER_DIRECT_INVOKE(thread_fini, td);
482 rlqentry_free(td->td_rlqe);
483 turnstile_free(td->td_turnstile);
484 sleepq_free(td->td_sleepqueue);
485 umtx_thread_fini(td);
486 MPASS(td->td_sel == NULL);
490 * For a newly created process,
491 * link up all the structures and its initial threads etc.
493 * {arch}/{arch}/machdep.c {arch}_init(), init386() etc.
494 * proc_dtor() (should go away)
498 proc_linkup0(struct proc *p, struct thread *td)
500 TAILQ_INIT(&p->p_threads); /* all threads in proc */
505 proc_linkup(struct proc *p, struct thread *td)
508 sigqueue_init(&p->p_sigqueue, p);
509 p->p_ksi = ksiginfo_alloc(M_WAITOK);
510 if (p->p_ksi != NULL) {
511 /* XXX p_ksi may be null if ksiginfo zone is not ready */
512 p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
514 LIST_INIT(&p->p_mqnotifier);
520 ast_suspend(struct thread *td, int tda __unused)
526 * We need to check to see if we have to exit or wait due to a
527 * single threading requirement or some other STOP condition.
530 thread_suspend_check(0);
534 extern int max_threads_per_proc;
537 * Initialize global thread allocation resources.
546 * Place an upper limit on threads which can be allocated.
548 * Note that other factors may make the de facto limit much lower.
550 * Platform limits are somewhat arbitrary but deemed "more than good
551 * enough" for the foreseable future.
553 if (maxthread == 0) {
555 maxthread = MIN(maxproc * max_threads_per_proc, 1000000);
557 maxthread = MIN(maxproc * max_threads_per_proc, 100000);
561 mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
562 tid_bitmap = bit_alloc(maxthread, M_TIDHASH, M_WAITOK);
568 if (tid0 != THREAD0_TID)
569 panic("tid0 %d != %d\n", tid0, THREAD0_TID);
571 thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
572 thread_ctor, thread_dtor, thread_init, thread_fini,
573 32 - 1, UMA_ZONE_NOFREE);
574 tidhashtbl = hashinit(maxproc / 2, M_TIDHASH, &tidhash);
575 tidhashlock = (tidhash + 1) / 64;
578 tidhashtbl_lock = malloc(sizeof(*tidhashtbl_lock) * (tidhashlock + 1),
579 M_TIDHASH, M_WAITOK | M_ZERO);
580 for (i = 0; i < tidhashlock + 1; i++)
581 rw_init(&tidhashtbl_lock[i], "tidhash");
583 TASK_INIT(&thread_reap_task, 0, thread_reap_task_cb, NULL);
584 callout_init(&thread_reap_callout, 1);
585 callout_reset(&thread_reap_callout, 5 * hz,
586 thread_reap_callout_cb, NULL);
587 ast_register(TDA_SUSPEND, ASTR_ASTF_REQUIRED, 0, ast_suspend);
591 * Place an unused thread on the zombie list.
594 thread_zombie(struct thread *td)
596 struct thread_domain_data *tdd;
599 tdd = &thread_domain_data[td->td_allocdomain];
600 ztd = atomic_load_ptr(&tdd->tdd_zombies);
603 if (atomic_fcmpset_rel_ptr((uintptr_t *)&tdd->tdd_zombies,
604 (uintptr_t *)&ztd, (uintptr_t)td))
611 * Release a thread that has exited after cpu_throw().
614 thread_stash(struct thread *td)
616 atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
621 * Reap zombies from passed domain.
624 thread_reap_domain(struct thread_domain_data *tdd)
626 struct thread *itd, *ntd;
627 struct tidbatch tidbatch;
628 struct credbatch credbatch;
629 struct limbatch limbatch;
630 struct tdcountbatch tdcountbatch;
633 * Reading upfront is pessimal if followed by concurrent atomic_swap,
634 * but most of the time the list is empty.
636 if (tdd->tdd_zombies == NULL)
639 itd = (struct thread *)atomic_swap_ptr((uintptr_t *)&tdd->tdd_zombies,
645 * Multiple CPUs can get here, the race is fine as ticks is only
648 tdd->tdd_reapticks = ticks;
650 tidbatch_prep(&tidbatch);
651 credbatch_prep(&credbatch);
652 limbatch_prep(&limbatch);
653 tdcountbatch_prep(&tdcountbatch);
655 while (itd != NULL) {
656 ntd = itd->td_zombie;
657 EVENTHANDLER_DIRECT_INVOKE(thread_dtor, itd);
659 tidbatch_add(&tidbatch, itd);
660 credbatch_add(&credbatch, itd);
661 limbatch_add(&limbatch, itd);
662 tdcountbatch_add(&tdcountbatch, itd);
664 thread_free_batched(itd);
666 tidbatch_process(&tidbatch);
667 credbatch_process(&credbatch);
668 limbatch_process(&limbatch);
669 tdcountbatch_process(&tdcountbatch);
674 tidbatch_final(&tidbatch);
675 credbatch_final(&credbatch);
676 limbatch_final(&limbatch);
677 tdcountbatch_final(&tdcountbatch);
681 * Reap zombies from all domains.
684 thread_reap_all(void)
686 struct thread_domain_data *tdd;
689 domain = PCPU_GET(domain);
690 for (i = 0; i < vm_ndomains; i++) {
691 tdd = &thread_domain_data[(i + domain) % vm_ndomains];
692 thread_reap_domain(tdd);
697 * Reap zombies from local domain.
702 struct thread_domain_data *tdd;
705 domain = PCPU_GET(domain);
706 tdd = &thread_domain_data[domain];
708 thread_reap_domain(tdd);
712 thread_reap_task_cb(void *arg __unused, int pending __unused)
719 thread_reap_callout_cb(void *arg __unused)
721 struct thread_domain_data *tdd;
722 int i, cticks, lticks;
726 cticks = atomic_load_int(&ticks);
727 for (i = 0; i < vm_ndomains; i++) {
728 tdd = &thread_domain_data[i];
729 lticks = tdd->tdd_reapticks;
730 if (tdd->tdd_zombies != NULL &&
731 (u_int)(cticks - lticks) > 5 * hz) {
738 taskqueue_enqueue(taskqueue_thread, &thread_reap_task);
739 callout_reset(&thread_reap_callout, 5 * hz,
740 thread_reap_callout_cb, NULL);
744 * Calling this function guarantees that any thread that exited before
745 * the call is reaped when the function returns. By 'exited' we mean
746 * a thread removed from the process linkage with thread_unlink().
747 * Practically this means that caller must lock/unlock corresponding
748 * process lock before the call, to synchronize with thread_exit().
751 thread_reap_barrier(void)
756 * First do context switches to each CPU to ensure that all
757 * PCPU pc_deadthreads are moved to zombie list.
759 quiesce_all_cpus("", PDROP);
762 * Second, fire the task in the same thread as normal
763 * thread_reap() is done, to serialize reaping.
765 t = malloc(sizeof(*t), M_TEMP, M_WAITOK);
766 TASK_INIT(t, 0, thread_reap_task_cb, t);
767 taskqueue_enqueue(taskqueue_thread, t);
768 taskqueue_drain(taskqueue_thread, t);
776 thread_alloc(int pages)
781 if (!thread_count_inc()) {
786 td = uma_zalloc(thread_zone, M_WAITOK);
787 KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
788 if (!vm_thread_new(td, pages)) {
789 uma_zfree(thread_zone, td);
795 bzero(&td->td_sa.args, sizeof(td->td_sa.args));
796 kmsan_thread_alloc(td);
797 cpu_thread_alloc(td);
798 EVENTHANDLER_DIRECT_INVOKE(thread_ctor, td);
803 thread_alloc_stack(struct thread *td, int pages)
806 KASSERT(td->td_kstack == 0,
807 ("thread_alloc_stack called on a thread with kstack"));
808 if (!vm_thread_new(td, pages))
810 cpu_thread_alloc(td);
815 * Deallocate a thread.
818 thread_free_batched(struct thread *td)
821 lock_profile_thread_exit(td);
823 cpuset_rel(td->td_cpuset);
824 td->td_cpuset = NULL;
826 if (td->td_kstack != 0)
827 vm_thread_dispose(td);
828 callout_drain(&td->td_slpcallout);
830 * Freeing handled by the caller.
833 kmsan_thread_free(td);
834 uma_zfree(thread_zone, td);
838 thread_free(struct thread *td)
842 EVENTHANDLER_DIRECT_INVOKE(thread_dtor, td);
844 thread_free_batched(td);
850 thread_cow_get_proc(struct thread *newtd, struct proc *p)
853 PROC_LOCK_ASSERT(p, MA_OWNED);
854 newtd->td_realucred = crcowget(p->p_ucred);
855 newtd->td_ucred = newtd->td_realucred;
856 newtd->td_limit = lim_hold(p->p_limit);
857 newtd->td_cowgen = p->p_cowgen;
861 thread_cow_get(struct thread *newtd, struct thread *td)
864 MPASS(td->td_realucred == td->td_ucred);
865 newtd->td_realucred = crcowget(td->td_realucred);
866 newtd->td_ucred = newtd->td_realucred;
867 newtd->td_limit = lim_hold(td->td_limit);
868 newtd->td_cowgen = td->td_cowgen;
872 thread_cow_free(struct thread *td)
875 if (td->td_realucred != NULL)
877 if (td->td_limit != NULL)
878 lim_free(td->td_limit);
882 thread_cow_update(struct thread *td)
885 struct ucred *oldcred;
886 struct plimit *oldlimit;
890 oldcred = crcowsync();
891 oldlimit = lim_cowsync();
892 td->td_cowgen = p->p_cowgen;
896 if (oldlimit != NULL)
901 thread_cow_synced(struct thread *td)
906 PROC_LOCK_ASSERT(p, MA_OWNED);
907 MPASS(td->td_cowgen != p->p_cowgen);
908 MPASS(td->td_ucred == p->p_ucred);
909 MPASS(td->td_limit == p->p_limit);
910 td->td_cowgen = p->p_cowgen;
914 * Discard the current thread and exit from its context.
915 * Always called with scheduler locked.
917 * Because we can't free a thread while we're operating under its context,
918 * push the current thread into our CPU's deadthread holder. This means
919 * we needn't worry about someone else grabbing our context before we
925 uint64_t runtime, new_switchtime;
934 PROC_SLOCK_ASSERT(p, MA_OWNED);
935 mtx_assert(&Giant, MA_NOTOWNED);
937 PROC_LOCK_ASSERT(p, MA_OWNED);
938 KASSERT(p != NULL, ("thread exiting without a process"));
939 CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
940 (long)p->p_pid, td->td_name);
941 SDT_PROBE0(proc, , , lwp__exit);
942 KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
943 MPASS(td->td_realucred == td->td_ucred);
946 * drop FPU & debug register state storage, or any other
947 * architecture specific resources that
948 * would not be on a new untouched process.
953 * The last thread is left attached to the process
954 * So that the whole bundle gets recycled. Skip
955 * all this stuff if we never had threads.
956 * EXIT clears all sign of other threads when
957 * it goes to single threading, so the last thread always
958 * takes the short path.
960 if (p->p_flag & P_HADTHREADS) {
961 if (p->p_numthreads > 1) {
962 atomic_add_int(&td->td_proc->p_exitthreads, 1);
964 td2 = FIRST_THREAD_IN_PROC(p);
965 sched_exit_thread(td2, td);
968 * The test below is NOT true if we are the
969 * sole exiting thread. P_STOPPED_SINGLE is unset
970 * in exit1() after it is the only survivor.
972 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
973 if (p->p_numthreads == p->p_suspcount) {
974 thread_lock(p->p_singlethread);
975 wakeup_swapper = thread_unsuspend_one(
976 p->p_singlethread, p, false);
982 PCPU_SET(deadthread, td);
985 * The last thread is exiting.. but not through exit()
987 panic ("thread_exit: Last thread exiting on its own");
992 * If this thread is part of a process that is being tracked by hwpmc(4),
993 * inform the module of the thread's impending exit.
995 if (PMC_PROC_IS_USING_PMCS(td->td_proc)) {
996 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
997 PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT, NULL);
998 } else if (PMC_SYSTEM_SAMPLING_ACTIVE())
999 PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT_LOG, NULL);
1006 /* Do the same timestamp bookkeeping that mi_switch() would do. */
1007 new_switchtime = cpu_ticks();
1008 runtime = new_switchtime - PCPU_GET(switchtime);
1009 td->td_runtime += runtime;
1010 td->td_incruntime += runtime;
1011 PCPU_SET(switchtime, new_switchtime);
1012 PCPU_SET(switchticks, ticks);
1013 VM_CNT_INC(v_swtch);
1015 /* Save our resource usage in our process. */
1016 td->td_ru.ru_nvcsw++;
1017 ruxagg_locked(p, td);
1018 rucollect(&p->p_ru, &td->td_ru);
1021 TD_SET_STATE(td, TDS_INACTIVE);
1023 witness_thread_exit(td);
1025 CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
1027 panic("I'm a teapot!");
1032 * Do any thread specific cleanups that may be needed in wait()
1033 * called with Giant, proc and schedlock not held.
1036 thread_wait(struct proc *p)
1040 mtx_assert(&Giant, MA_NOTOWNED);
1041 KASSERT(p->p_numthreads == 1, ("multiple threads in thread_wait()"));
1042 KASSERT(p->p_exitthreads == 0, ("p_exitthreads leaking"));
1043 td = FIRST_THREAD_IN_PROC(p);
1044 /* Lock the last thread so we spin until it exits cpu_throw(). */
1047 lock_profile_thread_exit(td);
1048 cpuset_rel(td->td_cpuset);
1049 td->td_cpuset = NULL;
1050 cpu_thread_clean(td);
1051 thread_cow_free(td);
1052 callout_drain(&td->td_slpcallout);
1053 thread_reap(); /* check for zombie threads etc. */
1057 * Link a thread to a process.
1058 * set up anything that needs to be initialized for it to
1059 * be used by the process.
1062 thread_link(struct thread *td, struct proc *p)
1066 * XXX This can't be enabled because it's called for proc0 before
1067 * its lock has been created.
1068 * PROC_LOCK_ASSERT(p, MA_OWNED);
1070 TD_SET_STATE(td, TDS_INACTIVE);
1072 td->td_flags = TDF_INMEM;
1074 LIST_INIT(&td->td_contested);
1075 LIST_INIT(&td->td_lprof[0]);
1076 LIST_INIT(&td->td_lprof[1]);
1078 SLIST_INIT(&td->td_epochs);
1080 sigqueue_init(&td->td_sigqueue, p);
1081 callout_init(&td->td_slpcallout, 1);
1082 TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
1091 thread_unlink(struct thread *td)
1093 struct proc *p = td->td_proc;
1095 PROC_LOCK_ASSERT(p, MA_OWNED);
1097 MPASS(SLIST_EMPTY(&td->td_epochs));
1100 TAILQ_REMOVE(&p->p_threads, td, td_plist);
1102 /* could clear a few other things here */
1103 /* Must NOT clear links to proc! */
1107 calc_remaining(struct proc *p, int mode)
1111 PROC_LOCK_ASSERT(p, MA_OWNED);
1112 PROC_SLOCK_ASSERT(p, MA_OWNED);
1113 if (mode == SINGLE_EXIT)
1114 remaining = p->p_numthreads;
1115 else if (mode == SINGLE_BOUNDARY)
1116 remaining = p->p_numthreads - p->p_boundary_count;
1117 else if (mode == SINGLE_NO_EXIT || mode == SINGLE_ALLPROC)
1118 remaining = p->p_numthreads - p->p_suspcount;
1120 panic("calc_remaining: wrong mode %d", mode);
1125 remain_for_mode(int mode)
1128 return (mode == SINGLE_ALLPROC ? 0 : 1);
1132 weed_inhib(int mode, struct thread *td2, struct proc *p)
1136 PROC_LOCK_ASSERT(p, MA_OWNED);
1137 PROC_SLOCK_ASSERT(p, MA_OWNED);
1138 THREAD_LOCK_ASSERT(td2, MA_OWNED);
1143 * Since the thread lock is dropped by the scheduler we have
1144 * to retry to check for races.
1149 if (TD_IS_SUSPENDED(td2)) {
1150 wakeup_swapper |= thread_unsuspend_one(td2, p, true);
1154 if (TD_CAN_ABORT(td2)) {
1155 wakeup_swapper |= sleepq_abort(td2, EINTR);
1156 return (wakeup_swapper);
1159 case SINGLE_BOUNDARY:
1160 case SINGLE_NO_EXIT:
1161 if (TD_IS_SUSPENDED(td2) &&
1162 (td2->td_flags & TDF_BOUNDARY) == 0) {
1163 wakeup_swapper |= thread_unsuspend_one(td2, p, false);
1167 if (TD_CAN_ABORT(td2)) {
1168 wakeup_swapper |= sleepq_abort(td2, ERESTART);
1169 return (wakeup_swapper);
1172 case SINGLE_ALLPROC:
1174 * ALLPROC suspend tries to avoid spurious EINTR for
1175 * threads sleeping interruptable, by suspending the
1176 * thread directly, similarly to sig_suspend_threads().
1177 * Since such sleep is not neccessary performed at the user
1178 * boundary, TDF_ALLPROCSUSP is used to avoid immediate
1181 if (TD_IS_SUSPENDED(td2) &&
1182 (td2->td_flags & TDF_ALLPROCSUSP) == 0) {
1183 wakeup_swapper |= thread_unsuspend_one(td2, p, false);
1187 if (TD_CAN_ABORT(td2)) {
1188 td2->td_flags |= TDF_ALLPROCSUSP;
1189 wakeup_swapper |= sleepq_abort(td2, ERESTART);
1190 return (wakeup_swapper);
1197 return (wakeup_swapper);
1201 * Enforce single-threading.
1203 * Returns 1 if the caller must abort (another thread is waiting to
1204 * exit the process or similar). Process is locked!
1205 * Returns 0 when you are successfully the only thread running.
1206 * A process has successfully single threaded in the suspend mode when
1207 * There are no threads in user mode. Threads in the kernel must be
1208 * allowed to continue until they get to the user boundary. They may even
1209 * copy out their return values and data before suspending. They may however be
1210 * accelerated in reaching the user boundary as we will wake up
1211 * any sleeping threads that are interruptable. (PCATCH).
1214 thread_single(struct proc *p, int mode)
1218 int remaining, wakeup_swapper;
1221 KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
1222 mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
1223 ("invalid mode %d", mode));
1225 * If allowing non-ALLPROC singlethreading for non-curproc
1226 * callers, calc_remaining() and remain_for_mode() should be
1227 * adjusted to also account for td->td_proc != p. For now
1228 * this is not implemented because it is not used.
1230 KASSERT((mode == SINGLE_ALLPROC && td->td_proc != p) ||
1231 (mode != SINGLE_ALLPROC && td->td_proc == p),
1232 ("mode %d proc %p curproc %p", mode, p, td->td_proc));
1233 mtx_assert(&Giant, MA_NOTOWNED);
1234 PROC_LOCK_ASSERT(p, MA_OWNED);
1237 * Is someone already single threading?
1238 * Or may be singlethreading is not needed at all.
1240 if (mode == SINGLE_ALLPROC) {
1241 while ((p->p_flag & P_STOPPED_SINGLE) != 0) {
1242 if ((p->p_flag2 & P2_WEXIT) != 0)
1244 msleep(&p->p_flag, &p->p_mtx, PCATCH, "thrsgl", 0);
1246 } else if ((p->p_flag & P_HADTHREADS) == 0)
1248 if (p->p_singlethread != NULL && p->p_singlethread != td)
1251 if (mode == SINGLE_EXIT) {
1252 p->p_flag |= P_SINGLE_EXIT;
1253 p->p_flag &= ~P_SINGLE_BOUNDARY;
1255 p->p_flag &= ~P_SINGLE_EXIT;
1256 if (mode == SINGLE_BOUNDARY)
1257 p->p_flag |= P_SINGLE_BOUNDARY;
1259 p->p_flag &= ~P_SINGLE_BOUNDARY;
1261 if (mode == SINGLE_ALLPROC)
1262 p->p_flag |= P_TOTAL_STOP;
1263 p->p_flag |= P_STOPPED_SINGLE;
1265 p->p_singlethread = td;
1266 remaining = calc_remaining(p, mode);
1267 while (remaining != remain_for_mode(mode)) {
1268 if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
1271 FOREACH_THREAD_IN_PROC(p, td2) {
1275 ast_sched_locked(td2, TDA_SUSPEND);
1276 if (TD_IS_INHIBITED(td2)) {
1277 wakeup_swapper |= weed_inhib(mode, td2, p);
1279 } else if (TD_IS_RUNNING(td2)) {
1280 forward_signal(td2);
1288 remaining = calc_remaining(p, mode);
1291 * Maybe we suspended some threads.. was it enough?
1293 if (remaining == remain_for_mode(mode))
1298 * Wake us up when everyone else has suspended.
1299 * In the mean time we suspend as well.
1301 thread_suspend_switch(td, p);
1302 remaining = calc_remaining(p, mode);
1304 if (mode == SINGLE_EXIT) {
1306 * Convert the process to an unthreaded process. The
1307 * SINGLE_EXIT is called by exit1() or execve(), in
1308 * both cases other threads must be retired.
1310 KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
1311 p->p_singlethread = NULL;
1312 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
1315 * Wait for any remaining threads to exit cpu_throw().
1317 while (p->p_exitthreads != 0) {
1320 sched_relinquish(td);
1324 } else if (mode == SINGLE_BOUNDARY) {
1326 * Wait until all suspended threads are removed from
1327 * the processors. The thread_suspend_check()
1328 * increments p_boundary_count while it is still
1329 * running, which makes it possible for the execve()
1330 * to destroy vmspace while our other threads are
1331 * still using the address space.
1333 * We lock the thread, which is only allowed to
1334 * succeed after context switch code finished using
1335 * the address space.
1337 FOREACH_THREAD_IN_PROC(p, td2) {
1341 KASSERT((td2->td_flags & TDF_BOUNDARY) != 0,
1342 ("td %p not on boundary", td2));
1343 KASSERT(TD_IS_SUSPENDED(td2),
1344 ("td %p is not suspended", td2));
1353 thread_suspend_check_needed(void)
1360 PROC_LOCK_ASSERT(p, MA_OWNED);
1361 return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
1362 (td->td_dbgflags & TDB_SUSPEND) != 0));
1366 * Called in from locations that can safely check to see
1367 * whether we have to suspend or at least throttle for a
1368 * single-thread event (e.g. fork).
1370 * Such locations include userret().
1371 * If the "return_instead" argument is non zero, the thread must be able to
1372 * accept 0 (caller may continue), or 1 (caller must abort) as a result.
1374 * The 'return_instead' argument tells the function if it may do a
1375 * thread_exit() or suspend, or whether the caller must abort and back
1378 * If the thread that set the single_threading request has set the
1379 * P_SINGLE_EXIT bit in the process flags then this call will never return
1380 * if 'return_instead' is false, but will exit.
1382 * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
1383 *---------------+--------------------+---------------------
1384 * 0 | returns 0 | returns 0 or 1
1385 * | when ST ends | immediately
1386 *---------------+--------------------+---------------------
1387 * 1 | thread exits | returns 1
1389 * 0 = thread_exit() or suspension ok,
1390 * other = return error instead of stopping the thread.
1392 * While a full suspension is under effect, even a single threading
1393 * thread would be suspended if it made this call (but it shouldn't).
1394 * This call should only be made from places where
1395 * thread_exit() would be safe as that may be the outcome unless
1396 * return_instead is set.
1399 thread_suspend_check(int return_instead)
1407 mtx_assert(&Giant, MA_NOTOWNED);
1408 PROC_LOCK_ASSERT(p, MA_OWNED);
1409 while (thread_suspend_check_needed()) {
1410 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1411 KASSERT(p->p_singlethread != NULL,
1412 ("singlethread not set"));
1414 * The only suspension in action is a
1415 * single-threading. Single threader need not stop.
1416 * It is safe to access p->p_singlethread unlocked
1417 * because it can only be set to our address by us.
1419 if (p->p_singlethread == td)
1420 return (0); /* Exempt from stopping. */
1422 if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
1425 /* Should we goto user boundary if we didn't come from there? */
1426 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1427 (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
1431 * Ignore suspend requests if they are deferred.
1433 if ((td->td_flags & TDF_SBDRY) != 0) {
1434 KASSERT(return_instead,
1435 ("TDF_SBDRY set for unsafe thread_suspend_check"));
1436 KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
1437 (TDF_SEINTR | TDF_SERESTART),
1438 ("both TDF_SEINTR and TDF_SERESTART"));
1439 return (TD_SBDRY_INTR(td) ? TD_SBDRY_ERRNO(td) : 0);
1443 * If the process is waiting for us to exit,
1444 * this thread should just suicide.
1445 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
1447 if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
1451 * Allow Linux emulation layer to do some work
1452 * before thread suicide.
1454 if (__predict_false(p->p_sysent->sv_thread_detach != NULL))
1455 (p->p_sysent->sv_thread_detach)(td);
1456 umtx_thread_exit(td);
1458 panic("stopped thread did not exit");
1463 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1464 if (p->p_numthreads == p->p_suspcount + 1) {
1465 thread_lock(p->p_singlethread);
1466 wakeup_swapper = thread_unsuspend_one(
1467 p->p_singlethread, p, false);
1475 * When a thread suspends, it just
1476 * gets taken off all queues.
1478 thread_suspend_one(td);
1479 if (return_instead == 0) {
1480 p->p_boundary_count++;
1481 td->td_flags |= TDF_BOUNDARY;
1484 mi_switch(SW_INVOL | SWT_SUSPEND);
1491 * Check for possible stops and suspensions while executing a
1492 * casueword or similar transiently failing operation.
1494 * The sleep argument controls whether the function can handle a stop
1495 * request itself or it should return ERESTART and the request is
1496 * proceed at the kernel/user boundary in ast.
1498 * Typically, when retrying due to casueword(9) failure (rv == 1), we
1499 * should handle the stop requests there, with exception of cases when
1500 * the thread owns a kernel resource, for instance busied the umtx
1501 * key, or when functions return immediately if thread_check_susp()
1502 * returned non-zero. On the other hand, retrying the whole lock
1503 * operation, we better not stop there but delegate the handling to
1506 * If the request is for thread termination P_SINGLE_EXIT, we cannot
1507 * handle it at all, and simply return EINTR.
1510 thread_check_susp(struct thread *td, bool sleep)
1516 * The check for TDA_SUSPEND is racy, but it is enough to
1517 * eventually break the lockstep loop.
1519 if (!td_ast_pending(td, TDA_SUSPEND))
1524 if (p->p_flag & P_SINGLE_EXIT)
1526 else if (P_SHOULDSTOP(p) ||
1527 ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_SUSPEND)))
1528 error = sleep ? thread_suspend_check(0) : ERESTART;
1534 thread_suspend_switch(struct thread *td, struct proc *p)
1537 KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1538 PROC_LOCK_ASSERT(p, MA_OWNED);
1539 PROC_SLOCK_ASSERT(p, MA_OWNED);
1541 * We implement thread_suspend_one in stages here to avoid
1542 * dropping the proc lock while the thread lock is owned.
1544 if (p == td->td_proc) {
1550 ast_unsched_locked(td, TDA_SUSPEND);
1551 TD_SET_SUSPENDED(td);
1555 mi_switch(SW_VOL | SWT_SUSPEND);
1562 thread_suspend_one(struct thread *td)
1567 PROC_SLOCK_ASSERT(p, MA_OWNED);
1568 THREAD_LOCK_ASSERT(td, MA_OWNED);
1569 KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1571 ast_unsched_locked(td, TDA_SUSPEND);
1572 TD_SET_SUSPENDED(td);
1577 thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
1580 THREAD_LOCK_ASSERT(td, MA_OWNED);
1581 KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
1582 TD_CLR_SUSPENDED(td);
1583 td->td_flags &= ~TDF_ALLPROCSUSP;
1584 if (td->td_proc == p) {
1585 PROC_SLOCK_ASSERT(p, MA_OWNED);
1587 if (boundary && (td->td_flags & TDF_BOUNDARY) != 0) {
1588 td->td_flags &= ~TDF_BOUNDARY;
1589 p->p_boundary_count--;
1592 return (setrunnable(td, 0));
1596 thread_run_flash(struct thread *td)
1601 PROC_LOCK_ASSERT(p, MA_OWNED);
1603 if (TD_ON_SLEEPQ(td))
1604 sleepq_remove_nested(td);
1608 THREAD_LOCK_ASSERT(td, MA_OWNED);
1609 KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
1611 TD_CLR_SUSPENDED(td);
1613 MPASS(p->p_suspcount > 0);
1616 if (setrunnable(td, 0))
1621 * Allow all threads blocked by single threading to continue running.
1624 thread_unsuspend(struct proc *p)
1629 PROC_LOCK_ASSERT(p, MA_OWNED);
1630 PROC_SLOCK_ASSERT(p, MA_OWNED);
1632 if (!P_SHOULDSTOP(p)) {
1633 FOREACH_THREAD_IN_PROC(p, td) {
1635 if (TD_IS_SUSPENDED(td))
1636 wakeup_swapper |= thread_unsuspend_one(td, p,
1641 } else if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1642 p->p_numthreads == p->p_suspcount) {
1644 * Stopping everything also did the job for the single
1645 * threading request. Now we've downgraded to single-threaded,
1648 if (p->p_singlethread->td_proc == p) {
1649 thread_lock(p->p_singlethread);
1650 wakeup_swapper = thread_unsuspend_one(
1651 p->p_singlethread, p, false);
1659 * End the single threading mode..
1662 thread_single_end(struct proc *p, int mode)
1667 KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
1668 mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
1669 ("invalid mode %d", mode));
1670 PROC_LOCK_ASSERT(p, MA_OWNED);
1671 KASSERT((mode == SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) != 0) ||
1672 (mode != SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) == 0),
1673 ("mode %d does not match P_TOTAL_STOP", mode));
1674 KASSERT(mode == SINGLE_ALLPROC || p->p_singlethread == curthread,
1675 ("thread_single_end from other thread %p %p",
1676 curthread, p->p_singlethread));
1677 KASSERT(mode != SINGLE_BOUNDARY ||
1678 (p->p_flag & P_SINGLE_BOUNDARY) != 0,
1679 ("mis-matched SINGLE_BOUNDARY flags %x", p->p_flag));
1680 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY |
1683 p->p_singlethread = NULL;
1686 * If there are other threads they may now run,
1687 * unless of course there is a blanket 'stop order'
1688 * on the process. The single threader must be allowed
1689 * to continue however as this is a bad place to stop.
1691 if (p->p_numthreads != remain_for_mode(mode) && !P_SHOULDSTOP(p)) {
1692 FOREACH_THREAD_IN_PROC(p, td) {
1694 if (TD_IS_SUSPENDED(td)) {
1695 wakeup_swapper |= thread_unsuspend_one(td, p,
1701 KASSERT(mode != SINGLE_BOUNDARY || p->p_boundary_count == 0,
1702 ("inconsistent boundary count %d", p->p_boundary_count));
1710 * Locate a thread by number and return with proc lock held.
1712 * thread exit establishes proc -> tidhash lock ordering, but lookup
1713 * takes tidhash first and needs to return locked proc.
1715 * The problem is worked around by relying on type-safety of both
1716 * structures and doing the work in 2 steps:
1717 * - tidhash-locked lookup which saves both thread and proc pointers
1718 * - proc-locked verification that the found thread still matches
1721 tdfind_hash(lwpid_t tid, pid_t pid, struct proc **pp, struct thread **tdp)
1723 #define RUN_THRESH 16
1730 rw_rlock(TIDHASHLOCK(tid));
1732 LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1733 if (td->td_tid != tid) {
1738 if (pid != -1 && p->p_pid != pid) {
1742 if (run > RUN_THRESH) {
1743 if (rw_try_upgrade(TIDHASHLOCK(tid))) {
1744 LIST_REMOVE(td, td_hash);
1745 LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1747 rw_wunlock(TIDHASHLOCK(tid));
1755 rw_runlock(TIDHASHLOCK(tid));
1764 tdfind(lwpid_t tid, pid_t pid)
1770 if (td->td_tid == tid) {
1771 if (pid != -1 && td->td_proc->p_pid != pid)
1773 PROC_LOCK(td->td_proc);
1778 if (!tdfind_hash(tid, pid, &p, &td))
1781 if (td->td_tid != tid) {
1785 if (td->td_proc != p) {
1789 if (p->p_state == PRS_NEW) {
1798 tidhash_add(struct thread *td)
1800 rw_wlock(TIDHASHLOCK(td->td_tid));
1801 LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1802 rw_wunlock(TIDHASHLOCK(td->td_tid));
1806 tidhash_remove(struct thread *td)
1809 rw_wlock(TIDHASHLOCK(td->td_tid));
1810 LIST_REMOVE(td, td_hash);
1811 rw_wunlock(TIDHASHLOCK(td->td_tid));