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