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