2 * Copyright (c) 1982, 1986, 1990, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
38 #include "opt_hwpmc_hooks.h"
39 #include "opt_sched.h"
40 #include "opt_kdtrace.h"
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/cpuset.h>
45 #include <sys/kernel.h>
48 #include <sys/kthread.h>
49 #include <sys/mutex.h>
51 #include <sys/resourcevar.h>
52 #include <sys/sched.h>
55 #include <sys/sysctl.h>
57 #include <sys/turnstile.h>
59 #include <machine/pcb.h>
60 #include <machine/smp.h>
63 #include <sys/pmckern.h>
67 #include <sys/dtrace_bsd.h>
68 int dtrace_vtime_active;
69 dtrace_vtime_switch_func_t dtrace_vtime_switch_func;
73 * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
74 * the range 100-256 Hz (approximately).
76 #define ESTCPULIM(e) \
77 min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
78 RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
80 #define INVERSE_ESTCPU_WEIGHT (8 * smp_cpus)
82 #define INVERSE_ESTCPU_WEIGHT 8 /* 1 / (priorities per estcpu level). */
84 #define NICE_WEIGHT 1 /* Priorities per nice level. */
86 #define TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
89 * The schedulable entity that runs a context.
90 * This is an extension to the thread structure and is tailored to
91 * the requirements of this scheduler
94 fixpt_t ts_pctcpu; /* (j) %cpu during p_swtime. */
95 int ts_cpticks; /* (j) Ticks of cpu time. */
96 int ts_slptime; /* (j) Seconds !RUNNING. */
97 int ts_slice; /* Remaining part of time slice. */
99 struct runq *ts_runq; /* runq the thread is currently on */
101 char ts_name[TS_NAME_LEN];
105 /* flags kept in td_flags */
106 #define TDF_DIDRUN TDF_SCHED0 /* thread actually ran. */
107 #define TDF_BOUND TDF_SCHED1 /* Bound to one CPU. */
108 #define TDF_SLICEEND TDF_SCHED2 /* Thread time slice is over. */
110 /* flags kept in ts_flags */
111 #define TSF_AFFINITY 0x0001 /* Has a non-"full" CPU set. */
113 #define SKE_RUNQ_PCPU(ts) \
114 ((ts)->ts_runq != 0 && (ts)->ts_runq != &runq)
116 #define THREAD_CAN_SCHED(td, cpu) \
117 CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
119 static struct td_sched td_sched0;
120 struct mtx sched_lock;
122 static int realstathz = 127; /* stathz is sometimes 0 and run off of hz. */
123 static int sched_tdcnt; /* Total runnable threads in the system. */
124 static int sched_slice = 12; /* Thread run time before rescheduling. */
126 static void setup_runqs(void);
127 static void schedcpu(void);
128 static void schedcpu_thread(void);
129 static void sched_priority(struct thread *td, u_char prio);
130 static void sched_setup(void *dummy);
131 static void maybe_resched(struct thread *td);
132 static void updatepri(struct thread *td);
133 static void resetpriority(struct thread *td);
134 static void resetpriority_thread(struct thread *td);
136 static int sched_pickcpu(struct thread *td);
137 static int forward_wakeup(int cpunum);
138 static void kick_other_cpu(int pri, int cpuid);
141 static struct kproc_desc sched_kp = {
146 SYSINIT(schedcpu, SI_SUB_LAST, SI_ORDER_FIRST, kproc_start,
148 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
150 static void sched_initticks(void *dummy);
151 SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
157 static struct runq runq;
163 static struct runq runq_pcpu[MAXCPU];
164 long runq_length[MAXCPU];
166 static cpuset_t idle_cpus_mask;
169 struct pcpuidlestat {
173 static DPCPU_DEFINE(struct pcpuidlestat, idlestat);
181 for (i = 0; i < MAXCPU; ++i)
182 runq_init(&runq_pcpu[i]);
189 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
191 int error, new_val, period;
193 period = 1000000 / realstathz;
194 new_val = period * sched_slice;
195 error = sysctl_handle_int(oidp, &new_val, 0, req);
196 if (error != 0 || req->newptr == NULL)
200 sched_slice = imax(1, (new_val + period / 2) / period);
201 hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
206 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "Scheduler");
208 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
210 SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
211 NULL, 0, sysctl_kern_quantum, "I",
212 "Quantum for timeshare threads in microseconds");
213 SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
214 "Quantum for timeshare threads in stathz ticks");
216 /* Enable forwarding of wakeups to all other cpus */
217 static SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup, CTLFLAG_RD, NULL,
220 static int runq_fuzz = 1;
221 SYSCTL_INT(_kern_sched, OID_AUTO, runq_fuzz, CTLFLAG_RW, &runq_fuzz, 0, "");
223 static int forward_wakeup_enabled = 1;
224 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
225 &forward_wakeup_enabled, 0,
226 "Forwarding of wakeup to idle CPUs");
228 static int forward_wakeups_requested = 0;
229 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
230 &forward_wakeups_requested, 0,
231 "Requests for Forwarding of wakeup to idle CPUs");
233 static int forward_wakeups_delivered = 0;
234 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
235 &forward_wakeups_delivered, 0,
236 "Completed Forwarding of wakeup to idle CPUs");
238 static int forward_wakeup_use_mask = 1;
239 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
240 &forward_wakeup_use_mask, 0,
241 "Use the mask of idle cpus");
243 static int forward_wakeup_use_loop = 0;
244 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
245 &forward_wakeup_use_loop, 0,
246 "Use a loop to find idle cpus");
250 static int sched_followon = 0;
251 SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
253 "allow threads to share a quantum");
256 SDT_PROVIDER_DEFINE(sched);
258 SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
259 "struct proc *", "uint8_t");
260 SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
261 "struct proc *", "void *");
262 SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
263 "struct proc *", "void *", "int");
264 SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
265 "struct proc *", "uint8_t", "struct thread *");
266 SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
267 SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
269 SDT_PROBE_DEFINE(sched, , , on__cpu);
270 SDT_PROBE_DEFINE(sched, , , remain__cpu);
271 SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
279 KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
280 SDT_PROBE2(sched, , , load__change, NOCPU, sched_tdcnt);
288 KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
289 SDT_PROBE2(sched, , , load__change, NOCPU, sched_tdcnt);
292 * Arrange to reschedule if necessary, taking the priorities and
293 * schedulers into account.
296 maybe_resched(struct thread *td)
299 THREAD_LOCK_ASSERT(td, MA_OWNED);
300 if (td->td_priority < curthread->td_priority)
301 curthread->td_flags |= TDF_NEEDRESCHED;
305 * This function is called when a thread is about to be put on run queue
306 * because it has been made runnable or its priority has been adjusted. It
307 * determines if the new thread should be immediately preempted to. If so,
308 * it switches to it and eventually returns true. If not, it returns false
309 * so that the caller may place the thread on an appropriate run queue.
312 maybe_preempt(struct thread *td)
319 * The new thread should not preempt the current thread if any of the
320 * following conditions are true:
322 * - The kernel is in the throes of crashing (panicstr).
323 * - The current thread has a higher (numerically lower) or
324 * equivalent priority. Note that this prevents curthread from
325 * trying to preempt to itself.
326 * - It is too early in the boot for context switches (cold is set).
327 * - The current thread has an inhibitor set or is in the process of
328 * exiting. In this case, the current thread is about to switch
329 * out anyways, so there's no point in preempting. If we did,
330 * the current thread would not be properly resumed as well, so
331 * just avoid that whole landmine.
332 * - If the new thread's priority is not a realtime priority and
333 * the current thread's priority is not an idle priority and
334 * FULL_PREEMPTION is disabled.
336 * If all of these conditions are false, but the current thread is in
337 * a nested critical section, then we have to defer the preemption
338 * until we exit the critical section. Otherwise, switch immediately
342 THREAD_LOCK_ASSERT(td, MA_OWNED);
343 KASSERT((td->td_inhibitors == 0),
344 ("maybe_preempt: trying to run inhibited thread"));
345 pri = td->td_priority;
346 cpri = ctd->td_priority;
347 if (panicstr != NULL || pri >= cpri || cold /* || dumping */ ||
348 TD_IS_INHIBITED(ctd))
350 #ifndef FULL_PREEMPTION
351 if (pri > PRI_MAX_ITHD && cpri < PRI_MIN_IDLE)
355 if (ctd->td_critnest > 1) {
356 CTR1(KTR_PROC, "maybe_preempt: in critical section %d",
358 ctd->td_owepreempt = 1;
362 * Thread is runnable but not yet put on system run queue.
364 MPASS(ctd->td_lock == td->td_lock);
365 MPASS(TD_ON_RUNQ(td));
367 CTR3(KTR_PROC, "preempting to thread %p (pid %d, %s)\n", td,
368 td->td_proc->p_pid, td->td_name);
369 mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, td);
371 * td's lock pointer may have changed. We have to return with it
385 * Constants for digital decay and forget:
386 * 90% of (td_estcpu) usage in 5 * loadav time
387 * 95% of (ts_pctcpu) usage in 60 seconds (load insensitive)
388 * Note that, as ps(1) mentions, this can let percentages
389 * total over 100% (I've seen 137.9% for 3 processes).
391 * Note that schedclock() updates td_estcpu and p_cpticks asynchronously.
393 * We wish to decay away 90% of td_estcpu in (5 * loadavg) seconds.
394 * That is, the system wants to compute a value of decay such
395 * that the following for loop:
396 * for (i = 0; i < (5 * loadavg); i++)
397 * td_estcpu *= decay;
400 * for all values of loadavg:
402 * Mathematically this loop can be expressed by saying:
403 * decay ** (5 * loadavg) ~= .1
405 * The system computes decay as:
406 * decay = (2 * loadavg) / (2 * loadavg + 1)
408 * We wish to prove that the system's computation of decay
409 * will always fulfill the equation:
410 * decay ** (5 * loadavg) ~= .1
412 * If we compute b as:
415 * decay = b / (b + 1)
417 * We now need to prove two things:
418 * 1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
419 * 2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
422 * For x close to zero, exp(x) =~ 1 + x, since
423 * exp(x) = 0! + x**1/1! + x**2/2! + ... .
424 * therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
425 * For x close to zero, ln(1+x) =~ x, since
426 * ln(1+x) = x - x**2/2 + x**3/3 - ... -1 < x < 1
427 * therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
431 * Solve (factor)**(power) =~ .1 given power (5*loadav):
432 * solving for factor,
433 * ln(factor) =~ (-2.30/5*loadav), or
434 * factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
435 * exp(-1/b) =~ (b-1)/b =~ b/(b+1). QED
438 * Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
440 * power*ln(b/(b+1)) =~ -2.30, or
441 * power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav. QED
443 * Actual power values for the implemented algorithm are as follows:
445 * power: 5.68 10.32 14.94 19.55
448 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
449 #define loadfactor(loadav) (2 * (loadav))
450 #define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
452 /* decay 95% of `ts_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
453 static fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
454 SYSCTL_UINT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
457 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
458 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
459 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
461 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
462 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
464 * If you don't want to bother with the faster/more-accurate formula, you
465 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
466 * (more general) method of calculating the %age of CPU used by a process.
468 #define CCPU_SHIFT 11
471 * Recompute process priorities, every hz ticks.
472 * MP-safe, called without the Giant mutex.
478 register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
484 sx_slock(&allproc_lock);
485 FOREACH_PROC_IN_SYSTEM(p) {
487 if (p->p_state == PRS_NEW) {
491 FOREACH_THREAD_IN_PROC(p, td) {
496 * Increment sleep time (if sleeping). We
497 * ignore overflow, as above.
500 * The td_sched slptimes are not touched in wakeup
501 * because the thread may not HAVE everything in
502 * memory? XXX I think this is out of date.
504 if (TD_ON_RUNQ(td)) {
506 td->td_flags &= ~TDF_DIDRUN;
507 } else if (TD_IS_RUNNING(td)) {
509 /* Do not clear TDF_DIDRUN */
510 } else if (td->td_flags & TDF_DIDRUN) {
512 td->td_flags &= ~TDF_DIDRUN;
516 * ts_pctcpu is only for ps and ttyinfo().
518 ts->ts_pctcpu = (ts->ts_pctcpu * ccpu) >> FSHIFT;
520 * If the td_sched has been idle the entire second,
521 * stop recalculating its priority until
524 if (ts->ts_cpticks != 0) {
525 #if (FSHIFT >= CCPU_SHIFT)
526 ts->ts_pctcpu += (realstathz == 100)
527 ? ((fixpt_t) ts->ts_cpticks) <<
528 (FSHIFT - CCPU_SHIFT) :
529 100 * (((fixpt_t) ts->ts_cpticks)
530 << (FSHIFT - CCPU_SHIFT)) / realstathz;
532 ts->ts_pctcpu += ((FSCALE - ccpu) *
534 FSCALE / realstathz)) >> FSHIFT;
539 * If there are ANY running threads in this process,
540 * then don't count it as sleeping.
541 * XXX: this is broken.
544 if (ts->ts_slptime > 1) {
546 * In an ideal world, this should not
547 * happen, because whoever woke us
548 * up from the long sleep should have
549 * unwound the slptime and reset our
550 * priority before we run at the stale
551 * priority. Should KASSERT at some
552 * point when all the cases are fixed.
559 if (ts->ts_slptime > 1) {
563 td->td_estcpu = decay_cpu(loadfac, td->td_estcpu);
565 resetpriority_thread(td);
570 sx_sunlock(&allproc_lock);
574 * Main loop for a kthread that executes schedcpu once a second.
577 schedcpu_thread(void)
587 * Recalculate the priority of a process after it has slept for a while.
588 * For all load averages >= 1 and max td_estcpu of 255, sleeping for at
589 * least six times the loadfactor will decay td_estcpu to zero.
592 updatepri(struct thread *td)
599 loadfac = loadfactor(averunnable.ldavg[0]);
600 if (ts->ts_slptime > 5 * loadfac)
603 newcpu = td->td_estcpu;
604 ts->ts_slptime--; /* was incremented in schedcpu() */
605 while (newcpu && --ts->ts_slptime)
606 newcpu = decay_cpu(loadfac, newcpu);
607 td->td_estcpu = newcpu;
612 * Compute the priority of a process when running in user mode.
613 * Arrange to reschedule if the resulting priority is better
614 * than that of the current process.
617 resetpriority(struct thread *td)
619 register unsigned int newpriority;
621 if (td->td_pri_class == PRI_TIMESHARE) {
622 newpriority = PUSER + td->td_estcpu / INVERSE_ESTCPU_WEIGHT +
623 NICE_WEIGHT * (td->td_proc->p_nice - PRIO_MIN);
624 newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
626 sched_user_prio(td, newpriority);
631 * Update the thread's priority when the associated process's user
635 resetpriority_thread(struct thread *td)
638 /* Only change threads with a time sharing user priority. */
639 if (td->td_priority < PRI_MIN_TIMESHARE ||
640 td->td_priority > PRI_MAX_TIMESHARE)
643 /* XXX the whole needresched thing is broken, but not silly. */
646 sched_prio(td, td->td_user_pri);
651 sched_setup(void *dummy)
656 /* Account for thread0. */
661 * This routine determines time constants after stathz and hz are setup.
664 sched_initticks(void *dummy)
667 realstathz = stathz ? stathz : hz;
668 sched_slice = realstathz / 10; /* ~100ms */
669 hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
673 /* External interfaces start here */
676 * Very early in the boot some setup of scheduler-specific
677 * parts of proc0 and of some scheduler resources needs to be done.
685 * Set up the scheduler specific parts of proc0.
687 proc0.p_sched = NULL; /* XXX */
688 thread0.td_sched = &td_sched0;
689 thread0.td_lock = &sched_lock;
690 td_sched0.ts_slice = sched_slice;
691 mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
698 return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
700 return runq_check(&runq);
705 sched_rr_interval(void)
708 /* Convert sched_slice from stathz to hz. */
709 return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
713 * We adjust the priority of the current process. The priority of
714 * a process gets worse as it accumulates CPU time. The cpu usage
715 * estimator (td_estcpu) is increased here. resetpriority() will
716 * compute a different priority each time td_estcpu increases by
717 * INVERSE_ESTCPU_WEIGHT
718 * (until MAXPRI is reached). The cpu usage estimator ramps up
719 * quite quickly when the process is running (linearly), and decays
720 * away exponentially, at a rate which is proportionally slower when
721 * the system is busy. The basic principle is that the system will
722 * 90% forget that the process used a lot of CPU time in 5 * loadav
723 * seconds. This causes the system to favor processes which haven't
724 * run much recently, and to round-robin among other processes.
727 sched_clock(struct thread *td)
729 struct pcpuidlestat *stat;
732 THREAD_LOCK_ASSERT(td, MA_OWNED);
736 td->td_estcpu = ESTCPULIM(td->td_estcpu + 1);
737 if ((td->td_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
739 resetpriority_thread(td);
743 * Force a context switch if the current thread has used up a full
744 * time slice (default is 100ms).
746 if (!TD_IS_IDLETHREAD(td) && --ts->ts_slice <= 0) {
747 ts->ts_slice = sched_slice;
748 td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
751 stat = DPCPU_PTR(idlestat);
752 stat->oldidlecalls = stat->idlecalls;
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->td_estcpu = ESTCPULIM(td->td_estcpu + child->td_estcpu);
780 if ((child->td_flags & TDF_NOLOAD) == 0)
782 thread_unlock(child);
786 sched_fork(struct thread *td, struct thread *childtd)
788 sched_fork_thread(td, childtd);
792 sched_fork_thread(struct thread *td, struct thread *childtd)
796 childtd->td_oncpu = NOCPU;
797 childtd->td_lastcpu = NOCPU;
798 childtd->td_estcpu = td->td_estcpu;
799 childtd->td_lock = &sched_lock;
800 childtd->td_cpuset = cpuset_ref(td->td_cpuset);
801 childtd->td_priority = childtd->td_base_pri;
802 ts = childtd->td_sched;
803 bzero(ts, sizeof(*ts));
804 ts->ts_flags |= (td->td_sched->ts_flags & TSF_AFFINITY);
809 sched_nice(struct proc *p, int nice)
813 PROC_LOCK_ASSERT(p, MA_OWNED);
815 FOREACH_THREAD_IN_PROC(p, td) {
818 resetpriority_thread(td);
824 sched_class(struct thread *td, int class)
826 THREAD_LOCK_ASSERT(td, MA_OWNED);
827 td->td_pri_class = class;
831 * Adjust the priority of a thread.
834 sched_priority(struct thread *td, u_char prio)
838 KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "priority change",
839 "prio:%d", td->td_priority, "new prio:%d", prio, KTR_ATTR_LINKED,
840 sched_tdname(curthread));
841 SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
842 if (td != curthread && prio > td->td_priority) {
843 KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
844 "lend prio", "prio:%d", td->td_priority, "new prio:%d",
845 prio, KTR_ATTR_LINKED, sched_tdname(td));
846 SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
849 THREAD_LOCK_ASSERT(td, MA_OWNED);
850 if (td->td_priority == prio)
852 td->td_priority = prio;
853 if (TD_ON_RUNQ(td) && td->td_rqindex != (prio / RQ_PPQ)) {
855 sched_add(td, SRQ_BORING);
860 * Update a thread's priority when it is lent another thread's
864 sched_lend_prio(struct thread *td, u_char prio)
867 td->td_flags |= TDF_BORROWING;
868 sched_priority(td, prio);
872 * Restore a thread's priority when priority propagation is
873 * over. The prio argument is the minimum priority the thread
874 * needs to have to satisfy other possible priority lending
875 * requests. If the thread's regulary priority is less
876 * important than prio the thread will keep a priority boost
880 sched_unlend_prio(struct thread *td, u_char prio)
884 if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
885 td->td_base_pri <= PRI_MAX_TIMESHARE)
886 base_pri = td->td_user_pri;
888 base_pri = td->td_base_pri;
889 if (prio >= base_pri) {
890 td->td_flags &= ~TDF_BORROWING;
891 sched_prio(td, base_pri);
893 sched_lend_prio(td, prio);
897 sched_prio(struct thread *td, u_char prio)
901 /* First, update the base priority. */
902 td->td_base_pri = prio;
905 * If the thread is borrowing another thread's priority, don't ever
906 * lower the priority.
908 if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
911 /* Change the real priority. */
912 oldprio = td->td_priority;
913 sched_priority(td, prio);
916 * If the thread is on a turnstile, then let the turnstile update
919 if (TD_ON_LOCK(td) && oldprio != prio)
920 turnstile_adjust(td, oldprio);
924 sched_user_prio(struct thread *td, u_char prio)
927 THREAD_LOCK_ASSERT(td, MA_OWNED);
928 td->td_base_user_pri = prio;
929 if (td->td_lend_user_pri <= prio)
931 td->td_user_pri = prio;
935 sched_lend_user_prio(struct thread *td, u_char prio)
938 THREAD_LOCK_ASSERT(td, MA_OWNED);
939 td->td_lend_user_pri = prio;
940 td->td_user_pri = min(prio, td->td_base_user_pri);
941 if (td->td_priority > td->td_user_pri)
942 sched_prio(td, td->td_user_pri);
943 else if (td->td_priority != td->td_user_pri)
944 td->td_flags |= TDF_NEEDRESCHED;
948 sched_sleep(struct thread *td, int pri)
951 THREAD_LOCK_ASSERT(td, MA_OWNED);
952 td->td_slptick = ticks;
953 td->td_sched->ts_slptime = 0;
954 if (pri != 0 && PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
956 if (TD_IS_SUSPENDED(td) || pri >= PSOCK)
957 td->td_flags |= TDF_CANSWAP;
961 sched_switch(struct thread *td, struct thread *newtd, int flags)
972 THREAD_LOCK_ASSERT(td, MA_OWNED);
975 * Switch to the sched lock to fix things up and pick
977 * Block the td_lock in order to avoid breaking the critical path.
979 if (td->td_lock != &sched_lock) {
980 mtx_lock_spin(&sched_lock);
981 tmtx = thread_lock_block(td);
984 if ((td->td_flags & TDF_NOLOAD) == 0)
987 td->td_lastcpu = td->td_oncpu;
988 preempted = !((td->td_flags & TDF_SLICEEND) ||
989 (flags & SWT_RELINQUISH));
990 td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
991 td->td_owepreempt = 0;
992 td->td_oncpu = NOCPU;
995 * At the last moment, if this thread is still marked RUNNING,
996 * then put it back on the run queue as it has not been suspended
997 * or stopped or any thing else similar. We never put the idle
998 * threads on the run queue, however.
1000 if (td->td_flags & TDF_IDLETD) {
1003 CPU_CLR(PCPU_GET(cpuid), &idle_cpus_mask);
1006 if (TD_IS_RUNNING(td)) {
1007 /* Put us back on the run queue. */
1008 sched_add(td, preempted ?
1009 SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1010 SRQ_OURSELF|SRQ_YIELDING);
1015 * The thread we are about to run needs to be counted
1016 * as if it had been added to the run queue and selected.
1022 KASSERT((newtd->td_inhibitors == 0),
1023 ("trying to run inhibited thread"));
1024 newtd->td_flags |= TDF_DIDRUN;
1025 TD_SET_RUNNING(newtd);
1026 if ((newtd->td_flags & TDF_NOLOAD) == 0)
1029 newtd = choosethread();
1030 MPASS(newtd->td_lock == &sched_lock);
1035 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1036 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1039 SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
1042 lock_profile_release_lock(&sched_lock.lock_object);
1043 #ifdef KDTRACE_HOOKS
1045 * If DTrace has set the active vtime enum to anything
1046 * other than INACTIVE (0), then it should have set the
1049 if (dtrace_vtime_active)
1050 (*dtrace_vtime_switch_func)(newtd);
1053 cpu_switch(td, newtd, tmtx != NULL ? tmtx : td->td_lock);
1054 lock_profile_obtain_lock_success(&sched_lock.lock_object,
1055 0, 0, __FILE__, __LINE__);
1057 * Where am I? What year is it?
1058 * We are in the same thread that went to sleep above,
1059 * but any amount of time may have passed. All our context
1060 * will still be available as will local variables.
1061 * PCPU values however may have changed as we may have
1062 * changed CPU so don't trust cached values of them.
1063 * New threads will go to fork_exit() instead of here
1064 * so if you change things here you may need to change
1067 * If the thread above was exiting it will never wake
1068 * up again here, so either it has saved everything it
1069 * needed to, or the thread_wait() or wait() will
1073 SDT_PROBE0(sched, , , on__cpu);
1075 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1076 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1079 SDT_PROBE0(sched, , , remain__cpu);
1082 if (td->td_flags & TDF_IDLETD)
1083 CPU_SET(PCPU_GET(cpuid), &idle_cpus_mask);
1085 sched_lock.mtx_lock = (uintptr_t)td;
1086 td->td_oncpu = PCPU_GET(cpuid);
1087 MPASS(td->td_lock == &sched_lock);
1091 sched_wakeup(struct thread *td)
1093 struct td_sched *ts;
1095 THREAD_LOCK_ASSERT(td, MA_OWNED);
1097 td->td_flags &= ~TDF_CANSWAP;
1098 if (ts->ts_slptime > 1) {
1104 ts->ts_slice = sched_slice;
1105 sched_add(td, SRQ_BORING);
1110 forward_wakeup(int cpunum)
1113 cpuset_t dontuse, map, map2;
1117 mtx_assert(&sched_lock, MA_OWNED);
1119 CTR0(KTR_RUNQ, "forward_wakeup()");
1121 if ((!forward_wakeup_enabled) ||
1122 (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
1124 if (!smp_started || cold || panicstr)
1127 forward_wakeups_requested++;
1130 * Check the idle mask we received against what we calculated
1131 * before in the old version.
1133 me = PCPU_GET(cpuid);
1135 /* Don't bother if we should be doing it ourself. */
1136 if (CPU_ISSET(me, &idle_cpus_mask) &&
1137 (cpunum == NOCPU || me == cpunum))
1140 CPU_SETOF(me, &dontuse);
1141 CPU_OR(&dontuse, &stopped_cpus);
1142 CPU_OR(&dontuse, &hlt_cpus_mask);
1144 if (forward_wakeup_use_loop) {
1145 STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1147 if (!CPU_ISSET(id, &dontuse) &&
1148 pc->pc_curthread == pc->pc_idlethread) {
1154 if (forward_wakeup_use_mask) {
1155 map = idle_cpus_mask;
1156 CPU_NAND(&map, &dontuse);
1158 /* If they are both on, compare and use loop if different. */
1159 if (forward_wakeup_use_loop) {
1160 if (CPU_CMP(&map, &map2)) {
1161 printf("map != map2, loop method preferred\n");
1169 /* If we only allow a specific CPU, then mask off all the others. */
1170 if (cpunum != NOCPU) {
1171 KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
1172 iscpuset = CPU_ISSET(cpunum, &map);
1176 CPU_SETOF(cpunum, &map);
1178 if (!CPU_EMPTY(&map)) {
1179 forward_wakeups_delivered++;
1180 STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1182 if (!CPU_ISSET(id, &map))
1184 if (cpu_idle_wakeup(pc->pc_cpuid))
1187 if (!CPU_EMPTY(&map))
1188 ipi_selected(map, IPI_AST);
1191 if (cpunum == NOCPU)
1192 printf("forward_wakeup: Idle processor not found\n");
1197 kick_other_cpu(int pri, int cpuid)
1202 pcpu = pcpu_find(cpuid);
1203 if (CPU_ISSET(cpuid, &idle_cpus_mask)) {
1204 forward_wakeups_delivered++;
1205 if (!cpu_idle_wakeup(cpuid))
1206 ipi_cpu(cpuid, IPI_AST);
1210 cpri = pcpu->pc_curthread->td_priority;
1214 #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1215 #if !defined(FULL_PREEMPTION)
1216 if (pri <= PRI_MAX_ITHD)
1217 #endif /* ! FULL_PREEMPTION */
1219 ipi_cpu(cpuid, IPI_PREEMPT);
1222 #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1224 pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
1225 ipi_cpu(cpuid, IPI_AST);
1232 sched_pickcpu(struct thread *td)
1236 mtx_assert(&sched_lock, MA_OWNED);
1238 if (td->td_lastcpu != NOCPU && THREAD_CAN_SCHED(td, td->td_lastcpu))
1239 best = td->td_lastcpu;
1243 if (!THREAD_CAN_SCHED(td, cpu))
1248 else if (runq_length[cpu] < runq_length[best])
1251 KASSERT(best != NOCPU, ("no valid CPUs"));
1258 sched_add(struct thread *td, int flags)
1262 struct td_sched *ts;
1268 THREAD_LOCK_ASSERT(td, MA_OWNED);
1269 KASSERT((td->td_inhibitors == 0),
1270 ("sched_add: trying to run inhibited thread"));
1271 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1272 ("sched_add: bad thread state"));
1273 KASSERT(td->td_flags & TDF_INMEM,
1274 ("sched_add: thread swapped out"));
1276 KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
1277 "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1278 sched_tdname(curthread));
1279 KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
1280 KTR_ATTR_LINKED, sched_tdname(td));
1281 SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1282 flags & SRQ_PREEMPTED);
1286 * Now that the thread is moving to the run-queue, set the lock
1287 * to the scheduler's lock.
1289 if (td->td_lock != &sched_lock) {
1290 mtx_lock_spin(&sched_lock);
1291 thread_lock_set(td, &sched_lock);
1296 * If SMP is started and the thread is pinned or otherwise limited to
1297 * a specific set of CPUs, queue the thread to a per-CPU run queue.
1298 * Otherwise, queue the thread to the global run queue.
1300 * If SMP has not yet been started we must use the global run queue
1301 * as per-CPU state may not be initialized yet and we may crash if we
1302 * try to access the per-CPU run queues.
1304 if (smp_started && (td->td_pinned != 0 || td->td_flags & TDF_BOUND ||
1305 ts->ts_flags & TSF_AFFINITY)) {
1306 if (td->td_pinned != 0)
1307 cpu = td->td_lastcpu;
1308 else if (td->td_flags & TDF_BOUND) {
1309 /* Find CPU from bound runq. */
1310 KASSERT(SKE_RUNQ_PCPU(ts),
1311 ("sched_add: bound td_sched not on cpu runq"));
1312 cpu = ts->ts_runq - &runq_pcpu[0];
1314 /* Find a valid CPU for our cpuset */
1315 cpu = sched_pickcpu(td);
1316 ts->ts_runq = &runq_pcpu[cpu];
1319 "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td,
1323 "sched_add: adding td_sched:%p (td:%p) to gbl runq", ts,
1326 ts->ts_runq = &runq;
1329 cpuid = PCPU_GET(cpuid);
1330 if (single_cpu && cpu != cpuid) {
1331 kick_other_cpu(td->td_priority, cpu);
1334 tidlemsk = idle_cpus_mask;
1335 CPU_NAND(&tidlemsk, &hlt_cpus_mask);
1336 CPU_CLR(cpuid, &tidlemsk);
1338 if (!CPU_ISSET(cpuid, &idle_cpus_mask) &&
1339 ((flags & SRQ_INTR) == 0) &&
1340 !CPU_EMPTY(&tidlemsk))
1341 forwarded = forward_wakeup(cpu);
1345 if ((flags & SRQ_YIELDING) == 0 && maybe_preempt(td))
1352 if ((td->td_flags & TDF_NOLOAD) == 0)
1354 runq_add(ts->ts_runq, td, flags);
1360 struct td_sched *ts;
1363 THREAD_LOCK_ASSERT(td, MA_OWNED);
1364 KASSERT((td->td_inhibitors == 0),
1365 ("sched_add: trying to run inhibited thread"));
1366 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1367 ("sched_add: bad thread state"));
1368 KASSERT(td->td_flags & TDF_INMEM,
1369 ("sched_add: thread swapped out"));
1370 KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
1371 "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1372 sched_tdname(curthread));
1373 KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
1374 KTR_ATTR_LINKED, sched_tdname(td));
1375 SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1376 flags & SRQ_PREEMPTED);
1379 * Now that the thread is moving to the run-queue, set the lock
1380 * to the scheduler's lock.
1382 if (td->td_lock != &sched_lock) {
1383 mtx_lock_spin(&sched_lock);
1384 thread_lock_set(td, &sched_lock);
1387 CTR2(KTR_RUNQ, "sched_add: adding td_sched:%p (td:%p) to runq", ts, td);
1388 ts->ts_runq = &runq;
1391 * If we are yielding (on the way out anyhow) or the thread
1392 * being saved is US, then don't try be smart about preemption
1393 * or kicking off another CPU as it won't help and may hinder.
1394 * In the YIEDLING case, we are about to run whoever is being
1395 * put in the queue anyhow, and in the OURSELF case, we are
1396 * putting ourself on the run queue which also only happens
1397 * when we are about to yield.
1399 if ((flags & SRQ_YIELDING) == 0) {
1400 if (maybe_preempt(td))
1403 if ((td->td_flags & TDF_NOLOAD) == 0)
1405 runq_add(ts->ts_runq, td, flags);
1411 sched_rem(struct thread *td)
1413 struct td_sched *ts;
1416 KASSERT(td->td_flags & TDF_INMEM,
1417 ("sched_rem: thread swapped out"));
1418 KASSERT(TD_ON_RUNQ(td),
1419 ("sched_rem: thread not on run queue"));
1420 mtx_assert(&sched_lock, MA_OWNED);
1421 KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
1422 "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1423 sched_tdname(curthread));
1424 SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
1426 if ((td->td_flags & TDF_NOLOAD) == 0)
1429 if (ts->ts_runq != &runq)
1430 runq_length[ts->ts_runq - runq_pcpu]--;
1432 runq_remove(ts->ts_runq, td);
1437 * Select threads to run. Note that running threads still consume a
1446 mtx_assert(&sched_lock, MA_OWNED);
1448 struct thread *tdcpu;
1451 td = runq_choose_fuzz(&runq, runq_fuzz);
1452 tdcpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1456 tdcpu->td_priority < td->td_priority)) {
1457 CTR2(KTR_RUNQ, "choosing td %p from pcpu runq %d", tdcpu,
1460 rq = &runq_pcpu[PCPU_GET(cpuid)];
1462 CTR1(KTR_RUNQ, "choosing td_sched %p from main runq", td);
1467 td = runq_choose(&runq);
1473 runq_length[PCPU_GET(cpuid)]--;
1475 runq_remove(rq, td);
1476 td->td_flags |= TDF_DIDRUN;
1478 KASSERT(td->td_flags & TDF_INMEM,
1479 ("sched_choose: thread swapped out"));
1482 return (PCPU_GET(idlethread));
1486 sched_preempt(struct thread *td)
1489 SDT_PROBE2(sched, , , surrender, td, td->td_proc);
1491 if (td->td_critnest > 1)
1492 td->td_owepreempt = 1;
1494 mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, NULL);
1499 sched_userret(struct thread *td)
1502 * XXX we cheat slightly on the locking here to avoid locking in
1503 * the usual case. Setting td_priority here is essentially an
1504 * incomplete workaround for not setting it properly elsewhere.
1505 * Now that some interrupt handlers are threads, not setting it
1506 * properly elsewhere can clobber it in the window between setting
1507 * it here and returning to user mode, so don't waste time setting
1508 * it perfectly here.
1510 KASSERT((td->td_flags & TDF_BORROWING) == 0,
1511 ("thread with borrowed priority returning to userland"));
1512 if (td->td_priority != td->td_user_pri) {
1514 td->td_priority = td->td_user_pri;
1515 td->td_base_pri = td->td_user_pri;
1521 sched_bind(struct thread *td, int cpu)
1523 struct td_sched *ts;
1525 THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
1526 KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
1530 td->td_flags |= TDF_BOUND;
1532 ts->ts_runq = &runq_pcpu[cpu];
1533 if (PCPU_GET(cpuid) == cpu)
1536 mi_switch(SW_VOL, NULL);
1541 sched_unbind(struct thread* td)
1543 THREAD_LOCK_ASSERT(td, MA_OWNED);
1544 KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
1545 td->td_flags &= ~TDF_BOUND;
1549 sched_is_bound(struct thread *td)
1551 THREAD_LOCK_ASSERT(td, MA_OWNED);
1552 return (td->td_flags & TDF_BOUND);
1556 sched_relinquish(struct thread *td)
1559 mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
1566 return (sched_tdcnt);
1570 sched_sizeof_proc(void)
1572 return (sizeof(struct proc));
1576 sched_sizeof_thread(void)
1578 return (sizeof(struct thread) + sizeof(struct td_sched));
1582 sched_pctcpu(struct thread *td)
1584 struct td_sched *ts;
1586 THREAD_LOCK_ASSERT(td, MA_OWNED);
1588 return (ts->ts_pctcpu);
1593 * Calculates the contribution to the thread cpu usage for the latest
1594 * (unfinished) second.
1597 sched_pctcpu_delta(struct thread *td)
1599 struct td_sched *ts;
1603 THREAD_LOCK_ASSERT(td, MA_OWNED);
1606 realstathz = stathz ? stathz : hz;
1607 if (ts->ts_cpticks != 0) {
1608 #if (FSHIFT >= CCPU_SHIFT)
1609 delta = (realstathz == 100)
1610 ? ((fixpt_t) ts->ts_cpticks) <<
1611 (FSHIFT - CCPU_SHIFT) :
1612 100 * (((fixpt_t) ts->ts_cpticks)
1613 << (FSHIFT - CCPU_SHIFT)) / realstathz;
1615 delta = ((FSCALE - ccpu) *
1617 FSCALE / realstathz)) >> FSHIFT;
1631 * The actual idle process.
1634 sched_idletd(void *dummy)
1636 struct pcpuidlestat *stat;
1638 THREAD_NO_SLEEPING();
1639 stat = DPCPU_PTR(idlestat);
1641 mtx_assert(&Giant, MA_NOTOWNED);
1643 while (sched_runnable() == 0) {
1644 cpu_idle(stat->idlecalls + stat->oldidlecalls > 64);
1648 mtx_lock_spin(&sched_lock);
1649 mi_switch(SW_VOL | SWT_IDLE, NULL);
1650 mtx_unlock_spin(&sched_lock);
1655 * A CPU is entering for the first time or a thread is exiting.
1658 sched_throw(struct thread *td)
1661 * Correct spinlock nesting. The idle thread context that we are
1662 * borrowing was created so that it would start out with a single
1663 * spin lock (sched_lock) held in fork_trampoline(). Since we've
1664 * explicitly acquired locks in this function, the nesting count
1665 * is now 2 rather than 1. Since we are nested, calling
1666 * spinlock_exit() will simply adjust the counts without allowing
1667 * spin lock using code to interrupt us.
1670 mtx_lock_spin(&sched_lock);
1672 PCPU_SET(switchtime, cpu_ticks());
1673 PCPU_SET(switchticks, ticks);
1675 lock_profile_release_lock(&sched_lock.lock_object);
1676 MPASS(td->td_lock == &sched_lock);
1677 td->td_lastcpu = td->td_oncpu;
1678 td->td_oncpu = NOCPU;
1680 mtx_assert(&sched_lock, MA_OWNED);
1681 KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
1682 cpu_throw(td, choosethread()); /* doesn't return */
1686 sched_fork_exit(struct thread *td)
1690 * Finish setting up thread glue so that it begins execution in a
1691 * non-nested critical section with sched_lock held but not recursed.
1693 td->td_oncpu = PCPU_GET(cpuid);
1694 sched_lock.mtx_lock = (uintptr_t)td;
1695 lock_profile_obtain_lock_success(&sched_lock.lock_object,
1696 0, 0, __FILE__, __LINE__);
1697 THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
1701 sched_tdname(struct thread *td)
1704 struct td_sched *ts;
1707 if (ts->ts_name[0] == '\0')
1708 snprintf(ts->ts_name, sizeof(ts->ts_name),
1709 "%s tid %d", td->td_name, td->td_tid);
1710 return (ts->ts_name);
1712 return (td->td_name);
1718 sched_clear_tdname(struct thread *td)
1720 struct td_sched *ts;
1723 ts->ts_name[0] = '\0';
1728 sched_affinity(struct thread *td)
1731 struct td_sched *ts;
1734 THREAD_LOCK_ASSERT(td, MA_OWNED);
1737 * Set the TSF_AFFINITY flag if there is at least one CPU this
1738 * thread can't run on.
1741 ts->ts_flags &= ~TSF_AFFINITY;
1743 if (!THREAD_CAN_SCHED(td, cpu)) {
1744 ts->ts_flags |= TSF_AFFINITY;
1750 * If this thread can run on all CPUs, nothing else to do.
1752 if (!(ts->ts_flags & TSF_AFFINITY))
1755 /* Pinned threads and bound threads should be left alone. */
1756 if (td->td_pinned != 0 || td->td_flags & TDF_BOUND)
1759 switch (td->td_state) {
1762 * If we are on a per-CPU runqueue that is in the set,
1763 * then nothing needs to be done.
1765 if (ts->ts_runq != &runq &&
1766 THREAD_CAN_SCHED(td, ts->ts_runq - runq_pcpu))
1769 /* Put this thread on a valid per-CPU runqueue. */
1771 sched_add(td, SRQ_BORING);
1775 * See if our current CPU is in the set. If not, force a
1778 if (THREAD_CAN_SCHED(td, td->td_oncpu))
1781 td->td_flags |= TDF_NEEDRESCHED;
1782 if (td != curthread)
1783 ipi_cpu(cpu, IPI_AST);