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