sched_ule.c revision 217291
1109864Sjeff/*-
2165762Sjeff * Copyright (c) 2002-2007, Jeffrey Roberson <jeff@freebsd.org>
3109864Sjeff * All rights reserved.
4109864Sjeff *
5109864Sjeff * Redistribution and use in source and binary forms, with or without
6109864Sjeff * modification, are permitted provided that the following conditions
7109864Sjeff * are met:
8109864Sjeff * 1. Redistributions of source code must retain the above copyright
9109864Sjeff *    notice unmodified, this list of conditions, and the following
10109864Sjeff *    disclaimer.
11109864Sjeff * 2. Redistributions in binary form must reproduce the above copyright
12109864Sjeff *    notice, this list of conditions and the following disclaimer in the
13109864Sjeff *    documentation and/or other materials provided with the distribution.
14109864Sjeff *
15109864Sjeff * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16109864Sjeff * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17109864Sjeff * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18109864Sjeff * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19109864Sjeff * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20109864Sjeff * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21109864Sjeff * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22109864Sjeff * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23109864Sjeff * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24109864Sjeff * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25109864Sjeff */
26109864Sjeff
27171482Sjeff/*
28171482Sjeff * This file implements the ULE scheduler.  ULE supports independent CPU
29171482Sjeff * run queues and fine grain locking.  It has superior interactive
30171482Sjeff * performance under load even on uni-processor systems.
31171482Sjeff *
32171482Sjeff * etymology:
33172293Sjeff *   ULE is the last three letters in schedule.  It owes its name to a
34171482Sjeff * generic user created for a scheduling system by Paul Mikesell at
35171482Sjeff * Isilon Systems and a general lack of creativity on the part of the author.
36171482Sjeff */
37171482Sjeff
38116182Sobrien#include <sys/cdefs.h>
39191645Sjeff__FBSDID("$FreeBSD: head/sys/kern/sched_ule.c 217291 2011-01-11 22:13:19Z jhb $");
40116182Sobrien
41147565Speter#include "opt_hwpmc_hooks.h"
42179297Sjb#include "opt_kdtrace.h"
43147565Speter#include "opt_sched.h"
44134649Sscottl
45109864Sjeff#include <sys/param.h>
46109864Sjeff#include <sys/systm.h>
47131929Smarcel#include <sys/kdb.h>
48109864Sjeff#include <sys/kernel.h>
49109864Sjeff#include <sys/ktr.h>
50109864Sjeff#include <sys/lock.h>
51109864Sjeff#include <sys/mutex.h>
52109864Sjeff#include <sys/proc.h>
53112966Sjeff#include <sys/resource.h>
54122038Sjeff#include <sys/resourcevar.h>
55109864Sjeff#include <sys/sched.h>
56109864Sjeff#include <sys/smp.h>
57109864Sjeff#include <sys/sx.h>
58109864Sjeff#include <sys/sysctl.h>
59109864Sjeff#include <sys/sysproto.h>
60139453Sjhb#include <sys/turnstile.h>
61161599Sdavidxu#include <sys/umtx.h>
62109864Sjeff#include <sys/vmmeter.h>
63176735Sjeff#include <sys/cpuset.h>
64184439Sivoras#include <sys/sbuf.h>
65109864Sjeff
66145256Sjkoshy#ifdef HWPMC_HOOKS
67145256Sjkoshy#include <sys/pmckern.h>
68145256Sjkoshy#endif
69145256Sjkoshy
70179297Sjb#ifdef KDTRACE_HOOKS
71179297Sjb#include <sys/dtrace_bsd.h>
72179297Sjbint				dtrace_vtime_active;
73179297Sjbdtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
74179297Sjb#endif
75179297Sjb
76109864Sjeff#include <machine/cpu.h>
77121790Sjeff#include <machine/smp.h>
78109864Sjeff
79208165Srrs#if defined(__sparc64__)
80172345Sjeff#error "This architecture is not currently compatible with ULE"
81166190Sjeff#endif
82166190Sjeff
83171482Sjeff#define	KTR_ULE	0
84166137Sjeff
85187679Sjeff#define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
86187679Sjeff#define	TDQ_NAME_LEN	(sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
87187357Sjeff#define	TDQ_LOADNAME_LEN	(PCPU_NAME_LEN + sizeof(" load"))
88187357Sjeff
89166137Sjeff/*
90171482Sjeff * Thread scheduler specific section.  All fields are protected
91171482Sjeff * by the thread lock.
92146954Sjeff */
93164936Sjulianstruct td_sched {
94171482Sjeff	struct runq	*ts_runq;	/* Run-queue we're queued on. */
95171482Sjeff	short		ts_flags;	/* TSF_* flags. */
96164936Sjulian	u_char		ts_cpu;		/* CPU that we have affinity for. */
97177009Sjeff	int		ts_rltick;	/* Real last tick, for affinity. */
98171482Sjeff	int		ts_slice;	/* Ticks of slice remaining. */
99171482Sjeff	u_int		ts_slptime;	/* Number of ticks we vol. slept */
100171482Sjeff	u_int		ts_runtime;	/* Number of ticks we were running */
101164936Sjulian	int		ts_ltick;	/* Last tick that we were running on */
102199764Sivoras	int		ts_incrtick;	/* Last tick that we incremented on */
103164936Sjulian	int		ts_ftick;	/* First tick that we were running on */
104164936Sjulian	int		ts_ticks;	/* Tick count */
105187357Sjeff#ifdef KTR
106187357Sjeff	char		ts_name[TS_NAME_LEN];
107187357Sjeff#endif
108134791Sjulian};
109164936Sjulian/* flags kept in ts_flags */
110166108Sjeff#define	TSF_BOUND	0x0001		/* Thread can not migrate. */
111166108Sjeff#define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
112121790Sjeff
113164936Sjulianstatic struct td_sched td_sched0;
114109864Sjeff
115176735Sjeff#define	THREAD_CAN_MIGRATE(td)	((td)->td_pinned == 0)
116176735Sjeff#define	THREAD_CAN_SCHED(td, cpu)	\
117176735Sjeff    CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
118176735Sjeff
119109864Sjeff/*
120165762Sjeff * Cpu percentage computation macros and defines.
121111857Sjeff *
122165762Sjeff * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
123165762Sjeff * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
124165796Sjeff * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
125165762Sjeff * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
126165762Sjeff * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
127165762Sjeff * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
128165762Sjeff */
129165762Sjeff#define	SCHED_TICK_SECS		10
130165762Sjeff#define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
131165796Sjeff#define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
132165762Sjeff#define	SCHED_TICK_SHIFT	10
133165762Sjeff#define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
134165830Sjeff#define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
135165762Sjeff
136165762Sjeff/*
137165762Sjeff * These macros determine priorities for non-interactive threads.  They are
138165762Sjeff * assigned a priority based on their recent cpu utilization as expressed
139165762Sjeff * by the ratio of ticks to the tick total.  NHALF priorities at the start
140165762Sjeff * and end of the MIN to MAX timeshare range are only reachable with negative
141165762Sjeff * or positive nice respectively.
142165762Sjeff *
143165762Sjeff * PRI_RANGE:	Priority range for utilization dependent priorities.
144116642Sjeff * PRI_NRESV:	Number of nice values.
145165762Sjeff * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
146165762Sjeff * PRI_NICE:	Determines the part of the priority inherited from nice.
147109864Sjeff */
148165762Sjeff#define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
149121869Sjeff#define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
150165762Sjeff#define	SCHED_PRI_MIN		(PRI_MIN_TIMESHARE + SCHED_PRI_NHALF)
151165762Sjeff#define	SCHED_PRI_MAX		(PRI_MAX_TIMESHARE - SCHED_PRI_NHALF)
152217237Sjhb#define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN + 1)
153165762Sjeff#define	SCHED_PRI_TICKS(ts)						\
154165762Sjeff    (SCHED_TICK_HZ((ts)) /						\
155165827Sjeff    (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
156165762Sjeff#define	SCHED_PRI_NICE(nice)	(nice)
157109864Sjeff
158109864Sjeff/*
159165762Sjeff * These determine the interactivity of a process.  Interactivity differs from
160165762Sjeff * cpu utilization in that it expresses the voluntary time slept vs time ran
161165762Sjeff * while cpu utilization includes all time not running.  This more accurately
162165762Sjeff * models the intent of the thread.
163109864Sjeff *
164110645Sjeff * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
165110645Sjeff *		before throttling back.
166121868Sjeff * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
167116365Sjeff * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
168215102Sattilio * INTERACT_THRESH:	Threshold for placement on the current runq.
169109864Sjeff */
170165762Sjeff#define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
171165762Sjeff#define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
172116365Sjeff#define	SCHED_INTERACT_MAX	(100)
173116365Sjeff#define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
174121126Sjeff#define	SCHED_INTERACT_THRESH	(30)
175111857Sjeff
176109864Sjeff/*
177165762Sjeff * tickincr:		Converts a stathz tick into a hz domain scaled by
178165762Sjeff *			the shift factor.  Without the shift the error rate
179165762Sjeff *			due to rounding would be unacceptably high.
180165762Sjeff * realstathz:		stathz is sometimes 0 and run off of hz.
181165762Sjeff * sched_slice:		Runtime of each thread before rescheduling.
182171482Sjeff * preempt_thresh:	Priority threshold for preemption and remote IPIs.
183109864Sjeff */
184165762Sjeffstatic int sched_interact = SCHED_INTERACT_THRESH;
185165762Sjeffstatic int realstathz;
186165762Sjeffstatic int tickincr;
187177009Sjeffstatic int sched_slice = 1;
188172345Sjeff#ifdef PREEMPTION
189172345Sjeff#ifdef FULL_PREEMPTION
190172345Sjeffstatic int preempt_thresh = PRI_MAX_IDLE;
191172345Sjeff#else
192171482Sjeffstatic int preempt_thresh = PRI_MIN_KERN;
193172345Sjeff#endif
194172345Sjeff#else
195172345Sjeffstatic int preempt_thresh = 0;
196172345Sjeff#endif
197177903Sjeffstatic int static_boost = PRI_MIN_TIMESHARE;
198178277Sjeffstatic int sched_idlespins = 10000;
199212541Smavstatic int sched_idlespinthresh = 16;
200109864Sjeff
201109864Sjeff/*
202171482Sjeff * tdq - per processor runqs and statistics.  All fields are protected by the
203171482Sjeff * tdq_lock.  The load and lowpri may be accessed without to avoid excess
204171482Sjeff * locking in sched_pickcpu();
205109864Sjeff */
206164936Sjulianstruct tdq {
207177009Sjeff	/* Ordered to improve efficiency of cpu_search() and switch(). */
208177009Sjeff	struct mtx	tdq_lock;		/* run queue lock. */
209176735Sjeff	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
210178277Sjeff	volatile int	tdq_load;		/* Aggregate load. */
211212416Smav	volatile int	tdq_cpu_idle;		/* cpu_idle() is active. */
212176735Sjeff	int		tdq_sysload;		/* For loadavg, !ITHD load. */
213177009Sjeff	int		tdq_transferable;	/* Transferable thread count. */
214178277Sjeff	short		tdq_switchcnt;		/* Switches this tick. */
215178277Sjeff	short		tdq_oldswitchcnt;	/* Switches last tick. */
216177009Sjeff	u_char		tdq_lowpri;		/* Lowest priority thread. */
217177009Sjeff	u_char		tdq_ipipending;		/* IPI pending. */
218166557Sjeff	u_char		tdq_idx;		/* Current insert index. */
219166557Sjeff	u_char		tdq_ridx;		/* Current removal index. */
220177009Sjeff	struct runq	tdq_realtime;		/* real-time run queue. */
221177009Sjeff	struct runq	tdq_timeshare;		/* timeshare run queue. */
222177009Sjeff	struct runq	tdq_idle;		/* Queue of IDLE threads. */
223187357Sjeff	char		tdq_name[TDQ_NAME_LEN];
224187357Sjeff#ifdef KTR
225187357Sjeff	char		tdq_loadname[TDQ_LOADNAME_LEN];
226187357Sjeff#endif
227171482Sjeff} __aligned(64);
228109864Sjeff
229178277Sjeff/* Idle thread states and config. */
230178277Sjeff#define	TDQ_RUNNING	1
231178277Sjeff#define	TDQ_IDLE	2
232166108Sjeff
233123433Sjeff#ifdef SMP
234184439Sivorasstruct cpu_group *cpu_top;		/* CPU topology */
235123433Sjeff
236176735Sjeff#define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
237176735Sjeff#define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
238166108Sjeff
239123433Sjeff/*
240166108Sjeff * Run-time tunables.
241166108Sjeff */
242171506Sjeffstatic int rebalance = 1;
243172409Sjeffstatic int balance_interval = 128;	/* Default set in sched_initticks(). */
244166108Sjeffstatic int affinity;
245172409Sjeffstatic int steal_htt = 1;
246171506Sjeffstatic int steal_idle = 1;
247171506Sjeffstatic int steal_thresh = 2;
248166108Sjeff
249166108Sjeff/*
250165620Sjeff * One thread queue per processor.
251109864Sjeff */
252164936Sjulianstatic struct tdq	tdq_cpu[MAXCPU];
253172409Sjeffstatic struct tdq	*balance_tdq;
254172409Sjeffstatic int balance_ticks;
255129982Sjeff
256164936Sjulian#define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
257164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu[(x)])
258171713Sjeff#define	TDQ_ID(x)	((int)((x) - tdq_cpu))
259123433Sjeff#else	/* !SMP */
260164936Sjulianstatic struct tdq	tdq_cpu;
261129982Sjeff
262170315Sjeff#define	TDQ_ID(x)	(0)
263164936Sjulian#define	TDQ_SELF()	(&tdq_cpu)
264164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu)
265110028Sjeff#endif
266109864Sjeff
267171482Sjeff#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
268171482Sjeff#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
269171482Sjeff#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
270171482Sjeff#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
271176735Sjeff#define	TDQ_LOCKPTR(t)		(&(t)->tdq_lock)
272171482Sjeff
273163709Sjbstatic void sched_priority(struct thread *);
274146954Sjeffstatic void sched_thread_priority(struct thread *, u_char);
275163709Sjbstatic int sched_interact_score(struct thread *);
276163709Sjbstatic void sched_interact_update(struct thread *);
277163709Sjbstatic void sched_interact_fork(struct thread *);
278164936Sjulianstatic void sched_pctcpu_update(struct td_sched *);
279109864Sjeff
280110267Sjeff/* Operations on per processor queues */
281177435Sjeffstatic struct thread *tdq_choose(struct tdq *);
282164936Sjulianstatic void tdq_setup(struct tdq *);
283177435Sjeffstatic void tdq_load_add(struct tdq *, struct thread *);
284177435Sjeffstatic void tdq_load_rem(struct tdq *, struct thread *);
285177435Sjeffstatic __inline void tdq_runq_add(struct tdq *, struct thread *, int);
286177435Sjeffstatic __inline void tdq_runq_rem(struct tdq *, struct thread *);
287177005Sjeffstatic inline int sched_shouldpreempt(int, int, int);
288164936Sjulianvoid tdq_print(int cpu);
289165762Sjeffstatic void runq_print(struct runq *rq);
290171482Sjeffstatic void tdq_add(struct tdq *, struct thread *, int);
291110267Sjeff#ifdef SMP
292176735Sjeffstatic int tdq_move(struct tdq *, struct tdq *);
293171482Sjeffstatic int tdq_idled(struct tdq *);
294177435Sjeffstatic void tdq_notify(struct tdq *, struct thread *);
295177435Sjeffstatic struct thread *tdq_steal(struct tdq *, int);
296177435Sjeffstatic struct thread *runq_steal(struct runq *, int);
297177435Sjeffstatic int sched_pickcpu(struct thread *, int);
298172409Sjeffstatic void sched_balance(void);
299176735Sjeffstatic int sched_balance_pair(struct tdq *, struct tdq *);
300177435Sjeffstatic inline struct tdq *sched_setcpu(struct thread *, int, int);
301171482Sjeffstatic inline void thread_unblock_switch(struct thread *, struct mtx *);
302171713Sjeffstatic struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
303184439Sivorasstatic int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
304184439Sivorasstatic int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
305184439Sivoras    struct cpu_group *cg, int indent);
306121790Sjeff#endif
307110028Sjeff
308165762Sjeffstatic void sched_setup(void *dummy);
309177253SrwatsonSYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
310165762Sjeff
311165762Sjeffstatic void sched_initticks(void *dummy);
312177253SrwatsonSYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
313177253Srwatson    NULL);
314165762Sjeff
315171482Sjeff/*
316171482Sjeff * Print the threads waiting on a run-queue.
317171482Sjeff */
318165762Sjeffstatic void
319165762Sjeffrunq_print(struct runq *rq)
320165762Sjeff{
321165762Sjeff	struct rqhead *rqh;
322177435Sjeff	struct thread *td;
323165762Sjeff	int pri;
324165762Sjeff	int j;
325165762Sjeff	int i;
326165762Sjeff
327165762Sjeff	for (i = 0; i < RQB_LEN; i++) {
328165762Sjeff		printf("\t\trunq bits %d 0x%zx\n",
329165762Sjeff		    i, rq->rq_status.rqb_bits[i]);
330165762Sjeff		for (j = 0; j < RQB_BPW; j++)
331165762Sjeff			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
332165762Sjeff				pri = j + (i << RQB_L2BPW);
333165762Sjeff				rqh = &rq->rq_queues[pri];
334177435Sjeff				TAILQ_FOREACH(td, rqh, td_runq) {
335165762Sjeff					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
336177435Sjeff					    td, td->td_name, td->td_priority,
337177435Sjeff					    td->td_rqindex, pri);
338165762Sjeff				}
339165762Sjeff			}
340165762Sjeff	}
341165762Sjeff}
342165762Sjeff
343171482Sjeff/*
344171482Sjeff * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
345171482Sjeff */
346113357Sjeffvoid
347164936Sjuliantdq_print(int cpu)
348110267Sjeff{
349164936Sjulian	struct tdq *tdq;
350112994Sjeff
351164936Sjulian	tdq = TDQ_CPU(cpu);
352112994Sjeff
353171713Sjeff	printf("tdq %d:\n", TDQ_ID(tdq));
354176735Sjeff	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
355176735Sjeff	printf("\tLock name:      %s\n", tdq->tdq_name);
356165620Sjeff	printf("\tload:           %d\n", tdq->tdq_load);
357178277Sjeff	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
358178277Sjeff	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
359171482Sjeff	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
360165766Sjeff	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
361178277Sjeff	printf("\tload transferable: %d\n", tdq->tdq_transferable);
362178277Sjeff	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
363165762Sjeff	printf("\trealtime runq:\n");
364165762Sjeff	runq_print(&tdq->tdq_realtime);
365165762Sjeff	printf("\ttimeshare runq:\n");
366165762Sjeff	runq_print(&tdq->tdq_timeshare);
367165762Sjeff	printf("\tidle runq:\n");
368165762Sjeff	runq_print(&tdq->tdq_idle);
369113357Sjeff}
370112994Sjeff
371177005Sjeffstatic inline int
372177005Sjeffsched_shouldpreempt(int pri, int cpri, int remote)
373177005Sjeff{
374177005Sjeff	/*
375177005Sjeff	 * If the new priority is not better than the current priority there is
376177005Sjeff	 * nothing to do.
377177005Sjeff	 */
378177005Sjeff	if (pri >= cpri)
379177005Sjeff		return (0);
380177005Sjeff	/*
381177005Sjeff	 * Always preempt idle.
382177005Sjeff	 */
383177005Sjeff	if (cpri >= PRI_MIN_IDLE)
384177005Sjeff		return (1);
385177005Sjeff	/*
386177005Sjeff	 * If preemption is disabled don't preempt others.
387177005Sjeff	 */
388177005Sjeff	if (preempt_thresh == 0)
389177005Sjeff		return (0);
390177005Sjeff	/*
391177005Sjeff	 * Preempt if we exceed the threshold.
392177005Sjeff	 */
393177005Sjeff	if (pri <= preempt_thresh)
394177005Sjeff		return (1);
395177005Sjeff	/*
396177005Sjeff	 * If we're realtime or better and there is timeshare or worse running
397177005Sjeff	 * preempt only remote processors.
398177005Sjeff	 */
399177005Sjeff	if (remote && pri <= PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
400177005Sjeff		return (1);
401177005Sjeff	return (0);
402177005Sjeff}
403177005Sjeff
404171482Sjeff#define	TS_RQ_PPQ	(((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
405171482Sjeff/*
406171482Sjeff * Add a thread to the actual run-queue.  Keeps transferable counts up to
407171482Sjeff * date with what is actually on the run-queue.  Selects the correct
408171482Sjeff * queue position for timeshare threads.
409171482Sjeff */
410122744Sjeffstatic __inline void
411177435Sjefftdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
412122744Sjeff{
413177435Sjeff	struct td_sched *ts;
414177042Sjeff	u_char pri;
415177042Sjeff
416171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
417177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
418177009Sjeff
419177435Sjeff	pri = td->td_priority;
420177435Sjeff	ts = td->td_sched;
421177435Sjeff	TD_SET_RUNQ(td);
422177435Sjeff	if (THREAD_CAN_MIGRATE(td)) {
423165620Sjeff		tdq->tdq_transferable++;
424164936Sjulian		ts->ts_flags |= TSF_XFERABLE;
425123433Sjeff	}
426177042Sjeff	if (pri <= PRI_MAX_REALTIME) {
427177042Sjeff		ts->ts_runq = &tdq->tdq_realtime;
428177042Sjeff	} else if (pri <= PRI_MAX_TIMESHARE) {
429177042Sjeff		ts->ts_runq = &tdq->tdq_timeshare;
430165762Sjeff		KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
431165762Sjeff			("Invalid priority %d on timeshare runq", pri));
432165762Sjeff		/*
433165762Sjeff		 * This queue contains only priorities between MIN and MAX
434165762Sjeff		 * realtime.  Use the whole queue to represent these values.
435165762Sjeff		 */
436171713Sjeff		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
437165762Sjeff			pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
438165762Sjeff			pri = (pri + tdq->tdq_idx) % RQ_NQS;
439165766Sjeff			/*
440165766Sjeff			 * This effectively shortens the queue by one so we
441165766Sjeff			 * can have a one slot difference between idx and
442165766Sjeff			 * ridx while we wait for threads to drain.
443165766Sjeff			 */
444165766Sjeff			if (tdq->tdq_ridx != tdq->tdq_idx &&
445165766Sjeff			    pri == tdq->tdq_ridx)
446167664Sjeff				pri = (unsigned char)(pri - 1) % RQ_NQS;
447165762Sjeff		} else
448165766Sjeff			pri = tdq->tdq_ridx;
449177435Sjeff		runq_add_pri(ts->ts_runq, td, pri, flags);
450177042Sjeff		return;
451165762Sjeff	} else
452177009Sjeff		ts->ts_runq = &tdq->tdq_idle;
453177435Sjeff	runq_add(ts->ts_runq, td, flags);
454177009Sjeff}
455177009Sjeff
456171482Sjeff/*
457171482Sjeff * Remove a thread from a run-queue.  This typically happens when a thread
458171482Sjeff * is selected to run.  Running threads are not on the queue and the
459171482Sjeff * transferable count does not reflect them.
460171482Sjeff */
461122744Sjeffstatic __inline void
462177435Sjefftdq_runq_rem(struct tdq *tdq, struct thread *td)
463122744Sjeff{
464177435Sjeff	struct td_sched *ts;
465177435Sjeff
466177435Sjeff	ts = td->td_sched;
467171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
468171482Sjeff	KASSERT(ts->ts_runq != NULL,
469177435Sjeff	    ("tdq_runq_remove: thread %p null ts_runq", td));
470164936Sjulian	if (ts->ts_flags & TSF_XFERABLE) {
471165620Sjeff		tdq->tdq_transferable--;
472164936Sjulian		ts->ts_flags &= ~TSF_XFERABLE;
473123433Sjeff	}
474165766Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
475165766Sjeff		if (tdq->tdq_idx != tdq->tdq_ridx)
476177435Sjeff			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
477165766Sjeff		else
478177435Sjeff			runq_remove_idx(ts->ts_runq, td, NULL);
479165766Sjeff	} else
480177435Sjeff		runq_remove(ts->ts_runq, td);
481122744Sjeff}
482122744Sjeff
483171482Sjeff/*
484171482Sjeff * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
485171482Sjeff * for this thread to the referenced thread queue.
486171482Sjeff */
487113357Sjeffstatic void
488177435Sjefftdq_load_add(struct tdq *tdq, struct thread *td)
489113357Sjeff{
490171482Sjeff
491171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
492177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
493177902Sjeff
494165620Sjeff	tdq->tdq_load++;
495198854Sattilio	if ((td->td_flags & TDF_NOLOAD) == 0)
496177902Sjeff		tdq->tdq_sysload++;
497187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
498110267Sjeff}
499113357Sjeff
500171482Sjeff/*
501171482Sjeff * Remove the load from a thread that is transitioning to a sleep state or
502171482Sjeff * exiting.
503171482Sjeff */
504112994Sjeffstatic void
505177435Sjefftdq_load_rem(struct tdq *tdq, struct thread *td)
506110267Sjeff{
507171482Sjeff
508177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
509171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
510171482Sjeff	KASSERT(tdq->tdq_load != 0,
511171713Sjeff	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
512177902Sjeff
513165620Sjeff	tdq->tdq_load--;
514198854Sattilio	if ((td->td_flags & TDF_NOLOAD) == 0)
515177902Sjeff		tdq->tdq_sysload--;
516187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
517110267Sjeff}
518110267Sjeff
519176735Sjeff/*
520176735Sjeff * Set lowpri to its exact value by searching the run-queue and
521176735Sjeff * evaluating curthread.  curthread may be passed as an optimization.
522176735Sjeff */
523176735Sjeffstatic void
524176735Sjefftdq_setlowpri(struct tdq *tdq, struct thread *ctd)
525176735Sjeff{
526176735Sjeff	struct thread *td;
527176735Sjeff
528176735Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
529176735Sjeff	if (ctd == NULL)
530176735Sjeff		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
531177435Sjeff	td = tdq_choose(tdq);
532177435Sjeff	if (td == NULL || td->td_priority > ctd->td_priority)
533176735Sjeff		tdq->tdq_lowpri = ctd->td_priority;
534176735Sjeff	else
535176735Sjeff		tdq->tdq_lowpri = td->td_priority;
536176735Sjeff}
537176735Sjeff
538113357Sjeff#ifdef SMP
539176735Sjeffstruct cpu_search {
540194779Sjeff	cpuset_t cs_mask;
541176735Sjeff	u_int	cs_load;
542176735Sjeff	u_int	cs_cpu;
543176735Sjeff	int	cs_limit;	/* Min priority for low min load for high. */
544176735Sjeff};
545176735Sjeff
546176735Sjeff#define	CPU_SEARCH_LOWEST	0x1
547176735Sjeff#define	CPU_SEARCH_HIGHEST	0x2
548176735Sjeff#define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
549176735Sjeff
550194779Sjeff#define	CPUSET_FOREACH(cpu, mask)				\
551194779Sjeff	for ((cpu) = 0; (cpu) <= mp_maxid; (cpu)++)		\
552176735Sjeff		if ((mask) & 1 << (cpu))
553176735Sjeff
554177169Sjhbstatic __inline int cpu_search(struct cpu_group *cg, struct cpu_search *low,
555176735Sjeff    struct cpu_search *high, const int match);
556176735Sjeffint cpu_search_lowest(struct cpu_group *cg, struct cpu_search *low);
557176735Sjeffint cpu_search_highest(struct cpu_group *cg, struct cpu_search *high);
558176735Sjeffint cpu_search_both(struct cpu_group *cg, struct cpu_search *low,
559176735Sjeff    struct cpu_search *high);
560176735Sjeff
561116069Sjeff/*
562176735Sjeff * This routine compares according to the match argument and should be
563176735Sjeff * reduced in actual instantiations via constant propagation and dead code
564176735Sjeff * elimination.
565176735Sjeff */
566176735Sjeffstatic __inline int
567176735Sjeffcpu_compare(int cpu, struct cpu_search *low, struct cpu_search *high,
568176735Sjeff    const int match)
569176735Sjeff{
570176735Sjeff	struct tdq *tdq;
571176735Sjeff
572176735Sjeff	tdq = TDQ_CPU(cpu);
573176735Sjeff	if (match & CPU_SEARCH_LOWEST)
574194779Sjeff		if (CPU_ISSET(cpu, &low->cs_mask) &&
575176735Sjeff		    tdq->tdq_load < low->cs_load &&
576176735Sjeff		    tdq->tdq_lowpri > low->cs_limit) {
577176735Sjeff			low->cs_cpu = cpu;
578176735Sjeff			low->cs_load = tdq->tdq_load;
579176735Sjeff		}
580176735Sjeff	if (match & CPU_SEARCH_HIGHEST)
581194779Sjeff		if (CPU_ISSET(cpu, &high->cs_mask) &&
582176735Sjeff		    tdq->tdq_load >= high->cs_limit &&
583176735Sjeff		    tdq->tdq_load > high->cs_load &&
584176735Sjeff		    tdq->tdq_transferable) {
585176735Sjeff			high->cs_cpu = cpu;
586176735Sjeff			high->cs_load = tdq->tdq_load;
587176735Sjeff		}
588176735Sjeff	return (tdq->tdq_load);
589176735Sjeff}
590176735Sjeff
591176735Sjeff/*
592176735Sjeff * Search the tree of cpu_groups for the lowest or highest loaded cpu
593176735Sjeff * according to the match argument.  This routine actually compares the
594176735Sjeff * load on all paths through the tree and finds the least loaded cpu on
595176735Sjeff * the least loaded path, which may differ from the least loaded cpu in
596176735Sjeff * the system.  This balances work among caches and busses.
597116069Sjeff *
598176735Sjeff * This inline is instantiated in three forms below using constants for the
599176735Sjeff * match argument.  It is reduced to the minimum set for each case.  It is
600176735Sjeff * also recursive to the depth of the tree.
601116069Sjeff */
602177169Sjhbstatic __inline int
603176735Sjeffcpu_search(struct cpu_group *cg, struct cpu_search *low,
604176735Sjeff    struct cpu_search *high, const int match)
605176735Sjeff{
606176735Sjeff	int total;
607176735Sjeff
608176735Sjeff	total = 0;
609176735Sjeff	if (cg->cg_children) {
610176735Sjeff		struct cpu_search lgroup;
611176735Sjeff		struct cpu_search hgroup;
612176735Sjeff		struct cpu_group *child;
613176735Sjeff		u_int lload;
614176735Sjeff		int hload;
615176735Sjeff		int load;
616176735Sjeff		int i;
617176735Sjeff
618176735Sjeff		lload = -1;
619176735Sjeff		hload = -1;
620176735Sjeff		for (i = 0; i < cg->cg_children; i++) {
621176735Sjeff			child = &cg->cg_child[i];
622176735Sjeff			if (match & CPU_SEARCH_LOWEST) {
623176735Sjeff				lgroup = *low;
624176735Sjeff				lgroup.cs_load = -1;
625176735Sjeff			}
626176735Sjeff			if (match & CPU_SEARCH_HIGHEST) {
627176735Sjeff				hgroup = *high;
628176735Sjeff				lgroup.cs_load = 0;
629176735Sjeff			}
630176735Sjeff			switch (match) {
631176735Sjeff			case CPU_SEARCH_LOWEST:
632176735Sjeff				load = cpu_search_lowest(child, &lgroup);
633176735Sjeff				break;
634176735Sjeff			case CPU_SEARCH_HIGHEST:
635176735Sjeff				load = cpu_search_highest(child, &hgroup);
636176735Sjeff				break;
637176735Sjeff			case CPU_SEARCH_BOTH:
638176735Sjeff				load = cpu_search_both(child, &lgroup, &hgroup);
639176735Sjeff				break;
640176735Sjeff			}
641176735Sjeff			total += load;
642176735Sjeff			if (match & CPU_SEARCH_LOWEST)
643176735Sjeff				if (load < lload || low->cs_cpu == -1) {
644176735Sjeff					*low = lgroup;
645176735Sjeff					lload = load;
646176735Sjeff				}
647176735Sjeff			if (match & CPU_SEARCH_HIGHEST)
648176735Sjeff				if (load > hload || high->cs_cpu == -1) {
649176735Sjeff					hload = load;
650176735Sjeff					*high = hgroup;
651176735Sjeff				}
652176735Sjeff		}
653176735Sjeff	} else {
654176735Sjeff		int cpu;
655176735Sjeff
656194779Sjeff		CPUSET_FOREACH(cpu, cg->cg_mask)
657176735Sjeff			total += cpu_compare(cpu, low, high, match);
658176735Sjeff	}
659176735Sjeff	return (total);
660176735Sjeff}
661176735Sjeff
662176735Sjeff/*
663176735Sjeff * cpu_search instantiations must pass constants to maintain the inline
664176735Sjeff * optimization.
665176735Sjeff */
666176735Sjeffint
667176735Sjeffcpu_search_lowest(struct cpu_group *cg, struct cpu_search *low)
668176735Sjeff{
669176735Sjeff	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
670176735Sjeff}
671176735Sjeff
672176735Sjeffint
673176735Sjeffcpu_search_highest(struct cpu_group *cg, struct cpu_search *high)
674176735Sjeff{
675176735Sjeff	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
676176735Sjeff}
677176735Sjeff
678176735Sjeffint
679176735Sjeffcpu_search_both(struct cpu_group *cg, struct cpu_search *low,
680176735Sjeff    struct cpu_search *high)
681176735Sjeff{
682176735Sjeff	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
683176735Sjeff}
684176735Sjeff
685176735Sjeff/*
686176735Sjeff * Find the cpu with the least load via the least loaded path that has a
687176735Sjeff * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
688176735Sjeff * acceptable.
689176735Sjeff */
690176735Sjeffstatic inline int
691194779Sjeffsched_lowest(struct cpu_group *cg, cpuset_t mask, int pri)
692176735Sjeff{
693176735Sjeff	struct cpu_search low;
694176735Sjeff
695176735Sjeff	low.cs_cpu = -1;
696176735Sjeff	low.cs_load = -1;
697176735Sjeff	low.cs_mask = mask;
698176735Sjeff	low.cs_limit = pri;
699176735Sjeff	cpu_search_lowest(cg, &low);
700176735Sjeff	return low.cs_cpu;
701176735Sjeff}
702176735Sjeff
703176735Sjeff/*
704176735Sjeff * Find the cpu with the highest load via the highest loaded path.
705176735Sjeff */
706176735Sjeffstatic inline int
707194779Sjeffsched_highest(struct cpu_group *cg, cpuset_t mask, int minload)
708176735Sjeff{
709176735Sjeff	struct cpu_search high;
710176735Sjeff
711176735Sjeff	high.cs_cpu = -1;
712176735Sjeff	high.cs_load = 0;
713176735Sjeff	high.cs_mask = mask;
714176735Sjeff	high.cs_limit = minload;
715176735Sjeff	cpu_search_highest(cg, &high);
716176735Sjeff	return high.cs_cpu;
717176735Sjeff}
718176735Sjeff
719176735Sjeff/*
720176735Sjeff * Simultaneously find the highest and lowest loaded cpu reachable via
721176735Sjeff * cg.
722176735Sjeff */
723176735Sjeffstatic inline void
724194779Sjeffsched_both(struct cpu_group *cg, cpuset_t mask, int *lowcpu, int *highcpu)
725176735Sjeff{
726176735Sjeff	struct cpu_search high;
727176735Sjeff	struct cpu_search low;
728176735Sjeff
729176735Sjeff	low.cs_cpu = -1;
730176735Sjeff	low.cs_limit = -1;
731176735Sjeff	low.cs_load = -1;
732176735Sjeff	low.cs_mask = mask;
733176735Sjeff	high.cs_load = 0;
734176735Sjeff	high.cs_cpu = -1;
735176735Sjeff	high.cs_limit = -1;
736176735Sjeff	high.cs_mask = mask;
737176735Sjeff	cpu_search_both(cg, &low, &high);
738176735Sjeff	*lowcpu = low.cs_cpu;
739176735Sjeff	*highcpu = high.cs_cpu;
740176735Sjeff	return;
741176735Sjeff}
742176735Sjeff
743121790Sjeffstatic void
744176735Sjeffsched_balance_group(struct cpu_group *cg)
745116069Sjeff{
746194779Sjeff	cpuset_t mask;
747176735Sjeff	int high;
748176735Sjeff	int low;
749123487Sjeff	int i;
750123487Sjeff
751194779Sjeff	CPU_FILL(&mask);
752176735Sjeff	for (;;) {
753176735Sjeff		sched_both(cg, mask, &low, &high);
754176735Sjeff		if (low == high || low == -1 || high == -1)
755176735Sjeff			break;
756176735Sjeff		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low)))
757176735Sjeff			break;
758123487Sjeff		/*
759176735Sjeff		 * If we failed to move any threads determine which cpu
760176735Sjeff		 * to kick out of the set and try again.
761176735Sjeff	 	 */
762176735Sjeff		if (TDQ_CPU(high)->tdq_transferable == 0)
763194779Sjeff			CPU_CLR(high, &mask);
764176735Sjeff		else
765194779Sjeff			CPU_CLR(low, &mask);
766123487Sjeff	}
767176735Sjeff
768176735Sjeff	for (i = 0; i < cg->cg_children; i++)
769176735Sjeff		sched_balance_group(&cg->cg_child[i]);
770123487Sjeff}
771123487Sjeff
772123487Sjeffstatic void
773201148Sedsched_balance(void)
774123487Sjeff{
775172409Sjeff	struct tdq *tdq;
776123487Sjeff
777172409Sjeff	/*
778172409Sjeff	 * Select a random time between .5 * balance_interval and
779172409Sjeff	 * 1.5 * balance_interval.
780172409Sjeff	 */
781176735Sjeff	balance_ticks = max(balance_interval / 2, 1);
782176735Sjeff	balance_ticks += random() % balance_interval;
783171482Sjeff	if (smp_started == 0 || rebalance == 0)
784171482Sjeff		return;
785172409Sjeff	tdq = TDQ_SELF();
786172409Sjeff	TDQ_UNLOCK(tdq);
787176735Sjeff	sched_balance_group(cpu_top);
788172409Sjeff	TDQ_LOCK(tdq);
789123487Sjeff}
790123487Sjeff
791171482Sjeff/*
792171482Sjeff * Lock two thread queues using their address to maintain lock order.
793171482Sjeff */
794123487Sjeffstatic void
795171482Sjefftdq_lock_pair(struct tdq *one, struct tdq *two)
796171482Sjeff{
797171482Sjeff	if (one < two) {
798171482Sjeff		TDQ_LOCK(one);
799171482Sjeff		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
800171482Sjeff	} else {
801171482Sjeff		TDQ_LOCK(two);
802171482Sjeff		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
803171482Sjeff	}
804171482Sjeff}
805171482Sjeff
806171482Sjeff/*
807172409Sjeff * Unlock two thread queues.  Order is not important here.
808172409Sjeff */
809172409Sjeffstatic void
810172409Sjefftdq_unlock_pair(struct tdq *one, struct tdq *two)
811172409Sjeff{
812172409Sjeff	TDQ_UNLOCK(one);
813172409Sjeff	TDQ_UNLOCK(two);
814172409Sjeff}
815172409Sjeff
816172409Sjeff/*
817171482Sjeff * Transfer load between two imbalanced thread queues.
818171482Sjeff */
819176735Sjeffstatic int
820164936Sjuliansched_balance_pair(struct tdq *high, struct tdq *low)
821123487Sjeff{
822123433Sjeff	int transferable;
823116069Sjeff	int high_load;
824116069Sjeff	int low_load;
825176735Sjeff	int moved;
826116069Sjeff	int move;
827116069Sjeff	int diff;
828116069Sjeff	int i;
829116069Sjeff
830171482Sjeff	tdq_lock_pair(high, low);
831176735Sjeff	transferable = high->tdq_transferable;
832176735Sjeff	high_load = high->tdq_load;
833176735Sjeff	low_load = low->tdq_load;
834176735Sjeff	moved = 0;
835116069Sjeff	/*
836122744Sjeff	 * Determine what the imbalance is and then adjust that to how many
837165620Sjeff	 * threads we actually have to give up (transferable).
838122744Sjeff	 */
839171482Sjeff	if (transferable != 0) {
840171482Sjeff		diff = high_load - low_load;
841171482Sjeff		move = diff / 2;
842171482Sjeff		if (diff & 0x1)
843171482Sjeff			move++;
844171482Sjeff		move = min(move, transferable);
845171482Sjeff		for (i = 0; i < move; i++)
846176735Sjeff			moved += tdq_move(high, low);
847172293Sjeff		/*
848172293Sjeff		 * IPI the target cpu to force it to reschedule with the new
849172293Sjeff		 * workload.
850172293Sjeff		 */
851210939Sjhb		ipi_cpu(TDQ_ID(low), IPI_PREEMPT);
852171482Sjeff	}
853172409Sjeff	tdq_unlock_pair(high, low);
854176735Sjeff	return (moved);
855116069Sjeff}
856116069Sjeff
857171482Sjeff/*
858171482Sjeff * Move a thread from one thread queue to another.
859171482Sjeff */
860176735Sjeffstatic int
861171482Sjefftdq_move(struct tdq *from, struct tdq *to)
862116069Sjeff{
863171482Sjeff	struct td_sched *ts;
864171482Sjeff	struct thread *td;
865164936Sjulian	struct tdq *tdq;
866171482Sjeff	int cpu;
867116069Sjeff
868172409Sjeff	TDQ_LOCK_ASSERT(from, MA_OWNED);
869172409Sjeff	TDQ_LOCK_ASSERT(to, MA_OWNED);
870172409Sjeff
871164936Sjulian	tdq = from;
872171482Sjeff	cpu = TDQ_ID(to);
873177435Sjeff	td = tdq_steal(tdq, cpu);
874177435Sjeff	if (td == NULL)
875176735Sjeff		return (0);
876177435Sjeff	ts = td->td_sched;
877171482Sjeff	/*
878171482Sjeff	 * Although the run queue is locked the thread may be blocked.  Lock
879172409Sjeff	 * it to clear this and acquire the run-queue lock.
880171482Sjeff	 */
881171482Sjeff	thread_lock(td);
882172409Sjeff	/* Drop recursive lock on from acquired via thread_lock(). */
883171482Sjeff	TDQ_UNLOCK(from);
884171482Sjeff	sched_rem(td);
885166108Sjeff	ts->ts_cpu = cpu;
886171482Sjeff	td->td_lock = TDQ_LOCKPTR(to);
887171482Sjeff	tdq_add(to, td, SRQ_YIELDING);
888176735Sjeff	return (1);
889116069Sjeff}
890110267Sjeff
891171482Sjeff/*
892171482Sjeff * This tdq has idled.  Try to steal a thread from another cpu and switch
893171482Sjeff * to it.
894171482Sjeff */
895123433Sjeffstatic int
896164936Sjuliantdq_idled(struct tdq *tdq)
897121790Sjeff{
898176735Sjeff	struct cpu_group *cg;
899164936Sjulian	struct tdq *steal;
900194779Sjeff	cpuset_t mask;
901176735Sjeff	int thresh;
902171482Sjeff	int cpu;
903123433Sjeff
904172484Sjeff	if (smp_started == 0 || steal_idle == 0)
905172484Sjeff		return (1);
906194779Sjeff	CPU_FILL(&mask);
907194779Sjeff	CPU_CLR(PCPU_GET(cpuid), &mask);
908176735Sjeff	/* We don't want to be preempted while we're iterating. */
909171482Sjeff	spinlock_enter();
910176735Sjeff	for (cg = tdq->tdq_cg; cg != NULL; ) {
911191643Sjeff		if ((cg->cg_flags & CG_FLAG_THREAD) == 0)
912176735Sjeff			thresh = steal_thresh;
913176735Sjeff		else
914176735Sjeff			thresh = 1;
915176735Sjeff		cpu = sched_highest(cg, mask, thresh);
916176735Sjeff		if (cpu == -1) {
917176735Sjeff			cg = cg->cg_parent;
918176735Sjeff			continue;
919166108Sjeff		}
920176735Sjeff		steal = TDQ_CPU(cpu);
921194779Sjeff		CPU_CLR(cpu, &mask);
922176735Sjeff		tdq_lock_pair(tdq, steal);
923176735Sjeff		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
924176735Sjeff			tdq_unlock_pair(tdq, steal);
925176735Sjeff			continue;
926171482Sjeff		}
927176735Sjeff		/*
928176735Sjeff		 * If a thread was added while interrupts were disabled don't
929176735Sjeff		 * steal one here.  If we fail to acquire one due to affinity
930176735Sjeff		 * restrictions loop again with this cpu removed from the
931176735Sjeff		 * set.
932176735Sjeff		 */
933176735Sjeff		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
934176735Sjeff			tdq_unlock_pair(tdq, steal);
935176735Sjeff			continue;
936176735Sjeff		}
937176735Sjeff		spinlock_exit();
938176735Sjeff		TDQ_UNLOCK(steal);
939178272Sjeff		mi_switch(SW_VOL | SWT_IDLE, NULL);
940176735Sjeff		thread_unlock(curthread);
941176735Sjeff
942176735Sjeff		return (0);
943123433Sjeff	}
944171482Sjeff	spinlock_exit();
945123433Sjeff	return (1);
946121790Sjeff}
947121790Sjeff
948171482Sjeff/*
949171482Sjeff * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
950171482Sjeff */
951121790Sjeffstatic void
952177435Sjefftdq_notify(struct tdq *tdq, struct thread *td)
953121790Sjeff{
954185047Sjhb	struct thread *ctd;
955166247Sjeff	int pri;
956166108Sjeff	int cpu;
957121790Sjeff
958177005Sjeff	if (tdq->tdq_ipipending)
959177005Sjeff		return;
960177435Sjeff	cpu = td->td_sched->ts_cpu;
961177435Sjeff	pri = td->td_priority;
962185047Sjhb	ctd = pcpu_find(cpu)->pc_curthread;
963185047Sjhb	if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
964166137Sjeff		return;
965185047Sjhb	if (TD_IS_IDLETHREAD(ctd)) {
966178277Sjeff		/*
967178471Sjeff		 * If the MD code has an idle wakeup routine try that before
968178471Sjeff		 * falling back to IPI.
969178471Sjeff		 */
970212416Smav		if (!tdq->tdq_cpu_idle || cpu_idle_wakeup(cpu))
971178471Sjeff			return;
972178277Sjeff	}
973177005Sjeff	tdq->tdq_ipipending = 1;
974210939Sjhb	ipi_cpu(cpu, IPI_PREEMPT);
975121790Sjeff}
976121790Sjeff
977171482Sjeff/*
978171482Sjeff * Steals load from a timeshare queue.  Honors the rotating queue head
979171482Sjeff * index.
980171482Sjeff */
981177435Sjeffstatic struct thread *
982176735Sjeffrunq_steal_from(struct runq *rq, int cpu, u_char start)
983171482Sjeff{
984171482Sjeff	struct rqbits *rqb;
985171482Sjeff	struct rqhead *rqh;
986177435Sjeff	struct thread *td;
987171482Sjeff	int first;
988171482Sjeff	int bit;
989171482Sjeff	int pri;
990171482Sjeff	int i;
991171482Sjeff
992171482Sjeff	rqb = &rq->rq_status;
993171482Sjeff	bit = start & (RQB_BPW -1);
994171482Sjeff	pri = 0;
995171482Sjeff	first = 0;
996171482Sjeffagain:
997171482Sjeff	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
998171482Sjeff		if (rqb->rqb_bits[i] == 0)
999171482Sjeff			continue;
1000171482Sjeff		if (bit != 0) {
1001171482Sjeff			for (pri = bit; pri < RQB_BPW; pri++)
1002171482Sjeff				if (rqb->rqb_bits[i] & (1ul << pri))
1003171482Sjeff					break;
1004171482Sjeff			if (pri >= RQB_BPW)
1005171482Sjeff				continue;
1006171482Sjeff		} else
1007171482Sjeff			pri = RQB_FFS(rqb->rqb_bits[i]);
1008171482Sjeff		pri += (i << RQB_L2BPW);
1009171482Sjeff		rqh = &rq->rq_queues[pri];
1010177435Sjeff		TAILQ_FOREACH(td, rqh, td_runq) {
1011177435Sjeff			if (first && THREAD_CAN_MIGRATE(td) &&
1012177435Sjeff			    THREAD_CAN_SCHED(td, cpu))
1013177435Sjeff				return (td);
1014171482Sjeff			first = 1;
1015171482Sjeff		}
1016171482Sjeff	}
1017171482Sjeff	if (start != 0) {
1018171482Sjeff		start = 0;
1019171482Sjeff		goto again;
1020171482Sjeff	}
1021171482Sjeff
1022171482Sjeff	return (NULL);
1023171482Sjeff}
1024171482Sjeff
1025171482Sjeff/*
1026171482Sjeff * Steals load from a standard linear queue.
1027171482Sjeff */
1028177435Sjeffstatic struct thread *
1029176735Sjeffrunq_steal(struct runq *rq, int cpu)
1030121790Sjeff{
1031121790Sjeff	struct rqhead *rqh;
1032121790Sjeff	struct rqbits *rqb;
1033177435Sjeff	struct thread *td;
1034121790Sjeff	int word;
1035121790Sjeff	int bit;
1036121790Sjeff
1037121790Sjeff	rqb = &rq->rq_status;
1038121790Sjeff	for (word = 0; word < RQB_LEN; word++) {
1039121790Sjeff		if (rqb->rqb_bits[word] == 0)
1040121790Sjeff			continue;
1041121790Sjeff		for (bit = 0; bit < RQB_BPW; bit++) {
1042123231Speter			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
1043121790Sjeff				continue;
1044121790Sjeff			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
1045177435Sjeff			TAILQ_FOREACH(td, rqh, td_runq)
1046177435Sjeff				if (THREAD_CAN_MIGRATE(td) &&
1047177435Sjeff				    THREAD_CAN_SCHED(td, cpu))
1048177435Sjeff					return (td);
1049121790Sjeff		}
1050121790Sjeff	}
1051121790Sjeff	return (NULL);
1052121790Sjeff}
1053121790Sjeff
1054171482Sjeff/*
1055171482Sjeff * Attempt to steal a thread in priority order from a thread queue.
1056171482Sjeff */
1057177435Sjeffstatic struct thread *
1058176735Sjefftdq_steal(struct tdq *tdq, int cpu)
1059121790Sjeff{
1060177435Sjeff	struct thread *td;
1061121790Sjeff
1062171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1063177435Sjeff	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
1064177435Sjeff		return (td);
1065177435Sjeff	if ((td = runq_steal_from(&tdq->tdq_timeshare,
1066177435Sjeff	    cpu, tdq->tdq_ridx)) != NULL)
1067177435Sjeff		return (td);
1068176735Sjeff	return (runq_steal(&tdq->tdq_idle, cpu));
1069121790Sjeff}
1070123433Sjeff
1071171482Sjeff/*
1072171482Sjeff * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
1073172409Sjeff * current lock and returns with the assigned queue locked.
1074171482Sjeff */
1075171482Sjeffstatic inline struct tdq *
1076177435Sjeffsched_setcpu(struct thread *td, int cpu, int flags)
1077123433Sjeff{
1078177435Sjeff
1079171482Sjeff	struct tdq *tdq;
1080123433Sjeff
1081177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1082171482Sjeff	tdq = TDQ_CPU(cpu);
1083177435Sjeff	td->td_sched->ts_cpu = cpu;
1084177435Sjeff	/*
1085177435Sjeff	 * If the lock matches just return the queue.
1086177435Sjeff	 */
1087171482Sjeff	if (td->td_lock == TDQ_LOCKPTR(tdq))
1088171482Sjeff		return (tdq);
1089171482Sjeff#ifdef notyet
1090123433Sjeff	/*
1091172293Sjeff	 * If the thread isn't running its lockptr is a
1092171482Sjeff	 * turnstile or a sleepqueue.  We can just lock_set without
1093171482Sjeff	 * blocking.
1094123685Sjeff	 */
1095171482Sjeff	if (TD_CAN_RUN(td)) {
1096171482Sjeff		TDQ_LOCK(tdq);
1097171482Sjeff		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1098171482Sjeff		return (tdq);
1099171482Sjeff	}
1100171482Sjeff#endif
1101166108Sjeff	/*
1102171482Sjeff	 * The hard case, migration, we need to block the thread first to
1103171482Sjeff	 * prevent order reversals with other cpus locks.
1104166108Sjeff	 */
1105202889Sattilio	spinlock_enter();
1106171482Sjeff	thread_lock_block(td);
1107171482Sjeff	TDQ_LOCK(tdq);
1108171713Sjeff	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1109202889Sattilio	spinlock_exit();
1110171482Sjeff	return (tdq);
1111166108Sjeff}
1112166108Sjeff
1113178272SjeffSCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
1114178272SjeffSCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
1115178272SjeffSCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
1116178272SjeffSCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
1117178272SjeffSCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
1118178272SjeffSCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
1119178272Sjeff
1120166108Sjeffstatic int
1121177435Sjeffsched_pickcpu(struct thread *td, int flags)
1122171482Sjeff{
1123176735Sjeff	struct cpu_group *cg;
1124177435Sjeff	struct td_sched *ts;
1125171482Sjeff	struct tdq *tdq;
1126194779Sjeff	cpuset_t mask;
1127166108Sjeff	int self;
1128166108Sjeff	int pri;
1129166108Sjeff	int cpu;
1130166108Sjeff
1131176735Sjeff	self = PCPU_GET(cpuid);
1132177435Sjeff	ts = td->td_sched;
1133166108Sjeff	if (smp_started == 0)
1134166108Sjeff		return (self);
1135171506Sjeff	/*
1136171506Sjeff	 * Don't migrate a running thread from sched_switch().
1137171506Sjeff	 */
1138176735Sjeff	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1139176735Sjeff		return (ts->ts_cpu);
1140166108Sjeff	/*
1141176735Sjeff	 * Prefer to run interrupt threads on the processors that generate
1142176735Sjeff	 * the interrupt.
1143166108Sjeff	 */
1144176735Sjeff	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1145178272Sjeff	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
1146178272Sjeff		SCHED_STAT_INC(pickcpu_intrbind);
1147176735Sjeff		ts->ts_cpu = self;
1148178272Sjeff	}
1149166108Sjeff	/*
1150176735Sjeff	 * If the thread can run on the last cpu and the affinity has not
1151176735Sjeff	 * expired or it is idle run it there.
1152166108Sjeff	 */
1153176735Sjeff	pri = td->td_priority;
1154176735Sjeff	tdq = TDQ_CPU(ts->ts_cpu);
1155176735Sjeff	if (THREAD_CAN_SCHED(td, ts->ts_cpu)) {
1156178272Sjeff		if (tdq->tdq_lowpri > PRI_MIN_IDLE) {
1157178272Sjeff			SCHED_STAT_INC(pickcpu_idle_affinity);
1158176735Sjeff			return (ts->ts_cpu);
1159178272Sjeff		}
1160178272Sjeff		if (SCHED_AFFINITY(ts, CG_SHARE_L2) && tdq->tdq_lowpri > pri) {
1161178272Sjeff			SCHED_STAT_INC(pickcpu_affinity);
1162176735Sjeff			return (ts->ts_cpu);
1163178272Sjeff		}
1164139334Sjeff	}
1165123433Sjeff	/*
1166176735Sjeff	 * Search for the highest level in the tree that still has affinity.
1167123433Sjeff	 */
1168176735Sjeff	cg = NULL;
1169176735Sjeff	for (cg = tdq->tdq_cg; cg != NULL; cg = cg->cg_parent)
1170176735Sjeff		if (SCHED_AFFINITY(ts, cg->cg_level))
1171176735Sjeff			break;
1172176735Sjeff	cpu = -1;
1173194779Sjeff	mask = td->td_cpuset->cs_mask;
1174176735Sjeff	if (cg)
1175176735Sjeff		cpu = sched_lowest(cg, mask, pri);
1176176735Sjeff	if (cpu == -1)
1177176735Sjeff		cpu = sched_lowest(cpu_top, mask, -1);
1178171506Sjeff	/*
1179176735Sjeff	 * Compare the lowest loaded cpu to current cpu.
1180171506Sjeff	 */
1181177005Sjeff	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
1182178272Sjeff	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE) {
1183178272Sjeff		SCHED_STAT_INC(pickcpu_local);
1184177005Sjeff		cpu = self;
1185178272Sjeff	} else
1186178272Sjeff		SCHED_STAT_INC(pickcpu_lowest);
1187178272Sjeff	if (cpu != ts->ts_cpu)
1188178272Sjeff		SCHED_STAT_INC(pickcpu_migration);
1189177005Sjeff	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1190171482Sjeff	return (cpu);
1191123433Sjeff}
1192176735Sjeff#endif
1193123433Sjeff
1194117326Sjeff/*
1195121790Sjeff * Pick the highest priority task we have and return it.
1196117326Sjeff */
1197177435Sjeffstatic struct thread *
1198164936Sjuliantdq_choose(struct tdq *tdq)
1199110267Sjeff{
1200177435Sjeff	struct thread *td;
1201110267Sjeff
1202171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1203177435Sjeff	td = runq_choose(&tdq->tdq_realtime);
1204177435Sjeff	if (td != NULL)
1205177435Sjeff		return (td);
1206177435Sjeff	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1207177435Sjeff	if (td != NULL) {
1208177435Sjeff		KASSERT(td->td_priority >= PRI_MIN_TIMESHARE,
1209165762Sjeff		    ("tdq_choose: Invalid priority on timeshare queue %d",
1210177435Sjeff		    td->td_priority));
1211177435Sjeff		return (td);
1212165762Sjeff	}
1213177435Sjeff	td = runq_choose(&tdq->tdq_idle);
1214177435Sjeff	if (td != NULL) {
1215177435Sjeff		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1216165762Sjeff		    ("tdq_choose: Invalid priority on idle queue %d",
1217177435Sjeff		    td->td_priority));
1218177435Sjeff		return (td);
1219165762Sjeff	}
1220165762Sjeff
1221165762Sjeff	return (NULL);
1222110267Sjeff}
1223110267Sjeff
1224171482Sjeff/*
1225171482Sjeff * Initialize a thread queue.
1226171482Sjeff */
1227109864Sjeffstatic void
1228164936Sjuliantdq_setup(struct tdq *tdq)
1229110028Sjeff{
1230171482Sjeff
1231171713Sjeff	if (bootverbose)
1232171713Sjeff		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1233165762Sjeff	runq_init(&tdq->tdq_realtime);
1234165762Sjeff	runq_init(&tdq->tdq_timeshare);
1235165620Sjeff	runq_init(&tdq->tdq_idle);
1236176735Sjeff	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1237176735Sjeff	    "sched lock %d", (int)TDQ_ID(tdq));
1238176735Sjeff	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1239176735Sjeff	    MTX_SPIN | MTX_RECURSE);
1240187357Sjeff#ifdef KTR
1241187357Sjeff	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
1242187357Sjeff	    "CPU %d load", (int)TDQ_ID(tdq));
1243187357Sjeff#endif
1244110028Sjeff}
1245110028Sjeff
1246171713Sjeff#ifdef SMP
1247110028Sjeffstatic void
1248171713Sjeffsched_setup_smp(void)
1249171713Sjeff{
1250171713Sjeff	struct tdq *tdq;
1251171713Sjeff	int i;
1252171713Sjeff
1253176735Sjeff	cpu_top = smp_topo();
1254209059Sjhb	CPU_FOREACH(i) {
1255176735Sjeff		tdq = TDQ_CPU(i);
1256171713Sjeff		tdq_setup(tdq);
1257176735Sjeff		tdq->tdq_cg = smp_topo_find(cpu_top, i);
1258176735Sjeff		if (tdq->tdq_cg == NULL)
1259176735Sjeff			panic("Can't find cpu group for %d\n", i);
1260123433Sjeff	}
1261176735Sjeff	balance_tdq = TDQ_SELF();
1262176735Sjeff	sched_balance();
1263171713Sjeff}
1264171713Sjeff#endif
1265171713Sjeff
1266171713Sjeff/*
1267171713Sjeff * Setup the thread queues and initialize the topology based on MD
1268171713Sjeff * information.
1269171713Sjeff */
1270171713Sjeffstatic void
1271171713Sjeffsched_setup(void *dummy)
1272171713Sjeff{
1273171713Sjeff	struct tdq *tdq;
1274171713Sjeff
1275171713Sjeff	tdq = TDQ_SELF();
1276171713Sjeff#ifdef SMP
1277176734Sjeff	sched_setup_smp();
1278117237Sjeff#else
1279171713Sjeff	tdq_setup(tdq);
1280116069Sjeff#endif
1281171482Sjeff	/*
1282171482Sjeff	 * To avoid divide-by-zero, we set realstathz a dummy value
1283171482Sjeff	 * in case which sched_clock() called before sched_initticks().
1284171482Sjeff	 */
1285171482Sjeff	realstathz = hz;
1286171482Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1287171482Sjeff	tickincr = 1 << SCHED_TICK_SHIFT;
1288171482Sjeff
1289171482Sjeff	/* Add thread0's load since it's running. */
1290171482Sjeff	TDQ_LOCK(tdq);
1291171713Sjeff	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1292177435Sjeff	tdq_load_add(tdq, &thread0);
1293176735Sjeff	tdq->tdq_lowpri = thread0.td_priority;
1294171482Sjeff	TDQ_UNLOCK(tdq);
1295109864Sjeff}
1296109864Sjeff
1297171482Sjeff/*
1298171482Sjeff * This routine determines the tickincr after stathz and hz are setup.
1299171482Sjeff */
1300153533Sdavidxu/* ARGSUSED */
1301153533Sdavidxustatic void
1302153533Sdavidxusched_initticks(void *dummy)
1303153533Sdavidxu{
1304171482Sjeff	int incr;
1305171482Sjeff
1306153533Sdavidxu	realstathz = stathz ? stathz : hz;
1307166229Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1308153533Sdavidxu
1309153533Sdavidxu	/*
1310165762Sjeff	 * tickincr is shifted out by 10 to avoid rounding errors due to
1311165766Sjeff	 * hz not being evenly divisible by stathz on all platforms.
1312153533Sdavidxu	 */
1313171482Sjeff	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1314165762Sjeff	/*
1315165762Sjeff	 * This does not work for values of stathz that are more than
1316165762Sjeff	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1317165762Sjeff	 */
1318171482Sjeff	if (incr == 0)
1319171482Sjeff		incr = 1;
1320171482Sjeff	tickincr = incr;
1321166108Sjeff#ifdef SMP
1322171899Sjeff	/*
1323172409Sjeff	 * Set the default balance interval now that we know
1324172409Sjeff	 * what realstathz is.
1325172409Sjeff	 */
1326172409Sjeff	balance_interval = realstathz;
1327172409Sjeff	/*
1328189787Sjeff	 * Set steal thresh to roughly log2(mp_ncpu) but no greater than 4.
1329189787Sjeff	 * This prevents excess thrashing on large machines and excess idle
1330189787Sjeff	 * on smaller machines.
1331171899Sjeff	 */
1332189787Sjeff	steal_thresh = min(fls(mp_ncpus) - 1, 3);
1333166108Sjeff	affinity = SCHED_AFFINITY_DEFAULT;
1334166108Sjeff#endif
1335153533Sdavidxu}
1336153533Sdavidxu
1337153533Sdavidxu
1338109864Sjeff/*
1339171482Sjeff * This is the core of the interactivity algorithm.  Determines a score based
1340171482Sjeff * on past behavior.  It is the ratio of sleep time to run time scaled to
1341171482Sjeff * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1342171482Sjeff * differs from the cpu usage because it does not account for time spent
1343171482Sjeff * waiting on a run-queue.  Would be prettier if we had floating point.
1344171482Sjeff */
1345171482Sjeffstatic int
1346171482Sjeffsched_interact_score(struct thread *td)
1347171482Sjeff{
1348171482Sjeff	struct td_sched *ts;
1349171482Sjeff	int div;
1350171482Sjeff
1351171482Sjeff	ts = td->td_sched;
1352171482Sjeff	/*
1353171482Sjeff	 * The score is only needed if this is likely to be an interactive
1354171482Sjeff	 * task.  Don't go through the expense of computing it if there's
1355171482Sjeff	 * no chance.
1356171482Sjeff	 */
1357171482Sjeff	if (sched_interact <= SCHED_INTERACT_HALF &&
1358171482Sjeff		ts->ts_runtime >= ts->ts_slptime)
1359171482Sjeff			return (SCHED_INTERACT_HALF);
1360171482Sjeff
1361171482Sjeff	if (ts->ts_runtime > ts->ts_slptime) {
1362171482Sjeff		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1363171482Sjeff		return (SCHED_INTERACT_HALF +
1364171482Sjeff		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1365171482Sjeff	}
1366171482Sjeff	if (ts->ts_slptime > ts->ts_runtime) {
1367171482Sjeff		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1368171482Sjeff		return (ts->ts_runtime / div);
1369171482Sjeff	}
1370171482Sjeff	/* runtime == slptime */
1371171482Sjeff	if (ts->ts_runtime)
1372171482Sjeff		return (SCHED_INTERACT_HALF);
1373171482Sjeff
1374171482Sjeff	/*
1375171482Sjeff	 * This can happen if slptime and runtime are 0.
1376171482Sjeff	 */
1377171482Sjeff	return (0);
1378171482Sjeff
1379171482Sjeff}
1380171482Sjeff
1381171482Sjeff/*
1382109864Sjeff * Scale the scheduling priority according to the "interactivity" of this
1383109864Sjeff * process.
1384109864Sjeff */
1385113357Sjeffstatic void
1386163709Sjbsched_priority(struct thread *td)
1387109864Sjeff{
1388165762Sjeff	int score;
1389109864Sjeff	int pri;
1390109864Sjeff
1391217291Sjhb	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
1392113357Sjeff		return;
1393112966Sjeff	/*
1394165762Sjeff	 * If the score is interactive we place the thread in the realtime
1395165762Sjeff	 * queue with a priority that is less than kernel and interrupt
1396165762Sjeff	 * priorities.  These threads are not subject to nice restrictions.
1397112966Sjeff	 *
1398171482Sjeff	 * Scores greater than this are placed on the normal timeshare queue
1399165762Sjeff	 * where the priority is partially decided by the most recent cpu
1400165762Sjeff	 * utilization and the rest is decided by nice value.
1401172293Sjeff	 *
1402172293Sjeff	 * The nice value of the process has a linear effect on the calculated
1403172293Sjeff	 * score.  Negative nice values make it easier for a thread to be
1404172293Sjeff	 * considered interactive.
1405112966Sjeff	 */
1406198126Sjhb	score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1407165762Sjeff	if (score < sched_interact) {
1408165762Sjeff		pri = PRI_MIN_REALTIME;
1409217237Sjhb		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME + 1) /
1410217237Sjhb		    sched_interact) * score;
1411165762Sjeff		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1412166208Sjeff		    ("sched_priority: invalid interactive priority %d score %d",
1413166208Sjeff		    pri, score));
1414165762Sjeff	} else {
1415165762Sjeff		pri = SCHED_PRI_MIN;
1416165762Sjeff		if (td->td_sched->ts_ticks)
1417165762Sjeff			pri += SCHED_PRI_TICKS(td->td_sched);
1418165762Sjeff		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1419171482Sjeff		KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1420171482Sjeff		    ("sched_priority: invalid priority %d: nice %d, "
1421171482Sjeff		    "ticks %d ftick %d ltick %d tick pri %d",
1422171482Sjeff		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1423171482Sjeff		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1424171482Sjeff		    SCHED_PRI_TICKS(td->td_sched)));
1425165762Sjeff	}
1426165762Sjeff	sched_user_prio(td, pri);
1427112966Sjeff
1428112966Sjeff	return;
1429109864Sjeff}
1430109864Sjeff
1431121868Sjeff/*
1432121868Sjeff * This routine enforces a maximum limit on the amount of scheduling history
1433171482Sjeff * kept.  It is called after either the slptime or runtime is adjusted.  This
1434171482Sjeff * function is ugly due to integer math.
1435121868Sjeff */
1436116463Sjeffstatic void
1437163709Sjbsched_interact_update(struct thread *td)
1438116463Sjeff{
1439165819Sjeff	struct td_sched *ts;
1440166208Sjeff	u_int sum;
1441121605Sjeff
1442165819Sjeff	ts = td->td_sched;
1443171482Sjeff	sum = ts->ts_runtime + ts->ts_slptime;
1444121868Sjeff	if (sum < SCHED_SLP_RUN_MAX)
1445121868Sjeff		return;
1446121868Sjeff	/*
1447165819Sjeff	 * This only happens from two places:
1448165819Sjeff	 * 1) We have added an unusual amount of run time from fork_exit.
1449165819Sjeff	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1450165819Sjeff	 */
1451165819Sjeff	if (sum > SCHED_SLP_RUN_MAX * 2) {
1452171482Sjeff		if (ts->ts_runtime > ts->ts_slptime) {
1453171482Sjeff			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1454171482Sjeff			ts->ts_slptime = 1;
1455165819Sjeff		} else {
1456171482Sjeff			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1457171482Sjeff			ts->ts_runtime = 1;
1458165819Sjeff		}
1459165819Sjeff		return;
1460165819Sjeff	}
1461165819Sjeff	/*
1462121868Sjeff	 * If we have exceeded by more than 1/5th then the algorithm below
1463121868Sjeff	 * will not bring us back into range.  Dividing by two here forces
1464133427Sjeff	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1465121868Sjeff	 */
1466127850Sjeff	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1467171482Sjeff		ts->ts_runtime /= 2;
1468171482Sjeff		ts->ts_slptime /= 2;
1469121868Sjeff		return;
1470116463Sjeff	}
1471171482Sjeff	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1472171482Sjeff	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1473116463Sjeff}
1474116463Sjeff
1475171482Sjeff/*
1476171482Sjeff * Scale back the interactivity history when a child thread is created.  The
1477171482Sjeff * history is inherited from the parent but the thread may behave totally
1478171482Sjeff * differently.  For example, a shell spawning a compiler process.  We want
1479171482Sjeff * to learn that the compiler is behaving badly very quickly.
1480171482Sjeff */
1481121868Sjeffstatic void
1482163709Sjbsched_interact_fork(struct thread *td)
1483121868Sjeff{
1484121868Sjeff	int ratio;
1485121868Sjeff	int sum;
1486121868Sjeff
1487171482Sjeff	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1488121868Sjeff	if (sum > SCHED_SLP_RUN_FORK) {
1489121868Sjeff		ratio = sum / SCHED_SLP_RUN_FORK;
1490171482Sjeff		td->td_sched->ts_runtime /= ratio;
1491171482Sjeff		td->td_sched->ts_slptime /= ratio;
1492121868Sjeff	}
1493121868Sjeff}
1494121868Sjeff
1495113357Sjeff/*
1496171482Sjeff * Called from proc0_init() to setup the scheduler fields.
1497134791Sjulian */
1498134791Sjulianvoid
1499134791Sjulianschedinit(void)
1500134791Sjulian{
1501165762Sjeff
1502134791Sjulian	/*
1503134791Sjulian	 * Set up the scheduler specific parts of proc0.
1504134791Sjulian	 */
1505136167Sjulian	proc0.p_sched = NULL; /* XXX */
1506164936Sjulian	thread0.td_sched = &td_sched0;
1507165762Sjeff	td_sched0.ts_ltick = ticks;
1508165796Sjeff	td_sched0.ts_ftick = ticks;
1509177009Sjeff	td_sched0.ts_slice = sched_slice;
1510134791Sjulian}
1511134791Sjulian
1512134791Sjulian/*
1513113357Sjeff * This is only somewhat accurate since given many processes of the same
1514113357Sjeff * priority they will switch when their slices run out, which will be
1515165762Sjeff * at most sched_slice stathz ticks.
1516113357Sjeff */
1517109864Sjeffint
1518109864Sjeffsched_rr_interval(void)
1519109864Sjeff{
1520165762Sjeff
1521165762Sjeff	/* Convert sched_slice to hz */
1522165762Sjeff	return (hz/(realstathz/sched_slice));
1523109864Sjeff}
1524109864Sjeff
1525171482Sjeff/*
1526171482Sjeff * Update the percent cpu tracking information when it is requested or
1527171482Sjeff * the total history exceeds the maximum.  We keep a sliding history of
1528171482Sjeff * tick counts that slowly decays.  This is less precise than the 4BSD
1529171482Sjeff * mechanism since it happens with less regular and frequent events.
1530171482Sjeff */
1531121790Sjeffstatic void
1532164936Sjuliansched_pctcpu_update(struct td_sched *ts)
1533109864Sjeff{
1534165762Sjeff
1535165762Sjeff	if (ts->ts_ticks == 0)
1536165762Sjeff		return;
1537165796Sjeff	if (ticks - (hz / 10) < ts->ts_ltick &&
1538165796Sjeff	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1539165796Sjeff		return;
1540109864Sjeff	/*
1541109864Sjeff	 * Adjust counters and watermark for pctcpu calc.
1542116365Sjeff	 */
1543165762Sjeff	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1544164936Sjulian		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1545165762Sjeff			    SCHED_TICK_TARG;
1546165762Sjeff	else
1547164936Sjulian		ts->ts_ticks = 0;
1548164936Sjulian	ts->ts_ltick = ticks;
1549165762Sjeff	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1550109864Sjeff}
1551109864Sjeff
1552171482Sjeff/*
1553171482Sjeff * Adjust the priority of a thread.  Move it to the appropriate run-queue
1554171482Sjeff * if necessary.  This is the back-end for several priority related
1555171482Sjeff * functions.
1556171482Sjeff */
1557165762Sjeffstatic void
1558139453Sjhbsched_thread_priority(struct thread *td, u_char prio)
1559109864Sjeff{
1560164936Sjulian	struct td_sched *ts;
1561177009Sjeff	struct tdq *tdq;
1562177009Sjeff	int oldpri;
1563109864Sjeff
1564187357Sjeff	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
1565187357Sjeff	    "prio:%d", td->td_priority, "new prio:%d", prio,
1566187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(curthread));
1567187357Sjeff	if (td != curthread && prio > td->td_priority) {
1568187357Sjeff		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
1569187357Sjeff		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
1570187357Sjeff		    prio, KTR_ATTR_LINKED, sched_tdname(td));
1571187357Sjeff	}
1572164936Sjulian	ts = td->td_sched;
1573170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1574139453Sjhb	if (td->td_priority == prio)
1575139453Sjhb		return;
1576177376Sjeff	/*
1577177376Sjeff	 * If the priority has been elevated due to priority
1578177376Sjeff	 * propagation, we may have to move ourselves to a new
1579177376Sjeff	 * queue.  This could be optimized to not re-add in some
1580177376Sjeff	 * cases.
1581177376Sjeff	 */
1582165766Sjeff	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1583165762Sjeff		sched_rem(td);
1584165762Sjeff		td->td_priority = prio;
1585171482Sjeff		sched_add(td, SRQ_BORROWING);
1586177009Sjeff		return;
1587177009Sjeff	}
1588177376Sjeff	/*
1589177376Sjeff	 * If the thread is currently running we may have to adjust the lowpri
1590177376Sjeff	 * information so other cpus are aware of our current priority.
1591177376Sjeff	 */
1592177009Sjeff	if (TD_IS_RUNNING(td)) {
1593177376Sjeff		tdq = TDQ_CPU(ts->ts_cpu);
1594177376Sjeff		oldpri = td->td_priority;
1595177376Sjeff		td->td_priority = prio;
1596176735Sjeff		if (prio < tdq->tdq_lowpri)
1597171482Sjeff			tdq->tdq_lowpri = prio;
1598176735Sjeff		else if (tdq->tdq_lowpri == oldpri)
1599176735Sjeff			tdq_setlowpri(tdq, td);
1600177376Sjeff		return;
1601177009Sjeff	}
1602177376Sjeff	td->td_priority = prio;
1603109864Sjeff}
1604109864Sjeff
1605139453Sjhb/*
1606139453Sjhb * Update a thread's priority when it is lent another thread's
1607139453Sjhb * priority.
1608139453Sjhb */
1609109864Sjeffvoid
1610139453Sjhbsched_lend_prio(struct thread *td, u_char prio)
1611139453Sjhb{
1612139453Sjhb
1613139453Sjhb	td->td_flags |= TDF_BORROWING;
1614139453Sjhb	sched_thread_priority(td, prio);
1615139453Sjhb}
1616139453Sjhb
1617139453Sjhb/*
1618139453Sjhb * Restore a thread's priority when priority propagation is
1619139453Sjhb * over.  The prio argument is the minimum priority the thread
1620139453Sjhb * needs to have to satisfy other possible priority lending
1621139453Sjhb * requests.  If the thread's regular priority is less
1622139453Sjhb * important than prio, the thread will keep a priority boost
1623139453Sjhb * of prio.
1624139453Sjhb */
1625139453Sjhbvoid
1626139453Sjhbsched_unlend_prio(struct thread *td, u_char prio)
1627139453Sjhb{
1628139453Sjhb	u_char base_pri;
1629139453Sjhb
1630139453Sjhb	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1631139453Sjhb	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1632163709Sjb		base_pri = td->td_user_pri;
1633139453Sjhb	else
1634139453Sjhb		base_pri = td->td_base_pri;
1635139453Sjhb	if (prio >= base_pri) {
1636139455Sjhb		td->td_flags &= ~TDF_BORROWING;
1637139453Sjhb		sched_thread_priority(td, base_pri);
1638139453Sjhb	} else
1639139453Sjhb		sched_lend_prio(td, prio);
1640139453Sjhb}
1641139453Sjhb
1642171482Sjeff/*
1643171482Sjeff * Standard entry for setting the priority to an absolute value.
1644171482Sjeff */
1645139453Sjhbvoid
1646139453Sjhbsched_prio(struct thread *td, u_char prio)
1647139453Sjhb{
1648139453Sjhb	u_char oldprio;
1649139453Sjhb
1650139453Sjhb	/* First, update the base priority. */
1651139453Sjhb	td->td_base_pri = prio;
1652139453Sjhb
1653139453Sjhb	/*
1654139455Sjhb	 * If the thread is borrowing another thread's priority, don't
1655139453Sjhb	 * ever lower the priority.
1656139453Sjhb	 */
1657139453Sjhb	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1658139453Sjhb		return;
1659139453Sjhb
1660139453Sjhb	/* Change the real priority. */
1661139453Sjhb	oldprio = td->td_priority;
1662139453Sjhb	sched_thread_priority(td, prio);
1663139453Sjhb
1664139453Sjhb	/*
1665139453Sjhb	 * If the thread is on a turnstile, then let the turnstile update
1666139453Sjhb	 * its state.
1667139453Sjhb	 */
1668139453Sjhb	if (TD_ON_LOCK(td) && oldprio != prio)
1669139453Sjhb		turnstile_adjust(td, oldprio);
1670139453Sjhb}
1671139455Sjhb
1672171482Sjeff/*
1673171482Sjeff * Set the base user priority, does not effect current running priority.
1674171482Sjeff */
1675139453Sjhbvoid
1676163709Sjbsched_user_prio(struct thread *td, u_char prio)
1677161599Sdavidxu{
1678161599Sdavidxu
1679163709Sjb	td->td_base_user_pri = prio;
1680216313Sdavidxu	if (td->td_lend_user_pri <= prio)
1681216313Sdavidxu		return;
1682163709Sjb	td->td_user_pri = prio;
1683161599Sdavidxu}
1684161599Sdavidxu
1685161599Sdavidxuvoid
1686161599Sdavidxusched_lend_user_prio(struct thread *td, u_char prio)
1687161599Sdavidxu{
1688161599Sdavidxu
1689174536Sdavidxu	THREAD_LOCK_ASSERT(td, MA_OWNED);
1690216313Sdavidxu	td->td_lend_user_pri = prio;
1691216791Sdavidxu	td->td_user_pri = min(prio, td->td_base_user_pri);
1692216791Sdavidxu	if (td->td_priority > td->td_user_pri)
1693216791Sdavidxu		sched_prio(td, td->td_user_pri);
1694216791Sdavidxu	else if (td->td_priority != td->td_user_pri)
1695216791Sdavidxu		td->td_flags |= TDF_NEEDRESCHED;
1696161599Sdavidxu}
1697161599Sdavidxu
1698171482Sjeff/*
1699171713Sjeff * Handle migration from sched_switch().  This happens only for
1700171713Sjeff * cpu binding.
1701171713Sjeff */
1702171713Sjeffstatic struct mtx *
1703171713Sjeffsched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1704171713Sjeff{
1705171713Sjeff	struct tdq *tdn;
1706171713Sjeff
1707171713Sjeff	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1708171713Sjeff#ifdef SMP
1709177435Sjeff	tdq_load_rem(tdq, td);
1710171713Sjeff	/*
1711171713Sjeff	 * Do the lock dance required to avoid LOR.  We grab an extra
1712171713Sjeff	 * spinlock nesting to prevent preemption while we're
1713171713Sjeff	 * not holding either run-queue lock.
1714171713Sjeff	 */
1715171713Sjeff	spinlock_enter();
1716202889Sattilio	thread_lock_block(td);	/* This releases the lock on tdq. */
1717197223Sattilio
1718197223Sattilio	/*
1719197223Sattilio	 * Acquire both run-queue locks before placing the thread on the new
1720197223Sattilio	 * run-queue to avoid deadlocks created by placing a thread with a
1721197223Sattilio	 * blocked lock on the run-queue of a remote processor.  The deadlock
1722197223Sattilio	 * occurs when a third processor attempts to lock the two queues in
1723197223Sattilio	 * question while the target processor is spinning with its own
1724197223Sattilio	 * run-queue lock held while waiting for the blocked lock to clear.
1725197223Sattilio	 */
1726197223Sattilio	tdq_lock_pair(tdn, tdq);
1727171713Sjeff	tdq_add(tdn, td, flags);
1728177435Sjeff	tdq_notify(tdn, td);
1729197223Sattilio	TDQ_UNLOCK(tdn);
1730171713Sjeff	spinlock_exit();
1731171713Sjeff#endif
1732171713Sjeff	return (TDQ_LOCKPTR(tdn));
1733171713Sjeff}
1734171713Sjeff
1735171713Sjeff/*
1736202889Sattilio * Variadic version of thread_lock_unblock() that does not assume td_lock
1737202889Sattilio * is blocked.
1738171482Sjeff */
1739171482Sjeffstatic inline void
1740171482Sjeffthread_unblock_switch(struct thread *td, struct mtx *mtx)
1741171482Sjeff{
1742171482Sjeff	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1743171482Sjeff	    (uintptr_t)mtx);
1744171482Sjeff}
1745171482Sjeff
1746171482Sjeff/*
1747171482Sjeff * Switch threads.  This function has to handle threads coming in while
1748171482Sjeff * blocked for some reason, running, or idle.  It also must deal with
1749171482Sjeff * migrating a thread from one queue to another as running threads may
1750171482Sjeff * be assigned elsewhere via binding.
1751171482Sjeff */
1752161599Sdavidxuvoid
1753135051Sjuliansched_switch(struct thread *td, struct thread *newtd, int flags)
1754109864Sjeff{
1755165627Sjeff	struct tdq *tdq;
1756164936Sjulian	struct td_sched *ts;
1757171482Sjeff	struct mtx *mtx;
1758171713Sjeff	int srqflag;
1759171482Sjeff	int cpuid;
1760109864Sjeff
1761170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1762177376Sjeff	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
1763109864Sjeff
1764171482Sjeff	cpuid = PCPU_GET(cpuid);
1765171482Sjeff	tdq = TDQ_CPU(cpuid);
1766164936Sjulian	ts = td->td_sched;
1767171713Sjeff	mtx = td->td_lock;
1768171482Sjeff	ts->ts_rltick = ticks;
1769133555Sjeff	td->td_lastcpu = td->td_oncpu;
1770113339Sjulian	td->td_oncpu = NOCPU;
1771132266Sjhb	td->td_flags &= ~TDF_NEEDRESCHED;
1772144777Sups	td->td_owepreempt = 0;
1773178277Sjeff	tdq->tdq_switchcnt++;
1774123434Sjeff	/*
1775171482Sjeff	 * The lock pointer in an idle thread should never change.  Reset it
1776171482Sjeff	 * to CAN_RUN as well.
1777123434Sjeff	 */
1778167327Sjulian	if (TD_IS_IDLETHREAD(td)) {
1779171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1780139334Sjeff		TD_SET_CAN_RUN(td);
1781170293Sjeff	} else if (TD_IS_RUNNING(td)) {
1782171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1783171713Sjeff		srqflag = (flags & SW_PREEMPT) ?
1784170293Sjeff		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1785171713Sjeff		    SRQ_OURSELF|SRQ_YIELDING;
1786212153Smdf#ifdef SMP
1787212115Smdf		if (THREAD_CAN_MIGRATE(td) && !THREAD_CAN_SCHED(td, ts->ts_cpu))
1788212115Smdf			ts->ts_cpu = sched_pickcpu(td, 0);
1789212153Smdf#endif
1790171713Sjeff		if (ts->ts_cpu == cpuid)
1791177435Sjeff			tdq_runq_add(tdq, td, srqflag);
1792212115Smdf		else {
1793212115Smdf			KASSERT(THREAD_CAN_MIGRATE(td) ||
1794212115Smdf			    (ts->ts_flags & TSF_BOUND) != 0,
1795212115Smdf			    ("Thread %p shouldn't migrate", td));
1796171713Sjeff			mtx = sched_switch_migrate(tdq, td, srqflag);
1797212115Smdf		}
1798171482Sjeff	} else {
1799171482Sjeff		/* This thread must be going to sleep. */
1800171482Sjeff		TDQ_LOCK(tdq);
1801202889Sattilio		mtx = thread_lock_block(td);
1802177435Sjeff		tdq_load_rem(tdq, td);
1803171482Sjeff	}
1804171482Sjeff	/*
1805171482Sjeff	 * We enter here with the thread blocked and assigned to the
1806171482Sjeff	 * appropriate cpu run-queue or sleep-queue and with the current
1807171482Sjeff	 * thread-queue locked.
1808171482Sjeff	 */
1809171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1810171482Sjeff	newtd = choosethread();
1811171482Sjeff	/*
1812171482Sjeff	 * Call the MD code to switch contexts if necessary.
1813171482Sjeff	 */
1814145256Sjkoshy	if (td != newtd) {
1815145256Sjkoshy#ifdef	HWPMC_HOOKS
1816145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1817145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1818145256Sjkoshy#endif
1819174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1820172411Sjeff		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1821179297Sjb
1822179297Sjb#ifdef KDTRACE_HOOKS
1823179297Sjb		/*
1824179297Sjb		 * If DTrace has set the active vtime enum to anything
1825179297Sjb		 * other than INACTIVE (0), then it should have set the
1826179297Sjb		 * function to call.
1827179297Sjb		 */
1828179297Sjb		if (dtrace_vtime_active)
1829179297Sjb			(*dtrace_vtime_switch_func)(newtd);
1830179297Sjb#endif
1831179297Sjb
1832171482Sjeff		cpu_switch(td, newtd, mtx);
1833171482Sjeff		/*
1834171482Sjeff		 * We may return from cpu_switch on a different cpu.  However,
1835171482Sjeff		 * we always return with td_lock pointing to the current cpu's
1836171482Sjeff		 * run queue lock.
1837171482Sjeff		 */
1838171482Sjeff		cpuid = PCPU_GET(cpuid);
1839171482Sjeff		tdq = TDQ_CPU(cpuid);
1840174629Sjeff		lock_profile_obtain_lock_success(
1841174629Sjeff		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1842145256Sjkoshy#ifdef	HWPMC_HOOKS
1843145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1844145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1845145256Sjkoshy#endif
1846171482Sjeff	} else
1847171482Sjeff		thread_unblock_switch(td, mtx);
1848171482Sjeff	/*
1849171482Sjeff	 * Assert that all went well and return.
1850171482Sjeff	 */
1851171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1852171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1853171482Sjeff	td->td_oncpu = cpuid;
1854109864Sjeff}
1855109864Sjeff
1856171482Sjeff/*
1857171482Sjeff * Adjust thread priorities as a result of a nice request.
1858171482Sjeff */
1859109864Sjeffvoid
1860130551Sjuliansched_nice(struct proc *p, int nice)
1861109864Sjeff{
1862109864Sjeff	struct thread *td;
1863109864Sjeff
1864130551Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
1865165762Sjeff
1866130551Sjulian	p->p_nice = nice;
1867163709Sjb	FOREACH_THREAD_IN_PROC(p, td) {
1868170293Sjeff		thread_lock(td);
1869163709Sjb		sched_priority(td);
1870165762Sjeff		sched_prio(td, td->td_base_user_pri);
1871170293Sjeff		thread_unlock(td);
1872130551Sjulian	}
1873109864Sjeff}
1874109864Sjeff
1875171482Sjeff/*
1876171482Sjeff * Record the sleep time for the interactivity scorer.
1877171482Sjeff */
1878109864Sjeffvoid
1879177085Sjeffsched_sleep(struct thread *td, int prio)
1880109864Sjeff{
1881165762Sjeff
1882170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1883109864Sjeff
1884172264Sjeff	td->td_slptick = ticks;
1885201347Skib	if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
1886177085Sjeff		td->td_flags |= TDF_CANSWAP;
1887177903Sjeff	if (static_boost == 1 && prio)
1888177085Sjeff		sched_prio(td, prio);
1889177903Sjeff	else if (static_boost && td->td_priority > static_boost)
1890177903Sjeff		sched_prio(td, static_boost);
1891109864Sjeff}
1892109864Sjeff
1893171482Sjeff/*
1894171482Sjeff * Schedule a thread to resume execution and record how long it voluntarily
1895171482Sjeff * slept.  We also update the pctcpu, interactivity, and priority.
1896171482Sjeff */
1897109864Sjeffvoid
1898109864Sjeffsched_wakeup(struct thread *td)
1899109864Sjeff{
1900166229Sjeff	struct td_sched *ts;
1901171482Sjeff	int slptick;
1902165762Sjeff
1903170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1904166229Sjeff	ts = td->td_sched;
1905177085Sjeff	td->td_flags &= ~TDF_CANSWAP;
1906109864Sjeff	/*
1907165762Sjeff	 * If we slept for more than a tick update our interactivity and
1908165762Sjeff	 * priority.
1909109864Sjeff	 */
1910172264Sjeff	slptick = td->td_slptick;
1911172264Sjeff	td->td_slptick = 0;
1912171482Sjeff	if (slptick && slptick != ticks) {
1913166208Sjeff		u_int hzticks;
1914109864Sjeff
1915171482Sjeff		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1916171482Sjeff		ts->ts_slptime += hzticks;
1917165819Sjeff		sched_interact_update(td);
1918166229Sjeff		sched_pctcpu_update(ts);
1919109864Sjeff	}
1920166229Sjeff	/* Reset the slice value after we sleep. */
1921166229Sjeff	ts->ts_slice = sched_slice;
1922166190Sjeff	sched_add(td, SRQ_BORING);
1923109864Sjeff}
1924109864Sjeff
1925109864Sjeff/*
1926109864Sjeff * Penalize the parent for creating a new child and initialize the child's
1927109864Sjeff * priority.
1928109864Sjeff */
1929109864Sjeffvoid
1930163709Sjbsched_fork(struct thread *td, struct thread *child)
1931109864Sjeff{
1932170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1933164936Sjulian	sched_fork_thread(td, child);
1934165762Sjeff	/*
1935165762Sjeff	 * Penalize the parent and child for forking.
1936165762Sjeff	 */
1937165762Sjeff	sched_interact_fork(child);
1938165762Sjeff	sched_priority(child);
1939171482Sjeff	td->td_sched->ts_runtime += tickincr;
1940165762Sjeff	sched_interact_update(td);
1941165762Sjeff	sched_priority(td);
1942164936Sjulian}
1943109864Sjeff
1944171482Sjeff/*
1945171482Sjeff * Fork a new thread, may be within the same process.
1946171482Sjeff */
1947164936Sjulianvoid
1948164936Sjuliansched_fork_thread(struct thread *td, struct thread *child)
1949164936Sjulian{
1950164936Sjulian	struct td_sched *ts;
1951164936Sjulian	struct td_sched *ts2;
1952164936Sjulian
1953177426Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1954165762Sjeff	/*
1955165762Sjeff	 * Initialize child.
1956165762Sjeff	 */
1957177426Sjeff	ts = td->td_sched;
1958177426Sjeff	ts2 = child->td_sched;
1959171482Sjeff	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1960176735Sjeff	child->td_cpuset = cpuset_ref(td->td_cpuset);
1961164936Sjulian	ts2->ts_cpu = ts->ts_cpu;
1962177426Sjeff	ts2->ts_flags = 0;
1963165762Sjeff	/*
1964217078Sjhb	 * Grab our parents cpu estimation information.
1965165762Sjeff	 */
1966164936Sjulian	ts2->ts_ticks = ts->ts_ticks;
1967164936Sjulian	ts2->ts_ltick = ts->ts_ltick;
1968199764Sivoras	ts2->ts_incrtick = ts->ts_incrtick;
1969164936Sjulian	ts2->ts_ftick = ts->ts_ftick;
1970165762Sjeff	/*
1971217078Sjhb	 * Do not inherit any borrowed priority from the parent.
1972217078Sjhb	 */
1973217078Sjhb	child->td_priority = child->td_base_pri;
1974217078Sjhb	/*
1975165762Sjeff	 * And update interactivity score.
1976165762Sjeff	 */
1977171482Sjeff	ts2->ts_slptime = ts->ts_slptime;
1978171482Sjeff	ts2->ts_runtime = ts->ts_runtime;
1979165762Sjeff	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
1980187357Sjeff#ifdef KTR
1981187357Sjeff	bzero(ts2->ts_name, sizeof(ts2->ts_name));
1982187357Sjeff#endif
1983113357Sjeff}
1984113357Sjeff
1985171482Sjeff/*
1986171482Sjeff * Adjust the priority class of a thread.
1987171482Sjeff */
1988113357Sjeffvoid
1989163709Sjbsched_class(struct thread *td, int class)
1990113357Sjeff{
1991113357Sjeff
1992170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1993163709Sjb	if (td->td_pri_class == class)
1994113357Sjeff		return;
1995163709Sjb	td->td_pri_class = class;
1996109864Sjeff}
1997109864Sjeff
1998109864Sjeff/*
1999109864Sjeff * Return some of the child's priority and interactivity to the parent.
2000109864Sjeff */
2001109864Sjeffvoid
2002164939Sjuliansched_exit(struct proc *p, struct thread *child)
2003109864Sjeff{
2004165762Sjeff	struct thread *td;
2005113372Sjeff
2006187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2007187357Sjeff	    "prio:td", child->td_priority);
2008177368Sjeff	PROC_LOCK_ASSERT(p, MA_OWNED);
2009165762Sjeff	td = FIRST_THREAD_IN_PROC(p);
2010165762Sjeff	sched_exit_thread(td, child);
2011113372Sjeff}
2012113372Sjeff
2013171482Sjeff/*
2014171482Sjeff * Penalize another thread for the time spent on this one.  This helps to
2015171482Sjeff * worsen the priority and interactivity of processes which schedule batch
2016171482Sjeff * jobs such as make.  This has little effect on the make process itself but
2017171482Sjeff * causes new processes spawned by it to receive worse scores immediately.
2018171482Sjeff */
2019113372Sjeffvoid
2020164939Sjuliansched_exit_thread(struct thread *td, struct thread *child)
2021164936Sjulian{
2022165762Sjeff
2023187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2024187357Sjeff	    "prio:td", child->td_priority);
2025165762Sjeff	/*
2026165762Sjeff	 * Give the child's runtime to the parent without returning the
2027165762Sjeff	 * sleep time as a penalty to the parent.  This causes shells that
2028165762Sjeff	 * launch expensive things to mark their children as expensive.
2029165762Sjeff	 */
2030170293Sjeff	thread_lock(td);
2031171482Sjeff	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2032164939Sjulian	sched_interact_update(td);
2033165762Sjeff	sched_priority(td);
2034170293Sjeff	thread_unlock(td);
2035164936Sjulian}
2036164936Sjulian
2037177005Sjeffvoid
2038177005Sjeffsched_preempt(struct thread *td)
2039177005Sjeff{
2040177005Sjeff	struct tdq *tdq;
2041177005Sjeff
2042177005Sjeff	thread_lock(td);
2043177005Sjeff	tdq = TDQ_SELF();
2044177005Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2045177005Sjeff	tdq->tdq_ipipending = 0;
2046177005Sjeff	if (td->td_priority > tdq->tdq_lowpri) {
2047178272Sjeff		int flags;
2048178272Sjeff
2049178272Sjeff		flags = SW_INVOL | SW_PREEMPT;
2050177005Sjeff		if (td->td_critnest > 1)
2051177005Sjeff			td->td_owepreempt = 1;
2052178272Sjeff		else if (TD_IS_IDLETHREAD(td))
2053178272Sjeff			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2054177005Sjeff		else
2055178272Sjeff			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2056177005Sjeff	}
2057177005Sjeff	thread_unlock(td);
2058177005Sjeff}
2059177005Sjeff
2060171482Sjeff/*
2061171482Sjeff * Fix priorities on return to user-space.  Priorities may be elevated due
2062171482Sjeff * to static priorities in msleep() or similar.
2063171482Sjeff */
2064164936Sjulianvoid
2065164936Sjuliansched_userret(struct thread *td)
2066164936Sjulian{
2067164936Sjulian	/*
2068164936Sjulian	 * XXX we cheat slightly on the locking here to avoid locking in
2069164936Sjulian	 * the usual case.  Setting td_priority here is essentially an
2070164936Sjulian	 * incomplete workaround for not setting it properly elsewhere.
2071164936Sjulian	 * Now that some interrupt handlers are threads, not setting it
2072164936Sjulian	 * properly elsewhere can clobber it in the window between setting
2073164936Sjulian	 * it here and returning to user mode, so don't waste time setting
2074164936Sjulian	 * it perfectly here.
2075164936Sjulian	 */
2076164936Sjulian	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2077164936Sjulian	    ("thread with borrowed priority returning to userland"));
2078164936Sjulian	if (td->td_priority != td->td_user_pri) {
2079170293Sjeff		thread_lock(td);
2080164936Sjulian		td->td_priority = td->td_user_pri;
2081164936Sjulian		td->td_base_pri = td->td_user_pri;
2082177005Sjeff		tdq_setlowpri(TDQ_SELF(), td);
2083170293Sjeff		thread_unlock(td);
2084164936Sjulian        }
2085164936Sjulian}
2086164936Sjulian
2087171482Sjeff/*
2088171482Sjeff * Handle a stathz tick.  This is really only relevant for timeshare
2089171482Sjeff * threads.
2090171482Sjeff */
2091164936Sjulianvoid
2092121127Sjeffsched_clock(struct thread *td)
2093109864Sjeff{
2094164936Sjulian	struct tdq *tdq;
2095164936Sjulian	struct td_sched *ts;
2096109864Sjeff
2097171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2098164936Sjulian	tdq = TDQ_SELF();
2099172409Sjeff#ifdef SMP
2100133427Sjeff	/*
2101172409Sjeff	 * We run the long term load balancer infrequently on the first cpu.
2102172409Sjeff	 */
2103172409Sjeff	if (balance_tdq == tdq) {
2104172409Sjeff		if (balance_ticks && --balance_ticks == 0)
2105172409Sjeff			sched_balance();
2106172409Sjeff	}
2107172409Sjeff#endif
2108172409Sjeff	/*
2109178277Sjeff	 * Save the old switch count so we have a record of the last ticks
2110178277Sjeff	 * activity.   Initialize the new switch count based on our load.
2111178277Sjeff	 * If there is some activity seed it to reflect that.
2112178277Sjeff	 */
2113178277Sjeff	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
2114178471Sjeff	tdq->tdq_switchcnt = tdq->tdq_load;
2115178277Sjeff	/*
2116165766Sjeff	 * Advance the insert index once for each tick to ensure that all
2117165766Sjeff	 * threads get a chance to run.
2118133427Sjeff	 */
2119165766Sjeff	if (tdq->tdq_idx == tdq->tdq_ridx) {
2120165766Sjeff		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2121165766Sjeff		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2122165766Sjeff			tdq->tdq_ridx = tdq->tdq_idx;
2123165766Sjeff	}
2124165766Sjeff	ts = td->td_sched;
2125175104Sjeff	if (td->td_pri_class & PRI_FIFO_BIT)
2126113357Sjeff		return;
2127217291Sjhb	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2128175104Sjeff		/*
2129175104Sjeff		 * We used a tick; charge it to the thread so
2130175104Sjeff		 * that we can compute our interactivity.
2131175104Sjeff		 */
2132175104Sjeff		td->td_sched->ts_runtime += tickincr;
2133175104Sjeff		sched_interact_update(td);
2134177009Sjeff		sched_priority(td);
2135175104Sjeff	}
2136113357Sjeff	/*
2137109864Sjeff	 * We used up one time slice.
2138109864Sjeff	 */
2139164936Sjulian	if (--ts->ts_slice > 0)
2140113357Sjeff		return;
2141109864Sjeff	/*
2142177009Sjeff	 * We're out of time, force a requeue at userret().
2143109864Sjeff	 */
2144177009Sjeff	ts->ts_slice = sched_slice;
2145113357Sjeff	td->td_flags |= TDF_NEEDRESCHED;
2146109864Sjeff}
2147109864Sjeff
2148171482Sjeff/*
2149171482Sjeff * Called once per hz tick.  Used for cpu utilization information.  This
2150171482Sjeff * is easier than trying to scale based on stathz.
2151171482Sjeff */
2152171482Sjeffvoid
2153212541Smavsched_tick(int cnt)
2154171482Sjeff{
2155171482Sjeff	struct td_sched *ts;
2156171482Sjeff
2157171482Sjeff	ts = curthread->td_sched;
2158180607Sjeff	/*
2159180607Sjeff	 * Ticks is updated asynchronously on a single cpu.  Check here to
2160180607Sjeff	 * avoid incrementing ts_ticks multiple times in a single tick.
2161180607Sjeff	 */
2162199764Sivoras	if (ts->ts_incrtick == ticks)
2163180607Sjeff		return;
2164171482Sjeff	/* Adjust ticks for pctcpu */
2165212541Smav	ts->ts_ticks += cnt << SCHED_TICK_SHIFT;
2166171482Sjeff	ts->ts_ltick = ticks;
2167199764Sivoras	ts->ts_incrtick = ticks;
2168171482Sjeff	/*
2169215102Sattilio	 * Update if we've exceeded our desired tick threshold by over one
2170171482Sjeff	 * second.
2171171482Sjeff	 */
2172171482Sjeff	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2173171482Sjeff		sched_pctcpu_update(ts);
2174171482Sjeff}
2175171482Sjeff
2176171482Sjeff/*
2177171482Sjeff * Return whether the current CPU has runnable tasks.  Used for in-kernel
2178171482Sjeff * cooperative idle threads.
2179171482Sjeff */
2180109864Sjeffint
2181109864Sjeffsched_runnable(void)
2182109864Sjeff{
2183164936Sjulian	struct tdq *tdq;
2184115998Sjeff	int load;
2185109864Sjeff
2186115998Sjeff	load = 1;
2187115998Sjeff
2188164936Sjulian	tdq = TDQ_SELF();
2189121605Sjeff	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2190165620Sjeff		if (tdq->tdq_load > 0)
2191121605Sjeff			goto out;
2192121605Sjeff	} else
2193165620Sjeff		if (tdq->tdq_load - 1 > 0)
2194121605Sjeff			goto out;
2195115998Sjeff	load = 0;
2196115998Sjeffout:
2197115998Sjeff	return (load);
2198109864Sjeff}
2199109864Sjeff
2200171482Sjeff/*
2201171482Sjeff * Choose the highest priority thread to run.  The thread is removed from
2202171482Sjeff * the run-queue while running however the load remains.  For SMP we set
2203171482Sjeff * the tdq in the global idle bitmask if it idles here.
2204171482Sjeff */
2205166190Sjeffstruct thread *
2206109970Sjeffsched_choose(void)
2207109970Sjeff{
2208177435Sjeff	struct thread *td;
2209164936Sjulian	struct tdq *tdq;
2210109970Sjeff
2211164936Sjulian	tdq = TDQ_SELF();
2212171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2213177435Sjeff	td = tdq_choose(tdq);
2214177435Sjeff	if (td) {
2215177435Sjeff		td->td_sched->ts_ltick = ticks;
2216177435Sjeff		tdq_runq_rem(tdq, td);
2217177903Sjeff		tdq->tdq_lowpri = td->td_priority;
2218177435Sjeff		return (td);
2219109864Sjeff	}
2220177903Sjeff	tdq->tdq_lowpri = PRI_MAX_IDLE;
2221176735Sjeff	return (PCPU_GET(idlethread));
2222109864Sjeff}
2223109864Sjeff
2224171482Sjeff/*
2225171482Sjeff * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2226171482Sjeff * we always request it once we exit a critical section.
2227171482Sjeff */
2228171482Sjeffstatic inline void
2229171482Sjeffsched_setpreempt(struct thread *td)
2230166190Sjeff{
2231166190Sjeff	struct thread *ctd;
2232166190Sjeff	int cpri;
2233166190Sjeff	int pri;
2234166190Sjeff
2235177005Sjeff	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2236177005Sjeff
2237166190Sjeff	ctd = curthread;
2238166190Sjeff	pri = td->td_priority;
2239166190Sjeff	cpri = ctd->td_priority;
2240177005Sjeff	if (pri < cpri)
2241177005Sjeff		ctd->td_flags |= TDF_NEEDRESCHED;
2242166190Sjeff	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2243171482Sjeff		return;
2244177005Sjeff	if (!sched_shouldpreempt(pri, cpri, 0))
2245171482Sjeff		return;
2246171482Sjeff	ctd->td_owepreempt = 1;
2247166190Sjeff}
2248166190Sjeff
2249171482Sjeff/*
2250177009Sjeff * Add a thread to a thread queue.  Select the appropriate runq and add the
2251177009Sjeff * thread to it.  This is the internal function called when the tdq is
2252177009Sjeff * predetermined.
2253171482Sjeff */
2254109864Sjeffvoid
2255171482Sjefftdq_add(struct tdq *tdq, struct thread *td, int flags)
2256109864Sjeff{
2257109864Sjeff
2258171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2259166190Sjeff	KASSERT((td->td_inhibitors == 0),
2260166190Sjeff	    ("sched_add: trying to run inhibited thread"));
2261166190Sjeff	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2262166190Sjeff	    ("sched_add: bad thread state"));
2263172207Sjeff	KASSERT(td->td_flags & TDF_INMEM,
2264172207Sjeff	    ("sched_add: thread swapped out"));
2265171482Sjeff
2266171482Sjeff	if (td->td_priority < tdq->tdq_lowpri)
2267171482Sjeff		tdq->tdq_lowpri = td->td_priority;
2268177435Sjeff	tdq_runq_add(tdq, td, flags);
2269177435Sjeff	tdq_load_add(tdq, td);
2270171482Sjeff}
2271171482Sjeff
2272171482Sjeff/*
2273171482Sjeff * Select the target thread queue and add a thread to it.  Request
2274171482Sjeff * preemption or IPI a remote processor if required.
2275171482Sjeff */
2276171482Sjeffvoid
2277171482Sjeffsched_add(struct thread *td, int flags)
2278171482Sjeff{
2279171482Sjeff	struct tdq *tdq;
2280171482Sjeff#ifdef SMP
2281171482Sjeff	int cpu;
2282171482Sjeff#endif
2283187357Sjeff
2284187357Sjeff	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
2285187357Sjeff	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
2286187357Sjeff	    sched_tdname(curthread));
2287187357Sjeff	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
2288187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(td));
2289171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2290166108Sjeff	/*
2291171482Sjeff	 * Recalculate the priority before we select the target cpu or
2292171482Sjeff	 * run-queue.
2293166108Sjeff	 */
2294171482Sjeff	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2295171482Sjeff		sched_priority(td);
2296171482Sjeff#ifdef SMP
2297171482Sjeff	/*
2298171482Sjeff	 * Pick the destination cpu and if it isn't ours transfer to the
2299171482Sjeff	 * target cpu.
2300171482Sjeff	 */
2301177435Sjeff	cpu = sched_pickcpu(td, flags);
2302177435Sjeff	tdq = sched_setcpu(td, cpu, flags);
2303171482Sjeff	tdq_add(tdq, td, flags);
2304177009Sjeff	if (cpu != PCPU_GET(cpuid)) {
2305177435Sjeff		tdq_notify(tdq, td);
2306166108Sjeff		return;
2307166108Sjeff	}
2308171482Sjeff#else
2309171482Sjeff	tdq = TDQ_SELF();
2310171482Sjeff	TDQ_LOCK(tdq);
2311171482Sjeff	/*
2312171482Sjeff	 * Now that the thread is moving to the run-queue, set the lock
2313171482Sjeff	 * to the scheduler's lock.
2314171482Sjeff	 */
2315171482Sjeff	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2316171482Sjeff	tdq_add(tdq, td, flags);
2317166108Sjeff#endif
2318171482Sjeff	if (!(flags & SRQ_YIELDING))
2319171482Sjeff		sched_setpreempt(td);
2320109864Sjeff}
2321109864Sjeff
2322171482Sjeff/*
2323171482Sjeff * Remove a thread from a run-queue without running it.  This is used
2324171482Sjeff * when we're stealing a thread from a remote queue.  Otherwise all threads
2325171482Sjeff * exit by calling sched_exit_thread() and sched_throw() themselves.
2326171482Sjeff */
2327109864Sjeffvoid
2328121127Sjeffsched_rem(struct thread *td)
2329109864Sjeff{
2330164936Sjulian	struct tdq *tdq;
2331113357Sjeff
2332187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
2333187357Sjeff	    "prio:%d", td->td_priority);
2334177435Sjeff	tdq = TDQ_CPU(td->td_sched->ts_cpu);
2335171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2336171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2337166190Sjeff	KASSERT(TD_ON_RUNQ(td),
2338164936Sjulian	    ("sched_rem: thread not on run queue"));
2339177435Sjeff	tdq_runq_rem(tdq, td);
2340177435Sjeff	tdq_load_rem(tdq, td);
2341166190Sjeff	TD_SET_CAN_RUN(td);
2342176735Sjeff	if (td->td_priority == tdq->tdq_lowpri)
2343176735Sjeff		tdq_setlowpri(tdq, NULL);
2344109864Sjeff}
2345109864Sjeff
2346171482Sjeff/*
2347171482Sjeff * Fetch cpu utilization information.  Updates on demand.
2348171482Sjeff */
2349109864Sjefffixpt_t
2350121127Sjeffsched_pctcpu(struct thread *td)
2351109864Sjeff{
2352109864Sjeff	fixpt_t pctcpu;
2353164936Sjulian	struct td_sched *ts;
2354109864Sjeff
2355109864Sjeff	pctcpu = 0;
2356164936Sjulian	ts = td->td_sched;
2357164936Sjulian	if (ts == NULL)
2358121290Sjeff		return (0);
2359109864Sjeff
2360208787Sjhb	THREAD_LOCK_ASSERT(td, MA_OWNED);
2361164936Sjulian	if (ts->ts_ticks) {
2362109864Sjeff		int rtick;
2363109864Sjeff
2364165796Sjeff		sched_pctcpu_update(ts);
2365109864Sjeff		/* How many rtick per second ? */
2366165762Sjeff		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2367165762Sjeff		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2368109864Sjeff	}
2369109864Sjeff
2370109864Sjeff	return (pctcpu);
2371109864Sjeff}
2372109864Sjeff
2373176735Sjeff/*
2374176735Sjeff * Enforce affinity settings for a thread.  Called after adjustments to
2375176735Sjeff * cpumask.
2376176735Sjeff */
2377176729Sjeffvoid
2378176729Sjeffsched_affinity(struct thread *td)
2379176729Sjeff{
2380176735Sjeff#ifdef SMP
2381176735Sjeff	struct td_sched *ts;
2382176735Sjeff
2383176735Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2384176735Sjeff	ts = td->td_sched;
2385176735Sjeff	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2386176735Sjeff		return;
2387189787Sjeff	if (TD_ON_RUNQ(td)) {
2388189787Sjeff		sched_rem(td);
2389189787Sjeff		sched_add(td, SRQ_BORING);
2390189787Sjeff		return;
2391189787Sjeff	}
2392176735Sjeff	if (!TD_IS_RUNNING(td))
2393176735Sjeff		return;
2394176735Sjeff	/*
2395212115Smdf	 * Force a switch before returning to userspace.  If the
2396212115Smdf	 * target thread is not running locally send an ipi to force
2397212115Smdf	 * the issue.
2398176735Sjeff	 */
2399212974Sjhb	td->td_flags |= TDF_NEEDRESCHED;
2400212115Smdf	if (td != curthread)
2401212115Smdf		ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
2402176735Sjeff#endif
2403176729Sjeff}
2404176729Sjeff
2405171482Sjeff/*
2406171482Sjeff * Bind a thread to a target cpu.
2407171482Sjeff */
2408122038Sjeffvoid
2409122038Sjeffsched_bind(struct thread *td, int cpu)
2410122038Sjeff{
2411164936Sjulian	struct td_sched *ts;
2412122038Sjeff
2413171713Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2414208391Sjhb	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
2415164936Sjulian	ts = td->td_sched;
2416166137Sjeff	if (ts->ts_flags & TSF_BOUND)
2417166152Sjeff		sched_unbind(td);
2418212115Smdf	KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2419164936Sjulian	ts->ts_flags |= TSF_BOUND;
2420166137Sjeff	sched_pin();
2421123433Sjeff	if (PCPU_GET(cpuid) == cpu)
2422122038Sjeff		return;
2423166137Sjeff	ts->ts_cpu = cpu;
2424122038Sjeff	/* When we return from mi_switch we'll be on the correct cpu. */
2425131527Sphk	mi_switch(SW_VOL, NULL);
2426122038Sjeff}
2427122038Sjeff
2428171482Sjeff/*
2429171482Sjeff * Release a bound thread.
2430171482Sjeff */
2431122038Sjeffvoid
2432122038Sjeffsched_unbind(struct thread *td)
2433122038Sjeff{
2434165762Sjeff	struct td_sched *ts;
2435165762Sjeff
2436170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2437208391Sjhb	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
2438165762Sjeff	ts = td->td_sched;
2439166137Sjeff	if ((ts->ts_flags & TSF_BOUND) == 0)
2440166137Sjeff		return;
2441165762Sjeff	ts->ts_flags &= ~TSF_BOUND;
2442165762Sjeff	sched_unpin();
2443122038Sjeff}
2444122038Sjeff
2445109864Sjeffint
2446145256Sjkoshysched_is_bound(struct thread *td)
2447145256Sjkoshy{
2448170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2449164936Sjulian	return (td->td_sched->ts_flags & TSF_BOUND);
2450145256Sjkoshy}
2451145256Sjkoshy
2452171482Sjeff/*
2453171482Sjeff * Basic yield call.
2454171482Sjeff */
2455159630Sdavidxuvoid
2456159630Sdavidxusched_relinquish(struct thread *td)
2457159630Sdavidxu{
2458170293Sjeff	thread_lock(td);
2459178272Sjeff	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
2460170293Sjeff	thread_unlock(td);
2461159630Sdavidxu}
2462159630Sdavidxu
2463171482Sjeff/*
2464171482Sjeff * Return the total system load.
2465171482Sjeff */
2466145256Sjkoshyint
2467125289Sjeffsched_load(void)
2468125289Sjeff{
2469125289Sjeff#ifdef SMP
2470125289Sjeff	int total;
2471125289Sjeff	int i;
2472125289Sjeff
2473125289Sjeff	total = 0;
2474209059Sjhb	CPU_FOREACH(i)
2475176735Sjeff		total += TDQ_CPU(i)->tdq_sysload;
2476125289Sjeff	return (total);
2477125289Sjeff#else
2478165620Sjeff	return (TDQ_SELF()->tdq_sysload);
2479125289Sjeff#endif
2480125289Sjeff}
2481125289Sjeff
2482125289Sjeffint
2483109864Sjeffsched_sizeof_proc(void)
2484109864Sjeff{
2485109864Sjeff	return (sizeof(struct proc));
2486109864Sjeff}
2487109864Sjeff
2488109864Sjeffint
2489109864Sjeffsched_sizeof_thread(void)
2490109864Sjeff{
2491109864Sjeff	return (sizeof(struct thread) + sizeof(struct td_sched));
2492109864Sjeff}
2493159570Sdavidxu
2494191676Sjeff#ifdef SMP
2495191676Sjeff#define	TDQ_IDLESPIN(tdq)						\
2496191676Sjeff    ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
2497191676Sjeff#else
2498191676Sjeff#define	TDQ_IDLESPIN(tdq)	1
2499191676Sjeff#endif
2500191676Sjeff
2501166190Sjeff/*
2502166190Sjeff * The actual idle process.
2503166190Sjeff */
2504166190Sjeffvoid
2505166190Sjeffsched_idletd(void *dummy)
2506166190Sjeff{
2507166190Sjeff	struct thread *td;
2508171482Sjeff	struct tdq *tdq;
2509178277Sjeff	int switchcnt;
2510178277Sjeff	int i;
2511166190Sjeff
2512191643Sjeff	mtx_assert(&Giant, MA_NOTOWNED);
2513166190Sjeff	td = curthread;
2514171482Sjeff	tdq = TDQ_SELF();
2515171482Sjeff	for (;;) {
2516171482Sjeff#ifdef SMP
2517178277Sjeff		if (tdq_idled(tdq) == 0)
2518178277Sjeff			continue;
2519171482Sjeff#endif
2520178277Sjeff		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2521178277Sjeff		/*
2522178277Sjeff		 * If we're switching very frequently, spin while checking
2523178277Sjeff		 * for load rather than entering a low power state that
2524191643Sjeff		 * may require an IPI.  However, don't do any busy
2525191643Sjeff		 * loops while on SMT machines as this simply steals
2526191643Sjeff		 * cycles from cores doing useful work.
2527178277Sjeff		 */
2528191676Sjeff		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
2529178277Sjeff			for (i = 0; i < sched_idlespins; i++) {
2530178277Sjeff				if (tdq->tdq_load)
2531178277Sjeff					break;
2532178277Sjeff				cpu_spinwait();
2533178277Sjeff			}
2534178277Sjeff		}
2535191643Sjeff		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2536212416Smav		if (tdq->tdq_load == 0) {
2537212416Smav			tdq->tdq_cpu_idle = 1;
2538212416Smav			if (tdq->tdq_load == 0) {
2539212541Smav				cpu_idle(switchcnt > sched_idlespinthresh * 4);
2540212416Smav				tdq->tdq_switchcnt++;
2541212416Smav			}
2542212416Smav			tdq->tdq_cpu_idle = 0;
2543212416Smav		}
2544178277Sjeff		if (tdq->tdq_load) {
2545178277Sjeff			thread_lock(td);
2546178277Sjeff			mi_switch(SW_VOL | SWT_IDLE, NULL);
2547178277Sjeff			thread_unlock(td);
2548178277Sjeff		}
2549171482Sjeff	}
2550166190Sjeff}
2551166190Sjeff
2552170293Sjeff/*
2553170293Sjeff * A CPU is entering for the first time or a thread is exiting.
2554170293Sjeff */
2555170293Sjeffvoid
2556170293Sjeffsched_throw(struct thread *td)
2557170293Sjeff{
2558172411Sjeff	struct thread *newtd;
2559171482Sjeff	struct tdq *tdq;
2560171482Sjeff
2561171482Sjeff	tdq = TDQ_SELF();
2562170293Sjeff	if (td == NULL) {
2563171482Sjeff		/* Correct spinlock nesting and acquire the correct lock. */
2564171482Sjeff		TDQ_LOCK(tdq);
2565170293Sjeff		spinlock_exit();
2566170293Sjeff	} else {
2567171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2568177435Sjeff		tdq_load_rem(tdq, td);
2569174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2570170293Sjeff	}
2571170293Sjeff	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2572172411Sjeff	newtd = choosethread();
2573172411Sjeff	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2574170293Sjeff	PCPU_SET(switchtime, cpu_ticks());
2575170293Sjeff	PCPU_SET(switchticks, ticks);
2576172411Sjeff	cpu_throw(td, newtd);		/* doesn't return */
2577170293Sjeff}
2578170293Sjeff
2579171482Sjeff/*
2580171482Sjeff * This is called from fork_exit().  Just acquire the correct locks and
2581171482Sjeff * let fork do the rest of the work.
2582171482Sjeff */
2583170293Sjeffvoid
2584170600Sjeffsched_fork_exit(struct thread *td)
2585170293Sjeff{
2586171482Sjeff	struct td_sched *ts;
2587171482Sjeff	struct tdq *tdq;
2588171482Sjeff	int cpuid;
2589170293Sjeff
2590170293Sjeff	/*
2591170293Sjeff	 * Finish setting up thread glue so that it begins execution in a
2592171482Sjeff	 * non-nested critical section with the scheduler lock held.
2593170293Sjeff	 */
2594171482Sjeff	cpuid = PCPU_GET(cpuid);
2595171482Sjeff	tdq = TDQ_CPU(cpuid);
2596171482Sjeff	ts = td->td_sched;
2597171482Sjeff	if (TD_IS_IDLETHREAD(td))
2598171482Sjeff		td->td_lock = TDQ_LOCKPTR(tdq);
2599171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2600171482Sjeff	td->td_oncpu = cpuid;
2601172411Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2602174629Sjeff	lock_profile_obtain_lock_success(
2603174629Sjeff	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2604170293Sjeff}
2605170293Sjeff
2606187357Sjeff/*
2607187357Sjeff * Create on first use to catch odd startup conditons.
2608187357Sjeff */
2609187357Sjeffchar *
2610187357Sjeffsched_tdname(struct thread *td)
2611187357Sjeff{
2612187357Sjeff#ifdef KTR
2613187357Sjeff	struct td_sched *ts;
2614187357Sjeff
2615187357Sjeff	ts = td->td_sched;
2616187357Sjeff	if (ts->ts_name[0] == '\0')
2617187357Sjeff		snprintf(ts->ts_name, sizeof(ts->ts_name),
2618187357Sjeff		    "%s tid %d", td->td_name, td->td_tid);
2619187357Sjeff	return (ts->ts_name);
2620187357Sjeff#else
2621187357Sjeff	return (td->td_name);
2622187357Sjeff#endif
2623187357Sjeff}
2624187357Sjeff
2625184439Sivoras#ifdef SMP
2626184439Sivoras
2627184439Sivoras/*
2628184439Sivoras * Build the CPU topology dump string. Is recursively called to collect
2629184439Sivoras * the topology tree.
2630184439Sivoras */
2631184439Sivorasstatic int
2632184439Sivorassysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
2633184439Sivoras    int indent)
2634184439Sivoras{
2635184439Sivoras	int i, first;
2636184439Sivoras
2637184439Sivoras	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
2638212821Savg	    "", 1 + indent / 2, cg->cg_level);
2639184439Sivoras	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"0x%x\">", indent, "",
2640184439Sivoras	    cg->cg_count, cg->cg_mask);
2641184439Sivoras	first = TRUE;
2642184439Sivoras	for (i = 0; i < MAXCPU; i++) {
2643184439Sivoras		if ((cg->cg_mask & (1 << i)) != 0) {
2644184439Sivoras			if (!first)
2645184439Sivoras				sbuf_printf(sb, ", ");
2646184439Sivoras			else
2647184439Sivoras				first = FALSE;
2648184439Sivoras			sbuf_printf(sb, "%d", i);
2649184439Sivoras		}
2650184439Sivoras	}
2651184439Sivoras	sbuf_printf(sb, "</cpu>\n");
2652184439Sivoras
2653184439Sivoras	if (cg->cg_flags != 0) {
2654210117Sivoras		sbuf_printf(sb, "%*s <flags>", indent, "");
2655184439Sivoras		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
2656208982Sivoras			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
2657208983Sivoras		if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
2658208983Sivoras			sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
2659191643Sjeff		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
2660208983Sivoras			sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
2661210117Sivoras		sbuf_printf(sb, "</flags>\n");
2662184439Sivoras	}
2663184439Sivoras
2664184439Sivoras	if (cg->cg_children > 0) {
2665184439Sivoras		sbuf_printf(sb, "%*s <children>\n", indent, "");
2666184439Sivoras		for (i = 0; i < cg->cg_children; i++)
2667184439Sivoras			sysctl_kern_sched_topology_spec_internal(sb,
2668184439Sivoras			    &cg->cg_child[i], indent+2);
2669184439Sivoras		sbuf_printf(sb, "%*s </children>\n", indent, "");
2670184439Sivoras	}
2671184439Sivoras	sbuf_printf(sb, "%*s</group>\n", indent, "");
2672184439Sivoras	return (0);
2673184439Sivoras}
2674184439Sivoras
2675184439Sivoras/*
2676184439Sivoras * Sysctl handler for retrieving topology dump. It's a wrapper for
2677184439Sivoras * the recursive sysctl_kern_smp_topology_spec_internal().
2678184439Sivoras */
2679184439Sivorasstatic int
2680184439Sivorassysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
2681184439Sivoras{
2682184439Sivoras	struct sbuf *topo;
2683184439Sivoras	int err;
2684184439Sivoras
2685184439Sivoras	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
2686184439Sivoras
2687184570Sivoras	topo = sbuf_new(NULL, NULL, 500, SBUF_AUTOEXTEND);
2688184439Sivoras	if (topo == NULL)
2689184439Sivoras		return (ENOMEM);
2690184439Sivoras
2691184439Sivoras	sbuf_printf(topo, "<groups>\n");
2692184439Sivoras	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
2693184439Sivoras	sbuf_printf(topo, "</groups>\n");
2694184439Sivoras
2695184439Sivoras	if (err == 0) {
2696184439Sivoras		sbuf_finish(topo);
2697184439Sivoras		err = SYSCTL_OUT(req, sbuf_data(topo), sbuf_len(topo));
2698184439Sivoras	}
2699184439Sivoras	sbuf_delete(topo);
2700184439Sivoras	return (err);
2701184439Sivoras}
2702214510Sdavidxu
2703184439Sivoras#endif
2704184439Sivoras
2705177435SjeffSYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2706171482SjeffSYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2707165762Sjeff    "Scheduler name");
2708171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2709171482Sjeff    "Slice size for timeshare threads");
2710171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2711171482Sjeff     "Interactivity score threshold");
2712171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2713171482Sjeff     0,"Min priority for preemption, lower priorities have greater precedence");
2714177085SjeffSYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost,
2715177085Sjeff     0,"Controls whether static kernel priorities are assigned to sleeping threads.");
2716178277SjeffSYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins,
2717178277Sjeff     0,"Number of times idle will spin waiting for new work.");
2718178277SjeffSYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW, &sched_idlespinthresh,
2719178277Sjeff     0,"Threshold before we will permit idle spinning.");
2720166108Sjeff#ifdef SMP
2721171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2722171482Sjeff    "Number of hz ticks to keep thread affinity for");
2723171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2724171482Sjeff    "Enables the long-term load balancer");
2725172409SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2726172409Sjeff    &balance_interval, 0,
2727172409Sjeff    "Average frequency in stathz ticks to run the long-term balancer");
2728171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2729171482Sjeff    "Steals work from another hyper-threaded core on idle");
2730171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2731171482Sjeff    "Attempts to steal work from other cores before idling");
2732171506SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2733171506Sjeff    "Minimum load on remote cpu before we'll steal");
2734184439Sivoras
2735184439Sivoras/* Retrieve SMP topology */
2736184439SivorasSYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
2737184439Sivoras    CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
2738184439Sivoras    "XML dump of detected CPU topology");
2739214510Sdavidxu
2740166108Sjeff#endif
2741165762Sjeff
2742172264Sjeff/* ps compat.  All cpu percentages from ULE are weighted. */
2743172293Sjeffstatic int ccpu = 0;
2744165762SjeffSYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2745