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