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