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. */
85 #define TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
88 * The schedulable entity that runs a context.
89 * This is an extension to the thread structure and is tailored to
90 * the requirements of this scheduler
93 fixpt_t ts_pctcpu; /* (j) %cpu during p_swtime. */
94 int ts_cpticks; /* (j) Ticks of cpu time. */
95 int ts_slptime; /* (j) Seconds !RUNNING. */
97 struct runq *ts_runq; /* runq the thread is currently on */
99 char ts_name[TS_NAME_LEN];
103 /* flags kept in td_flags */
104 #define TDF_DIDRUN TDF_SCHED0 /* thread actually ran. */
105 #define TDF_BOUND TDF_SCHED1 /* Bound to one CPU. */
107 /* flags kept in ts_flags */
108 #define TSF_AFFINITY 0x0001 /* Has a non-"full" CPU set. */
110 #define SKE_RUNQ_PCPU(ts) \
111 ((ts)->ts_runq != 0 && (ts)->ts_runq != &runq)
113 #define THREAD_CAN_SCHED(td, cpu) \
114 CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
116 static struct td_sched td_sched0;
117 struct mtx sched_lock;
119 static int sched_tdcnt; /* Total runnable threads in the system. */
120 static int sched_quantum; /* Roundrobin scheduling quantum in ticks. */
121 #define SCHED_QUANTUM (hz / 10) /* Default sched quantum */
123 static void setup_runqs(void);
124 static void schedcpu(void);
125 static void schedcpu_thread(void);
126 static void sched_priority(struct thread *td, u_char prio);
127 static void sched_setup(void *dummy);
128 static void maybe_resched(struct thread *td);
129 static void updatepri(struct thread *td);
130 static void resetpriority(struct thread *td);
131 static void resetpriority_thread(struct thread *td);
133 static int sched_pickcpu(struct thread *td);
134 static int forward_wakeup(int cpunum);
135 static void kick_other_cpu(int pri, int cpuid);
138 static struct kproc_desc sched_kp = {
143 SYSINIT(schedcpu, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, kproc_start,
145 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
150 static struct runq runq;
156 static struct runq runq_pcpu[MAXCPU];
157 long runq_length[MAXCPU];
160 struct pcpuidlestat {
164 static DPCPU_DEFINE(struct pcpuidlestat, idlestat);
172 for (i = 0; i < MAXCPU; ++i)
173 runq_init(&runq_pcpu[i]);
180 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
184 new_val = sched_quantum * tick;
185 error = sysctl_handle_int(oidp, &new_val, 0, req);
186 if (error != 0 || req->newptr == NULL)
190 sched_quantum = new_val / tick;
191 hogticks = 2 * sched_quantum;
195 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "Scheduler");
197 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
200 SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
201 0, sizeof sched_quantum, sysctl_kern_quantum, "I",
202 "Roundrobin scheduling quantum in microseconds");
205 /* Enable forwarding of wakeups to all other cpus */
206 SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup, CTLFLAG_RD, NULL, "Kernel SMP");
208 static int runq_fuzz = 1;
209 SYSCTL_INT(_kern_sched, OID_AUTO, runq_fuzz, CTLFLAG_RW, &runq_fuzz, 0, "");
211 static int forward_wakeup_enabled = 1;
212 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
213 &forward_wakeup_enabled, 0,
214 "Forwarding of wakeup to idle CPUs");
216 static int forward_wakeups_requested = 0;
217 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
218 &forward_wakeups_requested, 0,
219 "Requests for Forwarding of wakeup to idle CPUs");
221 static int forward_wakeups_delivered = 0;
222 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
223 &forward_wakeups_delivered, 0,
224 "Completed Forwarding of wakeup to idle CPUs");
226 static int forward_wakeup_use_mask = 1;
227 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
228 &forward_wakeup_use_mask, 0,
229 "Use the mask of idle cpus");
231 static int forward_wakeup_use_loop = 0;
232 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
233 &forward_wakeup_use_loop, 0,
234 "Use a loop to find idle cpus");
236 static int forward_wakeup_use_single = 0;
237 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, onecpu, CTLFLAG_RW,
238 &forward_wakeup_use_single, 0,
239 "Only signal one idle cpu");
241 static int forward_wakeup_use_htt = 0;
242 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, htt2, CTLFLAG_RW,
243 &forward_wakeup_use_htt, 0,
248 static int sched_followon = 0;
249 SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
251 "allow threads to share a quantum");
259 KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
267 KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
270 * Arrange to reschedule if necessary, taking the priorities and
271 * schedulers into account.
274 maybe_resched(struct thread *td)
277 THREAD_LOCK_ASSERT(td, MA_OWNED);
278 if (td->td_priority < curthread->td_priority)
279 curthread->td_flags |= TDF_NEEDRESCHED;
283 * This function is called when a thread is about to be put on run queue
284 * because it has been made runnable or its priority has been adjusted. It
285 * determines if the new thread should be immediately preempted to. If so,
286 * it switches to it and eventually returns true. If not, it returns false
287 * so that the caller may place the thread on an appropriate run queue.
290 maybe_preempt(struct thread *td)
297 * The new thread should not preempt the current thread if any of the
298 * following conditions are true:
300 * - The kernel is in the throes of crashing (panicstr).
301 * - The current thread has a higher (numerically lower) or
302 * equivalent priority. Note that this prevents curthread from
303 * trying to preempt to itself.
304 * - It is too early in the boot for context switches (cold is set).
305 * - The current thread has an inhibitor set or is in the process of
306 * exiting. In this case, the current thread is about to switch
307 * out anyways, so there's no point in preempting. If we did,
308 * the current thread would not be properly resumed as well, so
309 * just avoid that whole landmine.
310 * - If the new thread's priority is not a realtime priority and
311 * the current thread's priority is not an idle priority and
312 * FULL_PREEMPTION is disabled.
314 * If all of these conditions are false, but the current thread is in
315 * a nested critical section, then we have to defer the preemption
316 * until we exit the critical section. Otherwise, switch immediately
320 THREAD_LOCK_ASSERT(td, MA_OWNED);
321 KASSERT((td->td_inhibitors == 0),
322 ("maybe_preempt: trying to run inhibited thread"));
323 pri = td->td_priority;
324 cpri = ctd->td_priority;
325 if (panicstr != NULL || pri >= cpri || cold /* || dumping */ ||
326 TD_IS_INHIBITED(ctd))
328 #ifndef FULL_PREEMPTION
329 if (pri > PRI_MAX_ITHD && cpri < PRI_MIN_IDLE)
333 if (ctd->td_critnest > 1) {
334 CTR1(KTR_PROC, "maybe_preempt: in critical section %d",
336 ctd->td_owepreempt = 1;
340 * Thread is runnable but not yet put on system run queue.
342 MPASS(ctd->td_lock == td->td_lock);
343 MPASS(TD_ON_RUNQ(td));
345 CTR3(KTR_PROC, "preempting to thread %p (pid %d, %s)\n", td,
346 td->td_proc->p_pid, td->td_name);
347 mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, td);
349 * td's lock pointer may have changed. We have to return with it
363 * Constants for digital decay and forget:
364 * 90% of (td_estcpu) usage in 5 * loadav time
365 * 95% of (ts_pctcpu) usage in 60 seconds (load insensitive)
366 * Note that, as ps(1) mentions, this can let percentages
367 * total over 100% (I've seen 137.9% for 3 processes).
369 * Note that schedclock() updates td_estcpu and p_cpticks asynchronously.
371 * We wish to decay away 90% of td_estcpu in (5 * loadavg) seconds.
372 * That is, the system wants to compute a value of decay such
373 * that the following for loop:
374 * for (i = 0; i < (5 * loadavg); i++)
375 * td_estcpu *= decay;
378 * for all values of loadavg:
380 * Mathematically this loop can be expressed by saying:
381 * decay ** (5 * loadavg) ~= .1
383 * The system computes decay as:
384 * decay = (2 * loadavg) / (2 * loadavg + 1)
386 * We wish to prove that the system's computation of decay
387 * will always fulfill the equation:
388 * decay ** (5 * loadavg) ~= .1
390 * If we compute b as:
393 * decay = b / (b + 1)
395 * We now need to prove two things:
396 * 1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
397 * 2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
400 * For x close to zero, exp(x) =~ 1 + x, since
401 * exp(x) = 0! + x**1/1! + x**2/2! + ... .
402 * therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
403 * For x close to zero, ln(1+x) =~ x, since
404 * ln(1+x) = x - x**2/2 + x**3/3 - ... -1 < x < 1
405 * therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
409 * Solve (factor)**(power) =~ .1 given power (5*loadav):
410 * solving for factor,
411 * ln(factor) =~ (-2.30/5*loadav), or
412 * factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
413 * exp(-1/b) =~ (b-1)/b =~ b/(b+1). QED
416 * Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
418 * power*ln(b/(b+1)) =~ -2.30, or
419 * power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav. QED
421 * Actual power values for the implemented algorithm are as follows:
423 * power: 5.68 10.32 14.94 19.55
426 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
427 #define loadfactor(loadav) (2 * (loadav))
428 #define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
430 /* decay 95% of `ts_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
431 static fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
432 SYSCTL_UINT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
435 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
436 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
437 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
439 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
440 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
442 * If you don't want to bother with the faster/more-accurate formula, you
443 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
444 * (more general) method of calculating the %age of CPU used by a process.
446 #define CCPU_SHIFT 11
449 * Recompute process priorities, every hz ticks.
450 * MP-safe, called without the Giant mutex.
456 register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
460 int awake, realstathz;
462 realstathz = stathz ? stathz : hz;
463 sx_slock(&allproc_lock);
464 FOREACH_PROC_IN_SYSTEM(p) {
466 if (p->p_state == PRS_NEW) {
470 FOREACH_THREAD_IN_PROC(p, td) {
475 * Increment sleep time (if sleeping). We
476 * ignore overflow, as above.
479 * The td_sched slptimes are not touched in wakeup
480 * because the thread may not HAVE everything in
481 * memory? XXX I think this is out of date.
483 if (TD_ON_RUNQ(td)) {
485 td->td_flags &= ~TDF_DIDRUN;
486 } else if (TD_IS_RUNNING(td)) {
488 /* Do not clear TDF_DIDRUN */
489 } else if (td->td_flags & TDF_DIDRUN) {
491 td->td_flags &= ~TDF_DIDRUN;
495 * ts_pctcpu is only for ps and ttyinfo().
497 ts->ts_pctcpu = (ts->ts_pctcpu * ccpu) >> FSHIFT;
499 * If the td_sched has been idle the entire second,
500 * stop recalculating its priority until
503 if (ts->ts_cpticks != 0) {
504 #if (FSHIFT >= CCPU_SHIFT)
505 ts->ts_pctcpu += (realstathz == 100)
506 ? ((fixpt_t) ts->ts_cpticks) <<
507 (FSHIFT - CCPU_SHIFT) :
508 100 * (((fixpt_t) ts->ts_cpticks)
509 << (FSHIFT - CCPU_SHIFT)) / realstathz;
511 ts->ts_pctcpu += ((FSCALE - ccpu) *
513 FSCALE / realstathz)) >> FSHIFT;
518 * If there are ANY running threads in this process,
519 * then don't count it as sleeping.
520 * XXX: this is broken.
523 if (ts->ts_slptime > 1) {
525 * In an ideal world, this should not
526 * happen, because whoever woke us
527 * up from the long sleep should have
528 * unwound the slptime and reset our
529 * priority before we run at the stale
530 * priority. Should KASSERT at some
531 * point when all the cases are fixed.
538 if (ts->ts_slptime > 1) {
542 td->td_estcpu = decay_cpu(loadfac, td->td_estcpu);
544 resetpriority_thread(td);
549 sx_sunlock(&allproc_lock);
553 * Main loop for a kthread that executes schedcpu once a second.
556 schedcpu_thread(void)
566 * Recalculate the priority of a process after it has slept for a while.
567 * For all load averages >= 1 and max td_estcpu of 255, sleeping for at
568 * least six times the loadfactor will decay td_estcpu to zero.
571 updatepri(struct thread *td)
578 loadfac = loadfactor(averunnable.ldavg[0]);
579 if (ts->ts_slptime > 5 * loadfac)
582 newcpu = td->td_estcpu;
583 ts->ts_slptime--; /* was incremented in schedcpu() */
584 while (newcpu && --ts->ts_slptime)
585 newcpu = decay_cpu(loadfac, newcpu);
586 td->td_estcpu = newcpu;
591 * Compute the priority of a process when running in user mode.
592 * Arrange to reschedule if the resulting priority is better
593 * than that of the current process.
596 resetpriority(struct thread *td)
598 register unsigned int newpriority;
600 if (td->td_pri_class == PRI_TIMESHARE) {
601 newpriority = PUSER + td->td_estcpu / INVERSE_ESTCPU_WEIGHT +
602 NICE_WEIGHT * (td->td_proc->p_nice - PRIO_MIN);
603 newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
605 sched_user_prio(td, newpriority);
610 * Update the thread's priority when the associated process's user
614 resetpriority_thread(struct thread *td)
617 /* Only change threads with a time sharing user priority. */
618 if (td->td_priority < PRI_MIN_TIMESHARE ||
619 td->td_priority > PRI_MAX_TIMESHARE)
622 /* XXX the whole needresched thing is broken, but not silly. */
625 sched_prio(td, td->td_user_pri);
630 sched_setup(void *dummy)
634 if (sched_quantum == 0)
635 sched_quantum = SCHED_QUANTUM;
636 hogticks = 2 * sched_quantum;
638 /* Account for thread0. */
642 /* External interfaces start here */
645 * Very early in the boot some setup of scheduler-specific
646 * parts of proc0 and of some scheduler resources needs to be done.
654 * Set up the scheduler specific parts of proc0.
656 proc0.p_sched = NULL; /* XXX */
657 thread0.td_sched = &td_sched0;
658 thread0.td_lock = &sched_lock;
659 mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
666 return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
668 return runq_check(&runq);
673 sched_rr_interval(void)
675 if (sched_quantum == 0)
676 sched_quantum = SCHED_QUANTUM;
677 return (sched_quantum);
681 * We adjust the priority of the current process. The priority of
682 * a process gets worse as it accumulates CPU time. The cpu usage
683 * estimator (td_estcpu) is increased here. resetpriority() will
684 * compute a different priority each time td_estcpu increases by
685 * INVERSE_ESTCPU_WEIGHT
686 * (until MAXPRI is reached). The cpu usage estimator ramps up
687 * quite quickly when the process is running (linearly), and decays
688 * away exponentially, at a rate which is proportionally slower when
689 * the system is busy. The basic principle is that the system will
690 * 90% forget that the process used a lot of CPU time in 5 * loadav
691 * seconds. This causes the system to favor processes which haven't
692 * run much recently, and to round-robin among other processes.
695 sched_clock(struct thread *td)
697 struct pcpuidlestat *stat;
700 THREAD_LOCK_ASSERT(td, MA_OWNED);
704 td->td_estcpu = ESTCPULIM(td->td_estcpu + 1);
705 if ((td->td_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
707 resetpriority_thread(td);
711 * Force a context switch if the current thread has used up a full
712 * quantum (default quantum is 100ms).
714 if (!TD_IS_IDLETHREAD(td) &&
715 ticks - PCPU_GET(switchticks) >= sched_quantum)
716 td->td_flags |= TDF_NEEDRESCHED;
718 stat = DPCPU_PTR(idlestat);
719 stat->oldidlecalls = stat->idlecalls;
724 * Charge child's scheduling CPU usage to parent.
727 sched_exit(struct proc *p, struct thread *td)
730 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "proc exit",
731 "prio:td", td->td_priority);
733 PROC_LOCK_ASSERT(p, MA_OWNED);
734 sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
738 sched_exit_thread(struct thread *td, struct thread *child)
741 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "exit",
742 "prio:td", child->td_priority);
744 td->td_estcpu = ESTCPULIM(td->td_estcpu + child->td_estcpu);
747 if ((child->td_flags & TDF_NOLOAD) == 0)
749 thread_unlock(child);
753 sched_fork(struct thread *td, struct thread *childtd)
755 sched_fork_thread(td, childtd);
759 sched_fork_thread(struct thread *td, struct thread *childtd)
763 childtd->td_estcpu = td->td_estcpu;
764 childtd->td_lock = &sched_lock;
765 childtd->td_cpuset = cpuset_ref(td->td_cpuset);
766 childtd->td_priority = childtd->td_base_pri;
767 ts = childtd->td_sched;
768 bzero(ts, sizeof(*ts));
769 ts->ts_flags |= (td->td_sched->ts_flags & TSF_AFFINITY);
773 sched_nice(struct proc *p, int nice)
777 PROC_LOCK_ASSERT(p, MA_OWNED);
779 FOREACH_THREAD_IN_PROC(p, td) {
782 resetpriority_thread(td);
788 sched_class(struct thread *td, int class)
790 THREAD_LOCK_ASSERT(td, MA_OWNED);
791 td->td_pri_class = class;
795 * Adjust the priority of a thread.
798 sched_priority(struct thread *td, u_char prio)
802 KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "priority change",
803 "prio:%d", td->td_priority, "new prio:%d", prio, KTR_ATTR_LINKED,
804 sched_tdname(curthread));
805 if (td != curthread && prio > td->td_priority) {
806 KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
807 "lend prio", "prio:%d", td->td_priority, "new prio:%d",
808 prio, KTR_ATTR_LINKED, sched_tdname(td));
810 THREAD_LOCK_ASSERT(td, MA_OWNED);
811 if (td->td_priority == prio)
813 td->td_priority = prio;
814 if (TD_ON_RUNQ(td) && td->td_rqindex != (prio / RQ_PPQ)) {
816 sched_add(td, SRQ_BORING);
821 * Update a thread's priority when it is lent another thread's
825 sched_lend_prio(struct thread *td, u_char prio)
828 td->td_flags |= TDF_BORROWING;
829 sched_priority(td, prio);
833 * Restore a thread's priority when priority propagation is
834 * over. The prio argument is the minimum priority the thread
835 * needs to have to satisfy other possible priority lending
836 * requests. If the thread's regulary priority is less
837 * important than prio the thread will keep a priority boost
841 sched_unlend_prio(struct thread *td, u_char prio)
845 if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
846 td->td_base_pri <= PRI_MAX_TIMESHARE)
847 base_pri = td->td_user_pri;
849 base_pri = td->td_base_pri;
850 if (prio >= base_pri) {
851 td->td_flags &= ~TDF_BORROWING;
852 sched_prio(td, base_pri);
854 sched_lend_prio(td, prio);
858 sched_prio(struct thread *td, u_char prio)
862 /* First, update the base priority. */
863 td->td_base_pri = prio;
866 * If the thread is borrowing another thread's priority, don't ever
867 * lower the priority.
869 if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
872 /* Change the real priority. */
873 oldprio = td->td_priority;
874 sched_priority(td, prio);
877 * If the thread is on a turnstile, then let the turnstile update
880 if (TD_ON_LOCK(td) && oldprio != prio)
881 turnstile_adjust(td, oldprio);
885 sched_user_prio(struct thread *td, u_char prio)
888 THREAD_LOCK_ASSERT(td, MA_OWNED);
889 td->td_base_user_pri = prio;
890 if (td->td_lend_user_pri <= prio)
892 td->td_user_pri = prio;
896 sched_lend_user_prio(struct thread *td, u_char prio)
899 THREAD_LOCK_ASSERT(td, MA_OWNED);
900 td->td_lend_user_pri = prio;
901 td->td_user_pri = min(prio, td->td_base_user_pri);
902 if (td->td_priority > td->td_user_pri)
903 sched_prio(td, td->td_user_pri);
904 else if (td->td_priority != td->td_user_pri)
905 td->td_flags |= TDF_NEEDRESCHED;
909 sched_sleep(struct thread *td, int pri)
912 THREAD_LOCK_ASSERT(td, MA_OWNED);
913 td->td_slptick = ticks;
914 td->td_sched->ts_slptime = 0;
915 if (pri != 0 && PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
917 if (TD_IS_SUSPENDED(td) || pri >= PSOCK)
918 td->td_flags |= TDF_CANSWAP;
922 sched_switch(struct thread *td, struct thread *newtd, int flags)
932 THREAD_LOCK_ASSERT(td, MA_OWNED);
935 * Switch to the sched lock to fix things up and pick
937 * Block the td_lock in order to avoid breaking the critical path.
939 if (td->td_lock != &sched_lock) {
940 mtx_lock_spin(&sched_lock);
941 tmtx = thread_lock_block(td);
944 if ((td->td_flags & TDF_NOLOAD) == 0)
947 td->td_lastcpu = td->td_oncpu;
948 if (!(flags & SW_PREEMPT))
949 td->td_flags &= ~TDF_NEEDRESCHED;
950 td->td_owepreempt = 0;
951 td->td_oncpu = NOCPU;
954 * At the last moment, if this thread is still marked RUNNING,
955 * then put it back on the run queue as it has not been suspended
956 * or stopped or any thing else similar. We never put the idle
957 * threads on the run queue, however.
959 if (td->td_flags & TDF_IDLETD) {
962 idle_cpus_mask &= ~PCPU_GET(cpumask);
965 if (TD_IS_RUNNING(td)) {
966 /* Put us back on the run queue. */
967 sched_add(td, (flags & SW_PREEMPT) ?
968 SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
969 SRQ_OURSELF|SRQ_YIELDING);
974 * The thread we are about to run needs to be counted
975 * as if it had been added to the run queue and selected.
981 KASSERT((newtd->td_inhibitors == 0),
982 ("trying to run inhibited thread"));
983 newtd->td_flags |= TDF_DIDRUN;
984 TD_SET_RUNNING(newtd);
985 if ((newtd->td_flags & TDF_NOLOAD) == 0)
988 newtd = choosethread();
989 MPASS(newtd->td_lock == &sched_lock);
994 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
995 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
998 lock_profile_release_lock(&sched_lock.lock_object);
1001 * If DTrace has set the active vtime enum to anything
1002 * other than INACTIVE (0), then it should have set the
1005 if (dtrace_vtime_active)
1006 (*dtrace_vtime_switch_func)(newtd);
1009 cpu_switch(td, newtd, tmtx != NULL ? tmtx : td->td_lock);
1010 lock_profile_obtain_lock_success(&sched_lock.lock_object,
1011 0, 0, __FILE__, __LINE__);
1013 * Where am I? What year is it?
1014 * We are in the same thread that went to sleep above,
1015 * but any amount of time may have passed. All our context
1016 * will still be available as will local variables.
1017 * PCPU values however may have changed as we may have
1018 * changed CPU so don't trust cached values of them.
1019 * New threads will go to fork_exit() instead of here
1020 * so if you change things here you may need to change
1023 * If the thread above was exiting it will never wake
1024 * up again here, so either it has saved everything it
1025 * needed to, or the thread_wait() or wait() will
1029 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1030 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1035 if (td->td_flags & TDF_IDLETD)
1036 idle_cpus_mask |= PCPU_GET(cpumask);
1038 sched_lock.mtx_lock = (uintptr_t)td;
1039 td->td_oncpu = PCPU_GET(cpuid);
1040 MPASS(td->td_lock == &sched_lock);
1044 sched_wakeup(struct thread *td)
1046 struct td_sched *ts;
1048 THREAD_LOCK_ASSERT(td, MA_OWNED);
1050 td->td_flags &= ~TDF_CANSWAP;
1051 if (ts->ts_slptime > 1) {
1057 sched_add(td, SRQ_BORING);
1062 forward_wakeup(int cpunum)
1065 cpumask_t dontuse, id, map, map2, map3, me;
1067 mtx_assert(&sched_lock, MA_OWNED);
1069 CTR0(KTR_RUNQ, "forward_wakeup()");
1071 if ((!forward_wakeup_enabled) ||
1072 (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
1074 if (!smp_started || cold || panicstr)
1077 forward_wakeups_requested++;
1080 * Check the idle mask we received against what we calculated
1081 * before in the old version.
1083 me = PCPU_GET(cpumask);
1085 /* Don't bother if we should be doing it ourself. */
1086 if ((me & idle_cpus_mask) && (cpunum == NOCPU || me == (1 << cpunum)))
1089 dontuse = me | stopped_cpus | hlt_cpus_mask;
1091 if (forward_wakeup_use_loop) {
1092 SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {
1093 id = pc->pc_cpumask;
1094 if ((id & dontuse) == 0 &&
1095 pc->pc_curthread == pc->pc_idlethread) {
1101 if (forward_wakeup_use_mask) {
1103 map = idle_cpus_mask & ~dontuse;
1105 /* If they are both on, compare and use loop if different. */
1106 if (forward_wakeup_use_loop) {
1108 printf("map (%02X) != map3 (%02X)\n", map,
1117 /* If we only allow a specific CPU, then mask off all the others. */
1118 if (cpunum != NOCPU) {
1119 KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
1120 map &= (1 << cpunum);
1122 /* Try choose an idle die. */
1123 if (forward_wakeup_use_htt) {
1124 map2 = (map & (map >> 1)) & 0x5555;
1130 /* Set only one bit. */
1131 if (forward_wakeup_use_single) {
1132 map = map & ((~map) + 1);
1136 forward_wakeups_delivered++;
1137 SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {
1138 id = pc->pc_cpumask;
1139 if ((map & id) == 0)
1141 if (cpu_idle_wakeup(pc->pc_cpuid))
1145 ipi_selected(map, IPI_AST);
1148 if (cpunum == NOCPU)
1149 printf("forward_wakeup: Idle processor not found\n");
1154 kick_other_cpu(int pri, int cpuid)
1159 pcpu = pcpu_find(cpuid);
1160 if (idle_cpus_mask & pcpu->pc_cpumask) {
1161 forward_wakeups_delivered++;
1162 if (!cpu_idle_wakeup(cpuid))
1163 ipi_cpu(cpuid, IPI_AST);
1167 cpri = pcpu->pc_curthread->td_priority;
1171 #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1172 #if !defined(FULL_PREEMPTION)
1173 if (pri <= PRI_MAX_ITHD)
1174 #endif /* ! FULL_PREEMPTION */
1176 ipi_cpu(cpuid, IPI_PREEMPT);
1179 #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1181 pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
1182 ipi_cpu(cpuid, IPI_AST);
1189 sched_pickcpu(struct thread *td)
1193 mtx_assert(&sched_lock, MA_OWNED);
1195 if (THREAD_CAN_SCHED(td, td->td_lastcpu))
1196 best = td->td_lastcpu;
1200 if (!THREAD_CAN_SCHED(td, cpu))
1205 else if (runq_length[cpu] < runq_length[best])
1208 KASSERT(best != NOCPU, ("no valid CPUs"));
1215 sched_add(struct thread *td, int flags)
1218 struct td_sched *ts;
1224 THREAD_LOCK_ASSERT(td, MA_OWNED);
1225 KASSERT((td->td_inhibitors == 0),
1226 ("sched_add: trying to run inhibited thread"));
1227 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1228 ("sched_add: bad thread state"));
1229 KASSERT(td->td_flags & TDF_INMEM,
1230 ("sched_add: thread swapped out"));
1232 KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
1233 "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1234 sched_tdname(curthread));
1235 KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
1236 KTR_ATTR_LINKED, sched_tdname(td));
1240 * Now that the thread is moving to the run-queue, set the lock
1241 * to the scheduler's lock.
1243 if (td->td_lock != &sched_lock) {
1244 mtx_lock_spin(&sched_lock);
1245 thread_lock_set(td, &sched_lock);
1250 * If SMP is started and the thread is pinned or otherwise limited to
1251 * a specific set of CPUs, queue the thread to a per-CPU run queue.
1252 * Otherwise, queue the thread to the global run queue.
1254 * If SMP has not yet been started we must use the global run queue
1255 * as per-CPU state may not be initialized yet and we may crash if we
1256 * try to access the per-CPU run queues.
1258 if (smp_started && (td->td_pinned != 0 || td->td_flags & TDF_BOUND ||
1259 ts->ts_flags & TSF_AFFINITY)) {
1260 if (td->td_pinned != 0)
1261 cpu = td->td_lastcpu;
1262 else if (td->td_flags & TDF_BOUND) {
1263 /* Find CPU from bound runq. */
1264 KASSERT(SKE_RUNQ_PCPU(ts),
1265 ("sched_add: bound td_sched not on cpu runq"));
1266 cpu = ts->ts_runq - &runq_pcpu[0];
1268 /* Find a valid CPU for our cpuset */
1269 cpu = sched_pickcpu(td);
1270 ts->ts_runq = &runq_pcpu[cpu];
1273 "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td,
1277 "sched_add: adding td_sched:%p (td:%p) to gbl runq", ts,
1280 ts->ts_runq = &runq;
1283 if (single_cpu && (cpu != PCPU_GET(cpuid))) {
1284 kick_other_cpu(td->td_priority, cpu);
1287 cpumask_t me = PCPU_GET(cpumask);
1288 cpumask_t idle = idle_cpus_mask & me;
1290 if (!idle && ((flags & SRQ_INTR) == 0) &&
1291 (idle_cpus_mask & ~(hlt_cpus_mask | me)))
1292 forwarded = forward_wakeup(cpu);
1296 if ((flags & SRQ_YIELDING) == 0 && maybe_preempt(td))
1303 if ((td->td_flags & TDF_NOLOAD) == 0)
1305 runq_add(ts->ts_runq, td, flags);
1311 struct td_sched *ts;
1314 THREAD_LOCK_ASSERT(td, MA_OWNED);
1315 KASSERT((td->td_inhibitors == 0),
1316 ("sched_add: trying to run inhibited thread"));
1317 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1318 ("sched_add: bad thread state"));
1319 KASSERT(td->td_flags & TDF_INMEM,
1320 ("sched_add: thread swapped out"));
1321 KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
1322 "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1323 sched_tdname(curthread));
1324 KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
1325 KTR_ATTR_LINKED, sched_tdname(td));
1328 * Now that the thread is moving to the run-queue, set the lock
1329 * to the scheduler's lock.
1331 if (td->td_lock != &sched_lock) {
1332 mtx_lock_spin(&sched_lock);
1333 thread_lock_set(td, &sched_lock);
1336 CTR2(KTR_RUNQ, "sched_add: adding td_sched:%p (td:%p) to runq", ts, td);
1337 ts->ts_runq = &runq;
1340 * If we are yielding (on the way out anyhow) or the thread
1341 * being saved is US, then don't try be smart about preemption
1342 * or kicking off another CPU as it won't help and may hinder.
1343 * In the YIEDLING case, we are about to run whoever is being
1344 * put in the queue anyhow, and in the OURSELF case, we are
1345 * puting ourself on the run queue which also only happens
1346 * when we are about to yield.
1348 if ((flags & SRQ_YIELDING) == 0) {
1349 if (maybe_preempt(td))
1352 if ((td->td_flags & TDF_NOLOAD) == 0)
1354 runq_add(ts->ts_runq, td, flags);
1360 sched_rem(struct thread *td)
1362 struct td_sched *ts;
1365 KASSERT(td->td_flags & TDF_INMEM,
1366 ("sched_rem: thread swapped out"));
1367 KASSERT(TD_ON_RUNQ(td),
1368 ("sched_rem: thread not on run queue"));
1369 mtx_assert(&sched_lock, MA_OWNED);
1370 KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
1371 "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1372 sched_tdname(curthread));
1374 if ((td->td_flags & TDF_NOLOAD) == 0)
1377 if (ts->ts_runq != &runq)
1378 runq_length[ts->ts_runq - runq_pcpu]--;
1380 runq_remove(ts->ts_runq, td);
1385 * Select threads to run. Note that running threads still consume a
1394 mtx_assert(&sched_lock, MA_OWNED);
1396 struct thread *tdcpu;
1399 td = runq_choose_fuzz(&runq, runq_fuzz);
1400 tdcpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1404 tdcpu->td_priority < td->td_priority)) {
1405 CTR2(KTR_RUNQ, "choosing td %p from pcpu runq %d", tdcpu,
1408 rq = &runq_pcpu[PCPU_GET(cpuid)];
1410 CTR1(KTR_RUNQ, "choosing td_sched %p from main runq", td);
1415 td = runq_choose(&runq);
1421 runq_length[PCPU_GET(cpuid)]--;
1423 runq_remove(rq, td);
1424 td->td_flags |= TDF_DIDRUN;
1426 KASSERT(td->td_flags & TDF_INMEM,
1427 ("sched_choose: thread swapped out"));
1430 return (PCPU_GET(idlethread));
1434 sched_preempt(struct thread *td)
1437 if (td->td_critnest > 1)
1438 td->td_owepreempt = 1;
1440 mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, NULL);
1445 sched_userret(struct thread *td)
1448 * XXX we cheat slightly on the locking here to avoid locking in
1449 * the usual case. Setting td_priority here is essentially an
1450 * incomplete workaround for not setting it properly elsewhere.
1451 * Now that some interrupt handlers are threads, not setting it
1452 * properly elsewhere can clobber it in the window between setting
1453 * it here and returning to user mode, so don't waste time setting
1454 * it perfectly here.
1456 KASSERT((td->td_flags & TDF_BORROWING) == 0,
1457 ("thread with borrowed priority returning to userland"));
1458 if (td->td_priority != td->td_user_pri) {
1460 td->td_priority = td->td_user_pri;
1461 td->td_base_pri = td->td_user_pri;
1467 sched_bind(struct thread *td, int cpu)
1469 struct td_sched *ts;
1471 THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
1472 KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
1476 td->td_flags |= TDF_BOUND;
1478 ts->ts_runq = &runq_pcpu[cpu];
1479 if (PCPU_GET(cpuid) == cpu)
1482 mi_switch(SW_VOL, NULL);
1487 sched_unbind(struct thread* td)
1489 THREAD_LOCK_ASSERT(td, MA_OWNED);
1490 KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
1491 td->td_flags &= ~TDF_BOUND;
1495 sched_is_bound(struct thread *td)
1497 THREAD_LOCK_ASSERT(td, MA_OWNED);
1498 return (td->td_flags & TDF_BOUND);
1502 sched_relinquish(struct thread *td)
1505 mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
1512 return (sched_tdcnt);
1516 sched_sizeof_proc(void)
1518 return (sizeof(struct proc));
1522 sched_sizeof_thread(void)
1524 return (sizeof(struct thread) + sizeof(struct td_sched));
1528 sched_pctcpu(struct thread *td)
1530 struct td_sched *ts;
1532 THREAD_LOCK_ASSERT(td, MA_OWNED);
1534 return (ts->ts_pctcpu);
1543 * The actual idle process.
1546 sched_idletd(void *dummy)
1548 struct pcpuidlestat *stat;
1550 stat = DPCPU_PTR(idlestat);
1552 mtx_assert(&Giant, MA_NOTOWNED);
1554 while (sched_runnable() == 0) {
1555 cpu_idle(stat->idlecalls + stat->oldidlecalls > 64);
1559 mtx_lock_spin(&sched_lock);
1560 mi_switch(SW_VOL | SWT_IDLE, NULL);
1561 mtx_unlock_spin(&sched_lock);
1566 * A CPU is entering for the first time or a thread is exiting.
1569 sched_throw(struct thread *td)
1572 * Correct spinlock nesting. The idle thread context that we are
1573 * borrowing was created so that it would start out with a single
1574 * spin lock (sched_lock) held in fork_trampoline(). Since we've
1575 * explicitly acquired locks in this function, the nesting count
1576 * is now 2 rather than 1. Since we are nested, calling
1577 * spinlock_exit() will simply adjust the counts without allowing
1578 * spin lock using code to interrupt us.
1581 mtx_lock_spin(&sched_lock);
1584 lock_profile_release_lock(&sched_lock.lock_object);
1585 MPASS(td->td_lock == &sched_lock);
1587 mtx_assert(&sched_lock, MA_OWNED);
1588 KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
1589 PCPU_SET(switchtime, cpu_ticks());
1590 PCPU_SET(switchticks, ticks);
1591 cpu_throw(td, choosethread()); /* doesn't return */
1595 sched_fork_exit(struct thread *td)
1599 * Finish setting up thread glue so that it begins execution in a
1600 * non-nested critical section with sched_lock held but not recursed.
1602 td->td_oncpu = PCPU_GET(cpuid);
1603 sched_lock.mtx_lock = (uintptr_t)td;
1604 lock_profile_obtain_lock_success(&sched_lock.lock_object,
1605 0, 0, __FILE__, __LINE__);
1606 THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
1610 sched_tdname(struct thread *td)
1613 struct td_sched *ts;
1616 if (ts->ts_name[0] == '\0')
1617 snprintf(ts->ts_name, sizeof(ts->ts_name),
1618 "%s tid %d", td->td_name, td->td_tid);
1619 return (ts->ts_name);
1621 return (td->td_name);
1626 sched_affinity(struct thread *td)
1629 struct td_sched *ts;
1632 THREAD_LOCK_ASSERT(td, MA_OWNED);
1635 * Set the TSF_AFFINITY flag if there is at least one CPU this
1636 * thread can't run on.
1639 ts->ts_flags &= ~TSF_AFFINITY;
1641 if (!THREAD_CAN_SCHED(td, cpu)) {
1642 ts->ts_flags |= TSF_AFFINITY;
1648 * If this thread can run on all CPUs, nothing else to do.
1650 if (!(ts->ts_flags & TSF_AFFINITY))
1653 /* Pinned threads and bound threads should be left alone. */
1654 if (td->td_pinned != 0 || td->td_flags & TDF_BOUND)
1657 switch (td->td_state) {
1660 * If we are on a per-CPU runqueue that is in the set,
1661 * then nothing needs to be done.
1663 if (ts->ts_runq != &runq &&
1664 THREAD_CAN_SCHED(td, ts->ts_runq - runq_pcpu))
1667 /* Put this thread on a valid per-CPU runqueue. */
1669 sched_add(td, SRQ_BORING);
1673 * See if our current CPU is in the set. If not, force a
1676 if (THREAD_CAN_SCHED(td, td->td_oncpu))
1679 td->td_flags |= TDF_NEEDRESCHED;
1680 if (td != curthread)
1681 ipi_cpu(cpu, IPI_AST);