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