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"
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
45 #include <sys/kthread.h>
46 #include <sys/mutex.h>
48 #include <sys/resourcevar.h>
49 #include <sys/sched.h>
51 #include <sys/sysctl.h>
53 #include <sys/turnstile.h>
55 #include <machine/pcb.h>
56 #include <machine/smp.h>
59 #include <sys/pmckern.h>
63 * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
64 * the range 100-256 Hz (approximately).
66 #define ESTCPULIM(e) \
67 min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
68 RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
70 #define INVERSE_ESTCPU_WEIGHT (8 * smp_cpus)
72 #define INVERSE_ESTCPU_WEIGHT 8 /* 1 / (priorities per estcpu level). */
74 #define NICE_WEIGHT 1 /* Priorities per nice level. */
77 * The schedulable entity that runs a context.
78 * This is an extension to the thread structure and is tailored to
79 * the requirements of this scheduler
82 TAILQ_ENTRY(td_sched) ts_procq; /* (j/z) Run queue. */
83 struct thread *ts_thread; /* (*) Active associated thread. */
84 fixpt_t ts_pctcpu; /* (j) %cpu during p_swtime. */
85 u_char ts_rqindex; /* (j) Run queue index. */
86 int ts_cpticks; /* (j) Ticks of cpu time. */
87 struct runq *ts_runq; /* runq the thread is currently on */
90 /* flags kept in td_flags */
91 #define TDF_DIDRUN TDF_SCHED0 /* thread actually ran. */
92 #define TDF_EXIT TDF_SCHED1 /* thread is being killed. */
93 #define TDF_BOUND TDF_SCHED2
95 #define ts_flags ts_thread->td_flags
96 #define TSF_DIDRUN TDF_DIDRUN /* thread actually ran. */
97 #define TSF_EXIT TDF_EXIT /* thread is being killed. */
98 #define TSF_BOUND TDF_BOUND /* stuck to one CPU */
100 #define SKE_RUNQ_PCPU(ts) \
101 ((ts)->ts_runq != 0 && (ts)->ts_runq != &runq)
103 static struct td_sched td_sched0;
105 static int sched_tdcnt; /* Total runnable threads in the system. */
106 static int sched_quantum; /* Roundrobin scheduling quantum in ticks. */
107 #define SCHED_QUANTUM (hz / 10) /* Default sched quantum */
109 static struct callout roundrobin_callout;
111 static void setup_runqs(void);
112 static void roundrobin(void *arg);
113 static void schedcpu(void);
114 static void schedcpu_thread(void);
115 static void sched_priority(struct thread *td, u_char prio);
116 static void sched_setup(void *dummy);
117 static void maybe_resched(struct thread *td);
118 static void updatepri(struct thread *td);
119 static void resetpriority(struct thread *td);
120 static void resetpriority_thread(struct thread *td);
122 static int forward_wakeup(int cpunum);
125 static struct kproc_desc sched_kp = {
130 SYSINIT(schedcpu, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, kproc_start, &sched_kp)
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 forward_wakeup_enabled = 1;
188 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
189 &forward_wakeup_enabled, 0,
190 "Forwarding of wakeup to idle CPUs");
192 static int forward_wakeups_requested = 0;
193 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
194 &forward_wakeups_requested, 0,
195 "Requests for Forwarding of wakeup to idle CPUs");
197 static int forward_wakeups_delivered = 0;
198 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
199 &forward_wakeups_delivered, 0,
200 "Completed Forwarding of wakeup to idle CPUs");
202 static int forward_wakeup_use_mask = 1;
203 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
204 &forward_wakeup_use_mask, 0,
205 "Use the mask of idle cpus");
207 static int forward_wakeup_use_loop = 0;
208 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
209 &forward_wakeup_use_loop, 0,
210 "Use a loop to find idle cpus");
212 static int forward_wakeup_use_single = 0;
213 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, onecpu, CTLFLAG_RW,
214 &forward_wakeup_use_single, 0,
215 "Only signal one idle cpu");
217 static int forward_wakeup_use_htt = 0;
218 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, htt2, CTLFLAG_RW,
219 &forward_wakeup_use_htt, 0,
224 static int sched_followon = 0;
225 SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
227 "allow threads to share a quantum");
234 CTR1(KTR_SCHED, "global load: %d", sched_tdcnt);
241 CTR1(KTR_SCHED, "global load: %d", sched_tdcnt);
244 * Arrange to reschedule if necessary, taking the priorities and
245 * schedulers into account.
248 maybe_resched(struct thread *td)
251 mtx_assert(&sched_lock, MA_OWNED);
252 if (td->td_priority < curthread->td_priority)
253 curthread->td_flags |= TDF_NEEDRESCHED;
257 * Force switch among equal priority processes every 100ms.
258 * We don't actually need to force a context switch of the current process.
259 * The act of firing the event triggers a context switch to softclock() and
260 * then switching back out again which is equivalent to a preemption, thus
261 * no further work is needed on the local CPU.
265 roundrobin(void *arg)
269 mtx_lock_spin(&sched_lock);
270 forward_roundrobin();
271 mtx_unlock_spin(&sched_lock);
274 callout_reset(&roundrobin_callout, sched_quantum, roundrobin, NULL);
278 * Constants for digital decay and forget:
279 * 90% of (td_estcpu) usage in 5 * loadav time
280 * 95% of (ts_pctcpu) usage in 60 seconds (load insensitive)
281 * Note that, as ps(1) mentions, this can let percentages
282 * total over 100% (I've seen 137.9% for 3 processes).
284 * Note that schedclock() updates td_estcpu and p_cpticks asynchronously.
286 * We wish to decay away 90% of td_estcpu in (5 * loadavg) seconds.
287 * That is, the system wants to compute a value of decay such
288 * that the following for loop:
289 * for (i = 0; i < (5 * loadavg); i++)
290 * td_estcpu *= decay;
293 * for all values of loadavg:
295 * Mathematically this loop can be expressed by saying:
296 * decay ** (5 * loadavg) ~= .1
298 * The system computes decay as:
299 * decay = (2 * loadavg) / (2 * loadavg + 1)
301 * We wish to prove that the system's computation of decay
302 * will always fulfill the equation:
303 * decay ** (5 * loadavg) ~= .1
305 * If we compute b as:
308 * decay = b / (b + 1)
310 * We now need to prove two things:
311 * 1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
312 * 2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
315 * For x close to zero, exp(x) =~ 1 + x, since
316 * exp(x) = 0! + x**1/1! + x**2/2! + ... .
317 * therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
318 * For x close to zero, ln(1+x) =~ x, since
319 * ln(1+x) = x - x**2/2 + x**3/3 - ... -1 < x < 1
320 * therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
324 * Solve (factor)**(power) =~ .1 given power (5*loadav):
325 * solving for factor,
326 * ln(factor) =~ (-2.30/5*loadav), or
327 * factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
328 * exp(-1/b) =~ (b-1)/b =~ b/(b+1). QED
331 * Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
333 * power*ln(b/(b+1)) =~ -2.30, or
334 * power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav. QED
336 * Actual power values for the implemented algorithm are as follows:
338 * power: 5.68 10.32 14.94 19.55
341 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
342 #define loadfactor(loadav) (2 * (loadav))
343 #define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
345 /* decay 95% of `ts_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
346 static fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
347 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
350 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
351 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
352 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
354 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
355 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
357 * If you don't want to bother with the faster/more-accurate formula, you
358 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
359 * (more general) method of calculating the %age of CPU used by a process.
361 #define CCPU_SHIFT 11
364 * Recompute process priorities, every hz ticks.
365 * MP-safe, called without the Giant mutex.
371 register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
375 int awake, realstathz;
377 realstathz = stathz ? stathz : hz;
378 sx_slock(&allproc_lock);
379 FOREACH_PROC_IN_SYSTEM(p) {
381 * Prevent state changes and protect run queue.
383 mtx_lock_spin(&sched_lock);
385 * Increment time in/out of memory. We ignore overflow; with
386 * 16-bit int's (remember them?) overflow takes 45 days.
389 FOREACH_THREAD_IN_PROC(p, td) {
393 * Increment sleep time (if sleeping). We
394 * ignore overflow, as above.
397 * The td_sched slptimes are not touched in wakeup
398 * because the thread may not HAVE everything in
399 * memory? XXX I think this is out of date.
401 if (TD_ON_RUNQ(td)) {
403 ts->ts_flags &= ~TSF_DIDRUN;
404 } else if (TD_IS_RUNNING(td)) {
406 /* Do not clear TSF_DIDRUN */
407 } else if (ts->ts_flags & TSF_DIDRUN) {
409 ts->ts_flags &= ~TSF_DIDRUN;
413 * ts_pctcpu is only for ps and ttyinfo().
414 * Do it per td_sched, and add them up at the end?
417 ts->ts_pctcpu = (ts->ts_pctcpu * ccpu) >> FSHIFT;
419 * If the td_sched has been idle the entire second,
420 * stop recalculating its priority until
423 if (ts->ts_cpticks != 0) {
424 #if (FSHIFT >= CCPU_SHIFT)
425 ts->ts_pctcpu += (realstathz == 100)
426 ? ((fixpt_t) ts->ts_cpticks) <<
427 (FSHIFT - CCPU_SHIFT) :
428 100 * (((fixpt_t) ts->ts_cpticks)
429 << (FSHIFT - CCPU_SHIFT)) / realstathz;
431 ts->ts_pctcpu += ((FSCALE - ccpu) *
433 FSCALE / realstathz)) >> FSHIFT;
438 * If there are ANY running threads in this process,
439 * then don't count it as sleeping.
444 if (td->td_slptime > 1) {
446 * In an ideal world, this should not
447 * happen, because whoever woke us
448 * up from the long sleep should have
449 * unwound the slptime and reset our
450 * priority before we run at the stale
451 * priority. Should KASSERT at some
452 * point when all the cases are fixed.
459 if (td->td_slptime > 1)
461 td->td_estcpu = decay_cpu(loadfac, td->td_estcpu);
463 resetpriority_thread(td);
464 } /* end of thread loop */
465 mtx_unlock_spin(&sched_lock);
466 } /* end of process loop */
467 sx_sunlock(&allproc_lock);
471 * Main loop for a kthread that executes schedcpu once a second.
474 schedcpu_thread(void)
484 * Recalculate the priority of a process after it has slept for a while.
485 * For all load averages >= 1 and max td_estcpu of 255, sleeping for at
486 * least six times the loadfactor will decay td_estcpu to zero.
489 updatepri(struct thread *td)
491 register fixpt_t loadfac;
492 register unsigned int newcpu;
494 loadfac = loadfactor(averunnable.ldavg[0]);
495 if (td->td_slptime > 5 * loadfac)
498 newcpu = td->td_estcpu;
499 td->td_slptime--; /* was incremented in schedcpu() */
500 while (newcpu && --td->td_slptime)
501 newcpu = decay_cpu(loadfac, newcpu);
502 td->td_estcpu = newcpu;
507 * Compute the priority of a process when running in user mode.
508 * Arrange to reschedule if the resulting priority is better
509 * than that of the current process.
512 resetpriority(struct thread *td)
514 register unsigned int newpriority;
516 if (td->td_pri_class == PRI_TIMESHARE) {
517 newpriority = PUSER + td->td_estcpu / INVERSE_ESTCPU_WEIGHT +
518 NICE_WEIGHT * (td->td_proc->p_nice - PRIO_MIN);
519 newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
521 sched_user_prio(td, newpriority);
526 * Update the thread's priority when the associated process's user
530 resetpriority_thread(struct thread *td)
533 /* Only change threads with a time sharing user priority. */
534 if (td->td_priority < PRI_MIN_TIMESHARE ||
535 td->td_priority > PRI_MAX_TIMESHARE)
538 /* XXX the whole needresched thing is broken, but not silly. */
541 sched_prio(td, td->td_user_pri);
546 sched_setup(void *dummy)
550 if (sched_quantum == 0)
551 sched_quantum = SCHED_QUANTUM;
552 hogticks = 2 * sched_quantum;
554 callout_init(&roundrobin_callout, CALLOUT_MPSAFE);
556 /* Kick off timeout driven events by calling first time. */
559 /* Account for thread0. */
563 /* External interfaces start here */
565 * Very early in the boot some setup of scheduler-specific
566 * parts of proc0 and of some scheduler resources needs to be done.
574 * Set up the scheduler specific parts of proc0.
576 proc0.p_sched = NULL; /* XXX */
577 thread0.td_sched = &td_sched0;
578 td_sched0.ts_thread = &thread0;
585 return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
587 return runq_check(&runq);
592 sched_rr_interval(void)
594 if (sched_quantum == 0)
595 sched_quantum = SCHED_QUANTUM;
596 return (sched_quantum);
600 * We adjust the priority of the current process. The priority of
601 * a process gets worse as it accumulates CPU time. The cpu usage
602 * estimator (td_estcpu) is increased here. resetpriority() will
603 * compute a different priority each time td_estcpu increases by
604 * INVERSE_ESTCPU_WEIGHT
605 * (until MAXPRI is reached). The cpu usage estimator ramps up
606 * quite quickly when the process is running (linearly), and decays
607 * away exponentially, at a rate which is proportionally slower when
608 * the system is busy. The basic principle is that the system will
609 * 90% forget that the process used a lot of CPU time in 5 * loadav
610 * seconds. This causes the system to favor processes which haven't
611 * run much recently, and to round-robin among other processes.
614 sched_clock(struct thread *td)
618 mtx_assert(&sched_lock, MA_OWNED);
622 td->td_estcpu = ESTCPULIM(td->td_estcpu + 1);
623 if ((td->td_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
625 resetpriority_thread(td);
630 * charge childs scheduling cpu usage to parent.
633 sched_exit(struct proc *p, struct thread *td)
636 CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
637 td, td->td_proc->p_comm, td->td_priority);
639 sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
643 sched_exit_thread(struct thread *td, struct thread *child)
645 struct proc *childproc = child->td_proc;
647 CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
648 child, childproc->p_comm, child->td_priority);
649 td->td_estcpu = ESTCPULIM(td->td_estcpu + child->td_estcpu);
650 childproc->p_estcpu = ESTCPULIM(childproc->p_estcpu +
652 if ((child->td_proc->p_flag & P_NOLOAD) == 0)
657 sched_fork(struct thread *td, struct thread *childtd)
659 sched_fork_thread(td, childtd);
663 sched_fork_thread(struct thread *td, struct thread *childtd)
665 childtd->td_estcpu = td->td_estcpu;
666 sched_newthread(childtd);
670 sched_nice(struct proc *p, int nice)
674 PROC_LOCK_ASSERT(p, MA_OWNED);
675 mtx_assert(&sched_lock, MA_OWNED);
677 FOREACH_THREAD_IN_PROC(p, td) {
679 resetpriority_thread(td);
684 sched_class(struct thread *td, int class)
686 mtx_assert(&sched_lock, MA_OWNED);
687 td->td_pri_class = class;
691 * Adjust the priority of a thread.
694 sched_priority(struct thread *td, u_char prio)
696 CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
697 td, td->td_proc->p_comm, td->td_priority, prio, curthread,
698 curthread->td_proc->p_comm);
700 mtx_assert(&sched_lock, MA_OWNED);
701 if (td->td_priority == prio)
703 td->td_priority = prio;
704 if (TD_ON_RUNQ(td) &&
705 td->td_sched->ts_rqindex != (prio / RQ_PPQ)) {
707 sched_add(td, SRQ_BORING);
712 * Update a thread's priority when it is lent another thread's
716 sched_lend_prio(struct thread *td, u_char prio)
719 td->td_flags |= TDF_BORROWING;
720 sched_priority(td, prio);
724 * Restore a thread's priority when priority propagation is
725 * over. The prio argument is the minimum priority the thread
726 * needs to have to satisfy other possible priority lending
727 * requests. If the thread's regulary priority is less
728 * important than prio the thread will keep a priority boost
732 sched_unlend_prio(struct thread *td, u_char prio)
736 if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
737 td->td_base_pri <= PRI_MAX_TIMESHARE)
738 base_pri = td->td_user_pri;
740 base_pri = td->td_base_pri;
741 if (prio >= base_pri) {
742 td->td_flags &= ~TDF_BORROWING;
743 sched_prio(td, base_pri);
745 sched_lend_prio(td, prio);
749 sched_prio(struct thread *td, u_char prio)
753 /* First, update the base priority. */
754 td->td_base_pri = prio;
757 * If the thread is borrowing another thread's priority, don't ever
758 * lower the priority.
760 if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
763 /* Change the real priority. */
764 oldprio = td->td_priority;
765 sched_priority(td, prio);
768 * If the thread is on a turnstile, then let the turnstile update
771 if (TD_ON_LOCK(td) && oldprio != prio)
772 turnstile_adjust(td, oldprio);
776 sched_user_prio(struct thread *td, u_char prio)
780 td->td_base_user_pri = prio;
781 if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
783 oldprio = td->td_user_pri;
784 td->td_user_pri = prio;
786 if (TD_ON_UPILOCK(td) && oldprio != prio)
787 umtx_pi_adjust(td, oldprio);
791 sched_lend_user_prio(struct thread *td, u_char prio)
795 td->td_flags |= TDF_UBORROWING;
797 oldprio = td->td_user_pri;
798 td->td_user_pri = prio;
800 if (TD_ON_UPILOCK(td) && oldprio != prio)
801 umtx_pi_adjust(td, oldprio);
805 sched_unlend_user_prio(struct thread *td, u_char prio)
809 base_pri = td->td_base_user_pri;
810 if (prio >= base_pri) {
811 td->td_flags &= ~TDF_UBORROWING;
812 sched_user_prio(td, base_pri);
814 sched_lend_user_prio(td, prio);
818 sched_sleep(struct thread *td)
821 mtx_assert(&sched_lock, MA_OWNED);
826 sched_switch(struct thread *td, struct thread *newtd, int flags)
834 mtx_assert(&sched_lock, MA_OWNED);
836 if ((p->p_flag & P_NOLOAD) == 0)
840 * We are volunteering to switch out so we get to nominate
841 * a successor for the rest of our quantum
842 * First try another thread in our process
844 * this is too expensive to do without per process run queues
845 * so skip it for now.
846 * XXX keep this comment as a marker.
848 if (sched_followon &&
849 (p->p_flag & P_HADTHREADS) &&
856 newtd->td_flags |= (td->td_flags & TDF_NEEDRESCHED);
858 td->td_lastcpu = td->td_oncpu;
859 td->td_flags &= ~TDF_NEEDRESCHED;
860 td->td_owepreempt = 0;
861 td->td_oncpu = NOCPU;
863 * At the last moment, if this thread is still marked RUNNING,
864 * then put it back on the run queue as it has not been suspended
865 * or stopped or any thing else similar. We never put the idle
866 * threads on the run queue, however.
868 if (td->td_flags & TDF_IDLETD) {
871 idle_cpus_mask &= ~PCPU_GET(cpumask);
874 if (TD_IS_RUNNING(td)) {
875 /* Put us back on the run queue. */
876 sched_add(td, (flags & SW_PREEMPT) ?
877 SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
878 SRQ_OURSELF|SRQ_YIELDING);
883 * The thread we are about to run needs to be counted
884 * as if it had been added to the run queue and selected.
890 KASSERT((newtd->td_inhibitors == 0),
891 ("trying to run inhibited thread"));
892 newtd->td_sched->ts_flags |= TSF_DIDRUN;
893 TD_SET_RUNNING(newtd);
894 if ((newtd->td_proc->p_flag & P_NOLOAD) == 0)
897 newtd = choosethread();
902 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
903 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
907 cpu_switch(td, newtd);
909 * Where am I? What year is it?
910 * We are in the same thread that went to sleep above,
911 * but any amount of time may have passed. All out context
912 * will still be available as will local variables.
913 * PCPU values however may have changed as we may have
914 * changed CPU so don't trust cached values of them.
915 * New threads will go to fork_exit() instead of here
916 * so if you change things here you may need to change
918 * If the thread above was exiting it will never wake
919 * up again here, so either it has saved everything it
920 * needed to, or the thread_wait() or wait() will
924 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
925 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
930 if (td->td_flags & TDF_IDLETD)
931 idle_cpus_mask |= PCPU_GET(cpumask);
933 sched_lock.mtx_lock = (uintptr_t)td;
934 td->td_oncpu = PCPU_GET(cpuid);
938 sched_wakeup(struct thread *td)
940 mtx_assert(&sched_lock, MA_OWNED);
941 if (td->td_slptime > 1) {
946 sched_add(td, SRQ_BORING);
950 /* enable HTT_2 if you have a 2-way HTT cpu.*/
952 forward_wakeup(int cpunum)
954 cpumask_t map, me, dontuse;
959 mtx_assert(&sched_lock, MA_OWNED);
961 CTR0(KTR_RUNQ, "forward_wakeup()");
963 if ((!forward_wakeup_enabled) ||
964 (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
966 if (!smp_started || cold || panicstr)
969 forward_wakeups_requested++;
972 * check the idle mask we received against what we calculated before
973 * in the old version.
975 me = PCPU_GET(cpumask);
977 * don't bother if we should be doing it ourself..
979 if ((me & idle_cpus_mask) && (cpunum == NOCPU || me == (1 << cpunum)))
982 dontuse = me | stopped_cpus | hlt_cpus_mask;
984 if (forward_wakeup_use_loop) {
985 SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {
987 if ( (id & dontuse) == 0 &&
988 pc->pc_curthread == pc->pc_idlethread) {
994 if (forward_wakeup_use_mask) {
996 map = idle_cpus_mask & ~dontuse;
998 /* If they are both on, compare and use loop if different */
999 if (forward_wakeup_use_loop) {
1001 printf("map (%02X) != map3 (%02X)\n",
1009 /* If we only allow a specific CPU, then mask off all the others */
1010 if (cpunum != NOCPU) {
1011 KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
1012 map &= (1 << cpunum);
1014 /* Try choose an idle die. */
1015 if (forward_wakeup_use_htt) {
1016 map2 = (map & (map >> 1)) & 0x5555;
1022 /* set only one bit */
1023 if (forward_wakeup_use_single) {
1024 map = map & ((~map) + 1);
1028 forward_wakeups_delivered++;
1029 ipi_selected(map, IPI_AST);
1032 if (cpunum == NOCPU)
1033 printf("forward_wakeup: Idle processor not found\n");
1039 static void kick_other_cpu(int pri,int cpuid);
1042 kick_other_cpu(int pri,int cpuid)
1044 struct pcpu * pcpu = pcpu_find(cpuid);
1045 int cpri = pcpu->pc_curthread->td_priority;
1047 if (idle_cpus_mask & pcpu->pc_cpumask) {
1048 forward_wakeups_delivered++;
1049 ipi_selected(pcpu->pc_cpumask, IPI_AST);
1056 #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1057 #if !defined(FULL_PREEMPTION)
1058 if (pri <= PRI_MAX_ITHD)
1059 #endif /* ! FULL_PREEMPTION */
1061 ipi_selected(pcpu->pc_cpumask, IPI_PREEMPT);
1064 #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1066 pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
1067 ipi_selected( pcpu->pc_cpumask , IPI_AST);
1073 sched_add(struct thread *td, int flags)
1076 struct td_sched *ts;
1082 mtx_assert(&sched_lock, MA_OWNED);
1083 KASSERT((td->td_inhibitors == 0),
1084 ("sched_add: trying to run inhibited thread"));
1085 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1086 ("sched_add: bad thread state"));
1087 KASSERT(td->td_proc->p_sflag & PS_INMEM,
1088 ("sched_add: process swapped out"));
1089 CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
1090 td, td->td_proc->p_comm, td->td_priority, curthread,
1091 curthread->td_proc->p_comm);
1094 if (td->td_pinned != 0) {
1095 cpu = td->td_lastcpu;
1096 ts->ts_runq = &runq_pcpu[cpu];
1099 "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td, cpu);
1100 } else if ((ts)->ts_flags & TSF_BOUND) {
1101 /* Find CPU from bound runq */
1102 KASSERT(SKE_RUNQ_PCPU(ts),("sched_add: bound td_sched not on cpu runq"));
1103 cpu = ts->ts_runq - &runq_pcpu[0];
1106 "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td, cpu);
1109 "sched_add: adding td_sched:%p (td:%p) to gbl runq", ts, td);
1111 ts->ts_runq = &runq;
1114 if (single_cpu && (cpu != PCPU_GET(cpuid))) {
1115 kick_other_cpu(td->td_priority,cpu);
1119 cpumask_t me = PCPU_GET(cpumask);
1120 int idle = idle_cpus_mask & me;
1122 if (!idle && ((flags & SRQ_INTR) == 0) &&
1123 (idle_cpus_mask & ~(hlt_cpus_mask | me)))
1124 forwarded = forward_wakeup(cpu);
1128 if ((flags & SRQ_YIELDING) == 0 && maybe_preempt(td))
1135 if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1137 runq_add(ts->ts_runq, ts, flags);
1141 struct td_sched *ts;
1143 mtx_assert(&sched_lock, MA_OWNED);
1144 KASSERT((td->td_inhibitors == 0),
1145 ("sched_add: trying to run inhibited thread"));
1146 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1147 ("sched_add: bad thread state"));
1148 KASSERT(td->td_proc->p_sflag & PS_INMEM,
1149 ("sched_add: process swapped out"));
1150 CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
1151 td, td->td_proc->p_comm, td->td_priority, curthread,
1152 curthread->td_proc->p_comm);
1154 CTR2(KTR_RUNQ, "sched_add: adding td_sched:%p (td:%p) to runq", ts, td);
1155 ts->ts_runq = &runq;
1158 * If we are yielding (on the way out anyhow)
1159 * or the thread being saved is US,
1160 * then don't try be smart about preemption
1161 * or kicking off another CPU
1162 * as it won't help and may hinder.
1163 * In the YIEDLING case, we are about to run whoever is
1164 * being put in the queue anyhow, and in the
1165 * OURSELF case, we are puting ourself on the run queue
1166 * which also only happens when we are about to yield.
1168 if((flags & SRQ_YIELDING) == 0) {
1169 if (maybe_preempt(td))
1172 if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1174 runq_add(ts->ts_runq, ts, flags);
1180 sched_rem(struct thread *td)
1182 struct td_sched *ts;
1185 KASSERT(td->td_proc->p_sflag & PS_INMEM,
1186 ("sched_rem: process swapped out"));
1187 KASSERT(TD_ON_RUNQ(td),
1188 ("sched_rem: thread not on run queue"));
1189 mtx_assert(&sched_lock, MA_OWNED);
1190 CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
1191 td, td->td_proc->p_comm, td->td_priority, curthread,
1192 curthread->td_proc->p_comm);
1194 if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1196 runq_remove(ts->ts_runq, ts);
1201 * Select threads to run.
1202 * Notice that the running threads still consume a slot.
1207 struct td_sched *ts;
1211 struct td_sched *kecpu;
1214 ts = runq_choose(&runq);
1215 kecpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1219 kecpu->ts_thread->td_priority < ts->ts_thread->td_priority)) {
1220 CTR2(KTR_RUNQ, "choosing td_sched %p from pcpu runq %d", kecpu,
1223 rq = &runq_pcpu[PCPU_GET(cpuid)];
1225 CTR1(KTR_RUNQ, "choosing td_sched %p from main runq", ts);
1230 ts = runq_choose(&runq);
1234 runq_remove(rq, ts);
1235 ts->ts_flags |= TSF_DIDRUN;
1237 KASSERT(ts->ts_thread->td_proc->p_sflag & PS_INMEM,
1238 ("sched_choose: process swapped out"));
1239 return (ts->ts_thread);
1241 return (PCPU_GET(idlethread));
1245 sched_userret(struct thread *td)
1248 * XXX we cheat slightly on the locking here to avoid locking in
1249 * the usual case. Setting td_priority here is essentially an
1250 * incomplete workaround for not setting it properly elsewhere.
1251 * Now that some interrupt handlers are threads, not setting it
1252 * properly elsewhere can clobber it in the window between setting
1253 * it here and returning to user mode, so don't waste time setting
1254 * it perfectly here.
1256 KASSERT((td->td_flags & TDF_BORROWING) == 0,
1257 ("thread with borrowed priority returning to userland"));
1258 if (td->td_priority != td->td_user_pri) {
1259 mtx_lock_spin(&sched_lock);
1260 td->td_priority = td->td_user_pri;
1261 td->td_base_pri = td->td_user_pri;
1262 mtx_unlock_spin(&sched_lock);
1267 sched_bind(struct thread *td, int cpu)
1269 struct td_sched *ts;
1271 mtx_assert(&sched_lock, MA_OWNED);
1272 KASSERT(TD_IS_RUNNING(td),
1273 ("sched_bind: cannot bind non-running thread"));
1277 ts->ts_flags |= TSF_BOUND;
1279 ts->ts_runq = &runq_pcpu[cpu];
1280 if (PCPU_GET(cpuid) == cpu)
1283 mi_switch(SW_VOL, NULL);
1288 sched_unbind(struct thread* td)
1290 mtx_assert(&sched_lock, MA_OWNED);
1291 td->td_sched->ts_flags &= ~TSF_BOUND;
1295 sched_is_bound(struct thread *td)
1297 mtx_assert(&sched_lock, MA_OWNED);
1298 return (td->td_sched->ts_flags & TSF_BOUND);
1302 sched_relinquish(struct thread *td)
1304 mtx_lock_spin(&sched_lock);
1305 if (td->td_pri_class == PRI_TIMESHARE)
1306 sched_prio(td, PRI_MAX_TIMESHARE);
1307 mi_switch(SW_VOL, NULL);
1308 mtx_unlock_spin(&sched_lock);
1314 return (sched_tdcnt);
1318 sched_sizeof_proc(void)
1320 return (sizeof(struct proc));
1324 sched_sizeof_thread(void)
1326 return (sizeof(struct thread) + sizeof(struct td_sched));
1330 sched_pctcpu(struct thread *td)
1332 struct td_sched *ts;
1335 return (ts->ts_pctcpu);
1344 * The actual idle process.
1347 sched_idletd(void *dummy)
1355 mtx_assert(&Giant, MA_NOTOWNED);
1357 while (sched_runnable() == 0)
1360 mtx_lock_spin(&sched_lock);
1361 mi_switch(SW_VOL, NULL);
1362 mtx_unlock_spin(&sched_lock);
1366 #define KERN_SWITCH_INCLUDE 1
1367 #include "kern/kern_switch.c"