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