Home | History | Annotate | Line # | Download | only in kern
kern_lwp.c revision 1.40.2.6
      1 /*	$NetBSD: kern_lwp.c,v 1.40.2.6 2006/12/29 20:27:43 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2001, 2006 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  *	 IDL -------> SUSPENDED
    131  *		    > RUN
    132  *
    133  *	 RUN -------> ONPROC		ONPROC -----> RUN
    134  *	            > STOPPED			    > SLEEP
    135  *	            > SUSPENDED			    > STOPPED
    136  *						    > SUSPENDED
    137  *						    > ZOMB
    138  *
    139  *	 STOPPED ---> RUN		SUSPENDED --> RUN
    140  *	            > SLEEP			    > SLEEP
    141  *
    142  *	 SLEEP -----> ONPROC
    143  *		    > RUN
    144  *		    > STOPPED
    145  *		    > SUSPENDED
    146  *
    147  * Locking
    148  *
    149  *	The majority of fields in 'struct lwp' are covered by a single,
    150  *	general spin mutex pointed to by lwp::l_mutex.  The locks covering
    151  *	each field are documented in sys/lwp.h.
    152  *
    153  *	State transitions must be made with the LWP's general lock held.  In
    154  *	a multiprocessor kernel, state transitions may cause the LWP's lock
    155  *	pointer to change.  On uniprocessor kernels, most scheduler and
    156  *	synchronisation objects such as sleep queues and LWPs are protected
    157  *	by only one mutex (sched_mutex).  In this case, LWPs' lock pointers
    158  *	will never change and will always reference sched_mutex.
    159  *
    160  *	Manipulation of the general lock is not performed directly, but
    161  *	through calls to lwp_lock(), lwp_relock() and similar.
    162  *
    163  *	States and their associated locks:
    164  *
    165  *	LSIDL, LSZOMB
    166  *
    167  *		Always covered by sched_mutex.
    168  *
    169  *	LSONPROC, LSRUN:
    170  *
    171  *		Always covered by sched_mutex, which protects the run queues
    172  *		and other miscellaneous items.  If the scheduler is changed
    173  *		to use per-CPU run queues, this may become a per-CPU mutex.
    174  *
    175  *	LSSLEEP:
    176  *
    177  *		Covered by a mutex associated with the sleep queue that the
    178  *		LWP resides on, indirectly referenced by l_sleepq->sq_mutex.
    179  *
    180  *	LSSTOP, LSSUSPENDED:
    181  *
    182  *		If the LWP was previously sleeping (l_wchan != NULL), then
    183  *		l_mutex references the sleep queue mutex.  If the LWP was
    184  *		runnable or on the CPU when halted, or has been removed from
    185  *		the sleep queue since halted, then the mutex is sched_mutex.
    186  *
    187  *	The lock order is as follows:
    188  *
    189  *		sleepq_t::sq_mutex -> sched_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.40.2.6 2006/12/29 20:27:43 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/pool.h>
    219 #include <sys/proc.h>
    220 #include <sys/sa.h>
    221 #include <sys/syscallargs.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), 16, 0, 0, "lwppl",
    232     &pool_allocator_nointr);
    233 POOL_INIT(lwp_uc_pool, sizeof(ucontext_t), 0, 0, 0, "lwpucpl",
    234     &pool_allocator_nointr);
    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 	LOCK_ASSERT(mutex_owned(&t->l_proc->p_smutex));
    268 	LOCK_ASSERT(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 & (L_WEXIT | L_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 |= L_WSUSPEND;
    287 		lwp_need_userret(t);
    288 		lwp_unlock(t);
    289 		break;
    290 
    291 	case LSSLEEP:
    292 		t->l_flag |= L_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 & L_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 |= L_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 	LOCK_ASSERT(mutex_owned(&l->l_proc->p_smutex));
    344 	LOCK_ASSERT(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 & L_WREBOOT) != 0) {
    352 		lwp_unlock(l);
    353 		return;
    354 	}
    355 
    356 	l->l_flag &= ~L_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 
    380 	DPRINTF(("lwp_wait1: %d.%d waiting for %d.\n",
    381 	    p->p_pid, l->l_lid, lid));
    382 
    383 	LOCK_ASSERT(mutex_owned(&p->p_smutex));
    384 
    385 	/*
    386 	 * We try to check for deadlock:
    387 	 *
    388 	 * 1) If all other LWPs are waiting for exits or suspended.
    389 	 * 2) If we are trying to wait on ourself.
    390 	 *
    391 	 * XXX we'd like to check for a cycle of waiting LWPs (specific LID
    392 	 * waits, not any-LWP waits) and detect that sort of deadlock, but
    393 	 * we don't have a good place to store the lwp that is being waited
    394 	 * for. wchan is already filled with &p->p_nlwps, and putting the
    395 	 * lwp address in there for deadlock tracing would require exiting
    396 	 * LWPs to call wakeup on both their own address and &p->p_nlwps, to
    397 	 * get threads sleeping on any LWP exiting.
    398 	 */
    399 	if (lid == l->l_lid)
    400 		return EDEADLK;
    401 
    402 	p->p_nlwpwait++;
    403 
    404 	for (;;) {
    405 		/*
    406 		 * Avoid a race between exit1() and sigexit(): if the
    407 		 * process is dumping core, then we need to bail out: call
    408 		 * into lwp_userret() where we will be suspended until the
    409 		 * deed is done.
    410 		 */
    411 		if ((p->p_sflag & PS_WCORE) != 0) {
    412 			mutex_exit(&p->p_smutex);
    413 			lwp_userret(l);
    414 #ifdef DIAGNOSTIC
    415 			panic("lwp_wait1");
    416 #endif
    417 			/* NOTREACHED */
    418 		}
    419 
    420 		/*
    421 		 * First off, drain any detached LWP that is waiting to be
    422 		 * reaped.
    423 		 */
    424 		while ((l2 = p->p_zomblwp) != NULL) {
    425 			p->p_zomblwp = NULL;
    426 			lwp_free(l2, 0, 0);	/* releases proc mutex */
    427 			mutex_enter(&p->p_smutex);
    428 		}
    429 
    430 		/*
    431 		 * Now look for an LWP to collect.  If the whole process is
    432 		 * exiting, count detached LWPs as eligible to be collected,
    433 		 * but don't drain them here.
    434 		 */
    435 		nfound = 0;
    436 		LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
    437 			if (l2 == l || (lid != 0 && l2->l_lid != lid))
    438 				continue;
    439 			if ((l2->l_prflag & LPR_DETACHED) != 0) {
    440 				nfound += ((flags & LWPWAIT_EXITCONTROL) != 0);
    441 				continue;
    442 			}
    443 			nfound++;
    444 
    445 			/* No need to lock the LWP in order to see LSZOMB. */
    446 			if (l2->l_stat != LSZOMB)
    447 				continue;
    448 
    449 			if (departed)
    450 				*departed = l2->l_lid;
    451 			lwp_free(l2, 0, 0);
    452 			mutex_enter(&p->p_smutex);
    453 			p->p_nlwpwait--;
    454 			return 0;
    455 		}
    456 
    457 		if (nfound == 0) {
    458 			error = ESRCH;
    459 			break;
    460 		}
    461 		if ((flags & LWPWAIT_EXITCONTROL) != 0) {
    462 			KASSERT(p->p_nlwps > 1);
    463 			cv_wait(&p->p_lwpcv, &p->p_smutex);
    464 			continue;
    465 		}
    466 		if ((p->p_sflag & PS_WEXIT) != 0 ||
    467 		    p->p_nrlwps <= p->p_nlwpwait + p->p_ndlwps) {
    468 			error = EDEADLK;
    469 			break;
    470 		}
    471 		if ((error = cv_wait_sig(&p->p_lwpcv, &p->p_smutex)) != 0)
    472 			break;
    473 	}
    474 
    475 	p->p_nlwpwait--;
    476 	return error;
    477 }
    478 
    479 /*
    480  * Create a new LWP within process 'p2', using LWP 'l1' as a template.
    481  * The new LWP is created in state LSIDL and must be set running,
    482  * suspended, or stopped by the caller.
    483  */
    484 int
    485 newlwp(struct lwp *l1, struct proc *p2, vaddr_t uaddr, boolean_t inmem,
    486     int flags, void *stack, size_t stacksize,
    487     void (*func)(void *), void *arg, struct lwp **rnewlwpp)
    488 {
    489 	struct lwp *l2, *isfree;
    490 	turnstile_t *ts;
    491 
    492 	/*
    493 	 * First off, reap any detached LWP waiting to be collected.
    494 	 * We can re-use its LWP structure and turnstile.
    495 	 */
    496 	isfree = NULL;
    497 	if (p2->p_zomblwp != NULL) {
    498 		mutex_enter(&p2->p_smutex);
    499 		if ((isfree = p2->p_zomblwp) != NULL) {
    500 			p2->p_zomblwp = NULL;
    501 			lwp_free(isfree, 1, 0);	/* releases proc mutex */
    502 		} else
    503 			mutex_exit(&p2->p_smutex);
    504 	}
    505 	if (isfree == NULL) {
    506 		l2 = pool_get(&lwp_pool, PR_WAITOK);
    507 		memset(l2, 0, sizeof(*l2));
    508 		l2->l_ts = pool_cache_get(&turnstile_cache, PR_WAITOK);
    509 	} else {
    510 		l2 = isfree;
    511 		ts = l2->l_ts;
    512 		memset(l2, 0, sizeof(*l2));
    513 		l2->l_ts = ts;
    514 	}
    515 
    516 	l2->l_stat = LSIDL;
    517 	l2->l_forw = l2->l_back = NULL;
    518 	l2->l_proc = p2;
    519 	l2->l_refcnt = 1;
    520 	l2->l_priority = l1->l_priority;
    521 	l2->l_usrpri = l1->l_usrpri;
    522 	l2->l_mutex = &sched_mutex;
    523 	l2->l_cpu = l1->l_cpu;
    524 	l2->l_flag = inmem ? L_INMEM : 0;
    525 	lwp_initspecific(l2);
    526 
    527 	if (p2->p_flag & P_SYSTEM) {
    528 		/*
    529 		 * Mark it as a system process and not a candidate for
    530 		 * swapping.
    531 		 */
    532 		l2->l_flag |= L_SYSTEM | L_INMEM;
    533 	}
    534 
    535 	lwp_update_creds(l2);
    536 	callout_init(&l2->l_tsleep_ch);
    537 	l2->l_syncobj = &sched_syncobj;
    538 
    539 	if (rnewlwpp != NULL)
    540 		*rnewlwpp = l2;
    541 
    542 	l2->l_addr = UAREA_TO_USER(uaddr);
    543 	uvm_lwp_fork(l1, l2, stack, stacksize, func,
    544 	    (arg != NULL) ? arg : l2);
    545 
    546 	mutex_enter(&p2->p_smutex);
    547 
    548 	if ((flags & LWP_DETACHED) != 0) {
    549 		l2->l_prflag = LPR_DETACHED;
    550 		p2->p_ndlwps++;
    551 	} else
    552 		l2->l_prflag = 0;
    553 
    554 	if ((p2->p_sflag & PS_SA) == 0) {
    555 		l2->l_sigmask = &l2->l_sigstore.ss_mask;
    556 		l2->l_sigstk = &l2->l_sigstore.ss_stk;
    557 		*l2->l_sigmask = *l1->l_sigmask;
    558 	} else {
    559 		l2->l_sigmask = &p2->p_sigstore.ss_mask;
    560 		l2->l_sigstk = &p2->p_sigstore.ss_stk;
    561 	}
    562 
    563 	CIRCLEQ_INIT(&l2->l_sigpend.sp_info);
    564 	sigemptyset(&l2->l_sigpend.sp_set);
    565 
    566 	l2->l_lid = ++p2->p_nlwpid;
    567 	LIST_INSERT_HEAD(&p2->p_lwps, l2, l_sibling);
    568 	p2->p_nlwps++;
    569 
    570 	mutex_exit(&p2->p_smutex);
    571 
    572 	mutex_enter(&proclist_mutex);
    573 	LIST_INSERT_HEAD(&alllwp, l2, l_list);
    574 	mutex_exit(&proclist_mutex);
    575 
    576 	if (p2->p_emul->e_lwp_fork)
    577 		(*p2->p_emul->e_lwp_fork)(l1, l2);
    578 
    579 	return (0);
    580 }
    581 
    582 /*
    583  * Quit the process.  This will call cpu_exit, which will call cpu_switch,
    584  * so this can only be used meaningfully if you're willing to switch away.
    585  * Calling with l!=curlwp would be weird.
    586  */
    587 void
    588 lwp_exit(struct lwp *l)
    589 {
    590 	struct proc *p = l->l_proc;
    591 	struct lwp *l2;
    592 
    593 	DPRINTF(("lwp_exit: %d.%d exiting.\n", p->p_pid, l->l_lid));
    594 	DPRINTF((" nlwps: %d nzlwps: %d\n", p->p_nlwps, p->p_nzlwps));
    595 
    596 	/*
    597 	 * Verify that we hold no locks other than the kernel lock.
    598 	 */
    599 #ifdef MULTIPROCESSOR
    600 	LOCKDEBUG_BARRIER(&kernel_lock, 0);
    601 #else
    602 	LOCKDEBUG_BARRIER(NULL, 0);
    603 #endif
    604 
    605 	/*
    606 	 * If we are the last live LWP in a process, we need to exit the
    607 	 * entire process.  We do so with an exit status of zero, because
    608 	 * it's a "controlled" exit, and because that's what Solaris does.
    609 	 *
    610 	 * We are not quite a zombie yet, but for accounting purposes we
    611 	 * must increment the count of zombies here.
    612 	 *
    613 	 * Note: the last LWP's specificdata will be deleted here.
    614 	 */
    615 	mutex_enter(&p->p_smutex);
    616 
    617 	if (p->p_nlwps - p->p_nzlwps == 1) {
    618 		DPRINTF(("lwp_exit: %d.%d calling exit1()\n",
    619 		    p->p_pid, l->l_lid));
    620 		exit1(l, 0);
    621 		/* NOTREACHED */
    622 	}
    623 	p->p_nzlwps++;
    624 	mutex_exit(&p->p_smutex);
    625 
    626 	if (p->p_emul->e_lwp_exit)
    627 		(*p->p_emul->e_lwp_exit)(l);
    628 
    629 	/* Delete the specificdata while it's still safe to sleep. */
    630 	specificdata_fini(lwp_specificdata_domain, &l->l_specdataref);
    631 
    632 	/*
    633 	 * Release our cached credentials.
    634 	 */
    635 	kauth_cred_free(l->l_cred);
    636 
    637 	/*
    638 	 * Remove the LWP from the global list.
    639 	 */
    640 	mutex_enter(&proclist_mutex);
    641 	LIST_REMOVE(l, l_list);
    642 	mutex_exit(&proclist_mutex);
    643 
    644 	/*
    645 	 * Get rid of all references to the LWP that others (e.g. procfs)
    646 	 * may have, and mark the LWP as a zombie.  If the LWP is detached,
    647 	 * mark it waiting for collection in the proc structure.  Note that
    648 	 * before we can do that, we need to free any other dead, deatched
    649 	 * LWP waiting to meet its maker.
    650 	 *
    651 	 * XXXSMP disable preemption.
    652 	 */
    653 	mutex_enter(&p->p_smutex);
    654 	lwp_drainrefs(l);
    655 
    656 	if ((p->p_sflag & PS_SA) == 0) {
    657 		/*
    658 		 * Clear any private, pending signals.  XXXLWP Small
    659 		 * chance that we may defer process-wide signals by
    660 		 * taking L_PENDSIG with us to the grave.
    661 		 */
    662 		sigclear(&l->l_sigpend, NULL);
    663 	}
    664 
    665 	if ((l->l_prflag & LPR_DETACHED) != 0) {
    666 		while ((l2 = p->p_zomblwp) != NULL) {
    667 			p->p_zomblwp = NULL;
    668 			lwp_free(l2, 0, 0);	/* releases proc mutex */
    669 			mutex_enter(&p->p_smutex);
    670 		}
    671 		p->p_zomblwp = l;
    672 	}
    673 	lwp_lock(l);
    674 	l->l_stat = LSZOMB;
    675 	lwp_unlock(l);
    676 	p->p_nrlwps--;
    677 
    678 	/*
    679 	 * Add our run time to the process' base value.  Once we're off
    680 	 * p_lwps, we won't be found by calcru().
    681 	 */
    682 	timeradd(&l->l_rtime, &p->p_rtime, &p->p_rtime);
    683 	mutex_exit(&p->p_smutex);
    684 
    685 	/*
    686 	 * We can no longer block.  At this point, lwp_free() may already
    687 	 * be gunning for us.  On a multi-CPU system, we may be off p_lwps.
    688 	 *
    689 	 * Free MD LWP resources.
    690 	 */
    691 #ifndef __NO_CPU_LWP_FREE
    692 	cpu_lwp_free(l, 0);
    693 #endif
    694 	pmap_deactivate(l);
    695 
    696 	/*
    697 	 * Release the kernel lock, signal another LWP to collect us,
    698 	 * and switch away into oblivion.
    699 	 */
    700 	(void)KERNEL_UNLOCK(0, l);	/* XXXSMP assert count == 1 */
    701 	cv_broadcast(&p->p_lwpcv);
    702 	cpu_exit(l);
    703 }
    704 
    705 /*
    706  * We are called from cpu_exit() once it is safe to schedule the dead LWP's
    707  * resources to be freed (i.e., once we've switched to the idle PCB for the
    708  * current CPU).
    709  */
    710 void
    711 lwp_exit2(struct lwp *l)
    712 {
    713 	/* XXXSMP re-enable preemption */
    714 }
    715 
    716 /*
    717  * Free a dead LWP's remaining resources.
    718  *
    719  * XXXLWP limits.
    720  */
    721 void
    722 lwp_free(struct lwp *l, int recycle, int last)
    723 {
    724 	struct proc *p = l->l_proc;
    725 
    726 	/*
    727 	 * If this was not the last LWP in the process, then adjust
    728 	 * counters and unlock.
    729 	 */
    730 	if (!last) {
    731 		LIST_REMOVE(l, l_sibling);
    732 		p->p_nlwps--;
    733 		p->p_nzlwps--;
    734 		if ((l->l_prflag & LPR_DETACHED) != 0)
    735 			p->p_ndlwps--;
    736 		mutex_exit(&p->p_smutex);
    737 
    738 #ifdef MULTIPROCESSOR
    739 		/*
    740 		 * In the unlikely event that the LWP is still on the CPU,
    741 		 * then spin until it has switched away.  We need to release
    742 		 * all locks to avoid deadlock against interrupt handlers on
    743 		 * the target CPU.
    744 		 */
    745 		if (l->l_cpu->ci_curlwp == l) {
    746 			int count;
    747 			count = KERNEL_UNLOCK(0, l);
    748 			while (l->l_cpu->ci_curlwp == l)
    749 				SPINLOCK_BACKOFF_HOOK;
    750 			KERNEL_LOCK(count, l);
    751 		}
    752 #endif
    753 	}
    754 
    755 	/*
    756 	 * Free the LWP's turnstile and the LWP structure itself unless the
    757 	 * caller wants to recycle them.
    758 	 *
    759 	 * We can't return turnstile0 to the pool (it didn't come from it),
    760 	 * so if it comes up just drop it quietly and move on.
    761 	 *
    762 	 * We don't recycle the VM resources at this time.
    763 	 */
    764 	if (!recycle && l->l_ts != &turnstile0)
    765 		pool_cache_put(&turnstile_cache, l->l_ts);
    766 #ifndef __NO_CPU_LWP_FREE
    767 	cpu_lwp_free2(l);
    768 #endif
    769 	uvm_lwp_exit(l);
    770 	if (!recycle)
    771 		pool_put(&lwp_pool, l);
    772 }
    773 
    774 /*
    775  * Pick a LWP to represent the process for those operations which
    776  * want information about a "process" that is actually associated
    777  * with a LWP.
    778  *
    779  * If 'locking' is false, no locking or lock checks are performed.
    780  * This is intended for use by DDB.
    781  *
    782  * We don't bother locking the LWP here, since code that uses this
    783  * interface is broken by design and an exact match is not required.
    784  */
    785 struct lwp *
    786 proc_representative_lwp(struct proc *p, int *nrlwps, int locking)
    787 {
    788 	struct lwp *l, *onproc, *running, *sleeping, *stopped, *suspended;
    789 	struct lwp *signalled;
    790 	int cnt;
    791 
    792 	if (locking) {
    793 		LOCK_ASSERT(mutex_owned(&p->p_smutex));
    794 	}
    795 
    796 	/* Trivial case: only one LWP */
    797 	if (p->p_nlwps == 1) {
    798 		l = LIST_FIRST(&p->p_lwps);
    799 		if (nrlwps)
    800 			*nrlwps = (l->l_stat == LSONPROC || LSRUN);
    801 		return l;
    802 	}
    803 
    804 	cnt = 0;
    805 	switch (p->p_stat) {
    806 	case SSTOP:
    807 	case SACTIVE:
    808 		/* Pick the most live LWP */
    809 		onproc = running = sleeping = stopped = suspended = NULL;
    810 		signalled = NULL;
    811 		LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    812 			if (l->l_lid == p->p_sigctx.ps_lwp)
    813 				signalled = l;
    814 			switch (l->l_stat) {
    815 			case LSONPROC:
    816 				onproc = l;
    817 				cnt++;
    818 				break;
    819 			case LSRUN:
    820 				running = l;
    821 				cnt++;
    822 				break;
    823 			case LSSLEEP:
    824 				sleeping = l;
    825 				break;
    826 			case LSSTOP:
    827 				stopped = l;
    828 				break;
    829 			case LSSUSPENDED:
    830 				suspended = l;
    831 				break;
    832 			}
    833 		}
    834 		if (nrlwps)
    835 			*nrlwps = cnt;
    836 		if (signalled)
    837 			l = signalled;
    838 		else if (onproc)
    839 			l = onproc;
    840 		else if (running)
    841 			l = running;
    842 		else if (sleeping)
    843 			l = sleeping;
    844 		else if (stopped)
    845 			l = stopped;
    846 		else if (suspended)
    847 			l = suspended;
    848 		else
    849 			break;
    850 		return l;
    851 		if (nrlwps)
    852 			*nrlwps = 0;
    853 		l = LIST_FIRST(&p->p_lwps);
    854 		return l;
    855 #ifdef DIAGNOSTIC
    856 	case SIDL:
    857 	case SZOMB:
    858 	case SDYING:
    859 	case SDEAD:
    860 		if (locking)
    861 			mutex_exit(&p->p_smutex);
    862 		/* We have more than one LWP and we're in SIDL?
    863 		 * How'd that happen?
    864 		 */
    865 		panic("Too many LWPs in idle/dying process %d (%s) stat = %d",
    866 		    p->p_pid, p->p_comm, p->p_stat);
    867 		break;
    868 	default:
    869 		if (locking)
    870 			mutex_exit(&p->p_smutex);
    871 		panic("Process %d (%s) in unknown state %d",
    872 		    p->p_pid, p->p_comm, p->p_stat);
    873 #endif
    874 	}
    875 
    876 	if (locking)
    877 		mutex_exit(&p->p_smutex);
    878 	panic("proc_representative_lwp: couldn't find a lwp for process"
    879 		" %d (%s)", p->p_pid, p->p_comm);
    880 	/* NOTREACHED */
    881 	return NULL;
    882 }
    883 
    884 /*
    885  * Look up a live LWP within the speicifed process, and return it locked.
    886  *
    887  * Must be called with p->p_smutex held.
    888  */
    889 struct lwp *
    890 lwp_find(struct proc *p, int id)
    891 {
    892 	struct lwp *l;
    893 
    894 	LOCK_ASSERT(mutex_owned(&p->p_smutex));
    895 
    896 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
    897 		if (l->l_lid == id)
    898 			break;
    899 	}
    900 
    901 	/*
    902 	 * No need to lock - all of these conditions will
    903 	 * be visible with the process level mutex held.
    904 	 */
    905 	if (l != NULL && (l->l_stat == LSIDL || l->l_stat == LSZOMB))
    906 		l = NULL;
    907 
    908 	return l;
    909 }
    910 
    911 /*
    912  * Update an LWP's cached credentials to mirror the process' master copy.
    913  *
    914  * This happens early in the syscall path, on user trap, and on LWP
    915  * creation.  A long-running LWP can also voluntarily choose to update
    916  * it's credentials by calling this routine.  This may be called from
    917  * LWP_CACHE_CREDS(), which checks l->l_cred != p->p_cred beforehand.
    918  */
    919 void
    920 lwp_update_creds(struct lwp *l)
    921 {
    922 	kauth_cred_t oc;
    923 	struct proc *p;
    924 
    925 	p = l->l_proc;
    926 	oc = l->l_cred;
    927 
    928 	mutex_enter(&p->p_mutex);
    929 	kauth_cred_hold(p->p_cred);
    930 	l->l_cred = p->p_cred;
    931 	mutex_exit(&p->p_mutex);
    932 	if (oc != NULL) {
    933 		KERNEL_LOCK(1, l);		/* XXXSMP */
    934 		kauth_cred_free(oc);
    935 		(void)KERNEL_UNLOCK(1, l);	/* XXXSMP */
    936 	}
    937 }
    938 
    939 /*
    940  * Verify that an LWP is locked, and optionally verify that the lock matches
    941  * one we specify.
    942  */
    943 int
    944 lwp_locked(struct lwp *l, kmutex_t *mtx)
    945 {
    946 	kmutex_t *cur = l->l_mutex;
    947 
    948 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
    949 	return mutex_owned(cur) && (mtx == cur || mtx == NULL);
    950 #else
    951 	return mutex_owned(cur);
    952 #endif
    953 }
    954 
    955 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
    956 /*
    957  * Lock an LWP.
    958  */
    959 void
    960 lwp_lock_retry(struct lwp *l, kmutex_t *old)
    961 {
    962 
    963 	/*
    964 	 * XXXgcc ignoring kmutex_t * volatile on i386
    965 	 *
    966 	 * gcc version 4.1.2 20061021 prerelease (NetBSD nb1 20061021)
    967 	 */
    968 #if 1
    969 	while (l->l_mutex != old) {
    970 #else
    971 	for (;;) {
    972 #endif
    973 		smutex_exit(old);
    974 		old = l->l_mutex;
    975 		smutex_enter(old);
    976 
    977 		/*
    978 		 * mutex_enter() will have posted a read barrier.  Re-test
    979 		 * l->l_mutex.  If it has changed, we need to try again.
    980 		 */
    981 #if 1
    982 	}
    983 #else
    984 	} while (__predict_false(l->l_mutex != old));
    985 #endif
    986 }
    987 #endif
    988 
    989 /*
    990  * Lend a new mutex to an LWP.  The old mutex must be held.
    991  */
    992 void
    993 lwp_setlock(struct lwp *l, kmutex_t *new)
    994 {
    995 
    996 	LOCK_ASSERT(mutex_owned(l->l_mutex));
    997 
    998 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
    999 	mb_write();
   1000 	l->l_mutex = new;
   1001 #else
   1002 	(void)new;
   1003 #endif
   1004 }
   1005 
   1006 /*
   1007  * Lend a new mutex to an LWP, and release the old mutex.  The old mutex
   1008  * must be held.
   1009  */
   1010 void
   1011 lwp_unlock_to(struct lwp *l, kmutex_t *new)
   1012 {
   1013 	kmutex_t *old;
   1014 
   1015 	LOCK_ASSERT(mutex_owned(l->l_mutex));
   1016 
   1017 	old = l->l_mutex;
   1018 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
   1019 	mb_write();
   1020 	l->l_mutex = new;
   1021 #else
   1022 	(void)new;
   1023 #endif
   1024 	smutex_exit(old);
   1025 }
   1026 
   1027 /*
   1028  * Acquire a new mutex, and donate it to an LWP.  The LWP must already be
   1029  * locked.
   1030  */
   1031 void
   1032 lwp_relock(struct lwp *l, kmutex_t *new)
   1033 {
   1034 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
   1035 	kmutex_t *old;
   1036 #endif
   1037 
   1038 	LOCK_ASSERT(mutex_owned(l->l_mutex));
   1039 
   1040 #if defined(MULTIPROCESSOR) || defined(LOCKDEBUG)
   1041 	old = l->l_mutex;
   1042 	if (old != new) {
   1043 		smutex_enter(new);
   1044 		l->l_mutex = new;
   1045 		smutex_exit(old);
   1046 	}
   1047 #else
   1048 	(void)new;
   1049 #endif
   1050 }
   1051 
   1052 /*
   1053  * Handle exceptions for mi_userret().  Called if a member of L_USERRET is
   1054  * set.
   1055  */
   1056 void
   1057 lwp_userret(struct lwp *l)
   1058 {
   1059 	struct proc *p;
   1060 	int sig;
   1061 
   1062 	p = l->l_proc;
   1063 
   1064 	/*
   1065 	 * It should be safe to do this read unlocked on a multiprocessor
   1066 	 * system..
   1067 	 */
   1068 	while ((l->l_flag & L_USERRET) != 0) {
   1069 		/*
   1070 		 * Process pending signals first, unless the process
   1071 		 * is dumping core, where we will instead enter the
   1072 		 * L_WSUSPEND case below.
   1073 		 */
   1074 		if ((l->l_flag & (L_PENDSIG | L_WCORE)) == L_PENDSIG) {
   1075 			KERNEL_LOCK(1, l);	/* XXXSMP pool_put() below */
   1076 			mutex_enter(&p->p_smutex);
   1077 			while ((sig = issignal(l)) != 0)
   1078 				postsig(sig);
   1079 			mutex_exit(&p->p_smutex);
   1080 			(void)KERNEL_UNLOCK(0, l);	/* XXXSMP */
   1081 		}
   1082 
   1083 		/*
   1084 		 * Core-dump or suspend pending.
   1085 		 *
   1086 		 * In case of core dump, suspend ourselves, so that the
   1087 		 * kernel stack and therefore the userland registers saved
   1088 		 * in the trapframe are around for coredump() to write them
   1089 		 * out.  We issue a wakeup on p->p_lwpcv so that sigexit()
   1090 		 * will write the core file out once all other LWPs are
   1091 		 * suspended.
   1092 		 */
   1093 		if ((l->l_flag & L_WSUSPEND) != 0) {
   1094 			mutex_enter(&p->p_smutex);
   1095 			p->p_nrlwps--;
   1096 			cv_broadcast(&p->p_lwpcv);
   1097 			lwp_lock(l);
   1098 			l->l_stat = LSSUSPENDED;
   1099 			mutex_exit(&p->p_smutex);
   1100 			mi_switch(l, NULL);
   1101 		}
   1102 
   1103 		/* Process is exiting. */
   1104 		if ((l->l_flag & L_WEXIT) != 0) {
   1105 			KERNEL_LOCK(1, l);
   1106 			lwp_exit(l);
   1107 			KASSERT(0);
   1108 			/* NOTREACHED */
   1109 		}
   1110 	}
   1111 
   1112 	/*
   1113 	 * Timer events are handled specially.  We only try once to deliver
   1114 	 * pending timer upcalls; if if fails, we can try again on the next
   1115 	 * loop around.  If we need to re-enter lwp_userret(), MD code will
   1116 	 * bounce us back here through the trap path after we return.
   1117 	 */
   1118 	if (p->p_timerpend)
   1119 		timerupcall(l);
   1120 }
   1121 
   1122 /*
   1123  * Force an LWP to enter the kernel, to take a trip through lwp_userret().
   1124  */
   1125 void
   1126 lwp_need_userret(struct lwp *l)
   1127 {
   1128 	LOCK_ASSERT(lwp_locked(l, NULL));
   1129 
   1130 	/*
   1131 	 * Since the tests in lwp_userret() are done unlocked, make sure
   1132 	 * that the condition will be seen before forcing the LWP to enter
   1133 	 * kernel mode.
   1134 	 */
   1135 	mb_write();
   1136 
   1137 	lwp_changepri(l, PUSER);
   1138 	cpu_signotify(l);
   1139 }
   1140 
   1141 /*
   1142  * Add one reference to an LWP.  This will prevent the LWP from
   1143  * exiting, thus keep the lwp structure and PCB around to inspect.
   1144  */
   1145 void
   1146 lwp_addref(struct lwp *l)
   1147 {
   1148 
   1149 	LOCK_ASSERT(mutex_owned(&l->l_proc->p_smutex));
   1150 	KASSERT(l->l_stat != LSZOMB);
   1151 	KASSERT(l->l_refcnt != 0);
   1152 
   1153 	l->l_refcnt++;
   1154 }
   1155 
   1156 /*
   1157  * Remove one reference to an LWP.  If this is the last reference,
   1158  * then we must finalize the LWP's death.
   1159  */
   1160 void
   1161 lwp_delref(struct lwp *l)
   1162 {
   1163 	struct proc *p = l->l_proc;
   1164 	u_int refcnt;
   1165 
   1166 	mutex_enter(&p->p_smutex);
   1167 	refcnt = --l->l_refcnt;
   1168 	mutex_exit(&p->p_smutex);
   1169 
   1170 	if (refcnt == 0)
   1171 		cv_broadcast(&p->p_refcv);
   1172 }
   1173 
   1174 /*
   1175  * Drain all references to the current LWP.
   1176  */
   1177 void
   1178 lwp_drainrefs(struct lwp *l)
   1179 {
   1180 	struct proc *p = l->l_proc;
   1181 
   1182 	LOCK_ASSERT(mutex_owned(&p->p_smutex));
   1183 	KASSERT(l->l_refcnt != 0);
   1184 
   1185 	l->l_refcnt--;
   1186 	while (l->l_refcnt != 0)
   1187 		cv_wait(&p->p_refcv, &p->p_smutex);
   1188 }
   1189 
   1190 /*
   1191  * lwp_specific_key_create --
   1192  *	Create a key for subsystem lwp-specific data.
   1193  */
   1194 int
   1195 lwp_specific_key_create(specificdata_key_t *keyp, specificdata_dtor_t dtor)
   1196 {
   1197 
   1198 	return (specificdata_key_create(lwp_specificdata_domain, keyp, dtor));
   1199 }
   1200 
   1201 /*
   1202  * lwp_specific_key_delete --
   1203  *	Delete a key for subsystem lwp-specific data.
   1204  */
   1205 void
   1206 lwp_specific_key_delete(specificdata_key_t key)
   1207 {
   1208 
   1209 	specificdata_key_delete(lwp_specificdata_domain, key);
   1210 }
   1211 
   1212 /*
   1213  * lwp_initspecific --
   1214  *	Initialize an LWP's specificdata container.
   1215  */
   1216 void
   1217 lwp_initspecific(struct lwp *l)
   1218 {
   1219 	int error;
   1220 
   1221 	error = specificdata_init(lwp_specificdata_domain, &l->l_specdataref);
   1222 	KASSERT(error == 0);
   1223 }
   1224 
   1225 /*
   1226  * lwp_finispecific --
   1227  *	Finalize an LWP's specificdata container.
   1228  */
   1229 void
   1230 lwp_finispecific(struct lwp *l)
   1231 {
   1232 
   1233 	specificdata_fini(lwp_specificdata_domain, &l->l_specdataref);
   1234 }
   1235 
   1236 /*
   1237  * lwp_getspecific --
   1238  *	Return lwp-specific data corresponding to the specified key.
   1239  *
   1240  *	Note: LWP specific data is NOT INTERLOCKED.  An LWP should access
   1241  *	only its OWN SPECIFIC DATA.  If it is necessary to access another
   1242  *	LWP's specifc data, care must be taken to ensure that doing so
   1243  *	would not cause internal data structure inconsistency (i.e. caller
   1244  *	can guarantee that the target LWP is not inside an lwp_getspecific()
   1245  *	or lwp_setspecific() call).
   1246  */
   1247 void *
   1248 lwp_getspecific(specificdata_key_t key)
   1249 {
   1250 
   1251 	return (specificdata_getspecific_unlocked(lwp_specificdata_domain,
   1252 						  &curlwp->l_specdataref, key));
   1253 }
   1254 
   1255 void *
   1256 _lwp_getspecific_by_lwp(struct lwp *l, specificdata_key_t key)
   1257 {
   1258 
   1259 	return (specificdata_getspecific_unlocked(lwp_specificdata_domain,
   1260 						  &l->l_specdataref, key));
   1261 }
   1262 
   1263 /*
   1264  * lwp_setspecific --
   1265  *	Set lwp-specific data corresponding to the specified key.
   1266  */
   1267 void
   1268 lwp_setspecific(specificdata_key_t key, void *data)
   1269 {
   1270 
   1271 	specificdata_setspecific(lwp_specificdata_domain,
   1272 				 &curlwp->l_specdataref, key, data);
   1273 }
   1274