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