2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1982, 1986, 1990, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 #include <sys/cdefs.h>
38 #include "opt_hwpmc_hooks.h"
39 #include "opt_sched.h"
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/cpuset.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>
54 #include <sys/sysctl.h>
56 #include <sys/turnstile.h>
57 #include <sys/umtxvar.h>
58 #include <machine/pcb.h>
59 #include <machine/smp.h>
62 #include <sys/pmckern.h>
66 #include <sys/dtrace_bsd.h>
67 int __read_mostly 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.
91 * All fields are protected by the scheduler lock.
94 fixpt_t ts_pctcpu; /* %cpu during p_swtime. */
95 u_int ts_estcpu; /* Estimated cpu utilization. */
96 int ts_cpticks; /* Ticks of cpu time. */
97 int ts_slptime; /* Seconds !RUNNING. */
98 int ts_slice; /* Remaining part of time slice. */
100 struct runq *ts_runq; /* runq the thread is currently on */
102 char ts_name[TS_NAME_LEN];
106 /* flags kept in td_flags */
107 #define TDF_DIDRUN TDF_SCHED0 /* thread actually ran. */
108 #define TDF_BOUND TDF_SCHED1 /* Bound to one CPU. */
109 #define TDF_SLICEEND TDF_SCHED2 /* Thread time slice is over. */
111 /* flags kept in ts_flags */
112 #define TSF_AFFINITY 0x0001 /* Has a non-"full" CPU set. */
114 #define SKE_RUNQ_PCPU(ts) \
115 ((ts)->ts_runq != 0 && (ts)->ts_runq != &runq)
117 #define THREAD_CAN_SCHED(td, cpu) \
118 CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
120 _Static_assert(sizeof(struct thread) + sizeof(struct td_sched) <=
121 sizeof(struct thread0_storage),
122 "increase struct thread0_storage.t0st_sched size");
124 static struct mtx sched_lock;
126 static int realstathz = 127; /* stathz is sometimes 0 and run off of hz. */
127 static int sched_tdcnt; /* Total runnable threads in the system. */
128 static int sched_slice = 12; /* Thread run time before rescheduling. */
130 static void setup_runqs(void);
131 static void schedcpu(void);
132 static void schedcpu_thread(void);
133 static void sched_priority(struct thread *td, u_char prio);
134 static void sched_setup(void *dummy);
135 static void maybe_resched(struct thread *td);
136 static void updatepri(struct thread *td);
137 static void resetpriority(struct thread *td);
138 static void resetpriority_thread(struct thread *td);
140 static int sched_pickcpu(struct thread *td);
141 static int forward_wakeup(int cpunum);
142 static void kick_other_cpu(int pri, int cpuid);
145 static struct kproc_desc sched_kp = {
150 SYSINIT(schedcpu, SI_SUB_LAST, SI_ORDER_FIRST, kproc_start,
152 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
154 static void sched_initticks(void *dummy);
155 SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
161 static struct runq runq;
167 static struct runq runq_pcpu[MAXCPU];
168 long runq_length[MAXCPU];
170 static cpuset_t idle_cpus_mask;
173 struct pcpuidlestat {
177 DPCPU_DEFINE_STATIC(struct pcpuidlestat, idlestat);
185 for (i = 0; i < MAXCPU; ++i)
186 runq_init(&runq_pcpu[i]);
193 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
195 int error, new_val, period;
197 period = 1000000 / realstathz;
198 new_val = period * sched_slice;
199 error = sysctl_handle_int(oidp, &new_val, 0, req);
200 if (error != 0 || req->newptr == NULL)
204 sched_slice = imax(1, (new_val + period / 2) / period);
205 hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
210 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
213 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
215 SYSCTL_PROC(_kern_sched, OID_AUTO, quantum,
216 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
217 sysctl_kern_quantum, "I",
218 "Quantum for timeshare threads in microseconds");
219 SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
220 "Quantum for timeshare threads in stathz ticks");
222 /* Enable forwarding of wakeups to all other cpus */
223 static SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup,
224 CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
227 static int runq_fuzz = 1;
228 SYSCTL_INT(_kern_sched, OID_AUTO, runq_fuzz, CTLFLAG_RW, &runq_fuzz, 0, "");
230 static int forward_wakeup_enabled = 1;
231 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
232 &forward_wakeup_enabled, 0,
233 "Forwarding of wakeup to idle CPUs");
235 static int forward_wakeups_requested = 0;
236 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
237 &forward_wakeups_requested, 0,
238 "Requests for Forwarding of wakeup to idle CPUs");
240 static int forward_wakeups_delivered = 0;
241 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
242 &forward_wakeups_delivered, 0,
243 "Completed Forwarding of wakeup to idle CPUs");
245 static int forward_wakeup_use_mask = 1;
246 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
247 &forward_wakeup_use_mask, 0,
248 "Use the mask of idle cpus");
250 static int forward_wakeup_use_loop = 0;
251 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
252 &forward_wakeup_use_loop, 0,
253 "Use a loop to find idle cpus");
257 static int sched_followon = 0;
258 SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
260 "allow threads to share a quantum");
263 SDT_PROVIDER_DEFINE(sched);
265 SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
266 "struct proc *", "uint8_t");
267 SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
268 "struct proc *", "void *");
269 SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
270 "struct proc *", "void *", "int");
271 SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
272 "struct proc *", "uint8_t", "struct thread *");
273 SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
274 SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
276 SDT_PROBE_DEFINE(sched, , , on__cpu);
277 SDT_PROBE_DEFINE(sched, , , remain__cpu);
278 SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
286 KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
287 SDT_PROBE2(sched, , , load__change, NOCPU, sched_tdcnt);
295 KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
296 SDT_PROBE2(sched, , , load__change, NOCPU, sched_tdcnt);
299 * Arrange to reschedule if necessary, taking the priorities and
300 * schedulers into account.
303 maybe_resched(struct thread *td)
306 THREAD_LOCK_ASSERT(td, MA_OWNED);
307 if (td->td_priority < curthread->td_priority)
308 curthread->td_flags |= TDF_NEEDRESCHED;
312 * This function is called when a thread is about to be put on run queue
313 * because it has been made runnable or its priority has been adjusted. It
314 * determines if the new thread should preempt the current thread. If so,
315 * it sets td_owepreempt to request a preemption.
318 maybe_preempt(struct thread *td)
325 * The new thread should not preempt the current thread if any of the
326 * following conditions are true:
328 * - The kernel is in the throes of crashing (panicstr).
329 * - The current thread has a higher (numerically lower) or
330 * equivalent priority. Note that this prevents curthread from
331 * trying to preempt to itself.
332 * - The current thread has an inhibitor set or is in the process of
333 * exiting. In this case, the current thread is about to switch
334 * out anyways, so there's no point in preempting. If we did,
335 * the current thread would not be properly resumed as well, so
336 * just avoid that whole landmine.
337 * - If the new thread's priority is not a realtime priority and
338 * the current thread's priority is not an idle priority and
339 * FULL_PREEMPTION is disabled.
341 * If all of these conditions are false, but the current thread is in
342 * a nested critical section, then we have to defer the preemption
343 * until we exit the critical section. Otherwise, switch immediately
347 THREAD_LOCK_ASSERT(td, MA_OWNED);
348 KASSERT((td->td_inhibitors == 0),
349 ("maybe_preempt: trying to run inhibited thread"));
350 pri = td->td_priority;
351 cpri = ctd->td_priority;
352 if (KERNEL_PANICKED() || pri >= cpri /* || dumping */ ||
353 TD_IS_INHIBITED(ctd))
355 #ifndef FULL_PREEMPTION
356 if (pri > PRI_MAX_ITHD && cpri < PRI_MIN_IDLE)
360 CTR0(KTR_PROC, "maybe_preempt: scheduling preemption");
361 ctd->td_owepreempt = 1;
369 * Constants for digital decay and forget:
370 * 90% of (ts_estcpu) usage in 5 * loadav time
371 * 95% of (ts_pctcpu) usage in 60 seconds (load insensitive)
372 * Note that, as ps(1) mentions, this can let percentages
373 * total over 100% (I've seen 137.9% for 3 processes).
375 * Note that schedclock() updates ts_estcpu and p_cpticks asynchronously.
377 * We wish to decay away 90% of ts_estcpu in (5 * loadavg) seconds.
378 * That is, the system wants to compute a value of decay such
379 * that the following for loop:
380 * for (i = 0; i < (5 * loadavg); i++)
381 * ts_estcpu *= decay;
384 * for all values of loadavg:
386 * Mathematically this loop can be expressed by saying:
387 * decay ** (5 * loadavg) ~= .1
389 * The system computes decay as:
390 * decay = (2 * loadavg) / (2 * loadavg + 1)
392 * We wish to prove that the system's computation of decay
393 * will always fulfill the equation:
394 * decay ** (5 * loadavg) ~= .1
396 * If we compute b as:
399 * decay = b / (b + 1)
401 * We now need to prove two things:
402 * 1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
403 * 2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
406 * For x close to zero, exp(x) =~ 1 + x, since
407 * exp(x) = 0! + x**1/1! + x**2/2! + ... .
408 * therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
409 * For x close to zero, ln(1+x) =~ x, since
410 * ln(1+x) = x - x**2/2 + x**3/3 - ... -1 < x < 1
411 * therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
415 * Solve (factor)**(power) =~ .1 given power (5*loadav):
416 * solving for factor,
417 * ln(factor) =~ (-2.30/5*loadav), or
418 * factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
419 * exp(-1/b) =~ (b-1)/b =~ b/(b+1). QED
422 * Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
424 * power*ln(b/(b+1)) =~ -2.30, or
425 * power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav. QED
427 * Actual power values for the implemented algorithm are as follows:
429 * power: 5.68 10.32 14.94 19.55
432 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
433 #define loadfactor(loadav) (2 * (loadav))
434 #define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
436 /* decay 95% of `ts_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
437 static fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
438 SYSCTL_UINT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0,
439 "Decay factor used for updating %CPU");
442 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
443 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
444 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
446 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
447 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
449 * If you don't want to bother with the faster/more-accurate formula, you
450 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
451 * (more general) method of calculating the %age of CPU used by a process.
453 #define CCPU_SHIFT 11
456 * Recompute process priorities, every hz ticks.
457 * MP-safe, called without the Giant mutex.
463 fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
469 sx_slock(&allproc_lock);
470 FOREACH_PROC_IN_SYSTEM(p) {
472 if (p->p_state == PRS_NEW) {
476 FOREACH_THREAD_IN_PROC(p, td) {
478 ts = td_get_sched(td);
481 * Increment sleep time (if sleeping). We
482 * ignore overflow, as above.
485 * The td_sched slptimes are not touched in wakeup
486 * because the thread may not HAVE everything in
487 * memory? XXX I think this is out of date.
489 if (TD_ON_RUNQ(td)) {
491 td->td_flags &= ~TDF_DIDRUN;
492 } else if (TD_IS_RUNNING(td)) {
494 /* Do not clear TDF_DIDRUN */
495 } else if (td->td_flags & TDF_DIDRUN) {
497 td->td_flags &= ~TDF_DIDRUN;
501 * ts_pctcpu is only for ps and ttyinfo().
503 ts->ts_pctcpu = (ts->ts_pctcpu * ccpu) >> FSHIFT;
505 * If the td_sched has been idle the entire second,
506 * stop recalculating its priority until
509 if (ts->ts_cpticks != 0) {
510 #if (FSHIFT >= CCPU_SHIFT)
511 ts->ts_pctcpu += (realstathz == 100)
512 ? ((fixpt_t) ts->ts_cpticks) <<
513 (FSHIFT - CCPU_SHIFT) :
514 100 * (((fixpt_t) ts->ts_cpticks)
515 << (FSHIFT - CCPU_SHIFT)) / realstathz;
517 ts->ts_pctcpu += ((FSCALE - ccpu) *
519 FSCALE / realstathz)) >> FSHIFT;
524 * If there are ANY running threads in this process,
525 * then don't count it as sleeping.
526 * XXX: this is broken.
529 if (ts->ts_slptime > 1) {
531 * In an ideal world, this should not
532 * happen, because whoever woke us
533 * up from the long sleep should have
534 * unwound the slptime and reset our
535 * priority before we run at the stale
536 * priority. Should KASSERT at some
537 * point when all the cases are fixed.
544 if (ts->ts_slptime > 1) {
548 ts->ts_estcpu = decay_cpu(loadfac, ts->ts_estcpu);
550 resetpriority_thread(td);
555 sx_sunlock(&allproc_lock);
559 * Main loop for a kthread that executes schedcpu once a second.
562 schedcpu_thread(void)
572 * Recalculate the priority of a process after it has slept for a while.
573 * For all load averages >= 1 and max ts_estcpu of 255, sleeping for at
574 * least six times the loadfactor will decay ts_estcpu to zero.
577 updatepri(struct thread *td)
583 ts = td_get_sched(td);
584 loadfac = loadfactor(averunnable.ldavg[0]);
585 if (ts->ts_slptime > 5 * loadfac)
588 newcpu = ts->ts_estcpu;
589 ts->ts_slptime--; /* was incremented in schedcpu() */
590 while (newcpu && --ts->ts_slptime)
591 newcpu = decay_cpu(loadfac, newcpu);
592 ts->ts_estcpu = newcpu;
597 * Compute the priority of a process when running in user mode.
598 * Arrange to reschedule if the resulting priority is better
599 * than that of the current process.
602 resetpriority(struct thread *td)
606 if (td->td_pri_class != PRI_TIMESHARE)
608 newpriority = PUSER +
609 td_get_sched(td)->ts_estcpu / INVERSE_ESTCPU_WEIGHT +
610 NICE_WEIGHT * (td->td_proc->p_nice - PRIO_MIN);
611 newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
613 sched_user_prio(td, newpriority);
617 * Update the thread's priority when the associated process's user
621 resetpriority_thread(struct thread *td)
624 /* Only change threads with a time sharing user priority. */
625 if (td->td_priority < PRI_MIN_TIMESHARE ||
626 td->td_priority > PRI_MAX_TIMESHARE)
629 /* XXX the whole needresched thing is broken, but not silly. */
632 sched_prio(td, td->td_user_pri);
637 sched_setup(void *dummy)
642 /* Account for thread0. */
647 * This routine determines time constants after stathz and hz are setup.
650 sched_initticks(void *dummy)
653 realstathz = stathz ? stathz : hz;
654 sched_slice = realstathz / 10; /* ~100ms */
655 hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
659 /* External interfaces start here */
662 * Very early in the boot some setup of scheduler-specific
663 * parts of proc0 and of some scheduler resources needs to be done.
672 * Set up the scheduler specific parts of thread0.
674 thread0.td_lock = &sched_lock;
675 td_get_sched(&thread0)->ts_slice = sched_slice;
676 mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN);
683 /* Nothing needed. */
690 return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
692 return runq_check(&runq);
697 sched_rr_interval(void)
700 /* Convert sched_slice from stathz to hz. */
701 return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
705 * We adjust the priority of the current process. The priority of a
706 * process gets worse as it accumulates CPU time. The cpu usage
707 * estimator (ts_estcpu) is increased here. resetpriority() will
708 * compute a different priority each time ts_estcpu increases by
709 * INVERSE_ESTCPU_WEIGHT (until PRI_MAX_TIMESHARE is reached). The
710 * cpu usage estimator ramps up quite quickly when the process is
711 * running (linearly), and decays away exponentially, at a rate which
712 * is proportionally slower when the system is busy. The basic
713 * principle is that the system will 90% forget that the process used
714 * a lot of CPU time in 5 * loadav seconds. This causes the system to
715 * favor processes which haven't run much recently, and to round-robin
716 * among other processes.
719 sched_clock_tick(struct thread *td)
721 struct pcpuidlestat *stat;
724 THREAD_LOCK_ASSERT(td, MA_OWNED);
725 ts = td_get_sched(td);
728 ts->ts_estcpu = ESTCPULIM(ts->ts_estcpu + 1);
729 if ((ts->ts_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
731 resetpriority_thread(td);
735 * Force a context switch if the current thread has used up a full
736 * time slice (default is 100ms).
738 if (!TD_IS_IDLETHREAD(td) && --ts->ts_slice <= 0) {
739 ts->ts_slice = sched_slice;
740 td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
743 stat = DPCPU_PTR(idlestat);
744 stat->oldidlecalls = stat->idlecalls;
749 sched_clock(struct thread *td, int cnt)
752 for ( ; cnt > 0; cnt--)
753 sched_clock_tick(td);
757 * Charge child's scheduling CPU usage to parent.
760 sched_exit(struct proc *p, struct thread *td)
763 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "proc exit",
764 "prio:%d", td->td_priority);
766 PROC_LOCK_ASSERT(p, MA_OWNED);
767 sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
771 sched_exit_thread(struct thread *td, struct thread *child)
774 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "exit",
775 "prio:%d", child->td_priority);
777 td_get_sched(td)->ts_estcpu = ESTCPULIM(td_get_sched(td)->ts_estcpu +
778 td_get_sched(child)->ts_estcpu);
781 if ((child->td_flags & TDF_NOLOAD) == 0)
783 thread_unlock(child);
787 sched_fork(struct thread *td, struct thread *childtd)
789 sched_fork_thread(td, childtd);
793 sched_fork_thread(struct thread *td, struct thread *childtd)
795 struct td_sched *ts, *tsc;
797 childtd->td_oncpu = NOCPU;
798 childtd->td_lastcpu = NOCPU;
799 childtd->td_lock = &sched_lock;
800 childtd->td_cpuset = cpuset_ref(td->td_cpuset);
801 childtd->td_domain.dr_policy = td->td_cpuset->cs_domain;
802 childtd->td_priority = childtd->td_base_pri;
803 ts = td_get_sched(childtd);
804 bzero(ts, sizeof(*ts));
805 tsc = td_get_sched(td);
806 ts->ts_estcpu = tsc->ts_estcpu;
807 ts->ts_flags |= (tsc->ts_flags & TSF_AFFINITY);
812 sched_nice(struct proc *p, int nice)
816 PROC_LOCK_ASSERT(p, MA_OWNED);
818 FOREACH_THREAD_IN_PROC(p, td) {
821 resetpriority_thread(td);
827 sched_class(struct thread *td, int class)
829 THREAD_LOCK_ASSERT(td, MA_OWNED);
830 td->td_pri_class = class;
834 * Adjust the priority of a thread.
837 sched_priority(struct thread *td, u_char prio)
840 KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "priority change",
841 "prio:%d", td->td_priority, "new prio:%d", prio, KTR_ATTR_LINKED,
842 sched_tdname(curthread));
843 SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
844 if (td != curthread && prio > td->td_priority) {
845 KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
846 "lend prio", "prio:%d", td->td_priority, "new prio:%d",
847 prio, KTR_ATTR_LINKED, sched_tdname(td));
848 SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
851 THREAD_LOCK_ASSERT(td, MA_OWNED);
852 if (td->td_priority == prio)
854 td->td_priority = prio;
855 if (TD_ON_RUNQ(td) && td->td_rqindex != (prio / RQ_PPQ)) {
857 sched_add(td, SRQ_BORING | SRQ_HOLDTD);
862 * Update a thread's priority when it is lent another thread's
866 sched_lend_prio(struct thread *td, u_char prio)
869 td->td_flags |= TDF_BORROWING;
870 sched_priority(td, prio);
874 * Restore a thread's priority when priority propagation is
875 * over. The prio argument is the minimum priority the thread
876 * needs to have to satisfy other possible priority lending
877 * requests. If the thread's regulary priority is less
878 * important than prio the thread will keep a priority boost
882 sched_unlend_prio(struct thread *td, u_char prio)
886 if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
887 td->td_base_pri <= PRI_MAX_TIMESHARE)
888 base_pri = td->td_user_pri;
890 base_pri = td->td_base_pri;
891 if (prio >= base_pri) {
892 td->td_flags &= ~TDF_BORROWING;
893 sched_prio(td, base_pri);
895 sched_lend_prio(td, prio);
899 sched_prio(struct thread *td, u_char prio)
903 /* First, update the base priority. */
904 td->td_base_pri = prio;
907 * If the thread is borrowing another thread's priority, don't ever
908 * lower the priority.
910 if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
913 /* Change the real priority. */
914 oldprio = td->td_priority;
915 sched_priority(td, prio);
918 * If the thread is on a turnstile, then let the turnstile update
921 if (TD_ON_LOCK(td) && oldprio != prio)
922 turnstile_adjust(td, oldprio);
926 sched_user_prio(struct thread *td, u_char prio)
929 THREAD_LOCK_ASSERT(td, MA_OWNED);
930 td->td_base_user_pri = prio;
931 if (td->td_lend_user_pri <= prio)
933 td->td_user_pri = prio;
937 sched_lend_user_prio(struct thread *td, u_char prio)
940 THREAD_LOCK_ASSERT(td, MA_OWNED);
941 td->td_lend_user_pri = prio;
942 td->td_user_pri = min(prio, td->td_base_user_pri);
943 if (td->td_priority > td->td_user_pri)
944 sched_prio(td, td->td_user_pri);
945 else if (td->td_priority != td->td_user_pri)
946 td->td_flags |= TDF_NEEDRESCHED;
950 * Like the above but first check if there is anything to do.
953 sched_lend_user_prio_cond(struct thread *td, u_char prio)
956 if (td->td_lend_user_pri != prio)
958 if (td->td_user_pri != min(prio, td->td_base_user_pri))
960 if (td->td_priority != td->td_user_pri)
966 sched_lend_user_prio(td, prio);
971 sched_sleep(struct thread *td, int pri)
974 THREAD_LOCK_ASSERT(td, MA_OWNED);
975 td->td_slptick = ticks;
976 td_get_sched(td)->ts_slptime = 0;
977 if (pri != 0 && PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
979 if (TD_IS_SUSPENDED(td) || pri >= PSOCK)
980 td->td_flags |= TDF_CANSWAP;
984 sched_switch(struct thread *td, int flags)
986 struct thread *newtd;
993 ts = td_get_sched(td);
996 THREAD_LOCK_ASSERT(td, MA_OWNED);
998 td->td_lastcpu = td->td_oncpu;
999 preempted = (td->td_flags & TDF_SLICEEND) == 0 &&
1000 (flags & SW_PREEMPT) != 0;
1001 td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
1002 td->td_owepreempt = 0;
1003 td->td_oncpu = NOCPU;
1006 * At the last moment, if this thread is still marked RUNNING,
1007 * then put it back on the run queue as it has not been suspended
1008 * or stopped or any thing else similar. We never put the idle
1009 * threads on the run queue, however.
1011 if (td->td_flags & TDF_IDLETD) {
1014 CPU_CLR(PCPU_GET(cpuid), &idle_cpus_mask);
1017 if (TD_IS_RUNNING(td)) {
1018 /* Put us back on the run queue. */
1019 sched_add(td, preempted ?
1020 SRQ_HOLDTD|SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1021 SRQ_HOLDTD|SRQ_OURSELF|SRQ_YIELDING);
1026 * Switch to the sched lock to fix things up and pick
1027 * a new thread. Block the td_lock in order to avoid
1028 * breaking the critical path.
1030 if (td->td_lock != &sched_lock) {
1031 mtx_lock_spin(&sched_lock);
1032 tmtx = thread_lock_block(td);
1033 mtx_unlock_spin(tmtx);
1036 if ((td->td_flags & TDF_NOLOAD) == 0)
1039 newtd = choosethread();
1040 MPASS(newtd->td_lock == &sched_lock);
1042 #if (KTR_COMPILE & KTR_SCHED) != 0
1043 if (TD_IS_IDLETHREAD(td))
1044 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle",
1045 "prio:%d", td->td_priority);
1047 KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td),
1048 "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg,
1049 "lockname:\"%s\"", td->td_lockname);
1054 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1055 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1058 SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
1061 lock_profile_release_lock(&sched_lock.lock_object, true);
1062 #ifdef KDTRACE_HOOKS
1064 * If DTrace has set the active vtime enum to anything
1065 * other than INACTIVE (0), then it should have set the
1068 if (dtrace_vtime_active)
1069 (*dtrace_vtime_switch_func)(newtd);
1072 cpu_switch(td, newtd, tmtx);
1073 lock_profile_obtain_lock_success(&sched_lock.lock_object, true,
1074 0, 0, __FILE__, __LINE__);
1076 * Where am I? What year is it?
1077 * We are in the same thread that went to sleep above,
1078 * but any amount of time may have passed. All our context
1079 * will still be available as will local variables.
1080 * PCPU values however may have changed as we may have
1081 * changed CPU so don't trust cached values of them.
1082 * New threads will go to fork_exit() instead of here
1083 * so if you change things here you may need to change
1086 * If the thread above was exiting it will never wake
1087 * up again here, so either it has saved everything it
1088 * needed to, or the thread_wait() or wait() will
1092 SDT_PROBE0(sched, , , on__cpu);
1094 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1095 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1098 td->td_lock = &sched_lock;
1099 SDT_PROBE0(sched, , , remain__cpu);
1102 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
1103 "prio:%d", td->td_priority);
1106 if (td->td_flags & TDF_IDLETD)
1107 CPU_SET(PCPU_GET(cpuid), &idle_cpus_mask);
1109 sched_lock.mtx_lock = (uintptr_t)td;
1110 td->td_oncpu = PCPU_GET(cpuid);
1112 mtx_unlock_spin(&sched_lock);
1116 sched_wakeup(struct thread *td, int srqflags)
1118 struct td_sched *ts;
1120 THREAD_LOCK_ASSERT(td, MA_OWNED);
1121 ts = td_get_sched(td);
1122 td->td_flags &= ~TDF_CANSWAP;
1123 if (ts->ts_slptime > 1) {
1129 ts->ts_slice = sched_slice;
1130 sched_add(td, srqflags);
1135 forward_wakeup(int cpunum)
1138 cpuset_t dontuse, map, map2;
1142 mtx_assert(&sched_lock, MA_OWNED);
1144 CTR0(KTR_RUNQ, "forward_wakeup()");
1146 if ((!forward_wakeup_enabled) ||
1147 (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
1149 if (!smp_started || KERNEL_PANICKED())
1152 forward_wakeups_requested++;
1155 * Check the idle mask we received against what we calculated
1156 * before in the old version.
1158 me = PCPU_GET(cpuid);
1160 /* Don't bother if we should be doing it ourself. */
1161 if (CPU_ISSET(me, &idle_cpus_mask) &&
1162 (cpunum == NOCPU || me == cpunum))
1165 CPU_SETOF(me, &dontuse);
1166 CPU_OR(&dontuse, &dontuse, &stopped_cpus);
1167 CPU_OR(&dontuse, &dontuse, &hlt_cpus_mask);
1169 if (forward_wakeup_use_loop) {
1170 STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1172 if (!CPU_ISSET(id, &dontuse) &&
1173 pc->pc_curthread == pc->pc_idlethread) {
1179 if (forward_wakeup_use_mask) {
1180 map = idle_cpus_mask;
1181 CPU_ANDNOT(&map, &map, &dontuse);
1183 /* If they are both on, compare and use loop if different. */
1184 if (forward_wakeup_use_loop) {
1185 if (CPU_CMP(&map, &map2)) {
1186 printf("map != map2, loop method preferred\n");
1194 /* If we only allow a specific CPU, then mask off all the others. */
1195 if (cpunum != NOCPU) {
1196 KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
1197 iscpuset = CPU_ISSET(cpunum, &map);
1201 CPU_SETOF(cpunum, &map);
1203 if (!CPU_EMPTY(&map)) {
1204 forward_wakeups_delivered++;
1205 STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1207 if (!CPU_ISSET(id, &map))
1209 if (cpu_idle_wakeup(pc->pc_cpuid))
1212 if (!CPU_EMPTY(&map))
1213 ipi_selected(map, IPI_AST);
1216 if (cpunum == NOCPU)
1217 printf("forward_wakeup: Idle processor not found\n");
1222 kick_other_cpu(int pri, int cpuid)
1227 pcpu = pcpu_find(cpuid);
1228 if (CPU_ISSET(cpuid, &idle_cpus_mask)) {
1229 forward_wakeups_delivered++;
1230 if (!cpu_idle_wakeup(cpuid))
1231 ipi_cpu(cpuid, IPI_AST);
1235 cpri = pcpu->pc_curthread->td_priority;
1239 #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1240 #if !defined(FULL_PREEMPTION)
1241 if (pri <= PRI_MAX_ITHD)
1242 #endif /* ! FULL_PREEMPTION */
1244 ipi_cpu(cpuid, IPI_PREEMPT);
1247 #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1249 if (pcpu->pc_curthread->td_lock == &sched_lock) {
1250 pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
1251 ipi_cpu(cpuid, IPI_AST);
1258 sched_pickcpu(struct thread *td)
1262 mtx_assert(&sched_lock, MA_OWNED);
1264 if (td->td_lastcpu != NOCPU && THREAD_CAN_SCHED(td, td->td_lastcpu))
1265 best = td->td_lastcpu;
1269 if (!THREAD_CAN_SCHED(td, cpu))
1274 else if (runq_length[cpu] < runq_length[best])
1277 KASSERT(best != NOCPU, ("no valid CPUs"));
1284 sched_add(struct thread *td, int flags)
1288 struct td_sched *ts;
1293 ts = td_get_sched(td);
1294 THREAD_LOCK_ASSERT(td, MA_OWNED);
1295 KASSERT((td->td_inhibitors == 0),
1296 ("sched_add: trying to run inhibited thread"));
1297 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1298 ("sched_add: bad thread state"));
1299 KASSERT(td->td_flags & TDF_INMEM,
1300 ("sched_add: thread swapped out"));
1302 KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
1303 "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1304 sched_tdname(curthread));
1305 KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
1306 KTR_ATTR_LINKED, sched_tdname(td));
1307 SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1308 flags & SRQ_PREEMPTED);
1311 * Now that the thread is moving to the run-queue, set the lock
1312 * to the scheduler's lock.
1314 if (td->td_lock != &sched_lock) {
1315 mtx_lock_spin(&sched_lock);
1316 if ((flags & SRQ_HOLD) != 0)
1317 td->td_lock = &sched_lock;
1319 thread_lock_set(td, &sched_lock);
1324 * If SMP is started and the thread is pinned or otherwise limited to
1325 * a specific set of CPUs, queue the thread to a per-CPU run queue.
1326 * Otherwise, queue the thread to the global run queue.
1328 * If SMP has not yet been started we must use the global run queue
1329 * as per-CPU state may not be initialized yet and we may crash if we
1330 * try to access the per-CPU run queues.
1332 if (smp_started && (td->td_pinned != 0 || td->td_flags & TDF_BOUND ||
1333 ts->ts_flags & TSF_AFFINITY)) {
1334 if (td->td_pinned != 0)
1335 cpu = td->td_lastcpu;
1336 else if (td->td_flags & TDF_BOUND) {
1337 /* Find CPU from bound runq. */
1338 KASSERT(SKE_RUNQ_PCPU(ts),
1339 ("sched_add: bound td_sched not on cpu runq"));
1340 cpu = ts->ts_runq - &runq_pcpu[0];
1342 /* Find a valid CPU for our cpuset */
1343 cpu = sched_pickcpu(td);
1344 ts->ts_runq = &runq_pcpu[cpu];
1347 "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td,
1351 "sched_add: adding td_sched:%p (td:%p) to gbl runq", ts,
1354 ts->ts_runq = &runq;
1357 if ((td->td_flags & TDF_NOLOAD) == 0)
1359 runq_add(ts->ts_runq, td, flags);
1363 cpuid = PCPU_GET(cpuid);
1364 if (single_cpu && cpu != cpuid) {
1365 kick_other_cpu(td->td_priority, cpu);
1368 tidlemsk = idle_cpus_mask;
1369 CPU_ANDNOT(&tidlemsk, &tidlemsk, &hlt_cpus_mask);
1370 CPU_CLR(cpuid, &tidlemsk);
1372 if (!CPU_ISSET(cpuid, &idle_cpus_mask) &&
1373 ((flags & SRQ_INTR) == 0) &&
1374 !CPU_EMPTY(&tidlemsk))
1375 forwarded = forward_wakeup(cpu);
1379 if (!maybe_preempt(td))
1383 if ((flags & SRQ_HOLDTD) == 0)
1388 struct td_sched *ts;
1390 ts = td_get_sched(td);
1391 THREAD_LOCK_ASSERT(td, MA_OWNED);
1392 KASSERT((td->td_inhibitors == 0),
1393 ("sched_add: trying to run inhibited thread"));
1394 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1395 ("sched_add: bad thread state"));
1396 KASSERT(td->td_flags & TDF_INMEM,
1397 ("sched_add: thread swapped out"));
1398 KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
1399 "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1400 sched_tdname(curthread));
1401 KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
1402 KTR_ATTR_LINKED, sched_tdname(td));
1403 SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1404 flags & SRQ_PREEMPTED);
1407 * Now that the thread is moving to the run-queue, set the lock
1408 * to the scheduler's lock.
1410 if (td->td_lock != &sched_lock) {
1411 mtx_lock_spin(&sched_lock);
1412 if ((flags & SRQ_HOLD) != 0)
1413 td->td_lock = &sched_lock;
1415 thread_lock_set(td, &sched_lock);
1418 CTR2(KTR_RUNQ, "sched_add: adding td_sched:%p (td:%p) to runq", ts, td);
1419 ts->ts_runq = &runq;
1421 if ((td->td_flags & TDF_NOLOAD) == 0)
1423 runq_add(ts->ts_runq, td, flags);
1424 if (!maybe_preempt(td))
1426 if ((flags & SRQ_HOLDTD) == 0)
1432 sched_rem(struct thread *td)
1434 struct td_sched *ts;
1436 ts = td_get_sched(td);
1437 KASSERT(td->td_flags & TDF_INMEM,
1438 ("sched_rem: thread swapped out"));
1439 KASSERT(TD_ON_RUNQ(td),
1440 ("sched_rem: thread not on run queue"));
1441 mtx_assert(&sched_lock, MA_OWNED);
1442 KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
1443 "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1444 sched_tdname(curthread));
1445 SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
1447 if ((td->td_flags & TDF_NOLOAD) == 0)
1450 if (ts->ts_runq != &runq)
1451 runq_length[ts->ts_runq - runq_pcpu]--;
1453 runq_remove(ts->ts_runq, td);
1458 * Select threads to run. Note that running threads still consume a
1467 mtx_assert(&sched_lock, MA_OWNED);
1469 struct thread *tdcpu;
1472 td = runq_choose_fuzz(&runq, runq_fuzz);
1473 tdcpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1477 tdcpu->td_priority < td->td_priority)) {
1478 CTR2(KTR_RUNQ, "choosing td %p from pcpu runq %d", tdcpu,
1481 rq = &runq_pcpu[PCPU_GET(cpuid)];
1483 CTR1(KTR_RUNQ, "choosing td_sched %p from main runq", td);
1488 td = runq_choose(&runq);
1494 runq_length[PCPU_GET(cpuid)]--;
1496 runq_remove(rq, td);
1497 td->td_flags |= TDF_DIDRUN;
1499 KASSERT(td->td_flags & TDF_INMEM,
1500 ("sched_choose: thread swapped out"));
1503 return (PCPU_GET(idlethread));
1507 sched_preempt(struct thread *td)
1510 SDT_PROBE2(sched, , , surrender, td, td->td_proc);
1511 if (td->td_critnest > 1) {
1512 td->td_owepreempt = 1;
1515 mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT);
1520 sched_userret_slowpath(struct thread *td)
1524 td->td_priority = td->td_user_pri;
1525 td->td_base_pri = td->td_user_pri;
1530 sched_bind(struct thread *td, int cpu)
1532 struct td_sched *ts;
1534 THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
1535 KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
1537 ts = td_get_sched(td);
1539 td->td_flags |= TDF_BOUND;
1541 ts->ts_runq = &runq_pcpu[cpu];
1542 if (PCPU_GET(cpuid) == cpu)
1551 sched_unbind(struct thread* td)
1553 THREAD_LOCK_ASSERT(td, MA_OWNED);
1554 KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
1555 td->td_flags &= ~TDF_BOUND;
1559 sched_is_bound(struct thread *td)
1561 THREAD_LOCK_ASSERT(td, MA_OWNED);
1562 return (td->td_flags & TDF_BOUND);
1566 sched_relinquish(struct thread *td)
1569 mi_switch(SW_VOL | SWT_RELINQUISH);
1575 return (sched_tdcnt);
1579 sched_sizeof_proc(void)
1581 return (sizeof(struct proc));
1585 sched_sizeof_thread(void)
1587 return (sizeof(struct thread) + sizeof(struct td_sched));
1591 sched_pctcpu(struct thread *td)
1593 struct td_sched *ts;
1595 THREAD_LOCK_ASSERT(td, MA_OWNED);
1596 ts = td_get_sched(td);
1597 return (ts->ts_pctcpu);
1602 * Calculates the contribution to the thread cpu usage for the latest
1603 * (unfinished) second.
1606 sched_pctcpu_delta(struct thread *td)
1608 struct td_sched *ts;
1612 THREAD_LOCK_ASSERT(td, MA_OWNED);
1613 ts = td_get_sched(td);
1615 realstathz = stathz ? stathz : hz;
1616 if (ts->ts_cpticks != 0) {
1617 #if (FSHIFT >= CCPU_SHIFT)
1618 delta = (realstathz == 100)
1619 ? ((fixpt_t) ts->ts_cpticks) <<
1620 (FSHIFT - CCPU_SHIFT) :
1621 100 * (((fixpt_t) ts->ts_cpticks)
1622 << (FSHIFT - CCPU_SHIFT)) / realstathz;
1624 delta = ((FSCALE - ccpu) *
1626 FSCALE / realstathz)) >> FSHIFT;
1635 sched_estcpu(struct thread *td)
1638 return (td_get_sched(td)->ts_estcpu);
1642 * The actual idle process.
1645 sched_idletd(void *dummy)
1647 struct pcpuidlestat *stat;
1649 THREAD_NO_SLEEPING();
1650 stat = DPCPU_PTR(idlestat);
1652 mtx_assert(&Giant, MA_NOTOWNED);
1654 while (sched_runnable() == 0) {
1655 cpu_idle(stat->idlecalls + stat->oldidlecalls > 64);
1659 mtx_lock_spin(&sched_lock);
1660 mi_switch(SW_VOL | SWT_IDLE);
1665 * A CPU is entering for the first time or a thread is exiting.
1668 sched_throw(struct thread *td)
1671 * Correct spinlock nesting. The idle thread context that we are
1672 * borrowing was created so that it would start out with a single
1673 * spin lock (sched_lock) held in fork_trampoline(). Since we've
1674 * explicitly acquired locks in this function, the nesting count
1675 * is now 2 rather than 1. Since we are nested, calling
1676 * spinlock_exit() will simply adjust the counts without allowing
1677 * spin lock using code to interrupt us.
1680 mtx_lock_spin(&sched_lock);
1682 PCPU_SET(switchtime, cpu_ticks());
1683 PCPU_SET(switchticks, ticks);
1685 lock_profile_release_lock(&sched_lock.lock_object, true);
1686 MPASS(td->td_lock == &sched_lock);
1687 td->td_lastcpu = td->td_oncpu;
1688 td->td_oncpu = NOCPU;
1690 mtx_assert(&sched_lock, MA_OWNED);
1691 KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
1692 cpu_throw(td, choosethread()); /* doesn't return */
1696 sched_fork_exit(struct thread *td)
1700 * Finish setting up thread glue so that it begins execution in a
1701 * non-nested critical section with sched_lock held but not recursed.
1703 td->td_oncpu = PCPU_GET(cpuid);
1704 sched_lock.mtx_lock = (uintptr_t)td;
1705 lock_profile_obtain_lock_success(&sched_lock.lock_object, true,
1706 0, 0, __FILE__, __LINE__);
1707 THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
1709 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
1710 "prio:%d", td->td_priority);
1711 SDT_PROBE0(sched, , , on__cpu);
1715 sched_tdname(struct thread *td)
1718 struct td_sched *ts;
1720 ts = td_get_sched(td);
1721 if (ts->ts_name[0] == '\0')
1722 snprintf(ts->ts_name, sizeof(ts->ts_name),
1723 "%s tid %d", td->td_name, td->td_tid);
1724 return (ts->ts_name);
1726 return (td->td_name);
1732 sched_clear_tdname(struct thread *td)
1734 struct td_sched *ts;
1736 ts = td_get_sched(td);
1737 ts->ts_name[0] = '\0';
1742 sched_affinity(struct thread *td)
1745 struct td_sched *ts;
1748 THREAD_LOCK_ASSERT(td, MA_OWNED);
1751 * Set the TSF_AFFINITY flag if there is at least one CPU this
1752 * thread can't run on.
1754 ts = td_get_sched(td);
1755 ts->ts_flags &= ~TSF_AFFINITY;
1757 if (!THREAD_CAN_SCHED(td, cpu)) {
1758 ts->ts_flags |= TSF_AFFINITY;
1764 * If this thread can run on all CPUs, nothing else to do.
1766 if (!(ts->ts_flags & TSF_AFFINITY))
1769 /* Pinned threads and bound threads should be left alone. */
1770 if (td->td_pinned != 0 || td->td_flags & TDF_BOUND)
1773 switch (td->td_state) {
1776 * If we are on a per-CPU runqueue that is in the set,
1777 * then nothing needs to be done.
1779 if (ts->ts_runq != &runq &&
1780 THREAD_CAN_SCHED(td, ts->ts_runq - runq_pcpu))
1783 /* Put this thread on a valid per-CPU runqueue. */
1785 sched_add(td, SRQ_HOLDTD | SRQ_BORING);
1789 * See if our current CPU is in the set. If not, force a
1792 if (THREAD_CAN_SCHED(td, td->td_oncpu))
1795 td->td_flags |= TDF_NEEDRESCHED;
1796 if (td != curthread)
1797 ipi_cpu(cpu, IPI_AST);