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