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$");
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>
56236344Srstone#include <sys/sdt.h>
57109864Sjeff#include <sys/smp.h>
58109864Sjeff#include <sys/sx.h>
59109864Sjeff#include <sys/sysctl.h>
60109864Sjeff#include <sys/sysproto.h>
61139453Sjhb#include <sys/turnstile.h>
62161599Sdavidxu#include <sys/umtx.h>
63109864Sjeff#include <sys/vmmeter.h>
64176735Sjeff#include <sys/cpuset.h>
65184439Sivoras#include <sys/sbuf.h>
66109864Sjeff
67145256Sjkoshy#ifdef HWPMC_HOOKS
68145256Sjkoshy#include <sys/pmckern.h>
69145256Sjkoshy#endif
70145256Sjkoshy
71179297Sjb#ifdef KDTRACE_HOOKS
72179297Sjb#include <sys/dtrace_bsd.h>
73179297Sjbint				dtrace_vtime_active;
74179297Sjbdtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
75179297Sjb#endif
76179297Sjb
77109864Sjeff#include <machine/cpu.h>
78121790Sjeff#include <machine/smp.h>
79109864Sjeff
80230691Smarius#if defined(__powerpc__) && defined(E500)
81172345Sjeff#error "This architecture is not currently compatible with ULE"
82166190Sjeff#endif
83166190Sjeff
84171482Sjeff#define	KTR_ULE	0
85166137Sjeff
86187679Sjeff#define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
87187679Sjeff#define	TDQ_NAME_LEN	(sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
88224221Sattilio#define	TDQ_LOADNAME_LEN	(sizeof("CPU ") + sizeof(__XSTRING(MAXCPU)) - 1 + sizeof(" load"))
89187357Sjeff
90166137Sjeff/*
91171482Sjeff * Thread scheduler specific section.  All fields are protected
92171482Sjeff * by the thread lock.
93146954Sjeff */
94164936Sjulianstruct td_sched {
95171482Sjeff	struct runq	*ts_runq;	/* Run-queue we're queued on. */
96171482Sjeff	short		ts_flags;	/* TSF_* flags. */
97164936Sjulian	u_char		ts_cpu;		/* CPU that we have affinity for. */
98177009Sjeff	int		ts_rltick;	/* Real last tick, for affinity. */
99171482Sjeff	int		ts_slice;	/* Ticks of slice remaining. */
100171482Sjeff	u_int		ts_slptime;	/* Number of ticks we vol. slept */
101171482Sjeff	u_int		ts_runtime;	/* Number of ticks we were running */
102164936Sjulian	int		ts_ltick;	/* Last tick that we were running 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)
128230173Savg#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
192241248Smav/* Flags kept in td_flags. */
193241248Smav#define	TDF_SLICEEND	TDF_SCHED2	/* Thread time slice is over. */
194241248Smav
195109864Sjeff/*
196165762Sjeff * tickincr:		Converts a stathz tick into a hz domain scaled by
197165762Sjeff *			the shift factor.  Without the shift the error rate
198165762Sjeff *			due to rounding would be unacceptably high.
199165762Sjeff * realstathz:		stathz is sometimes 0 and run off of hz.
200165762Sjeff * sched_slice:		Runtime of each thread before rescheduling.
201171482Sjeff * preempt_thresh:	Priority threshold for preemption and remote IPIs.
202109864Sjeff */
203165762Sjeffstatic int sched_interact = SCHED_INTERACT_THRESH;
204241249Smavstatic int realstathz = 127;
205242544Seadlerstatic int tickincr = 8 << SCHED_TICK_SHIFT;
206241249Smavstatic int sched_slice = 12;
207172345Sjeff#ifdef PREEMPTION
208172345Sjeff#ifdef FULL_PREEMPTION
209172345Sjeffstatic int preempt_thresh = PRI_MAX_IDLE;
210172345Sjeff#else
211171482Sjeffstatic int preempt_thresh = PRI_MIN_KERN;
212172345Sjeff#endif
213172345Sjeff#else
214172345Sjeffstatic int preempt_thresh = 0;
215172345Sjeff#endif
216217351Sjhbstatic int static_boost = PRI_MIN_BATCH;
217178277Sjeffstatic int sched_idlespins = 10000;
218236546Smavstatic int sched_idlespinthresh = -1;
219109864Sjeff
220109864Sjeff/*
221171482Sjeff * tdq - per processor runqs and statistics.  All fields are protected by the
222171482Sjeff * tdq_lock.  The load and lowpri may be accessed without to avoid excess
223171482Sjeff * locking in sched_pickcpu();
224109864Sjeff */
225164936Sjulianstruct tdq {
226177009Sjeff	/* Ordered to improve efficiency of cpu_search() and switch(). */
227177009Sjeff	struct mtx	tdq_lock;		/* run queue lock. */
228176735Sjeff	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
229178277Sjeff	volatile int	tdq_load;		/* Aggregate load. */
230212416Smav	volatile int	tdq_cpu_idle;		/* cpu_idle() is active. */
231176735Sjeff	int		tdq_sysload;		/* For loadavg, !ITHD load. */
232177009Sjeff	int		tdq_transferable;	/* Transferable thread count. */
233178277Sjeff	short		tdq_switchcnt;		/* Switches this tick. */
234178277Sjeff	short		tdq_oldswitchcnt;	/* Switches last tick. */
235177009Sjeff	u_char		tdq_lowpri;		/* Lowest priority thread. */
236177009Sjeff	u_char		tdq_ipipending;		/* IPI pending. */
237166557Sjeff	u_char		tdq_idx;		/* Current insert index. */
238166557Sjeff	u_char		tdq_ridx;		/* Current removal index. */
239177009Sjeff	struct runq	tdq_realtime;		/* real-time run queue. */
240177009Sjeff	struct runq	tdq_timeshare;		/* timeshare run queue. */
241177009Sjeff	struct runq	tdq_idle;		/* Queue of IDLE threads. */
242187357Sjeff	char		tdq_name[TDQ_NAME_LEN];
243187357Sjeff#ifdef KTR
244187357Sjeff	char		tdq_loadname[TDQ_LOADNAME_LEN];
245187357Sjeff#endif
246171482Sjeff} __aligned(64);
247109864Sjeff
248178277Sjeff/* Idle thread states and config. */
249178277Sjeff#define	TDQ_RUNNING	1
250178277Sjeff#define	TDQ_IDLE	2
251166108Sjeff
252123433Sjeff#ifdef SMP
253184439Sivorasstruct cpu_group *cpu_top;		/* CPU topology */
254123433Sjeff
255176735Sjeff#define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
256176735Sjeff#define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
257166108Sjeff
258123433Sjeff/*
259166108Sjeff * Run-time tunables.
260166108Sjeff */
261171506Sjeffstatic int rebalance = 1;
262172409Sjeffstatic int balance_interval = 128;	/* Default set in sched_initticks(). */
263166108Sjeffstatic int affinity;
264171506Sjeffstatic int steal_idle = 1;
265171506Sjeffstatic int steal_thresh = 2;
266166108Sjeff
267166108Sjeff/*
268165620Sjeff * One thread queue per processor.
269109864Sjeff */
270164936Sjulianstatic struct tdq	tdq_cpu[MAXCPU];
271172409Sjeffstatic struct tdq	*balance_tdq;
272172409Sjeffstatic int balance_ticks;
273233599Smavstatic DPCPU_DEFINE(uint32_t, randomval);
274129982Sjeff
275164936Sjulian#define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
276164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu[(x)])
277171713Sjeff#define	TDQ_ID(x)	((int)((x) - tdq_cpu))
278123433Sjeff#else	/* !SMP */
279164936Sjulianstatic struct tdq	tdq_cpu;
280129982Sjeff
281170315Sjeff#define	TDQ_ID(x)	(0)
282164936Sjulian#define	TDQ_SELF()	(&tdq_cpu)
283164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu)
284110028Sjeff#endif
285109864Sjeff
286171482Sjeff#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
287171482Sjeff#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
288171482Sjeff#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
289171482Sjeff#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
290176735Sjeff#define	TDQ_LOCKPTR(t)		(&(t)->tdq_lock)
291171482Sjeff
292163709Sjbstatic void sched_priority(struct thread *);
293146954Sjeffstatic void sched_thread_priority(struct thread *, u_char);
294163709Sjbstatic int sched_interact_score(struct thread *);
295163709Sjbstatic void sched_interact_update(struct thread *);
296163709Sjbstatic void sched_interact_fork(struct thread *);
297234166Smavstatic void sched_pctcpu_update(struct td_sched *, int);
298109864Sjeff
299110267Sjeff/* Operations on per processor queues */
300177435Sjeffstatic struct thread *tdq_choose(struct tdq *);
301164936Sjulianstatic void tdq_setup(struct tdq *);
302177435Sjeffstatic void tdq_load_add(struct tdq *, struct thread *);
303177435Sjeffstatic void tdq_load_rem(struct tdq *, struct thread *);
304177435Sjeffstatic __inline void tdq_runq_add(struct tdq *, struct thread *, int);
305177435Sjeffstatic __inline void tdq_runq_rem(struct tdq *, struct thread *);
306177005Sjeffstatic inline int sched_shouldpreempt(int, int, int);
307164936Sjulianvoid tdq_print(int cpu);
308165762Sjeffstatic void runq_print(struct runq *rq);
309171482Sjeffstatic void tdq_add(struct tdq *, struct thread *, int);
310110267Sjeff#ifdef SMP
311176735Sjeffstatic int tdq_move(struct tdq *, struct tdq *);
312171482Sjeffstatic int tdq_idled(struct tdq *);
313177435Sjeffstatic void tdq_notify(struct tdq *, struct thread *);
314177435Sjeffstatic struct thread *tdq_steal(struct tdq *, int);
315177435Sjeffstatic struct thread *runq_steal(struct runq *, int);
316177435Sjeffstatic int sched_pickcpu(struct thread *, int);
317172409Sjeffstatic void sched_balance(void);
318176735Sjeffstatic int sched_balance_pair(struct tdq *, struct tdq *);
319177435Sjeffstatic inline struct tdq *sched_setcpu(struct thread *, int, int);
320171482Sjeffstatic inline void thread_unblock_switch(struct thread *, struct mtx *);
321171713Sjeffstatic struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
322184439Sivorasstatic int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
323184439Sivorasstatic int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
324184439Sivoras    struct cpu_group *cg, int indent);
325121790Sjeff#endif
326110028Sjeff
327165762Sjeffstatic void sched_setup(void *dummy);
328177253SrwatsonSYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
329165762Sjeff
330165762Sjeffstatic void sched_initticks(void *dummy);
331177253SrwatsonSYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
332177253Srwatson    NULL);
333165762Sjeff
334236344SrstoneSDT_PROVIDER_DEFINE(sched);
335236344Srstone
336262057SavgSDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
337236344Srstone    "struct proc *", "uint8_t");
338262057SavgSDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
339236344Srstone    "struct proc *", "void *");
340262057SavgSDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
341236344Srstone    "struct proc *", "void *", "int");
342262057SavgSDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
343236344Srstone    "struct proc *", "uint8_t", "struct thread *");
344262057SavgSDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
345262057SavgSDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
346236344Srstone    "struct proc *");
347262057SavgSDT_PROBE_DEFINE(sched, , , on__cpu);
348262057SavgSDT_PROBE_DEFINE(sched, , , remain__cpu);
349262057SavgSDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
350236344Srstone    "struct proc *");
351236344Srstone
352171482Sjeff/*
353171482Sjeff * Print the threads waiting on a run-queue.
354171482Sjeff */
355165762Sjeffstatic void
356165762Sjeffrunq_print(struct runq *rq)
357165762Sjeff{
358165762Sjeff	struct rqhead *rqh;
359177435Sjeff	struct thread *td;
360165762Sjeff	int pri;
361165762Sjeff	int j;
362165762Sjeff	int i;
363165762Sjeff
364165762Sjeff	for (i = 0; i < RQB_LEN; i++) {
365165762Sjeff		printf("\t\trunq bits %d 0x%zx\n",
366165762Sjeff		    i, rq->rq_status.rqb_bits[i]);
367165762Sjeff		for (j = 0; j < RQB_BPW; j++)
368165762Sjeff			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
369165762Sjeff				pri = j + (i << RQB_L2BPW);
370165762Sjeff				rqh = &rq->rq_queues[pri];
371177435Sjeff				TAILQ_FOREACH(td, rqh, td_runq) {
372165762Sjeff					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
373177435Sjeff					    td, td->td_name, td->td_priority,
374177435Sjeff					    td->td_rqindex, pri);
375165762Sjeff				}
376165762Sjeff			}
377165762Sjeff	}
378165762Sjeff}
379165762Sjeff
380171482Sjeff/*
381171482Sjeff * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
382171482Sjeff */
383113357Sjeffvoid
384164936Sjuliantdq_print(int cpu)
385110267Sjeff{
386164936Sjulian	struct tdq *tdq;
387112994Sjeff
388164936Sjulian	tdq = TDQ_CPU(cpu);
389112994Sjeff
390171713Sjeff	printf("tdq %d:\n", TDQ_ID(tdq));
391176735Sjeff	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
392176735Sjeff	printf("\tLock name:      %s\n", tdq->tdq_name);
393165620Sjeff	printf("\tload:           %d\n", tdq->tdq_load);
394178277Sjeff	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
395178277Sjeff	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
396171482Sjeff	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
397165766Sjeff	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
398178277Sjeff	printf("\tload transferable: %d\n", tdq->tdq_transferable);
399178277Sjeff	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
400165762Sjeff	printf("\trealtime runq:\n");
401165762Sjeff	runq_print(&tdq->tdq_realtime);
402165762Sjeff	printf("\ttimeshare runq:\n");
403165762Sjeff	runq_print(&tdq->tdq_timeshare);
404165762Sjeff	printf("\tidle runq:\n");
405165762Sjeff	runq_print(&tdq->tdq_idle);
406113357Sjeff}
407112994Sjeff
408177005Sjeffstatic inline int
409177005Sjeffsched_shouldpreempt(int pri, int cpri, int remote)
410177005Sjeff{
411177005Sjeff	/*
412177005Sjeff	 * If the new priority is not better than the current priority there is
413177005Sjeff	 * nothing to do.
414177005Sjeff	 */
415177005Sjeff	if (pri >= cpri)
416177005Sjeff		return (0);
417177005Sjeff	/*
418177005Sjeff	 * Always preempt idle.
419177005Sjeff	 */
420177005Sjeff	if (cpri >= PRI_MIN_IDLE)
421177005Sjeff		return (1);
422177005Sjeff	/*
423177005Sjeff	 * If preemption is disabled don't preempt others.
424177005Sjeff	 */
425177005Sjeff	if (preempt_thresh == 0)
426177005Sjeff		return (0);
427177005Sjeff	/*
428177005Sjeff	 * Preempt if we exceed the threshold.
429177005Sjeff	 */
430177005Sjeff	if (pri <= preempt_thresh)
431177005Sjeff		return (1);
432177005Sjeff	/*
433217351Sjhb	 * If we're interactive or better and there is non-interactive
434217351Sjhb	 * or worse running preempt only remote processors.
435177005Sjeff	 */
436217351Sjhb	if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
437177005Sjeff		return (1);
438177005Sjeff	return (0);
439177005Sjeff}
440177005Sjeff
441171482Sjeff/*
442171482Sjeff * Add a thread to the actual run-queue.  Keeps transferable counts up to
443171482Sjeff * date with what is actually on the run-queue.  Selects the correct
444171482Sjeff * queue position for timeshare threads.
445171482Sjeff */
446122744Sjeffstatic __inline void
447177435Sjefftdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
448122744Sjeff{
449177435Sjeff	struct td_sched *ts;
450177042Sjeff	u_char pri;
451177042Sjeff
452171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
453177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
454177009Sjeff
455177435Sjeff	pri = td->td_priority;
456177435Sjeff	ts = td->td_sched;
457177435Sjeff	TD_SET_RUNQ(td);
458177435Sjeff	if (THREAD_CAN_MIGRATE(td)) {
459165620Sjeff		tdq->tdq_transferable++;
460164936Sjulian		ts->ts_flags |= TSF_XFERABLE;
461123433Sjeff	}
462217351Sjhb	if (pri < PRI_MIN_BATCH) {
463177042Sjeff		ts->ts_runq = &tdq->tdq_realtime;
464217351Sjhb	} else if (pri <= PRI_MAX_BATCH) {
465177042Sjeff		ts->ts_runq = &tdq->tdq_timeshare;
466217351Sjhb		KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
467165762Sjeff			("Invalid priority %d on timeshare runq", pri));
468165762Sjeff		/*
469165762Sjeff		 * This queue contains only priorities between MIN and MAX
470165762Sjeff		 * realtime.  Use the whole queue to represent these values.
471165762Sjeff		 */
472171713Sjeff		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
473230173Savg			pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
474165762Sjeff			pri = (pri + tdq->tdq_idx) % RQ_NQS;
475165766Sjeff			/*
476165766Sjeff			 * This effectively shortens the queue by one so we
477165766Sjeff			 * can have a one slot difference between idx and
478165766Sjeff			 * ridx while we wait for threads to drain.
479165766Sjeff			 */
480165766Sjeff			if (tdq->tdq_ridx != tdq->tdq_idx &&
481165766Sjeff			    pri == tdq->tdq_ridx)
482167664Sjeff				pri = (unsigned char)(pri - 1) % RQ_NQS;
483165762Sjeff		} else
484165766Sjeff			pri = tdq->tdq_ridx;
485177435Sjeff		runq_add_pri(ts->ts_runq, td, pri, flags);
486177042Sjeff		return;
487165762Sjeff	} else
488177009Sjeff		ts->ts_runq = &tdq->tdq_idle;
489177435Sjeff	runq_add(ts->ts_runq, td, flags);
490177009Sjeff}
491177009Sjeff
492171482Sjeff/*
493171482Sjeff * Remove a thread from a run-queue.  This typically happens when a thread
494171482Sjeff * is selected to run.  Running threads are not on the queue and the
495171482Sjeff * transferable count does not reflect them.
496171482Sjeff */
497122744Sjeffstatic __inline void
498177435Sjefftdq_runq_rem(struct tdq *tdq, struct thread *td)
499122744Sjeff{
500177435Sjeff	struct td_sched *ts;
501177435Sjeff
502177435Sjeff	ts = td->td_sched;
503171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
504171482Sjeff	KASSERT(ts->ts_runq != NULL,
505177435Sjeff	    ("tdq_runq_remove: thread %p null ts_runq", td));
506164936Sjulian	if (ts->ts_flags & TSF_XFERABLE) {
507165620Sjeff		tdq->tdq_transferable--;
508164936Sjulian		ts->ts_flags &= ~TSF_XFERABLE;
509123433Sjeff	}
510165766Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
511165766Sjeff		if (tdq->tdq_idx != tdq->tdq_ridx)
512177435Sjeff			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
513165766Sjeff		else
514177435Sjeff			runq_remove_idx(ts->ts_runq, td, NULL);
515165766Sjeff	} else
516177435Sjeff		runq_remove(ts->ts_runq, td);
517122744Sjeff}
518122744Sjeff
519171482Sjeff/*
520171482Sjeff * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
521171482Sjeff * for this thread to the referenced thread queue.
522171482Sjeff */
523113357Sjeffstatic void
524177435Sjefftdq_load_add(struct tdq *tdq, struct thread *td)
525113357Sjeff{
526171482Sjeff
527171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
528177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
529177902Sjeff
530165620Sjeff	tdq->tdq_load++;
531198854Sattilio	if ((td->td_flags & TDF_NOLOAD) == 0)
532177902Sjeff		tdq->tdq_sysload++;
533187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
534262057Savg	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
535110267Sjeff}
536113357Sjeff
537171482Sjeff/*
538171482Sjeff * Remove the load from a thread that is transitioning to a sleep state or
539171482Sjeff * exiting.
540171482Sjeff */
541112994Sjeffstatic void
542177435Sjefftdq_load_rem(struct tdq *tdq, struct thread *td)
543110267Sjeff{
544171482Sjeff
545177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
546171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
547171482Sjeff	KASSERT(tdq->tdq_load != 0,
548171713Sjeff	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
549177902Sjeff
550165620Sjeff	tdq->tdq_load--;
551198854Sattilio	if ((td->td_flags & TDF_NOLOAD) == 0)
552177902Sjeff		tdq->tdq_sysload--;
553187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
554262057Savg	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
555110267Sjeff}
556110267Sjeff
557176735Sjeff/*
558176735Sjeff * Set lowpri to its exact value by searching the run-queue and
559176735Sjeff * evaluating curthread.  curthread may be passed as an optimization.
560176735Sjeff */
561176735Sjeffstatic void
562176735Sjefftdq_setlowpri(struct tdq *tdq, struct thread *ctd)
563176735Sjeff{
564176735Sjeff	struct thread *td;
565176735Sjeff
566176735Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
567176735Sjeff	if (ctd == NULL)
568176735Sjeff		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
569177435Sjeff	td = tdq_choose(tdq);
570177435Sjeff	if (td == NULL || td->td_priority > ctd->td_priority)
571176735Sjeff		tdq->tdq_lowpri = ctd->td_priority;
572176735Sjeff	else
573176735Sjeff		tdq->tdq_lowpri = td->td_priority;
574176735Sjeff}
575176735Sjeff
576113357Sjeff#ifdef SMP
577176735Sjeffstruct cpu_search {
578194779Sjeff	cpuset_t cs_mask;
579233599Smav	u_int	cs_prefer;
580233599Smav	int	cs_pri;		/* Min priority for low. */
581233599Smav	int	cs_limit;	/* Max load for low, min load for high. */
582233599Smav	int	cs_cpu;
583233599Smav	int	cs_load;
584176735Sjeff};
585176735Sjeff
586176735Sjeff#define	CPU_SEARCH_LOWEST	0x1
587176735Sjeff#define	CPU_SEARCH_HIGHEST	0x2
588176735Sjeff#define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
589176735Sjeff
590194779Sjeff#define	CPUSET_FOREACH(cpu, mask)				\
591194779Sjeff	for ((cpu) = 0; (cpu) <= mp_maxid; (cpu)++)		\
592222813Sattilio		if (CPU_ISSET(cpu, &mask))
593176735Sjeff
594233599Smavstatic __inline int cpu_search(const struct cpu_group *cg, struct cpu_search *low,
595176735Sjeff    struct cpu_search *high, const int match);
596233599Smavint cpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low);
597233599Smavint cpu_search_highest(const struct cpu_group *cg, struct cpu_search *high);
598233599Smavint cpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
599176735Sjeff    struct cpu_search *high);
600176735Sjeff
601116069Sjeff/*
602176735Sjeff * Search the tree of cpu_groups for the lowest or highest loaded cpu
603176735Sjeff * according to the match argument.  This routine actually compares the
604176735Sjeff * load on all paths through the tree and finds the least loaded cpu on
605176735Sjeff * the least loaded path, which may differ from the least loaded cpu in
606176735Sjeff * the system.  This balances work among caches and busses.
607116069Sjeff *
608176735Sjeff * This inline is instantiated in three forms below using constants for the
609176735Sjeff * match argument.  It is reduced to the minimum set for each case.  It is
610176735Sjeff * also recursive to the depth of the tree.
611116069Sjeff */
612177169Sjhbstatic __inline int
613233599Smavcpu_search(const struct cpu_group *cg, struct cpu_search *low,
614176735Sjeff    struct cpu_search *high, const int match)
615176735Sjeff{
616233599Smav	struct cpu_search lgroup;
617233599Smav	struct cpu_search hgroup;
618233599Smav	cpuset_t cpumask;
619233599Smav	struct cpu_group *child;
620233599Smav	struct tdq *tdq;
621236547Smav	int cpu, i, hload, lload, load, total, rnd, *rndptr;
622176735Sjeff
623176735Sjeff	total = 0;
624233599Smav	cpumask = cg->cg_mask;
625233599Smav	if (match & CPU_SEARCH_LOWEST) {
626233599Smav		lload = INT_MAX;
627233599Smav		lgroup = *low;
628233599Smav	}
629233599Smav	if (match & CPU_SEARCH_HIGHEST) {
630236547Smav		hload = INT_MIN;
631233599Smav		hgroup = *high;
632233599Smav	}
633176735Sjeff
634233599Smav	/* Iterate through the child CPU groups and then remaining CPUs. */
635256208Smav	for (i = cg->cg_children, cpu = mp_maxid; ; ) {
636236547Smav		if (i == 0) {
637256208Smav#ifdef HAVE_INLINE_FFSL
638256208Smav			cpu = CPU_FFS(&cpumask) - 1;
639256208Smav#else
640236547Smav			while (cpu >= 0 && !CPU_ISSET(cpu, &cpumask))
641236547Smav				cpu--;
642256208Smav#endif
643236547Smav			if (cpu < 0)
644233599Smav				break;
645233599Smav			child = NULL;
646233599Smav		} else
647236547Smav			child = &cg->cg_child[i - 1];
648233599Smav
649236547Smav		if (match & CPU_SEARCH_LOWEST)
650236547Smav			lgroup.cs_cpu = -1;
651236547Smav		if (match & CPU_SEARCH_HIGHEST)
652236547Smav			hgroup.cs_cpu = -1;
653233599Smav		if (child) {			/* Handle child CPU group. */
654233599Smav			CPU_NAND(&cpumask, &child->cg_mask);
655176735Sjeff			switch (match) {
656176735Sjeff			case CPU_SEARCH_LOWEST:
657176735Sjeff				load = cpu_search_lowest(child, &lgroup);
658176735Sjeff				break;
659176735Sjeff			case CPU_SEARCH_HIGHEST:
660176735Sjeff				load = cpu_search_highest(child, &hgroup);
661176735Sjeff				break;
662176735Sjeff			case CPU_SEARCH_BOTH:
663176735Sjeff				load = cpu_search_both(child, &lgroup, &hgroup);
664176735Sjeff				break;
665176735Sjeff			}
666233599Smav		} else {			/* Handle child CPU. */
667256208Smav			CPU_CLR(cpu, &cpumask);
668233599Smav			tdq = TDQ_CPU(cpu);
669233599Smav			load = tdq->tdq_load * 256;
670236547Smav			rndptr = DPCPU_PTR(randomval);
671236547Smav			rnd = (*rndptr = *rndptr * 69069 + 5) >> 26;
672233599Smav			if (match & CPU_SEARCH_LOWEST) {
673233599Smav				if (cpu == low->cs_prefer)
674233599Smav					load -= 64;
675233599Smav				/* If that CPU is allowed and get data. */
676236547Smav				if (tdq->tdq_lowpri > lgroup.cs_pri &&
677236547Smav				    tdq->tdq_load <= lgroup.cs_limit &&
678236547Smav				    CPU_ISSET(cpu, &lgroup.cs_mask)) {
679233599Smav					lgroup.cs_cpu = cpu;
680233599Smav					lgroup.cs_load = load - rnd;
681176735Sjeff				}
682233599Smav			}
683233599Smav			if (match & CPU_SEARCH_HIGHEST)
684236547Smav				if (tdq->tdq_load >= hgroup.cs_limit &&
685236547Smav				    tdq->tdq_transferable &&
686236547Smav				    CPU_ISSET(cpu, &hgroup.cs_mask)) {
687233599Smav					hgroup.cs_cpu = cpu;
688233599Smav					hgroup.cs_load = load - rnd;
689176735Sjeff				}
690176735Sjeff		}
691233599Smav		total += load;
692176735Sjeff
693233599Smav		/* We have info about child item. Compare it. */
694233599Smav		if (match & CPU_SEARCH_LOWEST) {
695236547Smav			if (lgroup.cs_cpu >= 0 &&
696233599Smav			    (load < lload ||
697233599Smav			     (load == lload && lgroup.cs_load < low->cs_load))) {
698233599Smav				lload = load;
699233599Smav				low->cs_cpu = lgroup.cs_cpu;
700233599Smav				low->cs_load = lgroup.cs_load;
701233599Smav			}
702233599Smav		}
703233599Smav		if (match & CPU_SEARCH_HIGHEST)
704236547Smav			if (hgroup.cs_cpu >= 0 &&
705233599Smav			    (load > hload ||
706233599Smav			     (load == hload && hgroup.cs_load > high->cs_load))) {
707233599Smav				hload = load;
708233599Smav				high->cs_cpu = hgroup.cs_cpu;
709233599Smav				high->cs_load = hgroup.cs_load;
710233599Smav			}
711236547Smav		if (child) {
712236547Smav			i--;
713236547Smav			if (i == 0 && CPU_EMPTY(&cpumask))
714236547Smav				break;
715256208Smav		}
716256208Smav#ifndef HAVE_INLINE_FFSL
717256208Smav		else
718236547Smav			cpu--;
719256208Smav#endif
720176735Sjeff	}
721176735Sjeff	return (total);
722176735Sjeff}
723176735Sjeff
724176735Sjeff/*
725176735Sjeff * cpu_search instantiations must pass constants to maintain the inline
726176735Sjeff * optimization.
727176735Sjeff */
728176735Sjeffint
729233599Smavcpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low)
730176735Sjeff{
731176735Sjeff	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
732176735Sjeff}
733176735Sjeff
734176735Sjeffint
735233599Smavcpu_search_highest(const struct cpu_group *cg, struct cpu_search *high)
736176735Sjeff{
737176735Sjeff	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
738176735Sjeff}
739176735Sjeff
740176735Sjeffint
741233599Smavcpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
742176735Sjeff    struct cpu_search *high)
743176735Sjeff{
744176735Sjeff	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
745176735Sjeff}
746176735Sjeff
747176735Sjeff/*
748176735Sjeff * Find the cpu with the least load via the least loaded path that has a
749176735Sjeff * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
750176735Sjeff * acceptable.
751176735Sjeff */
752176735Sjeffstatic inline int
753233599Smavsched_lowest(const struct cpu_group *cg, cpuset_t mask, int pri, int maxload,
754233599Smav    int prefer)
755176735Sjeff{
756176735Sjeff	struct cpu_search low;
757176735Sjeff
758176735Sjeff	low.cs_cpu = -1;
759233599Smav	low.cs_prefer = prefer;
760176735Sjeff	low.cs_mask = mask;
761233599Smav	low.cs_pri = pri;
762233599Smav	low.cs_limit = maxload;
763176735Sjeff	cpu_search_lowest(cg, &low);
764176735Sjeff	return low.cs_cpu;
765176735Sjeff}
766176735Sjeff
767176735Sjeff/*
768176735Sjeff * Find the cpu with the highest load via the highest loaded path.
769176735Sjeff */
770176735Sjeffstatic inline int
771233599Smavsched_highest(const struct cpu_group *cg, cpuset_t mask, int minload)
772176735Sjeff{
773176735Sjeff	struct cpu_search high;
774176735Sjeff
775176735Sjeff	high.cs_cpu = -1;
776176735Sjeff	high.cs_mask = mask;
777176735Sjeff	high.cs_limit = minload;
778176735Sjeff	cpu_search_highest(cg, &high);
779176735Sjeff	return high.cs_cpu;
780176735Sjeff}
781176735Sjeff
782121790Sjeffstatic void
783176735Sjeffsched_balance_group(struct cpu_group *cg)
784116069Sjeff{
785233599Smav	cpuset_t hmask, lmask;
786233599Smav	int high, low, anylow;
787123487Sjeff
788233599Smav	CPU_FILL(&hmask);
789176735Sjeff	for (;;) {
790233599Smav		high = sched_highest(cg, hmask, 1);
791233599Smav		/* Stop if there is no more CPU with transferrable threads. */
792233599Smav		if (high == -1)
793176735Sjeff			break;
794233599Smav		CPU_CLR(high, &hmask);
795233599Smav		CPU_COPY(&hmask, &lmask);
796233599Smav		/* Stop if there is no more CPU left for low. */
797233599Smav		if (CPU_EMPTY(&lmask))
798176735Sjeff			break;
799233599Smav		anylow = 1;
800233599Smavnextlow:
801233599Smav		low = sched_lowest(cg, lmask, -1,
802233599Smav		    TDQ_CPU(high)->tdq_load - 1, high);
803233599Smav		/* Stop if we looked well and found no less loaded CPU. */
804233599Smav		if (anylow && low == -1)
805233599Smav			break;
806233599Smav		/* Go to next high if we found no less loaded CPU. */
807233599Smav		if (low == -1)
808233599Smav			continue;
809233599Smav		/* Transfer thread from high to low. */
810233599Smav		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low))) {
811233599Smav			/* CPU that got thread can no longer be a donor. */
812233599Smav			CPU_CLR(low, &hmask);
813233599Smav		} else {
814233599Smav			/*
815233599Smav			 * If failed, then there is no threads on high
816233599Smav			 * that can run on this low. Drop low from low
817233599Smav			 * mask and look for different one.
818233599Smav			 */
819233599Smav			CPU_CLR(low, &lmask);
820233599Smav			anylow = 0;
821233599Smav			goto nextlow;
822233599Smav		}
823123487Sjeff	}
824123487Sjeff}
825123487Sjeff
826123487Sjeffstatic void
827201148Sedsched_balance(void)
828123487Sjeff{
829172409Sjeff	struct tdq *tdq;
830123487Sjeff
831172409Sjeff	/*
832172409Sjeff	 * Select a random time between .5 * balance_interval and
833172409Sjeff	 * 1.5 * balance_interval.
834172409Sjeff	 */
835176735Sjeff	balance_ticks = max(balance_interval / 2, 1);
836176735Sjeff	balance_ticks += random() % balance_interval;
837171482Sjeff	if (smp_started == 0 || rebalance == 0)
838171482Sjeff		return;
839172409Sjeff	tdq = TDQ_SELF();
840172409Sjeff	TDQ_UNLOCK(tdq);
841176735Sjeff	sched_balance_group(cpu_top);
842172409Sjeff	TDQ_LOCK(tdq);
843123487Sjeff}
844123487Sjeff
845171482Sjeff/*
846171482Sjeff * Lock two thread queues using their address to maintain lock order.
847171482Sjeff */
848123487Sjeffstatic void
849171482Sjefftdq_lock_pair(struct tdq *one, struct tdq *two)
850171482Sjeff{
851171482Sjeff	if (one < two) {
852171482Sjeff		TDQ_LOCK(one);
853171482Sjeff		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
854171482Sjeff	} else {
855171482Sjeff		TDQ_LOCK(two);
856171482Sjeff		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
857171482Sjeff	}
858171482Sjeff}
859171482Sjeff
860171482Sjeff/*
861172409Sjeff * Unlock two thread queues.  Order is not important here.
862172409Sjeff */
863172409Sjeffstatic void
864172409Sjefftdq_unlock_pair(struct tdq *one, struct tdq *two)
865172409Sjeff{
866172409Sjeff	TDQ_UNLOCK(one);
867172409Sjeff	TDQ_UNLOCK(two);
868172409Sjeff}
869172409Sjeff
870172409Sjeff/*
871171482Sjeff * Transfer load between two imbalanced thread queues.
872171482Sjeff */
873176735Sjeffstatic int
874164936Sjuliansched_balance_pair(struct tdq *high, struct tdq *low)
875123487Sjeff{
876176735Sjeff	int moved;
877230691Smarius	int cpu;
878116069Sjeff
879171482Sjeff	tdq_lock_pair(high, low);
880176735Sjeff	moved = 0;
881116069Sjeff	/*
882122744Sjeff	 * Determine what the imbalance is and then adjust that to how many
883165620Sjeff	 * threads we actually have to give up (transferable).
884122744Sjeff	 */
885233599Smav	if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load &&
886233599Smav	    (moved = tdq_move(high, low)) > 0) {
887172293Sjeff		/*
888230691Smarius		 * In case the target isn't the current cpu IPI it to force a
889230691Smarius		 * reschedule with the new workload.
890172293Sjeff		 */
891230691Smarius		cpu = TDQ_ID(low);
892230691Smarius		sched_pin();
893230691Smarius		if (cpu != PCPU_GET(cpuid))
894230691Smarius			ipi_cpu(cpu, IPI_PREEMPT);
895230691Smarius		sched_unpin();
896171482Sjeff	}
897172409Sjeff	tdq_unlock_pair(high, low);
898176735Sjeff	return (moved);
899116069Sjeff}
900116069Sjeff
901171482Sjeff/*
902171482Sjeff * Move a thread from one thread queue to another.
903171482Sjeff */
904176735Sjeffstatic int
905171482Sjefftdq_move(struct tdq *from, struct tdq *to)
906116069Sjeff{
907171482Sjeff	struct td_sched *ts;
908171482Sjeff	struct thread *td;
909164936Sjulian	struct tdq *tdq;
910171482Sjeff	int cpu;
911116069Sjeff
912172409Sjeff	TDQ_LOCK_ASSERT(from, MA_OWNED);
913172409Sjeff	TDQ_LOCK_ASSERT(to, MA_OWNED);
914172409Sjeff
915164936Sjulian	tdq = from;
916171482Sjeff	cpu = TDQ_ID(to);
917177435Sjeff	td = tdq_steal(tdq, cpu);
918177435Sjeff	if (td == NULL)
919176735Sjeff		return (0);
920177435Sjeff	ts = td->td_sched;
921171482Sjeff	/*
922171482Sjeff	 * Although the run queue is locked the thread may be blocked.  Lock
923172409Sjeff	 * it to clear this and acquire the run-queue lock.
924171482Sjeff	 */
925171482Sjeff	thread_lock(td);
926172409Sjeff	/* Drop recursive lock on from acquired via thread_lock(). */
927171482Sjeff	TDQ_UNLOCK(from);
928171482Sjeff	sched_rem(td);
929166108Sjeff	ts->ts_cpu = cpu;
930171482Sjeff	td->td_lock = TDQ_LOCKPTR(to);
931171482Sjeff	tdq_add(to, td, SRQ_YIELDING);
932176735Sjeff	return (1);
933116069Sjeff}
934110267Sjeff
935171482Sjeff/*
936171482Sjeff * This tdq has idled.  Try to steal a thread from another cpu and switch
937171482Sjeff * to it.
938171482Sjeff */
939123433Sjeffstatic int
940164936Sjuliantdq_idled(struct tdq *tdq)
941121790Sjeff{
942176735Sjeff	struct cpu_group *cg;
943164936Sjulian	struct tdq *steal;
944194779Sjeff	cpuset_t mask;
945176735Sjeff	int thresh;
946171482Sjeff	int cpu;
947123433Sjeff
948172484Sjeff	if (smp_started == 0 || steal_idle == 0)
949172484Sjeff		return (1);
950194779Sjeff	CPU_FILL(&mask);
951194779Sjeff	CPU_CLR(PCPU_GET(cpuid), &mask);
952176735Sjeff	/* We don't want to be preempted while we're iterating. */
953171482Sjeff	spinlock_enter();
954176735Sjeff	for (cg = tdq->tdq_cg; cg != NULL; ) {
955191643Sjeff		if ((cg->cg_flags & CG_FLAG_THREAD) == 0)
956176735Sjeff			thresh = steal_thresh;
957176735Sjeff		else
958176735Sjeff			thresh = 1;
959176735Sjeff		cpu = sched_highest(cg, mask, thresh);
960176735Sjeff		if (cpu == -1) {
961176735Sjeff			cg = cg->cg_parent;
962176735Sjeff			continue;
963166108Sjeff		}
964176735Sjeff		steal = TDQ_CPU(cpu);
965194779Sjeff		CPU_CLR(cpu, &mask);
966176735Sjeff		tdq_lock_pair(tdq, steal);
967176735Sjeff		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
968176735Sjeff			tdq_unlock_pair(tdq, steal);
969176735Sjeff			continue;
970171482Sjeff		}
971176735Sjeff		/*
972176735Sjeff		 * If a thread was added while interrupts were disabled don't
973176735Sjeff		 * steal one here.  If we fail to acquire one due to affinity
974176735Sjeff		 * restrictions loop again with this cpu removed from the
975176735Sjeff		 * set.
976176735Sjeff		 */
977176735Sjeff		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
978176735Sjeff			tdq_unlock_pair(tdq, steal);
979176735Sjeff			continue;
980176735Sjeff		}
981176735Sjeff		spinlock_exit();
982176735Sjeff		TDQ_UNLOCK(steal);
983178272Sjeff		mi_switch(SW_VOL | SWT_IDLE, NULL);
984176735Sjeff		thread_unlock(curthread);
985176735Sjeff
986176735Sjeff		return (0);
987123433Sjeff	}
988171482Sjeff	spinlock_exit();
989123433Sjeff	return (1);
990121790Sjeff}
991121790Sjeff
992171482Sjeff/*
993171482Sjeff * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
994171482Sjeff */
995121790Sjeffstatic void
996177435Sjefftdq_notify(struct tdq *tdq, struct thread *td)
997121790Sjeff{
998185047Sjhb	struct thread *ctd;
999166247Sjeff	int pri;
1000166108Sjeff	int cpu;
1001121790Sjeff
1002177005Sjeff	if (tdq->tdq_ipipending)
1003177005Sjeff		return;
1004177435Sjeff	cpu = td->td_sched->ts_cpu;
1005177435Sjeff	pri = td->td_priority;
1006185047Sjhb	ctd = pcpu_find(cpu)->pc_curthread;
1007185047Sjhb	if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
1008166137Sjeff		return;
1009185047Sjhb	if (TD_IS_IDLETHREAD(ctd)) {
1010178277Sjeff		/*
1011178471Sjeff		 * If the MD code has an idle wakeup routine try that before
1012178471Sjeff		 * falling back to IPI.
1013178471Sjeff		 */
1014212416Smav		if (!tdq->tdq_cpu_idle || cpu_idle_wakeup(cpu))
1015178471Sjeff			return;
1016178277Sjeff	}
1017177005Sjeff	tdq->tdq_ipipending = 1;
1018210939Sjhb	ipi_cpu(cpu, IPI_PREEMPT);
1019121790Sjeff}
1020121790Sjeff
1021171482Sjeff/*
1022171482Sjeff * Steals load from a timeshare queue.  Honors the rotating queue head
1023171482Sjeff * index.
1024171482Sjeff */
1025177435Sjeffstatic struct thread *
1026176735Sjeffrunq_steal_from(struct runq *rq, int cpu, u_char start)
1027171482Sjeff{
1028171482Sjeff	struct rqbits *rqb;
1029171482Sjeff	struct rqhead *rqh;
1030233599Smav	struct thread *td, *first;
1031171482Sjeff	int bit;
1032171482Sjeff	int pri;
1033171482Sjeff	int i;
1034171482Sjeff
1035171482Sjeff	rqb = &rq->rq_status;
1036171482Sjeff	bit = start & (RQB_BPW -1);
1037171482Sjeff	pri = 0;
1038233599Smav	first = NULL;
1039171482Sjeffagain:
1040171482Sjeff	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1041171482Sjeff		if (rqb->rqb_bits[i] == 0)
1042171482Sjeff			continue;
1043171482Sjeff		if (bit != 0) {
1044171482Sjeff			for (pri = bit; pri < RQB_BPW; pri++)
1045171482Sjeff				if (rqb->rqb_bits[i] & (1ul << pri))
1046171482Sjeff					break;
1047171482Sjeff			if (pri >= RQB_BPW)
1048171482Sjeff				continue;
1049171482Sjeff		} else
1050171482Sjeff			pri = RQB_FFS(rqb->rqb_bits[i]);
1051171482Sjeff		pri += (i << RQB_L2BPW);
1052171482Sjeff		rqh = &rq->rq_queues[pri];
1053177435Sjeff		TAILQ_FOREACH(td, rqh, td_runq) {
1054177435Sjeff			if (first && THREAD_CAN_MIGRATE(td) &&
1055177435Sjeff			    THREAD_CAN_SCHED(td, cpu))
1056177435Sjeff				return (td);
1057233599Smav			first = td;
1058171482Sjeff		}
1059171482Sjeff	}
1060171482Sjeff	if (start != 0) {
1061171482Sjeff		start = 0;
1062171482Sjeff		goto again;
1063171482Sjeff	}
1064171482Sjeff
1065233599Smav	if (first && THREAD_CAN_MIGRATE(first) &&
1066233599Smav	    THREAD_CAN_SCHED(first, cpu))
1067233599Smav		return (first);
1068171482Sjeff	return (NULL);
1069171482Sjeff}
1070171482Sjeff
1071171482Sjeff/*
1072171482Sjeff * Steals load from a standard linear queue.
1073171482Sjeff */
1074177435Sjeffstatic struct thread *
1075176735Sjeffrunq_steal(struct runq *rq, int cpu)
1076121790Sjeff{
1077121790Sjeff	struct rqhead *rqh;
1078121790Sjeff	struct rqbits *rqb;
1079177435Sjeff	struct thread *td;
1080121790Sjeff	int word;
1081121790Sjeff	int bit;
1082121790Sjeff
1083121790Sjeff	rqb = &rq->rq_status;
1084121790Sjeff	for (word = 0; word < RQB_LEN; word++) {
1085121790Sjeff		if (rqb->rqb_bits[word] == 0)
1086121790Sjeff			continue;
1087121790Sjeff		for (bit = 0; bit < RQB_BPW; bit++) {
1088123231Speter			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
1089121790Sjeff				continue;
1090121790Sjeff			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
1091177435Sjeff			TAILQ_FOREACH(td, rqh, td_runq)
1092177435Sjeff				if (THREAD_CAN_MIGRATE(td) &&
1093177435Sjeff				    THREAD_CAN_SCHED(td, cpu))
1094177435Sjeff					return (td);
1095121790Sjeff		}
1096121790Sjeff	}
1097121790Sjeff	return (NULL);
1098121790Sjeff}
1099121790Sjeff
1100171482Sjeff/*
1101171482Sjeff * Attempt to steal a thread in priority order from a thread queue.
1102171482Sjeff */
1103177435Sjeffstatic struct thread *
1104176735Sjefftdq_steal(struct tdq *tdq, int cpu)
1105121790Sjeff{
1106177435Sjeff	struct thread *td;
1107121790Sjeff
1108171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1109177435Sjeff	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
1110177435Sjeff		return (td);
1111177435Sjeff	if ((td = runq_steal_from(&tdq->tdq_timeshare,
1112177435Sjeff	    cpu, tdq->tdq_ridx)) != NULL)
1113177435Sjeff		return (td);
1114176735Sjeff	return (runq_steal(&tdq->tdq_idle, cpu));
1115121790Sjeff}
1116123433Sjeff
1117171482Sjeff/*
1118171482Sjeff * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
1119172409Sjeff * current lock and returns with the assigned queue locked.
1120171482Sjeff */
1121171482Sjeffstatic inline struct tdq *
1122177435Sjeffsched_setcpu(struct thread *td, int cpu, int flags)
1123123433Sjeff{
1124177435Sjeff
1125171482Sjeff	struct tdq *tdq;
1126123433Sjeff
1127177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1128171482Sjeff	tdq = TDQ_CPU(cpu);
1129177435Sjeff	td->td_sched->ts_cpu = cpu;
1130177435Sjeff	/*
1131177435Sjeff	 * If the lock matches just return the queue.
1132177435Sjeff	 */
1133171482Sjeff	if (td->td_lock == TDQ_LOCKPTR(tdq))
1134171482Sjeff		return (tdq);
1135171482Sjeff#ifdef notyet
1136123433Sjeff	/*
1137172293Sjeff	 * If the thread isn't running its lockptr is a
1138171482Sjeff	 * turnstile or a sleepqueue.  We can just lock_set without
1139171482Sjeff	 * blocking.
1140123685Sjeff	 */
1141171482Sjeff	if (TD_CAN_RUN(td)) {
1142171482Sjeff		TDQ_LOCK(tdq);
1143171482Sjeff		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1144171482Sjeff		return (tdq);
1145171482Sjeff	}
1146171482Sjeff#endif
1147166108Sjeff	/*
1148171482Sjeff	 * The hard case, migration, we need to block the thread first to
1149171482Sjeff	 * prevent order reversals with other cpus locks.
1150166108Sjeff	 */
1151202889Sattilio	spinlock_enter();
1152171482Sjeff	thread_lock_block(td);
1153171482Sjeff	TDQ_LOCK(tdq);
1154171713Sjeff	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1155202889Sattilio	spinlock_exit();
1156171482Sjeff	return (tdq);
1157166108Sjeff}
1158166108Sjeff
1159178272SjeffSCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
1160178272SjeffSCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
1161178272SjeffSCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
1162178272SjeffSCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
1163178272SjeffSCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
1164178272SjeffSCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
1165178272Sjeff
1166166108Sjeffstatic int
1167177435Sjeffsched_pickcpu(struct thread *td, int flags)
1168171482Sjeff{
1169233599Smav	struct cpu_group *cg, *ccg;
1170177435Sjeff	struct td_sched *ts;
1171171482Sjeff	struct tdq *tdq;
1172194779Sjeff	cpuset_t mask;
1173233599Smav	int cpu, pri, self;
1174166108Sjeff
1175176735Sjeff	self = PCPU_GET(cpuid);
1176177435Sjeff	ts = td->td_sched;
1177166108Sjeff	if (smp_started == 0)
1178166108Sjeff		return (self);
1179171506Sjeff	/*
1180171506Sjeff	 * Don't migrate a running thread from sched_switch().
1181171506Sjeff	 */
1182176735Sjeff	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1183176735Sjeff		return (ts->ts_cpu);
1184166108Sjeff	/*
1185176735Sjeff	 * Prefer to run interrupt threads on the processors that generate
1186176735Sjeff	 * the interrupt.
1187166108Sjeff	 */
1188233599Smav	pri = td->td_priority;
1189176735Sjeff	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1190178272Sjeff	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
1191178272Sjeff		SCHED_STAT_INC(pickcpu_intrbind);
1192176735Sjeff		ts->ts_cpu = self;
1193233599Smav		if (TDQ_CPU(self)->tdq_lowpri > pri) {
1194233599Smav			SCHED_STAT_INC(pickcpu_affinity);
1195233599Smav			return (ts->ts_cpu);
1196233599Smav		}
1197178272Sjeff	}
1198166108Sjeff	/*
1199176735Sjeff	 * If the thread can run on the last cpu and the affinity has not
1200176735Sjeff	 * expired or it is idle run it there.
1201166108Sjeff	 */
1202176735Sjeff	tdq = TDQ_CPU(ts->ts_cpu);
1203233599Smav	cg = tdq->tdq_cg;
1204233599Smav	if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
1205233599Smav	    tdq->tdq_lowpri >= PRI_MIN_IDLE &&
1206233599Smav	    SCHED_AFFINITY(ts, CG_SHARE_L2)) {
1207233599Smav		if (cg->cg_flags & CG_FLAG_THREAD) {
1208233599Smav			CPUSET_FOREACH(cpu, cg->cg_mask) {
1209233599Smav				if (TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE)
1210233599Smav					break;
1211233599Smav			}
1212233599Smav		} else
1213233599Smav			cpu = INT_MAX;
1214233599Smav		if (cpu > mp_maxid) {
1215178272Sjeff			SCHED_STAT_INC(pickcpu_idle_affinity);
1216176735Sjeff			return (ts->ts_cpu);
1217178272Sjeff		}
1218139334Sjeff	}
1219123433Sjeff	/*
1220233599Smav	 * Search for the last level cache CPU group in the tree.
1221233599Smav	 * Skip caches with expired affinity time and SMT groups.
1222233599Smav	 * Affinity to higher level caches will be handled less aggressively.
1223123433Sjeff	 */
1224233599Smav	for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
1225233599Smav		if (cg->cg_flags & CG_FLAG_THREAD)
1226233599Smav			continue;
1227233599Smav		if (!SCHED_AFFINITY(ts, cg->cg_level))
1228233599Smav			continue;
1229233599Smav		ccg = cg;
1230233599Smav	}
1231233599Smav	if (ccg != NULL)
1232233599Smav		cg = ccg;
1233176735Sjeff	cpu = -1;
1234233599Smav	/* Search the group for the less loaded idle CPU we can run now. */
1235194779Sjeff	mask = td->td_cpuset->cs_mask;
1236233599Smav	if (cg != NULL && cg != cpu_top &&
1237233599Smav	    CPU_CMP(&cg->cg_mask, &cpu_top->cg_mask) != 0)
1238233599Smav		cpu = sched_lowest(cg, mask, max(pri, PRI_MAX_TIMESHARE),
1239233599Smav		    INT_MAX, ts->ts_cpu);
1240233599Smav	/* Search globally for the less loaded CPU we can run now. */
1241176735Sjeff	if (cpu == -1)
1242233599Smav		cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu);
1243233599Smav	/* Search globally for the less loaded CPU. */
1244233599Smav	if (cpu == -1)
1245233599Smav		cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu);
1246233599Smav	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1247171506Sjeff	/*
1248176735Sjeff	 * Compare the lowest loaded cpu to current cpu.
1249171506Sjeff	 */
1250177005Sjeff	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
1251233599Smav	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE &&
1252233599Smav	    TDQ_CPU(self)->tdq_load <= TDQ_CPU(cpu)->tdq_load + 1) {
1253178272Sjeff		SCHED_STAT_INC(pickcpu_local);
1254177005Sjeff		cpu = self;
1255178272Sjeff	} else
1256178272Sjeff		SCHED_STAT_INC(pickcpu_lowest);
1257178272Sjeff	if (cpu != ts->ts_cpu)
1258178272Sjeff		SCHED_STAT_INC(pickcpu_migration);
1259171482Sjeff	return (cpu);
1260123433Sjeff}
1261176735Sjeff#endif
1262123433Sjeff
1263117326Sjeff/*
1264121790Sjeff * Pick the highest priority task we have and return it.
1265117326Sjeff */
1266177435Sjeffstatic struct thread *
1267164936Sjuliantdq_choose(struct tdq *tdq)
1268110267Sjeff{
1269177435Sjeff	struct thread *td;
1270110267Sjeff
1271171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1272177435Sjeff	td = runq_choose(&tdq->tdq_realtime);
1273177435Sjeff	if (td != NULL)
1274177435Sjeff		return (td);
1275177435Sjeff	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1276177435Sjeff	if (td != NULL) {
1277217351Sjhb		KASSERT(td->td_priority >= PRI_MIN_BATCH,
1278165762Sjeff		    ("tdq_choose: Invalid priority on timeshare queue %d",
1279177435Sjeff		    td->td_priority));
1280177435Sjeff		return (td);
1281165762Sjeff	}
1282177435Sjeff	td = runq_choose(&tdq->tdq_idle);
1283177435Sjeff	if (td != NULL) {
1284177435Sjeff		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1285165762Sjeff		    ("tdq_choose: Invalid priority on idle queue %d",
1286177435Sjeff		    td->td_priority));
1287177435Sjeff		return (td);
1288165762Sjeff	}
1289165762Sjeff
1290165762Sjeff	return (NULL);
1291110267Sjeff}
1292110267Sjeff
1293171482Sjeff/*
1294171482Sjeff * Initialize a thread queue.
1295171482Sjeff */
1296109864Sjeffstatic void
1297164936Sjuliantdq_setup(struct tdq *tdq)
1298110028Sjeff{
1299171482Sjeff
1300171713Sjeff	if (bootverbose)
1301171713Sjeff		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1302165762Sjeff	runq_init(&tdq->tdq_realtime);
1303165762Sjeff	runq_init(&tdq->tdq_timeshare);
1304165620Sjeff	runq_init(&tdq->tdq_idle);
1305176735Sjeff	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1306176735Sjeff	    "sched lock %d", (int)TDQ_ID(tdq));
1307176735Sjeff	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1308176735Sjeff	    MTX_SPIN | MTX_RECURSE);
1309187357Sjeff#ifdef KTR
1310187357Sjeff	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
1311187357Sjeff	    "CPU %d load", (int)TDQ_ID(tdq));
1312187357Sjeff#endif
1313110028Sjeff}
1314110028Sjeff
1315171713Sjeff#ifdef SMP
1316110028Sjeffstatic void
1317171713Sjeffsched_setup_smp(void)
1318171713Sjeff{
1319171713Sjeff	struct tdq *tdq;
1320171713Sjeff	int i;
1321171713Sjeff
1322176735Sjeff	cpu_top = smp_topo();
1323209059Sjhb	CPU_FOREACH(i) {
1324176735Sjeff		tdq = TDQ_CPU(i);
1325171713Sjeff		tdq_setup(tdq);
1326176735Sjeff		tdq->tdq_cg = smp_topo_find(cpu_top, i);
1327176735Sjeff		if (tdq->tdq_cg == NULL)
1328176735Sjeff			panic("Can't find cpu group for %d\n", i);
1329123433Sjeff	}
1330176735Sjeff	balance_tdq = TDQ_SELF();
1331176735Sjeff	sched_balance();
1332171713Sjeff}
1333171713Sjeff#endif
1334171713Sjeff
1335171713Sjeff/*
1336171713Sjeff * Setup the thread queues and initialize the topology based on MD
1337171713Sjeff * information.
1338171713Sjeff */
1339171713Sjeffstatic void
1340171713Sjeffsched_setup(void *dummy)
1341171713Sjeff{
1342171713Sjeff	struct tdq *tdq;
1343171713Sjeff
1344171713Sjeff	tdq = TDQ_SELF();
1345171713Sjeff#ifdef SMP
1346176734Sjeff	sched_setup_smp();
1347117237Sjeff#else
1348171713Sjeff	tdq_setup(tdq);
1349116069Sjeff#endif
1350171482Sjeff
1351171482Sjeff	/* Add thread0's load since it's running. */
1352171482Sjeff	TDQ_LOCK(tdq);
1353171713Sjeff	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1354177435Sjeff	tdq_load_add(tdq, &thread0);
1355176735Sjeff	tdq->tdq_lowpri = thread0.td_priority;
1356171482Sjeff	TDQ_UNLOCK(tdq);
1357109864Sjeff}
1358109864Sjeff
1359171482Sjeff/*
1360241249Smav * This routine determines time constants after stathz and hz are setup.
1361171482Sjeff */
1362153533Sdavidxu/* ARGSUSED */
1363153533Sdavidxustatic void
1364153533Sdavidxusched_initticks(void *dummy)
1365153533Sdavidxu{
1366171482Sjeff	int incr;
1367171482Sjeff
1368153533Sdavidxu	realstathz = stathz ? stathz : hz;
1369241249Smav	sched_slice = realstathz / 10;	/* ~100ms */
1370241249Smav	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
1371241249Smav	    realstathz);
1372153533Sdavidxu
1373153533Sdavidxu	/*
1374165762Sjeff	 * tickincr is shifted out by 10 to avoid rounding errors due to
1375165766Sjeff	 * hz not being evenly divisible by stathz on all platforms.
1376153533Sdavidxu	 */
1377171482Sjeff	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1378165762Sjeff	/*
1379165762Sjeff	 * This does not work for values of stathz that are more than
1380165762Sjeff	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1381165762Sjeff	 */
1382171482Sjeff	if (incr == 0)
1383171482Sjeff		incr = 1;
1384171482Sjeff	tickincr = incr;
1385166108Sjeff#ifdef SMP
1386171899Sjeff	/*
1387172409Sjeff	 * Set the default balance interval now that we know
1388172409Sjeff	 * what realstathz is.
1389172409Sjeff	 */
1390172409Sjeff	balance_interval = realstathz;
1391166108Sjeff	affinity = SCHED_AFFINITY_DEFAULT;
1392166108Sjeff#endif
1393236546Smav	if (sched_idlespinthresh < 0)
1394247150Smav		sched_idlespinthresh = 2 * max(10000, 6 * hz) / realstathz;
1395153533Sdavidxu}
1396153533Sdavidxu
1397153533Sdavidxu
1398109864Sjeff/*
1399171482Sjeff * This is the core of the interactivity algorithm.  Determines a score based
1400171482Sjeff * on past behavior.  It is the ratio of sleep time to run time scaled to
1401171482Sjeff * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1402171482Sjeff * differs from the cpu usage because it does not account for time spent
1403171482Sjeff * waiting on a run-queue.  Would be prettier if we had floating point.
1404171482Sjeff */
1405171482Sjeffstatic int
1406171482Sjeffsched_interact_score(struct thread *td)
1407171482Sjeff{
1408171482Sjeff	struct td_sched *ts;
1409171482Sjeff	int div;
1410171482Sjeff
1411171482Sjeff	ts = td->td_sched;
1412171482Sjeff	/*
1413171482Sjeff	 * The score is only needed if this is likely to be an interactive
1414171482Sjeff	 * task.  Don't go through the expense of computing it if there's
1415171482Sjeff	 * no chance.
1416171482Sjeff	 */
1417171482Sjeff	if (sched_interact <= SCHED_INTERACT_HALF &&
1418171482Sjeff		ts->ts_runtime >= ts->ts_slptime)
1419171482Sjeff			return (SCHED_INTERACT_HALF);
1420171482Sjeff
1421171482Sjeff	if (ts->ts_runtime > ts->ts_slptime) {
1422171482Sjeff		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1423171482Sjeff		return (SCHED_INTERACT_HALF +
1424171482Sjeff		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1425171482Sjeff	}
1426171482Sjeff	if (ts->ts_slptime > ts->ts_runtime) {
1427171482Sjeff		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1428171482Sjeff		return (ts->ts_runtime / div);
1429171482Sjeff	}
1430171482Sjeff	/* runtime == slptime */
1431171482Sjeff	if (ts->ts_runtime)
1432171482Sjeff		return (SCHED_INTERACT_HALF);
1433171482Sjeff
1434171482Sjeff	/*
1435171482Sjeff	 * This can happen if slptime and runtime are 0.
1436171482Sjeff	 */
1437171482Sjeff	return (0);
1438171482Sjeff
1439171482Sjeff}
1440171482Sjeff
1441171482Sjeff/*
1442109864Sjeff * Scale the scheduling priority according to the "interactivity" of this
1443109864Sjeff * process.
1444109864Sjeff */
1445113357Sjeffstatic void
1446163709Sjbsched_priority(struct thread *td)
1447109864Sjeff{
1448165762Sjeff	int score;
1449109864Sjeff	int pri;
1450109864Sjeff
1451217291Sjhb	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
1452113357Sjeff		return;
1453112966Sjeff	/*
1454165762Sjeff	 * If the score is interactive we place the thread in the realtime
1455165762Sjeff	 * queue with a priority that is less than kernel and interrupt
1456165762Sjeff	 * priorities.  These threads are not subject to nice restrictions.
1457112966Sjeff	 *
1458171482Sjeff	 * Scores greater than this are placed on the normal timeshare queue
1459165762Sjeff	 * where the priority is partially decided by the most recent cpu
1460165762Sjeff	 * utilization and the rest is decided by nice value.
1461172293Sjeff	 *
1462172293Sjeff	 * The nice value of the process has a linear effect on the calculated
1463172293Sjeff	 * score.  Negative nice values make it easier for a thread to be
1464172293Sjeff	 * considered interactive.
1465112966Sjeff	 */
1466198126Sjhb	score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1467165762Sjeff	if (score < sched_interact) {
1468217351Sjhb		pri = PRI_MIN_INTERACT;
1469217351Sjhb		pri += ((PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) /
1470217237Sjhb		    sched_interact) * score;
1471217351Sjhb		KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
1472166208Sjeff		    ("sched_priority: invalid interactive priority %d score %d",
1473166208Sjeff		    pri, score));
1474165762Sjeff	} else {
1475165762Sjeff		pri = SCHED_PRI_MIN;
1476165762Sjeff		if (td->td_sched->ts_ticks)
1477230083Sjhb			pri += min(SCHED_PRI_TICKS(td->td_sched),
1478259835Sjhb			    SCHED_PRI_RANGE - 1);
1479165762Sjeff		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1480217351Sjhb		KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
1481171482Sjeff		    ("sched_priority: invalid priority %d: nice %d, "
1482171482Sjeff		    "ticks %d ftick %d ltick %d tick pri %d",
1483171482Sjeff		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1484171482Sjeff		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1485171482Sjeff		    SCHED_PRI_TICKS(td->td_sched)));
1486165762Sjeff	}
1487165762Sjeff	sched_user_prio(td, pri);
1488112966Sjeff
1489112966Sjeff	return;
1490109864Sjeff}
1491109864Sjeff
1492121868Sjeff/*
1493121868Sjeff * This routine enforces a maximum limit on the amount of scheduling history
1494171482Sjeff * kept.  It is called after either the slptime or runtime is adjusted.  This
1495171482Sjeff * function is ugly due to integer math.
1496121868Sjeff */
1497116463Sjeffstatic void
1498163709Sjbsched_interact_update(struct thread *td)
1499116463Sjeff{
1500165819Sjeff	struct td_sched *ts;
1501166208Sjeff	u_int sum;
1502121605Sjeff
1503165819Sjeff	ts = td->td_sched;
1504171482Sjeff	sum = ts->ts_runtime + ts->ts_slptime;
1505121868Sjeff	if (sum < SCHED_SLP_RUN_MAX)
1506121868Sjeff		return;
1507121868Sjeff	/*
1508165819Sjeff	 * This only happens from two places:
1509165819Sjeff	 * 1) We have added an unusual amount of run time from fork_exit.
1510165819Sjeff	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1511165819Sjeff	 */
1512165819Sjeff	if (sum > SCHED_SLP_RUN_MAX * 2) {
1513171482Sjeff		if (ts->ts_runtime > ts->ts_slptime) {
1514171482Sjeff			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1515171482Sjeff			ts->ts_slptime = 1;
1516165819Sjeff		} else {
1517171482Sjeff			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1518171482Sjeff			ts->ts_runtime = 1;
1519165819Sjeff		}
1520165819Sjeff		return;
1521165819Sjeff	}
1522165819Sjeff	/*
1523121868Sjeff	 * If we have exceeded by more than 1/5th then the algorithm below
1524121868Sjeff	 * will not bring us back into range.  Dividing by two here forces
1525133427Sjeff	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1526121868Sjeff	 */
1527127850Sjeff	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1528171482Sjeff		ts->ts_runtime /= 2;
1529171482Sjeff		ts->ts_slptime /= 2;
1530121868Sjeff		return;
1531116463Sjeff	}
1532171482Sjeff	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1533171482Sjeff	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1534116463Sjeff}
1535116463Sjeff
1536171482Sjeff/*
1537171482Sjeff * Scale back the interactivity history when a child thread is created.  The
1538171482Sjeff * history is inherited from the parent but the thread may behave totally
1539171482Sjeff * differently.  For example, a shell spawning a compiler process.  We want
1540171482Sjeff * to learn that the compiler is behaving badly very quickly.
1541171482Sjeff */
1542121868Sjeffstatic void
1543163709Sjbsched_interact_fork(struct thread *td)
1544121868Sjeff{
1545121868Sjeff	int ratio;
1546121868Sjeff	int sum;
1547121868Sjeff
1548171482Sjeff	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1549121868Sjeff	if (sum > SCHED_SLP_RUN_FORK) {
1550121868Sjeff		ratio = sum / SCHED_SLP_RUN_FORK;
1551171482Sjeff		td->td_sched->ts_runtime /= ratio;
1552171482Sjeff		td->td_sched->ts_slptime /= ratio;
1553121868Sjeff	}
1554121868Sjeff}
1555121868Sjeff
1556113357Sjeff/*
1557171482Sjeff * Called from proc0_init() to setup the scheduler fields.
1558134791Sjulian */
1559134791Sjulianvoid
1560134791Sjulianschedinit(void)
1561134791Sjulian{
1562165762Sjeff
1563134791Sjulian	/*
1564134791Sjulian	 * Set up the scheduler specific parts of proc0.
1565134791Sjulian	 */
1566136167Sjulian	proc0.p_sched = NULL; /* XXX */
1567164936Sjulian	thread0.td_sched = &td_sched0;
1568165762Sjeff	td_sched0.ts_ltick = ticks;
1569165796Sjeff	td_sched0.ts_ftick = ticks;
1570177009Sjeff	td_sched0.ts_slice = sched_slice;
1571134791Sjulian}
1572134791Sjulian
1573134791Sjulian/*
1574113357Sjeff * This is only somewhat accurate since given many processes of the same
1575113357Sjeff * priority they will switch when their slices run out, which will be
1576165762Sjeff * at most sched_slice stathz ticks.
1577113357Sjeff */
1578109864Sjeffint
1579109864Sjeffsched_rr_interval(void)
1580109864Sjeff{
1581165762Sjeff
1582241249Smav	/* Convert sched_slice from stathz to hz. */
1583241249Smav	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
1584109864Sjeff}
1585109864Sjeff
1586171482Sjeff/*
1587171482Sjeff * Update the percent cpu tracking information when it is requested or
1588171482Sjeff * the total history exceeds the maximum.  We keep a sliding history of
1589171482Sjeff * tick counts that slowly decays.  This is less precise than the 4BSD
1590171482Sjeff * mechanism since it happens with less regular and frequent events.
1591171482Sjeff */
1592121790Sjeffstatic void
1593234166Smavsched_pctcpu_update(struct td_sched *ts, int run)
1594109864Sjeff{
1595234166Smav	int t = ticks;
1596165762Sjeff
1597234166Smav	if (t - ts->ts_ltick >= SCHED_TICK_TARG) {
1598164936Sjulian		ts->ts_ticks = 0;
1599234166Smav		ts->ts_ftick = t - SCHED_TICK_TARG;
1600234166Smav	} else if (t - ts->ts_ftick >= SCHED_TICK_MAX) {
1601234166Smav		ts->ts_ticks = (ts->ts_ticks / (ts->ts_ltick - ts->ts_ftick)) *
1602234166Smav		    (ts->ts_ltick - (t - SCHED_TICK_TARG));
1603234166Smav		ts->ts_ftick = t - SCHED_TICK_TARG;
1604234166Smav	}
1605234166Smav	if (run)
1606234166Smav		ts->ts_ticks += (t - ts->ts_ltick) << SCHED_TICK_SHIFT;
1607234166Smav	ts->ts_ltick = t;
1608109864Sjeff}
1609109864Sjeff
1610171482Sjeff/*
1611171482Sjeff * Adjust the priority of a thread.  Move it to the appropriate run-queue
1612171482Sjeff * if necessary.  This is the back-end for several priority related
1613171482Sjeff * functions.
1614171482Sjeff */
1615165762Sjeffstatic void
1616139453Sjhbsched_thread_priority(struct thread *td, u_char prio)
1617109864Sjeff{
1618164936Sjulian	struct td_sched *ts;
1619177009Sjeff	struct tdq *tdq;
1620177009Sjeff	int oldpri;
1621109864Sjeff
1622187357Sjeff	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
1623187357Sjeff	    "prio:%d", td->td_priority, "new prio:%d", prio,
1624187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(curthread));
1625262057Savg	SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
1626240839Savg	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));
1630262057Savg		SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
1631236344Srstone		    curthread);
1632187357Sjeff	}
1633164936Sjulian	ts = td->td_sched;
1634170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1635139453Sjhb	if (td->td_priority == prio)
1636139453Sjhb		return;
1637177376Sjeff	/*
1638177376Sjeff	 * If the priority has been elevated due to priority
1639177376Sjeff	 * propagation, we may have to move ourselves to a new
1640177376Sjeff	 * queue.  This could be optimized to not re-add in some
1641177376Sjeff	 * cases.
1642177376Sjeff	 */
1643165766Sjeff	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1644165762Sjeff		sched_rem(td);
1645165762Sjeff		td->td_priority = prio;
1646171482Sjeff		sched_add(td, SRQ_BORROWING);
1647177009Sjeff		return;
1648177009Sjeff	}
1649177376Sjeff	/*
1650177376Sjeff	 * If the thread is currently running we may have to adjust the lowpri
1651177376Sjeff	 * information so other cpus are aware of our current priority.
1652177376Sjeff	 */
1653177009Sjeff	if (TD_IS_RUNNING(td)) {
1654177376Sjeff		tdq = TDQ_CPU(ts->ts_cpu);
1655177376Sjeff		oldpri = td->td_priority;
1656177376Sjeff		td->td_priority = prio;
1657176735Sjeff		if (prio < tdq->tdq_lowpri)
1658171482Sjeff			tdq->tdq_lowpri = prio;
1659176735Sjeff		else if (tdq->tdq_lowpri == oldpri)
1660176735Sjeff			tdq_setlowpri(tdq, td);
1661177376Sjeff		return;
1662177009Sjeff	}
1663177376Sjeff	td->td_priority = prio;
1664109864Sjeff}
1665109864Sjeff
1666139453Sjhb/*
1667139453Sjhb * Update a thread's priority when it is lent another thread's
1668139453Sjhb * priority.
1669139453Sjhb */
1670109864Sjeffvoid
1671139453Sjhbsched_lend_prio(struct thread *td, u_char prio)
1672139453Sjhb{
1673139453Sjhb
1674139453Sjhb	td->td_flags |= TDF_BORROWING;
1675139453Sjhb	sched_thread_priority(td, prio);
1676139453Sjhb}
1677139453Sjhb
1678139453Sjhb/*
1679139453Sjhb * Restore a thread's priority when priority propagation is
1680139453Sjhb * over.  The prio argument is the minimum priority the thread
1681139453Sjhb * needs to have to satisfy other possible priority lending
1682139453Sjhb * requests.  If the thread's regular priority is less
1683139453Sjhb * important than prio, the thread will keep a priority boost
1684139453Sjhb * of prio.
1685139453Sjhb */
1686139453Sjhbvoid
1687139453Sjhbsched_unlend_prio(struct thread *td, u_char prio)
1688139453Sjhb{
1689139453Sjhb	u_char base_pri;
1690139453Sjhb
1691139453Sjhb	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1692139453Sjhb	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1693163709Sjb		base_pri = td->td_user_pri;
1694139453Sjhb	else
1695139453Sjhb		base_pri = td->td_base_pri;
1696139453Sjhb	if (prio >= base_pri) {
1697139455Sjhb		td->td_flags &= ~TDF_BORROWING;
1698139453Sjhb		sched_thread_priority(td, base_pri);
1699139453Sjhb	} else
1700139453Sjhb		sched_lend_prio(td, prio);
1701139453Sjhb}
1702139453Sjhb
1703171482Sjeff/*
1704171482Sjeff * Standard entry for setting the priority to an absolute value.
1705171482Sjeff */
1706139453Sjhbvoid
1707139453Sjhbsched_prio(struct thread *td, u_char prio)
1708139453Sjhb{
1709139453Sjhb	u_char oldprio;
1710139453Sjhb
1711139453Sjhb	/* First, update the base priority. */
1712139453Sjhb	td->td_base_pri = prio;
1713139453Sjhb
1714139453Sjhb	/*
1715139455Sjhb	 * If the thread is borrowing another thread's priority, don't
1716139453Sjhb	 * ever lower the priority.
1717139453Sjhb	 */
1718139453Sjhb	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1719139453Sjhb		return;
1720139453Sjhb
1721139453Sjhb	/* Change the real priority. */
1722139453Sjhb	oldprio = td->td_priority;
1723139453Sjhb	sched_thread_priority(td, prio);
1724139453Sjhb
1725139453Sjhb	/*
1726139453Sjhb	 * If the thread is on a turnstile, then let the turnstile update
1727139453Sjhb	 * its state.
1728139453Sjhb	 */
1729139453Sjhb	if (TD_ON_LOCK(td) && oldprio != prio)
1730139453Sjhb		turnstile_adjust(td, oldprio);
1731139453Sjhb}
1732139455Sjhb
1733171482Sjeff/*
1734171482Sjeff * Set the base user priority, does not effect current running priority.
1735171482Sjeff */
1736139453Sjhbvoid
1737163709Sjbsched_user_prio(struct thread *td, u_char prio)
1738161599Sdavidxu{
1739161599Sdavidxu
1740163709Sjb	td->td_base_user_pri = prio;
1741216313Sdavidxu	if (td->td_lend_user_pri <= prio)
1742216313Sdavidxu		return;
1743163709Sjb	td->td_user_pri = prio;
1744161599Sdavidxu}
1745161599Sdavidxu
1746161599Sdavidxuvoid
1747161599Sdavidxusched_lend_user_prio(struct thread *td, u_char prio)
1748161599Sdavidxu{
1749161599Sdavidxu
1750174536Sdavidxu	THREAD_LOCK_ASSERT(td, MA_OWNED);
1751216313Sdavidxu	td->td_lend_user_pri = prio;
1752216791Sdavidxu	td->td_user_pri = min(prio, td->td_base_user_pri);
1753216791Sdavidxu	if (td->td_priority > td->td_user_pri)
1754216791Sdavidxu		sched_prio(td, td->td_user_pri);
1755216791Sdavidxu	else if (td->td_priority != td->td_user_pri)
1756216791Sdavidxu		td->td_flags |= TDF_NEEDRESCHED;
1757161599Sdavidxu}
1758161599Sdavidxu
1759171482Sjeff/*
1760171713Sjeff * Handle migration from sched_switch().  This happens only for
1761171713Sjeff * cpu binding.
1762171713Sjeff */
1763171713Sjeffstatic struct mtx *
1764171713Sjeffsched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1765171713Sjeff{
1766171713Sjeff	struct tdq *tdn;
1767171713Sjeff
1768171713Sjeff	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1769171713Sjeff#ifdef SMP
1770177435Sjeff	tdq_load_rem(tdq, td);
1771171713Sjeff	/*
1772171713Sjeff	 * Do the lock dance required to avoid LOR.  We grab an extra
1773171713Sjeff	 * spinlock nesting to prevent preemption while we're
1774171713Sjeff	 * not holding either run-queue lock.
1775171713Sjeff	 */
1776171713Sjeff	spinlock_enter();
1777202889Sattilio	thread_lock_block(td);	/* This releases the lock on tdq. */
1778197223Sattilio
1779197223Sattilio	/*
1780197223Sattilio	 * Acquire both run-queue locks before placing the thread on the new
1781197223Sattilio	 * run-queue to avoid deadlocks created by placing a thread with a
1782197223Sattilio	 * blocked lock on the run-queue of a remote processor.  The deadlock
1783197223Sattilio	 * occurs when a third processor attempts to lock the two queues in
1784197223Sattilio	 * question while the target processor is spinning with its own
1785197223Sattilio	 * run-queue lock held while waiting for the blocked lock to clear.
1786197223Sattilio	 */
1787197223Sattilio	tdq_lock_pair(tdn, tdq);
1788171713Sjeff	tdq_add(tdn, td, flags);
1789177435Sjeff	tdq_notify(tdn, td);
1790197223Sattilio	TDQ_UNLOCK(tdn);
1791171713Sjeff	spinlock_exit();
1792171713Sjeff#endif
1793171713Sjeff	return (TDQ_LOCKPTR(tdn));
1794171713Sjeff}
1795171713Sjeff
1796171713Sjeff/*
1797202889Sattilio * Variadic version of thread_lock_unblock() that does not assume td_lock
1798202889Sattilio * is blocked.
1799171482Sjeff */
1800171482Sjeffstatic inline void
1801171482Sjeffthread_unblock_switch(struct thread *td, struct mtx *mtx)
1802171482Sjeff{
1803171482Sjeff	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1804171482Sjeff	    (uintptr_t)mtx);
1805171482Sjeff}
1806171482Sjeff
1807171482Sjeff/*
1808171482Sjeff * Switch threads.  This function has to handle threads coming in while
1809171482Sjeff * blocked for some reason, running, or idle.  It also must deal with
1810171482Sjeff * migrating a thread from one queue to another as running threads may
1811171482Sjeff * be assigned elsewhere via binding.
1812171482Sjeff */
1813161599Sdavidxuvoid
1814135051Sjuliansched_switch(struct thread *td, struct thread *newtd, int flags)
1815109864Sjeff{
1816165627Sjeff	struct tdq *tdq;
1817164936Sjulian	struct td_sched *ts;
1818171482Sjeff	struct mtx *mtx;
1819171713Sjeff	int srqflag;
1820241248Smav	int cpuid, preempted;
1821109864Sjeff
1822170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1823177376Sjeff	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
1824109864Sjeff
1825171482Sjeff	cpuid = PCPU_GET(cpuid);
1826171482Sjeff	tdq = TDQ_CPU(cpuid);
1827164936Sjulian	ts = td->td_sched;
1828171713Sjeff	mtx = td->td_lock;
1829234166Smav	sched_pctcpu_update(ts, 1);
1830171482Sjeff	ts->ts_rltick = ticks;
1831133555Sjeff	td->td_lastcpu = td->td_oncpu;
1832113339Sjulian	td->td_oncpu = NOCPU;
1833241248Smav	preempted = !(td->td_flags & TDF_SLICEEND);
1834241248Smav	td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
1835144777Sups	td->td_owepreempt = 0;
1836247150Smav	if (!TD_IS_IDLETHREAD(td))
1837247150Smav		tdq->tdq_switchcnt++;
1838123434Sjeff	/*
1839171482Sjeff	 * The lock pointer in an idle thread should never change.  Reset it
1840171482Sjeff	 * to CAN_RUN as well.
1841123434Sjeff	 */
1842167327Sjulian	if (TD_IS_IDLETHREAD(td)) {
1843171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1844139334Sjeff		TD_SET_CAN_RUN(td);
1845170293Sjeff	} else if (TD_IS_RUNNING(td)) {
1846171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1847241248Smav		srqflag = preempted ?
1848170293Sjeff		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1849171713Sjeff		    SRQ_OURSELF|SRQ_YIELDING;
1850212153Smdf#ifdef SMP
1851212115Smdf		if (THREAD_CAN_MIGRATE(td) && !THREAD_CAN_SCHED(td, ts->ts_cpu))
1852212115Smdf			ts->ts_cpu = sched_pickcpu(td, 0);
1853212153Smdf#endif
1854171713Sjeff		if (ts->ts_cpu == cpuid)
1855177435Sjeff			tdq_runq_add(tdq, td, srqflag);
1856212115Smdf		else {
1857212115Smdf			KASSERT(THREAD_CAN_MIGRATE(td) ||
1858212115Smdf			    (ts->ts_flags & TSF_BOUND) != 0,
1859212115Smdf			    ("Thread %p shouldn't migrate", td));
1860171713Sjeff			mtx = sched_switch_migrate(tdq, td, srqflag);
1861212115Smdf		}
1862171482Sjeff	} else {
1863171482Sjeff		/* This thread must be going to sleep. */
1864171482Sjeff		TDQ_LOCK(tdq);
1865202889Sattilio		mtx = thread_lock_block(td);
1866177435Sjeff		tdq_load_rem(tdq, td);
1867171482Sjeff	}
1868171482Sjeff	/*
1869171482Sjeff	 * We enter here with the thread blocked and assigned to the
1870171482Sjeff	 * appropriate cpu run-queue or sleep-queue and with the current
1871171482Sjeff	 * thread-queue locked.
1872171482Sjeff	 */
1873171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1874171482Sjeff	newtd = choosethread();
1875171482Sjeff	/*
1876171482Sjeff	 * Call the MD code to switch contexts if necessary.
1877171482Sjeff	 */
1878145256Sjkoshy	if (td != newtd) {
1879145256Sjkoshy#ifdef	HWPMC_HOOKS
1880145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1881145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1882145256Sjkoshy#endif
1883262057Savg		SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
1884174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1885172411Sjeff		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1886234166Smav		sched_pctcpu_update(newtd->td_sched, 0);
1887179297Sjb
1888179297Sjb#ifdef KDTRACE_HOOKS
1889179297Sjb		/*
1890179297Sjb		 * If DTrace has set the active vtime enum to anything
1891179297Sjb		 * other than INACTIVE (0), then it should have set the
1892179297Sjb		 * function to call.
1893179297Sjb		 */
1894179297Sjb		if (dtrace_vtime_active)
1895179297Sjb			(*dtrace_vtime_switch_func)(newtd);
1896179297Sjb#endif
1897179297Sjb
1898171482Sjeff		cpu_switch(td, newtd, mtx);
1899171482Sjeff		/*
1900171482Sjeff		 * We may return from cpu_switch on a different cpu.  However,
1901171482Sjeff		 * we always return with td_lock pointing to the current cpu's
1902171482Sjeff		 * run queue lock.
1903171482Sjeff		 */
1904171482Sjeff		cpuid = PCPU_GET(cpuid);
1905171482Sjeff		tdq = TDQ_CPU(cpuid);
1906174629Sjeff		lock_profile_obtain_lock_success(
1907174629Sjeff		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1908236344Srstone
1909262057Savg		SDT_PROBE0(sched, , , on__cpu);
1910145256Sjkoshy#ifdef	HWPMC_HOOKS
1911145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1912145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1913145256Sjkoshy#endif
1914236344Srstone	} else {
1915171482Sjeff		thread_unblock_switch(td, mtx);
1916262057Savg		SDT_PROBE0(sched, , , remain__cpu);
1917236344Srstone	}
1918171482Sjeff	/*
1919171482Sjeff	 * Assert that all went well and return.
1920171482Sjeff	 */
1921171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1922171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1923171482Sjeff	td->td_oncpu = cpuid;
1924109864Sjeff}
1925109864Sjeff
1926171482Sjeff/*
1927171482Sjeff * Adjust thread priorities as a result of a nice request.
1928171482Sjeff */
1929109864Sjeffvoid
1930130551Sjuliansched_nice(struct proc *p, int nice)
1931109864Sjeff{
1932109864Sjeff	struct thread *td;
1933109864Sjeff
1934130551Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
1935165762Sjeff
1936130551Sjulian	p->p_nice = nice;
1937163709Sjb	FOREACH_THREAD_IN_PROC(p, td) {
1938170293Sjeff		thread_lock(td);
1939163709Sjb		sched_priority(td);
1940165762Sjeff		sched_prio(td, td->td_base_user_pri);
1941170293Sjeff		thread_unlock(td);
1942130551Sjulian	}
1943109864Sjeff}
1944109864Sjeff
1945171482Sjeff/*
1946171482Sjeff * Record the sleep time for the interactivity scorer.
1947171482Sjeff */
1948109864Sjeffvoid
1949177085Sjeffsched_sleep(struct thread *td, int prio)
1950109864Sjeff{
1951165762Sjeff
1952170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1953109864Sjeff
1954172264Sjeff	td->td_slptick = ticks;
1955201347Skib	if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
1956177085Sjeff		td->td_flags |= TDF_CANSWAP;
1957217410Sjhb	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
1958217410Sjhb		return;
1959177903Sjeff	if (static_boost == 1 && prio)
1960177085Sjeff		sched_prio(td, prio);
1961177903Sjeff	else if (static_boost && td->td_priority > static_boost)
1962177903Sjeff		sched_prio(td, static_boost);
1963109864Sjeff}
1964109864Sjeff
1965171482Sjeff/*
1966171482Sjeff * Schedule a thread to resume execution and record how long it voluntarily
1967171482Sjeff * slept.  We also update the pctcpu, interactivity, and priority.
1968171482Sjeff */
1969109864Sjeffvoid
1970109864Sjeffsched_wakeup(struct thread *td)
1971109864Sjeff{
1972166229Sjeff	struct td_sched *ts;
1973171482Sjeff	int slptick;
1974165762Sjeff
1975170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1976166229Sjeff	ts = td->td_sched;
1977177085Sjeff	td->td_flags &= ~TDF_CANSWAP;
1978109864Sjeff	/*
1979165762Sjeff	 * If we slept for more than a tick update our interactivity and
1980165762Sjeff	 * priority.
1981109864Sjeff	 */
1982172264Sjeff	slptick = td->td_slptick;
1983172264Sjeff	td->td_slptick = 0;
1984171482Sjeff	if (slptick && slptick != ticks) {
1985234166Smav		ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
1986165819Sjeff		sched_interact_update(td);
1987234166Smav		sched_pctcpu_update(ts, 0);
1988109864Sjeff	}
1989166229Sjeff	/* Reset the slice value after we sleep. */
1990166229Sjeff	ts->ts_slice = sched_slice;
1991166190Sjeff	sched_add(td, SRQ_BORING);
1992109864Sjeff}
1993109864Sjeff
1994109864Sjeff/*
1995109864Sjeff * Penalize the parent for creating a new child and initialize the child's
1996109864Sjeff * priority.
1997109864Sjeff */
1998109864Sjeffvoid
1999163709Sjbsched_fork(struct thread *td, struct thread *child)
2000109864Sjeff{
2001170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2002234166Smav	sched_pctcpu_update(td->td_sched, 1);
2003164936Sjulian	sched_fork_thread(td, child);
2004165762Sjeff	/*
2005165762Sjeff	 * Penalize the parent and child for forking.
2006165762Sjeff	 */
2007165762Sjeff	sched_interact_fork(child);
2008165762Sjeff	sched_priority(child);
2009171482Sjeff	td->td_sched->ts_runtime += tickincr;
2010165762Sjeff	sched_interact_update(td);
2011165762Sjeff	sched_priority(td);
2012164936Sjulian}
2013109864Sjeff
2014171482Sjeff/*
2015171482Sjeff * Fork a new thread, may be within the same process.
2016171482Sjeff */
2017164936Sjulianvoid
2018164936Sjuliansched_fork_thread(struct thread *td, struct thread *child)
2019164936Sjulian{
2020164936Sjulian	struct td_sched *ts;
2021164936Sjulian	struct td_sched *ts2;
2022164936Sjulian
2023177426Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2024165762Sjeff	/*
2025165762Sjeff	 * Initialize child.
2026165762Sjeff	 */
2027177426Sjeff	ts = td->td_sched;
2028177426Sjeff	ts2 = child->td_sched;
2029171482Sjeff	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
2030176735Sjeff	child->td_cpuset = cpuset_ref(td->td_cpuset);
2031164936Sjulian	ts2->ts_cpu = ts->ts_cpu;
2032177426Sjeff	ts2->ts_flags = 0;
2033165762Sjeff	/*
2034217078Sjhb	 * Grab our parents cpu estimation information.
2035165762Sjeff	 */
2036164936Sjulian	ts2->ts_ticks = ts->ts_ticks;
2037164936Sjulian	ts2->ts_ltick = ts->ts_ltick;
2038164936Sjulian	ts2->ts_ftick = ts->ts_ftick;
2039165762Sjeff	/*
2040217078Sjhb	 * Do not inherit any borrowed priority from the parent.
2041217078Sjhb	 */
2042217078Sjhb	child->td_priority = child->td_base_pri;
2043217078Sjhb	/*
2044165762Sjeff	 * And update interactivity score.
2045165762Sjeff	 */
2046171482Sjeff	ts2->ts_slptime = ts->ts_slptime;
2047171482Sjeff	ts2->ts_runtime = ts->ts_runtime;
2048165762Sjeff	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
2049187357Sjeff#ifdef KTR
2050187357Sjeff	bzero(ts2->ts_name, sizeof(ts2->ts_name));
2051187357Sjeff#endif
2052113357Sjeff}
2053113357Sjeff
2054171482Sjeff/*
2055171482Sjeff * Adjust the priority class of a thread.
2056171482Sjeff */
2057113357Sjeffvoid
2058163709Sjbsched_class(struct thread *td, int class)
2059113357Sjeff{
2060113357Sjeff
2061170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2062163709Sjb	if (td->td_pri_class == class)
2063113357Sjeff		return;
2064163709Sjb	td->td_pri_class = class;
2065109864Sjeff}
2066109864Sjeff
2067109864Sjeff/*
2068109864Sjeff * Return some of the child's priority and interactivity to the parent.
2069109864Sjeff */
2070109864Sjeffvoid
2071164939Sjuliansched_exit(struct proc *p, struct thread *child)
2072109864Sjeff{
2073165762Sjeff	struct thread *td;
2074113372Sjeff
2075187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2076225199Sdelphij	    "prio:%d", child->td_priority);
2077177368Sjeff	PROC_LOCK_ASSERT(p, MA_OWNED);
2078165762Sjeff	td = FIRST_THREAD_IN_PROC(p);
2079165762Sjeff	sched_exit_thread(td, child);
2080113372Sjeff}
2081113372Sjeff
2082171482Sjeff/*
2083171482Sjeff * Penalize another thread for the time spent on this one.  This helps to
2084171482Sjeff * worsen the priority and interactivity of processes which schedule batch
2085171482Sjeff * jobs such as make.  This has little effect on the make process itself but
2086171482Sjeff * causes new processes spawned by it to receive worse scores immediately.
2087171482Sjeff */
2088113372Sjeffvoid
2089164939Sjuliansched_exit_thread(struct thread *td, struct thread *child)
2090164936Sjulian{
2091165762Sjeff
2092187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2093225199Sdelphij	    "prio:%d", child->td_priority);
2094165762Sjeff	/*
2095165762Sjeff	 * Give the child's runtime to the parent without returning the
2096165762Sjeff	 * sleep time as a penalty to the parent.  This causes shells that
2097165762Sjeff	 * launch expensive things to mark their children as expensive.
2098165762Sjeff	 */
2099170293Sjeff	thread_lock(td);
2100171482Sjeff	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2101164939Sjulian	sched_interact_update(td);
2102165762Sjeff	sched_priority(td);
2103170293Sjeff	thread_unlock(td);
2104164936Sjulian}
2105164936Sjulian
2106177005Sjeffvoid
2107177005Sjeffsched_preempt(struct thread *td)
2108177005Sjeff{
2109177005Sjeff	struct tdq *tdq;
2110177005Sjeff
2111236344Srstone	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
2112236344Srstone
2113177005Sjeff	thread_lock(td);
2114177005Sjeff	tdq = TDQ_SELF();
2115177005Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2116177005Sjeff	tdq->tdq_ipipending = 0;
2117177005Sjeff	if (td->td_priority > tdq->tdq_lowpri) {
2118178272Sjeff		int flags;
2119178272Sjeff
2120178272Sjeff		flags = SW_INVOL | SW_PREEMPT;
2121177005Sjeff		if (td->td_critnest > 1)
2122177005Sjeff			td->td_owepreempt = 1;
2123178272Sjeff		else if (TD_IS_IDLETHREAD(td))
2124178272Sjeff			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2125177005Sjeff		else
2126178272Sjeff			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2127177005Sjeff	}
2128177005Sjeff	thread_unlock(td);
2129177005Sjeff}
2130177005Sjeff
2131171482Sjeff/*
2132171482Sjeff * Fix priorities on return to user-space.  Priorities may be elevated due
2133171482Sjeff * to static priorities in msleep() or similar.
2134171482Sjeff */
2135164936Sjulianvoid
2136164936Sjuliansched_userret(struct thread *td)
2137164936Sjulian{
2138164936Sjulian	/*
2139164936Sjulian	 * XXX we cheat slightly on the locking here to avoid locking in
2140164936Sjulian	 * the usual case.  Setting td_priority here is essentially an
2141164936Sjulian	 * incomplete workaround for not setting it properly elsewhere.
2142164936Sjulian	 * Now that some interrupt handlers are threads, not setting it
2143164936Sjulian	 * properly elsewhere can clobber it in the window between setting
2144164936Sjulian	 * it here and returning to user mode, so don't waste time setting
2145164936Sjulian	 * it perfectly here.
2146164936Sjulian	 */
2147164936Sjulian	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2148164936Sjulian	    ("thread with borrowed priority returning to userland"));
2149164936Sjulian	if (td->td_priority != td->td_user_pri) {
2150170293Sjeff		thread_lock(td);
2151164936Sjulian		td->td_priority = td->td_user_pri;
2152164936Sjulian		td->td_base_pri = td->td_user_pri;
2153177005Sjeff		tdq_setlowpri(TDQ_SELF(), td);
2154170293Sjeff		thread_unlock(td);
2155164936Sjulian        }
2156164936Sjulian}
2157164936Sjulian
2158171482Sjeff/*
2159171482Sjeff * Handle a stathz tick.  This is really only relevant for timeshare
2160171482Sjeff * threads.
2161171482Sjeff */
2162164936Sjulianvoid
2163121127Sjeffsched_clock(struct thread *td)
2164109864Sjeff{
2165164936Sjulian	struct tdq *tdq;
2166164936Sjulian	struct td_sched *ts;
2167109864Sjeff
2168171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2169164936Sjulian	tdq = TDQ_SELF();
2170172409Sjeff#ifdef SMP
2171133427Sjeff	/*
2172172409Sjeff	 * We run the long term load balancer infrequently on the first cpu.
2173172409Sjeff	 */
2174172409Sjeff	if (balance_tdq == tdq) {
2175172409Sjeff		if (balance_ticks && --balance_ticks == 0)
2176172409Sjeff			sched_balance();
2177172409Sjeff	}
2178172409Sjeff#endif
2179172409Sjeff	/*
2180178277Sjeff	 * Save the old switch count so we have a record of the last ticks
2181178277Sjeff	 * activity.   Initialize the new switch count based on our load.
2182178277Sjeff	 * If there is some activity seed it to reflect that.
2183178277Sjeff	 */
2184178277Sjeff	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
2185178471Sjeff	tdq->tdq_switchcnt = tdq->tdq_load;
2186178277Sjeff	/*
2187165766Sjeff	 * Advance the insert index once for each tick to ensure that all
2188165766Sjeff	 * threads get a chance to run.
2189133427Sjeff	 */
2190165766Sjeff	if (tdq->tdq_idx == tdq->tdq_ridx) {
2191165766Sjeff		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2192165766Sjeff		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2193165766Sjeff			tdq->tdq_ridx = tdq->tdq_idx;
2194165766Sjeff	}
2195165766Sjeff	ts = td->td_sched;
2196234166Smav	sched_pctcpu_update(ts, 1);
2197175104Sjeff	if (td->td_pri_class & PRI_FIFO_BIT)
2198113357Sjeff		return;
2199217291Sjhb	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2200175104Sjeff		/*
2201175104Sjeff		 * We used a tick; charge it to the thread so
2202175104Sjeff		 * that we can compute our interactivity.
2203175104Sjeff		 */
2204175104Sjeff		td->td_sched->ts_runtime += tickincr;
2205175104Sjeff		sched_interact_update(td);
2206177009Sjeff		sched_priority(td);
2207175104Sjeff	}
2208241249Smav
2209113357Sjeff	/*
2210241249Smav	 * Force a context switch if the current thread has used up a full
2211241249Smav	 * time slice (default is 100ms).
2212109864Sjeff	 */
2213241249Smav	if (!TD_IS_IDLETHREAD(td) && --ts->ts_slice <= 0) {
2214241249Smav		ts->ts_slice = sched_slice;
2215241249Smav		td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
2216241249Smav	}
2217109864Sjeff}
2218109864Sjeff
2219171482Sjeff/*
2220234166Smav * Called once per hz tick.
2221171482Sjeff */
2222171482Sjeffvoid
2223212541Smavsched_tick(int cnt)
2224171482Sjeff{
2225171482Sjeff
2226171482Sjeff}
2227171482Sjeff
2228171482Sjeff/*
2229171482Sjeff * Return whether the current CPU has runnable tasks.  Used for in-kernel
2230171482Sjeff * cooperative idle threads.
2231171482Sjeff */
2232109864Sjeffint
2233109864Sjeffsched_runnable(void)
2234109864Sjeff{
2235164936Sjulian	struct tdq *tdq;
2236115998Sjeff	int load;
2237109864Sjeff
2238115998Sjeff	load = 1;
2239115998Sjeff
2240164936Sjulian	tdq = TDQ_SELF();
2241121605Sjeff	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2242165620Sjeff		if (tdq->tdq_load > 0)
2243121605Sjeff			goto out;
2244121605Sjeff	} else
2245165620Sjeff		if (tdq->tdq_load - 1 > 0)
2246121605Sjeff			goto out;
2247115998Sjeff	load = 0;
2248115998Sjeffout:
2249115998Sjeff	return (load);
2250109864Sjeff}
2251109864Sjeff
2252171482Sjeff/*
2253171482Sjeff * Choose the highest priority thread to run.  The thread is removed from
2254171482Sjeff * the run-queue while running however the load remains.  For SMP we set
2255171482Sjeff * the tdq in the global idle bitmask if it idles here.
2256171482Sjeff */
2257166190Sjeffstruct thread *
2258109970Sjeffsched_choose(void)
2259109970Sjeff{
2260177435Sjeff	struct thread *td;
2261164936Sjulian	struct tdq *tdq;
2262109970Sjeff
2263164936Sjulian	tdq = TDQ_SELF();
2264171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2265177435Sjeff	td = tdq_choose(tdq);
2266177435Sjeff	if (td) {
2267177435Sjeff		tdq_runq_rem(tdq, td);
2268177903Sjeff		tdq->tdq_lowpri = td->td_priority;
2269177435Sjeff		return (td);
2270109864Sjeff	}
2271177903Sjeff	tdq->tdq_lowpri = PRI_MAX_IDLE;
2272176735Sjeff	return (PCPU_GET(idlethread));
2273109864Sjeff}
2274109864Sjeff
2275171482Sjeff/*
2276171482Sjeff * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2277171482Sjeff * we always request it once we exit a critical section.
2278171482Sjeff */
2279171482Sjeffstatic inline void
2280171482Sjeffsched_setpreempt(struct thread *td)
2281166190Sjeff{
2282166190Sjeff	struct thread *ctd;
2283166190Sjeff	int cpri;
2284166190Sjeff	int pri;
2285166190Sjeff
2286177005Sjeff	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2287177005Sjeff
2288166190Sjeff	ctd = curthread;
2289166190Sjeff	pri = td->td_priority;
2290166190Sjeff	cpri = ctd->td_priority;
2291177005Sjeff	if (pri < cpri)
2292177005Sjeff		ctd->td_flags |= TDF_NEEDRESCHED;
2293166190Sjeff	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2294171482Sjeff		return;
2295177005Sjeff	if (!sched_shouldpreempt(pri, cpri, 0))
2296171482Sjeff		return;
2297171482Sjeff	ctd->td_owepreempt = 1;
2298166190Sjeff}
2299166190Sjeff
2300171482Sjeff/*
2301177009Sjeff * Add a thread to a thread queue.  Select the appropriate runq and add the
2302177009Sjeff * thread to it.  This is the internal function called when the tdq is
2303177009Sjeff * predetermined.
2304171482Sjeff */
2305109864Sjeffvoid
2306171482Sjefftdq_add(struct tdq *tdq, struct thread *td, int flags)
2307109864Sjeff{
2308109864Sjeff
2309171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2310166190Sjeff	KASSERT((td->td_inhibitors == 0),
2311166190Sjeff	    ("sched_add: trying to run inhibited thread"));
2312166190Sjeff	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2313166190Sjeff	    ("sched_add: bad thread state"));
2314172207Sjeff	KASSERT(td->td_flags & TDF_INMEM,
2315172207Sjeff	    ("sched_add: thread swapped out"));
2316171482Sjeff
2317171482Sjeff	if (td->td_priority < tdq->tdq_lowpri)
2318171482Sjeff		tdq->tdq_lowpri = td->td_priority;
2319177435Sjeff	tdq_runq_add(tdq, td, flags);
2320177435Sjeff	tdq_load_add(tdq, td);
2321171482Sjeff}
2322171482Sjeff
2323171482Sjeff/*
2324171482Sjeff * Select the target thread queue and add a thread to it.  Request
2325171482Sjeff * preemption or IPI a remote processor if required.
2326171482Sjeff */
2327171482Sjeffvoid
2328171482Sjeffsched_add(struct thread *td, int flags)
2329171482Sjeff{
2330171482Sjeff	struct tdq *tdq;
2331171482Sjeff#ifdef SMP
2332171482Sjeff	int cpu;
2333171482Sjeff#endif
2334187357Sjeff
2335187357Sjeff	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
2336187357Sjeff	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
2337187357Sjeff	    sched_tdname(curthread));
2338187357Sjeff	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
2339187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(td));
2340236344Srstone	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
2341236344Srstone	    flags & SRQ_PREEMPTED);
2342171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2343166108Sjeff	/*
2344171482Sjeff	 * Recalculate the priority before we select the target cpu or
2345171482Sjeff	 * run-queue.
2346166108Sjeff	 */
2347171482Sjeff	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2348171482Sjeff		sched_priority(td);
2349171482Sjeff#ifdef SMP
2350171482Sjeff	/*
2351171482Sjeff	 * Pick the destination cpu and if it isn't ours transfer to the
2352171482Sjeff	 * target cpu.
2353171482Sjeff	 */
2354177435Sjeff	cpu = sched_pickcpu(td, flags);
2355177435Sjeff	tdq = sched_setcpu(td, cpu, flags);
2356171482Sjeff	tdq_add(tdq, td, flags);
2357177009Sjeff	if (cpu != PCPU_GET(cpuid)) {
2358177435Sjeff		tdq_notify(tdq, td);
2359166108Sjeff		return;
2360166108Sjeff	}
2361171482Sjeff#else
2362171482Sjeff	tdq = TDQ_SELF();
2363171482Sjeff	TDQ_LOCK(tdq);
2364171482Sjeff	/*
2365171482Sjeff	 * Now that the thread is moving to the run-queue, set the lock
2366171482Sjeff	 * to the scheduler's lock.
2367171482Sjeff	 */
2368171482Sjeff	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2369171482Sjeff	tdq_add(tdq, td, flags);
2370166108Sjeff#endif
2371171482Sjeff	if (!(flags & SRQ_YIELDING))
2372171482Sjeff		sched_setpreempt(td);
2373109864Sjeff}
2374109864Sjeff
2375171482Sjeff/*
2376171482Sjeff * Remove a thread from a run-queue without running it.  This is used
2377171482Sjeff * when we're stealing a thread from a remote queue.  Otherwise all threads
2378171482Sjeff * exit by calling sched_exit_thread() and sched_throw() themselves.
2379171482Sjeff */
2380109864Sjeffvoid
2381121127Sjeffsched_rem(struct thread *td)
2382109864Sjeff{
2383164936Sjulian	struct tdq *tdq;
2384113357Sjeff
2385187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
2386187357Sjeff	    "prio:%d", td->td_priority);
2387236344Srstone	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
2388177435Sjeff	tdq = TDQ_CPU(td->td_sched->ts_cpu);
2389171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2390171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2391166190Sjeff	KASSERT(TD_ON_RUNQ(td),
2392164936Sjulian	    ("sched_rem: thread not on run queue"));
2393177435Sjeff	tdq_runq_rem(tdq, td);
2394177435Sjeff	tdq_load_rem(tdq, td);
2395166190Sjeff	TD_SET_CAN_RUN(td);
2396176735Sjeff	if (td->td_priority == tdq->tdq_lowpri)
2397176735Sjeff		tdq_setlowpri(tdq, NULL);
2398109864Sjeff}
2399109864Sjeff
2400171482Sjeff/*
2401171482Sjeff * Fetch cpu utilization information.  Updates on demand.
2402171482Sjeff */
2403109864Sjefffixpt_t
2404121127Sjeffsched_pctcpu(struct thread *td)
2405109864Sjeff{
2406109864Sjeff	fixpt_t pctcpu;
2407164936Sjulian	struct td_sched *ts;
2408109864Sjeff
2409109864Sjeff	pctcpu = 0;
2410164936Sjulian	ts = td->td_sched;
2411164936Sjulian	if (ts == NULL)
2412121290Sjeff		return (0);
2413109864Sjeff
2414208787Sjhb	THREAD_LOCK_ASSERT(td, MA_OWNED);
2415234166Smav	sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2416164936Sjulian	if (ts->ts_ticks) {
2417109864Sjeff		int rtick;
2418109864Sjeff
2419109864Sjeff		/* How many rtick per second ? */
2420165762Sjeff		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2421165762Sjeff		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2422109864Sjeff	}
2423109864Sjeff
2424109864Sjeff	return (pctcpu);
2425109864Sjeff}
2426109864Sjeff
2427176735Sjeff/*
2428176735Sjeff * Enforce affinity settings for a thread.  Called after adjustments to
2429176735Sjeff * cpumask.
2430176735Sjeff */
2431176729Sjeffvoid
2432176729Sjeffsched_affinity(struct thread *td)
2433176729Sjeff{
2434176735Sjeff#ifdef SMP
2435176735Sjeff	struct td_sched *ts;
2436176735Sjeff
2437176735Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2438176735Sjeff	ts = td->td_sched;
2439176735Sjeff	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2440176735Sjeff		return;
2441189787Sjeff	if (TD_ON_RUNQ(td)) {
2442189787Sjeff		sched_rem(td);
2443189787Sjeff		sched_add(td, SRQ_BORING);
2444189787Sjeff		return;
2445189787Sjeff	}
2446176735Sjeff	if (!TD_IS_RUNNING(td))
2447176735Sjeff		return;
2448176735Sjeff	/*
2449212115Smdf	 * Force a switch before returning to userspace.  If the
2450212115Smdf	 * target thread is not running locally send an ipi to force
2451212115Smdf	 * the issue.
2452176735Sjeff	 */
2453212974Sjhb	td->td_flags |= TDF_NEEDRESCHED;
2454212115Smdf	if (td != curthread)
2455212115Smdf		ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
2456176735Sjeff#endif
2457176729Sjeff}
2458176729Sjeff
2459171482Sjeff/*
2460171482Sjeff * Bind a thread to a target cpu.
2461171482Sjeff */
2462122038Sjeffvoid
2463122038Sjeffsched_bind(struct thread *td, int cpu)
2464122038Sjeff{
2465164936Sjulian	struct td_sched *ts;
2466122038Sjeff
2467171713Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2468208391Sjhb	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
2469164936Sjulian	ts = td->td_sched;
2470166137Sjeff	if (ts->ts_flags & TSF_BOUND)
2471166152Sjeff		sched_unbind(td);
2472212115Smdf	KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2473164936Sjulian	ts->ts_flags |= TSF_BOUND;
2474166137Sjeff	sched_pin();
2475123433Sjeff	if (PCPU_GET(cpuid) == cpu)
2476122038Sjeff		return;
2477166137Sjeff	ts->ts_cpu = cpu;
2478122038Sjeff	/* When we return from mi_switch we'll be on the correct cpu. */
2479131527Sphk	mi_switch(SW_VOL, NULL);
2480122038Sjeff}
2481122038Sjeff
2482171482Sjeff/*
2483171482Sjeff * Release a bound thread.
2484171482Sjeff */
2485122038Sjeffvoid
2486122038Sjeffsched_unbind(struct thread *td)
2487122038Sjeff{
2488165762Sjeff	struct td_sched *ts;
2489165762Sjeff
2490170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2491208391Sjhb	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
2492165762Sjeff	ts = td->td_sched;
2493166137Sjeff	if ((ts->ts_flags & TSF_BOUND) == 0)
2494166137Sjeff		return;
2495165762Sjeff	ts->ts_flags &= ~TSF_BOUND;
2496165762Sjeff	sched_unpin();
2497122038Sjeff}
2498122038Sjeff
2499109864Sjeffint
2500145256Sjkoshysched_is_bound(struct thread *td)
2501145256Sjkoshy{
2502170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2503164936Sjulian	return (td->td_sched->ts_flags & TSF_BOUND);
2504145256Sjkoshy}
2505145256Sjkoshy
2506171482Sjeff/*
2507171482Sjeff * Basic yield call.
2508171482Sjeff */
2509159630Sdavidxuvoid
2510159630Sdavidxusched_relinquish(struct thread *td)
2511159630Sdavidxu{
2512170293Sjeff	thread_lock(td);
2513178272Sjeff	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
2514170293Sjeff	thread_unlock(td);
2515159630Sdavidxu}
2516159630Sdavidxu
2517171482Sjeff/*
2518171482Sjeff * Return the total system load.
2519171482Sjeff */
2520145256Sjkoshyint
2521125289Sjeffsched_load(void)
2522125289Sjeff{
2523125289Sjeff#ifdef SMP
2524125289Sjeff	int total;
2525125289Sjeff	int i;
2526125289Sjeff
2527125289Sjeff	total = 0;
2528209059Sjhb	CPU_FOREACH(i)
2529176735Sjeff		total += TDQ_CPU(i)->tdq_sysload;
2530125289Sjeff	return (total);
2531125289Sjeff#else
2532165620Sjeff	return (TDQ_SELF()->tdq_sysload);
2533125289Sjeff#endif
2534125289Sjeff}
2535125289Sjeff
2536125289Sjeffint
2537109864Sjeffsched_sizeof_proc(void)
2538109864Sjeff{
2539109864Sjeff	return (sizeof(struct proc));
2540109864Sjeff}
2541109864Sjeff
2542109864Sjeffint
2543109864Sjeffsched_sizeof_thread(void)
2544109864Sjeff{
2545109864Sjeff	return (sizeof(struct thread) + sizeof(struct td_sched));
2546109864Sjeff}
2547159570Sdavidxu
2548191676Sjeff#ifdef SMP
2549191676Sjeff#define	TDQ_IDLESPIN(tdq)						\
2550191676Sjeff    ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
2551191676Sjeff#else
2552191676Sjeff#define	TDQ_IDLESPIN(tdq)	1
2553191676Sjeff#endif
2554191676Sjeff
2555166190Sjeff/*
2556166190Sjeff * The actual idle process.
2557166190Sjeff */
2558166190Sjeffvoid
2559166190Sjeffsched_idletd(void *dummy)
2560166190Sjeff{
2561166190Sjeff	struct thread *td;
2562171482Sjeff	struct tdq *tdq;
2563247150Smav	int oldswitchcnt, switchcnt;
2564178277Sjeff	int i;
2565166190Sjeff
2566191643Sjeff	mtx_assert(&Giant, MA_NOTOWNED);
2567166190Sjeff	td = curthread;
2568171482Sjeff	tdq = TDQ_SELF();
2569247150Smav	oldswitchcnt = -1;
2570171482Sjeff	for (;;) {
2571247150Smav		if (tdq->tdq_load) {
2572247150Smav			thread_lock(td);
2573247150Smav			mi_switch(SW_VOL | SWT_IDLE, NULL);
2574247150Smav			thread_unlock(td);
2575247150Smav		}
2576247150Smav		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2577171482Sjeff#ifdef SMP
2578247150Smav		if (switchcnt != oldswitchcnt) {
2579247150Smav			oldswitchcnt = switchcnt;
2580247150Smav			if (tdq_idled(tdq) == 0)
2581247150Smav				continue;
2582247150Smav		}
2583247150Smav		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2584247150Smav#else
2585247150Smav		oldswitchcnt = switchcnt;
2586171482Sjeff#endif
2587178277Sjeff		/*
2588178277Sjeff		 * If we're switching very frequently, spin while checking
2589178277Sjeff		 * for load rather than entering a low power state that
2590191643Sjeff		 * may require an IPI.  However, don't do any busy
2591191643Sjeff		 * loops while on SMT machines as this simply steals
2592191643Sjeff		 * cycles from cores doing useful work.
2593178277Sjeff		 */
2594191676Sjeff		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
2595178277Sjeff			for (i = 0; i < sched_idlespins; i++) {
2596178277Sjeff				if (tdq->tdq_load)
2597178277Sjeff					break;
2598178277Sjeff				cpu_spinwait();
2599178277Sjeff			}
2600178277Sjeff		}
2601247150Smav
2602247150Smav		/* If there was context switch during spin, restart it. */
2603191643Sjeff		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2604247150Smav		if (tdq->tdq_load != 0 || switchcnt != oldswitchcnt)
2605247150Smav			continue;
2606247150Smav
2607247150Smav		/* Run main MD idle handler. */
2608247150Smav		tdq->tdq_cpu_idle = 1;
2609247150Smav		cpu_idle(switchcnt * 4 > sched_idlespinthresh);
2610247150Smav		tdq->tdq_cpu_idle = 0;
2611247150Smav
2612247150Smav		/*
2613247150Smav		 * Account thread-less hardware interrupts and
2614247150Smav		 * other wakeup reasons equal to context switches.
2615247150Smav		 */
2616247150Smav		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2617247150Smav		if (switchcnt != oldswitchcnt)
2618247150Smav			continue;
2619247150Smav		tdq->tdq_switchcnt++;
2620247150Smav		oldswitchcnt++;
2621171482Sjeff	}
2622166190Sjeff}
2623166190Sjeff
2624170293Sjeff/*
2625170293Sjeff * A CPU is entering for the first time or a thread is exiting.
2626170293Sjeff */
2627170293Sjeffvoid
2628170293Sjeffsched_throw(struct thread *td)
2629170293Sjeff{
2630172411Sjeff	struct thread *newtd;
2631171482Sjeff	struct tdq *tdq;
2632171482Sjeff
2633171482Sjeff	tdq = TDQ_SELF();
2634170293Sjeff	if (td == NULL) {
2635171482Sjeff		/* Correct spinlock nesting and acquire the correct lock. */
2636171482Sjeff		TDQ_LOCK(tdq);
2637170293Sjeff		spinlock_exit();
2638230079Sjhb		PCPU_SET(switchtime, cpu_ticks());
2639230079Sjhb		PCPU_SET(switchticks, ticks);
2640170293Sjeff	} else {
2641171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2642177435Sjeff		tdq_load_rem(tdq, td);
2643174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2644170293Sjeff	}
2645170293Sjeff	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2646172411Sjeff	newtd = choosethread();
2647172411Sjeff	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2648172411Sjeff	cpu_throw(td, newtd);		/* doesn't return */
2649170293Sjeff}
2650170293Sjeff
2651171482Sjeff/*
2652171482Sjeff * This is called from fork_exit().  Just acquire the correct locks and
2653171482Sjeff * let fork do the rest of the work.
2654171482Sjeff */
2655170293Sjeffvoid
2656170600Sjeffsched_fork_exit(struct thread *td)
2657170293Sjeff{
2658171482Sjeff	struct td_sched *ts;
2659171482Sjeff	struct tdq *tdq;
2660171482Sjeff	int cpuid;
2661170293Sjeff
2662170293Sjeff	/*
2663170293Sjeff	 * Finish setting up thread glue so that it begins execution in a
2664171482Sjeff	 * non-nested critical section with the scheduler lock held.
2665170293Sjeff	 */
2666171482Sjeff	cpuid = PCPU_GET(cpuid);
2667171482Sjeff	tdq = TDQ_CPU(cpuid);
2668171482Sjeff	ts = td->td_sched;
2669171482Sjeff	if (TD_IS_IDLETHREAD(td))
2670171482Sjeff		td->td_lock = TDQ_LOCKPTR(tdq);
2671171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2672171482Sjeff	td->td_oncpu = cpuid;
2673172411Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2674174629Sjeff	lock_profile_obtain_lock_success(
2675174629Sjeff	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2676170293Sjeff}
2677170293Sjeff
2678187357Sjeff/*
2679187357Sjeff * Create on first use to catch odd startup conditons.
2680187357Sjeff */
2681187357Sjeffchar *
2682187357Sjeffsched_tdname(struct thread *td)
2683187357Sjeff{
2684187357Sjeff#ifdef KTR
2685187357Sjeff	struct td_sched *ts;
2686187357Sjeff
2687187357Sjeff	ts = td->td_sched;
2688187357Sjeff	if (ts->ts_name[0] == '\0')
2689187357Sjeff		snprintf(ts->ts_name, sizeof(ts->ts_name),
2690187357Sjeff		    "%s tid %d", td->td_name, td->td_tid);
2691187357Sjeff	return (ts->ts_name);
2692187357Sjeff#else
2693187357Sjeff	return (td->td_name);
2694187357Sjeff#endif
2695187357Sjeff}
2696187357Sjeff
2697233814Sjhb#ifdef KTR
2698233814Sjhbvoid
2699233814Sjhbsched_clear_tdname(struct thread *td)
2700233814Sjhb{
2701233814Sjhb	struct td_sched *ts;
2702233814Sjhb
2703233814Sjhb	ts = td->td_sched;
2704233814Sjhb	ts->ts_name[0] = '\0';
2705233814Sjhb}
2706233814Sjhb#endif
2707233814Sjhb
2708184439Sivoras#ifdef SMP
2709184439Sivoras
2710184439Sivoras/*
2711184439Sivoras * Build the CPU topology dump string. Is recursively called to collect
2712184439Sivoras * the topology tree.
2713184439Sivoras */
2714184439Sivorasstatic int
2715184439Sivorassysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
2716184439Sivoras    int indent)
2717184439Sivoras{
2718222813Sattilio	char cpusetbuf[CPUSETBUFSIZ];
2719184439Sivoras	int i, first;
2720184439Sivoras
2721184439Sivoras	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
2722212821Savg	    "", 1 + indent / 2, cg->cg_level);
2723222813Sattilio	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
2724222813Sattilio	    cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
2725184439Sivoras	first = TRUE;
2726184439Sivoras	for (i = 0; i < MAXCPU; i++) {
2727222813Sattilio		if (CPU_ISSET(i, &cg->cg_mask)) {
2728184439Sivoras			if (!first)
2729184439Sivoras				sbuf_printf(sb, ", ");
2730184439Sivoras			else
2731184439Sivoras				first = FALSE;
2732184439Sivoras			sbuf_printf(sb, "%d", i);
2733184439Sivoras		}
2734184439Sivoras	}
2735184439Sivoras	sbuf_printf(sb, "</cpu>\n");
2736184439Sivoras
2737184439Sivoras	if (cg->cg_flags != 0) {
2738210117Sivoras		sbuf_printf(sb, "%*s <flags>", indent, "");
2739184439Sivoras		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
2740208982Sivoras			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
2741208983Sivoras		if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
2742208983Sivoras			sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
2743191643Sjeff		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
2744208983Sivoras			sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
2745210117Sivoras		sbuf_printf(sb, "</flags>\n");
2746184439Sivoras	}
2747184439Sivoras
2748184439Sivoras	if (cg->cg_children > 0) {
2749184439Sivoras		sbuf_printf(sb, "%*s <children>\n", indent, "");
2750184439Sivoras		for (i = 0; i < cg->cg_children; i++)
2751184439Sivoras			sysctl_kern_sched_topology_spec_internal(sb,
2752184439Sivoras			    &cg->cg_child[i], indent+2);
2753184439Sivoras		sbuf_printf(sb, "%*s </children>\n", indent, "");
2754184439Sivoras	}
2755184439Sivoras	sbuf_printf(sb, "%*s</group>\n", indent, "");
2756184439Sivoras	return (0);
2757184439Sivoras}
2758184439Sivoras
2759184439Sivoras/*
2760184439Sivoras * Sysctl handler for retrieving topology dump. It's a wrapper for
2761184439Sivoras * the recursive sysctl_kern_smp_topology_spec_internal().
2762184439Sivoras */
2763184439Sivorasstatic int
2764184439Sivorassysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
2765184439Sivoras{
2766184439Sivoras	struct sbuf *topo;
2767184439Sivoras	int err;
2768184439Sivoras
2769184439Sivoras	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
2770184439Sivoras
2771184570Sivoras	topo = sbuf_new(NULL, NULL, 500, SBUF_AUTOEXTEND);
2772184439Sivoras	if (topo == NULL)
2773184439Sivoras		return (ENOMEM);
2774184439Sivoras
2775184439Sivoras	sbuf_printf(topo, "<groups>\n");
2776184439Sivoras	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
2777184439Sivoras	sbuf_printf(topo, "</groups>\n");
2778184439Sivoras
2779184439Sivoras	if (err == 0) {
2780184439Sivoras		sbuf_finish(topo);
2781184439Sivoras		err = SYSCTL_OUT(req, sbuf_data(topo), sbuf_len(topo));
2782184439Sivoras	}
2783184439Sivoras	sbuf_delete(topo);
2784184439Sivoras	return (err);
2785184439Sivoras}
2786214510Sdavidxu
2787184439Sivoras#endif
2788184439Sivoras
2789241249Smavstatic int
2790241249Smavsysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
2791241249Smav{
2792241249Smav	int error, new_val, period;
2793241249Smav
2794241249Smav	period = 1000000 / realstathz;
2795241249Smav	new_val = period * sched_slice;
2796241249Smav	error = sysctl_handle_int(oidp, &new_val, 0, req);
2797241249Smav	if (error != 0 || req->newptr == NULL)
2798241249Smav		return (error);
2799241249Smav	if (new_val <= 0)
2800241249Smav		return (EINVAL);
2801241249Smav	sched_slice = imax(1, (new_val + period / 2) / period);
2802241249Smav	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
2803241249Smav	    realstathz);
2804241249Smav	return (0);
2805241249Smav}
2806241249Smav
2807177435SjeffSYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2808171482SjeffSYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2809165762Sjeff    "Scheduler name");
2810241249SmavSYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
2811241249Smav    NULL, 0, sysctl_kern_quantum, "I",
2812241249Smav    "Quantum for timeshare threads in microseconds");
2813171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2814241249Smav    "Quantum for timeshare threads in stathz ticks");
2815171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2816241249Smav    "Interactivity score threshold");
2817241249SmavSYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW,
2818241249Smav    &preempt_thresh, 0,
2819241249Smav    "Maximal (lowest) priority for preemption");
2820241249SmavSYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost, 0,
2821241249Smav    "Assign static kernel priorities to sleeping threads");
2822241249SmavSYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins, 0,
2823241249Smav    "Number of times idle thread will spin waiting for new work");
2824241249SmavSYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW,
2825241249Smav    &sched_idlespinthresh, 0,
2826241249Smav    "Threshold before we will permit idle thread spinning");
2827166108Sjeff#ifdef SMP
2828171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2829171482Sjeff    "Number of hz ticks to keep thread affinity for");
2830171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2831171482Sjeff    "Enables the long-term load balancer");
2832172409SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2833172409Sjeff    &balance_interval, 0,
2834241249Smav    "Average period in stathz ticks to run the long-term balancer");
2835171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2836171482Sjeff    "Attempts to steal work from other cores before idling");
2837171506SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2838241249Smav    "Minimum load on remote CPU before we'll steal");
2839184439SivorasSYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
2840241249Smav    CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
2841184439Sivoras    "XML dump of detected CPU topology");
2842166108Sjeff#endif
2843165762Sjeff
2844172264Sjeff/* ps compat.  All cpu percentages from ULE are weighted. */
2845172293Sjeffstatic int ccpu = 0;
2846165762SjeffSYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2847