sched_ule.c revision 208787
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 208787 2010-06-03 16:02:11Z 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#ifdef KTRACE
66109864Sjeff#include <sys/uio.h>
67109864Sjeff#include <sys/ktrace.h>
68109864Sjeff#endif
69109864Sjeff
70145256Sjkoshy#ifdef HWPMC_HOOKS
71145256Sjkoshy#include <sys/pmckern.h>
72145256Sjkoshy#endif
73145256Sjkoshy
74179297Sjb#ifdef KDTRACE_HOOKS
75179297Sjb#include <sys/dtrace_bsd.h>
76179297Sjbint				dtrace_vtime_active;
77179297Sjbdtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
78179297Sjb#endif
79179297Sjb
80109864Sjeff#include <machine/cpu.h>
81121790Sjeff#include <machine/smp.h>
82109864Sjeff
83208165Srrs#if defined(__sparc64__)
84172345Sjeff#error "This architecture is not currently compatible with ULE"
85166190Sjeff#endif
86166190Sjeff
87171482Sjeff#define	KTR_ULE	0
88166137Sjeff
89187679Sjeff#define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
90187679Sjeff#define	TDQ_NAME_LEN	(sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
91187357Sjeff#define	TDQ_LOADNAME_LEN	(PCPU_NAME_LEN + sizeof(" load"))
92187357Sjeff
93166137Sjeff/*
94171482Sjeff * Thread scheduler specific section.  All fields are protected
95171482Sjeff * by the thread lock.
96146954Sjeff */
97164936Sjulianstruct td_sched {
98171482Sjeff	struct runq	*ts_runq;	/* Run-queue we're queued on. */
99171482Sjeff	short		ts_flags;	/* TSF_* flags. */
100164936Sjulian	u_char		ts_cpu;		/* CPU that we have affinity for. */
101177009Sjeff	int		ts_rltick;	/* Real last tick, for affinity. */
102171482Sjeff	int		ts_slice;	/* Ticks of slice remaining. */
103171482Sjeff	u_int		ts_slptime;	/* Number of ticks we vol. slept */
104171482Sjeff	u_int		ts_runtime;	/* Number of ticks we were running */
105164936Sjulian	int		ts_ltick;	/* Last tick that we were running on */
106199764Sivoras	int		ts_incrtick;	/* Last tick that we incremented on */
107164936Sjulian	int		ts_ftick;	/* First tick that we were running on */
108164936Sjulian	int		ts_ticks;	/* Tick count */
109187357Sjeff#ifdef KTR
110187357Sjeff	char		ts_name[TS_NAME_LEN];
111187357Sjeff#endif
112134791Sjulian};
113164936Sjulian/* flags kept in ts_flags */
114166108Sjeff#define	TSF_BOUND	0x0001		/* Thread can not migrate. */
115166108Sjeff#define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
116121790Sjeff
117164936Sjulianstatic struct td_sched td_sched0;
118109864Sjeff
119176735Sjeff#define	THREAD_CAN_MIGRATE(td)	((td)->td_pinned == 0)
120176735Sjeff#define	THREAD_CAN_SCHED(td, cpu)	\
121176735Sjeff    CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
122176735Sjeff
123109864Sjeff/*
124165762Sjeff * Cpu percentage computation macros and defines.
125111857Sjeff *
126165762Sjeff * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
127165762Sjeff * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
128165796Sjeff * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
129165762Sjeff * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
130165762Sjeff * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
131165762Sjeff * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
132165762Sjeff */
133165762Sjeff#define	SCHED_TICK_SECS		10
134165762Sjeff#define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
135165796Sjeff#define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
136165762Sjeff#define	SCHED_TICK_SHIFT	10
137165762Sjeff#define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
138165830Sjeff#define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
139165762Sjeff
140165762Sjeff/*
141165762Sjeff * These macros determine priorities for non-interactive threads.  They are
142165762Sjeff * assigned a priority based on their recent cpu utilization as expressed
143165762Sjeff * by the ratio of ticks to the tick total.  NHALF priorities at the start
144165762Sjeff * and end of the MIN to MAX timeshare range are only reachable with negative
145165762Sjeff * or positive nice respectively.
146165762Sjeff *
147165762Sjeff * PRI_RANGE:	Priority range for utilization dependent priorities.
148116642Sjeff * PRI_NRESV:	Number of nice values.
149165762Sjeff * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
150165762Sjeff * PRI_NICE:	Determines the part of the priority inherited from nice.
151109864Sjeff */
152165762Sjeff#define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
153121869Sjeff#define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
154165762Sjeff#define	SCHED_PRI_MIN		(PRI_MIN_TIMESHARE + SCHED_PRI_NHALF)
155165762Sjeff#define	SCHED_PRI_MAX		(PRI_MAX_TIMESHARE - SCHED_PRI_NHALF)
156170787Sjeff#define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN)
157165762Sjeff#define	SCHED_PRI_TICKS(ts)						\
158165762Sjeff    (SCHED_TICK_HZ((ts)) /						\
159165827Sjeff    (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
160165762Sjeff#define	SCHED_PRI_NICE(nice)	(nice)
161109864Sjeff
162109864Sjeff/*
163165762Sjeff * These determine the interactivity of a process.  Interactivity differs from
164165762Sjeff * cpu utilization in that it expresses the voluntary time slept vs time ran
165165762Sjeff * while cpu utilization includes all time not running.  This more accurately
166165762Sjeff * models the intent of the thread.
167109864Sjeff *
168110645Sjeff * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
169110645Sjeff *		before throttling back.
170121868Sjeff * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
171116365Sjeff * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
172111857Sjeff * INTERACT_THRESH:	Threshhold for placement on the current runq.
173109864Sjeff */
174165762Sjeff#define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
175165762Sjeff#define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
176116365Sjeff#define	SCHED_INTERACT_MAX	(100)
177116365Sjeff#define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
178121126Sjeff#define	SCHED_INTERACT_THRESH	(30)
179111857Sjeff
180109864Sjeff/*
181165762Sjeff * tickincr:		Converts a stathz tick into a hz domain scaled by
182165762Sjeff *			the shift factor.  Without the shift the error rate
183165762Sjeff *			due to rounding would be unacceptably high.
184165762Sjeff * realstathz:		stathz is sometimes 0 and run off of hz.
185165762Sjeff * sched_slice:		Runtime of each thread before rescheduling.
186171482Sjeff * preempt_thresh:	Priority threshold for preemption and remote IPIs.
187109864Sjeff */
188165762Sjeffstatic int sched_interact = SCHED_INTERACT_THRESH;
189165762Sjeffstatic int realstathz;
190165762Sjeffstatic int tickincr;
191177009Sjeffstatic int sched_slice = 1;
192172345Sjeff#ifdef PREEMPTION
193172345Sjeff#ifdef FULL_PREEMPTION
194172345Sjeffstatic int preempt_thresh = PRI_MAX_IDLE;
195172345Sjeff#else
196171482Sjeffstatic int preempt_thresh = PRI_MIN_KERN;
197172345Sjeff#endif
198172345Sjeff#else
199172345Sjeffstatic int preempt_thresh = 0;
200172345Sjeff#endif
201177903Sjeffstatic int static_boost = PRI_MIN_TIMESHARE;
202178277Sjeffstatic int sched_idlespins = 10000;
203178277Sjeffstatic int sched_idlespinthresh = 4;
204109864Sjeff
205109864Sjeff/*
206171482Sjeff * tdq - per processor runqs and statistics.  All fields are protected by the
207171482Sjeff * tdq_lock.  The load and lowpri may be accessed without to avoid excess
208171482Sjeff * locking in sched_pickcpu();
209109864Sjeff */
210164936Sjulianstruct tdq {
211177009Sjeff	/* Ordered to improve efficiency of cpu_search() and switch(). */
212177009Sjeff	struct mtx	tdq_lock;		/* run queue lock. */
213176735Sjeff	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
214178277Sjeff	volatile int	tdq_load;		/* Aggregate load. */
215176735Sjeff	int		tdq_sysload;		/* For loadavg, !ITHD load. */
216177009Sjeff	int		tdq_transferable;	/* Transferable thread count. */
217178277Sjeff	short		tdq_switchcnt;		/* Switches this tick. */
218178277Sjeff	short		tdq_oldswitchcnt;	/* Switches last tick. */
219177009Sjeff	u_char		tdq_lowpri;		/* Lowest priority thread. */
220177009Sjeff	u_char		tdq_ipipending;		/* IPI pending. */
221166557Sjeff	u_char		tdq_idx;		/* Current insert index. */
222166557Sjeff	u_char		tdq_ridx;		/* Current removal index. */
223177009Sjeff	struct runq	tdq_realtime;		/* real-time run queue. */
224177009Sjeff	struct runq	tdq_timeshare;		/* timeshare run queue. */
225177009Sjeff	struct runq	tdq_idle;		/* Queue of IDLE threads. */
226187357Sjeff	char		tdq_name[TDQ_NAME_LEN];
227187357Sjeff#ifdef KTR
228187357Sjeff	char		tdq_loadname[TDQ_LOADNAME_LEN];
229187357Sjeff#endif
230171482Sjeff} __aligned(64);
231109864Sjeff
232178277Sjeff/* Idle thread states and config. */
233178277Sjeff#define	TDQ_RUNNING	1
234178277Sjeff#define	TDQ_IDLE	2
235166108Sjeff
236123433Sjeff#ifdef SMP
237184439Sivorasstruct cpu_group *cpu_top;		/* CPU topology */
238123433Sjeff
239176735Sjeff#define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
240176735Sjeff#define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
241166108Sjeff
242123433Sjeff/*
243166108Sjeff * Run-time tunables.
244166108Sjeff */
245171506Sjeffstatic int rebalance = 1;
246172409Sjeffstatic int balance_interval = 128;	/* Default set in sched_initticks(). */
247166108Sjeffstatic int affinity;
248172409Sjeffstatic int steal_htt = 1;
249171506Sjeffstatic int steal_idle = 1;
250171506Sjeffstatic int steal_thresh = 2;
251166108Sjeff
252166108Sjeff/*
253165620Sjeff * One thread queue per processor.
254109864Sjeff */
255164936Sjulianstatic struct tdq	tdq_cpu[MAXCPU];
256172409Sjeffstatic struct tdq	*balance_tdq;
257172409Sjeffstatic int balance_ticks;
258129982Sjeff
259164936Sjulian#define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
260164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu[(x)])
261171713Sjeff#define	TDQ_ID(x)	((int)((x) - tdq_cpu))
262123433Sjeff#else	/* !SMP */
263164936Sjulianstatic struct tdq	tdq_cpu;
264129982Sjeff
265170315Sjeff#define	TDQ_ID(x)	(0)
266164936Sjulian#define	TDQ_SELF()	(&tdq_cpu)
267164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu)
268110028Sjeff#endif
269109864Sjeff
270171482Sjeff#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
271171482Sjeff#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
272171482Sjeff#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
273171482Sjeff#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
274176735Sjeff#define	TDQ_LOCKPTR(t)		(&(t)->tdq_lock)
275171482Sjeff
276163709Sjbstatic void sched_priority(struct thread *);
277146954Sjeffstatic void sched_thread_priority(struct thread *, u_char);
278163709Sjbstatic int sched_interact_score(struct thread *);
279163709Sjbstatic void sched_interact_update(struct thread *);
280163709Sjbstatic void sched_interact_fork(struct thread *);
281164936Sjulianstatic void sched_pctcpu_update(struct td_sched *);
282109864Sjeff
283110267Sjeff/* Operations on per processor queues */
284177435Sjeffstatic struct thread *tdq_choose(struct tdq *);
285164936Sjulianstatic void tdq_setup(struct tdq *);
286177435Sjeffstatic void tdq_load_add(struct tdq *, struct thread *);
287177435Sjeffstatic void tdq_load_rem(struct tdq *, struct thread *);
288177435Sjeffstatic __inline void tdq_runq_add(struct tdq *, struct thread *, int);
289177435Sjeffstatic __inline void tdq_runq_rem(struct tdq *, struct thread *);
290177005Sjeffstatic inline int sched_shouldpreempt(int, int, int);
291164936Sjulianvoid tdq_print(int cpu);
292165762Sjeffstatic void runq_print(struct runq *rq);
293171482Sjeffstatic void tdq_add(struct tdq *, struct thread *, int);
294110267Sjeff#ifdef SMP
295176735Sjeffstatic int tdq_move(struct tdq *, struct tdq *);
296171482Sjeffstatic int tdq_idled(struct tdq *);
297177435Sjeffstatic void tdq_notify(struct tdq *, struct thread *);
298177435Sjeffstatic struct thread *tdq_steal(struct tdq *, int);
299177435Sjeffstatic struct thread *runq_steal(struct runq *, int);
300177435Sjeffstatic int sched_pickcpu(struct thread *, int);
301172409Sjeffstatic void sched_balance(void);
302176735Sjeffstatic int sched_balance_pair(struct tdq *, struct tdq *);
303177435Sjeffstatic inline struct tdq *sched_setcpu(struct thread *, int, int);
304171482Sjeffstatic inline void thread_unblock_switch(struct thread *, struct mtx *);
305171713Sjeffstatic struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
306184439Sivorasstatic int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
307184439Sivorasstatic int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
308184439Sivoras    struct cpu_group *cg, int indent);
309121790Sjeff#endif
310110028Sjeff
311165762Sjeffstatic void sched_setup(void *dummy);
312177253SrwatsonSYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
313165762Sjeff
314165762Sjeffstatic void sched_initticks(void *dummy);
315177253SrwatsonSYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
316177253Srwatson    NULL);
317165762Sjeff
318171482Sjeff/*
319171482Sjeff * Print the threads waiting on a run-queue.
320171482Sjeff */
321165762Sjeffstatic void
322165762Sjeffrunq_print(struct runq *rq)
323165762Sjeff{
324165762Sjeff	struct rqhead *rqh;
325177435Sjeff	struct thread *td;
326165762Sjeff	int pri;
327165762Sjeff	int j;
328165762Sjeff	int i;
329165762Sjeff
330165762Sjeff	for (i = 0; i < RQB_LEN; i++) {
331165762Sjeff		printf("\t\trunq bits %d 0x%zx\n",
332165762Sjeff		    i, rq->rq_status.rqb_bits[i]);
333165762Sjeff		for (j = 0; j < RQB_BPW; j++)
334165762Sjeff			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
335165762Sjeff				pri = j + (i << RQB_L2BPW);
336165762Sjeff				rqh = &rq->rq_queues[pri];
337177435Sjeff				TAILQ_FOREACH(td, rqh, td_runq) {
338165762Sjeff					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
339177435Sjeff					    td, td->td_name, td->td_priority,
340177435Sjeff					    td->td_rqindex, pri);
341165762Sjeff				}
342165762Sjeff			}
343165762Sjeff	}
344165762Sjeff}
345165762Sjeff
346171482Sjeff/*
347171482Sjeff * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
348171482Sjeff */
349113357Sjeffvoid
350164936Sjuliantdq_print(int cpu)
351110267Sjeff{
352164936Sjulian	struct tdq *tdq;
353112994Sjeff
354164936Sjulian	tdq = TDQ_CPU(cpu);
355112994Sjeff
356171713Sjeff	printf("tdq %d:\n", TDQ_ID(tdq));
357176735Sjeff	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
358176735Sjeff	printf("\tLock name:      %s\n", tdq->tdq_name);
359165620Sjeff	printf("\tload:           %d\n", tdq->tdq_load);
360178277Sjeff	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
361178277Sjeff	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
362171482Sjeff	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
363165766Sjeff	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
364178277Sjeff	printf("\tload transferable: %d\n", tdq->tdq_transferable);
365178277Sjeff	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
366165762Sjeff	printf("\trealtime runq:\n");
367165762Sjeff	runq_print(&tdq->tdq_realtime);
368165762Sjeff	printf("\ttimeshare runq:\n");
369165762Sjeff	runq_print(&tdq->tdq_timeshare);
370165762Sjeff	printf("\tidle runq:\n");
371165762Sjeff	runq_print(&tdq->tdq_idle);
372113357Sjeff}
373112994Sjeff
374177005Sjeffstatic inline int
375177005Sjeffsched_shouldpreempt(int pri, int cpri, int remote)
376177005Sjeff{
377177005Sjeff	/*
378177005Sjeff	 * If the new priority is not better than the current priority there is
379177005Sjeff	 * nothing to do.
380177005Sjeff	 */
381177005Sjeff	if (pri >= cpri)
382177005Sjeff		return (0);
383177005Sjeff	/*
384177005Sjeff	 * Always preempt idle.
385177005Sjeff	 */
386177005Sjeff	if (cpri >= PRI_MIN_IDLE)
387177005Sjeff		return (1);
388177005Sjeff	/*
389177005Sjeff	 * If preemption is disabled don't preempt others.
390177005Sjeff	 */
391177005Sjeff	if (preempt_thresh == 0)
392177005Sjeff		return (0);
393177005Sjeff	/*
394177005Sjeff	 * Preempt if we exceed the threshold.
395177005Sjeff	 */
396177005Sjeff	if (pri <= preempt_thresh)
397177005Sjeff		return (1);
398177005Sjeff	/*
399177005Sjeff	 * If we're realtime or better and there is timeshare or worse running
400177005Sjeff	 * preempt only remote processors.
401177005Sjeff	 */
402177005Sjeff	if (remote && pri <= PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
403177005Sjeff		return (1);
404177005Sjeff	return (0);
405177005Sjeff}
406177005Sjeff
407171482Sjeff#define	TS_RQ_PPQ	(((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
408171482Sjeff/*
409171482Sjeff * Add a thread to the actual run-queue.  Keeps transferable counts up to
410171482Sjeff * date with what is actually on the run-queue.  Selects the correct
411171482Sjeff * queue position for timeshare threads.
412171482Sjeff */
413122744Sjeffstatic __inline void
414177435Sjefftdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
415122744Sjeff{
416177435Sjeff	struct td_sched *ts;
417177042Sjeff	u_char pri;
418177042Sjeff
419171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
420177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
421177009Sjeff
422177435Sjeff	pri = td->td_priority;
423177435Sjeff	ts = td->td_sched;
424177435Sjeff	TD_SET_RUNQ(td);
425177435Sjeff	if (THREAD_CAN_MIGRATE(td)) {
426165620Sjeff		tdq->tdq_transferable++;
427164936Sjulian		ts->ts_flags |= TSF_XFERABLE;
428123433Sjeff	}
429177042Sjeff	if (pri <= PRI_MAX_REALTIME) {
430177042Sjeff		ts->ts_runq = &tdq->tdq_realtime;
431177042Sjeff	} else if (pri <= PRI_MAX_TIMESHARE) {
432177042Sjeff		ts->ts_runq = &tdq->tdq_timeshare;
433165762Sjeff		KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
434165762Sjeff			("Invalid priority %d on timeshare runq", pri));
435165762Sjeff		/*
436165762Sjeff		 * This queue contains only priorities between MIN and MAX
437165762Sjeff		 * realtime.  Use the whole queue to represent these values.
438165762Sjeff		 */
439171713Sjeff		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
440165762Sjeff			pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
441165762Sjeff			pri = (pri + tdq->tdq_idx) % RQ_NQS;
442165766Sjeff			/*
443165766Sjeff			 * This effectively shortens the queue by one so we
444165766Sjeff			 * can have a one slot difference between idx and
445165766Sjeff			 * ridx while we wait for threads to drain.
446165766Sjeff			 */
447165766Sjeff			if (tdq->tdq_ridx != tdq->tdq_idx &&
448165766Sjeff			    pri == tdq->tdq_ridx)
449167664Sjeff				pri = (unsigned char)(pri - 1) % RQ_NQS;
450165762Sjeff		} else
451165766Sjeff			pri = tdq->tdq_ridx;
452177435Sjeff		runq_add_pri(ts->ts_runq, td, pri, flags);
453177042Sjeff		return;
454165762Sjeff	} else
455177009Sjeff		ts->ts_runq = &tdq->tdq_idle;
456177435Sjeff	runq_add(ts->ts_runq, td, flags);
457177009Sjeff}
458177009Sjeff
459171482Sjeff/*
460171482Sjeff * Remove a thread from a run-queue.  This typically happens when a thread
461171482Sjeff * is selected to run.  Running threads are not on the queue and the
462171482Sjeff * transferable count does not reflect them.
463171482Sjeff */
464122744Sjeffstatic __inline void
465177435Sjefftdq_runq_rem(struct tdq *tdq, struct thread *td)
466122744Sjeff{
467177435Sjeff	struct td_sched *ts;
468177435Sjeff
469177435Sjeff	ts = td->td_sched;
470171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
471171482Sjeff	KASSERT(ts->ts_runq != NULL,
472177435Sjeff	    ("tdq_runq_remove: thread %p null ts_runq", td));
473164936Sjulian	if (ts->ts_flags & TSF_XFERABLE) {
474165620Sjeff		tdq->tdq_transferable--;
475164936Sjulian		ts->ts_flags &= ~TSF_XFERABLE;
476123433Sjeff	}
477165766Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
478165766Sjeff		if (tdq->tdq_idx != tdq->tdq_ridx)
479177435Sjeff			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
480165766Sjeff		else
481177435Sjeff			runq_remove_idx(ts->ts_runq, td, NULL);
482165766Sjeff	} else
483177435Sjeff		runq_remove(ts->ts_runq, td);
484122744Sjeff}
485122744Sjeff
486171482Sjeff/*
487171482Sjeff * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
488171482Sjeff * for this thread to the referenced thread queue.
489171482Sjeff */
490113357Sjeffstatic void
491177435Sjefftdq_load_add(struct tdq *tdq, struct thread *td)
492113357Sjeff{
493171482Sjeff
494171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
495177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
496177902Sjeff
497165620Sjeff	tdq->tdq_load++;
498198854Sattilio	if ((td->td_flags & TDF_NOLOAD) == 0)
499177902Sjeff		tdq->tdq_sysload++;
500187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
501110267Sjeff}
502113357Sjeff
503171482Sjeff/*
504171482Sjeff * Remove the load from a thread that is transitioning to a sleep state or
505171482Sjeff * exiting.
506171482Sjeff */
507112994Sjeffstatic void
508177435Sjefftdq_load_rem(struct tdq *tdq, struct thread *td)
509110267Sjeff{
510171482Sjeff
511177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
512171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
513171482Sjeff	KASSERT(tdq->tdq_load != 0,
514171713Sjeff	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
515177902Sjeff
516165620Sjeff	tdq->tdq_load--;
517198854Sattilio	if ((td->td_flags & TDF_NOLOAD) == 0)
518177902Sjeff		tdq->tdq_sysload--;
519187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
520110267Sjeff}
521110267Sjeff
522176735Sjeff/*
523176735Sjeff * Set lowpri to its exact value by searching the run-queue and
524176735Sjeff * evaluating curthread.  curthread may be passed as an optimization.
525176735Sjeff */
526176735Sjeffstatic void
527176735Sjefftdq_setlowpri(struct tdq *tdq, struct thread *ctd)
528176735Sjeff{
529176735Sjeff	struct thread *td;
530176735Sjeff
531176735Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
532176735Sjeff	if (ctd == NULL)
533176735Sjeff		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
534177435Sjeff	td = tdq_choose(tdq);
535177435Sjeff	if (td == NULL || td->td_priority > ctd->td_priority)
536176735Sjeff		tdq->tdq_lowpri = ctd->td_priority;
537176735Sjeff	else
538176735Sjeff		tdq->tdq_lowpri = td->td_priority;
539176735Sjeff}
540176735Sjeff
541113357Sjeff#ifdef SMP
542176735Sjeffstruct cpu_search {
543194779Sjeff	cpuset_t cs_mask;
544176735Sjeff	u_int	cs_load;
545176735Sjeff	u_int	cs_cpu;
546176735Sjeff	int	cs_limit;	/* Min priority for low min load for high. */
547176735Sjeff};
548176735Sjeff
549176735Sjeff#define	CPU_SEARCH_LOWEST	0x1
550176735Sjeff#define	CPU_SEARCH_HIGHEST	0x2
551176735Sjeff#define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
552176735Sjeff
553194779Sjeff#define	CPUSET_FOREACH(cpu, mask)				\
554194779Sjeff	for ((cpu) = 0; (cpu) <= mp_maxid; (cpu)++)		\
555176735Sjeff		if ((mask) & 1 << (cpu))
556176735Sjeff
557177169Sjhbstatic __inline int cpu_search(struct cpu_group *cg, struct cpu_search *low,
558176735Sjeff    struct cpu_search *high, const int match);
559176735Sjeffint cpu_search_lowest(struct cpu_group *cg, struct cpu_search *low);
560176735Sjeffint cpu_search_highest(struct cpu_group *cg, struct cpu_search *high);
561176735Sjeffint cpu_search_both(struct cpu_group *cg, struct cpu_search *low,
562176735Sjeff    struct cpu_search *high);
563176735Sjeff
564116069Sjeff/*
565176735Sjeff * This routine compares according to the match argument and should be
566176735Sjeff * reduced in actual instantiations via constant propagation and dead code
567176735Sjeff * elimination.
568176735Sjeff */
569176735Sjeffstatic __inline int
570176735Sjeffcpu_compare(int cpu, struct cpu_search *low, struct cpu_search *high,
571176735Sjeff    const int match)
572176735Sjeff{
573176735Sjeff	struct tdq *tdq;
574176735Sjeff
575176735Sjeff	tdq = TDQ_CPU(cpu);
576176735Sjeff	if (match & CPU_SEARCH_LOWEST)
577194779Sjeff		if (CPU_ISSET(cpu, &low->cs_mask) &&
578176735Sjeff		    tdq->tdq_load < low->cs_load &&
579176735Sjeff		    tdq->tdq_lowpri > low->cs_limit) {
580176735Sjeff			low->cs_cpu = cpu;
581176735Sjeff			low->cs_load = tdq->tdq_load;
582176735Sjeff		}
583176735Sjeff	if (match & CPU_SEARCH_HIGHEST)
584194779Sjeff		if (CPU_ISSET(cpu, &high->cs_mask) &&
585176735Sjeff		    tdq->tdq_load >= high->cs_limit &&
586176735Sjeff		    tdq->tdq_load > high->cs_load &&
587176735Sjeff		    tdq->tdq_transferable) {
588176735Sjeff			high->cs_cpu = cpu;
589176735Sjeff			high->cs_load = tdq->tdq_load;
590176735Sjeff		}
591176735Sjeff	return (tdq->tdq_load);
592176735Sjeff}
593176735Sjeff
594176735Sjeff/*
595176735Sjeff * Search the tree of cpu_groups for the lowest or highest loaded cpu
596176735Sjeff * according to the match argument.  This routine actually compares the
597176735Sjeff * load on all paths through the tree and finds the least loaded cpu on
598176735Sjeff * the least loaded path, which may differ from the least loaded cpu in
599176735Sjeff * the system.  This balances work among caches and busses.
600116069Sjeff *
601176735Sjeff * This inline is instantiated in three forms below using constants for the
602176735Sjeff * match argument.  It is reduced to the minimum set for each case.  It is
603176735Sjeff * also recursive to the depth of the tree.
604116069Sjeff */
605177169Sjhbstatic __inline int
606176735Sjeffcpu_search(struct cpu_group *cg, struct cpu_search *low,
607176735Sjeff    struct cpu_search *high, const int match)
608176735Sjeff{
609176735Sjeff	int total;
610176735Sjeff
611176735Sjeff	total = 0;
612176735Sjeff	if (cg->cg_children) {
613176735Sjeff		struct cpu_search lgroup;
614176735Sjeff		struct cpu_search hgroup;
615176735Sjeff		struct cpu_group *child;
616176735Sjeff		u_int lload;
617176735Sjeff		int hload;
618176735Sjeff		int load;
619176735Sjeff		int i;
620176735Sjeff
621176735Sjeff		lload = -1;
622176735Sjeff		hload = -1;
623176735Sjeff		for (i = 0; i < cg->cg_children; i++) {
624176735Sjeff			child = &cg->cg_child[i];
625176735Sjeff			if (match & CPU_SEARCH_LOWEST) {
626176735Sjeff				lgroup = *low;
627176735Sjeff				lgroup.cs_load = -1;
628176735Sjeff			}
629176735Sjeff			if (match & CPU_SEARCH_HIGHEST) {
630176735Sjeff				hgroup = *high;
631176735Sjeff				lgroup.cs_load = 0;
632176735Sjeff			}
633176735Sjeff			switch (match) {
634176735Sjeff			case CPU_SEARCH_LOWEST:
635176735Sjeff				load = cpu_search_lowest(child, &lgroup);
636176735Sjeff				break;
637176735Sjeff			case CPU_SEARCH_HIGHEST:
638176735Sjeff				load = cpu_search_highest(child, &hgroup);
639176735Sjeff				break;
640176735Sjeff			case CPU_SEARCH_BOTH:
641176735Sjeff				load = cpu_search_both(child, &lgroup, &hgroup);
642176735Sjeff				break;
643176735Sjeff			}
644176735Sjeff			total += load;
645176735Sjeff			if (match & CPU_SEARCH_LOWEST)
646176735Sjeff				if (load < lload || low->cs_cpu == -1) {
647176735Sjeff					*low = lgroup;
648176735Sjeff					lload = load;
649176735Sjeff				}
650176735Sjeff			if (match & CPU_SEARCH_HIGHEST)
651176735Sjeff				if (load > hload || high->cs_cpu == -1) {
652176735Sjeff					hload = load;
653176735Sjeff					*high = hgroup;
654176735Sjeff				}
655176735Sjeff		}
656176735Sjeff	} else {
657176735Sjeff		int cpu;
658176735Sjeff
659194779Sjeff		CPUSET_FOREACH(cpu, cg->cg_mask)
660176735Sjeff			total += cpu_compare(cpu, low, high, match);
661176735Sjeff	}
662176735Sjeff	return (total);
663176735Sjeff}
664176735Sjeff
665176735Sjeff/*
666176735Sjeff * cpu_search instantiations must pass constants to maintain the inline
667176735Sjeff * optimization.
668176735Sjeff */
669176735Sjeffint
670176735Sjeffcpu_search_lowest(struct cpu_group *cg, struct cpu_search *low)
671176735Sjeff{
672176735Sjeff	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
673176735Sjeff}
674176735Sjeff
675176735Sjeffint
676176735Sjeffcpu_search_highest(struct cpu_group *cg, struct cpu_search *high)
677176735Sjeff{
678176735Sjeff	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
679176735Sjeff}
680176735Sjeff
681176735Sjeffint
682176735Sjeffcpu_search_both(struct cpu_group *cg, struct cpu_search *low,
683176735Sjeff    struct cpu_search *high)
684176735Sjeff{
685176735Sjeff	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
686176735Sjeff}
687176735Sjeff
688176735Sjeff/*
689176735Sjeff * Find the cpu with the least load via the least loaded path that has a
690176735Sjeff * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
691176735Sjeff * acceptable.
692176735Sjeff */
693176735Sjeffstatic inline int
694194779Sjeffsched_lowest(struct cpu_group *cg, cpuset_t mask, int pri)
695176735Sjeff{
696176735Sjeff	struct cpu_search low;
697176735Sjeff
698176735Sjeff	low.cs_cpu = -1;
699176735Sjeff	low.cs_load = -1;
700176735Sjeff	low.cs_mask = mask;
701176735Sjeff	low.cs_limit = pri;
702176735Sjeff	cpu_search_lowest(cg, &low);
703176735Sjeff	return low.cs_cpu;
704176735Sjeff}
705176735Sjeff
706176735Sjeff/*
707176735Sjeff * Find the cpu with the highest load via the highest loaded path.
708176735Sjeff */
709176735Sjeffstatic inline int
710194779Sjeffsched_highest(struct cpu_group *cg, cpuset_t mask, int minload)
711176735Sjeff{
712176735Sjeff	struct cpu_search high;
713176735Sjeff
714176735Sjeff	high.cs_cpu = -1;
715176735Sjeff	high.cs_load = 0;
716176735Sjeff	high.cs_mask = mask;
717176735Sjeff	high.cs_limit = minload;
718176735Sjeff	cpu_search_highest(cg, &high);
719176735Sjeff	return high.cs_cpu;
720176735Sjeff}
721176735Sjeff
722176735Sjeff/*
723176735Sjeff * Simultaneously find the highest and lowest loaded cpu reachable via
724176735Sjeff * cg.
725176735Sjeff */
726176735Sjeffstatic inline void
727194779Sjeffsched_both(struct cpu_group *cg, cpuset_t mask, int *lowcpu, int *highcpu)
728176735Sjeff{
729176735Sjeff	struct cpu_search high;
730176735Sjeff	struct cpu_search low;
731176735Sjeff
732176735Sjeff	low.cs_cpu = -1;
733176735Sjeff	low.cs_limit = -1;
734176735Sjeff	low.cs_load = -1;
735176735Sjeff	low.cs_mask = mask;
736176735Sjeff	high.cs_load = 0;
737176735Sjeff	high.cs_cpu = -1;
738176735Sjeff	high.cs_limit = -1;
739176735Sjeff	high.cs_mask = mask;
740176735Sjeff	cpu_search_both(cg, &low, &high);
741176735Sjeff	*lowcpu = low.cs_cpu;
742176735Sjeff	*highcpu = high.cs_cpu;
743176735Sjeff	return;
744176735Sjeff}
745176735Sjeff
746121790Sjeffstatic void
747176735Sjeffsched_balance_group(struct cpu_group *cg)
748116069Sjeff{
749194779Sjeff	cpuset_t mask;
750176735Sjeff	int high;
751176735Sjeff	int low;
752123487Sjeff	int i;
753123487Sjeff
754194779Sjeff	CPU_FILL(&mask);
755176735Sjeff	for (;;) {
756176735Sjeff		sched_both(cg, mask, &low, &high);
757176735Sjeff		if (low == high || low == -1 || high == -1)
758176735Sjeff			break;
759176735Sjeff		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low)))
760176735Sjeff			break;
761123487Sjeff		/*
762176735Sjeff		 * If we failed to move any threads determine which cpu
763176735Sjeff		 * to kick out of the set and try again.
764176735Sjeff	 	 */
765176735Sjeff		if (TDQ_CPU(high)->tdq_transferable == 0)
766194779Sjeff			CPU_CLR(high, &mask);
767176735Sjeff		else
768194779Sjeff			CPU_CLR(low, &mask);
769123487Sjeff	}
770176735Sjeff
771176735Sjeff	for (i = 0; i < cg->cg_children; i++)
772176735Sjeff		sched_balance_group(&cg->cg_child[i]);
773123487Sjeff}
774123487Sjeff
775123487Sjeffstatic void
776201148Sedsched_balance(void)
777123487Sjeff{
778172409Sjeff	struct tdq *tdq;
779123487Sjeff
780172409Sjeff	/*
781172409Sjeff	 * Select a random time between .5 * balance_interval and
782172409Sjeff	 * 1.5 * balance_interval.
783172409Sjeff	 */
784176735Sjeff	balance_ticks = max(balance_interval / 2, 1);
785176735Sjeff	balance_ticks += random() % balance_interval;
786171482Sjeff	if (smp_started == 0 || rebalance == 0)
787171482Sjeff		return;
788172409Sjeff	tdq = TDQ_SELF();
789172409Sjeff	TDQ_UNLOCK(tdq);
790176735Sjeff	sched_balance_group(cpu_top);
791172409Sjeff	TDQ_LOCK(tdq);
792123487Sjeff}
793123487Sjeff
794171482Sjeff/*
795171482Sjeff * Lock two thread queues using their address to maintain lock order.
796171482Sjeff */
797123487Sjeffstatic void
798171482Sjefftdq_lock_pair(struct tdq *one, struct tdq *two)
799171482Sjeff{
800171482Sjeff	if (one < two) {
801171482Sjeff		TDQ_LOCK(one);
802171482Sjeff		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
803171482Sjeff	} else {
804171482Sjeff		TDQ_LOCK(two);
805171482Sjeff		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
806171482Sjeff	}
807171482Sjeff}
808171482Sjeff
809171482Sjeff/*
810172409Sjeff * Unlock two thread queues.  Order is not important here.
811172409Sjeff */
812172409Sjeffstatic void
813172409Sjefftdq_unlock_pair(struct tdq *one, struct tdq *two)
814172409Sjeff{
815172409Sjeff	TDQ_UNLOCK(one);
816172409Sjeff	TDQ_UNLOCK(two);
817172409Sjeff}
818172409Sjeff
819172409Sjeff/*
820171482Sjeff * Transfer load between two imbalanced thread queues.
821171482Sjeff */
822176735Sjeffstatic int
823164936Sjuliansched_balance_pair(struct tdq *high, struct tdq *low)
824123487Sjeff{
825123433Sjeff	int transferable;
826116069Sjeff	int high_load;
827116069Sjeff	int low_load;
828176735Sjeff	int moved;
829116069Sjeff	int move;
830116069Sjeff	int diff;
831116069Sjeff	int i;
832116069Sjeff
833171482Sjeff	tdq_lock_pair(high, low);
834176735Sjeff	transferable = high->tdq_transferable;
835176735Sjeff	high_load = high->tdq_load;
836176735Sjeff	low_load = low->tdq_load;
837176735Sjeff	moved = 0;
838116069Sjeff	/*
839122744Sjeff	 * Determine what the imbalance is and then adjust that to how many
840165620Sjeff	 * threads we actually have to give up (transferable).
841122744Sjeff	 */
842171482Sjeff	if (transferable != 0) {
843171482Sjeff		diff = high_load - low_load;
844171482Sjeff		move = diff / 2;
845171482Sjeff		if (diff & 0x1)
846171482Sjeff			move++;
847171482Sjeff		move = min(move, transferable);
848171482Sjeff		for (i = 0; i < move; i++)
849176735Sjeff			moved += tdq_move(high, low);
850172293Sjeff		/*
851172293Sjeff		 * IPI the target cpu to force it to reschedule with the new
852172293Sjeff		 * workload.
853172293Sjeff		 */
854172293Sjeff		ipi_selected(1 << TDQ_ID(low), IPI_PREEMPT);
855171482Sjeff	}
856172409Sjeff	tdq_unlock_pair(high, low);
857176735Sjeff	return (moved);
858116069Sjeff}
859116069Sjeff
860171482Sjeff/*
861171482Sjeff * Move a thread from one thread queue to another.
862171482Sjeff */
863176735Sjeffstatic int
864171482Sjefftdq_move(struct tdq *from, struct tdq *to)
865116069Sjeff{
866171482Sjeff	struct td_sched *ts;
867171482Sjeff	struct thread *td;
868164936Sjulian	struct tdq *tdq;
869171482Sjeff	int cpu;
870116069Sjeff
871172409Sjeff	TDQ_LOCK_ASSERT(from, MA_OWNED);
872172409Sjeff	TDQ_LOCK_ASSERT(to, MA_OWNED);
873172409Sjeff
874164936Sjulian	tdq = from;
875171482Sjeff	cpu = TDQ_ID(to);
876177435Sjeff	td = tdq_steal(tdq, cpu);
877177435Sjeff	if (td == NULL)
878176735Sjeff		return (0);
879177435Sjeff	ts = td->td_sched;
880171482Sjeff	/*
881171482Sjeff	 * Although the run queue is locked the thread may be blocked.  Lock
882172409Sjeff	 * it to clear this and acquire the run-queue lock.
883171482Sjeff	 */
884171482Sjeff	thread_lock(td);
885172409Sjeff	/* Drop recursive lock on from acquired via thread_lock(). */
886171482Sjeff	TDQ_UNLOCK(from);
887171482Sjeff	sched_rem(td);
888166108Sjeff	ts->ts_cpu = cpu;
889171482Sjeff	td->td_lock = TDQ_LOCKPTR(to);
890171482Sjeff	tdq_add(to, td, SRQ_YIELDING);
891176735Sjeff	return (1);
892116069Sjeff}
893110267Sjeff
894171482Sjeff/*
895171482Sjeff * This tdq has idled.  Try to steal a thread from another cpu and switch
896171482Sjeff * to it.
897171482Sjeff */
898123433Sjeffstatic int
899164936Sjuliantdq_idled(struct tdq *tdq)
900121790Sjeff{
901176735Sjeff	struct cpu_group *cg;
902164936Sjulian	struct tdq *steal;
903194779Sjeff	cpuset_t mask;
904176735Sjeff	int thresh;
905171482Sjeff	int cpu;
906123433Sjeff
907172484Sjeff	if (smp_started == 0 || steal_idle == 0)
908172484Sjeff		return (1);
909194779Sjeff	CPU_FILL(&mask);
910194779Sjeff	CPU_CLR(PCPU_GET(cpuid), &mask);
911176735Sjeff	/* We don't want to be preempted while we're iterating. */
912171482Sjeff	spinlock_enter();
913176735Sjeff	for (cg = tdq->tdq_cg; cg != NULL; ) {
914191643Sjeff		if ((cg->cg_flags & CG_FLAG_THREAD) == 0)
915176735Sjeff			thresh = steal_thresh;
916176735Sjeff		else
917176735Sjeff			thresh = 1;
918176735Sjeff		cpu = sched_highest(cg, mask, thresh);
919176735Sjeff		if (cpu == -1) {
920176735Sjeff			cg = cg->cg_parent;
921176735Sjeff			continue;
922166108Sjeff		}
923176735Sjeff		steal = TDQ_CPU(cpu);
924194779Sjeff		CPU_CLR(cpu, &mask);
925176735Sjeff		tdq_lock_pair(tdq, steal);
926176735Sjeff		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
927176735Sjeff			tdq_unlock_pair(tdq, steal);
928176735Sjeff			continue;
929171482Sjeff		}
930176735Sjeff		/*
931176735Sjeff		 * If a thread was added while interrupts were disabled don't
932176735Sjeff		 * steal one here.  If we fail to acquire one due to affinity
933176735Sjeff		 * restrictions loop again with this cpu removed from the
934176735Sjeff		 * set.
935176735Sjeff		 */
936176735Sjeff		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
937176735Sjeff			tdq_unlock_pair(tdq, steal);
938176735Sjeff			continue;
939176735Sjeff		}
940176735Sjeff		spinlock_exit();
941176735Sjeff		TDQ_UNLOCK(steal);
942178272Sjeff		mi_switch(SW_VOL | SWT_IDLE, NULL);
943176735Sjeff		thread_unlock(curthread);
944176735Sjeff
945176735Sjeff		return (0);
946123433Sjeff	}
947171482Sjeff	spinlock_exit();
948123433Sjeff	return (1);
949121790Sjeff}
950121790Sjeff
951171482Sjeff/*
952171482Sjeff * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
953171482Sjeff */
954121790Sjeffstatic void
955177435Sjefftdq_notify(struct tdq *tdq, struct thread *td)
956121790Sjeff{
957185047Sjhb	struct thread *ctd;
958166247Sjeff	int pri;
959166108Sjeff	int cpu;
960121790Sjeff
961177005Sjeff	if (tdq->tdq_ipipending)
962177005Sjeff		return;
963177435Sjeff	cpu = td->td_sched->ts_cpu;
964177435Sjeff	pri = td->td_priority;
965185047Sjhb	ctd = pcpu_find(cpu)->pc_curthread;
966185047Sjhb	if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
967166137Sjeff		return;
968185047Sjhb	if (TD_IS_IDLETHREAD(ctd)) {
969178277Sjeff		/*
970178471Sjeff		 * If the MD code has an idle wakeup routine try that before
971178471Sjeff		 * falling back to IPI.
972178471Sjeff		 */
973178471Sjeff		if (cpu_idle_wakeup(cpu))
974178471Sjeff			return;
975178277Sjeff	}
976177005Sjeff	tdq->tdq_ipipending = 1;
977171482Sjeff	ipi_selected(1 << cpu, IPI_PREEMPT);
978121790Sjeff}
979121790Sjeff
980171482Sjeff/*
981171482Sjeff * Steals load from a timeshare queue.  Honors the rotating queue head
982171482Sjeff * index.
983171482Sjeff */
984177435Sjeffstatic struct thread *
985176735Sjeffrunq_steal_from(struct runq *rq, int cpu, u_char start)
986171482Sjeff{
987171482Sjeff	struct rqbits *rqb;
988171482Sjeff	struct rqhead *rqh;
989177435Sjeff	struct thread *td;
990171482Sjeff	int first;
991171482Sjeff	int bit;
992171482Sjeff	int pri;
993171482Sjeff	int i;
994171482Sjeff
995171482Sjeff	rqb = &rq->rq_status;
996171482Sjeff	bit = start & (RQB_BPW -1);
997171482Sjeff	pri = 0;
998171482Sjeff	first = 0;
999171482Sjeffagain:
1000171482Sjeff	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1001171482Sjeff		if (rqb->rqb_bits[i] == 0)
1002171482Sjeff			continue;
1003171482Sjeff		if (bit != 0) {
1004171482Sjeff			for (pri = bit; pri < RQB_BPW; pri++)
1005171482Sjeff				if (rqb->rqb_bits[i] & (1ul << pri))
1006171482Sjeff					break;
1007171482Sjeff			if (pri >= RQB_BPW)
1008171482Sjeff				continue;
1009171482Sjeff		} else
1010171482Sjeff			pri = RQB_FFS(rqb->rqb_bits[i]);
1011171482Sjeff		pri += (i << RQB_L2BPW);
1012171482Sjeff		rqh = &rq->rq_queues[pri];
1013177435Sjeff		TAILQ_FOREACH(td, rqh, td_runq) {
1014177435Sjeff			if (first && THREAD_CAN_MIGRATE(td) &&
1015177435Sjeff			    THREAD_CAN_SCHED(td, cpu))
1016177435Sjeff				return (td);
1017171482Sjeff			first = 1;
1018171482Sjeff		}
1019171482Sjeff	}
1020171482Sjeff	if (start != 0) {
1021171482Sjeff		start = 0;
1022171482Sjeff		goto again;
1023171482Sjeff	}
1024171482Sjeff
1025171482Sjeff	return (NULL);
1026171482Sjeff}
1027171482Sjeff
1028171482Sjeff/*
1029171482Sjeff * Steals load from a standard linear queue.
1030171482Sjeff */
1031177435Sjeffstatic struct thread *
1032176735Sjeffrunq_steal(struct runq *rq, int cpu)
1033121790Sjeff{
1034121790Sjeff	struct rqhead *rqh;
1035121790Sjeff	struct rqbits *rqb;
1036177435Sjeff	struct thread *td;
1037121790Sjeff	int word;
1038121790Sjeff	int bit;
1039121790Sjeff
1040121790Sjeff	rqb = &rq->rq_status;
1041121790Sjeff	for (word = 0; word < RQB_LEN; word++) {
1042121790Sjeff		if (rqb->rqb_bits[word] == 0)
1043121790Sjeff			continue;
1044121790Sjeff		for (bit = 0; bit < RQB_BPW; bit++) {
1045123231Speter			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
1046121790Sjeff				continue;
1047121790Sjeff			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
1048177435Sjeff			TAILQ_FOREACH(td, rqh, td_runq)
1049177435Sjeff				if (THREAD_CAN_MIGRATE(td) &&
1050177435Sjeff				    THREAD_CAN_SCHED(td, cpu))
1051177435Sjeff					return (td);
1052121790Sjeff		}
1053121790Sjeff	}
1054121790Sjeff	return (NULL);
1055121790Sjeff}
1056121790Sjeff
1057171482Sjeff/*
1058171482Sjeff * Attempt to steal a thread in priority order from a thread queue.
1059171482Sjeff */
1060177435Sjeffstatic struct thread *
1061176735Sjefftdq_steal(struct tdq *tdq, int cpu)
1062121790Sjeff{
1063177435Sjeff	struct thread *td;
1064121790Sjeff
1065171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1066177435Sjeff	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
1067177435Sjeff		return (td);
1068177435Sjeff	if ((td = runq_steal_from(&tdq->tdq_timeshare,
1069177435Sjeff	    cpu, tdq->tdq_ridx)) != NULL)
1070177435Sjeff		return (td);
1071176735Sjeff	return (runq_steal(&tdq->tdq_idle, cpu));
1072121790Sjeff}
1073123433Sjeff
1074171482Sjeff/*
1075171482Sjeff * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
1076172409Sjeff * current lock and returns with the assigned queue locked.
1077171482Sjeff */
1078171482Sjeffstatic inline struct tdq *
1079177435Sjeffsched_setcpu(struct thread *td, int cpu, int flags)
1080123433Sjeff{
1081177435Sjeff
1082171482Sjeff	struct tdq *tdq;
1083123433Sjeff
1084177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1085171482Sjeff	tdq = TDQ_CPU(cpu);
1086177435Sjeff	td->td_sched->ts_cpu = cpu;
1087177435Sjeff	/*
1088177435Sjeff	 * If the lock matches just return the queue.
1089177435Sjeff	 */
1090171482Sjeff	if (td->td_lock == TDQ_LOCKPTR(tdq))
1091171482Sjeff		return (tdq);
1092171482Sjeff#ifdef notyet
1093123433Sjeff	/*
1094172293Sjeff	 * If the thread isn't running its lockptr is a
1095171482Sjeff	 * turnstile or a sleepqueue.  We can just lock_set without
1096171482Sjeff	 * blocking.
1097123685Sjeff	 */
1098171482Sjeff	if (TD_CAN_RUN(td)) {
1099171482Sjeff		TDQ_LOCK(tdq);
1100171482Sjeff		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1101171482Sjeff		return (tdq);
1102171482Sjeff	}
1103171482Sjeff#endif
1104166108Sjeff	/*
1105171482Sjeff	 * The hard case, migration, we need to block the thread first to
1106171482Sjeff	 * prevent order reversals with other cpus locks.
1107166108Sjeff	 */
1108202889Sattilio	spinlock_enter();
1109171482Sjeff	thread_lock_block(td);
1110171482Sjeff	TDQ_LOCK(tdq);
1111171713Sjeff	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1112202889Sattilio	spinlock_exit();
1113171482Sjeff	return (tdq);
1114166108Sjeff}
1115166108Sjeff
1116178272SjeffSCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
1117178272SjeffSCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
1118178272SjeffSCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
1119178272SjeffSCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
1120178272SjeffSCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
1121178272SjeffSCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
1122178272Sjeff
1123166108Sjeffstatic int
1124177435Sjeffsched_pickcpu(struct thread *td, int flags)
1125171482Sjeff{
1126176735Sjeff	struct cpu_group *cg;
1127177435Sjeff	struct td_sched *ts;
1128171482Sjeff	struct tdq *tdq;
1129194779Sjeff	cpuset_t mask;
1130166108Sjeff	int self;
1131166108Sjeff	int pri;
1132166108Sjeff	int cpu;
1133166108Sjeff
1134176735Sjeff	self = PCPU_GET(cpuid);
1135177435Sjeff	ts = td->td_sched;
1136166108Sjeff	if (smp_started == 0)
1137166108Sjeff		return (self);
1138171506Sjeff	/*
1139171506Sjeff	 * Don't migrate a running thread from sched_switch().
1140171506Sjeff	 */
1141176735Sjeff	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1142176735Sjeff		return (ts->ts_cpu);
1143166108Sjeff	/*
1144176735Sjeff	 * Prefer to run interrupt threads on the processors that generate
1145176735Sjeff	 * the interrupt.
1146166108Sjeff	 */
1147176735Sjeff	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1148178272Sjeff	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
1149178272Sjeff		SCHED_STAT_INC(pickcpu_intrbind);
1150176735Sjeff		ts->ts_cpu = self;
1151178272Sjeff	}
1152166108Sjeff	/*
1153176735Sjeff	 * If the thread can run on the last cpu and the affinity has not
1154176735Sjeff	 * expired or it is idle run it there.
1155166108Sjeff	 */
1156176735Sjeff	pri = td->td_priority;
1157176735Sjeff	tdq = TDQ_CPU(ts->ts_cpu);
1158176735Sjeff	if (THREAD_CAN_SCHED(td, ts->ts_cpu)) {
1159178272Sjeff		if (tdq->tdq_lowpri > PRI_MIN_IDLE) {
1160178272Sjeff			SCHED_STAT_INC(pickcpu_idle_affinity);
1161176735Sjeff			return (ts->ts_cpu);
1162178272Sjeff		}
1163178272Sjeff		if (SCHED_AFFINITY(ts, CG_SHARE_L2) && tdq->tdq_lowpri > pri) {
1164178272Sjeff			SCHED_STAT_INC(pickcpu_affinity);
1165176735Sjeff			return (ts->ts_cpu);
1166178272Sjeff		}
1167139334Sjeff	}
1168123433Sjeff	/*
1169176735Sjeff	 * Search for the highest level in the tree that still has affinity.
1170123433Sjeff	 */
1171176735Sjeff	cg = NULL;
1172176735Sjeff	for (cg = tdq->tdq_cg; cg != NULL; cg = cg->cg_parent)
1173176735Sjeff		if (SCHED_AFFINITY(ts, cg->cg_level))
1174176735Sjeff			break;
1175176735Sjeff	cpu = -1;
1176194779Sjeff	mask = td->td_cpuset->cs_mask;
1177176735Sjeff	if (cg)
1178176735Sjeff		cpu = sched_lowest(cg, mask, pri);
1179176735Sjeff	if (cpu == -1)
1180176735Sjeff		cpu = sched_lowest(cpu_top, mask, -1);
1181171506Sjeff	/*
1182176735Sjeff	 * Compare the lowest loaded cpu to current cpu.
1183171506Sjeff	 */
1184177005Sjeff	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
1185178272Sjeff	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE) {
1186178272Sjeff		SCHED_STAT_INC(pickcpu_local);
1187177005Sjeff		cpu = self;
1188178272Sjeff	} else
1189178272Sjeff		SCHED_STAT_INC(pickcpu_lowest);
1190178272Sjeff	if (cpu != ts->ts_cpu)
1191178272Sjeff		SCHED_STAT_INC(pickcpu_migration);
1192177005Sjeff	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1193171482Sjeff	return (cpu);
1194123433Sjeff}
1195176735Sjeff#endif
1196123433Sjeff
1197117326Sjeff/*
1198121790Sjeff * Pick the highest priority task we have and return it.
1199117326Sjeff */
1200177435Sjeffstatic struct thread *
1201164936Sjuliantdq_choose(struct tdq *tdq)
1202110267Sjeff{
1203177435Sjeff	struct thread *td;
1204110267Sjeff
1205171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1206177435Sjeff	td = runq_choose(&tdq->tdq_realtime);
1207177435Sjeff	if (td != NULL)
1208177435Sjeff		return (td);
1209177435Sjeff	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1210177435Sjeff	if (td != NULL) {
1211177435Sjeff		KASSERT(td->td_priority >= PRI_MIN_TIMESHARE,
1212165762Sjeff		    ("tdq_choose: Invalid priority on timeshare queue %d",
1213177435Sjeff		    td->td_priority));
1214177435Sjeff		return (td);
1215165762Sjeff	}
1216177435Sjeff	td = runq_choose(&tdq->tdq_idle);
1217177435Sjeff	if (td != NULL) {
1218177435Sjeff		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1219165762Sjeff		    ("tdq_choose: Invalid priority on idle queue %d",
1220177435Sjeff		    td->td_priority));
1221177435Sjeff		return (td);
1222165762Sjeff	}
1223165762Sjeff
1224165762Sjeff	return (NULL);
1225110267Sjeff}
1226110267Sjeff
1227171482Sjeff/*
1228171482Sjeff * Initialize a thread queue.
1229171482Sjeff */
1230109864Sjeffstatic void
1231164936Sjuliantdq_setup(struct tdq *tdq)
1232110028Sjeff{
1233171482Sjeff
1234171713Sjeff	if (bootverbose)
1235171713Sjeff		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1236165762Sjeff	runq_init(&tdq->tdq_realtime);
1237165762Sjeff	runq_init(&tdq->tdq_timeshare);
1238165620Sjeff	runq_init(&tdq->tdq_idle);
1239176735Sjeff	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1240176735Sjeff	    "sched lock %d", (int)TDQ_ID(tdq));
1241176735Sjeff	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1242176735Sjeff	    MTX_SPIN | MTX_RECURSE);
1243187357Sjeff#ifdef KTR
1244187357Sjeff	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
1245187357Sjeff	    "CPU %d load", (int)TDQ_ID(tdq));
1246187357Sjeff#endif
1247110028Sjeff}
1248110028Sjeff
1249171713Sjeff#ifdef SMP
1250110028Sjeffstatic void
1251171713Sjeffsched_setup_smp(void)
1252171713Sjeff{
1253171713Sjeff	struct tdq *tdq;
1254171713Sjeff	int i;
1255171713Sjeff
1256176735Sjeff	cpu_top = smp_topo();
1257176735Sjeff	for (i = 0; i < MAXCPU; i++) {
1258171713Sjeff		if (CPU_ABSENT(i))
1259171713Sjeff			continue;
1260176735Sjeff		tdq = TDQ_CPU(i);
1261171713Sjeff		tdq_setup(tdq);
1262176735Sjeff		tdq->tdq_cg = smp_topo_find(cpu_top, i);
1263176735Sjeff		if (tdq->tdq_cg == NULL)
1264176735Sjeff			panic("Can't find cpu group for %d\n", i);
1265123433Sjeff	}
1266176735Sjeff	balance_tdq = TDQ_SELF();
1267176735Sjeff	sched_balance();
1268171713Sjeff}
1269171713Sjeff#endif
1270171713Sjeff
1271171713Sjeff/*
1272171713Sjeff * Setup the thread queues and initialize the topology based on MD
1273171713Sjeff * information.
1274171713Sjeff */
1275171713Sjeffstatic void
1276171713Sjeffsched_setup(void *dummy)
1277171713Sjeff{
1278171713Sjeff	struct tdq *tdq;
1279171713Sjeff
1280171713Sjeff	tdq = TDQ_SELF();
1281171713Sjeff#ifdef SMP
1282176734Sjeff	sched_setup_smp();
1283117237Sjeff#else
1284171713Sjeff	tdq_setup(tdq);
1285116069Sjeff#endif
1286171482Sjeff	/*
1287171482Sjeff	 * To avoid divide-by-zero, we set realstathz a dummy value
1288171482Sjeff	 * in case which sched_clock() called before sched_initticks().
1289171482Sjeff	 */
1290171482Sjeff	realstathz = hz;
1291171482Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1292171482Sjeff	tickincr = 1 << SCHED_TICK_SHIFT;
1293171482Sjeff
1294171482Sjeff	/* Add thread0's load since it's running. */
1295171482Sjeff	TDQ_LOCK(tdq);
1296171713Sjeff	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1297177435Sjeff	tdq_load_add(tdq, &thread0);
1298176735Sjeff	tdq->tdq_lowpri = thread0.td_priority;
1299171482Sjeff	TDQ_UNLOCK(tdq);
1300109864Sjeff}
1301109864Sjeff
1302171482Sjeff/*
1303171482Sjeff * This routine determines the tickincr after stathz and hz are setup.
1304171482Sjeff */
1305153533Sdavidxu/* ARGSUSED */
1306153533Sdavidxustatic void
1307153533Sdavidxusched_initticks(void *dummy)
1308153533Sdavidxu{
1309171482Sjeff	int incr;
1310171482Sjeff
1311153533Sdavidxu	realstathz = stathz ? stathz : hz;
1312166229Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1313153533Sdavidxu
1314153533Sdavidxu	/*
1315165762Sjeff	 * tickincr is shifted out by 10 to avoid rounding errors due to
1316165766Sjeff	 * hz not being evenly divisible by stathz on all platforms.
1317153533Sdavidxu	 */
1318171482Sjeff	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1319165762Sjeff	/*
1320165762Sjeff	 * This does not work for values of stathz that are more than
1321165762Sjeff	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1322165762Sjeff	 */
1323171482Sjeff	if (incr == 0)
1324171482Sjeff		incr = 1;
1325171482Sjeff	tickincr = incr;
1326166108Sjeff#ifdef SMP
1327171899Sjeff	/*
1328172409Sjeff	 * Set the default balance interval now that we know
1329172409Sjeff	 * what realstathz is.
1330172409Sjeff	 */
1331172409Sjeff	balance_interval = realstathz;
1332172409Sjeff	/*
1333189787Sjeff	 * Set steal thresh to roughly log2(mp_ncpu) but no greater than 4.
1334189787Sjeff	 * This prevents excess thrashing on large machines and excess idle
1335189787Sjeff	 * on smaller machines.
1336171899Sjeff	 */
1337189787Sjeff	steal_thresh = min(fls(mp_ncpus) - 1, 3);
1338166108Sjeff	affinity = SCHED_AFFINITY_DEFAULT;
1339166108Sjeff#endif
1340153533Sdavidxu}
1341153533Sdavidxu
1342153533Sdavidxu
1343109864Sjeff/*
1344171482Sjeff * This is the core of the interactivity algorithm.  Determines a score based
1345171482Sjeff * on past behavior.  It is the ratio of sleep time to run time scaled to
1346171482Sjeff * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1347171482Sjeff * differs from the cpu usage because it does not account for time spent
1348171482Sjeff * waiting on a run-queue.  Would be prettier if we had floating point.
1349171482Sjeff */
1350171482Sjeffstatic int
1351171482Sjeffsched_interact_score(struct thread *td)
1352171482Sjeff{
1353171482Sjeff	struct td_sched *ts;
1354171482Sjeff	int div;
1355171482Sjeff
1356171482Sjeff	ts = td->td_sched;
1357171482Sjeff	/*
1358171482Sjeff	 * The score is only needed if this is likely to be an interactive
1359171482Sjeff	 * task.  Don't go through the expense of computing it if there's
1360171482Sjeff	 * no chance.
1361171482Sjeff	 */
1362171482Sjeff	if (sched_interact <= SCHED_INTERACT_HALF &&
1363171482Sjeff		ts->ts_runtime >= ts->ts_slptime)
1364171482Sjeff			return (SCHED_INTERACT_HALF);
1365171482Sjeff
1366171482Sjeff	if (ts->ts_runtime > ts->ts_slptime) {
1367171482Sjeff		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1368171482Sjeff		return (SCHED_INTERACT_HALF +
1369171482Sjeff		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1370171482Sjeff	}
1371171482Sjeff	if (ts->ts_slptime > ts->ts_runtime) {
1372171482Sjeff		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1373171482Sjeff		return (ts->ts_runtime / div);
1374171482Sjeff	}
1375171482Sjeff	/* runtime == slptime */
1376171482Sjeff	if (ts->ts_runtime)
1377171482Sjeff		return (SCHED_INTERACT_HALF);
1378171482Sjeff
1379171482Sjeff	/*
1380171482Sjeff	 * This can happen if slptime and runtime are 0.
1381171482Sjeff	 */
1382171482Sjeff	return (0);
1383171482Sjeff
1384171482Sjeff}
1385171482Sjeff
1386171482Sjeff/*
1387109864Sjeff * Scale the scheduling priority according to the "interactivity" of this
1388109864Sjeff * process.
1389109864Sjeff */
1390113357Sjeffstatic void
1391163709Sjbsched_priority(struct thread *td)
1392109864Sjeff{
1393165762Sjeff	int score;
1394109864Sjeff	int pri;
1395109864Sjeff
1396163709Sjb	if (td->td_pri_class != PRI_TIMESHARE)
1397113357Sjeff		return;
1398112966Sjeff	/*
1399165762Sjeff	 * If the score is interactive we place the thread in the realtime
1400165762Sjeff	 * queue with a priority that is less than kernel and interrupt
1401165762Sjeff	 * priorities.  These threads are not subject to nice restrictions.
1402112966Sjeff	 *
1403171482Sjeff	 * Scores greater than this are placed on the normal timeshare queue
1404165762Sjeff	 * where the priority is partially decided by the most recent cpu
1405165762Sjeff	 * utilization and the rest is decided by nice value.
1406172293Sjeff	 *
1407172293Sjeff	 * The nice value of the process has a linear effect on the calculated
1408172293Sjeff	 * score.  Negative nice values make it easier for a thread to be
1409172293Sjeff	 * considered interactive.
1410112966Sjeff	 */
1411198126Sjhb	score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1412165762Sjeff	if (score < sched_interact) {
1413165762Sjeff		pri = PRI_MIN_REALTIME;
1414165762Sjeff		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1415165762Sjeff		    * score;
1416165762Sjeff		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1417166208Sjeff		    ("sched_priority: invalid interactive priority %d score %d",
1418166208Sjeff		    pri, score));
1419165762Sjeff	} else {
1420165762Sjeff		pri = SCHED_PRI_MIN;
1421165762Sjeff		if (td->td_sched->ts_ticks)
1422165762Sjeff			pri += SCHED_PRI_TICKS(td->td_sched);
1423165762Sjeff		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1424171482Sjeff		KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1425171482Sjeff		    ("sched_priority: invalid priority %d: nice %d, "
1426171482Sjeff		    "ticks %d ftick %d ltick %d tick pri %d",
1427171482Sjeff		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1428171482Sjeff		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1429171482Sjeff		    SCHED_PRI_TICKS(td->td_sched)));
1430165762Sjeff	}
1431165762Sjeff	sched_user_prio(td, pri);
1432112966Sjeff
1433112966Sjeff	return;
1434109864Sjeff}
1435109864Sjeff
1436121868Sjeff/*
1437121868Sjeff * This routine enforces a maximum limit on the amount of scheduling history
1438171482Sjeff * kept.  It is called after either the slptime or runtime is adjusted.  This
1439171482Sjeff * function is ugly due to integer math.
1440121868Sjeff */
1441116463Sjeffstatic void
1442163709Sjbsched_interact_update(struct thread *td)
1443116463Sjeff{
1444165819Sjeff	struct td_sched *ts;
1445166208Sjeff	u_int sum;
1446121605Sjeff
1447165819Sjeff	ts = td->td_sched;
1448171482Sjeff	sum = ts->ts_runtime + ts->ts_slptime;
1449121868Sjeff	if (sum < SCHED_SLP_RUN_MAX)
1450121868Sjeff		return;
1451121868Sjeff	/*
1452165819Sjeff	 * This only happens from two places:
1453165819Sjeff	 * 1) We have added an unusual amount of run time from fork_exit.
1454165819Sjeff	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1455165819Sjeff	 */
1456165819Sjeff	if (sum > SCHED_SLP_RUN_MAX * 2) {
1457171482Sjeff		if (ts->ts_runtime > ts->ts_slptime) {
1458171482Sjeff			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1459171482Sjeff			ts->ts_slptime = 1;
1460165819Sjeff		} else {
1461171482Sjeff			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1462171482Sjeff			ts->ts_runtime = 1;
1463165819Sjeff		}
1464165819Sjeff		return;
1465165819Sjeff	}
1466165819Sjeff	/*
1467121868Sjeff	 * If we have exceeded by more than 1/5th then the algorithm below
1468121868Sjeff	 * will not bring us back into range.  Dividing by two here forces
1469133427Sjeff	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1470121868Sjeff	 */
1471127850Sjeff	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1472171482Sjeff		ts->ts_runtime /= 2;
1473171482Sjeff		ts->ts_slptime /= 2;
1474121868Sjeff		return;
1475116463Sjeff	}
1476171482Sjeff	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1477171482Sjeff	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1478116463Sjeff}
1479116463Sjeff
1480171482Sjeff/*
1481171482Sjeff * Scale back the interactivity history when a child thread is created.  The
1482171482Sjeff * history is inherited from the parent but the thread may behave totally
1483171482Sjeff * differently.  For example, a shell spawning a compiler process.  We want
1484171482Sjeff * to learn that the compiler is behaving badly very quickly.
1485171482Sjeff */
1486121868Sjeffstatic void
1487163709Sjbsched_interact_fork(struct thread *td)
1488121868Sjeff{
1489121868Sjeff	int ratio;
1490121868Sjeff	int sum;
1491121868Sjeff
1492171482Sjeff	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1493121868Sjeff	if (sum > SCHED_SLP_RUN_FORK) {
1494121868Sjeff		ratio = sum / SCHED_SLP_RUN_FORK;
1495171482Sjeff		td->td_sched->ts_runtime /= ratio;
1496171482Sjeff		td->td_sched->ts_slptime /= ratio;
1497121868Sjeff	}
1498121868Sjeff}
1499121868Sjeff
1500113357Sjeff/*
1501171482Sjeff * Called from proc0_init() to setup the scheduler fields.
1502134791Sjulian */
1503134791Sjulianvoid
1504134791Sjulianschedinit(void)
1505134791Sjulian{
1506165762Sjeff
1507134791Sjulian	/*
1508134791Sjulian	 * Set up the scheduler specific parts of proc0.
1509134791Sjulian	 */
1510136167Sjulian	proc0.p_sched = NULL; /* XXX */
1511164936Sjulian	thread0.td_sched = &td_sched0;
1512165762Sjeff	td_sched0.ts_ltick = ticks;
1513165796Sjeff	td_sched0.ts_ftick = ticks;
1514177009Sjeff	td_sched0.ts_slice = sched_slice;
1515134791Sjulian}
1516134791Sjulian
1517134791Sjulian/*
1518113357Sjeff * This is only somewhat accurate since given many processes of the same
1519113357Sjeff * priority they will switch when their slices run out, which will be
1520165762Sjeff * at most sched_slice stathz ticks.
1521113357Sjeff */
1522109864Sjeffint
1523109864Sjeffsched_rr_interval(void)
1524109864Sjeff{
1525165762Sjeff
1526165762Sjeff	/* Convert sched_slice to hz */
1527165762Sjeff	return (hz/(realstathz/sched_slice));
1528109864Sjeff}
1529109864Sjeff
1530171482Sjeff/*
1531171482Sjeff * Update the percent cpu tracking information when it is requested or
1532171482Sjeff * the total history exceeds the maximum.  We keep a sliding history of
1533171482Sjeff * tick counts that slowly decays.  This is less precise than the 4BSD
1534171482Sjeff * mechanism since it happens with less regular and frequent events.
1535171482Sjeff */
1536121790Sjeffstatic void
1537164936Sjuliansched_pctcpu_update(struct td_sched *ts)
1538109864Sjeff{
1539165762Sjeff
1540165762Sjeff	if (ts->ts_ticks == 0)
1541165762Sjeff		return;
1542165796Sjeff	if (ticks - (hz / 10) < ts->ts_ltick &&
1543165796Sjeff	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1544165796Sjeff		return;
1545109864Sjeff	/*
1546109864Sjeff	 * Adjust counters and watermark for pctcpu calc.
1547116365Sjeff	 */
1548165762Sjeff	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1549164936Sjulian		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1550165762Sjeff			    SCHED_TICK_TARG;
1551165762Sjeff	else
1552164936Sjulian		ts->ts_ticks = 0;
1553164936Sjulian	ts->ts_ltick = ticks;
1554165762Sjeff	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1555109864Sjeff}
1556109864Sjeff
1557171482Sjeff/*
1558171482Sjeff * Adjust the priority of a thread.  Move it to the appropriate run-queue
1559171482Sjeff * if necessary.  This is the back-end for several priority related
1560171482Sjeff * functions.
1561171482Sjeff */
1562165762Sjeffstatic void
1563139453Sjhbsched_thread_priority(struct thread *td, u_char prio)
1564109864Sjeff{
1565164936Sjulian	struct td_sched *ts;
1566177009Sjeff	struct tdq *tdq;
1567177009Sjeff	int oldpri;
1568109864Sjeff
1569187357Sjeff	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
1570187357Sjeff	    "prio:%d", td->td_priority, "new prio:%d", prio,
1571187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(curthread));
1572187357Sjeff	if (td != curthread && prio > td->td_priority) {
1573187357Sjeff		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
1574187357Sjeff		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
1575187357Sjeff		    prio, KTR_ATTR_LINKED, sched_tdname(td));
1576187357Sjeff	}
1577164936Sjulian	ts = td->td_sched;
1578170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1579139453Sjhb	if (td->td_priority == prio)
1580139453Sjhb		return;
1581177376Sjeff	/*
1582177376Sjeff	 * If the priority has been elevated due to priority
1583177376Sjeff	 * propagation, we may have to move ourselves to a new
1584177376Sjeff	 * queue.  This could be optimized to not re-add in some
1585177376Sjeff	 * cases.
1586177376Sjeff	 */
1587165766Sjeff	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1588165762Sjeff		sched_rem(td);
1589165762Sjeff		td->td_priority = prio;
1590171482Sjeff		sched_add(td, SRQ_BORROWING);
1591177009Sjeff		return;
1592177009Sjeff	}
1593177376Sjeff	/*
1594177376Sjeff	 * If the thread is currently running we may have to adjust the lowpri
1595177376Sjeff	 * information so other cpus are aware of our current priority.
1596177376Sjeff	 */
1597177009Sjeff	if (TD_IS_RUNNING(td)) {
1598177376Sjeff		tdq = TDQ_CPU(ts->ts_cpu);
1599177376Sjeff		oldpri = td->td_priority;
1600177376Sjeff		td->td_priority = prio;
1601176735Sjeff		if (prio < tdq->tdq_lowpri)
1602171482Sjeff			tdq->tdq_lowpri = prio;
1603176735Sjeff		else if (tdq->tdq_lowpri == oldpri)
1604176735Sjeff			tdq_setlowpri(tdq, td);
1605177376Sjeff		return;
1606177009Sjeff	}
1607177376Sjeff	td->td_priority = prio;
1608109864Sjeff}
1609109864Sjeff
1610139453Sjhb/*
1611139453Sjhb * Update a thread's priority when it is lent another thread's
1612139453Sjhb * priority.
1613139453Sjhb */
1614109864Sjeffvoid
1615139453Sjhbsched_lend_prio(struct thread *td, u_char prio)
1616139453Sjhb{
1617139453Sjhb
1618139453Sjhb	td->td_flags |= TDF_BORROWING;
1619139453Sjhb	sched_thread_priority(td, prio);
1620139453Sjhb}
1621139453Sjhb
1622139453Sjhb/*
1623139453Sjhb * Restore a thread's priority when priority propagation is
1624139453Sjhb * over.  The prio argument is the minimum priority the thread
1625139453Sjhb * needs to have to satisfy other possible priority lending
1626139453Sjhb * requests.  If the thread's regular priority is less
1627139453Sjhb * important than prio, the thread will keep a priority boost
1628139453Sjhb * of prio.
1629139453Sjhb */
1630139453Sjhbvoid
1631139453Sjhbsched_unlend_prio(struct thread *td, u_char prio)
1632139453Sjhb{
1633139453Sjhb	u_char base_pri;
1634139453Sjhb
1635139453Sjhb	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1636139453Sjhb	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1637163709Sjb		base_pri = td->td_user_pri;
1638139453Sjhb	else
1639139453Sjhb		base_pri = td->td_base_pri;
1640139453Sjhb	if (prio >= base_pri) {
1641139455Sjhb		td->td_flags &= ~TDF_BORROWING;
1642139453Sjhb		sched_thread_priority(td, base_pri);
1643139453Sjhb	} else
1644139453Sjhb		sched_lend_prio(td, prio);
1645139453Sjhb}
1646139453Sjhb
1647171482Sjeff/*
1648171482Sjeff * Standard entry for setting the priority to an absolute value.
1649171482Sjeff */
1650139453Sjhbvoid
1651139453Sjhbsched_prio(struct thread *td, u_char prio)
1652139453Sjhb{
1653139453Sjhb	u_char oldprio;
1654139453Sjhb
1655139453Sjhb	/* First, update the base priority. */
1656139453Sjhb	td->td_base_pri = prio;
1657139453Sjhb
1658139453Sjhb	/*
1659139455Sjhb	 * If the thread is borrowing another thread's priority, don't
1660139453Sjhb	 * ever lower the priority.
1661139453Sjhb	 */
1662139453Sjhb	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1663139453Sjhb		return;
1664139453Sjhb
1665139453Sjhb	/* Change the real priority. */
1666139453Sjhb	oldprio = td->td_priority;
1667139453Sjhb	sched_thread_priority(td, prio);
1668139453Sjhb
1669139453Sjhb	/*
1670139453Sjhb	 * If the thread is on a turnstile, then let the turnstile update
1671139453Sjhb	 * its state.
1672139453Sjhb	 */
1673139453Sjhb	if (TD_ON_LOCK(td) && oldprio != prio)
1674139453Sjhb		turnstile_adjust(td, oldprio);
1675139453Sjhb}
1676139455Sjhb
1677171482Sjeff/*
1678171482Sjeff * Set the base user priority, does not effect current running priority.
1679171482Sjeff */
1680139453Sjhbvoid
1681163709Sjbsched_user_prio(struct thread *td, u_char prio)
1682161599Sdavidxu{
1683161599Sdavidxu	u_char oldprio;
1684161599Sdavidxu
1685163709Sjb	td->td_base_user_pri = prio;
1686164939Sjulian	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1687164939Sjulian                return;
1688163709Sjb	oldprio = td->td_user_pri;
1689163709Sjb	td->td_user_pri = prio;
1690161599Sdavidxu}
1691161599Sdavidxu
1692161599Sdavidxuvoid
1693161599Sdavidxusched_lend_user_prio(struct thread *td, u_char prio)
1694161599Sdavidxu{
1695161599Sdavidxu	u_char oldprio;
1696161599Sdavidxu
1697174536Sdavidxu	THREAD_LOCK_ASSERT(td, MA_OWNED);
1698161599Sdavidxu	td->td_flags |= TDF_UBORROWING;
1699164091Smaxim	oldprio = td->td_user_pri;
1700163709Sjb	td->td_user_pri = prio;
1701161599Sdavidxu}
1702161599Sdavidxu
1703161599Sdavidxuvoid
1704161599Sdavidxusched_unlend_user_prio(struct thread *td, u_char prio)
1705161599Sdavidxu{
1706161599Sdavidxu	u_char base_pri;
1707161599Sdavidxu
1708174536Sdavidxu	THREAD_LOCK_ASSERT(td, MA_OWNED);
1709163709Sjb	base_pri = td->td_base_user_pri;
1710161599Sdavidxu	if (prio >= base_pri) {
1711161599Sdavidxu		td->td_flags &= ~TDF_UBORROWING;
1712163709Sjb		sched_user_prio(td, base_pri);
1713174536Sdavidxu	} else {
1714161599Sdavidxu		sched_lend_user_prio(td, prio);
1715174536Sdavidxu	}
1716161599Sdavidxu}
1717161599Sdavidxu
1718171482Sjeff/*
1719171713Sjeff * Handle migration from sched_switch().  This happens only for
1720171713Sjeff * cpu binding.
1721171713Sjeff */
1722171713Sjeffstatic struct mtx *
1723171713Sjeffsched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1724171713Sjeff{
1725171713Sjeff	struct tdq *tdn;
1726171713Sjeff
1727171713Sjeff	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1728171713Sjeff#ifdef SMP
1729177435Sjeff	tdq_load_rem(tdq, td);
1730171713Sjeff	/*
1731171713Sjeff	 * Do the lock dance required to avoid LOR.  We grab an extra
1732171713Sjeff	 * spinlock nesting to prevent preemption while we're
1733171713Sjeff	 * not holding either run-queue lock.
1734171713Sjeff	 */
1735171713Sjeff	spinlock_enter();
1736202889Sattilio	thread_lock_block(td);	/* This releases the lock on tdq. */
1737197223Sattilio
1738197223Sattilio	/*
1739197223Sattilio	 * Acquire both run-queue locks before placing the thread on the new
1740197223Sattilio	 * run-queue to avoid deadlocks created by placing a thread with a
1741197223Sattilio	 * blocked lock on the run-queue of a remote processor.  The deadlock
1742197223Sattilio	 * occurs when a third processor attempts to lock the two queues in
1743197223Sattilio	 * question while the target processor is spinning with its own
1744197223Sattilio	 * run-queue lock held while waiting for the blocked lock to clear.
1745197223Sattilio	 */
1746197223Sattilio	tdq_lock_pair(tdn, tdq);
1747171713Sjeff	tdq_add(tdn, td, flags);
1748177435Sjeff	tdq_notify(tdn, td);
1749197223Sattilio	TDQ_UNLOCK(tdn);
1750171713Sjeff	spinlock_exit();
1751171713Sjeff#endif
1752171713Sjeff	return (TDQ_LOCKPTR(tdn));
1753171713Sjeff}
1754171713Sjeff
1755171713Sjeff/*
1756202889Sattilio * Variadic version of thread_lock_unblock() that does not assume td_lock
1757202889Sattilio * is blocked.
1758171482Sjeff */
1759171482Sjeffstatic inline void
1760171482Sjeffthread_unblock_switch(struct thread *td, struct mtx *mtx)
1761171482Sjeff{
1762171482Sjeff	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1763171482Sjeff	    (uintptr_t)mtx);
1764171482Sjeff}
1765171482Sjeff
1766171482Sjeff/*
1767171482Sjeff * Switch threads.  This function has to handle threads coming in while
1768171482Sjeff * blocked for some reason, running, or idle.  It also must deal with
1769171482Sjeff * migrating a thread from one queue to another as running threads may
1770171482Sjeff * be assigned elsewhere via binding.
1771171482Sjeff */
1772161599Sdavidxuvoid
1773135051Sjuliansched_switch(struct thread *td, struct thread *newtd, int flags)
1774109864Sjeff{
1775165627Sjeff	struct tdq *tdq;
1776164936Sjulian	struct td_sched *ts;
1777171482Sjeff	struct mtx *mtx;
1778171713Sjeff	int srqflag;
1779171482Sjeff	int cpuid;
1780109864Sjeff
1781170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1782177376Sjeff	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
1783109864Sjeff
1784171482Sjeff	cpuid = PCPU_GET(cpuid);
1785171482Sjeff	tdq = TDQ_CPU(cpuid);
1786164936Sjulian	ts = td->td_sched;
1787171713Sjeff	mtx = td->td_lock;
1788171482Sjeff	ts->ts_rltick = ticks;
1789133555Sjeff	td->td_lastcpu = td->td_oncpu;
1790113339Sjulian	td->td_oncpu = NOCPU;
1791132266Sjhb	td->td_flags &= ~TDF_NEEDRESCHED;
1792144777Sups	td->td_owepreempt = 0;
1793178277Sjeff	tdq->tdq_switchcnt++;
1794123434Sjeff	/*
1795171482Sjeff	 * The lock pointer in an idle thread should never change.  Reset it
1796171482Sjeff	 * to CAN_RUN as well.
1797123434Sjeff	 */
1798167327Sjulian	if (TD_IS_IDLETHREAD(td)) {
1799171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1800139334Sjeff		TD_SET_CAN_RUN(td);
1801170293Sjeff	} else if (TD_IS_RUNNING(td)) {
1802171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1803171713Sjeff		srqflag = (flags & SW_PREEMPT) ?
1804170293Sjeff		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1805171713Sjeff		    SRQ_OURSELF|SRQ_YIELDING;
1806171713Sjeff		if (ts->ts_cpu == cpuid)
1807177435Sjeff			tdq_runq_add(tdq, td, srqflag);
1808171713Sjeff		else
1809171713Sjeff			mtx = sched_switch_migrate(tdq, td, srqflag);
1810171482Sjeff	} else {
1811171482Sjeff		/* This thread must be going to sleep. */
1812171482Sjeff		TDQ_LOCK(tdq);
1813202889Sattilio		mtx = thread_lock_block(td);
1814177435Sjeff		tdq_load_rem(tdq, td);
1815171482Sjeff	}
1816171482Sjeff	/*
1817171482Sjeff	 * We enter here with the thread blocked and assigned to the
1818171482Sjeff	 * appropriate cpu run-queue or sleep-queue and with the current
1819171482Sjeff	 * thread-queue locked.
1820171482Sjeff	 */
1821171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1822171482Sjeff	newtd = choosethread();
1823171482Sjeff	/*
1824171482Sjeff	 * Call the MD code to switch contexts if necessary.
1825171482Sjeff	 */
1826145256Sjkoshy	if (td != newtd) {
1827145256Sjkoshy#ifdef	HWPMC_HOOKS
1828145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1829145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1830145256Sjkoshy#endif
1831174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1832172411Sjeff		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1833179297Sjb
1834179297Sjb#ifdef KDTRACE_HOOKS
1835179297Sjb		/*
1836179297Sjb		 * If DTrace has set the active vtime enum to anything
1837179297Sjb		 * other than INACTIVE (0), then it should have set the
1838179297Sjb		 * function to call.
1839179297Sjb		 */
1840179297Sjb		if (dtrace_vtime_active)
1841179297Sjb			(*dtrace_vtime_switch_func)(newtd);
1842179297Sjb#endif
1843179297Sjb
1844171482Sjeff		cpu_switch(td, newtd, mtx);
1845171482Sjeff		/*
1846171482Sjeff		 * We may return from cpu_switch on a different cpu.  However,
1847171482Sjeff		 * we always return with td_lock pointing to the current cpu's
1848171482Sjeff		 * run queue lock.
1849171482Sjeff		 */
1850171482Sjeff		cpuid = PCPU_GET(cpuid);
1851171482Sjeff		tdq = TDQ_CPU(cpuid);
1852174629Sjeff		lock_profile_obtain_lock_success(
1853174629Sjeff		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1854145256Sjkoshy#ifdef	HWPMC_HOOKS
1855145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1856145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1857145256Sjkoshy#endif
1858171482Sjeff	} else
1859171482Sjeff		thread_unblock_switch(td, mtx);
1860171482Sjeff	/*
1861171482Sjeff	 * Assert that all went well and return.
1862171482Sjeff	 */
1863171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1864171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1865171482Sjeff	td->td_oncpu = cpuid;
1866109864Sjeff}
1867109864Sjeff
1868171482Sjeff/*
1869171482Sjeff * Adjust thread priorities as a result of a nice request.
1870171482Sjeff */
1871109864Sjeffvoid
1872130551Sjuliansched_nice(struct proc *p, int nice)
1873109864Sjeff{
1874109864Sjeff	struct thread *td;
1875109864Sjeff
1876130551Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
1877165762Sjeff
1878130551Sjulian	p->p_nice = nice;
1879163709Sjb	FOREACH_THREAD_IN_PROC(p, td) {
1880170293Sjeff		thread_lock(td);
1881163709Sjb		sched_priority(td);
1882165762Sjeff		sched_prio(td, td->td_base_user_pri);
1883170293Sjeff		thread_unlock(td);
1884130551Sjulian	}
1885109864Sjeff}
1886109864Sjeff
1887171482Sjeff/*
1888171482Sjeff * Record the sleep time for the interactivity scorer.
1889171482Sjeff */
1890109864Sjeffvoid
1891177085Sjeffsched_sleep(struct thread *td, int prio)
1892109864Sjeff{
1893165762Sjeff
1894170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1895109864Sjeff
1896172264Sjeff	td->td_slptick = ticks;
1897201347Skib	if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
1898177085Sjeff		td->td_flags |= TDF_CANSWAP;
1899177903Sjeff	if (static_boost == 1 && prio)
1900177085Sjeff		sched_prio(td, prio);
1901177903Sjeff	else if (static_boost && td->td_priority > static_boost)
1902177903Sjeff		sched_prio(td, static_boost);
1903109864Sjeff}
1904109864Sjeff
1905171482Sjeff/*
1906171482Sjeff * Schedule a thread to resume execution and record how long it voluntarily
1907171482Sjeff * slept.  We also update the pctcpu, interactivity, and priority.
1908171482Sjeff */
1909109864Sjeffvoid
1910109864Sjeffsched_wakeup(struct thread *td)
1911109864Sjeff{
1912166229Sjeff	struct td_sched *ts;
1913171482Sjeff	int slptick;
1914165762Sjeff
1915170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1916166229Sjeff	ts = td->td_sched;
1917177085Sjeff	td->td_flags &= ~TDF_CANSWAP;
1918109864Sjeff	/*
1919165762Sjeff	 * If we slept for more than a tick update our interactivity and
1920165762Sjeff	 * priority.
1921109864Sjeff	 */
1922172264Sjeff	slptick = td->td_slptick;
1923172264Sjeff	td->td_slptick = 0;
1924171482Sjeff	if (slptick && slptick != ticks) {
1925166208Sjeff		u_int hzticks;
1926109864Sjeff
1927171482Sjeff		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1928171482Sjeff		ts->ts_slptime += hzticks;
1929165819Sjeff		sched_interact_update(td);
1930166229Sjeff		sched_pctcpu_update(ts);
1931109864Sjeff	}
1932166229Sjeff	/* Reset the slice value after we sleep. */
1933166229Sjeff	ts->ts_slice = sched_slice;
1934166190Sjeff	sched_add(td, SRQ_BORING);
1935109864Sjeff}
1936109864Sjeff
1937109864Sjeff/*
1938109864Sjeff * Penalize the parent for creating a new child and initialize the child's
1939109864Sjeff * priority.
1940109864Sjeff */
1941109864Sjeffvoid
1942163709Sjbsched_fork(struct thread *td, struct thread *child)
1943109864Sjeff{
1944170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1945164936Sjulian	sched_fork_thread(td, child);
1946165762Sjeff	/*
1947165762Sjeff	 * Penalize the parent and child for forking.
1948165762Sjeff	 */
1949165762Sjeff	sched_interact_fork(child);
1950165762Sjeff	sched_priority(child);
1951171482Sjeff	td->td_sched->ts_runtime += tickincr;
1952165762Sjeff	sched_interact_update(td);
1953165762Sjeff	sched_priority(td);
1954164936Sjulian}
1955109864Sjeff
1956171482Sjeff/*
1957171482Sjeff * Fork a new thread, may be within the same process.
1958171482Sjeff */
1959164936Sjulianvoid
1960164936Sjuliansched_fork_thread(struct thread *td, struct thread *child)
1961164936Sjulian{
1962164936Sjulian	struct td_sched *ts;
1963164936Sjulian	struct td_sched *ts2;
1964164936Sjulian
1965177426Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1966165762Sjeff	/*
1967165762Sjeff	 * Initialize child.
1968165762Sjeff	 */
1969177426Sjeff	ts = td->td_sched;
1970177426Sjeff	ts2 = child->td_sched;
1971171482Sjeff	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1972176735Sjeff	child->td_cpuset = cpuset_ref(td->td_cpuset);
1973164936Sjulian	ts2->ts_cpu = ts->ts_cpu;
1974177426Sjeff	ts2->ts_flags = 0;
1975165762Sjeff	/*
1976165762Sjeff	 * Grab our parents cpu estimation information and priority.
1977165762Sjeff	 */
1978164936Sjulian	ts2->ts_ticks = ts->ts_ticks;
1979164936Sjulian	ts2->ts_ltick = ts->ts_ltick;
1980199764Sivoras	ts2->ts_incrtick = ts->ts_incrtick;
1981164936Sjulian	ts2->ts_ftick = ts->ts_ftick;
1982165762Sjeff	child->td_user_pri = td->td_user_pri;
1983165762Sjeff	child->td_base_user_pri = td->td_base_user_pri;
1984165762Sjeff	/*
1985165762Sjeff	 * And update interactivity score.
1986165762Sjeff	 */
1987171482Sjeff	ts2->ts_slptime = ts->ts_slptime;
1988171482Sjeff	ts2->ts_runtime = ts->ts_runtime;
1989165762Sjeff	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
1990187357Sjeff#ifdef KTR
1991187357Sjeff	bzero(ts2->ts_name, sizeof(ts2->ts_name));
1992187357Sjeff#endif
1993113357Sjeff}
1994113357Sjeff
1995171482Sjeff/*
1996171482Sjeff * Adjust the priority class of a thread.
1997171482Sjeff */
1998113357Sjeffvoid
1999163709Sjbsched_class(struct thread *td, int class)
2000113357Sjeff{
2001113357Sjeff
2002170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2003163709Sjb	if (td->td_pri_class == class)
2004113357Sjeff		return;
2005163709Sjb	td->td_pri_class = class;
2006109864Sjeff}
2007109864Sjeff
2008109864Sjeff/*
2009109864Sjeff * Return some of the child's priority and interactivity to the parent.
2010109864Sjeff */
2011109864Sjeffvoid
2012164939Sjuliansched_exit(struct proc *p, struct thread *child)
2013109864Sjeff{
2014165762Sjeff	struct thread *td;
2015113372Sjeff
2016187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2017187357Sjeff	    "prio:td", child->td_priority);
2018177368Sjeff	PROC_LOCK_ASSERT(p, MA_OWNED);
2019165762Sjeff	td = FIRST_THREAD_IN_PROC(p);
2020165762Sjeff	sched_exit_thread(td, child);
2021113372Sjeff}
2022113372Sjeff
2023171482Sjeff/*
2024171482Sjeff * Penalize another thread for the time spent on this one.  This helps to
2025171482Sjeff * worsen the priority and interactivity of processes which schedule batch
2026171482Sjeff * jobs such as make.  This has little effect on the make process itself but
2027171482Sjeff * causes new processes spawned by it to receive worse scores immediately.
2028171482Sjeff */
2029113372Sjeffvoid
2030164939Sjuliansched_exit_thread(struct thread *td, struct thread *child)
2031164936Sjulian{
2032165762Sjeff
2033187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2034187357Sjeff	    "prio:td", child->td_priority);
2035165762Sjeff	/*
2036165762Sjeff	 * Give the child's runtime to the parent without returning the
2037165762Sjeff	 * sleep time as a penalty to the parent.  This causes shells that
2038165762Sjeff	 * launch expensive things to mark their children as expensive.
2039165762Sjeff	 */
2040170293Sjeff	thread_lock(td);
2041171482Sjeff	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2042164939Sjulian	sched_interact_update(td);
2043165762Sjeff	sched_priority(td);
2044170293Sjeff	thread_unlock(td);
2045164936Sjulian}
2046164936Sjulian
2047177005Sjeffvoid
2048177005Sjeffsched_preempt(struct thread *td)
2049177005Sjeff{
2050177005Sjeff	struct tdq *tdq;
2051177005Sjeff
2052177005Sjeff	thread_lock(td);
2053177005Sjeff	tdq = TDQ_SELF();
2054177005Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2055177005Sjeff	tdq->tdq_ipipending = 0;
2056177005Sjeff	if (td->td_priority > tdq->tdq_lowpri) {
2057178272Sjeff		int flags;
2058178272Sjeff
2059178272Sjeff		flags = SW_INVOL | SW_PREEMPT;
2060177005Sjeff		if (td->td_critnest > 1)
2061177005Sjeff			td->td_owepreempt = 1;
2062178272Sjeff		else if (TD_IS_IDLETHREAD(td))
2063178272Sjeff			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2064177005Sjeff		else
2065178272Sjeff			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2066177005Sjeff	}
2067177005Sjeff	thread_unlock(td);
2068177005Sjeff}
2069177005Sjeff
2070171482Sjeff/*
2071171482Sjeff * Fix priorities on return to user-space.  Priorities may be elevated due
2072171482Sjeff * to static priorities in msleep() or similar.
2073171482Sjeff */
2074164936Sjulianvoid
2075164936Sjuliansched_userret(struct thread *td)
2076164936Sjulian{
2077164936Sjulian	/*
2078164936Sjulian	 * XXX we cheat slightly on the locking here to avoid locking in
2079164936Sjulian	 * the usual case.  Setting td_priority here is essentially an
2080164936Sjulian	 * incomplete workaround for not setting it properly elsewhere.
2081164936Sjulian	 * Now that some interrupt handlers are threads, not setting it
2082164936Sjulian	 * properly elsewhere can clobber it in the window between setting
2083164936Sjulian	 * it here and returning to user mode, so don't waste time setting
2084164936Sjulian	 * it perfectly here.
2085164936Sjulian	 */
2086164936Sjulian	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2087164936Sjulian	    ("thread with borrowed priority returning to userland"));
2088164936Sjulian	if (td->td_priority != td->td_user_pri) {
2089170293Sjeff		thread_lock(td);
2090164936Sjulian		td->td_priority = td->td_user_pri;
2091164936Sjulian		td->td_base_pri = td->td_user_pri;
2092177005Sjeff		tdq_setlowpri(TDQ_SELF(), td);
2093170293Sjeff		thread_unlock(td);
2094164936Sjulian        }
2095164936Sjulian}
2096164936Sjulian
2097171482Sjeff/*
2098171482Sjeff * Handle a stathz tick.  This is really only relevant for timeshare
2099171482Sjeff * threads.
2100171482Sjeff */
2101164936Sjulianvoid
2102121127Sjeffsched_clock(struct thread *td)
2103109864Sjeff{
2104164936Sjulian	struct tdq *tdq;
2105164936Sjulian	struct td_sched *ts;
2106109864Sjeff
2107171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2108164936Sjulian	tdq = TDQ_SELF();
2109172409Sjeff#ifdef SMP
2110133427Sjeff	/*
2111172409Sjeff	 * We run the long term load balancer infrequently on the first cpu.
2112172409Sjeff	 */
2113172409Sjeff	if (balance_tdq == tdq) {
2114172409Sjeff		if (balance_ticks && --balance_ticks == 0)
2115172409Sjeff			sched_balance();
2116172409Sjeff	}
2117172409Sjeff#endif
2118172409Sjeff	/*
2119178277Sjeff	 * Save the old switch count so we have a record of the last ticks
2120178277Sjeff	 * activity.   Initialize the new switch count based on our load.
2121178277Sjeff	 * If there is some activity seed it to reflect that.
2122178277Sjeff	 */
2123178277Sjeff	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
2124178471Sjeff	tdq->tdq_switchcnt = tdq->tdq_load;
2125178277Sjeff	/*
2126165766Sjeff	 * Advance the insert index once for each tick to ensure that all
2127165766Sjeff	 * threads get a chance to run.
2128133427Sjeff	 */
2129165766Sjeff	if (tdq->tdq_idx == tdq->tdq_ridx) {
2130165766Sjeff		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2131165766Sjeff		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2132165766Sjeff			tdq->tdq_ridx = tdq->tdq_idx;
2133165766Sjeff	}
2134165766Sjeff	ts = td->td_sched;
2135175104Sjeff	if (td->td_pri_class & PRI_FIFO_BIT)
2136113357Sjeff		return;
2137175104Sjeff	if (td->td_pri_class == PRI_TIMESHARE) {
2138175104Sjeff		/*
2139175104Sjeff		 * We used a tick; charge it to the thread so
2140175104Sjeff		 * that we can compute our interactivity.
2141175104Sjeff		 */
2142175104Sjeff		td->td_sched->ts_runtime += tickincr;
2143175104Sjeff		sched_interact_update(td);
2144177009Sjeff		sched_priority(td);
2145175104Sjeff	}
2146113357Sjeff	/*
2147109864Sjeff	 * We used up one time slice.
2148109864Sjeff	 */
2149164936Sjulian	if (--ts->ts_slice > 0)
2150113357Sjeff		return;
2151109864Sjeff	/*
2152177009Sjeff	 * We're out of time, force a requeue at userret().
2153109864Sjeff	 */
2154177009Sjeff	ts->ts_slice = sched_slice;
2155113357Sjeff	td->td_flags |= TDF_NEEDRESCHED;
2156109864Sjeff}
2157109864Sjeff
2158171482Sjeff/*
2159171482Sjeff * Called once per hz tick.  Used for cpu utilization information.  This
2160171482Sjeff * is easier than trying to scale based on stathz.
2161171482Sjeff */
2162171482Sjeffvoid
2163171482Sjeffsched_tick(void)
2164171482Sjeff{
2165171482Sjeff	struct td_sched *ts;
2166171482Sjeff
2167171482Sjeff	ts = curthread->td_sched;
2168180607Sjeff	/*
2169180607Sjeff	 * Ticks is updated asynchronously on a single cpu.  Check here to
2170180607Sjeff	 * avoid incrementing ts_ticks multiple times in a single tick.
2171180607Sjeff	 */
2172199764Sivoras	if (ts->ts_incrtick == ticks)
2173180607Sjeff		return;
2174171482Sjeff	/* Adjust ticks for pctcpu */
2175171482Sjeff	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2176171482Sjeff	ts->ts_ltick = ticks;
2177199764Sivoras	ts->ts_incrtick = ticks;
2178171482Sjeff	/*
2179171482Sjeff	 * Update if we've exceeded our desired tick threshhold by over one
2180171482Sjeff	 * second.
2181171482Sjeff	 */
2182171482Sjeff	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2183171482Sjeff		sched_pctcpu_update(ts);
2184171482Sjeff}
2185171482Sjeff
2186171482Sjeff/*
2187171482Sjeff * Return whether the current CPU has runnable tasks.  Used for in-kernel
2188171482Sjeff * cooperative idle threads.
2189171482Sjeff */
2190109864Sjeffint
2191109864Sjeffsched_runnable(void)
2192109864Sjeff{
2193164936Sjulian	struct tdq *tdq;
2194115998Sjeff	int load;
2195109864Sjeff
2196115998Sjeff	load = 1;
2197115998Sjeff
2198164936Sjulian	tdq = TDQ_SELF();
2199121605Sjeff	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2200165620Sjeff		if (tdq->tdq_load > 0)
2201121605Sjeff			goto out;
2202121605Sjeff	} else
2203165620Sjeff		if (tdq->tdq_load - 1 > 0)
2204121605Sjeff			goto out;
2205115998Sjeff	load = 0;
2206115998Sjeffout:
2207115998Sjeff	return (load);
2208109864Sjeff}
2209109864Sjeff
2210171482Sjeff/*
2211171482Sjeff * Choose the highest priority thread to run.  The thread is removed from
2212171482Sjeff * the run-queue while running however the load remains.  For SMP we set
2213171482Sjeff * the tdq in the global idle bitmask if it idles here.
2214171482Sjeff */
2215166190Sjeffstruct thread *
2216109970Sjeffsched_choose(void)
2217109970Sjeff{
2218177435Sjeff	struct thread *td;
2219164936Sjulian	struct tdq *tdq;
2220109970Sjeff
2221164936Sjulian	tdq = TDQ_SELF();
2222171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2223177435Sjeff	td = tdq_choose(tdq);
2224177435Sjeff	if (td) {
2225177435Sjeff		td->td_sched->ts_ltick = ticks;
2226177435Sjeff		tdq_runq_rem(tdq, td);
2227177903Sjeff		tdq->tdq_lowpri = td->td_priority;
2228177435Sjeff		return (td);
2229109864Sjeff	}
2230177903Sjeff	tdq->tdq_lowpri = PRI_MAX_IDLE;
2231176735Sjeff	return (PCPU_GET(idlethread));
2232109864Sjeff}
2233109864Sjeff
2234171482Sjeff/*
2235171482Sjeff * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2236171482Sjeff * we always request it once we exit a critical section.
2237171482Sjeff */
2238171482Sjeffstatic inline void
2239171482Sjeffsched_setpreempt(struct thread *td)
2240166190Sjeff{
2241166190Sjeff	struct thread *ctd;
2242166190Sjeff	int cpri;
2243166190Sjeff	int pri;
2244166190Sjeff
2245177005Sjeff	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2246177005Sjeff
2247166190Sjeff	ctd = curthread;
2248166190Sjeff	pri = td->td_priority;
2249166190Sjeff	cpri = ctd->td_priority;
2250177005Sjeff	if (pri < cpri)
2251177005Sjeff		ctd->td_flags |= TDF_NEEDRESCHED;
2252166190Sjeff	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2253171482Sjeff		return;
2254177005Sjeff	if (!sched_shouldpreempt(pri, cpri, 0))
2255171482Sjeff		return;
2256171482Sjeff	ctd->td_owepreempt = 1;
2257166190Sjeff}
2258166190Sjeff
2259171482Sjeff/*
2260177009Sjeff * Add a thread to a thread queue.  Select the appropriate runq and add the
2261177009Sjeff * thread to it.  This is the internal function called when the tdq is
2262177009Sjeff * predetermined.
2263171482Sjeff */
2264109864Sjeffvoid
2265171482Sjefftdq_add(struct tdq *tdq, struct thread *td, int flags)
2266109864Sjeff{
2267109864Sjeff
2268171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2269166190Sjeff	KASSERT((td->td_inhibitors == 0),
2270166190Sjeff	    ("sched_add: trying to run inhibited thread"));
2271166190Sjeff	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2272166190Sjeff	    ("sched_add: bad thread state"));
2273172207Sjeff	KASSERT(td->td_flags & TDF_INMEM,
2274172207Sjeff	    ("sched_add: thread swapped out"));
2275171482Sjeff
2276171482Sjeff	if (td->td_priority < tdq->tdq_lowpri)
2277171482Sjeff		tdq->tdq_lowpri = td->td_priority;
2278177435Sjeff	tdq_runq_add(tdq, td, flags);
2279177435Sjeff	tdq_load_add(tdq, td);
2280171482Sjeff}
2281171482Sjeff
2282171482Sjeff/*
2283171482Sjeff * Select the target thread queue and add a thread to it.  Request
2284171482Sjeff * preemption or IPI a remote processor if required.
2285171482Sjeff */
2286171482Sjeffvoid
2287171482Sjeffsched_add(struct thread *td, int flags)
2288171482Sjeff{
2289171482Sjeff	struct tdq *tdq;
2290171482Sjeff#ifdef SMP
2291171482Sjeff	int cpu;
2292171482Sjeff#endif
2293187357Sjeff
2294187357Sjeff	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
2295187357Sjeff	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
2296187357Sjeff	    sched_tdname(curthread));
2297187357Sjeff	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
2298187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(td));
2299171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2300166108Sjeff	/*
2301171482Sjeff	 * Recalculate the priority before we select the target cpu or
2302171482Sjeff	 * run-queue.
2303166108Sjeff	 */
2304171482Sjeff	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2305171482Sjeff		sched_priority(td);
2306171482Sjeff#ifdef SMP
2307171482Sjeff	/*
2308171482Sjeff	 * Pick the destination cpu and if it isn't ours transfer to the
2309171482Sjeff	 * target cpu.
2310171482Sjeff	 */
2311177435Sjeff	cpu = sched_pickcpu(td, flags);
2312177435Sjeff	tdq = sched_setcpu(td, cpu, flags);
2313171482Sjeff	tdq_add(tdq, td, flags);
2314177009Sjeff	if (cpu != PCPU_GET(cpuid)) {
2315177435Sjeff		tdq_notify(tdq, td);
2316166108Sjeff		return;
2317166108Sjeff	}
2318171482Sjeff#else
2319171482Sjeff	tdq = TDQ_SELF();
2320171482Sjeff	TDQ_LOCK(tdq);
2321171482Sjeff	/*
2322171482Sjeff	 * Now that the thread is moving to the run-queue, set the lock
2323171482Sjeff	 * to the scheduler's lock.
2324171482Sjeff	 */
2325171482Sjeff	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2326171482Sjeff	tdq_add(tdq, td, flags);
2327166108Sjeff#endif
2328171482Sjeff	if (!(flags & SRQ_YIELDING))
2329171482Sjeff		sched_setpreempt(td);
2330109864Sjeff}
2331109864Sjeff
2332171482Sjeff/*
2333171482Sjeff * Remove a thread from a run-queue without running it.  This is used
2334171482Sjeff * when we're stealing a thread from a remote queue.  Otherwise all threads
2335171482Sjeff * exit by calling sched_exit_thread() and sched_throw() themselves.
2336171482Sjeff */
2337109864Sjeffvoid
2338121127Sjeffsched_rem(struct thread *td)
2339109864Sjeff{
2340164936Sjulian	struct tdq *tdq;
2341113357Sjeff
2342187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
2343187357Sjeff	    "prio:%d", td->td_priority);
2344177435Sjeff	tdq = TDQ_CPU(td->td_sched->ts_cpu);
2345171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2346171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2347166190Sjeff	KASSERT(TD_ON_RUNQ(td),
2348164936Sjulian	    ("sched_rem: thread not on run queue"));
2349177435Sjeff	tdq_runq_rem(tdq, td);
2350177435Sjeff	tdq_load_rem(tdq, td);
2351166190Sjeff	TD_SET_CAN_RUN(td);
2352176735Sjeff	if (td->td_priority == tdq->tdq_lowpri)
2353176735Sjeff		tdq_setlowpri(tdq, NULL);
2354109864Sjeff}
2355109864Sjeff
2356171482Sjeff/*
2357171482Sjeff * Fetch cpu utilization information.  Updates on demand.
2358171482Sjeff */
2359109864Sjefffixpt_t
2360121127Sjeffsched_pctcpu(struct thread *td)
2361109864Sjeff{
2362109864Sjeff	fixpt_t pctcpu;
2363164936Sjulian	struct td_sched *ts;
2364109864Sjeff
2365109864Sjeff	pctcpu = 0;
2366164936Sjulian	ts = td->td_sched;
2367164936Sjulian	if (ts == NULL)
2368121290Sjeff		return (0);
2369109864Sjeff
2370208787Sjhb	THREAD_LOCK_ASSERT(td, MA_OWNED);
2371164936Sjulian	if (ts->ts_ticks) {
2372109864Sjeff		int rtick;
2373109864Sjeff
2374165796Sjeff		sched_pctcpu_update(ts);
2375109864Sjeff		/* How many rtick per second ? */
2376165762Sjeff		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2377165762Sjeff		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2378109864Sjeff	}
2379109864Sjeff
2380109864Sjeff	return (pctcpu);
2381109864Sjeff}
2382109864Sjeff
2383176735Sjeff/*
2384176735Sjeff * Enforce affinity settings for a thread.  Called after adjustments to
2385176735Sjeff * cpumask.
2386176735Sjeff */
2387176729Sjeffvoid
2388176729Sjeffsched_affinity(struct thread *td)
2389176729Sjeff{
2390176735Sjeff#ifdef SMP
2391176735Sjeff	struct td_sched *ts;
2392176735Sjeff	int cpu;
2393176735Sjeff
2394176735Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2395176735Sjeff	ts = td->td_sched;
2396176735Sjeff	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2397176735Sjeff		return;
2398189787Sjeff	if (TD_ON_RUNQ(td)) {
2399189787Sjeff		sched_rem(td);
2400189787Sjeff		sched_add(td, SRQ_BORING);
2401189787Sjeff		return;
2402189787Sjeff	}
2403176735Sjeff	if (!TD_IS_RUNNING(td))
2404176735Sjeff		return;
2405176735Sjeff	td->td_flags |= TDF_NEEDRESCHED;
2406176735Sjeff	if (!THREAD_CAN_MIGRATE(td))
2407176735Sjeff		return;
2408176735Sjeff	/*
2409176735Sjeff	 * Assign the new cpu and force a switch before returning to
2410176735Sjeff	 * userspace.  If the target thread is not running locally send
2411176735Sjeff	 * an ipi to force the issue.
2412176735Sjeff	 */
2413176735Sjeff	cpu = ts->ts_cpu;
2414177435Sjeff	ts->ts_cpu = sched_pickcpu(td, 0);
2415176735Sjeff	if (cpu != PCPU_GET(cpuid))
2416176735Sjeff		ipi_selected(1 << cpu, IPI_PREEMPT);
2417176735Sjeff#endif
2418176729Sjeff}
2419176729Sjeff
2420171482Sjeff/*
2421171482Sjeff * Bind a thread to a target cpu.
2422171482Sjeff */
2423122038Sjeffvoid
2424122038Sjeffsched_bind(struct thread *td, int cpu)
2425122038Sjeff{
2426164936Sjulian	struct td_sched *ts;
2427122038Sjeff
2428171713Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2429208391Sjhb	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
2430164936Sjulian	ts = td->td_sched;
2431166137Sjeff	if (ts->ts_flags & TSF_BOUND)
2432166152Sjeff		sched_unbind(td);
2433164936Sjulian	ts->ts_flags |= TSF_BOUND;
2434166137Sjeff	sched_pin();
2435123433Sjeff	if (PCPU_GET(cpuid) == cpu)
2436122038Sjeff		return;
2437166137Sjeff	ts->ts_cpu = cpu;
2438122038Sjeff	/* When we return from mi_switch we'll be on the correct cpu. */
2439131527Sphk	mi_switch(SW_VOL, NULL);
2440122038Sjeff}
2441122038Sjeff
2442171482Sjeff/*
2443171482Sjeff * Release a bound thread.
2444171482Sjeff */
2445122038Sjeffvoid
2446122038Sjeffsched_unbind(struct thread *td)
2447122038Sjeff{
2448165762Sjeff	struct td_sched *ts;
2449165762Sjeff
2450170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2451208391Sjhb	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
2452165762Sjeff	ts = td->td_sched;
2453166137Sjeff	if ((ts->ts_flags & TSF_BOUND) == 0)
2454166137Sjeff		return;
2455165762Sjeff	ts->ts_flags &= ~TSF_BOUND;
2456165762Sjeff	sched_unpin();
2457122038Sjeff}
2458122038Sjeff
2459109864Sjeffint
2460145256Sjkoshysched_is_bound(struct thread *td)
2461145256Sjkoshy{
2462170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2463164936Sjulian	return (td->td_sched->ts_flags & TSF_BOUND);
2464145256Sjkoshy}
2465145256Sjkoshy
2466171482Sjeff/*
2467171482Sjeff * Basic yield call.
2468171482Sjeff */
2469159630Sdavidxuvoid
2470159630Sdavidxusched_relinquish(struct thread *td)
2471159630Sdavidxu{
2472170293Sjeff	thread_lock(td);
2473178272Sjeff	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
2474170293Sjeff	thread_unlock(td);
2475159630Sdavidxu}
2476159630Sdavidxu
2477171482Sjeff/*
2478171482Sjeff * Return the total system load.
2479171482Sjeff */
2480145256Sjkoshyint
2481125289Sjeffsched_load(void)
2482125289Sjeff{
2483125289Sjeff#ifdef SMP
2484125289Sjeff	int total;
2485125289Sjeff	int i;
2486125289Sjeff
2487125289Sjeff	total = 0;
2488176735Sjeff	for (i = 0; i <= mp_maxid; i++)
2489176735Sjeff		total += TDQ_CPU(i)->tdq_sysload;
2490125289Sjeff	return (total);
2491125289Sjeff#else
2492165620Sjeff	return (TDQ_SELF()->tdq_sysload);
2493125289Sjeff#endif
2494125289Sjeff}
2495125289Sjeff
2496125289Sjeffint
2497109864Sjeffsched_sizeof_proc(void)
2498109864Sjeff{
2499109864Sjeff	return (sizeof(struct proc));
2500109864Sjeff}
2501109864Sjeff
2502109864Sjeffint
2503109864Sjeffsched_sizeof_thread(void)
2504109864Sjeff{
2505109864Sjeff	return (sizeof(struct thread) + sizeof(struct td_sched));
2506109864Sjeff}
2507159570Sdavidxu
2508191676Sjeff#ifdef SMP
2509191676Sjeff#define	TDQ_IDLESPIN(tdq)						\
2510191676Sjeff    ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
2511191676Sjeff#else
2512191676Sjeff#define	TDQ_IDLESPIN(tdq)	1
2513191676Sjeff#endif
2514191676Sjeff
2515166190Sjeff/*
2516166190Sjeff * The actual idle process.
2517166190Sjeff */
2518166190Sjeffvoid
2519166190Sjeffsched_idletd(void *dummy)
2520166190Sjeff{
2521166190Sjeff	struct thread *td;
2522171482Sjeff	struct tdq *tdq;
2523178277Sjeff	int switchcnt;
2524178277Sjeff	int i;
2525166190Sjeff
2526191643Sjeff	mtx_assert(&Giant, MA_NOTOWNED);
2527166190Sjeff	td = curthread;
2528171482Sjeff	tdq = TDQ_SELF();
2529171482Sjeff	for (;;) {
2530171482Sjeff#ifdef SMP
2531178277Sjeff		if (tdq_idled(tdq) == 0)
2532178277Sjeff			continue;
2533171482Sjeff#endif
2534178277Sjeff		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2535178277Sjeff		/*
2536178277Sjeff		 * If we're switching very frequently, spin while checking
2537178277Sjeff		 * for load rather than entering a low power state that
2538191643Sjeff		 * may require an IPI.  However, don't do any busy
2539191643Sjeff		 * loops while on SMT machines as this simply steals
2540191643Sjeff		 * cycles from cores doing useful work.
2541178277Sjeff		 */
2542191676Sjeff		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
2543178277Sjeff			for (i = 0; i < sched_idlespins; i++) {
2544178277Sjeff				if (tdq->tdq_load)
2545178277Sjeff					break;
2546178277Sjeff				cpu_spinwait();
2547178277Sjeff			}
2548178277Sjeff		}
2549191643Sjeff		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2550191643Sjeff		if (tdq->tdq_load == 0)
2551191643Sjeff			cpu_idle(switchcnt > 1);
2552178277Sjeff		if (tdq->tdq_load) {
2553178277Sjeff			thread_lock(td);
2554178277Sjeff			mi_switch(SW_VOL | SWT_IDLE, NULL);
2555178277Sjeff			thread_unlock(td);
2556178277Sjeff		}
2557171482Sjeff	}
2558166190Sjeff}
2559166190Sjeff
2560170293Sjeff/*
2561170293Sjeff * A CPU is entering for the first time or a thread is exiting.
2562170293Sjeff */
2563170293Sjeffvoid
2564170293Sjeffsched_throw(struct thread *td)
2565170293Sjeff{
2566172411Sjeff	struct thread *newtd;
2567171482Sjeff	struct tdq *tdq;
2568171482Sjeff
2569171482Sjeff	tdq = TDQ_SELF();
2570170293Sjeff	if (td == NULL) {
2571171482Sjeff		/* Correct spinlock nesting and acquire the correct lock. */
2572171482Sjeff		TDQ_LOCK(tdq);
2573170293Sjeff		spinlock_exit();
2574170293Sjeff	} else {
2575171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2576177435Sjeff		tdq_load_rem(tdq, td);
2577174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2578170293Sjeff	}
2579170293Sjeff	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2580172411Sjeff	newtd = choosethread();
2581172411Sjeff	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2582170293Sjeff	PCPU_SET(switchtime, cpu_ticks());
2583170293Sjeff	PCPU_SET(switchticks, ticks);
2584172411Sjeff	cpu_throw(td, newtd);		/* doesn't return */
2585170293Sjeff}
2586170293Sjeff
2587171482Sjeff/*
2588171482Sjeff * This is called from fork_exit().  Just acquire the correct locks and
2589171482Sjeff * let fork do the rest of the work.
2590171482Sjeff */
2591170293Sjeffvoid
2592170600Sjeffsched_fork_exit(struct thread *td)
2593170293Sjeff{
2594171482Sjeff	struct td_sched *ts;
2595171482Sjeff	struct tdq *tdq;
2596171482Sjeff	int cpuid;
2597170293Sjeff
2598170293Sjeff	/*
2599170293Sjeff	 * Finish setting up thread glue so that it begins execution in a
2600171482Sjeff	 * non-nested critical section with the scheduler lock held.
2601170293Sjeff	 */
2602171482Sjeff	cpuid = PCPU_GET(cpuid);
2603171482Sjeff	tdq = TDQ_CPU(cpuid);
2604171482Sjeff	ts = td->td_sched;
2605171482Sjeff	if (TD_IS_IDLETHREAD(td))
2606171482Sjeff		td->td_lock = TDQ_LOCKPTR(tdq);
2607171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2608171482Sjeff	td->td_oncpu = cpuid;
2609172411Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2610174629Sjeff	lock_profile_obtain_lock_success(
2611174629Sjeff	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2612170293Sjeff}
2613170293Sjeff
2614187357Sjeff/*
2615187357Sjeff * Create on first use to catch odd startup conditons.
2616187357Sjeff */
2617187357Sjeffchar *
2618187357Sjeffsched_tdname(struct thread *td)
2619187357Sjeff{
2620187357Sjeff#ifdef KTR
2621187357Sjeff	struct td_sched *ts;
2622187357Sjeff
2623187357Sjeff	ts = td->td_sched;
2624187357Sjeff	if (ts->ts_name[0] == '\0')
2625187357Sjeff		snprintf(ts->ts_name, sizeof(ts->ts_name),
2626187357Sjeff		    "%s tid %d", td->td_name, td->td_tid);
2627187357Sjeff	return (ts->ts_name);
2628187357Sjeff#else
2629187357Sjeff	return (td->td_name);
2630187357Sjeff#endif
2631187357Sjeff}
2632187357Sjeff
2633184439Sivoras#ifdef SMP
2634184439Sivoras
2635184439Sivoras/*
2636184439Sivoras * Build the CPU topology dump string. Is recursively called to collect
2637184439Sivoras * the topology tree.
2638184439Sivoras */
2639184439Sivorasstatic int
2640184439Sivorassysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
2641184439Sivoras    int indent)
2642184439Sivoras{
2643184439Sivoras	int i, first;
2644184439Sivoras
2645184439Sivoras	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
2646184439Sivoras	    "", indent, cg->cg_level);
2647184439Sivoras	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"0x%x\">", indent, "",
2648184439Sivoras	    cg->cg_count, cg->cg_mask);
2649184439Sivoras	first = TRUE;
2650184439Sivoras	for (i = 0; i < MAXCPU; i++) {
2651184439Sivoras		if ((cg->cg_mask & (1 << i)) != 0) {
2652184439Sivoras			if (!first)
2653184439Sivoras				sbuf_printf(sb, ", ");
2654184439Sivoras			else
2655184439Sivoras				first = FALSE;
2656184439Sivoras			sbuf_printf(sb, "%d", i);
2657184439Sivoras		}
2658184439Sivoras	}
2659184439Sivoras	sbuf_printf(sb, "</cpu>\n");
2660184439Sivoras
2661184439Sivoras	sbuf_printf(sb, "%*s <flags>", indent, "");
2662184439Sivoras	if (cg->cg_flags != 0) {
2663184439Sivoras		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
2664186435Sivoras			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>\n");
2665191643Sjeff		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
2666186435Sivoras			sbuf_printf(sb, "<flag name=\"THREAD\">SMT group</flag>\n");
2667184439Sivoras	}
2668184439Sivoras	sbuf_printf(sb, "</flags>\n");
2669184439Sivoras
2670184439Sivoras	if (cg->cg_children > 0) {
2671184439Sivoras		sbuf_printf(sb, "%*s <children>\n", indent, "");
2672184439Sivoras		for (i = 0; i < cg->cg_children; i++)
2673184439Sivoras			sysctl_kern_sched_topology_spec_internal(sb,
2674184439Sivoras			    &cg->cg_child[i], indent+2);
2675184439Sivoras		sbuf_printf(sb, "%*s </children>\n", indent, "");
2676184439Sivoras	}
2677184439Sivoras	sbuf_printf(sb, "%*s</group>\n", indent, "");
2678184439Sivoras	return (0);
2679184439Sivoras}
2680184439Sivoras
2681184439Sivoras/*
2682184439Sivoras * Sysctl handler for retrieving topology dump. It's a wrapper for
2683184439Sivoras * the recursive sysctl_kern_smp_topology_spec_internal().
2684184439Sivoras */
2685184439Sivorasstatic int
2686184439Sivorassysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
2687184439Sivoras{
2688184439Sivoras	struct sbuf *topo;
2689184439Sivoras	int err;
2690184439Sivoras
2691184439Sivoras	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
2692184439Sivoras
2693184570Sivoras	topo = sbuf_new(NULL, NULL, 500, SBUF_AUTOEXTEND);
2694184439Sivoras	if (topo == NULL)
2695184439Sivoras		return (ENOMEM);
2696184439Sivoras
2697184439Sivoras	sbuf_printf(topo, "<groups>\n");
2698184439Sivoras	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
2699184439Sivoras	sbuf_printf(topo, "</groups>\n");
2700184439Sivoras
2701184439Sivoras	if (err == 0) {
2702184439Sivoras		sbuf_finish(topo);
2703184439Sivoras		err = SYSCTL_OUT(req, sbuf_data(topo), sbuf_len(topo));
2704184439Sivoras	}
2705184439Sivoras	sbuf_delete(topo);
2706184439Sivoras	return (err);
2707184439Sivoras}
2708184439Sivoras#endif
2709184439Sivoras
2710177435SjeffSYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2711171482SjeffSYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2712165762Sjeff    "Scheduler name");
2713171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2714171482Sjeff    "Slice size for timeshare threads");
2715171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2716171482Sjeff     "Interactivity score threshold");
2717171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2718171482Sjeff     0,"Min priority for preemption, lower priorities have greater precedence");
2719177085SjeffSYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost,
2720177085Sjeff     0,"Controls whether static kernel priorities are assigned to sleeping threads.");
2721178277SjeffSYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins,
2722178277Sjeff     0,"Number of times idle will spin waiting for new work.");
2723178277SjeffSYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW, &sched_idlespinthresh,
2724178277Sjeff     0,"Threshold before we will permit idle spinning.");
2725166108Sjeff#ifdef SMP
2726171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2727171482Sjeff    "Number of hz ticks to keep thread affinity for");
2728171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2729171482Sjeff    "Enables the long-term load balancer");
2730172409SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2731172409Sjeff    &balance_interval, 0,
2732172409Sjeff    "Average frequency in stathz ticks to run the long-term balancer");
2733171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2734171482Sjeff    "Steals work from another hyper-threaded core on idle");
2735171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2736171482Sjeff    "Attempts to steal work from other cores before idling");
2737171506SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2738171506Sjeff    "Minimum load on remote cpu before we'll steal");
2739184439Sivoras
2740184439Sivoras/* Retrieve SMP topology */
2741184439SivorasSYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
2742184439Sivoras    CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
2743184439Sivoras    "XML dump of detected CPU topology");
2744166108Sjeff#endif
2745165762Sjeff
2746172264Sjeff/* ps compat.  All cpu percentages from ULE are weighted. */
2747172293Sjeffstatic int ccpu = 0;
2748165762SjeffSYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2749