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