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