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