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"
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/kernel.h>
47 #include <sys/kthread.h>
48 #include <sys/mutex.h>
50 #include <sys/resourcevar.h>
51 #include <sys/sched.h>
53 #include <sys/sysctl.h>
55 #include <sys/turnstile.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 can be given a context to run.
78 * A process may have several of these. Probably one per processor
79 * but posibly a few more. In this universe they are grouped
80 * with a KSEG that contains the priority and niceness
84 TAILQ_ENTRY(kse) ke_procq; /* (j/z) Run queue. */
85 struct thread *ke_thread; /* (*) Active associated thread. */
86 fixpt_t ke_pctcpu; /* (j) %cpu during p_swtime. */
87 char ke_rqindex; /* (j) Run queue index. */
89 KES_THREAD = 0x0, /* slaved to thread state */
91 } ke_state; /* (j) KSE status. */
92 int ke_cpticks; /* (j) Ticks of cpu time. */
93 struct runq *ke_runq; /* runq the kse is currently on */
96 #define ke_proc ke_thread->td_proc
97 #define ke_ksegrp ke_thread->td_ksegrp
99 #define td_kse td_sched
101 /* flags kept in td_flags */
102 #define TDF_DIDRUN TDF_SCHED0 /* KSE actually ran. */
103 #define TDF_EXIT TDF_SCHED1 /* KSE is being killed. */
104 #define TDF_BOUND TDF_SCHED2
106 #define ke_flags ke_thread->td_flags
107 #define KEF_DIDRUN TDF_DIDRUN /* KSE actually ran. */
108 #define KEF_EXIT TDF_EXIT /* KSE is being killed. */
109 #define KEF_BOUND TDF_BOUND /* stuck to one CPU */
111 #define SKE_RUNQ_PCPU(ke) \
112 ((ke)->ke_runq != 0 && (ke)->ke_runq != &runq)
115 struct thread *skg_last_assigned; /* (j) Last thread assigned to */
116 /* the system scheduler. */
117 int skg_avail_opennings; /* (j) Num KSEs requested in group. */
118 int skg_concurrency; /* (j) Num KSEs requested in group. */
120 #define kg_last_assigned kg_sched->skg_last_assigned
121 #define kg_avail_opennings kg_sched->skg_avail_opennings
122 #define kg_concurrency kg_sched->skg_concurrency
124 #define SLOT_RELEASE(kg) \
126 kg->kg_avail_opennings++; \
127 CTR3(KTR_RUNQ, "kg %p(%d) Slot released (->%d)", \
129 kg->kg_concurrency, \
130 kg->kg_avail_opennings); \
131 /* KASSERT((kg->kg_avail_opennings <= kg->kg_concurrency), \
132 ("slots out of whack"));*/ \
135 #define SLOT_USE(kg) \
137 kg->kg_avail_opennings--; \
138 CTR3(KTR_RUNQ, "kg %p(%d) Slot used (->%d)", \
140 kg->kg_concurrency, \
141 kg->kg_avail_opennings); \
142 /* KASSERT((kg->kg_avail_opennings >= 0), \
143 ("slots out of whack"));*/ \
147 * KSE_CAN_MIGRATE macro returns true if the kse can migrate between
150 #define KSE_CAN_MIGRATE(ke) \
151 ((ke)->ke_thread->td_pinned == 0 && ((ke)->ke_flags & KEF_BOUND) == 0)
153 static struct kse kse0;
154 static struct kg_sched kg_sched0;
156 static int sched_tdcnt; /* Total runnable threads in the system. */
157 static int sched_quantum; /* Roundrobin scheduling quantum in ticks. */
158 #define SCHED_QUANTUM (hz / 10) /* Default sched quantum */
160 static struct callout roundrobin_callout;
162 static void slot_fill(struct ksegrp *kg);
163 static struct kse *sched_choose(void); /* XXX Should be thread * */
165 static void setup_runqs(void);
166 static void roundrobin(void *arg);
167 static void schedcpu(void);
168 static void schedcpu_thread(void);
169 static void sched_priority(struct thread *td, u_char prio);
170 static void sched_setup(void *dummy);
171 static void maybe_resched(struct thread *td);
172 static void updatepri(struct ksegrp *kg);
173 static void resetpriority(struct ksegrp *kg);
174 static void resetpriority_thread(struct thread *td, struct ksegrp *kg);
176 static int forward_wakeup(int cpunum);
179 static struct kproc_desc sched_kp = {
184 SYSINIT(schedcpu, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, kproc_start, &sched_kp)
185 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
190 static struct runq runq;
196 static struct runq runq_pcpu[MAXCPU];
205 for (i = 0; i < MAXCPU; ++i)
206 runq_init(&runq_pcpu[i]);
213 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
217 new_val = sched_quantum * tick;
218 error = sysctl_handle_int(oidp, &new_val, 0, req);
219 if (error != 0 || req->newptr == NULL)
223 sched_quantum = new_val / tick;
224 hogticks = 2 * sched_quantum;
228 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "Scheduler");
230 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
233 SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
234 0, sizeof sched_quantum, sysctl_kern_quantum, "I",
235 "Roundrobin scheduling quantum in microseconds");
238 /* Enable forwarding of wakeups to all other cpus */
239 SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup, CTLFLAG_RD, NULL, "Kernel SMP");
241 static int forward_wakeup_enabled = 1;
242 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
243 &forward_wakeup_enabled, 0,
244 "Forwarding of wakeup to idle CPUs");
246 static int forward_wakeups_requested = 0;
247 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
248 &forward_wakeups_requested, 0,
249 "Requests for Forwarding of wakeup to idle CPUs");
251 static int forward_wakeups_delivered = 0;
252 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
253 &forward_wakeups_delivered, 0,
254 "Completed Forwarding of wakeup to idle CPUs");
256 static int forward_wakeup_use_mask = 1;
257 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
258 &forward_wakeup_use_mask, 0,
259 "Use the mask of idle cpus");
261 static int forward_wakeup_use_loop = 0;
262 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
263 &forward_wakeup_use_loop, 0,
264 "Use a loop to find idle cpus");
266 static int forward_wakeup_use_single = 0;
267 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, onecpu, CTLFLAG_RW,
268 &forward_wakeup_use_single, 0,
269 "Only signal one idle cpu");
271 static int forward_wakeup_use_htt = 0;
272 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, htt2, CTLFLAG_RW,
273 &forward_wakeup_use_htt, 0,
277 static int sched_followon = 0;
278 SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
280 "allow threads to share a quantum");
282 static int sched_pfollowons = 0;
283 SYSCTL_INT(_kern_sched, OID_AUTO, pfollowons, CTLFLAG_RD,
284 &sched_pfollowons, 0,
285 "number of followons done to a different ksegrp");
287 static int sched_kgfollowons = 0;
288 SYSCTL_INT(_kern_sched, OID_AUTO, kgfollowons, CTLFLAG_RD,
289 &sched_kgfollowons, 0,
290 "number of followons done in a ksegrp");
296 CTR1(KTR_SCHED, "global load: %d", sched_tdcnt);
303 CTR1(KTR_SCHED, "global load: %d", sched_tdcnt);
306 * Arrange to reschedule if necessary, taking the priorities and
307 * schedulers into account.
310 maybe_resched(struct thread *td)
313 mtx_assert(&sched_lock, MA_OWNED);
314 if (td->td_priority < curthread->td_priority)
315 curthread->td_flags |= TDF_NEEDRESCHED;
319 * Force switch among equal priority processes every 100ms.
320 * We don't actually need to force a context switch of the current process.
321 * The act of firing the event triggers a context switch to softclock() and
322 * then switching back out again which is equivalent to a preemption, thus
323 * no further work is needed on the local CPU.
327 roundrobin(void *arg)
331 mtx_lock_spin(&sched_lock);
332 forward_roundrobin();
333 mtx_unlock_spin(&sched_lock);
336 callout_reset(&roundrobin_callout, sched_quantum, roundrobin, NULL);
340 * Constants for digital decay and forget:
341 * 90% of (kg_estcpu) usage in 5 * loadav time
342 * 95% of (ke_pctcpu) usage in 60 seconds (load insensitive)
343 * Note that, as ps(1) mentions, this can let percentages
344 * total over 100% (I've seen 137.9% for 3 processes).
346 * Note that schedclock() updates kg_estcpu and p_cpticks asynchronously.
348 * We wish to decay away 90% of kg_estcpu in (5 * loadavg) seconds.
349 * That is, the system wants to compute a value of decay such
350 * that the following for loop:
351 * for (i = 0; i < (5 * loadavg); i++)
352 * kg_estcpu *= decay;
355 * for all values of loadavg:
357 * Mathematically this loop can be expressed by saying:
358 * decay ** (5 * loadavg) ~= .1
360 * The system computes decay as:
361 * decay = (2 * loadavg) / (2 * loadavg + 1)
363 * We wish to prove that the system's computation of decay
364 * will always fulfill the equation:
365 * decay ** (5 * loadavg) ~= .1
367 * If we compute b as:
370 * decay = b / (b + 1)
372 * We now need to prove two things:
373 * 1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
374 * 2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
377 * For x close to zero, exp(x) =~ 1 + x, since
378 * exp(x) = 0! + x**1/1! + x**2/2! + ... .
379 * therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
380 * For x close to zero, ln(1+x) =~ x, since
381 * ln(1+x) = x - x**2/2 + x**3/3 - ... -1 < x < 1
382 * therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
386 * Solve (factor)**(power) =~ .1 given power (5*loadav):
387 * solving for factor,
388 * ln(factor) =~ (-2.30/5*loadav), or
389 * factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
390 * exp(-1/b) =~ (b-1)/b =~ b/(b+1). QED
393 * Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
395 * power*ln(b/(b+1)) =~ -2.30, or
396 * power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav. QED
398 * Actual power values for the implemented algorithm are as follows:
400 * power: 5.68 10.32 14.94 19.55
403 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
404 #define loadfactor(loadav) (2 * (loadav))
405 #define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
407 /* decay 95% of `ke_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
408 static fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
409 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
412 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
413 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
414 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
416 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
417 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
419 * If you don't want to bother with the faster/more-accurate formula, you
420 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
421 * (more general) method of calculating the %age of CPU used by a process.
423 #define CCPU_SHIFT 11
426 * Recompute process priorities, every hz ticks.
427 * MP-safe, called without the Giant mutex.
433 register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
438 int awake, realstathz;
440 realstathz = stathz ? stathz : hz;
441 sx_slock(&allproc_lock);
442 FOREACH_PROC_IN_SYSTEM(p) {
444 * Prevent state changes and protect run queue.
446 mtx_lock_spin(&sched_lock);
448 * Increment time in/out of memory. We ignore overflow; with
449 * 16-bit int's (remember them?) overflow takes 45 days.
452 FOREACH_KSEGRP_IN_PROC(p, kg) {
454 FOREACH_THREAD_IN_GROUP(kg, td) {
457 * Increment sleep time (if sleeping). We
458 * ignore overflow, as above.
461 * The kse slptimes are not touched in wakeup
462 * because the thread may not HAVE a KSE.
464 if (ke->ke_state == KES_ONRUNQ) {
466 ke->ke_flags &= ~KEF_DIDRUN;
467 } else if ((ke->ke_state == KES_THREAD) &&
468 (TD_IS_RUNNING(td))) {
470 /* Do not clear KEF_DIDRUN */
471 } else if (ke->ke_flags & KEF_DIDRUN) {
473 ke->ke_flags &= ~KEF_DIDRUN;
477 * ke_pctcpu is only for ps and ttyinfo().
478 * Do it per kse, and add them up at the end?
481 ke->ke_pctcpu = (ke->ke_pctcpu * ccpu) >>
484 * If the kse has been idle the entire second,
485 * stop recalculating its priority until
488 if (ke->ke_cpticks == 0)
490 #if (FSHIFT >= CCPU_SHIFT)
491 ke->ke_pctcpu += (realstathz == 100)
492 ? ((fixpt_t) ke->ke_cpticks) <<
493 (FSHIFT - CCPU_SHIFT) :
494 100 * (((fixpt_t) ke->ke_cpticks)
495 << (FSHIFT - CCPU_SHIFT)) / realstathz;
497 ke->ke_pctcpu += ((FSCALE - ccpu) *
499 FSCALE / realstathz)) >> FSHIFT;
502 } /* end of kse loop */
504 * If there are ANY running threads in this KSEGRP,
505 * then don't count it as sleeping.
508 if (kg->kg_slptime > 1) {
510 * In an ideal world, this should not
511 * happen, because whoever woke us
512 * up from the long sleep should have
513 * unwound the slptime and reset our
514 * priority before we run at the stale
515 * priority. Should KASSERT at some
516 * point when all the cases are fixed.
523 if (kg->kg_slptime > 1)
525 kg->kg_estcpu = decay_cpu(loadfac, kg->kg_estcpu);
527 FOREACH_THREAD_IN_GROUP(kg, td) {
528 resetpriority_thread(td, kg);
530 } /* end of ksegrp loop */
531 mtx_unlock_spin(&sched_lock);
532 } /* end of process loop */
533 sx_sunlock(&allproc_lock);
537 * Main loop for a kthread that executes schedcpu once a second.
540 schedcpu_thread(void)
546 tsleep(&nowake, curthread->td_priority, "-", hz);
551 * Recalculate the priority of a process after it has slept for a while.
552 * For all load averages >= 1 and max kg_estcpu of 255, sleeping for at
553 * least six times the loadfactor will decay kg_estcpu to zero.
556 updatepri(struct ksegrp *kg)
558 register fixpt_t loadfac;
559 register unsigned int newcpu;
561 loadfac = loadfactor(averunnable.ldavg[0]);
562 if (kg->kg_slptime > 5 * loadfac)
565 newcpu = kg->kg_estcpu;
566 kg->kg_slptime--; /* was incremented in schedcpu() */
567 while (newcpu && --kg->kg_slptime)
568 newcpu = decay_cpu(loadfac, newcpu);
569 kg->kg_estcpu = newcpu;
574 * Compute the priority of a process when running in user mode.
575 * Arrange to reschedule if the resulting priority is better
576 * than that of the current process.
579 resetpriority(struct ksegrp *kg)
581 register unsigned int newpriority;
583 if (kg->kg_pri_class == PRI_TIMESHARE) {
584 newpriority = PUSER + kg->kg_estcpu / INVERSE_ESTCPU_WEIGHT +
585 NICE_WEIGHT * (kg->kg_proc->p_nice - PRIO_MIN);
586 newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
588 kg->kg_user_pri = newpriority;
593 * Update the thread's priority when the associated ksegroup's user
597 resetpriority_thread(struct thread *td, struct ksegrp *kg)
600 /* Only change threads with a time sharing user priority. */
601 if (td->td_priority < PRI_MIN_TIMESHARE ||
602 td->td_priority > PRI_MAX_TIMESHARE)
605 /* XXX the whole needresched thing is broken, but not silly. */
608 sched_prio(td, kg->kg_user_pri);
613 sched_setup(void *dummy)
617 if (sched_quantum == 0)
618 sched_quantum = SCHED_QUANTUM;
619 hogticks = 2 * sched_quantum;
621 callout_init(&roundrobin_callout, CALLOUT_MPSAFE);
623 /* Kick off timeout driven events by calling first time. */
626 /* Account for thread0. */
630 /* External interfaces start here */
632 * Very early in the boot some setup of scheduler-specific
633 * parts of proc0 and of some scheduler resources needs to be done.
641 * Set up the scheduler specific parts of proc0.
643 proc0.p_sched = NULL; /* XXX */
644 ksegrp0.kg_sched = &kg_sched0;
645 thread0.td_sched = &kse0;
646 kse0.ke_thread = &thread0;
647 kse0.ke_state = KES_THREAD;
648 kg_sched0.skg_concurrency = 1;
649 kg_sched0.skg_avail_opennings = 0; /* we are already running */
656 return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
658 return runq_check(&runq);
663 sched_rr_interval(void)
665 if (sched_quantum == 0)
666 sched_quantum = SCHED_QUANTUM;
667 return (sched_quantum);
671 * We adjust the priority of the current process. The priority of
672 * a process gets worse as it accumulates CPU time. The cpu usage
673 * estimator (kg_estcpu) is increased here. resetpriority() will
674 * compute a different priority each time kg_estcpu increases by
675 * INVERSE_ESTCPU_WEIGHT
676 * (until MAXPRI is reached). The cpu usage estimator ramps up
677 * quite quickly when the process is running (linearly), and decays
678 * away exponentially, at a rate which is proportionally slower when
679 * the system is busy. The basic principle is that the system will
680 * 90% forget that the process used a lot of CPU time in 5 * loadav
681 * seconds. This causes the system to favor processes which haven't
682 * run much recently, and to round-robin among other processes.
685 sched_clock(struct thread *td)
690 mtx_assert(&sched_lock, MA_OWNED);
695 kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + 1);
696 if ((kg->kg_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
698 resetpriority_thread(td, kg);
703 * charge childs scheduling cpu usage to parent.
705 * XXXKSE assume only one thread & kse & ksegrp keep estcpu in each ksegrp.
706 * Charge it to the ksegrp that did the wait since process estcpu is sum of
707 * all ksegrps, this is strictly as expected. Assume that the child process
708 * aggregated all the estcpu into the 'built-in' ksegrp.
711 sched_exit(struct proc *p, struct thread *td)
713 sched_exit_ksegrp(FIRST_KSEGRP_IN_PROC(p), td);
714 sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
718 sched_exit_ksegrp(struct ksegrp *kg, struct thread *childtd)
721 mtx_assert(&sched_lock, MA_OWNED);
722 kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + childtd->td_ksegrp->kg_estcpu);
726 sched_exit_thread(struct thread *td, struct thread *child)
728 CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
729 child, child->td_proc->p_comm, child->td_priority);
730 if ((child->td_proc->p_flag & P_NOLOAD) == 0)
735 sched_fork(struct thread *td, struct thread *childtd)
737 sched_fork_ksegrp(td, childtd->td_ksegrp);
738 sched_fork_thread(td, childtd);
742 sched_fork_ksegrp(struct thread *td, struct ksegrp *child)
744 mtx_assert(&sched_lock, MA_OWNED);
745 child->kg_estcpu = td->td_ksegrp->kg_estcpu;
749 sched_fork_thread(struct thread *td, struct thread *childtd)
751 sched_newthread(childtd);
755 sched_nice(struct proc *p, int nice)
760 PROC_LOCK_ASSERT(p, MA_OWNED);
761 mtx_assert(&sched_lock, MA_OWNED);
763 FOREACH_KSEGRP_IN_PROC(p, kg) {
765 FOREACH_THREAD_IN_GROUP(kg, td) {
766 resetpriority_thread(td, kg);
772 sched_class(struct ksegrp *kg, int class)
774 mtx_assert(&sched_lock, MA_OWNED);
775 kg->kg_pri_class = class;
779 * Adjust the priority of a thread.
780 * This may include moving the thread within the KSEGRP,
781 * changing the assignment of a kse to the thread,
782 * and moving a KSE in the system run queue.
785 sched_priority(struct thread *td, u_char prio)
787 CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
788 td, td->td_proc->p_comm, td->td_priority, prio, curthread,
789 curthread->td_proc->p_comm);
791 mtx_assert(&sched_lock, MA_OWNED);
792 if (td->td_priority == prio)
794 if (TD_ON_RUNQ(td)) {
795 adjustrunqueue(td, prio);
797 td->td_priority = prio;
802 * Update a thread's priority when it is lent another thread's
806 sched_lend_prio(struct thread *td, u_char prio)
809 td->td_flags |= TDF_BORROWING;
810 sched_priority(td, prio);
814 * Restore a thread's priority when priority propagation is
815 * over. The prio argument is the minimum priority the thread
816 * needs to have to satisfy other possible priority lending
817 * requests. If the thread's regulary priority is less
818 * important than prio the thread will keep a priority boost
822 sched_unlend_prio(struct thread *td, u_char prio)
826 if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
827 td->td_base_pri <= PRI_MAX_TIMESHARE)
828 base_pri = td->td_ksegrp->kg_user_pri;
830 base_pri = td->td_base_pri;
831 if (prio >= base_pri) {
832 td->td_flags &= ~TDF_BORROWING;
833 sched_prio(td, base_pri);
835 sched_lend_prio(td, prio);
839 sched_prio(struct thread *td, u_char prio)
843 /* First, update the base priority. */
844 td->td_base_pri = prio;
847 * If the thread is borrowing another thread's priority, don't ever
848 * lower the priority.
850 if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
853 /* Change the real priority. */
854 oldprio = td->td_priority;
855 sched_priority(td, prio);
858 * If the thread is on a turnstile, then let the turnstile update
861 if (TD_ON_LOCK(td) && oldprio != prio)
862 turnstile_adjust(td, oldprio);
866 sched_sleep(struct thread *td)
869 mtx_assert(&sched_lock, MA_OWNED);
870 td->td_ksegrp->kg_slptime = 0;
873 static void remrunqueue(struct thread *td);
876 sched_switch(struct thread *td, struct thread *newtd, int flags)
885 mtx_assert(&sched_lock, MA_OWNED);
887 if ((p->p_flag & P_NOLOAD) == 0)
890 * We are volunteering to switch out so we get to nominate
891 * a successor for the rest of our quantum
892 * First try another thread in our ksegrp, and then look for
893 * other ksegrps in our process.
895 if (sched_followon &&
896 (p->p_flag & P_HADTHREADS) &&
899 /* lets schedule another thread from this process */
901 if ((newtd = TAILQ_FIRST(&kg->kg_runq))) {
905 FOREACH_KSEGRP_IN_PROC(p, kg) {
906 if ((newtd = TAILQ_FIRST(&kg->kg_runq))) {
916 newtd->td_flags |= (td->td_flags & TDF_NEEDRESCHED);
918 td->td_lastcpu = td->td_oncpu;
919 td->td_flags &= ~TDF_NEEDRESCHED;
920 td->td_owepreempt = 0;
921 td->td_oncpu = NOCPU;
923 * At the last moment, if this thread is still marked RUNNING,
924 * then put it back on the run queue as it has not been suspended
925 * or stopped or any thing else similar. We never put the idle
926 * threads on the run queue, however.
928 if (td == PCPU_GET(idlethread))
931 SLOT_RELEASE(td->td_ksegrp);
932 if (TD_IS_RUNNING(td)) {
933 /* Put us back on the run queue (kse and all). */
934 setrunqueue(td, (flags & SW_PREEMPT) ?
935 SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
936 SRQ_OURSELF|SRQ_YIELDING);
937 } else if (p->p_flag & P_HADTHREADS) {
939 * We will not be on the run queue. So we must be
940 * sleeping or similar. As it's available,
941 * someone else can use the KSE if they need it.
942 * It's NOT available if we are about to need it
944 if (newtd == NULL || newtd->td_ksegrp != td->td_ksegrp)
945 slot_fill(td->td_ksegrp);
950 * The thread we are about to run needs to be counted
951 * as if it had been added to the run queue and selected.
957 KASSERT((newtd->td_inhibitors == 0),
958 ("trying to run inhibitted thread"));
959 SLOT_USE(newtd->td_ksegrp);
960 newtd->td_kse->ke_flags |= KEF_DIDRUN;
961 TD_SET_RUNNING(newtd);
962 if ((newtd->td_proc->p_flag & P_NOLOAD) == 0)
965 newtd = choosethread();
970 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
971 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
973 cpu_switch(td, newtd);
975 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
976 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
980 sched_lock.mtx_lock = (uintptr_t)td;
981 td->td_oncpu = PCPU_GET(cpuid);
985 sched_wakeup(struct thread *td)
989 mtx_assert(&sched_lock, MA_OWNED);
991 if (kg->kg_slptime > 1) {
996 setrunqueue(td, SRQ_BORING);
1000 /* enable HTT_2 if you have a 2-way HTT cpu.*/
1002 forward_wakeup(int cpunum)
1004 cpumask_t map, me, dontuse;
1009 mtx_assert(&sched_lock, MA_OWNED);
1011 CTR0(KTR_RUNQ, "forward_wakeup()");
1013 if ((!forward_wakeup_enabled) ||
1014 (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
1016 if (!smp_started || cold || panicstr)
1019 forward_wakeups_requested++;
1022 * check the idle mask we received against what we calculated before
1023 * in the old version.
1025 me = PCPU_GET(cpumask);
1027 * don't bother if we should be doing it ourself..
1029 if ((me & idle_cpus_mask) && (cpunum == NOCPU || me == (1 << cpunum)))
1032 dontuse = me | stopped_cpus | hlt_cpus_mask;
1034 if (forward_wakeup_use_loop) {
1035 SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {
1036 id = pc->pc_cpumask;
1037 if ( (id & dontuse) == 0 &&
1038 pc->pc_curthread == pc->pc_idlethread) {
1044 if (forward_wakeup_use_mask) {
1046 map = idle_cpus_mask & ~dontuse;
1048 /* If they are both on, compare and use loop if different */
1049 if (forward_wakeup_use_loop) {
1051 printf("map (%02X) != map3 (%02X)\n",
1059 /* If we only allow a specific CPU, then mask off all the others */
1060 if (cpunum != NOCPU) {
1061 KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
1062 map &= (1 << cpunum);
1064 /* Try choose an idle die. */
1065 if (forward_wakeup_use_htt) {
1066 map2 = (map & (map >> 1)) & 0x5555;
1072 /* set only one bit */
1073 if (forward_wakeup_use_single) {
1074 map = map & ((~map) + 1);
1078 forward_wakeups_delivered++;
1079 ipi_selected(map, IPI_AST);
1082 if (cpunum == NOCPU)
1083 printf("forward_wakeup: Idle processor not found\n");
1089 static void kick_other_cpu(int pri,int cpuid);
1092 kick_other_cpu(int pri,int cpuid)
1094 struct pcpu * pcpu = pcpu_find(cpuid);
1095 int cpri = pcpu->pc_curthread->td_priority;
1097 if (idle_cpus_mask & pcpu->pc_cpumask) {
1098 forward_wakeups_delivered++;
1099 ipi_selected(pcpu->pc_cpumask, IPI_AST);
1106 #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1107 #if !defined(FULL_PREEMPTION)
1108 if (pri <= PRI_MAX_ITHD)
1109 #endif /* ! FULL_PREEMPTION */
1111 ipi_selected(pcpu->pc_cpumask, IPI_PREEMPT);
1114 #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1116 pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
1117 ipi_selected( pcpu->pc_cpumask , IPI_AST);
1123 sched_add(struct thread *td, int flags)
1132 mtx_assert(&sched_lock, MA_OWNED);
1133 KASSERT(ke->ke_state != KES_ONRUNQ,
1134 ("sched_add: kse %p (%s) already in run queue", ke,
1135 ke->ke_proc->p_comm));
1136 KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1137 ("sched_add: process swapped out"));
1138 CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
1139 td, td->td_proc->p_comm, td->td_priority, curthread,
1140 curthread->td_proc->p_comm);
1143 if (td->td_pinned != 0) {
1144 cpu = td->td_lastcpu;
1145 ke->ke_runq = &runq_pcpu[cpu];
1148 "sched_add: Put kse:%p(td:%p) on cpu%d runq", ke, td, cpu);
1149 } else if ((ke)->ke_flags & KEF_BOUND) {
1150 /* Find CPU from bound runq */
1151 KASSERT(SKE_RUNQ_PCPU(ke),("sched_add: bound kse not on cpu runq"));
1152 cpu = ke->ke_runq - &runq_pcpu[0];
1155 "sched_add: Put kse:%p(td:%p) on cpu%d runq", ke, td, cpu);
1158 "sched_add: adding kse:%p (td:%p) to gbl runq", ke, td);
1160 ke->ke_runq = &runq;
1163 if (single_cpu && (cpu != PCPU_GET(cpuid))) {
1164 kick_other_cpu(td->td_priority,cpu);
1168 cpumask_t me = PCPU_GET(cpumask);
1169 int idle = idle_cpus_mask & me;
1171 if (!idle && ((flags & SRQ_INTR) == 0) &&
1172 (idle_cpus_mask & ~(hlt_cpus_mask | me)))
1173 forwarded = forward_wakeup(cpu);
1177 if ((flags & SRQ_YIELDING) == 0 && maybe_preempt(td))
1184 if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1186 SLOT_USE(td->td_ksegrp);
1187 runq_add(ke->ke_runq, ke, flags);
1188 ke->ke_state = KES_ONRUNQ;
1194 mtx_assert(&sched_lock, MA_OWNED);
1195 KASSERT(ke->ke_state != KES_ONRUNQ,
1196 ("sched_add: kse %p (%s) already in run queue", ke,
1197 ke->ke_proc->p_comm));
1198 KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1199 ("sched_add: process swapped out"));
1200 CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
1201 td, td->td_proc->p_comm, td->td_priority, curthread,
1202 curthread->td_proc->p_comm);
1203 CTR2(KTR_RUNQ, "sched_add: adding kse:%p (td:%p) to runq", ke, td);
1204 ke->ke_runq = &runq;
1207 * If we are yielding (on the way out anyhow)
1208 * or the thread being saved is US,
1209 * then don't try be smart about preemption
1210 * or kicking off another CPU
1211 * as it won't help and may hinder.
1212 * In the YIEDLING case, we are about to run whoever is
1213 * being put in the queue anyhow, and in the
1214 * OURSELF case, we are puting ourself on the run queue
1215 * which also only happens when we are about to yield.
1217 if((flags & SRQ_YIELDING) == 0) {
1218 if (maybe_preempt(td))
1221 if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1223 SLOT_USE(td->td_ksegrp);
1224 runq_add(ke->ke_runq, ke, flags);
1225 ke->ke_state = KES_ONRUNQ;
1231 sched_rem(struct thread *td)
1236 KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1237 ("sched_rem: process swapped out"));
1238 KASSERT((ke->ke_state == KES_ONRUNQ),
1239 ("sched_rem: KSE not on run queue"));
1240 mtx_assert(&sched_lock, MA_OWNED);
1241 CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
1242 td, td->td_proc->p_comm, td->td_priority, curthread,
1243 curthread->td_proc->p_comm);
1245 if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1247 SLOT_RELEASE(td->td_ksegrp);
1248 runq_remove(ke->ke_runq, ke);
1250 ke->ke_state = KES_THREAD;
1254 * Select threads to run.
1255 * Notice that the running threads still consume a slot.
1267 ke = runq_choose(&runq);
1268 kecpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1272 kecpu->ke_thread->td_priority < ke->ke_thread->td_priority)) {
1273 CTR2(KTR_RUNQ, "choosing kse %p from pcpu runq %d", kecpu,
1276 rq = &runq_pcpu[PCPU_GET(cpuid)];
1278 CTR1(KTR_RUNQ, "choosing kse %p from main runq", ke);
1283 ke = runq_choose(&runq);
1287 runq_remove(rq, ke);
1288 ke->ke_state = KES_THREAD;
1290 KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1291 ("sched_choose: process swapped out"));
1297 sched_userret(struct thread *td)
1301 * XXX we cheat slightly on the locking here to avoid locking in
1302 * the usual case. Setting td_priority here is essentially an
1303 * incomplete workaround for not setting it properly elsewhere.
1304 * Now that some interrupt handlers are threads, not setting it
1305 * properly elsewhere can clobber it in the window between setting
1306 * it here and returning to user mode, so don't waste time setting
1307 * it perfectly here.
1309 KASSERT((td->td_flags & TDF_BORROWING) == 0,
1310 ("thread with borrowed priority returning to userland"));
1312 if (td->td_priority != kg->kg_user_pri) {
1313 mtx_lock_spin(&sched_lock);
1314 td->td_priority = kg->kg_user_pri;
1315 td->td_base_pri = kg->kg_user_pri;
1316 mtx_unlock_spin(&sched_lock);
1321 sched_bind(struct thread *td, int cpu)
1325 mtx_assert(&sched_lock, MA_OWNED);
1326 KASSERT(TD_IS_RUNNING(td),
1327 ("sched_bind: cannot bind non-running thread"));
1331 ke->ke_flags |= KEF_BOUND;
1333 ke->ke_runq = &runq_pcpu[cpu];
1334 if (PCPU_GET(cpuid) == cpu)
1337 ke->ke_state = KES_THREAD;
1339 mi_switch(SW_VOL, NULL);
1344 sched_unbind(struct thread* td)
1346 mtx_assert(&sched_lock, MA_OWNED);
1347 td->td_kse->ke_flags &= ~KEF_BOUND;
1351 sched_is_bound(struct thread *td)
1353 mtx_assert(&sched_lock, MA_OWNED);
1354 return (td->td_kse->ke_flags & KEF_BOUND);
1360 return (sched_tdcnt);
1364 sched_sizeof_ksegrp(void)
1366 return (sizeof(struct ksegrp) + sizeof(struct kg_sched));
1369 sched_sizeof_proc(void)
1371 return (sizeof(struct proc));
1374 sched_sizeof_thread(void)
1376 return (sizeof(struct thread) + sizeof(struct kse));
1380 sched_pctcpu(struct thread *td)
1385 return (ke->ke_pctcpu);
1389 #define KERN_SWITCH_INCLUDE 1
1390 #include "kern/kern_switch.c"