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