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