1 /* $NetBSD: kern_lwp.c,v 1.136 2009/10/27 02:58:28 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
67 * Idle: the LWP has been created but has not yet executed,
68 * or it has ceased executing a unit of work and is waiting
69 * to be started again.
73 * Suspended: the LWP has had its execution suspended by
74 * another LWP in the same process using the _lwp_suspend()
75 * system call. User-level LWPs also enter the suspended
76 * state when the system is shutting down.
78 * The second set represent a "statement of intent" on behalf of the
79 * LWP. The LWP may in fact be executing on a processor, may be
80 * sleeping or idle. It is expected to take the necessary action to
81 * stop executing or become "running" again within a short timeframe.
82 * The LP_RUNNING flag in lwp::l_pflag indicates that an LWP is running.
83 * Importantly, it indicates that its state is tied to a CPU.
87 * Dead or dying: the LWP has released most of its resources
88 * and is about to switch away into oblivion, or has already
89 * switched away. When it switches away, its few remaining
90 * resources can be collected.
94 * Sleeping: the LWP has entered itself onto a sleep queue, and
95 * has switched away or will switch away shortly to allow other
96 * LWPs to run on the CPU.
100 * Stopped: the LWP has been stopped as a result of a job
101 * control signal, or as a result of the ptrace() interface.
103 * Stopped LWPs may run briefly within the kernel to handle
104 * signals that they receive, but will not return to user space
105 * until their process' state is changed away from stopped.
107 * Single LWPs within a process can not be set stopped
108 * selectively: all actions that can stop or continue LWPs
109 * occur at the process level.
113 * Note that the LSSTOP state may only be set when returning to
114 * user space in userret(), or when sleeping interruptably. The
115 * LSSUSPENDED state may only be set in userret(). Before setting
116 * those states, we try to ensure that the LWPs will release all
117 * locks that they hold, and at a minimum try to ensure that the
118 * LWP can be set runnable again by a signal.
120 * LWPs may transition states in the following ways:
122 * RUN -------> ONPROC ONPROC -----> RUN
127 * > IDL (special cases)
129 * STOPPED ---> RUN SUSPENDED --> RUN
132 * SLEEP -----> ONPROC IDL --------> RUN
134 * > STOPPED > STOPPED
135 * > ONPROC (special cases)
137 * Some state transitions are only possible with kernel threads (eg
138 * ONPROC -> IDL) and happen under tightly controlled circumstances
139 * free of unwanted side effects.
143 * Migration of threads from one CPU to another could be performed
144 * internally by the scheduler via sched_takecpu() or sched_catchlwp()
145 * functions. The universal lwp_migrate() function should be used for
146 * any other cases. Subsystems in the kernel must be aware that CPU
147 * of LWP may change, while it is not locked.
151 * The majority of fields in 'struct lwp' are covered by a single,
152 * general spin lock pointed to by lwp::l_mutex. The locks covering
153 * each field are documented in sys/lwp.h.
155 * State transitions must be made with the LWP's general lock held,
156 * and may cause the LWP's lock pointer to change. Manipulation of
157 * the general lock is not performed directly, but through calls to
158 * lwp_lock(), lwp_relock() and similar.
160 * States and their associated locks:
164 * Always covered by spc_lwplock, which protects running LWPs.
165 * This is a per-CPU lock and matches lwp::l_cpu.
169 * Always covered by spc_mutex, which protects the run queues.
170 * This is a per-CPU lock and matches lwp::l_cpu.
174 * Covered by a lock associated with the sleep queue that the
175 * LWP resides on. Matches lwp::l_sleepq::sq_mutex.
177 * LSSTOP, LSSUSPENDED:
179 * If the LWP was previously sleeping (l_wchan != NULL), then
180 * l_mutex references the sleep queue lock. If the LWP was
181 * runnable or on the CPU when halted, or has been removed from
182 * the sleep queue since halted, then the lock is spc_lwplock.
184 * The lock order is as follows:
186 * spc::spc_lwplock ->
187 * sleeptab::st_mutex ->
188 * tschain_t::tc_mutex ->
191 * Each process has an scheduler state lock (proc::p_lock), and a
192 * number of counters on LWPs and their states: p_nzlwps, p_nrlwps, and
193 * so on. When an LWP is to be entered into or removed from one of the
194 * following states, p_lock must be held and the process wide counters
197 * LSIDL, LSZOMB, LSSTOP, LSSUSPENDED
199 * (But not always for kernel threads. There are some special cases
200 * as mentioned above. See kern_softint.c.)
202 * Note that an LWP is considered running or likely to run soon if in
203 * one of the following states. This affects the value of p_nrlwps:
205 * LSRUN, LSONPROC, LSSLEEP
207 * p_lock does not need to be held when transitioning among these
208 * three states, hence p_lock is rarely taken for state transitions.
211 #include <sys/cdefs.h>
212 __KERNEL_RCSID(0, "$NetBSD: kern_lwp.c,v 1.136 2009/10/27 02:58:28 rmind Exp $");
215 #include "opt_lockdebug.h"
218 #define _LWP_API_PRIVATE
220 #include <sys/param.h>
221 #include <sys/systm.h>
223 #include <sys/pool.h>
224 #include <sys/proc.h>
226 #include <sys/savar.h>
227 #include <sys/syscallargs.h>
228 #include <sys/syscall_stats.h>
229 #include <sys/kauth.h>
230 #include <sys/sleepq.h>
231 #include <sys/lockdebug.h>
232 #include <sys/kmem.h>
233 #include <sys/pset.h>
234 #include <sys/intr.h>
235 #include <sys/lwpctl.h>
236 #include <sys/atomic.h>
237 #include <sys/filedesc.h>
239 #include <uvm/uvm_extern.h>
240 #include <uvm/uvm_object.h>
242 struct lwplist alllwp
= LIST_HEAD_INITIALIZER(alllwp
);
244 struct pool lwp_uc_pool
;
246 static pool_cache_t lwp_cache
;
247 static specificdata_domain_t lwp_specificdata_domain
;
253 pool_init(&lwp_uc_pool
, sizeof(ucontext_t
), 0, 0, 0, "lwpucpl",
254 &pool_allocator_nointr
, IPL_NONE
);
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
, 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;
598 l2
->l_pflag
= LP_MPSAFE
;
599 TAILQ_INIT(&l2
->l_ld_locks
);
602 * If not the first LWP in the process, grab a reference to the
606 if (p2
->p_nlwps
!= 0) {
607 KASSERT(l1
->l_proc
== p2
);
610 KASSERT(l1
->l_proc
!= p2
);
613 if (p2
->p_flag
& PK_SYSTEM
) {
614 /* Mark it as a system LWP. */
615 l2
->l_flag
|= LW_SYSTEM
;
619 l2
->l_mutex
= l1
->l_cpu
->ci_schedstate
.spc_mutex
;
620 l2
->l_cpu
= l1
->l_cpu
;
623 lwp_initspecific(l2
);
624 sched_lwp_fork(l1
, l2
);
625 lwp_update_creds(l2
);
626 callout_init(&l2
->l_timeout_ch
, CALLOUT_MPSAFE
);
627 callout_setfunc(&l2
->l_timeout_ch
, sleepq_timeout
, l2
);
628 cv_init(&l2
->l_sigcv
, "sigwait");
629 l2
->l_syncobj
= &sched_syncobj
;
631 if (rnewlwpp
!= NULL
)
634 uvm_lwp_setuarea(l2
, uaddr
);
635 uvm_lwp_fork(l1
, l2
, stack
, stacksize
, func
,
636 (arg
!= NULL
) ? arg
: l2
);
638 mutex_enter(p2
->p_lock
);
640 if ((flags
& LWP_DETACHED
) != 0) {
641 l2
->l_prflag
= LPR_DETACHED
;
646 l2
->l_sigmask
= l1
->l_sigmask
;
647 CIRCLEQ_INIT(&l2
->l_sigpend
.sp_info
);
648 sigemptyset(&l2
->l_sigpend
.sp_set
);
651 if (p2
->p_nlwpid
== 0)
653 l2
->l_lid
= p2
->p_nlwpid
;
654 LIST_INSERT_HEAD(&p2
->p_lwps
, l2
, l_sibling
);
657 if ((p2
->p_flag
& PK_SYSTEM
) == 0) {
658 /* Inherit an affinity */
659 if (l1
->l_flag
& LW_AFFINITY
) {
661 * Note that we hold the state lock while inheriting
662 * the affinity to avoid race with sched_setaffinity().
665 if (l1
->l_flag
& LW_AFFINITY
) {
666 kcpuset_use(l1
->l_affinity
);
667 l2
->l_affinity
= l1
->l_affinity
;
668 l2
->l_flag
|= LW_AFFINITY
;
673 /* Inherit a processor-set */
674 l2
->l_psid
= l1
->l_psid
;
675 /* Look for a CPU to start */
676 l2
->l_cpu
= sched_takecpu(l2
);
677 lwp_unlock_to(l2
, l2
->l_cpu
->ci_schedstate
.spc_mutex
);
679 mutex_exit(p2
->p_lock
);
681 mutex_enter(proc_lock
);
682 LIST_INSERT_HEAD(&alllwp
, l2
, l_list
);
683 mutex_exit(proc_lock
);
685 SYSCALL_TIME_LWP_INIT(l2
);
687 if (p2
->p_emul
->e_lwp_fork
)
688 (*p2
->p_emul
->e_lwp_fork
)(l1
, l2
);
694 * Called by MD code when a new LWP begins execution. Must be called
695 * with the previous LWP locked (so at splsched), or if there is no
696 * previous LWP, at splsched.
699 lwp_startup(struct lwp
*prev
, struct lwp
*new)
702 KASSERT(kpreempt_disabled());
705 * Normalize the count of the spin-mutexes, it was
706 * increased in mi_switch(). Unmark the state of
707 * context switch - it is finished for previous LWP.
709 curcpu()->ci_mtx_count
++;
711 prev
->l_ctxswtch
= 0;
713 KPREEMPT_DISABLE(new);
716 LOCKDEBUG_BARRIER(NULL
, 0);
717 KPREEMPT_ENABLE(new);
718 if ((new->l_pflag
& LP_MPSAFE
) == 0) {
727 lwp_exit(struct lwp
*l
)
729 struct proc
*p
= l
->l_proc
;
733 current
= (l
== curlwp
);
735 KASSERT(current
|| (l
->l_stat
== LSIDL
&& l
->l_target_cpu
== NULL
));
736 KASSERT(p
== curproc
);
739 * Verify that we hold no locks other than the kernel lock.
741 LOCKDEBUG_BARRIER(&kernel_lock
, 0);
744 * If we are the last live LWP in a process, we need to exit the
745 * entire process. We do so with an exit status of zero, because
746 * it's a "controlled" exit, and because that's what Solaris does.
748 * We are not quite a zombie yet, but for accounting purposes we
749 * must increment the count of zombies here.
751 * Note: the last LWP's specificdata will be deleted here.
753 mutex_enter(p
->p_lock
);
754 if (p
->p_nlwps
- p
->p_nzlwps
== 1) {
755 KASSERT(current
== true);
756 /* XXXSMP kernel_lock not held */
761 mutex_exit(p
->p_lock
);
763 if (p
->p_emul
->e_lwp_exit
)
764 (*p
->p_emul
->e_lwp_exit
)(l
);
766 /* Drop filedesc reference. */
769 /* Delete the specificdata while it's still safe to sleep. */
770 specificdata_fini(lwp_specificdata_domain
, &l
->l_specdataref
);
773 * Release our cached credentials.
775 kauth_cred_free(l
->l_cred
);
776 callout_destroy(&l
->l_timeout_ch
);
779 * Remove the LWP from the global list.
781 mutex_enter(proc_lock
);
782 LIST_REMOVE(l
, l_list
);
783 mutex_exit(proc_lock
);
786 * Get rid of all references to the LWP that others (e.g. procfs)
787 * may have, and mark the LWP as a zombie. If the LWP is detached,
788 * mark it waiting for collection in the proc structure. Note that
789 * before we can do that, we need to free any other dead, deatched
790 * LWP waiting to meet its maker.
792 mutex_enter(p
->p_lock
);
795 if ((l
->l_prflag
& LPR_DETACHED
) != 0) {
796 while ((l2
= p
->p_zomblwp
) != NULL
) {
798 lwp_free(l2
, false, false);/* releases proc mutex */
799 mutex_enter(p
->p_lock
);
807 * If we find a pending signal for the process and we have been
808 * asked to check for signals, then we loose: arrange to have
809 * all other LWPs in the process check for signals.
811 if ((l
->l_flag
& LW_PENDSIG
) != 0 &&
812 firstsig(&p
->p_sigpend
.sp_set
) != 0) {
813 LIST_FOREACH(l2
, &p
->p_lwps
, l_sibling
) {
815 l2
->l_flag
|= LW_PENDSIG
;
822 if (l
->l_name
!= NULL
)
823 strcpy(l
->l_name
, "(zombie)");
824 if (l
->l_flag
& LW_AFFINITY
) {
825 l
->l_flag
&= ~LW_AFFINITY
;
827 KASSERT(l
->l_affinity
== NULL
);
831 cv_broadcast(&p
->p_lwpcv
);
832 if (l
->l_lwpctl
!= NULL
)
833 l
->l_lwpctl
->lc_curcpu
= LWPCTL_CPU_EXITED
;
834 mutex_exit(p
->p_lock
);
836 /* Safe without lock since LWP is in zombie state */
838 kcpuset_unuse(l
->l_affinity
, NULL
);
839 l
->l_affinity
= NULL
;
843 * We can no longer block. At this point, lwp_free() may already
844 * be gunning for us. On a multi-CPU system, we may be off p_lwps.
846 * Free MD LWP resources.
854 * Release the kernel lock, and switch away into
858 /* XXXSMP hold in lwp_userret() */
859 KERNEL_UNLOCK_LAST(l
);
861 KERNEL_UNLOCK_ALL(l
, NULL
);
863 lwp_exit_switchaway(l
);
868 * Free a dead LWP's remaining resources.
873 lwp_free(struct lwp
*l
, bool recycle
, bool last
)
875 struct proc
*p
= l
->l_proc
;
879 KASSERT(l
!= curlwp
);
882 * If this was not the last LWP in the process, then adjust
883 * counters and unlock.
887 * Add the LWP's run time to the process' base value.
888 * This needs to co-incide with coming off p_lwps.
890 bintime_add(&p
->p_rtime
, &l
->l_rtime
);
891 p
->p_pctcpu
+= l
->l_pctcpu
;
892 ru
= &p
->p_stats
->p_ru
;
894 ru
->ru_nvcsw
+= (l
->l_ncsw
- l
->l_nivcsw
);
895 ru
->ru_nivcsw
+= l
->l_nivcsw
;
896 LIST_REMOVE(l
, l_sibling
);
899 if ((l
->l_prflag
& LPR_DETACHED
) != 0)
903 * Have any LWPs sleeping in lwp_wait() recheck for
906 cv_broadcast(&p
->p_lwpcv
);
907 mutex_exit(p
->p_lock
);
910 #ifdef MULTIPROCESSOR
912 * In the unlikely event that the LWP is still on the CPU,
913 * then spin until it has switched away. We need to release
914 * all locks to avoid deadlock against interrupt handlers on
917 if ((l
->l_pflag
& LP_RUNNING
) != 0 || l
->l_cpu
->ci_curlwp
== l
) {
919 (void)count
; /* XXXgcc */
920 KERNEL_UNLOCK_ALL(curlwp
, &count
);
921 while ((l
->l_pflag
& LP_RUNNING
) != 0 ||
922 l
->l_cpu
->ci_curlwp
== l
)
923 SPINLOCK_BACKOFF_HOOK
;
924 KERNEL_LOCK(count
, curlwp
);
929 * Destroy the LWP's remaining signal information.
931 ksiginfo_queue_init(&kq
);
932 sigclear(&l
->l_sigpend
, NULL
, &kq
);
933 ksiginfo_queue_drain(&kq
);
934 cv_destroy(&l
->l_sigcv
);
937 * Free the LWP's turnstile and the LWP structure itself unless the
938 * caller wants to recycle them. Also, free the scheduler specific
941 * We can't return turnstile0 to the pool (it didn't come from it),
942 * so if it comes up just drop it quietly and move on.
944 * We don't recycle the VM resources at this time.
946 if (l
->l_lwpctl
!= NULL
)
949 if (!recycle
&& l
->l_ts
!= &turnstile0
)
950 pool_cache_put(turnstile_cache
, l
->l_ts
);
951 if (l
->l_name
!= NULL
)
952 kmem_free(l
->l_name
, MAXCOMLEN
);
957 KASSERT(SLIST_EMPTY(&l
->l_pi_lenders
));
958 KASSERT(l
->l_inheritedprio
== -1);
960 pool_cache_put(lwp_cache
, l
);
964 * Migrate the LWP to the another CPU. Unlocks the LWP.
967 lwp_migrate(lwp_t
*l
, struct cpu_info
*tci
)
969 struct schedstate_percpu
*tspc
;
970 int lstat
= l
->l_stat
;
972 KASSERT(lwp_locked(l
, NULL
));
973 KASSERT(tci
!= NULL
);
975 /* If LWP is still on the CPU, it must be handled like LSONPROC */
976 if ((l
->l_pflag
& LP_RUNNING
) != 0) {
981 * The destination CPU could be changed while previous migration
984 if (l
->l_target_cpu
!= NULL
) {
985 l
->l_target_cpu
= tci
;
990 /* Nothing to do if trying to migrate to the same CPU */
991 if (l
->l_cpu
== tci
) {
996 KASSERT(l
->l_target_cpu
== NULL
);
997 tspc
= &tci
->ci_schedstate
;
1000 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
));
1224 (*l
->l_syncobj
->sobj_unsleep
)(l
, cleanup
);
1229 * Handle exceptions for mi_userret(). Called if a member of LW_USERRET is
1233 lwp_userret(struct lwp
*l
)
1239 KASSERT(l
== curlwp
);
1240 KASSERT(l
->l_stat
== LSONPROC
);
1243 #ifndef __HAVE_FAST_SOFTINTS
1244 /* Run pending soft interrupts. */
1245 if (l
->l_cpu
->ci_data
.cpu_softints
!= 0)
1250 /* Generate UNBLOCKED upcall if needed */
1251 if (l
->l_flag
& LW_SA_BLOCKING
) {
1252 sa_unblock_userret(l
);
1258 * It should be safe to do this read unlocked on a multiprocessor
1261 * LW_SA_UPCALL will be handled after the while() loop, so don't
1264 while ((l
->l_flag
& (LW_USERRET
& ~(LW_SA_UPCALL
))) != 0) {
1266 * Process pending signals first, unless the process
1267 * is dumping core or exiting, where we will instead
1268 * enter the LW_WSUSPEND case below.
1270 if ((l
->l_flag
& (LW_PENDSIG
| LW_WCORE
| LW_WEXIT
)) ==
1272 mutex_enter(p
->p_lock
);
1273 while ((sig
= issignal(l
)) != 0)
1275 mutex_exit(p
->p_lock
);
1279 * Core-dump or suspend pending.
1281 * In case of core dump, suspend ourselves, so that the
1282 * kernel stack and therefore the userland registers saved
1283 * in the trapframe are around for coredump() to write them
1284 * out. We issue a wakeup on p->p_lwpcv so that sigexit()
1285 * will write the core file out once all other LWPs are
1288 if ((l
->l_flag
& LW_WSUSPEND
) != 0) {
1289 mutex_enter(p
->p_lock
);
1291 cv_broadcast(&p
->p_lwpcv
);
1293 l
->l_stat
= LSSUSPENDED
;
1295 mutex_exit(p
->p_lock
);
1300 /* Process is exiting. */
1301 if ((l
->l_flag
& LW_WEXIT
) != 0) {
1307 /* Call userret hook; used by Linux emulation. */
1308 if ((l
->l_flag
& LW_WUSERRET
) != 0) {
1310 l
->l_flag
&= ~LW_WUSERRET
;
1312 hook
= p
->p_userret
;
1313 p
->p_userret
= NULL
;
1320 * Timer events are handled specially. We only try once to deliver
1321 * pending timer upcalls; if if fails, we can try again on the next
1322 * loop around. If we need to re-enter lwp_userret(), MD code will
1323 * bounce us back here through the trap path after we return.
1327 if (l
->l_flag
& LW_SA_UPCALL
)
1328 sa_upcall_userret(l
);
1329 #endif /* KERN_SA */
1333 * Force an LWP to enter the kernel, to take a trip through lwp_userret().
1336 lwp_need_userret(struct lwp
*l
)
1338 KASSERT(lwp_locked(l
, NULL
));
1341 * Since the tests in lwp_userret() are done unlocked, make sure
1342 * that the condition will be seen before forcing the LWP to enter
1350 * Add one reference to an LWP. This will prevent the LWP from
1351 * exiting, thus keep the lwp structure and PCB around to inspect.
1354 lwp_addref(struct lwp
*l
)
1357 KASSERT(mutex_owned(l
->l_proc
->p_lock
));
1358 KASSERT(l
->l_stat
!= LSZOMB
);
1359 KASSERT(l
->l_refcnt
!= 0);
1365 * Remove one reference to an LWP. If this is the last reference,
1366 * then we must finalize the LWP's death.
1369 lwp_delref(struct lwp
*l
)
1371 struct proc
*p
= l
->l_proc
;
1373 mutex_enter(p
->p_lock
);
1374 KASSERT(l
->l_stat
!= LSZOMB
);
1375 KASSERT(l
->l_refcnt
> 0);
1376 if (--l
->l_refcnt
== 0)
1377 cv_broadcast(&p
->p_lwpcv
);
1378 mutex_exit(p
->p_lock
);
1382 * Drain all references to the current LWP.
1385 lwp_drainrefs(struct lwp
*l
)
1387 struct proc
*p
= l
->l_proc
;
1389 KASSERT(mutex_owned(p
->p_lock
));
1390 KASSERT(l
->l_refcnt
!= 0);
1393 while (l
->l_refcnt
!= 0)
1394 cv_wait(&p
->p_lwpcv
, p
->p_lock
);
1398 * Return true if the specified LWP is 'alive'. Only p->p_lock need
1405 KASSERT(mutex_owned(l
->l_proc
->p_lock
));
1407 switch (l
->l_stat
) {
1420 * Return first live LWP in the process.
1423 lwp_find_first(proc_t
*p
)
1427 KASSERT(mutex_owned(p
->p_lock
));
1429 LIST_FOREACH(l
, &p
->p_lwps
, l_sibling
) {
1439 * lwp_specific_key_create --
1440 * Create a key for subsystem lwp-specific data.
1443 lwp_specific_key_create(specificdata_key_t
*keyp
, specificdata_dtor_t dtor
)
1446 return (specificdata_key_create(lwp_specificdata_domain
, keyp
, dtor
));
1450 * lwp_specific_key_delete --
1451 * Delete a key for subsystem lwp-specific data.
1454 lwp_specific_key_delete(specificdata_key_t key
)
1457 specificdata_key_delete(lwp_specificdata_domain
, key
);
1461 * lwp_initspecific --
1462 * Initialize an LWP's specificdata container.
1465 lwp_initspecific(struct lwp
*l
)
1469 error
= specificdata_init(lwp_specificdata_domain
, &l
->l_specdataref
);
1470 KASSERT(error
== 0);
1474 * lwp_finispecific --
1475 * Finalize an LWP's specificdata container.
1478 lwp_finispecific(struct lwp
*l
)
1481 specificdata_fini(lwp_specificdata_domain
, &l
->l_specdataref
);
1485 * lwp_getspecific --
1486 * Return lwp-specific data corresponding to the specified key.
1488 * Note: LWP specific data is NOT INTERLOCKED. An LWP should access
1489 * only its OWN SPECIFIC DATA. If it is necessary to access another
1490 * LWP's specifc data, care must be taken to ensure that doing so
1491 * would not cause internal data structure inconsistency (i.e. caller
1492 * can guarantee that the target LWP is not inside an lwp_getspecific()
1493 * or lwp_setspecific() call).
1496 lwp_getspecific(specificdata_key_t key
)
1499 return (specificdata_getspecific_unlocked(lwp_specificdata_domain
,
1500 &curlwp
->l_specdataref
, key
));
1504 _lwp_getspecific_by_lwp(struct lwp
*l
, specificdata_key_t key
)
1507 return (specificdata_getspecific_unlocked(lwp_specificdata_domain
,
1508 &l
->l_specdataref
, key
));
1512 * lwp_setspecific --
1513 * Set lwp-specific data corresponding to the specified key.
1516 lwp_setspecific(specificdata_key_t key
, void *data
)
1519 specificdata_setspecific(lwp_specificdata_domain
,
1520 &curlwp
->l_specdataref
, key
, data
);
1524 * Allocate a new lwpctl structure for a user LWP.
1527 lwp_ctl_alloc(vaddr_t
*uaddr
)
1530 u_int bit
, i
, offset
;
1531 struct uvm_object
*uao
;
1540 if (l
->l_lcpage
!= NULL
) {
1542 *uaddr
= lcp
->lcp_uaddr
+ (vaddr_t
)l
->l_lwpctl
- lcp
->lcp_kaddr
;
1546 /* First time around, allocate header structure for the process. */
1547 if ((lp
= p
->p_lwpctl
) == NULL
) {
1548 lp
= kmem_alloc(sizeof(*lp
), KM_SLEEP
);
1549 mutex_init(&lp
->lp_lock
, MUTEX_DEFAULT
, IPL_NONE
);
1551 TAILQ_INIT(&lp
->lp_pages
);
1552 mutex_enter(p
->p_lock
);
1553 if (p
->p_lwpctl
== NULL
) {
1555 mutex_exit(p
->p_lock
);
1557 mutex_exit(p
->p_lock
);
1558 mutex_destroy(&lp
->lp_lock
);
1559 kmem_free(lp
, sizeof(*lp
));
1565 * Set up an anonymous memory region to hold the shared pages.
1566 * Map them into the process' address space. The user vmspace
1567 * gets the first reference on the UAO.
1569 mutex_enter(&lp
->lp_lock
);
1570 if (lp
->lp_uao
== NULL
) {
1571 lp
->lp_uao
= uao_create(LWPCTL_UAREA_SZ
, 0);
1573 lp
->lp_max
= LWPCTL_UAREA_SZ
;
1574 lp
->lp_uva
= p
->p_emul
->e_vm_default_addr(p
,
1575 (vaddr_t
)p
->p_vmspace
->vm_daddr
, LWPCTL_UAREA_SZ
);
1576 error
= uvm_map(&p
->p_vmspace
->vm_map
, &lp
->lp_uva
,
1577 LWPCTL_UAREA_SZ
, lp
->lp_uao
, 0, 0, UVM_MAPFLAG(UVM_PROT_RW
,
1578 UVM_PROT_RW
, UVM_INH_NONE
, UVM_ADV_NORMAL
, 0));
1580 uao_detach(lp
->lp_uao
);
1582 mutex_exit(&lp
->lp_lock
);
1587 /* Get a free block and allocate for this LWP. */
1588 TAILQ_FOREACH(lcp
, &lp
->lp_pages
, lcp_chain
) {
1589 if (lcp
->lcp_nfree
!= 0)
1593 /* Nothing available - try to set up a free page. */
1594 if (lp
->lp_cur
== lp
->lp_max
) {
1595 mutex_exit(&lp
->lp_lock
);
1598 lcp
= kmem_alloc(LWPCTL_LCPAGE_SZ
, KM_SLEEP
);
1600 mutex_exit(&lp
->lp_lock
);
1604 * Wire the next page down in kernel space. Since this
1605 * is a new mapping, we must add a reference.
1608 (*uao
->pgops
->pgo_reference
)(uao
);
1609 lcp
->lcp_kaddr
= vm_map_min(kernel_map
);
1610 error
= uvm_map(kernel_map
, &lcp
->lcp_kaddr
, PAGE_SIZE
,
1611 uao
, lp
->lp_cur
, PAGE_SIZE
,
1612 UVM_MAPFLAG(UVM_PROT_RW
, UVM_PROT_RW
,
1613 UVM_INH_NONE
, UVM_ADV_RANDOM
, 0));
1615 mutex_exit(&lp
->lp_lock
);
1616 kmem_free(lcp
, LWPCTL_LCPAGE_SZ
);
1617 (*uao
->pgops
->pgo_detach
)(uao
);
1620 error
= uvm_map_pageable(kernel_map
, lcp
->lcp_kaddr
,
1621 lcp
->lcp_kaddr
+ PAGE_SIZE
, FALSE
, 0);
1623 mutex_exit(&lp
->lp_lock
);
1624 uvm_unmap(kernel_map
, lcp
->lcp_kaddr
,
1625 lcp
->lcp_kaddr
+ PAGE_SIZE
);
1626 kmem_free(lcp
, LWPCTL_LCPAGE_SZ
);
1629 /* Prepare the page descriptor and link into the list. */
1630 lcp
->lcp_uaddr
= lp
->lp_uva
+ lp
->lp_cur
;
1631 lp
->lp_cur
+= PAGE_SIZE
;
1632 lcp
->lcp_nfree
= LWPCTL_PER_PAGE
;
1634 memset(lcp
->lcp_bitmap
, 0xff, LWPCTL_BITMAP_SZ
);
1635 TAILQ_INSERT_HEAD(&lp
->lp_pages
, lcp
, lcp_chain
);
1637 for (i
= lcp
->lcp_rotor
; lcp
->lcp_bitmap
[i
] == 0;) {
1638 if (++i
>= LWPCTL_BITMAP_ENTRIES
)
1641 bit
= ffs(lcp
->lcp_bitmap
[i
]) - 1;
1642 lcp
->lcp_bitmap
[i
] ^= (1 << bit
);
1646 offset
= (i
<< 5) + bit
;
1647 l
->l_lwpctl
= (lwpctl_t
*)lcp
->lcp_kaddr
+ offset
;
1648 *uaddr
= lcp
->lcp_uaddr
+ offset
* sizeof(lwpctl_t
);
1649 mutex_exit(&lp
->lp_lock
);
1651 KPREEMPT_DISABLE(l
);
1652 l
->l_lwpctl
->lc_curcpu
= (int)curcpu()->ci_data
.cpu_index
;
1659 * Free an lwpctl structure back to the per-process list.
1662 lwp_ctl_free(lwp_t
*l
)
1668 lp
= l
->l_proc
->p_lwpctl
;
1669 KASSERT(lp
!= NULL
);
1672 offset
= (u_int
)((lwpctl_t
*)l
->l_lwpctl
- (lwpctl_t
*)lcp
->lcp_kaddr
);
1673 KASSERT(offset
< LWPCTL_PER_PAGE
);
1675 mutex_enter(&lp
->lp_lock
);
1678 lcp
->lcp_bitmap
[map
] |= (1 << (offset
& 31));
1679 if (lcp
->lcp_bitmap
[lcp
->lcp_rotor
] == 0)
1680 lcp
->lcp_rotor
= map
;
1681 if (TAILQ_FIRST(&lp
->lp_pages
)->lcp_nfree
== 0) {
1682 TAILQ_REMOVE(&lp
->lp_pages
, lcp
, lcp_chain
);
1683 TAILQ_INSERT_HEAD(&lp
->lp_pages
, lcp
, lcp_chain
);
1685 mutex_exit(&lp
->lp_lock
);
1689 * Process is exiting; tear down lwpctl state. This can only be safely
1690 * called by the last LWP in the process.
1695 lcpage_t
*lcp
, *next
;
1706 KASSERT(lp
!= NULL
);
1707 KASSERT(p
->p_nlwps
== 1);
1709 for (lcp
= TAILQ_FIRST(&lp
->lp_pages
); lcp
!= NULL
; lcp
= next
) {
1710 next
= TAILQ_NEXT(lcp
, lcp_chain
);
1711 uvm_unmap(kernel_map
, lcp
->lcp_kaddr
,
1712 lcp
->lcp_kaddr
+ PAGE_SIZE
);
1713 kmem_free(lcp
, LWPCTL_LCPAGE_SZ
);
1716 if (lp
->lp_uao
!= NULL
) {
1717 uvm_unmap(&p
->p_vmspace
->vm_map
, lp
->lp_uva
,
1718 lp
->lp_uva
+ LWPCTL_UAREA_SZ
);
1721 mutex_destroy(&lp
->lp_lock
);
1722 kmem_free(lp
, sizeof(*lp
));
1727 * Return the current LWP's "preemption counter". Used to detect
1728 * preemption across operations that can tolerate preemption without
1729 * crashing, but which may generate incorrect results if preempted.
1735 return curlwp
->l_ncsw
;
1740 lwp_whatis(uintptr_t addr
, void (*pr
)(const char *, ...))
1744 LIST_FOREACH(l
, &alllwp
, l_list
) {
1745 uintptr_t stack
= (uintptr_t)KSTACK_LOWEST_ADDR(l
);
1747 if (addr
< stack
|| stack
+ KSTACK_SIZE
<= addr
) {
1750 (*pr
)("%p is %p+%zu, LWP %p's stack\n",
1751 (void *)addr
, (void *)stack
,
1752 (size_t)(addr
- stack
), l
);
1755 #endif /* defined(DDB) */