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