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