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