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