2 * SPDX-License-Identifier: BSD-2-Clause
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 #include "opt_hwpmc_hooks.h"
42 #include "opt_sched.h"
44 #include <sys/param.h>
45 #include <sys/systm.h>
47 #include <sys/kernel.h>
49 #include <sys/limits.h>
51 #include <sys/mutex.h>
53 #include <sys/resource.h>
54 #include <sys/resourcevar.h>
55 #include <sys/sched.h>
59 #include <sys/sysctl.h>
60 #include <sys/sysproto.h>
61 #include <sys/turnstile.h>
62 #include <sys/umtxvar.h>
63 #include <sys/vmmeter.h>
64 #include <sys/cpuset.h>
68 #include <sys/pmckern.h>
72 #include <sys/dtrace_bsd.h>
73 int __read_mostly dtrace_vtime_active;
74 dtrace_vtime_switch_func_t dtrace_vtime_switch_func;
77 #include <machine/cpu.h>
78 #include <machine/smp.h>
82 #define TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
83 #define TDQ_NAME_LEN (sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
84 #define TDQ_LOADNAME_LEN (sizeof("CPU ") + sizeof(__XSTRING(MAXCPU)) - 1 + sizeof(" load"))
87 * Thread scheduler specific section. All fields are protected
91 struct runq *ts_runq; /* Run-queue we're queued on. */
92 short ts_flags; /* TSF_* flags. */
93 int ts_cpu; /* CPU that we have affinity for. */
94 int ts_rltick; /* Real last tick, for affinity. */
95 int ts_slice; /* Ticks of slice remaining. */
96 u_int ts_slptime; /* Number of ticks we vol. slept */
97 u_int ts_runtime; /* Number of ticks we were running */
98 int ts_ltick; /* Last tick that we were running on */
99 int ts_ftick; /* First tick that we were running on */
100 int ts_ticks; /* Tick count */
102 char ts_name[TS_NAME_LEN];
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 #define THREAD_CAN_MIGRATE(td) ((td)->td_pinned == 0)
110 #define THREAD_CAN_SCHED(td, cpu) \
111 CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
113 _Static_assert(sizeof(struct thread) + sizeof(struct td_sched) <=
114 sizeof(struct thread0_storage),
115 "increase struct thread0_storage.t0st_sched size");
118 * Priority ranges used for interactive and non-interactive timeshare
119 * threads. The timeshare priorities are split up into four ranges.
120 * The first range handles interactive threads. The last three ranges
121 * (NHALF, x, and NHALF) handle non-interactive threads with the outer
122 * ranges supporting nice values.
124 #define PRI_TIMESHARE_RANGE (PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
125 #define PRI_INTERACT_RANGE ((PRI_TIMESHARE_RANGE - SCHED_PRI_NRESV) / 2)
126 #define PRI_BATCH_RANGE (PRI_TIMESHARE_RANGE - PRI_INTERACT_RANGE)
128 #define PRI_MIN_INTERACT PRI_MIN_TIMESHARE
129 #define PRI_MAX_INTERACT (PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE - 1)
130 #define PRI_MIN_BATCH (PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE)
131 #define PRI_MAX_BATCH PRI_MAX_TIMESHARE
134 * Cpu percentage computation macros and defines.
136 * SCHED_TICK_SECS: Number of seconds to average the cpu usage across.
137 * SCHED_TICK_TARG: Number of hz ticks to average the cpu usage across.
138 * SCHED_TICK_MAX: Maximum number of ticks before scaling back.
139 * SCHED_TICK_SHIFT: Shift factor to avoid rounding away results.
140 * SCHED_TICK_HZ: Compute the number of hz ticks for a given ticks count.
141 * SCHED_TICK_TOTAL: Gives the amount of time we've been recording ticks.
143 #define SCHED_TICK_SECS 10
144 #define SCHED_TICK_TARG (hz * SCHED_TICK_SECS)
145 #define SCHED_TICK_MAX (SCHED_TICK_TARG + hz)
146 #define SCHED_TICK_SHIFT 10
147 #define SCHED_TICK_HZ(ts) ((ts)->ts_ticks >> SCHED_TICK_SHIFT)
148 #define SCHED_TICK_TOTAL(ts) (max((ts)->ts_ltick - (ts)->ts_ftick, hz))
151 * These macros determine priorities for non-interactive threads. They are
152 * assigned a priority based on their recent cpu utilization as expressed
153 * by the ratio of ticks to the tick total. NHALF priorities at the start
154 * and end of the MIN to MAX timeshare range are only reachable with negative
155 * or positive nice respectively.
157 * PRI_RANGE: Priority range for utilization dependent priorities.
158 * PRI_NRESV: Number of nice values.
159 * PRI_TICKS: Compute a priority in PRI_RANGE from the ticks count and total.
160 * PRI_NICE: Determines the part of the priority inherited from nice.
162 #define SCHED_PRI_NRESV (PRIO_MAX - PRIO_MIN)
163 #define SCHED_PRI_NHALF (SCHED_PRI_NRESV / 2)
164 #define SCHED_PRI_MIN (PRI_MIN_BATCH + SCHED_PRI_NHALF)
165 #define SCHED_PRI_MAX (PRI_MAX_BATCH - SCHED_PRI_NHALF)
166 #define SCHED_PRI_RANGE (SCHED_PRI_MAX - SCHED_PRI_MIN + 1)
167 #define SCHED_PRI_TICKS(ts) \
168 (SCHED_TICK_HZ((ts)) / \
169 (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
170 #define SCHED_PRI_NICE(nice) (nice)
173 * These determine the interactivity of a process. Interactivity differs from
174 * cpu utilization in that it expresses the voluntary time slept vs time ran
175 * while cpu utilization includes all time not running. This more accurately
176 * models the intent of the thread.
178 * SLP_RUN_MAX: Maximum amount of sleep time + run time we'll accumulate
179 * before throttling back.
180 * SLP_RUN_FORK: Maximum slp+run time to inherit at fork time.
181 * INTERACT_MAX: Maximum interactivity value. Smaller is better.
182 * INTERACT_THRESH: Threshold for placement on the current runq.
184 #define SCHED_SLP_RUN_MAX ((hz * 5) << SCHED_TICK_SHIFT)
185 #define SCHED_SLP_RUN_FORK ((hz / 2) << SCHED_TICK_SHIFT)
186 #define SCHED_INTERACT_MAX (100)
187 #define SCHED_INTERACT_HALF (SCHED_INTERACT_MAX / 2)
188 #define SCHED_INTERACT_THRESH (30)
191 * These parameters determine the slice behavior for batch work.
193 #define SCHED_SLICE_DEFAULT_DIVISOR 10 /* ~94 ms, 12 stathz ticks. */
194 #define SCHED_SLICE_MIN_DIVISOR 6 /* DEFAULT/MIN = ~16 ms. */
196 /* Flags kept in td_flags. */
197 #define TDF_PICKCPU TDF_SCHED0 /* Thread should pick new CPU. */
198 #define TDF_SLICEEND TDF_SCHED2 /* Thread time slice is over. */
201 * tickincr: Converts a stathz tick into a hz domain scaled by
202 * the shift factor. Without the shift the error rate
203 * due to rounding would be unacceptably high.
204 * realstathz: stathz is sometimes 0 and run off of hz.
205 * sched_slice: Runtime of each thread before rescheduling.
206 * preempt_thresh: Priority threshold for preemption and remote IPIs.
208 static u_int __read_mostly sched_interact = SCHED_INTERACT_THRESH;
209 static int __read_mostly tickincr = 8 << SCHED_TICK_SHIFT;
210 static int __read_mostly realstathz = 127; /* reset during boot. */
211 static int __read_mostly sched_slice = 10; /* reset during boot. */
212 static int __read_mostly sched_slice_min = 1; /* reset during boot. */
214 #ifdef FULL_PREEMPTION
215 static int __read_mostly preempt_thresh = PRI_MAX_IDLE;
217 static int __read_mostly preempt_thresh = PRI_MIN_KERN;
220 static int __read_mostly preempt_thresh = 0;
222 static int __read_mostly static_boost = PRI_MIN_BATCH;
223 static int __read_mostly sched_idlespins = 10000;
224 static int __read_mostly sched_idlespinthresh = -1;
227 * tdq - per processor runqs and statistics. A mutex synchronizes access to
228 * most fields. Some fields are loaded or modified without the mutex.
231 * (c) constant after initialization
232 * (f) flag, set with the tdq lock held, cleared on local CPU
233 * (l) all accesses are CPU-local
234 * (ls) stores are performed by the local CPU, loads may be lockless
235 * (t) all accesses are protected by the tdq mutex
236 * (ts) stores are serialized by the tdq mutex, loads may be lockless
240 * Ordered to improve efficiency of cpu_search() and switch().
241 * tdq_lock is padded to avoid false sharing with tdq_load and
244 struct mtx_padalign tdq_lock; /* run queue lock. */
245 struct cpu_group *tdq_cg; /* (c) Pointer to cpu topology. */
246 struct thread *tdq_curthread; /* (t) Current executing thread. */
247 int tdq_load; /* (ts) Aggregate load. */
248 int tdq_sysload; /* (ts) For loadavg, !ITHD load. */
249 int tdq_cpu_idle; /* (ls) cpu_idle() is active. */
250 int tdq_transferable; /* (ts) Transferable thread count. */
251 short tdq_switchcnt; /* (l) Switches this tick. */
252 short tdq_oldswitchcnt; /* (l) Switches last tick. */
253 u_char tdq_lowpri; /* (ts) Lowest priority thread. */
254 u_char tdq_owepreempt; /* (f) Remote preemption pending. */
255 u_char tdq_idx; /* (t) Current insert index. */
256 u_char tdq_ridx; /* (t) Current removal index. */
257 int tdq_id; /* (c) cpuid. */
258 struct runq tdq_realtime; /* (t) real-time run queue. */
259 struct runq tdq_timeshare; /* (t) timeshare run queue. */
260 struct runq tdq_idle; /* (t) Queue of IDLE threads. */
261 char tdq_name[TDQ_NAME_LEN];
263 char tdq_loadname[TDQ_LOADNAME_LEN];
267 /* Idle thread states and config. */
268 #define TDQ_RUNNING 1
271 /* Lockless accessors. */
272 #define TDQ_LOAD(tdq) atomic_load_int(&(tdq)->tdq_load)
273 #define TDQ_TRANSFERABLE(tdq) atomic_load_int(&(tdq)->tdq_transferable)
274 #define TDQ_SWITCHCNT(tdq) (atomic_load_short(&(tdq)->tdq_switchcnt) + \
275 atomic_load_short(&(tdq)->tdq_oldswitchcnt))
276 #define TDQ_SWITCHCNT_INC(tdq) (atomic_store_short(&(tdq)->tdq_switchcnt, \
277 atomic_load_short(&(tdq)->tdq_switchcnt) + 1))
280 struct cpu_group __read_mostly *cpu_top; /* CPU topology */
282 #define SCHED_AFFINITY_DEFAULT (max(1, hz / 1000))
283 #define SCHED_AFFINITY(ts, t) ((ts)->ts_rltick > ticks - ((t) * affinity))
288 static int rebalance = 1;
289 static int balance_interval = 128; /* Default set in sched_initticks(). */
290 static int __read_mostly affinity;
291 static int __read_mostly steal_idle = 1;
292 static int __read_mostly steal_thresh = 2;
293 static int __read_mostly always_steal = 0;
294 static int __read_mostly trysteal_limit = 2;
297 * One thread queue per processor.
299 static struct tdq __read_mostly *balance_tdq;
300 static int balance_ticks;
301 DPCPU_DEFINE_STATIC(struct tdq, tdq);
302 DPCPU_DEFINE_STATIC(uint32_t, randomval);
304 #define TDQ_SELF() ((struct tdq *)PCPU_GET(sched))
305 #define TDQ_CPU(x) (DPCPU_ID_PTR((x), tdq))
306 #define TDQ_ID(x) ((x)->tdq_id)
308 static struct tdq tdq_cpu;
310 #define TDQ_ID(x) (0)
311 #define TDQ_SELF() (&tdq_cpu)
312 #define TDQ_CPU(x) (&tdq_cpu)
315 #define TDQ_LOCK_ASSERT(t, type) mtx_assert(TDQ_LOCKPTR((t)), (type))
316 #define TDQ_LOCK(t) mtx_lock_spin(TDQ_LOCKPTR((t)))
317 #define TDQ_LOCK_FLAGS(t, f) mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
318 #define TDQ_TRYLOCK(t) mtx_trylock_spin(TDQ_LOCKPTR((t)))
319 #define TDQ_TRYLOCK_FLAGS(t, f) mtx_trylock_spin_flags(TDQ_LOCKPTR((t)), (f))
320 #define TDQ_UNLOCK(t) mtx_unlock_spin(TDQ_LOCKPTR((t)))
321 #define TDQ_LOCKPTR(t) ((struct mtx *)(&(t)->tdq_lock))
323 static void sched_setpreempt(int);
324 static void sched_priority(struct thread *);
325 static void sched_thread_priority(struct thread *, u_char);
326 static int sched_interact_score(struct thread *);
327 static void sched_interact_update(struct thread *);
328 static void sched_interact_fork(struct thread *);
329 static void sched_pctcpu_update(struct td_sched *, int);
331 /* Operations on per processor queues */
332 static struct thread *tdq_choose(struct tdq *);
333 static void tdq_setup(struct tdq *, int i);
334 static void tdq_load_add(struct tdq *, struct thread *);
335 static void tdq_load_rem(struct tdq *, struct thread *);
336 static __inline void tdq_runq_add(struct tdq *, struct thread *, int);
337 static __inline void tdq_runq_rem(struct tdq *, struct thread *);
338 static inline int sched_shouldpreempt(int, int, int);
339 static void tdq_print(int cpu);
340 static void runq_print(struct runq *rq);
341 static int tdq_add(struct tdq *, struct thread *, int);
343 static int tdq_move(struct tdq *, struct tdq *);
344 static int tdq_idled(struct tdq *);
345 static void tdq_notify(struct tdq *, int lowpri);
346 static struct thread *tdq_steal(struct tdq *, int);
347 static struct thread *runq_steal(struct runq *, int);
348 static int sched_pickcpu(struct thread *, int);
349 static void sched_balance(void);
350 static bool sched_balance_pair(struct tdq *, struct tdq *);
351 static inline struct tdq *sched_setcpu(struct thread *, int, int);
352 static inline void thread_unblock_switch(struct thread *, struct mtx *);
353 static int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
354 static int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
355 struct cpu_group *cg, int indent);
358 static void sched_setup(void *dummy);
359 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
361 static void sched_initticks(void *dummy);
362 SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
365 SDT_PROVIDER_DEFINE(sched);
367 SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
368 "struct proc *", "uint8_t");
369 SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
370 "struct proc *", "void *");
371 SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
372 "struct proc *", "void *", "int");
373 SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
374 "struct proc *", "uint8_t", "struct thread *");
375 SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
376 SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
378 SDT_PROBE_DEFINE(sched, , , on__cpu);
379 SDT_PROBE_DEFINE(sched, , , remain__cpu);
380 SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
384 * Print the threads waiting on a run-queue.
387 runq_print(struct runq *rq)
395 for (i = 0; i < RQB_LEN; i++) {
396 printf("\t\trunq bits %d 0x%zx\n",
397 i, rq->rq_status.rqb_bits[i]);
398 for (j = 0; j < RQB_BPW; j++)
399 if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
400 pri = j + (i << RQB_L2BPW);
401 rqh = &rq->rq_queues[pri];
402 TAILQ_FOREACH(td, rqh, td_runq) {
403 printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
404 td, td->td_name, td->td_priority,
405 td->td_rqindex, pri);
412 * Print the status of a per-cpu thread queue. Should be a ddb show cmd.
421 printf("tdq %d:\n", TDQ_ID(tdq));
422 printf("\tlock %p\n", TDQ_LOCKPTR(tdq));
423 printf("\tLock name: %s\n", tdq->tdq_name);
424 printf("\tload: %d\n", tdq->tdq_load);
425 printf("\tswitch cnt: %d\n", tdq->tdq_switchcnt);
426 printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
427 printf("\ttimeshare idx: %d\n", tdq->tdq_idx);
428 printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
429 printf("\tload transferable: %d\n", tdq->tdq_transferable);
430 printf("\tlowest priority: %d\n", tdq->tdq_lowpri);
431 printf("\trealtime runq:\n");
432 runq_print(&tdq->tdq_realtime);
433 printf("\ttimeshare runq:\n");
434 runq_print(&tdq->tdq_timeshare);
435 printf("\tidle runq:\n");
436 runq_print(&tdq->tdq_idle);
440 sched_shouldpreempt(int pri, int cpri, int remote)
443 * If the new priority is not better than the current priority there is
449 * Always preempt idle.
451 if (cpri >= PRI_MIN_IDLE)
454 * If preemption is disabled don't preempt others.
456 if (preempt_thresh == 0)
459 * Preempt if we exceed the threshold.
461 if (pri <= preempt_thresh)
464 * If we're interactive or better and there is non-interactive
465 * or worse running preempt only remote processors.
467 if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
473 * Add a thread to the actual run-queue. Keeps transferable counts up to
474 * date with what is actually on the run-queue. Selects the correct
475 * queue position for timeshare threads.
478 tdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
483 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
484 THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
486 pri = td->td_priority;
487 ts = td_get_sched(td);
489 if (THREAD_CAN_MIGRATE(td)) {
490 tdq->tdq_transferable++;
491 ts->ts_flags |= TSF_XFERABLE;
493 if (pri < PRI_MIN_BATCH) {
494 ts->ts_runq = &tdq->tdq_realtime;
495 } else if (pri <= PRI_MAX_BATCH) {
496 ts->ts_runq = &tdq->tdq_timeshare;
497 KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
498 ("Invalid priority %d on timeshare runq", pri));
500 * This queue contains only priorities between MIN and MAX
501 * batch. Use the whole queue to represent these values.
503 if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
504 pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
505 pri = (pri + tdq->tdq_idx) % RQ_NQS;
507 * This effectively shortens the queue by one so we
508 * can have a one slot difference between idx and
509 * ridx while we wait for threads to drain.
511 if (tdq->tdq_ridx != tdq->tdq_idx &&
512 pri == tdq->tdq_ridx)
513 pri = (unsigned char)(pri - 1) % RQ_NQS;
516 runq_add_pri(ts->ts_runq, td, pri, flags);
519 ts->ts_runq = &tdq->tdq_idle;
520 runq_add(ts->ts_runq, td, flags);
524 * Remove a thread from a run-queue. This typically happens when a thread
525 * is selected to run. Running threads are not on the queue and the
526 * transferable count does not reflect them.
529 tdq_runq_rem(struct tdq *tdq, struct thread *td)
533 ts = td_get_sched(td);
534 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
535 THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
536 KASSERT(ts->ts_runq != NULL,
537 ("tdq_runq_remove: thread %p null ts_runq", td));
538 if (ts->ts_flags & TSF_XFERABLE) {
539 tdq->tdq_transferable--;
540 ts->ts_flags &= ~TSF_XFERABLE;
542 if (ts->ts_runq == &tdq->tdq_timeshare) {
543 if (tdq->tdq_idx != tdq->tdq_ridx)
544 runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
546 runq_remove_idx(ts->ts_runq, td, NULL);
548 runq_remove(ts->ts_runq, td);
552 * Load is maintained for all threads RUNNING and ON_RUNQ. Add the load
553 * for this thread to the referenced thread queue.
556 tdq_load_add(struct tdq *tdq, struct thread *td)
559 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
560 THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
563 if ((td->td_flags & TDF_NOLOAD) == 0)
565 KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
566 SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
570 * Remove the load from a thread that is transitioning to a sleep state or
574 tdq_load_rem(struct tdq *tdq, struct thread *td)
577 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
578 THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
579 KASSERT(tdq->tdq_load != 0,
580 ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
583 if ((td->td_flags & TDF_NOLOAD) == 0)
585 KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
586 SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
590 * Bound timeshare latency by decreasing slice size as load increases. We
591 * consider the maximum latency as the sum of the threads waiting to run
592 * aside from curthread and target no more than sched_slice latency but
593 * no less than sched_slice_min runtime.
596 tdq_slice(struct tdq *tdq)
601 * It is safe to use sys_load here because this is called from
602 * contexts where timeshare threads are running and so there
603 * cannot be higher priority load in the system.
605 load = tdq->tdq_sysload - 1;
606 if (load >= SCHED_SLICE_MIN_DIVISOR)
607 return (sched_slice_min);
609 return (sched_slice);
610 return (sched_slice / load);
614 * Set lowpri to its exact value by searching the run-queue and
615 * evaluating curthread. curthread may be passed as an optimization.
618 tdq_setlowpri(struct tdq *tdq, struct thread *ctd)
622 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
624 ctd = tdq->tdq_curthread;
625 td = tdq_choose(tdq);
626 if (td == NULL || td->td_priority > ctd->td_priority)
627 tdq->tdq_lowpri = ctd->td_priority;
629 tdq->tdq_lowpri = td->td_priority;
634 * We need some randomness. Implement a classic Linear Congruential
635 * Generator X_{n+1}=(aX_n+c) mod m. These values are optimized for
636 * m = 2^32, a = 69069 and c = 5. We only return the upper 16 bits
637 * of the random state (in the low bits of our answer) to keep
638 * the maximum randomness.
645 rndptr = DPCPU_PTR(randomval);
646 *rndptr = *rndptr * 69069 + 5;
648 return (*rndptr >> 16);
652 cpuset_t *cs_mask; /* The mask of allowed CPUs to choose from. */
653 int cs_prefer; /* Prefer this CPU and groups including it. */
654 int cs_running; /* The thread is now running at cs_prefer. */
655 int cs_pri; /* Min priority for low. */
656 int cs_load; /* Max load for low, min load for high. */
657 int cs_trans; /* Min transferable load for high. */
660 struct cpu_search_res {
661 int csr_cpu; /* The best CPU found. */
662 int csr_load; /* The load of cs_cpu. */
666 * Search the tree of cpu_groups for the lowest or highest loaded CPU.
667 * These routines actually compare the load on all paths through the tree
668 * and find the least loaded cpu on the least loaded path, which may differ
669 * from the least loaded cpu in the system. This balances work among caches
673 cpu_search_lowest(const struct cpu_group *cg, const struct cpu_search *s,
674 struct cpu_search_res *r)
676 struct cpu_search_res lr;
678 int c, bload, l, load, p, total;
684 /* Loop through children CPU groups if there are any. */
685 if (cg->cg_children > 0) {
686 for (c = cg->cg_children - 1; c >= 0; c--) {
687 load = cpu_search_lowest(&cg->cg_child[c], s, &lr);
691 * When balancing do not prefer SMT groups with load >1.
692 * It allows round-robin between SMT groups with equal
693 * load within parent group for more fair scheduling.
695 if (__predict_false(s->cs_running) &&
696 (cg->cg_child[c].cg_flags & CG_FLAG_THREAD) &&
697 load >= 128 && (load & 128) != 0)
700 if (lr.csr_cpu >= 0 && (load < bload ||
701 (load == bload && lr.csr_load < r->csr_load))) {
703 r->csr_cpu = lr.csr_cpu;
704 r->csr_load = lr.csr_load;
710 /* Loop through children CPUs otherwise. */
711 for (c = cg->cg_last; c >= cg->cg_first; c--) {
712 if (!CPU_ISSET(c, &cg->cg_mask))
716 if (c == s->cs_prefer) {
717 if (__predict_false(s->cs_running))
726 * Check this CPU is acceptable.
727 * If the threads is already on the CPU, don't look on the TDQ
728 * priority, since it can be the priority of the thread itself.
730 if (l > s->cs_load ||
731 (atomic_load_char(&tdq->tdq_lowpri) <= s->cs_pri &&
732 (!s->cs_running || c != s->cs_prefer)) ||
733 !CPU_ISSET(c, s->cs_mask))
737 * When balancing do not prefer CPUs with load > 1.
738 * It allows round-robin between CPUs with equal load
739 * within the CPU group for more fair scheduling.
741 if (__predict_false(s->cs_running) && l > 0)
744 load -= sched_random() % 128;
745 if (bload > load - p) {
755 cpu_search_highest(const struct cpu_group *cg, const struct cpu_search *s,
756 struct cpu_search_res *r)
758 struct cpu_search_res lr;
760 int c, bload, l, load, total;
766 /* Loop through children CPU groups if there are any. */
767 if (cg->cg_children > 0) {
768 for (c = cg->cg_children - 1; c >= 0; c--) {
769 load = cpu_search_highest(&cg->cg_child[c], s, &lr);
771 if (lr.csr_cpu >= 0 && (load > bload ||
772 (load == bload && lr.csr_load > r->csr_load))) {
774 r->csr_cpu = lr.csr_cpu;
775 r->csr_load = lr.csr_load;
781 /* Loop through children CPUs otherwise. */
782 for (c = cg->cg_last; c >= cg->cg_first; c--) {
783 if (!CPU_ISSET(c, &cg->cg_mask))
791 * Check this CPU is acceptable.
793 if (l < s->cs_load || TDQ_TRANSFERABLE(tdq) < s->cs_trans ||
794 !CPU_ISSET(c, s->cs_mask))
797 load -= sched_random() % 256;
808 * Find the cpu with the least load via the least loaded path that has a
809 * lowpri greater than pri pri. A pri of -1 indicates any priority is
813 sched_lowest(const struct cpu_group *cg, cpuset_t *mask, int pri, int maxload,
814 int prefer, int running)
817 struct cpu_search_res r;
819 s.cs_prefer = prefer;
820 s.cs_running = running;
824 cpu_search_lowest(cg, &s, &r);
829 * Find the cpu with the highest load via the highest loaded path.
832 sched_highest(const struct cpu_group *cg, cpuset_t *mask, int minload,
836 struct cpu_search_res r;
840 s.cs_trans = mintrans;
841 cpu_search_highest(cg, &s, &r);
846 sched_balance_group(struct cpu_group *cg)
850 cpuset_t hmask, lmask;
851 int high, low, anylow;
855 high = sched_highest(cg, &hmask, 1, 0);
856 /* Stop if there is no more CPU with transferrable threads. */
859 CPU_CLR(high, &hmask);
860 CPU_COPY(&hmask, &lmask);
861 /* Stop if there is no more CPU left for low. */
862 if (CPU_EMPTY(&lmask))
865 if (TDQ_LOAD(tdq) == 1) {
867 * There is only one running thread. We can't move
868 * it from here, so tell it to pick new CPU by itself.
871 td = tdq->tdq_curthread;
872 if (td->td_lock == TDQ_LOCKPTR(tdq) &&
873 (td->td_flags & TDF_IDLETD) == 0 &&
874 THREAD_CAN_MIGRATE(td)) {
875 td->td_flags |= TDF_NEEDRESCHED | TDF_PICKCPU;
877 ipi_cpu(high, IPI_AST);
884 if (TDQ_TRANSFERABLE(tdq) == 0)
886 low = sched_lowest(cg, &lmask, -1, TDQ_LOAD(tdq) - 1, high, 1);
887 /* Stop if we looked well and found no less loaded CPU. */
888 if (anylow && low == -1)
890 /* Go to next high if we found no less loaded CPU. */
893 /* Transfer thread from high to low. */
894 if (sched_balance_pair(tdq, TDQ_CPU(low))) {
895 /* CPU that got thread can no longer be a donor. */
896 CPU_CLR(low, &hmask);
899 * If failed, then there is no threads on high
900 * that can run on this low. Drop low from low
901 * mask and look for different one.
903 CPU_CLR(low, &lmask);
915 balance_ticks = max(balance_interval / 2, 1) +
916 (sched_random() % balance_interval);
919 sched_balance_group(cpu_top);
924 * Lock two thread queues using their address to maintain lock order.
927 tdq_lock_pair(struct tdq *one, struct tdq *two)
931 TDQ_LOCK_FLAGS(two, MTX_DUPOK);
934 TDQ_LOCK_FLAGS(one, MTX_DUPOK);
939 * Unlock two thread queues. Order is not important here.
942 tdq_unlock_pair(struct tdq *one, struct tdq *two)
949 * Transfer load between two imbalanced thread queues. Returns true if a thread
950 * was moved between the queues, and false otherwise.
953 sched_balance_pair(struct tdq *high, struct tdq *low)
959 tdq_lock_pair(high, low);
962 * Transfer a thread from high to low.
964 if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load) {
965 lowpri = tdq_move(high, low);
968 * In case the target isn't the current CPU notify it of
969 * the new load, possibly sending an IPI to force it to
970 * reschedule. Otherwise maybe schedule a preemption.
973 if (cpu != PCPU_GET(cpuid))
974 tdq_notify(low, lowpri);
976 sched_setpreempt(low->tdq_lowpri);
980 tdq_unlock_pair(high, low);
985 * Move a thread from one thread queue to another. Returns -1 if the source
986 * queue was empty, else returns the maximum priority of all threads in
987 * the destination queue prior to the addition of the new thread. In the latter
988 * case, this priority can be used to determine whether an IPI needs to be
992 tdq_move(struct tdq *from, struct tdq *to)
997 TDQ_LOCK_ASSERT(from, MA_OWNED);
998 TDQ_LOCK_ASSERT(to, MA_OWNED);
1001 td = tdq_steal(from, cpu);
1006 * Although the run queue is locked the thread may be
1007 * blocked. We can not set the lock until it is unblocked.
1009 thread_lock_block_wait(td);
1011 THREAD_LOCKPTR_ASSERT(td, TDQ_LOCKPTR(from));
1012 td->td_lock = TDQ_LOCKPTR(to);
1013 td_get_sched(td)->ts_cpu = cpu;
1014 return (tdq_add(to, td, SRQ_YIELDING));
1018 * This tdq has idled. Try to steal a thread from another cpu and switch
1022 tdq_idled(struct tdq *tdq)
1024 struct cpu_group *cg, *parent;
1027 int cpu, switchcnt, goup;
1029 if (smp_started == 0 || steal_idle == 0 || tdq->tdq_cg == NULL)
1032 CPU_CLR(PCPU_GET(cpuid), &mask);
1034 switchcnt = TDQ_SWITCHCNT(tdq);
1035 for (cg = tdq->tdq_cg, goup = 0; ; ) {
1036 cpu = sched_highest(cg, &mask, steal_thresh, 1);
1038 * We were assigned a thread but not preempted. Returning
1039 * 0 here will cause our caller to switch to it.
1045 * We found no CPU to steal from in this group. Escalate to
1046 * the parent and repeat. But if parent has only two children
1047 * groups we can avoid searching this group again by searching
1048 * the other one specifically and then escalating two levels.
1055 parent = cg->cg_parent;
1058 if (parent->cg_children == 2) {
1059 if (cg == &parent->cg_child[0])
1060 cg = &parent->cg_child[1];
1062 cg = &parent->cg_child[0];
1068 steal = TDQ_CPU(cpu);
1070 * The data returned by sched_highest() is stale and
1071 * the chosen CPU no longer has an eligible thread.
1073 * Testing this ahead of tdq_lock_pair() only catches
1074 * this situation about 20% of the time on an 8 core
1075 * 16 thread Ryzen 7, but it still helps performance.
1077 if (TDQ_LOAD(steal) < steal_thresh ||
1078 TDQ_TRANSFERABLE(steal) == 0)
1081 * Try to lock both queues. If we are assigned a thread while
1082 * waited for the lock, switch to it now instead of stealing.
1083 * If we can't get the lock, then somebody likely got there
1084 * first so continue searching.
1087 if (tdq->tdq_load > 0) {
1088 mi_switch(SW_VOL | SWT_IDLE);
1091 if (TDQ_TRYLOCK_FLAGS(steal, MTX_DUPOK) == 0) {
1093 CPU_CLR(cpu, &mask);
1097 * The data returned by sched_highest() is stale and
1098 * the chosen CPU no longer has an eligible thread, or
1099 * we were preempted and the CPU loading info may be out
1100 * of date. The latter is rare. In either case restart
1103 if (TDQ_LOAD(steal) < steal_thresh ||
1104 TDQ_TRANSFERABLE(steal) == 0 ||
1105 switchcnt != TDQ_SWITCHCNT(tdq)) {
1106 tdq_unlock_pair(tdq, steal);
1110 * Steal the thread and switch to it.
1112 if (tdq_move(steal, tdq) != -1)
1115 * We failed to acquire a thread even though it looked
1116 * like one was available. This could be due to affinity
1117 * restrictions or for other reasons. Loop again after
1118 * removing this CPU from the set. The restart logic
1119 * above does not restore this CPU to the set due to the
1120 * likelyhood of failing here again.
1122 CPU_CLR(cpu, &mask);
1123 tdq_unlock_pair(tdq, steal);
1126 mi_switch(SW_VOL | SWT_IDLE);
1131 * Notify a remote cpu of new work. Sends an IPI if criteria are met.
1133 * "lowpri" is the minimum scheduling priority among all threads on
1134 * the queue prior to the addition of the new thread.
1137 tdq_notify(struct tdq *tdq, int lowpri)
1141 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1142 KASSERT(tdq->tdq_lowpri <= lowpri,
1143 ("tdq_notify: lowpri %d > tdq_lowpri %d", lowpri, tdq->tdq_lowpri));
1145 if (tdq->tdq_owepreempt)
1149 * Check to see if the newly added thread should preempt the one
1150 * currently running.
1152 if (!sched_shouldpreempt(tdq->tdq_lowpri, lowpri, 1))
1156 * Make sure that our caller's earlier update to tdq_load is
1157 * globally visible before we read tdq_cpu_idle. Idle thread
1158 * accesses both of them without locks, and the order is important.
1160 atomic_thread_fence_seq_cst();
1163 * Try to figure out if we can signal the idle thread instead of sending
1164 * an IPI. This check is racy; at worst, we will deliever an IPI
1168 if (TD_IS_IDLETHREAD(tdq->tdq_curthread) &&
1169 (atomic_load_int(&tdq->tdq_cpu_idle) == 0 || cpu_idle_wakeup(cpu)))
1173 * The run queues have been updated, so any switch on the remote CPU
1174 * will satisfy the preemption request.
1176 tdq->tdq_owepreempt = 1;
1177 ipi_cpu(cpu, IPI_PREEMPT);
1181 * Steals load from a timeshare queue. Honors the rotating queue head
1184 static struct thread *
1185 runq_steal_from(struct runq *rq, int cpu, u_char start)
1189 struct thread *td, *first;
1193 rqb = &rq->rq_status;
1194 bit = start & (RQB_BPW -1);
1197 for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1198 if (rqb->rqb_bits[i] == 0)
1201 bit = RQB_FFS(rqb->rqb_bits[i]);
1202 for (; bit < RQB_BPW; bit++) {
1203 if ((rqb->rqb_bits[i] & (1ul << bit)) == 0)
1205 rqh = &rq->rq_queues[bit + (i << RQB_L2BPW)];
1206 TAILQ_FOREACH(td, rqh, td_runq) {
1208 if (THREAD_CAN_MIGRATE(td) &&
1209 THREAD_CAN_SCHED(td, cpu))
1221 if (first && THREAD_CAN_MIGRATE(first) &&
1222 THREAD_CAN_SCHED(first, cpu))
1228 * Steals load from a standard linear queue.
1230 static struct thread *
1231 runq_steal(struct runq *rq, int cpu)
1239 rqb = &rq->rq_status;
1240 for (word = 0; word < RQB_LEN; word++) {
1241 if (rqb->rqb_bits[word] == 0)
1243 for (bit = 0; bit < RQB_BPW; bit++) {
1244 if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
1246 rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
1247 TAILQ_FOREACH(td, rqh, td_runq)
1248 if (THREAD_CAN_MIGRATE(td) &&
1249 THREAD_CAN_SCHED(td, cpu))
1257 * Attempt to steal a thread in priority order from a thread queue.
1259 static struct thread *
1260 tdq_steal(struct tdq *tdq, int cpu)
1264 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1265 if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
1267 if ((td = runq_steal_from(&tdq->tdq_timeshare,
1268 cpu, tdq->tdq_ridx)) != NULL)
1270 return (runq_steal(&tdq->tdq_idle, cpu));
1274 * Sets the thread lock and ts_cpu to match the requested cpu. Unlocks the
1275 * current lock and returns with the assigned queue locked.
1277 static inline struct tdq *
1278 sched_setcpu(struct thread *td, int cpu, int flags)
1284 THREAD_LOCK_ASSERT(td, MA_OWNED);
1286 td_get_sched(td)->ts_cpu = cpu;
1288 * If the lock matches just return the queue.
1290 if (td->td_lock == TDQ_LOCKPTR(tdq)) {
1291 KASSERT((flags & SRQ_HOLD) == 0,
1292 ("sched_setcpu: Invalid lock for SRQ_HOLD"));
1297 * The hard case, migration, we need to block the thread first to
1298 * prevent order reversals with other cpus locks.
1301 mtx = thread_lock_block(td);
1302 if ((flags & SRQ_HOLD) == 0)
1303 mtx_unlock_spin(mtx);
1305 thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1310 SCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
1311 SCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
1312 SCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
1313 SCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
1314 SCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
1315 SCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
1318 sched_pickcpu(struct thread *td, int flags)
1320 struct cpu_group *cg, *ccg;
1321 struct td_sched *ts;
1324 int cpu, pri, r, self, intr;
1326 self = PCPU_GET(cpuid);
1327 ts = td_get_sched(td);
1328 KASSERT(!CPU_ABSENT(ts->ts_cpu), ("sched_pickcpu: Start scheduler on "
1329 "absent CPU %d for thread %s.", ts->ts_cpu, td->td_name));
1330 if (smp_started == 0)
1333 * Don't migrate a running thread from sched_switch().
1335 if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1336 return (ts->ts_cpu);
1338 * Prefer to run interrupt threads on the processors that generate
1341 if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1342 curthread->td_intr_nesting_level) {
1344 if (tdq->tdq_lowpri >= PRI_MIN_IDLE) {
1345 SCHED_STAT_INC(pickcpu_idle_affinity);
1354 tdq = TDQ_CPU(ts->ts_cpu);
1358 * If the thread can run on the last cpu and the affinity has not
1359 * expired and it is idle, run it there.
1361 if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
1362 atomic_load_char(&tdq->tdq_lowpri) >= PRI_MIN_IDLE &&
1363 SCHED_AFFINITY(ts, CG_SHARE_L2)) {
1364 if (cg->cg_flags & CG_FLAG_THREAD) {
1365 /* Check all SMT threads for being idle. */
1366 for (cpu = cg->cg_first; cpu <= cg->cg_last; cpu++) {
1368 atomic_load_char(&TDQ_CPU(cpu)->tdq_lowpri);
1369 if (CPU_ISSET(cpu, &cg->cg_mask) &&
1373 if (cpu > cg->cg_last) {
1374 SCHED_STAT_INC(pickcpu_idle_affinity);
1375 return (ts->ts_cpu);
1378 SCHED_STAT_INC(pickcpu_idle_affinity);
1379 return (ts->ts_cpu);
1384 * Search for the last level cache CPU group in the tree.
1385 * Skip SMT, identical groups and caches with expired affinity.
1386 * Interrupt threads affinity is explicit and never expires.
1388 for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
1389 if (cg->cg_flags & CG_FLAG_THREAD)
1391 if (cg->cg_children == 1 || cg->cg_count == 1)
1393 if (cg->cg_level == CG_SHARE_NONE ||
1394 (!intr && !SCHED_AFFINITY(ts, cg->cg_level)))
1398 /* Found LLC shared by all CPUs, so do a global search. */
1402 mask = &td->td_cpuset->cs_mask;
1403 pri = td->td_priority;
1404 r = TD_IS_RUNNING(td);
1406 * Try hard to keep interrupts within found LLC. Search the LLC for
1407 * the least loaded CPU we can run now. For NUMA systems it should
1408 * be within target domain, and it also reduces scheduling overhead.
1410 if (ccg != NULL && intr) {
1411 cpu = sched_lowest(ccg, mask, pri, INT_MAX, ts->ts_cpu, r);
1413 SCHED_STAT_INC(pickcpu_intrbind);
1415 /* Search the LLC for the least loaded idle CPU we can run now. */
1417 cpu = sched_lowest(ccg, mask, max(pri, PRI_MAX_TIMESHARE),
1418 INT_MAX, ts->ts_cpu, r);
1420 SCHED_STAT_INC(pickcpu_affinity);
1422 /* Search globally for the least loaded CPU we can run now. */
1424 cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu, r);
1426 SCHED_STAT_INC(pickcpu_lowest);
1428 /* Search globally for the least loaded CPU. */
1430 cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu, r);
1432 SCHED_STAT_INC(pickcpu_lowest);
1434 KASSERT(cpu >= 0, ("sched_pickcpu: Failed to find a cpu."));
1435 KASSERT(!CPU_ABSENT(cpu), ("sched_pickcpu: Picked absent CPU %d.", cpu));
1437 * Compare the lowest loaded cpu to current cpu.
1440 if (THREAD_CAN_SCHED(td, self) && TDQ_SELF()->tdq_lowpri > pri &&
1441 atomic_load_char(&tdq->tdq_lowpri) < PRI_MIN_IDLE &&
1442 TDQ_LOAD(TDQ_SELF()) <= TDQ_LOAD(tdq) + 1) {
1443 SCHED_STAT_INC(pickcpu_local);
1446 if (cpu != ts->ts_cpu)
1447 SCHED_STAT_INC(pickcpu_migration);
1453 * Pick the highest priority task we have and return it.
1455 static struct thread *
1456 tdq_choose(struct tdq *tdq)
1460 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1461 td = runq_choose(&tdq->tdq_realtime);
1464 td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1466 KASSERT(td->td_priority >= PRI_MIN_BATCH,
1467 ("tdq_choose: Invalid priority on timeshare queue %d",
1471 td = runq_choose(&tdq->tdq_idle);
1473 KASSERT(td->td_priority >= PRI_MIN_IDLE,
1474 ("tdq_choose: Invalid priority on idle queue %d",
1483 * Initialize a thread queue.
1486 tdq_setup(struct tdq *tdq, int id)
1490 printf("ULE: setup cpu %d\n", id);
1491 runq_init(&tdq->tdq_realtime);
1492 runq_init(&tdq->tdq_timeshare);
1493 runq_init(&tdq->tdq_idle);
1495 snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1496 "sched lock %d", (int)TDQ_ID(tdq));
1497 mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock", MTX_SPIN);
1499 snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
1500 "CPU %d load", (int)TDQ_ID(tdq));
1506 sched_setup_smp(void)
1511 cpu_top = smp_topo();
1513 tdq = DPCPU_ID_PTR(i, tdq);
1515 tdq->tdq_cg = smp_topo_find(cpu_top, i);
1516 if (tdq->tdq_cg == NULL)
1517 panic("Can't find cpu group for %d\n", i);
1518 DPCPU_ID_SET(i, randomval, i * 69069 + 5);
1520 PCPU_SET(sched, DPCPU_PTR(tdq));
1521 balance_tdq = TDQ_SELF();
1526 * Setup the thread queues and initialize the topology based on MD
1530 sched_setup(void *dummy)
1537 tdq_setup(TDQ_SELF(), 0);
1541 /* Add thread0's load since it's running. */
1543 thread0.td_lock = TDQ_LOCKPTR(tdq);
1544 tdq_load_add(tdq, &thread0);
1545 tdq->tdq_curthread = &thread0;
1546 tdq->tdq_lowpri = thread0.td_priority;
1551 * This routine determines time constants after stathz and hz are setup.
1555 sched_initticks(void *dummy)
1559 realstathz = stathz ? stathz : hz;
1560 sched_slice = realstathz / SCHED_SLICE_DEFAULT_DIVISOR;
1561 sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
1562 hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
1566 * tickincr is shifted out by 10 to avoid rounding errors due to
1567 * hz not being evenly divisible by stathz on all platforms.
1569 incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1571 * This does not work for values of stathz that are more than
1572 * 1 << SCHED_TICK_SHIFT * hz. In practice this does not happen.
1579 * Set the default balance interval now that we know
1580 * what realstathz is.
1582 balance_interval = realstathz;
1583 balance_ticks = balance_interval;
1584 affinity = SCHED_AFFINITY_DEFAULT;
1586 if (sched_idlespinthresh < 0)
1587 sched_idlespinthresh = 2 * max(10000, 6 * hz) / realstathz;
1591 * This is the core of the interactivity algorithm. Determines a score based
1592 * on past behavior. It is the ratio of sleep time to run time scaled to
1593 * a [0, 100] integer. This is the voluntary sleep time of a process, which
1594 * differs from the cpu usage because it does not account for time spent
1595 * waiting on a run-queue. Would be prettier if we had floating point.
1597 * When a thread's sleep time is greater than its run time the
1601 * interactivity score = ---------------------
1602 * sleep time / run time
1605 * When a thread's run time is greater than its sleep time the
1609 * interactivity score = --------------------- + scaling factor
1610 * run time / sleep time
1613 sched_interact_score(struct thread *td)
1615 struct td_sched *ts;
1618 ts = td_get_sched(td);
1620 * The score is only needed if this is likely to be an interactive
1621 * task. Don't go through the expense of computing it if there's
1624 if (sched_interact <= SCHED_INTERACT_HALF &&
1625 ts->ts_runtime >= ts->ts_slptime)
1626 return (SCHED_INTERACT_HALF);
1628 if (ts->ts_runtime > ts->ts_slptime) {
1629 div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1630 return (SCHED_INTERACT_HALF +
1631 (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1633 if (ts->ts_slptime > ts->ts_runtime) {
1634 div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1635 return (ts->ts_runtime / div);
1637 /* runtime == slptime */
1639 return (SCHED_INTERACT_HALF);
1642 * This can happen if slptime and runtime are 0.
1649 * Scale the scheduling priority according to the "interactivity" of this
1653 sched_priority(struct thread *td)
1657 if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
1660 * If the score is interactive we place the thread in the realtime
1661 * queue with a priority that is less than kernel and interrupt
1662 * priorities. These threads are not subject to nice restrictions.
1664 * Scores greater than this are placed on the normal timeshare queue
1665 * where the priority is partially decided by the most recent cpu
1666 * utilization and the rest is decided by nice value.
1668 * The nice value of the process has a linear effect on the calculated
1669 * score. Negative nice values make it easier for a thread to be
1670 * considered interactive.
1672 score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1673 if (score < sched_interact) {
1674 pri = PRI_MIN_INTERACT;
1675 pri += (PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) * score /
1677 KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
1678 ("sched_priority: invalid interactive priority %u score %u",
1681 pri = SCHED_PRI_MIN;
1682 if (td_get_sched(td)->ts_ticks)
1683 pri += min(SCHED_PRI_TICKS(td_get_sched(td)),
1684 SCHED_PRI_RANGE - 1);
1685 pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1686 KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
1687 ("sched_priority: invalid priority %u: nice %d, "
1688 "ticks %d ftick %d ltick %d tick pri %d",
1689 pri, td->td_proc->p_nice, td_get_sched(td)->ts_ticks,
1690 td_get_sched(td)->ts_ftick, td_get_sched(td)->ts_ltick,
1691 SCHED_PRI_TICKS(td_get_sched(td))));
1693 sched_user_prio(td, pri);
1699 * This routine enforces a maximum limit on the amount of scheduling history
1700 * kept. It is called after either the slptime or runtime is adjusted. This
1701 * function is ugly due to integer math.
1704 sched_interact_update(struct thread *td)
1706 struct td_sched *ts;
1709 ts = td_get_sched(td);
1710 sum = ts->ts_runtime + ts->ts_slptime;
1711 if (sum < SCHED_SLP_RUN_MAX)
1714 * This only happens from two places:
1715 * 1) We have added an unusual amount of run time from fork_exit.
1716 * 2) We have added an unusual amount of sleep time from sched_sleep().
1718 if (sum > SCHED_SLP_RUN_MAX * 2) {
1719 if (ts->ts_runtime > ts->ts_slptime) {
1720 ts->ts_runtime = SCHED_SLP_RUN_MAX;
1723 ts->ts_slptime = SCHED_SLP_RUN_MAX;
1729 * If we have exceeded by more than 1/5th then the algorithm below
1730 * will not bring us back into range. Dividing by two here forces
1731 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1733 if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1734 ts->ts_runtime /= 2;
1735 ts->ts_slptime /= 2;
1738 ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1739 ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1743 * Scale back the interactivity history when a child thread is created. The
1744 * history is inherited from the parent but the thread may behave totally
1745 * differently. For example, a shell spawning a compiler process. We want
1746 * to learn that the compiler is behaving badly very quickly.
1749 sched_interact_fork(struct thread *td)
1751 struct td_sched *ts;
1755 ts = td_get_sched(td);
1756 sum = ts->ts_runtime + ts->ts_slptime;
1757 if (sum > SCHED_SLP_RUN_FORK) {
1758 ratio = sum / SCHED_SLP_RUN_FORK;
1759 ts->ts_runtime /= ratio;
1760 ts->ts_slptime /= ratio;
1765 * Called from proc0_init() to setup the scheduler fields.
1770 struct td_sched *ts0;
1773 * Set up the scheduler specific parts of thread0.
1775 ts0 = td_get_sched(&thread0);
1776 ts0->ts_ltick = ticks;
1777 ts0->ts_ftick = ticks;
1779 ts0->ts_cpu = curcpu; /* set valid CPU number */
1783 * schedinit_ap() is needed prior to calling sched_throw(NULL) to ensure that
1784 * the pcpu requirements are met for any calls in the period between curthread
1785 * initialization and sched_throw(). One can safely add threads to the queue
1786 * before sched_throw(), for instance, as long as the thread lock is setup
1789 * TDQ_SELF() relies on the below sched pcpu setting; it may be used only
1790 * after schedinit_ap().
1797 PCPU_SET(sched, DPCPU_PTR(tdq));
1799 PCPU_GET(idlethread)->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1803 * This is only somewhat accurate since given many processes of the same
1804 * priority they will switch when their slices run out, which will be
1805 * at most sched_slice stathz ticks.
1808 sched_rr_interval(void)
1811 /* Convert sched_slice from stathz to hz. */
1812 return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
1816 * Update the percent cpu tracking information when it is requested or
1817 * the total history exceeds the maximum. We keep a sliding history of
1818 * tick counts that slowly decays. This is less precise than the 4BSD
1819 * mechanism since it happens with less regular and frequent events.
1822 sched_pctcpu_update(struct td_sched *ts, int run)
1827 * The signed difference may be negative if the thread hasn't run for
1828 * over half of the ticks rollover period.
1830 if ((u_int)(t - ts->ts_ltick) >= SCHED_TICK_TARG) {
1832 ts->ts_ftick = t - SCHED_TICK_TARG;
1833 } else if (t - ts->ts_ftick >= SCHED_TICK_MAX) {
1834 ts->ts_ticks = (ts->ts_ticks / (ts->ts_ltick - ts->ts_ftick)) *
1835 (ts->ts_ltick - (t - SCHED_TICK_TARG));
1836 ts->ts_ftick = t - SCHED_TICK_TARG;
1839 ts->ts_ticks += (t - ts->ts_ltick) << SCHED_TICK_SHIFT;
1844 * Adjust the priority of a thread. Move it to the appropriate run-queue
1845 * if necessary. This is the back-end for several priority related
1849 sched_thread_priority(struct thread *td, u_char prio)
1851 struct td_sched *ts;
1855 KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
1856 "prio:%d", td->td_priority, "new prio:%d", prio,
1857 KTR_ATTR_LINKED, sched_tdname(curthread));
1858 SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
1859 if (td != curthread && prio < td->td_priority) {
1860 KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
1861 "lend prio", "prio:%d", td->td_priority, "new prio:%d",
1862 prio, KTR_ATTR_LINKED, sched_tdname(td));
1863 SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
1866 ts = td_get_sched(td);
1867 THREAD_LOCK_ASSERT(td, MA_OWNED);
1868 if (td->td_priority == prio)
1871 * If the priority has been elevated due to priority
1872 * propagation, we may have to move ourselves to a new
1873 * queue. This could be optimized to not re-add in some
1876 if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1878 td->td_priority = prio;
1879 sched_add(td, SRQ_BORROWING | SRQ_HOLDTD);
1883 * If the thread is currently running we may have to adjust the lowpri
1884 * information so other cpus are aware of our current priority.
1886 if (TD_IS_RUNNING(td)) {
1887 tdq = TDQ_CPU(ts->ts_cpu);
1888 oldpri = td->td_priority;
1889 td->td_priority = prio;
1890 if (prio < tdq->tdq_lowpri)
1891 tdq->tdq_lowpri = prio;
1892 else if (tdq->tdq_lowpri == oldpri)
1893 tdq_setlowpri(tdq, td);
1896 td->td_priority = prio;
1900 * Update a thread's priority when it is lent another thread's
1904 sched_lend_prio(struct thread *td, u_char prio)
1907 td->td_flags |= TDF_BORROWING;
1908 sched_thread_priority(td, prio);
1912 * Restore a thread's priority when priority propagation is
1913 * over. The prio argument is the minimum priority the thread
1914 * needs to have to satisfy other possible priority lending
1915 * requests. If the thread's regular priority is less
1916 * important than prio, the thread will keep a priority boost
1920 sched_unlend_prio(struct thread *td, u_char prio)
1924 if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1925 td->td_base_pri <= PRI_MAX_TIMESHARE)
1926 base_pri = td->td_user_pri;
1928 base_pri = td->td_base_pri;
1929 if (prio >= base_pri) {
1930 td->td_flags &= ~TDF_BORROWING;
1931 sched_thread_priority(td, base_pri);
1933 sched_lend_prio(td, prio);
1937 * Standard entry for setting the priority to an absolute value.
1940 sched_prio(struct thread *td, u_char prio)
1944 /* First, update the base priority. */
1945 td->td_base_pri = prio;
1948 * If the thread is borrowing another thread's priority, don't
1949 * ever lower the priority.
1951 if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1954 /* Change the real priority. */
1955 oldprio = td->td_priority;
1956 sched_thread_priority(td, prio);
1959 * If the thread is on a turnstile, then let the turnstile update
1962 if (TD_ON_LOCK(td) && oldprio != prio)
1963 turnstile_adjust(td, oldprio);
1967 * Set the base user priority, does not effect current running priority.
1970 sched_user_prio(struct thread *td, u_char prio)
1973 td->td_base_user_pri = prio;
1974 if (td->td_lend_user_pri <= prio)
1976 td->td_user_pri = prio;
1980 sched_lend_user_prio(struct thread *td, u_char prio)
1983 THREAD_LOCK_ASSERT(td, MA_OWNED);
1984 td->td_lend_user_pri = prio;
1985 td->td_user_pri = min(prio, td->td_base_user_pri);
1986 if (td->td_priority > td->td_user_pri)
1987 sched_prio(td, td->td_user_pri);
1988 else if (td->td_priority != td->td_user_pri)
1989 td->td_flags |= TDF_NEEDRESCHED;
1993 * Like the above but first check if there is anything to do.
1996 sched_lend_user_prio_cond(struct thread *td, u_char prio)
1999 if (td->td_lend_user_pri != prio)
2001 if (td->td_user_pri != min(prio, td->td_base_user_pri))
2003 if (td->td_priority != td->td_user_pri)
2009 sched_lend_user_prio(td, prio);
2015 * This tdq is about to idle. Try to steal a thread from another CPU before
2016 * choosing the idle thread.
2019 tdq_trysteal(struct tdq *tdq)
2021 struct cpu_group *cg, *parent;
2026 if (smp_started == 0 || steal_idle == 0 || trysteal_limit == 0 ||
2027 tdq->tdq_cg == NULL)
2030 CPU_CLR(PCPU_GET(cpuid), &mask);
2031 /* We don't want to be preempted while we're iterating. */
2034 for (i = 1, cg = tdq->tdq_cg, goup = 0; ; ) {
2035 cpu = sched_highest(cg, &mask, steal_thresh, 1);
2037 * If a thread was added while interrupts were disabled don't
2040 if (TDQ_LOAD(tdq) > 0) {
2046 * We found no CPU to steal from in this group. Escalate to
2047 * the parent and repeat. But if parent has only two children
2048 * groups we can avoid searching this group again by searching
2049 * the other one specifically and then escalating two levels.
2056 if (++i > trysteal_limit) {
2060 parent = cg->cg_parent;
2061 if (parent == NULL) {
2065 if (parent->cg_children == 2) {
2066 if (cg == &parent->cg_child[0])
2067 cg = &parent->cg_child[1];
2069 cg = &parent->cg_child[0];
2075 steal = TDQ_CPU(cpu);
2077 * The data returned by sched_highest() is stale and
2078 * the chosen CPU no longer has an eligible thread.
2079 * At this point unconditionally exit the loop to bound
2080 * the time spent in the critcal section.
2082 if (TDQ_LOAD(steal) < steal_thresh ||
2083 TDQ_TRANSFERABLE(steal) == 0)
2086 * Try to lock both queues. If we are assigned a thread while
2087 * waited for the lock, switch to it now instead of stealing.
2088 * If we can't get the lock, then somebody likely got there
2092 if (tdq->tdq_load > 0)
2094 if (TDQ_TRYLOCK_FLAGS(steal, MTX_DUPOK) == 0)
2097 * The data returned by sched_highest() is stale and
2098 * the chosen CPU no longer has an eligible thread.
2100 if (TDQ_LOAD(steal) < steal_thresh ||
2101 TDQ_TRANSFERABLE(steal) == 0) {
2106 * If we fail to acquire one due to affinity restrictions,
2107 * bail out and let the idle thread to a more complete search
2108 * outside of a critical section.
2110 if (tdq_move(steal, tdq) == -1) {
2122 * Handle migration from sched_switch(). This happens only for
2126 sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
2133 KASSERT(THREAD_CAN_MIGRATE(td) ||
2134 (td_get_sched(td)->ts_flags & TSF_BOUND) != 0,
2135 ("Thread %p shouldn't migrate", td));
2136 KASSERT(!CPU_ABSENT(td_get_sched(td)->ts_cpu), ("sched_switch_migrate: "
2137 "thread %s queued on absent CPU %d.", td->td_name,
2138 td_get_sched(td)->ts_cpu));
2139 tdn = TDQ_CPU(td_get_sched(td)->ts_cpu);
2141 tdq_load_rem(tdq, td);
2143 * Do the lock dance required to avoid LOR. We have an
2144 * extra spinlock nesting from sched_switch() which will
2145 * prevent preemption while we're holding neither run-queue lock.
2149 lowpri = tdq_add(tdn, td, flags);
2150 tdq_notify(tdn, lowpri);
2154 return (TDQ_LOCKPTR(tdn));
2158 * thread_lock_unblock() that does not assume td_lock is blocked.
2161 thread_unblock_switch(struct thread *td, struct mtx *mtx)
2163 atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
2168 * Switch threads. This function has to handle threads coming in while
2169 * blocked for some reason, running, or idle. It also must deal with
2170 * migrating a thread from one queue to another as running threads may
2171 * be assigned elsewhere via binding.
2174 sched_switch(struct thread *td, int flags)
2176 struct thread *newtd;
2178 struct td_sched *ts;
2181 int cpuid, preempted;
2186 THREAD_LOCK_ASSERT(td, MA_OWNED);
2188 cpuid = PCPU_GET(cpuid);
2190 ts = td_get_sched(td);
2191 sched_pctcpu_update(ts, 1);
2193 pickcpu = (td->td_flags & TDF_PICKCPU) != 0;
2195 ts->ts_rltick = ticks - affinity * MAX_CACHE_LEVELS;
2197 ts->ts_rltick = ticks;
2199 td->td_lastcpu = td->td_oncpu;
2200 preempted = (td->td_flags & TDF_SLICEEND) == 0 &&
2201 (flags & SW_PREEMPT) != 0;
2202 td->td_flags &= ~(TDF_NEEDRESCHED | TDF_PICKCPU | TDF_SLICEEND);
2203 td->td_owepreempt = 0;
2204 atomic_store_char(&tdq->tdq_owepreempt, 0);
2205 if (!TD_IS_IDLETHREAD(td))
2206 TDQ_SWITCHCNT_INC(tdq);
2209 * Always block the thread lock so we can drop the tdq lock early.
2211 mtx = thread_lock_block(td);
2213 if (TD_IS_IDLETHREAD(td)) {
2214 MPASS(mtx == TDQ_LOCKPTR(tdq));
2216 } else if (TD_IS_RUNNING(td)) {
2217 MPASS(mtx == TDQ_LOCKPTR(tdq));
2218 srqflag = preempted ?
2219 SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
2220 SRQ_OURSELF|SRQ_YIELDING;
2222 if (THREAD_CAN_MIGRATE(td) && (!THREAD_CAN_SCHED(td, ts->ts_cpu)
2224 ts->ts_cpu = sched_pickcpu(td, 0);
2226 if (ts->ts_cpu == cpuid)
2227 tdq_runq_add(tdq, td, srqflag);
2229 mtx = sched_switch_migrate(tdq, td, srqflag);
2231 /* This thread must be going to sleep. */
2232 if (mtx != TDQ_LOCKPTR(tdq)) {
2233 mtx_unlock_spin(mtx);
2236 tdq_load_rem(tdq, td);
2238 if (tdq->tdq_load == 0)
2243 #if (KTR_COMPILE & KTR_SCHED) != 0
2244 if (TD_IS_IDLETHREAD(td))
2245 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle",
2246 "prio:%d", td->td_priority);
2248 KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td),
2249 "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg,
2250 "lockname:\"%s\"", td->td_lockname);
2254 * We enter here with the thread blocked and assigned to the
2255 * appropriate cpu run-queue or sleep-queue and with the current
2256 * thread-queue locked.
2258 TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2259 MPASS(td == tdq->tdq_curthread);
2260 newtd = choosethread();
2261 sched_pctcpu_update(td_get_sched(newtd), 0);
2265 * Call the MD code to switch contexts if necessary.
2269 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
2270 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
2272 SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
2274 #ifdef KDTRACE_HOOKS
2276 * If DTrace has set the active vtime enum to anything
2277 * other than INACTIVE (0), then it should have set the
2280 if (dtrace_vtime_active)
2281 (*dtrace_vtime_switch_func)(newtd);
2283 td->td_oncpu = NOCPU;
2284 cpu_switch(td, newtd, mtx);
2285 cpuid = td->td_oncpu = PCPU_GET(cpuid);
2287 SDT_PROBE0(sched, , , on__cpu);
2289 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
2290 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
2293 thread_unblock_switch(td, mtx);
2294 SDT_PROBE0(sched, , , remain__cpu);
2296 KASSERT(curthread->td_md.md_spinlock_count == 1,
2297 ("invalid count %d", curthread->td_md.md_spinlock_count));
2299 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
2300 "prio:%d", td->td_priority);
2304 * Adjust thread priorities as a result of a nice request.
2307 sched_nice(struct proc *p, int nice)
2311 PROC_LOCK_ASSERT(p, MA_OWNED);
2314 FOREACH_THREAD_IN_PROC(p, td) {
2317 sched_prio(td, td->td_base_user_pri);
2323 * Record the sleep time for the interactivity scorer.
2326 sched_sleep(struct thread *td, int prio)
2329 THREAD_LOCK_ASSERT(td, MA_OWNED);
2331 td->td_slptick = ticks;
2332 if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
2333 td->td_flags |= TDF_CANSWAP;
2334 if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
2336 if (static_boost == 1 && prio)
2337 sched_prio(td, prio);
2338 else if (static_boost && td->td_priority > static_boost)
2339 sched_prio(td, static_boost);
2343 * Schedule a thread to resume execution and record how long it voluntarily
2344 * slept. We also update the pctcpu, interactivity, and priority.
2346 * Requires the thread lock on entry, drops on exit.
2349 sched_wakeup(struct thread *td, int srqflags)
2351 struct td_sched *ts;
2354 THREAD_LOCK_ASSERT(td, MA_OWNED);
2355 ts = td_get_sched(td);
2356 td->td_flags &= ~TDF_CANSWAP;
2359 * If we slept for more than a tick update our interactivity and
2362 slptick = td->td_slptick;
2364 if (slptick && slptick != ticks) {
2365 ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
2366 sched_interact_update(td);
2367 sched_pctcpu_update(ts, 0);
2370 * Reset the slice value since we slept and advanced the round-robin.
2373 sched_add(td, SRQ_BORING | srqflags);
2377 * Penalize the parent for creating a new child and initialize the child's
2381 sched_fork(struct thread *td, struct thread *child)
2383 THREAD_LOCK_ASSERT(td, MA_OWNED);
2384 sched_pctcpu_update(td_get_sched(td), 1);
2385 sched_fork_thread(td, child);
2387 * Penalize the parent and child for forking.
2389 sched_interact_fork(child);
2390 sched_priority(child);
2391 td_get_sched(td)->ts_runtime += tickincr;
2392 sched_interact_update(td);
2397 * Fork a new thread, may be within the same process.
2400 sched_fork_thread(struct thread *td, struct thread *child)
2402 struct td_sched *ts;
2403 struct td_sched *ts2;
2407 THREAD_LOCK_ASSERT(td, MA_OWNED);
2411 ts = td_get_sched(td);
2412 ts2 = td_get_sched(child);
2413 child->td_oncpu = NOCPU;
2414 child->td_lastcpu = NOCPU;
2415 child->td_lock = TDQ_LOCKPTR(tdq);
2416 child->td_cpuset = cpuset_ref(td->td_cpuset);
2417 child->td_domain.dr_policy = td->td_cpuset->cs_domain;
2418 ts2->ts_cpu = ts->ts_cpu;
2421 * Grab our parents cpu estimation information.
2423 ts2->ts_ticks = ts->ts_ticks;
2424 ts2->ts_ltick = ts->ts_ltick;
2425 ts2->ts_ftick = ts->ts_ftick;
2427 * Do not inherit any borrowed priority from the parent.
2429 child->td_priority = child->td_base_pri;
2431 * And update interactivity score.
2433 ts2->ts_slptime = ts->ts_slptime;
2434 ts2->ts_runtime = ts->ts_runtime;
2435 /* Attempt to quickly learn interactivity. */
2436 ts2->ts_slice = tdq_slice(tdq) - sched_slice_min;
2438 bzero(ts2->ts_name, sizeof(ts2->ts_name));
2443 * Adjust the priority class of a thread.
2446 sched_class(struct thread *td, int class)
2449 THREAD_LOCK_ASSERT(td, MA_OWNED);
2450 if (td->td_pri_class == class)
2452 td->td_pri_class = class;
2456 * Return some of the child's priority and interactivity to the parent.
2459 sched_exit(struct proc *p, struct thread *child)
2463 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2464 "prio:%d", child->td_priority);
2465 PROC_LOCK_ASSERT(p, MA_OWNED);
2466 td = FIRST_THREAD_IN_PROC(p);
2467 sched_exit_thread(td, child);
2471 * Penalize another thread for the time spent on this one. This helps to
2472 * worsen the priority and interactivity of processes which schedule batch
2473 * jobs such as make. This has little effect on the make process itself but
2474 * causes new processes spawned by it to receive worse scores immediately.
2477 sched_exit_thread(struct thread *td, struct thread *child)
2480 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2481 "prio:%d", child->td_priority);
2483 * Give the child's runtime to the parent without returning the
2484 * sleep time as a penalty to the parent. This causes shells that
2485 * launch expensive things to mark their children as expensive.
2488 td_get_sched(td)->ts_runtime += td_get_sched(child)->ts_runtime;
2489 sched_interact_update(td);
2495 sched_preempt(struct thread *td)
2500 SDT_PROBE2(sched, , , surrender, td, td->td_proc);
2504 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2505 if (td->td_priority > tdq->tdq_lowpri) {
2506 if (td->td_critnest == 1) {
2507 flags = SW_INVOL | SW_PREEMPT;
2508 flags |= TD_IS_IDLETHREAD(td) ? SWT_REMOTEWAKEIDLE :
2511 /* Switch dropped thread lock. */
2514 td->td_owepreempt = 1;
2516 tdq->tdq_owepreempt = 0;
2522 * Fix priorities on return to user-space. Priorities may be elevated due
2523 * to static priorities in msleep() or similar.
2526 sched_userret_slowpath(struct thread *td)
2530 td->td_priority = td->td_user_pri;
2531 td->td_base_pri = td->td_user_pri;
2532 tdq_setlowpri(TDQ_SELF(), td);
2537 * Handle a stathz tick. This is really only relevant for timeshare
2541 sched_clock(struct thread *td, int cnt)
2544 struct td_sched *ts;
2546 THREAD_LOCK_ASSERT(td, MA_OWNED);
2550 * We run the long term load balancer infrequently on the first cpu.
2552 if (balance_tdq == tdq && smp_started != 0 && rebalance != 0 &&
2553 balance_ticks != 0) {
2554 balance_ticks -= cnt;
2555 if (balance_ticks <= 0)
2560 * Save the old switch count so we have a record of the last ticks
2561 * activity. Initialize the new switch count based on our load.
2562 * If there is some activity seed it to reflect that.
2564 tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
2565 tdq->tdq_switchcnt = tdq->tdq_load;
2568 * Advance the insert index once for each tick to ensure that all
2569 * threads get a chance to run.
2571 if (tdq->tdq_idx == tdq->tdq_ridx) {
2572 tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2573 if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2574 tdq->tdq_ridx = tdq->tdq_idx;
2576 ts = td_get_sched(td);
2577 sched_pctcpu_update(ts, 1);
2578 if ((td->td_pri_class & PRI_FIFO_BIT) || TD_IS_IDLETHREAD(td))
2581 if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2583 * We used a tick; charge it to the thread so
2584 * that we can compute our interactivity.
2586 td_get_sched(td)->ts_runtime += tickincr * cnt;
2587 sched_interact_update(td);
2592 * Force a context switch if the current thread has used up a full
2593 * time slice (default is 100ms).
2595 ts->ts_slice += cnt;
2596 if (ts->ts_slice >= tdq_slice(tdq)) {
2598 td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
2603 sched_estcpu(struct thread *td __unused)
2610 * Return whether the current CPU has runnable tasks. Used for in-kernel
2611 * cooperative idle threads.
2614 sched_runnable(void)
2622 if ((curthread->td_flags & TDF_IDLETD) != 0) {
2623 if (TDQ_LOAD(tdq) > 0)
2626 if (TDQ_LOAD(tdq) - 1 > 0)
2634 * Choose the highest priority thread to run. The thread is removed from
2635 * the run-queue while running however the load remains.
2644 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2645 td = tdq_choose(tdq);
2647 tdq_runq_rem(tdq, td);
2648 tdq->tdq_lowpri = td->td_priority;
2650 tdq->tdq_lowpri = PRI_MAX_IDLE;
2651 td = PCPU_GET(idlethread);
2653 tdq->tdq_curthread = td;
2658 * Set owepreempt if the currently running thread has lower priority than "pri".
2659 * Preemption never happens directly in ULE, we always request it once we exit a
2663 sched_setpreempt(int pri)
2669 THREAD_LOCK_ASSERT(ctd, MA_OWNED);
2671 cpri = ctd->td_priority;
2673 ctd->td_flags |= TDF_NEEDRESCHED;
2674 if (KERNEL_PANICKED() || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2676 if (!sched_shouldpreempt(pri, cpri, 0))
2678 ctd->td_owepreempt = 1;
2682 * Add a thread to a thread queue. Select the appropriate runq and add the
2683 * thread to it. This is the internal function called when the tdq is
2687 tdq_add(struct tdq *tdq, struct thread *td, int flags)
2691 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2692 THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
2693 KASSERT((td->td_inhibitors == 0),
2694 ("sched_add: trying to run inhibited thread"));
2695 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2696 ("sched_add: bad thread state"));
2697 KASSERT(td->td_flags & TDF_INMEM,
2698 ("sched_add: thread swapped out"));
2700 lowpri = tdq->tdq_lowpri;
2701 if (td->td_priority < lowpri)
2702 tdq->tdq_lowpri = td->td_priority;
2703 tdq_runq_add(tdq, td, flags);
2704 tdq_load_add(tdq, td);
2709 * Select the target thread queue and add a thread to it. Request
2710 * preemption or IPI a remote processor if required.
2712 * Requires the thread lock on entry, drops on exit.
2715 sched_add(struct thread *td, int flags)
2722 KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
2723 "prio:%d", td->td_priority, KTR_ATTR_LINKED,
2724 sched_tdname(curthread));
2725 KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
2726 KTR_ATTR_LINKED, sched_tdname(td));
2727 SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
2728 flags & SRQ_PREEMPTED);
2729 THREAD_LOCK_ASSERT(td, MA_OWNED);
2731 * Recalculate the priority before we select the target cpu or
2734 if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2738 * Pick the destination cpu and if it isn't ours transfer to the
2741 cpu = sched_pickcpu(td, flags);
2742 tdq = sched_setcpu(td, cpu, flags);
2743 lowpri = tdq_add(tdq, td, flags);
2744 if (cpu != PCPU_GET(cpuid))
2745 tdq_notify(tdq, lowpri);
2746 else if (!(flags & SRQ_YIELDING))
2747 sched_setpreempt(td->td_priority);
2751 * Now that the thread is moving to the run-queue, set the lock
2752 * to the scheduler's lock.
2754 if (td->td_lock != TDQ_LOCKPTR(tdq)) {
2756 if ((flags & SRQ_HOLD) != 0)
2757 td->td_lock = TDQ_LOCKPTR(tdq);
2759 thread_lock_set(td, TDQ_LOCKPTR(tdq));
2761 (void)tdq_add(tdq, td, flags);
2762 if (!(flags & SRQ_YIELDING))
2763 sched_setpreempt(td->td_priority);
2765 if (!(flags & SRQ_HOLDTD))
2770 * Remove a thread from a run-queue without running it. This is used
2771 * when we're stealing a thread from a remote queue. Otherwise all threads
2772 * exit by calling sched_exit_thread() and sched_throw() themselves.
2775 sched_rem(struct thread *td)
2779 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
2780 "prio:%d", td->td_priority);
2781 SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
2782 tdq = TDQ_CPU(td_get_sched(td)->ts_cpu);
2783 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2784 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2785 KASSERT(TD_ON_RUNQ(td),
2786 ("sched_rem: thread not on run queue"));
2787 tdq_runq_rem(tdq, td);
2788 tdq_load_rem(tdq, td);
2790 if (td->td_priority == tdq->tdq_lowpri)
2791 tdq_setlowpri(tdq, NULL);
2795 * Fetch cpu utilization information. Updates on demand.
2798 sched_pctcpu(struct thread *td)
2801 struct td_sched *ts;
2804 ts = td_get_sched(td);
2806 THREAD_LOCK_ASSERT(td, MA_OWNED);
2807 sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2811 /* How many rtick per second ? */
2812 rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2813 pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2820 * Enforce affinity settings for a thread. Called after adjustments to
2824 sched_affinity(struct thread *td)
2827 struct td_sched *ts;
2829 THREAD_LOCK_ASSERT(td, MA_OWNED);
2830 ts = td_get_sched(td);
2831 if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2833 if (TD_ON_RUNQ(td)) {
2835 sched_add(td, SRQ_BORING | SRQ_HOLDTD);
2838 if (!TD_IS_RUNNING(td))
2841 * Force a switch before returning to userspace. If the
2842 * target thread is not running locally send an ipi to force
2845 td->td_flags |= TDF_NEEDRESCHED;
2846 if (td != curthread)
2847 ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
2852 * Bind a thread to a target cpu.
2855 sched_bind(struct thread *td, int cpu)
2857 struct td_sched *ts;
2859 THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2860 KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
2861 ts = td_get_sched(td);
2862 if (ts->ts_flags & TSF_BOUND)
2864 KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2865 ts->ts_flags |= TSF_BOUND;
2867 if (PCPU_GET(cpuid) == cpu)
2870 /* When we return from mi_switch we'll be on the correct cpu. */
2876 * Release a bound thread.
2879 sched_unbind(struct thread *td)
2881 struct td_sched *ts;
2883 THREAD_LOCK_ASSERT(td, MA_OWNED);
2884 KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
2885 ts = td_get_sched(td);
2886 if ((ts->ts_flags & TSF_BOUND) == 0)
2888 ts->ts_flags &= ~TSF_BOUND;
2893 sched_is_bound(struct thread *td)
2895 THREAD_LOCK_ASSERT(td, MA_OWNED);
2896 return (td_get_sched(td)->ts_flags & TSF_BOUND);
2903 sched_relinquish(struct thread *td)
2906 mi_switch(SW_VOL | SWT_RELINQUISH);
2910 * Return the total system load.
2921 total += atomic_load_int(&TDQ_CPU(i)->tdq_sysload);
2924 return (atomic_load_int(&TDQ_SELF()->tdq_sysload));
2929 sched_sizeof_proc(void)
2931 return (sizeof(struct proc));
2935 sched_sizeof_thread(void)
2937 return (sizeof(struct thread) + sizeof(struct td_sched));
2941 #define TDQ_IDLESPIN(tdq) \
2942 ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
2944 #define TDQ_IDLESPIN(tdq) 1
2948 * The actual idle process.
2951 sched_idletd(void *dummy)
2955 int oldswitchcnt, switchcnt;
2958 mtx_assert(&Giant, MA_NOTOWNED);
2961 THREAD_NO_SLEEPING();
2964 if (TDQ_LOAD(tdq)) {
2966 mi_switch(SW_VOL | SWT_IDLE);
2968 switchcnt = TDQ_SWITCHCNT(tdq);
2970 if (always_steal || switchcnt != oldswitchcnt) {
2971 oldswitchcnt = switchcnt;
2972 if (tdq_idled(tdq) == 0)
2975 switchcnt = TDQ_SWITCHCNT(tdq);
2977 oldswitchcnt = switchcnt;
2980 * If we're switching very frequently, spin while checking
2981 * for load rather than entering a low power state that
2982 * may require an IPI. However, don't do any busy
2983 * loops while on SMT machines as this simply steals
2984 * cycles from cores doing useful work.
2986 if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
2987 for (i = 0; i < sched_idlespins; i++) {
2994 /* If there was context switch during spin, restart it. */
2995 switchcnt = TDQ_SWITCHCNT(tdq);
2996 if (TDQ_LOAD(tdq) != 0 || switchcnt != oldswitchcnt)
2999 /* Run main MD idle handler. */
3000 atomic_store_int(&tdq->tdq_cpu_idle, 1);
3002 * Make sure that the tdq_cpu_idle update is globally visible
3003 * before cpu_idle() reads tdq_load. The order is important
3004 * to avoid races with tdq_notify().
3006 atomic_thread_fence_seq_cst();
3008 * Checking for again after the fence picks up assigned
3009 * threads often enough to make it worthwhile to do so in
3010 * order to avoid calling cpu_idle().
3012 if (TDQ_LOAD(tdq) != 0) {
3013 atomic_store_int(&tdq->tdq_cpu_idle, 0);
3016 cpu_idle(switchcnt * 4 > sched_idlespinthresh);
3017 atomic_store_int(&tdq->tdq_cpu_idle, 0);
3020 * Account thread-less hardware interrupts and
3021 * other wakeup reasons equal to context switches.
3023 switchcnt = TDQ_SWITCHCNT(tdq);
3024 if (switchcnt != oldswitchcnt)
3026 TDQ_SWITCHCNT_INC(tdq);
3032 * A CPU is entering for the first time or a thread is exiting.
3035 sched_throw(struct thread *td)
3037 struct thread *newtd;
3041 if (__predict_false(td == NULL)) {
3043 /* Correct spinlock nesting. */
3045 PCPU_SET(switchtime, cpu_ticks());
3046 PCPU_SET(switchticks, ticks);
3048 THREAD_LOCK_ASSERT(td, MA_OWNED);
3049 THREAD_LOCKPTR_ASSERT(td, TDQ_LOCKPTR(tdq));
3050 tdq_load_rem(tdq, td);
3051 td->td_lastcpu = td->td_oncpu;
3052 td->td_oncpu = NOCPU;
3053 thread_lock_block(td);
3055 newtd = choosethread();
3058 KASSERT(curthread->td_md.md_spinlock_count == 1,
3059 ("invalid count %d", curthread->td_md.md_spinlock_count));
3060 /* doesn't return */
3061 if (__predict_false(td == NULL))
3062 cpu_throw(td, newtd); /* doesn't return */
3064 cpu_switch(td, newtd, TDQ_LOCKPTR(tdq));
3068 * This is called from fork_exit(). Just acquire the correct locks and
3069 * let fork do the rest of the work.
3072 sched_fork_exit(struct thread *td)
3078 * Finish setting up thread glue so that it begins execution in a
3079 * non-nested critical section with the scheduler lock held.
3081 KASSERT(curthread->td_md.md_spinlock_count == 1,
3082 ("invalid count %d", curthread->td_md.md_spinlock_count));
3083 cpuid = PCPU_GET(cpuid);
3087 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
3088 td->td_oncpu = cpuid;
3089 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
3090 "prio:%d", td->td_priority);
3091 SDT_PROBE0(sched, , , on__cpu);
3095 * Create on first use to catch odd startup conditions.
3098 sched_tdname(struct thread *td)
3101 struct td_sched *ts;
3103 ts = td_get_sched(td);
3104 if (ts->ts_name[0] == '\0')
3105 snprintf(ts->ts_name, sizeof(ts->ts_name),
3106 "%s tid %d", td->td_name, td->td_tid);
3107 return (ts->ts_name);
3109 return (td->td_name);
3115 sched_clear_tdname(struct thread *td)
3117 struct td_sched *ts;
3119 ts = td_get_sched(td);
3120 ts->ts_name[0] = '\0';
3127 * Build the CPU topology dump string. Is recursively called to collect
3128 * the topology tree.
3131 sysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
3134 char cpusetbuf[CPUSETBUFSIZ];
3137 sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
3138 "", 1 + indent / 2, cg->cg_level);
3139 sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
3140 cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
3142 for (i = cg->cg_first; i <= cg->cg_last; i++) {
3143 if (CPU_ISSET(i, &cg->cg_mask)) {
3145 sbuf_printf(sb, ", ");
3148 sbuf_printf(sb, "%d", i);
3151 sbuf_printf(sb, "</cpu>\n");
3153 if (cg->cg_flags != 0) {
3154 sbuf_printf(sb, "%*s <flags>", indent, "");
3155 if ((cg->cg_flags & CG_FLAG_HTT) != 0)
3156 sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
3157 if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
3158 sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
3159 if ((cg->cg_flags & CG_FLAG_SMT) != 0)
3160 sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
3161 if ((cg->cg_flags & CG_FLAG_NODE) != 0)
3162 sbuf_printf(sb, "<flag name=\"NODE\">NUMA node</flag>");
3163 sbuf_printf(sb, "</flags>\n");
3166 if (cg->cg_children > 0) {
3167 sbuf_printf(sb, "%*s <children>\n", indent, "");
3168 for (i = 0; i < cg->cg_children; i++)
3169 sysctl_kern_sched_topology_spec_internal(sb,
3170 &cg->cg_child[i], indent+2);
3171 sbuf_printf(sb, "%*s </children>\n", indent, "");
3173 sbuf_printf(sb, "%*s</group>\n", indent, "");
3178 * Sysctl handler for retrieving topology dump. It's a wrapper for
3179 * the recursive sysctl_kern_smp_topology_spec_internal().
3182 sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
3187 KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
3189 topo = sbuf_new_for_sysctl(NULL, NULL, 512, req);
3193 sbuf_printf(topo, "<groups>\n");
3194 err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
3195 sbuf_printf(topo, "</groups>\n");
3198 err = sbuf_finish(topo);
3207 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
3209 int error, new_val, period;
3211 period = 1000000 / realstathz;
3212 new_val = period * sched_slice;
3213 error = sysctl_handle_int(oidp, &new_val, 0, req);
3214 if (error != 0 || req->newptr == NULL)
3218 sched_slice = imax(1, (new_val + period / 2) / period);
3219 sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
3220 hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
3225 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
3227 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
3229 SYSCTL_PROC(_kern_sched, OID_AUTO, quantum,
3230 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
3231 sysctl_kern_quantum, "I",
3232 "Quantum for timeshare threads in microseconds");
3233 SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
3234 "Quantum for timeshare threads in stathz ticks");
3235 SYSCTL_UINT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
3236 "Interactivity score threshold");
3237 SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW,
3239 "Maximal (lowest) priority for preemption");
3240 SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost, 0,
3241 "Assign static kernel priorities to sleeping threads");
3242 SYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins, 0,
3243 "Number of times idle thread will spin waiting for new work");
3244 SYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW,
3245 &sched_idlespinthresh, 0,
3246 "Threshold before we will permit idle thread spinning");
3248 SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
3249 "Number of hz ticks to keep thread affinity for");
3250 SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
3251 "Enables the long-term load balancer");
3252 SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
3253 &balance_interval, 0,
3254 "Average period in stathz ticks to run the long-term balancer");
3255 SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
3256 "Attempts to steal work from other cores before idling");
3257 SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
3258 "Minimum load on remote CPU before we'll steal");
3259 SYSCTL_INT(_kern_sched, OID_AUTO, trysteal_limit, CTLFLAG_RW, &trysteal_limit,
3260 0, "Topological distance limit for stealing threads in sched_switch()");
3261 SYSCTL_INT(_kern_sched, OID_AUTO, always_steal, CTLFLAG_RW, &always_steal, 0,
3262 "Always run the stealer from the idle thread");
3263 SYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
3264 CTLFLAG_MPSAFE | CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
3265 "XML dump of detected CPU topology");
3268 /* ps compat. All cpu percentages from ULE are weighted. */
3269 static int ccpu = 0;
3270 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0,
3271 "Decay factor used for updating %CPU in 4BSD scheduler");