2 * Copyright (c) 2002-2007, Jeffrey Roberson <jeff@freebsd.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice unmodified, this list of conditions, and the following
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 * This file implements the ULE scheduler. ULE supports independent CPU
29 * run queues and fine grain locking. It has superior interactive
30 * performance under load even on uni-processor systems.
33 * ULE is the last three letters in schedule. It owes its name to a
34 * generic user created for a scheduling system by Paul Mikesell at
35 * Isilon Systems and a general lack of creativity on the part of the author.
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
41 #include "opt_hwpmc_hooks.h"
42 #include "opt_kdtrace.h"
43 #include "opt_sched.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
48 #include <sys/kernel.h>
51 #include <sys/mutex.h>
53 #include <sys/resource.h>
54 #include <sys/resourcevar.h>
55 #include <sys/sched.h>
58 #include <sys/sysctl.h>
59 #include <sys/sysproto.h>
60 #include <sys/turnstile.h>
62 #include <sys/vmmeter.h>
63 #include <sys/cpuset.h>
67 #include <sys/ktrace.h>
71 #include <sys/pmckern.h>
75 #include <sys/dtrace_bsd.h>
76 int dtrace_vtime_active;
77 dtrace_vtime_switch_func_t dtrace_vtime_switch_func;
80 #include <machine/cpu.h>
81 #include <machine/smp.h>
83 #if defined(__sparc64__) || defined(__mips__)
84 #error "This architecture is not currently compatible with ULE"
90 * Thread scheduler specific section. All fields are protected
94 struct runq *ts_runq; /* Run-queue we're queued on. */
95 short ts_flags; /* TSF_* flags. */
96 u_char ts_cpu; /* CPU that we have affinity for. */
97 int ts_rltick; /* Real last tick, for affinity. */
98 int ts_slice; /* Ticks of slice remaining. */
99 u_int ts_slptime; /* Number of ticks we vol. slept */
100 u_int ts_runtime; /* Number of ticks we were running */
101 int ts_ltick; /* Last tick that we were running on */
102 int ts_ftick; /* First tick that we were running on */
103 int ts_ticks; /* Tick count */
105 /* flags kept in ts_flags */
106 #define TSF_BOUND 0x0001 /* Thread can not migrate. */
107 #define TSF_XFERABLE 0x0002 /* Thread was added as transferable. */
109 static struct td_sched td_sched0;
111 #define THREAD_CAN_MIGRATE(td) ((td)->td_pinned == 0)
112 #define THREAD_CAN_SCHED(td, cpu) \
113 CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
116 * Cpu percentage computation macros and defines.
118 * SCHED_TICK_SECS: Number of seconds to average the cpu usage across.
119 * SCHED_TICK_TARG: Number of hz ticks to average the cpu usage across.
120 * SCHED_TICK_MAX: Maximum number of ticks before scaling back.
121 * SCHED_TICK_SHIFT: Shift factor to avoid rounding away results.
122 * SCHED_TICK_HZ: Compute the number of hz ticks for a given ticks count.
123 * SCHED_TICK_TOTAL: Gives the amount of time we've been recording ticks.
125 #define SCHED_TICK_SECS 10
126 #define SCHED_TICK_TARG (hz * SCHED_TICK_SECS)
127 #define SCHED_TICK_MAX (SCHED_TICK_TARG + hz)
128 #define SCHED_TICK_SHIFT 10
129 #define SCHED_TICK_HZ(ts) ((ts)->ts_ticks >> SCHED_TICK_SHIFT)
130 #define SCHED_TICK_TOTAL(ts) (max((ts)->ts_ltick - (ts)->ts_ftick, hz))
133 * These macros determine priorities for non-interactive threads. They are
134 * assigned a priority based on their recent cpu utilization as expressed
135 * by the ratio of ticks to the tick total. NHALF priorities at the start
136 * and end of the MIN to MAX timeshare range are only reachable with negative
137 * or positive nice respectively.
139 * PRI_RANGE: Priority range for utilization dependent priorities.
140 * PRI_NRESV: Number of nice values.
141 * PRI_TICKS: Compute a priority in PRI_RANGE from the ticks count and total.
142 * PRI_NICE: Determines the part of the priority inherited from nice.
144 #define SCHED_PRI_NRESV (PRIO_MAX - PRIO_MIN)
145 #define SCHED_PRI_NHALF (SCHED_PRI_NRESV / 2)
146 #define SCHED_PRI_MIN (PRI_MIN_TIMESHARE + SCHED_PRI_NHALF)
147 #define SCHED_PRI_MAX (PRI_MAX_TIMESHARE - SCHED_PRI_NHALF)
148 #define SCHED_PRI_RANGE (SCHED_PRI_MAX - SCHED_PRI_MIN)
149 #define SCHED_PRI_TICKS(ts) \
150 (SCHED_TICK_HZ((ts)) / \
151 (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
152 #define SCHED_PRI_NICE(nice) (nice)
155 * These determine the interactivity of a process. Interactivity differs from
156 * cpu utilization in that it expresses the voluntary time slept vs time ran
157 * while cpu utilization includes all time not running. This more accurately
158 * models the intent of the thread.
160 * SLP_RUN_MAX: Maximum amount of sleep time + run time we'll accumulate
161 * before throttling back.
162 * SLP_RUN_FORK: Maximum slp+run time to inherit at fork time.
163 * INTERACT_MAX: Maximum interactivity value. Smaller is better.
164 * INTERACT_THRESH: Threshhold for placement on the current runq.
166 #define SCHED_SLP_RUN_MAX ((hz * 5) << SCHED_TICK_SHIFT)
167 #define SCHED_SLP_RUN_FORK ((hz / 2) << SCHED_TICK_SHIFT)
168 #define SCHED_INTERACT_MAX (100)
169 #define SCHED_INTERACT_HALF (SCHED_INTERACT_MAX / 2)
170 #define SCHED_INTERACT_THRESH (30)
173 * tickincr: Converts a stathz tick into a hz domain scaled by
174 * the shift factor. Without the shift the error rate
175 * due to rounding would be unacceptably high.
176 * realstathz: stathz is sometimes 0 and run off of hz.
177 * sched_slice: Runtime of each thread before rescheduling.
178 * preempt_thresh: Priority threshold for preemption and remote IPIs.
180 static int sched_interact = SCHED_INTERACT_THRESH;
181 static int realstathz;
183 static int sched_slice = 1;
185 #ifdef FULL_PREEMPTION
186 static int preempt_thresh = PRI_MAX_IDLE;
188 static int preempt_thresh = PRI_MIN_KERN;
191 static int preempt_thresh = 0;
193 static int static_boost = PRI_MIN_TIMESHARE;
194 static int sched_idlespins = 10000;
195 static int sched_idlespinthresh = 4;
198 * tdq - per processor runqs and statistics. All fields are protected by the
199 * tdq_lock. The load and lowpri may be accessed without to avoid excess
200 * locking in sched_pickcpu();
203 /* Ordered to improve efficiency of cpu_search() and switch(). */
204 struct mtx tdq_lock; /* run queue lock. */
205 struct cpu_group *tdq_cg; /* Pointer to cpu topology. */
206 volatile int tdq_load; /* Aggregate load. */
207 int tdq_sysload; /* For loadavg, !ITHD load. */
208 int tdq_transferable; /* Transferable thread count. */
209 volatile int tdq_idlestate; /* State of the idle thread. */
210 short tdq_switchcnt; /* Switches this tick. */
211 short tdq_oldswitchcnt; /* Switches last tick. */
212 u_char tdq_lowpri; /* Lowest priority thread. */
213 u_char tdq_ipipending; /* IPI pending. */
214 u_char tdq_idx; /* Current insert index. */
215 u_char tdq_ridx; /* Current removal index. */
216 struct runq tdq_realtime; /* real-time run queue. */
217 struct runq tdq_timeshare; /* timeshare run queue. */
218 struct runq tdq_idle; /* Queue of IDLE threads. */
219 char tdq_name[sizeof("sched lock") + 6];
222 /* Idle thread states and config. */
223 #define TDQ_RUNNING 1
227 struct cpu_group *cpu_top; /* CPU topology */
229 #define SCHED_AFFINITY_DEFAULT (max(1, hz / 1000))
230 #define SCHED_AFFINITY(ts, t) ((ts)->ts_rltick > ticks - ((t) * affinity))
235 static int rebalance = 1;
236 static int balance_interval = 128; /* Default set in sched_initticks(). */
238 static int steal_htt = 1;
239 static int steal_idle = 1;
240 static int steal_thresh = 2;
243 * One thread queue per processor.
245 static struct tdq tdq_cpu[MAXCPU];
246 static struct tdq *balance_tdq;
247 static int balance_ticks;
249 #define TDQ_SELF() (&tdq_cpu[PCPU_GET(cpuid)])
250 #define TDQ_CPU(x) (&tdq_cpu[(x)])
251 #define TDQ_ID(x) ((int)((x) - tdq_cpu))
253 static struct tdq tdq_cpu;
255 #define TDQ_ID(x) (0)
256 #define TDQ_SELF() (&tdq_cpu)
257 #define TDQ_CPU(x) (&tdq_cpu)
260 #define TDQ_LOCK_ASSERT(t, type) mtx_assert(TDQ_LOCKPTR((t)), (type))
261 #define TDQ_LOCK(t) mtx_lock_spin(TDQ_LOCKPTR((t)))
262 #define TDQ_LOCK_FLAGS(t, f) mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
263 #define TDQ_UNLOCK(t) mtx_unlock_spin(TDQ_LOCKPTR((t)))
264 #define TDQ_LOCKPTR(t) (&(t)->tdq_lock)
266 static void sched_priority(struct thread *);
267 static void sched_thread_priority(struct thread *, u_char);
268 static int sched_interact_score(struct thread *);
269 static void sched_interact_update(struct thread *);
270 static void sched_interact_fork(struct thread *);
271 static void sched_pctcpu_update(struct td_sched *);
273 /* Operations on per processor queues */
274 static struct thread *tdq_choose(struct tdq *);
275 static void tdq_setup(struct tdq *);
276 static void tdq_load_add(struct tdq *, struct thread *);
277 static void tdq_load_rem(struct tdq *, struct thread *);
278 static __inline void tdq_runq_add(struct tdq *, struct thread *, int);
279 static __inline void tdq_runq_rem(struct tdq *, struct thread *);
280 static inline int sched_shouldpreempt(int, int, int);
281 void tdq_print(int cpu);
282 static void runq_print(struct runq *rq);
283 static void tdq_add(struct tdq *, struct thread *, int);
285 static int tdq_move(struct tdq *, struct tdq *);
286 static int tdq_idled(struct tdq *);
287 static void tdq_notify(struct tdq *, struct thread *);
288 static struct thread *tdq_steal(struct tdq *, int);
289 static struct thread *runq_steal(struct runq *, int);
290 static int sched_pickcpu(struct thread *, int);
291 static void sched_balance(void);
292 static int sched_balance_pair(struct tdq *, struct tdq *);
293 static inline struct tdq *sched_setcpu(struct thread *, int, int);
294 static inline struct mtx *thread_block_switch(struct thread *);
295 static inline void thread_unblock_switch(struct thread *, struct mtx *);
296 static struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
297 static int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
298 static int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
299 struct cpu_group *cg, int indent);
302 static void sched_setup(void *dummy);
303 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
305 static void sched_initticks(void *dummy);
306 SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
310 * Print the threads waiting on a run-queue.
313 runq_print(struct runq *rq)
321 for (i = 0; i < RQB_LEN; i++) {
322 printf("\t\trunq bits %d 0x%zx\n",
323 i, rq->rq_status.rqb_bits[i]);
324 for (j = 0; j < RQB_BPW; j++)
325 if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
326 pri = j + (i << RQB_L2BPW);
327 rqh = &rq->rq_queues[pri];
328 TAILQ_FOREACH(td, rqh, td_runq) {
329 printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
330 td, td->td_name, td->td_priority,
331 td->td_rqindex, pri);
338 * Print the status of a per-cpu thread queue. Should be a ddb show cmd.
347 printf("tdq %d:\n", TDQ_ID(tdq));
348 printf("\tlock %p\n", TDQ_LOCKPTR(tdq));
349 printf("\tLock name: %s\n", tdq->tdq_name);
350 printf("\tload: %d\n", tdq->tdq_load);
351 printf("\tswitch cnt: %d\n", tdq->tdq_switchcnt);
352 printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
353 printf("\tidle state: %d\n", tdq->tdq_idlestate);
354 printf("\ttimeshare idx: %d\n", tdq->tdq_idx);
355 printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
356 printf("\tload transferable: %d\n", tdq->tdq_transferable);
357 printf("\tlowest priority: %d\n", tdq->tdq_lowpri);
358 printf("\trealtime runq:\n");
359 runq_print(&tdq->tdq_realtime);
360 printf("\ttimeshare runq:\n");
361 runq_print(&tdq->tdq_timeshare);
362 printf("\tidle runq:\n");
363 runq_print(&tdq->tdq_idle);
367 sched_shouldpreempt(int pri, int cpri, int remote)
370 * If the new priority is not better than the current priority there is
376 * Always preempt idle.
378 if (cpri >= PRI_MIN_IDLE)
381 * If preemption is disabled don't preempt others.
383 if (preempt_thresh == 0)
386 * Preempt if we exceed the threshold.
388 if (pri <= preempt_thresh)
391 * If we're realtime or better and there is timeshare or worse running
392 * preempt only remote processors.
394 if (remote && pri <= PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
399 #define TS_RQ_PPQ (((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
401 * Add a thread to the actual run-queue. Keeps transferable counts up to
402 * date with what is actually on the run-queue. Selects the correct
403 * queue position for timeshare threads.
406 tdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
411 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
412 THREAD_LOCK_ASSERT(td, MA_OWNED);
414 pri = td->td_priority;
417 if (THREAD_CAN_MIGRATE(td)) {
418 tdq->tdq_transferable++;
419 ts->ts_flags |= TSF_XFERABLE;
421 if (pri <= PRI_MAX_REALTIME) {
422 ts->ts_runq = &tdq->tdq_realtime;
423 } else if (pri <= PRI_MAX_TIMESHARE) {
424 ts->ts_runq = &tdq->tdq_timeshare;
425 KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
426 ("Invalid priority %d on timeshare runq", pri));
428 * This queue contains only priorities between MIN and MAX
429 * realtime. Use the whole queue to represent these values.
431 if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
432 pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
433 pri = (pri + tdq->tdq_idx) % RQ_NQS;
435 * This effectively shortens the queue by one so we
436 * can have a one slot difference between idx and
437 * ridx while we wait for threads to drain.
439 if (tdq->tdq_ridx != tdq->tdq_idx &&
440 pri == tdq->tdq_ridx)
441 pri = (unsigned char)(pri - 1) % RQ_NQS;
444 runq_add_pri(ts->ts_runq, td, pri, flags);
447 ts->ts_runq = &tdq->tdq_idle;
448 runq_add(ts->ts_runq, td, flags);
452 * Remove a thread from a run-queue. This typically happens when a thread
453 * is selected to run. Running threads are not on the queue and the
454 * transferable count does not reflect them.
457 tdq_runq_rem(struct tdq *tdq, struct thread *td)
462 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
463 KASSERT(ts->ts_runq != NULL,
464 ("tdq_runq_remove: thread %p null ts_runq", td));
465 if (ts->ts_flags & TSF_XFERABLE) {
466 tdq->tdq_transferable--;
467 ts->ts_flags &= ~TSF_XFERABLE;
469 if (ts->ts_runq == &tdq->tdq_timeshare) {
470 if (tdq->tdq_idx != tdq->tdq_ridx)
471 runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
473 runq_remove_idx(ts->ts_runq, td, NULL);
475 runq_remove(ts->ts_runq, td);
479 * Load is maintained for all threads RUNNING and ON_RUNQ. Add the load
480 * for this thread to the referenced thread queue.
483 tdq_load_add(struct tdq *tdq, struct thread *td)
486 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
487 THREAD_LOCK_ASSERT(td, MA_OWNED);
490 if ((td->td_proc->p_flag & P_NOLOAD) == 0)
492 CTR2(KTR_SCHED, "cpu %d load: %d", TDQ_ID(tdq), tdq->tdq_load);
496 * Remove the load from a thread that is transitioning to a sleep state or
500 tdq_load_rem(struct tdq *tdq, struct thread *td)
503 THREAD_LOCK_ASSERT(td, MA_OWNED);
504 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
505 KASSERT(tdq->tdq_load != 0,
506 ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
509 if ((td->td_proc->p_flag & P_NOLOAD) == 0)
511 CTR1(KTR_SCHED, "load: %d", tdq->tdq_load);
515 * Set lowpri to its exact value by searching the run-queue and
516 * evaluating curthread. curthread may be passed as an optimization.
519 tdq_setlowpri(struct tdq *tdq, struct thread *ctd)
523 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
525 ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
526 td = tdq_choose(tdq);
527 if (td == NULL || td->td_priority > ctd->td_priority)
528 tdq->tdq_lowpri = ctd->td_priority;
530 tdq->tdq_lowpri = td->td_priority;
535 cpumask_t cs_mask; /* Mask of valid cpus. */
538 int cs_limit; /* Min priority for low min load for high. */
541 #define CPU_SEARCH_LOWEST 0x1
542 #define CPU_SEARCH_HIGHEST 0x2
543 #define CPU_SEARCH_BOTH (CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
545 #define CPUMASK_FOREACH(cpu, mask) \
546 for ((cpu) = 0; (cpu) < sizeof((mask)) * 8; (cpu)++) \
547 if ((mask) & 1 << (cpu))
549 static __inline int cpu_search(struct cpu_group *cg, struct cpu_search *low,
550 struct cpu_search *high, const int match);
551 int cpu_search_lowest(struct cpu_group *cg, struct cpu_search *low);
552 int cpu_search_highest(struct cpu_group *cg, struct cpu_search *high);
553 int cpu_search_both(struct cpu_group *cg, struct cpu_search *low,
554 struct cpu_search *high);
557 * This routine compares according to the match argument and should be
558 * reduced in actual instantiations via constant propagation and dead code
562 cpu_compare(int cpu, struct cpu_search *low, struct cpu_search *high,
568 if (match & CPU_SEARCH_LOWEST)
569 if (low->cs_mask & (1 << cpu) &&
570 tdq->tdq_load < low->cs_load &&
571 tdq->tdq_lowpri > low->cs_limit) {
573 low->cs_load = tdq->tdq_load;
575 if (match & CPU_SEARCH_HIGHEST)
576 if (high->cs_mask & (1 << cpu) &&
577 tdq->tdq_load >= high->cs_limit &&
578 tdq->tdq_load > high->cs_load &&
579 tdq->tdq_transferable) {
581 high->cs_load = tdq->tdq_load;
583 return (tdq->tdq_load);
587 * Search the tree of cpu_groups for the lowest or highest loaded cpu
588 * according to the match argument. This routine actually compares the
589 * load on all paths through the tree and finds the least loaded cpu on
590 * the least loaded path, which may differ from the least loaded cpu in
591 * the system. This balances work among caches and busses.
593 * This inline is instantiated in three forms below using constants for the
594 * match argument. It is reduced to the minimum set for each case. It is
595 * also recursive to the depth of the tree.
598 cpu_search(struct cpu_group *cg, struct cpu_search *low,
599 struct cpu_search *high, const int match)
604 if (cg->cg_children) {
605 struct cpu_search lgroup;
606 struct cpu_search hgroup;
607 struct cpu_group *child;
615 for (i = 0; i < cg->cg_children; i++) {
616 child = &cg->cg_child[i];
617 if (match & CPU_SEARCH_LOWEST) {
621 if (match & CPU_SEARCH_HIGHEST) {
626 case CPU_SEARCH_LOWEST:
627 load = cpu_search_lowest(child, &lgroup);
629 case CPU_SEARCH_HIGHEST:
630 load = cpu_search_highest(child, &hgroup);
632 case CPU_SEARCH_BOTH:
633 load = cpu_search_both(child, &lgroup, &hgroup);
637 if (match & CPU_SEARCH_LOWEST)
638 if (load < lload || low->cs_cpu == -1) {
642 if (match & CPU_SEARCH_HIGHEST)
643 if (load > hload || high->cs_cpu == -1) {
651 CPUMASK_FOREACH(cpu, cg->cg_mask)
652 total += cpu_compare(cpu, low, high, match);
658 * cpu_search instantiations must pass constants to maintain the inline
662 cpu_search_lowest(struct cpu_group *cg, struct cpu_search *low)
664 return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
668 cpu_search_highest(struct cpu_group *cg, struct cpu_search *high)
670 return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
674 cpu_search_both(struct cpu_group *cg, struct cpu_search *low,
675 struct cpu_search *high)
677 return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
681 * Find the cpu with the least load via the least loaded path that has a
682 * lowpri greater than pri pri. A pri of -1 indicates any priority is
686 sched_lowest(struct cpu_group *cg, cpumask_t mask, int pri)
688 struct cpu_search low;
694 cpu_search_lowest(cg, &low);
699 * Find the cpu with the highest load via the highest loaded path.
702 sched_highest(struct cpu_group *cg, cpumask_t mask, int minload)
704 struct cpu_search high;
709 high.cs_limit = minload;
710 cpu_search_highest(cg, &high);
715 * Simultaneously find the highest and lowest loaded cpu reachable via
719 sched_both(struct cpu_group *cg, cpumask_t mask, int *lowcpu, int *highcpu)
721 struct cpu_search high;
722 struct cpu_search low;
732 cpu_search_both(cg, &low, &high);
733 *lowcpu = low.cs_cpu;
734 *highcpu = high.cs_cpu;
739 sched_balance_group(struct cpu_group *cg)
748 sched_both(cg, mask, &low, &high);
749 if (low == high || low == -1 || high == -1)
751 if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low)))
754 * If we failed to move any threads determine which cpu
755 * to kick out of the set and try again.
757 if (TDQ_CPU(high)->tdq_transferable == 0)
758 mask &= ~(1 << high);
763 for (i = 0; i < cg->cg_children; i++)
764 sched_balance_group(&cg->cg_child[i]);
773 * Select a random time between .5 * balance_interval and
774 * 1.5 * balance_interval.
776 balance_ticks = max(balance_interval / 2, 1);
777 balance_ticks += random() % balance_interval;
778 if (smp_started == 0 || rebalance == 0)
782 sched_balance_group(cpu_top);
787 * Lock two thread queues using their address to maintain lock order.
790 tdq_lock_pair(struct tdq *one, struct tdq *two)
794 TDQ_LOCK_FLAGS(two, MTX_DUPOK);
797 TDQ_LOCK_FLAGS(one, MTX_DUPOK);
802 * Unlock two thread queues. Order is not important here.
805 tdq_unlock_pair(struct tdq *one, struct tdq *two)
812 * Transfer load between two imbalanced thread queues.
815 sched_balance_pair(struct tdq *high, struct tdq *low)
825 tdq_lock_pair(high, low);
826 transferable = high->tdq_transferable;
827 high_load = high->tdq_load;
828 low_load = low->tdq_load;
831 * Determine what the imbalance is and then adjust that to how many
832 * threads we actually have to give up (transferable).
834 if (transferable != 0) {
835 diff = high_load - low_load;
839 move = min(move, transferable);
840 for (i = 0; i < move; i++)
841 moved += tdq_move(high, low);
843 * IPI the target cpu to force it to reschedule with the new
846 ipi_selected(1 << TDQ_ID(low), IPI_PREEMPT);
848 tdq_unlock_pair(high, low);
853 * Move a thread from one thread queue to another.
856 tdq_move(struct tdq *from, struct tdq *to)
863 TDQ_LOCK_ASSERT(from, MA_OWNED);
864 TDQ_LOCK_ASSERT(to, MA_OWNED);
868 td = tdq_steal(tdq, cpu);
873 * Although the run queue is locked the thread may be blocked. Lock
874 * it to clear this and acquire the run-queue lock.
877 /* Drop recursive lock on from acquired via thread_lock(). */
881 td->td_lock = TDQ_LOCKPTR(to);
882 tdq_add(to, td, SRQ_YIELDING);
887 * This tdq has idled. Try to steal a thread from another cpu and switch
891 tdq_idled(struct tdq *tdq)
893 struct cpu_group *cg;
899 if (smp_started == 0 || steal_idle == 0)
902 mask &= ~PCPU_GET(cpumask);
903 /* We don't want to be preempted while we're iterating. */
905 for (cg = tdq->tdq_cg; cg != NULL; ) {
906 if ((cg->cg_flags & (CG_FLAG_HTT | CG_FLAG_THREAD)) == 0)
907 thresh = steal_thresh;
910 cpu = sched_highest(cg, mask, thresh);
915 steal = TDQ_CPU(cpu);
917 tdq_lock_pair(tdq, steal);
918 if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
919 tdq_unlock_pair(tdq, steal);
923 * If a thread was added while interrupts were disabled don't
924 * steal one here. If we fail to acquire one due to affinity
925 * restrictions loop again with this cpu removed from the
928 if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
929 tdq_unlock_pair(tdq, steal);
934 mi_switch(SW_VOL | SWT_IDLE, NULL);
935 thread_unlock(curthread);
944 * Notify a remote cpu of new work. Sends an IPI if criteria are met.
947 tdq_notify(struct tdq *tdq, struct thread *td)
953 if (tdq->tdq_ipipending)
955 cpu = td->td_sched->ts_cpu;
956 pri = td->td_priority;
957 ctd = pcpu_find(cpu)->pc_curthread;
958 if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
960 if (TD_IS_IDLETHREAD(ctd)) {
962 * If the idle thread is still 'running' it's probably
963 * waiting on us to release the tdq spinlock already. No
966 if (tdq->tdq_idlestate == TDQ_RUNNING)
969 * If the MD code has an idle wakeup routine try that before
970 * falling back to IPI.
972 if (cpu_idle_wakeup(cpu))
975 tdq->tdq_ipipending = 1;
976 ipi_selected(1 << cpu, IPI_PREEMPT);
980 * Steals load from a timeshare queue. Honors the rotating queue head
983 static struct thread *
984 runq_steal_from(struct runq *rq, int cpu, u_char start)
994 rqb = &rq->rq_status;
995 bit = start & (RQB_BPW -1);
999 for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1000 if (rqb->rqb_bits[i] == 0)
1003 for (pri = bit; pri < RQB_BPW; pri++)
1004 if (rqb->rqb_bits[i] & (1ul << pri))
1009 pri = RQB_FFS(rqb->rqb_bits[i]);
1010 pri += (i << RQB_L2BPW);
1011 rqh = &rq->rq_queues[pri];
1012 TAILQ_FOREACH(td, rqh, td_runq) {
1013 if (first && THREAD_CAN_MIGRATE(td) &&
1014 THREAD_CAN_SCHED(td, cpu))
1028 * Steals load from a standard linear queue.
1030 static struct thread *
1031 runq_steal(struct runq *rq, int cpu)
1039 rqb = &rq->rq_status;
1040 for (word = 0; word < RQB_LEN; word++) {
1041 if (rqb->rqb_bits[word] == 0)
1043 for (bit = 0; bit < RQB_BPW; bit++) {
1044 if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
1046 rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
1047 TAILQ_FOREACH(td, rqh, td_runq)
1048 if (THREAD_CAN_MIGRATE(td) &&
1049 THREAD_CAN_SCHED(td, cpu))
1057 * Attempt to steal a thread in priority order from a thread queue.
1059 static struct thread *
1060 tdq_steal(struct tdq *tdq, int cpu)
1064 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1065 if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
1067 if ((td = runq_steal_from(&tdq->tdq_timeshare,
1068 cpu, tdq->tdq_ridx)) != NULL)
1070 return (runq_steal(&tdq->tdq_idle, cpu));
1074 * Sets the thread lock and ts_cpu to match the requested cpu. Unlocks the
1075 * current lock and returns with the assigned queue locked.
1077 static inline struct tdq *
1078 sched_setcpu(struct thread *td, int cpu, int flags)
1083 THREAD_LOCK_ASSERT(td, MA_OWNED);
1085 td->td_sched->ts_cpu = cpu;
1087 * If the lock matches just return the queue.
1089 if (td->td_lock == TDQ_LOCKPTR(tdq))
1093 * If the thread isn't running its lockptr is a
1094 * turnstile or a sleepqueue. We can just lock_set without
1097 if (TD_CAN_RUN(td)) {
1099 thread_lock_set(td, TDQ_LOCKPTR(tdq));
1104 * The hard case, migration, we need to block the thread first to
1105 * prevent order reversals with other cpus locks.
1107 thread_lock_block(td);
1109 thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1113 SCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
1114 SCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
1115 SCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
1116 SCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
1117 SCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
1118 SCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
1121 sched_pickcpu(struct thread *td, int flags)
1123 struct cpu_group *cg;
1124 struct td_sched *ts;
1131 self = PCPU_GET(cpuid);
1133 if (smp_started == 0)
1136 * Don't migrate a running thread from sched_switch().
1138 if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1139 return (ts->ts_cpu);
1141 * Prefer to run interrupt threads on the processors that generate
1144 if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1145 curthread->td_intr_nesting_level && ts->ts_cpu != self) {
1146 SCHED_STAT_INC(pickcpu_intrbind);
1150 * If the thread can run on the last cpu and the affinity has not
1151 * expired or it is idle run it there.
1153 pri = td->td_priority;
1154 tdq = TDQ_CPU(ts->ts_cpu);
1155 if (THREAD_CAN_SCHED(td, ts->ts_cpu)) {
1156 if (tdq->tdq_lowpri > PRI_MIN_IDLE) {
1157 SCHED_STAT_INC(pickcpu_idle_affinity);
1158 return (ts->ts_cpu);
1160 if (SCHED_AFFINITY(ts, CG_SHARE_L2) && tdq->tdq_lowpri > pri) {
1161 SCHED_STAT_INC(pickcpu_affinity);
1162 return (ts->ts_cpu);
1166 * Search for the highest level in the tree that still has affinity.
1169 for (cg = tdq->tdq_cg; cg != NULL; cg = cg->cg_parent)
1170 if (SCHED_AFFINITY(ts, cg->cg_level))
1173 mask = td->td_cpuset->cs_mask.__bits[0];
1175 cpu = sched_lowest(cg, mask, pri);
1177 cpu = sched_lowest(cpu_top, mask, -1);
1179 * Compare the lowest loaded cpu to current cpu.
1181 if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
1182 TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE) {
1183 SCHED_STAT_INC(pickcpu_local);
1186 SCHED_STAT_INC(pickcpu_lowest);
1187 if (cpu != ts->ts_cpu)
1188 SCHED_STAT_INC(pickcpu_migration);
1189 KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1195 * Pick the highest priority task we have and return it.
1197 static struct thread *
1198 tdq_choose(struct tdq *tdq)
1202 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1203 td = runq_choose(&tdq->tdq_realtime);
1206 td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1208 KASSERT(td->td_priority >= PRI_MIN_TIMESHARE,
1209 ("tdq_choose: Invalid priority on timeshare queue %d",
1213 td = runq_choose(&tdq->tdq_idle);
1215 KASSERT(td->td_priority >= PRI_MIN_IDLE,
1216 ("tdq_choose: Invalid priority on idle queue %d",
1225 * Initialize a thread queue.
1228 tdq_setup(struct tdq *tdq)
1232 printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1233 runq_init(&tdq->tdq_realtime);
1234 runq_init(&tdq->tdq_timeshare);
1235 runq_init(&tdq->tdq_idle);
1236 snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1237 "sched lock %d", (int)TDQ_ID(tdq));
1238 mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1239 MTX_SPIN | MTX_RECURSE);
1244 sched_setup_smp(void)
1249 cpu_top = smp_topo();
1250 for (i = 0; i < MAXCPU; i++) {
1255 tdq->tdq_cg = smp_topo_find(cpu_top, i);
1256 if (tdq->tdq_cg == NULL)
1257 panic("Can't find cpu group for %d\n", i);
1259 balance_tdq = TDQ_SELF();
1265 * Setup the thread queues and initialize the topology based on MD
1269 sched_setup(void *dummy)
1280 * To avoid divide-by-zero, we set realstathz a dummy value
1281 * in case which sched_clock() called before sched_initticks().
1284 sched_slice = (realstathz/10); /* ~100ms */
1285 tickincr = 1 << SCHED_TICK_SHIFT;
1287 /* Add thread0's load since it's running. */
1289 thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1290 tdq_load_add(tdq, &thread0);
1291 tdq->tdq_lowpri = thread0.td_priority;
1296 * This routine determines the tickincr after stathz and hz are setup.
1300 sched_initticks(void *dummy)
1304 realstathz = stathz ? stathz : hz;
1305 sched_slice = (realstathz/10); /* ~100ms */
1308 * tickincr is shifted out by 10 to avoid rounding errors due to
1309 * hz not being evenly divisible by stathz on all platforms.
1311 incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1313 * This does not work for values of stathz that are more than
1314 * 1 << SCHED_TICK_SHIFT * hz. In practice this does not happen.
1321 * Set the default balance interval now that we know
1322 * what realstathz is.
1324 balance_interval = realstathz;
1326 * Set steal thresh to log2(mp_ncpu) but no greater than 4. This
1327 * prevents excess thrashing on large machines and excess idle on
1330 steal_thresh = min(ffs(mp_ncpus) - 1, 3);
1331 affinity = SCHED_AFFINITY_DEFAULT;
1337 * This is the core of the interactivity algorithm. Determines a score based
1338 * on past behavior. It is the ratio of sleep time to run time scaled to
1339 * a [0, 100] integer. This is the voluntary sleep time of a process, which
1340 * differs from the cpu usage because it does not account for time spent
1341 * waiting on a run-queue. Would be prettier if we had floating point.
1344 sched_interact_score(struct thread *td)
1346 struct td_sched *ts;
1351 * The score is only needed if this is likely to be an interactive
1352 * task. Don't go through the expense of computing it if there's
1355 if (sched_interact <= SCHED_INTERACT_HALF &&
1356 ts->ts_runtime >= ts->ts_slptime)
1357 return (SCHED_INTERACT_HALF);
1359 if (ts->ts_runtime > ts->ts_slptime) {
1360 div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1361 return (SCHED_INTERACT_HALF +
1362 (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1364 if (ts->ts_slptime > ts->ts_runtime) {
1365 div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1366 return (ts->ts_runtime / div);
1368 /* runtime == slptime */
1370 return (SCHED_INTERACT_HALF);
1373 * This can happen if slptime and runtime are 0.
1380 * Scale the scheduling priority according to the "interactivity" of this
1384 sched_priority(struct thread *td)
1389 if (td->td_pri_class != PRI_TIMESHARE)
1392 * If the score is interactive we place the thread in the realtime
1393 * queue with a priority that is less than kernel and interrupt
1394 * priorities. These threads are not subject to nice restrictions.
1396 * Scores greater than this are placed on the normal timeshare queue
1397 * where the priority is partially decided by the most recent cpu
1398 * utilization and the rest is decided by nice value.
1400 * The nice value of the process has a linear effect on the calculated
1401 * score. Negative nice values make it easier for a thread to be
1402 * considered interactive.
1404 score = imax(0, sched_interact_score(td) - td->td_proc->p_nice);
1405 if (score < sched_interact) {
1406 pri = PRI_MIN_REALTIME;
1407 pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1409 KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1410 ("sched_priority: invalid interactive priority %d score %d",
1413 pri = SCHED_PRI_MIN;
1414 if (td->td_sched->ts_ticks)
1415 pri += SCHED_PRI_TICKS(td->td_sched);
1416 pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1417 KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1418 ("sched_priority: invalid priority %d: nice %d, "
1419 "ticks %d ftick %d ltick %d tick pri %d",
1420 pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1421 td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1422 SCHED_PRI_TICKS(td->td_sched)));
1424 sched_user_prio(td, pri);
1430 * This routine enforces a maximum limit on the amount of scheduling history
1431 * kept. It is called after either the slptime or runtime is adjusted. This
1432 * function is ugly due to integer math.
1435 sched_interact_update(struct thread *td)
1437 struct td_sched *ts;
1441 sum = ts->ts_runtime + ts->ts_slptime;
1442 if (sum < SCHED_SLP_RUN_MAX)
1445 * This only happens from two places:
1446 * 1) We have added an unusual amount of run time from fork_exit.
1447 * 2) We have added an unusual amount of sleep time from sched_sleep().
1449 if (sum > SCHED_SLP_RUN_MAX * 2) {
1450 if (ts->ts_runtime > ts->ts_slptime) {
1451 ts->ts_runtime = SCHED_SLP_RUN_MAX;
1454 ts->ts_slptime = SCHED_SLP_RUN_MAX;
1460 * If we have exceeded by more than 1/5th then the algorithm below
1461 * will not bring us back into range. Dividing by two here forces
1462 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1464 if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1465 ts->ts_runtime /= 2;
1466 ts->ts_slptime /= 2;
1469 ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1470 ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1474 * Scale back the interactivity history when a child thread is created. The
1475 * history is inherited from the parent but the thread may behave totally
1476 * differently. For example, a shell spawning a compiler process. We want
1477 * to learn that the compiler is behaving badly very quickly.
1480 sched_interact_fork(struct thread *td)
1485 sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1486 if (sum > SCHED_SLP_RUN_FORK) {
1487 ratio = sum / SCHED_SLP_RUN_FORK;
1488 td->td_sched->ts_runtime /= ratio;
1489 td->td_sched->ts_slptime /= ratio;
1494 * Called from proc0_init() to setup the scheduler fields.
1501 * Set up the scheduler specific parts of proc0.
1503 proc0.p_sched = NULL; /* XXX */
1504 thread0.td_sched = &td_sched0;
1505 td_sched0.ts_ltick = ticks;
1506 td_sched0.ts_ftick = ticks;
1507 td_sched0.ts_slice = sched_slice;
1511 * This is only somewhat accurate since given many processes of the same
1512 * priority they will switch when their slices run out, which will be
1513 * at most sched_slice stathz ticks.
1516 sched_rr_interval(void)
1519 /* Convert sched_slice to hz */
1520 return (hz/(realstathz/sched_slice));
1524 * Update the percent cpu tracking information when it is requested or
1525 * the total history exceeds the maximum. We keep a sliding history of
1526 * tick counts that slowly decays. This is less precise than the 4BSD
1527 * mechanism since it happens with less regular and frequent events.
1530 sched_pctcpu_update(struct td_sched *ts)
1533 if (ts->ts_ticks == 0)
1535 if (ticks - (hz / 10) < ts->ts_ltick &&
1536 SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1539 * Adjust counters and watermark for pctcpu calc.
1541 if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1542 ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1546 ts->ts_ltick = ticks;
1547 ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1551 * Adjust the priority of a thread. Move it to the appropriate run-queue
1552 * if necessary. This is the back-end for several priority related
1556 sched_thread_priority(struct thread *td, u_char prio)
1558 struct td_sched *ts;
1562 CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
1563 td, td->td_name, td->td_priority, prio, curthread,
1564 curthread->td_name);
1566 THREAD_LOCK_ASSERT(td, MA_OWNED);
1567 if (td->td_priority == prio)
1570 * If the priority has been elevated due to priority
1571 * propagation, we may have to move ourselves to a new
1572 * queue. This could be optimized to not re-add in some
1575 if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1577 td->td_priority = prio;
1578 sched_add(td, SRQ_BORROWING);
1582 * If the thread is currently running we may have to adjust the lowpri
1583 * information so other cpus are aware of our current priority.
1585 if (TD_IS_RUNNING(td)) {
1586 tdq = TDQ_CPU(ts->ts_cpu);
1587 oldpri = td->td_priority;
1588 td->td_priority = prio;
1589 if (prio < tdq->tdq_lowpri)
1590 tdq->tdq_lowpri = prio;
1591 else if (tdq->tdq_lowpri == oldpri)
1592 tdq_setlowpri(tdq, td);
1595 td->td_priority = prio;
1599 * Update a thread's priority when it is lent another thread's
1603 sched_lend_prio(struct thread *td, u_char prio)
1606 td->td_flags |= TDF_BORROWING;
1607 sched_thread_priority(td, prio);
1611 * Restore a thread's priority when priority propagation is
1612 * over. The prio argument is the minimum priority the thread
1613 * needs to have to satisfy other possible priority lending
1614 * requests. If the thread's regular priority is less
1615 * important than prio, the thread will keep a priority boost
1619 sched_unlend_prio(struct thread *td, u_char prio)
1623 if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1624 td->td_base_pri <= PRI_MAX_TIMESHARE)
1625 base_pri = td->td_user_pri;
1627 base_pri = td->td_base_pri;
1628 if (prio >= base_pri) {
1629 td->td_flags &= ~TDF_BORROWING;
1630 sched_thread_priority(td, base_pri);
1632 sched_lend_prio(td, prio);
1636 * Standard entry for setting the priority to an absolute value.
1639 sched_prio(struct thread *td, u_char prio)
1643 /* First, update the base priority. */
1644 td->td_base_pri = prio;
1647 * If the thread is borrowing another thread's priority, don't
1648 * ever lower the priority.
1650 if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1653 /* Change the real priority. */
1654 oldprio = td->td_priority;
1655 sched_thread_priority(td, prio);
1658 * If the thread is on a turnstile, then let the turnstile update
1661 if (TD_ON_LOCK(td) && oldprio != prio)
1662 turnstile_adjust(td, oldprio);
1666 * Set the base user priority, does not effect current running priority.
1669 sched_user_prio(struct thread *td, u_char prio)
1673 td->td_base_user_pri = prio;
1674 if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1676 oldprio = td->td_user_pri;
1677 td->td_user_pri = prio;
1681 sched_lend_user_prio(struct thread *td, u_char prio)
1685 THREAD_LOCK_ASSERT(td, MA_OWNED);
1686 td->td_flags |= TDF_UBORROWING;
1687 oldprio = td->td_user_pri;
1688 td->td_user_pri = prio;
1692 sched_unlend_user_prio(struct thread *td, u_char prio)
1696 THREAD_LOCK_ASSERT(td, MA_OWNED);
1697 base_pri = td->td_base_user_pri;
1698 if (prio >= base_pri) {
1699 td->td_flags &= ~TDF_UBORROWING;
1700 sched_user_prio(td, base_pri);
1702 sched_lend_user_prio(td, prio);
1707 * Block a thread for switching. Similar to thread_block() but does not
1708 * bump the spin count.
1710 static inline struct mtx *
1711 thread_block_switch(struct thread *td)
1715 THREAD_LOCK_ASSERT(td, MA_OWNED);
1717 td->td_lock = &blocked_lock;
1718 mtx_unlock_spin(lock);
1724 * Handle migration from sched_switch(). This happens only for
1728 sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1732 tdn = TDQ_CPU(td->td_sched->ts_cpu);
1734 tdq_load_rem(tdq, td);
1736 * Do the lock dance required to avoid LOR. We grab an extra
1737 * spinlock nesting to prevent preemption while we're
1738 * not holding either run-queue lock.
1741 thread_block_switch(td); /* This releases the lock on tdq. */
1743 tdq_add(tdn, td, flags);
1744 tdq_notify(tdn, td);
1746 * After we unlock tdn the new cpu still can't switch into this
1747 * thread until we've unblocked it in cpu_switch(). The lock
1748 * pointers may match in the case of HTT cores. Don't unlock here
1749 * or we can deadlock when the other CPU runs the IPI handler.
1751 if (TDQ_LOCKPTR(tdn) != TDQ_LOCKPTR(tdq)) {
1757 return (TDQ_LOCKPTR(tdn));
1761 * Release a thread that was blocked with thread_block_switch().
1764 thread_unblock_switch(struct thread *td, struct mtx *mtx)
1766 atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1771 * Switch threads. This function has to handle threads coming in while
1772 * blocked for some reason, running, or idle. It also must deal with
1773 * migrating a thread from one queue to another as running threads may
1774 * be assigned elsewhere via binding.
1777 sched_switch(struct thread *td, struct thread *newtd, int flags)
1780 struct td_sched *ts;
1785 THREAD_LOCK_ASSERT(td, MA_OWNED);
1786 KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
1788 cpuid = PCPU_GET(cpuid);
1789 tdq = TDQ_CPU(cpuid);
1792 ts->ts_rltick = ticks;
1793 td->td_lastcpu = td->td_oncpu;
1794 td->td_oncpu = NOCPU;
1795 td->td_flags &= ~TDF_NEEDRESCHED;
1796 td->td_owepreempt = 0;
1797 tdq->tdq_switchcnt++;
1799 * The lock pointer in an idle thread should never change. Reset it
1800 * to CAN_RUN as well.
1802 if (TD_IS_IDLETHREAD(td)) {
1803 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1805 } else if (TD_IS_RUNNING(td)) {
1806 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1807 srqflag = (flags & SW_PREEMPT) ?
1808 SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1809 SRQ_OURSELF|SRQ_YIELDING;
1810 if (ts->ts_cpu == cpuid)
1811 tdq_runq_add(tdq, td, srqflag);
1813 mtx = sched_switch_migrate(tdq, td, srqflag);
1815 /* This thread must be going to sleep. */
1817 mtx = thread_block_switch(td);
1818 tdq_load_rem(tdq, td);
1821 * We enter here with the thread blocked and assigned to the
1822 * appropriate cpu run-queue or sleep-queue and with the current
1823 * thread-queue locked.
1825 TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1826 newtd = choosethread();
1828 * Call the MD code to switch contexts if necessary.
1832 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1833 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1835 lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1836 TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1838 #ifdef KDTRACE_HOOKS
1840 * If DTrace has set the active vtime enum to anything
1841 * other than INACTIVE (0), then it should have set the
1844 if (dtrace_vtime_active)
1845 (*dtrace_vtime_switch_func)(newtd);
1848 cpu_switch(td, newtd, mtx);
1850 * We may return from cpu_switch on a different cpu. However,
1851 * we always return with td_lock pointing to the current cpu's
1854 cpuid = PCPU_GET(cpuid);
1855 tdq = TDQ_CPU(cpuid);
1856 lock_profile_obtain_lock_success(
1857 &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1859 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1860 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1863 thread_unblock_switch(td, mtx);
1865 * Assert that all went well and return.
1867 TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1868 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1869 td->td_oncpu = cpuid;
1873 * Adjust thread priorities as a result of a nice request.
1876 sched_nice(struct proc *p, int nice)
1880 PROC_LOCK_ASSERT(p, MA_OWNED);
1883 FOREACH_THREAD_IN_PROC(p, td) {
1886 sched_prio(td, td->td_base_user_pri);
1892 * Record the sleep time for the interactivity scorer.
1895 sched_sleep(struct thread *td, int prio)
1898 THREAD_LOCK_ASSERT(td, MA_OWNED);
1900 td->td_slptick = ticks;
1901 if (TD_IS_SUSPENDED(td) || prio <= PSOCK)
1902 td->td_flags |= TDF_CANSWAP;
1903 if (static_boost == 1 && prio)
1904 sched_prio(td, prio);
1905 else if (static_boost && td->td_priority > static_boost)
1906 sched_prio(td, static_boost);
1910 * Schedule a thread to resume execution and record how long it voluntarily
1911 * slept. We also update the pctcpu, interactivity, and priority.
1914 sched_wakeup(struct thread *td)
1916 struct td_sched *ts;
1919 THREAD_LOCK_ASSERT(td, MA_OWNED);
1921 td->td_flags &= ~TDF_CANSWAP;
1923 * If we slept for more than a tick update our interactivity and
1926 slptick = td->td_slptick;
1928 if (slptick && slptick != ticks) {
1931 hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1932 ts->ts_slptime += hzticks;
1933 sched_interact_update(td);
1934 sched_pctcpu_update(ts);
1936 /* Reset the slice value after we sleep. */
1937 ts->ts_slice = sched_slice;
1938 sched_add(td, SRQ_BORING);
1942 * Penalize the parent for creating a new child and initialize the child's
1946 sched_fork(struct thread *td, struct thread *child)
1948 THREAD_LOCK_ASSERT(td, MA_OWNED);
1949 sched_fork_thread(td, child);
1951 * Penalize the parent and child for forking.
1953 sched_interact_fork(child);
1954 sched_priority(child);
1955 td->td_sched->ts_runtime += tickincr;
1956 sched_interact_update(td);
1961 * Fork a new thread, may be within the same process.
1964 sched_fork_thread(struct thread *td, struct thread *child)
1966 struct td_sched *ts;
1967 struct td_sched *ts2;
1969 THREAD_LOCK_ASSERT(td, MA_OWNED);
1974 ts2 = child->td_sched;
1975 child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1976 child->td_cpuset = cpuset_ref(td->td_cpuset);
1977 ts2->ts_cpu = ts->ts_cpu;
1980 * Grab our parents cpu estimation information and priority.
1982 ts2->ts_ticks = ts->ts_ticks;
1983 ts2->ts_ltick = ts->ts_ltick;
1984 ts2->ts_ftick = ts->ts_ftick;
1985 child->td_user_pri = td->td_user_pri;
1986 child->td_base_user_pri = td->td_base_user_pri;
1988 * And update interactivity score.
1990 ts2->ts_slptime = ts->ts_slptime;
1991 ts2->ts_runtime = ts->ts_runtime;
1992 ts2->ts_slice = 1; /* Attempt to quickly learn interactivity. */
1996 * Adjust the priority class of a thread.
1999 sched_class(struct thread *td, int class)
2002 THREAD_LOCK_ASSERT(td, MA_OWNED);
2003 if (td->td_pri_class == class)
2005 td->td_pri_class = class;
2009 * Return some of the child's priority and interactivity to the parent.
2012 sched_exit(struct proc *p, struct thread *child)
2016 CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
2017 child, child->td_name, child->td_priority);
2019 PROC_LOCK_ASSERT(p, MA_OWNED);
2020 td = FIRST_THREAD_IN_PROC(p);
2021 sched_exit_thread(td, child);
2025 * Penalize another thread for the time spent on this one. This helps to
2026 * worsen the priority and interactivity of processes which schedule batch
2027 * jobs such as make. This has little effect on the make process itself but
2028 * causes new processes spawned by it to receive worse scores immediately.
2031 sched_exit_thread(struct thread *td, struct thread *child)
2034 CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
2035 child, child->td_name, child->td_priority);
2038 * Give the child's runtime to the parent without returning the
2039 * sleep time as a penalty to the parent. This causes shells that
2040 * launch expensive things to mark their children as expensive.
2043 td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2044 sched_interact_update(td);
2050 sched_preempt(struct thread *td)
2056 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2057 tdq->tdq_ipipending = 0;
2058 if (td->td_priority > tdq->tdq_lowpri) {
2061 flags = SW_INVOL | SW_PREEMPT;
2062 if (td->td_critnest > 1)
2063 td->td_owepreempt = 1;
2064 else if (TD_IS_IDLETHREAD(td))
2065 mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2067 mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2073 * Fix priorities on return to user-space. Priorities may be elevated due
2074 * to static priorities in msleep() or similar.
2077 sched_userret(struct thread *td)
2080 * XXX we cheat slightly on the locking here to avoid locking in
2081 * the usual case. Setting td_priority here is essentially an
2082 * incomplete workaround for not setting it properly elsewhere.
2083 * Now that some interrupt handlers are threads, not setting it
2084 * properly elsewhere can clobber it in the window between setting
2085 * it here and returning to user mode, so don't waste time setting
2086 * it perfectly here.
2088 KASSERT((td->td_flags & TDF_BORROWING) == 0,
2089 ("thread with borrowed priority returning to userland"));
2090 if (td->td_priority != td->td_user_pri) {
2092 td->td_priority = td->td_user_pri;
2093 td->td_base_pri = td->td_user_pri;
2094 tdq_setlowpri(TDQ_SELF(), td);
2100 * Handle a stathz tick. This is really only relevant for timeshare
2104 sched_clock(struct thread *td)
2107 struct td_sched *ts;
2109 THREAD_LOCK_ASSERT(td, MA_OWNED);
2113 * We run the long term load balancer infrequently on the first cpu.
2115 if (balance_tdq == tdq) {
2116 if (balance_ticks && --balance_ticks == 0)
2121 * Save the old switch count so we have a record of the last ticks
2122 * activity. Initialize the new switch count based on our load.
2123 * If there is some activity seed it to reflect that.
2125 tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
2126 tdq->tdq_switchcnt = tdq->tdq_load;
2128 * Advance the insert index once for each tick to ensure that all
2129 * threads get a chance to run.
2131 if (tdq->tdq_idx == tdq->tdq_ridx) {
2132 tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2133 if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2134 tdq->tdq_ridx = tdq->tdq_idx;
2137 if (td->td_pri_class & PRI_FIFO_BIT)
2139 if (td->td_pri_class == PRI_TIMESHARE) {
2141 * We used a tick; charge it to the thread so
2142 * that we can compute our interactivity.
2144 td->td_sched->ts_runtime += tickincr;
2145 sched_interact_update(td);
2149 * We used up one time slice.
2151 if (--ts->ts_slice > 0)
2154 * We're out of time, force a requeue at userret().
2156 ts->ts_slice = sched_slice;
2157 td->td_flags |= TDF_NEEDRESCHED;
2161 * Called once per hz tick. Used for cpu utilization information. This
2162 * is easier than trying to scale based on stathz.
2167 struct td_sched *ts;
2169 ts = curthread->td_sched;
2171 * Ticks is updated asynchronously on a single cpu. Check here to
2172 * avoid incrementing ts_ticks multiple times in a single tick.
2174 if (ts->ts_ltick == ticks)
2176 /* Adjust ticks for pctcpu */
2177 ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2178 ts->ts_ltick = ticks;
2180 * Update if we've exceeded our desired tick threshhold by over one
2183 if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2184 sched_pctcpu_update(ts);
2188 * Return whether the current CPU has runnable tasks. Used for in-kernel
2189 * cooperative idle threads.
2192 sched_runnable(void)
2200 if ((curthread->td_flags & TDF_IDLETD) != 0) {
2201 if (tdq->tdq_load > 0)
2204 if (tdq->tdq_load - 1 > 0)
2212 * Choose the highest priority thread to run. The thread is removed from
2213 * the run-queue while running however the load remains. For SMP we set
2214 * the tdq in the global idle bitmask if it idles here.
2223 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2224 td = tdq_choose(tdq);
2226 td->td_sched->ts_ltick = ticks;
2227 tdq_runq_rem(tdq, td);
2228 tdq->tdq_lowpri = td->td_priority;
2231 tdq->tdq_lowpri = PRI_MAX_IDLE;
2232 return (PCPU_GET(idlethread));
2236 * Set owepreempt if necessary. Preemption never happens directly in ULE,
2237 * we always request it once we exit a critical section.
2240 sched_setpreempt(struct thread *td)
2246 THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2249 pri = td->td_priority;
2250 cpri = ctd->td_priority;
2252 ctd->td_flags |= TDF_NEEDRESCHED;
2253 if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2255 if (!sched_shouldpreempt(pri, cpri, 0))
2257 ctd->td_owepreempt = 1;
2261 * Add a thread to a thread queue. Select the appropriate runq and add the
2262 * thread to it. This is the internal function called when the tdq is
2266 tdq_add(struct tdq *tdq, struct thread *td, int flags)
2269 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2270 KASSERT((td->td_inhibitors == 0),
2271 ("sched_add: trying to run inhibited thread"));
2272 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2273 ("sched_add: bad thread state"));
2274 KASSERT(td->td_flags & TDF_INMEM,
2275 ("sched_add: thread swapped out"));
2277 if (td->td_priority < tdq->tdq_lowpri)
2278 tdq->tdq_lowpri = td->td_priority;
2279 tdq_runq_add(tdq, td, flags);
2280 tdq_load_add(tdq, td);
2284 * Select the target thread queue and add a thread to it. Request
2285 * preemption or IPI a remote processor if required.
2288 sched_add(struct thread *td, int flags)
2294 CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
2295 td, td->td_name, td->td_priority, curthread,
2296 curthread->td_name);
2297 THREAD_LOCK_ASSERT(td, MA_OWNED);
2299 * Recalculate the priority before we select the target cpu or
2302 if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2306 * Pick the destination cpu and if it isn't ours transfer to the
2309 cpu = sched_pickcpu(td, flags);
2310 tdq = sched_setcpu(td, cpu, flags);
2311 tdq_add(tdq, td, flags);
2312 if (cpu != PCPU_GET(cpuid)) {
2313 tdq_notify(tdq, td);
2320 * Now that the thread is moving to the run-queue, set the lock
2321 * to the scheduler's lock.
2323 thread_lock_set(td, TDQ_LOCKPTR(tdq));
2324 tdq_add(tdq, td, flags);
2326 if (!(flags & SRQ_YIELDING))
2327 sched_setpreempt(td);
2331 * Remove a thread from a run-queue without running it. This is used
2332 * when we're stealing a thread from a remote queue. Otherwise all threads
2333 * exit by calling sched_exit_thread() and sched_throw() themselves.
2336 sched_rem(struct thread *td)
2340 CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
2341 td, td->td_name, td->td_priority, curthread,
2342 curthread->td_name);
2343 tdq = TDQ_CPU(td->td_sched->ts_cpu);
2344 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2345 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2346 KASSERT(TD_ON_RUNQ(td),
2347 ("sched_rem: thread not on run queue"));
2348 tdq_runq_rem(tdq, td);
2349 tdq_load_rem(tdq, td);
2351 if (td->td_priority == tdq->tdq_lowpri)
2352 tdq_setlowpri(tdq, NULL);
2356 * Fetch cpu utilization information. Updates on demand.
2359 sched_pctcpu(struct thread *td)
2362 struct td_sched *ts;
2373 sched_pctcpu_update(ts);
2374 /* How many rtick per second ? */
2375 rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2376 pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2384 * Enforce affinity settings for a thread. Called after adjustments to
2388 sched_affinity(struct thread *td)
2391 struct td_sched *ts;
2394 THREAD_LOCK_ASSERT(td, MA_OWNED);
2396 if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2398 if (!TD_IS_RUNNING(td))
2400 td->td_flags |= TDF_NEEDRESCHED;
2401 if (!THREAD_CAN_MIGRATE(td))
2404 * Assign the new cpu and force a switch before returning to
2405 * userspace. If the target thread is not running locally send
2406 * an ipi to force the issue.
2409 ts->ts_cpu = sched_pickcpu(td, 0);
2410 if (cpu != PCPU_GET(cpuid))
2411 ipi_selected(1 << cpu, IPI_PREEMPT);
2416 * Bind a thread to a target cpu.
2419 sched_bind(struct thread *td, int cpu)
2421 struct td_sched *ts;
2423 THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2425 if (ts->ts_flags & TSF_BOUND)
2427 ts->ts_flags |= TSF_BOUND;
2429 if (PCPU_GET(cpuid) == cpu)
2432 /* When we return from mi_switch we'll be on the correct cpu. */
2433 mi_switch(SW_VOL, NULL);
2437 * Release a bound thread.
2440 sched_unbind(struct thread *td)
2442 struct td_sched *ts;
2444 THREAD_LOCK_ASSERT(td, MA_OWNED);
2446 if ((ts->ts_flags & TSF_BOUND) == 0)
2448 ts->ts_flags &= ~TSF_BOUND;
2453 sched_is_bound(struct thread *td)
2455 THREAD_LOCK_ASSERT(td, MA_OWNED);
2456 return (td->td_sched->ts_flags & TSF_BOUND);
2463 sched_relinquish(struct thread *td)
2466 mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
2471 * Return the total system load.
2481 for (i = 0; i <= mp_maxid; i++)
2482 total += TDQ_CPU(i)->tdq_sysload;
2485 return (TDQ_SELF()->tdq_sysload);
2490 sched_sizeof_proc(void)
2492 return (sizeof(struct proc));
2496 sched_sizeof_thread(void)
2498 return (sizeof(struct thread) + sizeof(struct td_sched));
2502 * The actual idle process.
2505 sched_idletd(void *dummy)
2514 mtx_assert(&Giant, MA_NOTOWNED);
2515 /* ULE relies on preemption for idle interruption. */
2517 tdq->tdq_idlestate = TDQ_RUNNING;
2519 if (tdq_idled(tdq) == 0)
2522 switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2524 * If we're switching very frequently, spin while checking
2525 * for load rather than entering a low power state that
2528 if (switchcnt > sched_idlespinthresh) {
2529 for (i = 0; i < sched_idlespins; i++) {
2536 * We must set our state to IDLE before checking
2537 * tdq_load for the last time to avoid a race with
2540 if (tdq->tdq_load == 0) {
2541 switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2542 tdq->tdq_idlestate = TDQ_IDLE;
2543 if (tdq->tdq_load == 0)
2544 cpu_idle(switchcnt > 1);
2546 if (tdq->tdq_load) {
2548 mi_switch(SW_VOL | SWT_IDLE, NULL);
2555 * A CPU is entering for the first time or a thread is exiting.
2558 sched_throw(struct thread *td)
2560 struct thread *newtd;
2565 /* Correct spinlock nesting and acquire the correct lock. */
2569 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2570 tdq_load_rem(tdq, td);
2571 lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2573 KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2574 newtd = choosethread();
2575 TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2576 PCPU_SET(switchtime, cpu_ticks());
2577 PCPU_SET(switchticks, ticks);
2578 cpu_throw(td, newtd); /* doesn't return */
2582 * This is called from fork_exit(). Just acquire the correct locks and
2583 * let fork do the rest of the work.
2586 sched_fork_exit(struct thread *td)
2588 struct td_sched *ts;
2593 * Finish setting up thread glue so that it begins execution in a
2594 * non-nested critical section with the scheduler lock held.
2596 cpuid = PCPU_GET(cpuid);
2597 tdq = TDQ_CPU(cpuid);
2599 if (TD_IS_IDLETHREAD(td))
2600 td->td_lock = TDQ_LOCKPTR(tdq);
2601 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2602 td->td_oncpu = cpuid;
2603 TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2604 lock_profile_obtain_lock_success(
2605 &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2611 * Build the CPU topology dump string. Is recursively called to collect
2612 * the topology tree.
2615 sysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
2620 sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
2621 "", indent, cg->cg_level);
2622 sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"0x%x\">", indent, "",
2623 cg->cg_count, cg->cg_mask);
2625 for (i = 0; i < MAXCPU; i++) {
2626 if ((cg->cg_mask & (1 << i)) != 0) {
2628 sbuf_printf(sb, ", ");
2631 sbuf_printf(sb, "%d", i);
2634 sbuf_printf(sb, "</cpu>\n");
2636 sbuf_printf(sb, "%*s <flags>", indent, "");
2637 if (cg->cg_flags != 0) {
2638 if ((cg->cg_flags & CG_FLAG_HTT) != 0)
2639 sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>\n");
2640 if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
2641 sbuf_printf(sb, "<flag name=\"THREAD\">SMT group</flag>\n");
2643 sbuf_printf(sb, "</flags>\n");
2645 if (cg->cg_children > 0) {
2646 sbuf_printf(sb, "%*s <children>\n", indent, "");
2647 for (i = 0; i < cg->cg_children; i++)
2648 sysctl_kern_sched_topology_spec_internal(sb,
2649 &cg->cg_child[i], indent+2);
2650 sbuf_printf(sb, "%*s </children>\n", indent, "");
2652 sbuf_printf(sb, "%*s</group>\n", indent, "");
2657 * Sysctl handler for retrieving topology dump. It's a wrapper for
2658 * the recursive sysctl_kern_smp_topology_spec_internal().
2661 sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
2666 KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
2668 topo = sbuf_new(NULL, NULL, 500, SBUF_AUTOEXTEND);
2672 sbuf_printf(topo, "<groups>\n");
2673 err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
2674 sbuf_printf(topo, "</groups>\n");
2678 err = SYSCTL_OUT(req, sbuf_data(topo), sbuf_len(topo));
2685 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2686 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2688 SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2689 "Slice size for timeshare threads");
2690 SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2691 "Interactivity score threshold");
2692 SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2693 0,"Min priority for preemption, lower priorities have greater precedence");
2694 SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost,
2695 0,"Controls whether static kernel priorities are assigned to sleeping threads.");
2696 SYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins,
2697 0,"Number of times idle will spin waiting for new work.");
2698 SYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW, &sched_idlespinthresh,
2699 0,"Threshold before we will permit idle spinning.");
2701 SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2702 "Number of hz ticks to keep thread affinity for");
2703 SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2704 "Enables the long-term load balancer");
2705 SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2706 &balance_interval, 0,
2707 "Average frequency in stathz ticks to run the long-term balancer");
2708 SYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2709 "Steals work from another hyper-threaded core on idle");
2710 SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2711 "Attempts to steal work from other cores before idling");
2712 SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2713 "Minimum load on remote cpu before we'll steal");
2715 /* Retrieve SMP topology */
2716 SYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
2717 CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
2718 "XML dump of detected CPU topology");
2721 /* ps compat. All cpu percentages from ULE are weighted. */
2722 static int ccpu = 0;
2723 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");