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