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