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