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. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95
39 * $FreeBSD: src/sys/kern/kern_synch.c,v 1.87.2.6 2002/10/13 07:29:53 kbyanc Exp $
40 * $DragonFly: src/sys/kern/kern_synch.c,v 1.52 2005/11/09 03:39:15 dillon Exp $
43 #include "opt_ktrace.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
48 #include <sys/kernel.h>
49 #include <sys/signalvar.h>
50 #include <sys/resourcevar.h>
51 #include <sys/vmmeter.h>
52 #include <sys/sysctl.h>
53 #include <sys/thread2.h>
56 #include <sys/ktrace.h>
58 #include <sys/xwait.h>
60 #include <machine/cpu.h>
61 #include <machine/ipl.h>
62 #include <machine/smp.h>
64 TAILQ_HEAD(tslpque, thread);
66 static void sched_setup (void *dummy);
67 SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
71 int sched_quantum; /* Roundrobin scheduling quantum in ticks. */
73 int ncpus2, ncpus2_shift, ncpus2_mask;
76 static struct callout loadav_callout;
77 static struct callout schedcpu_callout;
78 MALLOC_DEFINE(M_TSLEEP, "tslpque", "tsleep queues");
80 struct loadavg averunnable =
81 { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */
83 * Constants for averages over 1, 5, and 15 minutes
84 * when sampling at 5 second intervals.
86 static fixpt_t cexp[3] = {
87 0.9200444146293232 * FSCALE, /* exp(-1/12) */
88 0.9834714538216174 * FSCALE, /* exp(-1/60) */
89 0.9944598480048967 * FSCALE, /* exp(-1/180) */
92 static void endtsleep (void *);
93 static void loadav (void *arg);
94 static void schedcpu (void *arg);
97 * Adjust the scheduler quantum. The quantum is specified in microseconds.
98 * Note that 'tick' is in microseconds per tick.
101 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
105 new_val = sched_quantum * tick;
106 error = sysctl_handle_int(oidp, &new_val, 0, req);
107 if (error != 0 || req->newptr == NULL)
111 sched_quantum = new_val / tick;
112 hogticks = 2 * sched_quantum;
116 SYSCTL_PROC(_kern, OID_AUTO, quantum, CTLTYPE_INT|CTLFLAG_RW,
117 0, sizeof sched_quantum, sysctl_kern_quantum, "I", "");
120 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
121 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
122 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
124 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
125 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
127 * If you don't want to bother with the faster/more-accurate formula, you
128 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
129 * (more general) method of calculating the %age of CPU used by a process.
131 * decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing
133 #define CCPU_SHIFT 11
135 static fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
136 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
139 * kernel uses `FSCALE', userland (SHOULD) use kern.fscale
141 static int fscale __unused = FSCALE;
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.
162 FOREACH_PROC_IN_SYSTEM(p) {
164 * Increment time in/out of memory and sleep time
165 * (if sleeping). We ignore overflow; with 16-bit int's
166 * (remember them?) overflow takes 45 days.
170 if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
174 * Only recalculate processes that are active or have slept
175 * less then 2 seconds. The schedulers understand this.
177 if (p->p_slptime <= 1) {
178 p->p_usched->recalculate(&p->p_lwp);
180 p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
184 wakeup((caddr_t)&lbolt);
185 callout_reset(&schedcpu_callout, hz, schedcpu, NULL);
189 * This is only used by ps. Generate a cpu percentage use over
190 * a period of one second.
193 updatepcpu(struct lwp *lp, int cpticks, int ttlticks)
198 acc = (cpticks << FSHIFT) / ttlticks;
199 if (ttlticks >= ESTCPUFREQ) {
200 lp->lwp_pctcpu = acc;
202 remticks = ESTCPUFREQ - ttlticks;
203 lp->lwp_pctcpu = (acc * ttlticks + lp->lwp_pctcpu * remticks) /
209 * We're only looking at 7 bits of the address; everything is
210 * aligned to 4, lots of things are aligned to greater powers
211 * of 2. Shift right by 8, i.e. drop the bottom 256 worth.
213 #define TABLESIZE 128
214 #define LOOKUP(x) (((intptr_t)(x) >> 8) & (TABLESIZE - 1))
216 static cpumask_t slpque_cpumasks[TABLESIZE];
219 * General scheduler initialization. We force a reschedule 25 times
220 * a second by default. Note that cpu0 is initialized in early boot and
221 * cannot make any high level calls.
223 * Each cpu has its own sleep queue.
226 sleep_gdinit(globaldata_t gd)
228 static struct tslpque slpque_cpu0[TABLESIZE];
231 if (gd->gd_cpuid == 0) {
232 sched_quantum = (hz + 24) / 25;
233 hogticks = 2 * sched_quantum;
235 gd->gd_tsleep_hash = slpque_cpu0;
238 gd->gd_tsleep_hash = malloc(sizeof(slpque_cpu0),
239 M_TSLEEP, M_WAITOK | M_ZERO);
241 gd->gd_tsleep_hash = slpque_cpu0;
243 for (i = 0; i < TABLESIZE; ++i)
244 TAILQ_INIT(&gd->gd_tsleep_hash[i]);
248 * General sleep call. Suspends the current process until a wakeup is
249 * performed on the specified identifier. The process will then be made
250 * runnable with the specified priority. Sleeps at most timo/hz seconds
251 * (0 means no timeout). If flags includes PCATCH flag, signals are checked
252 * before and after sleeping, else signals are not checked. Returns 0 if
253 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
254 * signal needs to be delivered, ERESTART is returned if the current system
255 * call should be restarted if possible, and EINTR is returned if the system
256 * call should be interrupted by the signal (return EINTR).
258 * Note that if we are a process, we release_curproc() before messing with
259 * the LWKT scheduler.
261 * During autoconfiguration or after a panic, a sleep will simply
262 * lower the priority briefly to allow interrupts, then return.
265 tsleep(void *ident, int flags, const char *wmesg, int timo)
267 struct thread *td = curthread;
268 struct proc *p = td->td_proc; /* may be NULL */
270 int sig = 0, catch = flags & PCATCH;
271 int id = LOOKUP(ident);
273 struct callout thandle;
276 * NOTE: removed KTRPOINT, it could cause races due to blocking
277 * even in stable. Just scrap it for now.
279 if (cold || panicstr) {
281 * After a panic, or during autoconfiguration,
282 * just give interrupts a chance, then just return;
283 * don't run any other procs or panic below,
284 * in case this is the idle process and already asleep.
287 oldpri = td->td_pri & TDPRI_MASK;
288 lwkt_setpri_self(safepri);
290 lwkt_setpri_self(oldpri);
294 KKASSERT(td != &gd->gd_idlethread); /* you must be kidding! */
295 crit_enter_quick(td);
296 KASSERT(ident != NULL, ("tsleep: no ident"));
297 KASSERT(p == NULL || p->p_stat == SRUN, ("tsleep %p %s %d",
298 ident, wmesg, p->p_stat));
300 td->td_wchan = ident;
301 td->td_wmesg = wmesg;
302 td->td_wdomain = flags & PDOMAIN_MASK;
304 if (flags & PNORESCHED)
305 td->td_flags |= TDF_NORESCHED;
306 p->p_usched->release_curproc(&p->p_lwp);
311 * note: all of this occurs on the current cpu, including any
312 * callout-based wakeups, so a critical section is a sufficient
315 lwkt_deschedule_self(td);
316 TAILQ_INSERT_TAIL(&gd->gd_tsleep_hash[id], td, td_threadq);
317 atomic_set_int(&slpque_cpumasks[id], gd->gd_cpumask);
319 callout_init(&thandle);
320 callout_reset(&thandle, timo, endtsleep, td);
323 * We put ourselves on the sleep queue and start our timeout
324 * before calling CURSIG, as we could stop there, and a wakeup
325 * or a SIGCONT (or both) could occur while we were stopped.
326 * A SIGCONT would cause us to be marked as SSLEEP
327 * without resuming us, thus we must be ready for sleep
328 * when CURSIG is called. If the wakeup happens while we're
329 * stopped, td->td_wchan will be 0 upon return from CURSIG.
333 p->p_flag |= P_SINTR;
334 if ((sig = CURSIG(p))) {
337 lwkt_schedule_self(td);
342 if (td->td_wchan == NULL) {
351 * If we are not the current process we have to remove ourself
352 * from the run queue.
354 KASSERT(p->p_stat == SRUN, ("PSTAT NOT SRUN %d %d", p->p_pid, p->p_stat));
356 * If this is the current 'user' process schedule another one.
358 clrrunnable(p, SSLEEP);
359 p->p_stats->p_ru.ru_nvcsw++;
361 KASSERT(p->p_stat == SRUN, ("tsleep: stat not srun"));
366 * Make sure we haven't switched cpus while we were asleep. It's
367 * not supposed to happen.
369 KKASSERT(gd == td->td_gd);
372 p->p_flag &= ~P_SINTR;
374 td->td_flags &= ~TDF_NORESCHED;
375 if (td->td_flags & TDF_TIMEOUT) {
376 td->td_flags &= ~TDF_TIMEOUT;
378 return (EWOULDBLOCK);
380 callout_stop(&thandle);
381 } else if (td->td_wmesg) {
383 * This can happen if a thread is woken up directly. Clear
384 * wmesg to avoid debugging confusion.
388 /* inline of iscaught() */
390 if (catch && (sig != 0 || (sig = CURSIG(p)))) {
391 if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
400 * Implement the timeout for tsleep. We interlock against
401 * wchan when setting TDF_TIMEOUT. For processes we remove
402 * the sleep if the process is stopped rather then sleeping,
403 * so it remains stopped.
405 * This type of callout timeout had better be scheduled on the same
406 * cpu the process is sleeping on.
416 td->td_flags |= TDF_TIMEOUT;
417 if ((p = td->td_proc) != NULL) {
418 if (p->p_stat == SSLEEP)
431 * Remove a process from its wait queue
433 * XXX not MP safe until called only on the cpu holding the sleeping
437 unsleep(struct thread *td)
442 id = LOOKUP(td->td_wchan);
444 TAILQ_REMOVE(&td->td_gd->gd_tsleep_hash[id], td, td_threadq);
445 if (TAILQ_FIRST(&td->td_gd->gd_tsleep_hash[id]) == NULL)
446 atomic_clear_int(&slpque_cpumasks[id], td->td_gd->gd_cpumask);
453 * Make all processes sleeping on the specified identifier runnable.
454 * count may be zero or one only.
456 * The domain encodes the sleep/wakeup domain AND the first cpu to check
457 * (which is always the current cpu). As we iterate across cpus
460 _wakeup(void *ident, int domain)
480 qp = &gd->gd_tsleep_hash[id];
482 for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) {
483 ntd = TAILQ_NEXT(td, td_threadq);
484 if (td->td_wchan == ident &&
485 td->td_wdomain == (domain & PDOMAIN_MASK)
487 TAILQ_REMOVE(qp, td, td_threadq);
488 if (TAILQ_FIRST(qp) == NULL) {
489 atomic_clear_int(&slpque_cpumasks[id],
493 if ((p = td->td_proc) != NULL && p->p_stat == SSLEEP) {
495 if (p->p_flag & P_INMEM) {
497 * LWKT scheduled now, there is no
498 * userland runq interaction until
499 * the thread tries to return to user
500 * mode. We do NOT call setrunqueue().
504 p->p_flag |= P_SWAPINREQ;
505 wakeup((caddr_t)&proc0);
507 /* END INLINE EXPANSION */
508 } else if (p == NULL) {
511 if (domain & PWAKEUP_ONE)
520 * We finished checking the current cpu but there still may be
521 * more work to do. Either wakeup_one was requested and no matching
522 * thread was found, or a normal wakeup was requested and we have
523 * to continue checking cpus.
525 * The cpu that started the wakeup sequence is encoded in the domain.
526 * We use this information to determine which cpus still need to be
527 * checked, locate a candidate cpu, and chain the wakeup
528 * asynchronously with an IPI message.
530 * It should be noted that this scheme is actually less expensive then
531 * the old scheme when waking up multiple threads, since we send
532 * only one IPI message per target candidate which may then schedule
533 * multiple threads. Before we could have wound up sending an IPI
534 * message for each thread on the target cpu (!= current cpu) that
535 * needed to be woken up.
537 * NOTE: Wakeups occuring on remote cpus are asynchronous. This
538 * should be ok since we are passing idents in the IPI rather then
541 if ((mask = slpque_cpumasks[id]) != 0) {
543 * Look for a cpu that might have work to do. Mask out cpus
544 * which have already been processed.
546 * 31xxxxxxxxxxxxxxxxxxxxxxxxxxxxx0
548 * start currentcpu start
551 * 11111111111111110000000000000111 case1
552 * 00000000111111110000000000000000 case2
554 * case1: We started at start_case1 and processed through
555 * to the current cpu. We have to check any bits
556 * after the current cpu, then check bits before
559 * case2: We have already checked all the bits from
560 * start_case2 to the end, and from 0 to the current
561 * cpu. We just have the bits from the current cpu
562 * to start_case2 left to check.
564 startcpu = PWAKEUP_DECODE(domain);
565 if (gd->gd_cpuid >= startcpu) {
569 tmask = mask & ~((gd->gd_cpumask << 1) - 1);
571 nextcpu = bsfl(mask & tmask);
572 lwkt_send_ipiq2(globaldata_find(nextcpu),
573 _wakeup, ident, domain);
575 tmask = (1 << startcpu) - 1;
577 nextcpu = bsfl(mask & tmask);
579 globaldata_find(nextcpu),
580 _wakeup, ident, domain);
587 tmask = ~((gd->gd_cpumask << 1) - 1) &
588 ((1 << startcpu) - 1);
590 nextcpu = bsfl(mask & tmask);
591 lwkt_send_ipiq2(globaldata_find(nextcpu),
592 _wakeup, ident, domain);
605 _wakeup(ident, PWAKEUP_ENCODE(0, mycpu->gd_cpuid));
609 wakeup_one(void *ident)
611 /* XXX potentially round-robin the first responding cpu */
612 _wakeup(ident, PWAKEUP_ENCODE(0, mycpu->gd_cpuid) | PWAKEUP_ONE);
616 wakeup_domain(void *ident, int domain)
618 _wakeup(ident, PWAKEUP_ENCODE(domain, mycpu->gd_cpuid));
622 wakeup_domain_one(void *ident, int domain)
624 /* XXX potentially round-robin the first responding cpu */
625 _wakeup(ident, PWAKEUP_ENCODE(domain, mycpu->gd_cpuid) | PWAKEUP_ONE);
629 * The machine independent parts of mi_switch().
631 * 'p' must be the current process.
634 mi_switch(struct proc *p)
636 thread_t td = p->p_thread;
640 KKASSERT(td == mycpu->gd_curthread);
642 crit_enter_quick(td);
645 * Check if the process exceeds its cpu resource allocation.
646 * If over max, kill it. Time spent in interrupts is not
647 * included. YYY 64 bit match is expensive. Ick.
649 * XXX move to the once-a-second process scan
651 ttime = td->td_sticks + td->td_uticks;
652 if (p->p_stat != SZOMB && p->p_limit->p_cpulimit != RLIM_INFINITY &&
653 ttime > p->p_limit->p_cpulimit) {
654 rlim = &p->p_rlimit[RLIMIT_CPU];
655 if (ttime / (rlim_t)1000000 >= rlim->rlim_max) {
656 killproc(p, "exceeded maximum CPU limit");
659 if (rlim->rlim_cur < rlim->rlim_max) {
660 /* XXX: we should make a private copy */
667 * If we are in a SSTOPped state we deschedule ourselves.
668 * YYY this needs to be cleaned up, remember that LWKTs stay on
669 * their run queue which works differently then the user scheduler
670 * which removes the process from the runq when it runs it.
672 mycpu->gd_cnt.v_swtch++;
673 if (p->p_stat == SSTOP)
674 lwkt_deschedule_self(td);
680 * Change process state to be runnable, placing it on the run queue if it
681 * is in memory, and awakening the swapper if it isn't in memory.
683 * This operation MUST OCCUR on the cpu that the thread is sleeping on.
686 setrunnable(struct proc *p)
695 panic("setrunnable");
698 unsleep(p->p_thread); /* e.g. when sending signals */
707 * The process is controlled by LWKT at this point, we do not mess
708 * around with the userland scheduler until the thread tries to
709 * return to user mode. We do not clear p_slptime or call
712 if (p->p_flag & P_INMEM) {
713 lwkt_schedule(p->p_thread);
715 p->p_flag |= P_SWAPINREQ;
716 wakeup((caddr_t)&proc0);
722 * Yield / synchronous reschedule. This is a bit tricky because the trap
723 * code might have set a lazy release on the switch function. Setting
724 * P_PASSIVE_ACQ will ensure that the lazy release executes when we call
725 * switch, and that we are given a greater chance of affinity with our
728 * We call lwkt_setpri_self() to rotate our thread to the end of the lwkt
729 * run queue. lwkt_switch() will also execute any assigned passive release
730 * (which usually calls release_curproc()), allowing a same/higher priority
731 * process to be designated as the current process.
733 * While it is possible for a lower priority process to be designated,
734 * it's call to lwkt_maybe_switch() in acquire_curproc() will likely
735 * round-robin back to us and we will be able to re-acquire the current
736 * process designation.
741 struct thread *td = curthread;
742 struct proc *p = td->td_proc;
744 lwkt_setpri_self(td->td_pri & TDPRI_MASK);
746 p->p_flag |= P_PASSIVE_ACQ;
748 p->p_flag &= ~P_PASSIVE_ACQ;
755 * Change the process state to NOT be runnable, removing it from the run
759 clrrunnable(struct proc *p, int stat)
761 crit_enter_quick(p->p_thread);
762 if (p->p_stat == SRUN && (p->p_flag & P_ONRUNQ))
763 p->p_usched->remrunqueue(&p->p_lwp);
765 crit_exit_quick(p->p_thread);
769 * Compute a tenex style load average of a quantity on
770 * 1, 5 and 15 minute intervals.
782 FOREACH_PROC_IN_SYSTEM(p) {
785 if ((td = p->p_thread) == NULL)
787 if (td->td_flags & TDF_BLOCKED)
797 for (i = 0; i < 3; i++)
798 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
799 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
802 * Schedule the next update to occur after 5 seconds, but add a
803 * random variation to avoid synchronisation with processes that
804 * run at regular intervals.
806 callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
812 sched_setup(void *dummy)
814 callout_init(&loadav_callout);
815 callout_init(&schedcpu_callout);
817 /* Kick off timeout driven events by calling first time. */