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