2 * Copyright (c) 1982, 1986, 1990, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
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.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95
35 * $FreeBSD: src/sys/kern/kern_synch.c,v 1.87.2.6 2002/10/13 07:29:53 kbyanc Exp $
38 #include "opt_ktrace.h"
40 #include <sys/param.h>
41 #include <sys/systm.h>
43 #include <sys/kernel.h>
44 #include <sys/signalvar.h>
45 #include <sys/resourcevar.h>
46 #include <sys/vmmeter.h>
47 #include <sys/sysctl.h>
50 #include <sys/kcollect.h>
52 #include <sys/ktrace.h>
55 #include <sys/serialize.h>
57 #include <sys/signal2.h>
58 #include <sys/thread2.h>
59 #include <sys/spinlock2.h>
60 #include <sys/mutex2.h>
62 #include <machine/cpu.h>
63 #include <machine/smp.h>
65 TAILQ_HEAD(tslpque
, thread
);
67 static void sched_setup (void *dummy
);
68 SYSINIT(sched_setup
, SI_SUB_KICK_SCHEDULER
, SI_ORDER_FIRST
, sched_setup
, NULL
);
72 int sched_quantum
; /* Roundrobin scheduling quantum in ticks. */
74 int ncpus2
, ncpus2_shift
, ncpus2_mask
; /* note: mask not cpumask_t */
75 int ncpus_fit
, ncpus_fit_mask
; /* note: mask not cpumask_t */
78 int tsleep_crypto_dump
= 0;
80 MALLOC_DEFINE(M_TSLEEP
, "tslpque", "tsleep queues");
82 #define __DEALL(ident) __DEQUALIFY(void *, ident)
84 #if !defined(KTR_TSLEEP)
85 #define KTR_TSLEEP KTR_ALL
87 KTR_INFO_MASTER(tsleep
);
88 KTR_INFO(KTR_TSLEEP
, tsleep
, tsleep_beg
, 0, "tsleep enter %p", const volatile void *ident
);
89 KTR_INFO(KTR_TSLEEP
, tsleep
, tsleep_end
, 1, "tsleep exit");
90 KTR_INFO(KTR_TSLEEP
, tsleep
, wakeup_beg
, 2, "wakeup enter %p", const volatile void *ident
);
91 KTR_INFO(KTR_TSLEEP
, tsleep
, wakeup_end
, 3, "wakeup exit");
92 KTR_INFO(KTR_TSLEEP
, tsleep
, ilockfail
, 4, "interlock failed %p", const volatile void *ident
);
94 #define logtsleep1(name) KTR_LOG(tsleep_ ## name)
95 #define logtsleep2(name, val) KTR_LOG(tsleep_ ## name, val)
97 struct loadavg averunnable
=
98 { {0, 0, 0}, FSCALE
}; /* load average, of runnable procs */
100 * Constants for averages over 1, 5, and 15 minutes
101 * when sampling at 5 second intervals.
103 static fixpt_t cexp
[3] = {
104 0.9200444146293232 * FSCALE
, /* exp(-1/12) */
105 0.9834714538216174 * FSCALE
, /* exp(-1/60) */
106 0.9944598480048967 * FSCALE
, /* exp(-1/180) */
109 static void endtsleep (void *);
110 static void loadav (void *arg
);
111 static void schedcpu (void *arg
);
114 * Adjust the scheduler quantum. The quantum is specified in microseconds.
115 * Note that 'tick' is in microseconds per tick.
118 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS
)
122 new_val
= sched_quantum
* ustick
;
123 error
= sysctl_handle_int(oidp
, &new_val
, 0, req
);
124 if (error
!= 0 || req
->newptr
== NULL
)
126 if (new_val
< ustick
)
128 sched_quantum
= new_val
/ ustick
;
132 SYSCTL_PROC(_kern
, OID_AUTO
, quantum
, CTLTYPE_INT
|CTLFLAG_RW
,
133 0, sizeof sched_quantum
, sysctl_kern_quantum
, "I", "");
135 static int pctcpu_decay
= 10;
136 SYSCTL_INT(_kern
, OID_AUTO
, pctcpu_decay
, CTLFLAG_RW
, &pctcpu_decay
, 0, "");
139 * kernel uses `FSCALE', userland (SHOULD) use kern.fscale
141 int fscale __unused
= FSCALE
; /* exported to systat */
142 SYSCTL_INT(_kern
, OID_AUTO
, fscale
, CTLFLAG_RD
, 0, FSCALE
, "");
145 * Recompute process priorities, once a second.
147 * Since the userland schedulers are typically event oriented, if the
148 * estcpu calculation at wakeup() time is not sufficient to make a
149 * process runnable relative to other processes in the system we have
150 * a 1-second recalc to help out.
152 * This code also allows us to store sysclock_t data in the process structure
153 * without fear of an overrun, since sysclock_t are guarenteed to hold
154 * several seconds worth of count.
156 * WARNING! callouts can preempt normal threads. However, they will not
157 * preempt a thread holding a spinlock so we *can* safely use spinlocks.
159 static int schedcpu_stats(struct proc
*p
, void *data __unused
);
160 static int schedcpu_resource(struct proc
*p
, void *data __unused
);
165 allproc_scan(schedcpu_stats
, NULL
, 1);
166 allproc_scan(schedcpu_resource
, NULL
, 1);
167 if (mycpu
->gd_cpuid
== 0) {
168 wakeup((caddr_t
)&lbolt
);
169 wakeup(lbolt_syncer
);
171 callout_reset(&mycpu
->gd_schedcpu_callout
, hz
, schedcpu
, NULL
);
175 * General process statistics once a second
178 schedcpu_stats(struct proc
*p
, void *data __unused
)
183 * Threads may not be completely set up if process in SIDL state.
185 if (p
->p_stat
== SIDL
)
189 if (lwkt_trytoken(&p
->p_token
) == FALSE
) {
195 FOREACH_LWP_IN_PROC(lp
, p
) {
196 if (lp
->lwp_stat
== LSSLEEP
) {
198 if (lp
->lwp_slptime
== 1)
199 p
->p_usched
->uload_update(lp
);
203 * Only recalculate processes that are active or have slept
204 * less then 2 seconds. The schedulers understand this.
205 * Otherwise decay by 50% per second.
207 if (lp
->lwp_slptime
<= 1) {
208 p
->p_usched
->recalculate(lp
);
212 decay
= pctcpu_decay
;
218 lp
->lwp_pctcpu
= (lp
->lwp_pctcpu
* (decay
- 1)) / decay
;
221 lwkt_reltoken(&p
->p_token
);
228 * Resource checks. XXX break out since ksignal/killproc can block,
229 * limiting us to one process killed per second. There is probably
233 schedcpu_resource(struct proc
*p
, void *data __unused
)
238 if (p
->p_stat
== SIDL
)
242 if (lwkt_trytoken(&p
->p_token
) == FALSE
) {
247 if (p
->p_stat
== SZOMB
|| p
->p_limit
== NULL
) {
248 lwkt_reltoken(&p
->p_token
);
254 FOREACH_LWP_IN_PROC(lp
, p
) {
256 * We may have caught an lp in the middle of being
257 * created, lwp_thread can be NULL.
259 if (lp
->lwp_thread
) {
260 ttime
+= lp
->lwp_thread
->td_sticks
;
261 ttime
+= lp
->lwp_thread
->td_uticks
;
265 switch(plimit_testcpulimit(p
->p_limit
, ttime
)) {
266 case PLIMIT_TESTCPU_KILL
:
267 killproc(p
, "exceeded maximum CPU limit");
269 case PLIMIT_TESTCPU_XCPU
:
270 if ((p
->p_flags
& P_XCPU
) == 0) {
271 p
->p_flags
|= P_XCPU
;
278 lwkt_reltoken(&p
->p_token
);
288 schedcpu_setup(void *arg
)
290 globaldata_t save_gd
= mycpu
;
294 for (n
= 0; n
< ncpus
; ++n
) {
295 gd
= globaldata_find(n
);
296 lwkt_setcpu_self(gd
);
297 callout_init_mp(&gd
->gd_loadav_callout
);
298 callout_init_mp(&gd
->gd_schedcpu_callout
);
302 lwkt_setcpu_self(save_gd
);
306 * This is only used by ps. Generate a cpu percentage use over
307 * a period of one second.
310 updatepcpu(struct lwp
*lp
, int cpticks
, int ttlticks
)
315 acc
= (cpticks
<< FSHIFT
) / ttlticks
;
316 if (ttlticks
>= ESTCPUFREQ
) {
317 lp
->lwp_pctcpu
= acc
;
319 remticks
= ESTCPUFREQ
- ttlticks
;
320 lp
->lwp_pctcpu
= (acc
* ttlticks
+ lp
->lwp_pctcpu
* remticks
) /
326 * tsleep/wakeup hash table parameters. Try to find the sweet spot for
327 * like addresses being slept on. The larger the table, the fewer
328 * unnecessary IPIs. However, larger sizes also have diminishing returns
331 #define TABLESIZE 8191 /* 4001, 8191, or 16369 */
332 #define LOOKUP(x) (((u_int)(uintptr_t)(x)) % TABLESIZE)
334 static cpumask_t slpque_cpumasks
[TABLESIZE
];
337 * General scheduler initialization. We force a reschedule 25 times
338 * a second by default. Note that cpu0 is initialized in early boot and
339 * cannot make any high level calls.
341 * Each cpu has its own sleep queue.
344 sleep_gdinit(globaldata_t gd
)
346 static struct tslpque slpque_cpu0
[TABLESIZE
];
349 if (gd
->gd_cpuid
== 0) {
350 sched_quantum
= (hz
+ 24) / 25;
351 gd
->gd_tsleep_hash
= slpque_cpu0
;
353 gd
->gd_tsleep_hash
= kmalloc(sizeof(slpque_cpu0
),
354 M_TSLEEP
, M_WAITOK
| M_ZERO
);
356 for (i
= 0; i
< TABLESIZE
; ++i
)
357 TAILQ_INIT(&gd
->gd_tsleep_hash
[i
]);
361 * This is a dandy function that allows us to interlock tsleep/wakeup
362 * operations with unspecified upper level locks, such as lockmgr locks,
363 * simply by holding a critical section. The sequence is:
365 * (acquire upper level lock)
366 * tsleep_interlock(blah)
367 * (release upper level lock)
370 * Basically this functions queues us on the tsleep queue without actually
371 * descheduling us. When tsleep() is later called with PINTERLOCK it
372 * assumes the thread was already queued, otherwise it queues it there.
374 * Thus it is possible to receive the wakeup prior to going to sleep and
375 * the race conditions are covered.
378 _tsleep_interlock(globaldata_t gd
, const volatile void *ident
, int flags
)
380 thread_t td
= gd
->gd_curthread
;
383 crit_enter_quick(td
);
384 if (td
->td_flags
& TDF_TSLEEPQ
) {
385 id
= LOOKUP(td
->td_wchan
);
386 TAILQ_REMOVE(&gd
->gd_tsleep_hash
[id
], td
, td_sleepq
);
387 if (TAILQ_FIRST(&gd
->gd_tsleep_hash
[id
]) == NULL
) {
388 ATOMIC_CPUMASK_NANDBIT(slpque_cpumasks
[id
],
392 td
->td_flags
|= TDF_TSLEEPQ
;
395 TAILQ_INSERT_TAIL(&gd
->gd_tsleep_hash
[id
], td
, td_sleepq
);
396 ATOMIC_CPUMASK_ORBIT(slpque_cpumasks
[id
], gd
->gd_cpuid
);
397 td
->td_wchan
= ident
;
398 td
->td_wdomain
= flags
& PDOMAIN_MASK
;
403 tsleep_interlock(const volatile void *ident
, int flags
)
405 _tsleep_interlock(mycpu
, ident
, flags
);
409 * Remove thread from sleepq. Must be called with a critical section held.
410 * The thread must not be migrating.
413 _tsleep_remove(thread_t td
)
415 globaldata_t gd
= mycpu
;
418 KKASSERT(td
->td_gd
== gd
&& IN_CRITICAL_SECT(td
));
419 KKASSERT((td
->td_flags
& TDF_MIGRATING
) == 0);
420 if (td
->td_flags
& TDF_TSLEEPQ
) {
421 td
->td_flags
&= ~TDF_TSLEEPQ
;
422 id
= LOOKUP(td
->td_wchan
);
423 TAILQ_REMOVE(&gd
->gd_tsleep_hash
[id
], td
, td_sleepq
);
424 if (TAILQ_FIRST(&gd
->gd_tsleep_hash
[id
]) == NULL
) {
425 ATOMIC_CPUMASK_NANDBIT(slpque_cpumasks
[id
],
434 tsleep_remove(thread_t td
)
440 * General sleep call. Suspends the current process until a wakeup is
441 * performed on the specified identifier. The process will then be made
442 * runnable with the specified priority. Sleeps at most timo/hz seconds
443 * (0 means no timeout). If flags includes PCATCH flag, signals are checked
444 * before and after sleeping, else signals are not checked. Returns 0 if
445 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
446 * signal needs to be delivered, ERESTART is returned if the current system
447 * call should be restarted if possible, and EINTR is returned if the system
448 * call should be interrupted by the signal (return EINTR).
450 * Note that if we are a process, we release_curproc() before messing with
451 * the LWKT scheduler.
453 * During autoconfiguration or after a panic, a sleep will simply
454 * lower the priority briefly to allow interrupts, then return.
456 * WARNING! This code can't block (short of switching away), or bad things
457 * will happen. No getting tokens, no blocking locks, etc.
460 tsleep(const volatile void *ident
, int flags
, const char *wmesg
, int timo
)
462 struct thread
*td
= curthread
;
463 struct lwp
*lp
= td
->td_lwp
;
464 struct proc
*p
= td
->td_proc
; /* may be NULL */
470 struct callout thandle
;
473 * Currently a severe hack. Make sure any delayed wakeups
474 * are flushed before we sleep or we might deadlock on whatever
475 * event we are sleeping on.
477 if (td
->td_flags
& TDF_DELAYED_WAKEUP
)
478 wakeup_end_delayed();
481 * NOTE: removed KTRPOINT, it could cause races due to blocking
482 * even in stable. Just scrap it for now.
484 if (!tsleep_crypto_dump
&& (tsleep_now_works
== 0 || panicstr
)) {
486 * After a panic, or before we actually have an operational
487 * softclock, just give interrupts a chance, then just return;
489 * don't run any other procs or panic below,
490 * in case this is the idle process and already asleep.
494 lwkt_setpri_self(safepri
);
496 lwkt_setpri_self(oldpri
);
499 logtsleep2(tsleep_beg
, ident
);
501 KKASSERT(td
!= &gd
->gd_idlethread
); /* you must be kidding! */
502 td
->td_wakefromcpu
= -1; /* overwritten by _wakeup */
505 * NOTE: all of this occurs on the current cpu, including any
506 * callout-based wakeups, so a critical section is a sufficient
509 * The entire sequence through to where we actually sleep must
510 * run without breaking the critical section.
512 catch = flags
& PCATCH
;
516 crit_enter_quick(td
);
518 KASSERT(ident
!= NULL
, ("tsleep: no ident"));
519 KASSERT(lp
== NULL
||
520 lp
->lwp_stat
== LSRUN
|| /* Obvious */
521 lp
->lwp_stat
== LSSTOP
, /* Set in tstop */
523 ident
, wmesg
, lp
->lwp_stat
));
526 * We interlock the sleep queue if the caller has not already done
527 * it for us. This must be done before we potentially acquire any
528 * tokens or we can loose the wakeup.
530 if ((flags
& PINTERLOCKED
) == 0) {
531 _tsleep_interlock(gd
, ident
, flags
);
535 * Setup for the current process (if this is a process). We must
536 * interlock with lwp_token to avoid remote wakeup races via
540 lwkt_gettoken(&lp
->lwp_token
);
543 * If the umbrella process is in the SCORE state then
544 * make sure that the thread is flagged going into a
545 * normal sleep to allow the core dump to proceed, otherwise
546 * the coredump can end up waiting forever. If the normal
547 * sleep is woken up, the thread will enter a stopped state
548 * upon return to userland.
550 * We do not want to interrupt or cause a thread exist at
551 * this juncture because that will mess-up the state the
552 * coredump is trying to save.
554 if (p
->p_stat
== SCORE
&&
555 (lp
->lwp_mpflags
& LWP_MP_WSTOP
) == 0) {
556 atomic_set_int(&lp
->lwp_mpflags
, LWP_MP_WSTOP
);
565 * Early termination if PCATCH was set and a
566 * signal is pending, interlocked with the
569 * Early termination only occurs when tsleep() is
570 * entered while in a normal LSRUN state.
572 if ((sig
= CURSIG(lp
)) != 0)
576 * Causes ksignal to wake us up if a signal is
577 * received (interlocked with lp->lwp_token).
579 lp
->lwp_flags
|= LWP_SINTR
;
586 * Make sure the current process has been untangled from
587 * the userland scheduler and initialize slptime to start
590 * NOTE: td->td_wakefromcpu is pre-set by the release function
591 * for the dfly scheduler, and then adjusted by _wakeup()
594 p
->p_usched
->release_curproc(lp
);
599 * If the interlocked flag is set but our cpu bit in the slpqueue
600 * is no longer set, then a wakeup was processed inbetween the
601 * tsleep_interlock() (ours or the callers), and here. This can
602 * occur under numerous circumstances including when we release the
605 * Extreme loads can cause the sending of an IPI (e.g. wakeup()'s)
606 * to process incoming IPIs, thus draining incoming wakeups.
608 if ((td
->td_flags
& TDF_TSLEEPQ
) == 0) {
609 logtsleep2(ilockfail
, ident
);
614 * scheduling is blocked while in a critical section. Coincide
615 * the descheduled-by-tsleep flag with the descheduling of the
618 * The timer callout is localized on our cpu and interlocked by
619 * our critical section.
621 lwkt_deschedule_self(td
);
622 td
->td_flags
|= TDF_TSLEEP_DESCHEDULED
;
623 td
->td_wmesg
= wmesg
;
626 * Setup the timeout, if any. The timeout is only operable while
627 * the thread is flagged descheduled.
629 KKASSERT((td
->td_flags
& TDF_TIMEOUT
) == 0);
631 callout_init_mp(&thandle
);
632 callout_reset(&thandle
, timo
, endtsleep
, td
);
640 * Ok, we are sleeping. Place us in the SSLEEP state.
642 KKASSERT((lp
->lwp_mpflags
& LWP_MP_ONRUNQ
) == 0);
645 * tstop() sets LSSTOP, so don't fiddle with that.
647 if (lp
->lwp_stat
!= LSSTOP
)
648 lp
->lwp_stat
= LSSLEEP
;
649 lp
->lwp_ru
.ru_nvcsw
++;
650 p
->p_usched
->uload_update(lp
);
654 * And when we are woken up, put us back in LSRUN. If we
655 * slept for over a second, recalculate our estcpu.
657 lp
->lwp_stat
= LSRUN
;
658 if (lp
->lwp_slptime
) {
659 p
->p_usched
->uload_update(lp
);
660 p
->p_usched
->recalculate(lp
);
668 * Make sure we haven't switched cpus while we were asleep. It's
669 * not supposed to happen. Cleanup our temporary flags.
671 KKASSERT(gd
== td
->td_gd
);
674 * Cleanup the timeout. If the timeout has already occured thandle
675 * has already been stopped, otherwise stop thandle. If the timeout
676 * is running (the callout thread must be blocked trying to get
677 * lwp_token) then wait for us to get scheduled.
680 while (td
->td_flags
& TDF_TIMEOUT_RUNNING
) {
681 /* else we won't get rescheduled! */
682 if (lp
->lwp_stat
!= LSSTOP
)
683 lp
->lwp_stat
= LSSLEEP
;
684 lwkt_deschedule_self(td
);
685 td
->td_wmesg
= "tsrace";
687 kprintf("td %p %s: timeout race\n", td
, td
->td_comm
);
689 if (td
->td_flags
& TDF_TIMEOUT
) {
690 td
->td_flags
&= ~TDF_TIMEOUT
;
693 /* does not block when on same cpu */
694 callout_stop(&thandle
);
697 td
->td_flags
&= ~TDF_TSLEEP_DESCHEDULED
;
700 * Make sure we have been removed from the sleepq. In most
701 * cases this will have been done for us already but it is
702 * possible for a scheduling IPI to be in-flight from a
703 * previous tsleep/tsleep_interlock() or due to a straight-out
704 * call to lwkt_schedule() (in the case of an interrupt thread),
705 * causing a spurious wakeup.
711 * Figure out the correct error return. If interrupted by a
712 * signal we want to return EINTR or ERESTART.
716 if (catch && error
== 0) {
717 if (sig
!= 0 || (sig
= CURSIG(lp
))) {
718 if (SIGISMEMBER(p
->p_sigacts
->ps_sigintr
, sig
))
725 lp
->lwp_flags
&= ~LWP_SINTR
;
728 * Unconditionally set us to LSRUN on resume. lwp_stat could
729 * be in a weird state due to the goto resume, particularly
730 * when tsleep() is called from tstop().
732 lp
->lwp_stat
= LSRUN
;
733 lwkt_reltoken(&lp
->lwp_token
);
735 logtsleep1(tsleep_end
);
741 * Interlocked spinlock sleep. An exclusively held spinlock must
742 * be passed to ssleep(). The function will atomically release the
743 * spinlock and tsleep on the ident, then reacquire the spinlock and
746 * This routine is fairly important along the critical path, so optimize it
750 ssleep(const volatile void *ident
, struct spinlock
*spin
, int flags
,
751 const char *wmesg
, int timo
)
753 globaldata_t gd
= mycpu
;
756 _tsleep_interlock(gd
, ident
, flags
);
757 spin_unlock_quick(gd
, spin
);
758 error
= tsleep(ident
, flags
| PINTERLOCKED
, wmesg
, timo
);
759 _spin_lock_quick(gd
, spin
, wmesg
);
765 lksleep(const volatile void *ident
, struct lock
*lock
, int flags
,
766 const char *wmesg
, int timo
)
768 globaldata_t gd
= mycpu
;
771 _tsleep_interlock(gd
, ident
, flags
);
772 lockmgr(lock
, LK_RELEASE
);
773 error
= tsleep(ident
, flags
| PINTERLOCKED
, wmesg
, timo
);
774 lockmgr(lock
, LK_EXCLUSIVE
);
780 * Interlocked mutex sleep. An exclusively held mutex must be passed
781 * to mtxsleep(). The function will atomically release the mutex
782 * and tsleep on the ident, then reacquire the mutex and return.
785 mtxsleep(const volatile void *ident
, struct mtx
*mtx
, int flags
,
786 const char *wmesg
, int timo
)
788 globaldata_t gd
= mycpu
;
791 _tsleep_interlock(gd
, ident
, flags
);
793 error
= tsleep(ident
, flags
| PINTERLOCKED
, wmesg
, timo
);
794 mtx_lock_ex_quick(mtx
);
800 * Interlocked serializer sleep. An exclusively held serializer must
801 * be passed to zsleep(). The function will atomically release
802 * the serializer and tsleep on the ident, then reacquire the serializer
806 zsleep(const volatile void *ident
, struct lwkt_serialize
*slz
, int flags
,
807 const char *wmesg
, int timo
)
809 globaldata_t gd
= mycpu
;
812 ASSERT_SERIALIZED(slz
);
814 _tsleep_interlock(gd
, ident
, flags
);
815 lwkt_serialize_exit(slz
);
816 ret
= tsleep(ident
, flags
| PINTERLOCKED
, wmesg
, timo
);
817 lwkt_serialize_enter(slz
);
823 * Directly block on the LWKT thread by descheduling it. This
824 * is much faster then tsleep(), but the only legal way to wake
825 * us up is to directly schedule the thread.
827 * Setting TDF_SINTR will cause new signals to directly schedule us.
829 * This routine must be called while in a critical section.
832 lwkt_sleep(const char *wmesg
, int flags
)
834 thread_t td
= curthread
;
837 if ((flags
& PCATCH
) == 0 || td
->td_lwp
== NULL
) {
838 td
->td_flags
|= TDF_BLOCKED
;
839 td
->td_wmesg
= wmesg
;
840 lwkt_deschedule_self(td
);
843 td
->td_flags
&= ~TDF_BLOCKED
;
846 if ((sig
= CURSIG(td
->td_lwp
)) != 0) {
847 if (SIGISMEMBER(td
->td_proc
->p_sigacts
->ps_sigintr
, sig
))
853 td
->td_flags
|= TDF_BLOCKED
| TDF_SINTR
;
854 td
->td_wmesg
= wmesg
;
855 lwkt_deschedule_self(td
);
857 td
->td_flags
&= ~(TDF_BLOCKED
| TDF_SINTR
);
863 * Implement the timeout for tsleep.
865 * This type of callout timeout is scheduled on the same cpu the process
866 * is sleeping on. Also, at the moment, the MP lock is held.
875 * We are going to have to get the lwp_token, which means we might
876 * block. This can race a tsleep getting woken up by other means
877 * so set TDF_TIMEOUT_RUNNING to force the tsleep to wait for our
878 * processing to complete (sorry tsleep!).
880 * We can safely set td_flags because td MUST be on the same cpu
883 KKASSERT(td
->td_gd
== mycpu
);
885 td
->td_flags
|= TDF_TIMEOUT_RUNNING
| TDF_TIMEOUT
;
888 * This can block but TDF_TIMEOUT_RUNNING will prevent the thread
889 * from exiting the tsleep on us. The flag is interlocked by virtue
890 * of lp being on the same cpu as we are.
892 if ((lp
= td
->td_lwp
) != NULL
)
893 lwkt_gettoken(&lp
->lwp_token
);
895 KKASSERT(td
->td_flags
& TDF_TSLEEP_DESCHEDULED
);
899 * callout timer should normally never be set in tstop()
900 * because it passes a timeout of 0. However, there is a
901 * case during thread exit (which SSTOP's all the threads)
902 * for which tstop() must break out and can (properly) leave
903 * the thread in LSSTOP.
905 KKASSERT(lp
->lwp_stat
!= LSSTOP
||
906 (lp
->lwp_mpflags
& LWP_MP_WEXIT
));
908 lwkt_reltoken(&lp
->lwp_token
);
913 KKASSERT(td
->td_gd
== mycpu
);
914 td
->td_flags
&= ~TDF_TIMEOUT_RUNNING
;
919 * Make all processes sleeping on the specified identifier runnable.
920 * count may be zero or one only.
922 * The domain encodes the sleep/wakeup domain, flags, plus the originating
925 * This call may run without the MP lock held. We can only manipulate thread
926 * state on the cpu owning the thread. We CANNOT manipulate process state
929 * _wakeup() can be passed to an IPI so we can't use (const volatile
933 _wakeup(void *ident
, int domain
)
943 logtsleep2(wakeup_beg
, ident
);
946 qp
= &gd
->gd_tsleep_hash
[id
];
948 for (td
= TAILQ_FIRST(qp
); td
!= NULL
; td
= ntd
) {
949 ntd
= TAILQ_NEXT(td
, td_sleepq
);
950 if (td
->td_wchan
== ident
&&
951 td
->td_wdomain
== (domain
& PDOMAIN_MASK
)
953 KKASSERT(td
->td_gd
== gd
);
955 td
->td_wakefromcpu
= PWAKEUP_DECODE(domain
);
956 if (td
->td_flags
& TDF_TSLEEP_DESCHEDULED
) {
958 if (domain
& PWAKEUP_ONE
)
966 * We finished checking the current cpu but there still may be
967 * more work to do. Either wakeup_one was requested and no matching
968 * thread was found, or a normal wakeup was requested and we have
969 * to continue checking cpus.
971 * It should be noted that this scheme is actually less expensive then
972 * the old scheme when waking up multiple threads, since we send
973 * only one IPI message per target candidate which may then schedule
974 * multiple threads. Before we could have wound up sending an IPI
975 * message for each thread on the target cpu (!= current cpu) that
976 * needed to be woken up.
978 * NOTE: Wakeups occuring on remote cpus are asynchronous. This
979 * should be ok since we are passing idents in the IPI rather then
982 if ((domain
& PWAKEUP_MYCPU
) == 0) {
983 mask
= slpque_cpumasks
[id
];
984 CPUMASK_ANDMASK(mask
, gd
->gd_other_cpus
);
985 if (CPUMASK_TESTNZERO(mask
)) {
986 lwkt_send_ipiq2_mask(mask
, _wakeup
, ident
,
987 domain
| PWAKEUP_MYCPU
);
991 logtsleep1(wakeup_end
);
996 * Wakeup all threads tsleep()ing on the specified ident, on all cpus
999 wakeup(const volatile void *ident
)
1001 globaldata_t gd
= mycpu
;
1002 thread_t td
= gd
->gd_curthread
;
1004 if (td
&& (td
->td_flags
& TDF_DELAYED_WAKEUP
)) {
1006 * If we are in a delayed wakeup section, record up to two wakeups in
1007 * a per-CPU queue and issue them when we block or exit the delayed
1010 if (atomic_cmpset_ptr(&gd
->gd_delayed_wakeup
[0], NULL
, ident
))
1012 if (atomic_cmpset_ptr(&gd
->gd_delayed_wakeup
[1], NULL
, ident
))
1015 ident
= atomic_swap_ptr(__DEQUALIFY(volatile void **, &gd
->gd_delayed_wakeup
[1]),
1017 ident
= atomic_swap_ptr(__DEQUALIFY(volatile void **, &gd
->gd_delayed_wakeup
[0]),
1021 _wakeup(__DEALL(ident
), PWAKEUP_ENCODE(0, gd
->gd_cpuid
));
1025 * Wakeup one thread tsleep()ing on the specified ident, on any cpu.
1028 wakeup_one(const volatile void *ident
)
1030 /* XXX potentially round-robin the first responding cpu */
1031 _wakeup(__DEALL(ident
), PWAKEUP_ENCODE(0, mycpu
->gd_cpuid
) |
1036 * Wakeup threads tsleep()ing on the specified ident on the current cpu
1040 wakeup_mycpu(const volatile void *ident
)
1042 _wakeup(__DEALL(ident
), PWAKEUP_ENCODE(0, mycpu
->gd_cpuid
) |
1047 * Wakeup one thread tsleep()ing on the specified ident on the current cpu
1051 wakeup_mycpu_one(const volatile void *ident
)
1053 /* XXX potentially round-robin the first responding cpu */
1054 _wakeup(__DEALL(ident
), PWAKEUP_ENCODE(0, mycpu
->gd_cpuid
) |
1055 PWAKEUP_MYCPU
| PWAKEUP_ONE
);
1059 * Wakeup all thread tsleep()ing on the specified ident on the specified cpu
1063 wakeup_oncpu(globaldata_t gd
, const volatile void *ident
)
1065 globaldata_t mygd
= mycpu
;
1067 _wakeup(__DEALL(ident
), PWAKEUP_ENCODE(0, mygd
->gd_cpuid
) |
1070 lwkt_send_ipiq2(gd
, _wakeup
, __DEALL(ident
),
1071 PWAKEUP_ENCODE(0, mygd
->gd_cpuid
) |
1077 * Wakeup one thread tsleep()ing on the specified ident on the specified cpu
1081 wakeup_oncpu_one(globaldata_t gd
, const volatile void *ident
)
1083 globaldata_t mygd
= mycpu
;
1085 _wakeup(__DEALL(ident
), PWAKEUP_ENCODE(0, mygd
->gd_cpuid
) |
1086 PWAKEUP_MYCPU
| PWAKEUP_ONE
);
1088 lwkt_send_ipiq2(gd
, _wakeup
, __DEALL(ident
),
1089 PWAKEUP_ENCODE(0, mygd
->gd_cpuid
) |
1090 PWAKEUP_MYCPU
| PWAKEUP_ONE
);
1095 * Wakeup all threads waiting on the specified ident that slept using
1096 * the specified domain, on all cpus.
1099 wakeup_domain(const volatile void *ident
, int domain
)
1101 _wakeup(__DEALL(ident
), PWAKEUP_ENCODE(domain
, mycpu
->gd_cpuid
));
1105 * Wakeup one thread waiting on the specified ident that slept using
1106 * the specified domain, on any cpu.
1109 wakeup_domain_one(const volatile void *ident
, int domain
)
1111 /* XXX potentially round-robin the first responding cpu */
1112 _wakeup(__DEALL(ident
),
1113 PWAKEUP_ENCODE(domain
, mycpu
->gd_cpuid
) | PWAKEUP_ONE
);
1117 wakeup_start_delayed(void)
1119 globaldata_t gd
= mycpu
;
1122 gd
->gd_curthread
->td_flags
|= TDF_DELAYED_WAKEUP
;
1127 wakeup_end_delayed(void)
1129 globaldata_t gd
= mycpu
;
1131 if (gd
->gd_curthread
->td_flags
& TDF_DELAYED_WAKEUP
) {
1133 gd
->gd_curthread
->td_flags
&= ~TDF_DELAYED_WAKEUP
;
1134 if (gd
->gd_delayed_wakeup
[0] || gd
->gd_delayed_wakeup
[1]) {
1135 if (gd
->gd_delayed_wakeup
[0]) {
1136 wakeup(gd
->gd_delayed_wakeup
[0]);
1137 gd
->gd_delayed_wakeup
[0] = NULL
;
1139 if (gd
->gd_delayed_wakeup
[1]) {
1140 wakeup(gd
->gd_delayed_wakeup
[1]);
1141 gd
->gd_delayed_wakeup
[1] = NULL
;
1151 * Make a process runnable. lp->lwp_token must be held on call and this
1152 * function must be called from the cpu owning lp.
1154 * This only has an effect if we are in LSSTOP or LSSLEEP.
1157 setrunnable(struct lwp
*lp
)
1159 thread_t td
= lp
->lwp_thread
;
1161 ASSERT_LWKT_TOKEN_HELD(&lp
->lwp_token
);
1162 KKASSERT(td
->td_gd
== mycpu
);
1164 if (lp
->lwp_stat
== LSSTOP
)
1165 lp
->lwp_stat
= LSSLEEP
;
1166 if (lp
->lwp_stat
== LSSLEEP
) {
1169 } else if (td
->td_flags
& TDF_SINTR
) {
1176 * The process is stopped due to some condition, usually because p_stat is
1177 * set to SSTOP, but also possibly due to being traced.
1179 * Caller must hold p->p_token
1181 * NOTE! If the caller sets SSTOP, the caller must also clear P_WAITED
1182 * because the parent may check the child's status before the child actually
1183 * gets to this routine.
1185 * This routine is called with the current lwp only, typically just
1186 * before returning to userland if the process state is detected as
1187 * possibly being in a stopped state.
1192 struct lwp
*lp
= curthread
->td_lwp
;
1193 struct proc
*p
= lp
->lwp_proc
;
1196 lwkt_gettoken(&lp
->lwp_token
);
1200 * If LWP_MP_WSTOP is set, we were sleeping
1201 * while our process was stopped. At this point
1202 * we were already counted as stopped.
1204 if ((lp
->lwp_mpflags
& LWP_MP_WSTOP
) == 0) {
1206 * If we're the last thread to stop, signal
1210 atomic_set_int(&lp
->lwp_mpflags
, LWP_MP_WSTOP
);
1211 wakeup(&p
->p_nstopped
);
1212 if (p
->p_nstopped
== p
->p_nthreads
) {
1214 * Token required to interlock kern_wait()
1218 lwkt_gettoken(&q
->p_token
);
1219 p
->p_flags
&= ~P_WAITED
;
1221 if ((q
->p_sigacts
->ps_flag
& PS_NOCLDSTOP
) == 0)
1222 ksignal(q
, SIGCHLD
);
1223 lwkt_reltoken(&q
->p_token
);
1229 * Wait here while in a stopped state, interlocked with lwp_token.
1230 * We must break-out if the whole process is trying to exit.
1232 while (STOPLWP(p
, lp
)) {
1233 lp
->lwp_stat
= LSSTOP
;
1234 tsleep(p
, 0, "stop", 0);
1237 atomic_clear_int(&lp
->lwp_mpflags
, LWP_MP_WSTOP
);
1239 lwkt_reltoken(&lp
->lwp_token
);
1243 * Compute a tenex style load average of a quantity on
1244 * 1, 5 and 15 minute intervals. This is a pcpu callout.
1246 * We segment the lwp scan on a pcpu basis. This does NOT
1247 * mean the associated lwps are on this cpu, it is done
1248 * just to break the work up.
1250 * The callout on cpu0 rolls up the stats from the other
1253 static int loadav_count_runnable(struct lwp
*p
, void *data
);
1258 globaldata_t gd
= mycpu
;
1259 struct loadavg
*avg
;
1263 alllwp_scan(loadav_count_runnable
, &nrun
, 1);
1264 gd
->gd_loadav_nrunnable
= nrun
;
1265 if (gd
->gd_cpuid
== 0) {
1268 for (i
= 0; i
< ncpus
; ++i
)
1269 nrun
+= globaldata_find(i
)->gd_loadav_nrunnable
;
1270 for (i
= 0; i
< 3; i
++) {
1271 avg
->ldavg
[i
] = (cexp
[i
] * avg
->ldavg
[i
] +
1272 (long)nrun
* FSCALE
* (FSCALE
- cexp
[i
])) >> FSHIFT
;
1277 * Schedule the next update to occur after 5 seconds, but add a
1278 * random variation to avoid synchronisation with processes that
1279 * run at regular intervals.
1281 callout_reset(&gd
->gd_loadav_callout
,
1282 hz
* 4 + (int)(krandom() % (hz
* 2 + 1)),
1287 loadav_count_runnable(struct lwp
*lp
, void *data
)
1292 switch (lp
->lwp_stat
) {
1294 if ((td
= lp
->lwp_thread
) == NULL
)
1296 if (td
->td_flags
& TDF_BLOCKED
)
1308 * Regular data collection
1311 collect_load_callback(int n
)
1313 int fscale
= averunnable
.fscale
;
1315 return ((averunnable
.ldavg
[0] * 100 + (fscale
>> 1)) / fscale
);
1320 sched_setup(void *dummy
)
1322 kcollect_register(KCOLLECT_LOAD
, "load", collect_load_callback
,
1323 KCOLLECT_SCALE(KCOLLECT_LOAD_FORMAT
, 0));
1324 /* Kick off timeout driven events by calling first time. */
1325 schedcpu_setup(NULL
);