2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2002-2007, Jeffrey Roberson <jeff@freebsd.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice unmodified, this list of conditions, and the following
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 * This file implements the ULE scheduler. ULE supports independent CPU
31 * run queues and fine grain locking. It has superior interactive
32 * performance under load even on uni-processor systems.
35 * ULE is the last three letters in schedule. It owes its name to a
36 * generic user created for a scheduling system by Paul Mikesell at
37 * Isilon Systems and a general lack of creativity on the part of the author.
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
43 #include "opt_hwpmc_hooks.h"
44 #include "opt_sched.h"
46 #include <sys/param.h>
47 #include <sys/systm.h>
49 #include <sys/kernel.h>
51 #include <sys/limits.h>
53 #include <sys/mutex.h>
55 #include <sys/resource.h>
56 #include <sys/resourcevar.h>
57 #include <sys/sched.h>
61 #include <sys/sysctl.h>
62 #include <sys/sysproto.h>
63 #include <sys/turnstile.h>
64 #include <sys/umtxvar.h>
65 #include <sys/vmmeter.h>
66 #include <sys/cpuset.h>
70 #include <sys/pmckern.h>
74 #include <sys/dtrace_bsd.h>
75 int __read_mostly dtrace_vtime_active;
76 dtrace_vtime_switch_func_t dtrace_vtime_switch_func;
79 #include <machine/cpu.h>
80 #include <machine/smp.h>
84 #define TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
85 #define TDQ_NAME_LEN (sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
86 #define TDQ_LOADNAME_LEN (sizeof("CPU ") + sizeof(__XSTRING(MAXCPU)) - 1 + sizeof(" load"))
89 * Thread scheduler specific section. All fields are protected
93 struct runq *ts_runq; /* Run-queue we're queued on. */
94 short ts_flags; /* TSF_* flags. */
95 int ts_cpu; /* CPU that we have affinity for. */
96 int ts_rltick; /* Real last tick, for affinity. */
97 int ts_slice; /* Ticks of slice remaining. */
98 u_int ts_slptime; /* Number of ticks we vol. slept */
99 u_int ts_runtime; /* Number of ticks we were running */
100 int ts_ltick; /* Last tick that we were running on */
101 int ts_ftick; /* First tick that we were running on */
102 int ts_ticks; /* Tick count */
104 char ts_name[TS_NAME_LEN];
107 /* flags kept in ts_flags */
108 #define TSF_BOUND 0x0001 /* Thread can not migrate. */
109 #define TSF_XFERABLE 0x0002 /* Thread was added as transferable. */
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)
115 _Static_assert(sizeof(struct thread) + sizeof(struct td_sched) <=
116 sizeof(struct thread0_storage),
117 "increase struct thread0_storage.t0st_sched size");
120 * Priority ranges used for interactive and non-interactive timeshare
121 * threads. The timeshare priorities are split up into four ranges.
122 * The first range handles interactive threads. The last three ranges
123 * (NHALF, x, and NHALF) handle non-interactive threads with the outer
124 * ranges supporting nice values.
126 #define PRI_TIMESHARE_RANGE (PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
127 #define PRI_INTERACT_RANGE ((PRI_TIMESHARE_RANGE - SCHED_PRI_NRESV) / 2)
128 #define PRI_BATCH_RANGE (PRI_TIMESHARE_RANGE - PRI_INTERACT_RANGE)
130 #define PRI_MIN_INTERACT PRI_MIN_TIMESHARE
131 #define PRI_MAX_INTERACT (PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE - 1)
132 #define PRI_MIN_BATCH (PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE)
133 #define PRI_MAX_BATCH PRI_MAX_TIMESHARE
136 * Cpu percentage computation macros and defines.
138 * SCHED_TICK_SECS: Number of seconds to average the cpu usage across.
139 * SCHED_TICK_TARG: Number of hz ticks to average the cpu usage across.
140 * SCHED_TICK_MAX: Maximum number of ticks before scaling back.
141 * SCHED_TICK_SHIFT: Shift factor to avoid rounding away results.
142 * SCHED_TICK_HZ: Compute the number of hz ticks for a given ticks count.
143 * SCHED_TICK_TOTAL: Gives the amount of time we've been recording ticks.
145 #define SCHED_TICK_SECS 10
146 #define SCHED_TICK_TARG (hz * SCHED_TICK_SECS)
147 #define SCHED_TICK_MAX (SCHED_TICK_TARG + hz)
148 #define SCHED_TICK_SHIFT 10
149 #define SCHED_TICK_HZ(ts) ((ts)->ts_ticks >> SCHED_TICK_SHIFT)
150 #define SCHED_TICK_TOTAL(ts) (max((ts)->ts_ltick - (ts)->ts_ftick, hz))
153 * These macros determine priorities for non-interactive threads. They are
154 * assigned a priority based on their recent cpu utilization as expressed
155 * by the ratio of ticks to the tick total. NHALF priorities at the start
156 * and end of the MIN to MAX timeshare range are only reachable with negative
157 * or positive nice respectively.
159 * PRI_RANGE: Priority range for utilization dependent priorities.
160 * PRI_NRESV: Number of nice values.
161 * PRI_TICKS: Compute a priority in PRI_RANGE from the ticks count and total.
162 * PRI_NICE: Determines the part of the priority inherited from nice.
164 #define SCHED_PRI_NRESV (PRIO_MAX - PRIO_MIN)
165 #define SCHED_PRI_NHALF (SCHED_PRI_NRESV / 2)
166 #define SCHED_PRI_MIN (PRI_MIN_BATCH + SCHED_PRI_NHALF)
167 #define SCHED_PRI_MAX (PRI_MAX_BATCH - SCHED_PRI_NHALF)
168 #define SCHED_PRI_RANGE (SCHED_PRI_MAX - SCHED_PRI_MIN + 1)
169 #define SCHED_PRI_TICKS(ts) \
170 (SCHED_TICK_HZ((ts)) / \
171 (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
172 #define SCHED_PRI_NICE(nice) (nice)
175 * These determine the interactivity of a process. Interactivity differs from
176 * cpu utilization in that it expresses the voluntary time slept vs time ran
177 * while cpu utilization includes all time not running. This more accurately
178 * models the intent of the thread.
180 * SLP_RUN_MAX: Maximum amount of sleep time + run time we'll accumulate
181 * before throttling back.
182 * SLP_RUN_FORK: Maximum slp+run time to inherit at fork time.
183 * INTERACT_MAX: Maximum interactivity value. Smaller is better.
184 * INTERACT_THRESH: Threshold for placement on the current runq.
186 #define SCHED_SLP_RUN_MAX ((hz * 5) << SCHED_TICK_SHIFT)
187 #define SCHED_SLP_RUN_FORK ((hz / 2) << SCHED_TICK_SHIFT)
188 #define SCHED_INTERACT_MAX (100)
189 #define SCHED_INTERACT_HALF (SCHED_INTERACT_MAX / 2)
190 #define SCHED_INTERACT_THRESH (30)
193 * These parameters determine the slice behavior for batch work.
195 #define SCHED_SLICE_DEFAULT_DIVISOR 10 /* ~94 ms, 12 stathz ticks. */
196 #define SCHED_SLICE_MIN_DIVISOR 6 /* DEFAULT/MIN = ~16 ms. */
198 /* Flags kept in td_flags. */
199 #define TDF_PICKCPU TDF_SCHED0 /* Thread should pick new CPU. */
200 #define TDF_SLICEEND TDF_SCHED2 /* Thread time slice is over. */
203 * tickincr: Converts a stathz tick into a hz domain scaled by
204 * the shift factor. Without the shift the error rate
205 * due to rounding would be unacceptably high.
206 * realstathz: stathz is sometimes 0 and run off of hz.
207 * sched_slice: Runtime of each thread before rescheduling.
208 * preempt_thresh: Priority threshold for preemption and remote IPIs.
210 static u_int __read_mostly sched_interact = SCHED_INTERACT_THRESH;
211 static int __read_mostly tickincr = 8 << SCHED_TICK_SHIFT;
212 static int __read_mostly realstathz = 127; /* reset during boot. */
213 static int __read_mostly sched_slice = 10; /* reset during boot. */
214 static int __read_mostly sched_slice_min = 1; /* reset during boot. */
216 #ifdef FULL_PREEMPTION
217 static int __read_mostly preempt_thresh = PRI_MAX_IDLE;
219 static int __read_mostly preempt_thresh = PRI_MIN_KERN;
222 static int __read_mostly preempt_thresh = 0;
224 static int __read_mostly static_boost = PRI_MIN_BATCH;
225 static int __read_mostly sched_idlespins = 10000;
226 static int __read_mostly sched_idlespinthresh = -1;
229 * tdq - per processor runqs and statistics. A mutex synchronizes access to
230 * most fields. Some fields are loaded or modified without the mutex.
233 * (c) constant after initialization
234 * (f) flag, set with the tdq lock held, cleared on local CPU
235 * (l) all accesses are CPU-local
236 * (ls) stores are performed by the local CPU, loads may be lockless
237 * (t) all accesses are protected by the tdq mutex
238 * (ts) stores are serialized by the tdq mutex, loads may be lockless
242 * Ordered to improve efficiency of cpu_search() and switch().
243 * tdq_lock is padded to avoid false sharing with tdq_load and
246 struct mtx_padalign tdq_lock; /* run queue lock. */
247 struct cpu_group *tdq_cg; /* (c) Pointer to cpu topology. */
248 struct thread *tdq_curthread; /* (t) Current executing thread. */
249 int tdq_load; /* (ts) Aggregate load. */
250 int tdq_sysload; /* (ts) For loadavg, !ITHD load. */
251 int tdq_cpu_idle; /* (ls) cpu_idle() is active. */
252 int tdq_transferable; /* (ts) Transferable thread count. */
253 short tdq_switchcnt; /* (l) Switches this tick. */
254 short tdq_oldswitchcnt; /* (l) Switches last tick. */
255 u_char tdq_lowpri; /* (ts) Lowest priority thread. */
256 u_char tdq_owepreempt; /* (f) Remote preemption pending. */
257 u_char tdq_idx; /* (t) Current insert index. */
258 u_char tdq_ridx; /* (t) Current removal index. */
259 int tdq_id; /* (c) cpuid. */
260 struct runq tdq_realtime; /* (t) real-time run queue. */
261 struct runq tdq_timeshare; /* (t) timeshare run queue. */
262 struct runq tdq_idle; /* (t) Queue of IDLE threads. */
263 char tdq_name[TDQ_NAME_LEN];
265 char tdq_loadname[TDQ_LOADNAME_LEN];
269 /* Idle thread states and config. */
270 #define TDQ_RUNNING 1
273 /* Lockless accessors. */
274 #define TDQ_LOAD(tdq) atomic_load_int(&(tdq)->tdq_load)
275 #define TDQ_TRANSFERABLE(tdq) atomic_load_int(&(tdq)->tdq_transferable)
276 #define TDQ_SWITCHCNT(tdq) (atomic_load_short(&(tdq)->tdq_switchcnt) + \
277 atomic_load_short(&(tdq)->tdq_oldswitchcnt))
278 #define TDQ_SWITCHCNT_INC(tdq) (atomic_store_short(&(tdq)->tdq_switchcnt, \
279 atomic_load_short(&(tdq)->tdq_switchcnt) + 1))
282 struct cpu_group __read_mostly *cpu_top; /* CPU topology */
284 #define SCHED_AFFINITY_DEFAULT (max(1, hz / 1000))
285 #define SCHED_AFFINITY(ts, t) ((ts)->ts_rltick > ticks - ((t) * affinity))
290 static int rebalance = 1;
291 static int balance_interval = 128; /* Default set in sched_initticks(). */
292 static int __read_mostly affinity;
293 static int __read_mostly steal_idle = 1;
294 static int __read_mostly steal_thresh = 2;
295 static int __read_mostly always_steal = 0;
296 static int __read_mostly trysteal_limit = 2;
299 * One thread queue per processor.
301 static struct tdq __read_mostly *balance_tdq;
302 static int balance_ticks;
303 DPCPU_DEFINE_STATIC(struct tdq, tdq);
304 DPCPU_DEFINE_STATIC(uint32_t, randomval);
306 #define TDQ_SELF() ((struct tdq *)PCPU_GET(sched))
307 #define TDQ_CPU(x) (DPCPU_ID_PTR((x), tdq))
308 #define TDQ_ID(x) ((x)->tdq_id)
310 static struct tdq tdq_cpu;
312 #define TDQ_ID(x) (0)
313 #define TDQ_SELF() (&tdq_cpu)
314 #define TDQ_CPU(x) (&tdq_cpu)
317 #define TDQ_LOCK_ASSERT(t, type) mtx_assert(TDQ_LOCKPTR((t)), (type))
318 #define TDQ_LOCK(t) mtx_lock_spin(TDQ_LOCKPTR((t)))
319 #define TDQ_LOCK_FLAGS(t, f) mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
320 #define TDQ_TRYLOCK(t) mtx_trylock_spin(TDQ_LOCKPTR((t)))
321 #define TDQ_TRYLOCK_FLAGS(t, f) mtx_trylock_spin_flags(TDQ_LOCKPTR((t)), (f))
322 #define TDQ_UNLOCK(t) mtx_unlock_spin(TDQ_LOCKPTR((t)))
323 #define TDQ_LOCKPTR(t) ((struct mtx *)(&(t)->tdq_lock))
325 static void sched_setpreempt(int);
326 static void sched_priority(struct thread *);
327 static void sched_thread_priority(struct thread *, u_char);
328 static int sched_interact_score(struct thread *);
329 static void sched_interact_update(struct thread *);
330 static void sched_interact_fork(struct thread *);
331 static void sched_pctcpu_update(struct td_sched *, int);
333 /* Operations on per processor queues */
334 static struct thread *tdq_choose(struct tdq *);
335 static void tdq_setup(struct tdq *, int i);
336 static void tdq_load_add(struct tdq *, struct thread *);
337 static void tdq_load_rem(struct tdq *, struct thread *);
338 static __inline void tdq_runq_add(struct tdq *, struct thread *, int);
339 static __inline void tdq_runq_rem(struct tdq *, struct thread *);
340 static inline int sched_shouldpreempt(int, int, int);
341 static void tdq_print(int cpu);
342 static void runq_print(struct runq *rq);
343 static int tdq_add(struct tdq *, struct thread *, int);
345 static int tdq_move(struct tdq *, struct tdq *);
346 static int tdq_idled(struct tdq *);
347 static void tdq_notify(struct tdq *, int lowpri);
348 static struct thread *tdq_steal(struct tdq *, int);
349 static struct thread *runq_steal(struct runq *, int);
350 static int sched_pickcpu(struct thread *, int);
351 static void sched_balance(void);
352 static bool sched_balance_pair(struct tdq *, struct tdq *);
353 static inline struct tdq *sched_setcpu(struct thread *, int, int);
354 static inline void thread_unblock_switch(struct thread *, struct mtx *);
355 static int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
356 static int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
357 struct cpu_group *cg, int indent);
360 static void sched_setup(void *dummy);
361 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
363 static void sched_initticks(void *dummy);
364 SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
367 SDT_PROVIDER_DEFINE(sched);
369 SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
370 "struct proc *", "uint8_t");
371 SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
372 "struct proc *", "void *");
373 SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
374 "struct proc *", "void *", "int");
375 SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
376 "struct proc *", "uint8_t", "struct thread *");
377 SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
378 SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
380 SDT_PROBE_DEFINE(sched, , , on__cpu);
381 SDT_PROBE_DEFINE(sched, , , remain__cpu);
382 SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
386 * Print the threads waiting on a run-queue.
389 runq_print(struct runq *rq)
397 for (i = 0; i < RQB_LEN; i++) {
398 printf("\t\trunq bits %d 0x%zx\n",
399 i, rq->rq_status.rqb_bits[i]);
400 for (j = 0; j < RQB_BPW; j++)
401 if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
402 pri = j + (i << RQB_L2BPW);
403 rqh = &rq->rq_queues[pri];
404 TAILQ_FOREACH(td, rqh, td_runq) {
405 printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
406 td, td->td_name, td->td_priority,
407 td->td_rqindex, pri);
414 * Print the status of a per-cpu thread queue. Should be a ddb show cmd.
423 printf("tdq %d:\n", TDQ_ID(tdq));
424 printf("\tlock %p\n", TDQ_LOCKPTR(tdq));
425 printf("\tLock name: %s\n", tdq->tdq_name);
426 printf("\tload: %d\n", tdq->tdq_load);
427 printf("\tswitch cnt: %d\n", tdq->tdq_switchcnt);
428 printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
429 printf("\ttimeshare idx: %d\n", tdq->tdq_idx);
430 printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
431 printf("\tload transferable: %d\n", tdq->tdq_transferable);
432 printf("\tlowest priority: %d\n", tdq->tdq_lowpri);
433 printf("\trealtime runq:\n");
434 runq_print(&tdq->tdq_realtime);
435 printf("\ttimeshare runq:\n");
436 runq_print(&tdq->tdq_timeshare);
437 printf("\tidle runq:\n");
438 runq_print(&tdq->tdq_idle);
442 sched_shouldpreempt(int pri, int cpri, int remote)
445 * If the new priority is not better than the current priority there is
451 * Always preempt idle.
453 if (cpri >= PRI_MIN_IDLE)
456 * If preemption is disabled don't preempt others.
458 if (preempt_thresh == 0)
461 * Preempt if we exceed the threshold.
463 if (pri <= preempt_thresh)
466 * If we're interactive or better and there is non-interactive
467 * or worse running preempt only remote processors.
469 if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
475 * Add a thread to the actual run-queue. Keeps transferable counts up to
476 * date with what is actually on the run-queue. Selects the correct
477 * queue position for timeshare threads.
480 tdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
485 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
486 THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
488 pri = td->td_priority;
489 ts = td_get_sched(td);
491 if (THREAD_CAN_MIGRATE(td)) {
492 tdq->tdq_transferable++;
493 ts->ts_flags |= TSF_XFERABLE;
495 if (pri < PRI_MIN_BATCH) {
496 ts->ts_runq = &tdq->tdq_realtime;
497 } else if (pri <= PRI_MAX_BATCH) {
498 ts->ts_runq = &tdq->tdq_timeshare;
499 KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
500 ("Invalid priority %d on timeshare runq", pri));
502 * This queue contains only priorities between MIN and MAX
503 * batch. Use the whole queue to represent these values.
505 if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
506 pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
507 pri = (pri + tdq->tdq_idx) % RQ_NQS;
509 * This effectively shortens the queue by one so we
510 * can have a one slot difference between idx and
511 * ridx while we wait for threads to drain.
513 if (tdq->tdq_ridx != tdq->tdq_idx &&
514 pri == tdq->tdq_ridx)
515 pri = (unsigned char)(pri - 1) % RQ_NQS;
518 runq_add_pri(ts->ts_runq, td, pri, flags);
521 ts->ts_runq = &tdq->tdq_idle;
522 runq_add(ts->ts_runq, td, flags);
526 * Remove a thread from a run-queue. This typically happens when a thread
527 * is selected to run. Running threads are not on the queue and the
528 * transferable count does not reflect them.
531 tdq_runq_rem(struct tdq *tdq, struct thread *td)
535 ts = td_get_sched(td);
536 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
537 THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
538 KASSERT(ts->ts_runq != NULL,
539 ("tdq_runq_remove: thread %p null ts_runq", td));
540 if (ts->ts_flags & TSF_XFERABLE) {
541 tdq->tdq_transferable--;
542 ts->ts_flags &= ~TSF_XFERABLE;
544 if (ts->ts_runq == &tdq->tdq_timeshare) {
545 if (tdq->tdq_idx != tdq->tdq_ridx)
546 runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
548 runq_remove_idx(ts->ts_runq, td, NULL);
550 runq_remove(ts->ts_runq, td);
554 * Load is maintained for all threads RUNNING and ON_RUNQ. Add the load
555 * for this thread to the referenced thread queue.
558 tdq_load_add(struct tdq *tdq, struct thread *td)
561 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
562 THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
565 if ((td->td_flags & TDF_NOLOAD) == 0)
567 KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
568 SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
572 * Remove the load from a thread that is transitioning to a sleep state or
576 tdq_load_rem(struct tdq *tdq, struct thread *td)
579 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
580 THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
581 KASSERT(tdq->tdq_load != 0,
582 ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
585 if ((td->td_flags & TDF_NOLOAD) == 0)
587 KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
588 SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
592 * Bound timeshare latency by decreasing slice size as load increases. We
593 * consider the maximum latency as the sum of the threads waiting to run
594 * aside from curthread and target no more than sched_slice latency but
595 * no less than sched_slice_min runtime.
598 tdq_slice(struct tdq *tdq)
603 * It is safe to use sys_load here because this is called from
604 * contexts where timeshare threads are running and so there
605 * cannot be higher priority load in the system.
607 load = tdq->tdq_sysload - 1;
608 if (load >= SCHED_SLICE_MIN_DIVISOR)
609 return (sched_slice_min);
611 return (sched_slice);
612 return (sched_slice / load);
616 * Set lowpri to its exact value by searching the run-queue and
617 * evaluating curthread. curthread may be passed as an optimization.
620 tdq_setlowpri(struct tdq *tdq, struct thread *ctd)
624 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
626 ctd = tdq->tdq_curthread;
627 td = tdq_choose(tdq);
628 if (td == NULL || td->td_priority > ctd->td_priority)
629 tdq->tdq_lowpri = ctd->td_priority;
631 tdq->tdq_lowpri = td->td_priority;
636 * We need some randomness. Implement a classic Linear Congruential
637 * Generator X_{n+1}=(aX_n+c) mod m. These values are optimized for
638 * m = 2^32, a = 69069 and c = 5. We only return the upper 16 bits
639 * of the random state (in the low bits of our answer) to keep
640 * the maximum randomness.
647 rndptr = DPCPU_PTR(randomval);
648 *rndptr = *rndptr * 69069 + 5;
650 return (*rndptr >> 16);
654 cpuset_t *cs_mask; /* The mask of allowed CPUs to choose from. */
655 int cs_prefer; /* Prefer this CPU and groups including it. */
656 int cs_running; /* The thread is now running at cs_prefer. */
657 int cs_pri; /* Min priority for low. */
658 int cs_load; /* Max load for low, min load for high. */
659 int cs_trans; /* Min transferable load for high. */
662 struct cpu_search_res {
663 int csr_cpu; /* The best CPU found. */
664 int csr_load; /* The load of cs_cpu. */
668 * Search the tree of cpu_groups for the lowest or highest loaded CPU.
669 * These routines actually compare the load on all paths through the tree
670 * and find the least loaded cpu on the least loaded path, which may differ
671 * from the least loaded cpu in the system. This balances work among caches
675 cpu_search_lowest(const struct cpu_group *cg, const struct cpu_search *s,
676 struct cpu_search_res *r)
678 struct cpu_search_res lr;
680 int c, bload, l, load, p, total;
686 /* Loop through children CPU groups if there are any. */
687 if (cg->cg_children > 0) {
688 for (c = cg->cg_children - 1; c >= 0; c--) {
689 load = cpu_search_lowest(&cg->cg_child[c], s, &lr);
693 * When balancing do not prefer SMT groups with load >1.
694 * It allows round-robin between SMT groups with equal
695 * load within parent group for more fair scheduling.
697 if (__predict_false(s->cs_running) &&
698 (cg->cg_child[c].cg_flags & CG_FLAG_THREAD) &&
699 load >= 128 && (load & 128) != 0)
702 if (lr.csr_cpu >= 0 && (load < bload ||
703 (load == bload && lr.csr_load < r->csr_load))) {
705 r->csr_cpu = lr.csr_cpu;
706 r->csr_load = lr.csr_load;
712 /* Loop through children CPUs otherwise. */
713 for (c = cg->cg_last; c >= cg->cg_first; c--) {
714 if (!CPU_ISSET(c, &cg->cg_mask))
718 if (c == s->cs_prefer) {
719 if (__predict_false(s->cs_running))
728 * Check this CPU is acceptable.
729 * If the threads is already on the CPU, don't look on the TDQ
730 * priority, since it can be the priority of the thread itself.
732 if (l > s->cs_load ||
733 (atomic_load_char(&tdq->tdq_lowpri) <= s->cs_pri &&
734 (!s->cs_running || c != s->cs_prefer)) ||
735 !CPU_ISSET(c, s->cs_mask))
739 * When balancing do not prefer CPUs with load > 1.
740 * It allows round-robin between CPUs with equal load
741 * within the CPU group for more fair scheduling.
743 if (__predict_false(s->cs_running) && l > 0)
746 load -= sched_random() % 128;
747 if (bload > load - p) {
757 cpu_search_highest(const struct cpu_group *cg, const struct cpu_search *s,
758 struct cpu_search_res *r)
760 struct cpu_search_res lr;
762 int c, bload, l, load, total;
768 /* Loop through children CPU groups if there are any. */
769 if (cg->cg_children > 0) {
770 for (c = cg->cg_children - 1; c >= 0; c--) {
771 load = cpu_search_highest(&cg->cg_child[c], s, &lr);
773 if (lr.csr_cpu >= 0 && (load > bload ||
774 (load == bload && lr.csr_load > r->csr_load))) {
776 r->csr_cpu = lr.csr_cpu;
777 r->csr_load = lr.csr_load;
783 /* Loop through children CPUs otherwise. */
784 for (c = cg->cg_last; c >= cg->cg_first; c--) {
785 if (!CPU_ISSET(c, &cg->cg_mask))
793 * Check this CPU is acceptable.
795 if (l < s->cs_load || TDQ_TRANSFERABLE(tdq) < s->cs_trans ||
796 !CPU_ISSET(c, s->cs_mask))
799 load -= sched_random() % 256;
810 * Find the cpu with the least load via the least loaded path that has a
811 * lowpri greater than pri pri. A pri of -1 indicates any priority is
815 sched_lowest(const struct cpu_group *cg, cpuset_t *mask, int pri, int maxload,
816 int prefer, int running)
819 struct cpu_search_res r;
821 s.cs_prefer = prefer;
822 s.cs_running = running;
826 cpu_search_lowest(cg, &s, &r);
831 * Find the cpu with the highest load via the highest loaded path.
834 sched_highest(const struct cpu_group *cg, cpuset_t *mask, int minload,
838 struct cpu_search_res r;
842 s.cs_trans = mintrans;
843 cpu_search_highest(cg, &s, &r);
848 sched_balance_group(struct cpu_group *cg)
852 cpuset_t hmask, lmask;
853 int high, low, anylow;
857 high = sched_highest(cg, &hmask, 1, 0);
858 /* Stop if there is no more CPU with transferrable threads. */
861 CPU_CLR(high, &hmask);
862 CPU_COPY(&hmask, &lmask);
863 /* Stop if there is no more CPU left for low. */
864 if (CPU_EMPTY(&lmask))
867 if (TDQ_LOAD(tdq) == 1) {
869 * There is only one running thread. We can't move
870 * it from here, so tell it to pick new CPU by itself.
873 td = tdq->tdq_curthread;
874 if (td->td_lock == TDQ_LOCKPTR(tdq) &&
875 (td->td_flags & TDF_IDLETD) == 0 &&
876 THREAD_CAN_MIGRATE(td)) {
877 td->td_flags |= TDF_NEEDRESCHED | TDF_PICKCPU;
879 ipi_cpu(high, IPI_AST);
886 if (TDQ_TRANSFERABLE(tdq) == 0)
888 low = sched_lowest(cg, &lmask, -1, TDQ_LOAD(tdq) - 1, high, 1);
889 /* Stop if we looked well and found no less loaded CPU. */
890 if (anylow && low == -1)
892 /* Go to next high if we found no less loaded CPU. */
895 /* Transfer thread from high to low. */
896 if (sched_balance_pair(tdq, TDQ_CPU(low))) {
897 /* CPU that got thread can no longer be a donor. */
898 CPU_CLR(low, &hmask);
901 * If failed, then there is no threads on high
902 * that can run on this low. Drop low from low
903 * mask and look for different one.
905 CPU_CLR(low, &lmask);
917 balance_ticks = max(balance_interval / 2, 1) +
918 (sched_random() % balance_interval);
921 sched_balance_group(cpu_top);
926 * Lock two thread queues using their address to maintain lock order.
929 tdq_lock_pair(struct tdq *one, struct tdq *two)
933 TDQ_LOCK_FLAGS(two, MTX_DUPOK);
936 TDQ_LOCK_FLAGS(one, MTX_DUPOK);
941 * Unlock two thread queues. Order is not important here.
944 tdq_unlock_pair(struct tdq *one, struct tdq *two)
951 * Transfer load between two imbalanced thread queues. Returns true if a thread
952 * was moved between the queues, and false otherwise.
955 sched_balance_pair(struct tdq *high, struct tdq *low)
961 tdq_lock_pair(high, low);
964 * Transfer a thread from high to low.
966 if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load) {
967 lowpri = tdq_move(high, low);
970 * In case the target isn't the current CPU notify it of
971 * the new load, possibly sending an IPI to force it to
972 * reschedule. Otherwise maybe schedule a preemption.
975 if (cpu != PCPU_GET(cpuid))
976 tdq_notify(low, lowpri);
978 sched_setpreempt(low->tdq_lowpri);
982 tdq_unlock_pair(high, low);
987 * Move a thread from one thread queue to another. Returns -1 if the source
988 * queue was empty, else returns the maximum priority of all threads in
989 * the destination queue prior to the addition of the new thread. In the latter
990 * case, this priority can be used to determine whether an IPI needs to be
994 tdq_move(struct tdq *from, struct tdq *to)
999 TDQ_LOCK_ASSERT(from, MA_OWNED);
1000 TDQ_LOCK_ASSERT(to, MA_OWNED);
1003 td = tdq_steal(from, cpu);
1008 * Although the run queue is locked the thread may be
1009 * blocked. We can not set the lock until it is unblocked.
1011 thread_lock_block_wait(td);
1013 THREAD_LOCKPTR_ASSERT(td, TDQ_LOCKPTR(from));
1014 td->td_lock = TDQ_LOCKPTR(to);
1015 td_get_sched(td)->ts_cpu = cpu;
1016 return (tdq_add(to, td, SRQ_YIELDING));
1020 * This tdq has idled. Try to steal a thread from another cpu and switch
1024 tdq_idled(struct tdq *tdq)
1026 struct cpu_group *cg, *parent;
1029 int cpu, switchcnt, goup;
1031 if (smp_started == 0 || steal_idle == 0 || tdq->tdq_cg == NULL)
1034 CPU_CLR(PCPU_GET(cpuid), &mask);
1036 switchcnt = TDQ_SWITCHCNT(tdq);
1037 for (cg = tdq->tdq_cg, goup = 0; ; ) {
1038 cpu = sched_highest(cg, &mask, steal_thresh, 1);
1040 * We were assigned a thread but not preempted. Returning
1041 * 0 here will cause our caller to switch to it.
1047 * We found no CPU to steal from in this group. Escalate to
1048 * the parent and repeat. But if parent has only two children
1049 * groups we can avoid searching this group again by searching
1050 * the other one specifically and then escalating two levels.
1057 parent = cg->cg_parent;
1060 if (parent->cg_children == 2) {
1061 if (cg == &parent->cg_child[0])
1062 cg = &parent->cg_child[1];
1064 cg = &parent->cg_child[0];
1070 steal = TDQ_CPU(cpu);
1072 * The data returned by sched_highest() is stale and
1073 * the chosen CPU no longer has an eligible thread.
1075 * Testing this ahead of tdq_lock_pair() only catches
1076 * this situation about 20% of the time on an 8 core
1077 * 16 thread Ryzen 7, but it still helps performance.
1079 if (TDQ_LOAD(steal) < steal_thresh ||
1080 TDQ_TRANSFERABLE(steal) == 0)
1083 * Try to lock both queues. If we are assigned a thread while
1084 * waited for the lock, switch to it now instead of stealing.
1085 * If we can't get the lock, then somebody likely got there
1086 * first so continue searching.
1089 if (tdq->tdq_load > 0) {
1090 mi_switch(SW_VOL | SWT_IDLE);
1093 if (TDQ_TRYLOCK_FLAGS(steal, MTX_DUPOK) == 0) {
1095 CPU_CLR(cpu, &mask);
1099 * The data returned by sched_highest() is stale and
1100 * the chosen CPU no longer has an eligible thread, or
1101 * we were preempted and the CPU loading info may be out
1102 * of date. The latter is rare. In either case restart
1105 if (TDQ_LOAD(steal) < steal_thresh ||
1106 TDQ_TRANSFERABLE(steal) == 0 ||
1107 switchcnt != TDQ_SWITCHCNT(tdq)) {
1108 tdq_unlock_pair(tdq, steal);
1112 * Steal the thread and switch to it.
1114 if (tdq_move(steal, tdq) != -1)
1117 * We failed to acquire a thread even though it looked
1118 * like one was available. This could be due to affinity
1119 * restrictions or for other reasons. Loop again after
1120 * removing this CPU from the set. The restart logic
1121 * above does not restore this CPU to the set due to the
1122 * likelyhood of failing here again.
1124 CPU_CLR(cpu, &mask);
1125 tdq_unlock_pair(tdq, steal);
1128 mi_switch(SW_VOL | SWT_IDLE);
1133 * Notify a remote cpu of new work. Sends an IPI if criteria are met.
1135 * "lowpri" is the minimum scheduling priority among all threads on
1136 * the queue prior to the addition of the new thread.
1139 tdq_notify(struct tdq *tdq, int lowpri)
1143 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1144 KASSERT(tdq->tdq_lowpri <= lowpri,
1145 ("tdq_notify: lowpri %d > tdq_lowpri %d", lowpri, tdq->tdq_lowpri));
1147 if (tdq->tdq_owepreempt)
1151 * Check to see if the newly added thread should preempt the one
1152 * currently running.
1154 if (!sched_shouldpreempt(tdq->tdq_lowpri, lowpri, 1))
1158 * Make sure that our caller's earlier update to tdq_load is
1159 * globally visible before we read tdq_cpu_idle. Idle thread
1160 * accesses both of them without locks, and the order is important.
1162 atomic_thread_fence_seq_cst();
1165 * Try to figure out if we can signal the idle thread instead of sending
1166 * an IPI. This check is racy; at worst, we will deliever an IPI
1170 if (TD_IS_IDLETHREAD(tdq->tdq_curthread) &&
1171 (atomic_load_int(&tdq->tdq_cpu_idle) == 0 || cpu_idle_wakeup(cpu)))
1175 * The run queues have been updated, so any switch on the remote CPU
1176 * will satisfy the preemption request.
1178 tdq->tdq_owepreempt = 1;
1179 ipi_cpu(cpu, IPI_PREEMPT);
1183 * Steals load from a timeshare queue. Honors the rotating queue head
1186 static struct thread *
1187 runq_steal_from(struct runq *rq, int cpu, u_char start)
1191 struct thread *td, *first;
1195 rqb = &rq->rq_status;
1196 bit = start & (RQB_BPW -1);
1199 for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1200 if (rqb->rqb_bits[i] == 0)
1203 bit = RQB_FFS(rqb->rqb_bits[i]);
1204 for (; bit < RQB_BPW; bit++) {
1205 if ((rqb->rqb_bits[i] & (1ul << bit)) == 0)
1207 rqh = &rq->rq_queues[bit + (i << RQB_L2BPW)];
1208 TAILQ_FOREACH(td, rqh, td_runq) {
1210 if (THREAD_CAN_MIGRATE(td) &&
1211 THREAD_CAN_SCHED(td, cpu))
1223 if (first && THREAD_CAN_MIGRATE(first) &&
1224 THREAD_CAN_SCHED(first, cpu))
1230 * Steals load from a standard linear queue.
1232 static struct thread *
1233 runq_steal(struct runq *rq, int cpu)
1241 rqb = &rq->rq_status;
1242 for (word = 0; word < RQB_LEN; word++) {
1243 if (rqb->rqb_bits[word] == 0)
1245 for (bit = 0; bit < RQB_BPW; bit++) {
1246 if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
1248 rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
1249 TAILQ_FOREACH(td, rqh, td_runq)
1250 if (THREAD_CAN_MIGRATE(td) &&
1251 THREAD_CAN_SCHED(td, cpu))
1259 * Attempt to steal a thread in priority order from a thread queue.
1261 static struct thread *
1262 tdq_steal(struct tdq *tdq, int cpu)
1266 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1267 if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
1269 if ((td = runq_steal_from(&tdq->tdq_timeshare,
1270 cpu, tdq->tdq_ridx)) != NULL)
1272 return (runq_steal(&tdq->tdq_idle, cpu));
1276 * Sets the thread lock and ts_cpu to match the requested cpu. Unlocks the
1277 * current lock and returns with the assigned queue locked.
1279 static inline struct tdq *
1280 sched_setcpu(struct thread *td, int cpu, int flags)
1286 THREAD_LOCK_ASSERT(td, MA_OWNED);
1288 td_get_sched(td)->ts_cpu = cpu;
1290 * If the lock matches just return the queue.
1292 if (td->td_lock == TDQ_LOCKPTR(tdq)) {
1293 KASSERT((flags & SRQ_HOLD) == 0,
1294 ("sched_setcpu: Invalid lock for SRQ_HOLD"));
1299 * The hard case, migration, we need to block the thread first to
1300 * prevent order reversals with other cpus locks.
1303 mtx = thread_lock_block(td);
1304 if ((flags & SRQ_HOLD) == 0)
1305 mtx_unlock_spin(mtx);
1307 thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1312 SCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
1313 SCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
1314 SCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
1315 SCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
1316 SCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
1317 SCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
1320 sched_pickcpu(struct thread *td, int flags)
1322 struct cpu_group *cg, *ccg;
1323 struct td_sched *ts;
1326 int cpu, pri, r, self, intr;
1328 self = PCPU_GET(cpuid);
1329 ts = td_get_sched(td);
1330 KASSERT(!CPU_ABSENT(ts->ts_cpu), ("sched_pickcpu: Start scheduler on "
1331 "absent CPU %d for thread %s.", ts->ts_cpu, td->td_name));
1332 if (smp_started == 0)
1335 * Don't migrate a running thread from sched_switch().
1337 if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1338 return (ts->ts_cpu);
1340 * Prefer to run interrupt threads on the processors that generate
1343 if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1344 curthread->td_intr_nesting_level) {
1346 if (tdq->tdq_lowpri >= PRI_MIN_IDLE) {
1347 SCHED_STAT_INC(pickcpu_idle_affinity);
1356 tdq = TDQ_CPU(ts->ts_cpu);
1360 * If the thread can run on the last cpu and the affinity has not
1361 * expired and it is idle, run it there.
1363 if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
1364 atomic_load_char(&tdq->tdq_lowpri) >= PRI_MIN_IDLE &&
1365 SCHED_AFFINITY(ts, CG_SHARE_L2)) {
1366 if (cg->cg_flags & CG_FLAG_THREAD) {
1367 /* Check all SMT threads for being idle. */
1368 for (cpu = cg->cg_first; cpu <= cg->cg_last; cpu++) {
1370 atomic_load_char(&TDQ_CPU(cpu)->tdq_lowpri);
1371 if (CPU_ISSET(cpu, &cg->cg_mask) &&
1375 if (cpu > cg->cg_last) {
1376 SCHED_STAT_INC(pickcpu_idle_affinity);
1377 return (ts->ts_cpu);
1380 SCHED_STAT_INC(pickcpu_idle_affinity);
1381 return (ts->ts_cpu);
1386 * Search for the last level cache CPU group in the tree.
1387 * Skip SMT, identical groups and caches with expired affinity.
1388 * Interrupt threads affinity is explicit and never expires.
1390 for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
1391 if (cg->cg_flags & CG_FLAG_THREAD)
1393 if (cg->cg_children == 1 || cg->cg_count == 1)
1395 if (cg->cg_level == CG_SHARE_NONE ||
1396 (!intr && !SCHED_AFFINITY(ts, cg->cg_level)))
1400 /* Found LLC shared by all CPUs, so do a global search. */
1404 mask = &td->td_cpuset->cs_mask;
1405 pri = td->td_priority;
1406 r = TD_IS_RUNNING(td);
1408 * Try hard to keep interrupts within found LLC. Search the LLC for
1409 * the least loaded CPU we can run now. For NUMA systems it should
1410 * be within target domain, and it also reduces scheduling overhead.
1412 if (ccg != NULL && intr) {
1413 cpu = sched_lowest(ccg, mask, pri, INT_MAX, ts->ts_cpu, r);
1415 SCHED_STAT_INC(pickcpu_intrbind);
1417 /* Search the LLC for the least loaded idle CPU we can run now. */
1419 cpu = sched_lowest(ccg, mask, max(pri, PRI_MAX_TIMESHARE),
1420 INT_MAX, ts->ts_cpu, r);
1422 SCHED_STAT_INC(pickcpu_affinity);
1424 /* Search globally for the least loaded CPU we can run now. */
1426 cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu, r);
1428 SCHED_STAT_INC(pickcpu_lowest);
1430 /* Search globally for the least loaded CPU. */
1432 cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu, r);
1434 SCHED_STAT_INC(pickcpu_lowest);
1436 KASSERT(cpu >= 0, ("sched_pickcpu: Failed to find a cpu."));
1437 KASSERT(!CPU_ABSENT(cpu), ("sched_pickcpu: Picked absent CPU %d.", cpu));
1439 * Compare the lowest loaded cpu to current cpu.
1442 if (THREAD_CAN_SCHED(td, self) && TDQ_SELF()->tdq_lowpri > pri &&
1443 atomic_load_char(&tdq->tdq_lowpri) < PRI_MIN_IDLE &&
1444 TDQ_LOAD(TDQ_SELF()) <= TDQ_LOAD(tdq) + 1) {
1445 SCHED_STAT_INC(pickcpu_local);
1448 if (cpu != ts->ts_cpu)
1449 SCHED_STAT_INC(pickcpu_migration);
1455 * Pick the highest priority task we have and return it.
1457 static struct thread *
1458 tdq_choose(struct tdq *tdq)
1462 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1463 td = runq_choose(&tdq->tdq_realtime);
1466 td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1468 KASSERT(td->td_priority >= PRI_MIN_BATCH,
1469 ("tdq_choose: Invalid priority on timeshare queue %d",
1473 td = runq_choose(&tdq->tdq_idle);
1475 KASSERT(td->td_priority >= PRI_MIN_IDLE,
1476 ("tdq_choose: Invalid priority on idle queue %d",
1485 * Initialize a thread queue.
1488 tdq_setup(struct tdq *tdq, int id)
1492 printf("ULE: setup cpu %d\n", id);
1493 runq_init(&tdq->tdq_realtime);
1494 runq_init(&tdq->tdq_timeshare);
1495 runq_init(&tdq->tdq_idle);
1497 snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1498 "sched lock %d", (int)TDQ_ID(tdq));
1499 mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock", MTX_SPIN);
1501 snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
1502 "CPU %d load", (int)TDQ_ID(tdq));
1508 sched_setup_smp(void)
1513 cpu_top = smp_topo();
1515 tdq = DPCPU_ID_PTR(i, tdq);
1517 tdq->tdq_cg = smp_topo_find(cpu_top, i);
1518 if (tdq->tdq_cg == NULL)
1519 panic("Can't find cpu group for %d\n", i);
1520 DPCPU_ID_SET(i, randomval, i * 69069 + 5);
1522 PCPU_SET(sched, DPCPU_PTR(tdq));
1523 balance_tdq = TDQ_SELF();
1528 * Setup the thread queues and initialize the topology based on MD
1532 sched_setup(void *dummy)
1539 tdq_setup(TDQ_SELF(), 0);
1543 /* Add thread0's load since it's running. */
1545 thread0.td_lock = TDQ_LOCKPTR(tdq);
1546 tdq_load_add(tdq, &thread0);
1547 tdq->tdq_curthread = &thread0;
1548 tdq->tdq_lowpri = thread0.td_priority;
1553 * This routine determines time constants after stathz and hz are setup.
1557 sched_initticks(void *dummy)
1561 realstathz = stathz ? stathz : hz;
1562 sched_slice = realstathz / SCHED_SLICE_DEFAULT_DIVISOR;
1563 sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
1564 hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
1568 * tickincr is shifted out by 10 to avoid rounding errors due to
1569 * hz not being evenly divisible by stathz on all platforms.
1571 incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1573 * This does not work for values of stathz that are more than
1574 * 1 << SCHED_TICK_SHIFT * hz. In practice this does not happen.
1581 * Set the default balance interval now that we know
1582 * what realstathz is.
1584 balance_interval = realstathz;
1585 balance_ticks = balance_interval;
1586 affinity = SCHED_AFFINITY_DEFAULT;
1588 if (sched_idlespinthresh < 0)
1589 sched_idlespinthresh = 2 * max(10000, 6 * hz) / realstathz;
1593 * This is the core of the interactivity algorithm. Determines a score based
1594 * on past behavior. It is the ratio of sleep time to run time scaled to
1595 * a [0, 100] integer. This is the voluntary sleep time of a process, which
1596 * differs from the cpu usage because it does not account for time spent
1597 * waiting on a run-queue. Would be prettier if we had floating point.
1599 * When a thread's sleep time is greater than its run time the
1603 * interactivity score = ---------------------
1604 * sleep time / run time
1607 * When a thread's run time is greater than its sleep time the
1611 * interactivity score = --------------------- + scaling factor
1612 * run time / sleep time
1615 sched_interact_score(struct thread *td)
1617 struct td_sched *ts;
1620 ts = td_get_sched(td);
1622 * The score is only needed if this is likely to be an interactive
1623 * task. Don't go through the expense of computing it if there's
1626 if (sched_interact <= SCHED_INTERACT_HALF &&
1627 ts->ts_runtime >= ts->ts_slptime)
1628 return (SCHED_INTERACT_HALF);
1630 if (ts->ts_runtime > ts->ts_slptime) {
1631 div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1632 return (SCHED_INTERACT_HALF +
1633 (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1635 if (ts->ts_slptime > ts->ts_runtime) {
1636 div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1637 return (ts->ts_runtime / div);
1639 /* runtime == slptime */
1641 return (SCHED_INTERACT_HALF);
1644 * This can happen if slptime and runtime are 0.
1651 * Scale the scheduling priority according to the "interactivity" of this
1655 sched_priority(struct thread *td)
1659 if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
1662 * If the score is interactive we place the thread in the realtime
1663 * queue with a priority that is less than kernel and interrupt
1664 * priorities. These threads are not subject to nice restrictions.
1666 * Scores greater than this are placed on the normal timeshare queue
1667 * where the priority is partially decided by the most recent cpu
1668 * utilization and the rest is decided by nice value.
1670 * The nice value of the process has a linear effect on the calculated
1671 * score. Negative nice values make it easier for a thread to be
1672 * considered interactive.
1674 score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1675 if (score < sched_interact) {
1676 pri = PRI_MIN_INTERACT;
1677 pri += (PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) * score /
1679 KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
1680 ("sched_priority: invalid interactive priority %u score %u",
1683 pri = SCHED_PRI_MIN;
1684 if (td_get_sched(td)->ts_ticks)
1685 pri += min(SCHED_PRI_TICKS(td_get_sched(td)),
1686 SCHED_PRI_RANGE - 1);
1687 pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1688 KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
1689 ("sched_priority: invalid priority %u: nice %d, "
1690 "ticks %d ftick %d ltick %d tick pri %d",
1691 pri, td->td_proc->p_nice, td_get_sched(td)->ts_ticks,
1692 td_get_sched(td)->ts_ftick, td_get_sched(td)->ts_ltick,
1693 SCHED_PRI_TICKS(td_get_sched(td))));
1695 sched_user_prio(td, pri);
1701 * This routine enforces a maximum limit on the amount of scheduling history
1702 * kept. It is called after either the slptime or runtime is adjusted. This
1703 * function is ugly due to integer math.
1706 sched_interact_update(struct thread *td)
1708 struct td_sched *ts;
1711 ts = td_get_sched(td);
1712 sum = ts->ts_runtime + ts->ts_slptime;
1713 if (sum < SCHED_SLP_RUN_MAX)
1716 * This only happens from two places:
1717 * 1) We have added an unusual amount of run time from fork_exit.
1718 * 2) We have added an unusual amount of sleep time from sched_sleep().
1720 if (sum > SCHED_SLP_RUN_MAX * 2) {
1721 if (ts->ts_runtime > ts->ts_slptime) {
1722 ts->ts_runtime = SCHED_SLP_RUN_MAX;
1725 ts->ts_slptime = SCHED_SLP_RUN_MAX;
1731 * If we have exceeded by more than 1/5th then the algorithm below
1732 * will not bring us back into range. Dividing by two here forces
1733 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1735 if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1736 ts->ts_runtime /= 2;
1737 ts->ts_slptime /= 2;
1740 ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1741 ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1745 * Scale back the interactivity history when a child thread is created. The
1746 * history is inherited from the parent but the thread may behave totally
1747 * differently. For example, a shell spawning a compiler process. We want
1748 * to learn that the compiler is behaving badly very quickly.
1751 sched_interact_fork(struct thread *td)
1753 struct td_sched *ts;
1757 ts = td_get_sched(td);
1758 sum = ts->ts_runtime + ts->ts_slptime;
1759 if (sum > SCHED_SLP_RUN_FORK) {
1760 ratio = sum / SCHED_SLP_RUN_FORK;
1761 ts->ts_runtime /= ratio;
1762 ts->ts_slptime /= ratio;
1767 * Called from proc0_init() to setup the scheduler fields.
1772 struct td_sched *ts0;
1775 * Set up the scheduler specific parts of thread0.
1777 ts0 = td_get_sched(&thread0);
1778 ts0->ts_ltick = ticks;
1779 ts0->ts_ftick = ticks;
1781 ts0->ts_cpu = curcpu; /* set valid CPU number */
1785 * schedinit_ap() is needed prior to calling sched_throw(NULL) to ensure that
1786 * the pcpu requirements are met for any calls in the period between curthread
1787 * initialization and sched_throw(). One can safely add threads to the queue
1788 * before sched_throw(), for instance, as long as the thread lock is setup
1791 * TDQ_SELF() relies on the below sched pcpu setting; it may be used only
1792 * after schedinit_ap().
1799 PCPU_SET(sched, DPCPU_PTR(tdq));
1801 PCPU_GET(idlethread)->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1805 * This is only somewhat accurate since given many processes of the same
1806 * priority they will switch when their slices run out, which will be
1807 * at most sched_slice stathz ticks.
1810 sched_rr_interval(void)
1813 /* Convert sched_slice from stathz to hz. */
1814 return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
1818 * Update the percent cpu tracking information when it is requested or
1819 * the total history exceeds the maximum. We keep a sliding history of
1820 * tick counts that slowly decays. This is less precise than the 4BSD
1821 * mechanism since it happens with less regular and frequent events.
1824 sched_pctcpu_update(struct td_sched *ts, int run)
1829 * The signed difference may be negative if the thread hasn't run for
1830 * over half of the ticks rollover period.
1832 if ((u_int)(t - ts->ts_ltick) >= SCHED_TICK_TARG) {
1834 ts->ts_ftick = t - SCHED_TICK_TARG;
1835 } else if (t - ts->ts_ftick >= SCHED_TICK_MAX) {
1836 ts->ts_ticks = (ts->ts_ticks / (ts->ts_ltick - ts->ts_ftick)) *
1837 (ts->ts_ltick - (t - SCHED_TICK_TARG));
1838 ts->ts_ftick = t - SCHED_TICK_TARG;
1841 ts->ts_ticks += (t - ts->ts_ltick) << SCHED_TICK_SHIFT;
1846 * Adjust the priority of a thread. Move it to the appropriate run-queue
1847 * if necessary. This is the back-end for several priority related
1851 sched_thread_priority(struct thread *td, u_char prio)
1853 struct td_sched *ts;
1857 KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
1858 "prio:%d", td->td_priority, "new prio:%d", prio,
1859 KTR_ATTR_LINKED, sched_tdname(curthread));
1860 SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
1861 if (td != curthread && prio < td->td_priority) {
1862 KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
1863 "lend prio", "prio:%d", td->td_priority, "new prio:%d",
1864 prio, KTR_ATTR_LINKED, sched_tdname(td));
1865 SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
1868 ts = td_get_sched(td);
1869 THREAD_LOCK_ASSERT(td, MA_OWNED);
1870 if (td->td_priority == prio)
1873 * If the priority has been elevated due to priority
1874 * propagation, we may have to move ourselves to a new
1875 * queue. This could be optimized to not re-add in some
1878 if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1880 td->td_priority = prio;
1881 sched_add(td, SRQ_BORROWING | SRQ_HOLDTD);
1885 * If the thread is currently running we may have to adjust the lowpri
1886 * information so other cpus are aware of our current priority.
1888 if (TD_IS_RUNNING(td)) {
1889 tdq = TDQ_CPU(ts->ts_cpu);
1890 oldpri = td->td_priority;
1891 td->td_priority = prio;
1892 if (prio < tdq->tdq_lowpri)
1893 tdq->tdq_lowpri = prio;
1894 else if (tdq->tdq_lowpri == oldpri)
1895 tdq_setlowpri(tdq, td);
1898 td->td_priority = prio;
1902 * Update a thread's priority when it is lent another thread's
1906 sched_lend_prio(struct thread *td, u_char prio)
1909 td->td_flags |= TDF_BORROWING;
1910 sched_thread_priority(td, prio);
1914 * Restore a thread's priority when priority propagation is
1915 * over. The prio argument is the minimum priority the thread
1916 * needs to have to satisfy other possible priority lending
1917 * requests. If the thread's regular priority is less
1918 * important than prio, the thread will keep a priority boost
1922 sched_unlend_prio(struct thread *td, u_char prio)
1926 if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1927 td->td_base_pri <= PRI_MAX_TIMESHARE)
1928 base_pri = td->td_user_pri;
1930 base_pri = td->td_base_pri;
1931 if (prio >= base_pri) {
1932 td->td_flags &= ~TDF_BORROWING;
1933 sched_thread_priority(td, base_pri);
1935 sched_lend_prio(td, prio);
1939 * Standard entry for setting the priority to an absolute value.
1942 sched_prio(struct thread *td, u_char prio)
1946 /* First, update the base priority. */
1947 td->td_base_pri = prio;
1950 * If the thread is borrowing another thread's priority, don't
1951 * ever lower the priority.
1953 if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1956 /* Change the real priority. */
1957 oldprio = td->td_priority;
1958 sched_thread_priority(td, prio);
1961 * If the thread is on a turnstile, then let the turnstile update
1964 if (TD_ON_LOCK(td) && oldprio != prio)
1965 turnstile_adjust(td, oldprio);
1969 * Set the base user priority, does not effect current running priority.
1972 sched_user_prio(struct thread *td, u_char prio)
1975 td->td_base_user_pri = prio;
1976 if (td->td_lend_user_pri <= prio)
1978 td->td_user_pri = prio;
1982 sched_lend_user_prio(struct thread *td, u_char prio)
1985 THREAD_LOCK_ASSERT(td, MA_OWNED);
1986 td->td_lend_user_pri = prio;
1987 td->td_user_pri = min(prio, td->td_base_user_pri);
1988 if (td->td_priority > td->td_user_pri)
1989 sched_prio(td, td->td_user_pri);
1990 else if (td->td_priority != td->td_user_pri)
1991 td->td_flags |= TDF_NEEDRESCHED;
1995 * Like the above but first check if there is anything to do.
1998 sched_lend_user_prio_cond(struct thread *td, u_char prio)
2001 if (td->td_lend_user_pri != prio)
2003 if (td->td_user_pri != min(prio, td->td_base_user_pri))
2005 if (td->td_priority != td->td_user_pri)
2011 sched_lend_user_prio(td, prio);
2017 * This tdq is about to idle. Try to steal a thread from another CPU before
2018 * choosing the idle thread.
2021 tdq_trysteal(struct tdq *tdq)
2023 struct cpu_group *cg, *parent;
2028 if (smp_started == 0 || steal_idle == 0 || trysteal_limit == 0 ||
2029 tdq->tdq_cg == NULL)
2032 CPU_CLR(PCPU_GET(cpuid), &mask);
2033 /* We don't want to be preempted while we're iterating. */
2036 for (i = 1, cg = tdq->tdq_cg, goup = 0; ; ) {
2037 cpu = sched_highest(cg, &mask, steal_thresh, 1);
2039 * If a thread was added while interrupts were disabled don't
2042 if (TDQ_LOAD(tdq) > 0) {
2048 * We found no CPU to steal from in this group. Escalate to
2049 * the parent and repeat. But if parent has only two children
2050 * groups we can avoid searching this group again by searching
2051 * the other one specifically and then escalating two levels.
2058 if (++i > trysteal_limit) {
2062 parent = cg->cg_parent;
2063 if (parent == NULL) {
2067 if (parent->cg_children == 2) {
2068 if (cg == &parent->cg_child[0])
2069 cg = &parent->cg_child[1];
2071 cg = &parent->cg_child[0];
2077 steal = TDQ_CPU(cpu);
2079 * The data returned by sched_highest() is stale and
2080 * the chosen CPU no longer has an eligible thread.
2081 * At this point unconditionally exit the loop to bound
2082 * the time spent in the critcal section.
2084 if (TDQ_LOAD(steal) < steal_thresh ||
2085 TDQ_TRANSFERABLE(steal) == 0)
2088 * Try to lock both queues. If we are assigned a thread while
2089 * waited for the lock, switch to it now instead of stealing.
2090 * If we can't get the lock, then somebody likely got there
2094 if (tdq->tdq_load > 0)
2096 if (TDQ_TRYLOCK_FLAGS(steal, MTX_DUPOK) == 0)
2099 * The data returned by sched_highest() is stale and
2100 * the chosen CPU no longer has an eligible thread.
2102 if (TDQ_LOAD(steal) < steal_thresh ||
2103 TDQ_TRANSFERABLE(steal) == 0) {
2108 * If we fail to acquire one due to affinity restrictions,
2109 * bail out and let the idle thread to a more complete search
2110 * outside of a critical section.
2112 if (tdq_move(steal, tdq) == -1) {
2124 * Handle migration from sched_switch(). This happens only for
2128 sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
2135 KASSERT(THREAD_CAN_MIGRATE(td) ||
2136 (td_get_sched(td)->ts_flags & TSF_BOUND) != 0,
2137 ("Thread %p shouldn't migrate", td));
2138 KASSERT(!CPU_ABSENT(td_get_sched(td)->ts_cpu), ("sched_switch_migrate: "
2139 "thread %s queued on absent CPU %d.", td->td_name,
2140 td_get_sched(td)->ts_cpu));
2141 tdn = TDQ_CPU(td_get_sched(td)->ts_cpu);
2143 tdq_load_rem(tdq, td);
2145 * Do the lock dance required to avoid LOR. We have an
2146 * extra spinlock nesting from sched_switch() which will
2147 * prevent preemption while we're holding neither run-queue lock.
2151 lowpri = tdq_add(tdn, td, flags);
2152 tdq_notify(tdn, lowpri);
2156 return (TDQ_LOCKPTR(tdn));
2160 * thread_lock_unblock() that does not assume td_lock is blocked.
2163 thread_unblock_switch(struct thread *td, struct mtx *mtx)
2165 atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
2170 * Switch threads. This function has to handle threads coming in while
2171 * blocked for some reason, running, or idle. It also must deal with
2172 * migrating a thread from one queue to another as running threads may
2173 * be assigned elsewhere via binding.
2176 sched_switch(struct thread *td, int flags)
2178 struct thread *newtd;
2180 struct td_sched *ts;
2183 int cpuid, preempted;
2188 THREAD_LOCK_ASSERT(td, MA_OWNED);
2190 cpuid = PCPU_GET(cpuid);
2192 ts = td_get_sched(td);
2193 sched_pctcpu_update(ts, 1);
2195 pickcpu = (td->td_flags & TDF_PICKCPU) != 0;
2197 ts->ts_rltick = ticks - affinity * MAX_CACHE_LEVELS;
2199 ts->ts_rltick = ticks;
2201 td->td_lastcpu = td->td_oncpu;
2202 preempted = (td->td_flags & TDF_SLICEEND) == 0 &&
2203 (flags & SW_PREEMPT) != 0;
2204 td->td_flags &= ~(TDF_NEEDRESCHED | TDF_PICKCPU | TDF_SLICEEND);
2205 td->td_owepreempt = 0;
2206 atomic_store_char(&tdq->tdq_owepreempt, 0);
2207 if (!TD_IS_IDLETHREAD(td))
2208 TDQ_SWITCHCNT_INC(tdq);
2211 * Always block the thread lock so we can drop the tdq lock early.
2213 mtx = thread_lock_block(td);
2215 if (TD_IS_IDLETHREAD(td)) {
2216 MPASS(mtx == TDQ_LOCKPTR(tdq));
2218 } else if (TD_IS_RUNNING(td)) {
2219 MPASS(mtx == TDQ_LOCKPTR(tdq));
2220 srqflag = preempted ?
2221 SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
2222 SRQ_OURSELF|SRQ_YIELDING;
2224 if (THREAD_CAN_MIGRATE(td) && (!THREAD_CAN_SCHED(td, ts->ts_cpu)
2226 ts->ts_cpu = sched_pickcpu(td, 0);
2228 if (ts->ts_cpu == cpuid)
2229 tdq_runq_add(tdq, td, srqflag);
2231 mtx = sched_switch_migrate(tdq, td, srqflag);
2233 /* This thread must be going to sleep. */
2234 if (mtx != TDQ_LOCKPTR(tdq)) {
2235 mtx_unlock_spin(mtx);
2238 tdq_load_rem(tdq, td);
2240 if (tdq->tdq_load == 0)
2245 #if (KTR_COMPILE & KTR_SCHED) != 0
2246 if (TD_IS_IDLETHREAD(td))
2247 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle",
2248 "prio:%d", td->td_priority);
2250 KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td),
2251 "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg,
2252 "lockname:\"%s\"", td->td_lockname);
2256 * We enter here with the thread blocked and assigned to the
2257 * appropriate cpu run-queue or sleep-queue and with the current
2258 * thread-queue locked.
2260 TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2261 MPASS(td == tdq->tdq_curthread);
2262 newtd = choosethread();
2263 sched_pctcpu_update(td_get_sched(newtd), 0);
2267 * Call the MD code to switch contexts if necessary.
2271 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
2272 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
2274 SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
2276 #ifdef KDTRACE_HOOKS
2278 * If DTrace has set the active vtime enum to anything
2279 * other than INACTIVE (0), then it should have set the
2282 if (dtrace_vtime_active)
2283 (*dtrace_vtime_switch_func)(newtd);
2285 td->td_oncpu = NOCPU;
2286 cpu_switch(td, newtd, mtx);
2287 cpuid = td->td_oncpu = PCPU_GET(cpuid);
2289 SDT_PROBE0(sched, , , on__cpu);
2291 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
2292 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
2295 thread_unblock_switch(td, mtx);
2296 SDT_PROBE0(sched, , , remain__cpu);
2298 KASSERT(curthread->td_md.md_spinlock_count == 1,
2299 ("invalid count %d", curthread->td_md.md_spinlock_count));
2301 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
2302 "prio:%d", td->td_priority);
2306 * Adjust thread priorities as a result of a nice request.
2309 sched_nice(struct proc *p, int nice)
2313 PROC_LOCK_ASSERT(p, MA_OWNED);
2316 FOREACH_THREAD_IN_PROC(p, td) {
2319 sched_prio(td, td->td_base_user_pri);
2325 * Record the sleep time for the interactivity scorer.
2328 sched_sleep(struct thread *td, int prio)
2331 THREAD_LOCK_ASSERT(td, MA_OWNED);
2333 td->td_slptick = ticks;
2334 if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
2335 td->td_flags |= TDF_CANSWAP;
2336 if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
2338 if (static_boost == 1 && prio)
2339 sched_prio(td, prio);
2340 else if (static_boost && td->td_priority > static_boost)
2341 sched_prio(td, static_boost);
2345 * Schedule a thread to resume execution and record how long it voluntarily
2346 * slept. We also update the pctcpu, interactivity, and priority.
2348 * Requires the thread lock on entry, drops on exit.
2351 sched_wakeup(struct thread *td, int srqflags)
2353 struct td_sched *ts;
2356 THREAD_LOCK_ASSERT(td, MA_OWNED);
2357 ts = td_get_sched(td);
2358 td->td_flags &= ~TDF_CANSWAP;
2361 * If we slept for more than a tick update our interactivity and
2364 slptick = td->td_slptick;
2366 if (slptick && slptick != ticks) {
2367 ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
2368 sched_interact_update(td);
2369 sched_pctcpu_update(ts, 0);
2372 * Reset the slice value since we slept and advanced the round-robin.
2375 sched_add(td, SRQ_BORING | srqflags);
2379 * Penalize the parent for creating a new child and initialize the child's
2383 sched_fork(struct thread *td, struct thread *child)
2385 THREAD_LOCK_ASSERT(td, MA_OWNED);
2386 sched_pctcpu_update(td_get_sched(td), 1);
2387 sched_fork_thread(td, child);
2389 * Penalize the parent and child for forking.
2391 sched_interact_fork(child);
2392 sched_priority(child);
2393 td_get_sched(td)->ts_runtime += tickincr;
2394 sched_interact_update(td);
2399 * Fork a new thread, may be within the same process.
2402 sched_fork_thread(struct thread *td, struct thread *child)
2404 struct td_sched *ts;
2405 struct td_sched *ts2;
2409 THREAD_LOCK_ASSERT(td, MA_OWNED);
2413 ts = td_get_sched(td);
2414 ts2 = td_get_sched(child);
2415 child->td_oncpu = NOCPU;
2416 child->td_lastcpu = NOCPU;
2417 child->td_lock = TDQ_LOCKPTR(tdq);
2418 child->td_cpuset = cpuset_ref(td->td_cpuset);
2419 child->td_domain.dr_policy = td->td_cpuset->cs_domain;
2420 ts2->ts_cpu = ts->ts_cpu;
2423 * Grab our parents cpu estimation information.
2425 ts2->ts_ticks = ts->ts_ticks;
2426 ts2->ts_ltick = ts->ts_ltick;
2427 ts2->ts_ftick = ts->ts_ftick;
2429 * Do not inherit any borrowed priority from the parent.
2431 child->td_priority = child->td_base_pri;
2433 * And update interactivity score.
2435 ts2->ts_slptime = ts->ts_slptime;
2436 ts2->ts_runtime = ts->ts_runtime;
2437 /* Attempt to quickly learn interactivity. */
2438 ts2->ts_slice = tdq_slice(tdq) - sched_slice_min;
2440 bzero(ts2->ts_name, sizeof(ts2->ts_name));
2445 * Adjust the priority class of a thread.
2448 sched_class(struct thread *td, int class)
2451 THREAD_LOCK_ASSERT(td, MA_OWNED);
2452 if (td->td_pri_class == class)
2454 td->td_pri_class = class;
2458 * Return some of the child's priority and interactivity to the parent.
2461 sched_exit(struct proc *p, struct thread *child)
2465 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2466 "prio:%d", child->td_priority);
2467 PROC_LOCK_ASSERT(p, MA_OWNED);
2468 td = FIRST_THREAD_IN_PROC(p);
2469 sched_exit_thread(td, child);
2473 * Penalize another thread for the time spent on this one. This helps to
2474 * worsen the priority and interactivity of processes which schedule batch
2475 * jobs such as make. This has little effect on the make process itself but
2476 * causes new processes spawned by it to receive worse scores immediately.
2479 sched_exit_thread(struct thread *td, struct thread *child)
2482 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2483 "prio:%d", child->td_priority);
2485 * Give the child's runtime to the parent without returning the
2486 * sleep time as a penalty to the parent. This causes shells that
2487 * launch expensive things to mark their children as expensive.
2490 td_get_sched(td)->ts_runtime += td_get_sched(child)->ts_runtime;
2491 sched_interact_update(td);
2497 sched_preempt(struct thread *td)
2502 SDT_PROBE2(sched, , , surrender, td, td->td_proc);
2506 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2507 if (td->td_priority > tdq->tdq_lowpri) {
2508 if (td->td_critnest == 1) {
2509 flags = SW_INVOL | SW_PREEMPT;
2510 flags |= TD_IS_IDLETHREAD(td) ? SWT_REMOTEWAKEIDLE :
2513 /* Switch dropped thread lock. */
2516 td->td_owepreempt = 1;
2518 tdq->tdq_owepreempt = 0;
2524 * Fix priorities on return to user-space. Priorities may be elevated due
2525 * to static priorities in msleep() or similar.
2528 sched_userret_slowpath(struct thread *td)
2532 td->td_priority = td->td_user_pri;
2533 td->td_base_pri = td->td_user_pri;
2534 tdq_setlowpri(TDQ_SELF(), td);
2539 * Handle a stathz tick. This is really only relevant for timeshare
2543 sched_clock(struct thread *td, int cnt)
2546 struct td_sched *ts;
2548 THREAD_LOCK_ASSERT(td, MA_OWNED);
2552 * We run the long term load balancer infrequently on the first cpu.
2554 if (balance_tdq == tdq && smp_started != 0 && rebalance != 0 &&
2555 balance_ticks != 0) {
2556 balance_ticks -= cnt;
2557 if (balance_ticks <= 0)
2562 * Save the old switch count so we have a record of the last ticks
2563 * activity. Initialize the new switch count based on our load.
2564 * If there is some activity seed it to reflect that.
2566 tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
2567 tdq->tdq_switchcnt = tdq->tdq_load;
2570 * Advance the insert index once for each tick to ensure that all
2571 * threads get a chance to run.
2573 if (tdq->tdq_idx == tdq->tdq_ridx) {
2574 tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2575 if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2576 tdq->tdq_ridx = tdq->tdq_idx;
2578 ts = td_get_sched(td);
2579 sched_pctcpu_update(ts, 1);
2580 if ((td->td_pri_class & PRI_FIFO_BIT) || TD_IS_IDLETHREAD(td))
2583 if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2585 * We used a tick; charge it to the thread so
2586 * that we can compute our interactivity.
2588 td_get_sched(td)->ts_runtime += tickincr * cnt;
2589 sched_interact_update(td);
2594 * Force a context switch if the current thread has used up a full
2595 * time slice (default is 100ms).
2597 ts->ts_slice += cnt;
2598 if (ts->ts_slice >= tdq_slice(tdq)) {
2600 td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
2605 sched_estcpu(struct thread *td __unused)
2612 * Return whether the current CPU has runnable tasks. Used for in-kernel
2613 * cooperative idle threads.
2616 sched_runnable(void)
2624 if ((curthread->td_flags & TDF_IDLETD) != 0) {
2625 if (TDQ_LOAD(tdq) > 0)
2628 if (TDQ_LOAD(tdq) - 1 > 0)
2636 * Choose the highest priority thread to run. The thread is removed from
2637 * the run-queue while running however the load remains.
2646 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2647 td = tdq_choose(tdq);
2649 tdq_runq_rem(tdq, td);
2650 tdq->tdq_lowpri = td->td_priority;
2652 tdq->tdq_lowpri = PRI_MAX_IDLE;
2653 td = PCPU_GET(idlethread);
2655 tdq->tdq_curthread = td;
2660 * Set owepreempt if the currently running thread has lower priority than "pri".
2661 * Preemption never happens directly in ULE, we always request it once we exit a
2665 sched_setpreempt(int pri)
2671 THREAD_LOCK_ASSERT(ctd, MA_OWNED);
2673 cpri = ctd->td_priority;
2675 ctd->td_flags |= TDF_NEEDRESCHED;
2676 if (KERNEL_PANICKED() || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2678 if (!sched_shouldpreempt(pri, cpri, 0))
2680 ctd->td_owepreempt = 1;
2684 * Add a thread to a thread queue. Select the appropriate runq and add the
2685 * thread to it. This is the internal function called when the tdq is
2689 tdq_add(struct tdq *tdq, struct thread *td, int flags)
2693 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2694 THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
2695 KASSERT((td->td_inhibitors == 0),
2696 ("sched_add: trying to run inhibited thread"));
2697 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2698 ("sched_add: bad thread state"));
2699 KASSERT(td->td_flags & TDF_INMEM,
2700 ("sched_add: thread swapped out"));
2702 lowpri = tdq->tdq_lowpri;
2703 if (td->td_priority < lowpri)
2704 tdq->tdq_lowpri = td->td_priority;
2705 tdq_runq_add(tdq, td, flags);
2706 tdq_load_add(tdq, td);
2711 * Select the target thread queue and add a thread to it. Request
2712 * preemption or IPI a remote processor if required.
2714 * Requires the thread lock on entry, drops on exit.
2717 sched_add(struct thread *td, int flags)
2724 KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
2725 "prio:%d", td->td_priority, KTR_ATTR_LINKED,
2726 sched_tdname(curthread));
2727 KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
2728 KTR_ATTR_LINKED, sched_tdname(td));
2729 SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
2730 flags & SRQ_PREEMPTED);
2731 THREAD_LOCK_ASSERT(td, MA_OWNED);
2733 * Recalculate the priority before we select the target cpu or
2736 if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2740 * Pick the destination cpu and if it isn't ours transfer to the
2743 cpu = sched_pickcpu(td, flags);
2744 tdq = sched_setcpu(td, cpu, flags);
2745 lowpri = tdq_add(tdq, td, flags);
2746 if (cpu != PCPU_GET(cpuid))
2747 tdq_notify(tdq, lowpri);
2748 else if (!(flags & SRQ_YIELDING))
2749 sched_setpreempt(td->td_priority);
2753 * Now that the thread is moving to the run-queue, set the lock
2754 * to the scheduler's lock.
2756 if (td->td_lock != TDQ_LOCKPTR(tdq)) {
2758 if ((flags & SRQ_HOLD) != 0)
2759 td->td_lock = TDQ_LOCKPTR(tdq);
2761 thread_lock_set(td, TDQ_LOCKPTR(tdq));
2763 (void)tdq_add(tdq, td, flags);
2764 if (!(flags & SRQ_YIELDING))
2765 sched_setpreempt(td->td_priority);
2767 if (!(flags & SRQ_HOLDTD))
2772 * Remove a thread from a run-queue without running it. This is used
2773 * when we're stealing a thread from a remote queue. Otherwise all threads
2774 * exit by calling sched_exit_thread() and sched_throw() themselves.
2777 sched_rem(struct thread *td)
2781 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
2782 "prio:%d", td->td_priority);
2783 SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
2784 tdq = TDQ_CPU(td_get_sched(td)->ts_cpu);
2785 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2786 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2787 KASSERT(TD_ON_RUNQ(td),
2788 ("sched_rem: thread not on run queue"));
2789 tdq_runq_rem(tdq, td);
2790 tdq_load_rem(tdq, td);
2792 if (td->td_priority == tdq->tdq_lowpri)
2793 tdq_setlowpri(tdq, NULL);
2797 * Fetch cpu utilization information. Updates on demand.
2800 sched_pctcpu(struct thread *td)
2803 struct td_sched *ts;
2806 ts = td_get_sched(td);
2808 THREAD_LOCK_ASSERT(td, MA_OWNED);
2809 sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2813 /* How many rtick per second ? */
2814 rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2815 pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2822 * Enforce affinity settings for a thread. Called after adjustments to
2826 sched_affinity(struct thread *td)
2829 struct td_sched *ts;
2831 THREAD_LOCK_ASSERT(td, MA_OWNED);
2832 ts = td_get_sched(td);
2833 if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2835 if (TD_ON_RUNQ(td)) {
2837 sched_add(td, SRQ_BORING | SRQ_HOLDTD);
2840 if (!TD_IS_RUNNING(td))
2843 * Force a switch before returning to userspace. If the
2844 * target thread is not running locally send an ipi to force
2847 td->td_flags |= TDF_NEEDRESCHED;
2848 if (td != curthread)
2849 ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
2854 * Bind a thread to a target cpu.
2857 sched_bind(struct thread *td, int cpu)
2859 struct td_sched *ts;
2861 THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2862 KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
2863 ts = td_get_sched(td);
2864 if (ts->ts_flags & TSF_BOUND)
2866 KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2867 ts->ts_flags |= TSF_BOUND;
2869 if (PCPU_GET(cpuid) == cpu)
2872 /* When we return from mi_switch we'll be on the correct cpu. */
2878 * Release a bound thread.
2881 sched_unbind(struct thread *td)
2883 struct td_sched *ts;
2885 THREAD_LOCK_ASSERT(td, MA_OWNED);
2886 KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
2887 ts = td_get_sched(td);
2888 if ((ts->ts_flags & TSF_BOUND) == 0)
2890 ts->ts_flags &= ~TSF_BOUND;
2895 sched_is_bound(struct thread *td)
2897 THREAD_LOCK_ASSERT(td, MA_OWNED);
2898 return (td_get_sched(td)->ts_flags & TSF_BOUND);
2905 sched_relinquish(struct thread *td)
2908 mi_switch(SW_VOL | SWT_RELINQUISH);
2912 * Return the total system load.
2923 total += atomic_load_int(&TDQ_CPU(i)->tdq_sysload);
2926 return (atomic_load_int(&TDQ_SELF()->tdq_sysload));
2931 sched_sizeof_proc(void)
2933 return (sizeof(struct proc));
2937 sched_sizeof_thread(void)
2939 return (sizeof(struct thread) + sizeof(struct td_sched));
2943 #define TDQ_IDLESPIN(tdq) \
2944 ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
2946 #define TDQ_IDLESPIN(tdq) 1
2950 * The actual idle process.
2953 sched_idletd(void *dummy)
2957 int oldswitchcnt, switchcnt;
2960 mtx_assert(&Giant, MA_NOTOWNED);
2963 THREAD_NO_SLEEPING();
2966 if (TDQ_LOAD(tdq)) {
2968 mi_switch(SW_VOL | SWT_IDLE);
2970 switchcnt = TDQ_SWITCHCNT(tdq);
2972 if (always_steal || switchcnt != oldswitchcnt) {
2973 oldswitchcnt = switchcnt;
2974 if (tdq_idled(tdq) == 0)
2977 switchcnt = TDQ_SWITCHCNT(tdq);
2979 oldswitchcnt = switchcnt;
2982 * If we're switching very frequently, spin while checking
2983 * for load rather than entering a low power state that
2984 * may require an IPI. However, don't do any busy
2985 * loops while on SMT machines as this simply steals
2986 * cycles from cores doing useful work.
2988 if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
2989 for (i = 0; i < sched_idlespins; i++) {
2996 /* If there was context switch during spin, restart it. */
2997 switchcnt = TDQ_SWITCHCNT(tdq);
2998 if (TDQ_LOAD(tdq) != 0 || switchcnt != oldswitchcnt)
3001 /* Run main MD idle handler. */
3002 atomic_store_int(&tdq->tdq_cpu_idle, 1);
3004 * Make sure that the tdq_cpu_idle update is globally visible
3005 * before cpu_idle() reads tdq_load. The order is important
3006 * to avoid races with tdq_notify().
3008 atomic_thread_fence_seq_cst();
3010 * Checking for again after the fence picks up assigned
3011 * threads often enough to make it worthwhile to do so in
3012 * order to avoid calling cpu_idle().
3014 if (TDQ_LOAD(tdq) != 0) {
3015 atomic_store_int(&tdq->tdq_cpu_idle, 0);
3018 cpu_idle(switchcnt * 4 > sched_idlespinthresh);
3019 atomic_store_int(&tdq->tdq_cpu_idle, 0);
3022 * Account thread-less hardware interrupts and
3023 * other wakeup reasons equal to context switches.
3025 switchcnt = TDQ_SWITCHCNT(tdq);
3026 if (switchcnt != oldswitchcnt)
3028 TDQ_SWITCHCNT_INC(tdq);
3034 * A CPU is entering for the first time or a thread is exiting.
3037 sched_throw(struct thread *td)
3039 struct thread *newtd;
3043 if (__predict_false(td == NULL)) {
3045 /* Correct spinlock nesting. */
3047 PCPU_SET(switchtime, cpu_ticks());
3048 PCPU_SET(switchticks, ticks);
3050 THREAD_LOCK_ASSERT(td, MA_OWNED);
3051 THREAD_LOCKPTR_ASSERT(td, TDQ_LOCKPTR(tdq));
3052 tdq_load_rem(tdq, td);
3053 td->td_lastcpu = td->td_oncpu;
3054 td->td_oncpu = NOCPU;
3055 thread_lock_block(td);
3057 newtd = choosethread();
3060 KASSERT(curthread->td_md.md_spinlock_count == 1,
3061 ("invalid count %d", curthread->td_md.md_spinlock_count));
3062 /* doesn't return */
3063 if (__predict_false(td == NULL))
3064 cpu_throw(td, newtd); /* doesn't return */
3066 cpu_switch(td, newtd, TDQ_LOCKPTR(tdq));
3070 * This is called from fork_exit(). Just acquire the correct locks and
3071 * let fork do the rest of the work.
3074 sched_fork_exit(struct thread *td)
3080 * Finish setting up thread glue so that it begins execution in a
3081 * non-nested critical section with the scheduler lock held.
3083 KASSERT(curthread->td_md.md_spinlock_count == 1,
3084 ("invalid count %d", curthread->td_md.md_spinlock_count));
3085 cpuid = PCPU_GET(cpuid);
3089 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
3090 td->td_oncpu = cpuid;
3091 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
3092 "prio:%d", td->td_priority);
3093 SDT_PROBE0(sched, , , on__cpu);
3097 * Create on first use to catch odd startup conditions.
3100 sched_tdname(struct thread *td)
3103 struct td_sched *ts;
3105 ts = td_get_sched(td);
3106 if (ts->ts_name[0] == '\0')
3107 snprintf(ts->ts_name, sizeof(ts->ts_name),
3108 "%s tid %d", td->td_name, td->td_tid);
3109 return (ts->ts_name);
3111 return (td->td_name);
3117 sched_clear_tdname(struct thread *td)
3119 struct td_sched *ts;
3121 ts = td_get_sched(td);
3122 ts->ts_name[0] = '\0';
3129 * Build the CPU topology dump string. Is recursively called to collect
3130 * the topology tree.
3133 sysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
3136 char cpusetbuf[CPUSETBUFSIZ];
3139 sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
3140 "", 1 + indent / 2, cg->cg_level);
3141 sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
3142 cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
3144 for (i = cg->cg_first; i <= cg->cg_last; i++) {
3145 if (CPU_ISSET(i, &cg->cg_mask)) {
3147 sbuf_printf(sb, ", ");
3150 sbuf_printf(sb, "%d", i);
3153 sbuf_printf(sb, "</cpu>\n");
3155 if (cg->cg_flags != 0) {
3156 sbuf_printf(sb, "%*s <flags>", indent, "");
3157 if ((cg->cg_flags & CG_FLAG_HTT) != 0)
3158 sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
3159 if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
3160 sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
3161 if ((cg->cg_flags & CG_FLAG_SMT) != 0)
3162 sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
3163 if ((cg->cg_flags & CG_FLAG_NODE) != 0)
3164 sbuf_printf(sb, "<flag name=\"NODE\">NUMA node</flag>");
3165 sbuf_printf(sb, "</flags>\n");
3168 if (cg->cg_children > 0) {
3169 sbuf_printf(sb, "%*s <children>\n", indent, "");
3170 for (i = 0; i < cg->cg_children; i++)
3171 sysctl_kern_sched_topology_spec_internal(sb,
3172 &cg->cg_child[i], indent+2);
3173 sbuf_printf(sb, "%*s </children>\n", indent, "");
3175 sbuf_printf(sb, "%*s</group>\n", indent, "");
3180 * Sysctl handler for retrieving topology dump. It's a wrapper for
3181 * the recursive sysctl_kern_smp_topology_spec_internal().
3184 sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
3189 KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
3191 topo = sbuf_new_for_sysctl(NULL, NULL, 512, req);
3195 sbuf_printf(topo, "<groups>\n");
3196 err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
3197 sbuf_printf(topo, "</groups>\n");
3200 err = sbuf_finish(topo);
3209 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
3211 int error, new_val, period;
3213 period = 1000000 / realstathz;
3214 new_val = period * sched_slice;
3215 error = sysctl_handle_int(oidp, &new_val, 0, req);
3216 if (error != 0 || req->newptr == NULL)
3220 sched_slice = imax(1, (new_val + period / 2) / period);
3221 sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
3222 hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
3227 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
3229 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
3231 SYSCTL_PROC(_kern_sched, OID_AUTO, quantum,
3232 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
3233 sysctl_kern_quantum, "I",
3234 "Quantum for timeshare threads in microseconds");
3235 SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
3236 "Quantum for timeshare threads in stathz ticks");
3237 SYSCTL_UINT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
3238 "Interactivity score threshold");
3239 SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW,
3241 "Maximal (lowest) priority for preemption");
3242 SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost, 0,
3243 "Assign static kernel priorities to sleeping threads");
3244 SYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins, 0,
3245 "Number of times idle thread will spin waiting for new work");
3246 SYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW,
3247 &sched_idlespinthresh, 0,
3248 "Threshold before we will permit idle thread spinning");
3250 SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
3251 "Number of hz ticks to keep thread affinity for");
3252 SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
3253 "Enables the long-term load balancer");
3254 SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
3255 &balance_interval, 0,
3256 "Average period in stathz ticks to run the long-term balancer");
3257 SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
3258 "Attempts to steal work from other cores before idling");
3259 SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
3260 "Minimum load on remote CPU before we'll steal");
3261 SYSCTL_INT(_kern_sched, OID_AUTO, trysteal_limit, CTLFLAG_RW, &trysteal_limit,
3262 0, "Topological distance limit for stealing threads in sched_switch()");
3263 SYSCTL_INT(_kern_sched, OID_AUTO, always_steal, CTLFLAG_RW, &always_steal, 0,
3264 "Always run the stealer from the idle thread");
3265 SYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
3266 CTLFLAG_MPSAFE | CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
3267 "XML dump of detected CPU topology");
3270 /* ps compat. All cpu percentages from ULE are weighted. */
3271 static int ccpu = 0;
3272 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0,
3273 "Decay factor used for updating %CPU in 4BSD scheduler");