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