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