Home | History | Annotate | Line # | Download | only in kern
kern_lwp.c revision 1.266
      1 /*	$NetBSD: kern_lwp.c,v 1.266 2023/10/15 10:27:11 riastradh Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2001, 2006, 2007, 2008, 2009, 2019, 2020, 2023
      5  *     The NetBSD Foundation, Inc.
      6  * All rights reserved.
      7  *
      8  * This code is derived from software contributed to The NetBSD Foundation
      9  * by Nathan J. Williams, and Andrew Doran.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 /*
     34  * Overview
     35  *
     36  *	Lightweight processes (LWPs) are the basic unit or thread of
     37  *	execution within the kernel.  The core state of an LWP is described
     38  *	by "struct lwp", also known as lwp_t.
     39  *
     40  *	Each LWP is contained within a process (described by "struct proc"),
     41  *	Every process contains at least one LWP, but may contain more.  The
     42  *	process describes attributes shared among all of its LWPs such as a
     43  *	private address space, global execution state (stopped, active,
     44  *	zombie, ...), signal disposition and so on.  On a multiprocessor
     45  *	machine, multiple LWPs be executing concurrently in the kernel.
     46  *
     47  * Execution states
     48  *
     49  *	At any given time, an LWP has overall state that is described by
     50  *	lwp::l_stat.  The states are broken into two sets below.  The first
     51  *	set is guaranteed to represent the absolute, current state of the
     52  *	LWP:
     53  *
     54  *	LSONPROC
     55  *
     56  *		On processor: the LWP is executing on a CPU, either in the
     57  *		kernel or in user space.
     58  *
     59  *	LSRUN
     60  *
     61  *		Runnable: the LWP is parked on a run queue, and may soon be
     62  *		chosen to run by an idle processor, or by a processor that
     63  *		has been asked to preempt a currently runnning but lower
     64  *		priority LWP.
     65  *
     66  *	LSIDL
     67  *
     68  *		Idle: the LWP has been created but has not yet executed, or
     69  *		it has ceased executing a unit of work and is waiting to be
     70  *		started again.  This state exists so that the LWP can occupy
     71  *		a slot in the process & PID table, but without having to
     72  *		worry about being touched; lookups of the LWP by ID will
     73  *		fail while in this state.  The LWP will become visible for
     74  *		lookup once its state transitions further.  Some special
     75  *		kernel threads also (ab)use this state to indicate that they
     76  *		are idle (soft interrupts and idle LWPs).
     77  *
     78  *	LSSUSPENDED:
     79  *
     80  *		Suspended: the LWP has had its execution suspended by
     81  *		another LWP in the same process using the _lwp_suspend()
     82  *		system call.  User-level LWPs also enter the suspended
     83  *		state when the system is shutting down.
     84  *
     85  *	The second set represent a "statement of intent" on behalf of the
     86  *	LWP.  The LWP may in fact be executing on a processor, may be
     87  *	sleeping or idle. It is expected to take the necessary action to
     88  *	stop executing or become "running" again within a short timeframe.
     89  *	The LP_RUNNING flag in lwp::l_pflag indicates that an LWP is running.
     90  *	Importantly, it indicates that its state is tied to a CPU.
     91  *
     92  *	LSZOMB:
     93  *
     94  *		Dead or dying: the LWP has released most of its resources
     95  *		and is about to switch away into oblivion, or has already
     96  *		switched away.  When it switches away, its few remaining
     97  *		resources can be collected.
     98  *
     99  *	LSSLEEP:
    100  *
    101  *		Sleeping: the LWP has entered itself onto a sleep queue, and
    102  *		has switched away or will switch away shortly to allow other
    103  *		LWPs to run on the CPU.
    104  *
    105  *	LSSTOP:
    106  *
    107  *		Stopped: the LWP has been stopped as a result of a job
    108  *		control signal, or as a result of the ptrace() interface.
    109  *
    110  *		Stopped LWPs may run briefly within the kernel to handle
    111  *		signals that they receive, but will not return to user space
    112  *		until their process' state is changed away from stopped.
    113  *
    114  *		Single LWPs within a process can not be set stopped
    115  *		selectively: all actions that can stop or continue LWPs
    116  *		occur at the process level.
    117  *
    118  * State transitions
    119  *
    120  *	Note that the LSSTOP state may only be set when returning to
    121  *	user space in userret(), or when sleeping interruptably.  The
    122  *	LSSUSPENDED state may only be set in userret().  Before setting
    123  *	those states, we try to ensure that the LWPs will release all
    124  *	locks that they hold, and at a minimum try to ensure that the
    125  *	LWP can be set runnable again by a signal.
    126  *
    127  *	LWPs may transition states in the following ways:
    128  *
    129  *	 RUN -------> ONPROC		ONPROC -----> RUN
    130  *		    				    > SLEEP
    131  *		    				    > STOPPED
    132  *						    > SUSPENDED
    133  *						    > ZOMB
    134  *						    > IDL (special cases)
    135  *
    136  *	 STOPPED ---> RUN		SUSPENDED --> RUN
    137  *	            > SLEEP
    138  *
    139  *	 SLEEP -----> ONPROC		IDL --------> RUN
    140  *		    > RUN			    > SUSPENDED
    141  *		    > STOPPED			    > STOPPED
    142  *						    > ONPROC (special cases)
    143  *
    144  *	Some state transitions are only possible with kernel threads (eg
    145  *	ONPROC -> IDL) and happen under tightly controlled circumstances
    146  *	free of unwanted side effects.
    147  *
    148  * Migration
    149  *
    150  *	Migration of threads from one CPU to another could be performed
    151  *	internally by the scheduler via sched_takecpu() or sched_catchlwp()
    152  *	functions.  The universal lwp_migrate() function should be used for
    153  *	any other cases.  Subsystems in the kernel must be aware that CPU
    154  *	of LWP may change, while it is not locked.
    155  *
    156  * Locking
    157  *
    158  *	The majority of fields in 'struct lwp' are covered by a single,
    159  *	general spin lock pointed to by lwp::l_mutex.  The locks covering
    160  *	each field are documented in sys/lwp.h.
    161  *
    162  *	State transitions must be made with the LWP's general lock held,
    163  *	and may cause the LWP's lock pointer to change.  Manipulation of
    164  *	the general lock is not performed directly, but through calls to
    165  *	lwp_lock(), lwp_unlock() and others.  It should be noted that the
    166  *	adaptive locks are not allowed to be released while the LWP's lock
    167  *	is being held (unlike for other spin-locks).
    168  *
    169  *	States and their associated locks:
    170  *
    171  *	LSIDL, LSONPROC, LSZOMB, LSSUPENDED:
    172  *
    173  *		Always covered by spc_lwplock, which protects LWPs not
    174  *		associated with any other sync object.  This is a per-CPU
    175  *		lock and matches lwp::l_cpu.
    176  *
    177  *	LSRUN:
    178  *
    179  *		Always covered by spc_mutex, which protects the run queues.
    180  *		This is a per-CPU lock and matches lwp::l_cpu.
    181  *
    182  *	LSSLEEP:
    183  *
    184  *		Covered by a lock associated with the sleep queue (sometimes
    185  *		a turnstile sleep queue) that the LWP resides on.  This can
    186  *		be spc_lwplock for SOBJ_SLEEPQ_NULL (an "untracked" sleep).
    187  *
    188  *	LSSTOP:
    189  *
    190  *		If the LWP was previously sleeping (l_wchan != NULL), then
    191  *		l_mutex references the sleep queue lock.  If the LWP was
    192  *		runnable or on the CPU when halted, or has been removed from
    193  *		the sleep queue since halted, then the lock is spc_lwplock.
    194  *
    195  *	The lock order is as follows:
    196  *
    197  *		sleepq -> turnstile -> spc_lwplock -> spc_mutex
    198  *
    199  *	Each process has a scheduler state lock (proc::p_lock), and a
    200  *	number of counters on LWPs and their states: p_nzlwps, p_nrlwps, and
    201  *	so on.  When an LWP is to be entered into or removed from one of the
    202  *	following states, p_lock must be held and the process wide counters
    203  *	adjusted:
    204  *
    205  *		LSIDL, LSZOMB, LSSTOP, LSSUSPENDED
    206  *
    207  *	(But not always for kernel threads.  There are some special cases
    208  *	as mentioned above: soft interrupts, and the idle loops.)
    209  *
    210  *	Note that an LWP is considered running or likely to run soon if in
    211  *	one of the following states.  This affects the value of p_nrlwps:
    212  *
    213  *		LSRUN, LSONPROC, LSSLEEP
    214  *
    215  *	p_lock does not need to be held when transitioning among these
    216  *	three states, hence p_lock is rarely taken for state transitions.
    217  */
    218 
    219 #include <sys/cdefs.h>
    220 __KERNEL_RCSID(0, "$NetBSD: kern_lwp.c,v 1.266 2023/10/15 10:27:11 riastradh Exp $");
    221 
    222 #include "opt_ddb.h"
    223 #include "opt_lockdebug.h"
    224 #include "opt_dtrace.h"
    225 
    226 #define _LWP_API_PRIVATE
    227 
    228 #include <sys/param.h>
    229 #include <sys/systm.h>
    230 #include <sys/cpu.h>
    231 #include <sys/pool.h>
    232 #include <sys/proc.h>
    233 #include <sys/syscallargs.h>
    234 #include <sys/syscall_stats.h>
    235 #include <sys/kauth.h>
    236 #include <sys/sleepq.h>
    237 #include <sys/lockdebug.h>
    238 #include <sys/kmem.h>
    239 #include <sys/pset.h>
    240 #include <sys/intr.h>
    241 #include <sys/lwpctl.h>
    242 #include <sys/atomic.h>
    243 #include <sys/filedesc.h>
    244 #include <sys/fstrans.h>
    245 #include <sys/dtrace_bsd.h>
    246 #include <sys/sdt.h>
    247 #include <sys/ptrace.h>
    248 #include <sys/xcall.h>
    249 #include <sys/uidinfo.h>
    250 #include <sys/sysctl.h>
    251 #include <sys/psref.h>
    252 #include <sys/msan.h>
    253 #include <sys/kcov.h>
    254 #include <sys/cprng.h>
    255 #include <sys/futex.h>
    256 #include <sys/syncobj.h>
    257 
    258 #include <uvm/uvm_extern.h>
    259 #include <uvm/uvm_object.h>
    260 
    261 static pool_cache_t	lwp_cache	__read_mostly;
    262 struct lwplist		alllwp		__cacheline_aligned;
    263 
    264 static int		lwp_ctor(void *, void *, int);
    265 static void		lwp_dtor(void *, void *);
    266 
    267 /* DTrace proc provider probes */
    268 SDT_PROVIDER_DEFINE(proc);
    269 
    270 SDT_PROBE_DEFINE1(proc, kernel, , lwp__create, "struct lwp *");
    271 SDT_PROBE_DEFINE1(proc, kernel, , lwp__start, "struct lwp *");
    272 SDT_PROBE_DEFINE1(proc, kernel, , lwp__exit, "struct lwp *");
    273 
    274 struct turnstile turnstile0 __cacheline_aligned;
    275 struct lwp lwp0 __aligned(MIN_LWP_ALIGNMENT) = {
    276 #ifdef LWP0_CPU_INFO
    277 	.l_cpu = LWP0_CPU_INFO,
    278 #endif
    279 #ifdef LWP0_MD_INITIALIZER
    280 	.l_md = LWP0_MD_INITIALIZER,
    281 #endif
    282 	.l_proc = &proc0,
    283 	.l_lid = 0,		/* we own proc0's slot in the pid table */
    284 	.l_flag = LW_SYSTEM,
    285 	.l_stat = LSONPROC,
    286 	.l_ts = &turnstile0,
    287 	.l_syncobj = &sched_syncobj,
    288 	.l_refcnt = 0,
    289 	.l_priority = PRI_USER + NPRI_USER - 1,
    290 	.l_inheritedprio = -1,
    291 	.l_class = SCHED_OTHER,
    292 	.l_psid = PS_NONE,
    293 	.l_pi_lenders = SLIST_HEAD_INITIALIZER(&lwp0.l_pi_lenders),
    294 	.l_name = __UNCONST("swapper"),
    295 	.l_fd = &filedesc0,
    296 };
    297 
    298 static int
    299 lwp_maxlwp(void)
    300 {
    301 	/* Assume 1 LWP per 1MiB. */
    302 	uint64_t lwps_per = ctob(physmem) / (1024 * 1024);
    303 
    304 	return MAX(MIN(MAXMAXLWP, lwps_per), MAXLWP);
    305 }
    306 
    307 static int sysctl_kern_maxlwp(SYSCTLFN_PROTO);
    308 
    309 /*
    310  * sysctl helper routine for kern.maxlwp. Ensures that the new
    311  * values are not too low or too high.
    312  */
    313 static int
    314 sysctl_kern_maxlwp(SYSCTLFN_ARGS)
    315 {
    316 	int error, nmaxlwp;
    317 	struct sysctlnode node;
    318 
    319 	nmaxlwp = maxlwp;
    320 	node = *rnode;
    321 	node.sysctl_data = &nmaxlwp;
    322 	error = sysctl_lookup(SYSCTLFN_CALL(&node));
    323 	if (error || newp == NULL)
    324 		return error;
    325 
    326 	if (nmaxlwp < 0 || nmaxlwp >= MAXMAXLWP)
    327 		return EINVAL;
    328 	if (nmaxlwp > lwp_maxlwp())
    329 		return EINVAL;
    330 	maxlwp = nmaxlwp;
    331 
    332 	return 0;
    333 }
    334 
    335 static void
    336 sysctl_kern_lwp_setup(void)
    337 {
    338 	sysctl_createv(NULL, 0, NULL, NULL,
    339 		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
    340 		       CTLTYPE_INT, "maxlwp",
    341 		       SYSCTL_DESCR("Maximum number of simultaneous threads"),
    342 		       sysctl_kern_maxlwp, 0, NULL, 0,
    343 		       CTL_KERN, CTL_CREATE, CTL_EOL);
    344 }
    345 
    346 void
    347 lwpinit(void)
    348 {
    349 
    350 	LIST_INIT(&alllwp);
    351 	lwpinit_specificdata();
    352 	/*
    353 	 * Provide a barrier to ensure that all mutex_oncpu() and rw_oncpu()
    354 	 * calls will exit before memory of LWPs is returned to the pool, where
    355 	 * KVA of LWP structure might be freed and re-used for other purposes.
    356 	 * Kernel preemption is disabled around mutex_oncpu() and rw_oncpu()
    357 	 * callers, therefore a regular passive serialization barrier will
    358 	 * do the job.
    359 	 */
    360 	lwp_cache = pool_cache_init(sizeof(lwp_t), MIN_LWP_ALIGNMENT, 0,
    361 	    PR_PSERIALIZE, "lwppl", NULL, IPL_NONE, lwp_ctor, lwp_dtor, NULL);
    362 
    363 	maxlwp = lwp_maxlwp();
    364 	sysctl_kern_lwp_setup();
    365 }
    366 
    367 void
    368 lwp0_init(void)
    369 {
    370 	struct lwp *l = &lwp0;
    371 
    372 	KASSERT((void *)uvm_lwp_getuarea(l) != NULL);
    373 
    374 	LIST_INSERT_HEAD(&alllwp, l, l_list);
    375 
    376 	callout_init(&l->l_timeout_ch, CALLOUT_MPSAFE);
    377 	callout_setfunc(&l->l_timeout_ch, sleepq_timeout, l);
    378 	cv_init(&l->l_sigcv, "sigwait");
    379 	cv_init(&l->l_waitcv, "vfork");
    380 
    381 	l->l_cred = kauth_cred_hold(proc0.p_cred);
    382 
    383 	kdtrace_thread_ctor(NULL, l);
    384 	lwp_initspecific(l);
    385 
    386 	SYSCALL_TIME_LWP_INIT(l);
    387 }
    388 
    389 /*
    390  * Initialize the non-zeroed portion of an lwp_t.
    391  */
    392 static int
    393 lwp_ctor(void *arg, void *obj, int flags)
    394 {
    395 	lwp_t *l = obj;
    396 
    397 	l->l_stat = LSIDL;
    398 	l->l_cpu = curcpu();
    399 	l->l_mutex = l->l_cpu->ci_schedstate.spc_lwplock;
    400 	l->l_ts = kmem_alloc(sizeof(*l->l_ts), flags == PR_WAITOK ?
    401 	    KM_SLEEP : KM_NOSLEEP);
    402 
    403 	if (l->l_ts == NULL) {
    404 		return ENOMEM;
    405 	} else {
    406 		turnstile_ctor(l->l_ts);
    407 		return 0;
    408 	}
    409 }
    410 
    411 static void
    412 lwp_dtor(void *arg, void *obj)
    413 {
    414 	lwp_t *l = obj;
    415 
    416 	/*
    417 	 * The value of l->l_cpu must still be valid at this point.
    418 	 */
    419 	KASSERT(l->l_cpu != NULL);
    420 
    421 	/*
    422 	 * We can't return turnstile0 to the pool (it didn't come from it),
    423 	 * so if it comes up just drop it quietly and move on.
    424 	 */
    425 	if (l->l_ts != &turnstile0)
    426 		kmem_free(l->l_ts, sizeof(*l->l_ts));
    427 }
    428 
    429 /*
    430  * Set an LWP suspended.
    431  *
    432  * Must be called with p_lock held, and the LWP locked.  Will unlock the
    433  * LWP before return.
    434  */
    435 int
    436 lwp_suspend(struct lwp *curl, struct lwp *t)
    437 {
    438 	int error;
    439 
    440 	KASSERT(mutex_owned(t->l_proc->p_lock));
    441 	KASSERT(lwp_locked(t, NULL));
    442 
    443 	KASSERT(curl != t || curl->l_stat == LSONPROC);
    444 
    445 	/*
    446 	 * If the current LWP has been told to exit, we must not suspend anyone
    447 	 * else or deadlock could occur.  We won't return to userspace.
    448 	 */
    449 	if ((curl->l_flag & (LW_WEXIT | LW_WCORE)) != 0) {
    450 		lwp_unlock(t);
    451 		return (EDEADLK);
    452 	}
    453 
    454 	if ((t->l_flag & LW_DBGSUSPEND) != 0) {
    455 		lwp_unlock(t);
    456 		return 0;
    457 	}
    458 
    459 	error = 0;
    460 
    461 	switch (t->l_stat) {
    462 	case LSRUN:
    463 	case LSONPROC:
    464 		t->l_flag |= LW_WSUSPEND;
    465 		lwp_need_userret(t);
    466 		lwp_unlock(t);
    467 		break;
    468 
    469 	case LSSLEEP:
    470 		t->l_flag |= LW_WSUSPEND;
    471 		lwp_need_userret(t);
    472 
    473 		/*
    474 		 * Kick the LWP and try to get it to the kernel boundary
    475 		 * so that it will release any locks that it holds.
    476 		 * setrunnable() will release the lock.
    477 		 */
    478 		if ((t->l_flag & LW_SINTR) != 0)
    479 			setrunnable(t);
    480 		else
    481 			lwp_unlock(t);
    482 		break;
    483 
    484 	case LSSUSPENDED:
    485 		lwp_unlock(t);
    486 		break;
    487 
    488 	case LSSTOP:
    489 		t->l_flag |= LW_WSUSPEND;
    490 		lwp_need_userret(t);
    491 		setrunnable(t);
    492 		break;
    493 
    494 	case LSIDL:
    495 	case LSZOMB:
    496 		error = EINTR; /* It's what Solaris does..... */
    497 		lwp_unlock(t);
    498 		break;
    499 	}
    500 
    501 	return (error);
    502 }
    503 
    504 /*
    505  * Restart a suspended LWP.
    506  *
    507  * Must be called with p_lock held, and the LWP locked.  Will unlock the
    508  * LWP before return.
    509  */
    510 void
    511 lwp_continue(struct lwp *l)
    512 {
    513 
    514 	KASSERT(mutex_owned(l->l_proc->p_lock));
    515 	KASSERT(lwp_locked(l, NULL));
    516 
    517 	/* If rebooting or not suspended, then just bail out. */
    518 	if ((l->l_flag & LW_WREBOOT) != 0) {
    519 		lwp_unlock(l);
    520 		return;
    521 	}
    522 
    523 	l->l_flag &= ~LW_WSUSPEND;
    524 
    525 	if (l->l_stat != LSSUSPENDED || (l->l_flag & LW_DBGSUSPEND) != 0) {
    526 		lwp_unlock(l);
    527 		return;
    528 	}
    529 
    530 	/* setrunnable() will release the lock. */
    531 	setrunnable(l);
    532 }
    533 
    534 /*
    535  * Restart a stopped LWP.
    536  *
    537  * Must be called with p_lock held, and the LWP NOT locked.  Will unlock the
    538  * LWP before return.
    539  */
    540 void
    541 lwp_unstop(struct lwp *l)
    542 {
    543 	struct proc *p = l->l_proc;
    544 
    545 	KASSERT(mutex_owned(&proc_lock));
    546 	KASSERT(mutex_owned(p->p_lock));
    547 
    548 	lwp_lock(l);
    549 
    550 	KASSERT((l->l_flag & LW_DBGSUSPEND) == 0);
    551 
    552 	/* If not stopped, then just bail out. */
    553 	if (l->l_stat != LSSTOP) {
    554 		lwp_unlock(l);
    555 		return;
    556 	}
    557 
    558 	p->p_stat = SACTIVE;
    559 	p->p_sflag &= ~PS_STOPPING;
    560 
    561 	if (!p->p_waited)
    562 		p->p_pptr->p_nstopchild--;
    563 
    564 	if (l->l_wchan == NULL) {
    565 		/* setrunnable() will release the lock. */
    566 		setrunnable(l);
    567 	} else if (p->p_xsig && (l->l_flag & LW_SINTR) != 0) {
    568 		/* setrunnable() so we can receive the signal */
    569 		setrunnable(l);
    570 	} else {
    571 		l->l_stat = LSSLEEP;
    572 		p->p_nrlwps++;
    573 		lwp_unlock(l);
    574 	}
    575 }
    576 
    577 /*
    578  * Wait for an LWP within the current process to exit.  If 'lid' is
    579  * non-zero, we are waiting for a specific LWP.
    580  *
    581  * Must be called with p->p_lock held.
    582  */
    583 int
    584 lwp_wait(struct lwp *l, lwpid_t lid, lwpid_t *departed, bool exiting)
    585 {
    586 	const lwpid_t curlid = l->l_lid;
    587 	proc_t *p = l->l_proc;
    588 	lwp_t *l2, *next;
    589 	int error;
    590 
    591 	KASSERT(mutex_owned(p->p_lock));
    592 
    593 	p->p_nlwpwait++;
    594 	l->l_waitingfor = lid;
    595 
    596 	for (;;) {
    597 		int nfound;
    598 
    599 		/*
    600 		 * Avoid a race between exit1() and sigexit(): if the
    601 		 * process is dumping core, then we need to bail out: call
    602 		 * into lwp_userret() where we will be suspended until the
    603 		 * deed is done.
    604 		 */
    605 		if ((p->p_sflag & PS_WCORE) != 0) {
    606 			mutex_exit(p->p_lock);
    607 			lwp_userret(l);
    608 			KASSERT(false);
    609 		}
    610 
    611 		/*
    612 		 * First off, drain any detached LWP that is waiting to be
    613 		 * reaped.
    614 		 */
    615 		if ((l2 = p->p_zomblwp) != NULL) {
    616 			p->p_zomblwp = NULL;
    617 			lwp_free(l2, false, false);/* releases proc mutex */
    618 			mutex_enter(p->p_lock);
    619 			continue;
    620 		}
    621 
    622 		/*
    623 		 * Now look for an LWP to collect.  If the whole process is
    624 		 * exiting, count detached LWPs as eligible to be collected,
    625 		 * but don't drain them here.
    626 		 */
    627 		nfound = 0;
    628 		error = 0;
    629 
    630 		/*
    631 		 * If given a specific LID, go via pid_table and make sure
    632 		 * it's not detached.
    633 		 */
    634 		if (lid != 0) {
    635 			l2 = proc_find_lwp(p, lid);
    636 			if (l2 == NULL) {
    637 				error = ESRCH;
    638 				break;
    639 			}
    640 			KASSERT(l2->l_lid == lid);
    641 			if ((l2->l_prflag & LPR_DETACHED) != 0) {
    642 				error = EINVAL;
    643 				break;
    644 			}
    645 		} else {
    646 			l2 = LIST_FIRST(&p->p_lwps);
    647 		}
    648 		for (; l2 != NULL; l2 = next) {
    649 			next = (lid != 0 ? NULL : LIST_NEXT(l2, l_sibling));
    650 
    651 			/*
    652 			 * If a specific wait and the target is waiting on
    653 			 * us, then avoid deadlock.  This also traps LWPs
    654 			 * that try to wait on themselves.
    655 			 *
    656 			 * Note that this does not handle more complicated
    657 			 * cycles, like: t1 -> t2 -> t3 -> t1.  The process
    658 			 * can still be killed so it is not a major problem.
    659 			 */
    660 			if (l2->l_lid == lid && l2->l_waitingfor == curlid) {
    661 				error = EDEADLK;
    662 				break;
    663 			}
    664 			if (l2 == l)
    665 				continue;
    666 			if ((l2->l_prflag & LPR_DETACHED) != 0) {
    667 				nfound += exiting;
    668 				continue;
    669 			}
    670 			if (lid != 0) {
    671 				/*
    672 				 * Mark this LWP as the first waiter, if there
    673 				 * is no other.
    674 				 */
    675 				if (l2->l_waiter == 0)
    676 					l2->l_waiter = curlid;
    677 			} else if (l2->l_waiter != 0) {
    678 				/*
    679 				 * It already has a waiter - so don't
    680 				 * collect it.  If the waiter doesn't
    681 				 * grab it we'll get another chance
    682 				 * later.
    683 				 */
    684 				nfound++;
    685 				continue;
    686 			}
    687 			nfound++;
    688 
    689 			/* No need to lock the LWP in order to see LSZOMB. */
    690 			if (l2->l_stat != LSZOMB)
    691 				continue;
    692 
    693 			/*
    694 			 * We're no longer waiting.  Reset the "first waiter"
    695 			 * pointer on the target, in case it was us.
    696 			 */
    697 			l->l_waitingfor = 0;
    698 			l2->l_waiter = 0;
    699 			p->p_nlwpwait--;
    700 			if (departed)
    701 				*departed = l2->l_lid;
    702 			sched_lwp_collect(l2);
    703 
    704 			/* lwp_free() releases the proc lock. */
    705 			lwp_free(l2, false, false);
    706 			mutex_enter(p->p_lock);
    707 			return 0;
    708 		}
    709 
    710 		if (error != 0)
    711 			break;
    712 		if (nfound == 0) {
    713 			error = ESRCH;
    714 			break;
    715 		}
    716 
    717 		/*
    718 		 * Note: since the lock will be dropped, need to restart on
    719 		 * wakeup to run all LWPs again, e.g. there may be new LWPs.
    720 		 */
    721 		if (exiting) {
    722 			KASSERT(p->p_nlwps > 1);
    723 			error = cv_timedwait(&p->p_lwpcv, p->p_lock, 1);
    724 			break;
    725 		}
    726 
    727 		/*
    728 		 * Break out if all LWPs are in _lwp_wait().  There are
    729 		 * other ways to hang the process with _lwp_wait(), but the
    730 		 * sleep is interruptable so little point checking for them.
    731 		 */
    732 		if (p->p_nlwpwait == p->p_nlwps) {
    733 			error = EDEADLK;
    734 			break;
    735 		}
    736 
    737 		/*
    738 		 * Sit around and wait for something to happen.  We'll be
    739 		 * awoken if any of the conditions examined change: if an
    740 		 * LWP exits, is collected, or is detached.
    741 		 */
    742 		if ((error = cv_wait_sig(&p->p_lwpcv, p->p_lock)) != 0)
    743 			break;
    744 	}
    745 
    746 	/*
    747 	 * We didn't find any LWPs to collect, we may have received a
    748 	 * signal, or some other condition has caused us to bail out.
    749 	 *
    750 	 * If waiting on a specific LWP, clear the waiters marker: some
    751 	 * other LWP may want it.  Then, kick all the remaining waiters
    752 	 * so that they can re-check for zombies and for deadlock.
    753 	 */
    754 	if (lid != 0) {
    755 		l2 = proc_find_lwp(p, lid);
    756 		KASSERT(l2 == NULL || l2->l_lid == lid);
    757 
    758 		if (l2 != NULL && l2->l_waiter == curlid)
    759 			l2->l_waiter = 0;
    760 	}
    761 	p->p_nlwpwait--;
    762 	l->l_waitingfor = 0;
    763 	cv_broadcast(&p->p_lwpcv);
    764 
    765 	return error;
    766 }
    767 
    768 /*
    769  * Create a new LWP within process 'p2', using LWP 'l1' as a template.
    770  * The new LWP is created in state LSIDL and must be set running,
    771  * suspended, or stopped by the caller.
    772  */
    773 int
    774 lwp_create(lwp_t *l1, proc_t *p2, vaddr_t uaddr, int flags,
    775     void *stack, size_t stacksize, void (*func)(void *), void *arg,
    776     lwp_t **rnewlwpp, int sclass, const sigset_t *sigmask,
    777     const stack_t *sigstk)
    778 {
    779 	struct lwp *l2;
    780 
    781 	KASSERT(l1 == curlwp || l1->l_proc == &proc0);
    782 
    783 	/*
    784 	 * Enforce limits, excluding the first lwp and kthreads.  We must
    785 	 * use the process credentials here when adjusting the limit, as
    786 	 * they are what's tied to the accounting entity.  However for
    787 	 * authorizing the action, we'll use the LWP's credentials.
    788 	 */
    789 	mutex_enter(p2->p_lock);
    790 	if (p2->p_nlwps != 0 && p2 != &proc0) {
    791 		uid_t uid = kauth_cred_getuid(p2->p_cred);
    792 		int count = chglwpcnt(uid, 1);
    793 		if (__predict_false(count >
    794 		    p2->p_rlimit[RLIMIT_NTHR].rlim_cur)) {
    795 			if (kauth_authorize_process(l1->l_cred,
    796 			    KAUTH_PROCESS_RLIMIT, p2,
    797 			    KAUTH_ARG(KAUTH_REQ_PROCESS_RLIMIT_BYPASS),
    798 			    &p2->p_rlimit[RLIMIT_NTHR], KAUTH_ARG(RLIMIT_NTHR))
    799 			    != 0) {
    800 				(void)chglwpcnt(uid, -1);
    801 				mutex_exit(p2->p_lock);
    802 				return EAGAIN;
    803 			}
    804 		}
    805 	}
    806 
    807 	/*
    808 	 * First off, reap any detached LWP waiting to be collected.
    809 	 * We can re-use its LWP structure and turnstile.
    810 	 */
    811 	if ((l2 = p2->p_zomblwp) != NULL) {
    812 		p2->p_zomblwp = NULL;
    813 		lwp_free(l2, true, false);
    814 		/* p2 now unlocked by lwp_free() */
    815 		KASSERT(l2->l_ts != NULL);
    816 		KASSERT(l2->l_inheritedprio == -1);
    817 		KASSERT(SLIST_EMPTY(&l2->l_pi_lenders));
    818 		memset(&l2->l_startzero, 0, sizeof(*l2) -
    819 		    offsetof(lwp_t, l_startzero));
    820 	} else {
    821 		mutex_exit(p2->p_lock);
    822 		l2 = pool_cache_get(lwp_cache, PR_WAITOK);
    823 		memset(&l2->l_startzero, 0, sizeof(*l2) -
    824 		    offsetof(lwp_t, l_startzero));
    825 		SLIST_INIT(&l2->l_pi_lenders);
    826 	}
    827 
    828 	/*
    829 	 * Because of lockless lookup via pid_table, the LWP can be locked
    830 	 * and inspected briefly even after it's freed, so a few fields are
    831 	 * kept stable.
    832 	 */
    833 	KASSERT(l2->l_stat == LSIDL);
    834 	KASSERT(l2->l_cpu != NULL);
    835 	KASSERT(l2->l_ts != NULL);
    836 	KASSERT(l2->l_mutex == l2->l_cpu->ci_schedstate.spc_lwplock);
    837 
    838 	l2->l_proc = p2;
    839 	l2->l_refcnt = 0;
    840 	l2->l_class = sclass;
    841 
    842 	/*
    843 	 * Allocate a process ID for this LWP.  We need to do this now
    844 	 * while we can still unwind if it fails.  Because we're marked
    845 	 * as LSIDL, no lookups by the ID will succeed.
    846 	 *
    847 	 * N.B. this will always succeed for the first LWP in a process,
    848 	 * because proc_alloc_lwpid() will usurp the slot.  Also note
    849 	 * that l2->l_proc MUST be valid so that lookups of the proc
    850 	 * will succeed, even if the LWP itself is not visible.
    851 	 */
    852 	if (__predict_false(proc_alloc_lwpid(p2, l2) == -1)) {
    853 		pool_cache_put(lwp_cache, l2);
    854 		return EAGAIN;
    855 	}
    856 
    857 	/*
    858 	 * If vfork(), we want the LWP to run fast and on the same CPU
    859 	 * as its parent, so that it can reuse the VM context and cache
    860 	 * footprint on the local CPU.
    861 	 */
    862 	l2->l_boostpri = ((flags & LWP_VFORK) ? PRI_KERNEL : PRI_USER);
    863  	l2->l_priority = l1->l_priority;
    864 	l2->l_inheritedprio = -1;
    865 	l2->l_protectprio = -1;
    866 	l2->l_auxprio = -1;
    867 	l2->l_flag = 0;
    868 	l2->l_pflag = LP_MPSAFE;
    869 	TAILQ_INIT(&l2->l_ld_locks);
    870 	l2->l_psrefs = 0;
    871 	kmsan_lwp_alloc(l2);
    872 
    873 	/*
    874 	 * For vfork, borrow parent's lwpctl context if it exists.
    875 	 * This also causes us to return via lwp_userret.
    876 	 */
    877 	if (flags & LWP_VFORK && l1->l_lwpctl) {
    878 		l2->l_lwpctl = l1->l_lwpctl;
    879 		l2->l_flag |= LW_LWPCTL;
    880 	}
    881 
    882 	/*
    883 	 * If not the first LWP in the process, grab a reference to the
    884 	 * descriptor table.
    885 	 */
    886 	l2->l_fd = p2->p_fd;
    887 	if (p2->p_nlwps != 0) {
    888 		KASSERT(l1->l_proc == p2);
    889 		fd_hold(l2);
    890 	} else {
    891 		KASSERT(l1->l_proc != p2);
    892 	}
    893 
    894 	if (p2->p_flag & PK_SYSTEM) {
    895 		/* Mark it as a system LWP. */
    896 		l2->l_flag |= LW_SYSTEM;
    897 	}
    898 
    899 	kdtrace_thread_ctor(NULL, l2);
    900 	lwp_initspecific(l2);
    901 	sched_lwp_fork(l1, l2);
    902 	callout_init(&l2->l_timeout_ch, CALLOUT_MPSAFE);
    903 	callout_setfunc(&l2->l_timeout_ch, sleepq_timeout, l2);
    904 	cv_init(&l2->l_sigcv, "sigwait");
    905 	cv_init(&l2->l_waitcv, "vfork");
    906 	l2->l_syncobj = &sched_syncobj;
    907 	PSREF_DEBUG_INIT_LWP(l2);
    908 
    909 	if (rnewlwpp != NULL)
    910 		*rnewlwpp = l2;
    911 
    912 	/*
    913 	 * PCU state needs to be saved before calling uvm_lwp_fork() so that
    914 	 * the MD cpu_lwp_fork() can copy the saved state to the new LWP.
    915 	 */
    916 	pcu_save_all(l1);
    917 #if PCU_UNIT_COUNT > 0
    918 	l2->l_pcu_valid = l1->l_pcu_valid;
    919 #endif
    920 
    921 	uvm_lwp_setuarea(l2, uaddr);
    922 	uvm_lwp_fork(l1, l2, stack, stacksize, func, (arg != NULL) ? arg : l2);
    923 
    924 	mutex_enter(p2->p_lock);
    925 	l2->l_cred = kauth_cred_hold(p2->p_cred);
    926 	if ((flags & LWP_DETACHED) != 0) {
    927 		l2->l_prflag = LPR_DETACHED;
    928 		p2->p_ndlwps++;
    929 	} else
    930 		l2->l_prflag = 0;
    931 
    932 	if (l1->l_proc == p2) {
    933 		/*
    934 		 * These flags are set while p_lock is held.  Copy with
    935 		 * p_lock held too, so the LWP doesn't sneak into the
    936 		 * process without them being set.
    937 		 */
    938 		l2->l_flag |= (l1->l_flag & (LW_WEXIT | LW_WREBOOT | LW_WCORE));
    939 	} else {
    940 		/* fork(): pending core/exit doesn't apply to child. */
    941 		l2->l_flag |= (l1->l_flag & LW_WREBOOT);
    942 	}
    943 
    944 	l2->l_sigstk = *sigstk;
    945 	l2->l_sigmask = *sigmask;
    946 	TAILQ_INIT(&l2->l_sigpend.sp_info);
    947 	sigemptyset(&l2->l_sigpend.sp_set);
    948 	LIST_INSERT_HEAD(&p2->p_lwps, l2, l_sibling);
    949 	p2->p_nlwps++;
    950 	p2->p_nrlwps++;
    951 
    952 	KASSERT(l2->l_affinity == NULL);
    953 
    954 	/* Inherit the affinity mask. */
    955 	if (l1->l_affinity) {
    956 		/*
    957 		 * Note that we hold the state lock while inheriting
    958 		 * the affinity to avoid race with sched_setaffinity().
    959 		 */
    960 		lwp_lock(l1);
    961 		if (l1->l_affinity) {
    962 			kcpuset_use(l1->l_affinity);
    963 			l2->l_affinity = l1->l_affinity;
    964 		}
    965 		lwp_unlock(l1);
    966 	}
    967 
    968 	/* Ensure a trip through lwp_userret() if needed. */
    969 	if ((l2->l_flag & LW_USERRET) != 0) {
    970 		lwp_need_userret(l2);
    971 	}
    972 
    973 	/* This marks the end of the "must be atomic" section. */
    974 	mutex_exit(p2->p_lock);
    975 
    976 	SDT_PROBE(proc, kernel, , lwp__create, l2, 0, 0, 0, 0);
    977 
    978 	mutex_enter(&proc_lock);
    979 	LIST_INSERT_HEAD(&alllwp, l2, l_list);
    980 	/* Inherit a processor-set */
    981 	l2->l_psid = l1->l_psid;
    982 	mutex_exit(&proc_lock);
    983 
    984 	SYSCALL_TIME_LWP_INIT(l2);
    985 
    986 	if (p2->p_emul->e_lwp_fork)
    987 		(*p2->p_emul->e_lwp_fork)(l1, l2);
    988 
    989 	return (0);
    990 }
    991 
    992 /*
    993  * Set a new LWP running.  If the process is stopping, then the LWP is
    994  * created stopped.
    995  */
    996 void
    997 lwp_start(lwp_t *l, int flags)
    998 {
    999 	proc_t *p = l->l_proc;
   1000 
   1001 	mutex_enter(p->p_lock);
   1002 	lwp_lock(l);
   1003 	KASSERT(l->l_stat == LSIDL);
   1004 	if ((flags & LWP_SUSPENDED) != 0) {
   1005 		/* It'll suspend itself in lwp_userret(). */
   1006 		l->l_flag |= LW_WSUSPEND;
   1007 		lwp_need_userret(l);
   1008 	}
   1009 	if (p->p_stat == SSTOP || (p->p_sflag & PS_STOPPING) != 0) {
   1010 		KASSERT(l->l_wchan == NULL);
   1011 	    	l->l_stat = LSSTOP;
   1012 		p->p_nrlwps--;
   1013 		lwp_unlock(l);
   1014 	} else {
   1015 		setrunnable(l);
   1016 		/* LWP now unlocked */
   1017 	}
   1018 	mutex_exit(p->p_lock);
   1019 }
   1020 
   1021 /*
   1022  * Called by MD code when a new LWP begins execution.  Must be called
   1023  * with the previous LWP locked (so at splsched), or if there is no
   1024  * previous LWP, at splsched.
   1025  */
   1026 void
   1027 lwp_startup(struct lwp *prev, struct lwp *new_lwp)
   1028 {
   1029 	kmutex_t *lock;
   1030 
   1031 	KASSERTMSG(new_lwp == curlwp, "l %p curlwp %p prevlwp %p", new_lwp, curlwp, prev);
   1032 	KASSERT(kpreempt_disabled());
   1033 	KASSERT(prev != NULL);
   1034 	KASSERT((prev->l_pflag & LP_RUNNING) != 0);
   1035 	KASSERT(curcpu()->ci_mtx_count == -2);
   1036 
   1037 	/*
   1038 	 * Immediately mark the previous LWP as no longer running and
   1039 	 * unlock (to keep lock wait times short as possible).  If a
   1040 	 * zombie, don't touch after clearing LP_RUNNING as it could be
   1041 	 * reaped by another CPU.  Use atomic_store_release to ensure
   1042 	 * this -- matches atomic_load_acquire in lwp_free.
   1043 	 */
   1044 	lock = prev->l_mutex;
   1045 	if (__predict_false(prev->l_stat == LSZOMB)) {
   1046 		atomic_store_release(&prev->l_pflag,
   1047 		    prev->l_pflag & ~LP_RUNNING);
   1048 	} else {
   1049 		prev->l_pflag &= ~LP_RUNNING;
   1050 	}
   1051 	mutex_spin_exit(lock);
   1052 
   1053 	/* Correct spin mutex count after mi_switch(). */
   1054 	curcpu()->ci_mtx_count = 0;
   1055 
   1056 	/* Install new VM context. */
   1057 	if (__predict_true(new_lwp->l_proc->p_vmspace)) {
   1058 		pmap_activate(new_lwp);
   1059 	}
   1060 
   1061 	/* We remain at IPL_SCHED from mi_switch() - reset it. */
   1062 	spl0();
   1063 
   1064 	LOCKDEBUG_BARRIER(NULL, 0);
   1065 	SDT_PROBE(proc, kernel, , lwp__start, new_lwp, 0, 0, 0, 0);
   1066 
   1067 	/* For kthreads, acquire kernel lock if not MPSAFE. */
   1068 	if (__predict_false((new_lwp->l_pflag & LP_MPSAFE) == 0)) {
   1069 		KERNEL_LOCK(1, new_lwp);
   1070 	}
   1071 }
   1072 
   1073 /*
   1074  * Exit an LWP.
   1075  *
   1076  * *** WARNING *** This can be called with (l != curlwp) in error paths.
   1077  */
   1078 void
   1079 lwp_exit(struct lwp *l)
   1080 {
   1081 	struct proc *p = l->l_proc;
   1082 	struct lwp *l2;
   1083 	bool current;
   1084 
   1085 	current = (l == curlwp);
   1086 
   1087 	KASSERT(current || l->l_stat == LSIDL);
   1088 	KASSERT(current || l->l_target_cpu == NULL);
   1089 	KASSERT(p == curproc);
   1090 
   1091 	SDT_PROBE(proc, kernel, , lwp__exit, l, 0, 0, 0, 0);
   1092 
   1093 	/* Verify that we hold no locks; for DIAGNOSTIC check kernel_lock. */
   1094 	LOCKDEBUG_BARRIER(NULL, 0);
   1095 	KASSERTMSG(curcpu()->ci_biglock_count == 0, "kernel_lock leaked");
   1096 
   1097 	/*
   1098 	 * If we are the last live LWP in a process, we need to exit the
   1099 	 * entire process.  We do so with an exit status of zero, because
   1100 	 * it's a "controlled" exit, and because that's what Solaris does.
   1101 	 *
   1102 	 * We are not quite a zombie yet, but for accounting purposes we
   1103 	 * must increment the count of zombies here.
   1104 	 *
   1105 	 * Note: the last LWP's specificdata will be deleted here.
   1106 	 */
   1107 	mutex_enter(p->p_lock);
   1108 	if (p->p_nlwps - p->p_nzlwps == 1) {
   1109 		KASSERT(current == true);
   1110 		KASSERT(p != &proc0);
   1111 		exit1(l, 0, 0);
   1112 		/* NOTREACHED */
   1113 	}
   1114 	p->p_nzlwps++;
   1115 
   1116 	/*
   1117 	 * Perform any required thread cleanup.  Do this early so
   1118 	 * anyone wanting to look us up with lwp_getref_lwpid() will
   1119 	 * fail to find us before we become a zombie.
   1120 	 *
   1121 	 * N.B. this will unlock p->p_lock on our behalf.
   1122 	 */
   1123 	lwp_thread_cleanup(l);
   1124 
   1125 	if (p->p_emul->e_lwp_exit)
   1126 		(*p->p_emul->e_lwp_exit)(l);
   1127 
   1128 	/* Drop filedesc reference. */
   1129 	fd_free();
   1130 
   1131 	/* Release fstrans private data. */
   1132 	fstrans_lwp_dtor(l);
   1133 
   1134 	/* Delete the specificdata while it's still safe to sleep. */
   1135 	lwp_finispecific(l);
   1136 
   1137 	/*
   1138 	 * Release our cached credentials.
   1139 	 */
   1140 	kauth_cred_free(l->l_cred);
   1141 	callout_destroy(&l->l_timeout_ch);
   1142 
   1143 	/*
   1144 	 * If traced, report LWP exit event to the debugger.
   1145 	 *
   1146 	 * Remove the LWP from the global list.
   1147 	 * Free its LID from the PID namespace if needed.
   1148 	 */
   1149 	mutex_enter(&proc_lock);
   1150 
   1151 	if ((p->p_slflag & (PSL_TRACED|PSL_TRACELWP_EXIT)) ==
   1152 	    (PSL_TRACED|PSL_TRACELWP_EXIT)) {
   1153 		mutex_enter(p->p_lock);
   1154 		if (ISSET(p->p_sflag, PS_WEXIT)) {
   1155 			mutex_exit(p->p_lock);
   1156 			/*
   1157 			 * We are exiting, bail out without informing parent
   1158 			 * about a terminating LWP as it would deadlock.
   1159 			 */
   1160 		} else {
   1161 			eventswitch(TRAP_LWP, PTRACE_LWP_EXIT, l->l_lid);
   1162 			mutex_enter(&proc_lock);
   1163 		}
   1164 	}
   1165 
   1166 	LIST_REMOVE(l, l_list);
   1167 	mutex_exit(&proc_lock);
   1168 
   1169 	/*
   1170 	 * Get rid of all references to the LWP that others (e.g. procfs)
   1171 	 * may have, and mark the LWP as a zombie.  If the LWP is detached,
   1172 	 * mark it waiting for collection in the proc structure.  Note that
   1173 	 * before we can do that, we need to free any other dead, deatched
   1174 	 * LWP waiting to meet its maker.
   1175 	 *
   1176 	 * All conditions need to be observed upon under the same hold of
   1177 	 * p_lock, because if the lock is dropped any of them can change.
   1178 	 */
   1179 	mutex_enter(p->p_lock);
   1180 	for (;;) {
   1181 		if (lwp_drainrefs(l))
   1182 			continue;
   1183 		if ((l->l_prflag & LPR_DETACHED) != 0) {
   1184 			if ((l2 = p->p_zomblwp) != NULL) {
   1185 				p->p_zomblwp = NULL;
   1186 				lwp_free(l2, false, false);
   1187 				/* proc now unlocked */
   1188 				mutex_enter(p->p_lock);
   1189 				continue;
   1190 			}
   1191 			p->p_zomblwp = l;
   1192 		}
   1193 		break;
   1194 	}
   1195 
   1196 	/*
   1197 	 * If we find a pending signal for the process and we have been
   1198 	 * asked to check for signals, then we lose: arrange to have
   1199 	 * all other LWPs in the process check for signals.
   1200 	 */
   1201 	if ((l->l_flag & LW_PENDSIG) != 0 &&
   1202 	    firstsig(&p->p_sigpend.sp_set) != 0) {
   1203 		LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
   1204 			lwp_lock(l2);
   1205 			signotify(l2);
   1206 			lwp_unlock(l2);
   1207 		}
   1208 	}
   1209 
   1210 	/*
   1211 	 * Release any PCU resources before becoming a zombie.
   1212 	 */
   1213 	pcu_discard_all(l);
   1214 
   1215 	lwp_lock(l);
   1216 	l->l_stat = LSZOMB;
   1217 	if (l->l_name != NULL) {
   1218 		strcpy(l->l_name, "(zombie)");
   1219 	}
   1220 	lwp_unlock(l);
   1221 	p->p_nrlwps--;
   1222 	if (l->l_lwpctl != NULL)
   1223 		l->l_lwpctl->lc_curcpu = LWPCTL_CPU_EXITED;
   1224 	mutex_exit(p->p_lock);
   1225 	cv_broadcast(&p->p_lwpcv);
   1226 
   1227 	/*
   1228 	 * We can no longer block.  At this point, lwp_free() may already
   1229 	 * be gunning for us.  On a multi-CPU system, we may be off p_lwps.
   1230 	 *
   1231 	 * Free MD LWP resources.
   1232 	 */
   1233 	cpu_lwp_free(l, 0);
   1234 
   1235 	if (current) {
   1236 		/* Switch away into oblivion. */
   1237 		lwp_lock(l);
   1238 		spc_lock(l->l_cpu);
   1239 		mi_switch(l);
   1240 		panic("lwp_exit");
   1241 	}
   1242 }
   1243 
   1244 /*
   1245  * Free a dead LWP's remaining resources.
   1246  *
   1247  * XXXLWP limits.
   1248  */
   1249 void
   1250 lwp_free(struct lwp *l, bool recycle, bool last)
   1251 {
   1252 	struct proc *p = l->l_proc;
   1253 	struct rusage *ru;
   1254 	ksiginfoq_t kq;
   1255 
   1256 	KASSERT(l != curlwp);
   1257 	KASSERT(last || mutex_owned(p->p_lock));
   1258 
   1259 	/*
   1260 	 * We use the process credentials instead of the lwp credentials here
   1261 	 * because the lwp credentials maybe cached (just after a setuid call)
   1262 	 * and we don't want pay for syncing, since the lwp is going away
   1263 	 * anyway
   1264 	 */
   1265 	if (p != &proc0 && p->p_nlwps != 1)
   1266 		(void)chglwpcnt(kauth_cred_getuid(p->p_cred), -1);
   1267 
   1268 	/*
   1269 	 * In the unlikely event that the LWP is still on the CPU,
   1270 	 * then spin until it has switched away.
   1271 	 *
   1272 	 * atomic_load_acquire matches atomic_store_release in
   1273 	 * lwp_startup and mi_switch.
   1274 	 */
   1275 	while (__predict_false((atomic_load_acquire(&l->l_pflag) & LP_RUNNING)
   1276 		!= 0)) {
   1277 		SPINLOCK_BACKOFF_HOOK;
   1278 	}
   1279 
   1280 	/*
   1281 	 * Now that the LWP's known off the CPU, reset its state back to
   1282 	 * LSIDL, which defeats anything that might have gotten a hold on
   1283 	 * the LWP via pid_table before the ID was freed.  It's important
   1284 	 * to do this with both the LWP locked and p_lock held.
   1285 	 *
   1286 	 * Also reset the CPU and lock pointer back to curcpu(), since the
   1287 	 * LWP will in all likelyhood be cached with the current CPU in
   1288 	 * lwp_cache when we free it and later allocated from there again
   1289 	 * (avoid incidental lock contention).
   1290 	 */
   1291 	lwp_lock(l);
   1292 	l->l_stat = LSIDL;
   1293 	l->l_cpu = curcpu();
   1294 	lwp_unlock_to(l, l->l_cpu->ci_schedstate.spc_lwplock);
   1295 
   1296 	/*
   1297 	 * If this was not the last LWP in the process, then adjust counters
   1298 	 * and unlock.  This is done differently for the last LWP in exit1().
   1299 	 */
   1300 	if (!last) {
   1301 		/*
   1302 		 * Add the LWP's run time to the process' base value.
   1303 		 * This needs to co-incide with coming off p_lwps.
   1304 		 */
   1305 		bintime_add(&p->p_rtime, &l->l_rtime);
   1306 		p->p_pctcpu += l->l_pctcpu;
   1307 		ru = &p->p_stats->p_ru;
   1308 		ruadd(ru, &l->l_ru);
   1309 		LIST_REMOVE(l, l_sibling);
   1310 		p->p_nlwps--;
   1311 		p->p_nzlwps--;
   1312 		if ((l->l_prflag & LPR_DETACHED) != 0)
   1313 			p->p_ndlwps--;
   1314 		mutex_exit(p->p_lock);
   1315 
   1316 		/*
   1317 		 * Have any LWPs sleeping in lwp_wait() recheck for
   1318 		 * deadlock.
   1319 		 */
   1320 		cv_broadcast(&p->p_lwpcv);
   1321 
   1322 		/* Free the LWP ID. */
   1323 		mutex_enter(&proc_lock);
   1324 		proc_free_lwpid(p, l->l_lid);
   1325 		mutex_exit(&proc_lock);
   1326 	}
   1327 
   1328 	/*
   1329 	 * Destroy the LWP's remaining signal information.
   1330 	 */
   1331 	ksiginfo_queue_init(&kq);
   1332 	sigclear(&l->l_sigpend, NULL, &kq);
   1333 	ksiginfo_queue_drain(&kq);
   1334 	cv_destroy(&l->l_sigcv);
   1335 	cv_destroy(&l->l_waitcv);
   1336 
   1337 	/*
   1338 	 * Free lwpctl structure and affinity.
   1339 	 */
   1340 	if (l->l_lwpctl) {
   1341 		lwp_ctl_free(l);
   1342 	}
   1343 	if (l->l_affinity) {
   1344 		kcpuset_unuse(l->l_affinity, NULL);
   1345 		l->l_affinity = NULL;
   1346 	}
   1347 
   1348 	/*
   1349 	 * Free remaining data structures and the LWP itself unless the
   1350 	 * caller wants to recycle.
   1351 	 */
   1352 	if (l->l_name != NULL)
   1353 		kmem_free(l->l_name, MAXCOMLEN);
   1354 
   1355 	kmsan_lwp_free(l);
   1356 	kcov_lwp_free(l);
   1357 	cpu_lwp_free2(l);
   1358 	uvm_lwp_exit(l);
   1359 
   1360 	KASSERT(SLIST_EMPTY(&l->l_pi_lenders));
   1361 	KASSERT(l->l_inheritedprio == -1);
   1362 	KASSERT(l->l_blcnt == 0);
   1363 	kdtrace_thread_dtor(NULL, l);
   1364 	if (!recycle)
   1365 		pool_cache_put(lwp_cache, l);
   1366 }
   1367 
   1368 /*
   1369  * Migrate the LWP to the another CPU.  Unlocks the LWP.
   1370  */
   1371 void
   1372 lwp_migrate(lwp_t *l, struct cpu_info *tci)
   1373 {
   1374 	struct schedstate_percpu *tspc;
   1375 	int lstat = l->l_stat;
   1376 
   1377 	KASSERT(lwp_locked(l, NULL));
   1378 	KASSERT(tci != NULL);
   1379 
   1380 	/* If LWP is still on the CPU, it must be handled like LSONPROC */
   1381 	if ((l->l_pflag & LP_RUNNING) != 0) {
   1382 		lstat = LSONPROC;
   1383 	}
   1384 
   1385 	/*
   1386 	 * The destination CPU could be changed while previous migration
   1387 	 * was not finished.
   1388 	 */
   1389 	if (l->l_target_cpu != NULL) {
   1390 		l->l_target_cpu = tci;
   1391 		lwp_unlock(l);
   1392 		return;
   1393 	}
   1394 
   1395 	/* Nothing to do if trying to migrate to the same CPU */
   1396 	if (l->l_cpu == tci) {
   1397 		lwp_unlock(l);
   1398 		return;
   1399 	}
   1400 
   1401 	KASSERT(l->l_target_cpu == NULL);
   1402 	tspc = &tci->ci_schedstate;
   1403 	switch (lstat) {
   1404 	case LSRUN:
   1405 		l->l_target_cpu = tci;
   1406 		break;
   1407 	case LSSLEEP:
   1408 		l->l_cpu = tci;
   1409 		break;
   1410 	case LSIDL:
   1411 	case LSSTOP:
   1412 	case LSSUSPENDED:
   1413 		l->l_cpu = tci;
   1414 		if (l->l_wchan == NULL) {
   1415 			lwp_unlock_to(l, tspc->spc_lwplock);
   1416 			return;
   1417 		}
   1418 		break;
   1419 	case LSONPROC:
   1420 		l->l_target_cpu = tci;
   1421 		spc_lock(l->l_cpu);
   1422 		sched_resched_cpu(l->l_cpu, PRI_USER_RT, true);
   1423 		/* spc now unlocked */
   1424 		break;
   1425 	}
   1426 	lwp_unlock(l);
   1427 }
   1428 
   1429 #define	lwp_find_exclude(l)					\
   1430 	((l)->l_stat == LSIDL || (l)->l_stat == LSZOMB)
   1431 
   1432 /*
   1433  * Find the LWP in the process.  Arguments may be zero, in such case,
   1434  * the calling process and first LWP in the list will be used.
   1435  * On success - returns proc locked.
   1436  *
   1437  * => pid == 0 -> look in curproc.
   1438  * => pid == -1 -> match any proc.
   1439  * => otherwise look up the proc.
   1440  *
   1441  * => lid == 0 -> first LWP in the proc
   1442  * => otherwise specific LWP
   1443  */
   1444 struct lwp *
   1445 lwp_find2(pid_t pid, lwpid_t lid)
   1446 {
   1447 	proc_t *p;
   1448 	lwp_t *l;
   1449 
   1450 	/* First LWP of specified proc. */
   1451 	if (lid == 0) {
   1452 		switch (pid) {
   1453 		case -1:
   1454 			/* No lookup keys. */
   1455 			return NULL;
   1456 		case 0:
   1457 			p = curproc;
   1458 			mutex_enter(p->p_lock);
   1459 			break;
   1460 		default:
   1461 			mutex_enter(&proc_lock);
   1462 			p = proc_find(pid);
   1463 			if (__predict_false(p == NULL)) {
   1464 				mutex_exit(&proc_lock);
   1465 				return NULL;
   1466 			}
   1467 			mutex_enter(p->p_lock);
   1468 			mutex_exit(&proc_lock);
   1469 			break;
   1470 		}
   1471 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
   1472 			if (__predict_true(!lwp_find_exclude(l)))
   1473 				break;
   1474 		}
   1475 		goto out;
   1476 	}
   1477 
   1478 	l = proc_find_lwp_acquire_proc(lid, &p);
   1479 	if (l == NULL)
   1480 		return NULL;
   1481 	KASSERT(p != NULL);
   1482 	KASSERT(mutex_owned(p->p_lock));
   1483 
   1484 	if (__predict_false(lwp_find_exclude(l))) {
   1485 		l = NULL;
   1486 		goto out;
   1487 	}
   1488 
   1489 	/* Apply proc filter, if applicable. */
   1490 	switch (pid) {
   1491 	case -1:
   1492 		/* Match anything. */
   1493 		break;
   1494 	case 0:
   1495 		if (p != curproc)
   1496 			l = NULL;
   1497 		break;
   1498 	default:
   1499 		if (p->p_pid != pid)
   1500 			l = NULL;
   1501 		break;
   1502 	}
   1503 
   1504  out:
   1505 	if (__predict_false(l == NULL)) {
   1506 		mutex_exit(p->p_lock);
   1507 	}
   1508 	return l;
   1509 }
   1510 
   1511 /*
   1512  * Look up a live LWP within the specified process.
   1513  *
   1514  * Must be called with p->p_lock held (as it looks at the radix tree,
   1515  * and also wants to exclude idle and zombie LWPs).
   1516  */
   1517 struct lwp *
   1518 lwp_find(struct proc *p, lwpid_t id)
   1519 {
   1520 	struct lwp *l;
   1521 
   1522 	KASSERT(mutex_owned(p->p_lock));
   1523 
   1524 	l = proc_find_lwp(p, id);
   1525 	KASSERT(l == NULL || l->l_lid == id);
   1526 
   1527 	/*
   1528 	 * No need to lock - all of these conditions will
   1529 	 * be visible with the process level mutex held.
   1530 	 */
   1531 	if (__predict_false(l != NULL && lwp_find_exclude(l)))
   1532 		l = NULL;
   1533 
   1534 	return l;
   1535 }
   1536 
   1537 /*
   1538  * Verify that an LWP is locked, and optionally verify that the lock matches
   1539  * one we specify.
   1540  */
   1541 int
   1542 lwp_locked(struct lwp *l, kmutex_t *mtx)
   1543 {
   1544 	kmutex_t *cur = l->l_mutex;
   1545 
   1546 	return mutex_owned(cur) && (mtx == cur || mtx == NULL);
   1547 }
   1548 
   1549 /*
   1550  * Lend a new mutex to an LWP.  The old mutex must be held.
   1551  */
   1552 kmutex_t *
   1553 lwp_setlock(struct lwp *l, kmutex_t *mtx)
   1554 {
   1555 	kmutex_t *oldmtx = l->l_mutex;
   1556 
   1557 	KASSERT(mutex_owned(oldmtx));
   1558 
   1559 	atomic_store_release(&l->l_mutex, mtx);
   1560 	return oldmtx;
   1561 }
   1562 
   1563 /*
   1564  * Lend a new mutex to an LWP, and release the old mutex.  The old mutex
   1565  * must be held.
   1566  */
   1567 void
   1568 lwp_unlock_to(struct lwp *l, kmutex_t *mtx)
   1569 {
   1570 	kmutex_t *old;
   1571 
   1572 	KASSERT(lwp_locked(l, NULL));
   1573 
   1574 	old = l->l_mutex;
   1575 	atomic_store_release(&l->l_mutex, mtx);
   1576 	mutex_spin_exit(old);
   1577 }
   1578 
   1579 int
   1580 lwp_trylock(struct lwp *l)
   1581 {
   1582 	kmutex_t *old;
   1583 
   1584 	for (;;) {
   1585 		if (!mutex_tryenter(old = atomic_load_consume(&l->l_mutex)))
   1586 			return 0;
   1587 		if (__predict_true(atomic_load_relaxed(&l->l_mutex) == old))
   1588 			return 1;
   1589 		mutex_spin_exit(old);
   1590 	}
   1591 }
   1592 
   1593 void
   1594 lwp_unsleep(lwp_t *l, bool unlock)
   1595 {
   1596 
   1597 	KASSERT(mutex_owned(l->l_mutex));
   1598 	(*l->l_syncobj->sobj_unsleep)(l, unlock);
   1599 }
   1600 
   1601 /*
   1602  * Lock an LWP.
   1603  */
   1604 void
   1605 lwp_lock(lwp_t *l)
   1606 {
   1607 	kmutex_t *old = atomic_load_consume(&l->l_mutex);
   1608 
   1609 	/*
   1610 	 * Note: mutex_spin_enter() will have posted a read barrier.
   1611 	 * Re-test l->l_mutex.  If it has changed, we need to try again.
   1612 	 */
   1613 	mutex_spin_enter(old);
   1614 	while (__predict_false(atomic_load_relaxed(&l->l_mutex) != old)) {
   1615 		mutex_spin_exit(old);
   1616 		old = atomic_load_consume(&l->l_mutex);
   1617 		mutex_spin_enter(old);
   1618 	}
   1619 }
   1620 
   1621 /*
   1622  * Unlock an LWP.
   1623  */
   1624 void
   1625 lwp_unlock(lwp_t *l)
   1626 {
   1627 
   1628 	mutex_spin_exit(l->l_mutex);
   1629 }
   1630 
   1631 void
   1632 lwp_changepri(lwp_t *l, pri_t pri)
   1633 {
   1634 
   1635 	KASSERT(mutex_owned(l->l_mutex));
   1636 
   1637 	if (l->l_priority == pri)
   1638 		return;
   1639 
   1640 	(*l->l_syncobj->sobj_changepri)(l, pri);
   1641 	KASSERT(l->l_priority == pri);
   1642 }
   1643 
   1644 void
   1645 lwp_lendpri(lwp_t *l, pri_t pri)
   1646 {
   1647 	KASSERT(mutex_owned(l->l_mutex));
   1648 
   1649 	(*l->l_syncobj->sobj_lendpri)(l, pri);
   1650 	KASSERT(l->l_inheritedprio == pri);
   1651 }
   1652 
   1653 pri_t
   1654 lwp_eprio(lwp_t *l)
   1655 {
   1656 	pri_t pri = l->l_priority;
   1657 
   1658 	KASSERT(mutex_owned(l->l_mutex));
   1659 
   1660 	/*
   1661 	 * Timeshared/user LWPs get a temporary priority boost for blocking
   1662 	 * in kernel.  This is key to good interactive response on a loaded
   1663 	 * system: without it, things will seem very sluggish to the user.
   1664 	 *
   1665 	 * The function of the boost is to get the LWP onto a CPU and
   1666 	 * running quickly.  Once that happens the LWP loses the priority
   1667 	 * boost and could be preempted very quickly by another LWP but that
   1668 	 * won't happen often enough to be a annoyance.
   1669 	 */
   1670 	if (pri <= MAXPRI_USER && l->l_boostpri > MAXPRI_USER)
   1671 		pri = (pri >> 1) + l->l_boostpri;
   1672 
   1673 	return MAX(l->l_auxprio, pri);
   1674 }
   1675 
   1676 /*
   1677  * Handle exceptions for mi_userret().  Called if a member of LW_USERRET is
   1678  * set or a preemption is required.
   1679  */
   1680 void
   1681 lwp_userret(struct lwp *l)
   1682 {
   1683 	struct proc *p;
   1684 	int sig, f;
   1685 
   1686 	KASSERT(l == curlwp);
   1687 	KASSERT(l->l_stat == LSONPROC);
   1688 	p = l->l_proc;
   1689 
   1690 	for (;;) {
   1691 		/*
   1692 		 * This is the main location that user preemptions are
   1693 		 * processed.
   1694 		 */
   1695 		preempt_point();
   1696 
   1697 		/*
   1698 		 * It is safe to do this unlocked and without raised SPL,
   1699 		 * since whenever a flag of interest is added to l_flag the
   1700 		 * LWP will take an AST and come down this path again.  If a
   1701 		 * remote CPU posts the AST, it will be done with an IPI
   1702 		 * (strongly synchronising).
   1703 		 */
   1704 		if ((f = atomic_load_relaxed(&l->l_flag) & LW_USERRET) == 0) {
   1705 			return;
   1706 		}
   1707 
   1708 		/*
   1709 		 * Start out with the correct credentials.
   1710 		 */
   1711 		if ((f & LW_CACHECRED) != 0) {
   1712 			kauth_cred_t oc = l->l_cred;
   1713 			mutex_enter(p->p_lock);
   1714 			l->l_cred = kauth_cred_hold(p->p_cred);
   1715 			lwp_lock(l);
   1716 			l->l_flag &= ~LW_CACHECRED;
   1717 			lwp_unlock(l);
   1718 			mutex_exit(p->p_lock);
   1719 			kauth_cred_free(oc);
   1720 		}
   1721 
   1722 		/*
   1723 		 * Process pending signals first, unless the process
   1724 		 * is dumping core or exiting, where we will instead
   1725 		 * enter the LW_WSUSPEND case below.
   1726 		 */
   1727 		if ((f & (LW_PENDSIG | LW_WCORE | LW_WEXIT)) == LW_PENDSIG) {
   1728 			mutex_enter(p->p_lock);
   1729 			while ((sig = issignal(l)) != 0)
   1730 				postsig(sig);
   1731 			mutex_exit(p->p_lock);
   1732 			continue;
   1733 		}
   1734 
   1735 		/*
   1736 		 * Core-dump or suspend pending.
   1737 		 *
   1738 		 * In case of core dump, suspend ourselves, so that the kernel
   1739 		 * stack and therefore the userland registers saved in the
   1740 		 * trapframe are around for coredump() to write them out.
   1741 		 * We also need to save any PCU resources that we have so that
   1742 		 * they accessible for coredump().  We issue a wakeup on
   1743 		 * p->p_lwpcv so that sigexit() will write the core file out
   1744 		 * once all other LWPs are suspended.
   1745 		 */
   1746 		if ((f & LW_WSUSPEND) != 0) {
   1747 			pcu_save_all(l);
   1748 			mutex_enter(p->p_lock);
   1749 			p->p_nrlwps--;
   1750 			lwp_lock(l);
   1751 			l->l_stat = LSSUSPENDED;
   1752 			lwp_unlock(l);
   1753 			mutex_exit(p->p_lock);
   1754 			cv_broadcast(&p->p_lwpcv);
   1755 			lwp_lock(l);
   1756 			spc_lock(l->l_cpu);
   1757 			mi_switch(l);
   1758 			continue;
   1759 		}
   1760 
   1761 		/*
   1762 		 * Process is exiting.  The core dump and signal cases must
   1763 		 * be handled first.
   1764 		 */
   1765 		if ((f & LW_WEXIT) != 0) {
   1766 			lwp_exit(l);
   1767 			KASSERT(0);
   1768 			/* NOTREACHED */
   1769 		}
   1770 
   1771 		/*
   1772 		 * Update lwpctl processor (for vfork child_return).
   1773 		 */
   1774 		if ((f & LW_LWPCTL) != 0) {
   1775 			lwp_lock(l);
   1776 			KASSERT(kpreempt_disabled());
   1777 			l->l_lwpctl->lc_curcpu = (int)cpu_index(l->l_cpu);
   1778 			l->l_lwpctl->lc_pctr++;
   1779 			l->l_flag &= ~LW_LWPCTL;
   1780 			lwp_unlock(l);
   1781 			continue;
   1782 		}
   1783 	}
   1784 }
   1785 
   1786 /*
   1787  * Force an LWP to enter the kernel, to take a trip through lwp_userret().
   1788  */
   1789 void
   1790 lwp_need_userret(struct lwp *l)
   1791 {
   1792 
   1793 	KASSERT(!cpu_intr_p());
   1794 	KASSERT(lwp_locked(l, NULL) || l->l_stat == LSIDL);
   1795 
   1796 	/*
   1797 	 * If the LWP is in any state other than LSONPROC, we know that it
   1798 	 * is executing in-kernel and will hit userret() on the way out.
   1799 	 *
   1800 	 * If the LWP is curlwp, then we know we'll be back out to userspace
   1801 	 * soon (can't be called from a hardware interrupt here).
   1802 	 *
   1803 	 * Otherwise, we can't be sure what the LWP is doing, so first make
   1804 	 * sure the update to l_flag will be globally visible, and then
   1805 	 * force the LWP to take a trip through trap() where it will do
   1806 	 * userret().
   1807 	 */
   1808 	if (l->l_stat == LSONPROC && l != curlwp) {
   1809 		membar_producer();
   1810 		cpu_signotify(l);
   1811 	}
   1812 }
   1813 
   1814 /*
   1815  * Add one reference to an LWP.  This will prevent the LWP from
   1816  * exiting, thus keep the lwp structure and PCB around to inspect.
   1817  */
   1818 void
   1819 lwp_addref(struct lwp *l)
   1820 {
   1821 	KASSERT(mutex_owned(l->l_proc->p_lock));
   1822 	KASSERT(l->l_stat != LSZOMB);
   1823 	l->l_refcnt++;
   1824 }
   1825 
   1826 /*
   1827  * Remove one reference to an LWP.  If this is the last reference,
   1828  * then we must finalize the LWP's death.
   1829  */
   1830 void
   1831 lwp_delref(struct lwp *l)
   1832 {
   1833 	struct proc *p = l->l_proc;
   1834 
   1835 	mutex_enter(p->p_lock);
   1836 	lwp_delref2(l);
   1837 	mutex_exit(p->p_lock);
   1838 }
   1839 
   1840 /*
   1841  * Remove one reference to an LWP.  If this is the last reference,
   1842  * then we must finalize the LWP's death.  The proc mutex is held
   1843  * on entry.
   1844  */
   1845 void
   1846 lwp_delref2(struct lwp *l)
   1847 {
   1848 	struct proc *p = l->l_proc;
   1849 
   1850 	KASSERT(mutex_owned(p->p_lock));
   1851 	KASSERT(l->l_stat != LSZOMB);
   1852 	KASSERT(l->l_refcnt > 0);
   1853 
   1854 	if (--l->l_refcnt == 0)
   1855 		cv_broadcast(&p->p_lwpcv);
   1856 }
   1857 
   1858 /*
   1859  * Drain all references to the current LWP.  Returns true if
   1860  * we blocked.
   1861  */
   1862 bool
   1863 lwp_drainrefs(struct lwp *l)
   1864 {
   1865 	struct proc *p = l->l_proc;
   1866 	bool rv = false;
   1867 
   1868 	KASSERT(mutex_owned(p->p_lock));
   1869 
   1870 	l->l_prflag |= LPR_DRAINING;
   1871 
   1872 	while (l->l_refcnt > 0) {
   1873 		rv = true;
   1874 		cv_wait(&p->p_lwpcv, p->p_lock);
   1875 	}
   1876 	return rv;
   1877 }
   1878 
   1879 /*
   1880  * Return true if the specified LWP is 'alive'.  Only p->p_lock need
   1881  * be held.
   1882  */
   1883 bool
   1884 lwp_alive(lwp_t *l)
   1885 {
   1886 
   1887 	KASSERT(mutex_owned(l->l_proc->p_lock));
   1888 
   1889 	switch (l->l_stat) {
   1890 	case LSSLEEP:
   1891 	case LSRUN:
   1892 	case LSONPROC:
   1893 	case LSSTOP:
   1894 	case LSSUSPENDED:
   1895 		return true;
   1896 	default:
   1897 		return false;
   1898 	}
   1899 }
   1900 
   1901 /*
   1902  * Return first live LWP in the process.
   1903  */
   1904 lwp_t *
   1905 lwp_find_first(proc_t *p)
   1906 {
   1907 	lwp_t *l;
   1908 
   1909 	KASSERT(mutex_owned(p->p_lock));
   1910 
   1911 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
   1912 		if (lwp_alive(l)) {
   1913 			return l;
   1914 		}
   1915 	}
   1916 
   1917 	return NULL;
   1918 }
   1919 
   1920 /*
   1921  * Allocate a new lwpctl structure for a user LWP.
   1922  */
   1923 int
   1924 lwp_ctl_alloc(vaddr_t *uaddr)
   1925 {
   1926 	lcproc_t *lp;
   1927 	u_int bit, i, offset;
   1928 	struct uvm_object *uao;
   1929 	int error;
   1930 	lcpage_t *lcp;
   1931 	proc_t *p;
   1932 	lwp_t *l;
   1933 
   1934 	l = curlwp;
   1935 	p = l->l_proc;
   1936 
   1937 	/* don't allow a vforked process to create lwp ctls */
   1938 	if (p->p_lflag & PL_PPWAIT)
   1939 		return EBUSY;
   1940 
   1941 	if (l->l_lcpage != NULL) {
   1942 		lcp = l->l_lcpage;
   1943 		*uaddr = lcp->lcp_uaddr + (vaddr_t)l->l_lwpctl - lcp->lcp_kaddr;
   1944 		return 0;
   1945 	}
   1946 
   1947 	/* First time around, allocate header structure for the process. */
   1948 	if ((lp = p->p_lwpctl) == NULL) {
   1949 		lp = kmem_alloc(sizeof(*lp), KM_SLEEP);
   1950 		mutex_init(&lp->lp_lock, MUTEX_DEFAULT, IPL_NONE);
   1951 		lp->lp_uao = NULL;
   1952 		TAILQ_INIT(&lp->lp_pages);
   1953 		mutex_enter(p->p_lock);
   1954 		if (p->p_lwpctl == NULL) {
   1955 			p->p_lwpctl = lp;
   1956 			mutex_exit(p->p_lock);
   1957 		} else {
   1958 			mutex_exit(p->p_lock);
   1959 			mutex_destroy(&lp->lp_lock);
   1960 			kmem_free(lp, sizeof(*lp));
   1961 			lp = p->p_lwpctl;
   1962 		}
   1963 	}
   1964 
   1965  	/*
   1966  	 * Set up an anonymous memory region to hold the shared pages.
   1967  	 * Map them into the process' address space.  The user vmspace
   1968  	 * gets the first reference on the UAO.
   1969  	 */
   1970 	mutex_enter(&lp->lp_lock);
   1971 	if (lp->lp_uao == NULL) {
   1972 		lp->lp_uao = uao_create(LWPCTL_UAREA_SZ, 0);
   1973 		lp->lp_cur = 0;
   1974 		lp->lp_max = LWPCTL_UAREA_SZ;
   1975 		lp->lp_uva = p->p_emul->e_vm_default_addr(p,
   1976 		     (vaddr_t)p->p_vmspace->vm_daddr, LWPCTL_UAREA_SZ,
   1977 		     p->p_vmspace->vm_map.flags & VM_MAP_TOPDOWN);
   1978 		error = uvm_map(&p->p_vmspace->vm_map, &lp->lp_uva,
   1979 		    LWPCTL_UAREA_SZ, lp->lp_uao, 0, 0, UVM_MAPFLAG(UVM_PROT_RW,
   1980 		    UVM_PROT_RW, UVM_INH_NONE, UVM_ADV_NORMAL, 0));
   1981 		if (error != 0) {
   1982 			uao_detach(lp->lp_uao);
   1983 			lp->lp_uao = NULL;
   1984 			mutex_exit(&lp->lp_lock);
   1985 			return error;
   1986 		}
   1987 	}
   1988 
   1989 	/* Get a free block and allocate for this LWP. */
   1990 	TAILQ_FOREACH(lcp, &lp->lp_pages, lcp_chain) {
   1991 		if (lcp->lcp_nfree != 0)
   1992 			break;
   1993 	}
   1994 	if (lcp == NULL) {
   1995 		/* Nothing available - try to set up a free page. */
   1996 		if (lp->lp_cur == lp->lp_max) {
   1997 			mutex_exit(&lp->lp_lock);
   1998 			return ENOMEM;
   1999 		}
   2000 		lcp = kmem_alloc(LWPCTL_LCPAGE_SZ, KM_SLEEP);
   2001 
   2002 		/*
   2003 		 * Wire the next page down in kernel space.  Since this
   2004 		 * is a new mapping, we must add a reference.
   2005 		 */
   2006 		uao = lp->lp_uao;
   2007 		(*uao->pgops->pgo_reference)(uao);
   2008 		lcp->lcp_kaddr = vm_map_min(kernel_map);
   2009 		error = uvm_map(kernel_map, &lcp->lcp_kaddr, PAGE_SIZE,
   2010 		    uao, lp->lp_cur, PAGE_SIZE,
   2011 		    UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW,
   2012 		    UVM_INH_NONE, UVM_ADV_RANDOM, 0));
   2013 		if (error != 0) {
   2014 			mutex_exit(&lp->lp_lock);
   2015 			kmem_free(lcp, LWPCTL_LCPAGE_SZ);
   2016 			(*uao->pgops->pgo_detach)(uao);
   2017 			return error;
   2018 		}
   2019 		error = uvm_map_pageable(kernel_map, lcp->lcp_kaddr,
   2020 		    lcp->lcp_kaddr + PAGE_SIZE, FALSE, 0);
   2021 		if (error != 0) {
   2022 			mutex_exit(&lp->lp_lock);
   2023 			uvm_unmap(kernel_map, lcp->lcp_kaddr,
   2024 			    lcp->lcp_kaddr + PAGE_SIZE);
   2025 			kmem_free(lcp, LWPCTL_LCPAGE_SZ);
   2026 			return error;
   2027 		}
   2028 		/* Prepare the page descriptor and link into the list. */
   2029 		lcp->lcp_uaddr = lp->lp_uva + lp->lp_cur;
   2030 		lp->lp_cur += PAGE_SIZE;
   2031 		lcp->lcp_nfree = LWPCTL_PER_PAGE;
   2032 		lcp->lcp_rotor = 0;
   2033 		memset(lcp->lcp_bitmap, 0xff, LWPCTL_BITMAP_SZ);
   2034 		TAILQ_INSERT_HEAD(&lp->lp_pages, lcp, lcp_chain);
   2035 	}
   2036 	for (i = lcp->lcp_rotor; lcp->lcp_bitmap[i] == 0;) {
   2037 		if (++i >= LWPCTL_BITMAP_ENTRIES)
   2038 			i = 0;
   2039 	}
   2040 	bit = ffs(lcp->lcp_bitmap[i]) - 1;
   2041 	lcp->lcp_bitmap[i] ^= (1U << bit);
   2042 	lcp->lcp_rotor = i;
   2043 	lcp->lcp_nfree--;
   2044 	l->l_lcpage = lcp;
   2045 	offset = (i << 5) + bit;
   2046 	l->l_lwpctl = (lwpctl_t *)lcp->lcp_kaddr + offset;
   2047 	*uaddr = lcp->lcp_uaddr + offset * sizeof(lwpctl_t);
   2048 	mutex_exit(&lp->lp_lock);
   2049 
   2050 	KPREEMPT_DISABLE(l);
   2051 	l->l_lwpctl->lc_curcpu = (int)cpu_index(curcpu());
   2052 	KPREEMPT_ENABLE(l);
   2053 
   2054 	return 0;
   2055 }
   2056 
   2057 /*
   2058  * Free an lwpctl structure back to the per-process list.
   2059  */
   2060 void
   2061 lwp_ctl_free(lwp_t *l)
   2062 {
   2063 	struct proc *p = l->l_proc;
   2064 	lcproc_t *lp;
   2065 	lcpage_t *lcp;
   2066 	u_int map, offset;
   2067 
   2068 	/* don't free a lwp context we borrowed for vfork */
   2069 	if (p->p_lflag & PL_PPWAIT) {
   2070 		l->l_lwpctl = NULL;
   2071 		return;
   2072 	}
   2073 
   2074 	lp = p->p_lwpctl;
   2075 	KASSERT(lp != NULL);
   2076 
   2077 	lcp = l->l_lcpage;
   2078 	offset = (u_int)((lwpctl_t *)l->l_lwpctl - (lwpctl_t *)lcp->lcp_kaddr);
   2079 	KASSERT(offset < LWPCTL_PER_PAGE);
   2080 
   2081 	mutex_enter(&lp->lp_lock);
   2082 	lcp->lcp_nfree++;
   2083 	map = offset >> 5;
   2084 	lcp->lcp_bitmap[map] |= (1U << (offset & 31));
   2085 	if (lcp->lcp_bitmap[lcp->lcp_rotor] == 0)
   2086 		lcp->lcp_rotor = map;
   2087 	if (TAILQ_FIRST(&lp->lp_pages)->lcp_nfree == 0) {
   2088 		TAILQ_REMOVE(&lp->lp_pages, lcp, lcp_chain);
   2089 		TAILQ_INSERT_HEAD(&lp->lp_pages, lcp, lcp_chain);
   2090 	}
   2091 	mutex_exit(&lp->lp_lock);
   2092 }
   2093 
   2094 /*
   2095  * Process is exiting; tear down lwpctl state.  This can only be safely
   2096  * called by the last LWP in the process.
   2097  */
   2098 void
   2099 lwp_ctl_exit(void)
   2100 {
   2101 	lcpage_t *lcp, *next;
   2102 	lcproc_t *lp;
   2103 	proc_t *p;
   2104 	lwp_t *l;
   2105 
   2106 	l = curlwp;
   2107 	l->l_lwpctl = NULL;
   2108 	l->l_lcpage = NULL;
   2109 	p = l->l_proc;
   2110 	lp = p->p_lwpctl;
   2111 
   2112 	KASSERT(lp != NULL);
   2113 	KASSERT(p->p_nlwps == 1);
   2114 
   2115 	for (lcp = TAILQ_FIRST(&lp->lp_pages); lcp != NULL; lcp = next) {
   2116 		next = TAILQ_NEXT(lcp, lcp_chain);
   2117 		uvm_unmap(kernel_map, lcp->lcp_kaddr,
   2118 		    lcp->lcp_kaddr + PAGE_SIZE);
   2119 		kmem_free(lcp, LWPCTL_LCPAGE_SZ);
   2120 	}
   2121 
   2122 	if (lp->lp_uao != NULL) {
   2123 		uvm_unmap(&p->p_vmspace->vm_map, lp->lp_uva,
   2124 		    lp->lp_uva + LWPCTL_UAREA_SZ);
   2125 	}
   2126 
   2127 	mutex_destroy(&lp->lp_lock);
   2128 	kmem_free(lp, sizeof(*lp));
   2129 	p->p_lwpctl = NULL;
   2130 }
   2131 
   2132 /*
   2133  * Return the current LWP's "preemption counter".  Used to detect
   2134  * preemption across operations that can tolerate preemption without
   2135  * crashing, but which may generate incorrect results if preempted.
   2136  *
   2137  * We do arithmetic in unsigned long to avoid undefined behaviour in
   2138  * the event of arithmetic overflow on LP32, and issue __insn_barrier()
   2139  * on both sides so this can safely be used to detect changes to the
   2140  * preemption counter in loops around other memory accesses even in the
   2141  * event of whole-program optimization (e.g., gcc -flto).
   2142  */
   2143 long
   2144 lwp_pctr(void)
   2145 {
   2146 	unsigned long pctr;
   2147 
   2148 	__insn_barrier();
   2149 	pctr = curlwp->l_ru.ru_nvcsw;
   2150 	pctr += curlwp->l_ru.ru_nivcsw;
   2151 	__insn_barrier();
   2152 	return pctr;
   2153 }
   2154 
   2155 /*
   2156  * Set an LWP's private data pointer.
   2157  */
   2158 int
   2159 lwp_setprivate(struct lwp *l, void *ptr)
   2160 {
   2161 	int error = 0;
   2162 
   2163 	l->l_private = ptr;
   2164 #ifdef __HAVE_CPU_LWP_SETPRIVATE
   2165 	error = cpu_lwp_setprivate(l, ptr);
   2166 #endif
   2167 	return error;
   2168 }
   2169 
   2170 /*
   2171  * Perform any thread-related cleanup on LWP exit.
   2172  * N.B. l->l_proc->p_lock must be HELD on entry but will
   2173  * be released before returning!
   2174  */
   2175 void
   2176 lwp_thread_cleanup(struct lwp *l)
   2177 {
   2178 
   2179 	KASSERT(mutex_owned(l->l_proc->p_lock));
   2180 	mutex_exit(l->l_proc->p_lock);
   2181 
   2182 	/*
   2183 	 * If the LWP has robust futexes, release them all
   2184 	 * now.
   2185 	 */
   2186 	if (__predict_false(l->l_robust_head != 0)) {
   2187 		futex_release_all_lwp(l);
   2188 	}
   2189 }
   2190 
   2191 #if defined(DDB)
   2192 #include <machine/pcb.h>
   2193 
   2194 void
   2195 lwp_whatis(uintptr_t addr, void (*pr)(const char *, ...))
   2196 {
   2197 	lwp_t *l;
   2198 
   2199 	LIST_FOREACH(l, &alllwp, l_list) {
   2200 		uintptr_t stack = (uintptr_t)KSTACK_LOWEST_ADDR(l);
   2201 
   2202 		if (addr < stack || stack + KSTACK_SIZE <= addr) {
   2203 			continue;
   2204 		}
   2205 		(*pr)("%p is %p+%zu, LWP %p's stack\n",
   2206 		    (void *)addr, (void *)stack,
   2207 		    (size_t)(addr - stack), l);
   2208 	}
   2209 }
   2210 #endif /* defined(DDB) */
   2211