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 * 4. 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
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
38 #include "opt_hwpmc_hooks.h"
39 #include "opt_sched.h"
40 #include "opt_kdtrace.h"
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/cpuset.h>
45 #include <sys/kernel.h>
48 #include <sys/kthread.h>
49 #include <sys/mutex.h>
51 #include <sys/resourcevar.h>
52 #include <sys/sched.h>
54 #include <sys/sysctl.h>
56 #include <sys/turnstile.h>
58 #include <machine/pcb.h>
59 #include <machine/smp.h>
62 #include <sys/pmckern.h>
66 #include <sys/dtrace_bsd.h>
67 int dtrace_vtime_active;
68 dtrace_vtime_switch_func_t dtrace_vtime_switch_func;
72 * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
73 * the range 100-256 Hz (approximately).
75 #define ESTCPULIM(e) \
76 min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
77 RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
79 #define INVERSE_ESTCPU_WEIGHT (8 * smp_cpus)
81 #define INVERSE_ESTCPU_WEIGHT 8 /* 1 / (priorities per estcpu level). */
83 #define NICE_WEIGHT 1 /* Priorities per nice level. */
86 * The schedulable entity that runs a context.
87 * This is an extension to the thread structure and is tailored to
88 * the requirements of this scheduler
91 fixpt_t ts_pctcpu; /* (j) %cpu during p_swtime. */
92 int ts_cpticks; /* (j) Ticks of cpu time. */
93 int ts_slptime; /* (j) Seconds !RUNNING. */
94 struct runq *ts_runq; /* runq the thread is currently on */
97 /* flags kept in td_flags */
98 #define TDF_DIDRUN TDF_SCHED0 /* thread actually ran. */
99 #define TDF_BOUND TDF_SCHED1 /* Bound to one CPU. */
101 #define SKE_RUNQ_PCPU(ts) \
102 ((ts)->ts_runq != 0 && (ts)->ts_runq != &runq)
104 static struct td_sched td_sched0;
105 struct mtx sched_lock;
107 static int sched_tdcnt; /* Total runnable threads in the system. */
108 static int sched_quantum; /* Roundrobin scheduling quantum in ticks. */
109 #define SCHED_QUANTUM (hz / 10) /* Default sched quantum */
111 static void setup_runqs(void);
112 static void schedcpu(void);
113 static void schedcpu_thread(void);
114 static void sched_priority(struct thread *td, u_char prio);
115 static void sched_setup(void *dummy);
116 static void maybe_resched(struct thread *td);
117 static void updatepri(struct thread *td);
118 static void resetpriority(struct thread *td);
119 static void resetpriority_thread(struct thread *td);
121 static int forward_wakeup(int cpunum);
124 static struct kproc_desc sched_kp = {
129 SYSINIT(schedcpu, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, kproc_start,
131 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
136 static struct runq runq;
142 static struct runq runq_pcpu[MAXCPU];
151 for (i = 0; i < MAXCPU; ++i)
152 runq_init(&runq_pcpu[i]);
159 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
163 new_val = sched_quantum * tick;
164 error = sysctl_handle_int(oidp, &new_val, 0, req);
165 if (error != 0 || req->newptr == NULL)
169 sched_quantum = new_val / tick;
170 hogticks = 2 * sched_quantum;
174 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "Scheduler");
176 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
179 SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
180 0, sizeof sched_quantum, sysctl_kern_quantum, "I",
181 "Roundrobin scheduling quantum in microseconds");
184 /* Enable forwarding of wakeups to all other cpus */
185 SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup, CTLFLAG_RD, NULL, "Kernel SMP");
187 static int runq_fuzz = 1;
188 SYSCTL_INT(_kern_sched, OID_AUTO, runq_fuzz, CTLFLAG_RW, &runq_fuzz, 0, "");
190 static int forward_wakeup_enabled = 1;
191 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
192 &forward_wakeup_enabled, 0,
193 "Forwarding of wakeup to idle CPUs");
195 static int forward_wakeups_requested = 0;
196 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
197 &forward_wakeups_requested, 0,
198 "Requests for Forwarding of wakeup to idle CPUs");
200 static int forward_wakeups_delivered = 0;
201 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
202 &forward_wakeups_delivered, 0,
203 "Completed Forwarding of wakeup to idle CPUs");
205 static int forward_wakeup_use_mask = 1;
206 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
207 &forward_wakeup_use_mask, 0,
208 "Use the mask of idle cpus");
210 static int forward_wakeup_use_loop = 0;
211 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
212 &forward_wakeup_use_loop, 0,
213 "Use a loop to find idle cpus");
215 static int forward_wakeup_use_single = 0;
216 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, onecpu, CTLFLAG_RW,
217 &forward_wakeup_use_single, 0,
218 "Only signal one idle cpu");
220 static int forward_wakeup_use_htt = 0;
221 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, htt2, CTLFLAG_RW,
222 &forward_wakeup_use_htt, 0,
227 static int sched_followon = 0;
228 SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
230 "allow threads to share a quantum");
237 CTR1(KTR_SCHED, "global load: %d", sched_tdcnt);
244 CTR1(KTR_SCHED, "global load: %d", sched_tdcnt);
247 * Arrange to reschedule if necessary, taking the priorities and
248 * schedulers into account.
251 maybe_resched(struct thread *td)
254 THREAD_LOCK_ASSERT(td, MA_OWNED);
255 if (td->td_priority < curthread->td_priority)
256 curthread->td_flags |= TDF_NEEDRESCHED;
260 * This function is called when a thread is about to be put on run queue
261 * because it has been made runnable or its priority has been adjusted. It
262 * determines if the new thread should be immediately preempted to. If so,
263 * it switches to it and eventually returns true. If not, it returns false
264 * so that the caller may place the thread on an appropriate run queue.
267 maybe_preempt(struct thread *td)
276 * The new thread should not preempt the current thread if any of the
277 * following conditions are true:
279 * - The kernel is in the throes of crashing (panicstr).
280 * - The current thread has a higher (numerically lower) or
281 * equivalent priority. Note that this prevents curthread from
282 * trying to preempt to itself.
283 * - It is too early in the boot for context switches (cold is set).
284 * - The current thread has an inhibitor set or is in the process of
285 * exiting. In this case, the current thread is about to switch
286 * out anyways, so there's no point in preempting. If we did,
287 * the current thread would not be properly resumed as well, so
288 * just avoid that whole landmine.
289 * - If the new thread's priority is not a realtime priority and
290 * the current thread's priority is not an idle priority and
291 * FULL_PREEMPTION is disabled.
293 * If all of these conditions are false, but the current thread is in
294 * a nested critical section, then we have to defer the preemption
295 * until we exit the critical section. Otherwise, switch immediately
299 THREAD_LOCK_ASSERT(td, MA_OWNED);
300 KASSERT((td->td_inhibitors == 0),
301 ("maybe_preempt: trying to run inhibited thread"));
302 pri = td->td_priority;
303 cpri = ctd->td_priority;
304 if (panicstr != NULL || pri >= cpri || cold /* || dumping */ ||
305 TD_IS_INHIBITED(ctd))
307 #ifndef FULL_PREEMPTION
308 if (pri > PRI_MAX_ITHD && cpri < PRI_MIN_IDLE)
312 if (ctd->td_critnest > 1) {
313 CTR1(KTR_PROC, "maybe_preempt: in critical section %d",
315 ctd->td_owepreempt = 1;
319 * Thread is runnable but not yet put on system run queue.
321 MPASS(ctd->td_lock == td->td_lock);
322 MPASS(TD_ON_RUNQ(td));
324 CTR3(KTR_PROC, "preempting to thread %p (pid %d, %s)\n", td,
325 td->td_proc->p_pid, td->td_name);
326 mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, td);
328 * td's lock pointer may have changed. We have to return with it
342 * Constants for digital decay and forget:
343 * 90% of (td_estcpu) usage in 5 * loadav time
344 * 95% of (ts_pctcpu) usage in 60 seconds (load insensitive)
345 * Note that, as ps(1) mentions, this can let percentages
346 * total over 100% (I've seen 137.9% for 3 processes).
348 * Note that schedclock() updates td_estcpu and p_cpticks asynchronously.
350 * We wish to decay away 90% of td_estcpu in (5 * loadavg) seconds.
351 * That is, the system wants to compute a value of decay such
352 * that the following for loop:
353 * for (i = 0; i < (5 * loadavg); i++)
354 * td_estcpu *= decay;
357 * for all values of loadavg:
359 * Mathematically this loop can be expressed by saying:
360 * decay ** (5 * loadavg) ~= .1
362 * The system computes decay as:
363 * decay = (2 * loadavg) / (2 * loadavg + 1)
365 * We wish to prove that the system's computation of decay
366 * will always fulfill the equation:
367 * decay ** (5 * loadavg) ~= .1
369 * If we compute b as:
372 * decay = b / (b + 1)
374 * We now need to prove two things:
375 * 1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
376 * 2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
379 * For x close to zero, exp(x) =~ 1 + x, since
380 * exp(x) = 0! + x**1/1! + x**2/2! + ... .
381 * therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
382 * For x close to zero, ln(1+x) =~ x, since
383 * ln(1+x) = x - x**2/2 + x**3/3 - ... -1 < x < 1
384 * therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
388 * Solve (factor)**(power) =~ .1 given power (5*loadav):
389 * solving for factor,
390 * ln(factor) =~ (-2.30/5*loadav), or
391 * factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
392 * exp(-1/b) =~ (b-1)/b =~ b/(b+1). QED
395 * Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
397 * power*ln(b/(b+1)) =~ -2.30, or
398 * power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav. QED
400 * Actual power values for the implemented algorithm are as follows:
402 * power: 5.68 10.32 14.94 19.55
405 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
406 #define loadfactor(loadav) (2 * (loadav))
407 #define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
409 /* decay 95% of `ts_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
410 static fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
411 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
414 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
415 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
416 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
418 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
419 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
421 * If you don't want to bother with the faster/more-accurate formula, you
422 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
423 * (more general) method of calculating the %age of CPU used by a process.
425 #define CCPU_SHIFT 11
428 * Recompute process priorities, every hz ticks.
429 * MP-safe, called without the Giant mutex.
435 register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
439 int awake, realstathz;
441 realstathz = stathz ? stathz : hz;
442 sx_slock(&allproc_lock);
443 FOREACH_PROC_IN_SYSTEM(p) {
445 FOREACH_THREAD_IN_PROC(p, td) {
450 * Increment sleep time (if sleeping). We
451 * ignore overflow, as above.
454 * The td_sched slptimes are not touched in wakeup
455 * because the thread may not HAVE everything in
456 * memory? XXX I think this is out of date.
458 if (TD_ON_RUNQ(td)) {
460 td->td_flags &= ~TDF_DIDRUN;
461 } else if (TD_IS_RUNNING(td)) {
463 /* Do not clear TDF_DIDRUN */
464 } else if (td->td_flags & TDF_DIDRUN) {
466 td->td_flags &= ~TDF_DIDRUN;
470 * ts_pctcpu is only for ps and ttyinfo().
472 ts->ts_pctcpu = (ts->ts_pctcpu * ccpu) >> FSHIFT;
474 * If the td_sched has been idle the entire second,
475 * stop recalculating its priority until
478 if (ts->ts_cpticks != 0) {
479 #if (FSHIFT >= CCPU_SHIFT)
480 ts->ts_pctcpu += (realstathz == 100)
481 ? ((fixpt_t) ts->ts_cpticks) <<
482 (FSHIFT - CCPU_SHIFT) :
483 100 * (((fixpt_t) ts->ts_cpticks)
484 << (FSHIFT - CCPU_SHIFT)) / realstathz;
486 ts->ts_pctcpu += ((FSCALE - ccpu) *
488 FSCALE / realstathz)) >> FSHIFT;
493 * If there are ANY running threads in this process,
494 * then don't count it as sleeping.
499 if (ts->ts_slptime > 1) {
501 * In an ideal world, this should not
502 * happen, because whoever woke us
503 * up from the long sleep should have
504 * unwound the slptime and reset our
505 * priority before we run at the stale
506 * priority. Should KASSERT at some
507 * point when all the cases are fixed.
514 if (ts->ts_slptime > 1) {
518 td->td_estcpu = decay_cpu(loadfac, td->td_estcpu);
520 resetpriority_thread(td);
522 } /* end of thread loop */
524 } /* end of process loop */
525 sx_sunlock(&allproc_lock);
529 * Main loop for a kthread that executes schedcpu once a second.
532 schedcpu_thread(void)
542 * Recalculate the priority of a process after it has slept for a while.
543 * For all load averages >= 1 and max td_estcpu of 255, sleeping for at
544 * least six times the loadfactor will decay td_estcpu to zero.
547 updatepri(struct thread *td)
554 loadfac = loadfactor(averunnable.ldavg[0]);
555 if (ts->ts_slptime > 5 * loadfac)
558 newcpu = td->td_estcpu;
559 ts->ts_slptime--; /* was incremented in schedcpu() */
560 while (newcpu && --ts->ts_slptime)
561 newcpu = decay_cpu(loadfac, newcpu);
562 td->td_estcpu = newcpu;
567 * Compute the priority of a process when running in user mode.
568 * Arrange to reschedule if the resulting priority is better
569 * than that of the current process.
572 resetpriority(struct thread *td)
574 register unsigned int newpriority;
576 if (td->td_pri_class == PRI_TIMESHARE) {
577 newpriority = PUSER + td->td_estcpu / INVERSE_ESTCPU_WEIGHT +
578 NICE_WEIGHT * (td->td_proc->p_nice - PRIO_MIN);
579 newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
581 sched_user_prio(td, newpriority);
586 * Update the thread's priority when the associated process's user
590 resetpriority_thread(struct thread *td)
593 /* Only change threads with a time sharing user priority. */
594 if (td->td_priority < PRI_MIN_TIMESHARE ||
595 td->td_priority > PRI_MAX_TIMESHARE)
598 /* XXX the whole needresched thing is broken, but not silly. */
601 sched_prio(td, td->td_user_pri);
606 sched_setup(void *dummy)
610 if (sched_quantum == 0)
611 sched_quantum = SCHED_QUANTUM;
612 hogticks = 2 * sched_quantum;
614 /* Account for thread0. */
618 /* External interfaces start here */
620 * Very early in the boot some setup of scheduler-specific
621 * parts of proc0 and of some scheduler resources needs to be done.
629 * Set up the scheduler specific parts of proc0.
631 proc0.p_sched = NULL; /* XXX */
632 thread0.td_sched = &td_sched0;
633 thread0.td_lock = &sched_lock;
634 mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
641 return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
643 return runq_check(&runq);
648 sched_rr_interval(void)
650 if (sched_quantum == 0)
651 sched_quantum = SCHED_QUANTUM;
652 return (sched_quantum);
656 * We adjust the priority of the current process. The priority of
657 * a process gets worse as it accumulates CPU time. The cpu usage
658 * estimator (td_estcpu) is increased here. resetpriority() will
659 * compute a different priority each time td_estcpu increases by
660 * INVERSE_ESTCPU_WEIGHT
661 * (until MAXPRI is reached). The cpu usage estimator ramps up
662 * quite quickly when the process is running (linearly), and decays
663 * away exponentially, at a rate which is proportionally slower when
664 * the system is busy. The basic principle is that the system will
665 * 90% forget that the process used a lot of CPU time in 5 * loadav
666 * seconds. This causes the system to favor processes which haven't
667 * run much recently, and to round-robin among other processes.
670 sched_clock(struct thread *td)
674 THREAD_LOCK_ASSERT(td, MA_OWNED);
678 td->td_estcpu = ESTCPULIM(td->td_estcpu + 1);
679 if ((td->td_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
681 resetpriority_thread(td);
685 * Force a context switch if the current thread has used up a full
686 * quantum (default quantum is 100ms).
688 if (!TD_IS_IDLETHREAD(td) &&
689 ticks - PCPU_GET(switchticks) >= sched_quantum)
690 td->td_flags |= TDF_NEEDRESCHED;
694 * charge childs scheduling cpu usage to parent.
697 sched_exit(struct proc *p, struct thread *td)
700 CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
701 td, td->td_name, td->td_priority);
702 PROC_LOCK_ASSERT(p, MA_OWNED);
703 sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
707 sched_exit_thread(struct thread *td, struct thread *child)
710 CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
711 child, child->td_name, child->td_priority);
713 td->td_estcpu = ESTCPULIM(td->td_estcpu + child->td_estcpu);
715 mtx_lock_spin(&sched_lock);
716 if ((child->td_proc->p_flag & P_NOLOAD) == 0)
718 mtx_unlock_spin(&sched_lock);
722 sched_fork(struct thread *td, struct thread *childtd)
724 sched_fork_thread(td, childtd);
728 sched_fork_thread(struct thread *td, struct thread *childtd)
732 childtd->td_estcpu = td->td_estcpu;
733 childtd->td_lock = &sched_lock;
734 childtd->td_cpuset = cpuset_ref(td->td_cpuset);
735 ts = childtd->td_sched;
736 bzero(ts, sizeof(*ts));
740 sched_nice(struct proc *p, int nice)
744 PROC_LOCK_ASSERT(p, MA_OWNED);
746 FOREACH_THREAD_IN_PROC(p, td) {
749 resetpriority_thread(td);
755 sched_class(struct thread *td, int class)
757 THREAD_LOCK_ASSERT(td, MA_OWNED);
758 td->td_pri_class = class;
762 * Adjust the priority of a thread.
765 sched_priority(struct thread *td, u_char prio)
767 CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
768 td, td->td_name, td->td_priority, prio, curthread,
771 THREAD_LOCK_ASSERT(td, MA_OWNED);
772 if (td->td_priority == prio)
774 td->td_priority = prio;
775 if (TD_ON_RUNQ(td) && td->td_rqindex != (prio / RQ_PPQ)) {
777 sched_add(td, SRQ_BORING);
782 * Update a thread's priority when it is lent another thread's
786 sched_lend_prio(struct thread *td, u_char prio)
789 td->td_flags |= TDF_BORROWING;
790 sched_priority(td, prio);
794 * Restore a thread's priority when priority propagation is
795 * over. The prio argument is the minimum priority the thread
796 * needs to have to satisfy other possible priority lending
797 * requests. If the thread's regulary priority is less
798 * important than prio the thread will keep a priority boost
802 sched_unlend_prio(struct thread *td, u_char prio)
806 if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
807 td->td_base_pri <= PRI_MAX_TIMESHARE)
808 base_pri = td->td_user_pri;
810 base_pri = td->td_base_pri;
811 if (prio >= base_pri) {
812 td->td_flags &= ~TDF_BORROWING;
813 sched_prio(td, base_pri);
815 sched_lend_prio(td, prio);
819 sched_prio(struct thread *td, u_char prio)
823 /* First, update the base priority. */
824 td->td_base_pri = prio;
827 * If the thread is borrowing another thread's priority, don't ever
828 * lower the priority.
830 if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
833 /* Change the real priority. */
834 oldprio = td->td_priority;
835 sched_priority(td, prio);
838 * If the thread is on a turnstile, then let the turnstile update
841 if (TD_ON_LOCK(td) && oldprio != prio)
842 turnstile_adjust(td, oldprio);
846 sched_user_prio(struct thread *td, u_char prio)
850 THREAD_LOCK_ASSERT(td, MA_OWNED);
851 td->td_base_user_pri = prio;
852 if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
854 oldprio = td->td_user_pri;
855 td->td_user_pri = prio;
859 sched_lend_user_prio(struct thread *td, u_char prio)
863 THREAD_LOCK_ASSERT(td, MA_OWNED);
864 td->td_flags |= TDF_UBORROWING;
865 oldprio = td->td_user_pri;
866 td->td_user_pri = prio;
870 sched_unlend_user_prio(struct thread *td, u_char prio)
874 THREAD_LOCK_ASSERT(td, MA_OWNED);
875 base_pri = td->td_base_user_pri;
876 if (prio >= base_pri) {
877 td->td_flags &= ~TDF_UBORROWING;
878 sched_user_prio(td, base_pri);
880 sched_lend_user_prio(td, prio);
885 sched_sleep(struct thread *td, int pri)
888 THREAD_LOCK_ASSERT(td, MA_OWNED);
889 td->td_slptick = ticks;
890 td->td_sched->ts_slptime = 0;
893 if (TD_IS_SUSPENDED(td) || pri <= PSOCK)
894 td->td_flags |= TDF_CANSWAP;
898 sched_switch(struct thread *td, struct thread *newtd, int flags)
906 THREAD_LOCK_ASSERT(td, MA_OWNED);
908 * Switch to the sched lock to fix things up and pick
911 if (td->td_lock != &sched_lock) {
912 mtx_lock_spin(&sched_lock);
916 if ((p->p_flag & P_NOLOAD) == 0)
920 newtd->td_flags |= (td->td_flags & TDF_NEEDRESCHED);
922 td->td_lastcpu = td->td_oncpu;
923 td->td_flags &= ~TDF_NEEDRESCHED;
924 td->td_owepreempt = 0;
925 td->td_oncpu = NOCPU;
927 * At the last moment, if this thread is still marked RUNNING,
928 * then put it back on the run queue as it has not been suspended
929 * or stopped or any thing else similar. We never put the idle
930 * threads on the run queue, however.
932 if (td->td_flags & TDF_IDLETD) {
935 idle_cpus_mask &= ~PCPU_GET(cpumask);
938 if (TD_IS_RUNNING(td)) {
939 /* Put us back on the run queue. */
940 sched_add(td, (flags & SW_PREEMPT) ?
941 SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
942 SRQ_OURSELF|SRQ_YIELDING);
947 * The thread we are about to run needs to be counted
948 * as if it had been added to the run queue and selected.
954 KASSERT((newtd->td_inhibitors == 0),
955 ("trying to run inhibited thread"));
956 newtd->td_flags |= TDF_DIDRUN;
957 TD_SET_RUNNING(newtd);
958 if ((newtd->td_proc->p_flag & P_NOLOAD) == 0)
961 newtd = choosethread();
963 MPASS(newtd->td_lock == &sched_lock);
967 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
968 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
971 lock_profile_release_lock(&sched_lock.lock_object);
974 * If DTrace has set the active vtime enum to anything
975 * other than INACTIVE (0), then it should have set the
978 if (dtrace_vtime_active)
979 (*dtrace_vtime_switch_func)(newtd);
982 cpu_switch(td, newtd, td->td_lock);
983 lock_profile_obtain_lock_success(&sched_lock.lock_object,
984 0, 0, __FILE__, __LINE__);
986 * Where am I? What year is it?
987 * We are in the same thread that went to sleep above,
988 * but any amount of time may have passed. All out context
989 * will still be available as will local variables.
990 * PCPU values however may have changed as we may have
991 * changed CPU so don't trust cached values of them.
992 * New threads will go to fork_exit() instead of here
993 * so if you change things here you may need to change
995 * If the thread above was exiting it will never wake
996 * up again here, so either it has saved everything it
997 * needed to, or the thread_wait() or wait() will
1001 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1002 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1007 if (td->td_flags & TDF_IDLETD)
1008 idle_cpus_mask |= PCPU_GET(cpumask);
1010 sched_lock.mtx_lock = (uintptr_t)td;
1011 td->td_oncpu = PCPU_GET(cpuid);
1012 MPASS(td->td_lock == &sched_lock);
1016 sched_wakeup(struct thread *td)
1018 struct td_sched *ts;
1020 THREAD_LOCK_ASSERT(td, MA_OWNED);
1022 td->td_flags &= ~TDF_CANSWAP;
1023 if (ts->ts_slptime > 1) {
1027 td->td_slptick = ticks;
1029 sched_add(td, SRQ_BORING);
1033 /* enable HTT_2 if you have a 2-way HTT cpu.*/
1035 forward_wakeup(int cpunum)
1037 cpumask_t map, me, dontuse;
1042 mtx_assert(&sched_lock, MA_OWNED);
1044 CTR0(KTR_RUNQ, "forward_wakeup()");
1046 if ((!forward_wakeup_enabled) ||
1047 (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
1049 if (!smp_started || cold || panicstr)
1052 forward_wakeups_requested++;
1055 * check the idle mask we received against what we calculated before
1056 * in the old version.
1058 me = PCPU_GET(cpumask);
1060 * don't bother if we should be doing it ourself..
1062 if ((me & idle_cpus_mask) && (cpunum == NOCPU || me == (1 << cpunum)))
1065 dontuse = me | stopped_cpus | hlt_cpus_mask;
1067 if (forward_wakeup_use_loop) {
1068 SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {
1069 id = pc->pc_cpumask;
1070 if ( (id & dontuse) == 0 &&
1071 pc->pc_curthread == pc->pc_idlethread) {
1077 if (forward_wakeup_use_mask) {
1079 map = idle_cpus_mask & ~dontuse;
1081 /* If they are both on, compare and use loop if different */
1082 if (forward_wakeup_use_loop) {
1084 printf("map (%02X) != map3 (%02X)\n",
1092 /* If we only allow a specific CPU, then mask off all the others */
1093 if (cpunum != NOCPU) {
1094 KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
1095 map &= (1 << cpunum);
1097 /* Try choose an idle die. */
1098 if (forward_wakeup_use_htt) {
1099 map2 = (map & (map >> 1)) & 0x5555;
1105 /* set only one bit */
1106 if (forward_wakeup_use_single) {
1107 map = map & ((~map) + 1);
1111 forward_wakeups_delivered++;
1112 ipi_selected(map, IPI_AST);
1115 if (cpunum == NOCPU)
1116 printf("forward_wakeup: Idle processor not found\n");
1122 static void kick_other_cpu(int pri,int cpuid);
1125 kick_other_cpu(int pri,int cpuid)
1127 struct pcpu * pcpu = pcpu_find(cpuid);
1128 int cpri = pcpu->pc_curthread->td_priority;
1130 if (idle_cpus_mask & pcpu->pc_cpumask) {
1131 forward_wakeups_delivered++;
1132 ipi_selected(pcpu->pc_cpumask, IPI_AST);
1139 #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1140 #if !defined(FULL_PREEMPTION)
1141 if (pri <= PRI_MAX_ITHD)
1142 #endif /* ! FULL_PREEMPTION */
1144 ipi_selected(pcpu->pc_cpumask, IPI_PREEMPT);
1147 #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1149 pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
1150 ipi_selected( pcpu->pc_cpumask , IPI_AST);
1156 sched_add(struct thread *td, int flags)
1159 struct td_sched *ts;
1165 THREAD_LOCK_ASSERT(td, MA_OWNED);
1166 KASSERT((td->td_inhibitors == 0),
1167 ("sched_add: trying to run inhibited thread"));
1168 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1169 ("sched_add: bad thread state"));
1170 KASSERT(td->td_flags & TDF_INMEM,
1171 ("sched_add: thread swapped out"));
1172 CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
1173 td, td->td_name, td->td_priority, curthread,
1174 curthread->td_name);
1176 * Now that the thread is moving to the run-queue, set the lock
1177 * to the scheduler's lock.
1179 if (td->td_lock != &sched_lock) {
1180 mtx_lock_spin(&sched_lock);
1181 thread_lock_set(td, &sched_lock);
1185 if (td->td_pinned != 0) {
1186 cpu = td->td_lastcpu;
1187 ts->ts_runq = &runq_pcpu[cpu];
1190 "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td, cpu);
1191 } else if ((td)->td_flags & TDF_BOUND) {
1192 /* Find CPU from bound runq */
1193 KASSERT(SKE_RUNQ_PCPU(ts),("sched_add: bound td_sched not on cpu runq"));
1194 cpu = ts->ts_runq - &runq_pcpu[0];
1197 "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td, cpu);
1200 "sched_add: adding td_sched:%p (td:%p) to gbl runq", ts, td);
1202 ts->ts_runq = &runq;
1205 if (single_cpu && (cpu != PCPU_GET(cpuid))) {
1206 kick_other_cpu(td->td_priority,cpu);
1210 cpumask_t me = PCPU_GET(cpumask);
1211 int idle = idle_cpus_mask & me;
1213 if (!idle && ((flags & SRQ_INTR) == 0) &&
1214 (idle_cpus_mask & ~(hlt_cpus_mask | me)))
1215 forwarded = forward_wakeup(cpu);
1219 if ((flags & SRQ_YIELDING) == 0 && maybe_preempt(td))
1226 if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1228 runq_add(ts->ts_runq, td, flags);
1232 struct td_sched *ts;
1234 THREAD_LOCK_ASSERT(td, MA_OWNED);
1235 KASSERT((td->td_inhibitors == 0),
1236 ("sched_add: trying to run inhibited thread"));
1237 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1238 ("sched_add: bad thread state"));
1239 KASSERT(td->td_flags & TDF_INMEM,
1240 ("sched_add: thread swapped out"));
1241 CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
1242 td, td->td_name, td->td_priority, curthread,
1243 curthread->td_name);
1245 * Now that the thread is moving to the run-queue, set the lock
1246 * to the scheduler's lock.
1248 if (td->td_lock != &sched_lock) {
1249 mtx_lock_spin(&sched_lock);
1250 thread_lock_set(td, &sched_lock);
1253 CTR2(KTR_RUNQ, "sched_add: adding td_sched:%p (td:%p) to runq", ts, td);
1254 ts->ts_runq = &runq;
1257 * If we are yielding (on the way out anyhow)
1258 * or the thread being saved is US,
1259 * then don't try be smart about preemption
1260 * or kicking off another CPU
1261 * as it won't help and may hinder.
1262 * In the YIEDLING case, we are about to run whoever is
1263 * being put in the queue anyhow, and in the
1264 * OURSELF case, we are puting ourself on the run queue
1265 * which also only happens when we are about to yield.
1267 if((flags & SRQ_YIELDING) == 0) {
1268 if (maybe_preempt(td))
1271 if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1273 runq_add(ts->ts_runq, td, flags);
1279 sched_rem(struct thread *td)
1281 struct td_sched *ts;
1284 KASSERT(td->td_flags & TDF_INMEM,
1285 ("sched_rem: thread swapped out"));
1286 KASSERT(TD_ON_RUNQ(td),
1287 ("sched_rem: thread not on run queue"));
1288 mtx_assert(&sched_lock, MA_OWNED);
1289 CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
1290 td, td->td_name, td->td_priority, curthread,
1291 curthread->td_name);
1293 if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1295 runq_remove(ts->ts_runq, td);
1300 * Select threads to run.
1301 * Notice that the running threads still consume a slot.
1309 mtx_assert(&sched_lock, MA_OWNED);
1311 struct thread *tdcpu;
1314 td = runq_choose_fuzz(&runq, runq_fuzz);
1315 tdcpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1319 tdcpu->td_priority < td->td_priority)) {
1320 CTR2(KTR_RUNQ, "choosing td %p from pcpu runq %d", tdcpu,
1323 rq = &runq_pcpu[PCPU_GET(cpuid)];
1325 CTR1(KTR_RUNQ, "choosing td_sched %p from main runq", td);
1330 td = runq_choose(&runq);
1334 runq_remove(rq, td);
1335 td->td_flags |= TDF_DIDRUN;
1337 KASSERT(td->td_flags & TDF_INMEM,
1338 ("sched_choose: thread swapped out"));
1341 return (PCPU_GET(idlethread));
1345 sched_preempt(struct thread *td)
1348 if (td->td_critnest > 1)
1349 td->td_owepreempt = 1;
1351 mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, NULL);
1356 sched_userret(struct thread *td)
1359 * XXX we cheat slightly on the locking here to avoid locking in
1360 * the usual case. Setting td_priority here is essentially an
1361 * incomplete workaround for not setting it properly elsewhere.
1362 * Now that some interrupt handlers are threads, not setting it
1363 * properly elsewhere can clobber it in the window between setting
1364 * it here and returning to user mode, so don't waste time setting
1365 * it perfectly here.
1367 KASSERT((td->td_flags & TDF_BORROWING) == 0,
1368 ("thread with borrowed priority returning to userland"));
1369 if (td->td_priority != td->td_user_pri) {
1371 td->td_priority = td->td_user_pri;
1372 td->td_base_pri = td->td_user_pri;
1378 sched_bind(struct thread *td, int cpu)
1380 struct td_sched *ts;
1382 THREAD_LOCK_ASSERT(td, MA_OWNED);
1383 KASSERT(TD_IS_RUNNING(td),
1384 ("sched_bind: cannot bind non-running thread"));
1388 td->td_flags |= TDF_BOUND;
1390 ts->ts_runq = &runq_pcpu[cpu];
1391 if (PCPU_GET(cpuid) == cpu)
1394 mi_switch(SW_VOL, NULL);
1399 sched_unbind(struct thread* td)
1401 THREAD_LOCK_ASSERT(td, MA_OWNED);
1402 td->td_flags &= ~TDF_BOUND;
1406 sched_is_bound(struct thread *td)
1408 THREAD_LOCK_ASSERT(td, MA_OWNED);
1409 return (td->td_flags & TDF_BOUND);
1413 sched_relinquish(struct thread *td)
1416 mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
1423 return (sched_tdcnt);
1427 sched_sizeof_proc(void)
1429 return (sizeof(struct proc));
1433 sched_sizeof_thread(void)
1435 return (sizeof(struct thread) + sizeof(struct td_sched));
1439 sched_pctcpu(struct thread *td)
1441 struct td_sched *ts;
1444 return (ts->ts_pctcpu);
1453 * The actual idle process.
1456 sched_idletd(void *dummy)
1460 mtx_assert(&Giant, MA_NOTOWNED);
1462 while (sched_runnable() == 0)
1465 mtx_lock_spin(&sched_lock);
1466 mi_switch(SW_VOL | SWT_IDLE, NULL);
1467 mtx_unlock_spin(&sched_lock);
1472 * A CPU is entering for the first time or a thread is exiting.
1475 sched_throw(struct thread *td)
1478 * Correct spinlock nesting. The idle thread context that we are
1479 * borrowing was created so that it would start out with a single
1480 * spin lock (sched_lock) held in fork_trampoline(). Since we've
1481 * explicitly acquired locks in this function, the nesting count
1482 * is now 2 rather than 1. Since we are nested, calling
1483 * spinlock_exit() will simply adjust the counts without allowing
1484 * spin lock using code to interrupt us.
1487 mtx_lock_spin(&sched_lock);
1490 lock_profile_release_lock(&sched_lock.lock_object);
1491 MPASS(td->td_lock == &sched_lock);
1493 mtx_assert(&sched_lock, MA_OWNED);
1494 KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
1495 PCPU_SET(switchtime, cpu_ticks());
1496 PCPU_SET(switchticks, ticks);
1497 cpu_throw(td, choosethread()); /* doesn't return */
1501 sched_fork_exit(struct thread *td)
1505 * Finish setting up thread glue so that it begins execution in a
1506 * non-nested critical section with sched_lock held but not recursed.
1508 td->td_oncpu = PCPU_GET(cpuid);
1509 sched_lock.mtx_lock = (uintptr_t)td;
1510 lock_profile_obtain_lock_success(&sched_lock.lock_object,
1511 0, 0, __FILE__, __LINE__);
1512 THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
1516 sched_affinity(struct thread *td)