1 /*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 2002-2007, Jeffrey Roberson <jeff@freebsd.org>
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice unmodified, this list of conditions, and the following
12 * disclaimer.
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.
16 *
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.
27 */
28
29 /*
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.
33 *
34 * etymology:
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.
38 */
39
40 #include <sys/cdefs.h>
41 #include "opt_hwpmc_hooks.h"
42 #include "opt_sched.h"
43
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/kdb.h>
47 #include <sys/kernel.h>
48 #include <sys/ktr.h>
49 #include <sys/limits.h>
50 #include <sys/lock.h>
51 #include <sys/mutex.h>
52 #include <sys/proc.h>
53 #include <sys/resource.h>
54 #include <sys/resourcevar.h>
55 #include <sys/runq.h>
56 #include <sys/sched.h>
57 #include <sys/sdt.h>
58 #include <sys/smp.h>
59 #include <sys/sx.h>
60 #include <sys/sysctl.h>
61 #include <sys/sysproto.h>
62 #include <sys/turnstile.h>
63 #include <sys/umtxvar.h>
64 #include <sys/vmmeter.h>
65 #include <sys/cpuset.h>
66 #include <sys/sbuf.h>
67
68 #ifdef HWPMC_HOOKS
69 #include <sys/pmckern.h>
70 #endif
71
72 #ifdef KDTRACE_HOOKS
73 #include <sys/dtrace_bsd.h>
74 int __read_mostly dtrace_vtime_active;
75 dtrace_vtime_switch_func_t dtrace_vtime_switch_func;
76 #endif
77
78 #include <machine/cpu.h>
79 #include <machine/smp.h>
80
81 #define KTR_ULE 0
82
83 #define TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
84 #define TDQ_NAME_LEN (sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
85 #define TDQ_LOADNAME_LEN (sizeof("CPU ") + sizeof(__XSTRING(MAXCPU)) - 1 + sizeof(" load"))
86
87 /*
88 * Thread scheduler specific section. All fields are protected
89 * by the thread lock.
90 */
91 struct td_sched {
92 short ts_flags; /* TSF_* flags. */
93 int ts_cpu; /* CPU we are on, or were last on. */
94 u_int ts_rltick; /* Real last tick, for affinity. */
95 u_int ts_slice; /* Ticks of slice remaining. */
96 u_int ts_ftick; /* %CPU window's first tick */
97 u_int ts_ltick; /* %CPU window's last tick */
98 /* All ticks count below are stored shifted by SCHED_TICK_SHIFT. */
99 u_int ts_slptime; /* Number of ticks we vol. slept */
100 u_int ts_runtime; /* Number of ticks we were running */
101 u_int ts_ticks; /* pctcpu window's running tick count */
102 #ifdef KTR
103 char ts_name[TS_NAME_LEN];
104 #endif
105 };
106 /* flags kept in ts_flags */
107 #define TSF_BOUND 0x0001 /* Thread can not migrate. */
108 #define TSF_XFERABLE 0x0002 /* Thread was added as transferable. */
109
110 #define THREAD_CAN_MIGRATE(td) ((td)->td_pinned == 0)
111 #define THREAD_CAN_SCHED(td, cpu) \
112 CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
113
114 _Static_assert(sizeof(struct thread) + sizeof(struct td_sched) <=
115 sizeof(struct thread0_storage),
116 "increase struct thread0_storage.t0st_sched size");
117
118 /*
119 * Priority ranges used for interactive and non-interactive timeshare
120 * threads. The timeshare priorities are split up into four ranges.
121 * The first range handles interactive threads. The last three ranges
122 * (NHALF, x, and NHALF) handle non-interactive threads with the outer
123 * ranges supporting nice values.
124 */
125 #define PRI_TIMESHARE_RANGE (PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
126 #define PRI_INTERACT_RANGE ((PRI_TIMESHARE_RANGE - SCHED_PRI_NRESV) / 2)
127 #define PRI_BATCH_RANGE (PRI_TIMESHARE_RANGE - PRI_INTERACT_RANGE)
128
129 #define PRI_MIN_INTERACT PRI_MIN_TIMESHARE
130 #define PRI_MAX_INTERACT (PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE - 1)
131 #define PRI_MIN_BATCH (PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE)
132 #define PRI_MAX_BATCH PRI_MAX_TIMESHARE
133
134 /*
135 * These macros determine priorities for non-interactive threads. They are
136 * assigned a priority based on their recent cpu utilization as expressed
137 * by the ratio of ticks to the tick total. NHALF priorities at the start
138 * and end of the MIN to MAX timeshare range are only reachable with negative
139 * or positive nice respectively.
140 *
141 * CPU_RANGE: Length of range for priorities computed from CPU use.
142 * NICE: Priority offset due to the nice value.
143 * 5/4 is to preserve historical nice effect on computation ratios.
144 * NRESV: Number of priority levels reserved to account for nice values.
145 */
146 #define SCHED_PRI_CPU_RANGE (PRI_BATCH_RANGE - SCHED_PRI_NRESV)
147 #define SCHED_PRI_NICE(nice) (((nice) - PRIO_MIN) * 5 / 4)
148 #define SCHED_PRI_NRESV SCHED_PRI_NICE(PRIO_MAX)
149
150 /*
151 * Runqueue indices for the implemented scheduling policies' priority bounds.
152 *
153 * In ULE's implementation, realtime policy covers the ITHD, REALTIME and
154 * INTERACT (see above) ranges, timesharing the BATCH range (see above), and
155 * idle policy the IDLE range.
156 *
157 * Priorities from these ranges must not be assigned to the same runqueue's
158 * queue.
159 */
160 #define RQ_RT_POL_MIN (RQ_PRI_TO_QUEUE_IDX(PRI_MIN_ITHD))
161 #define RQ_RT_POL_MAX (RQ_PRI_TO_QUEUE_IDX(PRI_MAX_INTERACT))
162 #define RQ_TS_POL_MIN (RQ_PRI_TO_QUEUE_IDX(PRI_MIN_BATCH))
163 #define RQ_TS_POL_MAX (RQ_PRI_TO_QUEUE_IDX(PRI_MAX_BATCH))
164 #define RQ_ID_POL_MIN (RQ_PRI_TO_QUEUE_IDX(PRI_MIN_IDLE))
165 #define RQ_ID_POL_MAX (RQ_PRI_TO_QUEUE_IDX(PRI_MAX_IDLE))
166
167 _Static_assert(RQ_RT_POL_MAX != RQ_TS_POL_MIN,
168 "ULE's realtime and timeshare policies' runqueue ranges overlap");
169 _Static_assert(RQ_TS_POL_MAX != RQ_ID_POL_MIN,
170 "ULE's timeshare and idle policies' runqueue ranges overlap");
171
172 /* Helper to treat the timeshare range as a circular group of queues. */
173 #define RQ_TS_POL_MODULO (RQ_TS_POL_MAX - RQ_TS_POL_MIN + 1)
174
175 /*
176 * Cpu percentage computation macros and defines.
177 *
178 * SCHED_TICK_SECS: Max number of seconds to average the cpu usage across.
179 * Must be at most 20 to avoid overflow in sched_pctcpu()'s current formula.
180 * SCHED_TICK_MAX: Max number of hz ticks matching SCHED_TICK_SECS.
181 * SCHED_TICK_SHIFT: Shift factor to avoid rounding away results.
182 * SCHED_TICK_RUN_SHIFTED: Number of shifted ticks running in last window.
183 * SCHED_TICK_LENGTH: Length of last window in shifted ticks or 1 if empty.
184 * SCHED_CPU_DECAY_NUMER: Numerator of %CPU decay factor.
185 * SCHED_CPU_DECAY_DENOM: Denominator of %CPU decay factor.
186 */
187 #define SCHED_TICK_SECS 11
188 #define SCHED_TICK_MAX(hz) ((hz) * SCHED_TICK_SECS)
189 #define SCHED_TICK_SHIFT 10
190 #define SCHED_TICK_RUN_SHIFTED(ts) ((ts)->ts_ticks)
191 #define SCHED_TICK_LENGTH(ts) (max((ts)->ts_ltick - (ts)->ts_ftick, 1))
192 #define SCHED_CPU_DECAY_NUMER 10
193 #define SCHED_CPU_DECAY_DENOM 11
194 _Static_assert(SCHED_CPU_DECAY_NUMER >= 0 && SCHED_CPU_DECAY_DENOM > 0 &&
195 SCHED_CPU_DECAY_NUMER <= SCHED_CPU_DECAY_DENOM,
196 "Inconsistent values for SCHED_CPU_DECAY_NUMER and/or "
197 "SCHED_CPU_DECAY_DENOM");
198
199 /*
200 * These determine the interactivity of a process. Interactivity differs from
201 * cpu utilization in that it expresses the voluntary time slept vs time ran
202 * while cpu utilization includes all time not running. This more accurately
203 * models the intent of the thread.
204 *
205 * SLP_RUN_MAX: Maximum amount of sleep time + run time we'll accumulate
206 * before throttling back.
207 * SLP_RUN_FORK: Maximum slp+run time to inherit at fork time.
208 * INTERACT_MAX: Maximum interactivity value. Smaller is better.
209 * INTERACT_THRESH: Threshold for placement on the current runq.
210 */
211 #define SCHED_SLP_RUN_MAX ((hz * 5) << SCHED_TICK_SHIFT)
212 #define SCHED_SLP_RUN_FORK ((hz / 2) << SCHED_TICK_SHIFT)
213 #define SCHED_INTERACT_MAX (100)
214 #define SCHED_INTERACT_HALF (SCHED_INTERACT_MAX / 2)
215 #define SCHED_INTERACT_THRESH (30)
216
217 /*
218 * These parameters determine the slice behavior for batch work.
219 */
220 #define SCHED_SLICE_DEFAULT_DIVISOR 10 /* ~94 ms, 12 stathz ticks. */
221 #define SCHED_SLICE_MIN_DIVISOR 6 /* DEFAULT/MIN = ~16 ms. */
222
223 /* Flags kept in td_flags. */
224 #define TDF_PICKCPU TDF_SCHED0 /* Thread should pick new CPU. */
225 #define TDF_SLICEEND TDF_SCHED2 /* Thread time slice is over. */
226
227 /*
228 * tickincr: Converts a stathz tick into a hz domain scaled by
229 * the shift factor. Without the shift the error rate
230 * due to rounding would be unacceptably high.
231 * realstathz: stathz is sometimes 0 and run off of hz.
232 * sched_slice: Runtime of each thread before rescheduling.
233 * preempt_thresh: Priority threshold for preemption and remote IPIs.
234 */
235 static u_int __read_mostly sched_interact = SCHED_INTERACT_THRESH;
236 static int __read_mostly tickincr = 8 << SCHED_TICK_SHIFT;
237 static int __read_mostly realstathz = 127; /* reset during boot. */
238 static int __read_mostly sched_slice = 10; /* reset during boot. */
239 static int __read_mostly sched_slice_min = 1; /* reset during boot. */
240 #ifdef PREEMPTION
241 #ifdef FULL_PREEMPTION
242 static int __read_mostly preempt_thresh = PRI_MAX_IDLE;
243 #else
244 static int __read_mostly preempt_thresh = PRI_MIN_KERN;
245 #endif
246 #else
247 static int __read_mostly preempt_thresh = 0;
248 #endif
249 static int __read_mostly static_boost = PRI_MIN_BATCH;
250 static int __read_mostly sched_idlespins = 10000;
251 static int __read_mostly sched_idlespinthresh = -1;
252
253 /*
254 * tdq - per processor runqs and statistics. A mutex synchronizes access to
255 * most fields. Some fields are loaded or modified without the mutex.
256 *
257 * Locking protocols:
258 * (c) constant after initialization
259 * (f) flag, set with the tdq lock held, cleared on local CPU
260 * (l) all accesses are CPU-local
261 * (ls) stores are performed by the local CPU, loads may be lockless
262 * (t) all accesses are protected by the tdq mutex
263 * (ts) stores are serialized by the tdq mutex, loads may be lockless
264 */
265 struct tdq {
266 /*
267 * Ordered to improve efficiency of cpu_search() and switch().
268 * tdq_lock is padded to avoid false sharing with tdq_load and
269 * tdq_cpu_idle.
270 */
271 struct mtx_padalign tdq_lock; /* run queue lock. */
272 struct cpu_group *tdq_cg; /* (c) Pointer to cpu topology. */
273 struct thread *tdq_curthread; /* (t) Current executing thread. */
274 int tdq_load; /* (ts) Aggregate load. */
275 int tdq_sysload; /* (ts) For loadavg, !ITHD load. */
276 int tdq_cpu_idle; /* (ls) cpu_idle() is active. */
277 int tdq_transferable; /* (ts) Transferable thread count. */
278 short tdq_switchcnt; /* (l) Switches this tick. */
279 short tdq_oldswitchcnt; /* (l) Switches last tick. */
280 u_char tdq_lowpri; /* (ts) Lowest priority thread. */
281 u_char tdq_owepreempt; /* (f) Remote preemption pending. */
282 u_char tdq_ts_off; /* (t) TS insertion offset. */
283 u_char tdq_ts_deq_off; /* (t) TS dequeue offset. */
284 /*
285 * (t) Number of (stathz) ticks since last offset incrementation
286 * correction.
287 */
288 u_char tdq_ts_ticks;
289 int tdq_id; /* (c) cpuid. */
290 struct runq tdq_runq; /* (t) Run queue. */
291 char tdq_name[TDQ_NAME_LEN];
292 #ifdef KTR
293 char tdq_loadname[TDQ_LOADNAME_LEN];
294 #endif
295 };
296
297 /* Idle thread states and config. */
298 #define TDQ_RUNNING 1
299 #define TDQ_IDLE 2
300
301 /* Lockless accessors. */
302 #define TDQ_LOAD(tdq) atomic_load_int(&(tdq)->tdq_load)
303 #define TDQ_TRANSFERABLE(tdq) atomic_load_int(&(tdq)->tdq_transferable)
304 #define TDQ_SWITCHCNT(tdq) (atomic_load_short(&(tdq)->tdq_switchcnt) + \
305 atomic_load_short(&(tdq)->tdq_oldswitchcnt))
306 #define TDQ_SWITCHCNT_INC(tdq) (atomic_store_short(&(tdq)->tdq_switchcnt, \
307 atomic_load_short(&(tdq)->tdq_switchcnt) + 1))
308
309 #ifdef SMP
310 struct cpu_group __read_mostly *cpu_top; /* CPU topology */
311
312 #define SCHED_AFFINITY_DEFAULT (max(1, hz / 1000))
313 /*
314 * This inequality has to be written with a positive difference of ticks to
315 * correctly handle wraparound.
316 */
317 #define SCHED_AFFINITY(ts, t) ((u_int)ticks - (ts)->ts_rltick < (t) * affinity)
318
319 /*
320 * Run-time tunables.
321 */
322 static int rebalance = 1;
323 static int balance_interval = 128; /* Default set in sched_initticks(). */
324 static int __read_mostly affinity;
325 static int __read_mostly steal_idle = 1;
326 static int __read_mostly steal_thresh = 2;
327 static int __read_mostly always_steal = 0;
328 static int __read_mostly trysteal_limit = 2;
329
330 /*
331 * One thread queue per processor.
332 */
333 static struct tdq __read_mostly *balance_tdq;
334 static int balance_ticks;
335 DPCPU_DEFINE_STATIC(struct tdq, tdq);
336 DPCPU_DEFINE_STATIC(uint32_t, randomval);
337
338 #define TDQ_SELF() ((struct tdq *)PCPU_GET(sched))
339 #define TDQ_CPU(x) (DPCPU_ID_PTR((x), tdq))
340 #define TDQ_ID(x) ((x)->tdq_id)
341 #else /* !SMP */
342 static struct tdq tdq_cpu;
343
344 #define TDQ_ID(x) (0)
345 #define TDQ_SELF() (&tdq_cpu)
346 #define TDQ_CPU(x) (&tdq_cpu)
347 #endif
348
349 #define TDQ_LOCK_ASSERT(t, type) mtx_assert(TDQ_LOCKPTR((t)), (type))
350 #define TDQ_LOCK(t) mtx_lock_spin(TDQ_LOCKPTR((t)))
351 #define TDQ_LOCK_FLAGS(t, f) mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
352 #define TDQ_TRYLOCK(t) mtx_trylock_spin(TDQ_LOCKPTR((t)))
353 #define TDQ_TRYLOCK_FLAGS(t, f) mtx_trylock_spin_flags(TDQ_LOCKPTR((t)), (f))
354 #define TDQ_UNLOCK(t) mtx_unlock_spin(TDQ_LOCKPTR((t)))
355 #define TDQ_LOCKPTR(t) ((struct mtx *)(&(t)->tdq_lock))
356
357 static void sched_setpreempt(int);
358 static void sched_priority(struct thread *);
359 static void sched_thread_priority(struct thread *, u_char);
360 static int sched_interact_score(struct thread *);
361 static void sched_interact_update(struct thread *);
362 static void sched_interact_fork(struct thread *);
363 static void sched_pctcpu_update(struct td_sched *, int);
364
365 /* Operations on per processor queues */
366 static inline struct thread *runq_choose_realtime(struct runq *const rq);
367 static inline struct thread *runq_choose_timeshare(struct runq *const rq,
368 int off);
369 static inline struct thread *runq_choose_idle(struct runq *const rq);
370 static struct thread *tdq_choose(struct tdq *);
371
372 static void tdq_setup(struct tdq *, int i);
373 static void tdq_load_add(struct tdq *, struct thread *);
374 static void tdq_load_rem(struct tdq *, struct thread *);
375 static inline void tdq_runq_add(struct tdq *, struct thread *, int);
376 static inline void tdq_advance_ts_deq_off(struct tdq *, bool);
377 static inline void tdq_runq_rem(struct tdq *, struct thread *);
378 static inline int sched_shouldpreempt(int, int, int);
379 static void tdq_print(int cpu);
380 static void runq_print(struct runq *rq);
381 static int tdq_add(struct tdq *, struct thread *, int);
382 #ifdef SMP
383 static int tdq_move(struct tdq *, struct tdq *);
384 static int tdq_idled(struct tdq *);
385 static void tdq_notify(struct tdq *, int lowpri);
386
387 static bool runq_steal_pred(const int idx, struct rq_queue *const q,
388 void *const data);
389 static inline struct thread *runq_steal_range(struct runq *const rq,
390 const int lvl_min, const int lvl_max, int cpu);
391 static inline struct thread *runq_steal_realtime(struct runq *const rq,
392 int cpu);
393 static inline struct thread *runq_steal_timeshare(struct runq *const rq,
394 int cpu, int off);
395 static inline struct thread *runq_steal_idle(struct runq *const rq,
396 int cpu);
397 static struct thread *tdq_steal(struct tdq *, int);
398
399 static int sched_pickcpu(struct thread *, int);
400 static void sched_balance(void);
401 static bool sched_balance_pair(struct tdq *, struct tdq *);
402 static inline struct tdq *sched_setcpu(struct thread *, int, int);
403 static inline void thread_unblock_switch(struct thread *, struct mtx *);
404 static int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
405 static int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
406 struct cpu_group *cg, int indent);
407 #endif
408
409 static void sched_setup(void *dummy);
410 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
411
412 static void sched_initticks(void *dummy);
413 SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
414 NULL);
415
416 SDT_PROVIDER_DEFINE(sched);
417
418 SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
419 "struct proc *", "uint8_t");
420 SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
421 "struct proc *", "void *");
422 SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
423 "struct proc *", "void *", "int");
424 SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
425 "struct proc *", "uint8_t", "struct thread *");
426 SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
427 SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
428 "struct proc *");
429 SDT_PROBE_DEFINE(sched, , , on__cpu);
430 SDT_PROBE_DEFINE(sched, , , remain__cpu);
431 SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
432 "struct proc *");
433
434 /*
435 * Print the threads waiting on a run-queue.
436 */
437 static void
runq_print(struct runq * rq)438 runq_print(struct runq *rq)
439 {
440 struct rq_queue *rqq;
441 struct thread *td;
442 int pri;
443 int j;
444 int i;
445
446 for (i = 0; i < RQSW_NB; i++) {
447 printf("\t\trunq bits %d %#lx\n",
448 i, rq->rq_status.rq_sw[i]);
449 for (j = 0; j < RQSW_BPW; j++)
450 if (rq->rq_status.rq_sw[i] & (1ul << j)) {
451 pri = RQSW_TO_QUEUE_IDX(i, j);
452 rqq = &rq->rq_queues[pri];
453 TAILQ_FOREACH(td, rqq, td_runq) {
454 printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
455 td, td->td_name, td->td_priority,
456 td->td_rqindex, pri);
457 }
458 }
459 }
460 }
461
462 /*
463 * Print the status of a per-cpu thread queue. Should be a ddb show cmd.
464 */
465 static void __unused
tdq_print(int cpu)466 tdq_print(int cpu)
467 {
468 struct tdq *tdq;
469
470 tdq = TDQ_CPU(cpu);
471
472 printf("tdq %d:\n", TDQ_ID(tdq));
473 printf("\tlock %p\n", TDQ_LOCKPTR(tdq));
474 printf("\tLock name: %s\n", tdq->tdq_name);
475 printf("\tload: %d\n", tdq->tdq_load);
476 printf("\tswitch cnt: %d\n", tdq->tdq_switchcnt);
477 printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
478 printf("\tTS insert offset: %d\n", tdq->tdq_ts_off);
479 printf("\tTS dequeue offset: %d\n", tdq->tdq_ts_deq_off);
480 printf("\tload transferable: %d\n", tdq->tdq_transferable);
481 printf("\tlowest priority: %d\n", tdq->tdq_lowpri);
482 printf("\trunq:\n");
483 runq_print(&tdq->tdq_runq);
484 }
485
486 static inline int
sched_shouldpreempt(int pri,int cpri,int remote)487 sched_shouldpreempt(int pri, int cpri, int remote)
488 {
489 /*
490 * If the new priority is not better than the current priority there is
491 * nothing to do.
492 */
493 if (pri >= cpri)
494 return (0);
495 /*
496 * Always preempt idle.
497 */
498 if (cpri >= PRI_MIN_IDLE)
499 return (1);
500 /*
501 * If preemption is disabled don't preempt others.
502 */
503 if (preempt_thresh == 0)
504 return (0);
505 /*
506 * Preempt if we exceed the threshold.
507 */
508 if (pri <= preempt_thresh)
509 return (1);
510 /*
511 * If we're interactive or better and there is non-interactive
512 * or worse running preempt only remote processors.
513 */
514 if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
515 return (1);
516 return (0);
517 }
518
519 /*
520 * Add a thread to the actual run-queue. Keeps transferable counts up to
521 * date with what is actually on the run-queue. Selects the correct
522 * queue position for timeshare threads.
523 */
524 static inline void
tdq_runq_add(struct tdq * tdq,struct thread * td,int flags)525 tdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
526 {
527 struct td_sched *ts;
528 u_char pri, idx;
529
530 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
531 THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
532
533 pri = td->td_priority;
534 ts = td_get_sched(td);
535 TD_SET_RUNQ(td);
536 if (THREAD_CAN_MIGRATE(td)) {
537 tdq->tdq_transferable++;
538 ts->ts_flags |= TSF_XFERABLE;
539 }
540 if (PRI_MIN_BATCH <= pri && pri <= PRI_MAX_BATCH) {
541 /*
542 * The queues allocated to the batch range are not used as
543 * a simple array but as a "circular" one where the insertion
544 * index (derived from 'pri') is offset by 'tdq_ts_off'. 'idx'
545 * is first set to the offset of the wanted queue in the TS'
546 * selection policy range.
547 */
548 if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) != 0)
549 /* Current queue from which processes are being run. */
550 idx = tdq->tdq_ts_deq_off;
551 else {
552 idx = (RQ_PRI_TO_QUEUE_IDX(pri) - RQ_TS_POL_MIN +
553 tdq->tdq_ts_off) % RQ_TS_POL_MODULO;
554 /*
555 * We avoid enqueuing low priority threads in the queue
556 * that we are still draining, effectively shortening
557 * the runqueue by one queue.
558 */
559 if (tdq->tdq_ts_deq_off != tdq->tdq_ts_off &&
560 idx == tdq->tdq_ts_deq_off)
561 /* Ensure the dividend is positive. */
562 idx = (idx - 1 + RQ_TS_POL_MODULO) %
563 RQ_TS_POL_MODULO;
564 }
565 /* Absolute queue index. */
566 idx += RQ_TS_POL_MIN;
567 runq_add_idx(&tdq->tdq_runq, td, idx, flags);
568 } else
569 runq_add(&tdq->tdq_runq, td, flags);
570 }
571
572 /*
573 * Advance the timesharing dequeue offset to the next non-empty queue or the
574 * insertion offset, whichever is closer.
575 *
576 * If 'deq_queue_known_empty' is true, then the queue where timesharing threads
577 * are currently removed for execution (pointed to by 'tdq_ts_deq_off') is
578 * assumed empty. Otherwise, this condition is checked for.
579 */
580 static inline void
tdq_advance_ts_deq_off(struct tdq * tdq,bool deq_queue_known_empty)581 tdq_advance_ts_deq_off(struct tdq *tdq, bool deq_queue_known_empty)
582 {
583 /*
584 * We chose a simple iterative algorithm since the difference between
585 * offsets is small in practice (see sched_clock()).
586 */
587 while (tdq->tdq_ts_deq_off != tdq->tdq_ts_off) {
588 if (deq_queue_known_empty)
589 deq_queue_known_empty = false;
590 else if (!runq_is_queue_empty(&tdq->tdq_runq,
591 tdq->tdq_ts_deq_off + RQ_TS_POL_MIN))
592 break;
593
594 tdq->tdq_ts_deq_off = (tdq->tdq_ts_deq_off + 1) %
595 RQ_TS_POL_MODULO;
596 }
597 }
598
599 /*
600 * Remove a thread from a run-queue. This typically happens when a thread
601 * is selected to run. Running threads are not on the queue and the
602 * transferable count does not reflect them.
603 */
604 static inline void
tdq_runq_rem(struct tdq * tdq,struct thread * td)605 tdq_runq_rem(struct tdq *tdq, struct thread *td)
606 {
607 struct td_sched *ts;
608 bool queue_empty;
609
610 ts = td_get_sched(td);
611 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
612 THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
613 if (ts->ts_flags & TSF_XFERABLE) {
614 tdq->tdq_transferable--;
615 ts->ts_flags &= ~TSF_XFERABLE;
616 }
617 queue_empty = runq_remove(&tdq->tdq_runq, td);
618 /*
619 * If thread has a batch priority and the queue from which it was
620 * removed is now empty, advance the batch's queue removal index if it
621 * lags with respect to the batch's queue insertion index, so that we
622 * may eventually be able to advance the latter in sched_clock().
623 */
624 if (PRI_MIN_BATCH <= td->td_priority &&
625 td->td_priority <= PRI_MAX_BATCH && queue_empty &&
626 tdq->tdq_ts_deq_off + RQ_TS_POL_MIN == td->td_rqindex)
627 tdq_advance_ts_deq_off(tdq, true);
628 }
629
630 /*
631 * Load is maintained for all threads RUNNING and ON_RUNQ. Add the load
632 * for this thread to the referenced thread queue.
633 */
634 static void
tdq_load_add(struct tdq * tdq,struct thread * td)635 tdq_load_add(struct tdq *tdq, struct thread *td)
636 {
637
638 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
639 THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
640
641 tdq->tdq_load++;
642 if ((td->td_flags & TDF_NOLOAD) == 0)
643 tdq->tdq_sysload++;
644 KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
645 SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
646 }
647
648 /*
649 * Remove the load from a thread that is transitioning to a sleep state or
650 * exiting.
651 */
652 static void
tdq_load_rem(struct tdq * tdq,struct thread * td)653 tdq_load_rem(struct tdq *tdq, struct thread *td)
654 {
655
656 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
657 THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
658 KASSERT(tdq->tdq_load != 0,
659 ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
660
661 tdq->tdq_load--;
662 if ((td->td_flags & TDF_NOLOAD) == 0)
663 tdq->tdq_sysload--;
664 KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
665 SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
666 }
667
668 /*
669 * Bound timeshare latency by decreasing slice size as load increases. We
670 * consider the maximum latency as the sum of the threads waiting to run
671 * aside from curthread and target no more than sched_slice latency but
672 * no less than sched_slice_min runtime.
673 */
674 static inline u_int
tdq_slice(struct tdq * tdq)675 tdq_slice(struct tdq *tdq)
676 {
677 int load;
678
679 /*
680 * It is safe to use sys_load here because this is called from
681 * contexts where timeshare threads are running and so there
682 * cannot be higher priority load in the system.
683 */
684 load = tdq->tdq_sysload - 1;
685 if (load >= SCHED_SLICE_MIN_DIVISOR)
686 return (sched_slice_min);
687 if (load <= 1)
688 return (sched_slice);
689 return (sched_slice / load);
690 }
691
692 /*
693 * Set lowpri to its exact value by searching the run-queue and
694 * evaluating curthread. curthread may be passed as an optimization.
695 */
696 static void
tdq_setlowpri(struct tdq * tdq,struct thread * ctd)697 tdq_setlowpri(struct tdq *tdq, struct thread *ctd)
698 {
699 struct thread *td;
700
701 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
702 if (ctd == NULL)
703 ctd = tdq->tdq_curthread;
704 td = tdq_choose(tdq);
705 if (td == NULL || td->td_priority > ctd->td_priority)
706 tdq->tdq_lowpri = ctd->td_priority;
707 else
708 tdq->tdq_lowpri = td->td_priority;
709 }
710
711 #ifdef SMP
712 /*
713 * We need some randomness. Implement a classic Linear Congruential
714 * Generator X_{n+1}=(aX_n+c) mod m. These values are optimized for
715 * m = 2^32, a = 69069 and c = 5. We only return the upper 16 bits
716 * of the random state (in the low bits of our answer) to keep
717 * the maximum randomness.
718 */
719 static uint32_t
sched_random(void)720 sched_random(void)
721 {
722 uint32_t *rndptr;
723
724 rndptr = DPCPU_PTR(randomval);
725 *rndptr = *rndptr * 69069 + 5;
726
727 return (*rndptr >> 16);
728 }
729
730 struct cpu_search {
731 cpuset_t *cs_mask; /* The mask of allowed CPUs to choose from. */
732 int cs_prefer; /* Prefer this CPU and groups including it. */
733 int cs_running; /* The thread is now running at cs_prefer. */
734 int cs_pri; /* Min priority for low. */
735 int cs_load; /* Max load for low, min load for high. */
736 int cs_trans; /* Min transferable load for high. */
737 };
738
739 struct cpu_search_res {
740 int csr_cpu; /* The best CPU found. */
741 int csr_load; /* The load of cs_cpu. */
742 };
743
744 /*
745 * Search the tree of cpu_groups for the lowest or highest loaded CPU.
746 * These routines actually compare the load on all paths through the tree
747 * and find the least loaded cpu on the least loaded path, which may differ
748 * from the least loaded cpu in the system. This balances work among caches
749 * and buses.
750 */
751 static int
cpu_search_lowest(const struct cpu_group * cg,const struct cpu_search * s,struct cpu_search_res * r)752 cpu_search_lowest(const struct cpu_group *cg, const struct cpu_search *s,
753 struct cpu_search_res *r)
754 {
755 struct cpu_search_res lr;
756 struct tdq *tdq;
757 int c, bload, l, load, p, total;
758
759 total = 0;
760 bload = INT_MAX;
761 r->csr_cpu = -1;
762
763 /* Loop through children CPU groups if there are any. */
764 if (cg->cg_children > 0) {
765 for (c = cg->cg_children - 1; c >= 0; c--) {
766 load = cpu_search_lowest(&cg->cg_child[c], s, &lr);
767 total += load;
768
769 /*
770 * When balancing do not prefer SMT groups with load >1.
771 * It allows round-robin between SMT groups with equal
772 * load within parent group for more fair scheduling.
773 */
774 if (__predict_false(s->cs_running) &&
775 (cg->cg_child[c].cg_flags & CG_FLAG_THREAD) &&
776 load >= 128 && (load & 128) != 0)
777 load += 128;
778
779 if (lr.csr_cpu >= 0 && (load < bload ||
780 (load == bload && lr.csr_load < r->csr_load))) {
781 bload = load;
782 r->csr_cpu = lr.csr_cpu;
783 r->csr_load = lr.csr_load;
784 }
785 }
786 return (total);
787 }
788
789 /* Loop through children CPUs otherwise. */
790 for (c = cg->cg_last; c >= cg->cg_first; c--) {
791 if (!CPU_ISSET(c, &cg->cg_mask))
792 continue;
793 tdq = TDQ_CPU(c);
794 l = TDQ_LOAD(tdq);
795 if (c == s->cs_prefer) {
796 if (__predict_false(s->cs_running))
797 l--;
798 p = 128;
799 } else
800 p = 0;
801 load = l * 256;
802 total += load - p;
803
804 /*
805 * Check this CPU is acceptable.
806 * If the threads is already on the CPU, don't look on the TDQ
807 * priority, since it can be the priority of the thread itself.
808 */
809 if (l > s->cs_load ||
810 (atomic_load_char(&tdq->tdq_lowpri) <= s->cs_pri &&
811 (!s->cs_running || c != s->cs_prefer)) ||
812 !CPU_ISSET(c, s->cs_mask))
813 continue;
814
815 /*
816 * When balancing do not prefer CPUs with load > 1.
817 * It allows round-robin between CPUs with equal load
818 * within the CPU group for more fair scheduling.
819 */
820 if (__predict_false(s->cs_running) && l > 0)
821 p = 0;
822
823 load -= sched_random() % 128;
824 if (bload > load - p) {
825 bload = load - p;
826 r->csr_cpu = c;
827 r->csr_load = load;
828 }
829 }
830 return (total);
831 }
832
833 static int
cpu_search_highest(const struct cpu_group * cg,const struct cpu_search * s,struct cpu_search_res * r)834 cpu_search_highest(const struct cpu_group *cg, const struct cpu_search *s,
835 struct cpu_search_res *r)
836 {
837 struct cpu_search_res lr;
838 struct tdq *tdq;
839 int c, bload, l, load, total;
840
841 total = 0;
842 bload = INT_MIN;
843 r->csr_cpu = -1;
844
845 /* Loop through children CPU groups if there are any. */
846 if (cg->cg_children > 0) {
847 for (c = cg->cg_children - 1; c >= 0; c--) {
848 load = cpu_search_highest(&cg->cg_child[c], s, &lr);
849 total += load;
850 if (lr.csr_cpu >= 0 && (load > bload ||
851 (load == bload && lr.csr_load > r->csr_load))) {
852 bload = load;
853 r->csr_cpu = lr.csr_cpu;
854 r->csr_load = lr.csr_load;
855 }
856 }
857 return (total);
858 }
859
860 /* Loop through children CPUs otherwise. */
861 for (c = cg->cg_last; c >= cg->cg_first; c--) {
862 if (!CPU_ISSET(c, &cg->cg_mask))
863 continue;
864 tdq = TDQ_CPU(c);
865 l = TDQ_LOAD(tdq);
866 load = l * 256;
867 total += load;
868
869 /*
870 * Check this CPU is acceptable.
871 */
872 if (l < s->cs_load || TDQ_TRANSFERABLE(tdq) < s->cs_trans ||
873 !CPU_ISSET(c, s->cs_mask))
874 continue;
875
876 load -= sched_random() % 256;
877 if (load > bload) {
878 bload = load;
879 r->csr_cpu = c;
880 }
881 }
882 r->csr_load = bload;
883 return (total);
884 }
885
886 /*
887 * Find the cpu with the least load via the least loaded path that has a
888 * lowpri greater than pri pri. A pri of -1 indicates any priority is
889 * acceptable.
890 */
891 static inline int
sched_lowest(const struct cpu_group * cg,cpuset_t * mask,int pri,int maxload,int prefer,int running)892 sched_lowest(const struct cpu_group *cg, cpuset_t *mask, int pri, int maxload,
893 int prefer, int running)
894 {
895 struct cpu_search s;
896 struct cpu_search_res r;
897
898 s.cs_prefer = prefer;
899 s.cs_running = running;
900 s.cs_mask = mask;
901 s.cs_pri = pri;
902 s.cs_load = maxload;
903 cpu_search_lowest(cg, &s, &r);
904 return (r.csr_cpu);
905 }
906
907 /*
908 * Find the cpu with the highest load via the highest loaded path.
909 */
910 static inline int
sched_highest(const struct cpu_group * cg,cpuset_t * mask,int minload,int mintrans)911 sched_highest(const struct cpu_group *cg, cpuset_t *mask, int minload,
912 int mintrans)
913 {
914 struct cpu_search s;
915 struct cpu_search_res r;
916
917 s.cs_mask = mask;
918 s.cs_load = minload;
919 s.cs_trans = mintrans;
920 cpu_search_highest(cg, &s, &r);
921 return (r.csr_cpu);
922 }
923
924 static void
sched_balance_group(struct cpu_group * cg)925 sched_balance_group(struct cpu_group *cg)
926 {
927 struct tdq *tdq;
928 struct thread *td;
929 cpuset_t hmask, lmask;
930 int high, low, anylow;
931
932 CPU_FILL(&hmask);
933 for (;;) {
934 high = sched_highest(cg, &hmask, 1, 0);
935 /* Stop if there is no more CPU with transferrable threads. */
936 if (high == -1)
937 break;
938 CPU_CLR(high, &hmask);
939 CPU_COPY(&hmask, &lmask);
940 /* Stop if there is no more CPU left for low. */
941 if (CPU_EMPTY(&lmask))
942 break;
943 tdq = TDQ_CPU(high);
944 if (TDQ_LOAD(tdq) == 1) {
945 /*
946 * There is only one running thread. We can't move
947 * it from here, so tell it to pick new CPU by itself.
948 */
949 TDQ_LOCK(tdq);
950 td = tdq->tdq_curthread;
951 if (td->td_lock == TDQ_LOCKPTR(tdq) &&
952 (td->td_flags & TDF_IDLETD) == 0 &&
953 THREAD_CAN_MIGRATE(td)) {
954 td->td_flags |= TDF_PICKCPU;
955 ast_sched_locked(td, TDA_SCHED);
956 if (high != curcpu)
957 ipi_cpu(high, IPI_AST);
958 }
959 TDQ_UNLOCK(tdq);
960 break;
961 }
962 anylow = 1;
963 nextlow:
964 if (TDQ_TRANSFERABLE(tdq) == 0)
965 continue;
966 low = sched_lowest(cg, &lmask, -1, TDQ_LOAD(tdq) - 1, high, 1);
967 /* Stop if we looked well and found no less loaded CPU. */
968 if (anylow && low == -1)
969 break;
970 /* Go to next high if we found no less loaded CPU. */
971 if (low == -1)
972 continue;
973 /* Transfer thread from high to low. */
974 if (sched_balance_pair(tdq, TDQ_CPU(low))) {
975 /* CPU that got thread can no longer be a donor. */
976 CPU_CLR(low, &hmask);
977 } else {
978 /*
979 * If failed, then there is no threads on high
980 * that can run on this low. Drop low from low
981 * mask and look for different one.
982 */
983 CPU_CLR(low, &lmask);
984 anylow = 0;
985 goto nextlow;
986 }
987 }
988 }
989
990 static void
sched_balance(void)991 sched_balance(void)
992 {
993 struct tdq *tdq;
994
995 balance_ticks = max(balance_interval / 2, 1) +
996 (sched_random() % balance_interval);
997 tdq = TDQ_SELF();
998 TDQ_UNLOCK(tdq);
999 sched_balance_group(cpu_top);
1000 TDQ_LOCK(tdq);
1001 }
1002
1003 /*
1004 * Lock two thread queues using their address to maintain lock order.
1005 */
1006 static void
tdq_lock_pair(struct tdq * one,struct tdq * two)1007 tdq_lock_pair(struct tdq *one, struct tdq *two)
1008 {
1009 if (one < two) {
1010 TDQ_LOCK(one);
1011 TDQ_LOCK_FLAGS(two, MTX_DUPOK);
1012 } else {
1013 TDQ_LOCK(two);
1014 TDQ_LOCK_FLAGS(one, MTX_DUPOK);
1015 }
1016 }
1017
1018 /*
1019 * Unlock two thread queues. Order is not important here.
1020 */
1021 static void
tdq_unlock_pair(struct tdq * one,struct tdq * two)1022 tdq_unlock_pair(struct tdq *one, struct tdq *two)
1023 {
1024 TDQ_UNLOCK(one);
1025 TDQ_UNLOCK(two);
1026 }
1027
1028 /*
1029 * Transfer load between two imbalanced thread queues. Returns true if a thread
1030 * was moved between the queues, and false otherwise.
1031 */
1032 static bool
sched_balance_pair(struct tdq * high,struct tdq * low)1033 sched_balance_pair(struct tdq *high, struct tdq *low)
1034 {
1035 int cpu, lowpri;
1036 bool ret;
1037
1038 ret = false;
1039 tdq_lock_pair(high, low);
1040
1041 /*
1042 * Transfer a thread from high to low.
1043 */
1044 if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load) {
1045 lowpri = tdq_move(high, low);
1046 if (lowpri != -1) {
1047 /*
1048 * In case the target isn't the current CPU notify it of
1049 * the new load, possibly sending an IPI to force it to
1050 * reschedule. Otherwise maybe schedule a preemption.
1051 */
1052 cpu = TDQ_ID(low);
1053 if (cpu != PCPU_GET(cpuid))
1054 tdq_notify(low, lowpri);
1055 else
1056 sched_setpreempt(low->tdq_lowpri);
1057 ret = true;
1058 }
1059 }
1060 tdq_unlock_pair(high, low);
1061 return (ret);
1062 }
1063
1064 /*
1065 * Move a thread from one thread queue to another. Returns -1 if the source
1066 * queue was empty, else returns the maximum priority of all threads in
1067 * the destination queue prior to the addition of the new thread. In the latter
1068 * case, this priority can be used to determine whether an IPI needs to be
1069 * delivered.
1070 */
1071 static int
tdq_move(struct tdq * from,struct tdq * to)1072 tdq_move(struct tdq *from, struct tdq *to)
1073 {
1074 struct thread *td;
1075 int cpu;
1076
1077 TDQ_LOCK_ASSERT(from, MA_OWNED);
1078 TDQ_LOCK_ASSERT(to, MA_OWNED);
1079
1080 cpu = TDQ_ID(to);
1081 td = tdq_steal(from, cpu);
1082 if (td == NULL)
1083 return (-1);
1084
1085 /*
1086 * Although the run queue is locked the thread may be
1087 * blocked. We can not set the lock until it is unblocked.
1088 */
1089 thread_lock_block_wait(td);
1090 sched_rem(td);
1091 THREAD_LOCKPTR_ASSERT(td, TDQ_LOCKPTR(from));
1092 td->td_lock = TDQ_LOCKPTR(to);
1093 td_get_sched(td)->ts_cpu = cpu;
1094 return (tdq_add(to, td, SRQ_YIELDING));
1095 }
1096
1097 /*
1098 * This tdq has idled. Try to steal a thread from another cpu and switch
1099 * to it.
1100 */
1101 static int
tdq_idled(struct tdq * tdq)1102 tdq_idled(struct tdq *tdq)
1103 {
1104 struct cpu_group *cg, *parent;
1105 struct tdq *steal;
1106 cpuset_t mask;
1107 int cpu, switchcnt, goup;
1108
1109 if (smp_started == 0 || steal_idle == 0 || tdq->tdq_cg == NULL)
1110 return (1);
1111 CPU_FILL(&mask);
1112 CPU_CLR(PCPU_GET(cpuid), &mask);
1113 restart:
1114 switchcnt = TDQ_SWITCHCNT(tdq);
1115 for (cg = tdq->tdq_cg, goup = 0; ; ) {
1116 cpu = sched_highest(cg, &mask, steal_thresh, 1);
1117 /*
1118 * We were assigned a thread but not preempted. Returning
1119 * 0 here will cause our caller to switch to it.
1120 */
1121 if (TDQ_LOAD(tdq))
1122 return (0);
1123
1124 /*
1125 * We found no CPU to steal from in this group. Escalate to
1126 * the parent and repeat. But if parent has only two children
1127 * groups we can avoid searching this group again by searching
1128 * the other one specifically and then escalating two levels.
1129 */
1130 if (cpu == -1) {
1131 if (goup) {
1132 cg = cg->cg_parent;
1133 goup = 0;
1134 }
1135 parent = cg->cg_parent;
1136 if (parent == NULL)
1137 return (1);
1138 if (parent->cg_children == 2) {
1139 if (cg == &parent->cg_child[0])
1140 cg = &parent->cg_child[1];
1141 else
1142 cg = &parent->cg_child[0];
1143 goup = 1;
1144 } else
1145 cg = parent;
1146 continue;
1147 }
1148 steal = TDQ_CPU(cpu);
1149 /*
1150 * The data returned by sched_highest() is stale and
1151 * the chosen CPU no longer has an eligible thread.
1152 *
1153 * Testing this ahead of tdq_lock_pair() only catches
1154 * this situation about 20% of the time on an 8 core
1155 * 16 thread Ryzen 7, but it still helps performance.
1156 */
1157 if (TDQ_LOAD(steal) < steal_thresh ||
1158 TDQ_TRANSFERABLE(steal) == 0)
1159 goto restart;
1160 /*
1161 * Try to lock both queues. If we are assigned a thread while
1162 * waited for the lock, switch to it now instead of stealing.
1163 * If we can't get the lock, then somebody likely got there
1164 * first so continue searching.
1165 */
1166 TDQ_LOCK(tdq);
1167 if (tdq->tdq_load > 0) {
1168 mi_switch(SW_VOL | SWT_IDLE);
1169 return (0);
1170 }
1171 if (TDQ_TRYLOCK_FLAGS(steal, MTX_DUPOK) == 0) {
1172 TDQ_UNLOCK(tdq);
1173 CPU_CLR(cpu, &mask);
1174 continue;
1175 }
1176 /*
1177 * The data returned by sched_highest() is stale and
1178 * the chosen CPU no longer has an eligible thread, or
1179 * we were preempted and the CPU loading info may be out
1180 * of date. The latter is rare. In either case restart
1181 * the search.
1182 */
1183 if (TDQ_LOAD(steal) < steal_thresh ||
1184 TDQ_TRANSFERABLE(steal) == 0 ||
1185 switchcnt != TDQ_SWITCHCNT(tdq)) {
1186 tdq_unlock_pair(tdq, steal);
1187 goto restart;
1188 }
1189 /*
1190 * Steal the thread and switch to it.
1191 */
1192 if (tdq_move(steal, tdq) != -1)
1193 break;
1194 /*
1195 * We failed to acquire a thread even though it looked
1196 * like one was available. This could be due to affinity
1197 * restrictions or for other reasons. Loop again after
1198 * removing this CPU from the set. The restart logic
1199 * above does not restore this CPU to the set due to the
1200 * likelyhood of failing here again.
1201 */
1202 CPU_CLR(cpu, &mask);
1203 tdq_unlock_pair(tdq, steal);
1204 }
1205 TDQ_UNLOCK(steal);
1206 mi_switch(SW_VOL | SWT_IDLE);
1207 return (0);
1208 }
1209
1210 /*
1211 * Notify a remote cpu of new work. Sends an IPI if criteria are met.
1212 *
1213 * "lowpri" is the minimum scheduling priority among all threads on
1214 * the queue prior to the addition of the new thread.
1215 */
1216 static void
tdq_notify(struct tdq * tdq,int lowpri)1217 tdq_notify(struct tdq *tdq, int lowpri)
1218 {
1219 int cpu;
1220
1221 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1222 KASSERT(tdq->tdq_lowpri <= lowpri,
1223 ("tdq_notify: lowpri %d > tdq_lowpri %d", lowpri, tdq->tdq_lowpri));
1224
1225 if (tdq->tdq_owepreempt)
1226 return;
1227
1228 /*
1229 * Check to see if the newly added thread should preempt the one
1230 * currently running.
1231 */
1232 if (!sched_shouldpreempt(tdq->tdq_lowpri, lowpri, 1))
1233 return;
1234
1235 /*
1236 * Make sure that our caller's earlier update to tdq_load is
1237 * globally visible before we read tdq_cpu_idle. Idle thread
1238 * accesses both of them without locks, and the order is important.
1239 */
1240 atomic_thread_fence_seq_cst();
1241
1242 /*
1243 * Try to figure out if we can signal the idle thread instead of sending
1244 * an IPI. This check is racy; at worst, we will deliever an IPI
1245 * unnecessarily.
1246 */
1247 cpu = TDQ_ID(tdq);
1248 if (TD_IS_IDLETHREAD(tdq->tdq_curthread) &&
1249 (atomic_load_int(&tdq->tdq_cpu_idle) == 0 || cpu_idle_wakeup(cpu)))
1250 return;
1251
1252 /*
1253 * The run queues have been updated, so any switch on the remote CPU
1254 * will satisfy the preemption request.
1255 */
1256 tdq->tdq_owepreempt = 1;
1257 ipi_cpu(cpu, IPI_PREEMPT);
1258 }
1259
1260 struct runq_steal_pred_data {
1261 struct thread *td;
1262 int cpu;
1263 };
1264
1265 static bool
runq_steal_pred(const int idx,struct rq_queue * const q,void * const data)1266 runq_steal_pred(const int idx, struct rq_queue *const q, void *const data)
1267 {
1268 struct runq_steal_pred_data *const d = data;
1269 struct thread *td;
1270
1271 TAILQ_FOREACH(td, q, td_runq) {
1272 if (THREAD_CAN_MIGRATE(td) && THREAD_CAN_SCHED(td, d->cpu)) {
1273 d->td = td;
1274 return (true);
1275 }
1276 }
1277
1278 return (false);
1279 }
1280
1281 /*
1282 * Steals load contained in queues with indices in the specified range.
1283 */
1284 static inline struct thread *
runq_steal_range(struct runq * const rq,const int lvl_min,const int lvl_max,int cpu)1285 runq_steal_range(struct runq *const rq, const int lvl_min, const int lvl_max,
1286 int cpu)
1287 {
1288 struct runq_steal_pred_data data = {
1289 .td = NULL,
1290 .cpu = cpu,
1291 };
1292 int idx;
1293
1294 idx = runq_findq(rq, lvl_min, lvl_max, &runq_steal_pred, &data);
1295 if (idx != -1) {
1296 MPASS(data.td != NULL);
1297 return (data.td);
1298 }
1299
1300 MPASS(data.td == NULL);
1301 return (NULL);
1302 }
1303
1304 static inline struct thread *
runq_steal_realtime(struct runq * const rq,int cpu)1305 runq_steal_realtime(struct runq *const rq, int cpu)
1306 {
1307
1308 return (runq_steal_range(rq, RQ_RT_POL_MIN, RQ_RT_POL_MAX, cpu));
1309 }
1310
1311 /*
1312 * Steals load from a timeshare queue. Honors the rotating queue head
1313 * index.
1314 */
1315 static inline struct thread *
runq_steal_timeshare(struct runq * const rq,int cpu,int off)1316 runq_steal_timeshare(struct runq *const rq, int cpu, int off)
1317 {
1318 struct thread *td;
1319
1320 MPASS(0 <= off && off < RQ_TS_POL_MODULO);
1321
1322 td = runq_steal_range(rq, RQ_TS_POL_MIN + off, RQ_TS_POL_MAX, cpu);
1323 if (td != NULL || off == 0)
1324 return (td);
1325
1326 td = runq_steal_range(rq, RQ_TS_POL_MIN, RQ_TS_POL_MIN + off - 1, cpu);
1327 return (td);
1328 }
1329
1330 static inline struct thread *
runq_steal_idle(struct runq * const rq,int cpu)1331 runq_steal_idle(struct runq *const rq, int cpu)
1332 {
1333
1334 return (runq_steal_range(rq, RQ_ID_POL_MIN, RQ_ID_POL_MAX, cpu));
1335 }
1336
1337
1338 /*
1339 * Attempt to steal a thread in priority order from a thread queue.
1340 */
1341 static struct thread *
tdq_steal(struct tdq * tdq,int cpu)1342 tdq_steal(struct tdq *tdq, int cpu)
1343 {
1344 struct thread *td;
1345
1346 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1347 td = runq_steal_realtime(&tdq->tdq_runq, cpu);
1348 if (td != NULL)
1349 return (td);
1350 td = runq_steal_timeshare(&tdq->tdq_runq, cpu, tdq->tdq_ts_deq_off);
1351 if (td != NULL)
1352 return (td);
1353 return (runq_steal_idle(&tdq->tdq_runq, cpu));
1354 }
1355
1356 /*
1357 * Sets the thread lock and ts_cpu to match the requested cpu. Unlocks the
1358 * current lock and returns with the assigned queue locked.
1359 */
1360 static inline struct tdq *
sched_setcpu(struct thread * td,int cpu,int flags)1361 sched_setcpu(struct thread *td, int cpu, int flags)
1362 {
1363
1364 struct tdq *tdq;
1365 struct mtx *mtx;
1366
1367 THREAD_LOCK_ASSERT(td, MA_OWNED);
1368 tdq = TDQ_CPU(cpu);
1369 td_get_sched(td)->ts_cpu = cpu;
1370 /*
1371 * If the lock matches just return the queue.
1372 */
1373 if (td->td_lock == TDQ_LOCKPTR(tdq)) {
1374 KASSERT((flags & SRQ_HOLD) == 0,
1375 ("sched_setcpu: Invalid lock for SRQ_HOLD"));
1376 return (tdq);
1377 }
1378
1379 /*
1380 * The hard case, migration, we need to block the thread first to
1381 * prevent order reversals with other cpus locks.
1382 */
1383 spinlock_enter();
1384 mtx = thread_lock_block(td);
1385 if ((flags & SRQ_HOLD) == 0)
1386 mtx_unlock_spin(mtx);
1387 TDQ_LOCK(tdq);
1388 thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1389 spinlock_exit();
1390 return (tdq);
1391 }
1392
1393 SCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
1394 SCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
1395 SCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
1396 SCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
1397 SCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
1398 SCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
1399
1400 static int
sched_pickcpu(struct thread * td,int flags)1401 sched_pickcpu(struct thread *td, int flags)
1402 {
1403 struct cpu_group *cg, *ccg;
1404 struct td_sched *ts;
1405 struct tdq *tdq;
1406 cpuset_t *mask;
1407 int cpu, pri, r, self, intr;
1408
1409 self = PCPU_GET(cpuid);
1410 ts = td_get_sched(td);
1411 KASSERT(!CPU_ABSENT(ts->ts_cpu), ("sched_pickcpu: Start scheduler on "
1412 "absent CPU %d for thread %s.", ts->ts_cpu, td->td_name));
1413 if (smp_started == 0)
1414 return (self);
1415 /*
1416 * Don't migrate a running thread from sched_switch().
1417 */
1418 if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1419 return (ts->ts_cpu);
1420 /*
1421 * Prefer to run interrupt threads on the processors that generate
1422 * the interrupt.
1423 */
1424 if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1425 curthread->td_intr_nesting_level) {
1426 tdq = TDQ_SELF();
1427 if (tdq->tdq_lowpri >= PRI_MIN_IDLE) {
1428 SCHED_STAT_INC(pickcpu_idle_affinity);
1429 return (self);
1430 }
1431 ts->ts_cpu = self;
1432 intr = 1;
1433 cg = tdq->tdq_cg;
1434 goto llc;
1435 } else {
1436 intr = 0;
1437 tdq = TDQ_CPU(ts->ts_cpu);
1438 cg = tdq->tdq_cg;
1439 }
1440 /*
1441 * If the thread can run on the last cpu and the affinity has not
1442 * expired and it is idle, run it there.
1443 */
1444 if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
1445 atomic_load_char(&tdq->tdq_lowpri) >= PRI_MIN_IDLE &&
1446 SCHED_AFFINITY(ts, CG_SHARE_L2)) {
1447 if (cg->cg_flags & CG_FLAG_THREAD) {
1448 /* Check all SMT threads for being idle. */
1449 for (cpu = cg->cg_first; cpu <= cg->cg_last; cpu++) {
1450 pri =
1451 atomic_load_char(&TDQ_CPU(cpu)->tdq_lowpri);
1452 if (CPU_ISSET(cpu, &cg->cg_mask) &&
1453 pri < PRI_MIN_IDLE)
1454 break;
1455 }
1456 if (cpu > cg->cg_last) {
1457 SCHED_STAT_INC(pickcpu_idle_affinity);
1458 return (ts->ts_cpu);
1459 }
1460 } else {
1461 SCHED_STAT_INC(pickcpu_idle_affinity);
1462 return (ts->ts_cpu);
1463 }
1464 }
1465 llc:
1466 /*
1467 * Search for the last level cache CPU group in the tree.
1468 * Skip SMT, identical groups and caches with expired affinity.
1469 * Interrupt threads affinity is explicit and never expires.
1470 */
1471 for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
1472 if (cg->cg_flags & CG_FLAG_THREAD)
1473 continue;
1474 if (cg->cg_children == 1 || cg->cg_count == 1)
1475 continue;
1476 if (cg->cg_level == CG_SHARE_NONE ||
1477 (!intr && !SCHED_AFFINITY(ts, cg->cg_level)))
1478 continue;
1479 ccg = cg;
1480 }
1481 /* Found LLC shared by all CPUs, so do a global search. */
1482 if (ccg == cpu_top)
1483 ccg = NULL;
1484 cpu = -1;
1485 mask = &td->td_cpuset->cs_mask;
1486 pri = td->td_priority;
1487 r = TD_IS_RUNNING(td);
1488 /*
1489 * Try hard to keep interrupts within found LLC. Search the LLC for
1490 * the least loaded CPU we can run now. For NUMA systems it should
1491 * be within target domain, and it also reduces scheduling overhead.
1492 */
1493 if (ccg != NULL && intr) {
1494 cpu = sched_lowest(ccg, mask, pri, INT_MAX, ts->ts_cpu, r);
1495 if (cpu >= 0)
1496 SCHED_STAT_INC(pickcpu_intrbind);
1497 } else
1498 /* Search the LLC for the least loaded idle CPU we can run now. */
1499 if (ccg != NULL) {
1500 cpu = sched_lowest(ccg, mask, max(pri, PRI_MAX_TIMESHARE),
1501 INT_MAX, ts->ts_cpu, r);
1502 if (cpu >= 0)
1503 SCHED_STAT_INC(pickcpu_affinity);
1504 }
1505 /* Search globally for the least loaded CPU we can run now. */
1506 if (cpu < 0) {
1507 cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu, r);
1508 if (cpu >= 0)
1509 SCHED_STAT_INC(pickcpu_lowest);
1510 }
1511 /* Search globally for the least loaded CPU. */
1512 if (cpu < 0) {
1513 cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu, r);
1514 if (cpu >= 0)
1515 SCHED_STAT_INC(pickcpu_lowest);
1516 }
1517 KASSERT(cpu >= 0, ("sched_pickcpu: Failed to find a cpu."));
1518 KASSERT(!CPU_ABSENT(cpu), ("sched_pickcpu: Picked absent CPU %d.", cpu));
1519 /*
1520 * Compare the lowest loaded cpu to current cpu.
1521 */
1522 tdq = TDQ_CPU(cpu);
1523 if (THREAD_CAN_SCHED(td, self) && TDQ_SELF()->tdq_lowpri > pri &&
1524 atomic_load_char(&tdq->tdq_lowpri) < PRI_MIN_IDLE &&
1525 TDQ_LOAD(TDQ_SELF()) <= TDQ_LOAD(tdq) + 1) {
1526 SCHED_STAT_INC(pickcpu_local);
1527 cpu = self;
1528 }
1529 if (cpu != ts->ts_cpu)
1530 SCHED_STAT_INC(pickcpu_migration);
1531 return (cpu);
1532 }
1533 #endif
1534
1535 static inline struct thread *
runq_choose_realtime(struct runq * const rq)1536 runq_choose_realtime(struct runq *const rq)
1537 {
1538
1539 return (runq_first_thread_range(rq, RQ_RT_POL_MIN, RQ_RT_POL_MAX));
1540 }
1541
1542 static struct thread *
runq_choose_timeshare(struct runq * const rq,int off)1543 runq_choose_timeshare(struct runq *const rq, int off)
1544 {
1545 struct thread *td;
1546
1547 MPASS(0 <= off && off < RQ_TS_POL_MODULO);
1548
1549 td = runq_first_thread_range(rq, RQ_TS_POL_MIN + off, RQ_TS_POL_MAX);
1550 if (td != NULL || off == 0)
1551 return (td);
1552
1553 td = runq_first_thread_range(rq, RQ_TS_POL_MIN, RQ_TS_POL_MIN + off - 1);
1554 return (td);
1555 }
1556
1557 static inline struct thread *
runq_choose_idle(struct runq * const rq)1558 runq_choose_idle(struct runq *const rq)
1559 {
1560
1561 return (runq_first_thread_range(rq, RQ_ID_POL_MIN, RQ_ID_POL_MAX));
1562 }
1563
1564 /*
1565 * Pick the highest priority task we have and return it.
1566 */
1567 static struct thread *
tdq_choose(struct tdq * tdq)1568 tdq_choose(struct tdq *tdq)
1569 {
1570 struct thread *td;
1571
1572 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1573 td = runq_choose_realtime(&tdq->tdq_runq);
1574 if (td != NULL)
1575 return (td);
1576 td = runq_choose_timeshare(&tdq->tdq_runq, tdq->tdq_ts_deq_off);
1577 if (td != NULL) {
1578 KASSERT(td->td_priority >= PRI_MIN_BATCH,
1579 ("tdq_choose: Invalid priority on timeshare queue %d",
1580 td->td_priority));
1581 return (td);
1582 }
1583 td = runq_choose_idle(&tdq->tdq_runq);
1584 if (td != NULL) {
1585 KASSERT(td->td_priority >= PRI_MIN_IDLE,
1586 ("tdq_choose: Invalid priority on idle queue %d",
1587 td->td_priority));
1588 return (td);
1589 }
1590
1591 return (NULL);
1592 }
1593
1594 /*
1595 * Initialize a thread queue.
1596 */
1597 static void
tdq_setup(struct tdq * tdq,int id)1598 tdq_setup(struct tdq *tdq, int id)
1599 {
1600
1601 if (bootverbose)
1602 printf("ULE: setup cpu %d\n", id);
1603 runq_init(&tdq->tdq_runq);
1604 tdq->tdq_id = id;
1605 snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1606 "sched lock %d", (int)TDQ_ID(tdq));
1607 mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock", MTX_SPIN);
1608 #ifdef KTR
1609 snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
1610 "CPU %d load", (int)TDQ_ID(tdq));
1611 #endif
1612 }
1613
1614 #ifdef SMP
1615 static void
sched_setup_smp(void)1616 sched_setup_smp(void)
1617 {
1618 struct tdq *tdq;
1619 int i;
1620
1621 cpu_top = smp_topo();
1622 CPU_FOREACH(i) {
1623 tdq = DPCPU_ID_PTR(i, tdq);
1624 tdq_setup(tdq, i);
1625 tdq->tdq_cg = smp_topo_find(cpu_top, i);
1626 if (tdq->tdq_cg == NULL)
1627 panic("Can't find cpu group for %d\n", i);
1628 DPCPU_ID_SET(i, randomval, i * 69069 + 5);
1629 }
1630 PCPU_SET(sched, DPCPU_PTR(tdq));
1631 balance_tdq = TDQ_SELF();
1632 }
1633 #endif
1634
1635 /*
1636 * Setup the thread queues and initialize the topology based on MD
1637 * information.
1638 */
1639 static void
sched_setup(void * dummy)1640 sched_setup(void *dummy)
1641 {
1642 struct tdq *tdq;
1643
1644 #ifdef SMP
1645 sched_setup_smp();
1646 #else
1647 tdq_setup(TDQ_SELF(), 0);
1648 #endif
1649 tdq = TDQ_SELF();
1650
1651 /* Add thread0's load since it's running. */
1652 TDQ_LOCK(tdq);
1653 thread0.td_lock = TDQ_LOCKPTR(tdq);
1654 tdq_load_add(tdq, &thread0);
1655 tdq->tdq_curthread = &thread0;
1656 tdq->tdq_lowpri = thread0.td_priority;
1657 TDQ_UNLOCK(tdq);
1658 }
1659
1660 /*
1661 * This routine determines time constants after stathz and hz are setup.
1662 */
1663 /* ARGSUSED */
1664 static void
sched_initticks(void * dummy)1665 sched_initticks(void *dummy)
1666 {
1667 int incr;
1668
1669 realstathz = stathz ? stathz : hz;
1670 sched_slice = realstathz / SCHED_SLICE_DEFAULT_DIVISOR;
1671 sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
1672 hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
1673 realstathz);
1674
1675 /*
1676 * tickincr is shifted out by 10 to avoid rounding errors due to
1677 * hz not being evenly divisible by stathz on all platforms.
1678 */
1679 incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1680 /*
1681 * This does not work for values of stathz that are more than
1682 * 1 << SCHED_TICK_SHIFT * hz. In practice this does not happen.
1683 */
1684 if (incr == 0)
1685 incr = 1;
1686 tickincr = incr;
1687 #ifdef SMP
1688 /*
1689 * Set the default balance interval now that we know
1690 * what realstathz is.
1691 */
1692 balance_interval = realstathz;
1693 balance_ticks = balance_interval;
1694 affinity = SCHED_AFFINITY_DEFAULT;
1695 #endif
1696 if (sched_idlespinthresh < 0)
1697 sched_idlespinthresh = 2 * max(10000, 6 * hz) / realstathz;
1698 }
1699
1700 /*
1701 * This is the core of the interactivity algorithm. Determines a score based
1702 * on past behavior. It is the ratio of sleep time to run time scaled to
1703 * a [0, 100] integer. This is the voluntary sleep time of a process, which
1704 * differs from the cpu usage because it does not account for time spent
1705 * waiting on a run-queue. Would be prettier if we had floating point.
1706 *
1707 * When a thread's sleep time is greater than its run time the
1708 * calculation is:
1709 *
1710 * scaling factor
1711 * interactivity score = ---------------------
1712 * sleep time / run time
1713 *
1714 *
1715 * When a thread's run time is greater than its sleep time the
1716 * calculation is:
1717 *
1718 * scaling factor
1719 * interactivity score = 2 * scaling factor - ---------------------
1720 * run time / sleep time
1721 */
1722 static int
sched_interact_score(struct thread * td)1723 sched_interact_score(struct thread *td)
1724 {
1725 struct td_sched *ts;
1726 int div;
1727
1728 ts = td_get_sched(td);
1729 /*
1730 * The score is only needed if this is likely to be an interactive
1731 * task. Don't go through the expense of computing it if there's
1732 * no chance.
1733 */
1734 if (sched_interact <= SCHED_INTERACT_HALF &&
1735 ts->ts_runtime >= ts->ts_slptime)
1736 return (SCHED_INTERACT_HALF);
1737
1738 if (ts->ts_runtime > ts->ts_slptime) {
1739 div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1740 return (SCHED_INTERACT_HALF +
1741 (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1742 }
1743 if (ts->ts_slptime > ts->ts_runtime) {
1744 div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1745 return (ts->ts_runtime / div);
1746 }
1747 /* runtime == slptime */
1748 if (ts->ts_runtime)
1749 return (SCHED_INTERACT_HALF);
1750
1751 /*
1752 * This can happen if slptime and runtime are 0.
1753 */
1754 return (0);
1755
1756 }
1757
1758 /*
1759 * Scale the scheduling priority according to the "interactivity" of this
1760 * process.
1761 */
1762 static void
sched_priority(struct thread * td)1763 sched_priority(struct thread *td)
1764 {
1765 u_int pri, score;
1766 int nice;
1767
1768 if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
1769 return;
1770
1771 nice = td->td_proc->p_nice;
1772 /*
1773 * If the score is interactive we place the thread in the realtime
1774 * queue with a priority that is less than kernel and interrupt
1775 * priorities. These threads are not subject to nice restrictions.
1776 *
1777 * Scores greater than this are placed on the normal timeshare queue
1778 * where the priority is partially decided by the most recent cpu
1779 * utilization and the rest is decided by nice value.
1780 *
1781 * The nice value of the process has a linear effect on the calculated
1782 * score. Negative nice values make it easier for a thread to be
1783 * considered interactive.
1784 */
1785 score = imax(0, sched_interact_score(td) + nice);
1786 if (score < sched_interact) {
1787 pri = PRI_MIN_INTERACT;
1788 pri += (PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) * score /
1789 sched_interact;
1790 KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
1791 ("sched_priority: invalid interactive priority %u score %u",
1792 pri, score));
1793 } else {
1794 const struct td_sched *const ts = td_get_sched(td);
1795 const u_int run = SCHED_TICK_RUN_SHIFTED(ts);
1796 const u_int run_unshifted __unused = (run +
1797 (1 << SCHED_TICK_SHIFT) / 2) >> SCHED_TICK_SHIFT;
1798 const u_int len = SCHED_TICK_LENGTH(ts);
1799 const u_int nice_pri_off = SCHED_PRI_NICE(nice);
1800 const u_int cpu_pri_off = (((SCHED_PRI_CPU_RANGE - 1) *
1801 run + len / 2) / len + (1 << SCHED_TICK_SHIFT) / 2) >>
1802 SCHED_TICK_SHIFT;
1803
1804 MPASS(cpu_pri_off < SCHED_PRI_CPU_RANGE);
1805 pri = PRI_MIN_BATCH + cpu_pri_off + nice_pri_off;
1806 KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
1807 ("sched_priority: Invalid computed priority %u: "
1808 "Should be between %u and %u (PRI_MIN_BATCH: %u; "
1809 "Window size (ticks): %u, runtime (shifted ticks): %u,"
1810 "(unshifted ticks): %u => CPU pri off: %u; "
1811 "Nice: %d => nice pri off: %u)",
1812 pri, PRI_MIN_BATCH, PRI_MAX_BATCH, PRI_MIN_BATCH,
1813 len, run, run_unshifted, cpu_pri_off, nice, nice_pri_off));
1814 }
1815 sched_user_prio(td, pri);
1816
1817 return;
1818 }
1819
1820 /*
1821 * This routine enforces a maximum limit on the amount of scheduling history
1822 * kept. It is called after either the slptime or runtime is adjusted. This
1823 * function is ugly due to integer math.
1824 */
1825 static void
sched_interact_update(struct thread * td)1826 sched_interact_update(struct thread *td)
1827 {
1828 struct td_sched *ts;
1829 u_int sum;
1830
1831 ts = td_get_sched(td);
1832 sum = ts->ts_runtime + ts->ts_slptime;
1833 if (sum < SCHED_SLP_RUN_MAX)
1834 return;
1835 /*
1836 * This only happens from two places:
1837 * 1) We have added an unusual amount of run time from fork_exit.
1838 * 2) We have added an unusual amount of sleep time from sched_sleep().
1839 */
1840 if (sum > SCHED_SLP_RUN_MAX * 2) {
1841 if (ts->ts_runtime > ts->ts_slptime) {
1842 ts->ts_runtime = SCHED_SLP_RUN_MAX;
1843 ts->ts_slptime = 1;
1844 } else {
1845 ts->ts_slptime = SCHED_SLP_RUN_MAX;
1846 ts->ts_runtime = 1;
1847 }
1848 return;
1849 }
1850 /*
1851 * If we have exceeded by more than 1/5th then the algorithm below
1852 * will not bring us back into range. Dividing by two here forces
1853 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1854 */
1855 if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1856 ts->ts_runtime /= 2;
1857 ts->ts_slptime /= 2;
1858 return;
1859 }
1860 ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1861 ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1862 }
1863
1864 /*
1865 * Scale back the interactivity history when a child thread is created. The
1866 * history is inherited from the parent but the thread may behave totally
1867 * differently. For example, a shell spawning a compiler process. We want
1868 * to learn that the compiler is behaving badly very quickly.
1869 */
1870 static void
sched_interact_fork(struct thread * td)1871 sched_interact_fork(struct thread *td)
1872 {
1873 struct td_sched *ts;
1874 int ratio;
1875 int sum;
1876
1877 ts = td_get_sched(td);
1878 sum = ts->ts_runtime + ts->ts_slptime;
1879 if (sum > SCHED_SLP_RUN_FORK) {
1880 ratio = sum / SCHED_SLP_RUN_FORK;
1881 ts->ts_runtime /= ratio;
1882 ts->ts_slptime /= ratio;
1883 }
1884 }
1885
1886 /*
1887 * Called from proc0_init() to setup the scheduler fields.
1888 */
1889 void
schedinit(void)1890 schedinit(void)
1891 {
1892 struct td_sched *ts0;
1893
1894 /*
1895 * Set up the scheduler specific parts of thread0.
1896 */
1897 ts0 = td_get_sched(&thread0);
1898 ts0->ts_ftick = (u_int)ticks;
1899 ts0->ts_ltick = ts0->ts_ftick;
1900 ts0->ts_slice = 0;
1901 ts0->ts_cpu = curcpu; /* set valid CPU number */
1902 }
1903
1904 /*
1905 * schedinit_ap() is needed prior to calling sched_throw(NULL) to ensure that
1906 * the pcpu requirements are met for any calls in the period between curthread
1907 * initialization and sched_throw(). One can safely add threads to the queue
1908 * before sched_throw(), for instance, as long as the thread lock is setup
1909 * correctly.
1910 *
1911 * TDQ_SELF() relies on the below sched pcpu setting; it may be used only
1912 * after schedinit_ap().
1913 */
1914 void
schedinit_ap(void)1915 schedinit_ap(void)
1916 {
1917
1918 #ifdef SMP
1919 PCPU_SET(sched, DPCPU_PTR(tdq));
1920 #endif
1921 PCPU_GET(idlethread)->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1922 }
1923
1924 /*
1925 * This is only somewhat accurate since given many processes of the same
1926 * priority they will switch when their slices run out, which will be
1927 * at most sched_slice stathz ticks.
1928 */
1929 int
sched_rr_interval(void)1930 sched_rr_interval(void)
1931 {
1932
1933 /* Convert sched_slice from stathz to hz. */
1934 return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
1935 }
1936
1937 /*
1938 * Update the percent cpu tracking information when it is requested or the total
1939 * history exceeds the maximum. We keep a sliding history of tick counts that
1940 * slowly decays, for running threads (see comments below for more details).
1941 * This is less precise than the 4BSD mechanism since it happens with less
1942 * regular and frequent events.
1943 */
1944 static void
sched_pctcpu_update(struct td_sched * ts,int run)1945 sched_pctcpu_update(struct td_sched *ts, int run)
1946 {
1947 const u_int t = (u_int)ticks;
1948 u_int t_max = SCHED_TICK_MAX((u_int)hz);
1949 u_int t_tgt = ((t_max << SCHED_TICK_SHIFT) * SCHED_CPU_DECAY_NUMER /
1950 SCHED_CPU_DECAY_DENOM) >> SCHED_TICK_SHIFT;
1951 const u_int lu_span = t - ts->ts_ltick;
1952
1953 if (lu_span >= t_tgt) {
1954 /*
1955 * Forget all previous ticks if we are more than t_tgt
1956 * (currently, 10s) apart from the last update. Don't account
1957 * for more than 't_tgt' ticks when running.
1958 */
1959 ts->ts_ticks = run ? (t_tgt << SCHED_TICK_SHIFT) : 0;
1960 ts->ts_ftick = t - t_tgt;
1961 ts->ts_ltick = t;
1962 return;
1963 }
1964
1965 if (t - ts->ts_ftick >= t_max) {
1966 /*
1967 * First reduce the existing ticks to proportionally occupy only
1968 * what's left of the target window given 'lu_span' will occupy
1969 * the rest. Since sched_clock() is called frequently on
1970 * running threads, these threads have a small 'lu_span', and
1971 * the next formula basically becomes an exponential decay with
1972 * ratio r = SCHED_CPU_DECAY_NUMER / SCHED_CPU_DECAY_DENOM
1973 * (currently, 10/11) and period 1s. However, a sleeping thread
1974 * will see its accounted ticks drop linearly with a high slope
1975 * with respect to 'lu_span', approaching 0 as 'lu_span'
1976 * approaches 't_tgt' (so, continuously with respect to the
1977 * previous case). This rescaling is completely dependent on
1978 * the frequency of calls and the span since last update passed
1979 * at each call.
1980 */
1981 ts->ts_ticks = SCHED_TICK_RUN_SHIFTED(ts) /
1982 SCHED_TICK_LENGTH(ts) * (t_tgt - lu_span);
1983 ts->ts_ftick = t - t_tgt;
1984 }
1985
1986 if (run)
1987 ts->ts_ticks += lu_span << SCHED_TICK_SHIFT;
1988 ts->ts_ltick = t;
1989 }
1990
1991 /*
1992 * Adjust the priority of a thread. Move it to the appropriate run-queue
1993 * if necessary. This is the back-end for several priority related
1994 * functions.
1995 */
1996 static void
sched_thread_priority(struct thread * td,u_char prio)1997 sched_thread_priority(struct thread *td, u_char prio)
1998 {
1999 struct tdq *tdq;
2000 int oldpri;
2001
2002 KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
2003 "prio:%d", td->td_priority, "new prio:%d", prio,
2004 KTR_ATTR_LINKED, sched_tdname(curthread));
2005 SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
2006 if (td != curthread && prio < td->td_priority) {
2007 KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
2008 "lend prio", "prio:%d", td->td_priority, "new prio:%d",
2009 prio, KTR_ATTR_LINKED, sched_tdname(td));
2010 SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
2011 curthread);
2012 }
2013 THREAD_LOCK_ASSERT(td, MA_OWNED);
2014 if (td->td_priority == prio)
2015 return;
2016 /*
2017 * If the priority has been elevated due to priority
2018 * propagation, we may have to move ourselves to a new
2019 * queue. This could be optimized to not re-add in some
2020 * cases.
2021 */
2022 if (TD_ON_RUNQ(td) && prio < td->td_priority) {
2023 sched_rem(td);
2024 td->td_priority = prio;
2025 sched_add(td, SRQ_BORROWING | SRQ_HOLDTD);
2026 return;
2027 }
2028 /*
2029 * If the thread is currently running we may have to adjust the lowpri
2030 * information so other cpus are aware of our current priority.
2031 */
2032 if (TD_IS_RUNNING(td)) {
2033 tdq = TDQ_CPU(td_get_sched(td)->ts_cpu);
2034 oldpri = td->td_priority;
2035 td->td_priority = prio;
2036 if (prio < tdq->tdq_lowpri)
2037 tdq->tdq_lowpri = prio;
2038 else if (tdq->tdq_lowpri == oldpri)
2039 tdq_setlowpri(tdq, td);
2040 return;
2041 }
2042 td->td_priority = prio;
2043 }
2044
2045 /*
2046 * Update a thread's priority when it is lent another thread's
2047 * priority.
2048 */
2049 void
sched_lend_prio(struct thread * td,u_char prio)2050 sched_lend_prio(struct thread *td, u_char prio)
2051 {
2052
2053 td->td_flags |= TDF_BORROWING;
2054 sched_thread_priority(td, prio);
2055 }
2056
2057 /*
2058 * Restore a thread's priority when priority propagation is
2059 * over. The prio argument is the minimum priority the thread
2060 * needs to have to satisfy other possible priority lending
2061 * requests. If the thread's regular priority is less
2062 * important than prio, the thread will keep a priority boost
2063 * of prio.
2064 */
2065 void
sched_unlend_prio(struct thread * td,u_char prio)2066 sched_unlend_prio(struct thread *td, u_char prio)
2067 {
2068 u_char base_pri;
2069
2070 if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
2071 td->td_base_pri <= PRI_MAX_TIMESHARE)
2072 base_pri = td->td_user_pri;
2073 else
2074 base_pri = td->td_base_pri;
2075 if (prio >= base_pri) {
2076 td->td_flags &= ~TDF_BORROWING;
2077 sched_thread_priority(td, base_pri);
2078 } else
2079 sched_lend_prio(td, prio);
2080 }
2081
2082 /*
2083 * Standard entry for setting the priority to an absolute value.
2084 */
2085 void
sched_prio(struct thread * td,u_char prio)2086 sched_prio(struct thread *td, u_char prio)
2087 {
2088 u_char oldprio;
2089
2090 /* First, update the base priority. */
2091 td->td_base_pri = prio;
2092
2093 /*
2094 * If the thread is borrowing another thread's priority, don't
2095 * ever lower the priority.
2096 */
2097 if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
2098 return;
2099
2100 /* Change the real priority. */
2101 oldprio = td->td_priority;
2102 sched_thread_priority(td, prio);
2103
2104 /*
2105 * If the thread is on a turnstile, then let the turnstile update
2106 * its state.
2107 */
2108 if (TD_ON_LOCK(td) && oldprio != prio)
2109 turnstile_adjust(td, oldprio);
2110 }
2111
2112 /*
2113 * Set the base interrupt thread priority.
2114 */
2115 void
sched_ithread_prio(struct thread * td,u_char prio)2116 sched_ithread_prio(struct thread *td, u_char prio)
2117 {
2118 THREAD_LOCK_ASSERT(td, MA_OWNED);
2119 MPASS(td->td_pri_class == PRI_ITHD);
2120 td->td_base_ithread_pri = prio;
2121 sched_prio(td, prio);
2122 }
2123
2124 /*
2125 * Set the base user priority, does not effect current running priority.
2126 */
2127 void
sched_user_prio(struct thread * td,u_char prio)2128 sched_user_prio(struct thread *td, u_char prio)
2129 {
2130
2131 td->td_base_user_pri = prio;
2132 if (td->td_lend_user_pri <= prio)
2133 return;
2134 td->td_user_pri = prio;
2135 }
2136
2137 void
sched_lend_user_prio(struct thread * td,u_char prio)2138 sched_lend_user_prio(struct thread *td, u_char prio)
2139 {
2140
2141 THREAD_LOCK_ASSERT(td, MA_OWNED);
2142 td->td_lend_user_pri = prio;
2143 td->td_user_pri = min(prio, td->td_base_user_pri);
2144 if (td->td_priority > td->td_user_pri)
2145 sched_prio(td, td->td_user_pri);
2146 else if (td->td_priority != td->td_user_pri)
2147 ast_sched_locked(td, TDA_SCHED);
2148 }
2149
2150 /*
2151 * Like the above but first check if there is anything to do.
2152 */
2153 void
sched_lend_user_prio_cond(struct thread * td,u_char prio)2154 sched_lend_user_prio_cond(struct thread *td, u_char prio)
2155 {
2156
2157 if (td->td_lend_user_pri == prio)
2158 return;
2159
2160 thread_lock(td);
2161 sched_lend_user_prio(td, prio);
2162 thread_unlock(td);
2163 }
2164
2165 #ifdef SMP
2166 /*
2167 * This tdq is about to idle. Try to steal a thread from another CPU before
2168 * choosing the idle thread.
2169 */
2170 static void
tdq_trysteal(struct tdq * tdq)2171 tdq_trysteal(struct tdq *tdq)
2172 {
2173 struct cpu_group *cg, *parent;
2174 struct tdq *steal;
2175 cpuset_t mask;
2176 int cpu, i, goup;
2177
2178 if (smp_started == 0 || steal_idle == 0 || trysteal_limit == 0 ||
2179 tdq->tdq_cg == NULL)
2180 return;
2181 CPU_FILL(&mask);
2182 CPU_CLR(PCPU_GET(cpuid), &mask);
2183 /* We don't want to be preempted while we're iterating. */
2184 spinlock_enter();
2185 TDQ_UNLOCK(tdq);
2186 for (i = 1, cg = tdq->tdq_cg, goup = 0; ; ) {
2187 cpu = sched_highest(cg, &mask, steal_thresh, 1);
2188 /*
2189 * If a thread was added while interrupts were disabled don't
2190 * steal one here.
2191 */
2192 if (TDQ_LOAD(tdq) > 0) {
2193 TDQ_LOCK(tdq);
2194 break;
2195 }
2196
2197 /*
2198 * We found no CPU to steal from in this group. Escalate to
2199 * the parent and repeat. But if parent has only two children
2200 * groups we can avoid searching this group again by searching
2201 * the other one specifically and then escalating two levels.
2202 */
2203 if (cpu == -1) {
2204 if (goup) {
2205 cg = cg->cg_parent;
2206 goup = 0;
2207 }
2208 if (++i > trysteal_limit) {
2209 TDQ_LOCK(tdq);
2210 break;
2211 }
2212 parent = cg->cg_parent;
2213 if (parent == NULL) {
2214 TDQ_LOCK(tdq);
2215 break;
2216 }
2217 if (parent->cg_children == 2) {
2218 if (cg == &parent->cg_child[0])
2219 cg = &parent->cg_child[1];
2220 else
2221 cg = &parent->cg_child[0];
2222 goup = 1;
2223 } else
2224 cg = parent;
2225 continue;
2226 }
2227 steal = TDQ_CPU(cpu);
2228 /*
2229 * The data returned by sched_highest() is stale and
2230 * the chosen CPU no longer has an eligible thread.
2231 * At this point unconditionally exit the loop to bound
2232 * the time spent in the critcal section.
2233 */
2234 if (TDQ_LOAD(steal) < steal_thresh ||
2235 TDQ_TRANSFERABLE(steal) == 0)
2236 continue;
2237 /*
2238 * Try to lock both queues. If we are assigned a thread while
2239 * waited for the lock, switch to it now instead of stealing.
2240 * If we can't get the lock, then somebody likely got there
2241 * first.
2242 */
2243 TDQ_LOCK(tdq);
2244 if (tdq->tdq_load > 0)
2245 break;
2246 if (TDQ_TRYLOCK_FLAGS(steal, MTX_DUPOK) == 0)
2247 break;
2248 /*
2249 * The data returned by sched_highest() is stale and
2250 * the chosen CPU no longer has an eligible thread.
2251 */
2252 if (TDQ_LOAD(steal) < steal_thresh ||
2253 TDQ_TRANSFERABLE(steal) == 0) {
2254 TDQ_UNLOCK(steal);
2255 break;
2256 }
2257 /*
2258 * If we fail to acquire one due to affinity restrictions,
2259 * bail out and let the idle thread to a more complete search
2260 * outside of a critical section.
2261 */
2262 if (tdq_move(steal, tdq) == -1) {
2263 TDQ_UNLOCK(steal);
2264 break;
2265 }
2266 TDQ_UNLOCK(steal);
2267 break;
2268 }
2269 spinlock_exit();
2270 }
2271 #endif
2272
2273 /*
2274 * Handle migration from sched_switch(). This happens only for
2275 * cpu binding.
2276 */
2277 static struct mtx *
sched_switch_migrate(struct tdq * tdq,struct thread * td,int flags)2278 sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
2279 {
2280 struct tdq *tdn;
2281 #ifdef SMP
2282 int lowpri;
2283 #endif
2284
2285 KASSERT(THREAD_CAN_MIGRATE(td) ||
2286 (td_get_sched(td)->ts_flags & TSF_BOUND) != 0,
2287 ("Thread %p shouldn't migrate", td));
2288 KASSERT(!CPU_ABSENT(td_get_sched(td)->ts_cpu), ("sched_switch_migrate: "
2289 "thread %s queued on absent CPU %d.", td->td_name,
2290 td_get_sched(td)->ts_cpu));
2291 tdn = TDQ_CPU(td_get_sched(td)->ts_cpu);
2292 #ifdef SMP
2293 tdq_load_rem(tdq, td);
2294 /*
2295 * Do the lock dance required to avoid LOR. We have an
2296 * extra spinlock nesting from sched_switch() which will
2297 * prevent preemption while we're holding neither run-queue lock.
2298 */
2299 TDQ_UNLOCK(tdq);
2300 TDQ_LOCK(tdn);
2301 lowpri = tdq_add(tdn, td, flags);
2302 tdq_notify(tdn, lowpri);
2303 TDQ_UNLOCK(tdn);
2304 TDQ_LOCK(tdq);
2305 #endif
2306 return (TDQ_LOCKPTR(tdn));
2307 }
2308
2309 /*
2310 * thread_lock_unblock() that does not assume td_lock is blocked.
2311 */
2312 static inline void
thread_unblock_switch(struct thread * td,struct mtx * mtx)2313 thread_unblock_switch(struct thread *td, struct mtx *mtx)
2314 {
2315 atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
2316 (uintptr_t)mtx);
2317 }
2318
2319 /*
2320 * Switch threads. This function has to handle threads coming in while
2321 * blocked for some reason, running, or idle. It also must deal with
2322 * migrating a thread from one queue to another as running threads may
2323 * be assigned elsewhere via binding.
2324 */
2325 void
sched_switch(struct thread * td,int flags)2326 sched_switch(struct thread *td, int flags)
2327 {
2328 struct thread *newtd;
2329 struct tdq *tdq;
2330 struct td_sched *ts;
2331 struct mtx *mtx;
2332 int srqflag;
2333 int cpuid, preempted;
2334 #ifdef SMP
2335 int pickcpu;
2336 #endif
2337
2338 THREAD_LOCK_ASSERT(td, MA_OWNED);
2339
2340 cpuid = PCPU_GET(cpuid);
2341 tdq = TDQ_SELF();
2342 ts = td_get_sched(td);
2343 sched_pctcpu_update(ts, 1);
2344 #ifdef SMP
2345 pickcpu = (td->td_flags & TDF_PICKCPU) != 0;
2346 if (pickcpu)
2347 ts->ts_rltick = (u_int)ticks - affinity * MAX_CACHE_LEVELS;
2348 else
2349 ts->ts_rltick = (u_int)ticks;
2350 #endif
2351 td->td_lastcpu = td->td_oncpu;
2352 preempted = (td->td_flags & TDF_SLICEEND) == 0 &&
2353 (flags & SW_PREEMPT) != 0;
2354 td->td_flags &= ~(TDF_PICKCPU | TDF_SLICEEND);
2355 ast_unsched_locked(td, TDA_SCHED);
2356 td->td_owepreempt = 0;
2357 atomic_store_char(&tdq->tdq_owepreempt, 0);
2358 if (!TD_IS_IDLETHREAD(td))
2359 TDQ_SWITCHCNT_INC(tdq);
2360
2361 /*
2362 * Always block the thread lock so we can drop the tdq lock early.
2363 */
2364 mtx = thread_lock_block(td);
2365 spinlock_enter();
2366 if (TD_IS_IDLETHREAD(td)) {
2367 MPASS(mtx == TDQ_LOCKPTR(tdq));
2368 TD_SET_CAN_RUN(td);
2369 } else if (TD_IS_RUNNING(td)) {
2370 MPASS(mtx == TDQ_LOCKPTR(tdq));
2371 srqflag = SRQ_OURSELF | SRQ_YIELDING |
2372 (preempted ? SRQ_PREEMPTED : 0);
2373 #ifdef SMP
2374 if (THREAD_CAN_MIGRATE(td) && (!THREAD_CAN_SCHED(td, ts->ts_cpu)
2375 || pickcpu))
2376 ts->ts_cpu = sched_pickcpu(td, 0);
2377 #endif
2378 if (ts->ts_cpu == cpuid)
2379 tdq_runq_add(tdq, td, srqflag);
2380 else
2381 mtx = sched_switch_migrate(tdq, td, srqflag);
2382 } else {
2383 /* This thread must be going to sleep. */
2384 if (mtx != TDQ_LOCKPTR(tdq)) {
2385 mtx_unlock_spin(mtx);
2386 TDQ_LOCK(tdq);
2387 }
2388 tdq_load_rem(tdq, td);
2389 #ifdef SMP
2390 if (tdq->tdq_load == 0)
2391 tdq_trysteal(tdq);
2392 #endif
2393 }
2394
2395 #if (KTR_COMPILE & KTR_SCHED) != 0
2396 if (TD_IS_IDLETHREAD(td))
2397 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle",
2398 "prio:%d", td->td_priority);
2399 else
2400 KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td),
2401 "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg,
2402 "lockname:\"%s\"", td->td_lockname);
2403 #endif
2404
2405 /*
2406 * We enter here with the thread blocked and assigned to the
2407 * appropriate cpu run-queue or sleep-queue and with the current
2408 * thread-queue locked.
2409 */
2410 TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2411 MPASS(td == tdq->tdq_curthread);
2412 newtd = choosethread();
2413 sched_pctcpu_update(td_get_sched(newtd), 0);
2414 TDQ_UNLOCK(tdq);
2415
2416 /*
2417 * Call the MD code to switch contexts if necessary.
2418 */
2419 if (td != newtd) {
2420 #ifdef HWPMC_HOOKS
2421 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
2422 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
2423 #endif
2424 SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
2425
2426 #ifdef KDTRACE_HOOKS
2427 /*
2428 * If DTrace has set the active vtime enum to anything
2429 * other than INACTIVE (0), then it should have set the
2430 * function to call.
2431 */
2432 if (dtrace_vtime_active)
2433 (*dtrace_vtime_switch_func)(newtd);
2434 #endif
2435 td->td_oncpu = NOCPU;
2436 cpu_switch(td, newtd, mtx);
2437 cpuid = td->td_oncpu = PCPU_GET(cpuid);
2438
2439 SDT_PROBE0(sched, , , on__cpu);
2440 #ifdef HWPMC_HOOKS
2441 if (PMC_PROC_IS_USING_PMCS(td->td_proc))
2442 PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
2443 #endif
2444 } else {
2445 thread_unblock_switch(td, mtx);
2446 SDT_PROBE0(sched, , , remain__cpu);
2447 }
2448 KASSERT(curthread->td_md.md_spinlock_count == 1,
2449 ("invalid count %d", curthread->td_md.md_spinlock_count));
2450
2451 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
2452 "prio:%d", td->td_priority);
2453 }
2454
2455 /*
2456 * Adjust thread priorities as a result of a nice request.
2457 */
2458 void
sched_nice(struct proc * p,int nice)2459 sched_nice(struct proc *p, int nice)
2460 {
2461 struct thread *td;
2462
2463 PROC_LOCK_ASSERT(p, MA_OWNED);
2464
2465 p->p_nice = nice;
2466 FOREACH_THREAD_IN_PROC(p, td) {
2467 thread_lock(td);
2468 sched_priority(td);
2469 sched_prio(td, td->td_base_user_pri);
2470 thread_unlock(td);
2471 }
2472 }
2473
2474 /*
2475 * Record the sleep time for the interactivity scorer.
2476 */
2477 void
sched_sleep(struct thread * td,int prio)2478 sched_sleep(struct thread *td, int prio)
2479 {
2480
2481 THREAD_LOCK_ASSERT(td, MA_OWNED);
2482
2483 td->td_slptick = ticks;
2484 if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
2485 return;
2486 if (static_boost == 1 && prio)
2487 sched_prio(td, prio);
2488 else if (static_boost && td->td_priority > static_boost)
2489 sched_prio(td, static_boost);
2490 }
2491
2492 /*
2493 * Schedule a thread to resume execution and record how long it voluntarily
2494 * slept. We also update the pctcpu, interactivity, and priority.
2495 *
2496 * Requires the thread lock on entry, drops on exit.
2497 */
2498 void
sched_wakeup(struct thread * td,int srqflags)2499 sched_wakeup(struct thread *td, int srqflags)
2500 {
2501 struct td_sched *ts;
2502 int slptick;
2503
2504 THREAD_LOCK_ASSERT(td, MA_OWNED);
2505 ts = td_get_sched(td);
2506
2507 /*
2508 * If we slept for more than a tick update our interactivity and
2509 * priority.
2510 */
2511 slptick = td->td_slptick;
2512 td->td_slptick = 0;
2513 if (slptick && slptick != ticks) {
2514 ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
2515 sched_interact_update(td);
2516 sched_pctcpu_update(ts, 0);
2517 }
2518
2519 /*
2520 * When resuming an idle ithread, restore its base ithread
2521 * priority.
2522 */
2523 if (PRI_BASE(td->td_pri_class) == PRI_ITHD &&
2524 td->td_priority != td->td_base_ithread_pri)
2525 sched_prio(td, td->td_base_ithread_pri);
2526
2527 /*
2528 * Reset the slice value since we slept and advanced the round-robin.
2529 */
2530 ts->ts_slice = 0;
2531 sched_add(td, SRQ_BORING | srqflags);
2532 }
2533
2534 /*
2535 * Penalize the parent for creating a new child and initialize the child's
2536 * priority.
2537 */
2538 void
sched_fork(struct thread * td,struct thread * child)2539 sched_fork(struct thread *td, struct thread *child)
2540 {
2541 THREAD_LOCK_ASSERT(td, MA_OWNED);
2542 sched_pctcpu_update(td_get_sched(td), 1);
2543 sched_fork_thread(td, child);
2544 /*
2545 * Penalize the parent and child for forking.
2546 */
2547 sched_interact_fork(child);
2548 sched_priority(child);
2549 td_get_sched(td)->ts_runtime += tickincr;
2550 sched_interact_update(td);
2551 sched_priority(td);
2552 }
2553
2554 /*
2555 * Fork a new thread, may be within the same process.
2556 */
2557 void
sched_fork_thread(struct thread * td,struct thread * child)2558 sched_fork_thread(struct thread *td, struct thread *child)
2559 {
2560 struct td_sched *ts;
2561 struct td_sched *ts2;
2562 struct tdq *tdq;
2563
2564 tdq = TDQ_SELF();
2565 THREAD_LOCK_ASSERT(td, MA_OWNED);
2566 /*
2567 * Initialize child.
2568 */
2569 ts = td_get_sched(td);
2570 ts2 = td_get_sched(child);
2571 child->td_oncpu = NOCPU;
2572 child->td_lastcpu = NOCPU;
2573 child->td_lock = TDQ_LOCKPTR(tdq);
2574 child->td_cpuset = cpuset_ref(td->td_cpuset);
2575 child->td_domain.dr_policy = td->td_cpuset->cs_domain;
2576 ts2->ts_cpu = ts->ts_cpu;
2577 ts2->ts_flags = 0;
2578 /*
2579 * Grab our parents cpu estimation information.
2580 */
2581 ts2->ts_ticks = ts->ts_ticks;
2582 ts2->ts_ltick = ts->ts_ltick;
2583 ts2->ts_ftick = ts->ts_ftick;
2584 /*
2585 * Do not inherit any borrowed priority from the parent.
2586 */
2587 child->td_priority = child->td_base_pri;
2588 /*
2589 * And update interactivity score.
2590 */
2591 ts2->ts_slptime = ts->ts_slptime;
2592 ts2->ts_runtime = ts->ts_runtime;
2593 /* Attempt to quickly learn interactivity. */
2594 ts2->ts_slice = tdq_slice(tdq) - sched_slice_min;
2595 #ifdef KTR
2596 bzero(ts2->ts_name, sizeof(ts2->ts_name));
2597 #endif
2598 }
2599
2600 /*
2601 * Adjust the priority class of a thread.
2602 */
2603 void
sched_class(struct thread * td,int class)2604 sched_class(struct thread *td, int class)
2605 {
2606
2607 THREAD_LOCK_ASSERT(td, MA_OWNED);
2608 if (td->td_pri_class == class)
2609 return;
2610 td->td_pri_class = class;
2611 }
2612
2613 /*
2614 * Return some of the child's priority and interactivity to the parent.
2615 */
2616 void
sched_exit(struct proc * p,struct thread * child)2617 sched_exit(struct proc *p, struct thread *child)
2618 {
2619 struct thread *td;
2620
2621 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2622 "prio:%d", child->td_priority);
2623 PROC_LOCK_ASSERT(p, MA_OWNED);
2624 td = FIRST_THREAD_IN_PROC(p);
2625 sched_exit_thread(td, child);
2626 }
2627
2628 /*
2629 * Penalize another thread for the time spent on this one. This helps to
2630 * worsen the priority and interactivity of processes which schedule batch
2631 * jobs such as make. This has little effect on the make process itself but
2632 * causes new processes spawned by it to receive worse scores immediately.
2633 */
2634 void
sched_exit_thread(struct thread * td,struct thread * child)2635 sched_exit_thread(struct thread *td, struct thread *child)
2636 {
2637
2638 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2639 "prio:%d", child->td_priority);
2640 /*
2641 * Give the child's runtime to the parent without returning the
2642 * sleep time as a penalty to the parent. This causes shells that
2643 * launch expensive things to mark their children as expensive.
2644 */
2645 thread_lock(td);
2646 td_get_sched(td)->ts_runtime += td_get_sched(child)->ts_runtime;
2647 sched_interact_update(td);
2648 sched_priority(td);
2649 thread_unlock(td);
2650 }
2651
2652 void
sched_preempt(struct thread * td)2653 sched_preempt(struct thread *td)
2654 {
2655 struct tdq *tdq;
2656 int flags;
2657
2658 SDT_PROBE2(sched, , , surrender, td, td->td_proc);
2659
2660 thread_lock(td);
2661 tdq = TDQ_SELF();
2662 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2663 if (td->td_priority > tdq->tdq_lowpri) {
2664 if (td->td_critnest == 1) {
2665 flags = SW_INVOL | SW_PREEMPT;
2666 flags |= TD_IS_IDLETHREAD(td) ? SWT_REMOTEWAKEIDLE :
2667 SWT_REMOTEPREEMPT;
2668 mi_switch(flags);
2669 /* Switch dropped thread lock. */
2670 return;
2671 }
2672 td->td_owepreempt = 1;
2673 } else {
2674 tdq->tdq_owepreempt = 0;
2675 }
2676 thread_unlock(td);
2677 }
2678
2679 /*
2680 * Fix priorities on return to user-space. Priorities may be elevated due
2681 * to static priorities in msleep() or similar.
2682 */
2683 void
sched_userret_slowpath(struct thread * td)2684 sched_userret_slowpath(struct thread *td)
2685 {
2686
2687 thread_lock(td);
2688 td->td_priority = td->td_user_pri;
2689 td->td_base_pri = td->td_user_pri;
2690 tdq_setlowpri(TDQ_SELF(), td);
2691 thread_unlock(td);
2692 }
2693
2694 SCHED_STAT_DEFINE(ithread_demotions, "Interrupt thread priority demotions");
2695 SCHED_STAT_DEFINE(ithread_preemptions,
2696 "Interrupt thread preemptions due to time-sharing");
2697
2698 /*
2699 * Return time slice for a given thread. For ithreads this is
2700 * sched_slice. For other threads it is tdq_slice(tdq).
2701 */
2702 static inline u_int
td_slice(struct thread * td,struct tdq * tdq)2703 td_slice(struct thread *td, struct tdq *tdq)
2704 {
2705 if (PRI_BASE(td->td_pri_class) == PRI_ITHD)
2706 return (sched_slice);
2707 return (tdq_slice(tdq));
2708 }
2709
2710 /*
2711 * Handle a stathz tick. This is really only relevant for timeshare
2712 * and interrupt threads.
2713 */
2714 void
sched_clock(struct thread * td,int cnt)2715 sched_clock(struct thread *td, int cnt)
2716 {
2717 struct tdq *tdq;
2718 struct td_sched *ts;
2719
2720 THREAD_LOCK_ASSERT(td, MA_OWNED);
2721 tdq = TDQ_SELF();
2722 #ifdef SMP
2723 /*
2724 * We run the long term load balancer infrequently on the first cpu.
2725 */
2726 if (balance_tdq == tdq && smp_started != 0 && rebalance != 0 &&
2727 balance_ticks != 0) {
2728 balance_ticks -= cnt;
2729 if (balance_ticks <= 0)
2730 sched_balance();
2731 }
2732 #endif
2733 /*
2734 * Save the old switch count so we have a record of the last ticks
2735 * activity. Initialize the new switch count based on our load.
2736 * If there is some activity seed it to reflect that.
2737 */
2738 tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
2739 tdq->tdq_switchcnt = tdq->tdq_load;
2740
2741 /*
2742 * Advance the insert offset once for each tick to ensure that all
2743 * threads get a chance to run. In order not to change too much ULE's
2744 * anti-starvation and "nice" behaviors after the switch to a single
2745 * 256-queue runqueue, since the queue insert offset is incremented by
2746 * 1 at every tick (provided the system is not too loaded) and there are
2747 * now 109 distinct levels for the timesharing selection policy instead
2748 * of 64 before (separate runqueue), we apply a factor 7/4 when
2749 * increasing the insert offset, by incrementing it by 2 instead of
2750 * 1 except for one in four ticks.
2751 */
2752 if (tdq->tdq_ts_off == tdq->tdq_ts_deq_off) {
2753 tdq->tdq_ts_ticks += cnt;
2754 tdq->tdq_ts_off = (tdq->tdq_ts_off + 2 * cnt -
2755 tdq-> tdq_ts_ticks / 4) % RQ_TS_POL_MODULO;
2756 tdq->tdq_ts_ticks %= 4;
2757 tdq_advance_ts_deq_off(tdq, false);
2758 }
2759 ts = td_get_sched(td);
2760 sched_pctcpu_update(ts, 1);
2761 if ((td->td_pri_class & PRI_FIFO_BIT) || TD_IS_IDLETHREAD(td))
2762 return;
2763
2764 if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2765 /*
2766 * We used a tick; charge it to the thread so
2767 * that we can compute our interactivity.
2768 */
2769 td_get_sched(td)->ts_runtime += tickincr * cnt;
2770 sched_interact_update(td);
2771 sched_priority(td);
2772 }
2773
2774 /*
2775 * Force a context switch if the current thread has used up a full
2776 * time slice (default is 100ms).
2777 */
2778 ts->ts_slice += cnt;
2779 if (ts->ts_slice >= td_slice(td, tdq)) {
2780 ts->ts_slice = 0;
2781
2782 /*
2783 * If an ithread uses a full quantum, demote its
2784 * priority and preempt it.
2785 */
2786 if (PRI_BASE(td->td_pri_class) == PRI_ITHD) {
2787 SCHED_STAT_INC(ithread_preemptions);
2788 td->td_owepreempt = 1;
2789 if (td->td_base_pri + RQ_PPQ < PRI_MAX_ITHD) {
2790 SCHED_STAT_INC(ithread_demotions);
2791 sched_prio(td, td->td_base_pri + RQ_PPQ);
2792 }
2793 } else {
2794 ast_sched_locked(td, TDA_SCHED);
2795 td->td_flags |= TDF_SLICEEND;
2796 }
2797 }
2798 }
2799
2800 u_int
sched_estcpu(struct thread * td __unused)2801 sched_estcpu(struct thread *td __unused)
2802 {
2803
2804 return (0);
2805 }
2806
2807 /*
2808 * Return whether the current CPU has runnable tasks. Used for in-kernel
2809 * cooperative idle threads.
2810 */
2811 bool
sched_runnable(void)2812 sched_runnable(void)
2813 {
2814 struct tdq *tdq;
2815
2816 tdq = TDQ_SELF();
2817 return (TDQ_LOAD(tdq) > (TD_IS_IDLETHREAD(curthread) ? 0 : 1));
2818 }
2819
2820 /*
2821 * Choose the highest priority thread to run. The thread is removed from
2822 * the run-queue while running however the load remains.
2823 */
2824 struct thread *
sched_choose(void)2825 sched_choose(void)
2826 {
2827 struct thread *td;
2828 struct tdq *tdq;
2829
2830 tdq = TDQ_SELF();
2831 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2832 td = tdq_choose(tdq);
2833 if (td != NULL) {
2834 tdq_runq_rem(tdq, td);
2835 tdq->tdq_lowpri = td->td_priority;
2836 } else {
2837 tdq->tdq_lowpri = PRI_MAX_IDLE;
2838 td = PCPU_GET(idlethread);
2839 }
2840 tdq->tdq_curthread = td;
2841 return (td);
2842 }
2843
2844 /*
2845 * Set owepreempt if the currently running thread has lower priority than "pri".
2846 * Preemption never happens directly in ULE, we always request it once we exit a
2847 * critical section.
2848 */
2849 static void
sched_setpreempt(int pri)2850 sched_setpreempt(int pri)
2851 {
2852 struct thread *ctd;
2853 int cpri;
2854
2855 ctd = curthread;
2856 THREAD_LOCK_ASSERT(ctd, MA_OWNED);
2857
2858 cpri = ctd->td_priority;
2859 if (pri < cpri)
2860 ast_sched_locked(ctd, TDA_SCHED);
2861 if (KERNEL_PANICKED() || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2862 return;
2863 if (!sched_shouldpreempt(pri, cpri, 0))
2864 return;
2865 ctd->td_owepreempt = 1;
2866 }
2867
2868 /*
2869 * Add a thread to a thread queue. Select the appropriate runq and add the
2870 * thread to it. This is the internal function called when the tdq is
2871 * predetermined.
2872 */
2873 static int
tdq_add(struct tdq * tdq,struct thread * td,int flags)2874 tdq_add(struct tdq *tdq, struct thread *td, int flags)
2875 {
2876 int lowpri;
2877
2878 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2879 THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
2880 KASSERT((td->td_inhibitors == 0),
2881 ("sched_add: trying to run inhibited thread"));
2882 KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2883 ("sched_add: bad thread state"));
2884 KASSERT(td->td_flags & TDF_INMEM,
2885 ("sched_add: thread swapped out"));
2886
2887 lowpri = tdq->tdq_lowpri;
2888 if (td->td_priority < lowpri)
2889 tdq->tdq_lowpri = td->td_priority;
2890 tdq_runq_add(tdq, td, flags);
2891 tdq_load_add(tdq, td);
2892 return (lowpri);
2893 }
2894
2895 /*
2896 * Select the target thread queue and add a thread to it. Request
2897 * preemption or IPI a remote processor if required.
2898 *
2899 * Requires the thread lock on entry, drops on exit.
2900 */
2901 void
sched_add(struct thread * td,int flags)2902 sched_add(struct thread *td, int flags)
2903 {
2904 struct tdq *tdq;
2905 #ifdef SMP
2906 int cpu, lowpri;
2907 #endif
2908
2909 KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
2910 "prio:%d", td->td_priority, KTR_ATTR_LINKED,
2911 sched_tdname(curthread));
2912 KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
2913 KTR_ATTR_LINKED, sched_tdname(td));
2914 SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
2915 flags & SRQ_PREEMPTED);
2916 THREAD_LOCK_ASSERT(td, MA_OWNED);
2917 /*
2918 * Recalculate the priority before we select the target cpu or
2919 * run-queue.
2920 */
2921 if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2922 sched_priority(td);
2923 #ifdef SMP
2924 /*
2925 * Pick the destination cpu and if it isn't ours transfer to the
2926 * target cpu.
2927 */
2928 cpu = sched_pickcpu(td, flags);
2929 tdq = sched_setcpu(td, cpu, flags);
2930 lowpri = tdq_add(tdq, td, flags);
2931 if (cpu != PCPU_GET(cpuid))
2932 tdq_notify(tdq, lowpri);
2933 else if (!(flags & SRQ_YIELDING))
2934 sched_setpreempt(td->td_priority);
2935 #else
2936 tdq = TDQ_SELF();
2937 /*
2938 * Now that the thread is moving to the run-queue, set the lock
2939 * to the scheduler's lock.
2940 */
2941 if (td->td_lock != TDQ_LOCKPTR(tdq)) {
2942 TDQ_LOCK(tdq);
2943 if ((flags & SRQ_HOLD) != 0)
2944 td->td_lock = TDQ_LOCKPTR(tdq);
2945 else
2946 thread_lock_set(td, TDQ_LOCKPTR(tdq));
2947 }
2948 (void)tdq_add(tdq, td, flags);
2949 if (!(flags & SRQ_YIELDING))
2950 sched_setpreempt(td->td_priority);
2951 #endif
2952 if (!(flags & SRQ_HOLDTD))
2953 thread_unlock(td);
2954 }
2955
2956 /*
2957 * Remove a thread from a run-queue without running it. This is used
2958 * when we're stealing a thread from a remote queue. Otherwise all threads
2959 * exit by calling sched_exit_thread() and sched_throw() themselves.
2960 */
2961 void
sched_rem(struct thread * td)2962 sched_rem(struct thread *td)
2963 {
2964 struct tdq *tdq;
2965
2966 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
2967 "prio:%d", td->td_priority);
2968 SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
2969 tdq = TDQ_CPU(td_get_sched(td)->ts_cpu);
2970 TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2971 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2972 KASSERT(TD_ON_RUNQ(td),
2973 ("sched_rem: thread not on run queue"));
2974 tdq_runq_rem(tdq, td);
2975 tdq_load_rem(tdq, td);
2976 TD_SET_CAN_RUN(td);
2977 if (td->td_priority == tdq->tdq_lowpri)
2978 tdq_setlowpri(tdq, NULL);
2979 }
2980
2981 /*
2982 * Fetch cpu utilization information. Updates on demand.
2983 */
2984 fixpt_t
sched_pctcpu(struct thread * td)2985 sched_pctcpu(struct thread *td)
2986 {
2987 struct td_sched *ts;
2988 u_int len;
2989 fixpt_t pctcpu;
2990
2991 THREAD_LOCK_ASSERT(td, MA_OWNED);
2992 ts = td_get_sched(td);
2993 sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2994 len = SCHED_TICK_LENGTH(ts);
2995 pctcpu = ((FSHIFT >= SCHED_TICK_SHIFT ? /* Resolved at compile-time. */
2996 (SCHED_TICK_RUN_SHIFTED(ts) << (FSHIFT - SCHED_TICK_SHIFT)) :
2997 (SCHED_TICK_RUN_SHIFTED(ts) >> (SCHED_TICK_SHIFT - FSHIFT))) +
2998 len / 2) / len;
2999 return (pctcpu);
3000 }
3001
3002 /*
3003 * Enforce affinity settings for a thread. Called after adjustments to
3004 * cpumask.
3005 */
3006 void
sched_affinity(struct thread * td)3007 sched_affinity(struct thread *td)
3008 {
3009 #ifdef SMP
3010 struct td_sched *ts;
3011
3012 THREAD_LOCK_ASSERT(td, MA_OWNED);
3013 ts = td_get_sched(td);
3014 if (THREAD_CAN_SCHED(td, ts->ts_cpu))
3015 return;
3016 if (TD_ON_RUNQ(td)) {
3017 sched_rem(td);
3018 sched_add(td, SRQ_BORING | SRQ_HOLDTD);
3019 return;
3020 }
3021 if (!TD_IS_RUNNING(td))
3022 return;
3023 /*
3024 * Force a switch before returning to userspace. If the
3025 * target thread is not running locally send an ipi to force
3026 * the issue.
3027 */
3028 ast_sched_locked(td, TDA_SCHED);
3029 if (td != curthread)
3030 ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
3031 #endif
3032 }
3033
3034 /*
3035 * Bind a thread to a target cpu.
3036 */
3037 void
sched_bind(struct thread * td,int cpu)3038 sched_bind(struct thread *td, int cpu)
3039 {
3040 struct td_sched *ts;
3041
3042 THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
3043 KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
3044 ts = td_get_sched(td);
3045 if (ts->ts_flags & TSF_BOUND)
3046 sched_unbind(td);
3047 KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
3048 ts->ts_flags |= TSF_BOUND;
3049 sched_pin();
3050 if (PCPU_GET(cpuid) == cpu)
3051 return;
3052 ts->ts_cpu = cpu;
3053 /* When we return from mi_switch we'll be on the correct cpu. */
3054 mi_switch(SW_VOL | SWT_BIND);
3055 thread_lock(td);
3056 }
3057
3058 /*
3059 * Release a bound thread.
3060 */
3061 void
sched_unbind(struct thread * td)3062 sched_unbind(struct thread *td)
3063 {
3064 struct td_sched *ts;
3065
3066 THREAD_LOCK_ASSERT(td, MA_OWNED);
3067 KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
3068 ts = td_get_sched(td);
3069 if ((ts->ts_flags & TSF_BOUND) == 0)
3070 return;
3071 ts->ts_flags &= ~TSF_BOUND;
3072 sched_unpin();
3073 }
3074
3075 int
sched_is_bound(struct thread * td)3076 sched_is_bound(struct thread *td)
3077 {
3078 THREAD_LOCK_ASSERT(td, MA_OWNED);
3079 return (td_get_sched(td)->ts_flags & TSF_BOUND);
3080 }
3081
3082 /*
3083 * Basic yield call.
3084 */
3085 void
sched_relinquish(struct thread * td)3086 sched_relinquish(struct thread *td)
3087 {
3088 thread_lock(td);
3089 mi_switch(SW_VOL | SWT_RELINQUISH);
3090 }
3091
3092 /*
3093 * Return the total system load.
3094 */
3095 int
sched_load(void)3096 sched_load(void)
3097 {
3098 #ifdef SMP
3099 int total;
3100 int i;
3101
3102 total = 0;
3103 CPU_FOREACH(i)
3104 total += atomic_load_int(&TDQ_CPU(i)->tdq_sysload);
3105 return (total);
3106 #else
3107 return (atomic_load_int(&TDQ_SELF()->tdq_sysload));
3108 #endif
3109 }
3110
3111 int
sched_sizeof_proc(void)3112 sched_sizeof_proc(void)
3113 {
3114 return (sizeof(struct proc));
3115 }
3116
3117 int
sched_sizeof_thread(void)3118 sched_sizeof_thread(void)
3119 {
3120 return (sizeof(struct thread) + sizeof(struct td_sched));
3121 }
3122
3123 #ifdef SMP
3124 #define TDQ_IDLESPIN(tdq) \
3125 ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
3126 #else
3127 #define TDQ_IDLESPIN(tdq) 1
3128 #endif
3129
3130 /*
3131 * The actual idle process.
3132 */
3133 void
sched_idletd(void * dummy)3134 sched_idletd(void *dummy)
3135 {
3136 struct thread *td;
3137 struct tdq *tdq;
3138 int oldswitchcnt, switchcnt;
3139 int i;
3140
3141 mtx_assert(&Giant, MA_NOTOWNED);
3142 td = curthread;
3143 tdq = TDQ_SELF();
3144 THREAD_NO_SLEEPING();
3145 oldswitchcnt = -1;
3146 for (;;) {
3147 if (TDQ_LOAD(tdq)) {
3148 thread_lock(td);
3149 mi_switch(SW_VOL | SWT_IDLE);
3150 }
3151 switchcnt = TDQ_SWITCHCNT(tdq);
3152 #ifdef SMP
3153 if (always_steal || switchcnt != oldswitchcnt) {
3154 oldswitchcnt = switchcnt;
3155 if (tdq_idled(tdq) == 0)
3156 continue;
3157 }
3158 switchcnt = TDQ_SWITCHCNT(tdq);
3159 #else
3160 oldswitchcnt = switchcnt;
3161 #endif
3162 /*
3163 * If we're switching very frequently, spin while checking
3164 * for load rather than entering a low power state that
3165 * may require an IPI. However, don't do any busy
3166 * loops while on SMT machines as this simply steals
3167 * cycles from cores doing useful work.
3168 */
3169 if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
3170 for (i = 0; i < sched_idlespins; i++) {
3171 if (TDQ_LOAD(tdq))
3172 break;
3173 cpu_spinwait();
3174 }
3175 }
3176
3177 /* If there was context switch during spin, restart it. */
3178 switchcnt = TDQ_SWITCHCNT(tdq);
3179 if (TDQ_LOAD(tdq) != 0 || switchcnt != oldswitchcnt)
3180 continue;
3181
3182 /* Run main MD idle handler. */
3183 atomic_store_int(&tdq->tdq_cpu_idle, 1);
3184 /*
3185 * Make sure that the tdq_cpu_idle update is globally visible
3186 * before cpu_idle() reads tdq_load. The order is important
3187 * to avoid races with tdq_notify().
3188 */
3189 atomic_thread_fence_seq_cst();
3190 /*
3191 * Checking for again after the fence picks up assigned
3192 * threads often enough to make it worthwhile to do so in
3193 * order to avoid calling cpu_idle().
3194 */
3195 if (TDQ_LOAD(tdq) != 0) {
3196 atomic_store_int(&tdq->tdq_cpu_idle, 0);
3197 continue;
3198 }
3199 cpu_idle(switchcnt * 4 > sched_idlespinthresh);
3200 atomic_store_int(&tdq->tdq_cpu_idle, 0);
3201
3202 /*
3203 * Account thread-less hardware interrupts and
3204 * other wakeup reasons equal to context switches.
3205 */
3206 switchcnt = TDQ_SWITCHCNT(tdq);
3207 if (switchcnt != oldswitchcnt)
3208 continue;
3209 TDQ_SWITCHCNT_INC(tdq);
3210 oldswitchcnt++;
3211 }
3212 }
3213
3214 /*
3215 * sched_throw_grab() chooses a thread from the queue to switch to
3216 * next. It returns with the tdq lock dropped in a spinlock section to
3217 * keep interrupts disabled until the CPU is running in a proper threaded
3218 * context.
3219 */
3220 static struct thread *
sched_throw_grab(struct tdq * tdq)3221 sched_throw_grab(struct tdq *tdq)
3222 {
3223 struct thread *newtd;
3224
3225 newtd = choosethread();
3226 spinlock_enter();
3227 TDQ_UNLOCK(tdq);
3228 KASSERT(curthread->td_md.md_spinlock_count == 1,
3229 ("invalid count %d", curthread->td_md.md_spinlock_count));
3230 return (newtd);
3231 }
3232
3233 /*
3234 * A CPU is entering for the first time.
3235 */
3236 void
sched_ap_entry(void)3237 sched_ap_entry(void)
3238 {
3239 struct thread *newtd;
3240 struct tdq *tdq;
3241
3242 tdq = TDQ_SELF();
3243
3244 /* This should have been setup in schedinit_ap(). */
3245 THREAD_LOCKPTR_ASSERT(curthread, TDQ_LOCKPTR(tdq));
3246
3247 TDQ_LOCK(tdq);
3248 /* Correct spinlock nesting. */
3249 spinlock_exit();
3250 PCPU_SET(switchtime, cpu_ticks());
3251 PCPU_SET(switchticks, ticks);
3252
3253 newtd = sched_throw_grab(tdq);
3254
3255 /* doesn't return */
3256 cpu_throw(NULL, newtd);
3257 }
3258
3259 /*
3260 * A thread is exiting.
3261 */
3262 void
sched_throw(struct thread * td)3263 sched_throw(struct thread *td)
3264 {
3265 struct thread *newtd;
3266 struct tdq *tdq;
3267
3268 tdq = TDQ_SELF();
3269
3270 MPASS(td != NULL);
3271 THREAD_LOCK_ASSERT(td, MA_OWNED);
3272 THREAD_LOCKPTR_ASSERT(td, TDQ_LOCKPTR(tdq));
3273
3274 tdq_load_rem(tdq, td);
3275 td->td_lastcpu = td->td_oncpu;
3276 td->td_oncpu = NOCPU;
3277 thread_lock_block(td);
3278
3279 newtd = sched_throw_grab(tdq);
3280
3281 /* doesn't return */
3282 cpu_switch(td, newtd, TDQ_LOCKPTR(tdq));
3283 }
3284
3285 /*
3286 * This is called from fork_exit(). Just acquire the correct locks and
3287 * let fork do the rest of the work.
3288 */
3289 void
sched_fork_exit(struct thread * td)3290 sched_fork_exit(struct thread *td)
3291 {
3292 struct tdq *tdq;
3293 int cpuid;
3294
3295 /*
3296 * Finish setting up thread glue so that it begins execution in a
3297 * non-nested critical section with the scheduler lock held.
3298 */
3299 KASSERT(curthread->td_md.md_spinlock_count == 1,
3300 ("invalid count %d", curthread->td_md.md_spinlock_count));
3301 cpuid = PCPU_GET(cpuid);
3302 tdq = TDQ_SELF();
3303 TDQ_LOCK(tdq);
3304 spinlock_exit();
3305 MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
3306 td->td_oncpu = cpuid;
3307 KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
3308 "prio:%d", td->td_priority);
3309 SDT_PROBE0(sched, , , on__cpu);
3310 }
3311
3312 /*
3313 * Create on first use to catch odd startup conditions.
3314 */
3315 char *
sched_tdname(struct thread * td)3316 sched_tdname(struct thread *td)
3317 {
3318 #ifdef KTR
3319 struct td_sched *ts;
3320
3321 ts = td_get_sched(td);
3322 if (ts->ts_name[0] == '\0')
3323 snprintf(ts->ts_name, sizeof(ts->ts_name),
3324 "%s tid %d", td->td_name, td->td_tid);
3325 return (ts->ts_name);
3326 #else
3327 return (td->td_name);
3328 #endif
3329 }
3330
3331 #ifdef KTR
3332 void
sched_clear_tdname(struct thread * td)3333 sched_clear_tdname(struct thread *td)
3334 {
3335 struct td_sched *ts;
3336
3337 ts = td_get_sched(td);
3338 ts->ts_name[0] = '\0';
3339 }
3340 #endif
3341
3342 #ifdef SMP
3343
3344 /*
3345 * Build the CPU topology dump string. Is recursively called to collect
3346 * the topology tree.
3347 */
3348 static int
sysctl_kern_sched_topology_spec_internal(struct sbuf * sb,struct cpu_group * cg,int indent)3349 sysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
3350 int indent)
3351 {
3352 char cpusetbuf[CPUSETBUFSIZ];
3353 int i, first;
3354
3355 sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
3356 "", 1 + indent / 2, cg->cg_level);
3357 sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
3358 cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
3359 first = TRUE;
3360 for (i = cg->cg_first; i <= cg->cg_last; i++) {
3361 if (CPU_ISSET(i, &cg->cg_mask)) {
3362 if (!first)
3363 sbuf_cat(sb, ", ");
3364 else
3365 first = FALSE;
3366 sbuf_printf(sb, "%d", i);
3367 }
3368 }
3369 sbuf_cat(sb, "</cpu>\n");
3370
3371 if (cg->cg_flags != 0) {
3372 sbuf_printf(sb, "%*s <flags>", indent, "");
3373 if ((cg->cg_flags & CG_FLAG_HTT) != 0)
3374 sbuf_cat(sb, "<flag name=\"HTT\">HTT group</flag>");
3375 if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
3376 sbuf_cat(sb, "<flag name=\"THREAD\">THREAD group</flag>");
3377 if ((cg->cg_flags & CG_FLAG_SMT) != 0)
3378 sbuf_cat(sb, "<flag name=\"SMT\">SMT group</flag>");
3379 if ((cg->cg_flags & CG_FLAG_NODE) != 0)
3380 sbuf_cat(sb, "<flag name=\"NODE\">NUMA node</flag>");
3381 sbuf_cat(sb, "</flags>\n");
3382 }
3383
3384 if (cg->cg_children > 0) {
3385 sbuf_printf(sb, "%*s <children>\n", indent, "");
3386 for (i = 0; i < cg->cg_children; i++)
3387 sysctl_kern_sched_topology_spec_internal(sb,
3388 &cg->cg_child[i], indent+2);
3389 sbuf_printf(sb, "%*s </children>\n", indent, "");
3390 }
3391 sbuf_printf(sb, "%*s</group>\n", indent, "");
3392 return (0);
3393 }
3394
3395 /*
3396 * Sysctl handler for retrieving topology dump. It's a wrapper for
3397 * the recursive sysctl_kern_smp_topology_spec_internal().
3398 */
3399 static int
sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)3400 sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
3401 {
3402 struct sbuf *topo;
3403 int err;
3404
3405 KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
3406
3407 topo = sbuf_new_for_sysctl(NULL, NULL, 512, req);
3408 if (topo == NULL)
3409 return (ENOMEM);
3410
3411 sbuf_cat(topo, "<groups>\n");
3412 err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
3413 sbuf_cat(topo, "</groups>\n");
3414
3415 if (err == 0) {
3416 err = sbuf_finish(topo);
3417 }
3418 sbuf_delete(topo);
3419 return (err);
3420 }
3421
3422 #endif
3423
3424 static int
sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)3425 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
3426 {
3427 int error, new_val, period;
3428
3429 period = 1000000 / realstathz;
3430 new_val = period * sched_slice;
3431 error = sysctl_handle_int(oidp, &new_val, 0, req);
3432 if (error != 0 || req->newptr == NULL)
3433 return (error);
3434 if (new_val <= 0)
3435 return (EINVAL);
3436 sched_slice = imax(1, (new_val + period / 2) / period);
3437 sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
3438 hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
3439 realstathz);
3440 return (0);
3441 }
3442
3443 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
3444 "Scheduler");
3445 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
3446 "Scheduler name");
3447 SYSCTL_PROC(_kern_sched, OID_AUTO, quantum,
3448 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
3449 sysctl_kern_quantum, "I",
3450 "Quantum for timeshare threads in microseconds");
3451 SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
3452 "Quantum for timeshare threads in stathz ticks");
3453 SYSCTL_UINT(_kern_sched, OID_AUTO, interact, CTLFLAG_RWTUN, &sched_interact, 0,
3454 "Interactivity score threshold");
3455 SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RWTUN,
3456 &preempt_thresh, 0,
3457 "Maximal (lowest) priority for preemption");
3458 SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RWTUN, &static_boost, 0,
3459 "Assign static kernel priorities to sleeping threads");
3460 SYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RWTUN, &sched_idlespins, 0,
3461 "Number of times idle thread will spin waiting for new work");
3462 SYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW,
3463 &sched_idlespinthresh, 0,
3464 "Threshold before we will permit idle thread spinning");
3465 #ifdef SMP
3466 SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
3467 "Number of hz ticks to keep thread affinity for");
3468 SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RWTUN, &rebalance, 0,
3469 "Enables the long-term load balancer");
3470 SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
3471 &balance_interval, 0,
3472 "Average period in stathz ticks to run the long-term balancer");
3473 SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RWTUN, &steal_idle, 0,
3474 "Attempts to steal work from other cores before idling");
3475 SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RWTUN, &steal_thresh, 0,
3476 "Minimum load on remote CPU before we'll steal");
3477 SYSCTL_INT(_kern_sched, OID_AUTO, trysteal_limit, CTLFLAG_RWTUN,
3478 &trysteal_limit, 0,
3479 "Topological distance limit for stealing threads in sched_switch()");
3480 SYSCTL_INT(_kern_sched, OID_AUTO, always_steal, CTLFLAG_RWTUN, &always_steal, 0,
3481 "Always run the stealer from the idle thread");
3482 SYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
3483 CTLFLAG_MPSAFE | CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
3484 "XML dump of detected CPU topology");
3485 #endif
3486
3487 /* ps compat. All cpu percentages from ULE are weighted. */
3488 static int ccpu = 0;
3489 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0,
3490 "Decay factor used for updating %CPU in 4BSD scheduler");
3491