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