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