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