xref: /netbsd-src/sys/kern/kern_lwp.c (revision 213144e1de7024d4193d04aa51005ba3a5ad95e7)
1 /*	$NetBSD: kern_lwp.c,v 1.156 2011/02/21 20:23:28 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_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.156 2011/02/21 20:23:28 pooka 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 	 * For vfork, borrow parent's lwpctl context if it exists.
701 	 * This also causes us to return via lwp_userret.
702 	 */
703 	if (flags & LWP_VFORK && l1->l_lwpctl) {
704 		l2->l_lwpctl = l1->l_lwpctl;
705 		l2->l_flag |= LW_LWPCTL;
706 	}
707 
708 	/*
709 	 * If not the first LWP in the process, grab a reference to the
710 	 * descriptor table.
711 	 */
712 	l2->l_fd = p2->p_fd;
713 	if (p2->p_nlwps != 0) {
714 		KASSERT(l1->l_proc == p2);
715 		fd_hold(l2);
716 	} else {
717 		KASSERT(l1->l_proc != p2);
718 	}
719 
720 	if (p2->p_flag & PK_SYSTEM) {
721 		/* Mark it as a system LWP. */
722 		l2->l_flag |= LW_SYSTEM;
723 	}
724 
725 	kpreempt_disable();
726 	l2->l_mutex = l1->l_cpu->ci_schedstate.spc_mutex;
727 	l2->l_cpu = l1->l_cpu;
728 	kpreempt_enable();
729 
730 	kdtrace_thread_ctor(NULL, l2);
731 	lwp_initspecific(l2);
732 	sched_lwp_fork(l1, l2);
733 	lwp_update_creds(l2);
734 	callout_init(&l2->l_timeout_ch, CALLOUT_MPSAFE);
735 	callout_setfunc(&l2->l_timeout_ch, sleepq_timeout, l2);
736 	cv_init(&l2->l_sigcv, "sigwait");
737 	l2->l_syncobj = &sched_syncobj;
738 
739 	if (rnewlwpp != NULL)
740 		*rnewlwpp = l2;
741 
742 	uvm_lwp_setuarea(l2, uaddr);
743 	uvm_lwp_fork(l1, l2, stack, stacksize, func,
744 	    (arg != NULL) ? arg : l2);
745 
746 	if ((flags & LWP_PIDLID) != 0) {
747 		lid = proc_alloc_pid(p2);
748 		l2->l_pflag |= LP_PIDLID;
749 	} else {
750 		lid = 0;
751 	}
752 
753 	mutex_enter(p2->p_lock);
754 
755 	if ((flags & LWP_DETACHED) != 0) {
756 		l2->l_prflag = LPR_DETACHED;
757 		p2->p_ndlwps++;
758 	} else
759 		l2->l_prflag = 0;
760 
761 	l2->l_sigmask = l1->l_sigmask;
762 	CIRCLEQ_INIT(&l2->l_sigpend.sp_info);
763 	sigemptyset(&l2->l_sigpend.sp_set);
764 
765 	if (lid == 0) {
766 		p2->p_nlwpid++;
767 		if (p2->p_nlwpid == 0)
768 			p2->p_nlwpid++;
769 		lid = p2->p_nlwpid;
770 	}
771 	l2->l_lid = lid;
772 	LIST_INSERT_HEAD(&p2->p_lwps, l2, l_sibling);
773 	p2->p_nlwps++;
774 	p2->p_nrlwps++;
775 
776 	if ((p2->p_flag & PK_SYSTEM) == 0) {
777 		/* Inherit an affinity */
778 		if (l1->l_flag & LW_AFFINITY) {
779 			/*
780 			 * Note that we hold the state lock while inheriting
781 			 * the affinity to avoid race with sched_setaffinity().
782 			 */
783 			lwp_lock(l1);
784 			if (l1->l_flag & LW_AFFINITY) {
785 				kcpuset_use(l1->l_affinity);
786 				l2->l_affinity = l1->l_affinity;
787 				l2->l_flag |= LW_AFFINITY;
788 			}
789 			lwp_unlock(l1);
790 		}
791 		lwp_lock(l2);
792 		/* Inherit a processor-set */
793 		l2->l_psid = l1->l_psid;
794 		/* Look for a CPU to start */
795 		l2->l_cpu = sched_takecpu(l2);
796 		lwp_unlock_to(l2, l2->l_cpu->ci_schedstate.spc_mutex);
797 	}
798 	mutex_exit(p2->p_lock);
799 
800 	SDT_PROBE(proc,,,lwp_create, l2, 0,0,0,0);
801 
802 	mutex_enter(proc_lock);
803 	LIST_INSERT_HEAD(&alllwp, l2, l_list);
804 	mutex_exit(proc_lock);
805 
806 	SYSCALL_TIME_LWP_INIT(l2);
807 
808 	if (p2->p_emul->e_lwp_fork)
809 		(*p2->p_emul->e_lwp_fork)(l1, l2);
810 
811 	return (0);
812 }
813 
814 /*
815  * Called by MD code when a new LWP begins execution.  Must be called
816  * with the previous LWP locked (so at splsched), or if there is no
817  * previous LWP, at splsched.
818  */
819 void
820 lwp_startup(struct lwp *prev, struct lwp *new)
821 {
822 
823 	SDT_PROBE(proc,,,lwp_start, new, 0,0,0,0);
824 
825 	KASSERT(kpreempt_disabled());
826 	if (prev != NULL) {
827 		/*
828 		 * Normalize the count of the spin-mutexes, it was
829 		 * increased in mi_switch().  Unmark the state of
830 		 * context switch - it is finished for previous LWP.
831 		 */
832 		curcpu()->ci_mtx_count++;
833 		membar_exit();
834 		prev->l_ctxswtch = 0;
835 	}
836 	KPREEMPT_DISABLE(new);
837 	spl0();
838 	pmap_activate(new);
839 	LOCKDEBUG_BARRIER(NULL, 0);
840 	KPREEMPT_ENABLE(new);
841 	if ((new->l_pflag & LP_MPSAFE) == 0) {
842 		KERNEL_LOCK(1, new);
843 	}
844 }
845 
846 /*
847  * Exit an LWP.
848  */
849 void
850 lwp_exit(struct lwp *l)
851 {
852 	struct proc *p = l->l_proc;
853 	struct lwp *l2;
854 	bool current;
855 
856 	current = (l == curlwp);
857 
858 	KASSERT(current || (l->l_stat == LSIDL && l->l_target_cpu == NULL));
859 	KASSERT(p == curproc);
860 
861 	SDT_PROBE(proc,,,lwp_exit, l, 0,0,0,0);
862 
863 	/*
864 	 * Verify that we hold no locks other than the kernel lock.
865 	 */
866 	LOCKDEBUG_BARRIER(&kernel_lock, 0);
867 
868 	/*
869 	 * If we are the last live LWP in a process, we need to exit the
870 	 * entire process.  We do so with an exit status of zero, because
871 	 * it's a "controlled" exit, and because that's what Solaris does.
872 	 *
873 	 * We are not quite a zombie yet, but for accounting purposes we
874 	 * must increment the count of zombies here.
875 	 *
876 	 * Note: the last LWP's specificdata will be deleted here.
877 	 */
878 	mutex_enter(p->p_lock);
879 	if (p->p_nlwps - p->p_nzlwps == 1) {
880 		KASSERT(current == true);
881 		/* XXXSMP kernel_lock not held */
882 		exit1(l, 0);
883 		/* NOTREACHED */
884 	}
885 	p->p_nzlwps++;
886 	mutex_exit(p->p_lock);
887 
888 	if (p->p_emul->e_lwp_exit)
889 		(*p->p_emul->e_lwp_exit)(l);
890 
891 	/* Drop filedesc reference. */
892 	fd_free();
893 
894 	/* Delete the specificdata while it's still safe to sleep. */
895 	lwp_finispecific(l);
896 
897 	/*
898 	 * Release our cached credentials.
899 	 */
900 	kauth_cred_free(l->l_cred);
901 	callout_destroy(&l->l_timeout_ch);
902 
903 	/*
904 	 * Remove the LWP from the global list.
905 	 * Free its LID from the PID namespace if needed.
906 	 */
907 	mutex_enter(proc_lock);
908 	LIST_REMOVE(l, l_list);
909 	if ((l->l_pflag & LP_PIDLID) != 0 && l->l_lid != p->p_pid) {
910 		proc_free_pid(l->l_lid);
911 	}
912 	mutex_exit(proc_lock);
913 
914 	/*
915 	 * Get rid of all references to the LWP that others (e.g. procfs)
916 	 * may have, and mark the LWP as a zombie.  If the LWP is detached,
917 	 * mark it waiting for collection in the proc structure.  Note that
918 	 * before we can do that, we need to free any other dead, deatched
919 	 * LWP waiting to meet its maker.
920 	 */
921 	mutex_enter(p->p_lock);
922 	lwp_drainrefs(l);
923 
924 	if ((l->l_prflag & LPR_DETACHED) != 0) {
925 		while ((l2 = p->p_zomblwp) != NULL) {
926 			p->p_zomblwp = NULL;
927 			lwp_free(l2, false, false);/* releases proc mutex */
928 			mutex_enter(p->p_lock);
929 			l->l_refcnt++;
930 			lwp_drainrefs(l);
931 		}
932 		p->p_zomblwp = l;
933 	}
934 
935 	/*
936 	 * If we find a pending signal for the process and we have been
937 	 * asked to check for signals, then we lose: arrange to have
938 	 * all other LWPs in the process check for signals.
939 	 */
940 	if ((l->l_flag & LW_PENDSIG) != 0 &&
941 	    firstsig(&p->p_sigpend.sp_set) != 0) {
942 		LIST_FOREACH(l2, &p->p_lwps, l_sibling) {
943 			lwp_lock(l2);
944 			l2->l_flag |= LW_PENDSIG;
945 			lwp_unlock(l2);
946 		}
947 	}
948 
949 	lwp_lock(l);
950 	l->l_stat = LSZOMB;
951 	if (l->l_name != NULL)
952 		strcpy(l->l_name, "(zombie)");
953 	if (l->l_flag & LW_AFFINITY) {
954 		l->l_flag &= ~LW_AFFINITY;
955 	} else {
956 		KASSERT(l->l_affinity == NULL);
957 	}
958 	lwp_unlock(l);
959 	p->p_nrlwps--;
960 	cv_broadcast(&p->p_lwpcv);
961 	if (l->l_lwpctl != NULL)
962 		l->l_lwpctl->lc_curcpu = LWPCTL_CPU_EXITED;
963 	mutex_exit(p->p_lock);
964 
965 	/* Safe without lock since LWP is in zombie state */
966 	if (l->l_affinity) {
967 		kcpuset_unuse(l->l_affinity, NULL);
968 		l->l_affinity = NULL;
969 	}
970 
971 	/*
972 	 * We can no longer block.  At this point, lwp_free() may already
973 	 * be gunning for us.  On a multi-CPU system, we may be off p_lwps.
974 	 *
975 	 * Free MD LWP resources.
976 	 */
977 	cpu_lwp_free(l, 0);
978 
979 	if (current) {
980 		pmap_deactivate(l);
981 
982 		/*
983 		 * Release the kernel lock, and switch away into
984 		 * oblivion.
985 		 */
986 #ifdef notyet
987 		/* XXXSMP hold in lwp_userret() */
988 		KERNEL_UNLOCK_LAST(l);
989 #else
990 		KERNEL_UNLOCK_ALL(l, NULL);
991 #endif
992 		lwp_exit_switchaway(l);
993 	}
994 }
995 
996 /*
997  * Free a dead LWP's remaining resources.
998  *
999  * XXXLWP limits.
1000  */
1001 void
1002 lwp_free(struct lwp *l, bool recycle, bool last)
1003 {
1004 	struct proc *p = l->l_proc;
1005 	struct rusage *ru;
1006 	ksiginfoq_t kq;
1007 
1008 	KASSERT(l != curlwp);
1009 
1010 	/*
1011 	 * If this was not the last LWP in the process, then adjust
1012 	 * counters and unlock.
1013 	 */
1014 	if (!last) {
1015 		/*
1016 		 * Add the LWP's run time to the process' base value.
1017 		 * This needs to co-incide with coming off p_lwps.
1018 		 */
1019 		bintime_add(&p->p_rtime, &l->l_rtime);
1020 		p->p_pctcpu += l->l_pctcpu;
1021 		ru = &p->p_stats->p_ru;
1022 		ruadd(ru, &l->l_ru);
1023 		ru->ru_nvcsw += (l->l_ncsw - l->l_nivcsw);
1024 		ru->ru_nivcsw += l->l_nivcsw;
1025 		LIST_REMOVE(l, l_sibling);
1026 		p->p_nlwps--;
1027 		p->p_nzlwps--;
1028 		if ((l->l_prflag & LPR_DETACHED) != 0)
1029 			p->p_ndlwps--;
1030 
1031 		/*
1032 		 * Have any LWPs sleeping in lwp_wait() recheck for
1033 		 * deadlock.
1034 		 */
1035 		cv_broadcast(&p->p_lwpcv);
1036 		mutex_exit(p->p_lock);
1037 	}
1038 
1039 #ifdef MULTIPROCESSOR
1040 	/*
1041 	 * In the unlikely event that the LWP is still on the CPU,
1042 	 * then spin until it has switched away.  We need to release
1043 	 * all locks to avoid deadlock against interrupt handlers on
1044 	 * the target CPU.
1045 	 */
1046 	if ((l->l_pflag & LP_RUNNING) != 0 || l->l_cpu->ci_curlwp == l) {
1047 		int count;
1048 		(void)count; /* XXXgcc */
1049 		KERNEL_UNLOCK_ALL(curlwp, &count);
1050 		while ((l->l_pflag & LP_RUNNING) != 0 ||
1051 		    l->l_cpu->ci_curlwp == l)
1052 			SPINLOCK_BACKOFF_HOOK;
1053 		KERNEL_LOCK(count, curlwp);
1054 	}
1055 #endif
1056 
1057 	/*
1058 	 * Destroy the LWP's remaining signal information.
1059 	 */
1060 	ksiginfo_queue_init(&kq);
1061 	sigclear(&l->l_sigpend, NULL, &kq);
1062 	ksiginfo_queue_drain(&kq);
1063 	cv_destroy(&l->l_sigcv);
1064 
1065 	/*
1066 	 * Free the LWP's turnstile and the LWP structure itself unless the
1067 	 * caller wants to recycle them.  Also, free the scheduler specific
1068 	 * data.
1069 	 *
1070 	 * We can't return turnstile0 to the pool (it didn't come from it),
1071 	 * so if it comes up just drop it quietly and move on.
1072 	 *
1073 	 * We don't recycle the VM resources at this time.
1074 	 */
1075 	if (l->l_lwpctl != NULL)
1076 		lwp_ctl_free(l);
1077 
1078 	if (!recycle && l->l_ts != &turnstile0)
1079 		pool_cache_put(turnstile_cache, l->l_ts);
1080 	if (l->l_name != NULL)
1081 		kmem_free(l->l_name, MAXCOMLEN);
1082 
1083 	cpu_lwp_free2(l);
1084 	uvm_lwp_exit(l);
1085 
1086 	KASSERT(SLIST_EMPTY(&l->l_pi_lenders));
1087 	KASSERT(l->l_inheritedprio == -1);
1088 	KASSERT(l->l_blcnt == 0);
1089 	kdtrace_thread_dtor(NULL, l);
1090 	if (!recycle)
1091 		pool_cache_put(lwp_cache, l);
1092 }
1093 
1094 /*
1095  * Migrate the LWP to the another CPU.  Unlocks the LWP.
1096  */
1097 void
1098 lwp_migrate(lwp_t *l, struct cpu_info *tci)
1099 {
1100 	struct schedstate_percpu *tspc;
1101 	int lstat = l->l_stat;
1102 
1103 	KASSERT(lwp_locked(l, NULL));
1104 	KASSERT(tci != NULL);
1105 
1106 	/* If LWP is still on the CPU, it must be handled like LSONPROC */
1107 	if ((l->l_pflag & LP_RUNNING) != 0) {
1108 		lstat = LSONPROC;
1109 	}
1110 
1111 	/*
1112 	 * The destination CPU could be changed while previous migration
1113 	 * was not finished.
1114 	 */
1115 	if (l->l_target_cpu != NULL) {
1116 		l->l_target_cpu = tci;
1117 		lwp_unlock(l);
1118 		return;
1119 	}
1120 
1121 	/* Nothing to do if trying to migrate to the same CPU */
1122 	if (l->l_cpu == tci) {
1123 		lwp_unlock(l);
1124 		return;
1125 	}
1126 
1127 	KASSERT(l->l_target_cpu == NULL);
1128 	tspc = &tci->ci_schedstate;
1129 	switch (lstat) {
1130 	case LSRUN:
1131 		l->l_target_cpu = tci;
1132 		break;
1133 	case LSIDL:
1134 		l->l_cpu = tci;
1135 		lwp_unlock_to(l, tspc->spc_mutex);
1136 		return;
1137 	case LSSLEEP:
1138 		l->l_cpu = tci;
1139 		break;
1140 	case LSSTOP:
1141 	case LSSUSPENDED:
1142 		l->l_cpu = tci;
1143 		if (l->l_wchan == NULL) {
1144 			lwp_unlock_to(l, tspc->spc_lwplock);
1145 			return;
1146 		}
1147 		break;
1148 	case LSONPROC:
1149 		l->l_target_cpu = tci;
1150 		spc_lock(l->l_cpu);
1151 		cpu_need_resched(l->l_cpu, RESCHED_KPREEMPT);
1152 		spc_unlock(l->l_cpu);
1153 		break;
1154 	}
1155 	lwp_unlock(l);
1156 }
1157 
1158 /*
1159  * Find the LWP in the process.  Arguments may be zero, in such case,
1160  * the calling process and first LWP in the list will be used.
1161  * On success - returns proc locked.
1162  */
1163 struct lwp *
1164 lwp_find2(pid_t pid, lwpid_t lid)
1165 {
1166 	proc_t *p;
1167 	lwp_t *l;
1168 
1169 	/* Find the process. */
1170 	if (pid != 0) {
1171 		mutex_enter(proc_lock);
1172 		p = proc_find(pid);
1173 		if (p == NULL) {
1174 			mutex_exit(proc_lock);
1175 			return NULL;
1176 		}
1177 		mutex_enter(p->p_lock);
1178 		mutex_exit(proc_lock);
1179 	} else {
1180 		p = curlwp->l_proc;
1181 		mutex_enter(p->p_lock);
1182 	}
1183 	/* Find the thread. */
1184 	if (lid != 0) {
1185 		l = lwp_find(p, lid);
1186 	} else {
1187 		l = LIST_FIRST(&p->p_lwps);
1188 	}
1189 	if (l == NULL) {
1190 		mutex_exit(p->p_lock);
1191 	}
1192 	return l;
1193 }
1194 
1195 /*
1196  * Look up a live LWP within the specified process, and return it locked.
1197  *
1198  * Must be called with p->p_lock held.
1199  */
1200 struct lwp *
1201 lwp_find(struct proc *p, lwpid_t id)
1202 {
1203 	struct lwp *l;
1204 
1205 	KASSERT(mutex_owned(p->p_lock));
1206 
1207 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
1208 		if (l->l_lid == id)
1209 			break;
1210 	}
1211 
1212 	/*
1213 	 * No need to lock - all of these conditions will
1214 	 * be visible with the process level mutex held.
1215 	 */
1216 	if (l != NULL && (l->l_stat == LSIDL || l->l_stat == LSZOMB))
1217 		l = NULL;
1218 
1219 	return l;
1220 }
1221 
1222 /*
1223  * Update an LWP's cached credentials to mirror the process' master copy.
1224  *
1225  * This happens early in the syscall path, on user trap, and on LWP
1226  * creation.  A long-running LWP can also voluntarily choose to update
1227  * it's credentials by calling this routine.  This may be called from
1228  * LWP_CACHE_CREDS(), which checks l->l_cred != p->p_cred beforehand.
1229  */
1230 void
1231 lwp_update_creds(struct lwp *l)
1232 {
1233 	kauth_cred_t oc;
1234 	struct proc *p;
1235 
1236 	p = l->l_proc;
1237 	oc = l->l_cred;
1238 
1239 	mutex_enter(p->p_lock);
1240 	kauth_cred_hold(p->p_cred);
1241 	l->l_cred = p->p_cred;
1242 	l->l_prflag &= ~LPR_CRMOD;
1243 	mutex_exit(p->p_lock);
1244 	if (oc != NULL)
1245 		kauth_cred_free(oc);
1246 }
1247 
1248 /*
1249  * Verify that an LWP is locked, and optionally verify that the lock matches
1250  * one we specify.
1251  */
1252 int
1253 lwp_locked(struct lwp *l, kmutex_t *mtx)
1254 {
1255 	kmutex_t *cur = l->l_mutex;
1256 
1257 	return mutex_owned(cur) && (mtx == cur || mtx == NULL);
1258 }
1259 
1260 /*
1261  * Lend a new mutex to an LWP.  The old mutex must be held.
1262  */
1263 void
1264 lwp_setlock(struct lwp *l, kmutex_t *new)
1265 {
1266 
1267 	KASSERT(mutex_owned(l->l_mutex));
1268 
1269 	membar_exit();
1270 	l->l_mutex = new;
1271 }
1272 
1273 /*
1274  * Lend a new mutex to an LWP, and release the old mutex.  The old mutex
1275  * must be held.
1276  */
1277 void
1278 lwp_unlock_to(struct lwp *l, kmutex_t *new)
1279 {
1280 	kmutex_t *old;
1281 
1282 	KASSERT(lwp_locked(l, NULL));
1283 
1284 	old = l->l_mutex;
1285 	membar_exit();
1286 	l->l_mutex = new;
1287 	mutex_spin_exit(old);
1288 }
1289 
1290 int
1291 lwp_trylock(struct lwp *l)
1292 {
1293 	kmutex_t *old;
1294 
1295 	for (;;) {
1296 		if (!mutex_tryenter(old = l->l_mutex))
1297 			return 0;
1298 		if (__predict_true(l->l_mutex == old))
1299 			return 1;
1300 		mutex_spin_exit(old);
1301 	}
1302 }
1303 
1304 void
1305 lwp_unsleep(lwp_t *l, bool cleanup)
1306 {
1307 
1308 	KASSERT(mutex_owned(l->l_mutex));
1309 	(*l->l_syncobj->sobj_unsleep)(l, cleanup);
1310 }
1311 
1312 /*
1313  * Handle exceptions for mi_userret().  Called if a member of LW_USERRET is
1314  * set.
1315  */
1316 void
1317 lwp_userret(struct lwp *l)
1318 {
1319 	struct proc *p;
1320 	int sig;
1321 
1322 	KASSERT(l == curlwp);
1323 	KASSERT(l->l_stat == LSONPROC);
1324 	p = l->l_proc;
1325 
1326 #ifndef __HAVE_FAST_SOFTINTS
1327 	/* Run pending soft interrupts. */
1328 	if (l->l_cpu->ci_data.cpu_softints != 0)
1329 		softint_overlay();
1330 #endif
1331 
1332 #ifdef KERN_SA
1333 	/* Generate UNBLOCKED upcall if needed */
1334 	if (l->l_flag & LW_SA_BLOCKING) {
1335 		sa_unblock_userret(l);
1336 		/* NOTREACHED */
1337 	}
1338 #endif
1339 
1340 	/*
1341 	 * It should be safe to do this read unlocked on a multiprocessor
1342 	 * system..
1343 	 *
1344 	 * LW_SA_UPCALL will be handled after the while() loop, so don't
1345 	 * consider it now.
1346 	 */
1347 	while ((l->l_flag & (LW_USERRET & ~(LW_SA_UPCALL))) != 0) {
1348 		/*
1349 		 * Process pending signals first, unless the process
1350 		 * is dumping core or exiting, where we will instead
1351 		 * enter the LW_WSUSPEND case below.
1352 		 */
1353 		if ((l->l_flag & (LW_PENDSIG | LW_WCORE | LW_WEXIT)) ==
1354 		    LW_PENDSIG) {
1355 			mutex_enter(p->p_lock);
1356 			while ((sig = issignal(l)) != 0)
1357 				postsig(sig);
1358 			mutex_exit(p->p_lock);
1359 		}
1360 
1361 		/*
1362 		 * Core-dump or suspend pending.
1363 		 *
1364 		 * In case of core dump, suspend ourselves, so that the
1365 		 * kernel stack and therefore the userland registers saved
1366 		 * in the trapframe are around for coredump() to write them
1367 		 * out.  We issue a wakeup on p->p_lwpcv so that sigexit()
1368 		 * will write the core file out once all other LWPs are
1369 		 * suspended.
1370 		 */
1371 		if ((l->l_flag & LW_WSUSPEND) != 0) {
1372 			mutex_enter(p->p_lock);
1373 			p->p_nrlwps--;
1374 			cv_broadcast(&p->p_lwpcv);
1375 			lwp_lock(l);
1376 			l->l_stat = LSSUSPENDED;
1377 			lwp_unlock(l);
1378 			mutex_exit(p->p_lock);
1379 			lwp_lock(l);
1380 			mi_switch(l);
1381 		}
1382 
1383 		/* Process is exiting. */
1384 		if ((l->l_flag & LW_WEXIT) != 0) {
1385 			lwp_exit(l);
1386 			KASSERT(0);
1387 			/* NOTREACHED */
1388 		}
1389 
1390 		/* update lwpctl processor (for vfork child_return) */
1391 		if (l->l_flag & LW_LWPCTL) {
1392 			lwp_lock(l);
1393 			KASSERT(kpreempt_disabled());
1394 			l->l_lwpctl->lc_curcpu = (int)cpu_index(l->l_cpu);
1395 			l->l_lwpctl->lc_pctr++;
1396 			l->l_flag &= ~LW_LWPCTL;
1397 			lwp_unlock(l);
1398 		}
1399 	}
1400 
1401 #ifdef KERN_SA
1402 	/*
1403 	 * Timer events are handled specially.  We only try once to deliver
1404 	 * pending timer upcalls; if if fails, we can try again on the next
1405 	 * loop around.  If we need to re-enter lwp_userret(), MD code will
1406 	 * bounce us back here through the trap path after we return.
1407 	 */
1408 	if (p->p_timerpend)
1409 		timerupcall(l);
1410 	if (l->l_flag & LW_SA_UPCALL)
1411 		sa_upcall_userret(l);
1412 #endif /* KERN_SA */
1413 }
1414 
1415 /*
1416  * Force an LWP to enter the kernel, to take a trip through lwp_userret().
1417  */
1418 void
1419 lwp_need_userret(struct lwp *l)
1420 {
1421 	KASSERT(lwp_locked(l, NULL));
1422 
1423 	/*
1424 	 * Since the tests in lwp_userret() are done unlocked, make sure
1425 	 * that the condition will be seen before forcing the LWP to enter
1426 	 * kernel mode.
1427 	 */
1428 	membar_producer();
1429 	cpu_signotify(l);
1430 }
1431 
1432 /*
1433  * Add one reference to an LWP.  This will prevent the LWP from
1434  * exiting, thus keep the lwp structure and PCB around to inspect.
1435  */
1436 void
1437 lwp_addref(struct lwp *l)
1438 {
1439 
1440 	KASSERT(mutex_owned(l->l_proc->p_lock));
1441 	KASSERT(l->l_stat != LSZOMB);
1442 	KASSERT(l->l_refcnt != 0);
1443 
1444 	l->l_refcnt++;
1445 }
1446 
1447 /*
1448  * Remove one reference to an LWP.  If this is the last reference,
1449  * then we must finalize the LWP's death.
1450  */
1451 void
1452 lwp_delref(struct lwp *l)
1453 {
1454 	struct proc *p = l->l_proc;
1455 
1456 	mutex_enter(p->p_lock);
1457 	lwp_delref2(l);
1458 	mutex_exit(p->p_lock);
1459 }
1460 
1461 /*
1462  * Remove one reference to an LWP.  If this is the last reference,
1463  * then we must finalize the LWP's death.  The proc mutex is held
1464  * on entry.
1465  */
1466 void
1467 lwp_delref2(struct lwp *l)
1468 {
1469 	struct proc *p = l->l_proc;
1470 
1471 	KASSERT(mutex_owned(p->p_lock));
1472 	KASSERT(l->l_stat != LSZOMB);
1473 	KASSERT(l->l_refcnt > 0);
1474 	if (--l->l_refcnt == 0)
1475 		cv_broadcast(&p->p_lwpcv);
1476 }
1477 
1478 /*
1479  * Drain all references to the current LWP.
1480  */
1481 void
1482 lwp_drainrefs(struct lwp *l)
1483 {
1484 	struct proc *p = l->l_proc;
1485 
1486 	KASSERT(mutex_owned(p->p_lock));
1487 	KASSERT(l->l_refcnt != 0);
1488 
1489 	l->l_refcnt--;
1490 	while (l->l_refcnt != 0)
1491 		cv_wait(&p->p_lwpcv, p->p_lock);
1492 }
1493 
1494 /*
1495  * Return true if the specified LWP is 'alive'.  Only p->p_lock need
1496  * be held.
1497  */
1498 bool
1499 lwp_alive(lwp_t *l)
1500 {
1501 
1502 	KASSERT(mutex_owned(l->l_proc->p_lock));
1503 
1504 	switch (l->l_stat) {
1505 	case LSSLEEP:
1506 	case LSRUN:
1507 	case LSONPROC:
1508 	case LSSTOP:
1509 	case LSSUSPENDED:
1510 		return true;
1511 	default:
1512 		return false;
1513 	}
1514 }
1515 
1516 /*
1517  * Return first live LWP in the process.
1518  */
1519 lwp_t *
1520 lwp_find_first(proc_t *p)
1521 {
1522 	lwp_t *l;
1523 
1524 	KASSERT(mutex_owned(p->p_lock));
1525 
1526 	LIST_FOREACH(l, &p->p_lwps, l_sibling) {
1527 		if (lwp_alive(l)) {
1528 			return l;
1529 		}
1530 	}
1531 
1532 	return NULL;
1533 }
1534 
1535 /*
1536  * Allocate a new lwpctl structure for a user LWP.
1537  */
1538 int
1539 lwp_ctl_alloc(vaddr_t *uaddr)
1540 {
1541 	lcproc_t *lp;
1542 	u_int bit, i, offset;
1543 	struct uvm_object *uao;
1544 	int error;
1545 	lcpage_t *lcp;
1546 	proc_t *p;
1547 	lwp_t *l;
1548 
1549 	l = curlwp;
1550 	p = l->l_proc;
1551 
1552 	/* don't allow a vforked process to create lwp ctls */
1553 	if (p->p_lflag & PL_PPWAIT)
1554 		return EBUSY;
1555 
1556 	if (l->l_lcpage != NULL) {
1557 		lcp = l->l_lcpage;
1558 		*uaddr = lcp->lcp_uaddr + (vaddr_t)l->l_lwpctl - lcp->lcp_kaddr;
1559 		return 0;
1560 	}
1561 
1562 	/* First time around, allocate header structure for the process. */
1563 	if ((lp = p->p_lwpctl) == NULL) {
1564 		lp = kmem_alloc(sizeof(*lp), KM_SLEEP);
1565 		mutex_init(&lp->lp_lock, MUTEX_DEFAULT, IPL_NONE);
1566 		lp->lp_uao = NULL;
1567 		TAILQ_INIT(&lp->lp_pages);
1568 		mutex_enter(p->p_lock);
1569 		if (p->p_lwpctl == NULL) {
1570 			p->p_lwpctl = lp;
1571 			mutex_exit(p->p_lock);
1572 		} else {
1573 			mutex_exit(p->p_lock);
1574 			mutex_destroy(&lp->lp_lock);
1575 			kmem_free(lp, sizeof(*lp));
1576 			lp = p->p_lwpctl;
1577 		}
1578 	}
1579 
1580  	/*
1581  	 * Set up an anonymous memory region to hold the shared pages.
1582  	 * Map them into the process' address space.  The user vmspace
1583  	 * gets the first reference on the UAO.
1584  	 */
1585 	mutex_enter(&lp->lp_lock);
1586 	if (lp->lp_uao == NULL) {
1587 		lp->lp_uao = uao_create(LWPCTL_UAREA_SZ, 0);
1588 		lp->lp_cur = 0;
1589 		lp->lp_max = LWPCTL_UAREA_SZ;
1590 		lp->lp_uva = p->p_emul->e_vm_default_addr(p,
1591 		     (vaddr_t)p->p_vmspace->vm_daddr, LWPCTL_UAREA_SZ);
1592 		error = uvm_map(&p->p_vmspace->vm_map, &lp->lp_uva,
1593 		    LWPCTL_UAREA_SZ, lp->lp_uao, 0, 0, UVM_MAPFLAG(UVM_PROT_RW,
1594 		    UVM_PROT_RW, UVM_INH_NONE, UVM_ADV_NORMAL, 0));
1595 		if (error != 0) {
1596 			uao_detach(lp->lp_uao);
1597 			lp->lp_uao = NULL;
1598 			mutex_exit(&lp->lp_lock);
1599 			return error;
1600 		}
1601 	}
1602 
1603 	/* Get a free block and allocate for this LWP. */
1604 	TAILQ_FOREACH(lcp, &lp->lp_pages, lcp_chain) {
1605 		if (lcp->lcp_nfree != 0)
1606 			break;
1607 	}
1608 	if (lcp == NULL) {
1609 		/* Nothing available - try to set up a free page. */
1610 		if (lp->lp_cur == lp->lp_max) {
1611 			mutex_exit(&lp->lp_lock);
1612 			return ENOMEM;
1613 		}
1614 		lcp = kmem_alloc(LWPCTL_LCPAGE_SZ, KM_SLEEP);
1615 		if (lcp == NULL) {
1616 			mutex_exit(&lp->lp_lock);
1617 			return ENOMEM;
1618 		}
1619 		/*
1620 		 * Wire the next page down in kernel space.  Since this
1621 		 * is a new mapping, we must add a reference.
1622 		 */
1623 		uao = lp->lp_uao;
1624 		(*uao->pgops->pgo_reference)(uao);
1625 		lcp->lcp_kaddr = vm_map_min(kernel_map);
1626 		error = uvm_map(kernel_map, &lcp->lcp_kaddr, PAGE_SIZE,
1627 		    uao, lp->lp_cur, PAGE_SIZE,
1628 		    UVM_MAPFLAG(UVM_PROT_RW, UVM_PROT_RW,
1629 		    UVM_INH_NONE, UVM_ADV_RANDOM, 0));
1630 		if (error != 0) {
1631 			mutex_exit(&lp->lp_lock);
1632 			kmem_free(lcp, LWPCTL_LCPAGE_SZ);
1633 			(*uao->pgops->pgo_detach)(uao);
1634 			return error;
1635 		}
1636 		error = uvm_map_pageable(kernel_map, lcp->lcp_kaddr,
1637 		    lcp->lcp_kaddr + PAGE_SIZE, FALSE, 0);
1638 		if (error != 0) {
1639 			mutex_exit(&lp->lp_lock);
1640 			uvm_unmap(kernel_map, lcp->lcp_kaddr,
1641 			    lcp->lcp_kaddr + PAGE_SIZE);
1642 			kmem_free(lcp, LWPCTL_LCPAGE_SZ);
1643 			return error;
1644 		}
1645 		/* Prepare the page descriptor and link into the list. */
1646 		lcp->lcp_uaddr = lp->lp_uva + lp->lp_cur;
1647 		lp->lp_cur += PAGE_SIZE;
1648 		lcp->lcp_nfree = LWPCTL_PER_PAGE;
1649 		lcp->lcp_rotor = 0;
1650 		memset(lcp->lcp_bitmap, 0xff, LWPCTL_BITMAP_SZ);
1651 		TAILQ_INSERT_HEAD(&lp->lp_pages, lcp, lcp_chain);
1652 	}
1653 	for (i = lcp->lcp_rotor; lcp->lcp_bitmap[i] == 0;) {
1654 		if (++i >= LWPCTL_BITMAP_ENTRIES)
1655 			i = 0;
1656 	}
1657 	bit = ffs(lcp->lcp_bitmap[i]) - 1;
1658 	lcp->lcp_bitmap[i] ^= (1 << bit);
1659 	lcp->lcp_rotor = i;
1660 	lcp->lcp_nfree--;
1661 	l->l_lcpage = lcp;
1662 	offset = (i << 5) + bit;
1663 	l->l_lwpctl = (lwpctl_t *)lcp->lcp_kaddr + offset;
1664 	*uaddr = lcp->lcp_uaddr + offset * sizeof(lwpctl_t);
1665 	mutex_exit(&lp->lp_lock);
1666 
1667 	KPREEMPT_DISABLE(l);
1668 	l->l_lwpctl->lc_curcpu = (int)curcpu()->ci_data.cpu_index;
1669 	KPREEMPT_ENABLE(l);
1670 
1671 	return 0;
1672 }
1673 
1674 /*
1675  * Free an lwpctl structure back to the per-process list.
1676  */
1677 void
1678 lwp_ctl_free(lwp_t *l)
1679 {
1680 	struct proc *p = l->l_proc;
1681 	lcproc_t *lp;
1682 	lcpage_t *lcp;
1683 	u_int map, offset;
1684 
1685 	/* don't free a lwp context we borrowed for vfork */
1686 	if (p->p_lflag & PL_PPWAIT) {
1687 		l->l_lwpctl = NULL;
1688 		return;
1689 	}
1690 
1691 	lp = p->p_lwpctl;
1692 	KASSERT(lp != NULL);
1693 
1694 	lcp = l->l_lcpage;
1695 	offset = (u_int)((lwpctl_t *)l->l_lwpctl - (lwpctl_t *)lcp->lcp_kaddr);
1696 	KASSERT(offset < LWPCTL_PER_PAGE);
1697 
1698 	mutex_enter(&lp->lp_lock);
1699 	lcp->lcp_nfree++;
1700 	map = offset >> 5;
1701 	lcp->lcp_bitmap[map] |= (1 << (offset & 31));
1702 	if (lcp->lcp_bitmap[lcp->lcp_rotor] == 0)
1703 		lcp->lcp_rotor = map;
1704 	if (TAILQ_FIRST(&lp->lp_pages)->lcp_nfree == 0) {
1705 		TAILQ_REMOVE(&lp->lp_pages, lcp, lcp_chain);
1706 		TAILQ_INSERT_HEAD(&lp->lp_pages, lcp, lcp_chain);
1707 	}
1708 	mutex_exit(&lp->lp_lock);
1709 }
1710 
1711 /*
1712  * Process is exiting; tear down lwpctl state.  This can only be safely
1713  * called by the last LWP in the process.
1714  */
1715 void
1716 lwp_ctl_exit(void)
1717 {
1718 	lcpage_t *lcp, *next;
1719 	lcproc_t *lp;
1720 	proc_t *p;
1721 	lwp_t *l;
1722 
1723 	l = curlwp;
1724 	l->l_lwpctl = NULL;
1725 	l->l_lcpage = NULL;
1726 	p = l->l_proc;
1727 	lp = p->p_lwpctl;
1728 
1729 	KASSERT(lp != NULL);
1730 	KASSERT(p->p_nlwps == 1);
1731 
1732 	for (lcp = TAILQ_FIRST(&lp->lp_pages); lcp != NULL; lcp = next) {
1733 		next = TAILQ_NEXT(lcp, lcp_chain);
1734 		uvm_unmap(kernel_map, lcp->lcp_kaddr,
1735 		    lcp->lcp_kaddr + PAGE_SIZE);
1736 		kmem_free(lcp, LWPCTL_LCPAGE_SZ);
1737 	}
1738 
1739 	if (lp->lp_uao != NULL) {
1740 		uvm_unmap(&p->p_vmspace->vm_map, lp->lp_uva,
1741 		    lp->lp_uva + LWPCTL_UAREA_SZ);
1742 	}
1743 
1744 	mutex_destroy(&lp->lp_lock);
1745 	kmem_free(lp, sizeof(*lp));
1746 	p->p_lwpctl = NULL;
1747 }
1748 
1749 /*
1750  * Return the current LWP's "preemption counter".  Used to detect
1751  * preemption across operations that can tolerate preemption without
1752  * crashing, but which may generate incorrect results if preempted.
1753  */
1754 uint64_t
1755 lwp_pctr(void)
1756 {
1757 
1758 	return curlwp->l_ncsw;
1759 }
1760 
1761 /*
1762  * Set an LWP's private data pointer.
1763  */
1764 int
1765 lwp_setprivate(struct lwp *l, void *ptr)
1766 {
1767 	int error = 0;
1768 
1769 	l->l_private = ptr;
1770 #ifdef __HAVE_CPU_LWP_SETPRIVATE
1771 	error = cpu_lwp_setprivate(l, ptr);
1772 #endif
1773 	return error;
1774 }
1775 
1776 #if defined(DDB)
1777 #include <machine/pcb.h>
1778 
1779 void
1780 lwp_whatis(uintptr_t addr, void (*pr)(const char *, ...))
1781 {
1782 	lwp_t *l;
1783 
1784 	LIST_FOREACH(l, &alllwp, l_list) {
1785 		uintptr_t stack = (uintptr_t)KSTACK_LOWEST_ADDR(l);
1786 
1787 		if (addr < stack || stack + KSTACK_SIZE <= addr) {
1788 			continue;
1789 		}
1790 		(*pr)("%p is %p+%zu, LWP %p's stack\n",
1791 		    (void *)addr, (void *)stack,
1792 		    (size_t)(addr - stack), l);
1793 	}
1794 }
1795 #endif /* defined(DDB) */
1796