Home | History | Annotate | Line # | Download | only in kern
kern_lwp.c revision 1.162
      1 /*	$NetBSD: kern_lwp.c,v 1.162 2011/08/07 21:13:05 rmind Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2001, 2006, 2007, 2008, 2009 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 LP_RUNNING flag in lwp::l_pflag 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  *	LSONPROC, LSZOMB:
    165  *
    166  *		Always covered by spc_lwplock, which protects running LWPs.
    167  *		This is a per-CPU lock and matches lwp::l_cpu.
    168  *
    169  *	LSIDL, LSRUN:
    170  *
    171  *		Always covered by spc_mutex, which protects the run queues.
    172  *		This is a per-CPU lock and matches lwp::l_cpu.
    173  *
    174  *	LSSLEEP:
    175  *
    176  *		Covered by a lock associated with the sleep queue that the
    177  *		LWP resides on.  Matches lwp::l_sleepq::sq_mutex.
    178  *
    179  *	LSSTOP, LSSUSPENDED:
    180  *
    181  *		If the LWP was previously sleeping (l_wchan != NULL), then
    182  *		l_mutex references the sleep queue lock.  If the LWP was
    183  *		runnable or on the CPU when halted, or has been removed from
    184  *		the sleep queue since halted, then the lock is spc_lwplock.
    185  *
    186  *	The lock order is as follows:
    187  *
    188  *		spc::spc_lwplock ->
    189  *		    sleeptab::st_mutex ->
    190  *			tschain_t::tc_mutex ->
    191  *			    spc::spc_mutex
    192  *
    193  *	Each process has an scheduler state lock (proc::p_lock), and a
    194  *	number of counters on LWPs and their states: p_nzlwps, p_nrlwps, and
    195  *	so on.  When an LWP is to be entered into or removed from one of the
    196  *	following states, p_lock must be held and the process wide counters
    197  *	adjusted:
    198  *
    199  *		LSIDL, LSZOMB, LSSTOP, LSSUSPENDED
    200  *
    201  *	(But not always for kernel threads.  There are some special cases
    202  *	as mentioned above.  See kern_softint.c.)
    203  *
    204  *	Note that an LWP is considered running or likely to run soon if in
    205  *	one of the following states.  This affects the value of p_nrlwps:
    206  *
    207  *		LSRUN, LSONPROC, LSSLEEP
    208  *
    209  *	p_lock does not need to be held when transitioning among these
    210  *	three states, hence p_lock is rarely taken for state transitions.
    211  */
    212 
    213 #include <sys/cdefs.h>
    214 __KERNEL_RCSID(0, "$NetBSD: kern_lwp.c,v 1.162 2011/08/07 21:13:05 rmind Exp $");
    215 
    216 #include "opt_ddb.h"
    217 #include "opt_lockdebug.h"
    218 #include "opt_sa.h"
    219 #include "opt_dtrace.h"
    220 
    221 #define _LWP_API_PRIVATE
    222 
    223 #include <sys/param.h>
    224 #include <sys/systm.h>
    225 #include <sys/cpu.h>
    226 #include <sys/pool.h>
    227 #include <sys/proc.h>
    228 #include <sys/sa.h>
    229 #include <sys/savar.h>
    230 #include <sys/syscallargs.h>
    231 #include <sys/syscall_stats.h>
    232 #include <sys/kauth.h>
    233 #include <sys/pserialize.h>
    234 #include <sys/sleepq.h>
    235 #include <sys/lockdebug.h>
    236 #include <sys/kmem.h>
    237 #include <sys/pset.h>
    238 #include <sys/intr.h>
    239 #include <sys/lwpctl.h>
    240 #include <sys/atomic.h>
    241 #include <sys/filedesc.h>
    242 #include <sys/dtrace_bsd.h>
    243 #include <sys/sdt.h>
    244 #include <sys/xcall.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_PROBE_DEFINE(proc,,,lwp_create,
    256 	"struct lwp *", NULL,
    257 	NULL, NULL, NULL, NULL,
    258 	NULL, NULL, NULL, NULL);
    259 SDT_PROBE_DEFINE(proc,,,lwp_start,
    260 	"struct lwp *", NULL,
    261 	NULL, NULL, NULL, NULL,
    262 	NULL, NULL, NULL, NULL);
    263 SDT_PROBE_DEFINE(proc,,,lwp_exit,
    264 	"struct lwp *", NULL,
    265 	NULL, NULL, NULL, NULL,
    266 	NULL, NULL, NULL, NULL);
    267 
    268 struct turnstile turnstile0;
    269 struct lwp lwp0 __aligned(MIN_LWP_ALIGNMENT) = {
    270 #ifdef LWP0_CPU_INFO
    271 	.l_cpu = LWP0_CPU_INFO,
    272 #endif
    273 #ifdef LWP0_MD_INITIALIZER
    274 	.l_md = LWP0_MD_INITIALIZER,
    275 #endif
    276 	.l_proc = &proc0,
    277 	.l_lid = 1,
    278 	.l_flag = LW_SYSTEM,
    279 	.l_stat = LSONPROC,
    280 	.l_ts = &turnstile0,
    281 	.l_syncobj = &sched_syncobj,
    282 	.l_refcnt = 1,
    283 	.l_priority = PRI_USER + NPRI_USER - 1,
    284 	.l_inheritedprio = -1,
    285 	.l_class = SCHED_OTHER,
    286 	.l_psid = PS_NONE,
    287 	.l_pi_lenders = SLIST_HEAD_INITIALIZER(&lwp0.l_pi_lenders),
    288 	.l_name = __UNCONST("swapper"),
    289 	.l_fd = &filedesc0,
    290 };
    291 
    292 void
    293 lwpinit(void)
    294 {
    295 
    296 	LIST_INIT(&alllwp);
    297 	lwpinit_specificdata();
    298 	lwp_sys_init();
    299 	lwp_cache = pool_cache_init(sizeof(lwp_t), MIN_LWP_ALIGNMENT, 0, 0,
    300 	    "lwppl", NULL, IPL_NONE, NULL, lwp_dtor, NULL);
    301 }
    302 
    303 void
    304 lwp0_init(void)
    305 {
    306 	struct lwp *l = &lwp0;
    307 
    308 	KASSERT((void *)uvm_lwp_getuarea(l) != NULL);
    309 	KASSERT(l->l_lid == proc0.p_nlwpid);
    310 
    311 	LIST_INSERT_HEAD(&alllwp, l, l_list);
    312 
    313 	callout_init(&l->l_timeout_ch, CALLOUT_MPSAFE);
    314 	callout_setfunc(&l->l_timeout_ch, sleepq_timeout, l);
    315 	cv_init(&l->l_sigcv, "sigwait");
    316 
    317 	kauth_cred_hold(proc0.p_cred);
    318 	l->l_cred = proc0.p_cred;
    319 
    320 	lwp_initspecific(l);
    321 
    322 	SYSCALL_TIME_LWP_INIT(l);
    323 }
    324 
    325 static void
    326 lwp_dtor(void *arg, void *obj)
    327 {
    328 	lwp_t *l = obj;
    329 	uint64_t where;
    330 	(void)l;
    331 
    332 	/*
    333 	 * Provide a barrier to ensure that all mutex_oncpu() and rw_oncpu()
    334 	 * calls will exit before memory of LWP is returned to the pool, where
    335 	 * KVA of LWP structure might be freed and re-used for other purposes.
    336 	 * Kernel preemption is disabled around mutex_oncpu() and rw_oncpu()
    337 	 * callers, therefore cross-call to all CPUs will do the job.  Also,
    338 	 * the value of l->l_cpu must be still valid at this point.
    339 	 */
    340 	KASSERT(l->l_cpu != NULL);
    341 	where = xc_broadcast(0, (xcfunc_t)nullop, NULL, NULL);
    342 	xc_wait(where);
    343 }
    344 
    345 /*
    346  * Set an suspended.
    347  *
    348  * Must be called with p_lock held, and the LWP locked.  Will unlock the
    349  * LWP before return.
    350  */
    351 int
    352 lwp_suspend(struct lwp *curl, struct lwp *t)
    353 {
    354 	int error;
    355 
    356 	KASSERT(mutex_owned(t->l_proc->p_lock));
    357 	KASSERT(lwp_locked(t, NULL));
    358 
    359 	KASSERT(curl != t || curl->l_stat == LSONPROC);
    360 
    361 	/*
    362 	 * If the current LWP has been told to exit, we must not suspend anyone
    363 	 * else or deadlock could occur.  We won't return to userspace.
    364 	 */
    365 	if ((curl->l_flag & (LW_WEXIT | LW_WCORE)) != 0) {
    366 		lwp_unlock(t);
    367 		return (EDEADLK);
    368 	}
    369 
    370 	error = 0;
    371 
    372 	switch (t->l_stat) {
    373 	case LSRUN:
    374 	case LSONPROC:
    375 		t->l_flag |= LW_WSUSPEND;
    376 		lwp_need_userret(t);
    377 		lwp_unlock(t);
    378 		break;
    379 
    380 	case LSSLEEP:
    381 		t->l_flag |= LW_WSUSPEND;
    382 
    383 		/*
    384 		 * Kick the LWP and try to get it to the kernel boundary
    385 		 * so that it will release any locks that it holds.
    386 		 * setrunnable() will release the lock.
    387 		 */
    388 		if ((t->l_flag & LW_SINTR) != 0)
    389 			setrunnable(t);
    390 		else
    391 			lwp_unlock(t);
    392 		break;
    393 
    394 	case LSSUSPENDED:
    395 		lwp_unlock(t);
    396 		break;
    397 
    398 	case LSSTOP:
    399 		t->l_flag |= LW_WSUSPEND;
    400 		setrunnable(t);
    401 		break;
    402 
    403 	case LSIDL:
    404 	case LSZOMB:
    405 		error = EINTR; /* It's what Solaris does..... */
    406 		lwp_unlock(t);
    407 		break;
    408 	}
    409 
    410 	return (error);
    411 }
    412 
    413 /*
    414  * Restart a suspended LWP.
    415  *
    416  * Must be called with p_lock held, and the LWP locked.  Will unlock the
    417  * LWP before return.
    418  */
    419 void
    420 lwp_continue(struct lwp *l)
    421 {
    422 
    423 	KASSERT(mutex_owned(l->l_proc->p_lock));
    424 	KASSERT(lwp_locked(l, NULL));
    425 
    426 	/* If rebooting or not suspended, then just bail out. */
    427 	if ((l->l_flag & LW_WREBOOT) != 0) {
    428 		lwp_unlock(l);
    429 		return;
    430 	}
    431 
    432 	l->l_flag &= ~LW_WSUSPEND;
    433 
    434 	if (l->l_stat != LSSUSPENDED) {
    435 		lwp_unlock(l);
    436 		return;
    437 	}
    438 
    439 	/* setrunnable() will release the lock. */
    440 	setrunnable(l);
    441 }
    442 
    443 /*
    444  * Restart a stopped LWP.
    445  *
    446  * Must be called with p_lock held, and the LWP NOT locked.  Will unlock the
    447  * LWP before return.
    448  */
    449 void
    450 lwp_unstop(struct lwp *l)
    451 {
    452 	struct proc *p = l->l_proc;
    453 
    454 	KASSERT(mutex_owned(proc_lock));
    455 	KASSERT(mutex_owned(p->p_lock));
    456 
    457 	lwp_lock(l);
    458 
    459 	/* If not stopped, then just bail out. */
    460 	if (l->l_stat != LSSTOP) {
    461 		lwp_unlock(l);
    462 		return;
    463 	}
    464 
    465 	p->p_stat = SACTIVE;
    466 	p->p_sflag &= ~PS_STOPPING;
    467 
    468 	if (!p->p_waited)
    469 		p->p_pptr->p_nstopchild--;
    470 
    471 	if (l->l_wchan == NULL) {
    472 		/* setrunnable() will release the lock. */
    473 		setrunnable(l);
    474 	} else {
    475 		l->l_stat = LSSLEEP;
    476 		p->p_nrlwps++;
    477 		lwp_unlock(l);
    478 	}
    479 }
    480 
    481 /*
    482  * Wait for an LWP within the current process to exit.  If 'lid' is
    483  * non-zero, we are waiting for a specific LWP.
    484  *
    485  * Must be called with p->p_lock held.
    486  */
    487 int
    488 lwp_wait1(struct lwp *l, lwpid_t lid, lwpid_t *departed, int flags)
    489 {
    490 	struct proc *p = l->l_proc;
    491 	struct lwp *l2;
    492 	int nfound, error;
    493 	lwpid_t curlid;
    494 	bool exiting;
    495 
    496 	KASSERT(mutex_owned(p->p_lock));
    497 
    498 	p->p_nlwpwait++;
    499 	l->l_waitingfor = lid;
    500 	curlid = l->l_lid;
    501 	exiting = ((flags & LWPWAIT_EXITCONTROL) != 0);
    502 
    503 	for (;;) {
    504 		/*
    505 		 * Avoid a race between exit1() and sigexit(): if the
    506 		 * process is dumping core, then we need to bail out: call
    507 		 * into lwp_userret() where we will be suspended until the
    508 		 * deed is done.
    509 		 */
    510 		if ((p->p_sflag & PS_WCORE) != 0) {
    511 			mutex_exit(p->p_lock);
    512 			lwp_userret(l);
    513 #ifdef DIAGNOSTIC
    514 			panic("lwp_wait1");
    515 #endif
    516 			/* NOTREACHED */
    517 		}
    518 
    519 		/*
    520 		 * First off, drain any detached LWP that is waiting to be
    521 		 * reaped.
    522 		 */
    523 		while ((l2 = p->p_zomblwp) != NULL) {
    524 			p->p_zomblwp = NULL;
    525 			lwp_free(l2, false, false);/* releases proc mutex */
    526 			mutex_enter(p->p_lock);
    527 		}
    528 
    529 		/*
    530 		 * Now look for an LWP to collect.  If the whole process is
    531 		 * exiting, count detached LWPs as eligible to be collected,
    532 		 * but don't drain them here.
    533 		 */
    534 		nfound = 0;
    535 		error = 0;
    536 		LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
    537 			/*
    538 			 * If a specific wait and the target is waiting on
    539 			 * us, then avoid deadlock.  This also traps LWPs
    540 			 * that try to wait on themselves.
    541 			 *
    542 			 * Note that this does not handle more complicated
    543 			 * cycles, like: t1 -> t2 -> t3 -> t1.  The process
    544 			 * can still be killed so it is not a major problem.
    545 			 */
    546 			if (l2->l_lid == lid && l2->l_waitingfor == curlid) {
    547 				error = EDEADLK;
    548 				break;
    549 			}
    550 			if (l2 == l)
    551 				continue;
    552 			if ((l2->l_prflag & LPR_DETACHED) != 0) {
    553 				nfound += exiting;
    554 				continue;
    555 			}
    556 			if (lid != 0) {
    557 				if (l2->l_lid != lid)
    558 					continue;
    559 				/*
    560 				 * Mark this LWP as the first waiter, if there
    561 				 * is no other.
    562 				 */
    563 				if (l2->l_waiter == 0)
    564 					l2->l_waiter = curlid;
    565 			} else if (l2->l_waiter != 0) {
    566 				/*
    567 				 * It already has a waiter - so don't
    568 				 * collect it.  If the waiter doesn't
    569 				 * grab it we'll get another chance
    570 				 * later.
    571 				 */
    572 				nfound++;
    573 				continue;
    574 			}
    575 			nfound++;
    576 
    577 			/* No need to lock the LWP in order to see LSZOMB. */
    578 			if (l2->l_stat != LSZOMB)
    579 				continue;
    580 
    581 			/*
    582 			 * We're no longer waiting.  Reset the "first waiter"
    583 			 * pointer on the target, in case it was us.
    584 			 */
    585 			l->l_waitingfor = 0;
    586 			l2->l_waiter = 0;
    587 			p->p_nlwpwait--;
    588 			if (departed)
    589 				*departed = l2->l_lid;
    590 			sched_lwp_collect(l2);
    591 
    592 			/* lwp_free() releases the proc lock. */
    593 			lwp_free(l2, false, false);
    594 			mutex_enter(p->p_lock);
    595 			return 0;
    596 		}
    597 
    598 		if (error != 0)
    599 			break;
    600 		if (nfound == 0) {
    601 			error = ESRCH;
    602 			break;
    603 		}
    604 
    605 		/*
    606 		 * The kernel is careful to ensure that it can not deadlock
    607 		 * when exiting - just keep waiting.
    608 		 */
    609 		if (exiting) {
    610 			KASSERT(p->p_nlwps > 1);
    611 			cv_wait(&p->p_lwpcv, p->p_lock);
    612 			continue;
    613 		}
    614 
    615 		/*
    616 		 * If all other LWPs are waiting for exits or suspends
    617 		 * and the supply of zombies and potential zombies is
    618 		 * exhausted, then we are about to deadlock.
    619 		 *
    620 		 * If the process is exiting (and this LWP is not the one
    621 		 * that is coordinating the exit) then bail out now.
    622 		 */
    623 		if ((p->p_sflag & PS_WEXIT) != 0 ||
    624 		    p->p_nrlwps + p->p_nzlwps - p->p_ndlwps <= p->p_nlwpwait) {
    625 			error = EDEADLK;
    626 			break;
    627 		}
    628 
    629 		/*
    630 		 * Sit around and wait for something to happen.  We'll be
    631 		 * awoken if any of the conditions examined change: if an
    632 		 * LWP exits, is collected, or is detached.
    633 		 */
    634 		if ((error = cv_wait_sig(&p->p_lwpcv, p->p_lock)) != 0)
    635 			break;
    636 	}
    637 
    638 	/*
    639 	 * We didn't find any LWPs to collect, we may have received a
    640 	 * signal, or some other condition has caused us to bail out.
    641 	 *
    642 	 * If waiting on a specific LWP, clear the waiters marker: some
    643 	 * other LWP may want it.  Then, kick all the remaining waiters
    644 	 * so that they can re-check for zombies and for deadlock.
    645 	 */
    646 	if (lid != 0) {
    647 		LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
    648 			if (l2->l_lid == lid) {
    649 				if (l2->l_waiter == curlid)
    650 					l2->l_waiter = 0;
    651 				break;
    652 			}
    653 		}
    654 	}
    655 	p->p_nlwpwait--;
    656 	l->l_waitingfor = 0;
    657 	cv_broadcast(&p->p_lwpcv);
    658 
    659 	return error;
    660 }
    661 
    662 /*
    663  * Create a new LWP within process 'p2', using LWP 'l1' as a template.
    664  * The new LWP is created in state LSIDL and must be set running,
    665  * suspended, or stopped by the caller.
    666  */
    667 int
    668 lwp_create(lwp_t *l1, proc_t *p2, vaddr_t uaddr, int flags,
    669 	   void *stack, size_t stacksize, void (*func)(void *), void *arg,
    670 	   lwp_t **rnewlwpp, int sclass)
    671 {
    672 	struct lwp *l2, *isfree;
    673 	turnstile_t *ts;
    674 	lwpid_t lid;
    675 
    676 	KASSERT(l1 == curlwp || l1->l_proc == &proc0);
    677 
    678 	/*
    679 	 * First off, reap any detached LWP waiting to be collected.
    680 	 * We can re-use its LWP structure and turnstile.
    681 	 */
    682 	isfree = NULL;
    683 	if (p2->p_zomblwp != NULL) {
    684 		mutex_enter(p2->p_lock);
    685 		if ((isfree = p2->p_zomblwp) != NULL) {
    686 			p2->p_zomblwp = NULL;
    687 			lwp_free(isfree, true, false);/* releases proc mutex */
    688 		} else
    689 			mutex_exit(p2->p_lock);
    690 	}
    691 	if (isfree == NULL) {
    692 		l2 = pool_cache_get(lwp_cache, PR_WAITOK);
    693 		memset(l2, 0, sizeof(*l2));
    694 		l2->l_ts = pool_cache_get(turnstile_cache, PR_WAITOK);
    695 		SLIST_INIT(&l2->l_pi_lenders);
    696 	} else {
    697 		l2 = isfree;
    698 		ts = l2->l_ts;
    699 		KASSERT(l2->l_inheritedprio == -1);
    700 		KASSERT(SLIST_EMPTY(&l2->l_pi_lenders));
    701 		memset(l2, 0, sizeof(*l2));
    702 		l2->l_ts = ts;
    703 	}
    704 
    705 	l2->l_stat = LSIDL;
    706 	l2->l_proc = p2;
    707 	l2->l_refcnt = 1;
    708 	l2->l_class = sclass;
    709 
    710 	/*
    711 	 * If vfork(), we want the LWP to run fast and on the same CPU
    712 	 * as its parent, so that it can reuse the VM context and cache
    713 	 * footprint on the local CPU.
    714 	 */
    715 	l2->l_kpriority = ((flags & LWP_VFORK) ? true : false);
    716 	l2->l_kpribase = PRI_KERNEL;
    717 	l2->l_priority = l1->l_priority;
    718 	l2->l_inheritedprio = -1;
    719 	l2->l_flag = 0;
    720 	l2->l_pflag = LP_MPSAFE;
    721 	TAILQ_INIT(&l2->l_ld_locks);
    722 
    723 	/*
    724 	 * For vfork, borrow parent's lwpctl context if it exists.
    725 	 * This also causes us to return via lwp_userret.
    726 	 */
    727 	if (flags & LWP_VFORK && l1->l_lwpctl) {
    728 		l2->l_lwpctl = l1->l_lwpctl;
    729 		l2->l_flag |= LW_LWPCTL;
    730 	}
    731 
    732 	/*
    733 	 * If not the first LWP in the process, grab a reference to the
    734 	 * descriptor table.
    735 	 */
    736 	l2->l_fd = p2->p_fd;
    737 	if (p2->p_nlwps != 0) {
    738 		KASSERT(l1->l_proc == p2);
    739 		fd_hold(l2);
    740 	} else {
    741 		KASSERT(l1->l_proc != p2);
    742 	}
    743 
    744 	if (p2->p_flag & PK_SYSTEM) {
    745 		/* Mark it as a system LWP. */
    746 		l2->l_flag |= LW_SYSTEM;
    747 	}
    748 
    749 	kpreempt_disable();
    750 	l2->l_mutex = l1->l_cpu->ci_schedstate.spc_mutex;
    751 	l2->l_cpu = l1->l_cpu;
    752 	kpreempt_enable();
    753 
    754 	kdtrace_thread_ctor(NULL, l2);
    755 	lwp_initspecific(l2);
    756 	sched_lwp_fork(l1, l2);
    757 	lwp_update_creds(l2);
    758 	callout_init(&l2->l_timeout_ch, CALLOUT_MPSAFE);
    759 	callout_setfunc(&l2->l_timeout_ch, sleepq_timeout, l2);
    760 	cv_init(&l2->l_sigcv, "sigwait");
    761 	l2->l_syncobj = &sched_syncobj;
    762 
    763 	if (rnewlwpp != NULL)
    764 		*rnewlwpp = l2;
    765 
    766 	/*
    767 	 * PCU state needs to be saved before calling uvm_lwp_fork() so that
    768 	 * the MD cpu_lwp_fork() can copy the saved state to the new LWP.
    769 	 */
    770 	pcu_save_all(l1);
    771 
    772 	uvm_lwp_setuarea(l2, uaddr);
    773 	uvm_lwp_fork(l1, l2, stack, stacksize, func,
    774 	    (arg != NULL) ? arg : l2);
    775 
    776 	if ((flags & LWP_PIDLID) != 0) {
    777 		lid = proc_alloc_pid(p2);
    778 		l2->l_pflag |= LP_PIDLID;
    779 	} else {
    780 		lid = 0;
    781 	}
    782 
    783 	mutex_enter(p2->p_lock);
    784 
    785 	if ((flags & LWP_DETACHED) != 0) {
    786 		l2->l_prflag = LPR_DETACHED;
    787 		p2->p_ndlwps++;
    788 	} else
    789 		l2->l_prflag = 0;
    790 
    791 	l2->l_sigmask = l1->l_sigmask;
    792 	CIRCLEQ_INIT(&l2->l_sigpend.sp_info);
    793 	sigemptyset(&l2->l_sigpend.sp_set);
    794 
    795 	if (lid == 0) {
    796 		p2->p_nlwpid++;
    797 		if (p2->p_nlwpid == 0)
    798 			p2->p_nlwpid++;
    799 		lid = p2->p_nlwpid;
    800 	}
    801 	l2->l_lid = lid;
    802 	LIST_INSERT_HEAD(&p2->p_lwps, l2, l_sibling);
    803 	p2->p_nlwps++;
    804 	p2->p_nrlwps++;
    805 
    806 	KASSERT(l2->l_affinity == NULL);
    807 
    808 	if ((p2->p_flag & PK_SYSTEM) == 0) {
    809 		/* Inherit the affinity mask. */
    810 		if (l1->l_affinity) {
    811 			/*
    812 			 * Note that we hold the state lock while inheriting
    813 			 * the affinity to avoid race with sched_setaffinity().
    814 			 */
    815 			lwp_lock(l1);
    816 			if (l1->l_affinity) {
    817 				kcpuset_use(l1->l_affinity);
    818 				l2->l_affinity = l1->l_affinity;
    819 			}
    820 			lwp_unlock(l1);
    821 		}
    822 		lwp_lock(l2);
    823 		/* Inherit a processor-set */
    824 		l2->l_psid = l1->l_psid;
    825 		/* Look for a CPU to start */
    826 		l2->l_cpu = sched_takecpu(l2);
    827 		lwp_unlock_to(l2, l2->l_cpu->ci_schedstate.spc_mutex);
    828 	}
    829 	mutex_exit(p2->p_lock);
    830 
    831 	SDT_PROBE(proc,,,lwp_create, l2, 0,0,0,0);
    832 
    833 	mutex_enter(proc_lock);
    834 	LIST_INSERT_HEAD(&alllwp, l2, l_list);
    835 	mutex_exit(proc_lock);
    836 
    837 	SYSCALL_TIME_LWP_INIT(l2);
    838 
    839 	if (p2->p_emul->e_lwp_fork)
    840 		(*p2->p_emul->e_lwp_fork)(l1, l2);
    841 
    842 	return (0);
    843 }
    844 
    845 /*
    846  * Called by MD code when a new LWP begins execution.  Must be called
    847  * with the previous LWP locked (so at splsched), or if there is no
    848  * previous LWP, at splsched.
    849  */
    850 void
    851 lwp_startup(struct lwp *prev, struct lwp *new)
    852 {
    853 
    854 	SDT_PROBE(proc,,,lwp_start, new, 0,0,0,0);
    855 
    856 	KASSERT(kpreempt_disabled());
    857 	if (prev != NULL) {
    858 		/*
    859 		 * Normalize the count of the spin-mutexes, it was
    860 		 * increased in mi_switch().  Unmark the state of
    861 		 * context switch - it is finished for previous LWP.
    862 		 */
    863 		curcpu()->ci_mtx_count++;
    864 		membar_exit();
    865 		prev->l_ctxswtch = 0;
    866 	}
    867 	KPREEMPT_DISABLE(new);
    868 	spl0();
    869 	pmap_activate(new);
    870 
    871 	/* Note trip through cpu_switchto(). */
    872 	pserialize_switchpoint();
    873 
    874 	LOCKDEBUG_BARRIER(NULL, 0);
    875 	KPREEMPT_ENABLE(new);
    876 	if ((new->l_pflag & LP_MPSAFE) == 0) {
    877 		KERNEL_LOCK(1, new);
    878 	}
    879 }
    880 
    881 /*
    882  * Exit an LWP.
    883  */
    884 void
    885 lwp_exit(struct lwp *l)
    886 {
    887 	struct proc *p = l->l_proc;
    888 	struct lwp *l2;
    889 	bool current;
    890 
    891 	current = (l == curlwp);
    892 
    893 	KASSERT(current || (l->l_stat == LSIDL && l->l_target_cpu == NULL));
    894 	KASSERT(p == curproc);
    895 
    896 	SDT_PROBE(proc,,,lwp_exit, l, 0,0,0,0);
    897 
    898 	/*
    899 	 * Verify that we hold no locks other than the kernel lock.
    900 	 */
    901 	LOCKDEBUG_BARRIER(&kernel_lock, 0);
    902 
    903 	/*
    904 	 * If we are the last live LWP in a process, we need to exit the
    905 	 * entire process.  We do so with an exit status of zero, because
    906 	 * it's a "controlled" exit, and because that's what Solaris does.
    907 	 *
    908 	 * We are not quite a zombie yet, but for accounting purposes we
    909 	 * must increment the count of zombies here.
    910 	 *
    911 	 * Note: the last LWP's specificdata will be deleted here.
    912 	 */
    913 	mutex_enter(p->p_lock);
    914 	if (p->p_nlwps - p->p_nzlwps == 1) {
    915 		KASSERT(current == true);
    916 		/* XXXSMP kernel_lock not held */
    917 		exit1(l, 0);
    918 		/* NOTREACHED */
    919 	}
    920 	p->p_nzlwps++;
    921 	mutex_exit(p->p_lock);
    922 
    923 	if (p->p_emul->e_lwp_exit)
    924 		(*p->p_emul->e_lwp_exit)(l);
    925 
    926 	/* Drop filedesc reference. */
    927 	fd_free();
    928 
    929 	/* Delete the specificdata while it's still safe to sleep. */
    930 	lwp_finispecific(l);
    931 
    932 	/*
    933 	 * Release our cached credentials.
    934 	 */
    935 	kauth_cred_free(l->l_cred);
    936 	callout_destroy(&l->l_timeout_ch);
    937 
    938 	/*
    939 	 * Remove the LWP from the global list.
    940 	 * Free its LID from the PID namespace if needed.
    941 	 */
    942 	mutex_enter(proc_lock);
    943 	LIST_REMOVE(l, l_list);
    944 	if ((l->l_pflag & LP_PIDLID) != 0 && l->l_lid != p->p_pid) {
    945 		proc_free_pid(l->l_lid);
    946 	}
    947 	mutex_exit(proc_lock);
    948 
    949 	/*
    950 	 * Get rid of all references to the LWP that others (e.g. procfs)
    951 	 * may have, and mark the LWP as a zombie.  If the LWP is detached,
    952 	 * mark it waiting for collection in the proc structure.  Note that
    953 	 * before we can do that, we need to free any other dead, deatched
    954 	 * LWP waiting to meet its maker.
    955 	 */
    956 	mutex_enter(p->p_lock);
    957 	lwp_drainrefs(l);
    958 
    959 	if ((l->l_prflag & LPR_DETACHED) != 0) {
    960 		while ((l2 = p->p_zomblwp) != NULL) {
    961 			p->p_zomblwp = NULL;
    962 			lwp_free(l2, false, false);/* releases proc mutex */
    963 			mutex_enter(p->p_lock);
    964 			l->l_refcnt++;
    965 			lwp_drainrefs(l);
    966 		}
    967 		p->p_zomblwp = l;
    968 	}
    969 
    970 	/*
    971 	 * If we find a pending signal for the process and we have been
    972 	 * asked to check for signals, then we lose: arrange to have
    973 	 * all other LWPs in the process check for signals.
    974 	 */
    975 	if ((l->l_flag & LW_PENDSIG) != 0 &&
    976 	    firstsig(&p->p_sigpend.sp_set) != 0) {
    977 		LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
    978 			lwp_lock(l2);
    979 			l2->l_flag |= LW_PENDSIG;
    980 			lwp_unlock(l2);
    981 		}
    982 	}
    983 
    984 	/*
    985 	 * Release any PCU resources before becoming a zombie.
    986 	 */
    987 	pcu_discard_all(l);
    988 
    989 	lwp_lock(l);
    990 	l->l_stat = LSZOMB;
    991 	if (l->l_name != NULL) {
    992 		strcpy(l->l_name, "(zombie)");
    993 	}
    994 	lwp_unlock(l);
    995 	p->p_nrlwps--;
    996 	cv_broadcast(&p->p_lwpcv);
    997 	if (l->l_lwpctl != NULL)
    998 		l->l_lwpctl->lc_curcpu = LWPCTL_CPU_EXITED;
    999 	mutex_exit(p->p_lock);
   1000 
   1001 	/*
   1002 	 * We can no longer block.  At this point, lwp_free() may already
   1003 	 * be gunning for us.  On a multi-CPU system, we may be off p_lwps.
   1004 	 *
   1005 	 * Free MD LWP resources.
   1006 	 */
   1007 	cpu_lwp_free(l, 0);
   1008 
   1009 	if (current) {
   1010 		pmap_deactivate(l);
   1011 
   1012 		/*
   1013 		 * Release the kernel lock, and switch away into
   1014 		 * oblivion.
   1015 		 */
   1016 #ifdef notyet
   1017 		/* XXXSMP hold in lwp_userret() */
   1018 		KERNEL_UNLOCK_LAST(l);
   1019 #else
   1020 		KERNEL_UNLOCK_ALL(l, NULL);
   1021 #endif
   1022 		lwp_exit_switchaway(l);
   1023 	}
   1024 }
   1025 
   1026 /*
   1027  * Free a dead LWP's remaining resources.
   1028  *
   1029  * XXXLWP limits.
   1030  */
   1031 void
   1032 lwp_free(struct lwp *l, bool recycle, bool last)
   1033 {
   1034 	struct proc *p = l->l_proc;
   1035 	struct rusage *ru;
   1036 	ksiginfoq_t kq;
   1037 
   1038 	KASSERT(l != curlwp);
   1039 	KASSERT(last || mutex_owned(p->p_lock));
   1040 
   1041 	/*
   1042 	 * If this was not the last LWP in the process, then adjust
   1043 	 * counters and unlock.
   1044 	 */
   1045 	if (!last) {
   1046 		/*
   1047 		 * Add the LWP's run time to the process' base value.
   1048 		 * This needs to co-incide with coming off p_lwps.
   1049 		 */
   1050 		bintime_add(&p->p_rtime, &l->l_rtime);
   1051 		p->p_pctcpu += l->l_pctcpu;
   1052 		ru = &p->p_stats->p_ru;
   1053 		ruadd(ru, &l->l_ru);
   1054 		ru->ru_nvcsw += (l->l_ncsw - l->l_nivcsw);
   1055 		ru->ru_nivcsw += l->l_nivcsw;
   1056 		LIST_REMOVE(l, l_sibling);
   1057 		p->p_nlwps--;
   1058 		p->p_nzlwps--;
   1059 		if ((l->l_prflag & LPR_DETACHED) != 0)
   1060 			p->p_ndlwps--;
   1061 
   1062 		/*
   1063 		 * Have any LWPs sleeping in lwp_wait() recheck for
   1064 		 * deadlock.
   1065 		 */
   1066 		cv_broadcast(&p->p_lwpcv);
   1067 		mutex_exit(p->p_lock);
   1068 	}
   1069 
   1070 #ifdef MULTIPROCESSOR
   1071 	/*
   1072 	 * In the unlikely event that the LWP is still on the CPU,
   1073 	 * then spin until it has switched away.  We need to release
   1074 	 * all locks to avoid deadlock against interrupt handlers on
   1075 	 * the target CPU.
   1076 	 */
   1077 	if ((l->l_pflag & LP_RUNNING) != 0 || l->l_cpu->ci_curlwp == l) {
   1078 		int count;
   1079 		(void)count; /* XXXgcc */
   1080 		KERNEL_UNLOCK_ALL(curlwp, &count);
   1081 		while ((l->l_pflag & LP_RUNNING) != 0 ||
   1082 		    l->l_cpu->ci_curlwp == l)
   1083 			SPINLOCK_BACKOFF_HOOK;
   1084 		KERNEL_LOCK(count, curlwp);
   1085 	}
   1086 #endif
   1087 
   1088 	/*
   1089 	 * Destroy the LWP's remaining signal information.
   1090 	 */
   1091 	ksiginfo_queue_init(&kq);
   1092 	sigclear(&l->l_sigpend, NULL, &kq);
   1093 	ksiginfo_queue_drain(&kq);
   1094 	cv_destroy(&l->l_sigcv);
   1095 
   1096 	/*
   1097 	 * Free lwpctl structure and affinity.
   1098 	 */
   1099 	if (l->l_lwpctl) {
   1100 		lwp_ctl_free(l);
   1101 	}
   1102 	if (l->l_affinity) {
   1103 		kcpuset_unuse(l->l_affinity, NULL);
   1104 		l->l_affinity = NULL;
   1105 	}
   1106 
   1107 	/*
   1108 	 * Free the LWP's turnstile and the LWP structure itself unless the
   1109 	 * caller wants to recycle them.  Also, free the scheduler specific
   1110 	 * data.
   1111 	 *
   1112 	 * We can't return turnstile0 to the pool (it didn't come from it),
   1113 	 * so if it comes up just drop it quietly and move on.
   1114 	 *
   1115 	 * We don't recycle the VM resources at this time.
   1116 	 */
   1117 
   1118 	if (!recycle && l->l_ts != &turnstile0)
   1119 		pool_cache_put(turnstile_cache, l->l_ts);
   1120 	if (l->l_name != NULL)
   1121 		kmem_free(l->l_name, MAXCOMLEN);
   1122 
   1123 	cpu_lwp_free2(l);
   1124 	uvm_lwp_exit(l);
   1125 
   1126 	KASSERT(SLIST_EMPTY(&l->l_pi_lenders));
   1127 	KASSERT(l->l_inheritedprio == -1);
   1128 	KASSERT(l->l_blcnt == 0);
   1129 	kdtrace_thread_dtor(NULL, l);
   1130 	if (!recycle)
   1131 		pool_cache_put(lwp_cache, l);
   1132 }
   1133 
   1134 /*
   1135  * Migrate the LWP to the another CPU.  Unlocks the LWP.
   1136  */
   1137 void
   1138 lwp_migrate(lwp_t *l, struct cpu_info *tci)
   1139 {
   1140 	struct schedstate_percpu *tspc;
   1141 	int lstat = l->l_stat;
   1142 
   1143 	KASSERT(lwp_locked(l, NULL));
   1144 	KASSERT(tci != NULL);
   1145 
   1146 	/* If LWP is still on the CPU, it must be handled like LSONPROC */
   1147 	if ((l->l_pflag & LP_RUNNING) != 0) {
   1148 		lstat = LSONPROC;
   1149 	}
   1150 
   1151 	/*
   1152 	 * The destination CPU could be changed while previous migration
   1153 	 * was not finished.
   1154 	 */
   1155 	if (l->l_target_cpu != NULL) {
   1156 		l->l_target_cpu = tci;
   1157 		lwp_unlock(l);
   1158 		return;
   1159 	}
   1160 
   1161 	/* Nothing to do if trying to migrate to the same CPU */
   1162 	if (l->l_cpu == tci) {
   1163 		lwp_unlock(l);
   1164 		return;
   1165 	}
   1166 
   1167 	KASSERT(l->l_target_cpu == NULL);
   1168 	tspc = &tci->ci_schedstate;
   1169 	switch (lstat) {
   1170 	case LSRUN:
   1171 		l->l_target_cpu = tci;
   1172 		break;
   1173 	case LSIDL:
   1174 		l->l_cpu = tci;
   1175 		lwp_unlock_to(l, tspc->spc_mutex);
   1176 		return;
   1177 	case LSSLEEP:
   1178 		l->l_cpu = tci;
   1179 		break;
   1180 	case LSSTOP:
   1181 	case LSSUSPENDED:
   1182 		l->l_cpu = tci;
   1183 		if (l->l_wchan == NULL) {
   1184 			lwp_unlock_to(l, tspc->spc_lwplock);
   1185 			return;
   1186 		}
   1187 		break;
   1188 	case LSONPROC:
   1189 		l->l_target_cpu = tci;
   1190 		spc_lock(l->l_cpu);
   1191 		cpu_need_resched(l->l_cpu, RESCHED_KPREEMPT);
   1192 		spc_unlock(l->l_cpu);
   1193 		break;
   1194 	}
   1195 	lwp_unlock(l);
   1196 }
   1197 
   1198 /*
   1199  * Find the LWP in the process.  Arguments may be zero, in such case,
   1200  * the calling process and first LWP in the list will be used.
   1201  * On success - returns proc locked.
   1202  */
   1203 struct lwp *
   1204 lwp_find2(pid_t pid, lwpid_t lid)
   1205 {
   1206 	proc_t *p;
   1207 	lwp_t *l;
   1208 
   1209 	/* Find the process. */
   1210 	if (pid != 0) {
   1211 		mutex_enter(proc_lock);
   1212 		p = proc_find(pid);
   1213 		if (p == NULL) {
   1214 			mutex_exit(proc_lock);
   1215 			return NULL;
   1216 		}
   1217 		mutex_enter(p->p_lock);
   1218 		mutex_exit(proc_lock);
   1219 	} else {
   1220 		p = curlwp->l_proc;
   1221 		mutex_enter(p->p_lock);
   1222 	}
   1223 	/* Find the thread. */
   1224 	if (lid != 0) {
   1225 		l = lwp_find(p, lid);
   1226 	} else {
   1227 		l = LIST_FIRST(&p->p_lwps);
   1228 	}
   1229 	if (l == NULL) {
   1230 		mutex_exit(p->p_lock);
   1231 	}
   1232 	return l;
   1233 }
   1234 
   1235 /*
   1236  * Look up a live LWP within the specified process, and return it locked.
   1237  *
   1238  * Must be called with p->p_lock held.
   1239  */
   1240 struct lwp *
   1241 lwp_find(struct proc *p, lwpid_t id)
   1242 {
   1243 	struct lwp *l;
   1244 
   1245 	KASSERT(mutex_owned(p->p_lock));
   1246 
   1247 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
   1248 		if (l->l_lid == id)
   1249 			break;
   1250 	}
   1251 
   1252 	/*
   1253 	 * No need to lock - all of these conditions will
   1254 	 * be visible with the process level mutex held.
   1255 	 */
   1256 	if (l != NULL && (l->l_stat == LSIDL || l->l_stat == LSZOMB))
   1257 		l = NULL;
   1258 
   1259 	return l;
   1260 }
   1261 
   1262 /*
   1263  * Update an LWP's cached credentials to mirror the process' master copy.
   1264  *
   1265  * This happens early in the syscall path, on user trap, and on LWP
   1266  * creation.  A long-running LWP can also voluntarily choose to update
   1267  * it's credentials by calling this routine.  This may be called from
   1268  * LWP_CACHE_CREDS(), which checks l->l_cred != p->p_cred beforehand.
   1269  */
   1270 void
   1271 lwp_update_creds(struct lwp *l)
   1272 {
   1273 	kauth_cred_t oc;
   1274 	struct proc *p;
   1275 
   1276 	p = l->l_proc;
   1277 	oc = l->l_cred;
   1278 
   1279 	mutex_enter(p->p_lock);
   1280 	kauth_cred_hold(p->p_cred);
   1281 	l->l_cred = p->p_cred;
   1282 	l->l_prflag &= ~LPR_CRMOD;
   1283 	mutex_exit(p->p_lock);
   1284 	if (oc != NULL)
   1285 		kauth_cred_free(oc);
   1286 }
   1287 
   1288 /*
   1289  * Verify that an LWP is locked, and optionally verify that the lock matches
   1290  * one we specify.
   1291  */
   1292 int
   1293 lwp_locked(struct lwp *l, kmutex_t *mtx)
   1294 {
   1295 	kmutex_t *cur = l->l_mutex;
   1296 
   1297 	return mutex_owned(cur) && (mtx == cur || mtx == NULL);
   1298 }
   1299 
   1300 /*
   1301  * Lend a new mutex to an LWP.  The old mutex must be held.
   1302  */
   1303 void
   1304 lwp_setlock(struct lwp *l, kmutex_t *new)
   1305 {
   1306 
   1307 	KASSERT(mutex_owned(l->l_mutex));
   1308 
   1309 	membar_exit();
   1310 	l->l_mutex = new;
   1311 }
   1312 
   1313 /*
   1314  * Lend a new mutex to an LWP, and release the old mutex.  The old mutex
   1315  * must be held.
   1316  */
   1317 void
   1318 lwp_unlock_to(struct lwp *l, kmutex_t *new)
   1319 {
   1320 	kmutex_t *old;
   1321 
   1322 	KASSERT(lwp_locked(l, NULL));
   1323 
   1324 	old = l->l_mutex;
   1325 	membar_exit();
   1326 	l->l_mutex = new;
   1327 	mutex_spin_exit(old);
   1328 }
   1329 
   1330 int
   1331 lwp_trylock(struct lwp *l)
   1332 {
   1333 	kmutex_t *old;
   1334 
   1335 	for (;;) {
   1336 		if (!mutex_tryenter(old = l->l_mutex))
   1337 			return 0;
   1338 		if (__predict_true(l->l_mutex == old))
   1339 			return 1;
   1340 		mutex_spin_exit(old);
   1341 	}
   1342 }
   1343 
   1344 void
   1345 lwp_unsleep(lwp_t *l, bool cleanup)
   1346 {
   1347 
   1348 	KASSERT(mutex_owned(l->l_mutex));
   1349 	(*l->l_syncobj->sobj_unsleep)(l, cleanup);
   1350 }
   1351 
   1352 /*
   1353  * Handle exceptions for mi_userret().  Called if a member of LW_USERRET is
   1354  * set.
   1355  */
   1356 void
   1357 lwp_userret(struct lwp *l)
   1358 {
   1359 	struct proc *p;
   1360 	int sig;
   1361 
   1362 	KASSERT(l == curlwp);
   1363 	KASSERT(l->l_stat == LSONPROC);
   1364 	p = l->l_proc;
   1365 
   1366 #ifndef __HAVE_FAST_SOFTINTS
   1367 	/* Run pending soft interrupts. */
   1368 	if (l->l_cpu->ci_data.cpu_softints != 0)
   1369 		softint_overlay();
   1370 #endif
   1371 
   1372 #ifdef KERN_SA
   1373 	/* Generate UNBLOCKED upcall if needed */
   1374 	if (l->l_flag & LW_SA_BLOCKING) {
   1375 		sa_unblock_userret(l);
   1376 		/* NOTREACHED */
   1377 	}
   1378 #endif
   1379 
   1380 	/*
   1381 	 * It should be safe to do this read unlocked on a multiprocessor
   1382 	 * system..
   1383 	 *
   1384 	 * LW_SA_UPCALL will be handled after the while() loop, so don't
   1385 	 * consider it now.
   1386 	 */
   1387 	while ((l->l_flag & (LW_USERRET & ~(LW_SA_UPCALL))) != 0) {
   1388 		/*
   1389 		 * Process pending signals first, unless the process
   1390 		 * is dumping core or exiting, where we will instead
   1391 		 * enter the LW_WSUSPEND case below.
   1392 		 */
   1393 		if ((l->l_flag & (LW_PENDSIG | LW_WCORE | LW_WEXIT)) ==
   1394 		    LW_PENDSIG) {
   1395 			mutex_enter(p->p_lock);
   1396 			while ((sig = issignal(l)) != 0)
   1397 				postsig(sig);
   1398 			mutex_exit(p->p_lock);
   1399 		}
   1400 
   1401 		/*
   1402 		 * Core-dump or suspend pending.
   1403 		 *
   1404 		 * In case of core dump, suspend ourselves, so that the kernel
   1405 		 * stack and therefore the userland registers saved in the
   1406 		 * trapframe are around for coredump() to write them out.
   1407 		 * We also need to save any PCU resources that we have so that
   1408 		 * they accessible for coredump().  We issue a wakeup on
   1409 		 * p->p_lwpcv so that sigexit() will write the core file out
   1410 		 * once all other LWPs are suspended.
   1411 		 */
   1412 		if ((l->l_flag & LW_WSUSPEND) != 0) {
   1413 			pcu_save_all(l);
   1414 			mutex_enter(p->p_lock);
   1415 			p->p_nrlwps--;
   1416 			cv_broadcast(&p->p_lwpcv);
   1417 			lwp_lock(l);
   1418 			l->l_stat = LSSUSPENDED;
   1419 			lwp_unlock(l);
   1420 			mutex_exit(p->p_lock);
   1421 			lwp_lock(l);
   1422 			mi_switch(l);
   1423 		}
   1424 
   1425 		/* Process is exiting. */
   1426 		if ((l->l_flag & LW_WEXIT) != 0) {
   1427 			lwp_exit(l);
   1428 			KASSERT(0);
   1429 			/* NOTREACHED */
   1430 		}
   1431 
   1432 		/* update lwpctl processor (for vfork child_return) */
   1433 		if (l->l_flag & LW_LWPCTL) {
   1434 			lwp_lock(l);
   1435 			KASSERT(kpreempt_disabled());
   1436 			l->l_lwpctl->lc_curcpu = (int)cpu_index(l->l_cpu);
   1437 			l->l_lwpctl->lc_pctr++;
   1438 			l->l_flag &= ~LW_LWPCTL;
   1439 			lwp_unlock(l);
   1440 		}
   1441 	}
   1442 
   1443 #ifdef KERN_SA
   1444 	/*
   1445 	 * Timer events are handled specially.  We only try once to deliver
   1446 	 * pending timer upcalls; if if fails, we can try again on the next
   1447 	 * loop around.  If we need to re-enter lwp_userret(), MD code will
   1448 	 * bounce us back here through the trap path after we return.
   1449 	 */
   1450 	if (p->p_timerpend)
   1451 		timerupcall(l);
   1452 	if (l->l_flag & LW_SA_UPCALL)
   1453 		sa_upcall_userret(l);
   1454 #endif /* KERN_SA */
   1455 }
   1456 
   1457 /*
   1458  * Force an LWP to enter the kernel, to take a trip through lwp_userret().
   1459  */
   1460 void
   1461 lwp_need_userret(struct lwp *l)
   1462 {
   1463 	KASSERT(lwp_locked(l, NULL));
   1464 
   1465 	/*
   1466 	 * Since the tests in lwp_userret() are done unlocked, make sure
   1467 	 * that the condition will be seen before forcing the LWP to enter
   1468 	 * kernel mode.
   1469 	 */
   1470 	membar_producer();
   1471 	cpu_signotify(l);
   1472 }
   1473 
   1474 /*
   1475  * Add one reference to an LWP.  This will prevent the LWP from
   1476  * exiting, thus keep the lwp structure and PCB around to inspect.
   1477  */
   1478 void
   1479 lwp_addref(struct lwp *l)
   1480 {
   1481 
   1482 	KASSERT(mutex_owned(l->l_proc->p_lock));
   1483 	KASSERT(l->l_stat != LSZOMB);
   1484 	KASSERT(l->l_refcnt != 0);
   1485 
   1486 	l->l_refcnt++;
   1487 }
   1488 
   1489 /*
   1490  * Remove one reference to an LWP.  If this is the last reference,
   1491  * then we must finalize the LWP's death.
   1492  */
   1493 void
   1494 lwp_delref(struct lwp *l)
   1495 {
   1496 	struct proc *p = l->l_proc;
   1497 
   1498 	mutex_enter(p->p_lock);
   1499 	lwp_delref2(l);
   1500 	mutex_exit(p->p_lock);
   1501 }
   1502 
   1503 /*
   1504  * Remove one reference to an LWP.  If this is the last reference,
   1505  * then we must finalize the LWP's death.  The proc mutex is held
   1506  * on entry.
   1507  */
   1508 void
   1509 lwp_delref2(struct lwp *l)
   1510 {
   1511 	struct proc *p = l->l_proc;
   1512 
   1513 	KASSERT(mutex_owned(p->p_lock));
   1514 	KASSERT(l->l_stat != LSZOMB);
   1515 	KASSERT(l->l_refcnt > 0);
   1516 	if (--l->l_refcnt == 0)
   1517 		cv_broadcast(&p->p_lwpcv);
   1518 }
   1519 
   1520 /*
   1521  * Drain all references to the current LWP.
   1522  */
   1523 void
   1524 lwp_drainrefs(struct lwp *l)
   1525 {
   1526 	struct proc *p = l->l_proc;
   1527 
   1528 	KASSERT(mutex_owned(p->p_lock));
   1529 	KASSERT(l->l_refcnt != 0);
   1530 
   1531 	l->l_refcnt--;
   1532 	while (l->l_refcnt != 0)
   1533 		cv_wait(&p->p_lwpcv, p->p_lock);
   1534 }
   1535 
   1536 /*
   1537  * Return true if the specified LWP is 'alive'.  Only p->p_lock need
   1538  * be held.
   1539  */
   1540 bool
   1541 lwp_alive(lwp_t *l)
   1542 {
   1543 
   1544 	KASSERT(mutex_owned(l->l_proc->p_lock));
   1545 
   1546 	switch (l->l_stat) {
   1547 	case LSSLEEP:
   1548 	case LSRUN:
   1549 	case LSONPROC:
   1550 	case LSSTOP:
   1551 	case LSSUSPENDED:
   1552 		return true;
   1553 	default:
   1554 		return false;
   1555 	}
   1556 }
   1557 
   1558 /*
   1559  * Return first live LWP in the process.
   1560  */
   1561 lwp_t *
   1562 lwp_find_first(proc_t *p)
   1563 {
   1564 	lwp_t *l;
   1565 
   1566 	KASSERT(mutex_owned(p->p_lock));
   1567 
   1568 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
   1569 		if (lwp_alive(l)) {
   1570 			return l;
   1571 		}
   1572 	}
   1573 
   1574 	return NULL;
   1575 }
   1576 
   1577 /*
   1578  * Allocate a new lwpctl structure for a user LWP.
   1579  */
   1580 int
   1581 lwp_ctl_alloc(vaddr_t *uaddr)
   1582 {
   1583 	lcproc_t *lp;
   1584 	u_int bit, i, offset;
   1585 	struct uvm_object *uao;
   1586 	int error;
   1587 	lcpage_t *lcp;
   1588 	proc_t *p;
   1589 	lwp_t *l;
   1590 
   1591 	l = curlwp;
   1592 	p = l->l_proc;
   1593 
   1594 	/* don't allow a vforked process to create lwp ctls */
   1595 	if (p->p_lflag & PL_PPWAIT)
   1596 		return EBUSY;
   1597 
   1598 	if (l->l_lcpage != NULL) {
   1599 		lcp = l->l_lcpage;
   1600 		*uaddr = lcp->lcp_uaddr + (vaddr_t)l->l_lwpctl - lcp->lcp_kaddr;
   1601 		return 0;
   1602 	}
   1603 
   1604 	/* First time around, allocate header structure for the process. */
   1605 	if ((lp = p->p_lwpctl) == NULL) {
   1606 		lp = kmem_alloc(sizeof(*lp), KM_SLEEP);
   1607 		mutex_init(&lp->lp_lock, MUTEX_DEFAULT, IPL_NONE);
   1608 		lp->lp_uao = NULL;
   1609 		TAILQ_INIT(&lp->lp_pages);
   1610 		mutex_enter(p->p_lock);
   1611 		if (p->p_lwpctl == NULL) {
   1612 			p->p_lwpctl = lp;
   1613 			mutex_exit(p->p_lock);
   1614 		} else {
   1615 			mutex_exit(p->p_lock);
   1616 			mutex_destroy(&lp->lp_lock);
   1617 			kmem_free(lp, sizeof(*lp));
   1618 			lp = p->p_lwpctl;
   1619 		}
   1620 	}
   1621 
   1622  	/*
   1623  	 * Set up an anonymous memory region to hold the shared pages.
   1624  	 * Map them into the process' address space.  The user vmspace
   1625  	 * gets the first reference on the UAO.
   1626  	 */
   1627 	mutex_enter(&lp->lp_lock);
   1628 	if (lp->lp_uao == NULL) {
   1629 		lp->lp_uao = uao_create(LWPCTL_UAREA_SZ, 0);
   1630 		lp->lp_cur = 0;
   1631 		lp->lp_max = LWPCTL_UAREA_SZ;
   1632 		lp->lp_uva = p->p_emul->e_vm_default_addr(p,
   1633 		     (vaddr_t)p->p_vmspace->vm_daddr, LWPCTL_UAREA_SZ);
   1634 		error = uvm_map(&p->p_vmspace->vm_map, &lp->lp_uva,
   1635 		    LWPCTL_UAREA_SZ, lp->lp_uao, 0, 0, UVM_MAPFLAG(UVM_PROT_RW,
   1636 		    UVM_PROT_RW, UVM_INH_NONE, UVM_ADV_NORMAL, 0));
   1637 		if (error != 0) {
   1638 			uao_detach(lp->lp_uao);
   1639 			lp->lp_uao = NULL;
   1640 			mutex_exit(&lp->lp_lock);
   1641 			return error;
   1642 		}
   1643 	}
   1644 
   1645 	/* Get a free block and allocate for this LWP. */
   1646 	TAILQ_FOREACH(lcp, &lp->lp_pages, lcp_chain) {
   1647 		if (lcp->lcp_nfree != 0)
   1648 			break;
   1649 	}
   1650 	if (lcp == NULL) {
   1651 		/* Nothing available - try to set up a free page. */
   1652 		if (lp->lp_cur == lp->lp_max) {
   1653 			mutex_exit(&lp->lp_lock);
   1654 			return ENOMEM;
   1655 		}
   1656 		lcp = kmem_alloc(LWPCTL_LCPAGE_SZ, KM_SLEEP);
   1657 		if (lcp == NULL) {
   1658 			mutex_exit(&lp->lp_lock);
   1659 			return ENOMEM;
   1660 		}
   1661 		/*
   1662 		 * Wire the next page down in kernel space.  Since this
   1663 		 * is a new mapping, we must add a reference.
   1664 		 */
   1665 		uao = lp->lp_uao;
   1666 		(*uao->pgops->pgo_reference)(uao);
   1667 		lcp->lcp_kaddr = vm_map_min(kernel_map);
   1668 		error = uvm_map(kernel_map, &lcp->lcp_kaddr, PAGE_SIZE,
   1669 		    uao, lp->lp_cur, PAGE_SIZE,
   1670 		    UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW,
   1671 		    UVM_INH_NONE, UVM_ADV_RANDOM, 0));
   1672 		if (error != 0) {
   1673 			mutex_exit(&lp->lp_lock);
   1674 			kmem_free(lcp, LWPCTL_LCPAGE_SZ);
   1675 			(*uao->pgops->pgo_detach)(uao);
   1676 			return error;
   1677 		}
   1678 		error = uvm_map_pageable(kernel_map, lcp->lcp_kaddr,
   1679 		    lcp->lcp_kaddr + PAGE_SIZE, FALSE, 0);
   1680 		if (error != 0) {
   1681 			mutex_exit(&lp->lp_lock);
   1682 			uvm_unmap(kernel_map, lcp->lcp_kaddr,
   1683 			    lcp->lcp_kaddr + PAGE_SIZE);
   1684 			kmem_free(lcp, LWPCTL_LCPAGE_SZ);
   1685 			return error;
   1686 		}
   1687 		/* Prepare the page descriptor and link into the list. */
   1688 		lcp->lcp_uaddr = lp->lp_uva + lp->lp_cur;
   1689 		lp->lp_cur += PAGE_SIZE;
   1690 		lcp->lcp_nfree = LWPCTL_PER_PAGE;
   1691 		lcp->lcp_rotor = 0;
   1692 		memset(lcp->lcp_bitmap, 0xff, LWPCTL_BITMAP_SZ);
   1693 		TAILQ_INSERT_HEAD(&lp->lp_pages, lcp, lcp_chain);
   1694 	}
   1695 	for (i = lcp->lcp_rotor; lcp->lcp_bitmap[i] == 0;) {
   1696 		if (++i >= LWPCTL_BITMAP_ENTRIES)
   1697 			i = 0;
   1698 	}
   1699 	bit = ffs(lcp->lcp_bitmap[i]) - 1;
   1700 	lcp->lcp_bitmap[i] ^= (1 << bit);
   1701 	lcp->lcp_rotor = i;
   1702 	lcp->lcp_nfree--;
   1703 	l->l_lcpage = lcp;
   1704 	offset = (i << 5) + bit;
   1705 	l->l_lwpctl = (lwpctl_t *)lcp->lcp_kaddr + offset;
   1706 	*uaddr = lcp->lcp_uaddr + offset * sizeof(lwpctl_t);
   1707 	mutex_exit(&lp->lp_lock);
   1708 
   1709 	KPREEMPT_DISABLE(l);
   1710 	l->l_lwpctl->lc_curcpu = (int)curcpu()->ci_data.cpu_index;
   1711 	KPREEMPT_ENABLE(l);
   1712 
   1713 	return 0;
   1714 }
   1715 
   1716 /*
   1717  * Free an lwpctl structure back to the per-process list.
   1718  */
   1719 void
   1720 lwp_ctl_free(lwp_t *l)
   1721 {
   1722 	struct proc *p = l->l_proc;
   1723 	lcproc_t *lp;
   1724 	lcpage_t *lcp;
   1725 	u_int map, offset;
   1726 
   1727 	/* don't free a lwp context we borrowed for vfork */
   1728 	if (p->p_lflag & PL_PPWAIT) {
   1729 		l->l_lwpctl = NULL;
   1730 		return;
   1731 	}
   1732 
   1733 	lp = p->p_lwpctl;
   1734 	KASSERT(lp != NULL);
   1735 
   1736 	lcp = l->l_lcpage;
   1737 	offset = (u_int)((lwpctl_t *)l->l_lwpctl - (lwpctl_t *)lcp->lcp_kaddr);
   1738 	KASSERT(offset < LWPCTL_PER_PAGE);
   1739 
   1740 	mutex_enter(&lp->lp_lock);
   1741 	lcp->lcp_nfree++;
   1742 	map = offset >> 5;
   1743 	lcp->lcp_bitmap[map] |= (1 << (offset & 31));
   1744 	if (lcp->lcp_bitmap[lcp->lcp_rotor] == 0)
   1745 		lcp->lcp_rotor = map;
   1746 	if (TAILQ_FIRST(&lp->lp_pages)->lcp_nfree == 0) {
   1747 		TAILQ_REMOVE(&lp->lp_pages, lcp, lcp_chain);
   1748 		TAILQ_INSERT_HEAD(&lp->lp_pages, lcp, lcp_chain);
   1749 	}
   1750 	mutex_exit(&lp->lp_lock);
   1751 }
   1752 
   1753 /*
   1754  * Process is exiting; tear down lwpctl state.  This can only be safely
   1755  * called by the last LWP in the process.
   1756  */
   1757 void
   1758 lwp_ctl_exit(void)
   1759 {
   1760 	lcpage_t *lcp, *next;
   1761 	lcproc_t *lp;
   1762 	proc_t *p;
   1763 	lwp_t *l;
   1764 
   1765 	l = curlwp;
   1766 	l->l_lwpctl = NULL;
   1767 	l->l_lcpage = NULL;
   1768 	p = l->l_proc;
   1769 	lp = p->p_lwpctl;
   1770 
   1771 	KASSERT(lp != NULL);
   1772 	KASSERT(p->p_nlwps == 1);
   1773 
   1774 	for (lcp = TAILQ_FIRST(&lp->lp_pages); lcp != NULL; lcp = next) {
   1775 		next = TAILQ_NEXT(lcp, lcp_chain);
   1776 		uvm_unmap(kernel_map, lcp->lcp_kaddr,
   1777 		    lcp->lcp_kaddr + PAGE_SIZE);
   1778 		kmem_free(lcp, LWPCTL_LCPAGE_SZ);
   1779 	}
   1780 
   1781 	if (lp->lp_uao != NULL) {
   1782 		uvm_unmap(&p->p_vmspace->vm_map, lp->lp_uva,
   1783 		    lp->lp_uva + LWPCTL_UAREA_SZ);
   1784 	}
   1785 
   1786 	mutex_destroy(&lp->lp_lock);
   1787 	kmem_free(lp, sizeof(*lp));
   1788 	p->p_lwpctl = NULL;
   1789 }
   1790 
   1791 /*
   1792  * Return the current LWP's "preemption counter".  Used to detect
   1793  * preemption across operations that can tolerate preemption without
   1794  * crashing, but which may generate incorrect results if preempted.
   1795  */
   1796 uint64_t
   1797 lwp_pctr(void)
   1798 {
   1799 
   1800 	return curlwp->l_ncsw;
   1801 }
   1802 
   1803 /*
   1804  * Set an LWP's private data pointer.
   1805  */
   1806 int
   1807 lwp_setprivate(struct lwp *l, void *ptr)
   1808 {
   1809 	int error = 0;
   1810 
   1811 	l->l_private = ptr;
   1812 #ifdef __HAVE_CPU_LWP_SETPRIVATE
   1813 	error = cpu_lwp_setprivate(l, ptr);
   1814 #endif
   1815 	return error;
   1816 }
   1817 
   1818 #if defined(DDB)
   1819 #include <machine/pcb.h>
   1820 
   1821 void
   1822 lwp_whatis(uintptr_t addr, void (*pr)(const char *, ...))
   1823 {
   1824 	lwp_t *l;
   1825 
   1826 	LIST_FOREACH(l, &alllwp, l_list) {
   1827 		uintptr_t stack = (uintptr_t)KSTACK_LOWEST_ADDR(l);
   1828 
   1829 		if (addr < stack || stack + KSTACK_SIZE <= addr) {
   1830 			continue;
   1831 		}
   1832 		(*pr)("%p is %p+%zu, LWP %p's stack\n",
   1833 		    (void *)addr, (void *)stack,
   1834 		    (size_t)(addr - stack), l);
   1835 	}
   1836 }
   1837 #endif /* defined(DDB) */
   1838