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