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) == 0x700,
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) == 0x3e4,
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) == 0x288,
124 "struct proc KBI p_comm");
125 _Static_assert(offsetof(struct proc, p_emuldata) == 0x31c,
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 = NULL;
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 thread' 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 == NULL, ("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 cpu_thread_new_kstack(td);
807 EVENTHANDLER_DIRECT_INVOKE(thread_ctor, td);
808 return (td);
809 }
810
811 int
thread_recycle(struct thread * td,int pages)812 thread_recycle(struct thread *td, int pages)
813 {
814 if (td->td_kstack == NULL || td->td_kstack_pages != pages) {
815 if (td->td_kstack != NULL)
816 vm_thread_dispose(td);
817 if (!vm_thread_new(td, pages))
818 return (ENOMEM);
819 cpu_thread_new_kstack(td);
820 }
821 kasan_thread_alloc(td);
822 kmsan_thread_alloc(td);
823 return (0);
824 }
825
826 /*
827 * Deallocate a thread.
828 */
829 static void
thread_free_batched(struct thread * td)830 thread_free_batched(struct thread *td)
831 {
832
833 lock_profile_thread_exit(td);
834 if (td->td_cpuset)
835 cpuset_rel(td->td_cpuset);
836 td->td_cpuset = NULL;
837 cpu_thread_free(td);
838 if (td->td_kstack != NULL)
839 vm_thread_dispose(td);
840 callout_drain(&td->td_slpcallout);
841 /*
842 * Freeing handled by the caller.
843 */
844 td->td_tid = -1;
845 kmsan_thread_free(td);
846 uma_zfree(thread_zone, td);
847 }
848
849 void
thread_free(struct thread * td)850 thread_free(struct thread *td)
851 {
852 lwpid_t tid;
853
854 EVENTHANDLER_DIRECT_INVOKE(thread_dtor, td);
855 tid = td->td_tid;
856 thread_free_batched(td);
857 tid_free(tid);
858 thread_count_dec();
859 }
860
861 void
thread_cow_get_proc(struct thread * newtd,struct proc * p)862 thread_cow_get_proc(struct thread *newtd, struct proc *p)
863 {
864
865 PROC_LOCK_ASSERT(p, MA_OWNED);
866 newtd->td_realucred = crcowget(p->p_ucred);
867 newtd->td_ucred = newtd->td_realucred;
868 newtd->td_limit = lim_hold(p->p_limit);
869 newtd->td_cowgen = p->p_cowgen;
870 }
871
872 void
thread_cow_get(struct thread * newtd,struct thread * td)873 thread_cow_get(struct thread *newtd, struct thread *td)
874 {
875
876 MPASS(td->td_realucred == td->td_ucred);
877 newtd->td_realucred = crcowget(td->td_realucred);
878 newtd->td_ucred = newtd->td_realucred;
879 newtd->td_limit = lim_hold(td->td_limit);
880 newtd->td_cowgen = td->td_cowgen;
881 }
882
883 void
thread_cow_free(struct thread * td)884 thread_cow_free(struct thread *td)
885 {
886
887 if (td->td_realucred != NULL)
888 crcowfree(td);
889 if (td->td_limit != NULL)
890 lim_free(td->td_limit);
891 }
892
893 void
thread_cow_update(struct thread * td)894 thread_cow_update(struct thread *td)
895 {
896 struct proc *p;
897 struct ucred *oldcred;
898 struct plimit *oldlimit;
899
900 p = td->td_proc;
901 PROC_LOCK(p);
902 oldcred = crcowsync();
903 oldlimit = lim_cowsync();
904 td->td_cowgen = p->p_cowgen;
905 PROC_UNLOCK(p);
906 if (oldcred != NULL)
907 crfree(oldcred);
908 if (oldlimit != NULL)
909 lim_free(oldlimit);
910 }
911
912 void
thread_cow_synced(struct thread * td)913 thread_cow_synced(struct thread *td)
914 {
915 struct proc *p;
916
917 p = td->td_proc;
918 PROC_LOCK_ASSERT(p, MA_OWNED);
919 MPASS(td->td_cowgen != p->p_cowgen);
920 MPASS(td->td_ucred == p->p_ucred);
921 MPASS(td->td_limit == p->p_limit);
922 td->td_cowgen = p->p_cowgen;
923 }
924
925 /*
926 * Discard the current thread and exit from its context.
927 * Always called with scheduler locked.
928 *
929 * Because we can't free a thread while we're operating under its context,
930 * push the current thread into our CPU's deadthread holder. This means
931 * we needn't worry about someone else grabbing our context before we
932 * do a cpu_throw().
933 */
934 void
thread_exit(void)935 thread_exit(void)
936 {
937 uint64_t runtime, new_switchtime;
938 struct thread *td;
939 struct thread *td2;
940 struct proc *p;
941
942 td = curthread;
943 p = td->td_proc;
944
945 PROC_SLOCK_ASSERT(p, MA_OWNED);
946 mtx_assert(&Giant, MA_NOTOWNED);
947
948 PROC_LOCK_ASSERT(p, MA_OWNED);
949 KASSERT(p != NULL, ("thread exiting without a process"));
950 CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
951 (long)p->p_pid, td->td_name);
952 SDT_PROBE0(proc, , , lwp__exit);
953 KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
954 MPASS(td->td_realucred == td->td_ucred);
955
956 /*
957 * drop FPU & debug register state storage, or any other
958 * architecture specific resources that
959 * would not be on a new untouched process.
960 */
961 cpu_thread_exit(td);
962
963 /*
964 * The last thread is left attached to the process
965 * So that the whole bundle gets recycled. Skip
966 * all this stuff if we never had threads.
967 * EXIT clears all sign of other threads when
968 * it goes to single threading, so the last thread always
969 * takes the short path.
970 */
971 if (p->p_flag & P_HADTHREADS) {
972 if (p->p_numthreads > 1) {
973 atomic_add_int(&td->td_proc->p_exitthreads, 1);
974 thread_unlink(td);
975 td2 = FIRST_THREAD_IN_PROC(p);
976 sched_exit_thread(td2, td);
977
978 /*
979 * The test below is NOT true if we are the
980 * sole exiting thread. P_STOPPED_SINGLE is unset
981 * in exit1() after it is the only survivor.
982 */
983 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
984 if (p->p_numthreads == p->p_suspcount) {
985 thread_lock(p->p_singlethread);
986 thread_unsuspend_one(p->p_singlethread,
987 p, false);
988 }
989 }
990
991 PCPU_SET(deadthread, td);
992 } else {
993 /*
994 * The last thread is exiting.. but not through exit()
995 */
996 panic ("thread_exit: Last thread exiting on its own");
997 }
998 }
999 #ifdef HWPMC_HOOKS
1000 /*
1001 * If this thread is part of a process that is being tracked by hwpmc(4),
1002 * inform the module of the thread's impending exit.
1003 */
1004 if (PMC_PROC_IS_USING_PMCS(td->td_proc)) {
1005 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1006 PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT, NULL);
1007 } else if (PMC_SYSTEM_SAMPLING_ACTIVE())
1008 PMC_CALL_HOOK_UNLOCKED(td, PMC_FN_THR_EXIT_LOG, NULL);
1009 #endif
1010
1011 #ifdef HWT_HOOKS
1012 HWT_CALL_HOOK(td, HWT_THREAD_EXIT, NULL);
1013 #endif
1014
1015 PROC_UNLOCK(p);
1016 PROC_STATLOCK(p);
1017 thread_lock(td);
1018 PROC_SUNLOCK(p);
1019
1020 /* Do the same timestamp bookkeeping that mi_switch() would do. */
1021 new_switchtime = cpu_ticks();
1022 runtime = new_switchtime - PCPU_GET(switchtime);
1023 td->td_runtime += runtime;
1024 td->td_incruntime += runtime;
1025 PCPU_SET(switchtime, new_switchtime);
1026 PCPU_SET(switchticks, ticks);
1027 VM_CNT_INC(v_swtch);
1028
1029 /* Save our resource usage in our process. */
1030 td->td_ru.ru_nvcsw++;
1031 ruxagg_locked(p, td);
1032 rucollect(&p->p_ru, &td->td_ru);
1033 PROC_STATUNLOCK(p);
1034
1035 TD_SET_STATE(td, TDS_INACTIVE);
1036 #ifdef WITNESS
1037 witness_thread_exit(td);
1038 #endif
1039 CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
1040 sched_throw(td);
1041 panic("I'm a teapot!");
1042 /* NOTREACHED */
1043 }
1044
1045 /*
1046 * Do any thread specific cleanups that may be needed in wait()
1047 * called with Giant, proc and schedlock not held.
1048 */
1049 void
thread_wait(struct proc * p)1050 thread_wait(struct proc *p)
1051 {
1052 struct thread *td;
1053
1054 mtx_assert(&Giant, MA_NOTOWNED);
1055 KASSERT(p->p_numthreads == 1, ("multiple threads in thread_wait()"));
1056 KASSERT(p->p_exitthreads == 0, ("p_exitthreads leaking"));
1057 td = FIRST_THREAD_IN_PROC(p);
1058 /* Lock the last thread so we spin until it exits cpu_throw(). */
1059 thread_lock(td);
1060 thread_unlock(td);
1061 lock_profile_thread_exit(td);
1062 cpuset_rel(td->td_cpuset);
1063 td->td_cpuset = NULL;
1064 cpu_thread_clean(td);
1065 thread_cow_free(td);
1066 callout_drain(&td->td_slpcallout);
1067 thread_reap(); /* check for zombie threads etc. */
1068 }
1069
1070 /*
1071 * Link a thread to a process.
1072 * set up anything that needs to be initialized for it to
1073 * be used by the process.
1074 */
1075 void
thread_link(struct thread * td,struct proc * p)1076 thread_link(struct thread *td, struct proc *p)
1077 {
1078
1079 /*
1080 * XXX This can't be enabled because it's called for proc0 before
1081 * its lock has been created.
1082 * PROC_LOCK_ASSERT(p, MA_OWNED);
1083 */
1084 TD_SET_STATE(td, TDS_INACTIVE);
1085 td->td_proc = p;
1086 td->td_flags = TDF_INMEM;
1087
1088 LIST_INIT(&td->td_contested);
1089 LIST_INIT(&td->td_lprof[0]);
1090 LIST_INIT(&td->td_lprof[1]);
1091 #ifdef EPOCH_TRACE
1092 SLIST_INIT(&td->td_epochs);
1093 #endif
1094 sigqueue_init(&td->td_sigqueue, p);
1095 callout_init(&td->td_slpcallout, 1);
1096 TAILQ_INSERT_TAIL(&p->p_threads, td, td_plist);
1097 p->p_numthreads++;
1098 }
1099
1100 /*
1101 * Called from:
1102 * thread_exit()
1103 */
1104 void
thread_unlink(struct thread * td)1105 thread_unlink(struct thread *td)
1106 {
1107 struct proc *p = td->td_proc;
1108
1109 PROC_LOCK_ASSERT(p, MA_OWNED);
1110 #ifdef EPOCH_TRACE
1111 MPASS(SLIST_EMPTY(&td->td_epochs));
1112 #endif
1113
1114 TAILQ_REMOVE(&p->p_threads, td, td_plist);
1115 p->p_numthreads--;
1116 /* could clear a few other things here */
1117 /* Must NOT clear links to proc! */
1118 }
1119
1120 static int
calc_remaining(struct proc * p,int mode)1121 calc_remaining(struct proc *p, int mode)
1122 {
1123 int remaining;
1124
1125 PROC_LOCK_ASSERT(p, MA_OWNED);
1126 PROC_SLOCK_ASSERT(p, MA_OWNED);
1127 if (mode == SINGLE_EXIT)
1128 remaining = p->p_numthreads;
1129 else if (mode == SINGLE_BOUNDARY)
1130 remaining = p->p_numthreads - p->p_boundary_count;
1131 else if (mode == SINGLE_NO_EXIT || mode == SINGLE_ALLPROC)
1132 remaining = p->p_numthreads - p->p_suspcount;
1133 else
1134 panic("calc_remaining: wrong mode %d", mode);
1135 return (remaining);
1136 }
1137
1138 static int
remain_for_mode(int mode)1139 remain_for_mode(int mode)
1140 {
1141
1142 return (mode == SINGLE_ALLPROC ? 0 : 1);
1143 }
1144
1145 static void
weed_inhib(int mode,struct thread * td2,struct proc * p)1146 weed_inhib(int mode, struct thread *td2, struct proc *p)
1147 {
1148 PROC_LOCK_ASSERT(p, MA_OWNED);
1149 PROC_SLOCK_ASSERT(p, MA_OWNED);
1150 THREAD_LOCK_ASSERT(td2, MA_OWNED);
1151
1152 /*
1153 * Since the thread lock is dropped by the scheduler we have
1154 * to retry to check for races.
1155 */
1156 restart:
1157 switch (mode) {
1158 case SINGLE_EXIT:
1159 if (TD_IS_SUSPENDED(td2)) {
1160 thread_unsuspend_one(td2, p, true);
1161 thread_lock(td2);
1162 goto restart;
1163 }
1164 if (TD_CAN_ABORT(td2)) {
1165 sleepq_abort(td2, EINTR);
1166 return;
1167 }
1168 break;
1169 case SINGLE_BOUNDARY:
1170 case SINGLE_NO_EXIT:
1171 if (TD_IS_SUSPENDED(td2) &&
1172 (td2->td_flags & TDF_BOUNDARY) == 0) {
1173 thread_unsuspend_one(td2, p, false);
1174 thread_lock(td2);
1175 goto restart;
1176 }
1177 if (TD_CAN_ABORT(td2)) {
1178 sleepq_abort(td2, ERESTART);
1179 return;
1180 }
1181 break;
1182 case SINGLE_ALLPROC:
1183 /*
1184 * ALLPROC suspend tries to avoid spurious EINTR for
1185 * threads sleeping interruptable, by suspending the
1186 * thread directly, similarly to sig_suspend_threads().
1187 * Since such sleep is not neccessary performed at the user
1188 * boundary, TDF_ALLPROCSUSP is used to avoid immediate
1189 * un-suspend.
1190 */
1191 if (TD_IS_SUSPENDED(td2) &&
1192 (td2->td_flags & TDF_ALLPROCSUSP) == 0) {
1193 thread_unsuspend_one(td2, p, false);
1194 thread_lock(td2);
1195 goto restart;
1196 }
1197 if (TD_CAN_ABORT(td2)) {
1198 td2->td_flags |= TDF_ALLPROCSUSP;
1199 sleepq_abort(td2, ERESTART);
1200 return;
1201 }
1202 break;
1203 default:
1204 break;
1205 }
1206 thread_unlock(td2);
1207 }
1208
1209 /*
1210 * Enforce single-threading.
1211 *
1212 * Returns 1 if the caller must abort (another thread is waiting to
1213 * exit the process or similar). Process is locked!
1214 * Returns 0 when you are successfully the only thread running.
1215 * A process has successfully single threaded in the suspend mode when
1216 * There are no threads in user mode. Threads in the kernel must be
1217 * allowed to continue until they get to the user boundary. They may even
1218 * copy out their return values and data before suspending. They may however be
1219 * accelerated in reaching the user boundary as we will wake up
1220 * any sleeping threads that are interruptable. (PCATCH).
1221 */
1222 int
thread_single(struct proc * p,int mode)1223 thread_single(struct proc *p, int mode)
1224 {
1225 struct thread *td;
1226 struct thread *td2;
1227 int remaining;
1228
1229 td = curthread;
1230 KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
1231 mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
1232 ("invalid mode %d", mode));
1233 /*
1234 * If allowing non-ALLPROC singlethreading for non-curproc
1235 * callers, calc_remaining() and remain_for_mode() should be
1236 * adjusted to also account for td->td_proc != p. For now
1237 * this is not implemented because it is not used.
1238 */
1239 KASSERT((mode == SINGLE_ALLPROC && td->td_proc != p) ||
1240 (mode != SINGLE_ALLPROC && td->td_proc == p),
1241 ("mode %d proc %p curproc %p", mode, p, td->td_proc));
1242 mtx_assert(&Giant, MA_NOTOWNED);
1243 PROC_LOCK_ASSERT(p, MA_OWNED);
1244
1245 /*
1246 * Is someone already single threading?
1247 * Or may be singlethreading is not needed at all.
1248 */
1249 if (mode == SINGLE_ALLPROC) {
1250 while ((p->p_flag & P_STOPPED_SINGLE) != 0) {
1251 if ((p->p_flag2 & P2_WEXIT) != 0)
1252 return (1);
1253 msleep(&p->p_flag, &p->p_mtx, PCATCH, "thrsgl", 0);
1254 }
1255 if ((p->p_flag & (P_STOPPED_SIG | P_TRACED)) != 0 ||
1256 (p->p_flag2 & P2_WEXIT) != 0)
1257 return (1);
1258 } else if ((p->p_flag & P_HADTHREADS) == 0)
1259 return (0);
1260 if (p->p_singlethread != NULL && p->p_singlethread != td)
1261 return (1);
1262
1263 if (mode == SINGLE_EXIT) {
1264 p->p_flag |= P_SINGLE_EXIT;
1265 p->p_flag &= ~P_SINGLE_BOUNDARY;
1266 } else {
1267 p->p_flag &= ~P_SINGLE_EXIT;
1268 if (mode == SINGLE_BOUNDARY)
1269 p->p_flag |= P_SINGLE_BOUNDARY;
1270 else
1271 p->p_flag &= ~P_SINGLE_BOUNDARY;
1272 }
1273 if (mode == SINGLE_ALLPROC)
1274 p->p_flag |= P_TOTAL_STOP;
1275 p->p_flag |= P_STOPPED_SINGLE;
1276 PROC_SLOCK(p);
1277 p->p_singlethread = td;
1278 remaining = calc_remaining(p, mode);
1279 while (remaining != remain_for_mode(mode)) {
1280 if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
1281 goto stopme;
1282 FOREACH_THREAD_IN_PROC(p, td2) {
1283 if (td2 == td)
1284 continue;
1285 thread_lock(td2);
1286 ast_sched_locked(td2, TDA_SUSPEND);
1287 if (TD_IS_INHIBITED(td2)) {
1288 weed_inhib(mode, td2, p);
1289 #ifdef SMP
1290 } else if (TD_IS_RUNNING(td2)) {
1291 forward_signal(td2);
1292 thread_unlock(td2);
1293 #endif
1294 } else
1295 thread_unlock(td2);
1296 }
1297 remaining = calc_remaining(p, mode);
1298
1299 /*
1300 * Maybe we suspended some threads.. was it enough?
1301 */
1302 if (remaining == remain_for_mode(mode))
1303 break;
1304
1305 stopme:
1306 /*
1307 * Wake us up when everyone else has suspended.
1308 * In the mean time we suspend as well.
1309 */
1310 thread_suspend_switch(td, p);
1311 remaining = calc_remaining(p, mode);
1312 }
1313 if (mode == SINGLE_EXIT) {
1314 /*
1315 * Convert the process to an unthreaded process. The
1316 * SINGLE_EXIT is called by exit1() or execve(), in
1317 * both cases other threads must be retired.
1318 */
1319 KASSERT(p->p_numthreads == 1, ("Unthreading with >1 threads"));
1320 p->p_singlethread = NULL;
1321 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_HADTHREADS);
1322
1323 /*
1324 * Wait for any remaining threads to exit cpu_throw().
1325 */
1326 while (p->p_exitthreads != 0) {
1327 PROC_SUNLOCK(p);
1328 PROC_UNLOCK(p);
1329 sched_relinquish(td);
1330 PROC_LOCK(p);
1331 PROC_SLOCK(p);
1332 }
1333 } else if (mode == SINGLE_BOUNDARY) {
1334 /*
1335 * Wait until all suspended threads are removed from
1336 * the processors. The thread_suspend_check()
1337 * increments p_boundary_count while it is still
1338 * running, which makes it possible for the execve()
1339 * to destroy vmspace while our other threads are
1340 * still using the address space.
1341 *
1342 * We lock the thread, which is only allowed to
1343 * succeed after context switch code finished using
1344 * the address space.
1345 */
1346 FOREACH_THREAD_IN_PROC(p, td2) {
1347 if (td2 == td)
1348 continue;
1349 thread_lock(td2);
1350 KASSERT((td2->td_flags & TDF_BOUNDARY) != 0,
1351 ("td %p not on boundary", td2));
1352 KASSERT(TD_IS_SUSPENDED(td2),
1353 ("td %p is not suspended", td2));
1354 thread_unlock(td2);
1355 }
1356 }
1357 PROC_SUNLOCK(p);
1358 return (0);
1359 }
1360
1361 bool
thread_suspend_check_needed(void)1362 thread_suspend_check_needed(void)
1363 {
1364 struct proc *p;
1365 struct thread *td;
1366
1367 td = curthread;
1368 p = td->td_proc;
1369 PROC_LOCK_ASSERT(p, MA_OWNED);
1370 return (P_SHOULDSTOP(p) || ((p->p_flag & P_TRACED) != 0 &&
1371 (td->td_dbgflags & TDB_SUSPEND) != 0));
1372 }
1373
1374 /*
1375 * Called in from locations that can safely check to see
1376 * whether we have to suspend or at least throttle for a
1377 * single-thread event (e.g. fork).
1378 *
1379 * Such locations include userret().
1380 * If the "return_instead" argument is non zero, the thread must be able to
1381 * accept 0 (caller may continue), or 1 (caller must abort) as a result.
1382 *
1383 * The 'return_instead' argument tells the function if it may do a
1384 * thread_exit() or suspend, or whether the caller must abort and back
1385 * out instead.
1386 *
1387 * If the thread that set the single_threading request has set the
1388 * P_SINGLE_EXIT bit in the process flags then this call will never return
1389 * if 'return_instead' is false, but will exit.
1390 *
1391 * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
1392 *---------------+--------------------+---------------------
1393 * 0 | returns 0 | returns 0 or 1
1394 * | when ST ends | immediately
1395 *---------------+--------------------+---------------------
1396 * 1 | thread exits | returns 1
1397 * | | immediately
1398 * 0 = thread_exit() or suspension ok,
1399 * other = return error instead of stopping the thread.
1400 *
1401 * While a full suspension is under effect, even a single threading
1402 * thread would be suspended if it made this call (but it shouldn't).
1403 * This call should only be made from places where
1404 * thread_exit() would be safe as that may be the outcome unless
1405 * return_instead is set.
1406 */
1407 int
thread_suspend_check(int return_instead)1408 thread_suspend_check(int return_instead)
1409 {
1410 struct thread *td;
1411 struct proc *p;
1412
1413 td = curthread;
1414 p = td->td_proc;
1415 mtx_assert(&Giant, MA_NOTOWNED);
1416 PROC_LOCK_ASSERT(p, MA_OWNED);
1417 while (thread_suspend_check_needed()) {
1418 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1419 KASSERT(p->p_singlethread != NULL,
1420 ("singlethread not set"));
1421 /*
1422 * The only suspension in action is a
1423 * single-threading. Single threader need not stop.
1424 * It is safe to access p->p_singlethread unlocked
1425 * because it can only be set to our address by us.
1426 */
1427 if (p->p_singlethread == td)
1428 return (0); /* Exempt from stopping. */
1429 }
1430 if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
1431 return (EINTR);
1432
1433 /* Should we goto user boundary if we didn't come from there? */
1434 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1435 (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
1436 return (ERESTART);
1437
1438 /*
1439 * Ignore suspend requests if they are deferred.
1440 */
1441 if ((td->td_flags & TDF_SBDRY) != 0) {
1442 KASSERT(return_instead,
1443 ("TDF_SBDRY set for unsafe thread_suspend_check"));
1444 KASSERT((td->td_flags & (TDF_SEINTR | TDF_SERESTART)) !=
1445 (TDF_SEINTR | TDF_SERESTART),
1446 ("both TDF_SEINTR and TDF_SERESTART"));
1447 return (TD_SBDRY_INTR(td) ? TD_SBDRY_ERRNO(td) : 0);
1448 }
1449
1450 /*
1451 * We might get here with return_instead == 1 if
1452 * other checks missed it. Then we must not suspend
1453 * regardless of P_SHOULDSTOP() or debugger request.
1454 */
1455 if (return_instead)
1456 return (EINTR);
1457
1458 /*
1459 * If the process is waiting for us to exit,
1460 * this thread should just suicide.
1461 * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
1462 */
1463 if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td)) {
1464 PROC_UNLOCK(p);
1465
1466 /*
1467 * Allow Linux emulation layer to do some work
1468 * before thread suicide.
1469 */
1470 if (__predict_false(p->p_sysent->sv_thread_detach != NULL))
1471 (p->p_sysent->sv_thread_detach)(td);
1472 umtx_thread_exit(td);
1473 kern_thr_exit(td);
1474 panic("stopped thread did not exit");
1475 }
1476
1477 PROC_SLOCK(p);
1478 thread_stopped(p);
1479 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
1480 if (p->p_numthreads == p->p_suspcount + 1) {
1481 thread_lock(p->p_singlethread);
1482 thread_unsuspend_one(p->p_singlethread, p,
1483 false);
1484 }
1485 }
1486 PROC_UNLOCK(p);
1487 thread_lock(td);
1488 /*
1489 * When a thread suspends, it just
1490 * gets taken off all queues.
1491 */
1492 thread_suspend_one(td);
1493 MPASS(!return_instead);
1494 p->p_boundary_count++;
1495 td->td_flags |= TDF_BOUNDARY;
1496 PROC_SUNLOCK(p);
1497 mi_switch(SW_INVOL | SWT_SUSPEND);
1498 PROC_LOCK(p);
1499 }
1500 return (0);
1501 }
1502
1503 /*
1504 * Check for possible stops and suspensions while executing a
1505 * casueword or similar transiently failing operation.
1506 *
1507 * The sleep argument controls whether the function can handle a stop
1508 * request itself or it should return ERESTART and the request is
1509 * proceed at the kernel/user boundary in ast.
1510 *
1511 * Typically, when retrying due to casueword(9) failure (rv == 1), we
1512 * should handle the stop requests there, with exception of cases when
1513 * the thread owns a kernel resource, for instance busied the umtx
1514 * key, or when functions return immediately if thread_check_susp()
1515 * returned non-zero. On the other hand, retrying the whole lock
1516 * operation, we better not stop there but delegate the handling to
1517 * ast.
1518 *
1519 * If the request is for thread termination P_SINGLE_EXIT, we cannot
1520 * handle it at all, and simply return EINTR.
1521 */
1522 int
thread_check_susp(struct thread * td,bool sleep)1523 thread_check_susp(struct thread *td, bool sleep)
1524 {
1525 struct proc *p;
1526 int error;
1527
1528 /*
1529 * The check for TDA_SUSPEND is racy, but it is enough to
1530 * eventually break the lockstep loop.
1531 */
1532 if (!td_ast_pending(td, TDA_SUSPEND))
1533 return (0);
1534 error = 0;
1535 p = td->td_proc;
1536 PROC_LOCK(p);
1537 if (p->p_flag & P_SINGLE_EXIT)
1538 error = EINTR;
1539 else if (P_SHOULDSTOP(p) ||
1540 ((p->p_flag & P_TRACED) && (td->td_dbgflags & TDB_SUSPEND)))
1541 error = sleep ? thread_suspend_check(0) : ERESTART;
1542 PROC_UNLOCK(p);
1543 return (error);
1544 }
1545
1546 void
thread_suspend_switch(struct thread * td,struct proc * p)1547 thread_suspend_switch(struct thread *td, struct proc *p)
1548 {
1549
1550 KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1551 PROC_LOCK_ASSERT(p, MA_OWNED);
1552 PROC_SLOCK_ASSERT(p, MA_OWNED);
1553 /*
1554 * We implement thread_suspend_one in stages here to avoid
1555 * dropping the proc lock while the thread lock is owned.
1556 */
1557 if (p == td->td_proc) {
1558 thread_stopped(p);
1559 p->p_suspcount++;
1560 }
1561 PROC_UNLOCK(p);
1562 thread_lock(td);
1563 ast_unsched_locked(td, TDA_SUSPEND);
1564 TD_SET_SUSPENDED(td);
1565 sched_sleep(td, 0);
1566 PROC_SUNLOCK(p);
1567 DROP_GIANT();
1568 mi_switch(SW_VOL | SWT_SUSPEND);
1569 PICKUP_GIANT();
1570 PROC_LOCK(p);
1571 PROC_SLOCK(p);
1572 }
1573
1574 void
thread_suspend_one(struct thread * td)1575 thread_suspend_one(struct thread *td)
1576 {
1577 struct proc *p;
1578
1579 p = td->td_proc;
1580 PROC_SLOCK_ASSERT(p, MA_OWNED);
1581 THREAD_LOCK_ASSERT(td, MA_OWNED);
1582 KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
1583 p->p_suspcount++;
1584 ast_unsched_locked(td, TDA_SUSPEND);
1585 TD_SET_SUSPENDED(td);
1586 sched_sleep(td, 0);
1587 }
1588
1589 static void
thread_unsuspend_one(struct thread * td,struct proc * p,bool boundary)1590 thread_unsuspend_one(struct thread *td, struct proc *p, bool boundary)
1591 {
1592
1593 THREAD_LOCK_ASSERT(td, MA_OWNED);
1594 KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
1595 TD_CLR_SUSPENDED(td);
1596 td->td_flags &= ~TDF_ALLPROCSUSP;
1597 if (td->td_proc == p) {
1598 PROC_SLOCK_ASSERT(p, MA_OWNED);
1599 p->p_suspcount--;
1600 if (boundary && (td->td_flags & TDF_BOUNDARY) != 0) {
1601 td->td_flags &= ~TDF_BOUNDARY;
1602 p->p_boundary_count--;
1603 }
1604 }
1605 setrunnable(td, 0);
1606 }
1607
1608 void
thread_run_flash(struct thread * td)1609 thread_run_flash(struct thread *td)
1610 {
1611 struct proc *p;
1612
1613 p = td->td_proc;
1614 PROC_LOCK_ASSERT(p, MA_OWNED);
1615
1616 if (TD_ON_SLEEPQ(td))
1617 sleepq_remove_nested(td);
1618 else
1619 thread_lock(td);
1620
1621 THREAD_LOCK_ASSERT(td, MA_OWNED);
1622 KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
1623
1624 TD_CLR_SUSPENDED(td);
1625 PROC_SLOCK(p);
1626 MPASS(p->p_suspcount > 0);
1627 p->p_suspcount--;
1628 PROC_SUNLOCK(p);
1629 setrunnable(td, 0);
1630 }
1631
1632 /*
1633 * Allow all threads blocked by single threading to continue running.
1634 */
1635 void
thread_unsuspend(struct proc * p)1636 thread_unsuspend(struct proc *p)
1637 {
1638 struct thread *td;
1639
1640 PROC_LOCK_ASSERT(p, MA_OWNED);
1641 PROC_SLOCK_ASSERT(p, MA_OWNED);
1642 if (!P_SHOULDSTOP(p)) {
1643 FOREACH_THREAD_IN_PROC(p, td) {
1644 thread_lock(td);
1645 if (TD_IS_SUSPENDED(td))
1646 thread_unsuspend_one(td, p, true);
1647 else
1648 thread_unlock(td);
1649 }
1650 } else if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
1651 p->p_numthreads == p->p_suspcount) {
1652 /*
1653 * Stopping everything also did the job for the single
1654 * threading request. Now we've downgraded to single-threaded,
1655 * let it continue.
1656 */
1657 if (p->p_singlethread->td_proc == p) {
1658 thread_lock(p->p_singlethread);
1659 thread_unsuspend_one(p->p_singlethread, p, false);
1660 }
1661 }
1662 }
1663
1664 /*
1665 * End the single threading mode..
1666 */
1667 void
thread_single_end(struct proc * p,int mode)1668 thread_single_end(struct proc *p, int mode)
1669 {
1670 struct thread *td;
1671
1672 KASSERT(mode == SINGLE_EXIT || mode == SINGLE_BOUNDARY ||
1673 mode == SINGLE_ALLPROC || mode == SINGLE_NO_EXIT,
1674 ("invalid mode %d", mode));
1675 PROC_LOCK_ASSERT(p, MA_OWNED);
1676 KASSERT((mode == SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) != 0) ||
1677 (mode != SINGLE_ALLPROC && (p->p_flag & P_TOTAL_STOP) == 0),
1678 ("mode %d does not match P_TOTAL_STOP", mode));
1679 KASSERT(mode == SINGLE_ALLPROC || p->p_singlethread == curthread,
1680 ("thread_single_end from other thread %p %p",
1681 curthread, p->p_singlethread));
1682 KASSERT(mode != SINGLE_BOUNDARY ||
1683 (p->p_flag & P_SINGLE_BOUNDARY) != 0,
1684 ("mis-matched SINGLE_BOUNDARY flags %x", p->p_flag));
1685 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY |
1686 P_TOTAL_STOP);
1687 PROC_SLOCK(p);
1688 p->p_singlethread = NULL;
1689
1690 /*
1691 * If there are other threads they may now run,
1692 * unless of course there is a blanket 'stop order'
1693 * on the process. The single threader must be allowed
1694 * to continue however as this is a bad place to stop.
1695 */
1696 if (p->p_numthreads != remain_for_mode(mode) && !P_SHOULDSTOP(p)) {
1697 FOREACH_THREAD_IN_PROC(p, td) {
1698 thread_lock(td);
1699 if (TD_IS_SUSPENDED(td))
1700 thread_unsuspend_one(td, p, true);
1701 else
1702 thread_unlock(td);
1703 }
1704 }
1705 KASSERT(mode != SINGLE_BOUNDARY || P_SHOULDSTOP(p) ||
1706 p->p_boundary_count == 0,
1707 ("pid %d proc %p flags %#x inconsistent boundary count %d",
1708 p->p_pid, p, p->p_flag, p->p_boundary_count));
1709 PROC_SUNLOCK(p);
1710 wakeup(&p->p_flag);
1711 }
1712
1713 /*
1714 * Locate a thread by number and return with proc lock held.
1715 *
1716 * thread exit establishes proc -> tidhash lock ordering, but lookup
1717 * takes tidhash first and needs to return locked proc.
1718 *
1719 * The problem is worked around by relying on type-safety of both
1720 * structures and doing the work in 2 steps:
1721 * - tidhash-locked lookup which saves both thread and proc pointers
1722 * - proc-locked verification that the found thread still matches
1723 */
1724 static bool
tdfind_hash(lwpid_t tid,pid_t pid,struct proc ** pp,struct thread ** tdp)1725 tdfind_hash(lwpid_t tid, pid_t pid, struct proc **pp, struct thread **tdp)
1726 {
1727 #define RUN_THRESH 16
1728 struct proc *p;
1729 struct thread *td;
1730 int run;
1731 bool locked;
1732
1733 run = 0;
1734 rw_rlock(TIDHASHLOCK(tid));
1735 locked = true;
1736 LIST_FOREACH(td, TIDHASH(tid), td_hash) {
1737 if (td->td_tid != tid) {
1738 run++;
1739 continue;
1740 }
1741 p = td->td_proc;
1742 if (pid != -1 && p->p_pid != pid) {
1743 td = NULL;
1744 break;
1745 }
1746 if (run > RUN_THRESH) {
1747 if (rw_try_upgrade(TIDHASHLOCK(tid))) {
1748 LIST_REMOVE(td, td_hash);
1749 LIST_INSERT_HEAD(TIDHASH(td->td_tid),
1750 td, td_hash);
1751 rw_wunlock(TIDHASHLOCK(tid));
1752 locked = false;
1753 break;
1754 }
1755 }
1756 break;
1757 }
1758 if (locked)
1759 rw_runlock(TIDHASHLOCK(tid));
1760 if (td == NULL)
1761 return (false);
1762 *pp = p;
1763 *tdp = td;
1764 return (true);
1765 }
1766
1767 struct thread *
tdfind(lwpid_t tid,pid_t pid)1768 tdfind(lwpid_t tid, pid_t pid)
1769 {
1770 struct proc *p;
1771 struct thread *td;
1772
1773 td = curthread;
1774 if (td->td_tid == tid) {
1775 if (pid != -1 && td->td_proc->p_pid != pid)
1776 return (NULL);
1777 PROC_LOCK(td->td_proc);
1778 return (td);
1779 }
1780
1781 for (;;) {
1782 if (!tdfind_hash(tid, pid, &p, &td))
1783 return (NULL);
1784 PROC_LOCK(p);
1785 if (td->td_tid != tid) {
1786 PROC_UNLOCK(p);
1787 continue;
1788 }
1789 if (td->td_proc != p) {
1790 PROC_UNLOCK(p);
1791 continue;
1792 }
1793 if (p->p_state == PRS_NEW) {
1794 PROC_UNLOCK(p);
1795 return (NULL);
1796 }
1797 return (td);
1798 }
1799 }
1800
1801 void
tidhash_add(struct thread * td)1802 tidhash_add(struct thread *td)
1803 {
1804 rw_wlock(TIDHASHLOCK(td->td_tid));
1805 LIST_INSERT_HEAD(TIDHASH(td->td_tid), td, td_hash);
1806 rw_wunlock(TIDHASHLOCK(td->td_tid));
1807 }
1808
1809 void
tidhash_remove(struct thread * td)1810 tidhash_remove(struct thread *td)
1811 {
1812
1813 rw_wlock(TIDHASHLOCK(td->td_tid));
1814 LIST_REMOVE(td, td_hash);
1815 rw_wunlock(TIDHASHLOCK(td->td_tid));
1816 }
1817