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