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