1 /* $NetBSD: kern_lwp.c,v 1.128 2009/03/03 21:55:06 rmind Exp $ */
4 * Copyright (c) 2001, 2006, 2007, 2008, 2009 The NetBSD Foundation, Inc.
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Nathan J. Williams, and Andrew Doran.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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.
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.
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.
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
55 * On processor: the LWP is executing on a CPU, either in the
56 * kernel or in user space.
60 * Runnable: the LWP is parked on a run queue, and may soon be
61 * chosen to run by an idle processor, or by a processor that
62 * has been asked to preempt a currently runnning but lower
63 * priority LWP. If the LWP is not swapped in (LW_INMEM == 0)
64 * then the LWP is not on a run queue, but may be soon.
68 * Idle: the LWP has been created but has not yet executed,
69 * or it has ceased executing a unit of work and is waiting
70 * to be started again.
74 * Suspended: the LWP has had its execution suspended by
75 * another LWP in the same process using the _lwp_suspend()
76 * system call. User-level LWPs also enter the suspended
77 * state when the system is shutting down.
79 * The second set represent a "statement of intent" on behalf of the
80 * LWP. The LWP may in fact be executing on a processor, may be
81 * sleeping or idle. It is expected to take the necessary action to
82 * stop executing or become "running" again within a short timeframe.
83 * The LP_RUNNING flag in lwp::l_pflag indicates that an LWP is running.
84 * Importantly, it indicates that its state is tied to a CPU.
88 * Dead or dying: the LWP has released most of its resources
89 * and is about to switch away into oblivion, or has already
90 * switched away. When it switches away, its few remaining
91 * resources can be collected.
95 * Sleeping: the LWP has entered itself onto a sleep queue, and
96 * has switched away or will switch away shortly to allow other
97 * LWPs to run on the CPU.
101 * Stopped: the LWP has been stopped as a result of a job
102 * control signal, or as a result of the ptrace() interface.
104 * Stopped LWPs may run briefly within the kernel to handle
105 * signals that they receive, but will not return to user space
106 * until their process' state is changed away from stopped.
108 * Single LWPs within a process can not be set stopped
109 * selectively: all actions that can stop or continue LWPs
110 * occur at the process level.
114 * Note that the LSSTOP state may only be set when returning to
115 * user space in userret(), or when sleeping interruptably. The
116 * LSSUSPENDED state may only be set in userret(). Before setting
117 * those states, we try to ensure that the LWPs will release all
118 * locks that they hold, and at a minimum try to ensure that the
119 * LWP can be set runnable again by a signal.
121 * LWPs may transition states in the following ways:
123 * RUN -------> ONPROC ONPROC -----> RUN
128 * > IDL (special cases)
130 * STOPPED ---> RUN SUSPENDED --> RUN
133 * SLEEP -----> ONPROC IDL --------> RUN
135 * > STOPPED > STOPPED
136 * > ONPROC (special cases)
138 * Some state transitions are only possible with kernel threads (eg
139 * ONPROC -> IDL) and happen under tightly controlled circumstances
140 * free of unwanted side effects.
144 * Migration of threads from one CPU to another could be performed
145 * internally by the scheduler via sched_takecpu() or sched_catchlwp()
146 * functions. The universal lwp_migrate() function should be used for
147 * any other cases. Subsystems in the kernel must be aware that CPU
148 * of LWP may change, while it is not locked.
152 * The majority of fields in 'struct lwp' are covered by a single,
153 * general spin lock pointed to by lwp::l_mutex. The locks covering
154 * each field are documented in sys/lwp.h.
156 * State transitions must be made with the LWP's general lock held,
157 * and may cause the LWP's lock pointer to change. Manipulation of
158 * the general lock is not performed directly, but through calls to
159 * lwp_lock(), lwp_relock() and similar.
161 * States and their associated locks:
165 * Always covered by spc_lwplock, which protects running LWPs.
166 * This is a per-CPU lock and matches lwp::l_cpu.
170 * Always covered by spc_mutex, which protects the run queues.
171 * This is a per-CPU lock and matches lwp::l_cpu.
175 * Covered by a lock associated with the sleep queue that the
176 * LWP resides on. Matches lwp::l_sleepq::sq_mutex.
178 * LSSTOP, LSSUSPENDED:
180 * If the LWP was previously sleeping (l_wchan != NULL), then
181 * l_mutex references the sleep queue lock. If the LWP was
182 * runnable or on the CPU when halted, or has been removed from
183 * the sleep queue since halted, then the lock is spc_lwplock.
185 * The lock order is as follows:
187 * spc::spc_lwplock ->
188 * sleeptab::st_mutex ->
189 * tschain_t::tc_mutex ->
192 * Each process has an scheduler state lock (proc::p_lock), and a
193 * number of counters on LWPs and their states: p_nzlwps, p_nrlwps, and
194 * so on. When an LWP is to be entered into or removed from one of the
195 * following states, p_lock must be held and the process wide counters
198 * LSIDL, LSZOMB, LSSTOP, LSSUSPENDED
200 * (But not always for kernel threads. There are some special cases
201 * as mentioned above. See kern_softint.c.)
203 * Note that an LWP is considered running or likely to run soon if in
204 * one of the following states. This affects the value of p_nrlwps:
206 * LSRUN, LSONPROC, LSSLEEP
208 * p_lock does not need to be held when transitioning among these
209 * three states, hence p_lock is rarely taken for state transitions.
212 #include <sys/cdefs.h>
213 __KERNEL_RCSID(0, "$NetBSD: kern_lwp.c,v 1.128 2009/03/03 21:55:06 rmind Exp $");
216 #include "opt_lockdebug.h"
219 #define _LWP_API_PRIVATE
221 #include <sys/param.h>
222 #include <sys/systm.h>
224 #include <sys/pool.h>
225 #include <sys/proc.h>
227 #include <sys/savar.h>
228 #include <sys/syscallargs.h>
229 #include <sys/syscall_stats.h>
230 #include <sys/kauth.h>
231 #include <sys/sleepq.h>
232 #include <sys/user.h>
233 #include <sys/lockdebug.h>
234 #include <sys/kmem.h>
235 #include <sys/pset.h>
236 #include <sys/intr.h>
237 #include <sys/lwpctl.h>
238 #include <sys/atomic.h>
240 #include <uvm/uvm_extern.h>
241 #include <uvm/uvm_object.h>
243 struct lwplist alllwp
= LIST_HEAD_INITIALIZER(alllwp
);
245 POOL_INIT(lwp_uc_pool
, sizeof(ucontext_t
), 0, 0, 0, "lwpucpl",
246 &pool_allocator_nointr
, IPL_NONE
);
248 static pool_cache_t lwp_cache
;
249 static specificdata_domain_t lwp_specificdata_domain
;
255 lwp_specificdata_domain
= specificdata_domain_create();
256 KASSERT(lwp_specificdata_domain
!= NULL
);
258 lwp_cache
= pool_cache_init(sizeof(lwp_t
), MIN_LWP_ALIGNMENT
, 0, 0,
259 "lwppl", NULL
, IPL_NONE
, NULL
, NULL
, NULL
);
265 * Must be called with p_lock held, and the LWP locked. Will unlock the
269 lwp_suspend(struct lwp
*curl
, struct lwp
*t
)
273 KASSERT(mutex_owned(t
->l_proc
->p_lock
));
274 KASSERT(lwp_locked(t
, NULL
));
276 KASSERT(curl
!= t
|| curl
->l_stat
== LSONPROC
);
279 * If the current LWP has been told to exit, we must not suspend anyone
280 * else or deadlock could occur. We won't return to userspace.
282 if ((curl
->l_flag
& (LW_WEXIT
| LW_WCORE
)) != 0) {
292 t
->l_flag
|= LW_WSUSPEND
;
298 t
->l_flag
|= LW_WSUSPEND
;
301 * Kick the LWP and try to get it to the kernel boundary
302 * so that it will release any locks that it holds.
303 * setrunnable() will release the lock.
305 if ((t
->l_flag
& LW_SINTR
) != 0)
316 t
->l_flag
|= LW_WSUSPEND
;
322 error
= EINTR
; /* It's what Solaris does..... */
331 * Restart a suspended LWP.
333 * Must be called with p_lock held, and the LWP locked. Will unlock the
337 lwp_continue(struct lwp
*l
)
340 KASSERT(mutex_owned(l
->l_proc
->p_lock
));
341 KASSERT(lwp_locked(l
, NULL
));
343 /* If rebooting or not suspended, then just bail out. */
344 if ((l
->l_flag
& LW_WREBOOT
) != 0) {
349 l
->l_flag
&= ~LW_WSUSPEND
;
351 if (l
->l_stat
!= LSSUSPENDED
) {
356 /* setrunnable() will release the lock. */
361 * Wait for an LWP within the current process to exit. If 'lid' is
362 * non-zero, we are waiting for a specific LWP.
364 * Must be called with p->p_lock held.
367 lwp_wait1(struct lwp
*l
, lwpid_t lid
, lwpid_t
*departed
, int flags
)
369 struct proc
*p
= l
->l_proc
;
375 KASSERT(mutex_owned(p
->p_lock
));
378 l
->l_waitingfor
= lid
;
380 exiting
= ((flags
& LWPWAIT_EXITCONTROL
) != 0);
384 * Avoid a race between exit1() and sigexit(): if the
385 * process is dumping core, then we need to bail out: call
386 * into lwp_userret() where we will be suspended until the
389 if ((p
->p_sflag
& PS_WCORE
) != 0) {
390 mutex_exit(p
->p_lock
);
399 * First off, drain any detached LWP that is waiting to be
402 while ((l2
= p
->p_zomblwp
) != NULL
) {
404 lwp_free(l2
, false, false);/* releases proc mutex */
405 mutex_enter(p
->p_lock
);
409 * Now look for an LWP to collect. If the whole process is
410 * exiting, count detached LWPs as eligible to be collected,
411 * but don't drain them here.
415 LIST_FOREACH(l2
, &p
->p_lwps
, l_sibling
) {
417 * If a specific wait and the target is waiting on
418 * us, then avoid deadlock. This also traps LWPs
419 * that try to wait on themselves.
421 * Note that this does not handle more complicated
422 * cycles, like: t1 -> t2 -> t3 -> t1. The process
423 * can still be killed so it is not a major problem.
425 if (l2
->l_lid
== lid
&& l2
->l_waitingfor
== curlid
) {
431 if ((l2
->l_prflag
& LPR_DETACHED
) != 0) {
436 if (l2
->l_lid
!= lid
)
439 * Mark this LWP as the first waiter, if there
442 if (l2
->l_waiter
== 0)
443 l2
->l_waiter
= curlid
;
444 } else if (l2
->l_waiter
!= 0) {
446 * It already has a waiter - so don't
447 * collect it. If the waiter doesn't
448 * grab it we'll get another chance
456 /* No need to lock the LWP in order to see LSZOMB. */
457 if (l2
->l_stat
!= LSZOMB
)
461 * We're no longer waiting. Reset the "first waiter"
462 * pointer on the target, in case it was us.
468 *departed
= l2
->l_lid
;
469 sched_lwp_collect(l2
);
471 /* lwp_free() releases the proc lock. */
472 lwp_free(l2
, false, false);
473 mutex_enter(p
->p_lock
);
485 * The kernel is careful to ensure that it can not deadlock
486 * when exiting - just keep waiting.
489 KASSERT(p
->p_nlwps
> 1);
490 cv_wait(&p
->p_lwpcv
, p
->p_lock
);
495 * If all other LWPs are waiting for exits or suspends
496 * and the supply of zombies and potential zombies is
497 * exhausted, then we are about to deadlock.
499 * If the process is exiting (and this LWP is not the one
500 * that is coordinating the exit) then bail out now.
502 if ((p
->p_sflag
& PS_WEXIT
) != 0 ||
503 p
->p_nrlwps
+ p
->p_nzlwps
- p
->p_ndlwps
<= p
->p_nlwpwait
) {
509 * Sit around and wait for something to happen. We'll be
510 * awoken if any of the conditions examined change: if an
511 * LWP exits, is collected, or is detached.
513 if ((error
= cv_wait_sig(&p
->p_lwpcv
, p
->p_lock
)) != 0)
518 * We didn't find any LWPs to collect, we may have received a
519 * signal, or some other condition has caused us to bail out.
521 * If waiting on a specific LWP, clear the waiters marker: some
522 * other LWP may want it. Then, kick all the remaining waiters
523 * so that they can re-check for zombies and for deadlock.
526 LIST_FOREACH(l2
, &p
->p_lwps
, l_sibling
) {
527 if (l2
->l_lid
== lid
) {
528 if (l2
->l_waiter
== curlid
)
536 cv_broadcast(&p
->p_lwpcv
);
542 * Create a new LWP within process 'p2', using LWP 'l1' as a template.
543 * The new LWP is created in state LSIDL and must be set running,
544 * suspended, or stopped by the caller.
547 lwp_create(lwp_t
*l1
, proc_t
*p2
, vaddr_t uaddr
, bool inmem
, int flags
,
548 void *stack
, size_t stacksize
, void (*func
)(void *), void *arg
,
549 lwp_t
**rnewlwpp
, int sclass
)
551 struct lwp
*l2
, *isfree
;
554 KASSERT(l1
== curlwp
|| l1
->l_proc
== &proc0
);
557 * First off, reap any detached LWP waiting to be collected.
558 * We can re-use its LWP structure and turnstile.
561 if (p2
->p_zomblwp
!= NULL
) {
562 mutex_enter(p2
->p_lock
);
563 if ((isfree
= p2
->p_zomblwp
) != NULL
) {
564 p2
->p_zomblwp
= NULL
;
565 lwp_free(isfree
, true, false);/* releases proc mutex */
567 mutex_exit(p2
->p_lock
);
569 if (isfree
== NULL
) {
570 l2
= pool_cache_get(lwp_cache
, PR_WAITOK
);
571 memset(l2
, 0, sizeof(*l2
));
572 l2
->l_ts
= pool_cache_get(turnstile_cache
, PR_WAITOK
);
573 SLIST_INIT(&l2
->l_pi_lenders
);
577 KASSERT(l2
->l_inheritedprio
== -1);
578 KASSERT(SLIST_EMPTY(&l2
->l_pi_lenders
));
579 memset(l2
, 0, sizeof(*l2
));
586 l2
->l_class
= sclass
;
589 * If vfork(), we want the LWP to run fast and on the same CPU
590 * as its parent, so that it can reuse the VM context and cache
591 * footprint on the local CPU.
593 l2
->l_kpriority
= ((flags
& LWP_VFORK
) ? true : false);
594 l2
->l_kpribase
= PRI_KERNEL
;
595 l2
->l_priority
= l1
->l_priority
;
596 l2
->l_inheritedprio
= -1;
597 l2
->l_flag
= inmem
? LW_INMEM
: 0;
598 l2
->l_pflag
= LP_MPSAFE
;
600 TAILQ_INIT(&l2
->l_ld_locks
);
602 if (p2
->p_flag
& PK_SYSTEM
) {
603 /* Mark it as a system LWP and not a candidate for swapping */
604 l2
->l_flag
|= LW_SYSTEM
;
608 l2
->l_mutex
= l1
->l_cpu
->ci_schedstate
.spc_mutex
;
609 l2
->l_cpu
= l1
->l_cpu
;
612 lwp_initspecific(l2
);
613 sched_lwp_fork(l1
, l2
);
614 lwp_update_creds(l2
);
615 callout_init(&l2
->l_timeout_ch
, CALLOUT_MPSAFE
);
616 callout_setfunc(&l2
->l_timeout_ch
, sleepq_timeout
, l2
);
617 mutex_init(&l2
->l_swaplock
, MUTEX_DEFAULT
, IPL_NONE
);
618 cv_init(&l2
->l_sigcv
, "sigwait");
619 l2
->l_syncobj
= &sched_syncobj
;
621 if (rnewlwpp
!= NULL
)
624 l2
->l_addr
= UAREA_TO_USER(uaddr
);
625 uvm_lwp_fork(l1
, l2
, stack
, stacksize
, func
,
626 (arg
!= NULL
) ? arg
: l2
);
628 mutex_enter(p2
->p_lock
);
630 if ((flags
& LWP_DETACHED
) != 0) {
631 l2
->l_prflag
= LPR_DETACHED
;
636 l2
->l_sigmask
= l1
->l_sigmask
;
637 CIRCLEQ_INIT(&l2
->l_sigpend
.sp_info
);
638 sigemptyset(&l2
->l_sigpend
.sp_set
);
641 if (p2
->p_nlwpid
== 0)
643 l2
->l_lid
= p2
->p_nlwpid
;
644 LIST_INSERT_HEAD(&p2
->p_lwps
, l2
, l_sibling
);
647 if ((p2
->p_flag
& PK_SYSTEM
) == 0) {
648 /* Inherit an affinity */
649 if (l1
->l_flag
& LW_AFFINITY
) {
651 * Note that we hold the state lock while inheriting
652 * the affinity to avoid race with sched_setaffinity().
655 if (l1
->l_flag
& LW_AFFINITY
) {
656 kcpuset_use(l1
->l_affinity
);
657 l2
->l_affinity
= l1
->l_affinity
;
658 l2
->l_flag
|= LW_AFFINITY
;
663 /* Inherit a processor-set */
664 l2
->l_psid
= l1
->l_psid
;
665 /* Look for a CPU to start */
666 l2
->l_cpu
= sched_takecpu(l2
);
667 lwp_unlock_to(l2
, l2
->l_cpu
->ci_schedstate
.spc_mutex
);
669 mutex_exit(p2
->p_lock
);
671 mutex_enter(proc_lock
);
672 LIST_INSERT_HEAD(&alllwp
, l2
, l_list
);
673 mutex_exit(proc_lock
);
675 SYSCALL_TIME_LWP_INIT(l2
);
677 if (p2
->p_emul
->e_lwp_fork
)
678 (*p2
->p_emul
->e_lwp_fork
)(l1
, l2
);
684 * Called by MD code when a new LWP begins execution. Must be called
685 * with the previous LWP locked (so at splsched), or if there is no
686 * previous LWP, at splsched.
689 lwp_startup(struct lwp
*prev
, struct lwp
*new)
692 KASSERT(kpreempt_disabled());
695 * Normalize the count of the spin-mutexes, it was
696 * increased in mi_switch(). Unmark the state of
697 * context switch - it is finished for previous LWP.
699 curcpu()->ci_mtx_count
++;
701 prev
->l_ctxswtch
= 0;
703 KPREEMPT_DISABLE(new);
706 LOCKDEBUG_BARRIER(NULL
, 0);
707 KPREEMPT_ENABLE(new);
708 if ((new->l_pflag
& LP_MPSAFE
) == 0) {
717 lwp_exit(struct lwp
*l
)
719 struct proc
*p
= l
->l_proc
;
723 current
= (l
== curlwp
);
725 KASSERT(current
|| (l
->l_stat
== LSIDL
&& l
->l_target_cpu
== NULL
));
728 * Verify that we hold no locks other than the kernel lock.
730 LOCKDEBUG_BARRIER(&kernel_lock
, 0);
733 * If we are the last live LWP in a process, we need to exit the
734 * entire process. We do so with an exit status of zero, because
735 * it's a "controlled" exit, and because that's what Solaris does.
737 * We are not quite a zombie yet, but for accounting purposes we
738 * must increment the count of zombies here.
740 * Note: the last LWP's specificdata will be deleted here.
742 mutex_enter(p
->p_lock
);
743 if (p
->p_nlwps
- p
->p_nzlwps
== 1) {
744 KASSERT(current
== true);
745 /* XXXSMP kernel_lock not held */
750 mutex_exit(p
->p_lock
);
752 if (p
->p_emul
->e_lwp_exit
)
753 (*p
->p_emul
->e_lwp_exit
)(l
);
755 /* Delete the specificdata while it's still safe to sleep. */
756 specificdata_fini(lwp_specificdata_domain
, &l
->l_specdataref
);
759 * Release our cached credentials.
761 kauth_cred_free(l
->l_cred
);
762 callout_destroy(&l
->l_timeout_ch
);
765 * While we can still block, mark the LWP as unswappable to
766 * prevent conflicts with the with the swapper.
772 * Remove the LWP from the global list.
774 mutex_enter(proc_lock
);
775 LIST_REMOVE(l
, l_list
);
776 mutex_exit(proc_lock
);
779 * Get rid of all references to the LWP that others (e.g. procfs)
780 * may have, and mark the LWP as a zombie. If the LWP is detached,
781 * mark it waiting for collection in the proc structure. Note that
782 * before we can do that, we need to free any other dead, deatched
783 * LWP waiting to meet its maker.
785 mutex_enter(p
->p_lock
);
788 if ((l
->l_prflag
& LPR_DETACHED
) != 0) {
789 while ((l2
= p
->p_zomblwp
) != NULL
) {
791 lwp_free(l2
, false, false);/* releases proc mutex */
792 mutex_enter(p
->p_lock
);
800 * If we find a pending signal for the process and we have been
801 * asked to check for signals, then we loose: arrange to have
802 * all other LWPs in the process check for signals.
804 if ((l
->l_flag
& LW_PENDSIG
) != 0 &&
805 firstsig(&p
->p_sigpend
.sp_set
) != 0) {
806 LIST_FOREACH(l2
, &p
->p_lwps
, l_sibling
) {
808 l2
->l_flag
|= LW_PENDSIG
;
815 if (l
->l_name
!= NULL
)
816 strcpy(l
->l_name
, "(zombie)");
817 if (l
->l_flag
& LW_AFFINITY
) {
818 l
->l_flag
&= ~LW_AFFINITY
;
820 KASSERT(l
->l_affinity
== NULL
);
824 cv_broadcast(&p
->p_lwpcv
);
825 if (l
->l_lwpctl
!= NULL
)
826 l
->l_lwpctl
->lc_curcpu
= LWPCTL_CPU_EXITED
;
827 mutex_exit(p
->p_lock
);
829 /* Safe without lock since LWP is in zombie state */
831 kcpuset_unuse(l
->l_affinity
, NULL
);
832 l
->l_affinity
= NULL
;
836 * We can no longer block. At this point, lwp_free() may already
837 * be gunning for us. On a multi-CPU system, we may be off p_lwps.
839 * Free MD LWP resources.
841 #ifndef __NO_CPU_LWP_FREE
849 * Release the kernel lock, and switch away into
853 /* XXXSMP hold in lwp_userret() */
854 KERNEL_UNLOCK_LAST(l
);
856 KERNEL_UNLOCK_ALL(l
, NULL
);
858 lwp_exit_switchaway(l
);
863 * Free a dead LWP's remaining resources.
868 lwp_free(struct lwp
*l
, bool recycle
, bool last
)
870 struct proc
*p
= l
->l_proc
;
874 KASSERT(l
!= curlwp
);
877 * If this was not the last LWP in the process, then adjust
878 * counters and unlock.
882 * Add the LWP's run time to the process' base value.
883 * This needs to co-incide with coming off p_lwps.
885 bintime_add(&p
->p_rtime
, &l
->l_rtime
);
886 p
->p_pctcpu
+= l
->l_pctcpu
;
887 ru
= &p
->p_stats
->p_ru
;
889 ru
->ru_nvcsw
+= (l
->l_ncsw
- l
->l_nivcsw
);
890 ru
->ru_nivcsw
+= l
->l_nivcsw
;
891 LIST_REMOVE(l
, l_sibling
);
894 if ((l
->l_prflag
& LPR_DETACHED
) != 0)
898 * Have any LWPs sleeping in lwp_wait() recheck for
901 cv_broadcast(&p
->p_lwpcv
);
902 mutex_exit(p
->p_lock
);
905 #ifdef MULTIPROCESSOR
907 * In the unlikely event that the LWP is still on the CPU,
908 * then spin until it has switched away. We need to release
909 * all locks to avoid deadlock against interrupt handlers on
912 if ((l
->l_pflag
& LP_RUNNING
) != 0 || l
->l_cpu
->ci_curlwp
== l
) {
914 (void)count
; /* XXXgcc */
915 KERNEL_UNLOCK_ALL(curlwp
, &count
);
916 while ((l
->l_pflag
& LP_RUNNING
) != 0 ||
917 l
->l_cpu
->ci_curlwp
== l
)
918 SPINLOCK_BACKOFF_HOOK
;
919 KERNEL_LOCK(count
, curlwp
);
924 * Destroy the LWP's remaining signal information.
926 ksiginfo_queue_init(&kq
);
927 sigclear(&l
->l_sigpend
, NULL
, &kq
);
928 ksiginfo_queue_drain(&kq
);
929 cv_destroy(&l
->l_sigcv
);
930 mutex_destroy(&l
->l_swaplock
);
933 * Free the LWP's turnstile and the LWP structure itself unless the
934 * caller wants to recycle them. Also, free the scheduler specific
937 * We can't return turnstile0 to the pool (it didn't come from it),
938 * so if it comes up just drop it quietly and move on.
940 * We don't recycle the VM resources at this time.
942 if (l
->l_lwpctl
!= NULL
)
945 if (!recycle
&& l
->l_ts
!= &turnstile0
)
946 pool_cache_put(turnstile_cache
, l
->l_ts
);
947 if (l
->l_name
!= NULL
)
948 kmem_free(l
->l_name
, MAXCOMLEN
);
949 #ifndef __NO_CPU_LWP_FREE
952 KASSERT((l
->l_flag
& LW_INMEM
) != 0);
954 KASSERT(SLIST_EMPTY(&l
->l_pi_lenders
));
955 KASSERT(l
->l_inheritedprio
== -1);
957 pool_cache_put(lwp_cache
, l
);
961 * Migrate the LWP to the another CPU. Unlocks the LWP.
964 lwp_migrate(lwp_t
*l
, struct cpu_info
*tci
)
966 struct schedstate_percpu
*tspc
;
967 int lstat
= l
->l_stat
;
969 KASSERT(lwp_locked(l
, NULL
));
970 KASSERT(tci
!= NULL
);
972 /* If LWP is still on the CPU, it must be handled like LSONPROC */
973 if ((l
->l_pflag
& LP_RUNNING
) != 0) {
978 * The destination CPU could be changed while previous migration
981 if (l
->l_target_cpu
!= NULL
) {
982 l
->l_target_cpu
= tci
;
987 /* Nothing to do if trying to migrate to the same CPU */
988 if (l
->l_cpu
== tci
) {
993 KASSERT(l
->l_target_cpu
== NULL
);
994 tspc
= &tci
->ci_schedstate
;
997 if (l
->l_flag
& LW_INMEM
) {
998 l
->l_target_cpu
= tci
;
1004 lwp_unlock_to(l
, tspc
->spc_mutex
);
1012 if (l
->l_wchan
== NULL
) {
1013 lwp_unlock_to(l
, tspc
->spc_lwplock
);
1018 l
->l_target_cpu
= tci
;
1020 cpu_need_resched(l
->l_cpu
, RESCHED_KPREEMPT
);
1021 spc_unlock(l
->l_cpu
);
1028 * Find the LWP in the process. Arguments may be zero, in such case,
1029 * the calling process and first LWP in the list will be used.
1030 * On success - returns proc locked.
1033 lwp_find2(pid_t pid
, lwpid_t lid
)
1038 /* Find the process */
1039 p
= (pid
== 0) ? curlwp
->l_proc
: p_find(pid
, PFIND_UNLOCK_FAIL
);
1042 mutex_enter(p
->p_lock
);
1044 /* Case of p_find */
1045 mutex_exit(proc_lock
);
1048 /* Find the thread */
1049 l
= (lid
== 0) ? LIST_FIRST(&p
->p_lwps
) : lwp_find(p
, lid
);
1051 mutex_exit(p
->p_lock
);
1058 * Look up a live LWP within the speicifed process, and return it locked.
1060 * Must be called with p->p_lock held.
1063 lwp_find(struct proc
*p
, int id
)
1067 KASSERT(mutex_owned(p
->p_lock
));
1069 LIST_FOREACH(l
, &p
->p_lwps
, l_sibling
) {
1075 * No need to lock - all of these conditions will
1076 * be visible with the process level mutex held.
1078 if (l
!= NULL
&& (l
->l_stat
== LSIDL
|| l
->l_stat
== LSZOMB
))
1085 * Update an LWP's cached credentials to mirror the process' master copy.
1087 * This happens early in the syscall path, on user trap, and on LWP
1088 * creation. A long-running LWP can also voluntarily choose to update
1089 * it's credentials by calling this routine. This may be called from
1090 * LWP_CACHE_CREDS(), which checks l->l_cred != p->p_cred beforehand.
1093 lwp_update_creds(struct lwp
*l
)
1101 mutex_enter(p
->p_lock
);
1102 kauth_cred_hold(p
->p_cred
);
1103 l
->l_cred
= p
->p_cred
;
1104 l
->l_prflag
&= ~LPR_CRMOD
;
1105 mutex_exit(p
->p_lock
);
1107 kauth_cred_free(oc
);
1111 * Verify that an LWP is locked, and optionally verify that the lock matches
1115 lwp_locked(struct lwp
*l
, kmutex_t
*mtx
)
1117 kmutex_t
*cur
= l
->l_mutex
;
1119 return mutex_owned(cur
) && (mtx
== cur
|| mtx
== NULL
);
1126 lwp_lock_retry(struct lwp
*l
, kmutex_t
*old
)
1130 * XXXgcc ignoring kmutex_t * volatile on i386
1132 * gcc version 4.1.2 20061021 prerelease (NetBSD nb1 20061021)
1135 while (l
->l_mutex
!= old
) {
1139 mutex_spin_exit(old
);
1141 mutex_spin_enter(old
);
1144 * mutex_enter() will have posted a read barrier. Re-test
1145 * l->l_mutex. If it has changed, we need to try again.
1150 } while (__predict_false(l
->l_mutex
!= old
));
1157 * Lend a new mutex to an LWP. The old mutex must be held.
1160 lwp_setlock(struct lwp
*l
, kmutex_t
*new)
1163 KASSERT(mutex_owned(l
->l_mutex
));
1170 * Lend a new mutex to an LWP, and release the old mutex. The old mutex
1174 lwp_unlock_to(struct lwp
*l
, kmutex_t
*new)
1178 KASSERT(mutex_owned(l
->l_mutex
));
1183 mutex_spin_exit(old
);
1187 * Acquire a new mutex, and donate it to an LWP. The LWP must already be
1191 lwp_relock(struct lwp
*l
, kmutex_t
*new)
1195 KASSERT(mutex_owned(l
->l_mutex
));
1199 mutex_spin_enter(new);
1201 mutex_spin_exit(old
);
1206 lwp_trylock(struct lwp
*l
)
1211 if (!mutex_tryenter(old
= l
->l_mutex
))
1213 if (__predict_true(l
->l_mutex
== old
))
1215 mutex_spin_exit(old
);
1220 lwp_unsleep(lwp_t
*l
, bool cleanup
)
1223 KASSERT(mutex_owned(l
->l_mutex
));
1225 return (*l
->l_syncobj
->sobj_unsleep
)(l
, cleanup
);
1230 * Handle exceptions for mi_userret(). Called if a member of LW_USERRET is
1234 lwp_userret(struct lwp
*l
)
1240 KASSERT(l
== curlwp
);
1241 KASSERT(l
->l_stat
== LSONPROC
);
1244 #ifndef __HAVE_FAST_SOFTINTS
1245 /* Run pending soft interrupts. */
1246 if (l
->l_cpu
->ci_data
.cpu_softints
!= 0)
1251 /* Generate UNBLOCKED upcall if needed */
1252 if (l
->l_flag
& LW_SA_BLOCKING
) {
1253 sa_unblock_userret(l
);
1259 * It should be safe to do this read unlocked on a multiprocessor
1262 * LW_SA_UPCALL will be handled after the while() loop, so don't
1265 while ((l
->l_flag
& (LW_USERRET
& ~(LW_SA_UPCALL
))) != 0) {
1267 * Process pending signals first, unless the process
1268 * is dumping core or exiting, where we will instead
1269 * enter the LW_WSUSPEND case below.
1271 if ((l
->l_flag
& (LW_PENDSIG
| LW_WCORE
| LW_WEXIT
)) ==
1273 mutex_enter(p
->p_lock
);
1274 while ((sig
= issignal(l
)) != 0)
1276 mutex_exit(p
->p_lock
);
1280 * Core-dump or suspend pending.
1282 * In case of core dump, suspend ourselves, so that the
1283 * kernel stack and therefore the userland registers saved
1284 * in the trapframe are around for coredump() to write them
1285 * out. We issue a wakeup on p->p_lwpcv so that sigexit()
1286 * will write the core file out once all other LWPs are
1289 if ((l
->l_flag
& LW_WSUSPEND
) != 0) {
1290 mutex_enter(p
->p_lock
);
1292 cv_broadcast(&p
->p_lwpcv
);
1294 l
->l_stat
= LSSUSPENDED
;
1296 mutex_exit(p
->p_lock
);
1301 /* Process is exiting. */
1302 if ((l
->l_flag
& LW_WEXIT
) != 0) {
1308 /* Call userret hook; used by Linux emulation. */
1309 if ((l
->l_flag
& LW_WUSERRET
) != 0) {
1311 l
->l_flag
&= ~LW_WUSERRET
;
1313 hook
= p
->p_userret
;
1314 p
->p_userret
= NULL
;
1321 * Timer events are handled specially. We only try once to deliver
1322 * pending timer upcalls; if if fails, we can try again on the next
1323 * loop around. If we need to re-enter lwp_userret(), MD code will
1324 * bounce us back here through the trap path after we return.
1328 if (l
->l_flag
& LW_SA_UPCALL
)
1329 sa_upcall_userret(l
);
1330 #endif /* KERN_SA */
1334 * Force an LWP to enter the kernel, to take a trip through lwp_userret().
1337 lwp_need_userret(struct lwp
*l
)
1339 KASSERT(lwp_locked(l
, NULL
));
1342 * Since the tests in lwp_userret() are done unlocked, make sure
1343 * that the condition will be seen before forcing the LWP to enter
1351 * Add one reference to an LWP. This will prevent the LWP from
1352 * exiting, thus keep the lwp structure and PCB around to inspect.
1355 lwp_addref(struct lwp
*l
)
1358 KASSERT(mutex_owned(l
->l_proc
->p_lock
));
1359 KASSERT(l
->l_stat
!= LSZOMB
);
1360 KASSERT(l
->l_refcnt
!= 0);
1366 * Remove one reference to an LWP. If this is the last reference,
1367 * then we must finalize the LWP's death.
1370 lwp_delref(struct lwp
*l
)
1372 struct proc
*p
= l
->l_proc
;
1374 mutex_enter(p
->p_lock
);
1375 KASSERT(l
->l_stat
!= LSZOMB
);
1376 KASSERT(l
->l_refcnt
> 0);
1377 if (--l
->l_refcnt
== 0)
1378 cv_broadcast(&p
->p_lwpcv
);
1379 mutex_exit(p
->p_lock
);
1383 * Drain all references to the current LWP.
1386 lwp_drainrefs(struct lwp
*l
)
1388 struct proc
*p
= l
->l_proc
;
1390 KASSERT(mutex_owned(p
->p_lock
));
1391 KASSERT(l
->l_refcnt
!= 0);
1394 while (l
->l_refcnt
!= 0)
1395 cv_wait(&p
->p_lwpcv
, p
->p_lock
);
1399 * Return true if the specified LWP is 'alive'. Only p->p_lock need
1406 KASSERT(mutex_owned(l
->l_proc
->p_lock
));
1408 switch (l
->l_stat
) {
1421 * Return first live LWP in the process.
1424 lwp_find_first(proc_t
*p
)
1428 KASSERT(mutex_owned(p
->p_lock
));
1430 LIST_FOREACH(l
, &p
->p_lwps
, l_sibling
) {
1440 * lwp_specific_key_create --
1441 * Create a key for subsystem lwp-specific data.
1444 lwp_specific_key_create(specificdata_key_t
*keyp
, specificdata_dtor_t dtor
)
1447 return (specificdata_key_create(lwp_specificdata_domain
, keyp
, dtor
));
1451 * lwp_specific_key_delete --
1452 * Delete a key for subsystem lwp-specific data.
1455 lwp_specific_key_delete(specificdata_key_t key
)
1458 specificdata_key_delete(lwp_specificdata_domain
, key
);
1462 * lwp_initspecific --
1463 * Initialize an LWP's specificdata container.
1466 lwp_initspecific(struct lwp
*l
)
1470 error
= specificdata_init(lwp_specificdata_domain
, &l
->l_specdataref
);
1471 KASSERT(error
== 0);
1475 * lwp_finispecific --
1476 * Finalize an LWP's specificdata container.
1479 lwp_finispecific(struct lwp
*l
)
1482 specificdata_fini(lwp_specificdata_domain
, &l
->l_specdataref
);
1486 * lwp_getspecific --
1487 * Return lwp-specific data corresponding to the specified key.
1489 * Note: LWP specific data is NOT INTERLOCKED. An LWP should access
1490 * only its OWN SPECIFIC DATA. If it is necessary to access another
1491 * LWP's specifc data, care must be taken to ensure that doing so
1492 * would not cause internal data structure inconsistency (i.e. caller
1493 * can guarantee that the target LWP is not inside an lwp_getspecific()
1494 * or lwp_setspecific() call).
1497 lwp_getspecific(specificdata_key_t key
)
1500 return (specificdata_getspecific_unlocked(lwp_specificdata_domain
,
1501 &curlwp
->l_specdataref
, key
));
1505 _lwp_getspecific_by_lwp(struct lwp
*l
, specificdata_key_t key
)
1508 return (specificdata_getspecific_unlocked(lwp_specificdata_domain
,
1509 &l
->l_specdataref
, key
));
1513 * lwp_setspecific --
1514 * Set lwp-specific data corresponding to the specified key.
1517 lwp_setspecific(specificdata_key_t key
, void *data
)
1520 specificdata_setspecific(lwp_specificdata_domain
,
1521 &curlwp
->l_specdataref
, key
, data
);
1525 * Allocate a new lwpctl structure for a user LWP.
1528 lwp_ctl_alloc(vaddr_t
*uaddr
)
1531 u_int bit
, i
, offset
;
1532 struct uvm_object
*uao
;
1541 if (l
->l_lcpage
!= NULL
) {
1543 *uaddr
= lcp
->lcp_uaddr
+ (vaddr_t
)l
->l_lwpctl
- lcp
->lcp_kaddr
;
1547 /* First time around, allocate header structure for the process. */
1548 if ((lp
= p
->p_lwpctl
) == NULL
) {
1549 lp
= kmem_alloc(sizeof(*lp
), KM_SLEEP
);
1550 mutex_init(&lp
->lp_lock
, MUTEX_DEFAULT
, IPL_NONE
);
1552 TAILQ_INIT(&lp
->lp_pages
);
1553 mutex_enter(p
->p_lock
);
1554 if (p
->p_lwpctl
== NULL
) {
1556 mutex_exit(p
->p_lock
);
1558 mutex_exit(p
->p_lock
);
1559 mutex_destroy(&lp
->lp_lock
);
1560 kmem_free(lp
, sizeof(*lp
));
1566 * Set up an anonymous memory region to hold the shared pages.
1567 * Map them into the process' address space. The user vmspace
1568 * gets the first reference on the UAO.
1570 mutex_enter(&lp
->lp_lock
);
1571 if (lp
->lp_uao
== NULL
) {
1572 lp
->lp_uao
= uao_create(LWPCTL_UAREA_SZ
, 0);
1574 lp
->lp_max
= LWPCTL_UAREA_SZ
;
1575 lp
->lp_uva
= p
->p_emul
->e_vm_default_addr(p
,
1576 (vaddr_t
)p
->p_vmspace
->vm_daddr
, LWPCTL_UAREA_SZ
);
1577 error
= uvm_map(&p
->p_vmspace
->vm_map
, &lp
->lp_uva
,
1578 LWPCTL_UAREA_SZ
, lp
->lp_uao
, 0, 0, UVM_MAPFLAG(UVM_PROT_RW
,
1579 UVM_PROT_RW
, UVM_INH_NONE
, UVM_ADV_NORMAL
, 0));
1581 uao_detach(lp
->lp_uao
);
1583 mutex_exit(&lp
->lp_lock
);
1588 /* Get a free block and allocate for this LWP. */
1589 TAILQ_FOREACH(lcp
, &lp
->lp_pages
, lcp_chain
) {
1590 if (lcp
->lcp_nfree
!= 0)
1594 /* Nothing available - try to set up a free page. */
1595 if (lp
->lp_cur
== lp
->lp_max
) {
1596 mutex_exit(&lp
->lp_lock
);
1599 lcp
= kmem_alloc(LWPCTL_LCPAGE_SZ
, KM_SLEEP
);
1601 mutex_exit(&lp
->lp_lock
);
1605 * Wire the next page down in kernel space. Since this
1606 * is a new mapping, we must add a reference.
1609 (*uao
->pgops
->pgo_reference
)(uao
);
1610 lcp
->lcp_kaddr
= vm_map_min(kernel_map
);
1611 error
= uvm_map(kernel_map
, &lcp
->lcp_kaddr
, PAGE_SIZE
,
1612 uao
, lp
->lp_cur
, PAGE_SIZE
,
1613 UVM_MAPFLAG(UVM_PROT_RW
, UVM_PROT_RW
,
1614 UVM_INH_NONE
, UVM_ADV_RANDOM
, 0));
1616 mutex_exit(&lp
->lp_lock
);
1617 kmem_free(lcp
, LWPCTL_LCPAGE_SZ
);
1618 (*uao
->pgops
->pgo_detach
)(uao
);
1621 error
= uvm_map_pageable(kernel_map
, lcp
->lcp_kaddr
,
1622 lcp
->lcp_kaddr
+ PAGE_SIZE
, FALSE
, 0);
1624 mutex_exit(&lp
->lp_lock
);
1625 uvm_unmap(kernel_map
, lcp
->lcp_kaddr
,
1626 lcp
->lcp_kaddr
+ PAGE_SIZE
);
1627 kmem_free(lcp
, LWPCTL_LCPAGE_SZ
);
1630 /* Prepare the page descriptor and link into the list. */
1631 lcp
->lcp_uaddr
= lp
->lp_uva
+ lp
->lp_cur
;
1632 lp
->lp_cur
+= PAGE_SIZE
;
1633 lcp
->lcp_nfree
= LWPCTL_PER_PAGE
;
1635 memset(lcp
->lcp_bitmap
, 0xff, LWPCTL_BITMAP_SZ
);
1636 TAILQ_INSERT_HEAD(&lp
->lp_pages
, lcp
, lcp_chain
);
1638 for (i
= lcp
->lcp_rotor
; lcp
->lcp_bitmap
[i
] == 0;) {
1639 if (++i
>= LWPCTL_BITMAP_ENTRIES
)
1642 bit
= ffs(lcp
->lcp_bitmap
[i
]) - 1;
1643 lcp
->lcp_bitmap
[i
] ^= (1 << bit
);
1647 offset
= (i
<< 5) + bit
;
1648 l
->l_lwpctl
= (lwpctl_t
*)lcp
->lcp_kaddr
+ offset
;
1649 *uaddr
= lcp
->lcp_uaddr
+ offset
* sizeof(lwpctl_t
);
1650 mutex_exit(&lp
->lp_lock
);
1652 KPREEMPT_DISABLE(l
);
1653 l
->l_lwpctl
->lc_curcpu
= (int)curcpu()->ci_data
.cpu_index
;
1660 * Free an lwpctl structure back to the per-process list.
1663 lwp_ctl_free(lwp_t
*l
)
1669 lp
= l
->l_proc
->p_lwpctl
;
1670 KASSERT(lp
!= NULL
);
1673 offset
= (u_int
)((lwpctl_t
*)l
->l_lwpctl
- (lwpctl_t
*)lcp
->lcp_kaddr
);
1674 KASSERT(offset
< LWPCTL_PER_PAGE
);
1676 mutex_enter(&lp
->lp_lock
);
1679 lcp
->lcp_bitmap
[map
] |= (1 << (offset
& 31));
1680 if (lcp
->lcp_bitmap
[lcp
->lcp_rotor
] == 0)
1681 lcp
->lcp_rotor
= map
;
1682 if (TAILQ_FIRST(&lp
->lp_pages
)->lcp_nfree
== 0) {
1683 TAILQ_REMOVE(&lp
->lp_pages
, lcp
, lcp_chain
);
1684 TAILQ_INSERT_HEAD(&lp
->lp_pages
, lcp
, lcp_chain
);
1686 mutex_exit(&lp
->lp_lock
);
1690 * Process is exiting; tear down lwpctl state. This can only be safely
1691 * called by the last LWP in the process.
1696 lcpage_t
*lcp
, *next
;
1707 KASSERT(lp
!= NULL
);
1708 KASSERT(p
->p_nlwps
== 1);
1710 for (lcp
= TAILQ_FIRST(&lp
->lp_pages
); lcp
!= NULL
; lcp
= next
) {
1711 next
= TAILQ_NEXT(lcp
, lcp_chain
);
1712 uvm_unmap(kernel_map
, lcp
->lcp_kaddr
,
1713 lcp
->lcp_kaddr
+ PAGE_SIZE
);
1714 kmem_free(lcp
, LWPCTL_LCPAGE_SZ
);
1717 if (lp
->lp_uao
!= NULL
) {
1718 uvm_unmap(&p
->p_vmspace
->vm_map
, lp
->lp_uva
,
1719 lp
->lp_uva
+ LWPCTL_UAREA_SZ
);
1722 mutex_destroy(&lp
->lp_lock
);
1723 kmem_free(lp
, sizeof(*lp
));
1729 lwp_whatis(uintptr_t addr
, void (*pr
)(const char *, ...))
1733 LIST_FOREACH(l
, &alllwp
, l_list
) {
1734 uintptr_t stack
= (uintptr_t)KSTACK_LOWEST_ADDR(l
);
1736 if (addr
< stack
|| stack
+ KSTACK_SIZE
<= addr
) {
1739 (*pr
)("%p is %p+%zu, LWP %p's stack\n",
1740 (void *)addr
, (void *)stack
,
1741 (size_t)(addr
- stack
), l
);
1744 #endif /* defined(DDB) */