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