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: stable/10/sys/kern/sched_ule.c 316841 2017-04-14 14:44:06Z avg $");
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>
56235459Srstone#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
80171482Sjeff#define	KTR_ULE	0
81166137Sjeff
82187679Sjeff#define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
83187679Sjeff#define	TDQ_NAME_LEN	(sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
84224221Sattilio#define	TDQ_LOADNAME_LEN	(sizeof("CPU ") + sizeof(__XSTRING(MAXCPU)) - 1 + sizeof(" load"))
85187357Sjeff
86166137Sjeff/*
87171482Sjeff * Thread scheduler specific section.  All fields are protected
88171482Sjeff * by the thread lock.
89146954Sjeff */
90164936Sjulianstruct td_sched {
91171482Sjeff	struct runq	*ts_runq;	/* Run-queue we're queued on. */
92171482Sjeff	short		ts_flags;	/* TSF_* flags. */
93164936Sjulian	u_char		ts_cpu;		/* CPU that we have affinity for. */
94177009Sjeff	int		ts_rltick;	/* Real last tick, for affinity. */
95171482Sjeff	int		ts_slice;	/* Ticks of slice remaining. */
96171482Sjeff	u_int		ts_slptime;	/* Number of ticks we vol. slept */
97171482Sjeff	u_int		ts_runtime;	/* Number of ticks we were running */
98164936Sjulian	int		ts_ltick;	/* Last tick that we were running on */
99164936Sjulian	int		ts_ftick;	/* First tick that we were running on */
100164936Sjulian	int		ts_ticks;	/* Tick count */
101187357Sjeff#ifdef KTR
102187357Sjeff	char		ts_name[TS_NAME_LEN];
103187357Sjeff#endif
104134791Sjulian};
105164936Sjulian/* flags kept in ts_flags */
106166108Sjeff#define	TSF_BOUND	0x0001		/* Thread can not migrate. */
107166108Sjeff#define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
108121790Sjeff
109164936Sjulianstatic struct td_sched td_sched0;
110109864Sjeff
111176735Sjeff#define	THREAD_CAN_MIGRATE(td)	((td)->td_pinned == 0)
112176735Sjeff#define	THREAD_CAN_SCHED(td, cpu)	\
113176735Sjeff    CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
114176735Sjeff
115109864Sjeff/*
116217351Sjhb * Priority ranges used for interactive and non-interactive timeshare
117217410Sjhb * threads.  The timeshare priorities are split up into four ranges.
118217410Sjhb * The first range handles interactive threads.  The last three ranges
119217410Sjhb * (NHALF, x, and NHALF) handle non-interactive threads with the outer
120217410Sjhb * ranges supporting nice values.
121217351Sjhb */
122217410Sjhb#define	PRI_TIMESHARE_RANGE	(PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
123217410Sjhb#define	PRI_INTERACT_RANGE	((PRI_TIMESHARE_RANGE - SCHED_PRI_NRESV) / 2)
124228718Savg#define	PRI_BATCH_RANGE		(PRI_TIMESHARE_RANGE - PRI_INTERACT_RANGE)
125217410Sjhb
126217410Sjhb#define	PRI_MIN_INTERACT	PRI_MIN_TIMESHARE
127217410Sjhb#define	PRI_MAX_INTERACT	(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE - 1)
128217410Sjhb#define	PRI_MIN_BATCH		(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE)
129217351Sjhb#define	PRI_MAX_BATCH		PRI_MAX_TIMESHARE
130217351Sjhb
131217351Sjhb/*
132165762Sjeff * Cpu percentage computation macros and defines.
133111857Sjeff *
134165762Sjeff * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
135165762Sjeff * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
136165796Sjeff * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
137165762Sjeff * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
138165762Sjeff * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
139165762Sjeff * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
140165762Sjeff */
141165762Sjeff#define	SCHED_TICK_SECS		10
142165762Sjeff#define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
143165796Sjeff#define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
144165762Sjeff#define	SCHED_TICK_SHIFT	10
145165762Sjeff#define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
146165830Sjeff#define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
147165762Sjeff
148165762Sjeff/*
149165762Sjeff * These macros determine priorities for non-interactive threads.  They are
150165762Sjeff * assigned a priority based on their recent cpu utilization as expressed
151165762Sjeff * by the ratio of ticks to the tick total.  NHALF priorities at the start
152165762Sjeff * and end of the MIN to MAX timeshare range are only reachable with negative
153165762Sjeff * or positive nice respectively.
154165762Sjeff *
155165762Sjeff * PRI_RANGE:	Priority range for utilization dependent priorities.
156116642Sjeff * PRI_NRESV:	Number of nice values.
157165762Sjeff * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
158165762Sjeff * PRI_NICE:	Determines the part of the priority inherited from nice.
159109864Sjeff */
160165762Sjeff#define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
161121869Sjeff#define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
162217351Sjhb#define	SCHED_PRI_MIN		(PRI_MIN_BATCH + SCHED_PRI_NHALF)
163217351Sjhb#define	SCHED_PRI_MAX		(PRI_MAX_BATCH - SCHED_PRI_NHALF)
164217237Sjhb#define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN + 1)
165165762Sjeff#define	SCHED_PRI_TICKS(ts)						\
166165762Sjeff    (SCHED_TICK_HZ((ts)) /						\
167165827Sjeff    (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
168165762Sjeff#define	SCHED_PRI_NICE(nice)	(nice)
169109864Sjeff
170109864Sjeff/*
171165762Sjeff * These determine the interactivity of a process.  Interactivity differs from
172165762Sjeff * cpu utilization in that it expresses the voluntary time slept vs time ran
173165762Sjeff * while cpu utilization includes all time not running.  This more accurately
174165762Sjeff * models the intent of the thread.
175109864Sjeff *
176110645Sjeff * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
177110645Sjeff *		before throttling back.
178121868Sjeff * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
179116365Sjeff * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
180215102Sattilio * INTERACT_THRESH:	Threshold for placement on the current runq.
181109864Sjeff */
182165762Sjeff#define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
183165762Sjeff#define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
184116365Sjeff#define	SCHED_INTERACT_MAX	(100)
185116365Sjeff#define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
186121126Sjeff#define	SCHED_INTERACT_THRESH	(30)
187111857Sjeff
188242736Sjeff/*
189242736Sjeff * These parameters determine the slice behavior for batch work.
190242736Sjeff */
191242736Sjeff#define	SCHED_SLICE_DEFAULT_DIVISOR	10	/* ~94 ms, 12 stathz ticks. */
192242736Sjeff#define	SCHED_SLICE_MIN_DIVISOR		6	/* DEFAULT/MIN = ~16 ms. */
193242736Sjeff
194239157Smav/* Flags kept in td_flags. */
195239157Smav#define	TDF_SLICEEND	TDF_SCHED2	/* Thread time slice is over. */
196239157Smav
197109864Sjeff/*
198165762Sjeff * tickincr:		Converts a stathz tick into a hz domain scaled by
199165762Sjeff *			the shift factor.  Without the shift the error rate
200165762Sjeff *			due to rounding would be unacceptably high.
201165762Sjeff * realstathz:		stathz is sometimes 0 and run off of hz.
202165762Sjeff * sched_slice:		Runtime of each thread before rescheduling.
203171482Sjeff * preempt_thresh:	Priority threshold for preemption and remote IPIs.
204109864Sjeff */
205165762Sjeffstatic int sched_interact = SCHED_INTERACT_THRESH;
206241844Seadlerstatic int tickincr = 8 << SCHED_TICK_SHIFT;
207242736Sjeffstatic int realstathz = 127;	/* reset during boot. */
208242736Sjeffstatic int sched_slice = 10;	/* reset during boot. */
209242736Sjeffstatic int sched_slice_min = 1;	/* reset during boot. */
210172345Sjeff#ifdef PREEMPTION
211172345Sjeff#ifdef FULL_PREEMPTION
212172345Sjeffstatic int preempt_thresh = PRI_MAX_IDLE;
213172345Sjeff#else
214171482Sjeffstatic int preempt_thresh = PRI_MIN_KERN;
215172345Sjeff#endif
216172345Sjeff#else
217172345Sjeffstatic int preempt_thresh = 0;
218172345Sjeff#endif
219217351Sjhbstatic int static_boost = PRI_MIN_BATCH;
220178277Sjeffstatic int sched_idlespins = 10000;
221232740Smavstatic int sched_idlespinthresh = -1;
222109864Sjeff
223109864Sjeff/*
224171482Sjeff * tdq - per processor runqs and statistics.  All fields are protected by the
225171482Sjeff * tdq_lock.  The load and lowpri may be accessed without to avoid excess
226171482Sjeff * locking in sched_pickcpu();
227109864Sjeff */
228164936Sjulianstruct tdq {
229242014Sjimharris	/*
230242014Sjimharris	 * Ordered to improve efficiency of cpu_search() and switch().
231242014Sjimharris	 * tdq_lock is padded to avoid false sharing with tdq_load and
232242014Sjimharris	 * tdq_cpu_idle.
233242014Sjimharris	 */
234242402Sattilio	struct mtx_padalign tdq_lock;		/* run queue lock. */
235176735Sjeff	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
236178277Sjeff	volatile int	tdq_load;		/* Aggregate load. */
237212416Smav	volatile int	tdq_cpu_idle;		/* cpu_idle() is active. */
238176735Sjeff	int		tdq_sysload;		/* For loadavg, !ITHD load. */
239177009Sjeff	int		tdq_transferable;	/* Transferable thread count. */
240178277Sjeff	short		tdq_switchcnt;		/* Switches this tick. */
241178277Sjeff	short		tdq_oldswitchcnt;	/* Switches last tick. */
242177009Sjeff	u_char		tdq_lowpri;		/* Lowest priority thread. */
243177009Sjeff	u_char		tdq_ipipending;		/* IPI pending. */
244166557Sjeff	u_char		tdq_idx;		/* Current insert index. */
245166557Sjeff	u_char		tdq_ridx;		/* Current removal index. */
246177009Sjeff	struct runq	tdq_realtime;		/* real-time run queue. */
247177009Sjeff	struct runq	tdq_timeshare;		/* timeshare run queue. */
248177009Sjeff	struct runq	tdq_idle;		/* Queue of IDLE threads. */
249187357Sjeff	char		tdq_name[TDQ_NAME_LEN];
250187357Sjeff#ifdef KTR
251187357Sjeff	char		tdq_loadname[TDQ_LOADNAME_LEN];
252187357Sjeff#endif
253171482Sjeff} __aligned(64);
254109864Sjeff
255178277Sjeff/* Idle thread states and config. */
256178277Sjeff#define	TDQ_RUNNING	1
257178277Sjeff#define	TDQ_IDLE	2
258166108Sjeff
259123433Sjeff#ifdef SMP
260184439Sivorasstruct cpu_group *cpu_top;		/* CPU topology */
261123433Sjeff
262176735Sjeff#define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
263176735Sjeff#define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
264166108Sjeff
265123433Sjeff/*
266166108Sjeff * Run-time tunables.
267166108Sjeff */
268171506Sjeffstatic int rebalance = 1;
269172409Sjeffstatic int balance_interval = 128;	/* Default set in sched_initticks(). */
270166108Sjeffstatic int affinity;
271171506Sjeffstatic int steal_idle = 1;
272171506Sjeffstatic int steal_thresh = 2;
273166108Sjeff
274166108Sjeff/*
275165620Sjeff * One thread queue per processor.
276109864Sjeff */
277164936Sjulianstatic struct tdq	tdq_cpu[MAXCPU];
278172409Sjeffstatic struct tdq	*balance_tdq;
279172409Sjeffstatic int balance_ticks;
280232207Smavstatic DPCPU_DEFINE(uint32_t, randomval);
281129982Sjeff
282164936Sjulian#define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
283164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu[(x)])
284171713Sjeff#define	TDQ_ID(x)	((int)((x) - tdq_cpu))
285123433Sjeff#else	/* !SMP */
286164936Sjulianstatic struct tdq	tdq_cpu;
287129982Sjeff
288170315Sjeff#define	TDQ_ID(x)	(0)
289164936Sjulian#define	TDQ_SELF()	(&tdq_cpu)
290164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu)
291110028Sjeff#endif
292109864Sjeff
293171482Sjeff#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
294171482Sjeff#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
295171482Sjeff#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
296171482Sjeff#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
297242402Sattilio#define	TDQ_LOCKPTR(t)		((struct mtx *)(&(t)->tdq_lock))
298171482Sjeff
299163709Sjbstatic void sched_priority(struct thread *);
300146954Sjeffstatic void sched_thread_priority(struct thread *, u_char);
301163709Sjbstatic int sched_interact_score(struct thread *);
302163709Sjbstatic void sched_interact_update(struct thread *);
303163709Sjbstatic void sched_interact_fork(struct thread *);
304232917Smavstatic void sched_pctcpu_update(struct td_sched *, int);
305109864Sjeff
306110267Sjeff/* Operations on per processor queues */
307177435Sjeffstatic struct thread *tdq_choose(struct tdq *);
308164936Sjulianstatic void tdq_setup(struct tdq *);
309177435Sjeffstatic void tdq_load_add(struct tdq *, struct thread *);
310177435Sjeffstatic void tdq_load_rem(struct tdq *, struct thread *);
311177435Sjeffstatic __inline void tdq_runq_add(struct tdq *, struct thread *, int);
312177435Sjeffstatic __inline void tdq_runq_rem(struct tdq *, struct thread *);
313177005Sjeffstatic inline int sched_shouldpreempt(int, int, int);
314164936Sjulianvoid tdq_print(int cpu);
315165762Sjeffstatic void runq_print(struct runq *rq);
316171482Sjeffstatic void tdq_add(struct tdq *, struct thread *, int);
317110267Sjeff#ifdef SMP
318176735Sjeffstatic int tdq_move(struct tdq *, struct tdq *);
319171482Sjeffstatic int tdq_idled(struct tdq *);
320177435Sjeffstatic void tdq_notify(struct tdq *, struct thread *);
321177435Sjeffstatic struct thread *tdq_steal(struct tdq *, int);
322177435Sjeffstatic struct thread *runq_steal(struct runq *, int);
323177435Sjeffstatic int sched_pickcpu(struct thread *, int);
324172409Sjeffstatic void sched_balance(void);
325176735Sjeffstatic int sched_balance_pair(struct tdq *, struct tdq *);
326177435Sjeffstatic inline struct tdq *sched_setcpu(struct thread *, int, int);
327171482Sjeffstatic inline void thread_unblock_switch(struct thread *, struct mtx *);
328171713Sjeffstatic struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
329184439Sivorasstatic int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
330184439Sivorasstatic int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
331184439Sivoras    struct cpu_group *cg, int indent);
332121790Sjeff#endif
333110028Sjeff
334165762Sjeffstatic void sched_setup(void *dummy);
335177253SrwatsonSYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
336165762Sjeff
337165762Sjeffstatic void sched_initticks(void *dummy);
338177253SrwatsonSYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
339177253Srwatson    NULL);
340165762Sjeff
341235459SrstoneSDT_PROVIDER_DEFINE(sched);
342235459Srstone
343260817SavgSDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
344235459Srstone    "struct proc *", "uint8_t");
345260817SavgSDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
346235459Srstone    "struct proc *", "void *");
347260817SavgSDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
348235459Srstone    "struct proc *", "void *", "int");
349260817SavgSDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
350235459Srstone    "struct proc *", "uint8_t", "struct thread *");
351260817SavgSDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
352260817SavgSDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
353235459Srstone    "struct proc *");
354260817SavgSDT_PROBE_DEFINE(sched, , , on__cpu);
355260817SavgSDT_PROBE_DEFINE(sched, , , remain__cpu);
356260817SavgSDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
357235459Srstone    "struct proc *");
358235459Srstone
359171482Sjeff/*
360171482Sjeff * Print the threads waiting on a run-queue.
361171482Sjeff */
362165762Sjeffstatic void
363165762Sjeffrunq_print(struct runq *rq)
364165762Sjeff{
365165762Sjeff	struct rqhead *rqh;
366177435Sjeff	struct thread *td;
367165762Sjeff	int pri;
368165762Sjeff	int j;
369165762Sjeff	int i;
370165762Sjeff
371165762Sjeff	for (i = 0; i < RQB_LEN; i++) {
372165762Sjeff		printf("\t\trunq bits %d 0x%zx\n",
373165762Sjeff		    i, rq->rq_status.rqb_bits[i]);
374165762Sjeff		for (j = 0; j < RQB_BPW; j++)
375165762Sjeff			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
376165762Sjeff				pri = j + (i << RQB_L2BPW);
377165762Sjeff				rqh = &rq->rq_queues[pri];
378177435Sjeff				TAILQ_FOREACH(td, rqh, td_runq) {
379165762Sjeff					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
380177435Sjeff					    td, td->td_name, td->td_priority,
381177435Sjeff					    td->td_rqindex, pri);
382165762Sjeff				}
383165762Sjeff			}
384165762Sjeff	}
385165762Sjeff}
386165762Sjeff
387171482Sjeff/*
388171482Sjeff * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
389171482Sjeff */
390113357Sjeffvoid
391164936Sjuliantdq_print(int cpu)
392110267Sjeff{
393164936Sjulian	struct tdq *tdq;
394112994Sjeff
395164936Sjulian	tdq = TDQ_CPU(cpu);
396112994Sjeff
397171713Sjeff	printf("tdq %d:\n", TDQ_ID(tdq));
398176735Sjeff	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
399176735Sjeff	printf("\tLock name:      %s\n", tdq->tdq_name);
400165620Sjeff	printf("\tload:           %d\n", tdq->tdq_load);
401178277Sjeff	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
402178277Sjeff	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
403171482Sjeff	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
404165766Sjeff	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
405178277Sjeff	printf("\tload transferable: %d\n", tdq->tdq_transferable);
406178277Sjeff	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
407165762Sjeff	printf("\trealtime runq:\n");
408165762Sjeff	runq_print(&tdq->tdq_realtime);
409165762Sjeff	printf("\ttimeshare runq:\n");
410165762Sjeff	runq_print(&tdq->tdq_timeshare);
411165762Sjeff	printf("\tidle runq:\n");
412165762Sjeff	runq_print(&tdq->tdq_idle);
413113357Sjeff}
414112994Sjeff
415177005Sjeffstatic inline int
416177005Sjeffsched_shouldpreempt(int pri, int cpri, int remote)
417177005Sjeff{
418177005Sjeff	/*
419177005Sjeff	 * If the new priority is not better than the current priority there is
420177005Sjeff	 * nothing to do.
421177005Sjeff	 */
422177005Sjeff	if (pri >= cpri)
423177005Sjeff		return (0);
424177005Sjeff	/*
425177005Sjeff	 * Always preempt idle.
426177005Sjeff	 */
427177005Sjeff	if (cpri >= PRI_MIN_IDLE)
428177005Sjeff		return (1);
429177005Sjeff	/*
430177005Sjeff	 * If preemption is disabled don't preempt others.
431177005Sjeff	 */
432177005Sjeff	if (preempt_thresh == 0)
433177005Sjeff		return (0);
434177005Sjeff	/*
435177005Sjeff	 * Preempt if we exceed the threshold.
436177005Sjeff	 */
437177005Sjeff	if (pri <= preempt_thresh)
438177005Sjeff		return (1);
439177005Sjeff	/*
440217351Sjhb	 * If we're interactive or better and there is non-interactive
441217351Sjhb	 * or worse running preempt only remote processors.
442177005Sjeff	 */
443217351Sjhb	if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
444177005Sjeff		return (1);
445177005Sjeff	return (0);
446177005Sjeff}
447177005Sjeff
448171482Sjeff/*
449171482Sjeff * Add a thread to the actual run-queue.  Keeps transferable counts up to
450171482Sjeff * date with what is actually on the run-queue.  Selects the correct
451171482Sjeff * queue position for timeshare threads.
452171482Sjeff */
453122744Sjeffstatic __inline void
454177435Sjefftdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
455122744Sjeff{
456177435Sjeff	struct td_sched *ts;
457177042Sjeff	u_char pri;
458177042Sjeff
459171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
460177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
461177009Sjeff
462177435Sjeff	pri = td->td_priority;
463177435Sjeff	ts = td->td_sched;
464177435Sjeff	TD_SET_RUNQ(td);
465177435Sjeff	if (THREAD_CAN_MIGRATE(td)) {
466165620Sjeff		tdq->tdq_transferable++;
467164936Sjulian		ts->ts_flags |= TSF_XFERABLE;
468123433Sjeff	}
469217351Sjhb	if (pri < PRI_MIN_BATCH) {
470177042Sjeff		ts->ts_runq = &tdq->tdq_realtime;
471217351Sjhb	} else if (pri <= PRI_MAX_BATCH) {
472177042Sjeff		ts->ts_runq = &tdq->tdq_timeshare;
473217351Sjhb		KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
474165762Sjeff			("Invalid priority %d on timeshare runq", pri));
475165762Sjeff		/*
476165762Sjeff		 * This queue contains only priorities between MIN and MAX
477165762Sjeff		 * realtime.  Use the whole queue to represent these values.
478165762Sjeff		 */
479171713Sjeff		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
480228718Savg			pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
481165762Sjeff			pri = (pri + tdq->tdq_idx) % RQ_NQS;
482165766Sjeff			/*
483165766Sjeff			 * This effectively shortens the queue by one so we
484165766Sjeff			 * can have a one slot difference between idx and
485165766Sjeff			 * ridx while we wait for threads to drain.
486165766Sjeff			 */
487165766Sjeff			if (tdq->tdq_ridx != tdq->tdq_idx &&
488165766Sjeff			    pri == tdq->tdq_ridx)
489167664Sjeff				pri = (unsigned char)(pri - 1) % RQ_NQS;
490165762Sjeff		} else
491165766Sjeff			pri = tdq->tdq_ridx;
492177435Sjeff		runq_add_pri(ts->ts_runq, td, pri, flags);
493177042Sjeff		return;
494165762Sjeff	} else
495177009Sjeff		ts->ts_runq = &tdq->tdq_idle;
496177435Sjeff	runq_add(ts->ts_runq, td, flags);
497177009Sjeff}
498177009Sjeff
499171482Sjeff/*
500171482Sjeff * Remove a thread from a run-queue.  This typically happens when a thread
501171482Sjeff * is selected to run.  Running threads are not on the queue and the
502171482Sjeff * transferable count does not reflect them.
503171482Sjeff */
504122744Sjeffstatic __inline void
505177435Sjefftdq_runq_rem(struct tdq *tdq, struct thread *td)
506122744Sjeff{
507177435Sjeff	struct td_sched *ts;
508177435Sjeff
509177435Sjeff	ts = td->td_sched;
510171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
511171482Sjeff	KASSERT(ts->ts_runq != NULL,
512177435Sjeff	    ("tdq_runq_remove: thread %p null ts_runq", td));
513164936Sjulian	if (ts->ts_flags & TSF_XFERABLE) {
514165620Sjeff		tdq->tdq_transferable--;
515164936Sjulian		ts->ts_flags &= ~TSF_XFERABLE;
516123433Sjeff	}
517165766Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
518165766Sjeff		if (tdq->tdq_idx != tdq->tdq_ridx)
519177435Sjeff			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
520165766Sjeff		else
521177435Sjeff			runq_remove_idx(ts->ts_runq, td, NULL);
522165766Sjeff	} else
523177435Sjeff		runq_remove(ts->ts_runq, td);
524122744Sjeff}
525122744Sjeff
526171482Sjeff/*
527171482Sjeff * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
528171482Sjeff * for this thread to the referenced thread queue.
529171482Sjeff */
530113357Sjeffstatic void
531177435Sjefftdq_load_add(struct tdq *tdq, struct thread *td)
532113357Sjeff{
533171482Sjeff
534171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
535177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
536177902Sjeff
537165620Sjeff	tdq->tdq_load++;
538198854Sattilio	if ((td->td_flags & TDF_NOLOAD) == 0)
539177902Sjeff		tdq->tdq_sysload++;
540187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
541260817Savg	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
542110267Sjeff}
543113357Sjeff
544171482Sjeff/*
545171482Sjeff * Remove the load from a thread that is transitioning to a sleep state or
546171482Sjeff * exiting.
547171482Sjeff */
548112994Sjeffstatic void
549177435Sjefftdq_load_rem(struct tdq *tdq, struct thread *td)
550110267Sjeff{
551171482Sjeff
552177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
553171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
554171482Sjeff	KASSERT(tdq->tdq_load != 0,
555171713Sjeff	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
556177902Sjeff
557165620Sjeff	tdq->tdq_load--;
558198854Sattilio	if ((td->td_flags & TDF_NOLOAD) == 0)
559177902Sjeff		tdq->tdq_sysload--;
560187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
561260817Savg	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
562110267Sjeff}
563110267Sjeff
564176735Sjeff/*
565242736Sjeff * Bound timeshare latency by decreasing slice size as load increases.  We
566242736Sjeff * consider the maximum latency as the sum of the threads waiting to run
567242736Sjeff * aside from curthread and target no more than sched_slice latency but
568242736Sjeff * no less than sched_slice_min runtime.
569242736Sjeff */
570242736Sjeffstatic inline int
571242736Sjefftdq_slice(struct tdq *tdq)
572242736Sjeff{
573242736Sjeff	int load;
574242736Sjeff
575242736Sjeff	/*
576242736Sjeff	 * It is safe to use sys_load here because this is called from
577242736Sjeff	 * contexts where timeshare threads are running and so there
578242736Sjeff	 * cannot be higher priority load in the system.
579242736Sjeff	 */
580242736Sjeff	load = tdq->tdq_sysload - 1;
581242736Sjeff	if (load >= SCHED_SLICE_MIN_DIVISOR)
582242736Sjeff		return (sched_slice_min);
583242736Sjeff	if (load <= 1)
584242736Sjeff		return (sched_slice);
585242736Sjeff	return (sched_slice / load);
586242736Sjeff}
587242736Sjeff
588242736Sjeff/*
589176735Sjeff * Set lowpri to its exact value by searching the run-queue and
590176735Sjeff * evaluating curthread.  curthread may be passed as an optimization.
591176735Sjeff */
592176735Sjeffstatic void
593176735Sjefftdq_setlowpri(struct tdq *tdq, struct thread *ctd)
594176735Sjeff{
595176735Sjeff	struct thread *td;
596176735Sjeff
597176735Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
598176735Sjeff	if (ctd == NULL)
599176735Sjeff		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
600177435Sjeff	td = tdq_choose(tdq);
601177435Sjeff	if (td == NULL || td->td_priority > ctd->td_priority)
602176735Sjeff		tdq->tdq_lowpri = ctd->td_priority;
603176735Sjeff	else
604176735Sjeff		tdq->tdq_lowpri = td->td_priority;
605176735Sjeff}
606176735Sjeff
607113357Sjeff#ifdef SMP
608176735Sjeffstruct cpu_search {
609194779Sjeff	cpuset_t cs_mask;
610232207Smav	u_int	cs_prefer;
611232207Smav	int	cs_pri;		/* Min priority for low. */
612232207Smav	int	cs_limit;	/* Max load for low, min load for high. */
613232207Smav	int	cs_cpu;
614232207Smav	int	cs_load;
615176735Sjeff};
616176735Sjeff
617176735Sjeff#define	CPU_SEARCH_LOWEST	0x1
618176735Sjeff#define	CPU_SEARCH_HIGHEST	0x2
619176735Sjeff#define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
620176735Sjeff
621194779Sjeff#define	CPUSET_FOREACH(cpu, mask)				\
622194779Sjeff	for ((cpu) = 0; (cpu) <= mp_maxid; (cpu)++)		\
623222813Sattilio		if (CPU_ISSET(cpu, &mask))
624176735Sjeff
625268483Skibstatic __always_inline int cpu_search(const struct cpu_group *cg,
626268483Skib    struct cpu_search *low, struct cpu_search *high, const int match);
627268483Skibint __noinline cpu_search_lowest(const struct cpu_group *cg,
628268483Skib    struct cpu_search *low);
629268483Skibint __noinline cpu_search_highest(const struct cpu_group *cg,
630176735Sjeff    struct cpu_search *high);
631268483Skibint __noinline cpu_search_both(const struct cpu_group *cg,
632268483Skib    struct cpu_search *low, struct cpu_search *high);
633176735Sjeff
634116069Sjeff/*
635176735Sjeff * Search the tree of cpu_groups for the lowest or highest loaded cpu
636176735Sjeff * according to the match argument.  This routine actually compares the
637176735Sjeff * load on all paths through the tree and finds the least loaded cpu on
638176735Sjeff * the least loaded path, which may differ from the least loaded cpu in
639176735Sjeff * the system.  This balances work among caches and busses.
640116069Sjeff *
641176735Sjeff * This inline is instantiated in three forms below using constants for the
642176735Sjeff * match argument.  It is reduced to the minimum set for each case.  It is
643176735Sjeff * also recursive to the depth of the tree.
644116069Sjeff */
645268483Skibstatic __always_inline int
646232207Smavcpu_search(const struct cpu_group *cg, struct cpu_search *low,
647176735Sjeff    struct cpu_search *high, const int match)
648176735Sjeff{
649232207Smav	struct cpu_search lgroup;
650232207Smav	struct cpu_search hgroup;
651232207Smav	cpuset_t cpumask;
652232207Smav	struct cpu_group *child;
653232207Smav	struct tdq *tdq;
654234066Smav	int cpu, i, hload, lload, load, total, rnd, *rndptr;
655176735Sjeff
656176735Sjeff	total = 0;
657232207Smav	cpumask = cg->cg_mask;
658232207Smav	if (match & CPU_SEARCH_LOWEST) {
659232207Smav		lload = INT_MAX;
660232207Smav		lgroup = *low;
661232207Smav	}
662232207Smav	if (match & CPU_SEARCH_HIGHEST) {
663234066Smav		hload = INT_MIN;
664232207Smav		hgroup = *high;
665232207Smav	}
666176735Sjeff
667232207Smav	/* Iterate through the child CPU groups and then remaining CPUs. */
668255363Smav	for (i = cg->cg_children, cpu = mp_maxid; ; ) {
669234066Smav		if (i == 0) {
670255363Smav#ifdef HAVE_INLINE_FFSL
671255363Smav			cpu = CPU_FFS(&cpumask) - 1;
672255363Smav#else
673234066Smav			while (cpu >= 0 && !CPU_ISSET(cpu, &cpumask))
674234066Smav				cpu--;
675255363Smav#endif
676234066Smav			if (cpu < 0)
677232207Smav				break;
678232207Smav			child = NULL;
679232207Smav		} else
680234066Smav			child = &cg->cg_child[i - 1];
681232207Smav
682234066Smav		if (match & CPU_SEARCH_LOWEST)
683234066Smav			lgroup.cs_cpu = -1;
684234066Smav		if (match & CPU_SEARCH_HIGHEST)
685234066Smav			hgroup.cs_cpu = -1;
686232207Smav		if (child) {			/* Handle child CPU group. */
687232207Smav			CPU_NAND(&cpumask, &child->cg_mask);
688176735Sjeff			switch (match) {
689176735Sjeff			case CPU_SEARCH_LOWEST:
690176735Sjeff				load = cpu_search_lowest(child, &lgroup);
691176735Sjeff				break;
692176735Sjeff			case CPU_SEARCH_HIGHEST:
693176735Sjeff				load = cpu_search_highest(child, &hgroup);
694176735Sjeff				break;
695176735Sjeff			case CPU_SEARCH_BOTH:
696176735Sjeff				load = cpu_search_both(child, &lgroup, &hgroup);
697176735Sjeff				break;
698176735Sjeff			}
699232207Smav		} else {			/* Handle child CPU. */
700255363Smav			CPU_CLR(cpu, &cpumask);
701232207Smav			tdq = TDQ_CPU(cpu);
702232207Smav			load = tdq->tdq_load * 256;
703234066Smav			rndptr = DPCPU_PTR(randomval);
704234066Smav			rnd = (*rndptr = *rndptr * 69069 + 5) >> 26;
705232207Smav			if (match & CPU_SEARCH_LOWEST) {
706232207Smav				if (cpu == low->cs_prefer)
707232207Smav					load -= 64;
708232207Smav				/* If that CPU is allowed and get data. */
709234066Smav				if (tdq->tdq_lowpri > lgroup.cs_pri &&
710234066Smav				    tdq->tdq_load <= lgroup.cs_limit &&
711234066Smav				    CPU_ISSET(cpu, &lgroup.cs_mask)) {
712232207Smav					lgroup.cs_cpu = cpu;
713232207Smav					lgroup.cs_load = load - rnd;
714176735Sjeff				}
715232207Smav			}
716232207Smav			if (match & CPU_SEARCH_HIGHEST)
717234066Smav				if (tdq->tdq_load >= hgroup.cs_limit &&
718234066Smav				    tdq->tdq_transferable &&
719234066Smav				    CPU_ISSET(cpu, &hgroup.cs_mask)) {
720232207Smav					hgroup.cs_cpu = cpu;
721232207Smav					hgroup.cs_load = load - rnd;
722176735Sjeff				}
723176735Sjeff		}
724232207Smav		total += load;
725176735Sjeff
726232207Smav		/* We have info about child item. Compare it. */
727232207Smav		if (match & CPU_SEARCH_LOWEST) {
728234066Smav			if (lgroup.cs_cpu >= 0 &&
729232454Smav			    (load < lload ||
730232454Smav			     (load == lload && lgroup.cs_load < low->cs_load))) {
731232207Smav				lload = load;
732232207Smav				low->cs_cpu = lgroup.cs_cpu;
733232207Smav				low->cs_load = lgroup.cs_load;
734232207Smav			}
735232207Smav		}
736232207Smav		if (match & CPU_SEARCH_HIGHEST)
737234066Smav			if (hgroup.cs_cpu >= 0 &&
738232454Smav			    (load > hload ||
739232454Smav			     (load == hload && hgroup.cs_load > high->cs_load))) {
740232207Smav				hload = load;
741232207Smav				high->cs_cpu = hgroup.cs_cpu;
742232207Smav				high->cs_load = hgroup.cs_load;
743232207Smav			}
744234066Smav		if (child) {
745234066Smav			i--;
746234066Smav			if (i == 0 && CPU_EMPTY(&cpumask))
747234066Smav				break;
748255363Smav		}
749255363Smav#ifndef HAVE_INLINE_FFSL
750255363Smav		else
751234066Smav			cpu--;
752255363Smav#endif
753176735Sjeff	}
754176735Sjeff	return (total);
755176735Sjeff}
756176735Sjeff
757176735Sjeff/*
758176735Sjeff * cpu_search instantiations must pass constants to maintain the inline
759176735Sjeff * optimization.
760176735Sjeff */
761176735Sjeffint
762232207Smavcpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low)
763176735Sjeff{
764176735Sjeff	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
765176735Sjeff}
766176735Sjeff
767176735Sjeffint
768232207Smavcpu_search_highest(const struct cpu_group *cg, struct cpu_search *high)
769176735Sjeff{
770176735Sjeff	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
771176735Sjeff}
772176735Sjeff
773176735Sjeffint
774232207Smavcpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
775176735Sjeff    struct cpu_search *high)
776176735Sjeff{
777176735Sjeff	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
778176735Sjeff}
779176735Sjeff
780176735Sjeff/*
781176735Sjeff * Find the cpu with the least load via the least loaded path that has a
782176735Sjeff * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
783176735Sjeff * acceptable.
784176735Sjeff */
785176735Sjeffstatic inline int
786232207Smavsched_lowest(const struct cpu_group *cg, cpuset_t mask, int pri, int maxload,
787232207Smav    int prefer)
788176735Sjeff{
789176735Sjeff	struct cpu_search low;
790176735Sjeff
791176735Sjeff	low.cs_cpu = -1;
792232207Smav	low.cs_prefer = prefer;
793176735Sjeff	low.cs_mask = mask;
794232207Smav	low.cs_pri = pri;
795232207Smav	low.cs_limit = maxload;
796176735Sjeff	cpu_search_lowest(cg, &low);
797176735Sjeff	return low.cs_cpu;
798176735Sjeff}
799176735Sjeff
800176735Sjeff/*
801176735Sjeff * Find the cpu with the highest load via the highest loaded path.
802176735Sjeff */
803176735Sjeffstatic inline int
804232207Smavsched_highest(const struct cpu_group *cg, cpuset_t mask, int minload)
805176735Sjeff{
806176735Sjeff	struct cpu_search high;
807176735Sjeff
808176735Sjeff	high.cs_cpu = -1;
809176735Sjeff	high.cs_mask = mask;
810176735Sjeff	high.cs_limit = minload;
811176735Sjeff	cpu_search_highest(cg, &high);
812176735Sjeff	return high.cs_cpu;
813176735Sjeff}
814176735Sjeff
815121790Sjeffstatic void
816176735Sjeffsched_balance_group(struct cpu_group *cg)
817116069Sjeff{
818232207Smav	cpuset_t hmask, lmask;
819232207Smav	int high, low, anylow;
820123487Sjeff
821232207Smav	CPU_FILL(&hmask);
822176735Sjeff	for (;;) {
823232207Smav		high = sched_highest(cg, hmask, 1);
824232207Smav		/* Stop if there is no more CPU with transferrable threads. */
825232207Smav		if (high == -1)
826176735Sjeff			break;
827232207Smav		CPU_CLR(high, &hmask);
828232207Smav		CPU_COPY(&hmask, &lmask);
829232207Smav		/* Stop if there is no more CPU left for low. */
830232207Smav		if (CPU_EMPTY(&lmask))
831176735Sjeff			break;
832232207Smav		anylow = 1;
833232207Smavnextlow:
834232207Smav		low = sched_lowest(cg, lmask, -1,
835232207Smav		    TDQ_CPU(high)->tdq_load - 1, high);
836232207Smav		/* Stop if we looked well and found no less loaded CPU. */
837232207Smav		if (anylow && low == -1)
838232207Smav			break;
839232207Smav		/* Go to next high if we found no less loaded CPU. */
840232207Smav		if (low == -1)
841232207Smav			continue;
842232207Smav		/* Transfer thread from high to low. */
843232207Smav		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low))) {
844232207Smav			/* CPU that got thread can no longer be a donor. */
845232207Smav			CPU_CLR(low, &hmask);
846232207Smav		} else {
847232207Smav			/*
848232207Smav			 * If failed, then there is no threads on high
849232207Smav			 * that can run on this low. Drop low from low
850232207Smav			 * mask and look for different one.
851232207Smav			 */
852232207Smav			CPU_CLR(low, &lmask);
853232207Smav			anylow = 0;
854232207Smav			goto nextlow;
855232207Smav		}
856123487Sjeff	}
857123487Sjeff}
858123487Sjeff
859123487Sjeffstatic void
860201148Sedsched_balance(void)
861123487Sjeff{
862172409Sjeff	struct tdq *tdq;
863123487Sjeff
864172409Sjeff	/*
865172409Sjeff	 * Select a random time between .5 * balance_interval and
866172409Sjeff	 * 1.5 * balance_interval.
867172409Sjeff	 */
868176735Sjeff	balance_ticks = max(balance_interval / 2, 1);
869176735Sjeff	balance_ticks += random() % balance_interval;
870171482Sjeff	if (smp_started == 0 || rebalance == 0)
871171482Sjeff		return;
872172409Sjeff	tdq = TDQ_SELF();
873172409Sjeff	TDQ_UNLOCK(tdq);
874176735Sjeff	sched_balance_group(cpu_top);
875172409Sjeff	TDQ_LOCK(tdq);
876123487Sjeff}
877123487Sjeff
878171482Sjeff/*
879171482Sjeff * Lock two thread queues using their address to maintain lock order.
880171482Sjeff */
881123487Sjeffstatic void
882171482Sjefftdq_lock_pair(struct tdq *one, struct tdq *two)
883171482Sjeff{
884171482Sjeff	if (one < two) {
885171482Sjeff		TDQ_LOCK(one);
886171482Sjeff		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
887171482Sjeff	} else {
888171482Sjeff		TDQ_LOCK(two);
889171482Sjeff		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
890171482Sjeff	}
891171482Sjeff}
892171482Sjeff
893171482Sjeff/*
894172409Sjeff * Unlock two thread queues.  Order is not important here.
895172409Sjeff */
896172409Sjeffstatic void
897172409Sjefftdq_unlock_pair(struct tdq *one, struct tdq *two)
898172409Sjeff{
899172409Sjeff	TDQ_UNLOCK(one);
900172409Sjeff	TDQ_UNLOCK(two);
901172409Sjeff}
902172409Sjeff
903172409Sjeff/*
904171482Sjeff * Transfer load between two imbalanced thread queues.
905171482Sjeff */
906176735Sjeffstatic int
907164936Sjuliansched_balance_pair(struct tdq *high, struct tdq *low)
908123487Sjeff{
909176735Sjeff	int moved;
910226057Smarius	int cpu;
911116069Sjeff
912171482Sjeff	tdq_lock_pair(high, low);
913176735Sjeff	moved = 0;
914116069Sjeff	/*
915122744Sjeff	 * Determine what the imbalance is and then adjust that to how many
916165620Sjeff	 * threads we actually have to give up (transferable).
917122744Sjeff	 */
918232207Smav	if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load &&
919232207Smav	    (moved = tdq_move(high, low)) > 0) {
920172293Sjeff		/*
921226057Smarius		 * In case the target isn't the current cpu IPI it to force a
922226057Smarius		 * reschedule with the new workload.
923172293Sjeff		 */
924226057Smarius		cpu = TDQ_ID(low);
925226057Smarius		if (cpu != PCPU_GET(cpuid))
926226057Smarius			ipi_cpu(cpu, IPI_PREEMPT);
927171482Sjeff	}
928172409Sjeff	tdq_unlock_pair(high, low);
929176735Sjeff	return (moved);
930116069Sjeff}
931116069Sjeff
932171482Sjeff/*
933171482Sjeff * Move a thread from one thread queue to another.
934171482Sjeff */
935176735Sjeffstatic int
936171482Sjefftdq_move(struct tdq *from, struct tdq *to)
937116069Sjeff{
938171482Sjeff	struct td_sched *ts;
939171482Sjeff	struct thread *td;
940164936Sjulian	struct tdq *tdq;
941171482Sjeff	int cpu;
942116069Sjeff
943172409Sjeff	TDQ_LOCK_ASSERT(from, MA_OWNED);
944172409Sjeff	TDQ_LOCK_ASSERT(to, MA_OWNED);
945172409Sjeff
946164936Sjulian	tdq = from;
947171482Sjeff	cpu = TDQ_ID(to);
948177435Sjeff	td = tdq_steal(tdq, cpu);
949177435Sjeff	if (td == NULL)
950176735Sjeff		return (0);
951177435Sjeff	ts = td->td_sched;
952171482Sjeff	/*
953171482Sjeff	 * Although the run queue is locked the thread may be blocked.  Lock
954172409Sjeff	 * it to clear this and acquire the run-queue lock.
955171482Sjeff	 */
956171482Sjeff	thread_lock(td);
957172409Sjeff	/* Drop recursive lock on from acquired via thread_lock(). */
958171482Sjeff	TDQ_UNLOCK(from);
959171482Sjeff	sched_rem(td);
960166108Sjeff	ts->ts_cpu = cpu;
961171482Sjeff	td->td_lock = TDQ_LOCKPTR(to);
962171482Sjeff	tdq_add(to, td, SRQ_YIELDING);
963176735Sjeff	return (1);
964116069Sjeff}
965110267Sjeff
966171482Sjeff/*
967171482Sjeff * This tdq has idled.  Try to steal a thread from another cpu and switch
968171482Sjeff * to it.
969171482Sjeff */
970123433Sjeffstatic int
971164936Sjuliantdq_idled(struct tdq *tdq)
972121790Sjeff{
973176735Sjeff	struct cpu_group *cg;
974164936Sjulian	struct tdq *steal;
975194779Sjeff	cpuset_t mask;
976176735Sjeff	int thresh;
977171482Sjeff	int cpu;
978123433Sjeff
979172484Sjeff	if (smp_started == 0 || steal_idle == 0)
980172484Sjeff		return (1);
981194779Sjeff	CPU_FILL(&mask);
982194779Sjeff	CPU_CLR(PCPU_GET(cpuid), &mask);
983176735Sjeff	/* We don't want to be preempted while we're iterating. */
984171482Sjeff	spinlock_enter();
985176735Sjeff	for (cg = tdq->tdq_cg; cg != NULL; ) {
986191643Sjeff		if ((cg->cg_flags & CG_FLAG_THREAD) == 0)
987176735Sjeff			thresh = steal_thresh;
988176735Sjeff		else
989176735Sjeff			thresh = 1;
990176735Sjeff		cpu = sched_highest(cg, mask, thresh);
991176735Sjeff		if (cpu == -1) {
992176735Sjeff			cg = cg->cg_parent;
993176735Sjeff			continue;
994166108Sjeff		}
995176735Sjeff		steal = TDQ_CPU(cpu);
996194779Sjeff		CPU_CLR(cpu, &mask);
997176735Sjeff		tdq_lock_pair(tdq, steal);
998176735Sjeff		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
999176735Sjeff			tdq_unlock_pair(tdq, steal);
1000176735Sjeff			continue;
1001171482Sjeff		}
1002176735Sjeff		/*
1003176735Sjeff		 * If a thread was added while interrupts were disabled don't
1004176735Sjeff		 * steal one here.  If we fail to acquire one due to affinity
1005176735Sjeff		 * restrictions loop again with this cpu removed from the
1006176735Sjeff		 * set.
1007176735Sjeff		 */
1008176735Sjeff		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
1009176735Sjeff			tdq_unlock_pair(tdq, steal);
1010176735Sjeff			continue;
1011176735Sjeff		}
1012176735Sjeff		spinlock_exit();
1013176735Sjeff		TDQ_UNLOCK(steal);
1014178272Sjeff		mi_switch(SW_VOL | SWT_IDLE, NULL);
1015176735Sjeff		thread_unlock(curthread);
1016176735Sjeff
1017176735Sjeff		return (0);
1018123433Sjeff	}
1019171482Sjeff	spinlock_exit();
1020123433Sjeff	return (1);
1021121790Sjeff}
1022121790Sjeff
1023171482Sjeff/*
1024171482Sjeff * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
1025171482Sjeff */
1026121790Sjeffstatic void
1027177435Sjefftdq_notify(struct tdq *tdq, struct thread *td)
1028121790Sjeff{
1029185047Sjhb	struct thread *ctd;
1030166247Sjeff	int pri;
1031166108Sjeff	int cpu;
1032121790Sjeff
1033177005Sjeff	if (tdq->tdq_ipipending)
1034177005Sjeff		return;
1035177435Sjeff	cpu = td->td_sched->ts_cpu;
1036177435Sjeff	pri = td->td_priority;
1037185047Sjhb	ctd = pcpu_find(cpu)->pc_curthread;
1038185047Sjhb	if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
1039166137Sjeff		return;
1040271707Smav
1041271707Smav	/*
1042271707Smav	 * Make sure that tdq_load updated before calling this function
1043271707Smav	 * is globally visible before we read tdq_cpu_idle.  Idle thread
1044271707Smav	 * accesses both of them without locks, and the order is important.
1045271707Smav	 */
1046271707Smav	mb();
1047271707Smav
1048185047Sjhb	if (TD_IS_IDLETHREAD(ctd)) {
1049178277Sjeff		/*
1050178471Sjeff		 * If the MD code has an idle wakeup routine try that before
1051178471Sjeff		 * falling back to IPI.
1052178471Sjeff		 */
1053212416Smav		if (!tdq->tdq_cpu_idle || cpu_idle_wakeup(cpu))
1054178471Sjeff			return;
1055178277Sjeff	}
1056177005Sjeff	tdq->tdq_ipipending = 1;
1057210939Sjhb	ipi_cpu(cpu, IPI_PREEMPT);
1058121790Sjeff}
1059121790Sjeff
1060171482Sjeff/*
1061171482Sjeff * Steals load from a timeshare queue.  Honors the rotating queue head
1062171482Sjeff * index.
1063171482Sjeff */
1064177435Sjeffstatic struct thread *
1065176735Sjeffrunq_steal_from(struct runq *rq, int cpu, u_char start)
1066171482Sjeff{
1067171482Sjeff	struct rqbits *rqb;
1068171482Sjeff	struct rqhead *rqh;
1069232207Smav	struct thread *td, *first;
1070171482Sjeff	int bit;
1071171482Sjeff	int pri;
1072171482Sjeff	int i;
1073171482Sjeff
1074171482Sjeff	rqb = &rq->rq_status;
1075171482Sjeff	bit = start & (RQB_BPW -1);
1076171482Sjeff	pri = 0;
1077232207Smav	first = NULL;
1078171482Sjeffagain:
1079171482Sjeff	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1080171482Sjeff		if (rqb->rqb_bits[i] == 0)
1081171482Sjeff			continue;
1082171482Sjeff		if (bit != 0) {
1083171482Sjeff			for (pri = bit; pri < RQB_BPW; pri++)
1084171482Sjeff				if (rqb->rqb_bits[i] & (1ul << pri))
1085171482Sjeff					break;
1086171482Sjeff			if (pri >= RQB_BPW)
1087171482Sjeff				continue;
1088171482Sjeff		} else
1089171482Sjeff			pri = RQB_FFS(rqb->rqb_bits[i]);
1090171482Sjeff		pri += (i << RQB_L2BPW);
1091171482Sjeff		rqh = &rq->rq_queues[pri];
1092177435Sjeff		TAILQ_FOREACH(td, rqh, td_runq) {
1093177435Sjeff			if (first && THREAD_CAN_MIGRATE(td) &&
1094177435Sjeff			    THREAD_CAN_SCHED(td, cpu))
1095177435Sjeff				return (td);
1096232207Smav			first = td;
1097171482Sjeff		}
1098171482Sjeff	}
1099171482Sjeff	if (start != 0) {
1100171482Sjeff		start = 0;
1101171482Sjeff		goto again;
1102171482Sjeff	}
1103171482Sjeff
1104232207Smav	if (first && THREAD_CAN_MIGRATE(first) &&
1105232207Smav	    THREAD_CAN_SCHED(first, cpu))
1106232207Smav		return (first);
1107171482Sjeff	return (NULL);
1108171482Sjeff}
1109171482Sjeff
1110171482Sjeff/*
1111171482Sjeff * Steals load from a standard linear queue.
1112171482Sjeff */
1113177435Sjeffstatic struct thread *
1114176735Sjeffrunq_steal(struct runq *rq, int cpu)
1115121790Sjeff{
1116121790Sjeff	struct rqhead *rqh;
1117121790Sjeff	struct rqbits *rqb;
1118177435Sjeff	struct thread *td;
1119121790Sjeff	int word;
1120121790Sjeff	int bit;
1121121790Sjeff
1122121790Sjeff	rqb = &rq->rq_status;
1123121790Sjeff	for (word = 0; word < RQB_LEN; word++) {
1124121790Sjeff		if (rqb->rqb_bits[word] == 0)
1125121790Sjeff			continue;
1126121790Sjeff		for (bit = 0; bit < RQB_BPW; bit++) {
1127123231Speter			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
1128121790Sjeff				continue;
1129121790Sjeff			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
1130177435Sjeff			TAILQ_FOREACH(td, rqh, td_runq)
1131177435Sjeff				if (THREAD_CAN_MIGRATE(td) &&
1132177435Sjeff				    THREAD_CAN_SCHED(td, cpu))
1133177435Sjeff					return (td);
1134121790Sjeff		}
1135121790Sjeff	}
1136121790Sjeff	return (NULL);
1137121790Sjeff}
1138121790Sjeff
1139171482Sjeff/*
1140171482Sjeff * Attempt to steal a thread in priority order from a thread queue.
1141171482Sjeff */
1142177435Sjeffstatic struct thread *
1143176735Sjefftdq_steal(struct tdq *tdq, int cpu)
1144121790Sjeff{
1145177435Sjeff	struct thread *td;
1146121790Sjeff
1147171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1148177435Sjeff	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
1149177435Sjeff		return (td);
1150177435Sjeff	if ((td = runq_steal_from(&tdq->tdq_timeshare,
1151177435Sjeff	    cpu, tdq->tdq_ridx)) != NULL)
1152177435Sjeff		return (td);
1153176735Sjeff	return (runq_steal(&tdq->tdq_idle, cpu));
1154121790Sjeff}
1155123433Sjeff
1156171482Sjeff/*
1157171482Sjeff * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
1158172409Sjeff * current lock and returns with the assigned queue locked.
1159171482Sjeff */
1160171482Sjeffstatic inline struct tdq *
1161177435Sjeffsched_setcpu(struct thread *td, int cpu, int flags)
1162123433Sjeff{
1163177435Sjeff
1164171482Sjeff	struct tdq *tdq;
1165123433Sjeff
1166177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1167171482Sjeff	tdq = TDQ_CPU(cpu);
1168177435Sjeff	td->td_sched->ts_cpu = cpu;
1169177435Sjeff	/*
1170177435Sjeff	 * If the lock matches just return the queue.
1171177435Sjeff	 */
1172171482Sjeff	if (td->td_lock == TDQ_LOCKPTR(tdq))
1173171482Sjeff		return (tdq);
1174171482Sjeff#ifdef notyet
1175123433Sjeff	/*
1176172293Sjeff	 * If the thread isn't running its lockptr is a
1177171482Sjeff	 * turnstile or a sleepqueue.  We can just lock_set without
1178171482Sjeff	 * blocking.
1179123685Sjeff	 */
1180171482Sjeff	if (TD_CAN_RUN(td)) {
1181171482Sjeff		TDQ_LOCK(tdq);
1182171482Sjeff		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1183171482Sjeff		return (tdq);
1184171482Sjeff	}
1185171482Sjeff#endif
1186166108Sjeff	/*
1187171482Sjeff	 * The hard case, migration, we need to block the thread first to
1188171482Sjeff	 * prevent order reversals with other cpus locks.
1189166108Sjeff	 */
1190202889Sattilio	spinlock_enter();
1191171482Sjeff	thread_lock_block(td);
1192171482Sjeff	TDQ_LOCK(tdq);
1193171713Sjeff	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1194202889Sattilio	spinlock_exit();
1195171482Sjeff	return (tdq);
1196166108Sjeff}
1197166108Sjeff
1198178272SjeffSCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
1199178272SjeffSCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
1200178272SjeffSCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
1201178272SjeffSCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
1202178272SjeffSCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
1203178272SjeffSCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
1204178272Sjeff
1205166108Sjeffstatic int
1206177435Sjeffsched_pickcpu(struct thread *td, int flags)
1207171482Sjeff{
1208232207Smav	struct cpu_group *cg, *ccg;
1209177435Sjeff	struct td_sched *ts;
1210171482Sjeff	struct tdq *tdq;
1211194779Sjeff	cpuset_t mask;
1212232207Smav	int cpu, pri, self;
1213166108Sjeff
1214176735Sjeff	self = PCPU_GET(cpuid);
1215177435Sjeff	ts = td->td_sched;
1216166108Sjeff	if (smp_started == 0)
1217166108Sjeff		return (self);
1218171506Sjeff	/*
1219171506Sjeff	 * Don't migrate a running thread from sched_switch().
1220171506Sjeff	 */
1221176735Sjeff	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1222176735Sjeff		return (ts->ts_cpu);
1223166108Sjeff	/*
1224176735Sjeff	 * Prefer to run interrupt threads on the processors that generate
1225176735Sjeff	 * the interrupt.
1226166108Sjeff	 */
1227232207Smav	pri = td->td_priority;
1228176735Sjeff	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1229178272Sjeff	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
1230178272Sjeff		SCHED_STAT_INC(pickcpu_intrbind);
1231176735Sjeff		ts->ts_cpu = self;
1232232207Smav		if (TDQ_CPU(self)->tdq_lowpri > pri) {
1233232207Smav			SCHED_STAT_INC(pickcpu_affinity);
1234232207Smav			return (ts->ts_cpu);
1235232207Smav		}
1236178272Sjeff	}
1237166108Sjeff	/*
1238176735Sjeff	 * If the thread can run on the last cpu and the affinity has not
1239176735Sjeff	 * expired or it is idle run it there.
1240166108Sjeff	 */
1241176735Sjeff	tdq = TDQ_CPU(ts->ts_cpu);
1242232207Smav	cg = tdq->tdq_cg;
1243232207Smav	if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
1244232207Smav	    tdq->tdq_lowpri >= PRI_MIN_IDLE &&
1245232207Smav	    SCHED_AFFINITY(ts, CG_SHARE_L2)) {
1246232207Smav		if (cg->cg_flags & CG_FLAG_THREAD) {
1247232207Smav			CPUSET_FOREACH(cpu, cg->cg_mask) {
1248232207Smav				if (TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE)
1249232207Smav					break;
1250232207Smav			}
1251232207Smav		} else
1252232207Smav			cpu = INT_MAX;
1253232207Smav		if (cpu > mp_maxid) {
1254178272Sjeff			SCHED_STAT_INC(pickcpu_idle_affinity);
1255176735Sjeff			return (ts->ts_cpu);
1256178272Sjeff		}
1257139334Sjeff	}
1258123433Sjeff	/*
1259232207Smav	 * Search for the last level cache CPU group in the tree.
1260232207Smav	 * Skip caches with expired affinity time and SMT groups.
1261232207Smav	 * Affinity to higher level caches will be handled less aggressively.
1262123433Sjeff	 */
1263232207Smav	for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
1264232207Smav		if (cg->cg_flags & CG_FLAG_THREAD)
1265232207Smav			continue;
1266232207Smav		if (!SCHED_AFFINITY(ts, cg->cg_level))
1267232207Smav			continue;
1268232207Smav		ccg = cg;
1269232207Smav	}
1270232207Smav	if (ccg != NULL)
1271232207Smav		cg = ccg;
1272176735Sjeff	cpu = -1;
1273232207Smav	/* Search the group for the less loaded idle CPU we can run now. */
1274194779Sjeff	mask = td->td_cpuset->cs_mask;
1275232207Smav	if (cg != NULL && cg != cpu_top &&
1276232207Smav	    CPU_CMP(&cg->cg_mask, &cpu_top->cg_mask) != 0)
1277232207Smav		cpu = sched_lowest(cg, mask, max(pri, PRI_MAX_TIMESHARE),
1278232207Smav		    INT_MAX, ts->ts_cpu);
1279232207Smav	/* Search globally for the less loaded CPU we can run now. */
1280176735Sjeff	if (cpu == -1)
1281232207Smav		cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu);
1282232207Smav	/* Search globally for the less loaded CPU. */
1283232207Smav	if (cpu == -1)
1284232207Smav		cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu);
1285232454Smav	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1286171506Sjeff	/*
1287176735Sjeff	 * Compare the lowest loaded cpu to current cpu.
1288171506Sjeff	 */
1289177005Sjeff	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
1290232207Smav	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE &&
1291232207Smav	    TDQ_CPU(self)->tdq_load <= TDQ_CPU(cpu)->tdq_load + 1) {
1292178272Sjeff		SCHED_STAT_INC(pickcpu_local);
1293177005Sjeff		cpu = self;
1294178272Sjeff	} else
1295178272Sjeff		SCHED_STAT_INC(pickcpu_lowest);
1296178272Sjeff	if (cpu != ts->ts_cpu)
1297178272Sjeff		SCHED_STAT_INC(pickcpu_migration);
1298171482Sjeff	return (cpu);
1299123433Sjeff}
1300176735Sjeff#endif
1301123433Sjeff
1302117326Sjeff/*
1303121790Sjeff * Pick the highest priority task we have and return it.
1304117326Sjeff */
1305177435Sjeffstatic struct thread *
1306164936Sjuliantdq_choose(struct tdq *tdq)
1307110267Sjeff{
1308177435Sjeff	struct thread *td;
1309110267Sjeff
1310171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1311177435Sjeff	td = runq_choose(&tdq->tdq_realtime);
1312177435Sjeff	if (td != NULL)
1313177435Sjeff		return (td);
1314177435Sjeff	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1315177435Sjeff	if (td != NULL) {
1316217351Sjhb		KASSERT(td->td_priority >= PRI_MIN_BATCH,
1317165762Sjeff		    ("tdq_choose: Invalid priority on timeshare queue %d",
1318177435Sjeff		    td->td_priority));
1319177435Sjeff		return (td);
1320165762Sjeff	}
1321177435Sjeff	td = runq_choose(&tdq->tdq_idle);
1322177435Sjeff	if (td != NULL) {
1323177435Sjeff		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1324165762Sjeff		    ("tdq_choose: Invalid priority on idle queue %d",
1325177435Sjeff		    td->td_priority));
1326177435Sjeff		return (td);
1327165762Sjeff	}
1328165762Sjeff
1329165762Sjeff	return (NULL);
1330110267Sjeff}
1331110267Sjeff
1332171482Sjeff/*
1333171482Sjeff * Initialize a thread queue.
1334171482Sjeff */
1335109864Sjeffstatic void
1336164936Sjuliantdq_setup(struct tdq *tdq)
1337110028Sjeff{
1338171482Sjeff
1339171713Sjeff	if (bootverbose)
1340171713Sjeff		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1341165762Sjeff	runq_init(&tdq->tdq_realtime);
1342165762Sjeff	runq_init(&tdq->tdq_timeshare);
1343165620Sjeff	runq_init(&tdq->tdq_idle);
1344176735Sjeff	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1345176735Sjeff	    "sched lock %d", (int)TDQ_ID(tdq));
1346176735Sjeff	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1347176735Sjeff	    MTX_SPIN | MTX_RECURSE);
1348187357Sjeff#ifdef KTR
1349187357Sjeff	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
1350187357Sjeff	    "CPU %d load", (int)TDQ_ID(tdq));
1351187357Sjeff#endif
1352110028Sjeff}
1353110028Sjeff
1354171713Sjeff#ifdef SMP
1355110028Sjeffstatic void
1356171713Sjeffsched_setup_smp(void)
1357171713Sjeff{
1358171713Sjeff	struct tdq *tdq;
1359171713Sjeff	int i;
1360171713Sjeff
1361176735Sjeff	cpu_top = smp_topo();
1362209059Sjhb	CPU_FOREACH(i) {
1363176735Sjeff		tdq = TDQ_CPU(i);
1364171713Sjeff		tdq_setup(tdq);
1365176735Sjeff		tdq->tdq_cg = smp_topo_find(cpu_top, i);
1366176735Sjeff		if (tdq->tdq_cg == NULL)
1367176735Sjeff			panic("Can't find cpu group for %d\n", i);
1368123433Sjeff	}
1369176735Sjeff	balance_tdq = TDQ_SELF();
1370176735Sjeff	sched_balance();
1371171713Sjeff}
1372171713Sjeff#endif
1373171713Sjeff
1374171713Sjeff/*
1375171713Sjeff * Setup the thread queues and initialize the topology based on MD
1376171713Sjeff * information.
1377171713Sjeff */
1378171713Sjeffstatic void
1379171713Sjeffsched_setup(void *dummy)
1380171713Sjeff{
1381171713Sjeff	struct tdq *tdq;
1382171713Sjeff
1383171713Sjeff	tdq = TDQ_SELF();
1384171713Sjeff#ifdef SMP
1385176734Sjeff	sched_setup_smp();
1386117237Sjeff#else
1387171713Sjeff	tdq_setup(tdq);
1388116069Sjeff#endif
1389171482Sjeff
1390171482Sjeff	/* Add thread0's load since it's running. */
1391171482Sjeff	TDQ_LOCK(tdq);
1392171713Sjeff	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1393177435Sjeff	tdq_load_add(tdq, &thread0);
1394176735Sjeff	tdq->tdq_lowpri = thread0.td_priority;
1395171482Sjeff	TDQ_UNLOCK(tdq);
1396109864Sjeff}
1397109864Sjeff
1398171482Sjeff/*
1399239185Smav * This routine determines time constants after stathz and hz are setup.
1400171482Sjeff */
1401153533Sdavidxu/* ARGSUSED */
1402153533Sdavidxustatic void
1403153533Sdavidxusched_initticks(void *dummy)
1404153533Sdavidxu{
1405171482Sjeff	int incr;
1406171482Sjeff
1407153533Sdavidxu	realstathz = stathz ? stathz : hz;
1408242736Sjeff	sched_slice = realstathz / SCHED_SLICE_DEFAULT_DIVISOR;
1409242736Sjeff	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
1410239196Smav	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
1411239196Smav	    realstathz);
1412153533Sdavidxu
1413153533Sdavidxu	/*
1414165762Sjeff	 * tickincr is shifted out by 10 to avoid rounding errors due to
1415165766Sjeff	 * hz not being evenly divisible by stathz on all platforms.
1416153533Sdavidxu	 */
1417171482Sjeff	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1418165762Sjeff	/*
1419165762Sjeff	 * This does not work for values of stathz that are more than
1420165762Sjeff	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1421165762Sjeff	 */
1422171482Sjeff	if (incr == 0)
1423171482Sjeff		incr = 1;
1424171482Sjeff	tickincr = incr;
1425166108Sjeff#ifdef SMP
1426171899Sjeff	/*
1427172409Sjeff	 * Set the default balance interval now that we know
1428172409Sjeff	 * what realstathz is.
1429172409Sjeff	 */
1430172409Sjeff	balance_interval = realstathz;
1431166108Sjeff	affinity = SCHED_AFFINITY_DEFAULT;
1432166108Sjeff#endif
1433232740Smav	if (sched_idlespinthresh < 0)
1434242852Smav		sched_idlespinthresh = 2 * max(10000, 6 * hz) / realstathz;
1435153533Sdavidxu}
1436153533Sdavidxu
1437153533Sdavidxu
1438109864Sjeff/*
1439171482Sjeff * This is the core of the interactivity algorithm.  Determines a score based
1440171482Sjeff * on past behavior.  It is the ratio of sleep time to run time scaled to
1441171482Sjeff * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1442171482Sjeff * differs from the cpu usage because it does not account for time spent
1443171482Sjeff * waiting on a run-queue.  Would be prettier if we had floating point.
1444171482Sjeff */
1445171482Sjeffstatic int
1446171482Sjeffsched_interact_score(struct thread *td)
1447171482Sjeff{
1448171482Sjeff	struct td_sched *ts;
1449171482Sjeff	int div;
1450171482Sjeff
1451171482Sjeff	ts = td->td_sched;
1452171482Sjeff	/*
1453171482Sjeff	 * The score is only needed if this is likely to be an interactive
1454171482Sjeff	 * task.  Don't go through the expense of computing it if there's
1455171482Sjeff	 * no chance.
1456171482Sjeff	 */
1457171482Sjeff	if (sched_interact <= SCHED_INTERACT_HALF &&
1458171482Sjeff		ts->ts_runtime >= ts->ts_slptime)
1459171482Sjeff			return (SCHED_INTERACT_HALF);
1460171482Sjeff
1461171482Sjeff	if (ts->ts_runtime > ts->ts_slptime) {
1462171482Sjeff		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1463171482Sjeff		return (SCHED_INTERACT_HALF +
1464171482Sjeff		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1465171482Sjeff	}
1466171482Sjeff	if (ts->ts_slptime > ts->ts_runtime) {
1467171482Sjeff		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1468171482Sjeff		return (ts->ts_runtime / div);
1469171482Sjeff	}
1470171482Sjeff	/* runtime == slptime */
1471171482Sjeff	if (ts->ts_runtime)
1472171482Sjeff		return (SCHED_INTERACT_HALF);
1473171482Sjeff
1474171482Sjeff	/*
1475171482Sjeff	 * This can happen if slptime and runtime are 0.
1476171482Sjeff	 */
1477171482Sjeff	return (0);
1478171482Sjeff
1479171482Sjeff}
1480171482Sjeff
1481171482Sjeff/*
1482109864Sjeff * Scale the scheduling priority according to the "interactivity" of this
1483109864Sjeff * process.
1484109864Sjeff */
1485113357Sjeffstatic void
1486163709Sjbsched_priority(struct thread *td)
1487109864Sjeff{
1488165762Sjeff	int score;
1489109864Sjeff	int pri;
1490109864Sjeff
1491217291Sjhb	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
1492113357Sjeff		return;
1493112966Sjeff	/*
1494165762Sjeff	 * If the score is interactive we place the thread in the realtime
1495165762Sjeff	 * queue with a priority that is less than kernel and interrupt
1496165762Sjeff	 * priorities.  These threads are not subject to nice restrictions.
1497112966Sjeff	 *
1498171482Sjeff	 * Scores greater than this are placed on the normal timeshare queue
1499165762Sjeff	 * where the priority is partially decided by the most recent cpu
1500165762Sjeff	 * utilization and the rest is decided by nice value.
1501172293Sjeff	 *
1502172293Sjeff	 * The nice value of the process has a linear effect on the calculated
1503172293Sjeff	 * score.  Negative nice values make it easier for a thread to be
1504172293Sjeff	 * considered interactive.
1505112966Sjeff	 */
1506198126Sjhb	score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1507165762Sjeff	if (score < sched_interact) {
1508217351Sjhb		pri = PRI_MIN_INTERACT;
1509217351Sjhb		pri += ((PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) /
1510217237Sjhb		    sched_interact) * score;
1511217351Sjhb		KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
1512166208Sjeff		    ("sched_priority: invalid interactive priority %d score %d",
1513166208Sjeff		    pri, score));
1514165762Sjeff	} else {
1515165762Sjeff		pri = SCHED_PRI_MIN;
1516165762Sjeff		if (td->td_sched->ts_ticks)
1517228960Sjhb			pri += min(SCHED_PRI_TICKS(td->td_sched),
1518259834Sjhb			    SCHED_PRI_RANGE - 1);
1519165762Sjeff		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1520217351Sjhb		KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
1521171482Sjeff		    ("sched_priority: invalid priority %d: nice %d, "
1522171482Sjeff		    "ticks %d ftick %d ltick %d tick pri %d",
1523171482Sjeff		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1524171482Sjeff		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1525171482Sjeff		    SCHED_PRI_TICKS(td->td_sched)));
1526165762Sjeff	}
1527165762Sjeff	sched_user_prio(td, pri);
1528112966Sjeff
1529112966Sjeff	return;
1530109864Sjeff}
1531109864Sjeff
1532121868Sjeff/*
1533121868Sjeff * This routine enforces a maximum limit on the amount of scheduling history
1534171482Sjeff * kept.  It is called after either the slptime or runtime is adjusted.  This
1535171482Sjeff * function is ugly due to integer math.
1536121868Sjeff */
1537116463Sjeffstatic void
1538163709Sjbsched_interact_update(struct thread *td)
1539116463Sjeff{
1540165819Sjeff	struct td_sched *ts;
1541166208Sjeff	u_int sum;
1542121605Sjeff
1543165819Sjeff	ts = td->td_sched;
1544171482Sjeff	sum = ts->ts_runtime + ts->ts_slptime;
1545121868Sjeff	if (sum < SCHED_SLP_RUN_MAX)
1546121868Sjeff		return;
1547121868Sjeff	/*
1548165819Sjeff	 * This only happens from two places:
1549165819Sjeff	 * 1) We have added an unusual amount of run time from fork_exit.
1550165819Sjeff	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1551165819Sjeff	 */
1552165819Sjeff	if (sum > SCHED_SLP_RUN_MAX * 2) {
1553171482Sjeff		if (ts->ts_runtime > ts->ts_slptime) {
1554171482Sjeff			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1555171482Sjeff			ts->ts_slptime = 1;
1556165819Sjeff		} else {
1557171482Sjeff			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1558171482Sjeff			ts->ts_runtime = 1;
1559165819Sjeff		}
1560165819Sjeff		return;
1561165819Sjeff	}
1562165819Sjeff	/*
1563121868Sjeff	 * If we have exceeded by more than 1/5th then the algorithm below
1564121868Sjeff	 * will not bring us back into range.  Dividing by two here forces
1565133427Sjeff	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1566121868Sjeff	 */
1567127850Sjeff	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1568171482Sjeff		ts->ts_runtime /= 2;
1569171482Sjeff		ts->ts_slptime /= 2;
1570121868Sjeff		return;
1571116463Sjeff	}
1572171482Sjeff	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1573171482Sjeff	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1574116463Sjeff}
1575116463Sjeff
1576171482Sjeff/*
1577171482Sjeff * Scale back the interactivity history when a child thread is created.  The
1578171482Sjeff * history is inherited from the parent but the thread may behave totally
1579171482Sjeff * differently.  For example, a shell spawning a compiler process.  We want
1580171482Sjeff * to learn that the compiler is behaving badly very quickly.
1581171482Sjeff */
1582121868Sjeffstatic void
1583163709Sjbsched_interact_fork(struct thread *td)
1584121868Sjeff{
1585121868Sjeff	int ratio;
1586121868Sjeff	int sum;
1587121868Sjeff
1588171482Sjeff	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1589121868Sjeff	if (sum > SCHED_SLP_RUN_FORK) {
1590121868Sjeff		ratio = sum / SCHED_SLP_RUN_FORK;
1591171482Sjeff		td->td_sched->ts_runtime /= ratio;
1592171482Sjeff		td->td_sched->ts_slptime /= ratio;
1593121868Sjeff	}
1594121868Sjeff}
1595121868Sjeff
1596113357Sjeff/*
1597171482Sjeff * Called from proc0_init() to setup the scheduler fields.
1598134791Sjulian */
1599134791Sjulianvoid
1600134791Sjulianschedinit(void)
1601134791Sjulian{
1602165762Sjeff
1603134791Sjulian	/*
1604134791Sjulian	 * Set up the scheduler specific parts of proc0.
1605134791Sjulian	 */
1606136167Sjulian	proc0.p_sched = NULL; /* XXX */
1607164936Sjulian	thread0.td_sched = &td_sched0;
1608165762Sjeff	td_sched0.ts_ltick = ticks;
1609165796Sjeff	td_sched0.ts_ftick = ticks;
1610242736Sjeff	td_sched0.ts_slice = 0;
1611134791Sjulian}
1612134791Sjulian
1613134791Sjulian/*
1614113357Sjeff * This is only somewhat accurate since given many processes of the same
1615113357Sjeff * priority they will switch when their slices run out, which will be
1616165762Sjeff * at most sched_slice stathz ticks.
1617113357Sjeff */
1618109864Sjeffint
1619109864Sjeffsched_rr_interval(void)
1620109864Sjeff{
1621165762Sjeff
1622239185Smav	/* Convert sched_slice from stathz to hz. */
1623239196Smav	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
1624109864Sjeff}
1625109864Sjeff
1626171482Sjeff/*
1627171482Sjeff * Update the percent cpu tracking information when it is requested or
1628171482Sjeff * the total history exceeds the maximum.  We keep a sliding history of
1629171482Sjeff * tick counts that slowly decays.  This is less precise than the 4BSD
1630171482Sjeff * mechanism since it happens with less regular and frequent events.
1631171482Sjeff */
1632121790Sjeffstatic void
1633232917Smavsched_pctcpu_update(struct td_sched *ts, int run)
1634109864Sjeff{
1635232917Smav	int t = ticks;
1636165762Sjeff
1637232917Smav	if (t - ts->ts_ltick >= SCHED_TICK_TARG) {
1638164936Sjulian		ts->ts_ticks = 0;
1639232917Smav		ts->ts_ftick = t - SCHED_TICK_TARG;
1640232917Smav	} else if (t - ts->ts_ftick >= SCHED_TICK_MAX) {
1641232917Smav		ts->ts_ticks = (ts->ts_ticks / (ts->ts_ltick - ts->ts_ftick)) *
1642232917Smav		    (ts->ts_ltick - (t - SCHED_TICK_TARG));
1643232917Smav		ts->ts_ftick = t - SCHED_TICK_TARG;
1644232917Smav	}
1645232917Smav	if (run)
1646232917Smav		ts->ts_ticks += (t - ts->ts_ltick) << SCHED_TICK_SHIFT;
1647232917Smav	ts->ts_ltick = t;
1648109864Sjeff}
1649109864Sjeff
1650171482Sjeff/*
1651171482Sjeff * Adjust the priority of a thread.  Move it to the appropriate run-queue
1652171482Sjeff * if necessary.  This is the back-end for several priority related
1653171482Sjeff * functions.
1654171482Sjeff */
1655165762Sjeffstatic void
1656139453Sjhbsched_thread_priority(struct thread *td, u_char prio)
1657109864Sjeff{
1658164936Sjulian	struct td_sched *ts;
1659177009Sjeff	struct tdq *tdq;
1660177009Sjeff	int oldpri;
1661109864Sjeff
1662187357Sjeff	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
1663187357Sjeff	    "prio:%d", td->td_priority, "new prio:%d", prio,
1664187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(curthread));
1665260817Savg	SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
1666240513Savg	if (td != curthread && prio < td->td_priority) {
1667187357Sjeff		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
1668187357Sjeff		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
1669187357Sjeff		    prio, KTR_ATTR_LINKED, sched_tdname(td));
1670260817Savg		SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
1671235459Srstone		    curthread);
1672187357Sjeff	}
1673164936Sjulian	ts = td->td_sched;
1674170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1675139453Sjhb	if (td->td_priority == prio)
1676139453Sjhb		return;
1677177376Sjeff	/*
1678177376Sjeff	 * If the priority has been elevated due to priority
1679177376Sjeff	 * propagation, we may have to move ourselves to a new
1680177376Sjeff	 * queue.  This could be optimized to not re-add in some
1681177376Sjeff	 * cases.
1682177376Sjeff	 */
1683165766Sjeff	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1684165762Sjeff		sched_rem(td);
1685165762Sjeff		td->td_priority = prio;
1686171482Sjeff		sched_add(td, SRQ_BORROWING);
1687177009Sjeff		return;
1688177009Sjeff	}
1689177376Sjeff	/*
1690177376Sjeff	 * If the thread is currently running we may have to adjust the lowpri
1691177376Sjeff	 * information so other cpus are aware of our current priority.
1692177376Sjeff	 */
1693177009Sjeff	if (TD_IS_RUNNING(td)) {
1694177376Sjeff		tdq = TDQ_CPU(ts->ts_cpu);
1695177376Sjeff		oldpri = td->td_priority;
1696177376Sjeff		td->td_priority = prio;
1697176735Sjeff		if (prio < tdq->tdq_lowpri)
1698171482Sjeff			tdq->tdq_lowpri = prio;
1699176735Sjeff		else if (tdq->tdq_lowpri == oldpri)
1700176735Sjeff			tdq_setlowpri(tdq, td);
1701177376Sjeff		return;
1702177009Sjeff	}
1703177376Sjeff	td->td_priority = prio;
1704109864Sjeff}
1705109864Sjeff
1706139453Sjhb/*
1707139453Sjhb * Update a thread's priority when it is lent another thread's
1708139453Sjhb * priority.
1709139453Sjhb */
1710109864Sjeffvoid
1711139453Sjhbsched_lend_prio(struct thread *td, u_char prio)
1712139453Sjhb{
1713139453Sjhb
1714139453Sjhb	td->td_flags |= TDF_BORROWING;
1715139453Sjhb	sched_thread_priority(td, prio);
1716139453Sjhb}
1717139453Sjhb
1718139453Sjhb/*
1719139453Sjhb * Restore a thread's priority when priority propagation is
1720139453Sjhb * over.  The prio argument is the minimum priority the thread
1721139453Sjhb * needs to have to satisfy other possible priority lending
1722139453Sjhb * requests.  If the thread's regular priority is less
1723139453Sjhb * important than prio, the thread will keep a priority boost
1724139453Sjhb * of prio.
1725139453Sjhb */
1726139453Sjhbvoid
1727139453Sjhbsched_unlend_prio(struct thread *td, u_char prio)
1728139453Sjhb{
1729139453Sjhb	u_char base_pri;
1730139453Sjhb
1731139453Sjhb	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1732139453Sjhb	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1733163709Sjb		base_pri = td->td_user_pri;
1734139453Sjhb	else
1735139453Sjhb		base_pri = td->td_base_pri;
1736139453Sjhb	if (prio >= base_pri) {
1737139455Sjhb		td->td_flags &= ~TDF_BORROWING;
1738139453Sjhb		sched_thread_priority(td, base_pri);
1739139453Sjhb	} else
1740139453Sjhb		sched_lend_prio(td, prio);
1741139453Sjhb}
1742139453Sjhb
1743171482Sjeff/*
1744171482Sjeff * Standard entry for setting the priority to an absolute value.
1745171482Sjeff */
1746139453Sjhbvoid
1747139453Sjhbsched_prio(struct thread *td, u_char prio)
1748139453Sjhb{
1749139453Sjhb	u_char oldprio;
1750139453Sjhb
1751139453Sjhb	/* First, update the base priority. */
1752139453Sjhb	td->td_base_pri = prio;
1753139453Sjhb
1754139453Sjhb	/*
1755139455Sjhb	 * If the thread is borrowing another thread's priority, don't
1756139453Sjhb	 * ever lower the priority.
1757139453Sjhb	 */
1758139453Sjhb	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1759139453Sjhb		return;
1760139453Sjhb
1761139453Sjhb	/* Change the real priority. */
1762139453Sjhb	oldprio = td->td_priority;
1763139453Sjhb	sched_thread_priority(td, prio);
1764139453Sjhb
1765139453Sjhb	/*
1766139453Sjhb	 * If the thread is on a turnstile, then let the turnstile update
1767139453Sjhb	 * its state.
1768139453Sjhb	 */
1769139453Sjhb	if (TD_ON_LOCK(td) && oldprio != prio)
1770139453Sjhb		turnstile_adjust(td, oldprio);
1771139453Sjhb}
1772139455Sjhb
1773171482Sjeff/*
1774171482Sjeff * Set the base user priority, does not effect current running priority.
1775171482Sjeff */
1776139453Sjhbvoid
1777163709Sjbsched_user_prio(struct thread *td, u_char prio)
1778161599Sdavidxu{
1779161599Sdavidxu
1780163709Sjb	td->td_base_user_pri = prio;
1781216313Sdavidxu	if (td->td_lend_user_pri <= prio)
1782216313Sdavidxu		return;
1783163709Sjb	td->td_user_pri = prio;
1784161599Sdavidxu}
1785161599Sdavidxu
1786161599Sdavidxuvoid
1787161599Sdavidxusched_lend_user_prio(struct thread *td, u_char prio)
1788161599Sdavidxu{
1789161599Sdavidxu
1790174536Sdavidxu	THREAD_LOCK_ASSERT(td, MA_OWNED);
1791216313Sdavidxu	td->td_lend_user_pri = prio;
1792216791Sdavidxu	td->td_user_pri = min(prio, td->td_base_user_pri);
1793216791Sdavidxu	if (td->td_priority > td->td_user_pri)
1794216791Sdavidxu		sched_prio(td, td->td_user_pri);
1795216791Sdavidxu	else if (td->td_priority != td->td_user_pri)
1796216791Sdavidxu		td->td_flags |= TDF_NEEDRESCHED;
1797161599Sdavidxu}
1798161599Sdavidxu
1799171482Sjeff/*
1800171713Sjeff * Handle migration from sched_switch().  This happens only for
1801171713Sjeff * cpu binding.
1802171713Sjeff */
1803171713Sjeffstatic struct mtx *
1804171713Sjeffsched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1805171713Sjeff{
1806171713Sjeff	struct tdq *tdn;
1807171713Sjeff
1808171713Sjeff	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1809171713Sjeff#ifdef SMP
1810177435Sjeff	tdq_load_rem(tdq, td);
1811171713Sjeff	/*
1812171713Sjeff	 * Do the lock dance required to avoid LOR.  We grab an extra
1813171713Sjeff	 * spinlock nesting to prevent preemption while we're
1814171713Sjeff	 * not holding either run-queue lock.
1815171713Sjeff	 */
1816171713Sjeff	spinlock_enter();
1817202889Sattilio	thread_lock_block(td);	/* This releases the lock on tdq. */
1818197223Sattilio
1819197223Sattilio	/*
1820197223Sattilio	 * Acquire both run-queue locks before placing the thread on the new
1821197223Sattilio	 * run-queue to avoid deadlocks created by placing a thread with a
1822197223Sattilio	 * blocked lock on the run-queue of a remote processor.  The deadlock
1823197223Sattilio	 * occurs when a third processor attempts to lock the two queues in
1824197223Sattilio	 * question while the target processor is spinning with its own
1825197223Sattilio	 * run-queue lock held while waiting for the blocked lock to clear.
1826197223Sattilio	 */
1827197223Sattilio	tdq_lock_pair(tdn, tdq);
1828171713Sjeff	tdq_add(tdn, td, flags);
1829177435Sjeff	tdq_notify(tdn, td);
1830197223Sattilio	TDQ_UNLOCK(tdn);
1831171713Sjeff	spinlock_exit();
1832171713Sjeff#endif
1833171713Sjeff	return (TDQ_LOCKPTR(tdn));
1834171713Sjeff}
1835171713Sjeff
1836171713Sjeff/*
1837202889Sattilio * Variadic version of thread_lock_unblock() that does not assume td_lock
1838202889Sattilio * is blocked.
1839171482Sjeff */
1840171482Sjeffstatic inline void
1841171482Sjeffthread_unblock_switch(struct thread *td, struct mtx *mtx)
1842171482Sjeff{
1843171482Sjeff	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1844171482Sjeff	    (uintptr_t)mtx);
1845171482Sjeff}
1846171482Sjeff
1847171482Sjeff/*
1848171482Sjeff * Switch threads.  This function has to handle threads coming in while
1849171482Sjeff * blocked for some reason, running, or idle.  It also must deal with
1850171482Sjeff * migrating a thread from one queue to another as running threads may
1851171482Sjeff * be assigned elsewhere via binding.
1852171482Sjeff */
1853161599Sdavidxuvoid
1854135051Sjuliansched_switch(struct thread *td, struct thread *newtd, int flags)
1855109864Sjeff{
1856165627Sjeff	struct tdq *tdq;
1857164936Sjulian	struct td_sched *ts;
1858171482Sjeff	struct mtx *mtx;
1859171713Sjeff	int srqflag;
1860239157Smav	int cpuid, preempted;
1861109864Sjeff
1862170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1863177376Sjeff	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
1864109864Sjeff
1865171482Sjeff	cpuid = PCPU_GET(cpuid);
1866171482Sjeff	tdq = TDQ_CPU(cpuid);
1867164936Sjulian	ts = td->td_sched;
1868171713Sjeff	mtx = td->td_lock;
1869232917Smav	sched_pctcpu_update(ts, 1);
1870171482Sjeff	ts->ts_rltick = ticks;
1871133555Sjeff	td->td_lastcpu = td->td_oncpu;
1872113339Sjulian	td->td_oncpu = NOCPU;
1873312666Savg	preempted = (td->td_flags & TDF_SLICEEND) == 0 &&
1874312666Savg	    (flags & SW_PREEMPT) != 0;
1875239157Smav	td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
1876144777Sups	td->td_owepreempt = 0;
1877242852Smav	if (!TD_IS_IDLETHREAD(td))
1878242852Smav		tdq->tdq_switchcnt++;
1879123434Sjeff	/*
1880171482Sjeff	 * The lock pointer in an idle thread should never change.  Reset it
1881171482Sjeff	 * to CAN_RUN as well.
1882123434Sjeff	 */
1883167327Sjulian	if (TD_IS_IDLETHREAD(td)) {
1884171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1885139334Sjeff		TD_SET_CAN_RUN(td);
1886170293Sjeff	} else if (TD_IS_RUNNING(td)) {
1887171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1888239157Smav		srqflag = preempted ?
1889170293Sjeff		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1890171713Sjeff		    SRQ_OURSELF|SRQ_YIELDING;
1891212153Smdf#ifdef SMP
1892212115Smdf		if (THREAD_CAN_MIGRATE(td) && !THREAD_CAN_SCHED(td, ts->ts_cpu))
1893212115Smdf			ts->ts_cpu = sched_pickcpu(td, 0);
1894212153Smdf#endif
1895171713Sjeff		if (ts->ts_cpu == cpuid)
1896177435Sjeff			tdq_runq_add(tdq, td, srqflag);
1897212115Smdf		else {
1898212115Smdf			KASSERT(THREAD_CAN_MIGRATE(td) ||
1899212115Smdf			    (ts->ts_flags & TSF_BOUND) != 0,
1900212115Smdf			    ("Thread %p shouldn't migrate", td));
1901171713Sjeff			mtx = sched_switch_migrate(tdq, td, srqflag);
1902212115Smdf		}
1903171482Sjeff	} else {
1904171482Sjeff		/* This thread must be going to sleep. */
1905171482Sjeff		TDQ_LOCK(tdq);
1906202889Sattilio		mtx = thread_lock_block(td);
1907177435Sjeff		tdq_load_rem(tdq, td);
1908171482Sjeff	}
1909316841Savg
1910316841Savg#if (KTR_COMPILE & KTR_SCHED) != 0
1911316841Savg	if (TD_IS_IDLETHREAD(td))
1912316841Savg		KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle",
1913316841Savg		    "prio:%d", td->td_priority);
1914316841Savg	else
1915316841Savg		KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td),
1916316841Savg		    "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg,
1917316841Savg		    "lockname:\"%s\"", td->td_lockname);
1918316841Savg#endif
1919316841Savg
1920171482Sjeff	/*
1921171482Sjeff	 * We enter here with the thread blocked and assigned to the
1922171482Sjeff	 * appropriate cpu run-queue or sleep-queue and with the current
1923171482Sjeff	 * thread-queue locked.
1924171482Sjeff	 */
1925171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1926171482Sjeff	newtd = choosethread();
1927171482Sjeff	/*
1928171482Sjeff	 * Call the MD code to switch contexts if necessary.
1929171482Sjeff	 */
1930145256Sjkoshy	if (td != newtd) {
1931145256Sjkoshy#ifdef	HWPMC_HOOKS
1932145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1933145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1934145256Sjkoshy#endif
1935260817Savg		SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
1936174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1937172411Sjeff		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1938232917Smav		sched_pctcpu_update(newtd->td_sched, 0);
1939179297Sjb
1940179297Sjb#ifdef KDTRACE_HOOKS
1941179297Sjb		/*
1942179297Sjb		 * If DTrace has set the active vtime enum to anything
1943179297Sjb		 * other than INACTIVE (0), then it should have set the
1944179297Sjb		 * function to call.
1945179297Sjb		 */
1946179297Sjb		if (dtrace_vtime_active)
1947179297Sjb			(*dtrace_vtime_switch_func)(newtd);
1948179297Sjb#endif
1949179297Sjb
1950171482Sjeff		cpu_switch(td, newtd, mtx);
1951171482Sjeff		/*
1952171482Sjeff		 * We may return from cpu_switch on a different cpu.  However,
1953171482Sjeff		 * we always return with td_lock pointing to the current cpu's
1954171482Sjeff		 * run queue lock.
1955171482Sjeff		 */
1956171482Sjeff		cpuid = PCPU_GET(cpuid);
1957171482Sjeff		tdq = TDQ_CPU(cpuid);
1958174629Sjeff		lock_profile_obtain_lock_success(
1959174629Sjeff		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1960235459Srstone
1961260817Savg		SDT_PROBE0(sched, , , on__cpu);
1962145256Sjkoshy#ifdef	HWPMC_HOOKS
1963145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1964145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1965145256Sjkoshy#endif
1966235459Srstone	} else {
1967171482Sjeff		thread_unblock_switch(td, mtx);
1968260817Savg		SDT_PROBE0(sched, , , remain__cpu);
1969235459Srstone	}
1970316841Savg
1971316841Savg	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
1972316841Savg	    "prio:%d", td->td_priority);
1973316841Savg
1974171482Sjeff	/*
1975171482Sjeff	 * Assert that all went well and return.
1976171482Sjeff	 */
1977171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1978171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1979171482Sjeff	td->td_oncpu = cpuid;
1980109864Sjeff}
1981109864Sjeff
1982171482Sjeff/*
1983171482Sjeff * Adjust thread priorities as a result of a nice request.
1984171482Sjeff */
1985109864Sjeffvoid
1986130551Sjuliansched_nice(struct proc *p, int nice)
1987109864Sjeff{
1988109864Sjeff	struct thread *td;
1989109864Sjeff
1990130551Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
1991165762Sjeff
1992130551Sjulian	p->p_nice = nice;
1993163709Sjb	FOREACH_THREAD_IN_PROC(p, td) {
1994170293Sjeff		thread_lock(td);
1995163709Sjb		sched_priority(td);
1996165762Sjeff		sched_prio(td, td->td_base_user_pri);
1997170293Sjeff		thread_unlock(td);
1998130551Sjulian	}
1999109864Sjeff}
2000109864Sjeff
2001171482Sjeff/*
2002171482Sjeff * Record the sleep time for the interactivity scorer.
2003171482Sjeff */
2004109864Sjeffvoid
2005177085Sjeffsched_sleep(struct thread *td, int prio)
2006109864Sjeff{
2007165762Sjeff
2008170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2009109864Sjeff
2010172264Sjeff	td->td_slptick = ticks;
2011201347Skib	if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
2012177085Sjeff		td->td_flags |= TDF_CANSWAP;
2013217410Sjhb	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
2014217410Sjhb		return;
2015177903Sjeff	if (static_boost == 1 && prio)
2016177085Sjeff		sched_prio(td, prio);
2017177903Sjeff	else if (static_boost && td->td_priority > static_boost)
2018177903Sjeff		sched_prio(td, static_boost);
2019109864Sjeff}
2020109864Sjeff
2021171482Sjeff/*
2022171482Sjeff * Schedule a thread to resume execution and record how long it voluntarily
2023171482Sjeff * slept.  We also update the pctcpu, interactivity, and priority.
2024171482Sjeff */
2025109864Sjeffvoid
2026109864Sjeffsched_wakeup(struct thread *td)
2027109864Sjeff{
2028166229Sjeff	struct td_sched *ts;
2029171482Sjeff	int slptick;
2030165762Sjeff
2031170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2032166229Sjeff	ts = td->td_sched;
2033177085Sjeff	td->td_flags &= ~TDF_CANSWAP;
2034109864Sjeff	/*
2035165762Sjeff	 * If we slept for more than a tick update our interactivity and
2036165762Sjeff	 * priority.
2037109864Sjeff	 */
2038172264Sjeff	slptick = td->td_slptick;
2039172264Sjeff	td->td_slptick = 0;
2040171482Sjeff	if (slptick && slptick != ticks) {
2041232917Smav		ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
2042165819Sjeff		sched_interact_update(td);
2043232917Smav		sched_pctcpu_update(ts, 0);
2044109864Sjeff	}
2045242736Sjeff	/*
2046242736Sjeff	 * Reset the slice value since we slept and advanced the round-robin.
2047242736Sjeff	 */
2048242736Sjeff	ts->ts_slice = 0;
2049166190Sjeff	sched_add(td, SRQ_BORING);
2050109864Sjeff}
2051109864Sjeff
2052109864Sjeff/*
2053109864Sjeff * Penalize the parent for creating a new child and initialize the child's
2054109864Sjeff * priority.
2055109864Sjeff */
2056109864Sjeffvoid
2057163709Sjbsched_fork(struct thread *td, struct thread *child)
2058109864Sjeff{
2059170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2060232917Smav	sched_pctcpu_update(td->td_sched, 1);
2061164936Sjulian	sched_fork_thread(td, child);
2062165762Sjeff	/*
2063165762Sjeff	 * Penalize the parent and child for forking.
2064165762Sjeff	 */
2065165762Sjeff	sched_interact_fork(child);
2066165762Sjeff	sched_priority(child);
2067171482Sjeff	td->td_sched->ts_runtime += tickincr;
2068165762Sjeff	sched_interact_update(td);
2069165762Sjeff	sched_priority(td);
2070164936Sjulian}
2071109864Sjeff
2072171482Sjeff/*
2073171482Sjeff * Fork a new thread, may be within the same process.
2074171482Sjeff */
2075164936Sjulianvoid
2076164936Sjuliansched_fork_thread(struct thread *td, struct thread *child)
2077164936Sjulian{
2078164936Sjulian	struct td_sched *ts;
2079164936Sjulian	struct td_sched *ts2;
2080242736Sjeff	struct tdq *tdq;
2081164936Sjulian
2082242736Sjeff	tdq = TDQ_SELF();
2083177426Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2084165762Sjeff	/*
2085165762Sjeff	 * Initialize child.
2086165762Sjeff	 */
2087177426Sjeff	ts = td->td_sched;
2088177426Sjeff	ts2 = child->td_sched;
2089288463Sjhb	child->td_oncpu = NOCPU;
2090288463Sjhb	child->td_lastcpu = NOCPU;
2091242736Sjeff	child->td_lock = TDQ_LOCKPTR(tdq);
2092176735Sjeff	child->td_cpuset = cpuset_ref(td->td_cpuset);
2093164936Sjulian	ts2->ts_cpu = ts->ts_cpu;
2094177426Sjeff	ts2->ts_flags = 0;
2095165762Sjeff	/*
2096217078Sjhb	 * Grab our parents cpu estimation information.
2097165762Sjeff	 */
2098164936Sjulian	ts2->ts_ticks = ts->ts_ticks;
2099164936Sjulian	ts2->ts_ltick = ts->ts_ltick;
2100164936Sjulian	ts2->ts_ftick = ts->ts_ftick;
2101165762Sjeff	/*
2102217078Sjhb	 * Do not inherit any borrowed priority from the parent.
2103217078Sjhb	 */
2104217078Sjhb	child->td_priority = child->td_base_pri;
2105217078Sjhb	/*
2106165762Sjeff	 * And update interactivity score.
2107165762Sjeff	 */
2108171482Sjeff	ts2->ts_slptime = ts->ts_slptime;
2109171482Sjeff	ts2->ts_runtime = ts->ts_runtime;
2110242736Sjeff	/* Attempt to quickly learn interactivity. */
2111242736Sjeff	ts2->ts_slice = tdq_slice(tdq) - sched_slice_min;
2112187357Sjeff#ifdef KTR
2113187357Sjeff	bzero(ts2->ts_name, sizeof(ts2->ts_name));
2114187357Sjeff#endif
2115113357Sjeff}
2116113357Sjeff
2117171482Sjeff/*
2118171482Sjeff * Adjust the priority class of a thread.
2119171482Sjeff */
2120113357Sjeffvoid
2121163709Sjbsched_class(struct thread *td, int class)
2122113357Sjeff{
2123113357Sjeff
2124170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2125163709Sjb	if (td->td_pri_class == class)
2126113357Sjeff		return;
2127163709Sjb	td->td_pri_class = class;
2128109864Sjeff}
2129109864Sjeff
2130109864Sjeff/*
2131109864Sjeff * Return some of the child's priority and interactivity to the parent.
2132109864Sjeff */
2133109864Sjeffvoid
2134164939Sjuliansched_exit(struct proc *p, struct thread *child)
2135109864Sjeff{
2136165762Sjeff	struct thread *td;
2137113372Sjeff
2138187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2139225199Sdelphij	    "prio:%d", child->td_priority);
2140177368Sjeff	PROC_LOCK_ASSERT(p, MA_OWNED);
2141165762Sjeff	td = FIRST_THREAD_IN_PROC(p);
2142165762Sjeff	sched_exit_thread(td, child);
2143113372Sjeff}
2144113372Sjeff
2145171482Sjeff/*
2146171482Sjeff * Penalize another thread for the time spent on this one.  This helps to
2147171482Sjeff * worsen the priority and interactivity of processes which schedule batch
2148171482Sjeff * jobs such as make.  This has little effect on the make process itself but
2149171482Sjeff * causes new processes spawned by it to receive worse scores immediately.
2150171482Sjeff */
2151113372Sjeffvoid
2152164939Sjuliansched_exit_thread(struct thread *td, struct thread *child)
2153164936Sjulian{
2154165762Sjeff
2155187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2156225199Sdelphij	    "prio:%d", child->td_priority);
2157165762Sjeff	/*
2158165762Sjeff	 * Give the child's runtime to the parent without returning the
2159165762Sjeff	 * sleep time as a penalty to the parent.  This causes shells that
2160165762Sjeff	 * launch expensive things to mark their children as expensive.
2161165762Sjeff	 */
2162170293Sjeff	thread_lock(td);
2163171482Sjeff	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2164164939Sjulian	sched_interact_update(td);
2165165762Sjeff	sched_priority(td);
2166170293Sjeff	thread_unlock(td);
2167164936Sjulian}
2168164936Sjulian
2169177005Sjeffvoid
2170177005Sjeffsched_preempt(struct thread *td)
2171177005Sjeff{
2172177005Sjeff	struct tdq *tdq;
2173177005Sjeff
2174235459Srstone	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
2175235459Srstone
2176177005Sjeff	thread_lock(td);
2177177005Sjeff	tdq = TDQ_SELF();
2178177005Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2179177005Sjeff	tdq->tdq_ipipending = 0;
2180177005Sjeff	if (td->td_priority > tdq->tdq_lowpri) {
2181178272Sjeff		int flags;
2182178272Sjeff
2183178272Sjeff		flags = SW_INVOL | SW_PREEMPT;
2184177005Sjeff		if (td->td_critnest > 1)
2185177005Sjeff			td->td_owepreempt = 1;
2186178272Sjeff		else if (TD_IS_IDLETHREAD(td))
2187178272Sjeff			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2188177005Sjeff		else
2189178272Sjeff			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2190177005Sjeff	}
2191177005Sjeff	thread_unlock(td);
2192177005Sjeff}
2193177005Sjeff
2194171482Sjeff/*
2195171482Sjeff * Fix priorities on return to user-space.  Priorities may be elevated due
2196171482Sjeff * to static priorities in msleep() or similar.
2197171482Sjeff */
2198164936Sjulianvoid
2199164936Sjuliansched_userret(struct thread *td)
2200164936Sjulian{
2201164936Sjulian	/*
2202164936Sjulian	 * XXX we cheat slightly on the locking here to avoid locking in
2203164936Sjulian	 * the usual case.  Setting td_priority here is essentially an
2204164936Sjulian	 * incomplete workaround for not setting it properly elsewhere.
2205164936Sjulian	 * Now that some interrupt handlers are threads, not setting it
2206164936Sjulian	 * properly elsewhere can clobber it in the window between setting
2207164936Sjulian	 * it here and returning to user mode, so don't waste time setting
2208164936Sjulian	 * it perfectly here.
2209164936Sjulian	 */
2210164936Sjulian	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2211164936Sjulian	    ("thread with borrowed priority returning to userland"));
2212164936Sjulian	if (td->td_priority != td->td_user_pri) {
2213170293Sjeff		thread_lock(td);
2214164936Sjulian		td->td_priority = td->td_user_pri;
2215164936Sjulian		td->td_base_pri = td->td_user_pri;
2216177005Sjeff		tdq_setlowpri(TDQ_SELF(), td);
2217170293Sjeff		thread_unlock(td);
2218164936Sjulian        }
2219164936Sjulian}
2220164936Sjulian
2221171482Sjeff/*
2222171482Sjeff * Handle a stathz tick.  This is really only relevant for timeshare
2223171482Sjeff * threads.
2224171482Sjeff */
2225164936Sjulianvoid
2226121127Sjeffsched_clock(struct thread *td)
2227109864Sjeff{
2228164936Sjulian	struct tdq *tdq;
2229164936Sjulian	struct td_sched *ts;
2230109864Sjeff
2231171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2232164936Sjulian	tdq = TDQ_SELF();
2233172409Sjeff#ifdef SMP
2234133427Sjeff	/*
2235172409Sjeff	 * We run the long term load balancer infrequently on the first cpu.
2236172409Sjeff	 */
2237172409Sjeff	if (balance_tdq == tdq) {
2238172409Sjeff		if (balance_ticks && --balance_ticks == 0)
2239172409Sjeff			sched_balance();
2240172409Sjeff	}
2241172409Sjeff#endif
2242172409Sjeff	/*
2243178277Sjeff	 * Save the old switch count so we have a record of the last ticks
2244178277Sjeff	 * activity.   Initialize the new switch count based on our load.
2245178277Sjeff	 * If there is some activity seed it to reflect that.
2246178277Sjeff	 */
2247178277Sjeff	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
2248178471Sjeff	tdq->tdq_switchcnt = tdq->tdq_load;
2249178277Sjeff	/*
2250165766Sjeff	 * Advance the insert index once for each tick to ensure that all
2251165766Sjeff	 * threads get a chance to run.
2252133427Sjeff	 */
2253165766Sjeff	if (tdq->tdq_idx == tdq->tdq_ridx) {
2254165766Sjeff		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2255165766Sjeff		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2256165766Sjeff			tdq->tdq_ridx = tdq->tdq_idx;
2257165766Sjeff	}
2258165766Sjeff	ts = td->td_sched;
2259232917Smav	sched_pctcpu_update(ts, 1);
2260175104Sjeff	if (td->td_pri_class & PRI_FIFO_BIT)
2261113357Sjeff		return;
2262217291Sjhb	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2263175104Sjeff		/*
2264175104Sjeff		 * We used a tick; charge it to the thread so
2265175104Sjeff		 * that we can compute our interactivity.
2266175104Sjeff		 */
2267175104Sjeff		td->td_sched->ts_runtime += tickincr;
2268175104Sjeff		sched_interact_update(td);
2269177009Sjeff		sched_priority(td);
2270175104Sjeff	}
2271239185Smav
2272113357Sjeff	/*
2273239185Smav	 * Force a context switch if the current thread has used up a full
2274239185Smav	 * time slice (default is 100ms).
2275109864Sjeff	 */
2276242736Sjeff	if (!TD_IS_IDLETHREAD(td) && ++ts->ts_slice >= tdq_slice(tdq)) {
2277242736Sjeff		ts->ts_slice = 0;
2278239185Smav		td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
2279239185Smav	}
2280109864Sjeff}
2281109864Sjeff
2282171482Sjeff/*
2283232917Smav * Called once per hz tick.
2284171482Sjeff */
2285171482Sjeffvoid
2286212541Smavsched_tick(int cnt)
2287171482Sjeff{
2288171482Sjeff
2289171482Sjeff}
2290171482Sjeff
2291171482Sjeff/*
2292171482Sjeff * Return whether the current CPU has runnable tasks.  Used for in-kernel
2293171482Sjeff * cooperative idle threads.
2294171482Sjeff */
2295109864Sjeffint
2296109864Sjeffsched_runnable(void)
2297109864Sjeff{
2298164936Sjulian	struct tdq *tdq;
2299115998Sjeff	int load;
2300109864Sjeff
2301115998Sjeff	load = 1;
2302115998Sjeff
2303164936Sjulian	tdq = TDQ_SELF();
2304121605Sjeff	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2305165620Sjeff		if (tdq->tdq_load > 0)
2306121605Sjeff			goto out;
2307121605Sjeff	} else
2308165620Sjeff		if (tdq->tdq_load - 1 > 0)
2309121605Sjeff			goto out;
2310115998Sjeff	load = 0;
2311115998Sjeffout:
2312115998Sjeff	return (load);
2313109864Sjeff}
2314109864Sjeff
2315171482Sjeff/*
2316171482Sjeff * Choose the highest priority thread to run.  The thread is removed from
2317171482Sjeff * the run-queue while running however the load remains.  For SMP we set
2318171482Sjeff * the tdq in the global idle bitmask if it idles here.
2319171482Sjeff */
2320166190Sjeffstruct thread *
2321109970Sjeffsched_choose(void)
2322109970Sjeff{
2323177435Sjeff	struct thread *td;
2324164936Sjulian	struct tdq *tdq;
2325109970Sjeff
2326164936Sjulian	tdq = TDQ_SELF();
2327171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2328177435Sjeff	td = tdq_choose(tdq);
2329177435Sjeff	if (td) {
2330177435Sjeff		tdq_runq_rem(tdq, td);
2331177903Sjeff		tdq->tdq_lowpri = td->td_priority;
2332177435Sjeff		return (td);
2333109864Sjeff	}
2334177903Sjeff	tdq->tdq_lowpri = PRI_MAX_IDLE;
2335176735Sjeff	return (PCPU_GET(idlethread));
2336109864Sjeff}
2337109864Sjeff
2338171482Sjeff/*
2339171482Sjeff * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2340171482Sjeff * we always request it once we exit a critical section.
2341171482Sjeff */
2342171482Sjeffstatic inline void
2343171482Sjeffsched_setpreempt(struct thread *td)
2344166190Sjeff{
2345166190Sjeff	struct thread *ctd;
2346166190Sjeff	int cpri;
2347166190Sjeff	int pri;
2348166190Sjeff
2349177005Sjeff	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2350177005Sjeff
2351166190Sjeff	ctd = curthread;
2352166190Sjeff	pri = td->td_priority;
2353166190Sjeff	cpri = ctd->td_priority;
2354177005Sjeff	if (pri < cpri)
2355177005Sjeff		ctd->td_flags |= TDF_NEEDRESCHED;
2356166190Sjeff	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2357171482Sjeff		return;
2358177005Sjeff	if (!sched_shouldpreempt(pri, cpri, 0))
2359171482Sjeff		return;
2360171482Sjeff	ctd->td_owepreempt = 1;
2361166190Sjeff}
2362166190Sjeff
2363171482Sjeff/*
2364177009Sjeff * Add a thread to a thread queue.  Select the appropriate runq and add the
2365177009Sjeff * thread to it.  This is the internal function called when the tdq is
2366177009Sjeff * predetermined.
2367171482Sjeff */
2368109864Sjeffvoid
2369171482Sjefftdq_add(struct tdq *tdq, struct thread *td, int flags)
2370109864Sjeff{
2371109864Sjeff
2372171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2373166190Sjeff	KASSERT((td->td_inhibitors == 0),
2374166190Sjeff	    ("sched_add: trying to run inhibited thread"));
2375166190Sjeff	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2376166190Sjeff	    ("sched_add: bad thread state"));
2377172207Sjeff	KASSERT(td->td_flags & TDF_INMEM,
2378172207Sjeff	    ("sched_add: thread swapped out"));
2379171482Sjeff
2380171482Sjeff	if (td->td_priority < tdq->tdq_lowpri)
2381171482Sjeff		tdq->tdq_lowpri = td->td_priority;
2382177435Sjeff	tdq_runq_add(tdq, td, flags);
2383177435Sjeff	tdq_load_add(tdq, td);
2384171482Sjeff}
2385171482Sjeff
2386171482Sjeff/*
2387171482Sjeff * Select the target thread queue and add a thread to it.  Request
2388171482Sjeff * preemption or IPI a remote processor if required.
2389171482Sjeff */
2390171482Sjeffvoid
2391171482Sjeffsched_add(struct thread *td, int flags)
2392171482Sjeff{
2393171482Sjeff	struct tdq *tdq;
2394171482Sjeff#ifdef SMP
2395171482Sjeff	int cpu;
2396171482Sjeff#endif
2397187357Sjeff
2398187357Sjeff	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
2399187357Sjeff	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
2400187357Sjeff	    sched_tdname(curthread));
2401187357Sjeff	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
2402187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(td));
2403235459Srstone	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
2404235459Srstone	    flags & SRQ_PREEMPTED);
2405171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2406166108Sjeff	/*
2407171482Sjeff	 * Recalculate the priority before we select the target cpu or
2408171482Sjeff	 * run-queue.
2409166108Sjeff	 */
2410171482Sjeff	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2411171482Sjeff		sched_priority(td);
2412171482Sjeff#ifdef SMP
2413171482Sjeff	/*
2414171482Sjeff	 * Pick the destination cpu and if it isn't ours transfer to the
2415171482Sjeff	 * target cpu.
2416171482Sjeff	 */
2417177435Sjeff	cpu = sched_pickcpu(td, flags);
2418177435Sjeff	tdq = sched_setcpu(td, cpu, flags);
2419171482Sjeff	tdq_add(tdq, td, flags);
2420177009Sjeff	if (cpu != PCPU_GET(cpuid)) {
2421177435Sjeff		tdq_notify(tdq, td);
2422166108Sjeff		return;
2423166108Sjeff	}
2424171482Sjeff#else
2425171482Sjeff	tdq = TDQ_SELF();
2426171482Sjeff	TDQ_LOCK(tdq);
2427171482Sjeff	/*
2428171482Sjeff	 * Now that the thread is moving to the run-queue, set the lock
2429171482Sjeff	 * to the scheduler's lock.
2430171482Sjeff	 */
2431171482Sjeff	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2432171482Sjeff	tdq_add(tdq, td, flags);
2433166108Sjeff#endif
2434171482Sjeff	if (!(flags & SRQ_YIELDING))
2435171482Sjeff		sched_setpreempt(td);
2436109864Sjeff}
2437109864Sjeff
2438171482Sjeff/*
2439171482Sjeff * Remove a thread from a run-queue without running it.  This is used
2440171482Sjeff * when we're stealing a thread from a remote queue.  Otherwise all threads
2441171482Sjeff * exit by calling sched_exit_thread() and sched_throw() themselves.
2442171482Sjeff */
2443109864Sjeffvoid
2444121127Sjeffsched_rem(struct thread *td)
2445109864Sjeff{
2446164936Sjulian	struct tdq *tdq;
2447113357Sjeff
2448187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
2449187357Sjeff	    "prio:%d", td->td_priority);
2450235459Srstone	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
2451177435Sjeff	tdq = TDQ_CPU(td->td_sched->ts_cpu);
2452171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2453171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2454166190Sjeff	KASSERT(TD_ON_RUNQ(td),
2455164936Sjulian	    ("sched_rem: thread not on run queue"));
2456177435Sjeff	tdq_runq_rem(tdq, td);
2457177435Sjeff	tdq_load_rem(tdq, td);
2458166190Sjeff	TD_SET_CAN_RUN(td);
2459176735Sjeff	if (td->td_priority == tdq->tdq_lowpri)
2460176735Sjeff		tdq_setlowpri(tdq, NULL);
2461109864Sjeff}
2462109864Sjeff
2463171482Sjeff/*
2464171482Sjeff * Fetch cpu utilization information.  Updates on demand.
2465171482Sjeff */
2466109864Sjefffixpt_t
2467121127Sjeffsched_pctcpu(struct thread *td)
2468109864Sjeff{
2469109864Sjeff	fixpt_t pctcpu;
2470164936Sjulian	struct td_sched *ts;
2471109864Sjeff
2472109864Sjeff	pctcpu = 0;
2473164936Sjulian	ts = td->td_sched;
2474164936Sjulian	if (ts == NULL)
2475121290Sjeff		return (0);
2476109864Sjeff
2477208787Sjhb	THREAD_LOCK_ASSERT(td, MA_OWNED);
2478232917Smav	sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2479164936Sjulian	if (ts->ts_ticks) {
2480109864Sjeff		int rtick;
2481109864Sjeff
2482109864Sjeff		/* How many rtick per second ? */
2483165762Sjeff		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2484165762Sjeff		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2485109864Sjeff	}
2486109864Sjeff
2487109864Sjeff	return (pctcpu);
2488109864Sjeff}
2489109864Sjeff
2490176735Sjeff/*
2491176735Sjeff * Enforce affinity settings for a thread.  Called after adjustments to
2492176735Sjeff * cpumask.
2493176735Sjeff */
2494176729Sjeffvoid
2495176729Sjeffsched_affinity(struct thread *td)
2496176729Sjeff{
2497176735Sjeff#ifdef SMP
2498176735Sjeff	struct td_sched *ts;
2499176735Sjeff
2500176735Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2501176735Sjeff	ts = td->td_sched;
2502176735Sjeff	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2503176735Sjeff		return;
2504189787Sjeff	if (TD_ON_RUNQ(td)) {
2505189787Sjeff		sched_rem(td);
2506189787Sjeff		sched_add(td, SRQ_BORING);
2507189787Sjeff		return;
2508189787Sjeff	}
2509176735Sjeff	if (!TD_IS_RUNNING(td))
2510176735Sjeff		return;
2511176735Sjeff	/*
2512212115Smdf	 * Force a switch before returning to userspace.  If the
2513212115Smdf	 * target thread is not running locally send an ipi to force
2514212115Smdf	 * the issue.
2515176735Sjeff	 */
2516212974Sjhb	td->td_flags |= TDF_NEEDRESCHED;
2517212115Smdf	if (td != curthread)
2518212115Smdf		ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
2519176735Sjeff#endif
2520176729Sjeff}
2521176729Sjeff
2522171482Sjeff/*
2523171482Sjeff * Bind a thread to a target cpu.
2524171482Sjeff */
2525122038Sjeffvoid
2526122038Sjeffsched_bind(struct thread *td, int cpu)
2527122038Sjeff{
2528164936Sjulian	struct td_sched *ts;
2529122038Sjeff
2530171713Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2531208391Sjhb	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
2532164936Sjulian	ts = td->td_sched;
2533166137Sjeff	if (ts->ts_flags & TSF_BOUND)
2534166152Sjeff		sched_unbind(td);
2535212115Smdf	KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2536164936Sjulian	ts->ts_flags |= TSF_BOUND;
2537166137Sjeff	sched_pin();
2538123433Sjeff	if (PCPU_GET(cpuid) == cpu)
2539122038Sjeff		return;
2540166137Sjeff	ts->ts_cpu = cpu;
2541122038Sjeff	/* When we return from mi_switch we'll be on the correct cpu. */
2542131527Sphk	mi_switch(SW_VOL, NULL);
2543122038Sjeff}
2544122038Sjeff
2545171482Sjeff/*
2546171482Sjeff * Release a bound thread.
2547171482Sjeff */
2548122038Sjeffvoid
2549122038Sjeffsched_unbind(struct thread *td)
2550122038Sjeff{
2551165762Sjeff	struct td_sched *ts;
2552165762Sjeff
2553170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2554208391Sjhb	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
2555165762Sjeff	ts = td->td_sched;
2556166137Sjeff	if ((ts->ts_flags & TSF_BOUND) == 0)
2557166137Sjeff		return;
2558165762Sjeff	ts->ts_flags &= ~TSF_BOUND;
2559165762Sjeff	sched_unpin();
2560122038Sjeff}
2561122038Sjeff
2562109864Sjeffint
2563145256Sjkoshysched_is_bound(struct thread *td)
2564145256Sjkoshy{
2565170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2566164936Sjulian	return (td->td_sched->ts_flags & TSF_BOUND);
2567145256Sjkoshy}
2568145256Sjkoshy
2569171482Sjeff/*
2570171482Sjeff * Basic yield call.
2571171482Sjeff */
2572159630Sdavidxuvoid
2573159630Sdavidxusched_relinquish(struct thread *td)
2574159630Sdavidxu{
2575170293Sjeff	thread_lock(td);
2576178272Sjeff	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
2577170293Sjeff	thread_unlock(td);
2578159630Sdavidxu}
2579159630Sdavidxu
2580171482Sjeff/*
2581171482Sjeff * Return the total system load.
2582171482Sjeff */
2583145256Sjkoshyint
2584125289Sjeffsched_load(void)
2585125289Sjeff{
2586125289Sjeff#ifdef SMP
2587125289Sjeff	int total;
2588125289Sjeff	int i;
2589125289Sjeff
2590125289Sjeff	total = 0;
2591209059Sjhb	CPU_FOREACH(i)
2592176735Sjeff		total += TDQ_CPU(i)->tdq_sysload;
2593125289Sjeff	return (total);
2594125289Sjeff#else
2595165620Sjeff	return (TDQ_SELF()->tdq_sysload);
2596125289Sjeff#endif
2597125289Sjeff}
2598125289Sjeff
2599125289Sjeffint
2600109864Sjeffsched_sizeof_proc(void)
2601109864Sjeff{
2602109864Sjeff	return (sizeof(struct proc));
2603109864Sjeff}
2604109864Sjeff
2605109864Sjeffint
2606109864Sjeffsched_sizeof_thread(void)
2607109864Sjeff{
2608109864Sjeff	return (sizeof(struct thread) + sizeof(struct td_sched));
2609109864Sjeff}
2610159570Sdavidxu
2611191676Sjeff#ifdef SMP
2612191676Sjeff#define	TDQ_IDLESPIN(tdq)						\
2613191676Sjeff    ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
2614191676Sjeff#else
2615191676Sjeff#define	TDQ_IDLESPIN(tdq)	1
2616191676Sjeff#endif
2617191676Sjeff
2618166190Sjeff/*
2619166190Sjeff * The actual idle process.
2620166190Sjeff */
2621166190Sjeffvoid
2622166190Sjeffsched_idletd(void *dummy)
2623166190Sjeff{
2624166190Sjeff	struct thread *td;
2625171482Sjeff	struct tdq *tdq;
2626242852Smav	int oldswitchcnt, switchcnt;
2627178277Sjeff	int i;
2628166190Sjeff
2629191643Sjeff	mtx_assert(&Giant, MA_NOTOWNED);
2630166190Sjeff	td = curthread;
2631171482Sjeff	tdq = TDQ_SELF();
2632239585Sjhb	THREAD_NO_SLEEPING();
2633242852Smav	oldswitchcnt = -1;
2634171482Sjeff	for (;;) {
2635242852Smav		if (tdq->tdq_load) {
2636242852Smav			thread_lock(td);
2637242852Smav			mi_switch(SW_VOL | SWT_IDLE, NULL);
2638242852Smav			thread_unlock(td);
2639242852Smav		}
2640242852Smav		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2641171482Sjeff#ifdef SMP
2642242852Smav		if (switchcnt != oldswitchcnt) {
2643242852Smav			oldswitchcnt = switchcnt;
2644242852Smav			if (tdq_idled(tdq) == 0)
2645242852Smav				continue;
2646242852Smav		}
2647243069Smav		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2648243069Smav#else
2649243069Smav		oldswitchcnt = switchcnt;
2650171482Sjeff#endif
2651178277Sjeff		/*
2652178277Sjeff		 * If we're switching very frequently, spin while checking
2653178277Sjeff		 * for load rather than entering a low power state that
2654191643Sjeff		 * may require an IPI.  However, don't do any busy
2655191643Sjeff		 * loops while on SMT machines as this simply steals
2656191643Sjeff		 * cycles from cores doing useful work.
2657178277Sjeff		 */
2658191676Sjeff		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
2659178277Sjeff			for (i = 0; i < sched_idlespins; i++) {
2660178277Sjeff				if (tdq->tdq_load)
2661178277Sjeff					break;
2662178277Sjeff				cpu_spinwait();
2663178277Sjeff			}
2664178277Sjeff		}
2665242852Smav
2666242852Smav		/* If there was context switch during spin, restart it. */
2667191643Sjeff		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2668242852Smav		if (tdq->tdq_load != 0 || switchcnt != oldswitchcnt)
2669242852Smav			continue;
2670242852Smav
2671242852Smav		/* Run main MD idle handler. */
2672242852Smav		tdq->tdq_cpu_idle = 1;
2673271707Smav		/*
2674271707Smav		 * Make sure that tdq_cpu_idle update is globally visible
2675271707Smav		 * before cpu_idle() read tdq_load.  The order is important
2676271707Smav		 * to avoid race with tdq_notify.
2677271707Smav		 */
2678271707Smav		mb();
2679242852Smav		cpu_idle(switchcnt * 4 > sched_idlespinthresh);
2680242852Smav		tdq->tdq_cpu_idle = 0;
2681242852Smav
2682242852Smav		/*
2683242852Smav		 * Account thread-less hardware interrupts and
2684242852Smav		 * other wakeup reasons equal to context switches.
2685242852Smav		 */
2686242852Smav		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2687242852Smav		if (switchcnt != oldswitchcnt)
2688242852Smav			continue;
2689242852Smav		tdq->tdq_switchcnt++;
2690242852Smav		oldswitchcnt++;
2691171482Sjeff	}
2692166190Sjeff}
2693166190Sjeff
2694170293Sjeff/*
2695170293Sjeff * A CPU is entering for the first time or a thread is exiting.
2696170293Sjeff */
2697170293Sjeffvoid
2698170293Sjeffsched_throw(struct thread *td)
2699170293Sjeff{
2700172411Sjeff	struct thread *newtd;
2701171482Sjeff	struct tdq *tdq;
2702171482Sjeff
2703171482Sjeff	tdq = TDQ_SELF();
2704170293Sjeff	if (td == NULL) {
2705171482Sjeff		/* Correct spinlock nesting and acquire the correct lock. */
2706171482Sjeff		TDQ_LOCK(tdq);
2707170293Sjeff		spinlock_exit();
2708229429Sjhb		PCPU_SET(switchtime, cpu_ticks());
2709229429Sjhb		PCPU_SET(switchticks, ticks);
2710170293Sjeff	} else {
2711171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2712177435Sjeff		tdq_load_rem(tdq, td);
2713174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2714288463Sjhb		td->td_lastcpu = td->td_oncpu;
2715288463Sjhb		td->td_oncpu = NOCPU;
2716170293Sjeff	}
2717170293Sjeff	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2718172411Sjeff	newtd = choosethread();
2719172411Sjeff	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2720172411Sjeff	cpu_throw(td, newtd);		/* doesn't return */
2721170293Sjeff}
2722170293Sjeff
2723171482Sjeff/*
2724171482Sjeff * This is called from fork_exit().  Just acquire the correct locks and
2725171482Sjeff * let fork do the rest of the work.
2726171482Sjeff */
2727170293Sjeffvoid
2728170600Sjeffsched_fork_exit(struct thread *td)
2729170293Sjeff{
2730171482Sjeff	struct tdq *tdq;
2731171482Sjeff	int cpuid;
2732170293Sjeff
2733170293Sjeff	/*
2734170293Sjeff	 * Finish setting up thread glue so that it begins execution in a
2735171482Sjeff	 * non-nested critical section with the scheduler lock held.
2736170293Sjeff	 */
2737171482Sjeff	cpuid = PCPU_GET(cpuid);
2738171482Sjeff	tdq = TDQ_CPU(cpuid);
2739171482Sjeff	if (TD_IS_IDLETHREAD(td))
2740171482Sjeff		td->td_lock = TDQ_LOCKPTR(tdq);
2741171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2742171482Sjeff	td->td_oncpu = cpuid;
2743172411Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2744174629Sjeff	lock_profile_obtain_lock_success(
2745174629Sjeff	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2746315839Savg
2747315839Savg	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
2748315839Savg	    "prio:%d", td->td_priority);
2749315839Savg	SDT_PROBE0(sched, , , on__cpu);
2750170293Sjeff}
2751170293Sjeff
2752187357Sjeff/*
2753187357Sjeff * Create on first use to catch odd startup conditons.
2754187357Sjeff */
2755187357Sjeffchar *
2756187357Sjeffsched_tdname(struct thread *td)
2757187357Sjeff{
2758187357Sjeff#ifdef KTR
2759187357Sjeff	struct td_sched *ts;
2760187357Sjeff
2761187357Sjeff	ts = td->td_sched;
2762187357Sjeff	if (ts->ts_name[0] == '\0')
2763187357Sjeff		snprintf(ts->ts_name, sizeof(ts->ts_name),
2764187357Sjeff		    "%s tid %d", td->td_name, td->td_tid);
2765187357Sjeff	return (ts->ts_name);
2766187357Sjeff#else
2767187357Sjeff	return (td->td_name);
2768187357Sjeff#endif
2769187357Sjeff}
2770187357Sjeff
2771232700Sjhb#ifdef KTR
2772232700Sjhbvoid
2773232700Sjhbsched_clear_tdname(struct thread *td)
2774232700Sjhb{
2775232700Sjhb	struct td_sched *ts;
2776232700Sjhb
2777232700Sjhb	ts = td->td_sched;
2778232700Sjhb	ts->ts_name[0] = '\0';
2779232700Sjhb}
2780232700Sjhb#endif
2781232700Sjhb
2782184439Sivoras#ifdef SMP
2783184439Sivoras
2784184439Sivoras/*
2785184439Sivoras * Build the CPU topology dump string. Is recursively called to collect
2786184439Sivoras * the topology tree.
2787184439Sivoras */
2788184439Sivorasstatic int
2789184439Sivorassysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
2790184439Sivoras    int indent)
2791184439Sivoras{
2792222813Sattilio	char cpusetbuf[CPUSETBUFSIZ];
2793184439Sivoras	int i, first;
2794184439Sivoras
2795184439Sivoras	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
2796212821Savg	    "", 1 + indent / 2, cg->cg_level);
2797222813Sattilio	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
2798222813Sattilio	    cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
2799184439Sivoras	first = TRUE;
2800184439Sivoras	for (i = 0; i < MAXCPU; i++) {
2801222813Sattilio		if (CPU_ISSET(i, &cg->cg_mask)) {
2802184439Sivoras			if (!first)
2803184439Sivoras				sbuf_printf(sb, ", ");
2804184439Sivoras			else
2805184439Sivoras				first = FALSE;
2806184439Sivoras			sbuf_printf(sb, "%d", i);
2807184439Sivoras		}
2808184439Sivoras	}
2809184439Sivoras	sbuf_printf(sb, "</cpu>\n");
2810184439Sivoras
2811184439Sivoras	if (cg->cg_flags != 0) {
2812210117Sivoras		sbuf_printf(sb, "%*s <flags>", indent, "");
2813184439Sivoras		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
2814208982Sivoras			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
2815208983Sivoras		if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
2816208983Sivoras			sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
2817191643Sjeff		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
2818208983Sivoras			sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
2819210117Sivoras		sbuf_printf(sb, "</flags>\n");
2820184439Sivoras	}
2821184439Sivoras
2822184439Sivoras	if (cg->cg_children > 0) {
2823184439Sivoras		sbuf_printf(sb, "%*s <children>\n", indent, "");
2824184439Sivoras		for (i = 0; i < cg->cg_children; i++)
2825184439Sivoras			sysctl_kern_sched_topology_spec_internal(sb,
2826184439Sivoras			    &cg->cg_child[i], indent+2);
2827184439Sivoras		sbuf_printf(sb, "%*s </children>\n", indent, "");
2828184439Sivoras	}
2829184439Sivoras	sbuf_printf(sb, "%*s</group>\n", indent, "");
2830184439Sivoras	return (0);
2831184439Sivoras}
2832184439Sivoras
2833184439Sivoras/*
2834184439Sivoras * Sysctl handler for retrieving topology dump. It's a wrapper for
2835184439Sivoras * the recursive sysctl_kern_smp_topology_spec_internal().
2836184439Sivoras */
2837184439Sivorasstatic int
2838184439Sivorassysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
2839184439Sivoras{
2840184439Sivoras	struct sbuf *topo;
2841184439Sivoras	int err;
2842184439Sivoras
2843184439Sivoras	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
2844184439Sivoras
2845184570Sivoras	topo = sbuf_new(NULL, NULL, 500, SBUF_AUTOEXTEND);
2846184439Sivoras	if (topo == NULL)
2847184439Sivoras		return (ENOMEM);
2848184439Sivoras
2849184439Sivoras	sbuf_printf(topo, "<groups>\n");
2850184439Sivoras	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
2851184439Sivoras	sbuf_printf(topo, "</groups>\n");
2852184439Sivoras
2853184439Sivoras	if (err == 0) {
2854184439Sivoras		sbuf_finish(topo);
2855184439Sivoras		err = SYSCTL_OUT(req, sbuf_data(topo), sbuf_len(topo));
2856184439Sivoras	}
2857184439Sivoras	sbuf_delete(topo);
2858184439Sivoras	return (err);
2859184439Sivoras}
2860214510Sdavidxu
2861184439Sivoras#endif
2862184439Sivoras
2863239185Smavstatic int
2864239185Smavsysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
2865239185Smav{
2866239185Smav	int error, new_val, period;
2867239185Smav
2868239185Smav	period = 1000000 / realstathz;
2869239185Smav	new_val = period * sched_slice;
2870239185Smav	error = sysctl_handle_int(oidp, &new_val, 0, req);
2871239196Smav	if (error != 0 || req->newptr == NULL)
2872239185Smav		return (error);
2873239185Smav	if (new_val <= 0)
2874239185Smav		return (EINVAL);
2875239196Smav	sched_slice = imax(1, (new_val + period / 2) / period);
2876242736Sjeff	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
2877239196Smav	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
2878239196Smav	    realstathz);
2879239185Smav	return (0);
2880239185Smav}
2881239185Smav
2882177435SjeffSYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2883171482SjeffSYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2884165762Sjeff    "Scheduler name");
2885239185SmavSYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
2886239185Smav    NULL, 0, sysctl_kern_quantum, "I",
2887239196Smav    "Quantum for timeshare threads in microseconds");
2888171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2889239196Smav    "Quantum for timeshare threads in stathz ticks");
2890171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2891239196Smav    "Interactivity score threshold");
2892239196SmavSYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW,
2893239196Smav    &preempt_thresh, 0,
2894239196Smav    "Maximal (lowest) priority for preemption");
2895239196SmavSYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost, 0,
2896239196Smav    "Assign static kernel priorities to sleeping threads");
2897239196SmavSYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins, 0,
2898239196Smav    "Number of times idle thread will spin waiting for new work");
2899239196SmavSYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW,
2900239196Smav    &sched_idlespinthresh, 0,
2901239196Smav    "Threshold before we will permit idle thread spinning");
2902166108Sjeff#ifdef SMP
2903171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2904171482Sjeff    "Number of hz ticks to keep thread affinity for");
2905171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2906171482Sjeff    "Enables the long-term load balancer");
2907172409SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2908172409Sjeff    &balance_interval, 0,
2909239185Smav    "Average period in stathz ticks to run the long-term balancer");
2910171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2911171482Sjeff    "Attempts to steal work from other cores before idling");
2912171506SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2913239196Smav    "Minimum load on remote CPU before we'll steal");
2914184439SivorasSYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
2915239185Smav    CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
2916184439Sivoras    "XML dump of detected CPU topology");
2917166108Sjeff#endif
2918165762Sjeff
2919172264Sjeff/* ps compat.  All cpu percentages from ULE are weighted. */
2920172293Sjeffstatic int ccpu = 0;
2921165762SjeffSYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2922