FreeBSD kernel kern code
kern_thread.c
Go to the documentation of this file.
1/*-
2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3 *
4 * Copyright (C) 2001 Julian Elischer <julian@freebsd.org>.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
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.
17 *
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
28 * DAMAGE.
29 */
30
31#include "opt_witness.h"
32#include "opt_hwpmc_hooks.h"
33
34#include <sys/cdefs.h>
35__FBSDID("$FreeBSD$");
36
37#include <sys/param.h>
38#include <sys/systm.h>
39#include <sys/kernel.h>
40#include <sys/lock.h>
41#include <sys/msan.h>
42#include <sys/mutex.h>
43#include <sys/proc.h>
44#include <sys/bitstring.h>
45#include <sys/epoch.h>
46#include <sys/rangelock.h>
47#include <sys/resourcevar.h>
48#include <sys/sdt.h>
49#include <sys/smp.h>
50#include <sys/sched.h>
51#include <sys/sleepqueue.h>
52#include <sys/selinfo.h>
53#include <sys/syscallsubr.h>
54#include <sys/dtrace_bsd.h>
55#include <sys/sysent.h>
56#include <sys/turnstile.h>
57#include <sys/taskqueue.h>
58#include <sys/ktr.h>
59#include <sys/rwlock.h>
60#include <sys/umtxvar.h>
61#include <sys/vmmeter.h>
62#include <sys/cpuset.h>
63#ifdef HWPMC_HOOKS
64#include <sys/pmckern.h>
65#endif
66#include <sys/priv.h>
67
68#include <security/audit/audit.h>
69
70#include <vm/pmap.h>
71#include <vm/vm.h>
72#include <vm/vm_extern.h>
73#include <vm/uma.h>
74#include <vm/vm_phys.h>
75#include <sys/eventhandler.h>
76
77/*
78 * Asserts below verify the stability of struct thread and struct proc
79 * layout, as exposed by KBI to modules. On head, the KBI is allowed
80 * to drift, change to the structures must be accompanied by the
81 * assert update.
82 *
83 * On the stable branches after KBI freeze, conditions must not be
84 * violated. Typically new fields are moved to the end of the
85 * structures.
86 */
87#ifdef __amd64__
88_Static_assert(offsetof(struct thread, td_flags) == 0x108,
89 "struct thread KBI td_flags");
90_Static_assert(offsetof(struct thread, td_pflags) == 0x110,
91 "struct thread KBI td_pflags");
92_Static_assert(offsetof(struct thread, td_frame) == 0x4a8,
93 "struct thread KBI td_frame");
94_Static_assert(offsetof(struct thread, td_emuldata) == 0x6b0,
95 "struct thread KBI td_emuldata");
96_Static_assert(offsetof(struct proc, p_flag) == 0xb8,
97 "struct proc KBI p_flag");
98_Static_assert(offsetof(struct proc, p_pid) == 0xc4,
99 "struct proc KBI p_pid");
100_Static_assert(offsetof(struct proc, p_filemon) == 0x3c8,
101 "struct proc KBI p_filemon");
102_Static_assert(offsetof(struct proc, p_comm) == 0x3e0,
103 "struct proc KBI p_comm");
104_Static_assert(offsetof(struct proc, p_emuldata) == 0x4c8,
105 "struct proc KBI p_emuldata");
106#endif
107#ifdef __i386__
108_Static_assert(offsetof(struct thread, td_flags) == 0x9c,
109 "struct thread KBI td_flags");
110_Static_assert(offsetof(struct thread, td_pflags) == 0xa4,
111 "struct thread KBI td_pflags");
112_Static_assert(offsetof(struct thread, td_frame) == 0x308,
113 "struct thread KBI td_frame");
114_Static_assert(offsetof(struct thread, td_emuldata) == 0x34c,
115 "struct thread KBI td_emuldata");
116_Static_assert(offsetof(struct proc, p_flag) == 0x6c,
117 "struct proc KBI p_flag");
118_Static_assert(offsetof(struct proc, p_pid) == 0x78,
119 "struct proc KBI p_pid");
120_Static_assert(offsetof(struct proc, p_filemon) == 0x270,
121 "struct proc KBI p_filemon");
122_Static_assert(offsetof(struct proc, p_comm) == 0x284,
123 "struct proc KBI p_comm");
124_Static_assert(offsetof(struct proc, p_emuldata) == 0x310,
125 "struct proc KBI p_emuldata");
126#endif
127
129SDT_PROBE_DEFINE(proc, , , lwp__exit);
130
131/*
132 * thread related storage.
133 */
134static uma_zone_t thread_zone;
135
137 struct thread *tdd_zombies;
139} __aligned(CACHE_LINE_SIZE);
140
141static struct thread_domain_data thread_domain_data[MAXMEMDOM];
142
143static struct task thread_reap_task;
144static struct callout thread_reap_callout;
145
146static void thread_zombie(struct thread *);
147static void thread_reap(void);
148static void thread_reap_all(void);
149static void thread_reap_task_cb(void *, int);
150static void thread_reap_callout_cb(void *);
151static int thread_unsuspend_one(struct thread *td, struct proc *p,
152 bool boundary);
153static void thread_free_batched(struct thread *td);
154
155static __exclusive_cache_line struct mtx tid_lock;
156static bitstr_t *tid_bitmap;
157
158static MALLOC_DEFINE(M_TIDHASH, "tidhash", "thread hash");
159
160static int maxthread;
161SYSCTL_INT(_kern, OID_AUTO, maxthread, CTLFLAG_RDTUN,
162 &maxthread, 0, "Maximum number of threads");
163
164static __exclusive_cache_line int nthreads;
165
166static LIST_HEAD(tidhashhead, thread) *tidhashtbl;
167static u_long tidhash;
168static u_long tidhashlock;
169static struct rwlock *tidhashtbl_lock;
170#define TIDHASH(tid) (&tidhashtbl[(tid) & tidhash])
171#define TIDHASHLOCK(tid) (&tidhashtbl_lock[(tid) & tidhashlock])
172
177
178static bool
179thread_count_inc_try(void)
180{
181 int nthreads_new;
182
183 nthreads_new = atomic_fetchadd_int(&nthreads, 1) + 1;
184 if (nthreads_new >= maxthread - 100) {
185 if (priv_check_cred(curthread->td_ucred, PRIV_MAXPROC) != 0 ||
186 nthreads_new >= maxthread) {
187 atomic_subtract_int(&nthreads, 1);
188 return (false);
189 }
190 }
191 return (true);
192}
193
194static bool
196{
197 static struct timeval lastfail;
198 static int curfail;
199
200 thread_reap();
201 if (thread_count_inc_try()) {
202 return (true);
203 }
204
206 if (thread_count_inc_try()) {
207 return (true);
208 }
209
210 if (ppsratecheck(&lastfail, &curfail, 1)) {
211 printf("maxthread limit exceeded by uid %u "
212 "(pid %d); consider increasing kern.maxthread\n",
213 curthread->td_ucred->cr_ruid, curproc->p_pid);
214 }
215 return (false);
216}
217
218static void
220{
221
222 atomic_subtract_int(&nthreads, n);
223}
224
225static void
227{
228
230}
231
232static lwpid_t
234{
235 static lwpid_t trytid;
236 lwpid_t tid;
237
238 mtx_lock(&tid_lock);
239 /*
240 * It is an invariant that the bitmap is big enough to hold maxthread
241 * IDs. If we got to this point there has to be at least one free.
242 */
243 if (trytid >= maxthread)
244 trytid = 0;
245 bit_ffc_at(tid_bitmap, trytid, maxthread, &tid);
246 if (tid == -1) {
247 KASSERT(trytid != 0, ("unexpectedly ran out of IDs"));
248 trytid = 0;
249 bit_ffc_at(tid_bitmap, trytid, maxthread, &tid);
250 KASSERT(tid != -1, ("unexpectedly ran out of IDs"));
251 }
252 bit_set(tid_bitmap, tid);
253 trytid = tid + 1;
254 mtx_unlock(&tid_lock);
255 return (tid + NO_PID);
256}
257
258static void
259tid_free_locked(lwpid_t rtid)
260{
261 lwpid_t tid;
262
263 mtx_assert(&tid_lock, MA_OWNED);
264 KASSERT(rtid >= NO_PID,
265 ("%s: invalid tid %d\n", __func__, rtid));
266 tid = rtid - NO_PID;
267 KASSERT(bit_test(tid_bitmap, tid) != 0,
268 ("thread ID %d not allocated\n", rtid));
269 bit_clear(tid_bitmap, tid);
270}
271
272static void
273tid_free(lwpid_t rtid)
274{
275
276 mtx_lock(&tid_lock);
277 tid_free_locked(rtid);
278 mtx_unlock(&tid_lock);
279}
280
281static void
282tid_free_batch(lwpid_t *batch, int n)
283{
284 int i;
285
286 mtx_lock(&tid_lock);
287 for (i = 0; i < n; i++) {
288 tid_free_locked(batch[i]);
289 }
290 mtx_unlock(&tid_lock);
291}
292
293/*
294 * Batching for thread reapping.
295 */
296struct tidbatch {
297 lwpid_t tab[16];
298 int n;
300
301static void
303{
304
305 tb->n = 0;
306}
307
308static void
309tidbatch_add(struct tidbatch *tb, struct thread *td)
310{
311
312 KASSERT(tb->n < nitems(tb->tab),
313 ("%s: count too high %d", __func__, tb->n));
314 tb->tab[tb->n] = td->td_tid;
315 tb->n++;
316}
317
318static void
320{
321
322 KASSERT(tb->n <= nitems(tb->tab),
323 ("%s: count too high %d", __func__, tb->n));
324 if (tb->n == nitems(tb->tab)) {
325 tid_free_batch(tb->tab, tb->n);
326 tb->n = 0;
327 }
328}
329
330static void
332{
333
334 KASSERT(tb->n <= nitems(tb->tab),
335 ("%s: count too high %d", __func__, tb->n));
336 if (tb->n != 0) {
337 tid_free_batch(tb->tab, tb->n);
338 }
339}
340
341/*
342 * Prepare a thread for use.
343 */
344static int
345thread_ctor(void *mem, int size, void *arg, int flags)
346{
347 struct thread *td;
348
349 td = (struct thread *)mem;
350 TD_SET_STATE(td, TDS_INACTIVE);
351 td->td_lastcpu = td->td_oncpu = NOCPU;
352
353 /*
354 * Note that td_critnest begins life as 1 because the thread is not
355 * running and is thereby implicitly waiting to be on the receiving
356 * end of a context switch.
357 */
358 td->td_critnest = 1;
359 td->td_lend_user_pri = PRI_MAX;
360#ifdef AUDIT
361 audit_thread_alloc(td);
362#endif
363#ifdef KDTRACE_HOOKS
365#endif
367 MPASS(td->td_sel == NULL);
368 return (0);
369}
370
371/*
372 * Reclaim a thread after use.
373 */
374static void
375thread_dtor(void *mem, int size, void *arg)
376{
377 struct thread *td;
378
379 td = (struct thread *)mem;
380
381#ifdef INVARIANTS
382 /* Verify that this thread is in a safe state to free. */
383 switch (TD_GET_STATE(td)) {
384 case TDS_INHIBITED:
385 case TDS_RUNNING:
386 case TDS_CAN_RUN:
387 case TDS_RUNQ:
388 /*
389 * We must never unlink a thread that is in one of
390 * these states, because it is currently active.
391 */
392 panic("bad state for thread unlinking");
393 /* NOTREACHED */
394 case TDS_INACTIVE:
395 break;
396 default:
397 panic("bad thread state");
398 /* NOTREACHED */
399 }
400#endif
401#ifdef AUDIT
402 audit_thread_free(td);
403#endif
404#ifdef KDTRACE_HOOKS
406#endif
407 /* Free all OSD associated to this thread. */
408 osd_thread_exit(td);
409 td_softdep_cleanup(td);
410 MPASS(td->td_su == NULL);
411 seltdfini(td);
412}
413
414/*
415 * Initialize type-stable parts of a thread (when newly created).
416 */
417static int
418thread_init(void *mem, int size, int flags)
419{
420 struct thread *td;
421
422 td = (struct thread *)mem;
423
424 td->td_allocdomain = vm_phys_domain(vtophys(td));
425 td->td_sleepqueue = sleepq_alloc();
426 td->td_turnstile = turnstile_alloc();
427 td->td_rlqe = NULL;
428 EVENTHANDLER_DIRECT_INVOKE(thread_init, td);
430 td->td_kstack = 0;
431 td->td_sel = NULL;
432 return (0);
433}
434
435/*
436 * Tear down type-stable parts of a thread (just before being discarded).
437 */
438static void
439thread_fini(void *mem, int size)
440{
441 struct thread *td;
442
443 td = (struct thread *)mem;
444 EVENTHANDLER_DIRECT_INVOKE(thread_fini, td);
445 rlqentry_free(td->td_rlqe);
446 turnstile_free(td->td_turnstile);
447 sleepq_free(td->td_sleepqueue);
449 MPASS(td->td_sel == NULL);
450}
451
452/*
453 * For a newly created process,
454 * link up all the structures and its initial threads etc.
455 * called from:
456 * {arch}/{arch}/machdep.c {arch}_init(), init386() etc.
457 * proc_dtor() (should go away)
458 * proc_init()
459 */
460void
461proc_linkup0(struct proc *p, struct thread *td)
462{
463 TAILQ_INIT(&p->p_threads); /* all threads in proc */
464 proc_linkup(p, td);
465}
466
467void
468proc_linkup(struct proc *p, struct thread *td)
469{
470
471 sigqueue_init(&p->p_sigqueue, p);
472 p->p_ksi = ksiginfo_alloc(1);
473 if (p->p_ksi != NULL) {
474 /* XXX p_ksi may be null if ksiginfo zone is not ready */
475 p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
476 }
477 LIST_INIT(&p->p_mqnotifier);
478 p->p_numthreads = 0;
479 thread_link(td, p);
480}
481
482extern int max_threads_per_proc;
483
484/*
485 * Initialize global thread allocation resources.
486 */
487void
489{
490 u_long i;
491 lwpid_t tid0;
492 uint32_t flags;
493
494 /*
495 * Place an upper limit on threads which can be allocated.
496 *
497 * Note that other factors may make the de facto limit much lower.
498 *
499 * Platform limits are somewhat arbitrary but deemed "more than good
500 * enough" for the foreseable future.
501 */
502 if (maxthread == 0) {
503#ifdef _LP64
504 maxthread = MIN(maxproc * max_threads_per_proc, 1000000);
505#else
506 maxthread = MIN(maxproc * max_threads_per_proc, 100000);
507#endif
508 }
509
510 mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
511 tid_bitmap = bit_alloc(maxthread, M_TIDHASH, M_WAITOK);
512 /*
513 * Handle thread0.
514 */
516 tid0 = tid_alloc();
517 if (tid0 != THREAD0_TID)
518 panic("tid0 %d != %d\n", tid0, THREAD0_TID);
519
520 flags = UMA_ZONE_NOFREE;
521#ifdef __aarch64__
522 /*
523 * Force thread structures to be allocated from the direct map.
524 * Otherwise, superpage promotions and demotions may temporarily
525 * invalidate thread structure mappings. For most dynamically allocated
526 * structures this is not a problem, but translation faults cannot be
527 * handled without accessing curthread.
528 */
529 flags |= UMA_ZONE_CONTIG;
530#endif
531 thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
533 32 - 1, flags);
534 tidhashtbl = hashinit(maxproc / 2, M_TIDHASH, &tidhash);
535 tidhashlock = (tidhash + 1) / 64;
536 if (tidhashlock > 0)
537 tidhashlock--;
538 tidhashtbl_lock = malloc(sizeof(*tidhashtbl_lock) * (tidhashlock + 1),
539 M_TIDHASH, M_WAITOK | M_ZERO);
540 for (i = 0; i < tidhashlock + 1; i++)
541 rw_init(&tidhashtbl_lock[i], "tidhash");
542
543 TASK_INIT(&thread_reap_task, 0, thread_reap_task_cb, NULL);
545 callout_reset(&thread_reap_callout, 5 * hz,
547}
548
549/*
550 * Place an unused thread on the zombie list.
551 */
552void
553thread_zombie(struct thread *td)
554{
555 struct thread_domain_data *tdd;
556 struct thread *ztd;
557
558 tdd = &thread_domain_data[td->td_allocdomain];
559 ztd = atomic_load_ptr(&tdd->tdd_zombies);
560 for (;;) {
561 td->td_zombie = ztd;
562 if (atomic_fcmpset_rel_ptr((uintptr_t *)&tdd->tdd_zombies,
563 (uintptr_t *)&ztd, (uintptr_t)td))
564 break;
565 continue;
566 }
567}
568
569/*
570 * Release a thread that has exited after cpu_throw().
571 */
572void
573thread_stash(struct thread *td)
574{
575 atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
576 thread_zombie(td);
577}
578
579/*
580 * Reap zombies from passed domain.
581 */
582static void
584{
585 struct thread *itd, *ntd;
586 struct tidbatch tidbatch;
587 struct credbatch credbatch;
588 int tdcount;
589 struct plimit *lim;
590 int limcount;
591
592 /*
593 * Reading upfront is pessimal if followed by concurrent atomic_swap,
594 * but most of the time the list is empty.
595 */
596 if (tdd->tdd_zombies == NULL)
597 return;
598
599 itd = (struct thread *)atomic_swap_ptr((uintptr_t *)&tdd->tdd_zombies,
600 (uintptr_t)NULL);
601 if (itd == NULL)
602 return;
603
604 /*
605 * Multiple CPUs can get here, the race is fine as ticks is only
606 * advisory.
607 */
608 tdd->tdd_reapticks = ticks;
609
611 credbatch_prep(&credbatch);
612 tdcount = 0;
613 lim = NULL;
614 limcount = 0;
615
616 while (itd != NULL) {
617 ntd = itd->td_zombie;
618 EVENTHANDLER_DIRECT_INVOKE(thread_dtor, itd);
619 tidbatch_add(&tidbatch, itd);
620 credbatch_add(&credbatch, itd);
621 MPASS(itd->td_limit != NULL);
622 if (lim != itd->td_limit) {
623 if (limcount != 0) {
624 lim_freen(lim, limcount);
625 limcount = 0;
626 }
627 }
628 lim = itd->td_limit;
629 limcount++;
632 credbatch_process(&credbatch);
633 tdcount++;
634 if (tdcount == 32) {
635 thread_count_sub(tdcount);
636 tdcount = 0;
637 }
638 itd = ntd;
639 }
640
642 credbatch_final(&credbatch);
643 if (tdcount != 0) {
644 thread_count_sub(tdcount);
645 }
646 MPASS(limcount != 0);
647 lim_freen(lim, limcount);
648}
649
650/*
651 * Reap zombies from all domains.
652 */
653static void
655{
656 struct thread_domain_data *tdd;
657 int i, domain;
658
659 domain = PCPU_GET(domain);
660 for (i = 0; i < vm_ndomains; i++) {
661 tdd = &thread_domain_data[(i + domain) % vm_ndomains];
663 }
664}
665
666/*
667 * Reap zombies from local domain.
668 */
669static void
671{
672 struct thread_domain_data *tdd;
673 int domain;
674
675 domain = PCPU_GET(domain);
677
679}
680
681static void
682thread_reap_task_cb(void *arg __unused, int pending __unused)
683{
684
686}
687
688static void
689thread_reap_callout_cb(void *arg __unused)
690{
691 struct thread_domain_data *tdd;
692 int i, cticks, lticks;
693 bool wantreap;
694
695 wantreap = false;
696 cticks = atomic_load_int(&ticks);
697 for (i = 0; i < vm_ndomains; i++) {
698 tdd = &thread_domain_data[i];
699 lticks = tdd->tdd_reapticks;
700 if (tdd->tdd_zombies != NULL &&
701 (u_int)(cticks - lticks) > 5 * hz) {
702 wantreap = true;
703 break;
704 }
705 }
706
707 if (wantreap)
708 taskqueue_enqueue(taskqueue_thread, &thread_reap_task);
709 callout_reset(&thread_reap_callout, 5 * hz,
711}
712
713/*
714 * Calling this function guarantees that any thread that exited before
715 * the call is reaped when the function returns. By 'exited' we mean
716 * a thread removed from the process linkage with thread_unlink().
717 * Practically this means that caller must lock/unlock corresponding
718 * process lock before the call, to synchronize with thread_exit().
719 */
720void
722{
723 struct task *t;
724
725 /*
726 * First do context switches to each CPU to ensure that all
727 * PCPU pc_deadthreads are moved to zombie list.
728 */
729 quiesce_all_cpus("", PDROP);
730
731 /*
732 * Second, fire the task in the same thread as normal
733 * thread_reap() is done, to serialize reaping.
734 */
735 t = malloc(sizeof(*t), M_TEMP, M_WAITOK);
736 TASK_INIT(t, 0, thread_reap_task_cb, t);
737 taskqueue_enqueue(taskqueue_thread, t);
738 taskqueue_drain(taskqueue_thread, t);
739 free(t, M_TEMP);
740}
741
742/*
743 * Allocate a thread.
744 */
745struct thread *
746thread_alloc(int pages)
747{
748 struct thread *td;
749 lwpid_t tid;
750
751 if (!thread_count_inc()) {
752 return (NULL);
753 }
754
755 tid = tid_alloc();
756 td = uma_zalloc(thread_zone, M_WAITOK);
757 KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
758 if (!vm_thread_new(td, pages)) {
759 uma_zfree(thread_zone, td);
760 tid_free(tid);
762 return (NULL);
763 }
764 td->td_tid = tid;
765 bzero(&td->td_sa.args, sizeof(td->td_sa.args));
767 cpu_thread_alloc(td);
768 EVENTHANDLER_DIRECT_INVOKE(thread_ctor, td);
769 return (td);
770}
771
772int
773thread_alloc_stack(struct thread *td, int pages)
774{
775
776 KASSERT(td->td_kstack == 0,
777 ("thread_alloc_stack called on a thread with kstack"));
778 if (!vm_thread_new(td, pages))
779 return (0);
780 cpu_thread_alloc(td);
781 return (1);
782}
783
784/*
785 * Deallocate a thread.
786 */
787static void
788thread_free_batched(struct thread *td)
789{
790
791 lock_profile_thread_exit(td);
792 if (td->td_cpuset)
793 cpuset_rel(td->td_cpuset);
794 td->td_cpuset = NULL;
795 cpu_thread_free(td);
796 if (td->td_kstack != 0)
797 vm_thread_dispose(td);
798 callout_drain(&td->td_slpcallout);
799 /*
800 * Freeing handled by the caller.
801 */
802 td->td_tid = -1;
804 uma_zfree(thread_zone, td);
805}
806
807void
808thread_free(struct thread *td)
809{
810 lwpid_t tid;
811
812 EVENTHANDLER_DIRECT_INVOKE(thread_dtor, td);
813 tid = td->td_tid;
815 tid_free(tid);
817}
818
819void
820thread_cow_get_proc(struct thread *newtd, struct proc *p)
821{
822
823 PROC_LOCK_ASSERT(p, MA_OWNED);
824 newtd->td_realucred = crcowget(p->p_ucred);
825 newtd->td_ucred = newtd->td_realucred;
826 newtd->td_limit = lim_hold(p->p_limit);
827 newtd->td_cowgen = p->p_cowgen;
828}
829
830void
831thread_cow_get(struct thread *newtd, struct thread *td)
832{
833
834 MPASS(td->td_realucred == td->td_ucred);
835 newtd->td_realucred = crcowget(td->td_realucred);
836 newtd->td_ucred = newtd->td_realucred;
837 newtd->td_limit = lim_hold(td->td_limit);
838 newtd->td_cowgen = td->td_cowgen;
839}
840
841void
842thread_cow_free(struct thread *td)
843{
844
845 if (td->td_realucred != NULL)
846 crcowfree(td);
847 if (td->td_limit != NULL)
848 lim_free(td->td_limit);
849}
850
851void
852thread_cow_update(struct thread *td)
853{
854 struct proc *p;
855 struct ucred *oldcred;
856 struct plimit *oldlimit;
857
858 p = td->td_proc;
859 PROC_LOCK(p);
860 oldcred = crcowsync();
861 oldlimit = lim_cowsync();
862 td->td_cowgen = p->p_cowgen;
863 PROC_UNLOCK(p);
864 if (oldcred != NULL)
865 crfree(oldcred);
866 if (oldlimit != NULL)
867 lim_free(oldlimit);
868}
869
870void
871thread_cow_synced(struct thread *td)
872{
873 struct proc *p;
874
875 p = td->td_proc;
876 PROC_LOCK_ASSERT(p, MA_OWNED);
877 MPASS(td->td_cowgen != p->p_cowgen);
878 MPASS(td->td_ucred == p->p_ucred);
879 MPASS(td->td_limit == p->p_limit);
880 td->td_cowgen = p->p_cowgen;
881}
882
883/*
884 * Discard the current thread and exit from its context.
885 * Always called with scheduler locked.
886 *
887 * Because we can't free a thread while we're operating under its context,
888 * push the current thread into our CPU's deadthread holder. This means
889 * we needn't worry about someone else grabbing our context before we
890 * do a cpu_throw().
891 */
892void
894{
895 uint64_t runtime, new_switchtime;
896 struct thread *td;
897 struct thread *td2;
898 struct proc *p;
899 int wakeup_swapper;
900
901 td = curthread;
902 p = td->td_proc;
903
904 PROC_SLOCK_ASSERT(p, MA_OWNED);
905 mtx_assert(&Giant, MA_NOTOWNED);
906
907 PROC_LOCK_ASSERT(p, MA_OWNED);
908 KASSERT(p != NULL, ("thread exiting without a process"));
909 CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
910 (long)p->p_pid, td->td_name);
911 SDT_PROBE0(proc, , , lwp__exit);
912 KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
913 MPASS(td->td_realucred == td->td_ucred);
914
915 /*
916 * drop FPU & debug register state storage, or any other
917 * architecture specific resources that
918 * would not be on a new untouched process.
919 */
920 cpu_thread_exit(td);
921
922 /*
923 * The last thread is left attached to the process
924 * So that the whole bundle gets recycled. Skip
925 * all this stuff if we never had threads.
926 * EXIT clears all sign of other threads when
927 * it goes to single threading, so the last thread always
928 * takes the short path.
929 */
930 if (p->p_flag & P_HADTHREADS) {
931 if (p->p_numthreads > 1) {
932 atomic_add_int(&td->td_proc->p_exitthreads, 1);
933 thread_unlink(td);
934 td2 = FIRST_THREAD_IN_PROC(p);
935 sched_exit_thread(td2, td);
936
937 /*
938 * The test below is NOT true if we are the
939 * sole exiting thread. P_STOPPED_SINGLE is unset
940 * in exit1() after it is the only survivor.
941 */
942 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
943 if (p->p_numthreads == p->p_suspcount) {
944 thread_lock(p->p_singlethread);
945 wakeup_swapper = thread_unsuspend_one(
946 p->p_singlethread, p, false);
947 if (wakeup_swapper)
948 kick_proc0();
949 }
950 }
951
952 PCPU_SET(deadthread, td);
953 } else {
954 /*
955 * The last thread is exiting.. but not through exit()
956 */
957 panic ("thread_exit: Last thread exiting on its own");
958 }
959 }
960#ifdef HWPMC_HOOKS
961 /*
962 * If this thread is part of a process that is being tracked by hwpmc(4),
963 * inform the module of the thread's impending exit.
964 */
965 if (PMC_PROC_IS_USING_PMCS(td->td_proc)) {
966 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
967 PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT, NULL);
968 } else if (PMC_SYSTEM_SAMPLING_ACTIVE())
969 PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT_LOG, NULL);
970#endif
971 PROC_UNLOCK(p);
972 PROC_STATLOCK(p);
973 thread_lock(td);
974 PROC_SUNLOCK(p);
975
976 /* Do the same timestamp bookkeeping that mi_switch() would do. */
977 new_switchtime = cpu_ticks();
978 runtime = new_switchtime - PCPU_GET(switchtime);
979 td->td_runtime += runtime;
980 td->td_incruntime += runtime;
981 PCPU_SET(switchtime, new_switchtime);
982 PCPU_SET(switchticks, ticks);
983 VM_CNT_INC(v_swtch);
984
985 /* Save our resource usage in our process. */
986 td->td_ru.ru_nvcsw++;
987 ruxagg_locked(p, td);
988 rucollect(&p->p_ru, &td->td_ru);
989 PROC_STATUNLOCK(p);
990
991 TD_SET_STATE(td, TDS_INACTIVE);
992#ifdef WITNESS
994#endif
995 CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
996 sched_throw(td);
997 panic("I'm a teapot!");
998 /* NOTREACHED */
999}
1000
1001/*
1002 * Do any thread specific cleanups that may be needed in wait()
1003 * called with Giant, proc and schedlock not held.
1004 */
1005void
1006thread_wait(struct proc *p)
1007{
1008 struct thread *td;
1009
1010 mtx_assert(&Giant, MA_NOTOWNED);
1011 KASSERT(p->p_numthreads == 1, ("multiple threads in thread_wait()"));
1012 KASSERT(p->p_exitthreads == 0, ("p_exitthreads leaking"));
1013 td = FIRST_THREAD_IN_PROC(p);
1014 /* Lock the last thread so we spin until it exits cpu_throw(). */
1015 thread_lock(td);
1016 thread_unlock(td);
1017 lock_profile_thread_exit(td);
1018 cpuset_rel(td->td_cpuset);
1019 td->td_cpuset = NULL;
1020 cpu_thread_clean(td);
1021 thread_cow_free(td);
1022 callout_drain(&td->td_slpcallout);
1023 thread_reap(); /* check for zombie threads etc. */
1024}
1025
1026/*
1027 * Link a thread to a process.
1028 * set up anything that needs to be initialized for it to
1029 * be used by the process.
1030 */
1031void
1032thread_link(struct thread *td, struct proc *p)
1033{
1034
1035 /*
1036 * XXX This can't be enabled because it's called for proc0 before
1037 * its lock has been created.
1038 * PROC_LOCK_ASSERT(p, MA_OWNED);
1039 */
1040 TD_SET_STATE(td, TDS_INACTIVE);
1041 td->td_proc = p;
1042 td->td_flags = TDF_INMEM;
1043
1044 LIST_INIT(&td->td_contested);
1045 LIST_INIT(&td->td_lprof[0]);
1046 LIST_INIT(&td->td_lprof[1]);
1047#ifdef EPOCH_TRACE
1048 SLIST_INIT(&td->td_epochs);
1049#endif
1050 sigqueue_init(&td->td_sigqueue, p);
1051 callout_init(&td->td_slpcallout, 1);
1052 TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
1053 p->p_numthreads++;
1054}
1055
1056/*
1057 * Called from:
1058 * thread_exit()
1059 */
1060void
1061thread_unlink(struct thread *td)
1062{
1063 struct proc *p = td->td_proc;
1064
1065 PROC_LOCK_ASSERT(p, MA_OWNED);
1066#ifdef EPOCH_TRACE
1067 MPASS(SLIST_EMPTY(&td->td_epochs));
1068#endif
1069
1070 TAILQ_REMOVE(&p->p_threads, td, td_plist);
1071 p->p_numthreads--;
1072 /* could clear a few other things here */
1073 /* Must NOT clear links to proc! */
1074}
1075
1076static int
1077calc_remaining(struct proc *p, int mode)
1078{
1079 int remaining;
1080
1081 PROC_LOCK_ASSERT(p, MA_OWNED);
1082 PROC_SLOCK_ASSERT(p, MA_OWNED);
1083 if (mode == SINGLE_EXIT)
1084 remaining = p->p_numthreads;
1085 else if (mode == SINGLE_BOUNDARY)
1086 remaining = p->p_numthreads - p->p_boundary_count;
1087 else if (mode == SINGLE_NO_EXIT || mode == SINGLE_ALLPROC)
1088 remaining = p->p_numthreads - p->p_suspcount;
1089 else
1090 panic("calc_remaining: wrong mode %d", mode);
1091 return (remaining);
1092}
1093
1094static int
1096{
1097
1098 return (mode == SINGLE_ALLPROC ? 0 : 1);
1099}
1100
1101static int
1102weed_inhib(int mode, struct thread *td2, struct proc *p)
1103{
1104 int wakeup_swapper;
1105
1106 PROC_LOCK_ASSERT(p, MA_OWNED);
1107 PROC_SLOCK_ASSERT(p, MA_OWNED);
1108 THREAD_LOCK_ASSERT(td2, MA_OWNED);
1109
1110 wakeup_swapper = 0;
1111
1112 /*
1113 * Since the thread lock is dropped by the scheduler we have
1114 * to retry to check for races.
1115 */
1116restart:
1117 switch (mode) {
1118 case SINGLE_EXIT:
1119 if (TD_IS_SUSPENDED(td2)) {
1120 wakeup_swapper |= thread_unsuspend_one(td2, p, true);
1121 thread_lock(td2);
1122 goto restart;
1123 }
1124 if (TD_CAN_ABORT(td2)) {
1125 wakeup_swapper |= sleepq_abort(td2, EINTR);
1126 return (wakeup_swapper);
1127 }
1128 break;
1129 case SINGLE_BOUNDARY:
1130 case SINGLE_NO_EXIT:
1131 if (TD_IS_SUSPENDED(td2) &&
1132 (td2->td_flags & TDF_BOUNDARY) == 0) {
1133 wakeup_swapper |= thread_unsuspend_one(td2, p, false);
1134 thread_lock(td2);
1135 goto restart;
1136 }
1137 if (TD_CAN_ABORT(td2)) {
1138 wakeup_swapper |= sleepq_abort(td2, ERESTART);
1139 return (wakeup_swapper);
1140 }
1141 break;
1142 case SINGLE_ALLPROC:
1143 /*
1144 * ALLPROC suspend tries to avoid spurious EINTR for
1145 * threads sleeping interruptable, by suspending the
1146 * thread directly, similarly to sig_suspend_threads().
1147 * Since such sleep is not performed at the user
1148 * boundary, TDF_BOUNDARY flag is not set, and TDF_ALLPROCSUSP
1149 * is used to avoid immediate un-suspend.
1150 */
1151 if (TD_IS_SUSPENDED(td2) && (td2->td_flags & (TDF_BOUNDARY |
1152 TDF_ALLPROCSUSP)) == 0) {
1153 wakeup_swapper |= thread_unsuspend_one(td2, p, false);
1154 thread_lock(td2);
1155 goto restart;
1156 }
1157 if (TD_CAN_ABORT(td2)) {
1158 if ((td2->td_flags & TDF_SBDRY) == 0) {
1159 thread_suspend_one(td2);
1160 td2->td_flags |= TDF_ALLPROCSUSP;
1161 } else {
1162 wakeup_swapper |= sleepq_abort(td2, ERESTART);
1163 return (wakeup_swapper);
1164 }
1165 }
1166 break;
1167 default:
1168 break;
1169 }
1170 thread_unlock(td2);
1171 return (wakeup_swapper);
1172}
1173
1174/*
1175 * Enforce single-threading.
1176 *
1177 * Returns 1 if the caller must abort (another thread is waiting to
1178 * exit the process or similar). Process is locked!
1179 * Returns 0 when you are successfully the only thread running.
1180 * A process has successfully single threaded in the suspend mode when
1181 * There are no threads in user mode. Threads in the kernel must be
1182 * allowed to continue until they get to the user boundary. They may even
1183 * copy out their return values and data before suspending. They may however be
1184 * accelerated in reaching the user boundary as we will wake up
1185 * any sleeping threads that are interruptable. (PCATCH).
1186 */
1187int
1188thread_single(struct proc *p, int mode)
1189{
1190 struct thread *td;
1191 struct thread *td2;
1192 int remaining, wakeup_swapper;
1193
1194 td = curthread;
1195 KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
1196 mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
1197 ("invalid mode %d", mode));
1198 /*
1199 * If allowing non-ALLPROC singlethreading for non-curproc
1200 * callers, calc_remaining() and remain_for_mode() should be
1201 * adjusted to also account for td->td_proc != p. For now
1202 * this is not implemented because it is not used.
1203 */
1204 KASSERT((mode == SINGLE_ALLPROC && td->td_proc != p) ||
1205 (mode != SINGLE_ALLPROC && td->td_proc == p),
1206 ("mode %d proc %p curproc %p", mode, p, td->td_proc));
1207 mtx_assert(&Giant, MA_NOTOWNED);
1208 PROC_LOCK_ASSERT(p, MA_OWNED);
1209
1210 if ((p->p_flag & P_HADTHREADS) == 0 && mode != SINGLE_ALLPROC)
1211 return (0);
1212
1213 /* Is someone already single threading? */
1214 if (p->p_singlethread != NULL && p->p_singlethread != td)
1215 return (1);
1216
1217 if (mode == SINGLE_EXIT) {
1218 p->p_flag |= P_SINGLE_EXIT;
1219 p->p_flag &= ~P_SINGLE_BOUNDARY;
1220 } else {
1221 p->p_flag &= ~P_SINGLE_EXIT;
1222 if (mode == SINGLE_BOUNDARY)
1223 p->p_flag |= P_SINGLE_BOUNDARY;
1224 else
1225 p->p_flag &= ~P_SINGLE_BOUNDARY;
1226 }
1227 if (mode == SINGLE_ALLPROC)
1228 p->p_flag |= P_TOTAL_STOP;
1229 p->p_flag |= P_STOPPED_SINGLE;
1230 PROC_SLOCK(p);
1231 p->p_singlethread = td;
1232 remaining = calc_remaining(p, mode);
1233 while (remaining != remain_for_mode(mode)) {
1234 if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
1235 goto stopme;
1236 wakeup_swapper = 0;
1237 FOREACH_THREAD_IN_PROC(p, td2) {
1238 if (td2 == td)
1239 continue;
1240 thread_lock(td2);
1241 td2->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
1242 if (TD_IS_INHIBITED(td2)) {
1243 wakeup_swapper |= weed_inhib(mode, td2, p);
1244#ifdef SMP
1245 } else if (TD_IS_RUNNING(td2) && td != td2) {
1246 forward_signal(td2);
1247 thread_unlock(td2);
1248#endif
1249 } else
1250 thread_unlock(td2);
1251 }
1252 if (wakeup_swapper)
1253 kick_proc0();
1254 remaining = calc_remaining(p, mode);
1255
1256 /*
1257 * Maybe we suspended some threads.. was it enough?
1258 */
1259 if (remaining == remain_for_mode(mode))
1260 break;
1261
1262stopme:
1263 /*
1264 * Wake us up when everyone else has suspended.
1265 * In the mean time we suspend as well.
1266 */
1267 thread_suspend_switch(td, p);
1268 remaining = calc_remaining(p, mode);
1269 }
1270 if (mode == SINGLE_EXIT) {
1271 /*
1272 * Convert the process to an unthreaded process. The
1273 * SINGLE_EXIT is called by exit1() or execve(), in
1274 * both cases other threads must be retired.
1275 */
1276 KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
1277 p->p_singlethread = NULL;
1278 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
1279
1280 /*
1281 * Wait for any remaining threads to exit cpu_throw().
1282 */
1283 while (p->p_exitthreads != 0) {
1284 PROC_SUNLOCK(p);
1285 PROC_UNLOCK(p);
1286 sched_relinquish(td);
1287 PROC_LOCK(p);
1288 PROC_SLOCK(p);
1289 }
1290 } else if (mode == SINGLE_BOUNDARY) {
1291 /*
1292 * Wait until all suspended threads are removed from
1293 * the processors. The thread_suspend_check()
1294 * increments p_boundary_count while it is still
1295 * running, which makes it possible for the execve()
1296 * to destroy vmspace while our other threads are
1297 * still using the address space.
1298 *
1299 * We lock the thread, which is only allowed to
1300 * succeed after context switch code finished using
1301 * the address space.
1302 */
1303 FOREACH_THREAD_IN_PROC(p, td2) {
1304 if (td2 == td)
1305 continue;
1306 thread_lock(td2);
1307 KASSERT((td2->td_flags & TDF_BOUNDARY) != 0,
1308 ("td %p not on boundary", td2));
1309 KASSERT(TD_IS_SUSPENDED(td2),
1310 ("td %p is not suspended", td2));
1311 thread_unlock(td2);
1312 }
1313 }
1314 PROC_SUNLOCK(p);
1315 return (0);
1316}
1317
1318bool
1320{
1321 struct proc *p;
1322 struct thread *td;
1323
1324 td = curthread;
1325 p = td->td_proc;
1326 PROC_LOCK_ASSERT(p, MA_OWNED);
1327 return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
1328 (td->td_dbgflags & TDB_SUSPEND) != 0));
1329}
1330
1331/*
1332 * Called in from locations that can safely check to see
1333 * whether we have to suspend or at least throttle for a
1334 * single-thread event (e.g. fork).
1335 *
1336 * Such locations include userret().
1337 * If the "return_instead" argument is non zero, the thread must be able to
1338 * accept 0 (caller may continue), or 1 (caller must abort) as a result.
1339 *
1340 * The 'return_instead' argument tells the function if it may do a
1341 * thread_exit() or suspend, or whether the caller must abort and back
1342 * out instead.
1343 *
1344 * If the thread that set the single_threading request has set the
1345 * P_SINGLE_EXIT bit in the process flags then this call will never return
1346 * if 'return_instead' is false, but will exit.
1347 *
1348 * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
1349 *---------------+--------------------+---------------------
1350 * 0 | returns 0 | returns 0 or 1
1351 * | when ST ends | immediately
1352 *---------------+--------------------+---------------------
1353 * 1 | thread exits | returns 1
1354 * | | immediately
1355 * 0 = thread_exit() or suspension ok,
1356 * other = return error instead of stopping the thread.
1357 *
1358 * While a full suspension is under effect, even a single threading
1359 * thread would be suspended if it made this call (but it shouldn't).
1360 * This call should only be made from places where
1361 * thread_exit() would be safe as that may be the outcome unless
1362 * return_instead is set.
1363 */
1364int
1365thread_suspend_check(int return_instead)
1366{
1367 struct thread *td;
1368 struct proc *p;
1369 int wakeup_swapper;
1370
1371 td = curthread;
1372 p = td->td_proc;
1373 mtx_assert(&Giant, MA_NOTOWNED);
1374 PROC_LOCK_ASSERT(p, MA_OWNED);
1375 while (thread_suspend_check_needed()) {
1376 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1377 KASSERT(p->p_singlethread != NULL,
1378 ("singlethread not set"));
1379 /*
1380 * The only suspension in action is a
1381 * single-threading. Single threader need not stop.
1382 * It is safe to access p->p_singlethread unlocked
1383 * because it can only be set to our address by us.
1384 */
1385 if (p->p_singlethread == td)
1386 return (0); /* Exempt from stopping. */
1387 }
1388 if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
1389 return (EINTR);
1390
1391 /* Should we goto user boundary if we didn't come from there? */
1392 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1393 (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
1394 return (ERESTART);
1395
1396 /*
1397 * Ignore suspend requests if they are deferred.
1398 */
1399 if ((td->td_flags & TDF_SBDRY) != 0) {
1400 KASSERT(return_instead,
1401 ("TDF_SBDRY set for unsafe thread_suspend_check"));
1402 KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
1403 (TDF_SEINTR | TDF_SERESTART),
1404 ("both TDF_SEINTR and TDF_SERESTART"));
1405 return (TD_SBDRY_INTR(td) ? TD_SBDRY_ERRNO(td) : 0);
1406 }
1407
1408 /*
1409 * If the process is waiting for us to exit,
1410 * this thread should just suicide.
1411 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
1412 */
1413 if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
1414 PROC_UNLOCK(p);
1415
1416 /*
1417 * Allow Linux emulation layer to do some work
1418 * before thread suicide.
1419 */
1420 if (__predict_false(p->p_sysent->sv_thread_detach != NULL))
1421 (p->p_sysent->sv_thread_detach)(td);
1422 umtx_thread_exit(td);
1423 kern_thr_exit(td);
1424 panic("stopped thread did not exit");
1425 }
1426
1427 PROC_SLOCK(p);
1428 thread_stopped(p);
1429 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1430 if (p->p_numthreads == p->p_suspcount + 1) {
1431 thread_lock(p->p_singlethread);
1432 wakeup_swapper = thread_unsuspend_one(
1433 p->p_singlethread, p, false);
1434 if (wakeup_swapper)
1435 kick_proc0();
1436 }
1437 }
1438 PROC_UNLOCK(p);
1439 thread_lock(td);
1440 /*
1441 * When a thread suspends, it just
1442 * gets taken off all queues.
1443 */
1445 if (return_instead == 0) {
1446 p->p_boundary_count++;
1447 td->td_flags |= TDF_BOUNDARY;
1448 }
1449 PROC_SUNLOCK(p);
1450 mi_switch(SW_INVOL | SWT_SUSPEND);
1451 PROC_LOCK(p);
1452 }
1453 return (0);
1454}
1455
1456/*
1457 * Check for possible stops and suspensions while executing a
1458 * casueword or similar transiently failing operation.
1459 *
1460 * The sleep argument controls whether the function can handle a stop
1461 * request itself or it should return ERESTART and the request is
1462 * proceed at the kernel/user boundary in ast.
1463 *
1464 * Typically, when retrying due to casueword(9) failure (rv == 1), we
1465 * should handle the stop requests there, with exception of cases when
1466 * the thread owns a kernel resource, for instance busied the umtx
1467 * key, or when functions return immediately if thread_check_susp()
1468 * returned non-zero. On the other hand, retrying the whole lock
1469 * operation, we better not stop there but delegate the handling to
1470 * ast.
1471 *
1472 * If the request is for thread termination P_SINGLE_EXIT, we cannot
1473 * handle it at all, and simply return EINTR.
1474 */
1475int
1476thread_check_susp(struct thread *td, bool sleep)
1477{
1478 struct proc *p;
1479 int error;
1480
1481 /*
1482 * The check for TDF_NEEDSUSPCHK is racy, but it is enough to
1483 * eventually break the lockstep loop.
1484 */
1485 if ((td->td_flags & TDF_NEEDSUSPCHK) == 0)
1486 return (0);
1487 error = 0;
1488 p = td->td_proc;
1489 PROC_LOCK(p);
1490 if (p->p_flag & P_SINGLE_EXIT)
1491 error = EINTR;
1492 else if (P_SHOULDSTOP(p) ||
1493 ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_SUSPEND)))
1494 error = sleep ? thread_suspend_check(0) : ERESTART;
1495 PROC_UNLOCK(p);
1496 return (error);
1497}
1498
1499void
1500thread_suspend_switch(struct thread *td, struct proc *p)
1501{
1502
1503 KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1504 PROC_LOCK_ASSERT(p, MA_OWNED);
1505 PROC_SLOCK_ASSERT(p, MA_OWNED);
1506 /*
1507 * We implement thread_suspend_one in stages here to avoid
1508 * dropping the proc lock while the thread lock is owned.
1509 */
1510 if (p == td->td_proc) {
1511 thread_stopped(p);
1512 p->p_suspcount++;
1513 }
1514 PROC_UNLOCK(p);
1515 thread_lock(td);
1516 td->td_flags &= ~TDF_NEEDSUSPCHK;
1517 TD_SET_SUSPENDED(td);
1518 sched_sleep(td, 0);
1519 PROC_SUNLOCK(p);
1520 DROP_GIANT();
1521 mi_switch(SW_VOL | SWT_SUSPEND);
1522 PICKUP_GIANT();
1523 PROC_LOCK(p);
1524 PROC_SLOCK(p);
1525}
1526
1527void
1528thread_suspend_one(struct thread *td)
1529{
1530 struct proc *p;
1531
1532 p = td->td_proc;
1533 PROC_SLOCK_ASSERT(p, MA_OWNED);
1534 THREAD_LOCK_ASSERT(td, MA_OWNED);
1535 KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1536 p->p_suspcount++;
1537 td->td_flags &= ~TDF_NEEDSUSPCHK;
1538 TD_SET_SUSPENDED(td);
1539 sched_sleep(td, 0);
1540}
1541
1542static int
1543thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
1544{
1545
1546 THREAD_LOCK_ASSERT(td, MA_OWNED);
1547 KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
1548 TD_CLR_SUSPENDED(td);
1549 td->td_flags &= ~TDF_ALLPROCSUSP;
1550 if (td->td_proc == p) {
1551 PROC_SLOCK_ASSERT(p, MA_OWNED);
1552 p->p_suspcount--;
1553 if (boundary && (td->td_flags & TDF_BOUNDARY) != 0) {
1554 td->td_flags &= ~TDF_BOUNDARY;
1555 p->p_boundary_count--;
1556 }
1557 }
1558 return (setrunnable(td, 0));
1559}
1560
1561void
1562thread_run_flash(struct thread *td)
1563{
1564 struct proc *p;
1565
1566 p = td->td_proc;
1567 PROC_LOCK_ASSERT(p, MA_OWNED);
1568
1569 if (TD_ON_SLEEPQ(td))
1571 else
1572 thread_lock(td);
1573
1574 THREAD_LOCK_ASSERT(td, MA_OWNED);
1575 KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
1576
1577 TD_CLR_SUSPENDED(td);
1578 PROC_SLOCK(p);
1579 MPASS(p->p_suspcount > 0);
1580 p->p_suspcount--;
1581 PROC_SUNLOCK(p);
1582 if (setrunnable(td, 0))
1583 kick_proc0();
1584}
1585
1586/*
1587 * Allow all threads blocked by single threading to continue running.
1588 */
1589void
1590thread_unsuspend(struct proc *p)
1591{
1592 struct thread *td;
1593 int wakeup_swapper;
1594
1595 PROC_LOCK_ASSERT(p, MA_OWNED);
1596 PROC_SLOCK_ASSERT(p, MA_OWNED);
1597 wakeup_swapper = 0;
1598 if (!P_SHOULDSTOP(p)) {
1599 FOREACH_THREAD_IN_PROC(p, td) {
1600 thread_lock(td);
1601 if (TD_IS_SUSPENDED(td)) {
1602 wakeup_swapper |= thread_unsuspend_one(td, p,
1603 true);
1604 } else
1605 thread_unlock(td);
1606 }
1607 } else if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1608 p->p_numthreads == p->p_suspcount) {
1609 /*
1610 * Stopping everything also did the job for the single
1611 * threading request. Now we've downgraded to single-threaded,
1612 * let it continue.
1613 */
1614 if (p->p_singlethread->td_proc == p) {
1615 thread_lock(p->p_singlethread);
1616 wakeup_swapper = thread_unsuspend_one(
1617 p->p_singlethread, p, false);
1618 }
1619 }
1620 if (wakeup_swapper)
1621 kick_proc0();
1622}
1623
1624/*
1625 * End the single threading mode..
1626 */
1627void
1628thread_single_end(struct proc *p, int mode)
1629{
1630 struct thread *td;
1631 int wakeup_swapper;
1632
1633 KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
1634 mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
1635 ("invalid mode %d", mode));
1636 PROC_LOCK_ASSERT(p, MA_OWNED);
1637 KASSERT((mode == SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) != 0) ||
1638 (mode != SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) == 0),
1639 ("mode %d does not match P_TOTAL_STOP", mode));
1640 KASSERT(mode == SINGLE_ALLPROC || p->p_singlethread == curthread,
1641 ("thread_single_end from other thread %p %p",
1642 curthread, p->p_singlethread));
1643 KASSERT(mode != SINGLE_BOUNDARY ||
1644 (p->p_flag & P_SINGLE_BOUNDARY) != 0,
1645 ("mis-matched SINGLE_BOUNDARY flags %x", p->p_flag));
1646 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY |
1647 P_TOTAL_STOP);
1648 PROC_SLOCK(p);
1649 p->p_singlethread = NULL;
1650 wakeup_swapper = 0;
1651 /*
1652 * If there are other threads they may now run,
1653 * unless of course there is a blanket 'stop order'
1654 * on the process. The single threader must be allowed
1655 * to continue however as this is a bad place to stop.
1656 */
1657 if (p->p_numthreads != remain_for_mode(mode) && !P_SHOULDSTOP(p)) {
1658 FOREACH_THREAD_IN_PROC(p, td) {
1659 thread_lock(td);
1660 if (TD_IS_SUSPENDED(td)) {
1661 wakeup_swapper |= thread_unsuspend_one(td, p,
1662 mode == SINGLE_BOUNDARY);
1663 } else
1664 thread_unlock(td);
1665 }
1666 }
1667 KASSERT(mode != SINGLE_BOUNDARY || p->p_boundary_count == 0,
1668 ("inconsistent boundary count %d", p->p_boundary_count));
1669 PROC_SUNLOCK(p);
1670 if (wakeup_swapper)
1671 kick_proc0();
1672}
1673
1674/*
1675 * Locate a thread by number and return with proc lock held.
1676 *
1677 * thread exit establishes proc -> tidhash lock ordering, but lookup
1678 * takes tidhash first and needs to return locked proc.
1679 *
1680 * The problem is worked around by relying on type-safety of both
1681 * structures and doing the work in 2 steps:
1682 * - tidhash-locked lookup which saves both thread and proc pointers
1683 * - proc-locked verification that the found thread still matches
1684 */
1685static bool
1686tdfind_hash(lwpid_t tid, pid_t pid, struct proc **pp, struct thread **tdp)
1687{
1688#define RUN_THRESH 16
1689 struct proc *p;
1690 struct thread *td;
1691 int run;
1692 bool locked;
1693
1694 run = 0;
1695 rw_rlock(TIDHASHLOCK(tid));
1696 locked = true;
1697 LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1698 if (td->td_tid != tid) {
1699 run++;
1700 continue;
1701 }
1702 p = td->td_proc;
1703 if (pid != -1 && p->p_pid != pid) {
1704 td = NULL;
1705 break;
1706 }
1707 if (run > RUN_THRESH) {
1708 if (rw_try_upgrade(TIDHASHLOCK(tid))) {
1709 LIST_REMOVE(td, td_hash);
1710 LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1711 td, td_hash);
1712 rw_wunlock(TIDHASHLOCK(tid));
1713 locked = false;
1714 break;
1715 }
1716 }
1717 break;
1718 }
1719 if (locked)
1720 rw_runlock(TIDHASHLOCK(tid));
1721 if (td == NULL)
1722 return (false);
1723 *pp = p;
1724 *tdp = td;
1725 return (true);
1726}
1727
1728struct thread *
1729tdfind(lwpid_t tid, pid_t pid)
1730{
1731 struct proc *p;
1732 struct thread *td;
1733
1734 td = curthread;
1735 if (td->td_tid == tid) {
1736 if (pid != -1 && td->td_proc->p_pid != pid)
1737 return (NULL);
1738 PROC_LOCK(td->td_proc);
1739 return (td);
1740 }
1741
1742 for (;;) {
1743 if (!tdfind_hash(tid, pid, &p, &td))
1744 return (NULL);
1745 PROC_LOCK(p);
1746 if (td->td_tid != tid) {
1747 PROC_UNLOCK(p);
1748 continue;
1749 }
1750 if (td->td_proc != p) {
1751 PROC_UNLOCK(p);
1752 continue;
1753 }
1754 if (p->p_state == PRS_NEW) {
1755 PROC_UNLOCK(p);
1756 return (NULL);
1757 }
1758 return (td);
1759 }
1760}
1761
1762void
1763tidhash_add(struct thread *td)
1764{
1765 rw_wlock(TIDHASHLOCK(td->td_tid));
1766 LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1767 rw_wunlock(TIDHASHLOCK(td->td_tid));
1768}
1769
1770void
1771tidhash_remove(struct thread *td)
1772{
1773
1774 rw_wlock(TIDHASHLOCK(td->td_tid));
1775 LIST_REMOVE(td, td_hash);
1776 rw_wunlock(TIDHASHLOCK(td->td_tid));
1777}
_Static_assert(sizeof(struct acctv3) - offsetof(struct acctv3, ac_trailer)==sizeof(struct acctv2) - offsetof(struct acctv2, ac_trailer), "trailer")
volatile int ticks
Definition: kern_clock.c:380
void cpuset_rel(struct cpuset *set)
Definition: kern_cpuset.c:208
void kdtrace_thread_dtor(struct thread *td)
Definition: kern_dtrace.c:101
void kdtrace_thread_ctor(struct thread *td)
Definition: kern_dtrace.c:94
void *() malloc(size_t size, struct malloc_type *mtp, int flags)
Definition: kern_malloc.c:632
void free(void *addr, struct malloc_type *mtp)
Definition: kern_malloc.c:907
struct mtx __exclusive_cache_line Giant
Definition: kern_mutex.c:181
int priv_check_cred(struct ucred *cred, int priv)
Definition: kern_priv.c:151
EVENTHANDLER_LIST_DEFINE(process_ctor)
struct ucred * crcowget(struct ucred *cr)
Definition: kern_prot.c:1854
void credbatch_add(struct credbatch *crb, struct thread *td)
Definition: kern_prot.c:1953
void credbatch_final(struct credbatch *crb)
Definition: kern_prot.c:1979
struct ucred * crcowsync(void)
Definition: kern_prot.c:1928
void crfree(struct ucred *cr)
Definition: kern_prot.c:2035
void crcowfree(struct thread *td)
Definition: kern_prot.c:1918
void rlqentry_free(struct rl_q_entry *rleq)
void rucollect(struct rusage *ru, struct rusage *ru2)
void lim_free(struct plimit *limp)
struct plimit * lim_hold(struct plimit *limp)
struct plimit * lim_cowsync(void)
void ruxagg_locked(struct proc *p, struct thread *td)
void lim_freen(struct plimit *limp, int n)
void panic(const char *fmt,...)
void sigqueue_init(sigqueue_t *list, struct proc *p)
Definition: kern_sig.c:320
ksiginfo_t * ksiginfo_alloc(int wait)
Definition: kern_sig.c:291
void thread_stopped(struct proc *p)
Definition: kern_sig.c:3168
void mi_switch(int flags)
Definition: kern_synch.c:491
int setrunnable(struct thread *td, int srqflags)
Definition: kern_synch.c:567
cpu_tick_f * cpu_ticks
Definition: kern_tc.c:2174
int kern_thr_exit(struct thread *td)
Definition: kern_thr.c:325
static int calc_remaining(struct proc *p, int mode)
Definition: kern_thread.c:1077
static int maxthread
Definition: kern_thread.c:160
static void thread_reap_all(void)
Definition: kern_thread.c:654
struct tidbatch __aligned
static void thread_fini(void *mem, int size)
Definition: kern_thread.c:439
static LIST_HEAD(tidhashhead, thread)
Definition: kern_thread.c:166
static void thread_dtor(void *mem, int size, void *arg)
Definition: kern_thread.c:375
static void tidbatch_add(struct tidbatch *tb, struct thread *td)
Definition: kern_thread.c:309
static void thread_reap_domain(struct thread_domain_data *tdd)
Definition: kern_thread.c:583
void tidhash_add(struct thread *td)
Definition: kern_thread.c:1763
void thread_cow_synced(struct thread *td)
Definition: kern_thread.c:871
void thread_run_flash(struct thread *td)
Definition: kern_thread.c:1562
void thread_stash(struct thread *td)
Definition: kern_thread.c:573
static lwpid_t tid_alloc(void)
Definition: kern_thread.c:233
void thread_cow_update(struct thread *td)
Definition: kern_thread.c:852
void thread_cow_get_proc(struct thread *newtd, struct proc *p)
Definition: kern_thread.c:820
static __exclusive_cache_line struct mtx tid_lock
Definition: kern_thread.c:155
void proc_linkup(struct proc *p, struct thread *td)
Definition: kern_thread.c:468
static void thread_free_batched(struct thread *td)
Definition: kern_thread.c:788
void thread_cow_get(struct thread *newtd, struct thread *td)
Definition: kern_thread.c:831
static int thread_init(void *mem, int size, int flags)
Definition: kern_thread.c:418
void threadinit(void)
Definition: kern_thread.c:488
void thread_reap_barrier(void)
Definition: kern_thread.c:721
static bitstr_t * tid_bitmap
Definition: kern_thread.c:156
static void thread_reap(void)
Definition: kern_thread.c:670
static uma_zone_t thread_zone
Definition: kern_thread.c:134
static void tid_free_locked(lwpid_t rtid)
Definition: kern_thread.c:259
SDT_PROBE_DEFINE(proc,,, lwp__exit)
void tidhash_remove(struct thread *td)
Definition: kern_thread.c:1771
static void tid_free(lwpid_t rtid)
Definition: kern_thread.c:273
static int thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
Definition: kern_thread.c:1543
#define TIDHASHLOCK(tid)
static void tidbatch_final(struct tidbatch *tb)
Definition: kern_thread.c:331
static void thread_count_sub(int n)
Definition: kern_thread.c:219
static void tid_free_batch(lwpid_t *batch, int n)
Definition: kern_thread.c:282
int max_threads_per_proc
Definition: kern_thr.c:70
static void thread_zombie(struct thread *)
Definition: kern_thread.c:553
static struct task thread_reap_task
Definition: kern_thread.c:143
void thread_exit(void)
Definition: kern_thread.c:893
static void thread_count_dec(void)
Definition: kern_thread.c:226
static bool tdfind_hash(lwpid_t tid, pid_t pid, struct proc **pp, struct thread **tdp)
Definition: kern_thread.c:1686
static bool thread_count_inc(void)
Definition: kern_thread.c:195
static int weed_inhib(int mode, struct thread *td2, struct proc *p)
Definition: kern_thread.c:1102
__FBSDID("$FreeBSD$")
#define TIDHASH(tid)
void thread_link(struct thread *td, struct proc *p)
Definition: kern_thread.c:1032
int thread_check_susp(struct thread *td, bool sleep)
Definition: kern_thread.c:1476
int thread_suspend_check(int return_instead)
Definition: kern_thread.c:1365
static void tidbatch_process(struct tidbatch *tb)
Definition: kern_thread.c:319
void thread_single_end(struct proc *p, int mode)
Definition: kern_thread.c:1628
struct thread * thread_alloc(int pages)
Definition: kern_thread.c:746
struct thread * tdfind(lwpid_t tid, pid_t pid)
Definition: kern_thread.c:1729
int thread_single(struct proc *p, int mode)
Definition: kern_thread.c:1188
SYSCTL_INT(_kern, OID_AUTO, maxthread, CTLFLAG_RDTUN, &maxthread, 0, "Maximum number of threads")
static __exclusive_cache_line int nthreads
Definition: kern_thread.c:164
static struct callout thread_reap_callout
Definition: kern_thread.c:144
void proc_linkup0(struct proc *p, struct thread *td)
Definition: kern_thread.c:461
int thread_alloc_stack(struct thread *td, int pages)
Definition: kern_thread.c:773
static void thread_reap_task_cb(void *, int)
void thread_cow_free(struct thread *td)
Definition: kern_thread.c:842
bool thread_suspend_check_needed(void)
Definition: kern_thread.c:1319
void thread_wait(struct proc *p)
Definition: kern_thread.c:1006
static MALLOC_DEFINE(M_TIDHASH, "tidhash", "thread hash")
#define RUN_THRESH
SDT_PROVIDER_DECLARE(proc)
void thread_unsuspend(struct proc *p)
Definition: kern_thread.c:1590
void thread_free(struct thread *td)
Definition: kern_thread.c:808
void thread_suspend_one(struct thread *td)
Definition: kern_thread.c:1528
static int remain_for_mode(int mode)
Definition: kern_thread.c:1095
static void thread_reap_callout_cb(void *)
static void tidbatch_prep(struct tidbatch *tb)
Definition: kern_thread.c:302
static int thread_ctor(void *mem, int size, void *arg, int flags)
Definition: kern_thread.c:345
void thread_suspend_switch(struct thread *td, struct proc *p)
Definition: kern_thread.c:1500
void thread_unlink(struct thread *td)
Definition: kern_thread.c:1061
int ppsratecheck(struct timeval *lasttime, int *curpps, int maxpps)
Definition: kern_time.c:1118
void callout_init(struct callout *c, int mpsafe)
void umtx_thread_alloc(struct thread *td)
Definition: kern_umtx.c:4935
void umtx_thread_init(struct thread *td)
Definition: kern_umtx.c:4917
void umtx_thread_exit(struct thread *td)
Definition: kern_umtx.c:4981
void umtx_thread_fini(struct thread *td)
Definition: kern_umtx.c:4925
struct iommu_domain ** domain
Definition: msi_if.m:96
void sched_exit_thread(struct thread *td, struct thread *child)
Definition: sched_4bsd.c:773
void sched_relinquish(struct thread *td)
Definition: sched_4bsd.c:1567
void sched_throw(struct thread *td)
Definition: sched_4bsd.c:1702
int sched_sizeof_thread(void)
Definition: sched_4bsd.c:1586
void sched_sleep(struct thread *td, int pri)
Definition: sched_4bsd.c:973
struct thread * tdd_zombies
Definition: kern_thread.c:137
lwpid_t tab[16]
Definition: kern_thread.c:297
void * hashinit(int elements, struct malloc_type *type, u_long *hashmask)
Definition: subr_hash.c:86
void kmsan_thread_free(struct thread *td)
Definition: subr_msan.c:464
void kmsan_thread_alloc(struct thread *td)
Definition: subr_msan.c:439
int maxproc
Definition: subr_param.c:90
int hz
Definition: subr_param.c:85
int printf(const char *fmt,...)
Definition: subr_prf.c:397
void sleepq_remove_nested(struct thread *td)
struct sleepqueue * sleepq_alloc(void)
int sleepq_abort(struct thread *td, int intrval)
void sleepq_free(struct sleepqueue *sq)
int quiesce_all_cpus(const char *wmesg, int prio)
Definition: subr_smp.c:1011
uint16_t flags
Definition: subr_stats.c:2
int taskqueue_enqueue(struct taskqueue *queue, struct task *task)
void taskqueue_drain(struct taskqueue *queue, struct task *task)
void turnstile_free(struct turnstile *ts)
struct turnstile * turnstile_alloc(void)
void witness_thread_exit(struct thread *td)
void seltdfini(struct thread *td)
Definition: sys_generic.c:2020
struct mtx mtx
Definition: uipc_ktls.c:0
mode_t mode