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