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