sched_ule.c revision 242402
1109864Sjeff/*-
2165762Sjeff * Copyright (c) 2002-2007, Jeffrey Roberson <jeff@freebsd.org>
3109864Sjeff * All rights reserved.
4109864Sjeff *
5109864Sjeff * Redistribution and use in source and binary forms, with or without
6109864Sjeff * modification, are permitted provided that the following conditions
7109864Sjeff * are met:
8109864Sjeff * 1. Redistributions of source code must retain the above copyright
9109864Sjeff *    notice unmodified, this list of conditions, and the following
10109864Sjeff *    disclaimer.
11109864Sjeff * 2. Redistributions in binary form must reproduce the above copyright
12109864Sjeff *    notice, this list of conditions and the following disclaimer in the
13109864Sjeff *    documentation and/or other materials provided with the distribution.
14109864Sjeff *
15109864Sjeff * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16109864Sjeff * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17109864Sjeff * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18109864Sjeff * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19109864Sjeff * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20109864Sjeff * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21109864Sjeff * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22109864Sjeff * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23109864Sjeff * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24109864Sjeff * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25109864Sjeff */
26109864Sjeff
27171482Sjeff/*
28171482Sjeff * This file implements the ULE scheduler.  ULE supports independent CPU
29171482Sjeff * run queues and fine grain locking.  It has superior interactive
30171482Sjeff * performance under load even on uni-processor systems.
31171482Sjeff *
32171482Sjeff * etymology:
33172293Sjeff *   ULE is the last three letters in schedule.  It owes its name to a
34171482Sjeff * generic user created for a scheduling system by Paul Mikesell at
35171482Sjeff * Isilon Systems and a general lack of creativity on the part of the author.
36171482Sjeff */
37171482Sjeff
38116182Sobrien#include <sys/cdefs.h>
39191645Sjeff__FBSDID("$FreeBSD: head/sys/kern/sched_ule.c 242402 2012-10-31 18:07:18Z attilio $");
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
80236141Sraj#if defined(__powerpc__) && defined(BOOKE_E500)
81172345Sjeff#error "This architecture is not currently compatible with ULE"
82166190Sjeff#endif
83166190Sjeff
84171482Sjeff#define	KTR_ULE	0
85166137Sjeff
86187679Sjeff#define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
87187679Sjeff#define	TDQ_NAME_LEN	(sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
88224221Sattilio#define	TDQ_LOADNAME_LEN	(sizeof("CPU ") + sizeof(__XSTRING(MAXCPU)) - 1 + sizeof(" load"))
89187357Sjeff
90166137Sjeff/*
91171482Sjeff * Thread scheduler specific section.  All fields are protected
92171482Sjeff * by the thread lock.
93146954Sjeff */
94164936Sjulianstruct td_sched {
95171482Sjeff	struct runq	*ts_runq;	/* Run-queue we're queued on. */
96171482Sjeff	short		ts_flags;	/* TSF_* flags. */
97164936Sjulian	u_char		ts_cpu;		/* CPU that we have affinity for. */
98177009Sjeff	int		ts_rltick;	/* Real last tick, for affinity. */
99171482Sjeff	int		ts_slice;	/* Ticks of slice remaining. */
100171482Sjeff	u_int		ts_slptime;	/* Number of ticks we vol. slept */
101171482Sjeff	u_int		ts_runtime;	/* Number of ticks we were running */
102164936Sjulian	int		ts_ltick;	/* Last tick that we were running on */
103164936Sjulian	int		ts_ftick;	/* First tick that we were running on */
104164936Sjulian	int		ts_ticks;	/* Tick count */
105187357Sjeff#ifdef KTR
106187357Sjeff	char		ts_name[TS_NAME_LEN];
107187357Sjeff#endif
108134791Sjulian};
109164936Sjulian/* flags kept in ts_flags */
110166108Sjeff#define	TSF_BOUND	0x0001		/* Thread can not migrate. */
111166108Sjeff#define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
112121790Sjeff
113164936Sjulianstatic struct td_sched td_sched0;
114109864Sjeff
115176735Sjeff#define	THREAD_CAN_MIGRATE(td)	((td)->td_pinned == 0)
116176735Sjeff#define	THREAD_CAN_SCHED(td, cpu)	\
117176735Sjeff    CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
118176735Sjeff
119109864Sjeff/*
120217351Sjhb * Priority ranges used for interactive and non-interactive timeshare
121217410Sjhb * threads.  The timeshare priorities are split up into four ranges.
122217410Sjhb * The first range handles interactive threads.  The last three ranges
123217410Sjhb * (NHALF, x, and NHALF) handle non-interactive threads with the outer
124217410Sjhb * ranges supporting nice values.
125217351Sjhb */
126217410Sjhb#define	PRI_TIMESHARE_RANGE	(PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
127217410Sjhb#define	PRI_INTERACT_RANGE	((PRI_TIMESHARE_RANGE - SCHED_PRI_NRESV) / 2)
128228718Savg#define	PRI_BATCH_RANGE		(PRI_TIMESHARE_RANGE - PRI_INTERACT_RANGE)
129217410Sjhb
130217410Sjhb#define	PRI_MIN_INTERACT	PRI_MIN_TIMESHARE
131217410Sjhb#define	PRI_MAX_INTERACT	(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE - 1)
132217410Sjhb#define	PRI_MIN_BATCH		(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE)
133217351Sjhb#define	PRI_MAX_BATCH		PRI_MAX_TIMESHARE
134217351Sjhb
135217351Sjhb/*
136165762Sjeff * Cpu percentage computation macros and defines.
137111857Sjeff *
138165762Sjeff * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
139165762Sjeff * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
140165796Sjeff * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
141165762Sjeff * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
142165762Sjeff * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
143165762Sjeff * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
144165762Sjeff */
145165762Sjeff#define	SCHED_TICK_SECS		10
146165762Sjeff#define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
147165796Sjeff#define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
148165762Sjeff#define	SCHED_TICK_SHIFT	10
149165762Sjeff#define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
150165830Sjeff#define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
151165762Sjeff
152165762Sjeff/*
153165762Sjeff * These macros determine priorities for non-interactive threads.  They are
154165762Sjeff * assigned a priority based on their recent cpu utilization as expressed
155165762Sjeff * by the ratio of ticks to the tick total.  NHALF priorities at the start
156165762Sjeff * and end of the MIN to MAX timeshare range are only reachable with negative
157165762Sjeff * or positive nice respectively.
158165762Sjeff *
159165762Sjeff * PRI_RANGE:	Priority range for utilization dependent priorities.
160116642Sjeff * PRI_NRESV:	Number of nice values.
161165762Sjeff * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
162165762Sjeff * PRI_NICE:	Determines the part of the priority inherited from nice.
163109864Sjeff */
164165762Sjeff#define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
165121869Sjeff#define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
166217351Sjhb#define	SCHED_PRI_MIN		(PRI_MIN_BATCH + SCHED_PRI_NHALF)
167217351Sjhb#define	SCHED_PRI_MAX		(PRI_MAX_BATCH - SCHED_PRI_NHALF)
168217237Sjhb#define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN + 1)
169165762Sjeff#define	SCHED_PRI_TICKS(ts)						\
170165762Sjeff    (SCHED_TICK_HZ((ts)) /						\
171165827Sjeff    (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
172165762Sjeff#define	SCHED_PRI_NICE(nice)	(nice)
173109864Sjeff
174109864Sjeff/*
175165762Sjeff * These determine the interactivity of a process.  Interactivity differs from
176165762Sjeff * cpu utilization in that it expresses the voluntary time slept vs time ran
177165762Sjeff * while cpu utilization includes all time not running.  This more accurately
178165762Sjeff * models the intent of the thread.
179109864Sjeff *
180110645Sjeff * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
181110645Sjeff *		before throttling back.
182121868Sjeff * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
183116365Sjeff * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
184215102Sattilio * INTERACT_THRESH:	Threshold for placement on the current runq.
185109864Sjeff */
186165762Sjeff#define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
187165762Sjeff#define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
188116365Sjeff#define	SCHED_INTERACT_MAX	(100)
189116365Sjeff#define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
190121126Sjeff#define	SCHED_INTERACT_THRESH	(30)
191111857Sjeff
192239157Smav/* Flags kept in td_flags. */
193239157Smav#define	TDF_SLICEEND	TDF_SCHED2	/* Thread time slice is over. */
194239157Smav
195109864Sjeff/*
196165762Sjeff * tickincr:		Converts a stathz tick into a hz domain scaled by
197165762Sjeff *			the shift factor.  Without the shift the error rate
198165762Sjeff *			due to rounding would be unacceptably high.
199165762Sjeff * realstathz:		stathz is sometimes 0 and run off of hz.
200165762Sjeff * sched_slice:		Runtime of each thread before rescheduling.
201171482Sjeff * preempt_thresh:	Priority threshold for preemption and remote IPIs.
202109864Sjeff */
203165762Sjeffstatic int sched_interact = SCHED_INTERACT_THRESH;
204239185Smavstatic int realstathz = 127;
205241844Seadlerstatic int tickincr = 8 << SCHED_TICK_SHIFT;
206239185Smavstatic int sched_slice = 12;
207172345Sjeff#ifdef PREEMPTION
208172345Sjeff#ifdef FULL_PREEMPTION
209172345Sjeffstatic int preempt_thresh = PRI_MAX_IDLE;
210172345Sjeff#else
211171482Sjeffstatic int preempt_thresh = PRI_MIN_KERN;
212172345Sjeff#endif
213172345Sjeff#else
214172345Sjeffstatic int preempt_thresh = 0;
215172345Sjeff#endif
216217351Sjhbstatic int static_boost = PRI_MIN_BATCH;
217178277Sjeffstatic int sched_idlespins = 10000;
218232740Smavstatic int sched_idlespinthresh = -1;
219109864Sjeff
220109864Sjeff/*
221171482Sjeff * tdq - per processor runqs and statistics.  All fields are protected by the
222171482Sjeff * tdq_lock.  The load and lowpri may be accessed without to avoid excess
223171482Sjeff * locking in sched_pickcpu();
224109864Sjeff */
225164936Sjulianstruct tdq {
226242014Sjimharris	/*
227242014Sjimharris	 * Ordered to improve efficiency of cpu_search() and switch().
228242014Sjimharris	 * tdq_lock is padded to avoid false sharing with tdq_load and
229242014Sjimharris	 * tdq_cpu_idle.
230242014Sjimharris	 */
231242402Sattilio	struct mtx_padalign tdq_lock;		/* run queue lock. */
232176735Sjeff	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
233178277Sjeff	volatile int	tdq_load;		/* Aggregate load. */
234212416Smav	volatile int	tdq_cpu_idle;		/* cpu_idle() is active. */
235176735Sjeff	int		tdq_sysload;		/* For loadavg, !ITHD load. */
236177009Sjeff	int		tdq_transferable;	/* Transferable thread count. */
237178277Sjeff	short		tdq_switchcnt;		/* Switches this tick. */
238178277Sjeff	short		tdq_oldswitchcnt;	/* Switches last tick. */
239177009Sjeff	u_char		tdq_lowpri;		/* Lowest priority thread. */
240177009Sjeff	u_char		tdq_ipipending;		/* IPI pending. */
241166557Sjeff	u_char		tdq_idx;		/* Current insert index. */
242166557Sjeff	u_char		tdq_ridx;		/* Current removal index. */
243177009Sjeff	struct runq	tdq_realtime;		/* real-time run queue. */
244177009Sjeff	struct runq	tdq_timeshare;		/* timeshare run queue. */
245177009Sjeff	struct runq	tdq_idle;		/* Queue of IDLE threads. */
246187357Sjeff	char		tdq_name[TDQ_NAME_LEN];
247187357Sjeff#ifdef KTR
248187357Sjeff	char		tdq_loadname[TDQ_LOADNAME_LEN];
249187357Sjeff#endif
250171482Sjeff} __aligned(64);
251109864Sjeff
252178277Sjeff/* Idle thread states and config. */
253178277Sjeff#define	TDQ_RUNNING	1
254178277Sjeff#define	TDQ_IDLE	2
255166108Sjeff
256123433Sjeff#ifdef SMP
257184439Sivorasstruct cpu_group *cpu_top;		/* CPU topology */
258123433Sjeff
259176735Sjeff#define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
260176735Sjeff#define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
261166108Sjeff
262123433Sjeff/*
263166108Sjeff * Run-time tunables.
264166108Sjeff */
265171506Sjeffstatic int rebalance = 1;
266172409Sjeffstatic int balance_interval = 128;	/* Default set in sched_initticks(). */
267166108Sjeffstatic int affinity;
268171506Sjeffstatic int steal_idle = 1;
269171506Sjeffstatic int steal_thresh = 2;
270166108Sjeff
271166108Sjeff/*
272165620Sjeff * One thread queue per processor.
273109864Sjeff */
274164936Sjulianstatic struct tdq	tdq_cpu[MAXCPU];
275172409Sjeffstatic struct tdq	*balance_tdq;
276172409Sjeffstatic int balance_ticks;
277232207Smavstatic DPCPU_DEFINE(uint32_t, randomval);
278129982Sjeff
279164936Sjulian#define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
280164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu[(x)])
281171713Sjeff#define	TDQ_ID(x)	((int)((x) - tdq_cpu))
282123433Sjeff#else	/* !SMP */
283164936Sjulianstatic struct tdq	tdq_cpu;
284129982Sjeff
285170315Sjeff#define	TDQ_ID(x)	(0)
286164936Sjulian#define	TDQ_SELF()	(&tdq_cpu)
287164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu)
288110028Sjeff#endif
289109864Sjeff
290171482Sjeff#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
291171482Sjeff#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
292171482Sjeff#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
293171482Sjeff#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
294242402Sattilio#define	TDQ_LOCKPTR(t)		((struct mtx *)(&(t)->tdq_lock))
295171482Sjeff
296163709Sjbstatic void sched_priority(struct thread *);
297146954Sjeffstatic void sched_thread_priority(struct thread *, u_char);
298163709Sjbstatic int sched_interact_score(struct thread *);
299163709Sjbstatic void sched_interact_update(struct thread *);
300163709Sjbstatic void sched_interact_fork(struct thread *);
301232917Smavstatic void sched_pctcpu_update(struct td_sched *, int);
302109864Sjeff
303110267Sjeff/* Operations on per processor queues */
304177435Sjeffstatic struct thread *tdq_choose(struct tdq *);
305164936Sjulianstatic void tdq_setup(struct tdq *);
306177435Sjeffstatic void tdq_load_add(struct tdq *, struct thread *);
307177435Sjeffstatic void tdq_load_rem(struct tdq *, struct thread *);
308177435Sjeffstatic __inline void tdq_runq_add(struct tdq *, struct thread *, int);
309177435Sjeffstatic __inline void tdq_runq_rem(struct tdq *, struct thread *);
310177005Sjeffstatic inline int sched_shouldpreempt(int, int, int);
311164936Sjulianvoid tdq_print(int cpu);
312165762Sjeffstatic void runq_print(struct runq *rq);
313171482Sjeffstatic void tdq_add(struct tdq *, struct thread *, int);
314110267Sjeff#ifdef SMP
315176735Sjeffstatic int tdq_move(struct tdq *, struct tdq *);
316171482Sjeffstatic int tdq_idled(struct tdq *);
317177435Sjeffstatic void tdq_notify(struct tdq *, struct thread *);
318177435Sjeffstatic struct thread *tdq_steal(struct tdq *, int);
319177435Sjeffstatic struct thread *runq_steal(struct runq *, int);
320177435Sjeffstatic int sched_pickcpu(struct thread *, int);
321172409Sjeffstatic void sched_balance(void);
322176735Sjeffstatic int sched_balance_pair(struct tdq *, struct tdq *);
323177435Sjeffstatic inline struct tdq *sched_setcpu(struct thread *, int, int);
324171482Sjeffstatic inline void thread_unblock_switch(struct thread *, struct mtx *);
325171713Sjeffstatic struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
326184439Sivorasstatic int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
327184439Sivorasstatic int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
328184439Sivoras    struct cpu_group *cg, int indent);
329121790Sjeff#endif
330110028Sjeff
331165762Sjeffstatic void sched_setup(void *dummy);
332177253SrwatsonSYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
333165762Sjeff
334165762Sjeffstatic void sched_initticks(void *dummy);
335177253SrwatsonSYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
336177253Srwatson    NULL);
337165762Sjeff
338235459SrstoneSDT_PROVIDER_DEFINE(sched);
339235459Srstone
340235459SrstoneSDT_PROBE_DEFINE3(sched, , , change_pri, change-pri, "struct thread *",
341235459Srstone    "struct proc *", "uint8_t");
342235459SrstoneSDT_PROBE_DEFINE3(sched, , , dequeue, dequeue, "struct thread *",
343235459Srstone    "struct proc *", "void *");
344235459SrstoneSDT_PROBE_DEFINE4(sched, , , enqueue, enqueue, "struct thread *",
345235459Srstone    "struct proc *", "void *", "int");
346235459SrstoneSDT_PROBE_DEFINE4(sched, , , lend_pri, lend-pri, "struct thread *",
347235459Srstone    "struct proc *", "uint8_t", "struct thread *");
348235459SrstoneSDT_PROBE_DEFINE2(sched, , , load_change, load-change, "int", "int");
349235459SrstoneSDT_PROBE_DEFINE2(sched, , , off_cpu, off-cpu, "struct thread *",
350235459Srstone    "struct proc *");
351235459SrstoneSDT_PROBE_DEFINE(sched, , , on_cpu, on-cpu);
352235459SrstoneSDT_PROBE_DEFINE(sched, , , remain_cpu, remain-cpu);
353235459SrstoneSDT_PROBE_DEFINE2(sched, , , surrender, surrender, "struct thread *",
354235459Srstone    "struct proc *");
355235459Srstone
356171482Sjeff/*
357171482Sjeff * Print the threads waiting on a run-queue.
358171482Sjeff */
359165762Sjeffstatic void
360165762Sjeffrunq_print(struct runq *rq)
361165762Sjeff{
362165762Sjeff	struct rqhead *rqh;
363177435Sjeff	struct thread *td;
364165762Sjeff	int pri;
365165762Sjeff	int j;
366165762Sjeff	int i;
367165762Sjeff
368165762Sjeff	for (i = 0; i < RQB_LEN; i++) {
369165762Sjeff		printf("\t\trunq bits %d 0x%zx\n",
370165762Sjeff		    i, rq->rq_status.rqb_bits[i]);
371165762Sjeff		for (j = 0; j < RQB_BPW; j++)
372165762Sjeff			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
373165762Sjeff				pri = j + (i << RQB_L2BPW);
374165762Sjeff				rqh = &rq->rq_queues[pri];
375177435Sjeff				TAILQ_FOREACH(td, rqh, td_runq) {
376165762Sjeff					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
377177435Sjeff					    td, td->td_name, td->td_priority,
378177435Sjeff					    td->td_rqindex, pri);
379165762Sjeff				}
380165762Sjeff			}
381165762Sjeff	}
382165762Sjeff}
383165762Sjeff
384171482Sjeff/*
385171482Sjeff * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
386171482Sjeff */
387113357Sjeffvoid
388164936Sjuliantdq_print(int cpu)
389110267Sjeff{
390164936Sjulian	struct tdq *tdq;
391112994Sjeff
392164936Sjulian	tdq = TDQ_CPU(cpu);
393112994Sjeff
394171713Sjeff	printf("tdq %d:\n", TDQ_ID(tdq));
395176735Sjeff	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
396176735Sjeff	printf("\tLock name:      %s\n", tdq->tdq_name);
397165620Sjeff	printf("\tload:           %d\n", tdq->tdq_load);
398178277Sjeff	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
399178277Sjeff	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
400171482Sjeff	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
401165766Sjeff	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
402178277Sjeff	printf("\tload transferable: %d\n", tdq->tdq_transferable);
403178277Sjeff	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
404165762Sjeff	printf("\trealtime runq:\n");
405165762Sjeff	runq_print(&tdq->tdq_realtime);
406165762Sjeff	printf("\ttimeshare runq:\n");
407165762Sjeff	runq_print(&tdq->tdq_timeshare);
408165762Sjeff	printf("\tidle runq:\n");
409165762Sjeff	runq_print(&tdq->tdq_idle);
410113357Sjeff}
411112994Sjeff
412177005Sjeffstatic inline int
413177005Sjeffsched_shouldpreempt(int pri, int cpri, int remote)
414177005Sjeff{
415177005Sjeff	/*
416177005Sjeff	 * If the new priority is not better than the current priority there is
417177005Sjeff	 * nothing to do.
418177005Sjeff	 */
419177005Sjeff	if (pri >= cpri)
420177005Sjeff		return (0);
421177005Sjeff	/*
422177005Sjeff	 * Always preempt idle.
423177005Sjeff	 */
424177005Sjeff	if (cpri >= PRI_MIN_IDLE)
425177005Sjeff		return (1);
426177005Sjeff	/*
427177005Sjeff	 * If preemption is disabled don't preempt others.
428177005Sjeff	 */
429177005Sjeff	if (preempt_thresh == 0)
430177005Sjeff		return (0);
431177005Sjeff	/*
432177005Sjeff	 * Preempt if we exceed the threshold.
433177005Sjeff	 */
434177005Sjeff	if (pri <= preempt_thresh)
435177005Sjeff		return (1);
436177005Sjeff	/*
437217351Sjhb	 * If we're interactive or better and there is non-interactive
438217351Sjhb	 * or worse running preempt only remote processors.
439177005Sjeff	 */
440217351Sjhb	if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
441177005Sjeff		return (1);
442177005Sjeff	return (0);
443177005Sjeff}
444177005Sjeff
445171482Sjeff/*
446171482Sjeff * Add a thread to the actual run-queue.  Keeps transferable counts up to
447171482Sjeff * date with what is actually on the run-queue.  Selects the correct
448171482Sjeff * queue position for timeshare threads.
449171482Sjeff */
450122744Sjeffstatic __inline void
451177435Sjefftdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
452122744Sjeff{
453177435Sjeff	struct td_sched *ts;
454177042Sjeff	u_char pri;
455177042Sjeff
456171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
457177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
458177009Sjeff
459177435Sjeff	pri = td->td_priority;
460177435Sjeff	ts = td->td_sched;
461177435Sjeff	TD_SET_RUNQ(td);
462177435Sjeff	if (THREAD_CAN_MIGRATE(td)) {
463165620Sjeff		tdq->tdq_transferable++;
464164936Sjulian		ts->ts_flags |= TSF_XFERABLE;
465123433Sjeff	}
466217351Sjhb	if (pri < PRI_MIN_BATCH) {
467177042Sjeff		ts->ts_runq = &tdq->tdq_realtime;
468217351Sjhb	} else if (pri <= PRI_MAX_BATCH) {
469177042Sjeff		ts->ts_runq = &tdq->tdq_timeshare;
470217351Sjhb		KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
471165762Sjeff			("Invalid priority %d on timeshare runq", pri));
472165762Sjeff		/*
473165762Sjeff		 * This queue contains only priorities between MIN and MAX
474165762Sjeff		 * realtime.  Use the whole queue to represent these values.
475165762Sjeff		 */
476171713Sjeff		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
477228718Savg			pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
478165762Sjeff			pri = (pri + tdq->tdq_idx) % RQ_NQS;
479165766Sjeff			/*
480165766Sjeff			 * This effectively shortens the queue by one so we
481165766Sjeff			 * can have a one slot difference between idx and
482165766Sjeff			 * ridx while we wait for threads to drain.
483165766Sjeff			 */
484165766Sjeff			if (tdq->tdq_ridx != tdq->tdq_idx &&
485165766Sjeff			    pri == tdq->tdq_ridx)
486167664Sjeff				pri = (unsigned char)(pri - 1) % RQ_NQS;
487165762Sjeff		} else
488165766Sjeff			pri = tdq->tdq_ridx;
489177435Sjeff		runq_add_pri(ts->ts_runq, td, pri, flags);
490177042Sjeff		return;
491165762Sjeff	} else
492177009Sjeff		ts->ts_runq = &tdq->tdq_idle;
493177435Sjeff	runq_add(ts->ts_runq, td, flags);
494177009Sjeff}
495177009Sjeff
496171482Sjeff/*
497171482Sjeff * Remove a thread from a run-queue.  This typically happens when a thread
498171482Sjeff * is selected to run.  Running threads are not on the queue and the
499171482Sjeff * transferable count does not reflect them.
500171482Sjeff */
501122744Sjeffstatic __inline void
502177435Sjefftdq_runq_rem(struct tdq *tdq, struct thread *td)
503122744Sjeff{
504177435Sjeff	struct td_sched *ts;
505177435Sjeff
506177435Sjeff	ts = td->td_sched;
507171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
508171482Sjeff	KASSERT(ts->ts_runq != NULL,
509177435Sjeff	    ("tdq_runq_remove: thread %p null ts_runq", td));
510164936Sjulian	if (ts->ts_flags & TSF_XFERABLE) {
511165620Sjeff		tdq->tdq_transferable--;
512164936Sjulian		ts->ts_flags &= ~TSF_XFERABLE;
513123433Sjeff	}
514165766Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
515165766Sjeff		if (tdq->tdq_idx != tdq->tdq_ridx)
516177435Sjeff			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
517165766Sjeff		else
518177435Sjeff			runq_remove_idx(ts->ts_runq, td, NULL);
519165766Sjeff	} else
520177435Sjeff		runq_remove(ts->ts_runq, td);
521122744Sjeff}
522122744Sjeff
523171482Sjeff/*
524171482Sjeff * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
525171482Sjeff * for this thread to the referenced thread queue.
526171482Sjeff */
527113357Sjeffstatic void
528177435Sjefftdq_load_add(struct tdq *tdq, struct thread *td)
529113357Sjeff{
530171482Sjeff
531171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
532177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
533177902Sjeff
534165620Sjeff	tdq->tdq_load++;
535198854Sattilio	if ((td->td_flags & TDF_NOLOAD) == 0)
536177902Sjeff		tdq->tdq_sysload++;
537187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
538235459Srstone	SDT_PROBE2(sched, , , load_change, (int)TDQ_ID(tdq), tdq->tdq_load);
539110267Sjeff}
540113357Sjeff
541171482Sjeff/*
542171482Sjeff * Remove the load from a thread that is transitioning to a sleep state or
543171482Sjeff * exiting.
544171482Sjeff */
545112994Sjeffstatic void
546177435Sjefftdq_load_rem(struct tdq *tdq, struct thread *td)
547110267Sjeff{
548171482Sjeff
549177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
550171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
551171482Sjeff	KASSERT(tdq->tdq_load != 0,
552171713Sjeff	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
553177902Sjeff
554165620Sjeff	tdq->tdq_load--;
555198854Sattilio	if ((td->td_flags & TDF_NOLOAD) == 0)
556177902Sjeff		tdq->tdq_sysload--;
557187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
558235459Srstone	SDT_PROBE2(sched, , , load_change, (int)TDQ_ID(tdq), tdq->tdq_load);
559110267Sjeff}
560110267Sjeff
561176735Sjeff/*
562176735Sjeff * Set lowpri to its exact value by searching the run-queue and
563176735Sjeff * evaluating curthread.  curthread may be passed as an optimization.
564176735Sjeff */
565176735Sjeffstatic void
566176735Sjefftdq_setlowpri(struct tdq *tdq, struct thread *ctd)
567176735Sjeff{
568176735Sjeff	struct thread *td;
569176735Sjeff
570176735Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
571176735Sjeff	if (ctd == NULL)
572176735Sjeff		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
573177435Sjeff	td = tdq_choose(tdq);
574177435Sjeff	if (td == NULL || td->td_priority > ctd->td_priority)
575176735Sjeff		tdq->tdq_lowpri = ctd->td_priority;
576176735Sjeff	else
577176735Sjeff		tdq->tdq_lowpri = td->td_priority;
578176735Sjeff}
579176735Sjeff
580113357Sjeff#ifdef SMP
581176735Sjeffstruct cpu_search {
582194779Sjeff	cpuset_t cs_mask;
583232207Smav	u_int	cs_prefer;
584232207Smav	int	cs_pri;		/* Min priority for low. */
585232207Smav	int	cs_limit;	/* Max load for low, min load for high. */
586232207Smav	int	cs_cpu;
587232207Smav	int	cs_load;
588176735Sjeff};
589176735Sjeff
590176735Sjeff#define	CPU_SEARCH_LOWEST	0x1
591176735Sjeff#define	CPU_SEARCH_HIGHEST	0x2
592176735Sjeff#define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
593176735Sjeff
594194779Sjeff#define	CPUSET_FOREACH(cpu, mask)				\
595194779Sjeff	for ((cpu) = 0; (cpu) <= mp_maxid; (cpu)++)		\
596222813Sattilio		if (CPU_ISSET(cpu, &mask))
597176735Sjeff
598232207Smavstatic __inline int cpu_search(const struct cpu_group *cg, struct cpu_search *low,
599176735Sjeff    struct cpu_search *high, const int match);
600232207Smavint cpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low);
601232207Smavint cpu_search_highest(const struct cpu_group *cg, struct cpu_search *high);
602232207Smavint cpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
603176735Sjeff    struct cpu_search *high);
604176735Sjeff
605116069Sjeff/*
606176735Sjeff * Search the tree of cpu_groups for the lowest or highest loaded cpu
607176735Sjeff * according to the match argument.  This routine actually compares the
608176735Sjeff * load on all paths through the tree and finds the least loaded cpu on
609176735Sjeff * the least loaded path, which may differ from the least loaded cpu in
610176735Sjeff * the system.  This balances work among caches and busses.
611116069Sjeff *
612176735Sjeff * This inline is instantiated in three forms below using constants for the
613176735Sjeff * match argument.  It is reduced to the minimum set for each case.  It is
614176735Sjeff * also recursive to the depth of the tree.
615116069Sjeff */
616177169Sjhbstatic __inline int
617232207Smavcpu_search(const struct cpu_group *cg, struct cpu_search *low,
618176735Sjeff    struct cpu_search *high, const int match)
619176735Sjeff{
620232207Smav	struct cpu_search lgroup;
621232207Smav	struct cpu_search hgroup;
622232207Smav	cpuset_t cpumask;
623232207Smav	struct cpu_group *child;
624232207Smav	struct tdq *tdq;
625234066Smav	int cpu, i, hload, lload, load, total, rnd, *rndptr;
626176735Sjeff
627176735Sjeff	total = 0;
628232207Smav	cpumask = cg->cg_mask;
629232207Smav	if (match & CPU_SEARCH_LOWEST) {
630232207Smav		lload = INT_MAX;
631232207Smav		lgroup = *low;
632232207Smav	}
633232207Smav	if (match & CPU_SEARCH_HIGHEST) {
634234066Smav		hload = INT_MIN;
635232207Smav		hgroup = *high;
636232207Smav	}
637176735Sjeff
638232207Smav	/* Iterate through the child CPU groups and then remaining CPUs. */
639234066Smav	for (i = cg->cg_children, cpu = mp_maxid; i >= 0; ) {
640234066Smav		if (i == 0) {
641234066Smav			while (cpu >= 0 && !CPU_ISSET(cpu, &cpumask))
642234066Smav				cpu--;
643234066Smav			if (cpu < 0)
644232207Smav				break;
645232207Smav			child = NULL;
646232207Smav		} else
647234066Smav			child = &cg->cg_child[i - 1];
648232207Smav
649234066Smav		if (match & CPU_SEARCH_LOWEST)
650234066Smav			lgroup.cs_cpu = -1;
651234066Smav		if (match & CPU_SEARCH_HIGHEST)
652234066Smav			hgroup.cs_cpu = -1;
653232207Smav		if (child) {			/* Handle child CPU group. */
654232207Smav			CPU_NAND(&cpumask, &child->cg_mask);
655176735Sjeff			switch (match) {
656176735Sjeff			case CPU_SEARCH_LOWEST:
657176735Sjeff				load = cpu_search_lowest(child, &lgroup);
658176735Sjeff				break;
659176735Sjeff			case CPU_SEARCH_HIGHEST:
660176735Sjeff				load = cpu_search_highest(child, &hgroup);
661176735Sjeff				break;
662176735Sjeff			case CPU_SEARCH_BOTH:
663176735Sjeff				load = cpu_search_both(child, &lgroup, &hgroup);
664176735Sjeff				break;
665176735Sjeff			}
666232207Smav		} else {			/* Handle child CPU. */
667232207Smav			tdq = TDQ_CPU(cpu);
668232207Smav			load = tdq->tdq_load * 256;
669234066Smav			rndptr = DPCPU_PTR(randomval);
670234066Smav			rnd = (*rndptr = *rndptr * 69069 + 5) >> 26;
671232207Smav			if (match & CPU_SEARCH_LOWEST) {
672232207Smav				if (cpu == low->cs_prefer)
673232207Smav					load -= 64;
674232207Smav				/* If that CPU is allowed and get data. */
675234066Smav				if (tdq->tdq_lowpri > lgroup.cs_pri &&
676234066Smav				    tdq->tdq_load <= lgroup.cs_limit &&
677234066Smav				    CPU_ISSET(cpu, &lgroup.cs_mask)) {
678232207Smav					lgroup.cs_cpu = cpu;
679232207Smav					lgroup.cs_load = load - rnd;
680176735Sjeff				}
681232207Smav			}
682232207Smav			if (match & CPU_SEARCH_HIGHEST)
683234066Smav				if (tdq->tdq_load >= hgroup.cs_limit &&
684234066Smav				    tdq->tdq_transferable &&
685234066Smav				    CPU_ISSET(cpu, &hgroup.cs_mask)) {
686232207Smav					hgroup.cs_cpu = cpu;
687232207Smav					hgroup.cs_load = load - rnd;
688176735Sjeff				}
689176735Sjeff		}
690232207Smav		total += load;
691176735Sjeff
692232207Smav		/* We have info about child item. Compare it. */
693232207Smav		if (match & CPU_SEARCH_LOWEST) {
694234066Smav			if (lgroup.cs_cpu >= 0 &&
695232454Smav			    (load < lload ||
696232454Smav			     (load == lload && lgroup.cs_load < low->cs_load))) {
697232207Smav				lload = load;
698232207Smav				low->cs_cpu = lgroup.cs_cpu;
699232207Smav				low->cs_load = lgroup.cs_load;
700232207Smav			}
701232207Smav		}
702232207Smav		if (match & CPU_SEARCH_HIGHEST)
703234066Smav			if (hgroup.cs_cpu >= 0 &&
704232454Smav			    (load > hload ||
705232454Smav			     (load == hload && hgroup.cs_load > high->cs_load))) {
706232207Smav				hload = load;
707232207Smav				high->cs_cpu = hgroup.cs_cpu;
708232207Smav				high->cs_load = hgroup.cs_load;
709232207Smav			}
710234066Smav		if (child) {
711234066Smav			i--;
712234066Smav			if (i == 0 && CPU_EMPTY(&cpumask))
713234066Smav				break;
714234066Smav		} else
715234066Smav			cpu--;
716176735Sjeff	}
717176735Sjeff	return (total);
718176735Sjeff}
719176735Sjeff
720176735Sjeff/*
721176735Sjeff * cpu_search instantiations must pass constants to maintain the inline
722176735Sjeff * optimization.
723176735Sjeff */
724176735Sjeffint
725232207Smavcpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low)
726176735Sjeff{
727176735Sjeff	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
728176735Sjeff}
729176735Sjeff
730176735Sjeffint
731232207Smavcpu_search_highest(const struct cpu_group *cg, struct cpu_search *high)
732176735Sjeff{
733176735Sjeff	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
734176735Sjeff}
735176735Sjeff
736176735Sjeffint
737232207Smavcpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
738176735Sjeff    struct cpu_search *high)
739176735Sjeff{
740176735Sjeff	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
741176735Sjeff}
742176735Sjeff
743176735Sjeff/*
744176735Sjeff * Find the cpu with the least load via the least loaded path that has a
745176735Sjeff * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
746176735Sjeff * acceptable.
747176735Sjeff */
748176735Sjeffstatic inline int
749232207Smavsched_lowest(const struct cpu_group *cg, cpuset_t mask, int pri, int maxload,
750232207Smav    int prefer)
751176735Sjeff{
752176735Sjeff	struct cpu_search low;
753176735Sjeff
754176735Sjeff	low.cs_cpu = -1;
755232207Smav	low.cs_prefer = prefer;
756176735Sjeff	low.cs_mask = mask;
757232207Smav	low.cs_pri = pri;
758232207Smav	low.cs_limit = maxload;
759176735Sjeff	cpu_search_lowest(cg, &low);
760176735Sjeff	return low.cs_cpu;
761176735Sjeff}
762176735Sjeff
763176735Sjeff/*
764176735Sjeff * Find the cpu with the highest load via the highest loaded path.
765176735Sjeff */
766176735Sjeffstatic inline int
767232207Smavsched_highest(const struct cpu_group *cg, cpuset_t mask, int minload)
768176735Sjeff{
769176735Sjeff	struct cpu_search high;
770176735Sjeff
771176735Sjeff	high.cs_cpu = -1;
772176735Sjeff	high.cs_mask = mask;
773176735Sjeff	high.cs_limit = minload;
774176735Sjeff	cpu_search_highest(cg, &high);
775176735Sjeff	return high.cs_cpu;
776176735Sjeff}
777176735Sjeff
778176735Sjeff/*
779176735Sjeff * Simultaneously find the highest and lowest loaded cpu reachable via
780176735Sjeff * cg.
781176735Sjeff */
782232207Smavstatic inline void
783232207Smavsched_both(const struct cpu_group *cg, cpuset_t mask, int *lowcpu, int *highcpu)
784176735Sjeff{
785176735Sjeff	struct cpu_search high;
786176735Sjeff	struct cpu_search low;
787176735Sjeff
788176735Sjeff	low.cs_cpu = -1;
789232207Smav	low.cs_prefer = -1;
790232207Smav	low.cs_pri = -1;
791232207Smav	low.cs_limit = INT_MAX;
792176735Sjeff	low.cs_mask = mask;
793176735Sjeff	high.cs_cpu = -1;
794176735Sjeff	high.cs_limit = -1;
795176735Sjeff	high.cs_mask = mask;
796176735Sjeff	cpu_search_both(cg, &low, &high);
797176735Sjeff	*lowcpu = low.cs_cpu;
798176735Sjeff	*highcpu = high.cs_cpu;
799176735Sjeff	return;
800176735Sjeff}
801176735Sjeff
802121790Sjeffstatic void
803176735Sjeffsched_balance_group(struct cpu_group *cg)
804116069Sjeff{
805232207Smav	cpuset_t hmask, lmask;
806232207Smav	int high, low, anylow;
807123487Sjeff
808232207Smav	CPU_FILL(&hmask);
809176735Sjeff	for (;;) {
810232207Smav		high = sched_highest(cg, hmask, 1);
811232207Smav		/* Stop if there is no more CPU with transferrable threads. */
812232207Smav		if (high == -1)
813176735Sjeff			break;
814232207Smav		CPU_CLR(high, &hmask);
815232207Smav		CPU_COPY(&hmask, &lmask);
816232207Smav		/* Stop if there is no more CPU left for low. */
817232207Smav		if (CPU_EMPTY(&lmask))
818176735Sjeff			break;
819232207Smav		anylow = 1;
820232207Smavnextlow:
821232207Smav		low = sched_lowest(cg, lmask, -1,
822232207Smav		    TDQ_CPU(high)->tdq_load - 1, high);
823232207Smav		/* Stop if we looked well and found no less loaded CPU. */
824232207Smav		if (anylow && low == -1)
825232207Smav			break;
826232207Smav		/* Go to next high if we found no less loaded CPU. */
827232207Smav		if (low == -1)
828232207Smav			continue;
829232207Smav		/* Transfer thread from high to low. */
830232207Smav		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low))) {
831232207Smav			/* CPU that got thread can no longer be a donor. */
832232207Smav			CPU_CLR(low, &hmask);
833232207Smav		} else {
834232207Smav			/*
835232207Smav			 * If failed, then there is no threads on high
836232207Smav			 * that can run on this low. Drop low from low
837232207Smav			 * mask and look for different one.
838232207Smav			 */
839232207Smav			CPU_CLR(low, &lmask);
840232207Smav			anylow = 0;
841232207Smav			goto nextlow;
842232207Smav		}
843123487Sjeff	}
844123487Sjeff}
845123487Sjeff
846123487Sjeffstatic void
847201148Sedsched_balance(void)
848123487Sjeff{
849172409Sjeff	struct tdq *tdq;
850123487Sjeff
851172409Sjeff	/*
852172409Sjeff	 * Select a random time between .5 * balance_interval and
853172409Sjeff	 * 1.5 * balance_interval.
854172409Sjeff	 */
855176735Sjeff	balance_ticks = max(balance_interval / 2, 1);
856176735Sjeff	balance_ticks += random() % balance_interval;
857171482Sjeff	if (smp_started == 0 || rebalance == 0)
858171482Sjeff		return;
859172409Sjeff	tdq = TDQ_SELF();
860172409Sjeff	TDQ_UNLOCK(tdq);
861176735Sjeff	sched_balance_group(cpu_top);
862172409Sjeff	TDQ_LOCK(tdq);
863123487Sjeff}
864123487Sjeff
865171482Sjeff/*
866171482Sjeff * Lock two thread queues using their address to maintain lock order.
867171482Sjeff */
868123487Sjeffstatic void
869171482Sjefftdq_lock_pair(struct tdq *one, struct tdq *two)
870171482Sjeff{
871171482Sjeff	if (one < two) {
872171482Sjeff		TDQ_LOCK(one);
873171482Sjeff		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
874171482Sjeff	} else {
875171482Sjeff		TDQ_LOCK(two);
876171482Sjeff		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
877171482Sjeff	}
878171482Sjeff}
879171482Sjeff
880171482Sjeff/*
881172409Sjeff * Unlock two thread queues.  Order is not important here.
882172409Sjeff */
883172409Sjeffstatic void
884172409Sjefftdq_unlock_pair(struct tdq *one, struct tdq *two)
885172409Sjeff{
886172409Sjeff	TDQ_UNLOCK(one);
887172409Sjeff	TDQ_UNLOCK(two);
888172409Sjeff}
889172409Sjeff
890172409Sjeff/*
891171482Sjeff * Transfer load between two imbalanced thread queues.
892171482Sjeff */
893176735Sjeffstatic int
894164936Sjuliansched_balance_pair(struct tdq *high, struct tdq *low)
895123487Sjeff{
896176735Sjeff	int moved;
897226057Smarius	int cpu;
898116069Sjeff
899171482Sjeff	tdq_lock_pair(high, low);
900176735Sjeff	moved = 0;
901116069Sjeff	/*
902122744Sjeff	 * Determine what the imbalance is and then adjust that to how many
903165620Sjeff	 * threads we actually have to give up (transferable).
904122744Sjeff	 */
905232207Smav	if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load &&
906232207Smav	    (moved = tdq_move(high, low)) > 0) {
907172293Sjeff		/*
908226057Smarius		 * In case the target isn't the current cpu IPI it to force a
909226057Smarius		 * reschedule with the new workload.
910172293Sjeff		 */
911226057Smarius		cpu = TDQ_ID(low);
912226057Smarius		if (cpu != PCPU_GET(cpuid))
913226057Smarius			ipi_cpu(cpu, IPI_PREEMPT);
914171482Sjeff	}
915172409Sjeff	tdq_unlock_pair(high, low);
916176735Sjeff	return (moved);
917116069Sjeff}
918116069Sjeff
919171482Sjeff/*
920171482Sjeff * Move a thread from one thread queue to another.
921171482Sjeff */
922176735Sjeffstatic int
923171482Sjefftdq_move(struct tdq *from, struct tdq *to)
924116069Sjeff{
925171482Sjeff	struct td_sched *ts;
926171482Sjeff	struct thread *td;
927164936Sjulian	struct tdq *tdq;
928171482Sjeff	int cpu;
929116069Sjeff
930172409Sjeff	TDQ_LOCK_ASSERT(from, MA_OWNED);
931172409Sjeff	TDQ_LOCK_ASSERT(to, MA_OWNED);
932172409Sjeff
933164936Sjulian	tdq = from;
934171482Sjeff	cpu = TDQ_ID(to);
935177435Sjeff	td = tdq_steal(tdq, cpu);
936177435Sjeff	if (td == NULL)
937176735Sjeff		return (0);
938177435Sjeff	ts = td->td_sched;
939171482Sjeff	/*
940171482Sjeff	 * Although the run queue is locked the thread may be blocked.  Lock
941172409Sjeff	 * it to clear this and acquire the run-queue lock.
942171482Sjeff	 */
943171482Sjeff	thread_lock(td);
944172409Sjeff	/* Drop recursive lock on from acquired via thread_lock(). */
945171482Sjeff	TDQ_UNLOCK(from);
946171482Sjeff	sched_rem(td);
947166108Sjeff	ts->ts_cpu = cpu;
948171482Sjeff	td->td_lock = TDQ_LOCKPTR(to);
949171482Sjeff	tdq_add(to, td, SRQ_YIELDING);
950176735Sjeff	return (1);
951116069Sjeff}
952110267Sjeff
953171482Sjeff/*
954171482Sjeff * This tdq has idled.  Try to steal a thread from another cpu and switch
955171482Sjeff * to it.
956171482Sjeff */
957123433Sjeffstatic int
958164936Sjuliantdq_idled(struct tdq *tdq)
959121790Sjeff{
960176735Sjeff	struct cpu_group *cg;
961164936Sjulian	struct tdq *steal;
962194779Sjeff	cpuset_t mask;
963176735Sjeff	int thresh;
964171482Sjeff	int cpu;
965123433Sjeff
966172484Sjeff	if (smp_started == 0 || steal_idle == 0)
967172484Sjeff		return (1);
968194779Sjeff	CPU_FILL(&mask);
969194779Sjeff	CPU_CLR(PCPU_GET(cpuid), &mask);
970176735Sjeff	/* We don't want to be preempted while we're iterating. */
971171482Sjeff	spinlock_enter();
972176735Sjeff	for (cg = tdq->tdq_cg; cg != NULL; ) {
973191643Sjeff		if ((cg->cg_flags & CG_FLAG_THREAD) == 0)
974176735Sjeff			thresh = steal_thresh;
975176735Sjeff		else
976176735Sjeff			thresh = 1;
977176735Sjeff		cpu = sched_highest(cg, mask, thresh);
978176735Sjeff		if (cpu == -1) {
979176735Sjeff			cg = cg->cg_parent;
980176735Sjeff			continue;
981166108Sjeff		}
982176735Sjeff		steal = TDQ_CPU(cpu);
983194779Sjeff		CPU_CLR(cpu, &mask);
984176735Sjeff		tdq_lock_pair(tdq, steal);
985176735Sjeff		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
986176735Sjeff			tdq_unlock_pair(tdq, steal);
987176735Sjeff			continue;
988171482Sjeff		}
989176735Sjeff		/*
990176735Sjeff		 * If a thread was added while interrupts were disabled don't
991176735Sjeff		 * steal one here.  If we fail to acquire one due to affinity
992176735Sjeff		 * restrictions loop again with this cpu removed from the
993176735Sjeff		 * set.
994176735Sjeff		 */
995176735Sjeff		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
996176735Sjeff			tdq_unlock_pair(tdq, steal);
997176735Sjeff			continue;
998176735Sjeff		}
999176735Sjeff		spinlock_exit();
1000176735Sjeff		TDQ_UNLOCK(steal);
1001178272Sjeff		mi_switch(SW_VOL | SWT_IDLE, NULL);
1002176735Sjeff		thread_unlock(curthread);
1003176735Sjeff
1004176735Sjeff		return (0);
1005123433Sjeff	}
1006171482Sjeff	spinlock_exit();
1007123433Sjeff	return (1);
1008121790Sjeff}
1009121790Sjeff
1010171482Sjeff/*
1011171482Sjeff * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
1012171482Sjeff */
1013121790Sjeffstatic void
1014177435Sjefftdq_notify(struct tdq *tdq, struct thread *td)
1015121790Sjeff{
1016185047Sjhb	struct thread *ctd;
1017166247Sjeff	int pri;
1018166108Sjeff	int cpu;
1019121790Sjeff
1020177005Sjeff	if (tdq->tdq_ipipending)
1021177005Sjeff		return;
1022177435Sjeff	cpu = td->td_sched->ts_cpu;
1023177435Sjeff	pri = td->td_priority;
1024185047Sjhb	ctd = pcpu_find(cpu)->pc_curthread;
1025185047Sjhb	if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
1026166137Sjeff		return;
1027185047Sjhb	if (TD_IS_IDLETHREAD(ctd)) {
1028178277Sjeff		/*
1029178471Sjeff		 * If the MD code has an idle wakeup routine try that before
1030178471Sjeff		 * falling back to IPI.
1031178471Sjeff		 */
1032212416Smav		if (!tdq->tdq_cpu_idle || cpu_idle_wakeup(cpu))
1033178471Sjeff			return;
1034178277Sjeff	}
1035177005Sjeff	tdq->tdq_ipipending = 1;
1036210939Sjhb	ipi_cpu(cpu, IPI_PREEMPT);
1037121790Sjeff}
1038121790Sjeff
1039171482Sjeff/*
1040171482Sjeff * Steals load from a timeshare queue.  Honors the rotating queue head
1041171482Sjeff * index.
1042171482Sjeff */
1043177435Sjeffstatic struct thread *
1044176735Sjeffrunq_steal_from(struct runq *rq, int cpu, u_char start)
1045171482Sjeff{
1046171482Sjeff	struct rqbits *rqb;
1047171482Sjeff	struct rqhead *rqh;
1048232207Smav	struct thread *td, *first;
1049171482Sjeff	int bit;
1050171482Sjeff	int pri;
1051171482Sjeff	int i;
1052171482Sjeff
1053171482Sjeff	rqb = &rq->rq_status;
1054171482Sjeff	bit = start & (RQB_BPW -1);
1055171482Sjeff	pri = 0;
1056232207Smav	first = NULL;
1057171482Sjeffagain:
1058171482Sjeff	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1059171482Sjeff		if (rqb->rqb_bits[i] == 0)
1060171482Sjeff			continue;
1061171482Sjeff		if (bit != 0) {
1062171482Sjeff			for (pri = bit; pri < RQB_BPW; pri++)
1063171482Sjeff				if (rqb->rqb_bits[i] & (1ul << pri))
1064171482Sjeff					break;
1065171482Sjeff			if (pri >= RQB_BPW)
1066171482Sjeff				continue;
1067171482Sjeff		} else
1068171482Sjeff			pri = RQB_FFS(rqb->rqb_bits[i]);
1069171482Sjeff		pri += (i << RQB_L2BPW);
1070171482Sjeff		rqh = &rq->rq_queues[pri];
1071177435Sjeff		TAILQ_FOREACH(td, rqh, td_runq) {
1072177435Sjeff			if (first && THREAD_CAN_MIGRATE(td) &&
1073177435Sjeff			    THREAD_CAN_SCHED(td, cpu))
1074177435Sjeff				return (td);
1075232207Smav			first = td;
1076171482Sjeff		}
1077171482Sjeff	}
1078171482Sjeff	if (start != 0) {
1079171482Sjeff		start = 0;
1080171482Sjeff		goto again;
1081171482Sjeff	}
1082171482Sjeff
1083232207Smav	if (first && THREAD_CAN_MIGRATE(first) &&
1084232207Smav	    THREAD_CAN_SCHED(first, cpu))
1085232207Smav		return (first);
1086171482Sjeff	return (NULL);
1087171482Sjeff}
1088171482Sjeff
1089171482Sjeff/*
1090171482Sjeff * Steals load from a standard linear queue.
1091171482Sjeff */
1092177435Sjeffstatic struct thread *
1093176735Sjeffrunq_steal(struct runq *rq, int cpu)
1094121790Sjeff{
1095121790Sjeff	struct rqhead *rqh;
1096121790Sjeff	struct rqbits *rqb;
1097177435Sjeff	struct thread *td;
1098121790Sjeff	int word;
1099121790Sjeff	int bit;
1100121790Sjeff
1101121790Sjeff	rqb = &rq->rq_status;
1102121790Sjeff	for (word = 0; word < RQB_LEN; word++) {
1103121790Sjeff		if (rqb->rqb_bits[word] == 0)
1104121790Sjeff			continue;
1105121790Sjeff		for (bit = 0; bit < RQB_BPW; bit++) {
1106123231Speter			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
1107121790Sjeff				continue;
1108121790Sjeff			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
1109177435Sjeff			TAILQ_FOREACH(td, rqh, td_runq)
1110177435Sjeff				if (THREAD_CAN_MIGRATE(td) &&
1111177435Sjeff				    THREAD_CAN_SCHED(td, cpu))
1112177435Sjeff					return (td);
1113121790Sjeff		}
1114121790Sjeff	}
1115121790Sjeff	return (NULL);
1116121790Sjeff}
1117121790Sjeff
1118171482Sjeff/*
1119171482Sjeff * Attempt to steal a thread in priority order from a thread queue.
1120171482Sjeff */
1121177435Sjeffstatic struct thread *
1122176735Sjefftdq_steal(struct tdq *tdq, int cpu)
1123121790Sjeff{
1124177435Sjeff	struct thread *td;
1125121790Sjeff
1126171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1127177435Sjeff	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
1128177435Sjeff		return (td);
1129177435Sjeff	if ((td = runq_steal_from(&tdq->tdq_timeshare,
1130177435Sjeff	    cpu, tdq->tdq_ridx)) != NULL)
1131177435Sjeff		return (td);
1132176735Sjeff	return (runq_steal(&tdq->tdq_idle, cpu));
1133121790Sjeff}
1134123433Sjeff
1135171482Sjeff/*
1136171482Sjeff * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
1137172409Sjeff * current lock and returns with the assigned queue locked.
1138171482Sjeff */
1139171482Sjeffstatic inline struct tdq *
1140177435Sjeffsched_setcpu(struct thread *td, int cpu, int flags)
1141123433Sjeff{
1142177435Sjeff
1143171482Sjeff	struct tdq *tdq;
1144123433Sjeff
1145177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1146171482Sjeff	tdq = TDQ_CPU(cpu);
1147177435Sjeff	td->td_sched->ts_cpu = cpu;
1148177435Sjeff	/*
1149177435Sjeff	 * If the lock matches just return the queue.
1150177435Sjeff	 */
1151171482Sjeff	if (td->td_lock == TDQ_LOCKPTR(tdq))
1152171482Sjeff		return (tdq);
1153171482Sjeff#ifdef notyet
1154123433Sjeff	/*
1155172293Sjeff	 * If the thread isn't running its lockptr is a
1156171482Sjeff	 * turnstile or a sleepqueue.  We can just lock_set without
1157171482Sjeff	 * blocking.
1158123685Sjeff	 */
1159171482Sjeff	if (TD_CAN_RUN(td)) {
1160171482Sjeff		TDQ_LOCK(tdq);
1161171482Sjeff		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1162171482Sjeff		return (tdq);
1163171482Sjeff	}
1164171482Sjeff#endif
1165166108Sjeff	/*
1166171482Sjeff	 * The hard case, migration, we need to block the thread first to
1167171482Sjeff	 * prevent order reversals with other cpus locks.
1168166108Sjeff	 */
1169202889Sattilio	spinlock_enter();
1170171482Sjeff	thread_lock_block(td);
1171171482Sjeff	TDQ_LOCK(tdq);
1172171713Sjeff	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1173202889Sattilio	spinlock_exit();
1174171482Sjeff	return (tdq);
1175166108Sjeff}
1176166108Sjeff
1177178272SjeffSCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
1178178272SjeffSCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
1179178272SjeffSCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
1180178272SjeffSCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
1181178272SjeffSCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
1182178272SjeffSCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
1183178272Sjeff
1184166108Sjeffstatic int
1185177435Sjeffsched_pickcpu(struct thread *td, int flags)
1186171482Sjeff{
1187232207Smav	struct cpu_group *cg, *ccg;
1188177435Sjeff	struct td_sched *ts;
1189171482Sjeff	struct tdq *tdq;
1190194779Sjeff	cpuset_t mask;
1191232207Smav	int cpu, pri, self;
1192166108Sjeff
1193176735Sjeff	self = PCPU_GET(cpuid);
1194177435Sjeff	ts = td->td_sched;
1195166108Sjeff	if (smp_started == 0)
1196166108Sjeff		return (self);
1197171506Sjeff	/*
1198171506Sjeff	 * Don't migrate a running thread from sched_switch().
1199171506Sjeff	 */
1200176735Sjeff	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1201176735Sjeff		return (ts->ts_cpu);
1202166108Sjeff	/*
1203176735Sjeff	 * Prefer to run interrupt threads on the processors that generate
1204176735Sjeff	 * the interrupt.
1205166108Sjeff	 */
1206232207Smav	pri = td->td_priority;
1207176735Sjeff	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1208178272Sjeff	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
1209178272Sjeff		SCHED_STAT_INC(pickcpu_intrbind);
1210176735Sjeff		ts->ts_cpu = self;
1211232207Smav		if (TDQ_CPU(self)->tdq_lowpri > pri) {
1212232207Smav			SCHED_STAT_INC(pickcpu_affinity);
1213232207Smav			return (ts->ts_cpu);
1214232207Smav		}
1215178272Sjeff	}
1216166108Sjeff	/*
1217176735Sjeff	 * If the thread can run on the last cpu and the affinity has not
1218176735Sjeff	 * expired or it is idle run it there.
1219166108Sjeff	 */
1220176735Sjeff	tdq = TDQ_CPU(ts->ts_cpu);
1221232207Smav	cg = tdq->tdq_cg;
1222232207Smav	if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
1223232207Smav	    tdq->tdq_lowpri >= PRI_MIN_IDLE &&
1224232207Smav	    SCHED_AFFINITY(ts, CG_SHARE_L2)) {
1225232207Smav		if (cg->cg_flags & CG_FLAG_THREAD) {
1226232207Smav			CPUSET_FOREACH(cpu, cg->cg_mask) {
1227232207Smav				if (TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE)
1228232207Smav					break;
1229232207Smav			}
1230232207Smav		} else
1231232207Smav			cpu = INT_MAX;
1232232207Smav		if (cpu > mp_maxid) {
1233178272Sjeff			SCHED_STAT_INC(pickcpu_idle_affinity);
1234176735Sjeff			return (ts->ts_cpu);
1235178272Sjeff		}
1236139334Sjeff	}
1237123433Sjeff	/*
1238232207Smav	 * Search for the last level cache CPU group in the tree.
1239232207Smav	 * Skip caches with expired affinity time and SMT groups.
1240232207Smav	 * Affinity to higher level caches will be handled less aggressively.
1241123433Sjeff	 */
1242232207Smav	for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
1243232207Smav		if (cg->cg_flags & CG_FLAG_THREAD)
1244232207Smav			continue;
1245232207Smav		if (!SCHED_AFFINITY(ts, cg->cg_level))
1246232207Smav			continue;
1247232207Smav		ccg = cg;
1248232207Smav	}
1249232207Smav	if (ccg != NULL)
1250232207Smav		cg = ccg;
1251176735Sjeff	cpu = -1;
1252232207Smav	/* Search the group for the less loaded idle CPU we can run now. */
1253194779Sjeff	mask = td->td_cpuset->cs_mask;
1254232207Smav	if (cg != NULL && cg != cpu_top &&
1255232207Smav	    CPU_CMP(&cg->cg_mask, &cpu_top->cg_mask) != 0)
1256232207Smav		cpu = sched_lowest(cg, mask, max(pri, PRI_MAX_TIMESHARE),
1257232207Smav		    INT_MAX, ts->ts_cpu);
1258232207Smav	/* Search globally for the less loaded CPU we can run now. */
1259176735Sjeff	if (cpu == -1)
1260232207Smav		cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu);
1261232207Smav	/* Search globally for the less loaded CPU. */
1262232207Smav	if (cpu == -1)
1263232207Smav		cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu);
1264232454Smav	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1265171506Sjeff	/*
1266176735Sjeff	 * Compare the lowest loaded cpu to current cpu.
1267171506Sjeff	 */
1268177005Sjeff	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
1269232207Smav	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE &&
1270232207Smav	    TDQ_CPU(self)->tdq_load <= TDQ_CPU(cpu)->tdq_load + 1) {
1271178272Sjeff		SCHED_STAT_INC(pickcpu_local);
1272177005Sjeff		cpu = self;
1273178272Sjeff	} else
1274178272Sjeff		SCHED_STAT_INC(pickcpu_lowest);
1275178272Sjeff	if (cpu != ts->ts_cpu)
1276178272Sjeff		SCHED_STAT_INC(pickcpu_migration);
1277171482Sjeff	return (cpu);
1278123433Sjeff}
1279176735Sjeff#endif
1280123433Sjeff
1281117326Sjeff/*
1282121790Sjeff * Pick the highest priority task we have and return it.
1283117326Sjeff */
1284177435Sjeffstatic struct thread *
1285164936Sjuliantdq_choose(struct tdq *tdq)
1286110267Sjeff{
1287177435Sjeff	struct thread *td;
1288110267Sjeff
1289171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1290177435Sjeff	td = runq_choose(&tdq->tdq_realtime);
1291177435Sjeff	if (td != NULL)
1292177435Sjeff		return (td);
1293177435Sjeff	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1294177435Sjeff	if (td != NULL) {
1295217351Sjhb		KASSERT(td->td_priority >= PRI_MIN_BATCH,
1296165762Sjeff		    ("tdq_choose: Invalid priority on timeshare queue %d",
1297177435Sjeff		    td->td_priority));
1298177435Sjeff		return (td);
1299165762Sjeff	}
1300177435Sjeff	td = runq_choose(&tdq->tdq_idle);
1301177435Sjeff	if (td != NULL) {
1302177435Sjeff		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1303165762Sjeff		    ("tdq_choose: Invalid priority on idle queue %d",
1304177435Sjeff		    td->td_priority));
1305177435Sjeff		return (td);
1306165762Sjeff	}
1307165762Sjeff
1308165762Sjeff	return (NULL);
1309110267Sjeff}
1310110267Sjeff
1311171482Sjeff/*
1312171482Sjeff * Initialize a thread queue.
1313171482Sjeff */
1314109864Sjeffstatic void
1315164936Sjuliantdq_setup(struct tdq *tdq)
1316110028Sjeff{
1317171482Sjeff
1318171713Sjeff	if (bootverbose)
1319171713Sjeff		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1320165762Sjeff	runq_init(&tdq->tdq_realtime);
1321165762Sjeff	runq_init(&tdq->tdq_timeshare);
1322165620Sjeff	runq_init(&tdq->tdq_idle);
1323176735Sjeff	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1324176735Sjeff	    "sched lock %d", (int)TDQ_ID(tdq));
1325176735Sjeff	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1326176735Sjeff	    MTX_SPIN | MTX_RECURSE);
1327187357Sjeff#ifdef KTR
1328187357Sjeff	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
1329187357Sjeff	    "CPU %d load", (int)TDQ_ID(tdq));
1330187357Sjeff#endif
1331110028Sjeff}
1332110028Sjeff
1333171713Sjeff#ifdef SMP
1334110028Sjeffstatic void
1335171713Sjeffsched_setup_smp(void)
1336171713Sjeff{
1337171713Sjeff	struct tdq *tdq;
1338171713Sjeff	int i;
1339171713Sjeff
1340176735Sjeff	cpu_top = smp_topo();
1341209059Sjhb	CPU_FOREACH(i) {
1342176735Sjeff		tdq = TDQ_CPU(i);
1343171713Sjeff		tdq_setup(tdq);
1344176735Sjeff		tdq->tdq_cg = smp_topo_find(cpu_top, i);
1345176735Sjeff		if (tdq->tdq_cg == NULL)
1346176735Sjeff			panic("Can't find cpu group for %d\n", i);
1347123433Sjeff	}
1348176735Sjeff	balance_tdq = TDQ_SELF();
1349176735Sjeff	sched_balance();
1350171713Sjeff}
1351171713Sjeff#endif
1352171713Sjeff
1353171713Sjeff/*
1354171713Sjeff * Setup the thread queues and initialize the topology based on MD
1355171713Sjeff * information.
1356171713Sjeff */
1357171713Sjeffstatic void
1358171713Sjeffsched_setup(void *dummy)
1359171713Sjeff{
1360171713Sjeff	struct tdq *tdq;
1361171713Sjeff
1362171713Sjeff	tdq = TDQ_SELF();
1363171713Sjeff#ifdef SMP
1364176734Sjeff	sched_setup_smp();
1365117237Sjeff#else
1366171713Sjeff	tdq_setup(tdq);
1367116069Sjeff#endif
1368171482Sjeff
1369171482Sjeff	/* Add thread0's load since it's running. */
1370171482Sjeff	TDQ_LOCK(tdq);
1371171713Sjeff	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1372177435Sjeff	tdq_load_add(tdq, &thread0);
1373176735Sjeff	tdq->tdq_lowpri = thread0.td_priority;
1374171482Sjeff	TDQ_UNLOCK(tdq);
1375109864Sjeff}
1376109864Sjeff
1377171482Sjeff/*
1378239185Smav * This routine determines time constants after stathz and hz are setup.
1379171482Sjeff */
1380153533Sdavidxu/* ARGSUSED */
1381153533Sdavidxustatic void
1382153533Sdavidxusched_initticks(void *dummy)
1383153533Sdavidxu{
1384171482Sjeff	int incr;
1385171482Sjeff
1386153533Sdavidxu	realstathz = stathz ? stathz : hz;
1387239185Smav	sched_slice = realstathz / 10;	/* ~100ms */
1388239196Smav	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
1389239196Smav	    realstathz);
1390153533Sdavidxu
1391153533Sdavidxu	/*
1392165762Sjeff	 * tickincr is shifted out by 10 to avoid rounding errors due to
1393165766Sjeff	 * hz not being evenly divisible by stathz on all platforms.
1394153533Sdavidxu	 */
1395171482Sjeff	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1396165762Sjeff	/*
1397165762Sjeff	 * This does not work for values of stathz that are more than
1398165762Sjeff	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1399165762Sjeff	 */
1400171482Sjeff	if (incr == 0)
1401171482Sjeff		incr = 1;
1402171482Sjeff	tickincr = incr;
1403166108Sjeff#ifdef SMP
1404171899Sjeff	/*
1405172409Sjeff	 * Set the default balance interval now that we know
1406172409Sjeff	 * what realstathz is.
1407172409Sjeff	 */
1408172409Sjeff	balance_interval = realstathz;
1409166108Sjeff	affinity = SCHED_AFFINITY_DEFAULT;
1410166108Sjeff#endif
1411232740Smav	if (sched_idlespinthresh < 0)
1412239196Smav		sched_idlespinthresh = imax(16, 2 * hz / realstathz);
1413153533Sdavidxu}
1414153533Sdavidxu
1415153533Sdavidxu
1416109864Sjeff/*
1417171482Sjeff * This is the core of the interactivity algorithm.  Determines a score based
1418171482Sjeff * on past behavior.  It is the ratio of sleep time to run time scaled to
1419171482Sjeff * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1420171482Sjeff * differs from the cpu usage because it does not account for time spent
1421171482Sjeff * waiting on a run-queue.  Would be prettier if we had floating point.
1422171482Sjeff */
1423171482Sjeffstatic int
1424171482Sjeffsched_interact_score(struct thread *td)
1425171482Sjeff{
1426171482Sjeff	struct td_sched *ts;
1427171482Sjeff	int div;
1428171482Sjeff
1429171482Sjeff	ts = td->td_sched;
1430171482Sjeff	/*
1431171482Sjeff	 * The score is only needed if this is likely to be an interactive
1432171482Sjeff	 * task.  Don't go through the expense of computing it if there's
1433171482Sjeff	 * no chance.
1434171482Sjeff	 */
1435171482Sjeff	if (sched_interact <= SCHED_INTERACT_HALF &&
1436171482Sjeff		ts->ts_runtime >= ts->ts_slptime)
1437171482Sjeff			return (SCHED_INTERACT_HALF);
1438171482Sjeff
1439171482Sjeff	if (ts->ts_runtime > ts->ts_slptime) {
1440171482Sjeff		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1441171482Sjeff		return (SCHED_INTERACT_HALF +
1442171482Sjeff		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1443171482Sjeff	}
1444171482Sjeff	if (ts->ts_slptime > ts->ts_runtime) {
1445171482Sjeff		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1446171482Sjeff		return (ts->ts_runtime / div);
1447171482Sjeff	}
1448171482Sjeff	/* runtime == slptime */
1449171482Sjeff	if (ts->ts_runtime)
1450171482Sjeff		return (SCHED_INTERACT_HALF);
1451171482Sjeff
1452171482Sjeff	/*
1453171482Sjeff	 * This can happen if slptime and runtime are 0.
1454171482Sjeff	 */
1455171482Sjeff	return (0);
1456171482Sjeff
1457171482Sjeff}
1458171482Sjeff
1459171482Sjeff/*
1460109864Sjeff * Scale the scheduling priority according to the "interactivity" of this
1461109864Sjeff * process.
1462109864Sjeff */
1463113357Sjeffstatic void
1464163709Sjbsched_priority(struct thread *td)
1465109864Sjeff{
1466165762Sjeff	int score;
1467109864Sjeff	int pri;
1468109864Sjeff
1469217291Sjhb	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
1470113357Sjeff		return;
1471112966Sjeff	/*
1472165762Sjeff	 * If the score is interactive we place the thread in the realtime
1473165762Sjeff	 * queue with a priority that is less than kernel and interrupt
1474165762Sjeff	 * priorities.  These threads are not subject to nice restrictions.
1475112966Sjeff	 *
1476171482Sjeff	 * Scores greater than this are placed on the normal timeshare queue
1477165762Sjeff	 * where the priority is partially decided by the most recent cpu
1478165762Sjeff	 * utilization and the rest is decided by nice value.
1479172293Sjeff	 *
1480172293Sjeff	 * The nice value of the process has a linear effect on the calculated
1481172293Sjeff	 * score.  Negative nice values make it easier for a thread to be
1482172293Sjeff	 * considered interactive.
1483112966Sjeff	 */
1484198126Sjhb	score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1485165762Sjeff	if (score < sched_interact) {
1486217351Sjhb		pri = PRI_MIN_INTERACT;
1487217351Sjhb		pri += ((PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) /
1488217237Sjhb		    sched_interact) * score;
1489217351Sjhb		KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
1490166208Sjeff		    ("sched_priority: invalid interactive priority %d score %d",
1491166208Sjeff		    pri, score));
1492165762Sjeff	} else {
1493165762Sjeff		pri = SCHED_PRI_MIN;
1494165762Sjeff		if (td->td_sched->ts_ticks)
1495228960Sjhb			pri += min(SCHED_PRI_TICKS(td->td_sched),
1496228960Sjhb			    SCHED_PRI_RANGE);
1497165762Sjeff		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1498217351Sjhb		KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
1499171482Sjeff		    ("sched_priority: invalid priority %d: nice %d, "
1500171482Sjeff		    "ticks %d ftick %d ltick %d tick pri %d",
1501171482Sjeff		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1502171482Sjeff		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1503171482Sjeff		    SCHED_PRI_TICKS(td->td_sched)));
1504165762Sjeff	}
1505165762Sjeff	sched_user_prio(td, pri);
1506112966Sjeff
1507112966Sjeff	return;
1508109864Sjeff}
1509109864Sjeff
1510121868Sjeff/*
1511121868Sjeff * This routine enforces a maximum limit on the amount of scheduling history
1512171482Sjeff * kept.  It is called after either the slptime or runtime is adjusted.  This
1513171482Sjeff * function is ugly due to integer math.
1514121868Sjeff */
1515116463Sjeffstatic void
1516163709Sjbsched_interact_update(struct thread *td)
1517116463Sjeff{
1518165819Sjeff	struct td_sched *ts;
1519166208Sjeff	u_int sum;
1520121605Sjeff
1521165819Sjeff	ts = td->td_sched;
1522171482Sjeff	sum = ts->ts_runtime + ts->ts_slptime;
1523121868Sjeff	if (sum < SCHED_SLP_RUN_MAX)
1524121868Sjeff		return;
1525121868Sjeff	/*
1526165819Sjeff	 * This only happens from two places:
1527165819Sjeff	 * 1) We have added an unusual amount of run time from fork_exit.
1528165819Sjeff	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1529165819Sjeff	 */
1530165819Sjeff	if (sum > SCHED_SLP_RUN_MAX * 2) {
1531171482Sjeff		if (ts->ts_runtime > ts->ts_slptime) {
1532171482Sjeff			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1533171482Sjeff			ts->ts_slptime = 1;
1534165819Sjeff		} else {
1535171482Sjeff			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1536171482Sjeff			ts->ts_runtime = 1;
1537165819Sjeff		}
1538165819Sjeff		return;
1539165819Sjeff	}
1540165819Sjeff	/*
1541121868Sjeff	 * If we have exceeded by more than 1/5th then the algorithm below
1542121868Sjeff	 * will not bring us back into range.  Dividing by two here forces
1543133427Sjeff	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1544121868Sjeff	 */
1545127850Sjeff	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1546171482Sjeff		ts->ts_runtime /= 2;
1547171482Sjeff		ts->ts_slptime /= 2;
1548121868Sjeff		return;
1549116463Sjeff	}
1550171482Sjeff	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1551171482Sjeff	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1552116463Sjeff}
1553116463Sjeff
1554171482Sjeff/*
1555171482Sjeff * Scale back the interactivity history when a child thread is created.  The
1556171482Sjeff * history is inherited from the parent but the thread may behave totally
1557171482Sjeff * differently.  For example, a shell spawning a compiler process.  We want
1558171482Sjeff * to learn that the compiler is behaving badly very quickly.
1559171482Sjeff */
1560121868Sjeffstatic void
1561163709Sjbsched_interact_fork(struct thread *td)
1562121868Sjeff{
1563121868Sjeff	int ratio;
1564121868Sjeff	int sum;
1565121868Sjeff
1566171482Sjeff	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1567121868Sjeff	if (sum > SCHED_SLP_RUN_FORK) {
1568121868Sjeff		ratio = sum / SCHED_SLP_RUN_FORK;
1569171482Sjeff		td->td_sched->ts_runtime /= ratio;
1570171482Sjeff		td->td_sched->ts_slptime /= ratio;
1571121868Sjeff	}
1572121868Sjeff}
1573121868Sjeff
1574113357Sjeff/*
1575171482Sjeff * Called from proc0_init() to setup the scheduler fields.
1576134791Sjulian */
1577134791Sjulianvoid
1578134791Sjulianschedinit(void)
1579134791Sjulian{
1580165762Sjeff
1581134791Sjulian	/*
1582134791Sjulian	 * Set up the scheduler specific parts of proc0.
1583134791Sjulian	 */
1584136167Sjulian	proc0.p_sched = NULL; /* XXX */
1585164936Sjulian	thread0.td_sched = &td_sched0;
1586165762Sjeff	td_sched0.ts_ltick = ticks;
1587165796Sjeff	td_sched0.ts_ftick = ticks;
1588177009Sjeff	td_sched0.ts_slice = sched_slice;
1589134791Sjulian}
1590134791Sjulian
1591134791Sjulian/*
1592113357Sjeff * This is only somewhat accurate since given many processes of the same
1593113357Sjeff * priority they will switch when their slices run out, which will be
1594165762Sjeff * at most sched_slice stathz ticks.
1595113357Sjeff */
1596109864Sjeffint
1597109864Sjeffsched_rr_interval(void)
1598109864Sjeff{
1599165762Sjeff
1600239185Smav	/* Convert sched_slice from stathz to hz. */
1601239196Smav	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
1602109864Sjeff}
1603109864Sjeff
1604171482Sjeff/*
1605171482Sjeff * Update the percent cpu tracking information when it is requested or
1606171482Sjeff * the total history exceeds the maximum.  We keep a sliding history of
1607171482Sjeff * tick counts that slowly decays.  This is less precise than the 4BSD
1608171482Sjeff * mechanism since it happens with less regular and frequent events.
1609171482Sjeff */
1610121790Sjeffstatic void
1611232917Smavsched_pctcpu_update(struct td_sched *ts, int run)
1612109864Sjeff{
1613232917Smav	int t = ticks;
1614165762Sjeff
1615232917Smav	if (t - ts->ts_ltick >= SCHED_TICK_TARG) {
1616164936Sjulian		ts->ts_ticks = 0;
1617232917Smav		ts->ts_ftick = t - SCHED_TICK_TARG;
1618232917Smav	} else if (t - ts->ts_ftick >= SCHED_TICK_MAX) {
1619232917Smav		ts->ts_ticks = (ts->ts_ticks / (ts->ts_ltick - ts->ts_ftick)) *
1620232917Smav		    (ts->ts_ltick - (t - SCHED_TICK_TARG));
1621232917Smav		ts->ts_ftick = t - SCHED_TICK_TARG;
1622232917Smav	}
1623232917Smav	if (run)
1624232917Smav		ts->ts_ticks += (t - ts->ts_ltick) << SCHED_TICK_SHIFT;
1625232917Smav	ts->ts_ltick = t;
1626109864Sjeff}
1627109864Sjeff
1628171482Sjeff/*
1629171482Sjeff * Adjust the priority of a thread.  Move it to the appropriate run-queue
1630171482Sjeff * if necessary.  This is the back-end for several priority related
1631171482Sjeff * functions.
1632171482Sjeff */
1633165762Sjeffstatic void
1634139453Sjhbsched_thread_priority(struct thread *td, u_char prio)
1635109864Sjeff{
1636164936Sjulian	struct td_sched *ts;
1637177009Sjeff	struct tdq *tdq;
1638177009Sjeff	int oldpri;
1639109864Sjeff
1640187357Sjeff	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
1641187357Sjeff	    "prio:%d", td->td_priority, "new prio:%d", prio,
1642187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(curthread));
1643235459Srstone	SDT_PROBE3(sched, , , change_pri, td, td->td_proc, prio);
1644240513Savg	if (td != curthread && prio < td->td_priority) {
1645187357Sjeff		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
1646187357Sjeff		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
1647187357Sjeff		    prio, KTR_ATTR_LINKED, sched_tdname(td));
1648235459Srstone		SDT_PROBE4(sched, , , lend_pri, td, td->td_proc, prio,
1649235459Srstone		    curthread);
1650187357Sjeff	}
1651164936Sjulian	ts = td->td_sched;
1652170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1653139453Sjhb	if (td->td_priority == prio)
1654139453Sjhb		return;
1655177376Sjeff	/*
1656177376Sjeff	 * If the priority has been elevated due to priority
1657177376Sjeff	 * propagation, we may have to move ourselves to a new
1658177376Sjeff	 * queue.  This could be optimized to not re-add in some
1659177376Sjeff	 * cases.
1660177376Sjeff	 */
1661165766Sjeff	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1662165762Sjeff		sched_rem(td);
1663165762Sjeff		td->td_priority = prio;
1664171482Sjeff		sched_add(td, SRQ_BORROWING);
1665177009Sjeff		return;
1666177009Sjeff	}
1667177376Sjeff	/*
1668177376Sjeff	 * If the thread is currently running we may have to adjust the lowpri
1669177376Sjeff	 * information so other cpus are aware of our current priority.
1670177376Sjeff	 */
1671177009Sjeff	if (TD_IS_RUNNING(td)) {
1672177376Sjeff		tdq = TDQ_CPU(ts->ts_cpu);
1673177376Sjeff		oldpri = td->td_priority;
1674177376Sjeff		td->td_priority = prio;
1675176735Sjeff		if (prio < tdq->tdq_lowpri)
1676171482Sjeff			tdq->tdq_lowpri = prio;
1677176735Sjeff		else if (tdq->tdq_lowpri == oldpri)
1678176735Sjeff			tdq_setlowpri(tdq, td);
1679177376Sjeff		return;
1680177009Sjeff	}
1681177376Sjeff	td->td_priority = prio;
1682109864Sjeff}
1683109864Sjeff
1684139453Sjhb/*
1685139453Sjhb * Update a thread's priority when it is lent another thread's
1686139453Sjhb * priority.
1687139453Sjhb */
1688109864Sjeffvoid
1689139453Sjhbsched_lend_prio(struct thread *td, u_char prio)
1690139453Sjhb{
1691139453Sjhb
1692139453Sjhb	td->td_flags |= TDF_BORROWING;
1693139453Sjhb	sched_thread_priority(td, prio);
1694139453Sjhb}
1695139453Sjhb
1696139453Sjhb/*
1697139453Sjhb * Restore a thread's priority when priority propagation is
1698139453Sjhb * over.  The prio argument is the minimum priority the thread
1699139453Sjhb * needs to have to satisfy other possible priority lending
1700139453Sjhb * requests.  If the thread's regular priority is less
1701139453Sjhb * important than prio, the thread will keep a priority boost
1702139453Sjhb * of prio.
1703139453Sjhb */
1704139453Sjhbvoid
1705139453Sjhbsched_unlend_prio(struct thread *td, u_char prio)
1706139453Sjhb{
1707139453Sjhb	u_char base_pri;
1708139453Sjhb
1709139453Sjhb	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1710139453Sjhb	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1711163709Sjb		base_pri = td->td_user_pri;
1712139453Sjhb	else
1713139453Sjhb		base_pri = td->td_base_pri;
1714139453Sjhb	if (prio >= base_pri) {
1715139455Sjhb		td->td_flags &= ~TDF_BORROWING;
1716139453Sjhb		sched_thread_priority(td, base_pri);
1717139453Sjhb	} else
1718139453Sjhb		sched_lend_prio(td, prio);
1719139453Sjhb}
1720139453Sjhb
1721171482Sjeff/*
1722171482Sjeff * Standard entry for setting the priority to an absolute value.
1723171482Sjeff */
1724139453Sjhbvoid
1725139453Sjhbsched_prio(struct thread *td, u_char prio)
1726139453Sjhb{
1727139453Sjhb	u_char oldprio;
1728139453Sjhb
1729139453Sjhb	/* First, update the base priority. */
1730139453Sjhb	td->td_base_pri = prio;
1731139453Sjhb
1732139453Sjhb	/*
1733139455Sjhb	 * If the thread is borrowing another thread's priority, don't
1734139453Sjhb	 * ever lower the priority.
1735139453Sjhb	 */
1736139453Sjhb	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1737139453Sjhb		return;
1738139453Sjhb
1739139453Sjhb	/* Change the real priority. */
1740139453Sjhb	oldprio = td->td_priority;
1741139453Sjhb	sched_thread_priority(td, prio);
1742139453Sjhb
1743139453Sjhb	/*
1744139453Sjhb	 * If the thread is on a turnstile, then let the turnstile update
1745139453Sjhb	 * its state.
1746139453Sjhb	 */
1747139453Sjhb	if (TD_ON_LOCK(td) && oldprio != prio)
1748139453Sjhb		turnstile_adjust(td, oldprio);
1749139453Sjhb}
1750139455Sjhb
1751171482Sjeff/*
1752171482Sjeff * Set the base user priority, does not effect current running priority.
1753171482Sjeff */
1754139453Sjhbvoid
1755163709Sjbsched_user_prio(struct thread *td, u_char prio)
1756161599Sdavidxu{
1757161599Sdavidxu
1758163709Sjb	td->td_base_user_pri = prio;
1759216313Sdavidxu	if (td->td_lend_user_pri <= prio)
1760216313Sdavidxu		return;
1761163709Sjb	td->td_user_pri = prio;
1762161599Sdavidxu}
1763161599Sdavidxu
1764161599Sdavidxuvoid
1765161599Sdavidxusched_lend_user_prio(struct thread *td, u_char prio)
1766161599Sdavidxu{
1767161599Sdavidxu
1768174536Sdavidxu	THREAD_LOCK_ASSERT(td, MA_OWNED);
1769216313Sdavidxu	td->td_lend_user_pri = prio;
1770216791Sdavidxu	td->td_user_pri = min(prio, td->td_base_user_pri);
1771216791Sdavidxu	if (td->td_priority > td->td_user_pri)
1772216791Sdavidxu		sched_prio(td, td->td_user_pri);
1773216791Sdavidxu	else if (td->td_priority != td->td_user_pri)
1774216791Sdavidxu		td->td_flags |= TDF_NEEDRESCHED;
1775161599Sdavidxu}
1776161599Sdavidxu
1777171482Sjeff/*
1778171713Sjeff * Handle migration from sched_switch().  This happens only for
1779171713Sjeff * cpu binding.
1780171713Sjeff */
1781171713Sjeffstatic struct mtx *
1782171713Sjeffsched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1783171713Sjeff{
1784171713Sjeff	struct tdq *tdn;
1785171713Sjeff
1786171713Sjeff	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1787171713Sjeff#ifdef SMP
1788177435Sjeff	tdq_load_rem(tdq, td);
1789171713Sjeff	/*
1790171713Sjeff	 * Do the lock dance required to avoid LOR.  We grab an extra
1791171713Sjeff	 * spinlock nesting to prevent preemption while we're
1792171713Sjeff	 * not holding either run-queue lock.
1793171713Sjeff	 */
1794171713Sjeff	spinlock_enter();
1795202889Sattilio	thread_lock_block(td);	/* This releases the lock on tdq. */
1796197223Sattilio
1797197223Sattilio	/*
1798197223Sattilio	 * Acquire both run-queue locks before placing the thread on the new
1799197223Sattilio	 * run-queue to avoid deadlocks created by placing a thread with a
1800197223Sattilio	 * blocked lock on the run-queue of a remote processor.  The deadlock
1801197223Sattilio	 * occurs when a third processor attempts to lock the two queues in
1802197223Sattilio	 * question while the target processor is spinning with its own
1803197223Sattilio	 * run-queue lock held while waiting for the blocked lock to clear.
1804197223Sattilio	 */
1805197223Sattilio	tdq_lock_pair(tdn, tdq);
1806171713Sjeff	tdq_add(tdn, td, flags);
1807177435Sjeff	tdq_notify(tdn, td);
1808197223Sattilio	TDQ_UNLOCK(tdn);
1809171713Sjeff	spinlock_exit();
1810171713Sjeff#endif
1811171713Sjeff	return (TDQ_LOCKPTR(tdn));
1812171713Sjeff}
1813171713Sjeff
1814171713Sjeff/*
1815202889Sattilio * Variadic version of thread_lock_unblock() that does not assume td_lock
1816202889Sattilio * is blocked.
1817171482Sjeff */
1818171482Sjeffstatic inline void
1819171482Sjeffthread_unblock_switch(struct thread *td, struct mtx *mtx)
1820171482Sjeff{
1821171482Sjeff	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1822171482Sjeff	    (uintptr_t)mtx);
1823171482Sjeff}
1824171482Sjeff
1825171482Sjeff/*
1826171482Sjeff * Switch threads.  This function has to handle threads coming in while
1827171482Sjeff * blocked for some reason, running, or idle.  It also must deal with
1828171482Sjeff * migrating a thread from one queue to another as running threads may
1829171482Sjeff * be assigned elsewhere via binding.
1830171482Sjeff */
1831161599Sdavidxuvoid
1832135051Sjuliansched_switch(struct thread *td, struct thread *newtd, int flags)
1833109864Sjeff{
1834165627Sjeff	struct tdq *tdq;
1835164936Sjulian	struct td_sched *ts;
1836171482Sjeff	struct mtx *mtx;
1837171713Sjeff	int srqflag;
1838239157Smav	int cpuid, preempted;
1839109864Sjeff
1840170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1841177376Sjeff	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
1842109864Sjeff
1843171482Sjeff	cpuid = PCPU_GET(cpuid);
1844171482Sjeff	tdq = TDQ_CPU(cpuid);
1845164936Sjulian	ts = td->td_sched;
1846171713Sjeff	mtx = td->td_lock;
1847232917Smav	sched_pctcpu_update(ts, 1);
1848171482Sjeff	ts->ts_rltick = ticks;
1849133555Sjeff	td->td_lastcpu = td->td_oncpu;
1850113339Sjulian	td->td_oncpu = NOCPU;
1851239157Smav	preempted = !(td->td_flags & TDF_SLICEEND);
1852239157Smav	td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
1853144777Sups	td->td_owepreempt = 0;
1854178277Sjeff	tdq->tdq_switchcnt++;
1855123434Sjeff	/*
1856171482Sjeff	 * The lock pointer in an idle thread should never change.  Reset it
1857171482Sjeff	 * to CAN_RUN as well.
1858123434Sjeff	 */
1859167327Sjulian	if (TD_IS_IDLETHREAD(td)) {
1860171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1861139334Sjeff		TD_SET_CAN_RUN(td);
1862170293Sjeff	} else if (TD_IS_RUNNING(td)) {
1863171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1864239157Smav		srqflag = preempted ?
1865170293Sjeff		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1866171713Sjeff		    SRQ_OURSELF|SRQ_YIELDING;
1867212153Smdf#ifdef SMP
1868212115Smdf		if (THREAD_CAN_MIGRATE(td) && !THREAD_CAN_SCHED(td, ts->ts_cpu))
1869212115Smdf			ts->ts_cpu = sched_pickcpu(td, 0);
1870212153Smdf#endif
1871171713Sjeff		if (ts->ts_cpu == cpuid)
1872177435Sjeff			tdq_runq_add(tdq, td, srqflag);
1873212115Smdf		else {
1874212115Smdf			KASSERT(THREAD_CAN_MIGRATE(td) ||
1875212115Smdf			    (ts->ts_flags & TSF_BOUND) != 0,
1876212115Smdf			    ("Thread %p shouldn't migrate", td));
1877171713Sjeff			mtx = sched_switch_migrate(tdq, td, srqflag);
1878212115Smdf		}
1879171482Sjeff	} else {
1880171482Sjeff		/* This thread must be going to sleep. */
1881171482Sjeff		TDQ_LOCK(tdq);
1882202889Sattilio		mtx = thread_lock_block(td);
1883177435Sjeff		tdq_load_rem(tdq, td);
1884171482Sjeff	}
1885171482Sjeff	/*
1886171482Sjeff	 * We enter here with the thread blocked and assigned to the
1887171482Sjeff	 * appropriate cpu run-queue or sleep-queue and with the current
1888171482Sjeff	 * thread-queue locked.
1889171482Sjeff	 */
1890171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1891171482Sjeff	newtd = choosethread();
1892171482Sjeff	/*
1893171482Sjeff	 * Call the MD code to switch contexts if necessary.
1894171482Sjeff	 */
1895145256Sjkoshy	if (td != newtd) {
1896145256Sjkoshy#ifdef	HWPMC_HOOKS
1897145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1898145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1899145256Sjkoshy#endif
1900235459Srstone		SDT_PROBE2(sched, , , off_cpu, td, td->td_proc);
1901174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1902172411Sjeff		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1903232917Smav		sched_pctcpu_update(newtd->td_sched, 0);
1904179297Sjb
1905179297Sjb#ifdef KDTRACE_HOOKS
1906179297Sjb		/*
1907179297Sjb		 * If DTrace has set the active vtime enum to anything
1908179297Sjb		 * other than INACTIVE (0), then it should have set the
1909179297Sjb		 * function to call.
1910179297Sjb		 */
1911179297Sjb		if (dtrace_vtime_active)
1912179297Sjb			(*dtrace_vtime_switch_func)(newtd);
1913179297Sjb#endif
1914179297Sjb
1915171482Sjeff		cpu_switch(td, newtd, mtx);
1916171482Sjeff		/*
1917171482Sjeff		 * We may return from cpu_switch on a different cpu.  However,
1918171482Sjeff		 * we always return with td_lock pointing to the current cpu's
1919171482Sjeff		 * run queue lock.
1920171482Sjeff		 */
1921171482Sjeff		cpuid = PCPU_GET(cpuid);
1922171482Sjeff		tdq = TDQ_CPU(cpuid);
1923174629Sjeff		lock_profile_obtain_lock_success(
1924174629Sjeff		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1925235459Srstone
1926235459Srstone		SDT_PROBE0(sched, , , on_cpu);
1927145256Sjkoshy#ifdef	HWPMC_HOOKS
1928145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1929145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1930145256Sjkoshy#endif
1931235459Srstone	} else {
1932171482Sjeff		thread_unblock_switch(td, mtx);
1933235459Srstone		SDT_PROBE0(sched, , , remain_cpu);
1934235459Srstone	}
1935171482Sjeff	/*
1936171482Sjeff	 * Assert that all went well and return.
1937171482Sjeff	 */
1938171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1939171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1940171482Sjeff	td->td_oncpu = cpuid;
1941109864Sjeff}
1942109864Sjeff
1943171482Sjeff/*
1944171482Sjeff * Adjust thread priorities as a result of a nice request.
1945171482Sjeff */
1946109864Sjeffvoid
1947130551Sjuliansched_nice(struct proc *p, int nice)
1948109864Sjeff{
1949109864Sjeff	struct thread *td;
1950109864Sjeff
1951130551Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
1952165762Sjeff
1953130551Sjulian	p->p_nice = nice;
1954163709Sjb	FOREACH_THREAD_IN_PROC(p, td) {
1955170293Sjeff		thread_lock(td);
1956163709Sjb		sched_priority(td);
1957165762Sjeff		sched_prio(td, td->td_base_user_pri);
1958170293Sjeff		thread_unlock(td);
1959130551Sjulian	}
1960109864Sjeff}
1961109864Sjeff
1962171482Sjeff/*
1963171482Sjeff * Record the sleep time for the interactivity scorer.
1964171482Sjeff */
1965109864Sjeffvoid
1966177085Sjeffsched_sleep(struct thread *td, int prio)
1967109864Sjeff{
1968165762Sjeff
1969170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1970109864Sjeff
1971172264Sjeff	td->td_slptick = ticks;
1972201347Skib	if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
1973177085Sjeff		td->td_flags |= TDF_CANSWAP;
1974217410Sjhb	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
1975217410Sjhb		return;
1976177903Sjeff	if (static_boost == 1 && prio)
1977177085Sjeff		sched_prio(td, prio);
1978177903Sjeff	else if (static_boost && td->td_priority > static_boost)
1979177903Sjeff		sched_prio(td, static_boost);
1980109864Sjeff}
1981109864Sjeff
1982171482Sjeff/*
1983171482Sjeff * Schedule a thread to resume execution and record how long it voluntarily
1984171482Sjeff * slept.  We also update the pctcpu, interactivity, and priority.
1985171482Sjeff */
1986109864Sjeffvoid
1987109864Sjeffsched_wakeup(struct thread *td)
1988109864Sjeff{
1989166229Sjeff	struct td_sched *ts;
1990171482Sjeff	int slptick;
1991165762Sjeff
1992170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1993166229Sjeff	ts = td->td_sched;
1994177085Sjeff	td->td_flags &= ~TDF_CANSWAP;
1995109864Sjeff	/*
1996165762Sjeff	 * If we slept for more than a tick update our interactivity and
1997165762Sjeff	 * priority.
1998109864Sjeff	 */
1999172264Sjeff	slptick = td->td_slptick;
2000172264Sjeff	td->td_slptick = 0;
2001171482Sjeff	if (slptick && slptick != ticks) {
2002232917Smav		ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
2003165819Sjeff		sched_interact_update(td);
2004232917Smav		sched_pctcpu_update(ts, 0);
2005109864Sjeff	}
2006166229Sjeff	/* Reset the slice value after we sleep. */
2007166229Sjeff	ts->ts_slice = sched_slice;
2008166190Sjeff	sched_add(td, SRQ_BORING);
2009109864Sjeff}
2010109864Sjeff
2011109864Sjeff/*
2012109864Sjeff * Penalize the parent for creating a new child and initialize the child's
2013109864Sjeff * priority.
2014109864Sjeff */
2015109864Sjeffvoid
2016163709Sjbsched_fork(struct thread *td, struct thread *child)
2017109864Sjeff{
2018170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2019232917Smav	sched_pctcpu_update(td->td_sched, 1);
2020164936Sjulian	sched_fork_thread(td, child);
2021165762Sjeff	/*
2022165762Sjeff	 * Penalize the parent and child for forking.
2023165762Sjeff	 */
2024165762Sjeff	sched_interact_fork(child);
2025165762Sjeff	sched_priority(child);
2026171482Sjeff	td->td_sched->ts_runtime += tickincr;
2027165762Sjeff	sched_interact_update(td);
2028165762Sjeff	sched_priority(td);
2029164936Sjulian}
2030109864Sjeff
2031171482Sjeff/*
2032171482Sjeff * Fork a new thread, may be within the same process.
2033171482Sjeff */
2034164936Sjulianvoid
2035164936Sjuliansched_fork_thread(struct thread *td, struct thread *child)
2036164936Sjulian{
2037164936Sjulian	struct td_sched *ts;
2038164936Sjulian	struct td_sched *ts2;
2039164936Sjulian
2040177426Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2041165762Sjeff	/*
2042165762Sjeff	 * Initialize child.
2043165762Sjeff	 */
2044177426Sjeff	ts = td->td_sched;
2045177426Sjeff	ts2 = child->td_sched;
2046171482Sjeff	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
2047176735Sjeff	child->td_cpuset = cpuset_ref(td->td_cpuset);
2048164936Sjulian	ts2->ts_cpu = ts->ts_cpu;
2049177426Sjeff	ts2->ts_flags = 0;
2050165762Sjeff	/*
2051217078Sjhb	 * Grab our parents cpu estimation information.
2052165762Sjeff	 */
2053164936Sjulian	ts2->ts_ticks = ts->ts_ticks;
2054164936Sjulian	ts2->ts_ltick = ts->ts_ltick;
2055164936Sjulian	ts2->ts_ftick = ts->ts_ftick;
2056165762Sjeff	/*
2057217078Sjhb	 * Do not inherit any borrowed priority from the parent.
2058217078Sjhb	 */
2059217078Sjhb	child->td_priority = child->td_base_pri;
2060217078Sjhb	/*
2061165762Sjeff	 * And update interactivity score.
2062165762Sjeff	 */
2063171482Sjeff	ts2->ts_slptime = ts->ts_slptime;
2064171482Sjeff	ts2->ts_runtime = ts->ts_runtime;
2065165762Sjeff	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
2066187357Sjeff#ifdef KTR
2067187357Sjeff	bzero(ts2->ts_name, sizeof(ts2->ts_name));
2068187357Sjeff#endif
2069113357Sjeff}
2070113357Sjeff
2071171482Sjeff/*
2072171482Sjeff * Adjust the priority class of a thread.
2073171482Sjeff */
2074113357Sjeffvoid
2075163709Sjbsched_class(struct thread *td, int class)
2076113357Sjeff{
2077113357Sjeff
2078170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2079163709Sjb	if (td->td_pri_class == class)
2080113357Sjeff		return;
2081163709Sjb	td->td_pri_class = class;
2082109864Sjeff}
2083109864Sjeff
2084109864Sjeff/*
2085109864Sjeff * Return some of the child's priority and interactivity to the parent.
2086109864Sjeff */
2087109864Sjeffvoid
2088164939Sjuliansched_exit(struct proc *p, struct thread *child)
2089109864Sjeff{
2090165762Sjeff	struct thread *td;
2091113372Sjeff
2092187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2093225199Sdelphij	    "prio:%d", child->td_priority);
2094177368Sjeff	PROC_LOCK_ASSERT(p, MA_OWNED);
2095165762Sjeff	td = FIRST_THREAD_IN_PROC(p);
2096165762Sjeff	sched_exit_thread(td, child);
2097113372Sjeff}
2098113372Sjeff
2099171482Sjeff/*
2100171482Sjeff * Penalize another thread for the time spent on this one.  This helps to
2101171482Sjeff * worsen the priority and interactivity of processes which schedule batch
2102171482Sjeff * jobs such as make.  This has little effect on the make process itself but
2103171482Sjeff * causes new processes spawned by it to receive worse scores immediately.
2104171482Sjeff */
2105113372Sjeffvoid
2106164939Sjuliansched_exit_thread(struct thread *td, struct thread *child)
2107164936Sjulian{
2108165762Sjeff
2109187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2110225199Sdelphij	    "prio:%d", child->td_priority);
2111165762Sjeff	/*
2112165762Sjeff	 * Give the child's runtime to the parent without returning the
2113165762Sjeff	 * sleep time as a penalty to the parent.  This causes shells that
2114165762Sjeff	 * launch expensive things to mark their children as expensive.
2115165762Sjeff	 */
2116170293Sjeff	thread_lock(td);
2117171482Sjeff	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2118164939Sjulian	sched_interact_update(td);
2119165762Sjeff	sched_priority(td);
2120170293Sjeff	thread_unlock(td);
2121164936Sjulian}
2122164936Sjulian
2123177005Sjeffvoid
2124177005Sjeffsched_preempt(struct thread *td)
2125177005Sjeff{
2126177005Sjeff	struct tdq *tdq;
2127177005Sjeff
2128235459Srstone	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
2129235459Srstone
2130177005Sjeff	thread_lock(td);
2131177005Sjeff	tdq = TDQ_SELF();
2132177005Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2133177005Sjeff	tdq->tdq_ipipending = 0;
2134177005Sjeff	if (td->td_priority > tdq->tdq_lowpri) {
2135178272Sjeff		int flags;
2136178272Sjeff
2137178272Sjeff		flags = SW_INVOL | SW_PREEMPT;
2138177005Sjeff		if (td->td_critnest > 1)
2139177005Sjeff			td->td_owepreempt = 1;
2140178272Sjeff		else if (TD_IS_IDLETHREAD(td))
2141178272Sjeff			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2142177005Sjeff		else
2143178272Sjeff			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2144177005Sjeff	}
2145177005Sjeff	thread_unlock(td);
2146177005Sjeff}
2147177005Sjeff
2148171482Sjeff/*
2149171482Sjeff * Fix priorities on return to user-space.  Priorities may be elevated due
2150171482Sjeff * to static priorities in msleep() or similar.
2151171482Sjeff */
2152164936Sjulianvoid
2153164936Sjuliansched_userret(struct thread *td)
2154164936Sjulian{
2155164936Sjulian	/*
2156164936Sjulian	 * XXX we cheat slightly on the locking here to avoid locking in
2157164936Sjulian	 * the usual case.  Setting td_priority here is essentially an
2158164936Sjulian	 * incomplete workaround for not setting it properly elsewhere.
2159164936Sjulian	 * Now that some interrupt handlers are threads, not setting it
2160164936Sjulian	 * properly elsewhere can clobber it in the window between setting
2161164936Sjulian	 * it here and returning to user mode, so don't waste time setting
2162164936Sjulian	 * it perfectly here.
2163164936Sjulian	 */
2164164936Sjulian	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2165164936Sjulian	    ("thread with borrowed priority returning to userland"));
2166164936Sjulian	if (td->td_priority != td->td_user_pri) {
2167170293Sjeff		thread_lock(td);
2168164936Sjulian		td->td_priority = td->td_user_pri;
2169164936Sjulian		td->td_base_pri = td->td_user_pri;
2170177005Sjeff		tdq_setlowpri(TDQ_SELF(), td);
2171170293Sjeff		thread_unlock(td);
2172164936Sjulian        }
2173164936Sjulian}
2174164936Sjulian
2175171482Sjeff/*
2176171482Sjeff * Handle a stathz tick.  This is really only relevant for timeshare
2177171482Sjeff * threads.
2178171482Sjeff */
2179164936Sjulianvoid
2180121127Sjeffsched_clock(struct thread *td)
2181109864Sjeff{
2182164936Sjulian	struct tdq *tdq;
2183164936Sjulian	struct td_sched *ts;
2184109864Sjeff
2185171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2186164936Sjulian	tdq = TDQ_SELF();
2187172409Sjeff#ifdef SMP
2188133427Sjeff	/*
2189172409Sjeff	 * We run the long term load balancer infrequently on the first cpu.
2190172409Sjeff	 */
2191172409Sjeff	if (balance_tdq == tdq) {
2192172409Sjeff		if (balance_ticks && --balance_ticks == 0)
2193172409Sjeff			sched_balance();
2194172409Sjeff	}
2195172409Sjeff#endif
2196172409Sjeff	/*
2197178277Sjeff	 * Save the old switch count so we have a record of the last ticks
2198178277Sjeff	 * activity.   Initialize the new switch count based on our load.
2199178277Sjeff	 * If there is some activity seed it to reflect that.
2200178277Sjeff	 */
2201178277Sjeff	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
2202178471Sjeff	tdq->tdq_switchcnt = tdq->tdq_load;
2203178277Sjeff	/*
2204165766Sjeff	 * Advance the insert index once for each tick to ensure that all
2205165766Sjeff	 * threads get a chance to run.
2206133427Sjeff	 */
2207165766Sjeff	if (tdq->tdq_idx == tdq->tdq_ridx) {
2208165766Sjeff		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2209165766Sjeff		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2210165766Sjeff			tdq->tdq_ridx = tdq->tdq_idx;
2211165766Sjeff	}
2212165766Sjeff	ts = td->td_sched;
2213232917Smav	sched_pctcpu_update(ts, 1);
2214175104Sjeff	if (td->td_pri_class & PRI_FIFO_BIT)
2215113357Sjeff		return;
2216217291Sjhb	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2217175104Sjeff		/*
2218175104Sjeff		 * We used a tick; charge it to the thread so
2219175104Sjeff		 * that we can compute our interactivity.
2220175104Sjeff		 */
2221175104Sjeff		td->td_sched->ts_runtime += tickincr;
2222175104Sjeff		sched_interact_update(td);
2223177009Sjeff		sched_priority(td);
2224175104Sjeff	}
2225239185Smav
2226113357Sjeff	/*
2227239185Smav	 * Force a context switch if the current thread has used up a full
2228239185Smav	 * time slice (default is 100ms).
2229109864Sjeff	 */
2230239185Smav	if (!TD_IS_IDLETHREAD(td) && --ts->ts_slice <= 0) {
2231239185Smav		ts->ts_slice = sched_slice;
2232239185Smav		td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
2233239185Smav	}
2234109864Sjeff}
2235109864Sjeff
2236171482Sjeff/*
2237232917Smav * Called once per hz tick.
2238171482Sjeff */
2239171482Sjeffvoid
2240212541Smavsched_tick(int cnt)
2241171482Sjeff{
2242171482Sjeff
2243171482Sjeff}
2244171482Sjeff
2245171482Sjeff/*
2246171482Sjeff * Return whether the current CPU has runnable tasks.  Used for in-kernel
2247171482Sjeff * cooperative idle threads.
2248171482Sjeff */
2249109864Sjeffint
2250109864Sjeffsched_runnable(void)
2251109864Sjeff{
2252164936Sjulian	struct tdq *tdq;
2253115998Sjeff	int load;
2254109864Sjeff
2255115998Sjeff	load = 1;
2256115998Sjeff
2257164936Sjulian	tdq = TDQ_SELF();
2258121605Sjeff	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2259165620Sjeff		if (tdq->tdq_load > 0)
2260121605Sjeff			goto out;
2261121605Sjeff	} else
2262165620Sjeff		if (tdq->tdq_load - 1 > 0)
2263121605Sjeff			goto out;
2264115998Sjeff	load = 0;
2265115998Sjeffout:
2266115998Sjeff	return (load);
2267109864Sjeff}
2268109864Sjeff
2269171482Sjeff/*
2270171482Sjeff * Choose the highest priority thread to run.  The thread is removed from
2271171482Sjeff * the run-queue while running however the load remains.  For SMP we set
2272171482Sjeff * the tdq in the global idle bitmask if it idles here.
2273171482Sjeff */
2274166190Sjeffstruct thread *
2275109970Sjeffsched_choose(void)
2276109970Sjeff{
2277177435Sjeff	struct thread *td;
2278164936Sjulian	struct tdq *tdq;
2279109970Sjeff
2280164936Sjulian	tdq = TDQ_SELF();
2281171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2282177435Sjeff	td = tdq_choose(tdq);
2283177435Sjeff	if (td) {
2284177435Sjeff		tdq_runq_rem(tdq, td);
2285177903Sjeff		tdq->tdq_lowpri = td->td_priority;
2286177435Sjeff		return (td);
2287109864Sjeff	}
2288177903Sjeff	tdq->tdq_lowpri = PRI_MAX_IDLE;
2289176735Sjeff	return (PCPU_GET(idlethread));
2290109864Sjeff}
2291109864Sjeff
2292171482Sjeff/*
2293171482Sjeff * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2294171482Sjeff * we always request it once we exit a critical section.
2295171482Sjeff */
2296171482Sjeffstatic inline void
2297171482Sjeffsched_setpreempt(struct thread *td)
2298166190Sjeff{
2299166190Sjeff	struct thread *ctd;
2300166190Sjeff	int cpri;
2301166190Sjeff	int pri;
2302166190Sjeff
2303177005Sjeff	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2304177005Sjeff
2305166190Sjeff	ctd = curthread;
2306166190Sjeff	pri = td->td_priority;
2307166190Sjeff	cpri = ctd->td_priority;
2308177005Sjeff	if (pri < cpri)
2309177005Sjeff		ctd->td_flags |= TDF_NEEDRESCHED;
2310166190Sjeff	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2311171482Sjeff		return;
2312177005Sjeff	if (!sched_shouldpreempt(pri, cpri, 0))
2313171482Sjeff		return;
2314171482Sjeff	ctd->td_owepreempt = 1;
2315166190Sjeff}
2316166190Sjeff
2317171482Sjeff/*
2318177009Sjeff * Add a thread to a thread queue.  Select the appropriate runq and add the
2319177009Sjeff * thread to it.  This is the internal function called when the tdq is
2320177009Sjeff * predetermined.
2321171482Sjeff */
2322109864Sjeffvoid
2323171482Sjefftdq_add(struct tdq *tdq, struct thread *td, int flags)
2324109864Sjeff{
2325109864Sjeff
2326171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2327166190Sjeff	KASSERT((td->td_inhibitors == 0),
2328166190Sjeff	    ("sched_add: trying to run inhibited thread"));
2329166190Sjeff	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2330166190Sjeff	    ("sched_add: bad thread state"));
2331172207Sjeff	KASSERT(td->td_flags & TDF_INMEM,
2332172207Sjeff	    ("sched_add: thread swapped out"));
2333171482Sjeff
2334171482Sjeff	if (td->td_priority < tdq->tdq_lowpri)
2335171482Sjeff		tdq->tdq_lowpri = td->td_priority;
2336177435Sjeff	tdq_runq_add(tdq, td, flags);
2337177435Sjeff	tdq_load_add(tdq, td);
2338171482Sjeff}
2339171482Sjeff
2340171482Sjeff/*
2341171482Sjeff * Select the target thread queue and add a thread to it.  Request
2342171482Sjeff * preemption or IPI a remote processor if required.
2343171482Sjeff */
2344171482Sjeffvoid
2345171482Sjeffsched_add(struct thread *td, int flags)
2346171482Sjeff{
2347171482Sjeff	struct tdq *tdq;
2348171482Sjeff#ifdef SMP
2349171482Sjeff	int cpu;
2350171482Sjeff#endif
2351187357Sjeff
2352187357Sjeff	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
2353187357Sjeff	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
2354187357Sjeff	    sched_tdname(curthread));
2355187357Sjeff	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
2356187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(td));
2357235459Srstone	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
2358235459Srstone	    flags & SRQ_PREEMPTED);
2359171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2360166108Sjeff	/*
2361171482Sjeff	 * Recalculate the priority before we select the target cpu or
2362171482Sjeff	 * run-queue.
2363166108Sjeff	 */
2364171482Sjeff	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2365171482Sjeff		sched_priority(td);
2366171482Sjeff#ifdef SMP
2367171482Sjeff	/*
2368171482Sjeff	 * Pick the destination cpu and if it isn't ours transfer to the
2369171482Sjeff	 * target cpu.
2370171482Sjeff	 */
2371177435Sjeff	cpu = sched_pickcpu(td, flags);
2372177435Sjeff	tdq = sched_setcpu(td, cpu, flags);
2373171482Sjeff	tdq_add(tdq, td, flags);
2374177009Sjeff	if (cpu != PCPU_GET(cpuid)) {
2375177435Sjeff		tdq_notify(tdq, td);
2376166108Sjeff		return;
2377166108Sjeff	}
2378171482Sjeff#else
2379171482Sjeff	tdq = TDQ_SELF();
2380171482Sjeff	TDQ_LOCK(tdq);
2381171482Sjeff	/*
2382171482Sjeff	 * Now that the thread is moving to the run-queue, set the lock
2383171482Sjeff	 * to the scheduler's lock.
2384171482Sjeff	 */
2385171482Sjeff	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2386171482Sjeff	tdq_add(tdq, td, flags);
2387166108Sjeff#endif
2388171482Sjeff	if (!(flags & SRQ_YIELDING))
2389171482Sjeff		sched_setpreempt(td);
2390109864Sjeff}
2391109864Sjeff
2392171482Sjeff/*
2393171482Sjeff * Remove a thread from a run-queue without running it.  This is used
2394171482Sjeff * when we're stealing a thread from a remote queue.  Otherwise all threads
2395171482Sjeff * exit by calling sched_exit_thread() and sched_throw() themselves.
2396171482Sjeff */
2397109864Sjeffvoid
2398121127Sjeffsched_rem(struct thread *td)
2399109864Sjeff{
2400164936Sjulian	struct tdq *tdq;
2401113357Sjeff
2402187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
2403187357Sjeff	    "prio:%d", td->td_priority);
2404235459Srstone	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
2405177435Sjeff	tdq = TDQ_CPU(td->td_sched->ts_cpu);
2406171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2407171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2408166190Sjeff	KASSERT(TD_ON_RUNQ(td),
2409164936Sjulian	    ("sched_rem: thread not on run queue"));
2410177435Sjeff	tdq_runq_rem(tdq, td);
2411177435Sjeff	tdq_load_rem(tdq, td);
2412166190Sjeff	TD_SET_CAN_RUN(td);
2413176735Sjeff	if (td->td_priority == tdq->tdq_lowpri)
2414176735Sjeff		tdq_setlowpri(tdq, NULL);
2415109864Sjeff}
2416109864Sjeff
2417171482Sjeff/*
2418171482Sjeff * Fetch cpu utilization information.  Updates on demand.
2419171482Sjeff */
2420109864Sjefffixpt_t
2421121127Sjeffsched_pctcpu(struct thread *td)
2422109864Sjeff{
2423109864Sjeff	fixpt_t pctcpu;
2424164936Sjulian	struct td_sched *ts;
2425109864Sjeff
2426109864Sjeff	pctcpu = 0;
2427164936Sjulian	ts = td->td_sched;
2428164936Sjulian	if (ts == NULL)
2429121290Sjeff		return (0);
2430109864Sjeff
2431208787Sjhb	THREAD_LOCK_ASSERT(td, MA_OWNED);
2432232917Smav	sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2433164936Sjulian	if (ts->ts_ticks) {
2434109864Sjeff		int rtick;
2435109864Sjeff
2436109864Sjeff		/* How many rtick per second ? */
2437165762Sjeff		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2438165762Sjeff		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2439109864Sjeff	}
2440109864Sjeff
2441109864Sjeff	return (pctcpu);
2442109864Sjeff}
2443109864Sjeff
2444176735Sjeff/*
2445176735Sjeff * Enforce affinity settings for a thread.  Called after adjustments to
2446176735Sjeff * cpumask.
2447176735Sjeff */
2448176729Sjeffvoid
2449176729Sjeffsched_affinity(struct thread *td)
2450176729Sjeff{
2451176735Sjeff#ifdef SMP
2452176735Sjeff	struct td_sched *ts;
2453176735Sjeff
2454176735Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2455176735Sjeff	ts = td->td_sched;
2456176735Sjeff	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2457176735Sjeff		return;
2458189787Sjeff	if (TD_ON_RUNQ(td)) {
2459189787Sjeff		sched_rem(td);
2460189787Sjeff		sched_add(td, SRQ_BORING);
2461189787Sjeff		return;
2462189787Sjeff	}
2463176735Sjeff	if (!TD_IS_RUNNING(td))
2464176735Sjeff		return;
2465176735Sjeff	/*
2466212115Smdf	 * Force a switch before returning to userspace.  If the
2467212115Smdf	 * target thread is not running locally send an ipi to force
2468212115Smdf	 * the issue.
2469176735Sjeff	 */
2470212974Sjhb	td->td_flags |= TDF_NEEDRESCHED;
2471212115Smdf	if (td != curthread)
2472212115Smdf		ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
2473176735Sjeff#endif
2474176729Sjeff}
2475176729Sjeff
2476171482Sjeff/*
2477171482Sjeff * Bind a thread to a target cpu.
2478171482Sjeff */
2479122038Sjeffvoid
2480122038Sjeffsched_bind(struct thread *td, int cpu)
2481122038Sjeff{
2482164936Sjulian	struct td_sched *ts;
2483122038Sjeff
2484171713Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2485208391Sjhb	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
2486164936Sjulian	ts = td->td_sched;
2487166137Sjeff	if (ts->ts_flags & TSF_BOUND)
2488166152Sjeff		sched_unbind(td);
2489212115Smdf	KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2490164936Sjulian	ts->ts_flags |= TSF_BOUND;
2491166137Sjeff	sched_pin();
2492123433Sjeff	if (PCPU_GET(cpuid) == cpu)
2493122038Sjeff		return;
2494166137Sjeff	ts->ts_cpu = cpu;
2495122038Sjeff	/* When we return from mi_switch we'll be on the correct cpu. */
2496131527Sphk	mi_switch(SW_VOL, NULL);
2497122038Sjeff}
2498122038Sjeff
2499171482Sjeff/*
2500171482Sjeff * Release a bound thread.
2501171482Sjeff */
2502122038Sjeffvoid
2503122038Sjeffsched_unbind(struct thread *td)
2504122038Sjeff{
2505165762Sjeff	struct td_sched *ts;
2506165762Sjeff
2507170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2508208391Sjhb	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
2509165762Sjeff	ts = td->td_sched;
2510166137Sjeff	if ((ts->ts_flags & TSF_BOUND) == 0)
2511166137Sjeff		return;
2512165762Sjeff	ts->ts_flags &= ~TSF_BOUND;
2513165762Sjeff	sched_unpin();
2514122038Sjeff}
2515122038Sjeff
2516109864Sjeffint
2517145256Sjkoshysched_is_bound(struct thread *td)
2518145256Sjkoshy{
2519170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2520164936Sjulian	return (td->td_sched->ts_flags & TSF_BOUND);
2521145256Sjkoshy}
2522145256Sjkoshy
2523171482Sjeff/*
2524171482Sjeff * Basic yield call.
2525171482Sjeff */
2526159630Sdavidxuvoid
2527159630Sdavidxusched_relinquish(struct thread *td)
2528159630Sdavidxu{
2529170293Sjeff	thread_lock(td);
2530178272Sjeff	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
2531170293Sjeff	thread_unlock(td);
2532159630Sdavidxu}
2533159630Sdavidxu
2534171482Sjeff/*
2535171482Sjeff * Return the total system load.
2536171482Sjeff */
2537145256Sjkoshyint
2538125289Sjeffsched_load(void)
2539125289Sjeff{
2540125289Sjeff#ifdef SMP
2541125289Sjeff	int total;
2542125289Sjeff	int i;
2543125289Sjeff
2544125289Sjeff	total = 0;
2545209059Sjhb	CPU_FOREACH(i)
2546176735Sjeff		total += TDQ_CPU(i)->tdq_sysload;
2547125289Sjeff	return (total);
2548125289Sjeff#else
2549165620Sjeff	return (TDQ_SELF()->tdq_sysload);
2550125289Sjeff#endif
2551125289Sjeff}
2552125289Sjeff
2553125289Sjeffint
2554109864Sjeffsched_sizeof_proc(void)
2555109864Sjeff{
2556109864Sjeff	return (sizeof(struct proc));
2557109864Sjeff}
2558109864Sjeff
2559109864Sjeffint
2560109864Sjeffsched_sizeof_thread(void)
2561109864Sjeff{
2562109864Sjeff	return (sizeof(struct thread) + sizeof(struct td_sched));
2563109864Sjeff}
2564159570Sdavidxu
2565191676Sjeff#ifdef SMP
2566191676Sjeff#define	TDQ_IDLESPIN(tdq)						\
2567191676Sjeff    ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
2568191676Sjeff#else
2569191676Sjeff#define	TDQ_IDLESPIN(tdq)	1
2570191676Sjeff#endif
2571191676Sjeff
2572166190Sjeff/*
2573166190Sjeff * The actual idle process.
2574166190Sjeff */
2575166190Sjeffvoid
2576166190Sjeffsched_idletd(void *dummy)
2577166190Sjeff{
2578166190Sjeff	struct thread *td;
2579171482Sjeff	struct tdq *tdq;
2580178277Sjeff	int switchcnt;
2581178277Sjeff	int i;
2582166190Sjeff
2583191643Sjeff	mtx_assert(&Giant, MA_NOTOWNED);
2584166190Sjeff	td = curthread;
2585171482Sjeff	tdq = TDQ_SELF();
2586239585Sjhb	THREAD_NO_SLEEPING();
2587171482Sjeff	for (;;) {
2588171482Sjeff#ifdef SMP
2589178277Sjeff		if (tdq_idled(tdq) == 0)
2590178277Sjeff			continue;
2591171482Sjeff#endif
2592178277Sjeff		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2593178277Sjeff		/*
2594178277Sjeff		 * If we're switching very frequently, spin while checking
2595178277Sjeff		 * for load rather than entering a low power state that
2596191643Sjeff		 * may require an IPI.  However, don't do any busy
2597191643Sjeff		 * loops while on SMT machines as this simply steals
2598191643Sjeff		 * cycles from cores doing useful work.
2599178277Sjeff		 */
2600191676Sjeff		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
2601178277Sjeff			for (i = 0; i < sched_idlespins; i++) {
2602178277Sjeff				if (tdq->tdq_load)
2603178277Sjeff					break;
2604178277Sjeff				cpu_spinwait();
2605178277Sjeff			}
2606178277Sjeff		}
2607191643Sjeff		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2608212416Smav		if (tdq->tdq_load == 0) {
2609212416Smav			tdq->tdq_cpu_idle = 1;
2610212416Smav			if (tdq->tdq_load == 0) {
2611212541Smav				cpu_idle(switchcnt > sched_idlespinthresh * 4);
2612212416Smav				tdq->tdq_switchcnt++;
2613212416Smav			}
2614212416Smav			tdq->tdq_cpu_idle = 0;
2615212416Smav		}
2616178277Sjeff		if (tdq->tdq_load) {
2617178277Sjeff			thread_lock(td);
2618178277Sjeff			mi_switch(SW_VOL | SWT_IDLE, NULL);
2619178277Sjeff			thread_unlock(td);
2620178277Sjeff		}
2621171482Sjeff	}
2622166190Sjeff}
2623166190Sjeff
2624170293Sjeff/*
2625170293Sjeff * A CPU is entering for the first time or a thread is exiting.
2626170293Sjeff */
2627170293Sjeffvoid
2628170293Sjeffsched_throw(struct thread *td)
2629170293Sjeff{
2630172411Sjeff	struct thread *newtd;
2631171482Sjeff	struct tdq *tdq;
2632171482Sjeff
2633171482Sjeff	tdq = TDQ_SELF();
2634170293Sjeff	if (td == NULL) {
2635171482Sjeff		/* Correct spinlock nesting and acquire the correct lock. */
2636171482Sjeff		TDQ_LOCK(tdq);
2637170293Sjeff		spinlock_exit();
2638229429Sjhb		PCPU_SET(switchtime, cpu_ticks());
2639229429Sjhb		PCPU_SET(switchticks, ticks);
2640170293Sjeff	} else {
2641171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2642177435Sjeff		tdq_load_rem(tdq, td);
2643174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2644170293Sjeff	}
2645170293Sjeff	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2646172411Sjeff	newtd = choosethread();
2647172411Sjeff	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2648172411Sjeff	cpu_throw(td, newtd);		/* doesn't return */
2649170293Sjeff}
2650170293Sjeff
2651171482Sjeff/*
2652171482Sjeff * This is called from fork_exit().  Just acquire the correct locks and
2653171482Sjeff * let fork do the rest of the work.
2654171482Sjeff */
2655170293Sjeffvoid
2656170600Sjeffsched_fork_exit(struct thread *td)
2657170293Sjeff{
2658171482Sjeff	struct td_sched *ts;
2659171482Sjeff	struct tdq *tdq;
2660171482Sjeff	int cpuid;
2661170293Sjeff
2662170293Sjeff	/*
2663170293Sjeff	 * Finish setting up thread glue so that it begins execution in a
2664171482Sjeff	 * non-nested critical section with the scheduler lock held.
2665170293Sjeff	 */
2666171482Sjeff	cpuid = PCPU_GET(cpuid);
2667171482Sjeff	tdq = TDQ_CPU(cpuid);
2668171482Sjeff	ts = td->td_sched;
2669171482Sjeff	if (TD_IS_IDLETHREAD(td))
2670171482Sjeff		td->td_lock = TDQ_LOCKPTR(tdq);
2671171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2672171482Sjeff	td->td_oncpu = cpuid;
2673172411Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2674174629Sjeff	lock_profile_obtain_lock_success(
2675174629Sjeff	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2676170293Sjeff}
2677170293Sjeff
2678187357Sjeff/*
2679187357Sjeff * Create on first use to catch odd startup conditons.
2680187357Sjeff */
2681187357Sjeffchar *
2682187357Sjeffsched_tdname(struct thread *td)
2683187357Sjeff{
2684187357Sjeff#ifdef KTR
2685187357Sjeff	struct td_sched *ts;
2686187357Sjeff
2687187357Sjeff	ts = td->td_sched;
2688187357Sjeff	if (ts->ts_name[0] == '\0')
2689187357Sjeff		snprintf(ts->ts_name, sizeof(ts->ts_name),
2690187357Sjeff		    "%s tid %d", td->td_name, td->td_tid);
2691187357Sjeff	return (ts->ts_name);
2692187357Sjeff#else
2693187357Sjeff	return (td->td_name);
2694187357Sjeff#endif
2695187357Sjeff}
2696187357Sjeff
2697232700Sjhb#ifdef KTR
2698232700Sjhbvoid
2699232700Sjhbsched_clear_tdname(struct thread *td)
2700232700Sjhb{
2701232700Sjhb	struct td_sched *ts;
2702232700Sjhb
2703232700Sjhb	ts = td->td_sched;
2704232700Sjhb	ts->ts_name[0] = '\0';
2705232700Sjhb}
2706232700Sjhb#endif
2707232700Sjhb
2708184439Sivoras#ifdef SMP
2709184439Sivoras
2710184439Sivoras/*
2711184439Sivoras * Build the CPU topology dump string. Is recursively called to collect
2712184439Sivoras * the topology tree.
2713184439Sivoras */
2714184439Sivorasstatic int
2715184439Sivorassysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
2716184439Sivoras    int indent)
2717184439Sivoras{
2718222813Sattilio	char cpusetbuf[CPUSETBUFSIZ];
2719184439Sivoras	int i, first;
2720184439Sivoras
2721184439Sivoras	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
2722212821Savg	    "", 1 + indent / 2, cg->cg_level);
2723222813Sattilio	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
2724222813Sattilio	    cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
2725184439Sivoras	first = TRUE;
2726184439Sivoras	for (i = 0; i < MAXCPU; i++) {
2727222813Sattilio		if (CPU_ISSET(i, &cg->cg_mask)) {
2728184439Sivoras			if (!first)
2729184439Sivoras				sbuf_printf(sb, ", ");
2730184439Sivoras			else
2731184439Sivoras				first = FALSE;
2732184439Sivoras			sbuf_printf(sb, "%d", i);
2733184439Sivoras		}
2734184439Sivoras	}
2735184439Sivoras	sbuf_printf(sb, "</cpu>\n");
2736184439Sivoras
2737184439Sivoras	if (cg->cg_flags != 0) {
2738210117Sivoras		sbuf_printf(sb, "%*s <flags>", indent, "");
2739184439Sivoras		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
2740208982Sivoras			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
2741208983Sivoras		if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
2742208983Sivoras			sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
2743191643Sjeff		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
2744208983Sivoras			sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
2745210117Sivoras		sbuf_printf(sb, "</flags>\n");
2746184439Sivoras	}
2747184439Sivoras
2748184439Sivoras	if (cg->cg_children > 0) {
2749184439Sivoras		sbuf_printf(sb, "%*s <children>\n", indent, "");
2750184439Sivoras		for (i = 0; i < cg->cg_children; i++)
2751184439Sivoras			sysctl_kern_sched_topology_spec_internal(sb,
2752184439Sivoras			    &cg->cg_child[i], indent+2);
2753184439Sivoras		sbuf_printf(sb, "%*s </children>\n", indent, "");
2754184439Sivoras	}
2755184439Sivoras	sbuf_printf(sb, "%*s</group>\n", indent, "");
2756184439Sivoras	return (0);
2757184439Sivoras}
2758184439Sivoras
2759184439Sivoras/*
2760184439Sivoras * Sysctl handler for retrieving topology dump. It's a wrapper for
2761184439Sivoras * the recursive sysctl_kern_smp_topology_spec_internal().
2762184439Sivoras */
2763184439Sivorasstatic int
2764184439Sivorassysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
2765184439Sivoras{
2766184439Sivoras	struct sbuf *topo;
2767184439Sivoras	int err;
2768184439Sivoras
2769184439Sivoras	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
2770184439Sivoras
2771184570Sivoras	topo = sbuf_new(NULL, NULL, 500, SBUF_AUTOEXTEND);
2772184439Sivoras	if (topo == NULL)
2773184439Sivoras		return (ENOMEM);
2774184439Sivoras
2775184439Sivoras	sbuf_printf(topo, "<groups>\n");
2776184439Sivoras	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
2777184439Sivoras	sbuf_printf(topo, "</groups>\n");
2778184439Sivoras
2779184439Sivoras	if (err == 0) {
2780184439Sivoras		sbuf_finish(topo);
2781184439Sivoras		err = SYSCTL_OUT(req, sbuf_data(topo), sbuf_len(topo));
2782184439Sivoras	}
2783184439Sivoras	sbuf_delete(topo);
2784184439Sivoras	return (err);
2785184439Sivoras}
2786214510Sdavidxu
2787184439Sivoras#endif
2788184439Sivoras
2789239185Smavstatic int
2790239185Smavsysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
2791239185Smav{
2792239185Smav	int error, new_val, period;
2793239185Smav
2794239185Smav	period = 1000000 / realstathz;
2795239185Smav	new_val = period * sched_slice;
2796239185Smav	error = sysctl_handle_int(oidp, &new_val, 0, req);
2797239196Smav	if (error != 0 || req->newptr == NULL)
2798239185Smav		return (error);
2799239185Smav	if (new_val <= 0)
2800239185Smav		return (EINVAL);
2801239196Smav	sched_slice = imax(1, (new_val + period / 2) / period);
2802239196Smav	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
2803239196Smav	    realstathz);
2804239185Smav	return (0);
2805239185Smav}
2806239185Smav
2807177435SjeffSYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2808171482SjeffSYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2809165762Sjeff    "Scheduler name");
2810239185SmavSYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
2811239185Smav    NULL, 0, sysctl_kern_quantum, "I",
2812239196Smav    "Quantum for timeshare threads in microseconds");
2813171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2814239196Smav    "Quantum for timeshare threads in stathz ticks");
2815171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2816239196Smav    "Interactivity score threshold");
2817239196SmavSYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW,
2818239196Smav    &preempt_thresh, 0,
2819239196Smav    "Maximal (lowest) priority for preemption");
2820239196SmavSYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost, 0,
2821239196Smav    "Assign static kernel priorities to sleeping threads");
2822239196SmavSYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins, 0,
2823239196Smav    "Number of times idle thread will spin waiting for new work");
2824239196SmavSYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW,
2825239196Smav    &sched_idlespinthresh, 0,
2826239196Smav    "Threshold before we will permit idle thread spinning");
2827166108Sjeff#ifdef SMP
2828171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2829171482Sjeff    "Number of hz ticks to keep thread affinity for");
2830171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2831171482Sjeff    "Enables the long-term load balancer");
2832172409SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2833172409Sjeff    &balance_interval, 0,
2834239185Smav    "Average period in stathz ticks to run the long-term balancer");
2835171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2836171482Sjeff    "Attempts to steal work from other cores before idling");
2837171506SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2838239196Smav    "Minimum load on remote CPU before we'll steal");
2839184439SivorasSYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
2840239185Smav    CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
2841184439Sivoras    "XML dump of detected CPU topology");
2842166108Sjeff#endif
2843165762Sjeff
2844172264Sjeff/* ps compat.  All cpu percentages from ULE are weighted. */
2845172293Sjeffstatic int ccpu = 0;
2846165762SjeffSYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2847