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