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