Home | History | Annotate | Line # | Download | only in kern
kern_lwp.c revision 1.61.2.25
      1 /*	$NetBSD: kern_lwp.c,v 1.61.2.25 2007/11/01 21:58:18 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2001, 2006, 2007 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  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *        This product includes software developed by the NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*
     40  * Overview
     41  *
     42  *	Lightweight processes (LWPs) are the basic unit or thread of
     43  *	execution within the kernel.  The core state of an LWP is described
     44  *	by "struct lwp", also known as lwp_t.
     45  *
     46  *	Each LWP is contained within a process (described by "struct proc"),
     47  *	Every process contains at least one LWP, but may contain more.  The
     48  *	process describes attributes shared among all of its LWPs such as a
     49  *	private address space, global execution state (stopped, active,
     50  *	zombie, ...), signal disposition and so on.  On a multiprocessor
     51  *	machine, multiple LWPs be executing concurrently in the kernel.
     52  *
     53  * Execution states
     54  *
     55  *	At any given time, an LWP has overall state that is described by
     56  *	lwp::l_stat.  The states are broken into two sets below.  The first
     57  *	set is guaranteed to represent the absolute, current state of the
     58  *	LWP:
     59  *
     60  * 	LSONPROC
     61  *
     62  * 		On processor: the LWP is executing on a CPU, either in the
     63  * 		kernel or in user space.
     64  *
     65  * 	LSRUN
     66  *
     67  * 		Runnable: the LWP is parked on a run queue, and may soon be
     68  * 		chosen to run by a idle processor, or by a processor that
     69  * 		has been asked to preempt a currently runnning but lower
     70  * 		priority LWP.  If the LWP is not swapped in (L_INMEM == 0)
     71  *		then the LWP is not on a run queue, but may be soon.
     72  *
     73  * 	LSIDL
     74  *
     75  * 		Idle: the LWP has been created but has not yet executed,
     76  *		or it has ceased executing a unit of work and is waiting
     77  *		to be started again.
     78  *
     79  * 	LSSUSPENDED:
     80  *
     81  * 		Suspended: the LWP has had its execution suspended by
     82  *		another LWP in the same process using the _lwp_suspend()
     83  *		system call.  User-level LWPs also enter the suspended
     84  *		state when the system is shutting down.
     85  *
     86  *	The second set represent a "statement of intent" on behalf of the
     87  *	LWP.  The LWP may in fact be executing on a processor, may be
     88  *	sleeping or idle. It is expected to take the necessary action to
     89  *	stop executing or become "running" again within	a short timeframe.
     90  *	The LW_RUNNING flag in lwp::l_flag indicates that an LWP is running.
     91  *	Importantly, in indicates that its state is tied to a CPU.
     92  *
     93  * 	LSZOMB:
     94  *
     95  * 		Dead or dying: the LWP has released most of its resources
     96  *		and is a) about to switch away into oblivion b) has already
     97  *		switched away.  When it switches away, its few remaining
     98  *		resources can be collected.
     99  *
    100  * 	LSSLEEP:
    101  *
    102  * 		Sleeping: the LWP has entered itself onto a sleep queue, and
    103  * 		has switched away or will switch away shortly to allow other
    104  *		LWPs to run on the CPU.
    105  *
    106  * 	LSSTOP:
    107  *
    108  * 		Stopped: the LWP has been stopped as a result of a job
    109  * 		control signal, or as a result of the ptrace() interface.
    110  *
    111  * 		Stopped LWPs may run briefly within the kernel to handle
    112  * 		signals that they receive, but will not return to user space
    113  * 		until their process' state is changed away from stopped.
    114  *
    115  * 		Single LWPs within a process can not be set stopped
    116  * 		selectively: all actions that can stop or continue LWPs
    117  * 		occur at the process level.
    118  *
    119  * State transitions
    120  *
    121  *	Note that the LSSTOP state may only be set when returning to
    122  *	user space in userret(), or when sleeping interruptably.  The
    123  *	LSSUSPENDED state may only be set in userret().  Before setting
    124  *	those states, we try to ensure that the LWPs will release all
    125  *	locks that they hold, and at a minimum try to ensure that the
    126  *	LWP can be set runnable again by a signal.
    127  *
    128  *	LWPs may transition states in the following ways:
    129  *
    130  *	 RUN -------> ONPROC		ONPROC -----> RUN
    131  *	            > STOPPED			    > SLEEP
    132  *	            > SUSPENDED			    > STOPPED
    133  *						    > SUSPENDED
    134  *						    > ZOMB
    135  *
    136  *	 STOPPED ---> RUN		SUSPENDED --> RUN
    137  *	            > SLEEP			    > SLEEP
    138  *
    139  *	 SLEEP -----> ONPROC		IDL --------> RUN
    140  *		    > RUN		            > SUSPENDED
    141  *		    > STOPPED                       > STOPPED
    142  *		    > SUSPENDED
    143  *
    144  *	Other state transitions are possible with kernel threads (eg
    145  *	ONPROC -> IDL), but only happen under tightly controlled
    146  *	circumstances the side effects are understood.
    147  *
    148  * Locking
    149  *
    150  *	The majority of fields in 'struct lwp' are covered by a single,
    151  *	general spin lock pointed to by lwp::l_mutex.  The locks covering
    152  *	each field are documented in sys/lwp.h.
    153  *
    154  *	State transitions must be made with the LWP's general lock held,
    155  * 	and may cause the LWP's lock pointer to change. Manipulation of
    156  *	the general lock is not performed directly, but through calls to
    157  *	lwp_lock(), lwp_relock() and similar.
    158  *
    159  *	States and their associated locks:
    160  *
    161  *	LSONPROC, LSZOMB:
    162  *
    163  *		Always covered by spc_lwplock, which protects running LWPs.
    164  *		This is a per-CPU lock.
    165  *
    166  *	LSIDL, LSRUN:
    167  *
    168  *		Always covered by spc_mutex, which protects the run queues.
    169  *		This may be a per-CPU lock, depending on the scheduler.
    170  *
    171  *	LSSLEEP:
    172  *
    173  *		Covered by a lock associated with the sleep queue that the
    174  *		LWP resides on, indirectly referenced by l_sleepq->sq_mutex.
    175  *
    176  *	LSSTOP, LSSUSPENDED:
    177  *
    178  *		If the LWP was previously sleeping (l_wchan != NULL), then
    179  *		l_mutex references the sleep queue lock.  If the LWP was
    180  *		runnable or on the CPU when halted, or has been removed from
    181  *		the sleep queue since halted, then the lock is spc_lwplock.
    182  *
    183  *	The lock order is as follows:
    184  *
    185  *		spc::spc_lwplock ->
    186  *		    sleepq_t::sq_mutex ->
    187  *			tschain_t::tc_mutex ->
    188  *			    spc::spc_mutex
    189  *
    190  *	Each process has an scheduler state lock (proc::p_smutex), and a
    191  *	number of counters on LWPs and their states: p_nzlwps, p_nrlwps, and
    192  *	so on.  When an LWP is to be entered into or removed from one of the
    193  *	following states, p_mutex must be held and the process wide counters
    194  *	adjusted:
    195  *
    196  *		LSIDL, LSZOMB, LSSTOP, LSSUSPENDED
    197  *
    198  *	Note that an LWP is considered running or likely to run soon if in
    199  *	one of the following states.  This affects the value of p_nrlwps:
    200  *
    201  *		LSRUN, LSONPROC, LSSLEEP
    202  *
    203  *	p_smutex does not need to be held when transitioning among these
    204  *	three states.
    205  */
    206 
    207 #include <sys/cdefs.h>
    208 __KERNEL_RCSID(0, "$NetBSD: kern_lwp.c,v 1.61.2.25 2007/11/01 21:58:18 ad Exp $");
    209 
    210 #include "opt_multiprocessor.h"
    211 #include "opt_lockdebug.h"
    212 
    213 #define _LWP_API_PRIVATE
    214 
    215 #include <sys/param.h>
    216 #include <sys/systm.h>
    217 #include <sys/cpu.h>
    218 #include <sys/pool.h>
    219 #include <sys/proc.h>
    220 #include <sys/syscallargs.h>
    221 #include <sys/syscall_stats.h>
    222 #include <sys/kauth.h>
    223 #include <sys/sleepq.h>
    224 #include <sys/lockdebug.h>
    225 #include <sys/kmem.h>
    226 #include <sys/intr.h>
    227 
    228 #include <uvm/uvm_extern.h>
    229 
    230 struct lwplist	alllwp;
    231 
    232 POOL_INIT(lwp_pool, sizeof(struct lwp), MIN_LWP_ALIGNMENT, 0, 0, "lwppl",
    233     &pool_allocator_nointr, IPL_NONE);
    234 POOL_INIT(lwp_uc_pool, sizeof(ucontext_t), 0, 0, 0, "lwpucpl",
    235     &pool_allocator_nointr, IPL_NONE);
    236 
    237 static specificdata_domain_t lwp_specificdata_domain;
    238 
    239 #define LWP_DEBUG
    240 
    241 #ifdef LWP_DEBUG
    242 int lwp_debug = 0;
    243 #define DPRINTF(x) if (lwp_debug) printf x
    244 #else
    245 #define DPRINTF(x)
    246 #endif
    247 
    248 void
    249 lwpinit(void)
    250 {
    251 
    252 	lwp_specificdata_domain = specificdata_domain_create();
    253 	KASSERT(lwp_specificdata_domain != NULL);
    254 	lwp_sys_init();
    255 }
    256 
    257 /*
    258  * Set an suspended.
    259  *
    260  * Must be called with p_smutex held, and the LWP locked.  Will unlock the
    261  * LWP before return.
    262  */
    263 int
    264 lwp_suspend(struct lwp *curl, struct lwp *t)
    265 {
    266 	int error;
    267 
    268 	KASSERT(mutex_owned(&t->l_proc->p_smutex));
    269 	KASSERT(lwp_locked(t, NULL));
    270 
    271 	KASSERT(curl != t || curl->l_stat == LSONPROC);
    272 
    273 	/*
    274 	 * If the current LWP has been told to exit, we must not suspend anyone
    275 	 * else or deadlock could occur.  We won't return to userspace.
    276 	 */
    277 	if ((curl->l_stat & (LW_WEXIT | LW_WCORE)) != 0) {
    278 		lwp_unlock(t);
    279 		return (EDEADLK);
    280 	}
    281 
    282 	error = 0;
    283 
    284 	switch (t->l_stat) {
    285 	case LSRUN:
    286 	case LSONPROC:
    287 		t->l_flag |= LW_WSUSPEND;
    288 		lwp_need_userret(t);
    289 		lwp_unlock(t);
    290 		break;
    291 
    292 	case LSSLEEP:
    293 		t->l_flag |= LW_WSUSPEND;
    294 
    295 		/*
    296 		 * Kick the LWP and try to get it to the kernel boundary
    297 		 * so that it will release any locks that it holds.
    298 		 * setrunnable() will release the lock.
    299 		 */
    300 		if ((t->l_flag & LW_SINTR) != 0)
    301 			setrunnable(t);
    302 		else
    303 			lwp_unlock(t);
    304 		break;
    305 
    306 	case LSSUSPENDED:
    307 		lwp_unlock(t);
    308 		break;
    309 
    310 	case LSSTOP:
    311 		t->l_flag |= LW_WSUSPEND;
    312 		setrunnable(t);
    313 		break;
    314 
    315 	case LSIDL:
    316 	case LSZOMB:
    317 		error = EINTR; /* It's what Solaris does..... */
    318 		lwp_unlock(t);
    319 		break;
    320 	}
    321 
    322 	return (error);
    323 }
    324 
    325 /*
    326  * Restart a suspended LWP.
    327  *
    328  * Must be called with p_smutex held, and the LWP locked.  Will unlock the
    329  * LWP before return.
    330  */
    331 void
    332 lwp_continue(struct lwp *l)
    333 {
    334 
    335 	KASSERT(mutex_owned(&l->l_proc->p_smutex));
    336 	KASSERT(lwp_locked(l, NULL));
    337 
    338 	DPRINTF(("lwp_continue of %d.%d (%s), state %d, wchan %p\n",
    339 	    l->l_proc->p_pid, l->l_lid, l->l_proc->p_comm, l->l_stat,
    340 	    l->l_wchan));
    341 
    342 	/* If rebooting or not suspended, then just bail out. */
    343 	if ((l->l_flag & LW_WREBOOT) != 0) {
    344 		lwp_unlock(l);
    345 		return;
    346 	}
    347 
    348 	l->l_flag &= ~LW_WSUSPEND;
    349 
    350 	if (l->l_stat != LSSUSPENDED) {
    351 		lwp_unlock(l);
    352 		return;
    353 	}
    354 
    355 	/* setrunnable() will release the lock. */
    356 	setrunnable(l);
    357 }
    358 
    359 /*
    360  * Wait for an LWP within the current process to exit.  If 'lid' is
    361  * non-zero, we are waiting for a specific LWP.
    362  *
    363  * Must be called with p->p_smutex held.
    364  */
    365 int
    366 lwp_wait1(struct lwp *l, lwpid_t lid, lwpid_t *departed, int flags)
    367 {
    368 	struct proc *p = l->l_proc;
    369 	struct lwp *l2;
    370 	int nfound, error;
    371 	lwpid_t curlid;
    372 	bool exiting;
    373 	fixpt_t estcpu;
    374 
    375 	DPRINTF(("lwp_wait1: %d.%d waiting for %d.\n",
    376 	    p->p_pid, l->l_lid, lid));
    377 
    378 	KASSERT(mutex_owned(&p->p_smutex));
    379 
    380 	p->p_nlwpwait++;
    381 	l->l_waitingfor = lid;
    382 	curlid = l->l_lid;
    383 	exiting = ((flags & LWPWAIT_EXITCONTROL) != 0);
    384 
    385 	for (;;) {
    386 		/*
    387 		 * Avoid a race between exit1() and sigexit(): if the
    388 		 * process is dumping core, then we need to bail out: call
    389 		 * into lwp_userret() where we will be suspended until the
    390 		 * deed is done.
    391 		 */
    392 		if ((p->p_sflag & PS_WCORE) != 0) {
    393 			mutex_exit(&p->p_smutex);
    394 			lwp_userret(l);
    395 #ifdef DIAGNOSTIC
    396 			panic("lwp_wait1");
    397 #endif
    398 			/* NOTREACHED */
    399 		}
    400 
    401 		/*
    402 		 * First off, drain any detached LWP that is waiting to be
    403 		 * reaped.
    404 		 */
    405 		while ((l2 = p->p_zomblwp) != NULL) {
    406 			p->p_zomblwp = NULL;
    407 			lwp_free(l2, false, false);/* releases proc mutex */
    408 			mutex_enter(&p->p_smutex);
    409 		}
    410 
    411 		/*
    412 		 * Now look for an LWP to collect.  If the whole process is
    413 		 * exiting, count detached LWPs as eligible to be collected,
    414 		 * but don't drain them here.
    415 		 */
    416 		nfound = 0;
    417 		error = 0;
    418 		LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
    419 			/*
    420 			 * If a specific wait and the target is waiting on
    421 			 * us, then avoid deadlock.  This also traps LWPs
    422 			 * that try to wait on themselves.
    423 			 *
    424 			 * Note that this does not handle more complicated
    425 			 * cycles, like: t1 -> t2 -> t3 -> t1.  The process
    426 			 * can still be killed so it is not a major problem.
    427 			 */
    428 			if (l2->l_lid == lid && l2->l_waitingfor == curlid) {
    429 				error = EDEADLK;
    430 				break;
    431 			}
    432 			if (l2 == l)
    433 				continue;
    434 			if ((l2->l_prflag & LPR_DETACHED) != 0) {
    435 				nfound += exiting;
    436 				continue;
    437 			}
    438 			if (lid != 0) {
    439 				if (l2->l_lid != lid)
    440 					continue;
    441 				/*
    442 				 * Mark this LWP as the first waiter, if there
    443 				 * is no other.
    444 				 */
    445 				if (l2->l_waiter == 0)
    446 					l2->l_waiter = curlid;
    447 			} else if (l2->l_waiter != 0) {
    448 				/*
    449 				 * It already has a waiter - so don't
    450 				 * collect it.  If the waiter doesn't
    451 				 * grab it we'll get another chance
    452 				 * later.
    453 				 */
    454 				nfound++;
    455 				continue;
    456 			}
    457 			nfound++;
    458 
    459 			/* No need to lock the LWP in order to see LSZOMB. */
    460 			if (l2->l_stat != LSZOMB)
    461 				continue;
    462 
    463 			/*
    464 			 * We're no longer waiting.  Reset the "first waiter"
    465 			 * pointer on the target, in case it was us.
    466 			 */
    467 			l->l_waitingfor = 0;
    468 			l2->l_waiter = 0;
    469 			p->p_nlwpwait--;
    470 			if (departed)
    471 				*departed = l2->l_lid;
    472 			estcpu = l2->l_estcpu;
    473 
    474 			/* lwp_free() releases the proc lock. */
    475 			lwp_free(l2, false, false);
    476 			mutex_enter(&p->p_smutex);
    477 
    478 			/* Absorb estcpu value of collected LWP. */
    479 			lwp_lock(l);
    480 			l->l_estcpu += estcpu;
    481 			lwp_unlock(l);
    482 			return 0;
    483 		}
    484 
    485 		if (error != 0)
    486 			break;
    487 		if (nfound == 0) {
    488 			error = ESRCH;
    489 			break;
    490 		}
    491 
    492 		/*
    493 		 * The kernel is careful to ensure that it can not deadlock
    494 		 * when exiting - just keep waiting.
    495 		 */
    496 		if (exiting) {
    497 			KASSERT(p->p_nlwps > 1);
    498 			cv_wait(&p->p_lwpcv, &p->p_smutex);
    499 			continue;
    500 		}
    501 
    502 		/*
    503 		 * If all other LWPs are waiting for exits or suspends
    504 		 * and the supply of zombies and potential zombies is
    505 		 * exhausted, then we are about to deadlock.
    506 		 *
    507 		 * If the process is exiting (and this LWP is not the one
    508 		 * that is coordinating the exit) then bail out now.
    509 		 */
    510 		if ((p->p_sflag & PS_WEXIT) != 0 ||
    511 		    p->p_nrlwps + p->p_nzlwps - p->p_ndlwps <= p->p_nlwpwait) {
    512 			error = EDEADLK;
    513 			break;
    514 		}
    515 
    516 		/*
    517 		 * Sit around and wait for something to happen.  We'll be
    518 		 * awoken if any of the conditions examined change: if an
    519 		 * LWP exits, is collected, or is detached.
    520 		 */
    521 		if ((error = cv_wait_sig(&p->p_lwpcv, &p->p_smutex)) != 0)
    522 			break;
    523 	}
    524 
    525 	/*
    526 	 * We didn't find any LWPs to collect, we may have received a
    527 	 * signal, or some other condition has caused us to bail out.
    528 	 *
    529 	 * If waiting on a specific LWP, clear the waiters marker: some
    530 	 * other LWP may want it.  Then, kick all the remaining waiters
    531 	 * so that they can re-check for zombies and for deadlock.
    532 	 */
    533 	if (lid != 0) {
    534 		LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
    535 			if (l2->l_lid == lid) {
    536 				if (l2->l_waiter == curlid)
    537 					l2->l_waiter = 0;
    538 				break;
    539 			}
    540 		}
    541 	}
    542 	p->p_nlwpwait--;
    543 	l->l_waitingfor = 0;
    544 	cv_broadcast(&p->p_lwpcv);
    545 
    546 	return error;
    547 }
    548 
    549 /*
    550  * Create a new LWP within process 'p2', using LWP 'l1' as a template.
    551  * The new LWP is created in state LSIDL and must be set running,
    552  * suspended, or stopped by the caller.
    553  */
    554 int
    555 lwp_create(lwp_t *l1, proc_t *p2, vaddr_t uaddr, bool inmem, int flags,
    556 	   void *stack, size_t stacksize, void (*func)(void *), void *arg,
    557 	   lwp_t **rnewlwpp, int sclass)
    558 {
    559 	struct lwp *l2, *isfree;
    560 	turnstile_t *ts;
    561 
    562 	/*
    563 	 * First off, reap any detached LWP waiting to be collected.
    564 	 * We can re-use its LWP structure and turnstile.
    565 	 */
    566 	isfree = NULL;
    567 	if (p2->p_zomblwp != NULL) {
    568 		mutex_enter(&p2->p_smutex);
    569 		if ((isfree = p2->p_zomblwp) != NULL) {
    570 			p2->p_zomblwp = NULL;
    571 			lwp_free(isfree, true, false);/* releases proc mutex */
    572 		} else
    573 			mutex_exit(&p2->p_smutex);
    574 	}
    575 	if (isfree == NULL) {
    576 		l2 = pool_get(&lwp_pool, PR_WAITOK);
    577 		memset(l2, 0, sizeof(*l2));
    578 		l2->l_ts = pool_cache_get(turnstile_cache, PR_WAITOK);
    579 		SLIST_INIT(&l2->l_pi_lenders);
    580 	} else {
    581 		l2 = isfree;
    582 		ts = l2->l_ts;
    583 		KASSERT(l2->l_inheritedprio == -1);
    584 		KASSERT(SLIST_EMPTY(&l2->l_pi_lenders));
    585 		memset(l2, 0, sizeof(*l2));
    586 		l2->l_ts = ts;
    587 	}
    588 
    589 	l2->l_stat = LSIDL;
    590 	l2->l_proc = p2;
    591 	l2->l_refcnt = 1;
    592 	l2->l_class = sclass;
    593 	l2->l_kpriority = l1->l_kpriority;
    594 	l2->l_priority = l1->l_priority;
    595 	l2->l_inheritedprio = -1;
    596 	l2->l_estcpu = l1->l_estcpu;
    597 	l2->l_mutex = l1->l_cpu->ci_schedstate.spc_mutex;
    598 	l2->l_cpu = l1->l_cpu;
    599 	l2->l_flag = inmem ? LW_INMEM : 0;
    600 	l2->l_pflag = LP_MPSAFE;
    601 
    602 	if (p2->p_flag & PK_SYSTEM) {
    603 		/*
    604 		 * Mark it as a system process and not a candidate for
    605 		 * swapping.
    606 		 */
    607 		l2->l_flag |= LW_SYSTEM;
    608 	} else {
    609 		/* Look for a CPU to start */
    610 		l2->l_cpu = sched_takecpu(l2);
    611 		l2->l_mutex = l2->l_cpu->ci_schedstate.spc_mutex;
    612 	}
    613 
    614 	lwp_initspecific(l2);
    615 	sched_lwp_fork(l2);
    616 	lwp_update_creds(l2);
    617 	callout_init(&l2->l_timeout_ch, CALLOUT_MPSAFE);
    618 	callout_setfunc(&l2->l_timeout_ch, sleepq_timeout, l2);
    619 	mutex_init(&l2->l_swaplock, MUTEX_DEFAULT, IPL_NONE);
    620 	cv_init(&l2->l_sigcv, "sigwait");
    621 	l2->l_syncobj = &sched_syncobj;
    622 
    623 	if (rnewlwpp != NULL)
    624 		*rnewlwpp = l2;
    625 
    626 	l2->l_addr = UAREA_TO_USER(uaddr);
    627 	KERNEL_LOCK(1, curlwp);
    628 	uvm_lwp_fork(l1, l2, stack, stacksize, func,
    629 	    (arg != NULL) ? arg : l2);
    630 	KERNEL_UNLOCK_ONE(curlwp);
    631 
    632 	mutex_enter(&p2->p_smutex);
    633 
    634 	if ((flags & LWP_DETACHED) != 0) {
    635 		l2->l_prflag = LPR_DETACHED;
    636 		p2->p_ndlwps++;
    637 	} else
    638 		l2->l_prflag = 0;
    639 
    640 	l2->l_sigmask = l1->l_sigmask;
    641 	CIRCLEQ_INIT(&l2->l_sigpend.sp_info);
    642 	sigemptyset(&l2->l_sigpend.sp_set);
    643 
    644 	p2->p_nlwpid++;
    645 	if (p2->p_nlwpid == 0)
    646 		p2->p_nlwpid++;
    647 	l2->l_lid = p2->p_nlwpid;
    648 	LIST_INSERT_HEAD(&p2->p_lwps, l2, l_sibling);
    649 	p2->p_nlwps++;
    650 
    651 	mutex_exit(&p2->p_smutex);
    652 
    653 	mutex_enter(&proclist_lock);
    654 	mutex_enter(&proclist_mutex);
    655 	LIST_INSERT_HEAD(&alllwp, l2, l_list);
    656 	mutex_exit(&proclist_mutex);
    657 	mutex_exit(&proclist_lock);
    658 
    659 	SYSCALL_TIME_LWP_INIT(l2);
    660 
    661 	if (p2->p_emul->e_lwp_fork)
    662 		(*p2->p_emul->e_lwp_fork)(l1, l2);
    663 
    664 	return (0);
    665 }
    666 
    667 /*
    668  * Called by MD code when a new LWP begins execution.  Must be called
    669  * with the previous LWP locked (so at splsched), or if there is no
    670  * previous LWP, at splsched.
    671  */
    672 void
    673 lwp_startup(struct lwp *prev, struct lwp *new)
    674 {
    675 
    676 	if (prev != NULL) {
    677 		lwp_unlock(prev);
    678 	}
    679 	spl0();
    680 	pmap_activate(new);
    681 	LOCKDEBUG_BARRIER(NULL, 0);
    682 	if ((new->l_pflag & LP_MPSAFE) == 0) {
    683 		KERNEL_LOCK(1, new);
    684 	}
    685 }
    686 
    687 /*
    688  * Exit an LWP.
    689  */
    690 void
    691 lwp_exit(struct lwp *l)
    692 {
    693 	struct proc *p = l->l_proc;
    694 	struct lwp *l2;
    695 	bool current;
    696 
    697 	current = (l == curlwp);
    698 
    699 	DPRINTF(("lwp_exit: %d.%d exiting.\n", p->p_pid, l->l_lid));
    700 	DPRINTF((" nlwps: %d nzlwps: %d\n", p->p_nlwps, p->p_nzlwps));
    701 	KASSERT(current || l->l_stat == LSIDL);
    702 
    703 	/*
    704 	 * Verify that we hold no locks other than the kernel lock.
    705 	 */
    706 #ifdef MULTIPROCESSOR
    707 	LOCKDEBUG_BARRIER(&kernel_lock, 0);
    708 #else
    709 	LOCKDEBUG_BARRIER(NULL, 0);
    710 #endif
    711 
    712 	/*
    713 	 * If we are the last live LWP in a process, we need to exit the
    714 	 * entire process.  We do so with an exit status of zero, because
    715 	 * it's a "controlled" exit, and because that's what Solaris does.
    716 	 *
    717 	 * We are not quite a zombie yet, but for accounting purposes we
    718 	 * must increment the count of zombies here.
    719 	 *
    720 	 * Note: the last LWP's specificdata will be deleted here.
    721 	 */
    722 	mutex_enter(&p->p_smutex);
    723 	if (p->p_nlwps - p->p_nzlwps == 1) {
    724 		KASSERT(current == true);
    725 		DPRINTF(("lwp_exit: %d.%d calling exit1()\n",
    726 		    p->p_pid, l->l_lid));
    727 		exit1(l, 0);
    728 		/* NOTREACHED */
    729 	}
    730 	p->p_nzlwps++;
    731 	mutex_exit(&p->p_smutex);
    732 
    733 	if (p->p_emul->e_lwp_exit)
    734 		(*p->p_emul->e_lwp_exit)(l);
    735 
    736 	/* Delete the specificdata while it's still safe to sleep. */
    737 	specificdata_fini(lwp_specificdata_domain, &l->l_specdataref);
    738 
    739 	/*
    740 	 * Release our cached credentials.
    741 	 */
    742 	kauth_cred_free(l->l_cred);
    743 	callout_destroy(&l->l_timeout_ch);
    744 
    745 	/*
    746 	 * While we can still block, mark the LWP as unswappable to
    747 	 * prevent conflicts with the with the swapper.
    748 	 */
    749 	if (current)
    750 		uvm_lwp_hold(l);
    751 
    752 	/*
    753 	 * Remove the LWP from the global list.
    754 	 */
    755 	mutex_enter(&proclist_lock);
    756 	mutex_enter(&proclist_mutex);
    757 	LIST_REMOVE(l, l_list);
    758 	mutex_exit(&proclist_mutex);
    759 	mutex_exit(&proclist_lock);
    760 
    761 	/*
    762 	 * Get rid of all references to the LWP that others (e.g. procfs)
    763 	 * may have, and mark the LWP as a zombie.  If the LWP is detached,
    764 	 * mark it waiting for collection in the proc structure.  Note that
    765 	 * before we can do that, we need to free any other dead, deatched
    766 	 * LWP waiting to meet its maker.
    767 	 *
    768 	 * XXXSMP disable preemption.
    769 	 */
    770 	mutex_enter(&p->p_smutex);
    771 	lwp_drainrefs(l);
    772 
    773 	if ((l->l_prflag & LPR_DETACHED) != 0) {
    774 		while ((l2 = p->p_zomblwp) != NULL) {
    775 			p->p_zomblwp = NULL;
    776 			lwp_free(l2, false, false);/* releases proc mutex */
    777 			mutex_enter(&p->p_smutex);
    778 			l->l_refcnt++;
    779 			lwp_drainrefs(l);
    780 		}
    781 		p->p_zomblwp = l;
    782 	}
    783 
    784 	/*
    785 	 * If we find a pending signal for the process and we have been
    786 	 * asked to check for signals, then we loose: arrange to have
    787 	 * all other LWPs in the process check for signals.
    788 	 */
    789 	if ((l->l_flag & LW_PENDSIG) != 0 &&
    790 	    firstsig(&p->p_sigpend.sp_set) != 0) {
    791 		LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
    792 			lwp_lock(l2);
    793 			l2->l_flag |= LW_PENDSIG;
    794 			lwp_unlock(l2);
    795 		}
    796 	}
    797 
    798 	lwp_lock(l);
    799 	l->l_stat = LSZOMB;
    800 	lwp_unlock(l);
    801 	p->p_nrlwps--;
    802 	cv_broadcast(&p->p_lwpcv);
    803 	mutex_exit(&p->p_smutex);
    804 
    805 	/*
    806 	 * We can no longer block.  At this point, lwp_free() may already
    807 	 * be gunning for us.  On a multi-CPU system, we may be off p_lwps.
    808 	 *
    809 	 * Free MD LWP resources.
    810 	 */
    811 #ifndef __NO_CPU_LWP_FREE
    812 	cpu_lwp_free(l, 0);
    813 #endif
    814 
    815 	if (current) {
    816 		pmap_deactivate(l);
    817 
    818 		/*
    819 		 * Release the kernel lock, and switch away into
    820 		 * oblivion.
    821 		 */
    822 #ifdef notyet
    823 		/* XXXSMP hold in lwp_userret() */
    824 		KERNEL_UNLOCK_LAST(l);
    825 #else
    826 		KERNEL_UNLOCK_ALL(l, NULL);
    827 #endif
    828 		lwp_exit_switchaway(l);
    829 	}
    830 }
    831 
    832 void
    833 lwp_exit_switchaway(struct lwp *l)
    834 {
    835 	struct cpu_info *ci;
    836 	struct lwp *idlelwp;
    837 
    838 	/* Unlocked, but is for statistics only. */
    839 	uvmexp.swtch++;
    840 
    841 	(void)splsched();
    842 	l->l_flag &= ~LW_RUNNING;
    843 	ci = curcpu();
    844 	idlelwp = ci->ci_data.cpu_idlelwp;
    845 	idlelwp->l_stat = LSONPROC;
    846 
    847 	/*
    848 	 * cpu_onproc must be updated with the CPU locked, as
    849 	 * aston() may try to set a AST pending on the LWP (and
    850 	 * it does so with the CPU locked).  Otherwise, the LWP
    851 	 * may be destroyed before the AST can be set, leading
    852 	 * to a user-after-free.
    853 	 */
    854 	spc_lock(ci);
    855 	ci->ci_data.cpu_onproc = idlelwp;
    856 	spc_unlock(ci);
    857 	cpu_switchto(NULL, idlelwp, false);
    858 }
    859 
    860 /*
    861  * Free a dead LWP's remaining resources.
    862  *
    863  * XXXLWP limits.
    864  */
    865 void
    866 lwp_free(struct lwp *l, bool recycle, bool last)
    867 {
    868 	struct proc *p = l->l_proc;
    869 	ksiginfoq_t kq;
    870 
    871 	/*
    872 	 * If this was not the last LWP in the process, then adjust
    873 	 * counters and unlock.
    874 	 */
    875 	if (!last) {
    876 		/*
    877 		 * Add the LWP's run time to the process' base value.
    878 		 * This needs to co-incide with coming off p_lwps.
    879 		 */
    880 		timeradd(&l->l_rtime, &p->p_rtime, &p->p_rtime);
    881 		p->p_pctcpu += l->l_pctcpu;
    882 		LIST_REMOVE(l, l_sibling);
    883 		p->p_nlwps--;
    884 		p->p_nzlwps--;
    885 		if ((l->l_prflag & LPR_DETACHED) != 0)
    886 			p->p_ndlwps--;
    887 
    888 		/*
    889 		 * Have any LWPs sleeping in lwp_wait() recheck for
    890 		 * deadlock.
    891 		 */
    892 		cv_broadcast(&p->p_lwpcv);
    893 		mutex_exit(&p->p_smutex);
    894 	}
    895 
    896 #ifdef MULTIPROCESSOR
    897 	/*
    898 	 * In the unlikely event that the LWP is still on the CPU,
    899 	 * then spin until it has switched away.  We need to release
    900 	 * all locks to avoid deadlock against interrupt handlers on
    901 	 * the target CPU.
    902 	 */
    903 	if ((l->l_flag & LW_RUNNING) != 0 || l->l_cpu->ci_curlwp == l) {
    904 		int count;
    905 		(void)count; /* XXXgcc */
    906 		KERNEL_UNLOCK_ALL(curlwp, &count);
    907 		while ((l->l_flag & LW_RUNNING) != 0 ||
    908 		    l->l_cpu->ci_curlwp == l)
    909 			SPINLOCK_BACKOFF_HOOK;
    910 		KERNEL_LOCK(count, curlwp);
    911 	}
    912 #endif
    913 
    914 	/*
    915 	 * Destroy the LWP's remaining signal information.
    916 	 */
    917 	ksiginfo_queue_init(&kq);
    918 	sigclear(&l->l_sigpend, NULL, &kq);
    919 	ksiginfo_queue_drain(&kq);
    920 	cv_destroy(&l->l_sigcv);
    921 	mutex_destroy(&l->l_swaplock);
    922 
    923 	/*
    924 	 * Free the LWP's turnstile and the LWP structure itself unless the
    925 	 * caller wants to recycle them.  Also, free the scheduler specific data.
    926 	 *
    927 	 * We can't return turnstile0 to the pool (it didn't come from it),
    928 	 * so if it comes up just drop it quietly and move on.
    929 	 *
    930 	 * We don't recycle the VM resources at this time.
    931 	 */
    932 	if (!recycle && l->l_ts != &turnstile0)
    933 		pool_cache_put(turnstile_cache, l->l_ts);
    934 #ifndef __NO_CPU_LWP_FREE
    935 	cpu_lwp_free2(l);
    936 #endif
    937 	uvm_lwp_exit(l);
    938 	KASSERT(SLIST_EMPTY(&l->l_pi_lenders));
    939 	KASSERT(l->l_inheritedprio == -1);
    940 	sched_lwp_exit(l);
    941 	if (!recycle)
    942 		pool_put(&lwp_pool, l);
    943 }
    944 
    945 /*
    946  * Pick a LWP to represent the process for those operations which
    947  * want information about a "process" that is actually associated
    948  * with a LWP.
    949  *
    950  * If 'locking' is false, no locking or lock checks are performed.
    951  * This is intended for use by DDB.
    952  *
    953  * We don't bother locking the LWP here, since code that uses this
    954  * interface is broken by design and an exact match is not required.
    955  */
    956 struct lwp *
    957 proc_representative_lwp(struct proc *p, int *nrlwps, int locking)
    958 {
    959 	struct lwp *l, *onproc, *running, *sleeping, *stopped, *suspended;
    960 	struct lwp *signalled;
    961 	int cnt;
    962 
    963 	if (locking) {
    964 		KASSERT(mutex_owned(&p->p_smutex));
    965 	}
    966 
    967 	/* Trivial case: only one LWP */
    968 	if (p->p_nlwps == 1) {
    969 		l = LIST_FIRST(&p->p_lwps);
    970 		if (nrlwps)
    971 			*nrlwps = (l->l_stat == LSONPROC || l->l_stat == LSRUN);
    972 		return l;
    973 	}
    974 
    975 	cnt = 0;
    976 	switch (p->p_stat) {
    977 	case SSTOP:
    978 	case SACTIVE:
    979 		/* Pick the most live LWP */
    980 		onproc = running = sleeping = stopped = suspended = NULL;
    981 		signalled = NULL;
    982 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    983 			if ((l->l_flag & LW_IDLE) != 0) {
    984 				continue;
    985 			}
    986 			if (l->l_lid == p->p_sigctx.ps_lwp)
    987 				signalled = l;
    988 			switch (l->l_stat) {
    989 			case LSONPROC:
    990 				onproc = l;
    991 				cnt++;
    992 				break;
    993 			case LSRUN:
    994 				running = l;
    995 				cnt++;
    996 				break;
    997 			case LSSLEEP:
    998 				sleeping = l;
    999 				break;
   1000 			case LSSTOP:
   1001 				stopped = l;
   1002 				break;
   1003 			case LSSUSPENDED:
   1004 				suspended = l;
   1005 				break;
   1006 			}
   1007 		}
   1008 		if (nrlwps)
   1009 			*nrlwps = cnt;
   1010 		if (signalled)
   1011 			l = signalled;
   1012 		else if (onproc)
   1013 			l = onproc;
   1014 		else if (running)
   1015 			l = running;
   1016 		else if (sleeping)
   1017 			l = sleeping;
   1018 		else if (stopped)
   1019 			l = stopped;
   1020 		else if (suspended)
   1021 			l = suspended;
   1022 		else
   1023 			break;
   1024 		return l;
   1025 #ifdef DIAGNOSTIC
   1026 	case SIDL:
   1027 	case SZOMB:
   1028 	case SDYING:
   1029 	case SDEAD:
   1030 		if (locking)
   1031 			mutex_exit(&p->p_smutex);
   1032 		/* We have more than one LWP and we're in SIDL?
   1033 		 * How'd that happen?
   1034 		 */
   1035 		panic("Too many LWPs in idle/dying process %d (%s) stat = %d",
   1036 		    p->p_pid, p->p_comm, p->p_stat);
   1037 		break;
   1038 	default:
   1039 		if (locking)
   1040 			mutex_exit(&p->p_smutex);
   1041 		panic("Process %d (%s) in unknown state %d",
   1042 		    p->p_pid, p->p_comm, p->p_stat);
   1043 #endif
   1044 	}
   1045 
   1046 	if (locking)
   1047 		mutex_exit(&p->p_smutex);
   1048 	panic("proc_representative_lwp: couldn't find a lwp for process"
   1049 		" %d (%s)", p->p_pid, p->p_comm);
   1050 	/* NOTREACHED */
   1051 	return NULL;
   1052 }
   1053 
   1054 /*
   1055  * Look up a live LWP within the speicifed process, and return it locked.
   1056  *
   1057  * Must be called with p->p_smutex held.
   1058  */
   1059 struct lwp *
   1060 lwp_find(struct proc *p, int id)
   1061 {
   1062 	struct lwp *l;
   1063 
   1064 	KASSERT(mutex_owned(&p->p_smutex));
   1065 
   1066 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
   1067 		if (l->l_lid == id)
   1068 			break;
   1069 	}
   1070 
   1071 	/*
   1072 	 * No need to lock - all of these conditions will
   1073 	 * be visible with the process level mutex held.
   1074 	 */
   1075 	if (l != NULL && (l->l_stat == LSIDL || l->l_stat == LSZOMB))
   1076 		l = NULL;
   1077 
   1078 	return l;
   1079 }
   1080 
   1081 /*
   1082  * Update an LWP's cached credentials to mirror the process' master copy.
   1083  *
   1084  * This happens early in the syscall path, on user trap, and on LWP
   1085  * creation.  A long-running LWP can also voluntarily choose to update
   1086  * it's credentials by calling this routine.  This may be called from
   1087  * LWP_CACHE_CREDS(), which checks l->l_cred != p->p_cred beforehand.
   1088  */
   1089 void
   1090 lwp_update_creds(struct lwp *l)
   1091 {
   1092 	kauth_cred_t oc;
   1093 	struct proc *p;
   1094 
   1095 	p = l->l_proc;
   1096 	oc = l->l_cred;
   1097 
   1098 	mutex_enter(&p->p_mutex);
   1099 	kauth_cred_hold(p->p_cred);
   1100 	l->l_cred = p->p_cred;
   1101 	mutex_exit(&p->p_mutex);
   1102 	if (oc != NULL)
   1103 		kauth_cred_free(oc);
   1104 }
   1105 
   1106 /*
   1107  * Verify that an LWP is locked, and optionally verify that the lock matches
   1108  * one we specify.
   1109  */
   1110 int
   1111 lwp_locked(struct lwp *l, kmutex_t *mtx)
   1112 {
   1113 	kmutex_t *cur = l->l_mutex;
   1114 
   1115 	return mutex_owned(cur) && (mtx == cur || mtx == NULL);
   1116 }
   1117 
   1118 /*
   1119  * Lock an LWP.
   1120  */
   1121 void
   1122 lwp_lock_retry(struct lwp *l, kmutex_t *old)
   1123 {
   1124 
   1125 	/*
   1126 	 * XXXgcc ignoring kmutex_t * volatile on i386
   1127 	 *
   1128 	 * gcc version 4.1.2 20061021 prerelease (NetBSD nb1 20061021)
   1129 	 */
   1130 #if 1
   1131 	while (l->l_mutex != old) {
   1132 #else
   1133 	for (;;) {
   1134 #endif
   1135 		mutex_spin_exit(old);
   1136 		old = l->l_mutex;
   1137 		mutex_spin_enter(old);
   1138 
   1139 		/*
   1140 		 * mutex_enter() will have posted a read barrier.  Re-test
   1141 		 * l->l_mutex.  If it has changed, we need to try again.
   1142 		 */
   1143 #if 1
   1144 	}
   1145 #else
   1146 	} while (__predict_false(l->l_mutex != old));
   1147 #endif
   1148 }
   1149 
   1150 /*
   1151  * Lend a new mutex to an LWP.  The old mutex must be held.
   1152  */
   1153 void
   1154 lwp_setlock(struct lwp *l, kmutex_t *new)
   1155 {
   1156 
   1157 	KASSERT(mutex_owned(l->l_mutex));
   1158 
   1159 	mb_write();
   1160 	l->l_mutex = new;
   1161 }
   1162 
   1163 /*
   1164  * Lend a new mutex to an LWP, and release the old mutex.  The old mutex
   1165  * must be held.
   1166  */
   1167 void
   1168 lwp_unlock_to(struct lwp *l, kmutex_t *new)
   1169 {
   1170 	kmutex_t *old;
   1171 
   1172 	KASSERT(mutex_owned(l->l_mutex));
   1173 
   1174 	old = l->l_mutex;
   1175 	mb_write();
   1176 	l->l_mutex = new;
   1177 	mutex_spin_exit(old);
   1178 }
   1179 
   1180 /*
   1181  * Acquire a new mutex, and donate it to an LWP.  The LWP must already be
   1182  * locked.
   1183  */
   1184 void
   1185 lwp_relock(struct lwp *l, kmutex_t *new)
   1186 {
   1187 	kmutex_t *old;
   1188 
   1189 	KASSERT(mutex_owned(l->l_mutex));
   1190 
   1191 	old = l->l_mutex;
   1192 	if (old != new) {
   1193 		mutex_spin_enter(new);
   1194 		l->l_mutex = new;
   1195 		mutex_spin_exit(old);
   1196 	}
   1197 }
   1198 
   1199 int
   1200 lwp_trylock(struct lwp *l)
   1201 {
   1202 	kmutex_t *old;
   1203 
   1204 	for (;;) {
   1205 		if (!mutex_tryenter(old = l->l_mutex))
   1206 			return 0;
   1207 		if (__predict_true(l->l_mutex == old))
   1208 			return 1;
   1209 		mutex_spin_exit(old);
   1210 	}
   1211 }
   1212 
   1213 /*
   1214  * Handle exceptions for mi_userret().  Called if a member of LW_USERRET is
   1215  * set.
   1216  */
   1217 void
   1218 lwp_userret(struct lwp *l)
   1219 {
   1220 	struct proc *p;
   1221 	void (*hook)(void);
   1222 	int sig;
   1223 
   1224 	p = l->l_proc;
   1225 
   1226 #ifndef __HAVE_FAST_SOFTINTS
   1227 	/* Run pending soft interrupts. */
   1228 	if (l->l_cpu->ci_data.cpu_softints != 0)
   1229 		softint_overlay();
   1230 #endif
   1231 
   1232 	/*
   1233 	 * It should be safe to do this read unlocked on a multiprocessor
   1234 	 * system..
   1235 	 */
   1236 	while ((l->l_flag & LW_USERRET) != 0) {
   1237 		/*
   1238 		 * Process pending signals first, unless the process
   1239 		 * is dumping core or exiting, where we will instead
   1240 		 * enter the L_WSUSPEND case below.
   1241 		 */
   1242 		if ((l->l_flag & (LW_PENDSIG | LW_WCORE | LW_WEXIT)) ==
   1243 		    LW_PENDSIG) {
   1244 			mutex_enter(&p->p_smutex);
   1245 			while ((sig = issignal(l)) != 0)
   1246 				postsig(sig);
   1247 			mutex_exit(&p->p_smutex);
   1248 		}
   1249 
   1250 		/*
   1251 		 * Core-dump or suspend pending.
   1252 		 *
   1253 		 * In case of core dump, suspend ourselves, so that the
   1254 		 * kernel stack and therefore the userland registers saved
   1255 		 * in the trapframe are around for coredump() to write them
   1256 		 * out.  We issue a wakeup on p->p_lwpcv so that sigexit()
   1257 		 * will write the core file out once all other LWPs are
   1258 		 * suspended.
   1259 		 */
   1260 		if ((l->l_flag & LW_WSUSPEND) != 0) {
   1261 			mutex_enter(&p->p_smutex);
   1262 			p->p_nrlwps--;
   1263 			cv_broadcast(&p->p_lwpcv);
   1264 			lwp_lock(l);
   1265 			l->l_stat = LSSUSPENDED;
   1266 			mutex_exit(&p->p_smutex);
   1267 			mi_switch(l);
   1268 		}
   1269 
   1270 		/* Process is exiting. */
   1271 		if ((l->l_flag & LW_WEXIT) != 0) {
   1272 			KERNEL_LOCK(1, l);
   1273 			lwp_exit(l);
   1274 			KASSERT(0);
   1275 			/* NOTREACHED */
   1276 		}
   1277 
   1278 		/* Call userret hook; used by Linux emulation. */
   1279 		if ((l->l_flag & LW_WUSERRET) != 0) {
   1280 			lwp_lock(l);
   1281 			l->l_flag &= ~LW_WUSERRET;
   1282 			lwp_unlock(l);
   1283 			hook = p->p_userret;
   1284 			p->p_userret = NULL;
   1285 			(*hook)();
   1286 		}
   1287 	}
   1288 }
   1289 
   1290 /*
   1291  * Force an LWP to enter the kernel, to take a trip through lwp_userret().
   1292  */
   1293 void
   1294 lwp_need_userret(struct lwp *l)
   1295 {
   1296 	KASSERT(lwp_locked(l, NULL));
   1297 
   1298 	/*
   1299 	 * Since the tests in lwp_userret() are done unlocked, make sure
   1300 	 * that the condition will be seen before forcing the LWP to enter
   1301 	 * kernel mode.
   1302 	 */
   1303 	mb_write();
   1304 	cpu_signotify(l);
   1305 }
   1306 
   1307 /*
   1308  * Add one reference to an LWP.  This will prevent the LWP from
   1309  * exiting, thus keep the lwp structure and PCB around to inspect.
   1310  */
   1311 void
   1312 lwp_addref(struct lwp *l)
   1313 {
   1314 
   1315 	KASSERT(mutex_owned(&l->l_proc->p_smutex));
   1316 	KASSERT(l->l_stat != LSZOMB);
   1317 	KASSERT(l->l_refcnt != 0);
   1318 
   1319 	l->l_refcnt++;
   1320 }
   1321 
   1322 /*
   1323  * Remove one reference to an LWP.  If this is the last reference,
   1324  * then we must finalize the LWP's death.
   1325  */
   1326 void
   1327 lwp_delref(struct lwp *l)
   1328 {
   1329 	struct proc *p = l->l_proc;
   1330 
   1331 	mutex_enter(&p->p_smutex);
   1332 	KASSERT(l->l_stat != LSZOMB);
   1333 	KASSERT(l->l_refcnt > 0);
   1334 	if (--l->l_refcnt == 0)
   1335 		cv_broadcast(&p->p_lwpcv);
   1336 	mutex_exit(&p->p_smutex);
   1337 }
   1338 
   1339 /*
   1340  * Drain all references to the current LWP.
   1341  */
   1342 void
   1343 lwp_drainrefs(struct lwp *l)
   1344 {
   1345 	struct proc *p = l->l_proc;
   1346 
   1347 	KASSERT(mutex_owned(&p->p_smutex));
   1348 	KASSERT(l->l_refcnt != 0);
   1349 
   1350 	l->l_refcnt--;
   1351 	while (l->l_refcnt != 0)
   1352 		cv_wait(&p->p_lwpcv, &p->p_smutex);
   1353 }
   1354 
   1355 /*
   1356  * lwp_specific_key_create --
   1357  *	Create a key for subsystem lwp-specific data.
   1358  */
   1359 int
   1360 lwp_specific_key_create(specificdata_key_t *keyp, specificdata_dtor_t dtor)
   1361 {
   1362 
   1363 	return (specificdata_key_create(lwp_specificdata_domain, keyp, dtor));
   1364 }
   1365 
   1366 /*
   1367  * lwp_specific_key_delete --
   1368  *	Delete a key for subsystem lwp-specific data.
   1369  */
   1370 void
   1371 lwp_specific_key_delete(specificdata_key_t key)
   1372 {
   1373 
   1374 	specificdata_key_delete(lwp_specificdata_domain, key);
   1375 }
   1376 
   1377 /*
   1378  * lwp_initspecific --
   1379  *	Initialize an LWP's specificdata container.
   1380  */
   1381 void
   1382 lwp_initspecific(struct lwp *l)
   1383 {
   1384 	int error;
   1385 
   1386 	error = specificdata_init(lwp_specificdata_domain, &l->l_specdataref);
   1387 	KASSERT(error == 0);
   1388 }
   1389 
   1390 /*
   1391  * lwp_finispecific --
   1392  *	Finalize an LWP's specificdata container.
   1393  */
   1394 void
   1395 lwp_finispecific(struct lwp *l)
   1396 {
   1397 
   1398 	specificdata_fini(lwp_specificdata_domain, &l->l_specdataref);
   1399 }
   1400 
   1401 /*
   1402  * lwp_getspecific --
   1403  *	Return lwp-specific data corresponding to the specified key.
   1404  *
   1405  *	Note: LWP specific data is NOT INTERLOCKED.  An LWP should access
   1406  *	only its OWN SPECIFIC DATA.  If it is necessary to access another
   1407  *	LWP's specifc data, care must be taken to ensure that doing so
   1408  *	would not cause internal data structure inconsistency (i.e. caller
   1409  *	can guarantee that the target LWP is not inside an lwp_getspecific()
   1410  *	or lwp_setspecific() call).
   1411  */
   1412 void *
   1413 lwp_getspecific(specificdata_key_t key)
   1414 {
   1415 
   1416 	return (specificdata_getspecific_unlocked(lwp_specificdata_domain,
   1417 						  &curlwp->l_specdataref, key));
   1418 }
   1419 
   1420 void *
   1421 _lwp_getspecific_by_lwp(struct lwp *l, specificdata_key_t key)
   1422 {
   1423 
   1424 	return (specificdata_getspecific_unlocked(lwp_specificdata_domain,
   1425 						  &l->l_specdataref, key));
   1426 }
   1427 
   1428 /*
   1429  * lwp_setspecific --
   1430  *	Set lwp-specific data corresponding to the specified key.
   1431  */
   1432 void
   1433 lwp_setspecific(specificdata_key_t key, void *data)
   1434 {
   1435 
   1436 	specificdata_setspecific(lwp_specificdata_domain,
   1437 				 &curlwp->l_specdataref, key, data);
   1438 }
   1439