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