xref: /freebsd/sys/kern/sched_ule.c (revision cacdd70cc751fb68dec4b86c5e5b8c969b6e26ef)
1 /*-
2  * Copyright (c) 2002-2007, Jeffrey Roberson <jeff@freebsd.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice unmodified, this list of conditions, and the following
10  *    disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 /*
28  * This file implements the ULE scheduler.  ULE supports independent CPU
29  * run queues and fine grain locking.  It has superior interactive
30  * performance under load even on uni-processor systems.
31  *
32  * etymology:
33  *   ULE is the last three letters in schedule.  It owes its name to a
34  * generic user created for a scheduling system by Paul Mikesell at
35  * Isilon Systems and a general lack of creativity on the part of the author.
36  */
37 
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 #include "opt_hwpmc_hooks.h"
42 #include "opt_kdtrace.h"
43 #include "opt_sched.h"
44 
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kdb.h>
48 #include <sys/kernel.h>
49 #include <sys/ktr.h>
50 #include <sys/lock.h>
51 #include <sys/mutex.h>
52 #include <sys/proc.h>
53 #include <sys/resource.h>
54 #include <sys/resourcevar.h>
55 #include <sys/sched.h>
56 #include <sys/smp.h>
57 #include <sys/sx.h>
58 #include <sys/sysctl.h>
59 #include <sys/sysproto.h>
60 #include <sys/turnstile.h>
61 #include <sys/umtx.h>
62 #include <sys/vmmeter.h>
63 #include <sys/cpuset.h>
64 #ifdef KTRACE
65 #include <sys/uio.h>
66 #include <sys/ktrace.h>
67 #endif
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				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 #if defined(__sparc64__) || defined(__mips__)
83 #error "This architecture is not currently compatible with ULE"
84 #endif
85 
86 #define	KTR_ULE	0
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 	u_char		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 };
104 /* flags kept in ts_flags */
105 #define	TSF_BOUND	0x0001		/* Thread can not migrate. */
106 #define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
107 
108 static struct td_sched td_sched0;
109 
110 #define	THREAD_CAN_MIGRATE(td)	((td)->td_pinned == 0)
111 #define	THREAD_CAN_SCHED(td, cpu)	\
112     CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
113 
114 /*
115  * Cpu percentage computation macros and defines.
116  *
117  * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
118  * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
119  * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
120  * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
121  * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
122  * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
123  */
124 #define	SCHED_TICK_SECS		10
125 #define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
126 #define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
127 #define	SCHED_TICK_SHIFT	10
128 #define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
129 #define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
130 
131 /*
132  * These macros determine priorities for non-interactive threads.  They are
133  * assigned a priority based on their recent cpu utilization as expressed
134  * by the ratio of ticks to the tick total.  NHALF priorities at the start
135  * and end of the MIN to MAX timeshare range are only reachable with negative
136  * or positive nice respectively.
137  *
138  * PRI_RANGE:	Priority range for utilization dependent priorities.
139  * PRI_NRESV:	Number of nice values.
140  * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
141  * PRI_NICE:	Determines the part of the priority inherited from nice.
142  */
143 #define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
144 #define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
145 #define	SCHED_PRI_MIN		(PRI_MIN_TIMESHARE + SCHED_PRI_NHALF)
146 #define	SCHED_PRI_MAX		(PRI_MAX_TIMESHARE - SCHED_PRI_NHALF)
147 #define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN)
148 #define	SCHED_PRI_TICKS(ts)						\
149     (SCHED_TICK_HZ((ts)) /						\
150     (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
151 #define	SCHED_PRI_NICE(nice)	(nice)
152 
153 /*
154  * These determine the interactivity of a process.  Interactivity differs from
155  * cpu utilization in that it expresses the voluntary time slept vs time ran
156  * while cpu utilization includes all time not running.  This more accurately
157  * models the intent of the thread.
158  *
159  * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
160  *		before throttling back.
161  * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
162  * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
163  * INTERACT_THRESH:	Threshhold for placement on the current runq.
164  */
165 #define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
166 #define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
167 #define	SCHED_INTERACT_MAX	(100)
168 #define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
169 #define	SCHED_INTERACT_THRESH	(30)
170 
171 /*
172  * tickincr:		Converts a stathz tick into a hz domain scaled by
173  *			the shift factor.  Without the shift the error rate
174  *			due to rounding would be unacceptably high.
175  * realstathz:		stathz is sometimes 0 and run off of hz.
176  * sched_slice:		Runtime of each thread before rescheduling.
177  * preempt_thresh:	Priority threshold for preemption and remote IPIs.
178  */
179 static int sched_interact = SCHED_INTERACT_THRESH;
180 static int realstathz;
181 static int tickincr;
182 static int sched_slice = 1;
183 #ifdef PREEMPTION
184 #ifdef FULL_PREEMPTION
185 static int preempt_thresh = PRI_MAX_IDLE;
186 #else
187 static int preempt_thresh = PRI_MIN_KERN;
188 #endif
189 #else
190 static int preempt_thresh = 0;
191 #endif
192 static int static_boost = PRI_MIN_TIMESHARE;
193 static int sched_idlespins = 10000;
194 static int sched_idlespinthresh = 4;
195 
196 /*
197  * tdq - per processor runqs and statistics.  All fields are protected by the
198  * tdq_lock.  The load and lowpri may be accessed without to avoid excess
199  * locking in sched_pickcpu();
200  */
201 struct tdq {
202 	/* Ordered to improve efficiency of cpu_search() and switch(). */
203 	struct mtx	tdq_lock;		/* run queue lock. */
204 	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
205 	volatile int	tdq_load;		/* Aggregate load. */
206 	int		tdq_sysload;		/* For loadavg, !ITHD load. */
207 	int		tdq_transferable;	/* Transferable thread count. */
208 	volatile int	tdq_idlestate;		/* State of the idle thread. */
209 	short		tdq_switchcnt;		/* Switches this tick. */
210 	short		tdq_oldswitchcnt;	/* Switches last tick. */
211 	u_char		tdq_lowpri;		/* Lowest priority thread. */
212 	u_char		tdq_ipipending;		/* IPI pending. */
213 	u_char		tdq_idx;		/* Current insert index. */
214 	u_char		tdq_ridx;		/* Current removal index. */
215 	struct runq	tdq_realtime;		/* real-time run queue. */
216 	struct runq	tdq_timeshare;		/* timeshare run queue. */
217 	struct runq	tdq_idle;		/* Queue of IDLE threads. */
218 	char		tdq_name[sizeof("sched lock") + 6];
219 } __aligned(64);
220 
221 /* Idle thread states and config. */
222 #define	TDQ_RUNNING	1
223 #define	TDQ_IDLE	2
224 
225 #ifdef SMP
226 struct cpu_group *cpu_top;
227 
228 #define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
229 #define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
230 
231 /*
232  * Run-time tunables.
233  */
234 static int rebalance = 1;
235 static int balance_interval = 128;	/* Default set in sched_initticks(). */
236 static int affinity;
237 static int steal_htt = 1;
238 static int steal_idle = 1;
239 static int steal_thresh = 2;
240 
241 /*
242  * One thread queue per processor.
243  */
244 static struct tdq	tdq_cpu[MAXCPU];
245 static struct tdq	*balance_tdq;
246 static int balance_ticks;
247 
248 #define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
249 #define	TDQ_CPU(x)	(&tdq_cpu[(x)])
250 #define	TDQ_ID(x)	((int)((x) - tdq_cpu))
251 #else	/* !SMP */
252 static struct tdq	tdq_cpu;
253 
254 #define	TDQ_ID(x)	(0)
255 #define	TDQ_SELF()	(&tdq_cpu)
256 #define	TDQ_CPU(x)	(&tdq_cpu)
257 #endif
258 
259 #define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
260 #define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
261 #define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
262 #define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
263 #define	TDQ_LOCKPTR(t)		(&(t)->tdq_lock)
264 
265 static void sched_priority(struct thread *);
266 static void sched_thread_priority(struct thread *, u_char);
267 static int sched_interact_score(struct thread *);
268 static void sched_interact_update(struct thread *);
269 static void sched_interact_fork(struct thread *);
270 static void sched_pctcpu_update(struct td_sched *);
271 
272 /* Operations on per processor queues */
273 static struct thread *tdq_choose(struct tdq *);
274 static void tdq_setup(struct tdq *);
275 static void tdq_load_add(struct tdq *, struct thread *);
276 static void tdq_load_rem(struct tdq *, struct thread *);
277 static __inline void tdq_runq_add(struct tdq *, struct thread *, int);
278 static __inline void tdq_runq_rem(struct tdq *, struct thread *);
279 static inline int sched_shouldpreempt(int, int, int);
280 void tdq_print(int cpu);
281 static void runq_print(struct runq *rq);
282 static void tdq_add(struct tdq *, struct thread *, int);
283 #ifdef SMP
284 static int tdq_move(struct tdq *, struct tdq *);
285 static int tdq_idled(struct tdq *);
286 static void tdq_notify(struct tdq *, struct thread *);
287 static struct thread *tdq_steal(struct tdq *, int);
288 static struct thread *runq_steal(struct runq *, int);
289 static int sched_pickcpu(struct thread *, int);
290 static void sched_balance(void);
291 static int sched_balance_pair(struct tdq *, struct tdq *);
292 static inline struct tdq *sched_setcpu(struct thread *, int, int);
293 static inline struct mtx *thread_block_switch(struct thread *);
294 static inline void thread_unblock_switch(struct thread *, struct mtx *);
295 static struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
296 #endif
297 
298 static void sched_setup(void *dummy);
299 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
300 
301 static void sched_initticks(void *dummy);
302 SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
303     NULL);
304 
305 /*
306  * Print the threads waiting on a run-queue.
307  */
308 static void
309 runq_print(struct runq *rq)
310 {
311 	struct rqhead *rqh;
312 	struct thread *td;
313 	int pri;
314 	int j;
315 	int i;
316 
317 	for (i = 0; i < RQB_LEN; i++) {
318 		printf("\t\trunq bits %d 0x%zx\n",
319 		    i, rq->rq_status.rqb_bits[i]);
320 		for (j = 0; j < RQB_BPW; j++)
321 			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
322 				pri = j + (i << RQB_L2BPW);
323 				rqh = &rq->rq_queues[pri];
324 				TAILQ_FOREACH(td, rqh, td_runq) {
325 					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
326 					    td, td->td_name, td->td_priority,
327 					    td->td_rqindex, pri);
328 				}
329 			}
330 	}
331 }
332 
333 /*
334  * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
335  */
336 void
337 tdq_print(int cpu)
338 {
339 	struct tdq *tdq;
340 
341 	tdq = TDQ_CPU(cpu);
342 
343 	printf("tdq %d:\n", TDQ_ID(tdq));
344 	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
345 	printf("\tLock name:      %s\n", tdq->tdq_name);
346 	printf("\tload:           %d\n", tdq->tdq_load);
347 	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
348 	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
349 	printf("\tidle state:     %d\n", tdq->tdq_idlestate);
350 	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
351 	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
352 	printf("\tload transferable: %d\n", tdq->tdq_transferable);
353 	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
354 	printf("\trealtime runq:\n");
355 	runq_print(&tdq->tdq_realtime);
356 	printf("\ttimeshare runq:\n");
357 	runq_print(&tdq->tdq_timeshare);
358 	printf("\tidle runq:\n");
359 	runq_print(&tdq->tdq_idle);
360 }
361 
362 static inline int
363 sched_shouldpreempt(int pri, int cpri, int remote)
364 {
365 	/*
366 	 * If the new priority is not better than the current priority there is
367 	 * nothing to do.
368 	 */
369 	if (pri >= cpri)
370 		return (0);
371 	/*
372 	 * Always preempt idle.
373 	 */
374 	if (cpri >= PRI_MIN_IDLE)
375 		return (1);
376 	/*
377 	 * If preemption is disabled don't preempt others.
378 	 */
379 	if (preempt_thresh == 0)
380 		return (0);
381 	/*
382 	 * Preempt if we exceed the threshold.
383 	 */
384 	if (pri <= preempt_thresh)
385 		return (1);
386 	/*
387 	 * If we're realtime or better and there is timeshare or worse running
388 	 * preempt only remote processors.
389 	 */
390 	if (remote && pri <= PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
391 		return (1);
392 	return (0);
393 }
394 
395 #define	TS_RQ_PPQ	(((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
396 /*
397  * Add a thread to the actual run-queue.  Keeps transferable counts up to
398  * date with what is actually on the run-queue.  Selects the correct
399  * queue position for timeshare threads.
400  */
401 static __inline void
402 tdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
403 {
404 	struct td_sched *ts;
405 	u_char pri;
406 
407 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
408 	THREAD_LOCK_ASSERT(td, MA_OWNED);
409 
410 	pri = td->td_priority;
411 	ts = td->td_sched;
412 	TD_SET_RUNQ(td);
413 	if (THREAD_CAN_MIGRATE(td)) {
414 		tdq->tdq_transferable++;
415 		ts->ts_flags |= TSF_XFERABLE;
416 	}
417 	if (pri <= PRI_MAX_REALTIME) {
418 		ts->ts_runq = &tdq->tdq_realtime;
419 	} else if (pri <= PRI_MAX_TIMESHARE) {
420 		ts->ts_runq = &tdq->tdq_timeshare;
421 		KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
422 			("Invalid priority %d on timeshare runq", pri));
423 		/*
424 		 * This queue contains only priorities between MIN and MAX
425 		 * realtime.  Use the whole queue to represent these values.
426 		 */
427 		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
428 			pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
429 			pri = (pri + tdq->tdq_idx) % RQ_NQS;
430 			/*
431 			 * This effectively shortens the queue by one so we
432 			 * can have a one slot difference between idx and
433 			 * ridx while we wait for threads to drain.
434 			 */
435 			if (tdq->tdq_ridx != tdq->tdq_idx &&
436 			    pri == tdq->tdq_ridx)
437 				pri = (unsigned char)(pri - 1) % RQ_NQS;
438 		} else
439 			pri = tdq->tdq_ridx;
440 		runq_add_pri(ts->ts_runq, td, pri, flags);
441 		return;
442 	} else
443 		ts->ts_runq = &tdq->tdq_idle;
444 	runq_add(ts->ts_runq, td, flags);
445 }
446 
447 /*
448  * Remove a thread from a run-queue.  This typically happens when a thread
449  * is selected to run.  Running threads are not on the queue and the
450  * transferable count does not reflect them.
451  */
452 static __inline void
453 tdq_runq_rem(struct tdq *tdq, struct thread *td)
454 {
455 	struct td_sched *ts;
456 
457 	ts = td->td_sched;
458 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
459 	KASSERT(ts->ts_runq != NULL,
460 	    ("tdq_runq_remove: thread %p null ts_runq", td));
461 	if (ts->ts_flags & TSF_XFERABLE) {
462 		tdq->tdq_transferable--;
463 		ts->ts_flags &= ~TSF_XFERABLE;
464 	}
465 	if (ts->ts_runq == &tdq->tdq_timeshare) {
466 		if (tdq->tdq_idx != tdq->tdq_ridx)
467 			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
468 		else
469 			runq_remove_idx(ts->ts_runq, td, NULL);
470 	} else
471 		runq_remove(ts->ts_runq, td);
472 }
473 
474 /*
475  * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
476  * for this thread to the referenced thread queue.
477  */
478 static void
479 tdq_load_add(struct tdq *tdq, struct thread *td)
480 {
481 
482 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
483 	THREAD_LOCK_ASSERT(td, MA_OWNED);
484 
485 	tdq->tdq_load++;
486 	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
487 		tdq->tdq_sysload++;
488 	CTR2(KTR_SCHED, "cpu %d load: %d", TDQ_ID(tdq), tdq->tdq_load);
489 }
490 
491 /*
492  * Remove the load from a thread that is transitioning to a sleep state or
493  * exiting.
494  */
495 static void
496 tdq_load_rem(struct tdq *tdq, struct thread *td)
497 {
498 
499 	THREAD_LOCK_ASSERT(td, MA_OWNED);
500 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
501 	KASSERT(tdq->tdq_load != 0,
502 	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
503 
504 	tdq->tdq_load--;
505 	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
506 		tdq->tdq_sysload--;
507 	CTR1(KTR_SCHED, "load: %d", tdq->tdq_load);
508 }
509 
510 /*
511  * Set lowpri to its exact value by searching the run-queue and
512  * evaluating curthread.  curthread may be passed as an optimization.
513  */
514 static void
515 tdq_setlowpri(struct tdq *tdq, struct thread *ctd)
516 {
517 	struct thread *td;
518 
519 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
520 	if (ctd == NULL)
521 		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
522 	td = tdq_choose(tdq);
523 	if (td == NULL || td->td_priority > ctd->td_priority)
524 		tdq->tdq_lowpri = ctd->td_priority;
525 	else
526 		tdq->tdq_lowpri = td->td_priority;
527 }
528 
529 #ifdef SMP
530 struct cpu_search {
531 	cpumask_t cs_mask;	/* Mask of valid cpus. */
532 	u_int	cs_load;
533 	u_int	cs_cpu;
534 	int	cs_limit;	/* Min priority for low min load for high. */
535 };
536 
537 #define	CPU_SEARCH_LOWEST	0x1
538 #define	CPU_SEARCH_HIGHEST	0x2
539 #define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
540 
541 #define	CPUMASK_FOREACH(cpu, mask)				\
542 	for ((cpu) = 0; (cpu) < sizeof((mask)) * 8; (cpu)++)	\
543 		if ((mask) & 1 << (cpu))
544 
545 static __inline int cpu_search(struct cpu_group *cg, struct cpu_search *low,
546     struct cpu_search *high, const int match);
547 int cpu_search_lowest(struct cpu_group *cg, struct cpu_search *low);
548 int cpu_search_highest(struct cpu_group *cg, struct cpu_search *high);
549 int cpu_search_both(struct cpu_group *cg, struct cpu_search *low,
550     struct cpu_search *high);
551 
552 /*
553  * This routine compares according to the match argument and should be
554  * reduced in actual instantiations via constant propagation and dead code
555  * elimination.
556  */
557 static __inline int
558 cpu_compare(int cpu, struct cpu_search *low, struct cpu_search *high,
559     const int match)
560 {
561 	struct tdq *tdq;
562 
563 	tdq = TDQ_CPU(cpu);
564 	if (match & CPU_SEARCH_LOWEST)
565 		if (low->cs_mask & (1 << cpu) &&
566 		    tdq->tdq_load < low->cs_load &&
567 		    tdq->tdq_lowpri > low->cs_limit) {
568 			low->cs_cpu = cpu;
569 			low->cs_load = tdq->tdq_load;
570 		}
571 	if (match & CPU_SEARCH_HIGHEST)
572 		if (high->cs_mask & (1 << cpu) &&
573 		    tdq->tdq_load >= high->cs_limit &&
574 		    tdq->tdq_load > high->cs_load &&
575 		    tdq->tdq_transferable) {
576 			high->cs_cpu = cpu;
577 			high->cs_load = tdq->tdq_load;
578 		}
579 	return (tdq->tdq_load);
580 }
581 
582 /*
583  * Search the tree of cpu_groups for the lowest or highest loaded cpu
584  * according to the match argument.  This routine actually compares the
585  * load on all paths through the tree and finds the least loaded cpu on
586  * the least loaded path, which may differ from the least loaded cpu in
587  * the system.  This balances work among caches and busses.
588  *
589  * This inline is instantiated in three forms below using constants for the
590  * match argument.  It is reduced to the minimum set for each case.  It is
591  * also recursive to the depth of the tree.
592  */
593 static __inline int
594 cpu_search(struct cpu_group *cg, struct cpu_search *low,
595     struct cpu_search *high, const int match)
596 {
597 	int total;
598 
599 	total = 0;
600 	if (cg->cg_children) {
601 		struct cpu_search lgroup;
602 		struct cpu_search hgroup;
603 		struct cpu_group *child;
604 		u_int lload;
605 		int hload;
606 		int load;
607 		int i;
608 
609 		lload = -1;
610 		hload = -1;
611 		for (i = 0; i < cg->cg_children; i++) {
612 			child = &cg->cg_child[i];
613 			if (match & CPU_SEARCH_LOWEST) {
614 				lgroup = *low;
615 				lgroup.cs_load = -1;
616 			}
617 			if (match & CPU_SEARCH_HIGHEST) {
618 				hgroup = *high;
619 				lgroup.cs_load = 0;
620 			}
621 			switch (match) {
622 			case CPU_SEARCH_LOWEST:
623 				load = cpu_search_lowest(child, &lgroup);
624 				break;
625 			case CPU_SEARCH_HIGHEST:
626 				load = cpu_search_highest(child, &hgroup);
627 				break;
628 			case CPU_SEARCH_BOTH:
629 				load = cpu_search_both(child, &lgroup, &hgroup);
630 				break;
631 			}
632 			total += load;
633 			if (match & CPU_SEARCH_LOWEST)
634 				if (load < lload || low->cs_cpu == -1) {
635 					*low = lgroup;
636 					lload = load;
637 				}
638 			if (match & CPU_SEARCH_HIGHEST)
639 				if (load > hload || high->cs_cpu == -1) {
640 					hload = load;
641 					*high = hgroup;
642 				}
643 		}
644 	} else {
645 		int cpu;
646 
647 		CPUMASK_FOREACH(cpu, cg->cg_mask)
648 			total += cpu_compare(cpu, low, high, match);
649 	}
650 	return (total);
651 }
652 
653 /*
654  * cpu_search instantiations must pass constants to maintain the inline
655  * optimization.
656  */
657 int
658 cpu_search_lowest(struct cpu_group *cg, struct cpu_search *low)
659 {
660 	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
661 }
662 
663 int
664 cpu_search_highest(struct cpu_group *cg, struct cpu_search *high)
665 {
666 	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
667 }
668 
669 int
670 cpu_search_both(struct cpu_group *cg, struct cpu_search *low,
671     struct cpu_search *high)
672 {
673 	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
674 }
675 
676 /*
677  * Find the cpu with the least load via the least loaded path that has a
678  * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
679  * acceptable.
680  */
681 static inline int
682 sched_lowest(struct cpu_group *cg, cpumask_t mask, int pri)
683 {
684 	struct cpu_search low;
685 
686 	low.cs_cpu = -1;
687 	low.cs_load = -1;
688 	low.cs_mask = mask;
689 	low.cs_limit = pri;
690 	cpu_search_lowest(cg, &low);
691 	return low.cs_cpu;
692 }
693 
694 /*
695  * Find the cpu with the highest load via the highest loaded path.
696  */
697 static inline int
698 sched_highest(struct cpu_group *cg, cpumask_t mask, int minload)
699 {
700 	struct cpu_search high;
701 
702 	high.cs_cpu = -1;
703 	high.cs_load = 0;
704 	high.cs_mask = mask;
705 	high.cs_limit = minload;
706 	cpu_search_highest(cg, &high);
707 	return high.cs_cpu;
708 }
709 
710 /*
711  * Simultaneously find the highest and lowest loaded cpu reachable via
712  * cg.
713  */
714 static inline void
715 sched_both(struct cpu_group *cg, cpumask_t mask, int *lowcpu, int *highcpu)
716 {
717 	struct cpu_search high;
718 	struct cpu_search low;
719 
720 	low.cs_cpu = -1;
721 	low.cs_limit = -1;
722 	low.cs_load = -1;
723 	low.cs_mask = mask;
724 	high.cs_load = 0;
725 	high.cs_cpu = -1;
726 	high.cs_limit = -1;
727 	high.cs_mask = mask;
728 	cpu_search_both(cg, &low, &high);
729 	*lowcpu = low.cs_cpu;
730 	*highcpu = high.cs_cpu;
731 	return;
732 }
733 
734 static void
735 sched_balance_group(struct cpu_group *cg)
736 {
737 	cpumask_t mask;
738 	int high;
739 	int low;
740 	int i;
741 
742 	mask = -1;
743 	for (;;) {
744 		sched_both(cg, mask, &low, &high);
745 		if (low == high || low == -1 || high == -1)
746 			break;
747 		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low)))
748 			break;
749 		/*
750 		 * If we failed to move any threads determine which cpu
751 		 * to kick out of the set and try again.
752 	 	 */
753 		if (TDQ_CPU(high)->tdq_transferable == 0)
754 			mask &= ~(1 << high);
755 		else
756 			mask &= ~(1 << low);
757 	}
758 
759 	for (i = 0; i < cg->cg_children; i++)
760 		sched_balance_group(&cg->cg_child[i]);
761 }
762 
763 static void
764 sched_balance()
765 {
766 	struct tdq *tdq;
767 
768 	/*
769 	 * Select a random time between .5 * balance_interval and
770 	 * 1.5 * balance_interval.
771 	 */
772 	balance_ticks = max(balance_interval / 2, 1);
773 	balance_ticks += random() % balance_interval;
774 	if (smp_started == 0 || rebalance == 0)
775 		return;
776 	tdq = TDQ_SELF();
777 	TDQ_UNLOCK(tdq);
778 	sched_balance_group(cpu_top);
779 	TDQ_LOCK(tdq);
780 }
781 
782 /*
783  * Lock two thread queues using their address to maintain lock order.
784  */
785 static void
786 tdq_lock_pair(struct tdq *one, struct tdq *two)
787 {
788 	if (one < two) {
789 		TDQ_LOCK(one);
790 		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
791 	} else {
792 		TDQ_LOCK(two);
793 		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
794 	}
795 }
796 
797 /*
798  * Unlock two thread queues.  Order is not important here.
799  */
800 static void
801 tdq_unlock_pair(struct tdq *one, struct tdq *two)
802 {
803 	TDQ_UNLOCK(one);
804 	TDQ_UNLOCK(two);
805 }
806 
807 /*
808  * Transfer load between two imbalanced thread queues.
809  */
810 static int
811 sched_balance_pair(struct tdq *high, struct tdq *low)
812 {
813 	int transferable;
814 	int high_load;
815 	int low_load;
816 	int moved;
817 	int move;
818 	int diff;
819 	int i;
820 
821 	tdq_lock_pair(high, low);
822 	transferable = high->tdq_transferable;
823 	high_load = high->tdq_load;
824 	low_load = low->tdq_load;
825 	moved = 0;
826 	/*
827 	 * Determine what the imbalance is and then adjust that to how many
828 	 * threads we actually have to give up (transferable).
829 	 */
830 	if (transferable != 0) {
831 		diff = high_load - low_load;
832 		move = diff / 2;
833 		if (diff & 0x1)
834 			move++;
835 		move = min(move, transferable);
836 		for (i = 0; i < move; i++)
837 			moved += tdq_move(high, low);
838 		/*
839 		 * IPI the target cpu to force it to reschedule with the new
840 		 * workload.
841 		 */
842 		ipi_selected(1 << TDQ_ID(low), IPI_PREEMPT);
843 	}
844 	tdq_unlock_pair(high, low);
845 	return (moved);
846 }
847 
848 /*
849  * Move a thread from one thread queue to another.
850  */
851 static int
852 tdq_move(struct tdq *from, struct tdq *to)
853 {
854 	struct td_sched *ts;
855 	struct thread *td;
856 	struct tdq *tdq;
857 	int cpu;
858 
859 	TDQ_LOCK_ASSERT(from, MA_OWNED);
860 	TDQ_LOCK_ASSERT(to, MA_OWNED);
861 
862 	tdq = from;
863 	cpu = TDQ_ID(to);
864 	td = tdq_steal(tdq, cpu);
865 	if (td == NULL)
866 		return (0);
867 	ts = td->td_sched;
868 	/*
869 	 * Although the run queue is locked the thread may be blocked.  Lock
870 	 * it to clear this and acquire the run-queue lock.
871 	 */
872 	thread_lock(td);
873 	/* Drop recursive lock on from acquired via thread_lock(). */
874 	TDQ_UNLOCK(from);
875 	sched_rem(td);
876 	ts->ts_cpu = cpu;
877 	td->td_lock = TDQ_LOCKPTR(to);
878 	tdq_add(to, td, SRQ_YIELDING);
879 	return (1);
880 }
881 
882 /*
883  * This tdq has idled.  Try to steal a thread from another cpu and switch
884  * to it.
885  */
886 static int
887 tdq_idled(struct tdq *tdq)
888 {
889 	struct cpu_group *cg;
890 	struct tdq *steal;
891 	cpumask_t mask;
892 	int thresh;
893 	int cpu;
894 
895 	if (smp_started == 0 || steal_idle == 0)
896 		return (1);
897 	mask = -1;
898 	mask &= ~PCPU_GET(cpumask);
899 	/* We don't want to be preempted while we're iterating. */
900 	spinlock_enter();
901 	for (cg = tdq->tdq_cg; cg != NULL; ) {
902 		if ((cg->cg_flags & (CG_FLAG_HTT | CG_FLAG_THREAD)) == 0)
903 			thresh = steal_thresh;
904 		else
905 			thresh = 1;
906 		cpu = sched_highest(cg, mask, thresh);
907 		if (cpu == -1) {
908 			cg = cg->cg_parent;
909 			continue;
910 		}
911 		steal = TDQ_CPU(cpu);
912 		mask &= ~(1 << cpu);
913 		tdq_lock_pair(tdq, steal);
914 		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
915 			tdq_unlock_pair(tdq, steal);
916 			continue;
917 		}
918 		/*
919 		 * If a thread was added while interrupts were disabled don't
920 		 * steal one here.  If we fail to acquire one due to affinity
921 		 * restrictions loop again with this cpu removed from the
922 		 * set.
923 		 */
924 		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
925 			tdq_unlock_pair(tdq, steal);
926 			continue;
927 		}
928 		spinlock_exit();
929 		TDQ_UNLOCK(steal);
930 		mi_switch(SW_VOL | SWT_IDLE, NULL);
931 		thread_unlock(curthread);
932 
933 		return (0);
934 	}
935 	spinlock_exit();
936 	return (1);
937 }
938 
939 /*
940  * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
941  */
942 static void
943 tdq_notify(struct tdq *tdq, struct thread *td)
944 {
945 	int cpri;
946 	int pri;
947 	int cpu;
948 
949 	if (tdq->tdq_ipipending)
950 		return;
951 	cpu = td->td_sched->ts_cpu;
952 	pri = td->td_priority;
953 	cpri = pcpu_find(cpu)->pc_curthread->td_priority;
954 	if (!sched_shouldpreempt(pri, cpri, 1))
955 		return;
956 	if (TD_IS_IDLETHREAD(td)) {
957 		/*
958 		 * If the idle thread is still 'running' it's probably
959 		 * waiting on us to release the tdq spinlock already.  No
960 		 * need to ipi.
961 		 */
962 		if (tdq->tdq_idlestate == TDQ_RUNNING)
963 			return;
964 		/*
965 		 * If the MD code has an idle wakeup routine try that before
966 		 * falling back to IPI.
967 		 */
968 		if (cpu_idle_wakeup(cpu))
969 			return;
970 	}
971 	tdq->tdq_ipipending = 1;
972 	ipi_selected(1 << cpu, IPI_PREEMPT);
973 }
974 
975 /*
976  * Steals load from a timeshare queue.  Honors the rotating queue head
977  * index.
978  */
979 static struct thread *
980 runq_steal_from(struct runq *rq, int cpu, u_char start)
981 {
982 	struct rqbits *rqb;
983 	struct rqhead *rqh;
984 	struct thread *td;
985 	int first;
986 	int bit;
987 	int pri;
988 	int i;
989 
990 	rqb = &rq->rq_status;
991 	bit = start & (RQB_BPW -1);
992 	pri = 0;
993 	first = 0;
994 again:
995 	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
996 		if (rqb->rqb_bits[i] == 0)
997 			continue;
998 		if (bit != 0) {
999 			for (pri = bit; pri < RQB_BPW; pri++)
1000 				if (rqb->rqb_bits[i] & (1ul << pri))
1001 					break;
1002 			if (pri >= RQB_BPW)
1003 				continue;
1004 		} else
1005 			pri = RQB_FFS(rqb->rqb_bits[i]);
1006 		pri += (i << RQB_L2BPW);
1007 		rqh = &rq->rq_queues[pri];
1008 		TAILQ_FOREACH(td, rqh, td_runq) {
1009 			if (first && THREAD_CAN_MIGRATE(td) &&
1010 			    THREAD_CAN_SCHED(td, cpu))
1011 				return (td);
1012 			first = 1;
1013 		}
1014 	}
1015 	if (start != 0) {
1016 		start = 0;
1017 		goto again;
1018 	}
1019 
1020 	return (NULL);
1021 }
1022 
1023 /*
1024  * Steals load from a standard linear queue.
1025  */
1026 static struct thread *
1027 runq_steal(struct runq *rq, int cpu)
1028 {
1029 	struct rqhead *rqh;
1030 	struct rqbits *rqb;
1031 	struct thread *td;
1032 	int word;
1033 	int bit;
1034 
1035 	rqb = &rq->rq_status;
1036 	for (word = 0; word < RQB_LEN; word++) {
1037 		if (rqb->rqb_bits[word] == 0)
1038 			continue;
1039 		for (bit = 0; bit < RQB_BPW; bit++) {
1040 			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
1041 				continue;
1042 			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
1043 			TAILQ_FOREACH(td, rqh, td_runq)
1044 				if (THREAD_CAN_MIGRATE(td) &&
1045 				    THREAD_CAN_SCHED(td, cpu))
1046 					return (td);
1047 		}
1048 	}
1049 	return (NULL);
1050 }
1051 
1052 /*
1053  * Attempt to steal a thread in priority order from a thread queue.
1054  */
1055 static struct thread *
1056 tdq_steal(struct tdq *tdq, int cpu)
1057 {
1058 	struct thread *td;
1059 
1060 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1061 	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
1062 		return (td);
1063 	if ((td = runq_steal_from(&tdq->tdq_timeshare,
1064 	    cpu, tdq->tdq_ridx)) != NULL)
1065 		return (td);
1066 	return (runq_steal(&tdq->tdq_idle, cpu));
1067 }
1068 
1069 /*
1070  * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
1071  * current lock and returns with the assigned queue locked.
1072  */
1073 static inline struct tdq *
1074 sched_setcpu(struct thread *td, int cpu, int flags)
1075 {
1076 
1077 	struct tdq *tdq;
1078 
1079 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1080 	tdq = TDQ_CPU(cpu);
1081 	td->td_sched->ts_cpu = cpu;
1082 	/*
1083 	 * If the lock matches just return the queue.
1084 	 */
1085 	if (td->td_lock == TDQ_LOCKPTR(tdq))
1086 		return (tdq);
1087 #ifdef notyet
1088 	/*
1089 	 * If the thread isn't running its lockptr is a
1090 	 * turnstile or a sleepqueue.  We can just lock_set without
1091 	 * blocking.
1092 	 */
1093 	if (TD_CAN_RUN(td)) {
1094 		TDQ_LOCK(tdq);
1095 		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1096 		return (tdq);
1097 	}
1098 #endif
1099 	/*
1100 	 * The hard case, migration, we need to block the thread first to
1101 	 * prevent order reversals with other cpus locks.
1102 	 */
1103 	thread_lock_block(td);
1104 	TDQ_LOCK(tdq);
1105 	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1106 	return (tdq);
1107 }
1108 
1109 SCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
1110 SCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
1111 SCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
1112 SCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
1113 SCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
1114 SCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
1115 
1116 static int
1117 sched_pickcpu(struct thread *td, int flags)
1118 {
1119 	struct cpu_group *cg;
1120 	struct td_sched *ts;
1121 	struct tdq *tdq;
1122 	cpumask_t mask;
1123 	int self;
1124 	int pri;
1125 	int cpu;
1126 
1127 	self = PCPU_GET(cpuid);
1128 	ts = td->td_sched;
1129 	if (smp_started == 0)
1130 		return (self);
1131 	/*
1132 	 * Don't migrate a running thread from sched_switch().
1133 	 */
1134 	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1135 		return (ts->ts_cpu);
1136 	/*
1137 	 * Prefer to run interrupt threads on the processors that generate
1138 	 * the interrupt.
1139 	 */
1140 	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1141 	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
1142 		SCHED_STAT_INC(pickcpu_intrbind);
1143 		ts->ts_cpu = self;
1144 	}
1145 	/*
1146 	 * If the thread can run on the last cpu and the affinity has not
1147 	 * expired or it is idle run it there.
1148 	 */
1149 	pri = td->td_priority;
1150 	tdq = TDQ_CPU(ts->ts_cpu);
1151 	if (THREAD_CAN_SCHED(td, ts->ts_cpu)) {
1152 		if (tdq->tdq_lowpri > PRI_MIN_IDLE) {
1153 			SCHED_STAT_INC(pickcpu_idle_affinity);
1154 			return (ts->ts_cpu);
1155 		}
1156 		if (SCHED_AFFINITY(ts, CG_SHARE_L2) && tdq->tdq_lowpri > pri) {
1157 			SCHED_STAT_INC(pickcpu_affinity);
1158 			return (ts->ts_cpu);
1159 		}
1160 	}
1161 	/*
1162 	 * Search for the highest level in the tree that still has affinity.
1163 	 */
1164 	cg = NULL;
1165 	for (cg = tdq->tdq_cg; cg != NULL; cg = cg->cg_parent)
1166 		if (SCHED_AFFINITY(ts, cg->cg_level))
1167 			break;
1168 	cpu = -1;
1169 	mask = td->td_cpuset->cs_mask.__bits[0];
1170 	if (cg)
1171 		cpu = sched_lowest(cg, mask, pri);
1172 	if (cpu == -1)
1173 		cpu = sched_lowest(cpu_top, mask, -1);
1174 	/*
1175 	 * Compare the lowest loaded cpu to current cpu.
1176 	 */
1177 	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
1178 	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE) {
1179 		SCHED_STAT_INC(pickcpu_local);
1180 		cpu = self;
1181 	} else
1182 		SCHED_STAT_INC(pickcpu_lowest);
1183 	if (cpu != ts->ts_cpu)
1184 		SCHED_STAT_INC(pickcpu_migration);
1185 	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1186 	return (cpu);
1187 }
1188 #endif
1189 
1190 /*
1191  * Pick the highest priority task we have and return it.
1192  */
1193 static struct thread *
1194 tdq_choose(struct tdq *tdq)
1195 {
1196 	struct thread *td;
1197 
1198 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1199 	td = runq_choose(&tdq->tdq_realtime);
1200 	if (td != NULL)
1201 		return (td);
1202 	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1203 	if (td != NULL) {
1204 		KASSERT(td->td_priority >= PRI_MIN_TIMESHARE,
1205 		    ("tdq_choose: Invalid priority on timeshare queue %d",
1206 		    td->td_priority));
1207 		return (td);
1208 	}
1209 	td = runq_choose(&tdq->tdq_idle);
1210 	if (td != NULL) {
1211 		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1212 		    ("tdq_choose: Invalid priority on idle queue %d",
1213 		    td->td_priority));
1214 		return (td);
1215 	}
1216 
1217 	return (NULL);
1218 }
1219 
1220 /*
1221  * Initialize a thread queue.
1222  */
1223 static void
1224 tdq_setup(struct tdq *tdq)
1225 {
1226 
1227 	if (bootverbose)
1228 		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1229 	runq_init(&tdq->tdq_realtime);
1230 	runq_init(&tdq->tdq_timeshare);
1231 	runq_init(&tdq->tdq_idle);
1232 	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1233 	    "sched lock %d", (int)TDQ_ID(tdq));
1234 	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1235 	    MTX_SPIN | MTX_RECURSE);
1236 }
1237 
1238 #ifdef SMP
1239 static void
1240 sched_setup_smp(void)
1241 {
1242 	struct tdq *tdq;
1243 	int i;
1244 
1245 	cpu_top = smp_topo();
1246 	for (i = 0; i < MAXCPU; i++) {
1247 		if (CPU_ABSENT(i))
1248 			continue;
1249 		tdq = TDQ_CPU(i);
1250 		tdq_setup(tdq);
1251 		tdq->tdq_cg = smp_topo_find(cpu_top, i);
1252 		if (tdq->tdq_cg == NULL)
1253 			panic("Can't find cpu group for %d\n", i);
1254 	}
1255 	balance_tdq = TDQ_SELF();
1256 	sched_balance();
1257 }
1258 #endif
1259 
1260 /*
1261  * Setup the thread queues and initialize the topology based on MD
1262  * information.
1263  */
1264 static void
1265 sched_setup(void *dummy)
1266 {
1267 	struct tdq *tdq;
1268 
1269 	tdq = TDQ_SELF();
1270 #ifdef SMP
1271 	sched_setup_smp();
1272 #else
1273 	tdq_setup(tdq);
1274 #endif
1275 	/*
1276 	 * To avoid divide-by-zero, we set realstathz a dummy value
1277 	 * in case which sched_clock() called before sched_initticks().
1278 	 */
1279 	realstathz = hz;
1280 	sched_slice = (realstathz/10);	/* ~100ms */
1281 	tickincr = 1 << SCHED_TICK_SHIFT;
1282 
1283 	/* Add thread0's load since it's running. */
1284 	TDQ_LOCK(tdq);
1285 	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1286 	tdq_load_add(tdq, &thread0);
1287 	tdq->tdq_lowpri = thread0.td_priority;
1288 	TDQ_UNLOCK(tdq);
1289 }
1290 
1291 /*
1292  * This routine determines the tickincr after stathz and hz are setup.
1293  */
1294 /* ARGSUSED */
1295 static void
1296 sched_initticks(void *dummy)
1297 {
1298 	int incr;
1299 
1300 	realstathz = stathz ? stathz : hz;
1301 	sched_slice = (realstathz/10);	/* ~100ms */
1302 
1303 	/*
1304 	 * tickincr is shifted out by 10 to avoid rounding errors due to
1305 	 * hz not being evenly divisible by stathz on all platforms.
1306 	 */
1307 	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1308 	/*
1309 	 * This does not work for values of stathz that are more than
1310 	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1311 	 */
1312 	if (incr == 0)
1313 		incr = 1;
1314 	tickincr = incr;
1315 #ifdef SMP
1316 	/*
1317 	 * Set the default balance interval now that we know
1318 	 * what realstathz is.
1319 	 */
1320 	balance_interval = realstathz;
1321 	/*
1322 	 * Set steal thresh to log2(mp_ncpu) but no greater than 4.  This
1323 	 * prevents excess thrashing on large machines and excess idle on
1324 	 * smaller machines.
1325 	 */
1326 	steal_thresh = min(ffs(mp_ncpus) - 1, 3);
1327 	affinity = SCHED_AFFINITY_DEFAULT;
1328 #endif
1329 }
1330 
1331 
1332 /*
1333  * This is the core of the interactivity algorithm.  Determines a score based
1334  * on past behavior.  It is the ratio of sleep time to run time scaled to
1335  * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1336  * differs from the cpu usage because it does not account for time spent
1337  * waiting on a run-queue.  Would be prettier if we had floating point.
1338  */
1339 static int
1340 sched_interact_score(struct thread *td)
1341 {
1342 	struct td_sched *ts;
1343 	int div;
1344 
1345 	ts = td->td_sched;
1346 	/*
1347 	 * The score is only needed if this is likely to be an interactive
1348 	 * task.  Don't go through the expense of computing it if there's
1349 	 * no chance.
1350 	 */
1351 	if (sched_interact <= SCHED_INTERACT_HALF &&
1352 		ts->ts_runtime >= ts->ts_slptime)
1353 			return (SCHED_INTERACT_HALF);
1354 
1355 	if (ts->ts_runtime > ts->ts_slptime) {
1356 		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1357 		return (SCHED_INTERACT_HALF +
1358 		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1359 	}
1360 	if (ts->ts_slptime > ts->ts_runtime) {
1361 		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1362 		return (ts->ts_runtime / div);
1363 	}
1364 	/* runtime == slptime */
1365 	if (ts->ts_runtime)
1366 		return (SCHED_INTERACT_HALF);
1367 
1368 	/*
1369 	 * This can happen if slptime and runtime are 0.
1370 	 */
1371 	return (0);
1372 
1373 }
1374 
1375 /*
1376  * Scale the scheduling priority according to the "interactivity" of this
1377  * process.
1378  */
1379 static void
1380 sched_priority(struct thread *td)
1381 {
1382 	int score;
1383 	int pri;
1384 
1385 	if (td->td_pri_class != PRI_TIMESHARE)
1386 		return;
1387 	/*
1388 	 * If the score is interactive we place the thread in the realtime
1389 	 * queue with a priority that is less than kernel and interrupt
1390 	 * priorities.  These threads are not subject to nice restrictions.
1391 	 *
1392 	 * Scores greater than this are placed on the normal timeshare queue
1393 	 * where the priority is partially decided by the most recent cpu
1394 	 * utilization and the rest is decided by nice value.
1395 	 *
1396 	 * The nice value of the process has a linear effect on the calculated
1397 	 * score.  Negative nice values make it easier for a thread to be
1398 	 * considered interactive.
1399 	 */
1400 	score = imax(0, sched_interact_score(td) - td->td_proc->p_nice);
1401 	if (score < sched_interact) {
1402 		pri = PRI_MIN_REALTIME;
1403 		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1404 		    * score;
1405 		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1406 		    ("sched_priority: invalid interactive priority %d score %d",
1407 		    pri, score));
1408 	} else {
1409 		pri = SCHED_PRI_MIN;
1410 		if (td->td_sched->ts_ticks)
1411 			pri += SCHED_PRI_TICKS(td->td_sched);
1412 		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1413 		KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1414 		    ("sched_priority: invalid priority %d: nice %d, "
1415 		    "ticks %d ftick %d ltick %d tick pri %d",
1416 		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1417 		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1418 		    SCHED_PRI_TICKS(td->td_sched)));
1419 	}
1420 	sched_user_prio(td, pri);
1421 
1422 	return;
1423 }
1424 
1425 /*
1426  * This routine enforces a maximum limit on the amount of scheduling history
1427  * kept.  It is called after either the slptime or runtime is adjusted.  This
1428  * function is ugly due to integer math.
1429  */
1430 static void
1431 sched_interact_update(struct thread *td)
1432 {
1433 	struct td_sched *ts;
1434 	u_int sum;
1435 
1436 	ts = td->td_sched;
1437 	sum = ts->ts_runtime + ts->ts_slptime;
1438 	if (sum < SCHED_SLP_RUN_MAX)
1439 		return;
1440 	/*
1441 	 * This only happens from two places:
1442 	 * 1) We have added an unusual amount of run time from fork_exit.
1443 	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1444 	 */
1445 	if (sum > SCHED_SLP_RUN_MAX * 2) {
1446 		if (ts->ts_runtime > ts->ts_slptime) {
1447 			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1448 			ts->ts_slptime = 1;
1449 		} else {
1450 			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1451 			ts->ts_runtime = 1;
1452 		}
1453 		return;
1454 	}
1455 	/*
1456 	 * If we have exceeded by more than 1/5th then the algorithm below
1457 	 * will not bring us back into range.  Dividing by two here forces
1458 	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1459 	 */
1460 	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1461 		ts->ts_runtime /= 2;
1462 		ts->ts_slptime /= 2;
1463 		return;
1464 	}
1465 	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1466 	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1467 }
1468 
1469 /*
1470  * Scale back the interactivity history when a child thread is created.  The
1471  * history is inherited from the parent but the thread may behave totally
1472  * differently.  For example, a shell spawning a compiler process.  We want
1473  * to learn that the compiler is behaving badly very quickly.
1474  */
1475 static void
1476 sched_interact_fork(struct thread *td)
1477 {
1478 	int ratio;
1479 	int sum;
1480 
1481 	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1482 	if (sum > SCHED_SLP_RUN_FORK) {
1483 		ratio = sum / SCHED_SLP_RUN_FORK;
1484 		td->td_sched->ts_runtime /= ratio;
1485 		td->td_sched->ts_slptime /= ratio;
1486 	}
1487 }
1488 
1489 /*
1490  * Called from proc0_init() to setup the scheduler fields.
1491  */
1492 void
1493 schedinit(void)
1494 {
1495 
1496 	/*
1497 	 * Set up the scheduler specific parts of proc0.
1498 	 */
1499 	proc0.p_sched = NULL; /* XXX */
1500 	thread0.td_sched = &td_sched0;
1501 	td_sched0.ts_ltick = ticks;
1502 	td_sched0.ts_ftick = ticks;
1503 	td_sched0.ts_slice = sched_slice;
1504 }
1505 
1506 /*
1507  * This is only somewhat accurate since given many processes of the same
1508  * priority they will switch when their slices run out, which will be
1509  * at most sched_slice stathz ticks.
1510  */
1511 int
1512 sched_rr_interval(void)
1513 {
1514 
1515 	/* Convert sched_slice to hz */
1516 	return (hz/(realstathz/sched_slice));
1517 }
1518 
1519 /*
1520  * Update the percent cpu tracking information when it is requested or
1521  * the total history exceeds the maximum.  We keep a sliding history of
1522  * tick counts that slowly decays.  This is less precise than the 4BSD
1523  * mechanism since it happens with less regular and frequent events.
1524  */
1525 static void
1526 sched_pctcpu_update(struct td_sched *ts)
1527 {
1528 
1529 	if (ts->ts_ticks == 0)
1530 		return;
1531 	if (ticks - (hz / 10) < ts->ts_ltick &&
1532 	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1533 		return;
1534 	/*
1535 	 * Adjust counters and watermark for pctcpu calc.
1536 	 */
1537 	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1538 		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1539 			    SCHED_TICK_TARG;
1540 	else
1541 		ts->ts_ticks = 0;
1542 	ts->ts_ltick = ticks;
1543 	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1544 }
1545 
1546 /*
1547  * Adjust the priority of a thread.  Move it to the appropriate run-queue
1548  * if necessary.  This is the back-end for several priority related
1549  * functions.
1550  */
1551 static void
1552 sched_thread_priority(struct thread *td, u_char prio)
1553 {
1554 	struct td_sched *ts;
1555 	struct tdq *tdq;
1556 	int oldpri;
1557 
1558 	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
1559 	    td, td->td_name, td->td_priority, prio, curthread,
1560 	    curthread->td_name);
1561 	ts = td->td_sched;
1562 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1563 	if (td->td_priority == prio)
1564 		return;
1565 	/*
1566 	 * If the priority has been elevated due to priority
1567 	 * propagation, we may have to move ourselves to a new
1568 	 * queue.  This could be optimized to not re-add in some
1569 	 * cases.
1570 	 */
1571 	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1572 		sched_rem(td);
1573 		td->td_priority = prio;
1574 		sched_add(td, SRQ_BORROWING);
1575 		return;
1576 	}
1577 	/*
1578 	 * If the thread is currently running we may have to adjust the lowpri
1579 	 * information so other cpus are aware of our current priority.
1580 	 */
1581 	if (TD_IS_RUNNING(td)) {
1582 		tdq = TDQ_CPU(ts->ts_cpu);
1583 		oldpri = td->td_priority;
1584 		td->td_priority = prio;
1585 		if (prio < tdq->tdq_lowpri)
1586 			tdq->tdq_lowpri = prio;
1587 		else if (tdq->tdq_lowpri == oldpri)
1588 			tdq_setlowpri(tdq, td);
1589 		return;
1590 	}
1591 	td->td_priority = prio;
1592 }
1593 
1594 /*
1595  * Update a thread's priority when it is lent another thread's
1596  * priority.
1597  */
1598 void
1599 sched_lend_prio(struct thread *td, u_char prio)
1600 {
1601 
1602 	td->td_flags |= TDF_BORROWING;
1603 	sched_thread_priority(td, prio);
1604 }
1605 
1606 /*
1607  * Restore a thread's priority when priority propagation is
1608  * over.  The prio argument is the minimum priority the thread
1609  * needs to have to satisfy other possible priority lending
1610  * requests.  If the thread's regular priority is less
1611  * important than prio, the thread will keep a priority boost
1612  * of prio.
1613  */
1614 void
1615 sched_unlend_prio(struct thread *td, u_char prio)
1616 {
1617 	u_char base_pri;
1618 
1619 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1620 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1621 		base_pri = td->td_user_pri;
1622 	else
1623 		base_pri = td->td_base_pri;
1624 	if (prio >= base_pri) {
1625 		td->td_flags &= ~TDF_BORROWING;
1626 		sched_thread_priority(td, base_pri);
1627 	} else
1628 		sched_lend_prio(td, prio);
1629 }
1630 
1631 /*
1632  * Standard entry for setting the priority to an absolute value.
1633  */
1634 void
1635 sched_prio(struct thread *td, u_char prio)
1636 {
1637 	u_char oldprio;
1638 
1639 	/* First, update the base priority. */
1640 	td->td_base_pri = prio;
1641 
1642 	/*
1643 	 * If the thread is borrowing another thread's priority, don't
1644 	 * ever lower the priority.
1645 	 */
1646 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1647 		return;
1648 
1649 	/* Change the real priority. */
1650 	oldprio = td->td_priority;
1651 	sched_thread_priority(td, prio);
1652 
1653 	/*
1654 	 * If the thread is on a turnstile, then let the turnstile update
1655 	 * its state.
1656 	 */
1657 	if (TD_ON_LOCK(td) && oldprio != prio)
1658 		turnstile_adjust(td, oldprio);
1659 }
1660 
1661 /*
1662  * Set the base user priority, does not effect current running priority.
1663  */
1664 void
1665 sched_user_prio(struct thread *td, u_char prio)
1666 {
1667 	u_char oldprio;
1668 
1669 	td->td_base_user_pri = prio;
1670 	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1671                 return;
1672 	oldprio = td->td_user_pri;
1673 	td->td_user_pri = prio;
1674 }
1675 
1676 void
1677 sched_lend_user_prio(struct thread *td, u_char prio)
1678 {
1679 	u_char oldprio;
1680 
1681 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1682 	td->td_flags |= TDF_UBORROWING;
1683 	oldprio = td->td_user_pri;
1684 	td->td_user_pri = prio;
1685 }
1686 
1687 void
1688 sched_unlend_user_prio(struct thread *td, u_char prio)
1689 {
1690 	u_char base_pri;
1691 
1692 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1693 	base_pri = td->td_base_user_pri;
1694 	if (prio >= base_pri) {
1695 		td->td_flags &= ~TDF_UBORROWING;
1696 		sched_user_prio(td, base_pri);
1697 	} else {
1698 		sched_lend_user_prio(td, prio);
1699 	}
1700 }
1701 
1702 /*
1703  * Block a thread for switching.  Similar to thread_block() but does not
1704  * bump the spin count.
1705  */
1706 static inline struct mtx *
1707 thread_block_switch(struct thread *td)
1708 {
1709 	struct mtx *lock;
1710 
1711 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1712 	lock = td->td_lock;
1713 	td->td_lock = &blocked_lock;
1714 	mtx_unlock_spin(lock);
1715 
1716 	return (lock);
1717 }
1718 
1719 /*
1720  * Handle migration from sched_switch().  This happens only for
1721  * cpu binding.
1722  */
1723 static struct mtx *
1724 sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1725 {
1726 	struct tdq *tdn;
1727 
1728 	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1729 #ifdef SMP
1730 	tdq_load_rem(tdq, td);
1731 	/*
1732 	 * Do the lock dance required to avoid LOR.  We grab an extra
1733 	 * spinlock nesting to prevent preemption while we're
1734 	 * not holding either run-queue lock.
1735 	 */
1736 	spinlock_enter();
1737 	thread_block_switch(td);	/* This releases the lock on tdq. */
1738 	TDQ_LOCK(tdn);
1739 	tdq_add(tdn, td, flags);
1740 	tdq_notify(tdn, td);
1741 	/*
1742 	 * After we unlock tdn the new cpu still can't switch into this
1743 	 * thread until we've unblocked it in cpu_switch().  The lock
1744 	 * pointers may match in the case of HTT cores.  Don't unlock here
1745 	 * or we can deadlock when the other CPU runs the IPI handler.
1746 	 */
1747 	if (TDQ_LOCKPTR(tdn) != TDQ_LOCKPTR(tdq)) {
1748 		TDQ_UNLOCK(tdn);
1749 		TDQ_LOCK(tdq);
1750 	}
1751 	spinlock_exit();
1752 #endif
1753 	return (TDQ_LOCKPTR(tdn));
1754 }
1755 
1756 /*
1757  * Release a thread that was blocked with thread_block_switch().
1758  */
1759 static inline void
1760 thread_unblock_switch(struct thread *td, struct mtx *mtx)
1761 {
1762 	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1763 	    (uintptr_t)mtx);
1764 }
1765 
1766 /*
1767  * Switch threads.  This function has to handle threads coming in while
1768  * blocked for some reason, running, or idle.  It also must deal with
1769  * migrating a thread from one queue to another as running threads may
1770  * be assigned elsewhere via binding.
1771  */
1772 void
1773 sched_switch(struct thread *td, struct thread *newtd, int flags)
1774 {
1775 	struct tdq *tdq;
1776 	struct td_sched *ts;
1777 	struct mtx *mtx;
1778 	int srqflag;
1779 	int cpuid;
1780 
1781 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1782 	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
1783 
1784 	cpuid = PCPU_GET(cpuid);
1785 	tdq = TDQ_CPU(cpuid);
1786 	ts = td->td_sched;
1787 	mtx = td->td_lock;
1788 	ts->ts_rltick = ticks;
1789 	td->td_lastcpu = td->td_oncpu;
1790 	td->td_oncpu = NOCPU;
1791 	td->td_flags &= ~TDF_NEEDRESCHED;
1792 	td->td_owepreempt = 0;
1793 	tdq->tdq_switchcnt++;
1794 	/*
1795 	 * The lock pointer in an idle thread should never change.  Reset it
1796 	 * to CAN_RUN as well.
1797 	 */
1798 	if (TD_IS_IDLETHREAD(td)) {
1799 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1800 		TD_SET_CAN_RUN(td);
1801 	} else if (TD_IS_RUNNING(td)) {
1802 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1803 		srqflag = (flags & SW_PREEMPT) ?
1804 		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1805 		    SRQ_OURSELF|SRQ_YIELDING;
1806 		if (ts->ts_cpu == cpuid)
1807 			tdq_runq_add(tdq, td, srqflag);
1808 		else
1809 			mtx = sched_switch_migrate(tdq, td, srqflag);
1810 	} else {
1811 		/* This thread must be going to sleep. */
1812 		TDQ_LOCK(tdq);
1813 		mtx = thread_block_switch(td);
1814 		tdq_load_rem(tdq, td);
1815 	}
1816 	/*
1817 	 * We enter here with the thread blocked and assigned to the
1818 	 * appropriate cpu run-queue or sleep-queue and with the current
1819 	 * thread-queue locked.
1820 	 */
1821 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1822 	newtd = choosethread();
1823 	/*
1824 	 * Call the MD code to switch contexts if necessary.
1825 	 */
1826 	if (td != newtd) {
1827 #ifdef	HWPMC_HOOKS
1828 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1829 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1830 #endif
1831 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1832 		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1833 
1834 #ifdef KDTRACE_HOOKS
1835 		/*
1836 		 * If DTrace has set the active vtime enum to anything
1837 		 * other than INACTIVE (0), then it should have set the
1838 		 * function to call.
1839 		 */
1840 		if (dtrace_vtime_active)
1841 			(*dtrace_vtime_switch_func)(newtd);
1842 #endif
1843 
1844 		cpu_switch(td, newtd, mtx);
1845 		/*
1846 		 * We may return from cpu_switch on a different cpu.  However,
1847 		 * we always return with td_lock pointing to the current cpu's
1848 		 * run queue lock.
1849 		 */
1850 		cpuid = PCPU_GET(cpuid);
1851 		tdq = TDQ_CPU(cpuid);
1852 		lock_profile_obtain_lock_success(
1853 		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1854 #ifdef	HWPMC_HOOKS
1855 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1856 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1857 #endif
1858 	} else
1859 		thread_unblock_switch(td, mtx);
1860 	/*
1861 	 * Assert that all went well and return.
1862 	 */
1863 	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1864 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1865 	td->td_oncpu = cpuid;
1866 }
1867 
1868 /*
1869  * Adjust thread priorities as a result of a nice request.
1870  */
1871 void
1872 sched_nice(struct proc *p, int nice)
1873 {
1874 	struct thread *td;
1875 
1876 	PROC_LOCK_ASSERT(p, MA_OWNED);
1877 
1878 	p->p_nice = nice;
1879 	FOREACH_THREAD_IN_PROC(p, td) {
1880 		thread_lock(td);
1881 		sched_priority(td);
1882 		sched_prio(td, td->td_base_user_pri);
1883 		thread_unlock(td);
1884 	}
1885 }
1886 
1887 /*
1888  * Record the sleep time for the interactivity scorer.
1889  */
1890 void
1891 sched_sleep(struct thread *td, int prio)
1892 {
1893 
1894 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1895 
1896 	td->td_slptick = ticks;
1897 	if (TD_IS_SUSPENDED(td) || prio <= PSOCK)
1898 		td->td_flags |= TDF_CANSWAP;
1899 	if (static_boost == 1 && prio)
1900 		sched_prio(td, prio);
1901 	else if (static_boost && td->td_priority > static_boost)
1902 		sched_prio(td, static_boost);
1903 }
1904 
1905 /*
1906  * Schedule a thread to resume execution and record how long it voluntarily
1907  * slept.  We also update the pctcpu, interactivity, and priority.
1908  */
1909 void
1910 sched_wakeup(struct thread *td)
1911 {
1912 	struct td_sched *ts;
1913 	int slptick;
1914 
1915 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1916 	ts = td->td_sched;
1917 	td->td_flags &= ~TDF_CANSWAP;
1918 	/*
1919 	 * If we slept for more than a tick update our interactivity and
1920 	 * priority.
1921 	 */
1922 	slptick = td->td_slptick;
1923 	td->td_slptick = 0;
1924 	if (slptick && slptick != ticks) {
1925 		u_int hzticks;
1926 
1927 		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1928 		ts->ts_slptime += hzticks;
1929 		sched_interact_update(td);
1930 		sched_pctcpu_update(ts);
1931 	}
1932 	/* Reset the slice value after we sleep. */
1933 	ts->ts_slice = sched_slice;
1934 	sched_add(td, SRQ_BORING);
1935 }
1936 
1937 /*
1938  * Penalize the parent for creating a new child and initialize the child's
1939  * priority.
1940  */
1941 void
1942 sched_fork(struct thread *td, struct thread *child)
1943 {
1944 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1945 	sched_fork_thread(td, child);
1946 	/*
1947 	 * Penalize the parent and child for forking.
1948 	 */
1949 	sched_interact_fork(child);
1950 	sched_priority(child);
1951 	td->td_sched->ts_runtime += tickincr;
1952 	sched_interact_update(td);
1953 	sched_priority(td);
1954 }
1955 
1956 /*
1957  * Fork a new thread, may be within the same process.
1958  */
1959 void
1960 sched_fork_thread(struct thread *td, struct thread *child)
1961 {
1962 	struct td_sched *ts;
1963 	struct td_sched *ts2;
1964 
1965 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1966 	/*
1967 	 * Initialize child.
1968 	 */
1969 	ts = td->td_sched;
1970 	ts2 = child->td_sched;
1971 	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1972 	child->td_cpuset = cpuset_ref(td->td_cpuset);
1973 	ts2->ts_cpu = ts->ts_cpu;
1974 	ts2->ts_flags = 0;
1975 	/*
1976 	 * Grab our parents cpu estimation information and priority.
1977 	 */
1978 	ts2->ts_ticks = ts->ts_ticks;
1979 	ts2->ts_ltick = ts->ts_ltick;
1980 	ts2->ts_ftick = ts->ts_ftick;
1981 	child->td_user_pri = td->td_user_pri;
1982 	child->td_base_user_pri = td->td_base_user_pri;
1983 	/*
1984 	 * And update interactivity score.
1985 	 */
1986 	ts2->ts_slptime = ts->ts_slptime;
1987 	ts2->ts_runtime = ts->ts_runtime;
1988 	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
1989 }
1990 
1991 /*
1992  * Adjust the priority class of a thread.
1993  */
1994 void
1995 sched_class(struct thread *td, int class)
1996 {
1997 
1998 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1999 	if (td->td_pri_class == class)
2000 		return;
2001 	td->td_pri_class = class;
2002 }
2003 
2004 /*
2005  * Return some of the child's priority and interactivity to the parent.
2006  */
2007 void
2008 sched_exit(struct proc *p, struct thread *child)
2009 {
2010 	struct thread *td;
2011 
2012 	CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
2013 	    child, child->td_name, child->td_priority);
2014 
2015 	PROC_LOCK_ASSERT(p, MA_OWNED);
2016 	td = FIRST_THREAD_IN_PROC(p);
2017 	sched_exit_thread(td, child);
2018 }
2019 
2020 /*
2021  * Penalize another thread for the time spent on this one.  This helps to
2022  * worsen the priority and interactivity of processes which schedule batch
2023  * jobs such as make.  This has little effect on the make process itself but
2024  * causes new processes spawned by it to receive worse scores immediately.
2025  */
2026 void
2027 sched_exit_thread(struct thread *td, struct thread *child)
2028 {
2029 
2030 	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
2031 	    child, child->td_name, child->td_priority);
2032 
2033 	/*
2034 	 * Give the child's runtime to the parent without returning the
2035 	 * sleep time as a penalty to the parent.  This causes shells that
2036 	 * launch expensive things to mark their children as expensive.
2037 	 */
2038 	thread_lock(td);
2039 	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2040 	sched_interact_update(td);
2041 	sched_priority(td);
2042 	thread_unlock(td);
2043 }
2044 
2045 void
2046 sched_preempt(struct thread *td)
2047 {
2048 	struct tdq *tdq;
2049 
2050 	thread_lock(td);
2051 	tdq = TDQ_SELF();
2052 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2053 	tdq->tdq_ipipending = 0;
2054 	if (td->td_priority > tdq->tdq_lowpri) {
2055 		int flags;
2056 
2057 		flags = SW_INVOL | SW_PREEMPT;
2058 		if (td->td_critnest > 1)
2059 			td->td_owepreempt = 1;
2060 		else if (TD_IS_IDLETHREAD(td))
2061 			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2062 		else
2063 			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2064 	}
2065 	thread_unlock(td);
2066 }
2067 
2068 /*
2069  * Fix priorities on return to user-space.  Priorities may be elevated due
2070  * to static priorities in msleep() or similar.
2071  */
2072 void
2073 sched_userret(struct thread *td)
2074 {
2075 	/*
2076 	 * XXX we cheat slightly on the locking here to avoid locking in
2077 	 * the usual case.  Setting td_priority here is essentially an
2078 	 * incomplete workaround for not setting it properly elsewhere.
2079 	 * Now that some interrupt handlers are threads, not setting it
2080 	 * properly elsewhere can clobber it in the window between setting
2081 	 * it here and returning to user mode, so don't waste time setting
2082 	 * it perfectly here.
2083 	 */
2084 	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2085 	    ("thread with borrowed priority returning to userland"));
2086 	if (td->td_priority != td->td_user_pri) {
2087 		thread_lock(td);
2088 		td->td_priority = td->td_user_pri;
2089 		td->td_base_pri = td->td_user_pri;
2090 		tdq_setlowpri(TDQ_SELF(), td);
2091 		thread_unlock(td);
2092         }
2093 }
2094 
2095 /*
2096  * Handle a stathz tick.  This is really only relevant for timeshare
2097  * threads.
2098  */
2099 void
2100 sched_clock(struct thread *td)
2101 {
2102 	struct tdq *tdq;
2103 	struct td_sched *ts;
2104 
2105 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2106 	tdq = TDQ_SELF();
2107 #ifdef SMP
2108 	/*
2109 	 * We run the long term load balancer infrequently on the first cpu.
2110 	 */
2111 	if (balance_tdq == tdq) {
2112 		if (balance_ticks && --balance_ticks == 0)
2113 			sched_balance();
2114 	}
2115 #endif
2116 	/*
2117 	 * Save the old switch count so we have a record of the last ticks
2118 	 * activity.   Initialize the new switch count based on our load.
2119 	 * If there is some activity seed it to reflect that.
2120 	 */
2121 	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
2122 	tdq->tdq_switchcnt = tdq->tdq_load;
2123 	/*
2124 	 * Advance the insert index once for each tick to ensure that all
2125 	 * threads get a chance to run.
2126 	 */
2127 	if (tdq->tdq_idx == tdq->tdq_ridx) {
2128 		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2129 		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2130 			tdq->tdq_ridx = tdq->tdq_idx;
2131 	}
2132 	ts = td->td_sched;
2133 	if (td->td_pri_class & PRI_FIFO_BIT)
2134 		return;
2135 	if (td->td_pri_class == PRI_TIMESHARE) {
2136 		/*
2137 		 * We used a tick; charge it to the thread so
2138 		 * that we can compute our interactivity.
2139 		 */
2140 		td->td_sched->ts_runtime += tickincr;
2141 		sched_interact_update(td);
2142 		sched_priority(td);
2143 	}
2144 	/*
2145 	 * We used up one time slice.
2146 	 */
2147 	if (--ts->ts_slice > 0)
2148 		return;
2149 	/*
2150 	 * We're out of time, force a requeue at userret().
2151 	 */
2152 	ts->ts_slice = sched_slice;
2153 	td->td_flags |= TDF_NEEDRESCHED;
2154 }
2155 
2156 /*
2157  * Called once per hz tick.  Used for cpu utilization information.  This
2158  * is easier than trying to scale based on stathz.
2159  */
2160 void
2161 sched_tick(void)
2162 {
2163 	struct td_sched *ts;
2164 
2165 	ts = curthread->td_sched;
2166 	/*
2167 	 * Ticks is updated asynchronously on a single cpu.  Check here to
2168 	 * avoid incrementing ts_ticks multiple times in a single tick.
2169 	 */
2170 	if (ts->ts_ltick == ticks)
2171 		return;
2172 	/* Adjust ticks for pctcpu */
2173 	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2174 	ts->ts_ltick = ticks;
2175 	/*
2176 	 * Update if we've exceeded our desired tick threshhold by over one
2177 	 * second.
2178 	 */
2179 	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2180 		sched_pctcpu_update(ts);
2181 }
2182 
2183 /*
2184  * Return whether the current CPU has runnable tasks.  Used for in-kernel
2185  * cooperative idle threads.
2186  */
2187 int
2188 sched_runnable(void)
2189 {
2190 	struct tdq *tdq;
2191 	int load;
2192 
2193 	load = 1;
2194 
2195 	tdq = TDQ_SELF();
2196 	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2197 		if (tdq->tdq_load > 0)
2198 			goto out;
2199 	} else
2200 		if (tdq->tdq_load - 1 > 0)
2201 			goto out;
2202 	load = 0;
2203 out:
2204 	return (load);
2205 }
2206 
2207 /*
2208  * Choose the highest priority thread to run.  The thread is removed from
2209  * the run-queue while running however the load remains.  For SMP we set
2210  * the tdq in the global idle bitmask if it idles here.
2211  */
2212 struct thread *
2213 sched_choose(void)
2214 {
2215 	struct thread *td;
2216 	struct tdq *tdq;
2217 
2218 	tdq = TDQ_SELF();
2219 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2220 	td = tdq_choose(tdq);
2221 	if (td) {
2222 		td->td_sched->ts_ltick = ticks;
2223 		tdq_runq_rem(tdq, td);
2224 		tdq->tdq_lowpri = td->td_priority;
2225 		return (td);
2226 	}
2227 	tdq->tdq_lowpri = PRI_MAX_IDLE;
2228 	return (PCPU_GET(idlethread));
2229 }
2230 
2231 /*
2232  * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2233  * we always request it once we exit a critical section.
2234  */
2235 static inline void
2236 sched_setpreempt(struct thread *td)
2237 {
2238 	struct thread *ctd;
2239 	int cpri;
2240 	int pri;
2241 
2242 	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2243 
2244 	ctd = curthread;
2245 	pri = td->td_priority;
2246 	cpri = ctd->td_priority;
2247 	if (pri < cpri)
2248 		ctd->td_flags |= TDF_NEEDRESCHED;
2249 	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2250 		return;
2251 	if (!sched_shouldpreempt(pri, cpri, 0))
2252 		return;
2253 	ctd->td_owepreempt = 1;
2254 }
2255 
2256 /*
2257  * Add a thread to a thread queue.  Select the appropriate runq and add the
2258  * thread to it.  This is the internal function called when the tdq is
2259  * predetermined.
2260  */
2261 void
2262 tdq_add(struct tdq *tdq, struct thread *td, int flags)
2263 {
2264 
2265 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2266 	KASSERT((td->td_inhibitors == 0),
2267 	    ("sched_add: trying to run inhibited thread"));
2268 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2269 	    ("sched_add: bad thread state"));
2270 	KASSERT(td->td_flags & TDF_INMEM,
2271 	    ("sched_add: thread swapped out"));
2272 
2273 	if (td->td_priority < tdq->tdq_lowpri)
2274 		tdq->tdq_lowpri = td->td_priority;
2275 	tdq_runq_add(tdq, td, flags);
2276 	tdq_load_add(tdq, td);
2277 }
2278 
2279 /*
2280  * Select the target thread queue and add a thread to it.  Request
2281  * preemption or IPI a remote processor if required.
2282  */
2283 void
2284 sched_add(struct thread *td, int flags)
2285 {
2286 	struct tdq *tdq;
2287 #ifdef SMP
2288 	int cpu;
2289 #endif
2290 	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
2291 	    td, td->td_name, td->td_priority, curthread,
2292 	    curthread->td_name);
2293 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2294 	/*
2295 	 * Recalculate the priority before we select the target cpu or
2296 	 * run-queue.
2297 	 */
2298 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2299 		sched_priority(td);
2300 #ifdef SMP
2301 	/*
2302 	 * Pick the destination cpu and if it isn't ours transfer to the
2303 	 * target cpu.
2304 	 */
2305 	cpu = sched_pickcpu(td, flags);
2306 	tdq = sched_setcpu(td, cpu, flags);
2307 	tdq_add(tdq, td, flags);
2308 	if (cpu != PCPU_GET(cpuid)) {
2309 		tdq_notify(tdq, td);
2310 		return;
2311 	}
2312 #else
2313 	tdq = TDQ_SELF();
2314 	TDQ_LOCK(tdq);
2315 	/*
2316 	 * Now that the thread is moving to the run-queue, set the lock
2317 	 * to the scheduler's lock.
2318 	 */
2319 	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2320 	tdq_add(tdq, td, flags);
2321 #endif
2322 	if (!(flags & SRQ_YIELDING))
2323 		sched_setpreempt(td);
2324 }
2325 
2326 /*
2327  * Remove a thread from a run-queue without running it.  This is used
2328  * when we're stealing a thread from a remote queue.  Otherwise all threads
2329  * exit by calling sched_exit_thread() and sched_throw() themselves.
2330  */
2331 void
2332 sched_rem(struct thread *td)
2333 {
2334 	struct tdq *tdq;
2335 
2336 	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
2337 	    td, td->td_name, td->td_priority, curthread,
2338 	    curthread->td_name);
2339 	tdq = TDQ_CPU(td->td_sched->ts_cpu);
2340 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2341 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2342 	KASSERT(TD_ON_RUNQ(td),
2343 	    ("sched_rem: thread not on run queue"));
2344 	tdq_runq_rem(tdq, td);
2345 	tdq_load_rem(tdq, td);
2346 	TD_SET_CAN_RUN(td);
2347 	if (td->td_priority == tdq->tdq_lowpri)
2348 		tdq_setlowpri(tdq, NULL);
2349 }
2350 
2351 /*
2352  * Fetch cpu utilization information.  Updates on demand.
2353  */
2354 fixpt_t
2355 sched_pctcpu(struct thread *td)
2356 {
2357 	fixpt_t pctcpu;
2358 	struct td_sched *ts;
2359 
2360 	pctcpu = 0;
2361 	ts = td->td_sched;
2362 	if (ts == NULL)
2363 		return (0);
2364 
2365 	thread_lock(td);
2366 	if (ts->ts_ticks) {
2367 		int rtick;
2368 
2369 		sched_pctcpu_update(ts);
2370 		/* How many rtick per second ? */
2371 		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2372 		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2373 	}
2374 	thread_unlock(td);
2375 
2376 	return (pctcpu);
2377 }
2378 
2379 /*
2380  * Enforce affinity settings for a thread.  Called after adjustments to
2381  * cpumask.
2382  */
2383 void
2384 sched_affinity(struct thread *td)
2385 {
2386 #ifdef SMP
2387 	struct td_sched *ts;
2388 	int cpu;
2389 
2390 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2391 	ts = td->td_sched;
2392 	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2393 		return;
2394 	if (!TD_IS_RUNNING(td))
2395 		return;
2396 	td->td_flags |= TDF_NEEDRESCHED;
2397 	if (!THREAD_CAN_MIGRATE(td))
2398 		return;
2399 	/*
2400 	 * Assign the new cpu and force a switch before returning to
2401 	 * userspace.  If the target thread is not running locally send
2402 	 * an ipi to force the issue.
2403 	 */
2404 	cpu = ts->ts_cpu;
2405 	ts->ts_cpu = sched_pickcpu(td, 0);
2406 	if (cpu != PCPU_GET(cpuid))
2407 		ipi_selected(1 << cpu, IPI_PREEMPT);
2408 #endif
2409 }
2410 
2411 /*
2412  * Bind a thread to a target cpu.
2413  */
2414 void
2415 sched_bind(struct thread *td, int cpu)
2416 {
2417 	struct td_sched *ts;
2418 
2419 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2420 	ts = td->td_sched;
2421 	if (ts->ts_flags & TSF_BOUND)
2422 		sched_unbind(td);
2423 	ts->ts_flags |= TSF_BOUND;
2424 	sched_pin();
2425 	if (PCPU_GET(cpuid) == cpu)
2426 		return;
2427 	ts->ts_cpu = cpu;
2428 	/* When we return from mi_switch we'll be on the correct cpu. */
2429 	mi_switch(SW_VOL, NULL);
2430 }
2431 
2432 /*
2433  * Release a bound thread.
2434  */
2435 void
2436 sched_unbind(struct thread *td)
2437 {
2438 	struct td_sched *ts;
2439 
2440 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2441 	ts = td->td_sched;
2442 	if ((ts->ts_flags & TSF_BOUND) == 0)
2443 		return;
2444 	ts->ts_flags &= ~TSF_BOUND;
2445 	sched_unpin();
2446 }
2447 
2448 int
2449 sched_is_bound(struct thread *td)
2450 {
2451 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2452 	return (td->td_sched->ts_flags & TSF_BOUND);
2453 }
2454 
2455 /*
2456  * Basic yield call.
2457  */
2458 void
2459 sched_relinquish(struct thread *td)
2460 {
2461 	thread_lock(td);
2462 	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
2463 	thread_unlock(td);
2464 }
2465 
2466 /*
2467  * Return the total system load.
2468  */
2469 int
2470 sched_load(void)
2471 {
2472 #ifdef SMP
2473 	int total;
2474 	int i;
2475 
2476 	total = 0;
2477 	for (i = 0; i <= mp_maxid; i++)
2478 		total += TDQ_CPU(i)->tdq_sysload;
2479 	return (total);
2480 #else
2481 	return (TDQ_SELF()->tdq_sysload);
2482 #endif
2483 }
2484 
2485 int
2486 sched_sizeof_proc(void)
2487 {
2488 	return (sizeof(struct proc));
2489 }
2490 
2491 int
2492 sched_sizeof_thread(void)
2493 {
2494 	return (sizeof(struct thread) + sizeof(struct td_sched));
2495 }
2496 
2497 /*
2498  * The actual idle process.
2499  */
2500 void
2501 sched_idletd(void *dummy)
2502 {
2503 	struct thread *td;
2504 	struct tdq *tdq;
2505 	int switchcnt;
2506 	int i;
2507 
2508 	td = curthread;
2509 	tdq = TDQ_SELF();
2510 	mtx_assert(&Giant, MA_NOTOWNED);
2511 	/* ULE relies on preemption for idle interruption. */
2512 	for (;;) {
2513 		tdq->tdq_idlestate = TDQ_RUNNING;
2514 #ifdef SMP
2515 		if (tdq_idled(tdq) == 0)
2516 			continue;
2517 #endif
2518 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2519 		/*
2520 		 * If we're switching very frequently, spin while checking
2521 		 * for load rather than entering a low power state that
2522 		 * requires an IPI.
2523 		 */
2524 		if (switchcnt > sched_idlespinthresh) {
2525 			for (i = 0; i < sched_idlespins; i++) {
2526 				if (tdq->tdq_load)
2527 					break;
2528 				cpu_spinwait();
2529 			}
2530 		}
2531 		/*
2532 		 * We must set our state to IDLE before checking
2533 		 * tdq_load for the last time to avoid a race with
2534 		 * tdq_notify().
2535 		 */
2536 		if (tdq->tdq_load == 0) {
2537 			switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2538 			tdq->tdq_idlestate = TDQ_IDLE;
2539 			if (tdq->tdq_load == 0)
2540 				cpu_idle(switchcnt > 1);
2541 		}
2542 		if (tdq->tdq_load) {
2543 			thread_lock(td);
2544 			mi_switch(SW_VOL | SWT_IDLE, NULL);
2545 			thread_unlock(td);
2546 		}
2547 	}
2548 }
2549 
2550 /*
2551  * A CPU is entering for the first time or a thread is exiting.
2552  */
2553 void
2554 sched_throw(struct thread *td)
2555 {
2556 	struct thread *newtd;
2557 	struct tdq *tdq;
2558 
2559 	tdq = TDQ_SELF();
2560 	if (td == NULL) {
2561 		/* Correct spinlock nesting and acquire the correct lock. */
2562 		TDQ_LOCK(tdq);
2563 		spinlock_exit();
2564 	} else {
2565 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2566 		tdq_load_rem(tdq, td);
2567 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2568 	}
2569 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2570 	newtd = choosethread();
2571 	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2572 	PCPU_SET(switchtime, cpu_ticks());
2573 	PCPU_SET(switchticks, ticks);
2574 	cpu_throw(td, newtd);		/* doesn't return */
2575 }
2576 
2577 /*
2578  * This is called from fork_exit().  Just acquire the correct locks and
2579  * let fork do the rest of the work.
2580  */
2581 void
2582 sched_fork_exit(struct thread *td)
2583 {
2584 	struct td_sched *ts;
2585 	struct tdq *tdq;
2586 	int cpuid;
2587 
2588 	/*
2589 	 * Finish setting up thread glue so that it begins execution in a
2590 	 * non-nested critical section with the scheduler lock held.
2591 	 */
2592 	cpuid = PCPU_GET(cpuid);
2593 	tdq = TDQ_CPU(cpuid);
2594 	ts = td->td_sched;
2595 	if (TD_IS_IDLETHREAD(td))
2596 		td->td_lock = TDQ_LOCKPTR(tdq);
2597 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2598 	td->td_oncpu = cpuid;
2599 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2600 	lock_profile_obtain_lock_success(
2601 	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2602 }
2603 
2604 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2605 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2606     "Scheduler name");
2607 SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2608     "Slice size for timeshare threads");
2609 SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2610      "Interactivity score threshold");
2611 SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2612      0,"Min priority for preemption, lower priorities have greater precedence");
2613 SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost,
2614      0,"Controls whether static kernel priorities are assigned to sleeping threads.");
2615 SYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins,
2616      0,"Number of times idle will spin waiting for new work.");
2617 SYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW, &sched_idlespinthresh,
2618      0,"Threshold before we will permit idle spinning.");
2619 #ifdef SMP
2620 SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2621     "Number of hz ticks to keep thread affinity for");
2622 SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2623     "Enables the long-term load balancer");
2624 SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2625     &balance_interval, 0,
2626     "Average frequency in stathz ticks to run the long-term balancer");
2627 SYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2628     "Steals work from another hyper-threaded core on idle");
2629 SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2630     "Attempts to steal work from other cores before idling");
2631 SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2632     "Minimum load on remote cpu before we'll steal");
2633 #endif
2634 
2635 /* ps compat.  All cpu percentages from ULE are weighted. */
2636 static int ccpu = 0;
2637 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2638