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 __FBSDID("$FreeBSD$");
40 #include "opt_hwpmc_hooks.h"
41 #include "opt_sched.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/cpuset.h>
46 #include <sys/kernel.h>
49 #include <sys/kthread.h>
50 #include <sys/mutex.h>
52 #include <sys/resourcevar.h>
53 #include <sys/sched.h>
56 #include <sys/sysctl.h>
58 #include <sys/turnstile.h>
60 #include <machine/pcb.h>
61 #include <machine/smp.h>
64 #include <sys/pmckern.h>
68 #include <sys/dtrace_bsd.h>
69 int dtrace_vtime_active;
70 dtrace_vtime_switch_func_t dtrace_vtime_switch_func;
74 * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
75 * the range 100-256 Hz (approximately).
77 #define ESTCPULIM(e) \
78 min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
79 RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
81 #define INVERSE_ESTCPU_WEIGHT (8 * smp_cpus)
83 #define INVERSE_ESTCPU_WEIGHT 8 /* 1 / (priorities per estcpu level). */
85 #define NICE_WEIGHT 1 /* Priorities per nice level. */
87 #define TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
90 * The schedulable entity that runs a context.
91 * This is an extension to the thread structure and is tailored to
92 * the requirements of this scheduler.
93 * All fields are protected by the scheduler lock.
96 fixpt_t ts_pctcpu; /* %cpu during p_swtime. */
97 u_int ts_estcpu; /* Estimated cpu utilization. */
98 int ts_cpticks; /* Ticks of cpu time. */
99 int ts_slptime; /* Seconds !RUNNING. */
100 int ts_slice; /* Remaining part of time slice. */
102 struct runq *ts_runq; /* runq the thread is currently on */
104 char ts_name[TS_NAME_LEN];
108 /* flags kept in td_flags */
109 #define TDF_DIDRUN TDF_SCHED0 /* thread actually ran. */
110 #define TDF_BOUND TDF_SCHED1 /* Bound to one CPU. */
111 #define TDF_SLICEEND TDF_SCHED2 /* Thread time slice is over. */
113 /* flags kept in ts_flags */
114 #define TSF_AFFINITY 0x0001 /* Has a non-"full" CPU set. */
116 #define SKE_RUNQ_PCPU(ts) \
117 ((ts)->ts_runq != 0 && (ts)->ts_runq != &runq)
119 #define THREAD_CAN_SCHED(td, cpu) \
120 CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
122 _Static_assert(sizeof(struct thread) + sizeof(struct td_sched) <=
123 sizeof(struct thread0_storage),
124 "increase struct thread0_storage.t0st_sched size");
126 static struct mtx sched_lock;
128 static int realstathz = 127; /* stathz is sometimes 0 and run off of hz. */
129 static int sched_tdcnt; /* Total runnable threads in the system. */
130 static int sched_slice = 12; /* Thread run time before rescheduling. */
132 static void setup_runqs(void);
133 static void schedcpu(void);
134 static void schedcpu_thread(void);
135 static void sched_priority(struct thread *td, u_char prio);
136 static void sched_setup(void *dummy);
137 static void maybe_resched(struct thread *td);
138 static void updatepri(struct thread *td);
139 static void resetpriority(struct thread *td);
140 static void resetpriority_thread(struct thread *td);
142 static int sched_pickcpu(struct thread *td);
143 static int forward_wakeup(int cpunum);
144 static void kick_other_cpu(int pri, int cpuid);
147 static struct kproc_desc sched_kp = {
152 SYSINIT(schedcpu, SI_SUB_LAST, SI_ORDER_FIRST, kproc_start,
154 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
156 static void sched_initticks(void *dummy);
157 SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
163 static struct runq runq;
169 static struct runq runq_pcpu[MAXCPU];
170 long runq_length[MAXCPU];
172 static cpuset_t idle_cpus_mask;
175 struct pcpuidlestat {
179 static DPCPU_DEFINE(struct pcpuidlestat, idlestat);
187 for (i = 0; i < MAXCPU; ++i)
188 runq_init(&runq_pcpu[i]);
195 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
197 int error, new_val, period;
199 period = 1000000 / realstathz;
200 new_val = period * sched_slice;
201 error = sysctl_handle_int(oidp, &new_val, 0, req);
202 if (error != 0 || req->newptr == NULL)
206 sched_slice = imax(1, (new_val + period / 2) / period);
207 hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
212 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "Scheduler");
214 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
216 SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
217 NULL, 0, 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, CTLFLAG_RD, NULL,
226 static int runq_fuzz = 1;
227 SYSCTL_INT(_kern_sched, OID_AUTO, runq_fuzz, CTLFLAG_RW, &runq_fuzz, 0, "");
229 static int forward_wakeup_enabled = 1;
230 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
231 &forward_wakeup_enabled, 0,
232 "Forwarding of wakeup to idle CPUs");
234 static int forward_wakeups_requested = 0;
235 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
236 &forward_wakeups_requested, 0,
237 "Requests for Forwarding of wakeup to idle CPUs");
239 static int forward_wakeups_delivered = 0;
240 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
241 &forward_wakeups_delivered, 0,
242 "Completed Forwarding of wakeup to idle CPUs");
244 static int forward_wakeup_use_mask = 1;
245 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
246 &forward_wakeup_use_mask, 0,
247 "Use the mask of idle cpus");
249 static int forward_wakeup_use_loop = 0;
250 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
251 &forward_wakeup_use_loop, 0,
252 "Use a loop to find idle cpus");
256 static int sched_followon = 0;
257 SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
259 "allow threads to share a quantum");
262 SDT_PROVIDER_DEFINE(sched);
264 SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
265 "struct proc *", "uint8_t");
266 SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
267 "struct proc *", "void *");
268 SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
269 "struct proc *", "void *", "int");
270 SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
271 "struct proc *", "uint8_t", "struct thread *");
272 SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
273 SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
275 SDT_PROBE_DEFINE(sched, , , on__cpu);
276 SDT_PROBE_DEFINE(sched, , , remain__cpu);
277 SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
285 KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
286 SDT_PROBE2(sched, , , load__change, NOCPU, sched_tdcnt);
294 KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
295 SDT_PROBE2(sched, , , load__change, NOCPU, sched_tdcnt);
298 * Arrange to reschedule if necessary, taking the priorities and
299 * schedulers into account.
302 maybe_resched(struct thread *td)
305 THREAD_LOCK_ASSERT(td, MA_OWNED);
306 if (td->td_priority < curthread->td_priority)
307 curthread->td_flags |= TDF_NEEDRESCHED;
311 * This function is called when a thread is about to be put on run queue
312 * because it has been made runnable or its priority has been adjusted. It
313 * determines if the new thread should preempt the current thread. If so,
314 * it sets td_owepreempt to request a preemption.
317 maybe_preempt(struct thread *td)
324 * The new thread should not preempt the current thread if any of the
325 * following conditions are true:
327 * - The kernel is in the throes of crashing (panicstr).
328 * - The current thread has a higher (numerically lower) or
329 * equivalent priority. Note that this prevents curthread from
330 * trying to preempt to itself.
331 * - The current thread has an inhibitor set or is in the process of
332 * exiting. In this case, the current thread is about to switch
333 * out anyways, so there's no point in preempting. If we did,
334 * the current thread would not be properly resumed as well, so
335 * just avoid that whole landmine.
336 * - If the new thread's priority is not a realtime priority and
337 * the current thread's priority is not an idle priority and
338 * FULL_PREEMPTION is disabled.
340 * If all of these conditions are false, but the current thread is in
341 * a nested critical section, then we have to defer the preemption
342 * until we exit the critical section. Otherwise, switch immediately
346 THREAD_LOCK_ASSERT(td, MA_OWNED);
347 KASSERT((td->td_inhibitors == 0),
348 ("maybe_preempt: trying to run inhibited thread"));
349 pri = td->td_priority;
350 cpri = ctd->td_priority;
351 if (panicstr != NULL || pri >= cpri /* || dumping */ ||
352 TD_IS_INHIBITED(ctd))
354 #ifndef FULL_PREEMPTION
355 if (pri > PRI_MAX_ITHD && cpri < PRI_MIN_IDLE)
359 CTR0(KTR_PROC, "maybe_preempt: scheduling preemption");
360 ctd->td_owepreempt = 1;
368 * Constants for digital decay and forget:
369 * 90% of (ts_estcpu) usage in 5 * loadav time
370 * 95% of (ts_pctcpu) usage in 60 seconds (load insensitive)
371 * Note that, as ps(1) mentions, this can let percentages
372 * total over 100% (I've seen 137.9% for 3 processes).
374 * Note that schedclock() updates ts_estcpu and p_cpticks asynchronously.
376 * We wish to decay away 90% of ts_estcpu in (5 * loadavg) seconds.
377 * That is, the system wants to compute a value of decay such
378 * that the following for loop:
379 * for (i = 0; i < (5 * loadavg); i++)
380 * ts_estcpu *= decay;
383 * for all values of loadavg:
385 * Mathematically this loop can be expressed by saying:
386 * decay ** (5 * loadavg) ~= .1
388 * The system computes decay as:
389 * decay = (2 * loadavg) / (2 * loadavg + 1)
391 * We wish to prove that the system's computation of decay
392 * will always fulfill the equation:
393 * decay ** (5 * loadavg) ~= .1
395 * If we compute b as:
398 * decay = b / (b + 1)
400 * We now need to prove two things:
401 * 1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
402 * 2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
405 * For x close to zero, exp(x) =~ 1 + x, since
406 * exp(x) = 0! + x**1/1! + x**2/2! + ... .
407 * therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
408 * For x close to zero, ln(1+x) =~ x, since
409 * ln(1+x) = x - x**2/2 + x**3/3 - ... -1 < x < 1
410 * therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
414 * Solve (factor)**(power) =~ .1 given power (5*loadav):
415 * solving for factor,
416 * ln(factor) =~ (-2.30/5*loadav), or
417 * factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
418 * exp(-1/b) =~ (b-1)/b =~ b/(b+1). QED
421 * Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
423 * power*ln(b/(b+1)) =~ -2.30, or
424 * power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav. QED
426 * Actual power values for the implemented algorithm are as follows:
428 * power: 5.68 10.32 14.94 19.55
431 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
432 #define loadfactor(loadav) (2 * (loadav))
433 #define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
435 /* decay 95% of `ts_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
436 static fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
437 SYSCTL_UINT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
440 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
441 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
442 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
444 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
445 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
447 * If you don't want to bother with the faster/more-accurate formula, you
448 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
449 * (more general) method of calculating the %age of CPU used by a process.
451 #define CCPU_SHIFT 11
454 * Recompute process priorities, every hz ticks.
455 * MP-safe, called without the Giant mutex.
461 fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
467 sx_slock(&allproc_lock);
468 FOREACH_PROC_IN_SYSTEM(p) {
470 if (p->p_state == PRS_NEW) {
474 FOREACH_THREAD_IN_PROC(p, td) {
476 ts = td_get_sched(td);
479 * Increment sleep time (if sleeping). We
480 * ignore overflow, as above.
483 * The td_sched slptimes are not touched in wakeup
484 * because the thread may not HAVE everything in
485 * memory? XXX I think this is out of date.
487 if (TD_ON_RUNQ(td)) {
489 td->td_flags &= ~TDF_DIDRUN;
490 } else if (TD_IS_RUNNING(td)) {
492 /* Do not clear TDF_DIDRUN */
493 } else if (td->td_flags & TDF_DIDRUN) {
495 td->td_flags &= ~TDF_DIDRUN;
499 * ts_pctcpu is only for ps and ttyinfo().
501 ts->ts_pctcpu = (ts->ts_pctcpu * ccpu) >> FSHIFT;
503 * If the td_sched has been idle the entire second,
504 * stop recalculating its priority until
507 if (ts->ts_cpticks != 0) {
508 #if (FSHIFT >= CCPU_SHIFT)
509 ts->ts_pctcpu += (realstathz == 100)
510 ? ((fixpt_t) ts->ts_cpticks) <<
511 (FSHIFT - CCPU_SHIFT) :
512 100 * (((fixpt_t) ts->ts_cpticks)
513 << (FSHIFT - CCPU_SHIFT)) / realstathz;
515 ts->ts_pctcpu += ((FSCALE - ccpu) *
517 FSCALE / realstathz)) >> FSHIFT;
522 * If there are ANY running threads in this process,
523 * then don't count it as sleeping.
524 * XXX: this is broken.
527 if (ts->ts_slptime > 1) {
529 * In an ideal world, this should not
530 * happen, because whoever woke us
531 * up from the long sleep should have
532 * unwound the slptime and reset our
533 * priority before we run at the stale
534 * priority. Should KASSERT at some
535 * point when all the cases are fixed.
542 if (ts->ts_slptime > 1) {
546 ts->ts_estcpu = decay_cpu(loadfac, ts->ts_estcpu);
548 resetpriority_thread(td);
553 sx_sunlock(&allproc_lock);
557 * Main loop for a kthread that executes schedcpu once a second.
560 schedcpu_thread(void)
570 * Recalculate the priority of a process after it has slept for a while.
571 * For all load averages >= 1 and max ts_estcpu of 255, sleeping for at
572 * least six times the loadfactor will decay ts_estcpu to zero.
575 updatepri(struct thread *td)
581 ts = td_get_sched(td);
582 loadfac = loadfactor(averunnable.ldavg[0]);
583 if (ts->ts_slptime > 5 * loadfac)
586 newcpu = ts->ts_estcpu;
587 ts->ts_slptime--; /* was incremented in schedcpu() */
588 while (newcpu && --ts->ts_slptime)
589 newcpu = decay_cpu(loadfac, newcpu);
590 ts->ts_estcpu = newcpu;
595 * Compute the priority of a process when running in user mode.
596 * Arrange to reschedule if the resulting priority is better
597 * than that of the current process.
600 resetpriority(struct thread *td)
604 if (td->td_pri_class != PRI_TIMESHARE)
606 newpriority = PUSER +
607 td_get_sched(td)->ts_estcpu / INVERSE_ESTCPU_WEIGHT +
608 NICE_WEIGHT * (td->td_proc->p_nice - PRIO_MIN);
609 newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
611 sched_user_prio(td, newpriority);
615 * Update the thread's priority when the associated process's user
619 resetpriority_thread(struct thread *td)
622 /* Only change threads with a time sharing user priority. */
623 if (td->td_priority < PRI_MIN_TIMESHARE ||
624 td->td_priority > PRI_MAX_TIMESHARE)
627 /* XXX the whole needresched thing is broken, but not silly. */
630 sched_prio(td, td->td_user_pri);
635 sched_setup(void *dummy)
640 /* Account for thread0. */
645 * This routine determines time constants after stathz and hz are setup.
648 sched_initticks(void *dummy)
651 realstathz = stathz ? stathz : hz;
652 sched_slice = realstathz / 10; /* ~100ms */
653 hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
657 /* External interfaces start here */
660 * Very early in the boot some setup of scheduler-specific
661 * parts of proc0 and of some scheduler resources needs to be done.
670 * Set up the scheduler specific parts of thread0.
672 thread0.td_lock = &sched_lock;
673 td_get_sched(&thread0)->ts_slice = sched_slice;
674 mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
681 return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
683 return runq_check(&runq);
688 sched_rr_interval(void)
691 /* Convert sched_slice from stathz to hz. */
692 return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
696 * We adjust the priority of the current process. The priority of a
697 * process gets worse as it accumulates CPU time. The cpu usage
698 * estimator (ts_estcpu) is increased here. resetpriority() will
699 * compute a different priority each time ts_estcpu increases by
700 * INVERSE_ESTCPU_WEIGHT (until PRI_MAX_TIMESHARE is reached). The
701 * cpu usage estimator ramps up quite quickly when the process is
702 * running (linearly), and decays away exponentially, at a rate which
703 * is proportionally slower when the system is busy. The basic
704 * principle is that the system will 90% forget that the process used
705 * a lot of CPU time in 5 * loadav seconds. This causes the system to
706 * favor processes which haven't run much recently, and to round-robin
707 * among other processes.
710 sched_clock(struct thread *td)
712 struct pcpuidlestat *stat;
715 THREAD_LOCK_ASSERT(td, MA_OWNED);
716 ts = td_get_sched(td);
719 ts->ts_estcpu = ESTCPULIM(ts->ts_estcpu + 1);
720 if ((ts->ts_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
722 resetpriority_thread(td);
726 * Force a context switch if the current thread has used up a full
727 * time slice (default is 100ms).
729 if (!TD_IS_IDLETHREAD(td) && --ts->ts_slice <= 0) {
730 ts->ts_slice = sched_slice;
731 td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
734 stat = DPCPU_PTR(idlestat);
735 stat->oldidlecalls = stat->idlecalls;
740 * Charge child's scheduling CPU usage to parent.
743 sched_exit(struct proc *p, struct thread *td)
746 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "proc exit",
747 "prio:%d", td->td_priority);
749 PROC_LOCK_ASSERT(p, MA_OWNED);
750 sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
754 sched_exit_thread(struct thread *td, struct thread *child)
757 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "exit",
758 "prio:%d", child->td_priority);
760 td_get_sched(td)->ts_estcpu = ESTCPULIM(td_get_sched(td)->ts_estcpu +
761 td_get_sched(child)->ts_estcpu);
764 if ((child->td_flags & TDF_NOLOAD) == 0)
766 thread_unlock(child);
770 sched_fork(struct thread *td, struct thread *childtd)
772 sched_fork_thread(td, childtd);
776 sched_fork_thread(struct thread *td, struct thread *childtd)
778 struct td_sched *ts, *tsc;
780 childtd->td_oncpu = NOCPU;
781 childtd->td_lastcpu = NOCPU;
782 childtd->td_lock = &sched_lock;
783 childtd->td_cpuset = cpuset_ref(td->td_cpuset);
784 childtd->td_priority = childtd->td_base_pri;
785 ts = td_get_sched(childtd);
786 bzero(ts, sizeof(*ts));
787 tsc = td_get_sched(td);
788 ts->ts_estcpu = tsc->ts_estcpu;
789 ts->ts_flags |= (tsc->ts_flags & TSF_AFFINITY);
794 sched_nice(struct proc *p, int nice)
798 PROC_LOCK_ASSERT(p, MA_OWNED);
800 FOREACH_THREAD_IN_PROC(p, td) {
803 resetpriority_thread(td);
809 sched_class(struct thread *td, int class)
811 THREAD_LOCK_ASSERT(td, MA_OWNED);
812 td->td_pri_class = class;
816 * Adjust the priority of a thread.
819 sched_priority(struct thread *td, u_char prio)
823 KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "priority change",
824 "prio:%d", td->td_priority, "new prio:%d", prio, KTR_ATTR_LINKED,
825 sched_tdname(curthread));
826 SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
827 if (td != curthread && prio > td->td_priority) {
828 KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
829 "lend prio", "prio:%d", td->td_priority, "new prio:%d",
830 prio, KTR_ATTR_LINKED, sched_tdname(td));
831 SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
834 THREAD_LOCK_ASSERT(td, MA_OWNED);
835 if (td->td_priority == prio)
837 td->td_priority = prio;
838 if (TD_ON_RUNQ(td) && td->td_rqindex != (prio / RQ_PPQ)) {
840 sched_add(td, SRQ_BORING);
845 * Update a thread's priority when it is lent another thread's
849 sched_lend_prio(struct thread *td, u_char prio)
852 td->td_flags |= TDF_BORROWING;
853 sched_priority(td, prio);
857 * Restore a thread's priority when priority propagation is
858 * over. The prio argument is the minimum priority the thread
859 * needs to have to satisfy other possible priority lending
860 * requests. If the thread's regulary priority is less
861 * important than prio the thread will keep a priority boost
865 sched_unlend_prio(struct thread *td, u_char prio)
869 if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
870 td->td_base_pri <= PRI_MAX_TIMESHARE)
871 base_pri = td->td_user_pri;
873 base_pri = td->td_base_pri;
874 if (prio >= base_pri) {
875 td->td_flags &= ~TDF_BORROWING;
876 sched_prio(td, base_pri);
878 sched_lend_prio(td, prio);
882 sched_prio(struct thread *td, u_char prio)
886 /* First, update the base priority. */
887 td->td_base_pri = prio;
890 * If the thread is borrowing another thread's priority, don't ever
891 * lower the priority.
893 if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
896 /* Change the real priority. */
897 oldprio = td->td_priority;
898 sched_priority(td, prio);
901 * If the thread is on a turnstile, then let the turnstile update
904 if (TD_ON_LOCK(td) && oldprio != prio)
905 turnstile_adjust(td, oldprio);
909 sched_user_prio(struct thread *td, u_char prio)
912 THREAD_LOCK_ASSERT(td, MA_OWNED);
913 td->td_base_user_pri = prio;
914 if (td->td_lend_user_pri <= prio)
916 td->td_user_pri = prio;
920 sched_lend_user_prio(struct thread *td, u_char prio)
923 THREAD_LOCK_ASSERT(td, MA_OWNED);
924 td->td_lend_user_pri = prio;
925 td->td_user_pri = min(prio, td->td_base_user_pri);
926 if (td->td_priority > td->td_user_pri)
927 sched_prio(td, td->td_user_pri);
928 else if (td->td_priority != td->td_user_pri)
929 td->td_flags |= TDF_NEEDRESCHED;
933 sched_sleep(struct thread *td, int pri)
936 THREAD_LOCK_ASSERT(td, MA_OWNED);
937 td->td_slptick = ticks;
938 td_get_sched(td)->ts_slptime = 0;
939 if (pri != 0 && PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
941 if (TD_IS_SUSPENDED(td) || pri >= PSOCK)
942 td->td_flags |= TDF_CANSWAP;
946 sched_switch(struct thread *td, struct thread *newtd, int flags)
954 ts = td_get_sched(td);
957 THREAD_LOCK_ASSERT(td, MA_OWNED);
960 * Switch to the sched lock to fix things up and pick
962 * Block the td_lock in order to avoid breaking the critical path.
964 if (td->td_lock != &sched_lock) {
965 mtx_lock_spin(&sched_lock);
966 tmtx = thread_lock_block(td);
969 if ((td->td_flags & TDF_NOLOAD) == 0)
972 td->td_lastcpu = td->td_oncpu;
973 preempted = (td->td_flags & TDF_SLICEEND) == 0 &&
974 (flags & SW_PREEMPT) != 0;
975 td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
976 td->td_owepreempt = 0;
977 td->td_oncpu = NOCPU;
980 * At the last moment, if this thread is still marked RUNNING,
981 * then put it back on the run queue as it has not been suspended
982 * or stopped or any thing else similar. We never put the idle
983 * threads on the run queue, however.
985 if (td->td_flags & TDF_IDLETD) {
988 CPU_CLR(PCPU_GET(cpuid), &idle_cpus_mask);
991 if (TD_IS_RUNNING(td)) {
992 /* Put us back on the run queue. */
993 sched_add(td, preempted ?
994 SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
995 SRQ_OURSELF|SRQ_YIELDING);
1000 * The thread we are about to run needs to be counted
1001 * as if it had been added to the run queue and selected.
1007 KASSERT((newtd->td_inhibitors == 0),
1008 ("trying to run inhibited thread"));
1009 newtd->td_flags |= TDF_DIDRUN;
1010 TD_SET_RUNNING(newtd);
1011 if ((newtd->td_flags & TDF_NOLOAD) == 0)
1014 newtd = choosethread();
1015 MPASS(newtd->td_lock == &sched_lock);
1018 #if (KTR_COMPILE & KTR_SCHED) != 0
1019 if (TD_IS_IDLETHREAD(td))
1020 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle",
1021 "prio:%d", td->td_priority);
1023 KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td),
1024 "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg,
1025 "lockname:\"%s\"", td->td_lockname);
1030 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1031 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1034 SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
1037 lock_profile_release_lock(&sched_lock.lock_object);
1038 #ifdef KDTRACE_HOOKS
1040 * If DTrace has set the active vtime enum to anything
1041 * other than INACTIVE (0), then it should have set the
1044 if (dtrace_vtime_active)
1045 (*dtrace_vtime_switch_func)(newtd);
1048 cpu_switch(td, newtd, tmtx != NULL ? tmtx : td->td_lock);
1049 lock_profile_obtain_lock_success(&sched_lock.lock_object,
1050 0, 0, __FILE__, __LINE__);
1052 * Where am I? What year is it?
1053 * We are in the same thread that went to sleep above,
1054 * but any amount of time may have passed. All our context
1055 * will still be available as will local variables.
1056 * PCPU values however may have changed as we may have
1057 * changed CPU so don't trust cached values of them.
1058 * New threads will go to fork_exit() instead of here
1059 * so if you change things here you may need to change
1062 * If the thread above was exiting it will never wake
1063 * up again here, so either it has saved everything it
1064 * needed to, or the thread_wait() or wait() will
1068 SDT_PROBE0(sched, , , on__cpu);
1070 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1071 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1074 SDT_PROBE0(sched, , , remain__cpu);
1076 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
1077 "prio:%d", td->td_priority);
1080 if (td->td_flags & TDF_IDLETD)
1081 CPU_SET(PCPU_GET(cpuid), &idle_cpus_mask);
1083 sched_lock.mtx_lock = (uintptr_t)td;
1084 td->td_oncpu = PCPU_GET(cpuid);
1085 MPASS(td->td_lock == &sched_lock);
1089 sched_wakeup(struct thread *td)
1091 struct td_sched *ts;
1093 THREAD_LOCK_ASSERT(td, MA_OWNED);
1094 ts = td_get_sched(td);
1095 td->td_flags &= ~TDF_CANSWAP;
1096 if (ts->ts_slptime > 1) {
1102 ts->ts_slice = sched_slice;
1103 sched_add(td, SRQ_BORING);
1108 forward_wakeup(int cpunum)
1111 cpuset_t dontuse, map, map2;
1115 mtx_assert(&sched_lock, MA_OWNED);
1117 CTR0(KTR_RUNQ, "forward_wakeup()");
1119 if ((!forward_wakeup_enabled) ||
1120 (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
1122 if (!smp_started || panicstr)
1125 forward_wakeups_requested++;
1128 * Check the idle mask we received against what we calculated
1129 * before in the old version.
1131 me = PCPU_GET(cpuid);
1133 /* Don't bother if we should be doing it ourself. */
1134 if (CPU_ISSET(me, &idle_cpus_mask) &&
1135 (cpunum == NOCPU || me == cpunum))
1138 CPU_SETOF(me, &dontuse);
1139 CPU_OR(&dontuse, &stopped_cpus);
1140 CPU_OR(&dontuse, &hlt_cpus_mask);
1142 if (forward_wakeup_use_loop) {
1143 STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1145 if (!CPU_ISSET(id, &dontuse) &&
1146 pc->pc_curthread == pc->pc_idlethread) {
1152 if (forward_wakeup_use_mask) {
1153 map = idle_cpus_mask;
1154 CPU_NAND(&map, &dontuse);
1156 /* If they are both on, compare and use loop if different. */
1157 if (forward_wakeup_use_loop) {
1158 if (CPU_CMP(&map, &map2)) {
1159 printf("map != map2, loop method preferred\n");
1167 /* If we only allow a specific CPU, then mask off all the others. */
1168 if (cpunum != NOCPU) {
1169 KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
1170 iscpuset = CPU_ISSET(cpunum, &map);
1174 CPU_SETOF(cpunum, &map);
1176 if (!CPU_EMPTY(&map)) {
1177 forward_wakeups_delivered++;
1178 STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1180 if (!CPU_ISSET(id, &map))
1182 if (cpu_idle_wakeup(pc->pc_cpuid))
1185 if (!CPU_EMPTY(&map))
1186 ipi_selected(map, IPI_AST);
1189 if (cpunum == NOCPU)
1190 printf("forward_wakeup: Idle processor not found\n");
1195 kick_other_cpu(int pri, int cpuid)
1200 pcpu = pcpu_find(cpuid);
1201 if (CPU_ISSET(cpuid, &idle_cpus_mask)) {
1202 forward_wakeups_delivered++;
1203 if (!cpu_idle_wakeup(cpuid))
1204 ipi_cpu(cpuid, IPI_AST);
1208 cpri = pcpu->pc_curthread->td_priority;
1212 #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1213 #if !defined(FULL_PREEMPTION)
1214 if (pri <= PRI_MAX_ITHD)
1215 #endif /* ! FULL_PREEMPTION */
1217 ipi_cpu(cpuid, IPI_PREEMPT);
1220 #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1222 pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
1223 ipi_cpu(cpuid, IPI_AST);
1230 sched_pickcpu(struct thread *td)
1234 mtx_assert(&sched_lock, MA_OWNED);
1236 if (td->td_lastcpu != NOCPU && THREAD_CAN_SCHED(td, td->td_lastcpu))
1237 best = td->td_lastcpu;
1241 if (!THREAD_CAN_SCHED(td, cpu))
1246 else if (runq_length[cpu] < runq_length[best])
1249 KASSERT(best != NOCPU, ("no valid CPUs"));
1256 sched_add(struct thread *td, int flags)
1260 struct td_sched *ts;
1265 ts = td_get_sched(td);
1266 THREAD_LOCK_ASSERT(td, MA_OWNED);
1267 KASSERT((td->td_inhibitors == 0),
1268 ("sched_add: trying to run inhibited thread"));
1269 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1270 ("sched_add: bad thread state"));
1271 KASSERT(td->td_flags & TDF_INMEM,
1272 ("sched_add: thread swapped out"));
1274 KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
1275 "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1276 sched_tdname(curthread));
1277 KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
1278 KTR_ATTR_LINKED, sched_tdname(td));
1279 SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1280 flags & SRQ_PREEMPTED);
1284 * Now that the thread is moving to the run-queue, set the lock
1285 * to the scheduler's lock.
1287 if (td->td_lock != &sched_lock) {
1288 mtx_lock_spin(&sched_lock);
1289 thread_lock_set(td, &sched_lock);
1294 * If SMP is started and the thread is pinned or otherwise limited to
1295 * a specific set of CPUs, queue the thread to a per-CPU run queue.
1296 * Otherwise, queue the thread to the global run queue.
1298 * If SMP has not yet been started we must use the global run queue
1299 * as per-CPU state may not be initialized yet and we may crash if we
1300 * try to access the per-CPU run queues.
1302 if (smp_started && (td->td_pinned != 0 || td->td_flags & TDF_BOUND ||
1303 ts->ts_flags & TSF_AFFINITY)) {
1304 if (td->td_pinned != 0)
1305 cpu = td->td_lastcpu;
1306 else if (td->td_flags & TDF_BOUND) {
1307 /* Find CPU from bound runq. */
1308 KASSERT(SKE_RUNQ_PCPU(ts),
1309 ("sched_add: bound td_sched not on cpu runq"));
1310 cpu = ts->ts_runq - &runq_pcpu[0];
1312 /* Find a valid CPU for our cpuset */
1313 cpu = sched_pickcpu(td);
1314 ts->ts_runq = &runq_pcpu[cpu];
1317 "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td,
1321 "sched_add: adding td_sched:%p (td:%p) to gbl runq", ts,
1324 ts->ts_runq = &runq;
1327 if ((td->td_flags & TDF_NOLOAD) == 0)
1329 runq_add(ts->ts_runq, td, flags);
1333 cpuid = PCPU_GET(cpuid);
1334 if (single_cpu && cpu != cpuid) {
1335 kick_other_cpu(td->td_priority, cpu);
1338 tidlemsk = idle_cpus_mask;
1339 CPU_NAND(&tidlemsk, &hlt_cpus_mask);
1340 CPU_CLR(cpuid, &tidlemsk);
1342 if (!CPU_ISSET(cpuid, &idle_cpus_mask) &&
1343 ((flags & SRQ_INTR) == 0) &&
1344 !CPU_EMPTY(&tidlemsk))
1345 forwarded = forward_wakeup(cpu);
1349 if (!maybe_preempt(td))
1356 struct td_sched *ts;
1358 ts = td_get_sched(td);
1359 THREAD_LOCK_ASSERT(td, MA_OWNED);
1360 KASSERT((td->td_inhibitors == 0),
1361 ("sched_add: trying to run inhibited thread"));
1362 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1363 ("sched_add: bad thread state"));
1364 KASSERT(td->td_flags & TDF_INMEM,
1365 ("sched_add: thread swapped out"));
1366 KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
1367 "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1368 sched_tdname(curthread));
1369 KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
1370 KTR_ATTR_LINKED, sched_tdname(td));
1371 SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1372 flags & SRQ_PREEMPTED);
1375 * Now that the thread is moving to the run-queue, set the lock
1376 * to the scheduler's lock.
1378 if (td->td_lock != &sched_lock) {
1379 mtx_lock_spin(&sched_lock);
1380 thread_lock_set(td, &sched_lock);
1383 CTR2(KTR_RUNQ, "sched_add: adding td_sched:%p (td:%p) to runq", ts, td);
1384 ts->ts_runq = &runq;
1386 if ((td->td_flags & TDF_NOLOAD) == 0)
1388 runq_add(ts->ts_runq, td, flags);
1389 if (!maybe_preempt(td))
1395 sched_rem(struct thread *td)
1397 struct td_sched *ts;
1399 ts = td_get_sched(td);
1400 KASSERT(td->td_flags & TDF_INMEM,
1401 ("sched_rem: thread swapped out"));
1402 KASSERT(TD_ON_RUNQ(td),
1403 ("sched_rem: thread not on run queue"));
1404 mtx_assert(&sched_lock, MA_OWNED);
1405 KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
1406 "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1407 sched_tdname(curthread));
1408 SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
1410 if ((td->td_flags & TDF_NOLOAD) == 0)
1413 if (ts->ts_runq != &runq)
1414 runq_length[ts->ts_runq - runq_pcpu]--;
1416 runq_remove(ts->ts_runq, td);
1421 * Select threads to run. Note that running threads still consume a
1430 mtx_assert(&sched_lock, MA_OWNED);
1432 struct thread *tdcpu;
1435 td = runq_choose_fuzz(&runq, runq_fuzz);
1436 tdcpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1440 tdcpu->td_priority < td->td_priority)) {
1441 CTR2(KTR_RUNQ, "choosing td %p from pcpu runq %d", tdcpu,
1444 rq = &runq_pcpu[PCPU_GET(cpuid)];
1446 CTR1(KTR_RUNQ, "choosing td_sched %p from main runq", td);
1451 td = runq_choose(&runq);
1457 runq_length[PCPU_GET(cpuid)]--;
1459 runq_remove(rq, td);
1460 td->td_flags |= TDF_DIDRUN;
1462 KASSERT(td->td_flags & TDF_INMEM,
1463 ("sched_choose: thread swapped out"));
1466 return (PCPU_GET(idlethread));
1470 sched_preempt(struct thread *td)
1473 SDT_PROBE2(sched, , , surrender, td, td->td_proc);
1475 if (td->td_critnest > 1)
1476 td->td_owepreempt = 1;
1478 mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, NULL);
1483 sched_userret(struct thread *td)
1486 * XXX we cheat slightly on the locking here to avoid locking in
1487 * the usual case. Setting td_priority here is essentially an
1488 * incomplete workaround for not setting it properly elsewhere.
1489 * Now that some interrupt handlers are threads, not setting it
1490 * properly elsewhere can clobber it in the window between setting
1491 * it here and returning to user mode, so don't waste time setting
1492 * it perfectly here.
1494 KASSERT((td->td_flags & TDF_BORROWING) == 0,
1495 ("thread with borrowed priority returning to userland"));
1496 if (td->td_priority != td->td_user_pri) {
1498 td->td_priority = td->td_user_pri;
1499 td->td_base_pri = td->td_user_pri;
1505 sched_bind(struct thread *td, int cpu)
1507 struct td_sched *ts;
1509 THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
1510 KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
1512 ts = td_get_sched(td);
1514 td->td_flags |= TDF_BOUND;
1516 ts->ts_runq = &runq_pcpu[cpu];
1517 if (PCPU_GET(cpuid) == cpu)
1520 mi_switch(SW_VOL, NULL);
1525 sched_unbind(struct thread* td)
1527 THREAD_LOCK_ASSERT(td, MA_OWNED);
1528 KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
1529 td->td_flags &= ~TDF_BOUND;
1533 sched_is_bound(struct thread *td)
1535 THREAD_LOCK_ASSERT(td, MA_OWNED);
1536 return (td->td_flags & TDF_BOUND);
1540 sched_relinquish(struct thread *td)
1543 mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
1550 return (sched_tdcnt);
1554 sched_sizeof_proc(void)
1556 return (sizeof(struct proc));
1560 sched_sizeof_thread(void)
1562 return (sizeof(struct thread) + sizeof(struct td_sched));
1566 sched_pctcpu(struct thread *td)
1568 struct td_sched *ts;
1570 THREAD_LOCK_ASSERT(td, MA_OWNED);
1571 ts = td_get_sched(td);
1572 return (ts->ts_pctcpu);
1577 * Calculates the contribution to the thread cpu usage for the latest
1578 * (unfinished) second.
1581 sched_pctcpu_delta(struct thread *td)
1583 struct td_sched *ts;
1587 THREAD_LOCK_ASSERT(td, MA_OWNED);
1588 ts = td_get_sched(td);
1590 realstathz = stathz ? stathz : hz;
1591 if (ts->ts_cpticks != 0) {
1592 #if (FSHIFT >= CCPU_SHIFT)
1593 delta = (realstathz == 100)
1594 ? ((fixpt_t) ts->ts_cpticks) <<
1595 (FSHIFT - CCPU_SHIFT) :
1596 100 * (((fixpt_t) ts->ts_cpticks)
1597 << (FSHIFT - CCPU_SHIFT)) / realstathz;
1599 delta = ((FSCALE - ccpu) *
1601 FSCALE / realstathz)) >> FSHIFT;
1610 sched_estcpu(struct thread *td)
1613 return (td_get_sched(td)->ts_estcpu);
1617 * The actual idle process.
1620 sched_idletd(void *dummy)
1622 struct pcpuidlestat *stat;
1624 THREAD_NO_SLEEPING();
1625 stat = DPCPU_PTR(idlestat);
1627 mtx_assert(&Giant, MA_NOTOWNED);
1629 while (sched_runnable() == 0) {
1630 cpu_idle(stat->idlecalls + stat->oldidlecalls > 64);
1634 mtx_lock_spin(&sched_lock);
1635 mi_switch(SW_VOL | SWT_IDLE, NULL);
1636 mtx_unlock_spin(&sched_lock);
1641 * A CPU is entering for the first time or a thread is exiting.
1644 sched_throw(struct thread *td)
1647 * Correct spinlock nesting. The idle thread context that we are
1648 * borrowing was created so that it would start out with a single
1649 * spin lock (sched_lock) held in fork_trampoline(). Since we've
1650 * explicitly acquired locks in this function, the nesting count
1651 * is now 2 rather than 1. Since we are nested, calling
1652 * spinlock_exit() will simply adjust the counts without allowing
1653 * spin lock using code to interrupt us.
1656 mtx_lock_spin(&sched_lock);
1658 PCPU_SET(switchtime, cpu_ticks());
1659 PCPU_SET(switchticks, ticks);
1661 lock_profile_release_lock(&sched_lock.lock_object);
1662 MPASS(td->td_lock == &sched_lock);
1663 td->td_lastcpu = td->td_oncpu;
1664 td->td_oncpu = NOCPU;
1666 mtx_assert(&sched_lock, MA_OWNED);
1667 KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
1668 cpu_throw(td, choosethread()); /* doesn't return */
1672 sched_fork_exit(struct thread *td)
1676 * Finish setting up thread glue so that it begins execution in a
1677 * non-nested critical section with sched_lock held but not recursed.
1679 td->td_oncpu = PCPU_GET(cpuid);
1680 sched_lock.mtx_lock = (uintptr_t)td;
1681 lock_profile_obtain_lock_success(&sched_lock.lock_object,
1682 0, 0, __FILE__, __LINE__);
1683 THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
1685 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
1686 "prio:%d", td->td_priority);
1687 SDT_PROBE0(sched, , , on__cpu);
1691 sched_tdname(struct thread *td)
1694 struct td_sched *ts;
1696 ts = td_get_sched(td);
1697 if (ts->ts_name[0] == '\0')
1698 snprintf(ts->ts_name, sizeof(ts->ts_name),
1699 "%s tid %d", td->td_name, td->td_tid);
1700 return (ts->ts_name);
1702 return (td->td_name);
1708 sched_clear_tdname(struct thread *td)
1710 struct td_sched *ts;
1712 ts = td_get_sched(td);
1713 ts->ts_name[0] = '\0';
1718 sched_affinity(struct thread *td)
1721 struct td_sched *ts;
1724 THREAD_LOCK_ASSERT(td, MA_OWNED);
1727 * Set the TSF_AFFINITY flag if there is at least one CPU this
1728 * thread can't run on.
1730 ts = td_get_sched(td);
1731 ts->ts_flags &= ~TSF_AFFINITY;
1733 if (!THREAD_CAN_SCHED(td, cpu)) {
1734 ts->ts_flags |= TSF_AFFINITY;
1740 * If this thread can run on all CPUs, nothing else to do.
1742 if (!(ts->ts_flags & TSF_AFFINITY))
1745 /* Pinned threads and bound threads should be left alone. */
1746 if (td->td_pinned != 0 || td->td_flags & TDF_BOUND)
1749 switch (td->td_state) {
1752 * If we are on a per-CPU runqueue that is in the set,
1753 * then nothing needs to be done.
1755 if (ts->ts_runq != &runq &&
1756 THREAD_CAN_SCHED(td, ts->ts_runq - runq_pcpu))
1759 /* Put this thread on a valid per-CPU runqueue. */
1761 sched_add(td, SRQ_BORING);
1765 * See if our current CPU is in the set. If not, force a
1768 if (THREAD_CAN_SCHED(td, td->td_oncpu))
1771 td->td_flags |= TDF_NEEDRESCHED;
1772 if (td != curthread)
1773 ipi_cpu(cpu, IPI_AST);