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