sched_ule.c revision 232454
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 232454 2012-03-03 11:50:48Z mav $");
40116182Sobrien
41147565Speter#include "opt_hwpmc_hooks.h"
42179297Sjb#include "opt_kdtrace.h"
43147565Speter#include "opt_sched.h"
44134649Sscottl
45109864Sjeff#include <sys/param.h>
46109864Sjeff#include <sys/systm.h>
47131929Smarcel#include <sys/kdb.h>
48109864Sjeff#include <sys/kernel.h>
49109864Sjeff#include <sys/ktr.h>
50109864Sjeff#include <sys/lock.h>
51109864Sjeff#include <sys/mutex.h>
52109864Sjeff#include <sys/proc.h>
53112966Sjeff#include <sys/resource.h>
54122038Sjeff#include <sys/resourcevar.h>
55109864Sjeff#include <sys/sched.h>
56109864Sjeff#include <sys/smp.h>
57109864Sjeff#include <sys/sx.h>
58109864Sjeff#include <sys/sysctl.h>
59109864Sjeff#include <sys/sysproto.h>
60139453Sjhb#include <sys/turnstile.h>
61161599Sdavidxu#include <sys/umtx.h>
62109864Sjeff#include <sys/vmmeter.h>
63176735Sjeff#include <sys/cpuset.h>
64184439Sivoras#include <sys/sbuf.h>
65109864Sjeff
66145256Sjkoshy#ifdef HWPMC_HOOKS
67145256Sjkoshy#include <sys/pmckern.h>
68145256Sjkoshy#endif
69145256Sjkoshy
70179297Sjb#ifdef KDTRACE_HOOKS
71179297Sjb#include <sys/dtrace_bsd.h>
72179297Sjbint				dtrace_vtime_active;
73179297Sjbdtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
74179297Sjb#endif
75179297Sjb
76109864Sjeff#include <machine/cpu.h>
77121790Sjeff#include <machine/smp.h>
78109864Sjeff
79226057Smarius#if defined(__powerpc__) && defined(E500)
80172345Sjeff#error "This architecture is not currently compatible with ULE"
81166190Sjeff#endif
82166190Sjeff
83171482Sjeff#define	KTR_ULE	0
84166137Sjeff
85187679Sjeff#define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
86187679Sjeff#define	TDQ_NAME_LEN	(sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
87224221Sattilio#define	TDQ_LOADNAME_LEN	(sizeof("CPU ") + sizeof(__XSTRING(MAXCPU)) - 1 + sizeof(" load"))
88187357Sjeff
89166137Sjeff/*
90171482Sjeff * Thread scheduler specific section.  All fields are protected
91171482Sjeff * by the thread lock.
92146954Sjeff */
93164936Sjulianstruct td_sched {
94171482Sjeff	struct runq	*ts_runq;	/* Run-queue we're queued on. */
95171482Sjeff	short		ts_flags;	/* TSF_* flags. */
96164936Sjulian	u_char		ts_cpu;		/* CPU that we have affinity for. */
97177009Sjeff	int		ts_rltick;	/* Real last tick, for affinity. */
98171482Sjeff	int		ts_slice;	/* Ticks of slice remaining. */
99171482Sjeff	u_int		ts_slptime;	/* Number of ticks we vol. slept */
100171482Sjeff	u_int		ts_runtime;	/* Number of ticks we were running */
101164936Sjulian	int		ts_ltick;	/* Last tick that we were running on */
102199764Sivoras	int		ts_incrtick;	/* Last tick that we incremented on */
103164936Sjulian	int		ts_ftick;	/* First tick that we were running on */
104164936Sjulian	int		ts_ticks;	/* Tick count */
105187357Sjeff#ifdef KTR
106187357Sjeff	char		ts_name[TS_NAME_LEN];
107187357Sjeff#endif
108134791Sjulian};
109164936Sjulian/* flags kept in ts_flags */
110166108Sjeff#define	TSF_BOUND	0x0001		/* Thread can not migrate. */
111166108Sjeff#define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
112121790Sjeff
113164936Sjulianstatic struct td_sched td_sched0;
114109864Sjeff
115176735Sjeff#define	THREAD_CAN_MIGRATE(td)	((td)->td_pinned == 0)
116176735Sjeff#define	THREAD_CAN_SCHED(td, cpu)	\
117176735Sjeff    CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
118176735Sjeff
119109864Sjeff/*
120217351Sjhb * Priority ranges used for interactive and non-interactive timeshare
121217410Sjhb * threads.  The timeshare priorities are split up into four ranges.
122217410Sjhb * The first range handles interactive threads.  The last three ranges
123217410Sjhb * (NHALF, x, and NHALF) handle non-interactive threads with the outer
124217410Sjhb * ranges supporting nice values.
125217351Sjhb */
126217410Sjhb#define	PRI_TIMESHARE_RANGE	(PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
127217410Sjhb#define	PRI_INTERACT_RANGE	((PRI_TIMESHARE_RANGE - SCHED_PRI_NRESV) / 2)
128228718Savg#define	PRI_BATCH_RANGE		(PRI_TIMESHARE_RANGE - PRI_INTERACT_RANGE)
129217410Sjhb
130217410Sjhb#define	PRI_MIN_INTERACT	PRI_MIN_TIMESHARE
131217410Sjhb#define	PRI_MAX_INTERACT	(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE - 1)
132217410Sjhb#define	PRI_MIN_BATCH		(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE)
133217351Sjhb#define	PRI_MAX_BATCH		PRI_MAX_TIMESHARE
134217351Sjhb
135217351Sjhb/*
136165762Sjeff * Cpu percentage computation macros and defines.
137111857Sjeff *
138165762Sjeff * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
139165762Sjeff * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
140165796Sjeff * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
141165762Sjeff * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
142165762Sjeff * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
143165762Sjeff * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
144165762Sjeff */
145165762Sjeff#define	SCHED_TICK_SECS		10
146165762Sjeff#define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
147165796Sjeff#define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
148165762Sjeff#define	SCHED_TICK_SHIFT	10
149165762Sjeff#define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
150165830Sjeff#define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
151165762Sjeff
152165762Sjeff/*
153165762Sjeff * These macros determine priorities for non-interactive threads.  They are
154165762Sjeff * assigned a priority based on their recent cpu utilization as expressed
155165762Sjeff * by the ratio of ticks to the tick total.  NHALF priorities at the start
156165762Sjeff * and end of the MIN to MAX timeshare range are only reachable with negative
157165762Sjeff * or positive nice respectively.
158165762Sjeff *
159165762Sjeff * PRI_RANGE:	Priority range for utilization dependent priorities.
160116642Sjeff * PRI_NRESV:	Number of nice values.
161165762Sjeff * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
162165762Sjeff * PRI_NICE:	Determines the part of the priority inherited from nice.
163109864Sjeff */
164165762Sjeff#define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
165121869Sjeff#define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
166217351Sjhb#define	SCHED_PRI_MIN		(PRI_MIN_BATCH + SCHED_PRI_NHALF)
167217351Sjhb#define	SCHED_PRI_MAX		(PRI_MAX_BATCH - SCHED_PRI_NHALF)
168217237Sjhb#define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN + 1)
169165762Sjeff#define	SCHED_PRI_TICKS(ts)						\
170165762Sjeff    (SCHED_TICK_HZ((ts)) /						\
171165827Sjeff    (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
172165762Sjeff#define	SCHED_PRI_NICE(nice)	(nice)
173109864Sjeff
174109864Sjeff/*
175165762Sjeff * These determine the interactivity of a process.  Interactivity differs from
176165762Sjeff * cpu utilization in that it expresses the voluntary time slept vs time ran
177165762Sjeff * while cpu utilization includes all time not running.  This more accurately
178165762Sjeff * models the intent of the thread.
179109864Sjeff *
180110645Sjeff * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
181110645Sjeff *		before throttling back.
182121868Sjeff * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
183116365Sjeff * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
184215102Sattilio * INTERACT_THRESH:	Threshold for placement on the current runq.
185109864Sjeff */
186165762Sjeff#define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
187165762Sjeff#define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
188116365Sjeff#define	SCHED_INTERACT_MAX	(100)
189116365Sjeff#define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
190121126Sjeff#define	SCHED_INTERACT_THRESH	(30)
191111857Sjeff
192109864Sjeff/*
193165762Sjeff * tickincr:		Converts a stathz tick into a hz domain scaled by
194165762Sjeff *			the shift factor.  Without the shift the error rate
195165762Sjeff *			due to rounding would be unacceptably high.
196165762Sjeff * realstathz:		stathz is sometimes 0 and run off of hz.
197165762Sjeff * sched_slice:		Runtime of each thread before rescheduling.
198171482Sjeff * preempt_thresh:	Priority threshold for preemption and remote IPIs.
199109864Sjeff */
200165762Sjeffstatic int sched_interact = SCHED_INTERACT_THRESH;
201165762Sjeffstatic int realstathz;
202165762Sjeffstatic int tickincr;
203177009Sjeffstatic int sched_slice = 1;
204172345Sjeff#ifdef PREEMPTION
205172345Sjeff#ifdef FULL_PREEMPTION
206172345Sjeffstatic int preempt_thresh = PRI_MAX_IDLE;
207172345Sjeff#else
208171482Sjeffstatic int preempt_thresh = PRI_MIN_KERN;
209172345Sjeff#endif
210172345Sjeff#else
211172345Sjeffstatic int preempt_thresh = 0;
212172345Sjeff#endif
213217351Sjhbstatic int static_boost = PRI_MIN_BATCH;
214178277Sjeffstatic int sched_idlespins = 10000;
215212541Smavstatic int sched_idlespinthresh = 16;
216109864Sjeff
217109864Sjeff/*
218171482Sjeff * tdq - per processor runqs and statistics.  All fields are protected by the
219171482Sjeff * tdq_lock.  The load and lowpri may be accessed without to avoid excess
220171482Sjeff * locking in sched_pickcpu();
221109864Sjeff */
222164936Sjulianstruct tdq {
223177009Sjeff	/* Ordered to improve efficiency of cpu_search() and switch(). */
224177009Sjeff	struct mtx	tdq_lock;		/* run queue lock. */
225176735Sjeff	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
226178277Sjeff	volatile int	tdq_load;		/* Aggregate load. */
227212416Smav	volatile int	tdq_cpu_idle;		/* cpu_idle() is active. */
228176735Sjeff	int		tdq_sysload;		/* For loadavg, !ITHD load. */
229177009Sjeff	int		tdq_transferable;	/* Transferable thread count. */
230178277Sjeff	short		tdq_switchcnt;		/* Switches this tick. */
231178277Sjeff	short		tdq_oldswitchcnt;	/* Switches last tick. */
232177009Sjeff	u_char		tdq_lowpri;		/* Lowest priority thread. */
233177009Sjeff	u_char		tdq_ipipending;		/* IPI pending. */
234166557Sjeff	u_char		tdq_idx;		/* Current insert index. */
235166557Sjeff	u_char		tdq_ridx;		/* Current removal index. */
236177009Sjeff	struct runq	tdq_realtime;		/* real-time run queue. */
237177009Sjeff	struct runq	tdq_timeshare;		/* timeshare run queue. */
238177009Sjeff	struct runq	tdq_idle;		/* Queue of IDLE threads. */
239187357Sjeff	char		tdq_name[TDQ_NAME_LEN];
240187357Sjeff#ifdef KTR
241187357Sjeff	char		tdq_loadname[TDQ_LOADNAME_LEN];
242187357Sjeff#endif
243171482Sjeff} __aligned(64);
244109864Sjeff
245178277Sjeff/* Idle thread states and config. */
246178277Sjeff#define	TDQ_RUNNING	1
247178277Sjeff#define	TDQ_IDLE	2
248166108Sjeff
249123433Sjeff#ifdef SMP
250184439Sivorasstruct cpu_group *cpu_top;		/* CPU topology */
251123433Sjeff
252176735Sjeff#define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
253176735Sjeff#define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
254166108Sjeff
255123433Sjeff/*
256166108Sjeff * Run-time tunables.
257166108Sjeff */
258171506Sjeffstatic int rebalance = 1;
259172409Sjeffstatic int balance_interval = 128;	/* Default set in sched_initticks(). */
260166108Sjeffstatic int affinity;
261171506Sjeffstatic int steal_idle = 1;
262171506Sjeffstatic int steal_thresh = 2;
263166108Sjeff
264166108Sjeff/*
265165620Sjeff * One thread queue per processor.
266109864Sjeff */
267164936Sjulianstatic struct tdq	tdq_cpu[MAXCPU];
268172409Sjeffstatic struct tdq	*balance_tdq;
269172409Sjeffstatic int balance_ticks;
270232207Smavstatic DPCPU_DEFINE(uint32_t, randomval);
271129982Sjeff
272164936Sjulian#define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
273164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu[(x)])
274171713Sjeff#define	TDQ_ID(x)	((int)((x) - tdq_cpu))
275123433Sjeff#else	/* !SMP */
276164936Sjulianstatic struct tdq	tdq_cpu;
277129982Sjeff
278170315Sjeff#define	TDQ_ID(x)	(0)
279164936Sjulian#define	TDQ_SELF()	(&tdq_cpu)
280164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu)
281110028Sjeff#endif
282109864Sjeff
283171482Sjeff#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
284171482Sjeff#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
285171482Sjeff#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
286171482Sjeff#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
287176735Sjeff#define	TDQ_LOCKPTR(t)		(&(t)->tdq_lock)
288171482Sjeff
289163709Sjbstatic void sched_priority(struct thread *);
290146954Sjeffstatic void sched_thread_priority(struct thread *, u_char);
291163709Sjbstatic int sched_interact_score(struct thread *);
292163709Sjbstatic void sched_interact_update(struct thread *);
293163709Sjbstatic void sched_interact_fork(struct thread *);
294164936Sjulianstatic void sched_pctcpu_update(struct td_sched *);
295109864Sjeff
296110267Sjeff/* Operations on per processor queues */
297177435Sjeffstatic struct thread *tdq_choose(struct tdq *);
298164936Sjulianstatic void tdq_setup(struct tdq *);
299177435Sjeffstatic void tdq_load_add(struct tdq *, struct thread *);
300177435Sjeffstatic void tdq_load_rem(struct tdq *, struct thread *);
301177435Sjeffstatic __inline void tdq_runq_add(struct tdq *, struct thread *, int);
302177435Sjeffstatic __inline void tdq_runq_rem(struct tdq *, struct thread *);
303177005Sjeffstatic inline int sched_shouldpreempt(int, int, int);
304164936Sjulianvoid tdq_print(int cpu);
305165762Sjeffstatic void runq_print(struct runq *rq);
306171482Sjeffstatic void tdq_add(struct tdq *, struct thread *, int);
307110267Sjeff#ifdef SMP
308176735Sjeffstatic int tdq_move(struct tdq *, struct tdq *);
309171482Sjeffstatic int tdq_idled(struct tdq *);
310177435Sjeffstatic void tdq_notify(struct tdq *, struct thread *);
311177435Sjeffstatic struct thread *tdq_steal(struct tdq *, int);
312177435Sjeffstatic struct thread *runq_steal(struct runq *, int);
313177435Sjeffstatic int sched_pickcpu(struct thread *, int);
314172409Sjeffstatic void sched_balance(void);
315176735Sjeffstatic int sched_balance_pair(struct tdq *, struct tdq *);
316177435Sjeffstatic inline struct tdq *sched_setcpu(struct thread *, int, int);
317171482Sjeffstatic inline void thread_unblock_switch(struct thread *, struct mtx *);
318171713Sjeffstatic struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
319184439Sivorasstatic int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
320184439Sivorasstatic int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
321184439Sivoras    struct cpu_group *cg, int indent);
322121790Sjeff#endif
323110028Sjeff
324165762Sjeffstatic void sched_setup(void *dummy);
325177253SrwatsonSYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
326165762Sjeff
327165762Sjeffstatic void sched_initticks(void *dummy);
328177253SrwatsonSYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
329177253Srwatson    NULL);
330165762Sjeff
331171482Sjeff/*
332171482Sjeff * Print the threads waiting on a run-queue.
333171482Sjeff */
334165762Sjeffstatic void
335165762Sjeffrunq_print(struct runq *rq)
336165762Sjeff{
337165762Sjeff	struct rqhead *rqh;
338177435Sjeff	struct thread *td;
339165762Sjeff	int pri;
340165762Sjeff	int j;
341165762Sjeff	int i;
342165762Sjeff
343165762Sjeff	for (i = 0; i < RQB_LEN; i++) {
344165762Sjeff		printf("\t\trunq bits %d 0x%zx\n",
345165762Sjeff		    i, rq->rq_status.rqb_bits[i]);
346165762Sjeff		for (j = 0; j < RQB_BPW; j++)
347165762Sjeff			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
348165762Sjeff				pri = j + (i << RQB_L2BPW);
349165762Sjeff				rqh = &rq->rq_queues[pri];
350177435Sjeff				TAILQ_FOREACH(td, rqh, td_runq) {
351165762Sjeff					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
352177435Sjeff					    td, td->td_name, td->td_priority,
353177435Sjeff					    td->td_rqindex, pri);
354165762Sjeff				}
355165762Sjeff			}
356165762Sjeff	}
357165762Sjeff}
358165762Sjeff
359171482Sjeff/*
360171482Sjeff * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
361171482Sjeff */
362113357Sjeffvoid
363164936Sjuliantdq_print(int cpu)
364110267Sjeff{
365164936Sjulian	struct tdq *tdq;
366112994Sjeff
367164936Sjulian	tdq = TDQ_CPU(cpu);
368112994Sjeff
369171713Sjeff	printf("tdq %d:\n", TDQ_ID(tdq));
370176735Sjeff	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
371176735Sjeff	printf("\tLock name:      %s\n", tdq->tdq_name);
372165620Sjeff	printf("\tload:           %d\n", tdq->tdq_load);
373178277Sjeff	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
374178277Sjeff	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
375171482Sjeff	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
376165766Sjeff	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
377178277Sjeff	printf("\tload transferable: %d\n", tdq->tdq_transferable);
378178277Sjeff	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
379165762Sjeff	printf("\trealtime runq:\n");
380165762Sjeff	runq_print(&tdq->tdq_realtime);
381165762Sjeff	printf("\ttimeshare runq:\n");
382165762Sjeff	runq_print(&tdq->tdq_timeshare);
383165762Sjeff	printf("\tidle runq:\n");
384165762Sjeff	runq_print(&tdq->tdq_idle);
385113357Sjeff}
386112994Sjeff
387177005Sjeffstatic inline int
388177005Sjeffsched_shouldpreempt(int pri, int cpri, int remote)
389177005Sjeff{
390177005Sjeff	/*
391177005Sjeff	 * If the new priority is not better than the current priority there is
392177005Sjeff	 * nothing to do.
393177005Sjeff	 */
394177005Sjeff	if (pri >= cpri)
395177005Sjeff		return (0);
396177005Sjeff	/*
397177005Sjeff	 * Always preempt idle.
398177005Sjeff	 */
399177005Sjeff	if (cpri >= PRI_MIN_IDLE)
400177005Sjeff		return (1);
401177005Sjeff	/*
402177005Sjeff	 * If preemption is disabled don't preempt others.
403177005Sjeff	 */
404177005Sjeff	if (preempt_thresh == 0)
405177005Sjeff		return (0);
406177005Sjeff	/*
407177005Sjeff	 * Preempt if we exceed the threshold.
408177005Sjeff	 */
409177005Sjeff	if (pri <= preempt_thresh)
410177005Sjeff		return (1);
411177005Sjeff	/*
412217351Sjhb	 * If we're interactive or better and there is non-interactive
413217351Sjhb	 * or worse running preempt only remote processors.
414177005Sjeff	 */
415217351Sjhb	if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
416177005Sjeff		return (1);
417177005Sjeff	return (0);
418177005Sjeff}
419177005Sjeff
420171482Sjeff/*
421171482Sjeff * Add a thread to the actual run-queue.  Keeps transferable counts up to
422171482Sjeff * date with what is actually on the run-queue.  Selects the correct
423171482Sjeff * queue position for timeshare threads.
424171482Sjeff */
425122744Sjeffstatic __inline void
426177435Sjefftdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
427122744Sjeff{
428177435Sjeff	struct td_sched *ts;
429177042Sjeff	u_char pri;
430177042Sjeff
431171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
432177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
433177009Sjeff
434177435Sjeff	pri = td->td_priority;
435177435Sjeff	ts = td->td_sched;
436177435Sjeff	TD_SET_RUNQ(td);
437177435Sjeff	if (THREAD_CAN_MIGRATE(td)) {
438165620Sjeff		tdq->tdq_transferable++;
439164936Sjulian		ts->ts_flags |= TSF_XFERABLE;
440123433Sjeff	}
441217351Sjhb	if (pri < PRI_MIN_BATCH) {
442177042Sjeff		ts->ts_runq = &tdq->tdq_realtime;
443217351Sjhb	} else if (pri <= PRI_MAX_BATCH) {
444177042Sjeff		ts->ts_runq = &tdq->tdq_timeshare;
445217351Sjhb		KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
446165762Sjeff			("Invalid priority %d on timeshare runq", pri));
447165762Sjeff		/*
448165762Sjeff		 * This queue contains only priorities between MIN and MAX
449165762Sjeff		 * realtime.  Use the whole queue to represent these values.
450165762Sjeff		 */
451171713Sjeff		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
452228718Savg			pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
453165762Sjeff			pri = (pri + tdq->tdq_idx) % RQ_NQS;
454165766Sjeff			/*
455165766Sjeff			 * This effectively shortens the queue by one so we
456165766Sjeff			 * can have a one slot difference between idx and
457165766Sjeff			 * ridx while we wait for threads to drain.
458165766Sjeff			 */
459165766Sjeff			if (tdq->tdq_ridx != tdq->tdq_idx &&
460165766Sjeff			    pri == tdq->tdq_ridx)
461167664Sjeff				pri = (unsigned char)(pri - 1) % RQ_NQS;
462165762Sjeff		} else
463165766Sjeff			pri = tdq->tdq_ridx;
464177435Sjeff		runq_add_pri(ts->ts_runq, td, pri, flags);
465177042Sjeff		return;
466165762Sjeff	} else
467177009Sjeff		ts->ts_runq = &tdq->tdq_idle;
468177435Sjeff	runq_add(ts->ts_runq, td, flags);
469177009Sjeff}
470177009Sjeff
471171482Sjeff/*
472171482Sjeff * Remove a thread from a run-queue.  This typically happens when a thread
473171482Sjeff * is selected to run.  Running threads are not on the queue and the
474171482Sjeff * transferable count does not reflect them.
475171482Sjeff */
476122744Sjeffstatic __inline void
477177435Sjefftdq_runq_rem(struct tdq *tdq, struct thread *td)
478122744Sjeff{
479177435Sjeff	struct td_sched *ts;
480177435Sjeff
481177435Sjeff	ts = td->td_sched;
482171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
483171482Sjeff	KASSERT(ts->ts_runq != NULL,
484177435Sjeff	    ("tdq_runq_remove: thread %p null ts_runq", td));
485164936Sjulian	if (ts->ts_flags & TSF_XFERABLE) {
486165620Sjeff		tdq->tdq_transferable--;
487164936Sjulian		ts->ts_flags &= ~TSF_XFERABLE;
488123433Sjeff	}
489165766Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
490165766Sjeff		if (tdq->tdq_idx != tdq->tdq_ridx)
491177435Sjeff			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
492165766Sjeff		else
493177435Sjeff			runq_remove_idx(ts->ts_runq, td, NULL);
494165766Sjeff	} else
495177435Sjeff		runq_remove(ts->ts_runq, td);
496122744Sjeff}
497122744Sjeff
498171482Sjeff/*
499171482Sjeff * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
500171482Sjeff * for this thread to the referenced thread queue.
501171482Sjeff */
502113357Sjeffstatic void
503177435Sjefftdq_load_add(struct tdq *tdq, struct thread *td)
504113357Sjeff{
505171482Sjeff
506171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
507177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
508177902Sjeff
509165620Sjeff	tdq->tdq_load++;
510198854Sattilio	if ((td->td_flags & TDF_NOLOAD) == 0)
511177902Sjeff		tdq->tdq_sysload++;
512187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
513110267Sjeff}
514113357Sjeff
515171482Sjeff/*
516171482Sjeff * Remove the load from a thread that is transitioning to a sleep state or
517171482Sjeff * exiting.
518171482Sjeff */
519112994Sjeffstatic void
520177435Sjefftdq_load_rem(struct tdq *tdq, struct thread *td)
521110267Sjeff{
522171482Sjeff
523177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
524171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
525171482Sjeff	KASSERT(tdq->tdq_load != 0,
526171713Sjeff	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
527177902Sjeff
528165620Sjeff	tdq->tdq_load--;
529198854Sattilio	if ((td->td_flags & TDF_NOLOAD) == 0)
530177902Sjeff		tdq->tdq_sysload--;
531187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
532110267Sjeff}
533110267Sjeff
534176735Sjeff/*
535176735Sjeff * Set lowpri to its exact value by searching the run-queue and
536176735Sjeff * evaluating curthread.  curthread may be passed as an optimization.
537176735Sjeff */
538176735Sjeffstatic void
539176735Sjefftdq_setlowpri(struct tdq *tdq, struct thread *ctd)
540176735Sjeff{
541176735Sjeff	struct thread *td;
542176735Sjeff
543176735Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
544176735Sjeff	if (ctd == NULL)
545176735Sjeff		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
546177435Sjeff	td = tdq_choose(tdq);
547177435Sjeff	if (td == NULL || td->td_priority > ctd->td_priority)
548176735Sjeff		tdq->tdq_lowpri = ctd->td_priority;
549176735Sjeff	else
550176735Sjeff		tdq->tdq_lowpri = td->td_priority;
551176735Sjeff}
552176735Sjeff
553113357Sjeff#ifdef SMP
554176735Sjeffstruct cpu_search {
555194779Sjeff	cpuset_t cs_mask;
556232207Smav	u_int	cs_prefer;
557232207Smav	int	cs_pri;		/* Min priority for low. */
558232207Smav	int	cs_limit;	/* Max load for low, min load for high. */
559232207Smav	int	cs_cpu;
560232207Smav	int	cs_load;
561176735Sjeff};
562176735Sjeff
563176735Sjeff#define	CPU_SEARCH_LOWEST	0x1
564176735Sjeff#define	CPU_SEARCH_HIGHEST	0x2
565176735Sjeff#define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
566176735Sjeff
567194779Sjeff#define	CPUSET_FOREACH(cpu, mask)				\
568194779Sjeff	for ((cpu) = 0; (cpu) <= mp_maxid; (cpu)++)		\
569222813Sattilio		if (CPU_ISSET(cpu, &mask))
570176735Sjeff
571232207Smavstatic __inline int cpu_search(const struct cpu_group *cg, struct cpu_search *low,
572176735Sjeff    struct cpu_search *high, const int match);
573232207Smavint cpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low);
574232207Smavint cpu_search_highest(const struct cpu_group *cg, struct cpu_search *high);
575232207Smavint cpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
576176735Sjeff    struct cpu_search *high);
577176735Sjeff
578116069Sjeff/*
579176735Sjeff * Search the tree of cpu_groups for the lowest or highest loaded cpu
580176735Sjeff * according to the match argument.  This routine actually compares the
581176735Sjeff * load on all paths through the tree and finds the least loaded cpu on
582176735Sjeff * the least loaded path, which may differ from the least loaded cpu in
583176735Sjeff * the system.  This balances work among caches and busses.
584116069Sjeff *
585176735Sjeff * This inline is instantiated in three forms below using constants for the
586176735Sjeff * match argument.  It is reduced to the minimum set for each case.  It is
587176735Sjeff * also recursive to the depth of the tree.
588116069Sjeff */
589177169Sjhbstatic __inline int
590232207Smavcpu_search(const struct cpu_group *cg, struct cpu_search *low,
591176735Sjeff    struct cpu_search *high, const int match)
592176735Sjeff{
593232207Smav	struct cpu_search lgroup;
594232207Smav	struct cpu_search hgroup;
595232207Smav	cpuset_t cpumask;
596232207Smav	struct cpu_group *child;
597232207Smav	struct tdq *tdq;
598232207Smav	int cpu, i, hload, lload, load, total, rnd;
599176735Sjeff
600176735Sjeff	total = 0;
601232207Smav	cpumask = cg->cg_mask;
602232207Smav	if (match & CPU_SEARCH_LOWEST) {
603232207Smav		lload = INT_MAX;
604232207Smav		low->cs_load = INT_MAX;
605232207Smav		lgroup = *low;
606232207Smav	}
607232207Smav	if (match & CPU_SEARCH_HIGHEST) {
608232207Smav		hload = -1;
609232207Smav		high->cs_load = -1;
610232207Smav		hgroup = *high;
611232207Smav	}
612176735Sjeff
613232207Smav	/* Iterate through the child CPU groups and then remaining CPUs. */
614232207Smav	for (i = 0, cpu = 0; i <= cg->cg_children; ) {
615232207Smav		if (i >= cg->cg_children) {
616232207Smav			while (cpu <= mp_maxid && !CPU_ISSET(cpu, &cpumask))
617232207Smav				cpu++;
618232207Smav			if (cpu > mp_maxid)
619232207Smav				break;
620232207Smav			child = NULL;
621232207Smav		} else
622176735Sjeff			child = &cg->cg_child[i];
623232207Smav
624232207Smav		if (child) {			/* Handle child CPU group. */
625232207Smav			CPU_NAND(&cpumask, &child->cg_mask);
626176735Sjeff			switch (match) {
627176735Sjeff			case CPU_SEARCH_LOWEST:
628176735Sjeff				load = cpu_search_lowest(child, &lgroup);
629176735Sjeff				break;
630176735Sjeff			case CPU_SEARCH_HIGHEST:
631176735Sjeff				load = cpu_search_highest(child, &hgroup);
632176735Sjeff				break;
633176735Sjeff			case CPU_SEARCH_BOTH:
634176735Sjeff				load = cpu_search_both(child, &lgroup, &hgroup);
635176735Sjeff				break;
636176735Sjeff			}
637232207Smav		} else {			/* Handle child CPU. */
638232207Smav			tdq = TDQ_CPU(cpu);
639232207Smav			load = tdq->tdq_load * 256;
640232207Smav			rnd = DPCPU_SET(randomval,
641232207Smav			    DPCPU_GET(randomval) * 69069 + 5) >> 26;
642232207Smav			if (match & CPU_SEARCH_LOWEST) {
643232207Smav				if (cpu == low->cs_prefer)
644232207Smav					load -= 64;
645232207Smav				/* If that CPU is allowed and get data. */
646232207Smav				if (CPU_ISSET(cpu, &lgroup.cs_mask) &&
647232207Smav				    tdq->tdq_lowpri > lgroup.cs_pri &&
648232207Smav				    tdq->tdq_load <= lgroup.cs_limit) {
649232207Smav					lgroup.cs_cpu = cpu;
650232207Smav					lgroup.cs_load = load - rnd;
651176735Sjeff				}
652232207Smav			}
653232207Smav			if (match & CPU_SEARCH_HIGHEST)
654232207Smav				if (CPU_ISSET(cpu, &hgroup.cs_mask) &&
655232207Smav				    tdq->tdq_load >= hgroup.cs_limit &&
656232207Smav				    tdq->tdq_transferable) {
657232207Smav					hgroup.cs_cpu = cpu;
658232207Smav					hgroup.cs_load = load - rnd;
659176735Sjeff				}
660176735Sjeff		}
661232207Smav		total += load;
662176735Sjeff
663232207Smav		/* We have info about child item. Compare it. */
664232207Smav		if (match & CPU_SEARCH_LOWEST) {
665232454Smav			if (lgroup.cs_load != INT_MAX &&
666232454Smav			    (load < lload ||
667232454Smav			     (load == lload && lgroup.cs_load < low->cs_load))) {
668232207Smav				lload = load;
669232207Smav				low->cs_cpu = lgroup.cs_cpu;
670232207Smav				low->cs_load = lgroup.cs_load;
671232207Smav			}
672232207Smav		}
673232207Smav		if (match & CPU_SEARCH_HIGHEST)
674232454Smav			if (hgroup.cs_load != -1 &&
675232454Smav			    (load > hload ||
676232454Smav			     (load == hload && hgroup.cs_load > high->cs_load))) {
677232207Smav				hload = load;
678232207Smav				high->cs_cpu = hgroup.cs_cpu;
679232207Smav				high->cs_load = hgroup.cs_load;
680232207Smav			}
681232207Smav		if (child)
682232207Smav			i++;
683232207Smav		else
684232207Smav			cpu++;
685176735Sjeff	}
686176735Sjeff	return (total);
687176735Sjeff}
688176735Sjeff
689176735Sjeff/*
690176735Sjeff * cpu_search instantiations must pass constants to maintain the inline
691176735Sjeff * optimization.
692176735Sjeff */
693176735Sjeffint
694232207Smavcpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low)
695176735Sjeff{
696176735Sjeff	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
697176735Sjeff}
698176735Sjeff
699176735Sjeffint
700232207Smavcpu_search_highest(const struct cpu_group *cg, struct cpu_search *high)
701176735Sjeff{
702176735Sjeff	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
703176735Sjeff}
704176735Sjeff
705176735Sjeffint
706232207Smavcpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
707176735Sjeff    struct cpu_search *high)
708176735Sjeff{
709176735Sjeff	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
710176735Sjeff}
711176735Sjeff
712176735Sjeff/*
713176735Sjeff * Find the cpu with the least load via the least loaded path that has a
714176735Sjeff * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
715176735Sjeff * acceptable.
716176735Sjeff */
717176735Sjeffstatic inline int
718232207Smavsched_lowest(const struct cpu_group *cg, cpuset_t mask, int pri, int maxload,
719232207Smav    int prefer)
720176735Sjeff{
721176735Sjeff	struct cpu_search low;
722176735Sjeff
723176735Sjeff	low.cs_cpu = -1;
724232207Smav	low.cs_prefer = prefer;
725176735Sjeff	low.cs_mask = mask;
726232207Smav	low.cs_pri = pri;
727232207Smav	low.cs_limit = maxload;
728176735Sjeff	cpu_search_lowest(cg, &low);
729176735Sjeff	return low.cs_cpu;
730176735Sjeff}
731176735Sjeff
732176735Sjeff/*
733176735Sjeff * Find the cpu with the highest load via the highest loaded path.
734176735Sjeff */
735176735Sjeffstatic inline int
736232207Smavsched_highest(const struct cpu_group *cg, cpuset_t mask, int minload)
737176735Sjeff{
738176735Sjeff	struct cpu_search high;
739176735Sjeff
740176735Sjeff	high.cs_cpu = -1;
741176735Sjeff	high.cs_mask = mask;
742176735Sjeff	high.cs_limit = minload;
743176735Sjeff	cpu_search_highest(cg, &high);
744176735Sjeff	return high.cs_cpu;
745176735Sjeff}
746176735Sjeff
747176735Sjeff/*
748176735Sjeff * Simultaneously find the highest and lowest loaded cpu reachable via
749176735Sjeff * cg.
750176735Sjeff */
751232207Smavstatic inline void
752232207Smavsched_both(const struct cpu_group *cg, cpuset_t mask, int *lowcpu, int *highcpu)
753176735Sjeff{
754176735Sjeff	struct cpu_search high;
755176735Sjeff	struct cpu_search low;
756176735Sjeff
757176735Sjeff	low.cs_cpu = -1;
758232207Smav	low.cs_prefer = -1;
759232207Smav	low.cs_pri = -1;
760232207Smav	low.cs_limit = INT_MAX;
761176735Sjeff	low.cs_mask = mask;
762176735Sjeff	high.cs_cpu = -1;
763176735Sjeff	high.cs_limit = -1;
764176735Sjeff	high.cs_mask = mask;
765176735Sjeff	cpu_search_both(cg, &low, &high);
766176735Sjeff	*lowcpu = low.cs_cpu;
767176735Sjeff	*highcpu = high.cs_cpu;
768176735Sjeff	return;
769176735Sjeff}
770176735Sjeff
771121790Sjeffstatic void
772176735Sjeffsched_balance_group(struct cpu_group *cg)
773116069Sjeff{
774232207Smav	cpuset_t hmask, lmask;
775232207Smav	int high, low, anylow;
776123487Sjeff
777232207Smav	CPU_FILL(&hmask);
778176735Sjeff	for (;;) {
779232207Smav		high = sched_highest(cg, hmask, 1);
780232207Smav		/* Stop if there is no more CPU with transferrable threads. */
781232207Smav		if (high == -1)
782176735Sjeff			break;
783232207Smav		CPU_CLR(high, &hmask);
784232207Smav		CPU_COPY(&hmask, &lmask);
785232207Smav		/* Stop if there is no more CPU left for low. */
786232207Smav		if (CPU_EMPTY(&lmask))
787176735Sjeff			break;
788232207Smav		anylow = 1;
789232207Smavnextlow:
790232207Smav		low = sched_lowest(cg, lmask, -1,
791232207Smav		    TDQ_CPU(high)->tdq_load - 1, high);
792232207Smav		/* Stop if we looked well and found no less loaded CPU. */
793232207Smav		if (anylow && low == -1)
794232207Smav			break;
795232207Smav		/* Go to next high if we found no less loaded CPU. */
796232207Smav		if (low == -1)
797232207Smav			continue;
798232207Smav		/* Transfer thread from high to low. */
799232207Smav		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low))) {
800232207Smav			/* CPU that got thread can no longer be a donor. */
801232207Smav			CPU_CLR(low, &hmask);
802232207Smav		} else {
803232207Smav			/*
804232207Smav			 * If failed, then there is no threads on high
805232207Smav			 * that can run on this low. Drop low from low
806232207Smav			 * mask and look for different one.
807232207Smav			 */
808232207Smav			CPU_CLR(low, &lmask);
809232207Smav			anylow = 0;
810232207Smav			goto nextlow;
811232207Smav		}
812123487Sjeff	}
813123487Sjeff}
814123487Sjeff
815123487Sjeffstatic void
816201148Sedsched_balance(void)
817123487Sjeff{
818172409Sjeff	struct tdq *tdq;
819123487Sjeff
820172409Sjeff	/*
821172409Sjeff	 * Select a random time between .5 * balance_interval and
822172409Sjeff	 * 1.5 * balance_interval.
823172409Sjeff	 */
824176735Sjeff	balance_ticks = max(balance_interval / 2, 1);
825176735Sjeff	balance_ticks += random() % balance_interval;
826171482Sjeff	if (smp_started == 0 || rebalance == 0)
827171482Sjeff		return;
828172409Sjeff	tdq = TDQ_SELF();
829172409Sjeff	TDQ_UNLOCK(tdq);
830176735Sjeff	sched_balance_group(cpu_top);
831172409Sjeff	TDQ_LOCK(tdq);
832123487Sjeff}
833123487Sjeff
834171482Sjeff/*
835171482Sjeff * Lock two thread queues using their address to maintain lock order.
836171482Sjeff */
837123487Sjeffstatic void
838171482Sjefftdq_lock_pair(struct tdq *one, struct tdq *two)
839171482Sjeff{
840171482Sjeff	if (one < two) {
841171482Sjeff		TDQ_LOCK(one);
842171482Sjeff		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
843171482Sjeff	} else {
844171482Sjeff		TDQ_LOCK(two);
845171482Sjeff		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
846171482Sjeff	}
847171482Sjeff}
848171482Sjeff
849171482Sjeff/*
850172409Sjeff * Unlock two thread queues.  Order is not important here.
851172409Sjeff */
852172409Sjeffstatic void
853172409Sjefftdq_unlock_pair(struct tdq *one, struct tdq *two)
854172409Sjeff{
855172409Sjeff	TDQ_UNLOCK(one);
856172409Sjeff	TDQ_UNLOCK(two);
857172409Sjeff}
858172409Sjeff
859172409Sjeff/*
860171482Sjeff * Transfer load between two imbalanced thread queues.
861171482Sjeff */
862176735Sjeffstatic int
863164936Sjuliansched_balance_pair(struct tdq *high, struct tdq *low)
864123487Sjeff{
865176735Sjeff	int moved;
866226057Smarius	int cpu;
867116069Sjeff
868171482Sjeff	tdq_lock_pair(high, low);
869176735Sjeff	moved = 0;
870116069Sjeff	/*
871122744Sjeff	 * Determine what the imbalance is and then adjust that to how many
872165620Sjeff	 * threads we actually have to give up (transferable).
873122744Sjeff	 */
874232207Smav	if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load &&
875232207Smav	    (moved = tdq_move(high, low)) > 0) {
876172293Sjeff		/*
877226057Smarius		 * In case the target isn't the current cpu IPI it to force a
878226057Smarius		 * reschedule with the new workload.
879172293Sjeff		 */
880226057Smarius		cpu = TDQ_ID(low);
881226057Smarius		sched_pin();
882226057Smarius		if (cpu != PCPU_GET(cpuid))
883226057Smarius			ipi_cpu(cpu, IPI_PREEMPT);
884226057Smarius		sched_unpin();
885171482Sjeff	}
886172409Sjeff	tdq_unlock_pair(high, low);
887176735Sjeff	return (moved);
888116069Sjeff}
889116069Sjeff
890171482Sjeff/*
891171482Sjeff * Move a thread from one thread queue to another.
892171482Sjeff */
893176735Sjeffstatic int
894171482Sjefftdq_move(struct tdq *from, struct tdq *to)
895116069Sjeff{
896171482Sjeff	struct td_sched *ts;
897171482Sjeff	struct thread *td;
898164936Sjulian	struct tdq *tdq;
899171482Sjeff	int cpu;
900116069Sjeff
901172409Sjeff	TDQ_LOCK_ASSERT(from, MA_OWNED);
902172409Sjeff	TDQ_LOCK_ASSERT(to, MA_OWNED);
903172409Sjeff
904164936Sjulian	tdq = from;
905171482Sjeff	cpu = TDQ_ID(to);
906177435Sjeff	td = tdq_steal(tdq, cpu);
907177435Sjeff	if (td == NULL)
908176735Sjeff		return (0);
909177435Sjeff	ts = td->td_sched;
910171482Sjeff	/*
911171482Sjeff	 * Although the run queue is locked the thread may be blocked.  Lock
912172409Sjeff	 * it to clear this and acquire the run-queue lock.
913171482Sjeff	 */
914171482Sjeff	thread_lock(td);
915172409Sjeff	/* Drop recursive lock on from acquired via thread_lock(). */
916171482Sjeff	TDQ_UNLOCK(from);
917171482Sjeff	sched_rem(td);
918166108Sjeff	ts->ts_cpu = cpu;
919171482Sjeff	td->td_lock = TDQ_LOCKPTR(to);
920171482Sjeff	tdq_add(to, td, SRQ_YIELDING);
921176735Sjeff	return (1);
922116069Sjeff}
923110267Sjeff
924171482Sjeff/*
925171482Sjeff * This tdq has idled.  Try to steal a thread from another cpu and switch
926171482Sjeff * to it.
927171482Sjeff */
928123433Sjeffstatic int
929164936Sjuliantdq_idled(struct tdq *tdq)
930121790Sjeff{
931176735Sjeff	struct cpu_group *cg;
932164936Sjulian	struct tdq *steal;
933194779Sjeff	cpuset_t mask;
934176735Sjeff	int thresh;
935171482Sjeff	int cpu;
936123433Sjeff
937172484Sjeff	if (smp_started == 0 || steal_idle == 0)
938172484Sjeff		return (1);
939194779Sjeff	CPU_FILL(&mask);
940194779Sjeff	CPU_CLR(PCPU_GET(cpuid), &mask);
941176735Sjeff	/* We don't want to be preempted while we're iterating. */
942171482Sjeff	spinlock_enter();
943176735Sjeff	for (cg = tdq->tdq_cg; cg != NULL; ) {
944191643Sjeff		if ((cg->cg_flags & CG_FLAG_THREAD) == 0)
945176735Sjeff			thresh = steal_thresh;
946176735Sjeff		else
947176735Sjeff			thresh = 1;
948176735Sjeff		cpu = sched_highest(cg, mask, thresh);
949176735Sjeff		if (cpu == -1) {
950176735Sjeff			cg = cg->cg_parent;
951176735Sjeff			continue;
952166108Sjeff		}
953176735Sjeff		steal = TDQ_CPU(cpu);
954194779Sjeff		CPU_CLR(cpu, &mask);
955176735Sjeff		tdq_lock_pair(tdq, steal);
956176735Sjeff		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
957176735Sjeff			tdq_unlock_pair(tdq, steal);
958176735Sjeff			continue;
959171482Sjeff		}
960176735Sjeff		/*
961176735Sjeff		 * If a thread was added while interrupts were disabled don't
962176735Sjeff		 * steal one here.  If we fail to acquire one due to affinity
963176735Sjeff		 * restrictions loop again with this cpu removed from the
964176735Sjeff		 * set.
965176735Sjeff		 */
966176735Sjeff		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
967176735Sjeff			tdq_unlock_pair(tdq, steal);
968176735Sjeff			continue;
969176735Sjeff		}
970176735Sjeff		spinlock_exit();
971176735Sjeff		TDQ_UNLOCK(steal);
972178272Sjeff		mi_switch(SW_VOL | SWT_IDLE, NULL);
973176735Sjeff		thread_unlock(curthread);
974176735Sjeff
975176735Sjeff		return (0);
976123433Sjeff	}
977171482Sjeff	spinlock_exit();
978123433Sjeff	return (1);
979121790Sjeff}
980121790Sjeff
981171482Sjeff/*
982171482Sjeff * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
983171482Sjeff */
984121790Sjeffstatic void
985177435Sjefftdq_notify(struct tdq *tdq, struct thread *td)
986121790Sjeff{
987185047Sjhb	struct thread *ctd;
988166247Sjeff	int pri;
989166108Sjeff	int cpu;
990121790Sjeff
991177005Sjeff	if (tdq->tdq_ipipending)
992177005Sjeff		return;
993177435Sjeff	cpu = td->td_sched->ts_cpu;
994177435Sjeff	pri = td->td_priority;
995185047Sjhb	ctd = pcpu_find(cpu)->pc_curthread;
996185047Sjhb	if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
997166137Sjeff		return;
998185047Sjhb	if (TD_IS_IDLETHREAD(ctd)) {
999178277Sjeff		/*
1000178471Sjeff		 * If the MD code has an idle wakeup routine try that before
1001178471Sjeff		 * falling back to IPI.
1002178471Sjeff		 */
1003212416Smav		if (!tdq->tdq_cpu_idle || cpu_idle_wakeup(cpu))
1004178471Sjeff			return;
1005178277Sjeff	}
1006177005Sjeff	tdq->tdq_ipipending = 1;
1007210939Sjhb	ipi_cpu(cpu, IPI_PREEMPT);
1008121790Sjeff}
1009121790Sjeff
1010171482Sjeff/*
1011171482Sjeff * Steals load from a timeshare queue.  Honors the rotating queue head
1012171482Sjeff * index.
1013171482Sjeff */
1014177435Sjeffstatic struct thread *
1015176735Sjeffrunq_steal_from(struct runq *rq, int cpu, u_char start)
1016171482Sjeff{
1017171482Sjeff	struct rqbits *rqb;
1018171482Sjeff	struct rqhead *rqh;
1019232207Smav	struct thread *td, *first;
1020171482Sjeff	int bit;
1021171482Sjeff	int pri;
1022171482Sjeff	int i;
1023171482Sjeff
1024171482Sjeff	rqb = &rq->rq_status;
1025171482Sjeff	bit = start & (RQB_BPW -1);
1026171482Sjeff	pri = 0;
1027232207Smav	first = NULL;
1028171482Sjeffagain:
1029171482Sjeff	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1030171482Sjeff		if (rqb->rqb_bits[i] == 0)
1031171482Sjeff			continue;
1032171482Sjeff		if (bit != 0) {
1033171482Sjeff			for (pri = bit; pri < RQB_BPW; pri++)
1034171482Sjeff				if (rqb->rqb_bits[i] & (1ul << pri))
1035171482Sjeff					break;
1036171482Sjeff			if (pri >= RQB_BPW)
1037171482Sjeff				continue;
1038171482Sjeff		} else
1039171482Sjeff			pri = RQB_FFS(rqb->rqb_bits[i]);
1040171482Sjeff		pri += (i << RQB_L2BPW);
1041171482Sjeff		rqh = &rq->rq_queues[pri];
1042177435Sjeff		TAILQ_FOREACH(td, rqh, td_runq) {
1043177435Sjeff			if (first && THREAD_CAN_MIGRATE(td) &&
1044177435Sjeff			    THREAD_CAN_SCHED(td, cpu))
1045177435Sjeff				return (td);
1046232207Smav			first = td;
1047171482Sjeff		}
1048171482Sjeff	}
1049171482Sjeff	if (start != 0) {
1050171482Sjeff		start = 0;
1051171482Sjeff		goto again;
1052171482Sjeff	}
1053171482Sjeff
1054232207Smav	if (first && THREAD_CAN_MIGRATE(first) &&
1055232207Smav	    THREAD_CAN_SCHED(first, cpu))
1056232207Smav		return (first);
1057171482Sjeff	return (NULL);
1058171482Sjeff}
1059171482Sjeff
1060171482Sjeff/*
1061171482Sjeff * Steals load from a standard linear queue.
1062171482Sjeff */
1063177435Sjeffstatic struct thread *
1064176735Sjeffrunq_steal(struct runq *rq, int cpu)
1065121790Sjeff{
1066121790Sjeff	struct rqhead *rqh;
1067121790Sjeff	struct rqbits *rqb;
1068177435Sjeff	struct thread *td;
1069121790Sjeff	int word;
1070121790Sjeff	int bit;
1071121790Sjeff
1072121790Sjeff	rqb = &rq->rq_status;
1073121790Sjeff	for (word = 0; word < RQB_LEN; word++) {
1074121790Sjeff		if (rqb->rqb_bits[word] == 0)
1075121790Sjeff			continue;
1076121790Sjeff		for (bit = 0; bit < RQB_BPW; bit++) {
1077123231Speter			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
1078121790Sjeff				continue;
1079121790Sjeff			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
1080177435Sjeff			TAILQ_FOREACH(td, rqh, td_runq)
1081177435Sjeff				if (THREAD_CAN_MIGRATE(td) &&
1082177435Sjeff				    THREAD_CAN_SCHED(td, cpu))
1083177435Sjeff					return (td);
1084121790Sjeff		}
1085121790Sjeff	}
1086121790Sjeff	return (NULL);
1087121790Sjeff}
1088121790Sjeff
1089171482Sjeff/*
1090171482Sjeff * Attempt to steal a thread in priority order from a thread queue.
1091171482Sjeff */
1092177435Sjeffstatic struct thread *
1093176735Sjefftdq_steal(struct tdq *tdq, int cpu)
1094121790Sjeff{
1095177435Sjeff	struct thread *td;
1096121790Sjeff
1097171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1098177435Sjeff	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
1099177435Sjeff		return (td);
1100177435Sjeff	if ((td = runq_steal_from(&tdq->tdq_timeshare,
1101177435Sjeff	    cpu, tdq->tdq_ridx)) != NULL)
1102177435Sjeff		return (td);
1103176735Sjeff	return (runq_steal(&tdq->tdq_idle, cpu));
1104121790Sjeff}
1105123433Sjeff
1106171482Sjeff/*
1107171482Sjeff * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
1108172409Sjeff * current lock and returns with the assigned queue locked.
1109171482Sjeff */
1110171482Sjeffstatic inline struct tdq *
1111177435Sjeffsched_setcpu(struct thread *td, int cpu, int flags)
1112123433Sjeff{
1113177435Sjeff
1114171482Sjeff	struct tdq *tdq;
1115123433Sjeff
1116177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1117171482Sjeff	tdq = TDQ_CPU(cpu);
1118177435Sjeff	td->td_sched->ts_cpu = cpu;
1119177435Sjeff	/*
1120177435Sjeff	 * If the lock matches just return the queue.
1121177435Sjeff	 */
1122171482Sjeff	if (td->td_lock == TDQ_LOCKPTR(tdq))
1123171482Sjeff		return (tdq);
1124171482Sjeff#ifdef notyet
1125123433Sjeff	/*
1126172293Sjeff	 * If the thread isn't running its lockptr is a
1127171482Sjeff	 * turnstile or a sleepqueue.  We can just lock_set without
1128171482Sjeff	 * blocking.
1129123685Sjeff	 */
1130171482Sjeff	if (TD_CAN_RUN(td)) {
1131171482Sjeff		TDQ_LOCK(tdq);
1132171482Sjeff		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1133171482Sjeff		return (tdq);
1134171482Sjeff	}
1135171482Sjeff#endif
1136166108Sjeff	/*
1137171482Sjeff	 * The hard case, migration, we need to block the thread first to
1138171482Sjeff	 * prevent order reversals with other cpus locks.
1139166108Sjeff	 */
1140202889Sattilio	spinlock_enter();
1141171482Sjeff	thread_lock_block(td);
1142171482Sjeff	TDQ_LOCK(tdq);
1143171713Sjeff	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1144202889Sattilio	spinlock_exit();
1145171482Sjeff	return (tdq);
1146166108Sjeff}
1147166108Sjeff
1148178272SjeffSCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
1149178272SjeffSCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
1150178272SjeffSCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
1151178272SjeffSCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
1152178272SjeffSCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
1153178272SjeffSCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
1154178272Sjeff
1155166108Sjeffstatic int
1156177435Sjeffsched_pickcpu(struct thread *td, int flags)
1157171482Sjeff{
1158232207Smav	struct cpu_group *cg, *ccg;
1159177435Sjeff	struct td_sched *ts;
1160171482Sjeff	struct tdq *tdq;
1161194779Sjeff	cpuset_t mask;
1162232207Smav	int cpu, pri, self;
1163166108Sjeff
1164176735Sjeff	self = PCPU_GET(cpuid);
1165177435Sjeff	ts = td->td_sched;
1166166108Sjeff	if (smp_started == 0)
1167166108Sjeff		return (self);
1168171506Sjeff	/*
1169171506Sjeff	 * Don't migrate a running thread from sched_switch().
1170171506Sjeff	 */
1171176735Sjeff	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1172176735Sjeff		return (ts->ts_cpu);
1173166108Sjeff	/*
1174176735Sjeff	 * Prefer to run interrupt threads on the processors that generate
1175176735Sjeff	 * the interrupt.
1176166108Sjeff	 */
1177232207Smav	pri = td->td_priority;
1178176735Sjeff	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1179178272Sjeff	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
1180178272Sjeff		SCHED_STAT_INC(pickcpu_intrbind);
1181176735Sjeff		ts->ts_cpu = self;
1182232207Smav		if (TDQ_CPU(self)->tdq_lowpri > pri) {
1183232207Smav			SCHED_STAT_INC(pickcpu_affinity);
1184232207Smav			return (ts->ts_cpu);
1185232207Smav		}
1186178272Sjeff	}
1187166108Sjeff	/*
1188176735Sjeff	 * If the thread can run on the last cpu and the affinity has not
1189176735Sjeff	 * expired or it is idle run it there.
1190166108Sjeff	 */
1191176735Sjeff	tdq = TDQ_CPU(ts->ts_cpu);
1192232207Smav	cg = tdq->tdq_cg;
1193232207Smav	if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
1194232207Smav	    tdq->tdq_lowpri >= PRI_MIN_IDLE &&
1195232207Smav	    SCHED_AFFINITY(ts, CG_SHARE_L2)) {
1196232207Smav		if (cg->cg_flags & CG_FLAG_THREAD) {
1197232207Smav			CPUSET_FOREACH(cpu, cg->cg_mask) {
1198232207Smav				if (TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE)
1199232207Smav					break;
1200232207Smav			}
1201232207Smav		} else
1202232207Smav			cpu = INT_MAX;
1203232207Smav		if (cpu > mp_maxid) {
1204178272Sjeff			SCHED_STAT_INC(pickcpu_idle_affinity);
1205176735Sjeff			return (ts->ts_cpu);
1206178272Sjeff		}
1207139334Sjeff	}
1208123433Sjeff	/*
1209232207Smav	 * Search for the last level cache CPU group in the tree.
1210232207Smav	 * Skip caches with expired affinity time and SMT groups.
1211232207Smav	 * Affinity to higher level caches will be handled less aggressively.
1212123433Sjeff	 */
1213232207Smav	for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
1214232207Smav		if (cg->cg_flags & CG_FLAG_THREAD)
1215232207Smav			continue;
1216232207Smav		if (!SCHED_AFFINITY(ts, cg->cg_level))
1217232207Smav			continue;
1218232207Smav		ccg = cg;
1219232207Smav	}
1220232207Smav	if (ccg != NULL)
1221232207Smav		cg = ccg;
1222176735Sjeff	cpu = -1;
1223232207Smav	/* Search the group for the less loaded idle CPU we can run now. */
1224194779Sjeff	mask = td->td_cpuset->cs_mask;
1225232207Smav	if (cg != NULL && cg != cpu_top &&
1226232207Smav	    CPU_CMP(&cg->cg_mask, &cpu_top->cg_mask) != 0)
1227232207Smav		cpu = sched_lowest(cg, mask, max(pri, PRI_MAX_TIMESHARE),
1228232207Smav		    INT_MAX, ts->ts_cpu);
1229232207Smav	/* Search globally for the less loaded CPU we can run now. */
1230176735Sjeff	if (cpu == -1)
1231232207Smav		cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu);
1232232207Smav	/* Search globally for the less loaded CPU. */
1233232207Smav	if (cpu == -1)
1234232207Smav		cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu);
1235232454Smav	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1236171506Sjeff	/*
1237176735Sjeff	 * Compare the lowest loaded cpu to current cpu.
1238171506Sjeff	 */
1239177005Sjeff	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
1240232207Smav	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE &&
1241232207Smav	    TDQ_CPU(self)->tdq_load <= TDQ_CPU(cpu)->tdq_load + 1) {
1242178272Sjeff		SCHED_STAT_INC(pickcpu_local);
1243177005Sjeff		cpu = self;
1244178272Sjeff	} else
1245178272Sjeff		SCHED_STAT_INC(pickcpu_lowest);
1246178272Sjeff	if (cpu != ts->ts_cpu)
1247178272Sjeff		SCHED_STAT_INC(pickcpu_migration);
1248171482Sjeff	return (cpu);
1249123433Sjeff}
1250176735Sjeff#endif
1251123433Sjeff
1252117326Sjeff/*
1253121790Sjeff * Pick the highest priority task we have and return it.
1254117326Sjeff */
1255177435Sjeffstatic struct thread *
1256164936Sjuliantdq_choose(struct tdq *tdq)
1257110267Sjeff{
1258177435Sjeff	struct thread *td;
1259110267Sjeff
1260171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1261177435Sjeff	td = runq_choose(&tdq->tdq_realtime);
1262177435Sjeff	if (td != NULL)
1263177435Sjeff		return (td);
1264177435Sjeff	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1265177435Sjeff	if (td != NULL) {
1266217351Sjhb		KASSERT(td->td_priority >= PRI_MIN_BATCH,
1267165762Sjeff		    ("tdq_choose: Invalid priority on timeshare queue %d",
1268177435Sjeff		    td->td_priority));
1269177435Sjeff		return (td);
1270165762Sjeff	}
1271177435Sjeff	td = runq_choose(&tdq->tdq_idle);
1272177435Sjeff	if (td != NULL) {
1273177435Sjeff		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1274165762Sjeff		    ("tdq_choose: Invalid priority on idle queue %d",
1275177435Sjeff		    td->td_priority));
1276177435Sjeff		return (td);
1277165762Sjeff	}
1278165762Sjeff
1279165762Sjeff	return (NULL);
1280110267Sjeff}
1281110267Sjeff
1282171482Sjeff/*
1283171482Sjeff * Initialize a thread queue.
1284171482Sjeff */
1285109864Sjeffstatic void
1286164936Sjuliantdq_setup(struct tdq *tdq)
1287110028Sjeff{
1288171482Sjeff
1289171713Sjeff	if (bootverbose)
1290171713Sjeff		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1291165762Sjeff	runq_init(&tdq->tdq_realtime);
1292165762Sjeff	runq_init(&tdq->tdq_timeshare);
1293165620Sjeff	runq_init(&tdq->tdq_idle);
1294176735Sjeff	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1295176735Sjeff	    "sched lock %d", (int)TDQ_ID(tdq));
1296176735Sjeff	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1297176735Sjeff	    MTX_SPIN | MTX_RECURSE);
1298187357Sjeff#ifdef KTR
1299187357Sjeff	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
1300187357Sjeff	    "CPU %d load", (int)TDQ_ID(tdq));
1301187357Sjeff#endif
1302110028Sjeff}
1303110028Sjeff
1304171713Sjeff#ifdef SMP
1305110028Sjeffstatic void
1306171713Sjeffsched_setup_smp(void)
1307171713Sjeff{
1308171713Sjeff	struct tdq *tdq;
1309171713Sjeff	int i;
1310171713Sjeff
1311176735Sjeff	cpu_top = smp_topo();
1312209059Sjhb	CPU_FOREACH(i) {
1313176735Sjeff		tdq = TDQ_CPU(i);
1314171713Sjeff		tdq_setup(tdq);
1315176735Sjeff		tdq->tdq_cg = smp_topo_find(cpu_top, i);
1316176735Sjeff		if (tdq->tdq_cg == NULL)
1317176735Sjeff			panic("Can't find cpu group for %d\n", i);
1318123433Sjeff	}
1319176735Sjeff	balance_tdq = TDQ_SELF();
1320176735Sjeff	sched_balance();
1321171713Sjeff}
1322171713Sjeff#endif
1323171713Sjeff
1324171713Sjeff/*
1325171713Sjeff * Setup the thread queues and initialize the topology based on MD
1326171713Sjeff * information.
1327171713Sjeff */
1328171713Sjeffstatic void
1329171713Sjeffsched_setup(void *dummy)
1330171713Sjeff{
1331171713Sjeff	struct tdq *tdq;
1332171713Sjeff
1333171713Sjeff	tdq = TDQ_SELF();
1334171713Sjeff#ifdef SMP
1335176734Sjeff	sched_setup_smp();
1336117237Sjeff#else
1337171713Sjeff	tdq_setup(tdq);
1338116069Sjeff#endif
1339171482Sjeff	/*
1340171482Sjeff	 * To avoid divide-by-zero, we set realstathz a dummy value
1341171482Sjeff	 * in case which sched_clock() called before sched_initticks().
1342171482Sjeff	 */
1343171482Sjeff	realstathz = hz;
1344171482Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1345171482Sjeff	tickincr = 1 << SCHED_TICK_SHIFT;
1346171482Sjeff
1347171482Sjeff	/* Add thread0's load since it's running. */
1348171482Sjeff	TDQ_LOCK(tdq);
1349171713Sjeff	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1350177435Sjeff	tdq_load_add(tdq, &thread0);
1351176735Sjeff	tdq->tdq_lowpri = thread0.td_priority;
1352171482Sjeff	TDQ_UNLOCK(tdq);
1353109864Sjeff}
1354109864Sjeff
1355171482Sjeff/*
1356171482Sjeff * This routine determines the tickincr after stathz and hz are setup.
1357171482Sjeff */
1358153533Sdavidxu/* ARGSUSED */
1359153533Sdavidxustatic void
1360153533Sdavidxusched_initticks(void *dummy)
1361153533Sdavidxu{
1362171482Sjeff	int incr;
1363171482Sjeff
1364153533Sdavidxu	realstathz = stathz ? stathz : hz;
1365166229Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1366153533Sdavidxu
1367153533Sdavidxu	/*
1368165762Sjeff	 * tickincr is shifted out by 10 to avoid rounding errors due to
1369165766Sjeff	 * hz not being evenly divisible by stathz on all platforms.
1370153533Sdavidxu	 */
1371171482Sjeff	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1372165762Sjeff	/*
1373165762Sjeff	 * This does not work for values of stathz that are more than
1374165762Sjeff	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1375165762Sjeff	 */
1376171482Sjeff	if (incr == 0)
1377171482Sjeff		incr = 1;
1378171482Sjeff	tickincr = incr;
1379166108Sjeff#ifdef SMP
1380171899Sjeff	/*
1381172409Sjeff	 * Set the default balance interval now that we know
1382172409Sjeff	 * what realstathz is.
1383172409Sjeff	 */
1384172409Sjeff	balance_interval = realstathz;
1385172409Sjeff	/*
1386189787Sjeff	 * Set steal thresh to roughly log2(mp_ncpu) but no greater than 4.
1387189787Sjeff	 * This prevents excess thrashing on large machines and excess idle
1388189787Sjeff	 * on smaller machines.
1389171899Sjeff	 */
1390189787Sjeff	steal_thresh = min(fls(mp_ncpus) - 1, 3);
1391166108Sjeff	affinity = SCHED_AFFINITY_DEFAULT;
1392166108Sjeff#endif
1393153533Sdavidxu}
1394153533Sdavidxu
1395153533Sdavidxu
1396109864Sjeff/*
1397171482Sjeff * This is the core of the interactivity algorithm.  Determines a score based
1398171482Sjeff * on past behavior.  It is the ratio of sleep time to run time scaled to
1399171482Sjeff * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1400171482Sjeff * differs from the cpu usage because it does not account for time spent
1401171482Sjeff * waiting on a run-queue.  Would be prettier if we had floating point.
1402171482Sjeff */
1403171482Sjeffstatic int
1404171482Sjeffsched_interact_score(struct thread *td)
1405171482Sjeff{
1406171482Sjeff	struct td_sched *ts;
1407171482Sjeff	int div;
1408171482Sjeff
1409171482Sjeff	ts = td->td_sched;
1410171482Sjeff	/*
1411171482Sjeff	 * The score is only needed if this is likely to be an interactive
1412171482Sjeff	 * task.  Don't go through the expense of computing it if there's
1413171482Sjeff	 * no chance.
1414171482Sjeff	 */
1415171482Sjeff	if (sched_interact <= SCHED_INTERACT_HALF &&
1416171482Sjeff		ts->ts_runtime >= ts->ts_slptime)
1417171482Sjeff			return (SCHED_INTERACT_HALF);
1418171482Sjeff
1419171482Sjeff	if (ts->ts_runtime > ts->ts_slptime) {
1420171482Sjeff		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1421171482Sjeff		return (SCHED_INTERACT_HALF +
1422171482Sjeff		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1423171482Sjeff	}
1424171482Sjeff	if (ts->ts_slptime > ts->ts_runtime) {
1425171482Sjeff		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1426171482Sjeff		return (ts->ts_runtime / div);
1427171482Sjeff	}
1428171482Sjeff	/* runtime == slptime */
1429171482Sjeff	if (ts->ts_runtime)
1430171482Sjeff		return (SCHED_INTERACT_HALF);
1431171482Sjeff
1432171482Sjeff	/*
1433171482Sjeff	 * This can happen if slptime and runtime are 0.
1434171482Sjeff	 */
1435171482Sjeff	return (0);
1436171482Sjeff
1437171482Sjeff}
1438171482Sjeff
1439171482Sjeff/*
1440109864Sjeff * Scale the scheduling priority according to the "interactivity" of this
1441109864Sjeff * process.
1442109864Sjeff */
1443113357Sjeffstatic void
1444163709Sjbsched_priority(struct thread *td)
1445109864Sjeff{
1446165762Sjeff	int score;
1447109864Sjeff	int pri;
1448109864Sjeff
1449217291Sjhb	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
1450113357Sjeff		return;
1451112966Sjeff	/*
1452165762Sjeff	 * If the score is interactive we place the thread in the realtime
1453165762Sjeff	 * queue with a priority that is less than kernel and interrupt
1454165762Sjeff	 * priorities.  These threads are not subject to nice restrictions.
1455112966Sjeff	 *
1456171482Sjeff	 * Scores greater than this are placed on the normal timeshare queue
1457165762Sjeff	 * where the priority is partially decided by the most recent cpu
1458165762Sjeff	 * utilization and the rest is decided by nice value.
1459172293Sjeff	 *
1460172293Sjeff	 * The nice value of the process has a linear effect on the calculated
1461172293Sjeff	 * score.  Negative nice values make it easier for a thread to be
1462172293Sjeff	 * considered interactive.
1463112966Sjeff	 */
1464198126Sjhb	score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1465165762Sjeff	if (score < sched_interact) {
1466217351Sjhb		pri = PRI_MIN_INTERACT;
1467217351Sjhb		pri += ((PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) /
1468217237Sjhb		    sched_interact) * score;
1469217351Sjhb		KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
1470166208Sjeff		    ("sched_priority: invalid interactive priority %d score %d",
1471166208Sjeff		    pri, score));
1472165762Sjeff	} else {
1473165762Sjeff		pri = SCHED_PRI_MIN;
1474165762Sjeff		if (td->td_sched->ts_ticks)
1475228960Sjhb			pri += min(SCHED_PRI_TICKS(td->td_sched),
1476228960Sjhb			    SCHED_PRI_RANGE);
1477165762Sjeff		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1478217351Sjhb		KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
1479171482Sjeff		    ("sched_priority: invalid priority %d: nice %d, "
1480171482Sjeff		    "ticks %d ftick %d ltick %d tick pri %d",
1481171482Sjeff		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1482171482Sjeff		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1483171482Sjeff		    SCHED_PRI_TICKS(td->td_sched)));
1484165762Sjeff	}
1485165762Sjeff	sched_user_prio(td, pri);
1486112966Sjeff
1487112966Sjeff	return;
1488109864Sjeff}
1489109864Sjeff
1490121868Sjeff/*
1491121868Sjeff * This routine enforces a maximum limit on the amount of scheduling history
1492171482Sjeff * kept.  It is called after either the slptime or runtime is adjusted.  This
1493171482Sjeff * function is ugly due to integer math.
1494121868Sjeff */
1495116463Sjeffstatic void
1496163709Sjbsched_interact_update(struct thread *td)
1497116463Sjeff{
1498165819Sjeff	struct td_sched *ts;
1499166208Sjeff	u_int sum;
1500121605Sjeff
1501165819Sjeff	ts = td->td_sched;
1502171482Sjeff	sum = ts->ts_runtime + ts->ts_slptime;
1503121868Sjeff	if (sum < SCHED_SLP_RUN_MAX)
1504121868Sjeff		return;
1505121868Sjeff	/*
1506165819Sjeff	 * This only happens from two places:
1507165819Sjeff	 * 1) We have added an unusual amount of run time from fork_exit.
1508165819Sjeff	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1509165819Sjeff	 */
1510165819Sjeff	if (sum > SCHED_SLP_RUN_MAX * 2) {
1511171482Sjeff		if (ts->ts_runtime > ts->ts_slptime) {
1512171482Sjeff			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1513171482Sjeff			ts->ts_slptime = 1;
1514165819Sjeff		} else {
1515171482Sjeff			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1516171482Sjeff			ts->ts_runtime = 1;
1517165819Sjeff		}
1518165819Sjeff		return;
1519165819Sjeff	}
1520165819Sjeff	/*
1521121868Sjeff	 * If we have exceeded by more than 1/5th then the algorithm below
1522121868Sjeff	 * will not bring us back into range.  Dividing by two here forces
1523133427Sjeff	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1524121868Sjeff	 */
1525127850Sjeff	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1526171482Sjeff		ts->ts_runtime /= 2;
1527171482Sjeff		ts->ts_slptime /= 2;
1528121868Sjeff		return;
1529116463Sjeff	}
1530171482Sjeff	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1531171482Sjeff	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1532116463Sjeff}
1533116463Sjeff
1534171482Sjeff/*
1535171482Sjeff * Scale back the interactivity history when a child thread is created.  The
1536171482Sjeff * history is inherited from the parent but the thread may behave totally
1537171482Sjeff * differently.  For example, a shell spawning a compiler process.  We want
1538171482Sjeff * to learn that the compiler is behaving badly very quickly.
1539171482Sjeff */
1540121868Sjeffstatic void
1541163709Sjbsched_interact_fork(struct thread *td)
1542121868Sjeff{
1543121868Sjeff	int ratio;
1544121868Sjeff	int sum;
1545121868Sjeff
1546171482Sjeff	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1547121868Sjeff	if (sum > SCHED_SLP_RUN_FORK) {
1548121868Sjeff		ratio = sum / SCHED_SLP_RUN_FORK;
1549171482Sjeff		td->td_sched->ts_runtime /= ratio;
1550171482Sjeff		td->td_sched->ts_slptime /= ratio;
1551121868Sjeff	}
1552121868Sjeff}
1553121868Sjeff
1554113357Sjeff/*
1555171482Sjeff * Called from proc0_init() to setup the scheduler fields.
1556134791Sjulian */
1557134791Sjulianvoid
1558134791Sjulianschedinit(void)
1559134791Sjulian{
1560165762Sjeff
1561134791Sjulian	/*
1562134791Sjulian	 * Set up the scheduler specific parts of proc0.
1563134791Sjulian	 */
1564136167Sjulian	proc0.p_sched = NULL; /* XXX */
1565164936Sjulian	thread0.td_sched = &td_sched0;
1566165762Sjeff	td_sched0.ts_ltick = ticks;
1567165796Sjeff	td_sched0.ts_ftick = ticks;
1568177009Sjeff	td_sched0.ts_slice = sched_slice;
1569134791Sjulian}
1570134791Sjulian
1571134791Sjulian/*
1572113357Sjeff * This is only somewhat accurate since given many processes of the same
1573113357Sjeff * priority they will switch when their slices run out, which will be
1574165762Sjeff * at most sched_slice stathz ticks.
1575113357Sjeff */
1576109864Sjeffint
1577109864Sjeffsched_rr_interval(void)
1578109864Sjeff{
1579165762Sjeff
1580165762Sjeff	/* Convert sched_slice to hz */
1581165762Sjeff	return (hz/(realstathz/sched_slice));
1582109864Sjeff}
1583109864Sjeff
1584171482Sjeff/*
1585171482Sjeff * Update the percent cpu tracking information when it is requested or
1586171482Sjeff * the total history exceeds the maximum.  We keep a sliding history of
1587171482Sjeff * tick counts that slowly decays.  This is less precise than the 4BSD
1588171482Sjeff * mechanism since it happens with less regular and frequent events.
1589171482Sjeff */
1590121790Sjeffstatic void
1591164936Sjuliansched_pctcpu_update(struct td_sched *ts)
1592109864Sjeff{
1593165762Sjeff
1594165762Sjeff	if (ts->ts_ticks == 0)
1595165762Sjeff		return;
1596165796Sjeff	if (ticks - (hz / 10) < ts->ts_ltick &&
1597165796Sjeff	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1598165796Sjeff		return;
1599109864Sjeff	/*
1600109864Sjeff	 * Adjust counters and watermark for pctcpu calc.
1601116365Sjeff	 */
1602165762Sjeff	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1603164936Sjulian		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1604165762Sjeff			    SCHED_TICK_TARG;
1605165762Sjeff	else
1606164936Sjulian		ts->ts_ticks = 0;
1607164936Sjulian	ts->ts_ltick = ticks;
1608165762Sjeff	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1609109864Sjeff}
1610109864Sjeff
1611171482Sjeff/*
1612171482Sjeff * Adjust the priority of a thread.  Move it to the appropriate run-queue
1613171482Sjeff * if necessary.  This is the back-end for several priority related
1614171482Sjeff * functions.
1615171482Sjeff */
1616165762Sjeffstatic void
1617139453Sjhbsched_thread_priority(struct thread *td, u_char prio)
1618109864Sjeff{
1619164936Sjulian	struct td_sched *ts;
1620177009Sjeff	struct tdq *tdq;
1621177009Sjeff	int oldpri;
1622109864Sjeff
1623187357Sjeff	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
1624187357Sjeff	    "prio:%d", td->td_priority, "new prio:%d", prio,
1625187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(curthread));
1626187357Sjeff	if (td != curthread && prio > td->td_priority) {
1627187357Sjeff		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
1628187357Sjeff		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
1629187357Sjeff		    prio, KTR_ATTR_LINKED, sched_tdname(td));
1630187357Sjeff	}
1631164936Sjulian	ts = td->td_sched;
1632170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1633139453Sjhb	if (td->td_priority == prio)
1634139453Sjhb		return;
1635177376Sjeff	/*
1636177376Sjeff	 * If the priority has been elevated due to priority
1637177376Sjeff	 * propagation, we may have to move ourselves to a new
1638177376Sjeff	 * queue.  This could be optimized to not re-add in some
1639177376Sjeff	 * cases.
1640177376Sjeff	 */
1641165766Sjeff	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1642165762Sjeff		sched_rem(td);
1643165762Sjeff		td->td_priority = prio;
1644171482Sjeff		sched_add(td, SRQ_BORROWING);
1645177009Sjeff		return;
1646177009Sjeff	}
1647177376Sjeff	/*
1648177376Sjeff	 * If the thread is currently running we may have to adjust the lowpri
1649177376Sjeff	 * information so other cpus are aware of our current priority.
1650177376Sjeff	 */
1651177009Sjeff	if (TD_IS_RUNNING(td)) {
1652177376Sjeff		tdq = TDQ_CPU(ts->ts_cpu);
1653177376Sjeff		oldpri = td->td_priority;
1654177376Sjeff		td->td_priority = prio;
1655176735Sjeff		if (prio < tdq->tdq_lowpri)
1656171482Sjeff			tdq->tdq_lowpri = prio;
1657176735Sjeff		else if (tdq->tdq_lowpri == oldpri)
1658176735Sjeff			tdq_setlowpri(tdq, td);
1659177376Sjeff		return;
1660177009Sjeff	}
1661177376Sjeff	td->td_priority = prio;
1662109864Sjeff}
1663109864Sjeff
1664139453Sjhb/*
1665139453Sjhb * Update a thread's priority when it is lent another thread's
1666139453Sjhb * priority.
1667139453Sjhb */
1668109864Sjeffvoid
1669139453Sjhbsched_lend_prio(struct thread *td, u_char prio)
1670139453Sjhb{
1671139453Sjhb
1672139453Sjhb	td->td_flags |= TDF_BORROWING;
1673139453Sjhb	sched_thread_priority(td, prio);
1674139453Sjhb}
1675139453Sjhb
1676139453Sjhb/*
1677139453Sjhb * Restore a thread's priority when priority propagation is
1678139453Sjhb * over.  The prio argument is the minimum priority the thread
1679139453Sjhb * needs to have to satisfy other possible priority lending
1680139453Sjhb * requests.  If the thread's regular priority is less
1681139453Sjhb * important than prio, the thread will keep a priority boost
1682139453Sjhb * of prio.
1683139453Sjhb */
1684139453Sjhbvoid
1685139453Sjhbsched_unlend_prio(struct thread *td, u_char prio)
1686139453Sjhb{
1687139453Sjhb	u_char base_pri;
1688139453Sjhb
1689139453Sjhb	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1690139453Sjhb	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1691163709Sjb		base_pri = td->td_user_pri;
1692139453Sjhb	else
1693139453Sjhb		base_pri = td->td_base_pri;
1694139453Sjhb	if (prio >= base_pri) {
1695139455Sjhb		td->td_flags &= ~TDF_BORROWING;
1696139453Sjhb		sched_thread_priority(td, base_pri);
1697139453Sjhb	} else
1698139453Sjhb		sched_lend_prio(td, prio);
1699139453Sjhb}
1700139453Sjhb
1701171482Sjeff/*
1702171482Sjeff * Standard entry for setting the priority to an absolute value.
1703171482Sjeff */
1704139453Sjhbvoid
1705139453Sjhbsched_prio(struct thread *td, u_char prio)
1706139453Sjhb{
1707139453Sjhb	u_char oldprio;
1708139453Sjhb
1709139453Sjhb	/* First, update the base priority. */
1710139453Sjhb	td->td_base_pri = prio;
1711139453Sjhb
1712139453Sjhb	/*
1713139455Sjhb	 * If the thread is borrowing another thread's priority, don't
1714139453Sjhb	 * ever lower the priority.
1715139453Sjhb	 */
1716139453Sjhb	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1717139453Sjhb		return;
1718139453Sjhb
1719139453Sjhb	/* Change the real priority. */
1720139453Sjhb	oldprio = td->td_priority;
1721139453Sjhb	sched_thread_priority(td, prio);
1722139453Sjhb
1723139453Sjhb	/*
1724139453Sjhb	 * If the thread is on a turnstile, then let the turnstile update
1725139453Sjhb	 * its state.
1726139453Sjhb	 */
1727139453Sjhb	if (TD_ON_LOCK(td) && oldprio != prio)
1728139453Sjhb		turnstile_adjust(td, oldprio);
1729139453Sjhb}
1730139455Sjhb
1731171482Sjeff/*
1732171482Sjeff * Set the base user priority, does not effect current running priority.
1733171482Sjeff */
1734139453Sjhbvoid
1735163709Sjbsched_user_prio(struct thread *td, u_char prio)
1736161599Sdavidxu{
1737161599Sdavidxu
1738163709Sjb	td->td_base_user_pri = prio;
1739216313Sdavidxu	if (td->td_lend_user_pri <= prio)
1740216313Sdavidxu		return;
1741163709Sjb	td->td_user_pri = prio;
1742161599Sdavidxu}
1743161599Sdavidxu
1744161599Sdavidxuvoid
1745161599Sdavidxusched_lend_user_prio(struct thread *td, u_char prio)
1746161599Sdavidxu{
1747161599Sdavidxu
1748174536Sdavidxu	THREAD_LOCK_ASSERT(td, MA_OWNED);
1749216313Sdavidxu	td->td_lend_user_pri = prio;
1750216791Sdavidxu	td->td_user_pri = min(prio, td->td_base_user_pri);
1751216791Sdavidxu	if (td->td_priority > td->td_user_pri)
1752216791Sdavidxu		sched_prio(td, td->td_user_pri);
1753216791Sdavidxu	else if (td->td_priority != td->td_user_pri)
1754216791Sdavidxu		td->td_flags |= TDF_NEEDRESCHED;
1755161599Sdavidxu}
1756161599Sdavidxu
1757171482Sjeff/*
1758171713Sjeff * Handle migration from sched_switch().  This happens only for
1759171713Sjeff * cpu binding.
1760171713Sjeff */
1761171713Sjeffstatic struct mtx *
1762171713Sjeffsched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1763171713Sjeff{
1764171713Sjeff	struct tdq *tdn;
1765171713Sjeff
1766171713Sjeff	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1767171713Sjeff#ifdef SMP
1768177435Sjeff	tdq_load_rem(tdq, td);
1769171713Sjeff	/*
1770171713Sjeff	 * Do the lock dance required to avoid LOR.  We grab an extra
1771171713Sjeff	 * spinlock nesting to prevent preemption while we're
1772171713Sjeff	 * not holding either run-queue lock.
1773171713Sjeff	 */
1774171713Sjeff	spinlock_enter();
1775202889Sattilio	thread_lock_block(td);	/* This releases the lock on tdq. */
1776197223Sattilio
1777197223Sattilio	/*
1778197223Sattilio	 * Acquire both run-queue locks before placing the thread on the new
1779197223Sattilio	 * run-queue to avoid deadlocks created by placing a thread with a
1780197223Sattilio	 * blocked lock on the run-queue of a remote processor.  The deadlock
1781197223Sattilio	 * occurs when a third processor attempts to lock the two queues in
1782197223Sattilio	 * question while the target processor is spinning with its own
1783197223Sattilio	 * run-queue lock held while waiting for the blocked lock to clear.
1784197223Sattilio	 */
1785197223Sattilio	tdq_lock_pair(tdn, tdq);
1786171713Sjeff	tdq_add(tdn, td, flags);
1787177435Sjeff	tdq_notify(tdn, td);
1788197223Sattilio	TDQ_UNLOCK(tdn);
1789171713Sjeff	spinlock_exit();
1790171713Sjeff#endif
1791171713Sjeff	return (TDQ_LOCKPTR(tdn));
1792171713Sjeff}
1793171713Sjeff
1794171713Sjeff/*
1795202889Sattilio * Variadic version of thread_lock_unblock() that does not assume td_lock
1796202889Sattilio * is blocked.
1797171482Sjeff */
1798171482Sjeffstatic inline void
1799171482Sjeffthread_unblock_switch(struct thread *td, struct mtx *mtx)
1800171482Sjeff{
1801171482Sjeff	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1802171482Sjeff	    (uintptr_t)mtx);
1803171482Sjeff}
1804171482Sjeff
1805171482Sjeff/*
1806171482Sjeff * Switch threads.  This function has to handle threads coming in while
1807171482Sjeff * blocked for some reason, running, or idle.  It also must deal with
1808171482Sjeff * migrating a thread from one queue to another as running threads may
1809171482Sjeff * be assigned elsewhere via binding.
1810171482Sjeff */
1811161599Sdavidxuvoid
1812135051Sjuliansched_switch(struct thread *td, struct thread *newtd, int flags)
1813109864Sjeff{
1814165627Sjeff	struct tdq *tdq;
1815164936Sjulian	struct td_sched *ts;
1816171482Sjeff	struct mtx *mtx;
1817171713Sjeff	int srqflag;
1818171482Sjeff	int cpuid;
1819109864Sjeff
1820170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1821177376Sjeff	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
1822109864Sjeff
1823171482Sjeff	cpuid = PCPU_GET(cpuid);
1824171482Sjeff	tdq = TDQ_CPU(cpuid);
1825164936Sjulian	ts = td->td_sched;
1826171713Sjeff	mtx = td->td_lock;
1827171482Sjeff	ts->ts_rltick = ticks;
1828133555Sjeff	td->td_lastcpu = td->td_oncpu;
1829113339Sjulian	td->td_oncpu = NOCPU;
1830220198Sfabient	if (!(flags & SW_PREEMPT))
1831220198Sfabient		td->td_flags &= ~TDF_NEEDRESCHED;
1832144777Sups	td->td_owepreempt = 0;
1833178277Sjeff	tdq->tdq_switchcnt++;
1834123434Sjeff	/*
1835171482Sjeff	 * The lock pointer in an idle thread should never change.  Reset it
1836171482Sjeff	 * to CAN_RUN as well.
1837123434Sjeff	 */
1838167327Sjulian	if (TD_IS_IDLETHREAD(td)) {
1839171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1840139334Sjeff		TD_SET_CAN_RUN(td);
1841170293Sjeff	} else if (TD_IS_RUNNING(td)) {
1842171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1843171713Sjeff		srqflag = (flags & SW_PREEMPT) ?
1844170293Sjeff		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1845171713Sjeff		    SRQ_OURSELF|SRQ_YIELDING;
1846212153Smdf#ifdef SMP
1847212115Smdf		if (THREAD_CAN_MIGRATE(td) && !THREAD_CAN_SCHED(td, ts->ts_cpu))
1848212115Smdf			ts->ts_cpu = sched_pickcpu(td, 0);
1849212153Smdf#endif
1850171713Sjeff		if (ts->ts_cpu == cpuid)
1851177435Sjeff			tdq_runq_add(tdq, td, srqflag);
1852212115Smdf		else {
1853212115Smdf			KASSERT(THREAD_CAN_MIGRATE(td) ||
1854212115Smdf			    (ts->ts_flags & TSF_BOUND) != 0,
1855212115Smdf			    ("Thread %p shouldn't migrate", td));
1856171713Sjeff			mtx = sched_switch_migrate(tdq, td, srqflag);
1857212115Smdf		}
1858171482Sjeff	} else {
1859171482Sjeff		/* This thread must be going to sleep. */
1860171482Sjeff		TDQ_LOCK(tdq);
1861202889Sattilio		mtx = thread_lock_block(td);
1862177435Sjeff		tdq_load_rem(tdq, td);
1863171482Sjeff	}
1864171482Sjeff	/*
1865171482Sjeff	 * We enter here with the thread blocked and assigned to the
1866171482Sjeff	 * appropriate cpu run-queue or sleep-queue and with the current
1867171482Sjeff	 * thread-queue locked.
1868171482Sjeff	 */
1869171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1870171482Sjeff	newtd = choosethread();
1871171482Sjeff	/*
1872171482Sjeff	 * Call the MD code to switch contexts if necessary.
1873171482Sjeff	 */
1874145256Sjkoshy	if (td != newtd) {
1875145256Sjkoshy#ifdef	HWPMC_HOOKS
1876145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1877145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1878145256Sjkoshy#endif
1879174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1880172411Sjeff		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1881179297Sjb
1882179297Sjb#ifdef KDTRACE_HOOKS
1883179297Sjb		/*
1884179297Sjb		 * If DTrace has set the active vtime enum to anything
1885179297Sjb		 * other than INACTIVE (0), then it should have set the
1886179297Sjb		 * function to call.
1887179297Sjb		 */
1888179297Sjb		if (dtrace_vtime_active)
1889179297Sjb			(*dtrace_vtime_switch_func)(newtd);
1890179297Sjb#endif
1891179297Sjb
1892171482Sjeff		cpu_switch(td, newtd, mtx);
1893171482Sjeff		/*
1894171482Sjeff		 * We may return from cpu_switch on a different cpu.  However,
1895171482Sjeff		 * we always return with td_lock pointing to the current cpu's
1896171482Sjeff		 * run queue lock.
1897171482Sjeff		 */
1898171482Sjeff		cpuid = PCPU_GET(cpuid);
1899171482Sjeff		tdq = TDQ_CPU(cpuid);
1900174629Sjeff		lock_profile_obtain_lock_success(
1901174629Sjeff		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1902145256Sjkoshy#ifdef	HWPMC_HOOKS
1903145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1904145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1905145256Sjkoshy#endif
1906171482Sjeff	} else
1907171482Sjeff		thread_unblock_switch(td, mtx);
1908171482Sjeff	/*
1909171482Sjeff	 * Assert that all went well and return.
1910171482Sjeff	 */
1911171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1912171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1913171482Sjeff	td->td_oncpu = cpuid;
1914109864Sjeff}
1915109864Sjeff
1916171482Sjeff/*
1917171482Sjeff * Adjust thread priorities as a result of a nice request.
1918171482Sjeff */
1919109864Sjeffvoid
1920130551Sjuliansched_nice(struct proc *p, int nice)
1921109864Sjeff{
1922109864Sjeff	struct thread *td;
1923109864Sjeff
1924130551Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
1925165762Sjeff
1926130551Sjulian	p->p_nice = nice;
1927163709Sjb	FOREACH_THREAD_IN_PROC(p, td) {
1928170293Sjeff		thread_lock(td);
1929163709Sjb		sched_priority(td);
1930165762Sjeff		sched_prio(td, td->td_base_user_pri);
1931170293Sjeff		thread_unlock(td);
1932130551Sjulian	}
1933109864Sjeff}
1934109864Sjeff
1935171482Sjeff/*
1936171482Sjeff * Record the sleep time for the interactivity scorer.
1937171482Sjeff */
1938109864Sjeffvoid
1939177085Sjeffsched_sleep(struct thread *td, int prio)
1940109864Sjeff{
1941165762Sjeff
1942170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1943109864Sjeff
1944172264Sjeff	td->td_slptick = ticks;
1945201347Skib	if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
1946177085Sjeff		td->td_flags |= TDF_CANSWAP;
1947217410Sjhb	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
1948217410Sjhb		return;
1949177903Sjeff	if (static_boost == 1 && prio)
1950177085Sjeff		sched_prio(td, prio);
1951177903Sjeff	else if (static_boost && td->td_priority > static_boost)
1952177903Sjeff		sched_prio(td, static_boost);
1953109864Sjeff}
1954109864Sjeff
1955171482Sjeff/*
1956171482Sjeff * Schedule a thread to resume execution and record how long it voluntarily
1957171482Sjeff * slept.  We also update the pctcpu, interactivity, and priority.
1958171482Sjeff */
1959109864Sjeffvoid
1960109864Sjeffsched_wakeup(struct thread *td)
1961109864Sjeff{
1962166229Sjeff	struct td_sched *ts;
1963171482Sjeff	int slptick;
1964165762Sjeff
1965170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1966166229Sjeff	ts = td->td_sched;
1967177085Sjeff	td->td_flags &= ~TDF_CANSWAP;
1968109864Sjeff	/*
1969165762Sjeff	 * If we slept for more than a tick update our interactivity and
1970165762Sjeff	 * priority.
1971109864Sjeff	 */
1972172264Sjeff	slptick = td->td_slptick;
1973172264Sjeff	td->td_slptick = 0;
1974171482Sjeff	if (slptick && slptick != ticks) {
1975166208Sjeff		u_int hzticks;
1976109864Sjeff
1977171482Sjeff		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1978171482Sjeff		ts->ts_slptime += hzticks;
1979165819Sjeff		sched_interact_update(td);
1980166229Sjeff		sched_pctcpu_update(ts);
1981109864Sjeff	}
1982166229Sjeff	/* Reset the slice value after we sleep. */
1983166229Sjeff	ts->ts_slice = sched_slice;
1984166190Sjeff	sched_add(td, SRQ_BORING);
1985109864Sjeff}
1986109864Sjeff
1987109864Sjeff/*
1988109864Sjeff * Penalize the parent for creating a new child and initialize the child's
1989109864Sjeff * priority.
1990109864Sjeff */
1991109864Sjeffvoid
1992163709Sjbsched_fork(struct thread *td, struct thread *child)
1993109864Sjeff{
1994170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1995164936Sjulian	sched_fork_thread(td, child);
1996165762Sjeff	/*
1997165762Sjeff	 * Penalize the parent and child for forking.
1998165762Sjeff	 */
1999165762Sjeff	sched_interact_fork(child);
2000165762Sjeff	sched_priority(child);
2001171482Sjeff	td->td_sched->ts_runtime += tickincr;
2002165762Sjeff	sched_interact_update(td);
2003165762Sjeff	sched_priority(td);
2004164936Sjulian}
2005109864Sjeff
2006171482Sjeff/*
2007171482Sjeff * Fork a new thread, may be within the same process.
2008171482Sjeff */
2009164936Sjulianvoid
2010164936Sjuliansched_fork_thread(struct thread *td, struct thread *child)
2011164936Sjulian{
2012164936Sjulian	struct td_sched *ts;
2013164936Sjulian	struct td_sched *ts2;
2014164936Sjulian
2015177426Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2016165762Sjeff	/*
2017165762Sjeff	 * Initialize child.
2018165762Sjeff	 */
2019177426Sjeff	ts = td->td_sched;
2020177426Sjeff	ts2 = child->td_sched;
2021171482Sjeff	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
2022176735Sjeff	child->td_cpuset = cpuset_ref(td->td_cpuset);
2023164936Sjulian	ts2->ts_cpu = ts->ts_cpu;
2024177426Sjeff	ts2->ts_flags = 0;
2025165762Sjeff	/*
2026217078Sjhb	 * Grab our parents cpu estimation information.
2027165762Sjeff	 */
2028164936Sjulian	ts2->ts_ticks = ts->ts_ticks;
2029164936Sjulian	ts2->ts_ltick = ts->ts_ltick;
2030199764Sivoras	ts2->ts_incrtick = ts->ts_incrtick;
2031164936Sjulian	ts2->ts_ftick = ts->ts_ftick;
2032165762Sjeff	/*
2033217078Sjhb	 * Do not inherit any borrowed priority from the parent.
2034217078Sjhb	 */
2035217078Sjhb	child->td_priority = child->td_base_pri;
2036217078Sjhb	/*
2037165762Sjeff	 * And update interactivity score.
2038165762Sjeff	 */
2039171482Sjeff	ts2->ts_slptime = ts->ts_slptime;
2040171482Sjeff	ts2->ts_runtime = ts->ts_runtime;
2041165762Sjeff	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
2042187357Sjeff#ifdef KTR
2043187357Sjeff	bzero(ts2->ts_name, sizeof(ts2->ts_name));
2044187357Sjeff#endif
2045113357Sjeff}
2046113357Sjeff
2047171482Sjeff/*
2048171482Sjeff * Adjust the priority class of a thread.
2049171482Sjeff */
2050113357Sjeffvoid
2051163709Sjbsched_class(struct thread *td, int class)
2052113357Sjeff{
2053113357Sjeff
2054170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2055163709Sjb	if (td->td_pri_class == class)
2056113357Sjeff		return;
2057163709Sjb	td->td_pri_class = class;
2058109864Sjeff}
2059109864Sjeff
2060109864Sjeff/*
2061109864Sjeff * Return some of the child's priority and interactivity to the parent.
2062109864Sjeff */
2063109864Sjeffvoid
2064164939Sjuliansched_exit(struct proc *p, struct thread *child)
2065109864Sjeff{
2066165762Sjeff	struct thread *td;
2067113372Sjeff
2068187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2069225199Sdelphij	    "prio:%d", child->td_priority);
2070177368Sjeff	PROC_LOCK_ASSERT(p, MA_OWNED);
2071165762Sjeff	td = FIRST_THREAD_IN_PROC(p);
2072165762Sjeff	sched_exit_thread(td, child);
2073113372Sjeff}
2074113372Sjeff
2075171482Sjeff/*
2076171482Sjeff * Penalize another thread for the time spent on this one.  This helps to
2077171482Sjeff * worsen the priority and interactivity of processes which schedule batch
2078171482Sjeff * jobs such as make.  This has little effect on the make process itself but
2079171482Sjeff * causes new processes spawned by it to receive worse scores immediately.
2080171482Sjeff */
2081113372Sjeffvoid
2082164939Sjuliansched_exit_thread(struct thread *td, struct thread *child)
2083164936Sjulian{
2084165762Sjeff
2085187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2086225199Sdelphij	    "prio:%d", child->td_priority);
2087165762Sjeff	/*
2088165762Sjeff	 * Give the child's runtime to the parent without returning the
2089165762Sjeff	 * sleep time as a penalty to the parent.  This causes shells that
2090165762Sjeff	 * launch expensive things to mark their children as expensive.
2091165762Sjeff	 */
2092170293Sjeff	thread_lock(td);
2093171482Sjeff	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2094164939Sjulian	sched_interact_update(td);
2095165762Sjeff	sched_priority(td);
2096170293Sjeff	thread_unlock(td);
2097164936Sjulian}
2098164936Sjulian
2099177005Sjeffvoid
2100177005Sjeffsched_preempt(struct thread *td)
2101177005Sjeff{
2102177005Sjeff	struct tdq *tdq;
2103177005Sjeff
2104177005Sjeff	thread_lock(td);
2105177005Sjeff	tdq = TDQ_SELF();
2106177005Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2107177005Sjeff	tdq->tdq_ipipending = 0;
2108177005Sjeff	if (td->td_priority > tdq->tdq_lowpri) {
2109178272Sjeff		int flags;
2110178272Sjeff
2111178272Sjeff		flags = SW_INVOL | SW_PREEMPT;
2112177005Sjeff		if (td->td_critnest > 1)
2113177005Sjeff			td->td_owepreempt = 1;
2114178272Sjeff		else if (TD_IS_IDLETHREAD(td))
2115178272Sjeff			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2116177005Sjeff		else
2117178272Sjeff			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2118177005Sjeff	}
2119177005Sjeff	thread_unlock(td);
2120177005Sjeff}
2121177005Sjeff
2122171482Sjeff/*
2123171482Sjeff * Fix priorities on return to user-space.  Priorities may be elevated due
2124171482Sjeff * to static priorities in msleep() or similar.
2125171482Sjeff */
2126164936Sjulianvoid
2127164936Sjuliansched_userret(struct thread *td)
2128164936Sjulian{
2129164936Sjulian	/*
2130164936Sjulian	 * XXX we cheat slightly on the locking here to avoid locking in
2131164936Sjulian	 * the usual case.  Setting td_priority here is essentially an
2132164936Sjulian	 * incomplete workaround for not setting it properly elsewhere.
2133164936Sjulian	 * Now that some interrupt handlers are threads, not setting it
2134164936Sjulian	 * properly elsewhere can clobber it in the window between setting
2135164936Sjulian	 * it here and returning to user mode, so don't waste time setting
2136164936Sjulian	 * it perfectly here.
2137164936Sjulian	 */
2138164936Sjulian	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2139164936Sjulian	    ("thread with borrowed priority returning to userland"));
2140164936Sjulian	if (td->td_priority != td->td_user_pri) {
2141170293Sjeff		thread_lock(td);
2142164936Sjulian		td->td_priority = td->td_user_pri;
2143164936Sjulian		td->td_base_pri = td->td_user_pri;
2144177005Sjeff		tdq_setlowpri(TDQ_SELF(), td);
2145170293Sjeff		thread_unlock(td);
2146164936Sjulian        }
2147164936Sjulian}
2148164936Sjulian
2149171482Sjeff/*
2150171482Sjeff * Handle a stathz tick.  This is really only relevant for timeshare
2151171482Sjeff * threads.
2152171482Sjeff */
2153164936Sjulianvoid
2154121127Sjeffsched_clock(struct thread *td)
2155109864Sjeff{
2156164936Sjulian	struct tdq *tdq;
2157164936Sjulian	struct td_sched *ts;
2158109864Sjeff
2159171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2160164936Sjulian	tdq = TDQ_SELF();
2161172409Sjeff#ifdef SMP
2162133427Sjeff	/*
2163172409Sjeff	 * We run the long term load balancer infrequently on the first cpu.
2164172409Sjeff	 */
2165172409Sjeff	if (balance_tdq == tdq) {
2166172409Sjeff		if (balance_ticks && --balance_ticks == 0)
2167172409Sjeff			sched_balance();
2168172409Sjeff	}
2169172409Sjeff#endif
2170172409Sjeff	/*
2171178277Sjeff	 * Save the old switch count so we have a record of the last ticks
2172178277Sjeff	 * activity.   Initialize the new switch count based on our load.
2173178277Sjeff	 * If there is some activity seed it to reflect that.
2174178277Sjeff	 */
2175178277Sjeff	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
2176178471Sjeff	tdq->tdq_switchcnt = tdq->tdq_load;
2177178277Sjeff	/*
2178165766Sjeff	 * Advance the insert index once for each tick to ensure that all
2179165766Sjeff	 * threads get a chance to run.
2180133427Sjeff	 */
2181165766Sjeff	if (tdq->tdq_idx == tdq->tdq_ridx) {
2182165766Sjeff		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2183165766Sjeff		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2184165766Sjeff			tdq->tdq_ridx = tdq->tdq_idx;
2185165766Sjeff	}
2186165766Sjeff	ts = td->td_sched;
2187175104Sjeff	if (td->td_pri_class & PRI_FIFO_BIT)
2188113357Sjeff		return;
2189217291Sjhb	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2190175104Sjeff		/*
2191175104Sjeff		 * We used a tick; charge it to the thread so
2192175104Sjeff		 * that we can compute our interactivity.
2193175104Sjeff		 */
2194175104Sjeff		td->td_sched->ts_runtime += tickincr;
2195175104Sjeff		sched_interact_update(td);
2196177009Sjeff		sched_priority(td);
2197175104Sjeff	}
2198113357Sjeff	/*
2199109864Sjeff	 * We used up one time slice.
2200109864Sjeff	 */
2201164936Sjulian	if (--ts->ts_slice > 0)
2202113357Sjeff		return;
2203109864Sjeff	/*
2204177009Sjeff	 * We're out of time, force a requeue at userret().
2205109864Sjeff	 */
2206177009Sjeff	ts->ts_slice = sched_slice;
2207113357Sjeff	td->td_flags |= TDF_NEEDRESCHED;
2208109864Sjeff}
2209109864Sjeff
2210171482Sjeff/*
2211171482Sjeff * Called once per hz tick.  Used for cpu utilization information.  This
2212171482Sjeff * is easier than trying to scale based on stathz.
2213171482Sjeff */
2214171482Sjeffvoid
2215212541Smavsched_tick(int cnt)
2216171482Sjeff{
2217171482Sjeff	struct td_sched *ts;
2218171482Sjeff
2219171482Sjeff	ts = curthread->td_sched;
2220180607Sjeff	/*
2221180607Sjeff	 * Ticks is updated asynchronously on a single cpu.  Check here to
2222180607Sjeff	 * avoid incrementing ts_ticks multiple times in a single tick.
2223180607Sjeff	 */
2224199764Sivoras	if (ts->ts_incrtick == ticks)
2225180607Sjeff		return;
2226171482Sjeff	/* Adjust ticks for pctcpu */
2227212541Smav	ts->ts_ticks += cnt << SCHED_TICK_SHIFT;
2228171482Sjeff	ts->ts_ltick = ticks;
2229199764Sivoras	ts->ts_incrtick = ticks;
2230171482Sjeff	/*
2231215102Sattilio	 * Update if we've exceeded our desired tick threshold by over one
2232171482Sjeff	 * second.
2233171482Sjeff	 */
2234171482Sjeff	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2235171482Sjeff		sched_pctcpu_update(ts);
2236171482Sjeff}
2237171482Sjeff
2238171482Sjeff/*
2239171482Sjeff * Return whether the current CPU has runnable tasks.  Used for in-kernel
2240171482Sjeff * cooperative idle threads.
2241171482Sjeff */
2242109864Sjeffint
2243109864Sjeffsched_runnable(void)
2244109864Sjeff{
2245164936Sjulian	struct tdq *tdq;
2246115998Sjeff	int load;
2247109864Sjeff
2248115998Sjeff	load = 1;
2249115998Sjeff
2250164936Sjulian	tdq = TDQ_SELF();
2251121605Sjeff	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2252165620Sjeff		if (tdq->tdq_load > 0)
2253121605Sjeff			goto out;
2254121605Sjeff	} else
2255165620Sjeff		if (tdq->tdq_load - 1 > 0)
2256121605Sjeff			goto out;
2257115998Sjeff	load = 0;
2258115998Sjeffout:
2259115998Sjeff	return (load);
2260109864Sjeff}
2261109864Sjeff
2262171482Sjeff/*
2263171482Sjeff * Choose the highest priority thread to run.  The thread is removed from
2264171482Sjeff * the run-queue while running however the load remains.  For SMP we set
2265171482Sjeff * the tdq in the global idle bitmask if it idles here.
2266171482Sjeff */
2267166190Sjeffstruct thread *
2268109970Sjeffsched_choose(void)
2269109970Sjeff{
2270177435Sjeff	struct thread *td;
2271164936Sjulian	struct tdq *tdq;
2272109970Sjeff
2273164936Sjulian	tdq = TDQ_SELF();
2274171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2275177435Sjeff	td = tdq_choose(tdq);
2276177435Sjeff	if (td) {
2277177435Sjeff		td->td_sched->ts_ltick = ticks;
2278177435Sjeff		tdq_runq_rem(tdq, td);
2279177903Sjeff		tdq->tdq_lowpri = td->td_priority;
2280177435Sjeff		return (td);
2281109864Sjeff	}
2282177903Sjeff	tdq->tdq_lowpri = PRI_MAX_IDLE;
2283176735Sjeff	return (PCPU_GET(idlethread));
2284109864Sjeff}
2285109864Sjeff
2286171482Sjeff/*
2287171482Sjeff * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2288171482Sjeff * we always request it once we exit a critical section.
2289171482Sjeff */
2290171482Sjeffstatic inline void
2291171482Sjeffsched_setpreempt(struct thread *td)
2292166190Sjeff{
2293166190Sjeff	struct thread *ctd;
2294166190Sjeff	int cpri;
2295166190Sjeff	int pri;
2296166190Sjeff
2297177005Sjeff	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2298177005Sjeff
2299166190Sjeff	ctd = curthread;
2300166190Sjeff	pri = td->td_priority;
2301166190Sjeff	cpri = ctd->td_priority;
2302177005Sjeff	if (pri < cpri)
2303177005Sjeff		ctd->td_flags |= TDF_NEEDRESCHED;
2304166190Sjeff	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2305171482Sjeff		return;
2306177005Sjeff	if (!sched_shouldpreempt(pri, cpri, 0))
2307171482Sjeff		return;
2308171482Sjeff	ctd->td_owepreempt = 1;
2309166190Sjeff}
2310166190Sjeff
2311171482Sjeff/*
2312177009Sjeff * Add a thread to a thread queue.  Select the appropriate runq and add the
2313177009Sjeff * thread to it.  This is the internal function called when the tdq is
2314177009Sjeff * predetermined.
2315171482Sjeff */
2316109864Sjeffvoid
2317171482Sjefftdq_add(struct tdq *tdq, struct thread *td, int flags)
2318109864Sjeff{
2319109864Sjeff
2320171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2321166190Sjeff	KASSERT((td->td_inhibitors == 0),
2322166190Sjeff	    ("sched_add: trying to run inhibited thread"));
2323166190Sjeff	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2324166190Sjeff	    ("sched_add: bad thread state"));
2325172207Sjeff	KASSERT(td->td_flags & TDF_INMEM,
2326172207Sjeff	    ("sched_add: thread swapped out"));
2327171482Sjeff
2328171482Sjeff	if (td->td_priority < tdq->tdq_lowpri)
2329171482Sjeff		tdq->tdq_lowpri = td->td_priority;
2330177435Sjeff	tdq_runq_add(tdq, td, flags);
2331177435Sjeff	tdq_load_add(tdq, td);
2332171482Sjeff}
2333171482Sjeff
2334171482Sjeff/*
2335171482Sjeff * Select the target thread queue and add a thread to it.  Request
2336171482Sjeff * preemption or IPI a remote processor if required.
2337171482Sjeff */
2338171482Sjeffvoid
2339171482Sjeffsched_add(struct thread *td, int flags)
2340171482Sjeff{
2341171482Sjeff	struct tdq *tdq;
2342171482Sjeff#ifdef SMP
2343171482Sjeff	int cpu;
2344171482Sjeff#endif
2345187357Sjeff
2346187357Sjeff	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
2347187357Sjeff	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
2348187357Sjeff	    sched_tdname(curthread));
2349187357Sjeff	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
2350187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(td));
2351171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2352166108Sjeff	/*
2353171482Sjeff	 * Recalculate the priority before we select the target cpu or
2354171482Sjeff	 * run-queue.
2355166108Sjeff	 */
2356171482Sjeff	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2357171482Sjeff		sched_priority(td);
2358171482Sjeff#ifdef SMP
2359171482Sjeff	/*
2360171482Sjeff	 * Pick the destination cpu and if it isn't ours transfer to the
2361171482Sjeff	 * target cpu.
2362171482Sjeff	 */
2363177435Sjeff	cpu = sched_pickcpu(td, flags);
2364177435Sjeff	tdq = sched_setcpu(td, cpu, flags);
2365171482Sjeff	tdq_add(tdq, td, flags);
2366177009Sjeff	if (cpu != PCPU_GET(cpuid)) {
2367177435Sjeff		tdq_notify(tdq, td);
2368166108Sjeff		return;
2369166108Sjeff	}
2370171482Sjeff#else
2371171482Sjeff	tdq = TDQ_SELF();
2372171482Sjeff	TDQ_LOCK(tdq);
2373171482Sjeff	/*
2374171482Sjeff	 * Now that the thread is moving to the run-queue, set the lock
2375171482Sjeff	 * to the scheduler's lock.
2376171482Sjeff	 */
2377171482Sjeff	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2378171482Sjeff	tdq_add(tdq, td, flags);
2379166108Sjeff#endif
2380171482Sjeff	if (!(flags & SRQ_YIELDING))
2381171482Sjeff		sched_setpreempt(td);
2382109864Sjeff}
2383109864Sjeff
2384171482Sjeff/*
2385171482Sjeff * Remove a thread from a run-queue without running it.  This is used
2386171482Sjeff * when we're stealing a thread from a remote queue.  Otherwise all threads
2387171482Sjeff * exit by calling sched_exit_thread() and sched_throw() themselves.
2388171482Sjeff */
2389109864Sjeffvoid
2390121127Sjeffsched_rem(struct thread *td)
2391109864Sjeff{
2392164936Sjulian	struct tdq *tdq;
2393113357Sjeff
2394187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
2395187357Sjeff	    "prio:%d", td->td_priority);
2396177435Sjeff	tdq = TDQ_CPU(td->td_sched->ts_cpu);
2397171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2398171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2399166190Sjeff	KASSERT(TD_ON_RUNQ(td),
2400164936Sjulian	    ("sched_rem: thread not on run queue"));
2401177435Sjeff	tdq_runq_rem(tdq, td);
2402177435Sjeff	tdq_load_rem(tdq, td);
2403166190Sjeff	TD_SET_CAN_RUN(td);
2404176735Sjeff	if (td->td_priority == tdq->tdq_lowpri)
2405176735Sjeff		tdq_setlowpri(tdq, NULL);
2406109864Sjeff}
2407109864Sjeff
2408171482Sjeff/*
2409171482Sjeff * Fetch cpu utilization information.  Updates on demand.
2410171482Sjeff */
2411109864Sjefffixpt_t
2412121127Sjeffsched_pctcpu(struct thread *td)
2413109864Sjeff{
2414109864Sjeff	fixpt_t pctcpu;
2415164936Sjulian	struct td_sched *ts;
2416109864Sjeff
2417109864Sjeff	pctcpu = 0;
2418164936Sjulian	ts = td->td_sched;
2419164936Sjulian	if (ts == NULL)
2420121290Sjeff		return (0);
2421109864Sjeff
2422208787Sjhb	THREAD_LOCK_ASSERT(td, MA_OWNED);
2423164936Sjulian	if (ts->ts_ticks) {
2424109864Sjeff		int rtick;
2425109864Sjeff
2426165796Sjeff		sched_pctcpu_update(ts);
2427109864Sjeff		/* How many rtick per second ? */
2428165762Sjeff		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2429165762Sjeff		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2430109864Sjeff	}
2431109864Sjeff
2432109864Sjeff	return (pctcpu);
2433109864Sjeff}
2434109864Sjeff
2435176735Sjeff/*
2436176735Sjeff * Enforce affinity settings for a thread.  Called after adjustments to
2437176735Sjeff * cpumask.
2438176735Sjeff */
2439176729Sjeffvoid
2440176729Sjeffsched_affinity(struct thread *td)
2441176729Sjeff{
2442176735Sjeff#ifdef SMP
2443176735Sjeff	struct td_sched *ts;
2444176735Sjeff
2445176735Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2446176735Sjeff	ts = td->td_sched;
2447176735Sjeff	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2448176735Sjeff		return;
2449189787Sjeff	if (TD_ON_RUNQ(td)) {
2450189787Sjeff		sched_rem(td);
2451189787Sjeff		sched_add(td, SRQ_BORING);
2452189787Sjeff		return;
2453189787Sjeff	}
2454176735Sjeff	if (!TD_IS_RUNNING(td))
2455176735Sjeff		return;
2456176735Sjeff	/*
2457212115Smdf	 * Force a switch before returning to userspace.  If the
2458212115Smdf	 * target thread is not running locally send an ipi to force
2459212115Smdf	 * the issue.
2460176735Sjeff	 */
2461212974Sjhb	td->td_flags |= TDF_NEEDRESCHED;
2462212115Smdf	if (td != curthread)
2463212115Smdf		ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
2464176735Sjeff#endif
2465176729Sjeff}
2466176729Sjeff
2467171482Sjeff/*
2468171482Sjeff * Bind a thread to a target cpu.
2469171482Sjeff */
2470122038Sjeffvoid
2471122038Sjeffsched_bind(struct thread *td, int cpu)
2472122038Sjeff{
2473164936Sjulian	struct td_sched *ts;
2474122038Sjeff
2475171713Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2476208391Sjhb	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
2477164936Sjulian	ts = td->td_sched;
2478166137Sjeff	if (ts->ts_flags & TSF_BOUND)
2479166152Sjeff		sched_unbind(td);
2480212115Smdf	KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2481164936Sjulian	ts->ts_flags |= TSF_BOUND;
2482166137Sjeff	sched_pin();
2483123433Sjeff	if (PCPU_GET(cpuid) == cpu)
2484122038Sjeff		return;
2485166137Sjeff	ts->ts_cpu = cpu;
2486122038Sjeff	/* When we return from mi_switch we'll be on the correct cpu. */
2487131527Sphk	mi_switch(SW_VOL, NULL);
2488122038Sjeff}
2489122038Sjeff
2490171482Sjeff/*
2491171482Sjeff * Release a bound thread.
2492171482Sjeff */
2493122038Sjeffvoid
2494122038Sjeffsched_unbind(struct thread *td)
2495122038Sjeff{
2496165762Sjeff	struct td_sched *ts;
2497165762Sjeff
2498170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2499208391Sjhb	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
2500165762Sjeff	ts = td->td_sched;
2501166137Sjeff	if ((ts->ts_flags & TSF_BOUND) == 0)
2502166137Sjeff		return;
2503165762Sjeff	ts->ts_flags &= ~TSF_BOUND;
2504165762Sjeff	sched_unpin();
2505122038Sjeff}
2506122038Sjeff
2507109864Sjeffint
2508145256Sjkoshysched_is_bound(struct thread *td)
2509145256Sjkoshy{
2510170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2511164936Sjulian	return (td->td_sched->ts_flags & TSF_BOUND);
2512145256Sjkoshy}
2513145256Sjkoshy
2514171482Sjeff/*
2515171482Sjeff * Basic yield call.
2516171482Sjeff */
2517159630Sdavidxuvoid
2518159630Sdavidxusched_relinquish(struct thread *td)
2519159630Sdavidxu{
2520170293Sjeff	thread_lock(td);
2521178272Sjeff	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
2522170293Sjeff	thread_unlock(td);
2523159630Sdavidxu}
2524159630Sdavidxu
2525171482Sjeff/*
2526171482Sjeff * Return the total system load.
2527171482Sjeff */
2528145256Sjkoshyint
2529125289Sjeffsched_load(void)
2530125289Sjeff{
2531125289Sjeff#ifdef SMP
2532125289Sjeff	int total;
2533125289Sjeff	int i;
2534125289Sjeff
2535125289Sjeff	total = 0;
2536209059Sjhb	CPU_FOREACH(i)
2537176735Sjeff		total += TDQ_CPU(i)->tdq_sysload;
2538125289Sjeff	return (total);
2539125289Sjeff#else
2540165620Sjeff	return (TDQ_SELF()->tdq_sysload);
2541125289Sjeff#endif
2542125289Sjeff}
2543125289Sjeff
2544125289Sjeffint
2545109864Sjeffsched_sizeof_proc(void)
2546109864Sjeff{
2547109864Sjeff	return (sizeof(struct proc));
2548109864Sjeff}
2549109864Sjeff
2550109864Sjeffint
2551109864Sjeffsched_sizeof_thread(void)
2552109864Sjeff{
2553109864Sjeff	return (sizeof(struct thread) + sizeof(struct td_sched));
2554109864Sjeff}
2555159570Sdavidxu
2556191676Sjeff#ifdef SMP
2557191676Sjeff#define	TDQ_IDLESPIN(tdq)						\
2558191676Sjeff    ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
2559191676Sjeff#else
2560191676Sjeff#define	TDQ_IDLESPIN(tdq)	1
2561191676Sjeff#endif
2562191676Sjeff
2563166190Sjeff/*
2564166190Sjeff * The actual idle process.
2565166190Sjeff */
2566166190Sjeffvoid
2567166190Sjeffsched_idletd(void *dummy)
2568166190Sjeff{
2569166190Sjeff	struct thread *td;
2570171482Sjeff	struct tdq *tdq;
2571178277Sjeff	int switchcnt;
2572178277Sjeff	int i;
2573166190Sjeff
2574191643Sjeff	mtx_assert(&Giant, MA_NOTOWNED);
2575166190Sjeff	td = curthread;
2576171482Sjeff	tdq = TDQ_SELF();
2577171482Sjeff	for (;;) {
2578171482Sjeff#ifdef SMP
2579178277Sjeff		if (tdq_idled(tdq) == 0)
2580178277Sjeff			continue;
2581171482Sjeff#endif
2582178277Sjeff		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2583178277Sjeff		/*
2584178277Sjeff		 * If we're switching very frequently, spin while checking
2585178277Sjeff		 * for load rather than entering a low power state that
2586191643Sjeff		 * may require an IPI.  However, don't do any busy
2587191643Sjeff		 * loops while on SMT machines as this simply steals
2588191643Sjeff		 * cycles from cores doing useful work.
2589178277Sjeff		 */
2590191676Sjeff		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
2591178277Sjeff			for (i = 0; i < sched_idlespins; i++) {
2592178277Sjeff				if (tdq->tdq_load)
2593178277Sjeff					break;
2594178277Sjeff				cpu_spinwait();
2595178277Sjeff			}
2596178277Sjeff		}
2597191643Sjeff		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2598212416Smav		if (tdq->tdq_load == 0) {
2599212416Smav			tdq->tdq_cpu_idle = 1;
2600212416Smav			if (tdq->tdq_load == 0) {
2601212541Smav				cpu_idle(switchcnt > sched_idlespinthresh * 4);
2602212416Smav				tdq->tdq_switchcnt++;
2603212416Smav			}
2604212416Smav			tdq->tdq_cpu_idle = 0;
2605212416Smav		}
2606178277Sjeff		if (tdq->tdq_load) {
2607178277Sjeff			thread_lock(td);
2608178277Sjeff			mi_switch(SW_VOL | SWT_IDLE, NULL);
2609178277Sjeff			thread_unlock(td);
2610178277Sjeff		}
2611171482Sjeff	}
2612166190Sjeff}
2613166190Sjeff
2614170293Sjeff/*
2615170293Sjeff * A CPU is entering for the first time or a thread is exiting.
2616170293Sjeff */
2617170293Sjeffvoid
2618170293Sjeffsched_throw(struct thread *td)
2619170293Sjeff{
2620172411Sjeff	struct thread *newtd;
2621171482Sjeff	struct tdq *tdq;
2622171482Sjeff
2623171482Sjeff	tdq = TDQ_SELF();
2624170293Sjeff	if (td == NULL) {
2625171482Sjeff		/* Correct spinlock nesting and acquire the correct lock. */
2626171482Sjeff		TDQ_LOCK(tdq);
2627170293Sjeff		spinlock_exit();
2628229429Sjhb		PCPU_SET(switchtime, cpu_ticks());
2629229429Sjhb		PCPU_SET(switchticks, ticks);
2630170293Sjeff	} else {
2631171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2632177435Sjeff		tdq_load_rem(tdq, td);
2633174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2634170293Sjeff	}
2635170293Sjeff	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2636172411Sjeff	newtd = choosethread();
2637172411Sjeff	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2638172411Sjeff	cpu_throw(td, newtd);		/* doesn't return */
2639170293Sjeff}
2640170293Sjeff
2641171482Sjeff/*
2642171482Sjeff * This is called from fork_exit().  Just acquire the correct locks and
2643171482Sjeff * let fork do the rest of the work.
2644171482Sjeff */
2645170293Sjeffvoid
2646170600Sjeffsched_fork_exit(struct thread *td)
2647170293Sjeff{
2648171482Sjeff	struct td_sched *ts;
2649171482Sjeff	struct tdq *tdq;
2650171482Sjeff	int cpuid;
2651170293Sjeff
2652170293Sjeff	/*
2653170293Sjeff	 * Finish setting up thread glue so that it begins execution in a
2654171482Sjeff	 * non-nested critical section with the scheduler lock held.
2655170293Sjeff	 */
2656171482Sjeff	cpuid = PCPU_GET(cpuid);
2657171482Sjeff	tdq = TDQ_CPU(cpuid);
2658171482Sjeff	ts = td->td_sched;
2659171482Sjeff	if (TD_IS_IDLETHREAD(td))
2660171482Sjeff		td->td_lock = TDQ_LOCKPTR(tdq);
2661171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2662171482Sjeff	td->td_oncpu = cpuid;
2663172411Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2664174629Sjeff	lock_profile_obtain_lock_success(
2665174629Sjeff	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2666170293Sjeff}
2667170293Sjeff
2668187357Sjeff/*
2669187357Sjeff * Create on first use to catch odd startup conditons.
2670187357Sjeff */
2671187357Sjeffchar *
2672187357Sjeffsched_tdname(struct thread *td)
2673187357Sjeff{
2674187357Sjeff#ifdef KTR
2675187357Sjeff	struct td_sched *ts;
2676187357Sjeff
2677187357Sjeff	ts = td->td_sched;
2678187357Sjeff	if (ts->ts_name[0] == '\0')
2679187357Sjeff		snprintf(ts->ts_name, sizeof(ts->ts_name),
2680187357Sjeff		    "%s tid %d", td->td_name, td->td_tid);
2681187357Sjeff	return (ts->ts_name);
2682187357Sjeff#else
2683187357Sjeff	return (td->td_name);
2684187357Sjeff#endif
2685187357Sjeff}
2686187357Sjeff
2687184439Sivoras#ifdef SMP
2688184439Sivoras
2689184439Sivoras/*
2690184439Sivoras * Build the CPU topology dump string. Is recursively called to collect
2691184439Sivoras * the topology tree.
2692184439Sivoras */
2693184439Sivorasstatic int
2694184439Sivorassysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
2695184439Sivoras    int indent)
2696184439Sivoras{
2697222813Sattilio	char cpusetbuf[CPUSETBUFSIZ];
2698184439Sivoras	int i, first;
2699184439Sivoras
2700184439Sivoras	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
2701212821Savg	    "", 1 + indent / 2, cg->cg_level);
2702222813Sattilio	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
2703222813Sattilio	    cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
2704184439Sivoras	first = TRUE;
2705184439Sivoras	for (i = 0; i < MAXCPU; i++) {
2706222813Sattilio		if (CPU_ISSET(i, &cg->cg_mask)) {
2707184439Sivoras			if (!first)
2708184439Sivoras				sbuf_printf(sb, ", ");
2709184439Sivoras			else
2710184439Sivoras				first = FALSE;
2711184439Sivoras			sbuf_printf(sb, "%d", i);
2712184439Sivoras		}
2713184439Sivoras	}
2714184439Sivoras	sbuf_printf(sb, "</cpu>\n");
2715184439Sivoras
2716184439Sivoras	if (cg->cg_flags != 0) {
2717210117Sivoras		sbuf_printf(sb, "%*s <flags>", indent, "");
2718184439Sivoras		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
2719208982Sivoras			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
2720208983Sivoras		if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
2721208983Sivoras			sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
2722191643Sjeff		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
2723208983Sivoras			sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
2724210117Sivoras		sbuf_printf(sb, "</flags>\n");
2725184439Sivoras	}
2726184439Sivoras
2727184439Sivoras	if (cg->cg_children > 0) {
2728184439Sivoras		sbuf_printf(sb, "%*s <children>\n", indent, "");
2729184439Sivoras		for (i = 0; i < cg->cg_children; i++)
2730184439Sivoras			sysctl_kern_sched_topology_spec_internal(sb,
2731184439Sivoras			    &cg->cg_child[i], indent+2);
2732184439Sivoras		sbuf_printf(sb, "%*s </children>\n", indent, "");
2733184439Sivoras	}
2734184439Sivoras	sbuf_printf(sb, "%*s</group>\n", indent, "");
2735184439Sivoras	return (0);
2736184439Sivoras}
2737184439Sivoras
2738184439Sivoras/*
2739184439Sivoras * Sysctl handler for retrieving topology dump. It's a wrapper for
2740184439Sivoras * the recursive sysctl_kern_smp_topology_spec_internal().
2741184439Sivoras */
2742184439Sivorasstatic int
2743184439Sivorassysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
2744184439Sivoras{
2745184439Sivoras	struct sbuf *topo;
2746184439Sivoras	int err;
2747184439Sivoras
2748184439Sivoras	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
2749184439Sivoras
2750184570Sivoras	topo = sbuf_new(NULL, NULL, 500, SBUF_AUTOEXTEND);
2751184439Sivoras	if (topo == NULL)
2752184439Sivoras		return (ENOMEM);
2753184439Sivoras
2754184439Sivoras	sbuf_printf(topo, "<groups>\n");
2755184439Sivoras	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
2756184439Sivoras	sbuf_printf(topo, "</groups>\n");
2757184439Sivoras
2758184439Sivoras	if (err == 0) {
2759184439Sivoras		sbuf_finish(topo);
2760184439Sivoras		err = SYSCTL_OUT(req, sbuf_data(topo), sbuf_len(topo));
2761184439Sivoras	}
2762184439Sivoras	sbuf_delete(topo);
2763184439Sivoras	return (err);
2764184439Sivoras}
2765214510Sdavidxu
2766184439Sivoras#endif
2767184439Sivoras
2768177435SjeffSYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2769171482SjeffSYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2770165762Sjeff    "Scheduler name");
2771171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2772171482Sjeff    "Slice size for timeshare threads");
2773171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2774171482Sjeff     "Interactivity score threshold");
2775171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2776171482Sjeff     0,"Min priority for preemption, lower priorities have greater precedence");
2777177085SjeffSYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost,
2778177085Sjeff     0,"Controls whether static kernel priorities are assigned to sleeping threads.");
2779178277SjeffSYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins,
2780178277Sjeff     0,"Number of times idle will spin waiting for new work.");
2781178277SjeffSYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW, &sched_idlespinthresh,
2782178277Sjeff     0,"Threshold before we will permit idle spinning.");
2783166108Sjeff#ifdef SMP
2784171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2785171482Sjeff    "Number of hz ticks to keep thread affinity for");
2786171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2787171482Sjeff    "Enables the long-term load balancer");
2788172409SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2789172409Sjeff    &balance_interval, 0,
2790172409Sjeff    "Average frequency in stathz ticks to run the long-term balancer");
2791171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2792171482Sjeff    "Attempts to steal work from other cores before idling");
2793171506SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2794171506Sjeff    "Minimum load on remote cpu before we'll steal");
2795184439Sivoras
2796184439Sivoras/* Retrieve SMP topology */
2797184439SivorasSYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
2798184439Sivoras    CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
2799184439Sivoras    "XML dump of detected CPU topology");
2800214510Sdavidxu
2801166108Sjeff#endif
2802165762Sjeff
2803172264Sjeff/* ps compat.  All cpu percentages from ULE are weighted. */
2804172293Sjeffstatic int ccpu = 0;
2805165762SjeffSYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2806