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