sched_ule.c revision 191676
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 191676 2009-04-29 23:04:31Z jeff $");
40116182Sobrien
41147565Speter#include "opt_hwpmc_hooks.h"
42179297Sjb#include "opt_kdtrace.h"
43147565Speter#include "opt_sched.h"
44134649Sscottl
45109864Sjeff#include <sys/param.h>
46109864Sjeff#include <sys/systm.h>
47131929Smarcel#include <sys/kdb.h>
48109864Sjeff#include <sys/kernel.h>
49109864Sjeff#include <sys/ktr.h>
50109864Sjeff#include <sys/lock.h>
51109864Sjeff#include <sys/mutex.h>
52109864Sjeff#include <sys/proc.h>
53112966Sjeff#include <sys/resource.h>
54122038Sjeff#include <sys/resourcevar.h>
55109864Sjeff#include <sys/sched.h>
56109864Sjeff#include <sys/smp.h>
57109864Sjeff#include <sys/sx.h>
58109864Sjeff#include <sys/sysctl.h>
59109864Sjeff#include <sys/sysproto.h>
60139453Sjhb#include <sys/turnstile.h>
61161599Sdavidxu#include <sys/umtx.h>
62109864Sjeff#include <sys/vmmeter.h>
63176735Sjeff#include <sys/cpuset.h>
64184439Sivoras#include <sys/sbuf.h>
65109864Sjeff#ifdef KTRACE
66109864Sjeff#include <sys/uio.h>
67109864Sjeff#include <sys/ktrace.h>
68109864Sjeff#endif
69109864Sjeff
70145256Sjkoshy#ifdef HWPMC_HOOKS
71145256Sjkoshy#include <sys/pmckern.h>
72145256Sjkoshy#endif
73145256Sjkoshy
74179297Sjb#ifdef KDTRACE_HOOKS
75179297Sjb#include <sys/dtrace_bsd.h>
76179297Sjbint				dtrace_vtime_active;
77179297Sjbdtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
78179297Sjb#endif
79179297Sjb
80109864Sjeff#include <machine/cpu.h>
81121790Sjeff#include <machine/smp.h>
82109864Sjeff
83178215Smarcel#if defined(__sparc64__) || defined(__mips__)
84172345Sjeff#error "This architecture is not currently compatible with ULE"
85166190Sjeff#endif
86166190Sjeff
87171482Sjeff#define	KTR_ULE	0
88166137Sjeff
89187679Sjeff#define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
90187679Sjeff#define	TDQ_NAME_LEN	(sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
91187357Sjeff#define	TDQ_LOADNAME_LEN	(PCPU_NAME_LEN + sizeof(" load"))
92187357Sjeff
93166137Sjeff/*
94171482Sjeff * Thread scheduler specific section.  All fields are protected
95171482Sjeff * by the thread lock.
96146954Sjeff */
97164936Sjulianstruct td_sched {
98171482Sjeff	struct runq	*ts_runq;	/* Run-queue we're queued on. */
99171482Sjeff	short		ts_flags;	/* TSF_* flags. */
100164936Sjulian	u_char		ts_cpu;		/* CPU that we have affinity for. */
101177009Sjeff	int		ts_rltick;	/* Real last tick, for affinity. */
102171482Sjeff	int		ts_slice;	/* Ticks of slice remaining. */
103171482Sjeff	u_int		ts_slptime;	/* Number of ticks we vol. slept */
104171482Sjeff	u_int		ts_runtime;	/* Number of ticks we were running */
105164936Sjulian	int		ts_ltick;	/* Last tick that we were running on */
106164936Sjulian	int		ts_ftick;	/* First tick that we were running on */
107164936Sjulian	int		ts_ticks;	/* Tick count */
108187357Sjeff#ifdef KTR
109187357Sjeff	char		ts_name[TS_NAME_LEN];
110187357Sjeff#endif
111134791Sjulian};
112164936Sjulian/* flags kept in ts_flags */
113166108Sjeff#define	TSF_BOUND	0x0001		/* Thread can not migrate. */
114166108Sjeff#define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
115121790Sjeff
116164936Sjulianstatic struct td_sched td_sched0;
117109864Sjeff
118176735Sjeff#define	THREAD_CAN_MIGRATE(td)	((td)->td_pinned == 0)
119176735Sjeff#define	THREAD_CAN_SCHED(td, cpu)	\
120176735Sjeff    CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
121176735Sjeff
122109864Sjeff/*
123165762Sjeff * Cpu percentage computation macros and defines.
124111857Sjeff *
125165762Sjeff * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
126165762Sjeff * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
127165796Sjeff * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
128165762Sjeff * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
129165762Sjeff * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
130165762Sjeff * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
131165762Sjeff */
132165762Sjeff#define	SCHED_TICK_SECS		10
133165762Sjeff#define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
134165796Sjeff#define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
135165762Sjeff#define	SCHED_TICK_SHIFT	10
136165762Sjeff#define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
137165830Sjeff#define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
138165762Sjeff
139165762Sjeff/*
140165762Sjeff * These macros determine priorities for non-interactive threads.  They are
141165762Sjeff * assigned a priority based on their recent cpu utilization as expressed
142165762Sjeff * by the ratio of ticks to the tick total.  NHALF priorities at the start
143165762Sjeff * and end of the MIN to MAX timeshare range are only reachable with negative
144165762Sjeff * or positive nice respectively.
145165762Sjeff *
146165762Sjeff * PRI_RANGE:	Priority range for utilization dependent priorities.
147116642Sjeff * PRI_NRESV:	Number of nice values.
148165762Sjeff * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
149165762Sjeff * PRI_NICE:	Determines the part of the priority inherited from nice.
150109864Sjeff */
151165762Sjeff#define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
152121869Sjeff#define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
153165762Sjeff#define	SCHED_PRI_MIN		(PRI_MIN_TIMESHARE + SCHED_PRI_NHALF)
154165762Sjeff#define	SCHED_PRI_MAX		(PRI_MAX_TIMESHARE - SCHED_PRI_NHALF)
155170787Sjeff#define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN)
156165762Sjeff#define	SCHED_PRI_TICKS(ts)						\
157165762Sjeff    (SCHED_TICK_HZ((ts)) /						\
158165827Sjeff    (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
159165762Sjeff#define	SCHED_PRI_NICE(nice)	(nice)
160109864Sjeff
161109864Sjeff/*
162165762Sjeff * These determine the interactivity of a process.  Interactivity differs from
163165762Sjeff * cpu utilization in that it expresses the voluntary time slept vs time ran
164165762Sjeff * while cpu utilization includes all time not running.  This more accurately
165165762Sjeff * models the intent of the thread.
166109864Sjeff *
167110645Sjeff * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
168110645Sjeff *		before throttling back.
169121868Sjeff * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
170116365Sjeff * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
171111857Sjeff * INTERACT_THRESH:	Threshhold for placement on the current runq.
172109864Sjeff */
173165762Sjeff#define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
174165762Sjeff#define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
175116365Sjeff#define	SCHED_INTERACT_MAX	(100)
176116365Sjeff#define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
177121126Sjeff#define	SCHED_INTERACT_THRESH	(30)
178111857Sjeff
179109864Sjeff/*
180165762Sjeff * tickincr:		Converts a stathz tick into a hz domain scaled by
181165762Sjeff *			the shift factor.  Without the shift the error rate
182165762Sjeff *			due to rounding would be unacceptably high.
183165762Sjeff * realstathz:		stathz is sometimes 0 and run off of hz.
184165762Sjeff * sched_slice:		Runtime of each thread before rescheduling.
185171482Sjeff * preempt_thresh:	Priority threshold for preemption and remote IPIs.
186109864Sjeff */
187165762Sjeffstatic int sched_interact = SCHED_INTERACT_THRESH;
188165762Sjeffstatic int realstathz;
189165762Sjeffstatic int tickincr;
190177009Sjeffstatic int sched_slice = 1;
191172345Sjeff#ifdef PREEMPTION
192172345Sjeff#ifdef FULL_PREEMPTION
193172345Sjeffstatic int preempt_thresh = PRI_MAX_IDLE;
194172345Sjeff#else
195171482Sjeffstatic int preempt_thresh = PRI_MIN_KERN;
196172345Sjeff#endif
197172345Sjeff#else
198172345Sjeffstatic int preempt_thresh = 0;
199172345Sjeff#endif
200177903Sjeffstatic int static_boost = PRI_MIN_TIMESHARE;
201178277Sjeffstatic int sched_idlespins = 10000;
202178277Sjeffstatic int sched_idlespinthresh = 4;
203109864Sjeff
204109864Sjeff/*
205171482Sjeff * tdq - per processor runqs and statistics.  All fields are protected by the
206171482Sjeff * tdq_lock.  The load and lowpri may be accessed without to avoid excess
207171482Sjeff * locking in sched_pickcpu();
208109864Sjeff */
209164936Sjulianstruct tdq {
210177009Sjeff	/* Ordered to improve efficiency of cpu_search() and switch(). */
211177009Sjeff	struct mtx	tdq_lock;		/* run queue lock. */
212176735Sjeff	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
213178277Sjeff	volatile int	tdq_load;		/* Aggregate load. */
214176735Sjeff	int		tdq_sysload;		/* For loadavg, !ITHD load. */
215177009Sjeff	int		tdq_transferable;	/* Transferable thread count. */
216178277Sjeff	short		tdq_switchcnt;		/* Switches this tick. */
217178277Sjeff	short		tdq_oldswitchcnt;	/* Switches last tick. */
218177009Sjeff	u_char		tdq_lowpri;		/* Lowest priority thread. */
219177009Sjeff	u_char		tdq_ipipending;		/* IPI pending. */
220166557Sjeff	u_char		tdq_idx;		/* Current insert index. */
221166557Sjeff	u_char		tdq_ridx;		/* Current removal index. */
222177009Sjeff	struct runq	tdq_realtime;		/* real-time run queue. */
223177009Sjeff	struct runq	tdq_timeshare;		/* timeshare run queue. */
224177009Sjeff	struct runq	tdq_idle;		/* Queue of IDLE threads. */
225187357Sjeff	char		tdq_name[TDQ_NAME_LEN];
226187357Sjeff#ifdef KTR
227187357Sjeff	char		tdq_loadname[TDQ_LOADNAME_LEN];
228187357Sjeff#endif
229171482Sjeff} __aligned(64);
230109864Sjeff
231178277Sjeff/* Idle thread states and config. */
232178277Sjeff#define	TDQ_RUNNING	1
233178277Sjeff#define	TDQ_IDLE	2
234166108Sjeff
235123433Sjeff#ifdef SMP
236184439Sivorasstruct cpu_group *cpu_top;		/* CPU topology */
237123433Sjeff
238176735Sjeff#define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
239176735Sjeff#define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
240166108Sjeff
241123433Sjeff/*
242166108Sjeff * Run-time tunables.
243166108Sjeff */
244171506Sjeffstatic int rebalance = 1;
245172409Sjeffstatic int balance_interval = 128;	/* Default set in sched_initticks(). */
246166108Sjeffstatic int affinity;
247172409Sjeffstatic int steal_htt = 1;
248171506Sjeffstatic int steal_idle = 1;
249171506Sjeffstatic int steal_thresh = 2;
250166108Sjeff
251166108Sjeff/*
252165620Sjeff * One thread queue per processor.
253109864Sjeff */
254164936Sjulianstatic struct tdq	tdq_cpu[MAXCPU];
255172409Sjeffstatic struct tdq	*balance_tdq;
256172409Sjeffstatic int balance_ticks;
257129982Sjeff
258164936Sjulian#define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
259164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu[(x)])
260171713Sjeff#define	TDQ_ID(x)	((int)((x) - tdq_cpu))
261123433Sjeff#else	/* !SMP */
262164936Sjulianstatic struct tdq	tdq_cpu;
263129982Sjeff
264170315Sjeff#define	TDQ_ID(x)	(0)
265164936Sjulian#define	TDQ_SELF()	(&tdq_cpu)
266164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu)
267110028Sjeff#endif
268109864Sjeff
269171482Sjeff#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
270171482Sjeff#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
271171482Sjeff#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
272171482Sjeff#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
273176735Sjeff#define	TDQ_LOCKPTR(t)		(&(t)->tdq_lock)
274171482Sjeff
275163709Sjbstatic void sched_priority(struct thread *);
276146954Sjeffstatic void sched_thread_priority(struct thread *, u_char);
277163709Sjbstatic int sched_interact_score(struct thread *);
278163709Sjbstatic void sched_interact_update(struct thread *);
279163709Sjbstatic void sched_interact_fork(struct thread *);
280164936Sjulianstatic void sched_pctcpu_update(struct td_sched *);
281109864Sjeff
282110267Sjeff/* Operations on per processor queues */
283177435Sjeffstatic struct thread *tdq_choose(struct tdq *);
284164936Sjulianstatic void tdq_setup(struct tdq *);
285177435Sjeffstatic void tdq_load_add(struct tdq *, struct thread *);
286177435Sjeffstatic void tdq_load_rem(struct tdq *, struct thread *);
287177435Sjeffstatic __inline void tdq_runq_add(struct tdq *, struct thread *, int);
288177435Sjeffstatic __inline void tdq_runq_rem(struct tdq *, struct thread *);
289177005Sjeffstatic inline int sched_shouldpreempt(int, int, int);
290164936Sjulianvoid tdq_print(int cpu);
291165762Sjeffstatic void runq_print(struct runq *rq);
292171482Sjeffstatic void tdq_add(struct tdq *, struct thread *, int);
293110267Sjeff#ifdef SMP
294176735Sjeffstatic int tdq_move(struct tdq *, struct tdq *);
295171482Sjeffstatic int tdq_idled(struct tdq *);
296177435Sjeffstatic void tdq_notify(struct tdq *, struct thread *);
297177435Sjeffstatic struct thread *tdq_steal(struct tdq *, int);
298177435Sjeffstatic struct thread *runq_steal(struct runq *, int);
299177435Sjeffstatic int sched_pickcpu(struct thread *, int);
300172409Sjeffstatic void sched_balance(void);
301176735Sjeffstatic int sched_balance_pair(struct tdq *, struct tdq *);
302177435Sjeffstatic inline struct tdq *sched_setcpu(struct thread *, int, int);
303171482Sjeffstatic inline struct mtx *thread_block_switch(struct thread *);
304171482Sjeffstatic inline void thread_unblock_switch(struct thread *, struct mtx *);
305171713Sjeffstatic struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
306184439Sivorasstatic int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
307184439Sivorasstatic int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
308184439Sivoras    struct cpu_group *cg, int indent);
309121790Sjeff#endif
310110028Sjeff
311165762Sjeffstatic void sched_setup(void *dummy);
312177253SrwatsonSYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
313165762Sjeff
314165762Sjeffstatic void sched_initticks(void *dummy);
315177253SrwatsonSYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
316177253Srwatson    NULL);
317165762Sjeff
318171482Sjeff/*
319171482Sjeff * Print the threads waiting on a run-queue.
320171482Sjeff */
321165762Sjeffstatic void
322165762Sjeffrunq_print(struct runq *rq)
323165762Sjeff{
324165762Sjeff	struct rqhead *rqh;
325177435Sjeff	struct thread *td;
326165762Sjeff	int pri;
327165762Sjeff	int j;
328165762Sjeff	int i;
329165762Sjeff
330165762Sjeff	for (i = 0; i < RQB_LEN; i++) {
331165762Sjeff		printf("\t\trunq bits %d 0x%zx\n",
332165762Sjeff		    i, rq->rq_status.rqb_bits[i]);
333165762Sjeff		for (j = 0; j < RQB_BPW; j++)
334165762Sjeff			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
335165762Sjeff				pri = j + (i << RQB_L2BPW);
336165762Sjeff				rqh = &rq->rq_queues[pri];
337177435Sjeff				TAILQ_FOREACH(td, rqh, td_runq) {
338165762Sjeff					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
339177435Sjeff					    td, td->td_name, td->td_priority,
340177435Sjeff					    td->td_rqindex, pri);
341165762Sjeff				}
342165762Sjeff			}
343165762Sjeff	}
344165762Sjeff}
345165762Sjeff
346171482Sjeff/*
347171482Sjeff * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
348171482Sjeff */
349113357Sjeffvoid
350164936Sjuliantdq_print(int cpu)
351110267Sjeff{
352164936Sjulian	struct tdq *tdq;
353112994Sjeff
354164936Sjulian	tdq = TDQ_CPU(cpu);
355112994Sjeff
356171713Sjeff	printf("tdq %d:\n", TDQ_ID(tdq));
357176735Sjeff	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
358176735Sjeff	printf("\tLock name:      %s\n", tdq->tdq_name);
359165620Sjeff	printf("\tload:           %d\n", tdq->tdq_load);
360178277Sjeff	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
361178277Sjeff	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
362171482Sjeff	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
363165766Sjeff	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
364178277Sjeff	printf("\tload transferable: %d\n", tdq->tdq_transferable);
365178277Sjeff	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
366165762Sjeff	printf("\trealtime runq:\n");
367165762Sjeff	runq_print(&tdq->tdq_realtime);
368165762Sjeff	printf("\ttimeshare runq:\n");
369165762Sjeff	runq_print(&tdq->tdq_timeshare);
370165762Sjeff	printf("\tidle runq:\n");
371165762Sjeff	runq_print(&tdq->tdq_idle);
372113357Sjeff}
373112994Sjeff
374177005Sjeffstatic inline int
375177005Sjeffsched_shouldpreempt(int pri, int cpri, int remote)
376177005Sjeff{
377177005Sjeff	/*
378177005Sjeff	 * If the new priority is not better than the current priority there is
379177005Sjeff	 * nothing to do.
380177005Sjeff	 */
381177005Sjeff	if (pri >= cpri)
382177005Sjeff		return (0);
383177005Sjeff	/*
384177005Sjeff	 * Always preempt idle.
385177005Sjeff	 */
386177005Sjeff	if (cpri >= PRI_MIN_IDLE)
387177005Sjeff		return (1);
388177005Sjeff	/*
389177005Sjeff	 * If preemption is disabled don't preempt others.
390177005Sjeff	 */
391177005Sjeff	if (preempt_thresh == 0)
392177005Sjeff		return (0);
393177005Sjeff	/*
394177005Sjeff	 * Preempt if we exceed the threshold.
395177005Sjeff	 */
396177005Sjeff	if (pri <= preempt_thresh)
397177005Sjeff		return (1);
398177005Sjeff	/*
399177005Sjeff	 * If we're realtime or better and there is timeshare or worse running
400177005Sjeff	 * preempt only remote processors.
401177005Sjeff	 */
402177005Sjeff	if (remote && pri <= PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
403177005Sjeff		return (1);
404177005Sjeff	return (0);
405177005Sjeff}
406177005Sjeff
407171482Sjeff#define	TS_RQ_PPQ	(((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
408171482Sjeff/*
409171482Sjeff * Add a thread to the actual run-queue.  Keeps transferable counts up to
410171482Sjeff * date with what is actually on the run-queue.  Selects the correct
411171482Sjeff * queue position for timeshare threads.
412171482Sjeff */
413122744Sjeffstatic __inline void
414177435Sjefftdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
415122744Sjeff{
416177435Sjeff	struct td_sched *ts;
417177042Sjeff	u_char pri;
418177042Sjeff
419171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
420177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
421177009Sjeff
422177435Sjeff	pri = td->td_priority;
423177435Sjeff	ts = td->td_sched;
424177435Sjeff	TD_SET_RUNQ(td);
425177435Sjeff	if (THREAD_CAN_MIGRATE(td)) {
426165620Sjeff		tdq->tdq_transferable++;
427164936Sjulian		ts->ts_flags |= TSF_XFERABLE;
428123433Sjeff	}
429177042Sjeff	if (pri <= PRI_MAX_REALTIME) {
430177042Sjeff		ts->ts_runq = &tdq->tdq_realtime;
431177042Sjeff	} else if (pri <= PRI_MAX_TIMESHARE) {
432177042Sjeff		ts->ts_runq = &tdq->tdq_timeshare;
433165762Sjeff		KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
434165762Sjeff			("Invalid priority %d on timeshare runq", pri));
435165762Sjeff		/*
436165762Sjeff		 * This queue contains only priorities between MIN and MAX
437165762Sjeff		 * realtime.  Use the whole queue to represent these values.
438165762Sjeff		 */
439171713Sjeff		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
440165762Sjeff			pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
441165762Sjeff			pri = (pri + tdq->tdq_idx) % RQ_NQS;
442165766Sjeff			/*
443165766Sjeff			 * This effectively shortens the queue by one so we
444165766Sjeff			 * can have a one slot difference between idx and
445165766Sjeff			 * ridx while we wait for threads to drain.
446165766Sjeff			 */
447165766Sjeff			if (tdq->tdq_ridx != tdq->tdq_idx &&
448165766Sjeff			    pri == tdq->tdq_ridx)
449167664Sjeff				pri = (unsigned char)(pri - 1) % RQ_NQS;
450165762Sjeff		} else
451165766Sjeff			pri = tdq->tdq_ridx;
452177435Sjeff		runq_add_pri(ts->ts_runq, td, pri, flags);
453177042Sjeff		return;
454165762Sjeff	} else
455177009Sjeff		ts->ts_runq = &tdq->tdq_idle;
456177435Sjeff	runq_add(ts->ts_runq, td, flags);
457177009Sjeff}
458177009Sjeff
459171482Sjeff/*
460171482Sjeff * Remove a thread from a run-queue.  This typically happens when a thread
461171482Sjeff * is selected to run.  Running threads are not on the queue and the
462171482Sjeff * transferable count does not reflect them.
463171482Sjeff */
464122744Sjeffstatic __inline void
465177435Sjefftdq_runq_rem(struct tdq *tdq, struct thread *td)
466122744Sjeff{
467177435Sjeff	struct td_sched *ts;
468177435Sjeff
469177435Sjeff	ts = td->td_sched;
470171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
471171482Sjeff	KASSERT(ts->ts_runq != NULL,
472177435Sjeff	    ("tdq_runq_remove: thread %p null ts_runq", td));
473164936Sjulian	if (ts->ts_flags & TSF_XFERABLE) {
474165620Sjeff		tdq->tdq_transferable--;
475164936Sjulian		ts->ts_flags &= ~TSF_XFERABLE;
476123433Sjeff	}
477165766Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
478165766Sjeff		if (tdq->tdq_idx != tdq->tdq_ridx)
479177435Sjeff			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
480165766Sjeff		else
481177435Sjeff			runq_remove_idx(ts->ts_runq, td, NULL);
482165766Sjeff	} else
483177435Sjeff		runq_remove(ts->ts_runq, td);
484122744Sjeff}
485122744Sjeff
486171482Sjeff/*
487171482Sjeff * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
488171482Sjeff * for this thread to the referenced thread queue.
489171482Sjeff */
490113357Sjeffstatic void
491177435Sjefftdq_load_add(struct tdq *tdq, struct thread *td)
492113357Sjeff{
493171482Sjeff
494171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
495177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
496177902Sjeff
497165620Sjeff	tdq->tdq_load++;
498177902Sjeff	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
499177902Sjeff		tdq->tdq_sysload++;
500187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
501110267Sjeff}
502113357Sjeff
503171482Sjeff/*
504171482Sjeff * Remove the load from a thread that is transitioning to a sleep state or
505171482Sjeff * exiting.
506171482Sjeff */
507112994Sjeffstatic void
508177435Sjefftdq_load_rem(struct tdq *tdq, struct thread *td)
509110267Sjeff{
510171482Sjeff
511177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
512171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
513171482Sjeff	KASSERT(tdq->tdq_load != 0,
514171713Sjeff	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
515177902Sjeff
516165620Sjeff	tdq->tdq_load--;
517177902Sjeff	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
518177902Sjeff		tdq->tdq_sysload--;
519187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
520110267Sjeff}
521110267Sjeff
522176735Sjeff/*
523176735Sjeff * Set lowpri to its exact value by searching the run-queue and
524176735Sjeff * evaluating curthread.  curthread may be passed as an optimization.
525176735Sjeff */
526176735Sjeffstatic void
527176735Sjefftdq_setlowpri(struct tdq *tdq, struct thread *ctd)
528176735Sjeff{
529176735Sjeff	struct thread *td;
530176735Sjeff
531176735Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
532176735Sjeff	if (ctd == NULL)
533176735Sjeff		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
534177435Sjeff	td = tdq_choose(tdq);
535177435Sjeff	if (td == NULL || td->td_priority > ctd->td_priority)
536176735Sjeff		tdq->tdq_lowpri = ctd->td_priority;
537176735Sjeff	else
538176735Sjeff		tdq->tdq_lowpri = td->td_priority;
539176735Sjeff}
540176735Sjeff
541113357Sjeff#ifdef SMP
542176735Sjeffstruct cpu_search {
543176735Sjeff	cpumask_t cs_mask;	/* Mask of valid cpus. */
544176735Sjeff	u_int	cs_load;
545176735Sjeff	u_int	cs_cpu;
546176735Sjeff	int	cs_limit;	/* Min priority for low min load for high. */
547176735Sjeff};
548176735Sjeff
549176735Sjeff#define	CPU_SEARCH_LOWEST	0x1
550176735Sjeff#define	CPU_SEARCH_HIGHEST	0x2
551176735Sjeff#define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
552176735Sjeff
553176735Sjeff#define	CPUMASK_FOREACH(cpu, mask)				\
554176735Sjeff	for ((cpu) = 0; (cpu) < sizeof((mask)) * 8; (cpu)++)	\
555176735Sjeff		if ((mask) & 1 << (cpu))
556176735Sjeff
557177169Sjhbstatic __inline int cpu_search(struct cpu_group *cg, struct cpu_search *low,
558176735Sjeff    struct cpu_search *high, const int match);
559176735Sjeffint cpu_search_lowest(struct cpu_group *cg, struct cpu_search *low);
560176735Sjeffint cpu_search_highest(struct cpu_group *cg, struct cpu_search *high);
561176735Sjeffint cpu_search_both(struct cpu_group *cg, struct cpu_search *low,
562176735Sjeff    struct cpu_search *high);
563176735Sjeff
564116069Sjeff/*
565176735Sjeff * This routine compares according to the match argument and should be
566176735Sjeff * reduced in actual instantiations via constant propagation and dead code
567176735Sjeff * elimination.
568176735Sjeff */
569176735Sjeffstatic __inline int
570176735Sjeffcpu_compare(int cpu, struct cpu_search *low, struct cpu_search *high,
571176735Sjeff    const int match)
572176735Sjeff{
573176735Sjeff	struct tdq *tdq;
574176735Sjeff
575176735Sjeff	tdq = TDQ_CPU(cpu);
576176735Sjeff	if (match & CPU_SEARCH_LOWEST)
577176735Sjeff		if (low->cs_mask & (1 << cpu) &&
578176735Sjeff		    tdq->tdq_load < low->cs_load &&
579176735Sjeff		    tdq->tdq_lowpri > low->cs_limit) {
580176735Sjeff			low->cs_cpu = cpu;
581176735Sjeff			low->cs_load = tdq->tdq_load;
582176735Sjeff		}
583176735Sjeff	if (match & CPU_SEARCH_HIGHEST)
584176735Sjeff		if (high->cs_mask & (1 << cpu) &&
585176735Sjeff		    tdq->tdq_load >= high->cs_limit &&
586176735Sjeff		    tdq->tdq_load > high->cs_load &&
587176735Sjeff		    tdq->tdq_transferable) {
588176735Sjeff			high->cs_cpu = cpu;
589176735Sjeff			high->cs_load = tdq->tdq_load;
590176735Sjeff		}
591176735Sjeff	return (tdq->tdq_load);
592176735Sjeff}
593176735Sjeff
594176735Sjeff/*
595176735Sjeff * Search the tree of cpu_groups for the lowest or highest loaded cpu
596176735Sjeff * according to the match argument.  This routine actually compares the
597176735Sjeff * load on all paths through the tree and finds the least loaded cpu on
598176735Sjeff * the least loaded path, which may differ from the least loaded cpu in
599176735Sjeff * the system.  This balances work among caches and busses.
600116069Sjeff *
601176735Sjeff * This inline is instantiated in three forms below using constants for the
602176735Sjeff * match argument.  It is reduced to the minimum set for each case.  It is
603176735Sjeff * also recursive to the depth of the tree.
604116069Sjeff */
605177169Sjhbstatic __inline int
606176735Sjeffcpu_search(struct cpu_group *cg, struct cpu_search *low,
607176735Sjeff    struct cpu_search *high, const int match)
608176735Sjeff{
609176735Sjeff	int total;
610176735Sjeff
611176735Sjeff	total = 0;
612176735Sjeff	if (cg->cg_children) {
613176735Sjeff		struct cpu_search lgroup;
614176735Sjeff		struct cpu_search hgroup;
615176735Sjeff		struct cpu_group *child;
616176735Sjeff		u_int lload;
617176735Sjeff		int hload;
618176735Sjeff		int load;
619176735Sjeff		int i;
620176735Sjeff
621176735Sjeff		lload = -1;
622176735Sjeff		hload = -1;
623176735Sjeff		for (i = 0; i < cg->cg_children; i++) {
624176735Sjeff			child = &cg->cg_child[i];
625176735Sjeff			if (match & CPU_SEARCH_LOWEST) {
626176735Sjeff				lgroup = *low;
627176735Sjeff				lgroup.cs_load = -1;
628176735Sjeff			}
629176735Sjeff			if (match & CPU_SEARCH_HIGHEST) {
630176735Sjeff				hgroup = *high;
631176735Sjeff				lgroup.cs_load = 0;
632176735Sjeff			}
633176735Sjeff			switch (match) {
634176735Sjeff			case CPU_SEARCH_LOWEST:
635176735Sjeff				load = cpu_search_lowest(child, &lgroup);
636176735Sjeff				break;
637176735Sjeff			case CPU_SEARCH_HIGHEST:
638176735Sjeff				load = cpu_search_highest(child, &hgroup);
639176735Sjeff				break;
640176735Sjeff			case CPU_SEARCH_BOTH:
641176735Sjeff				load = cpu_search_both(child, &lgroup, &hgroup);
642176735Sjeff				break;
643176735Sjeff			}
644176735Sjeff			total += load;
645176735Sjeff			if (match & CPU_SEARCH_LOWEST)
646176735Sjeff				if (load < lload || low->cs_cpu == -1) {
647176735Sjeff					*low = lgroup;
648176735Sjeff					lload = load;
649176735Sjeff				}
650176735Sjeff			if (match & CPU_SEARCH_HIGHEST)
651176735Sjeff				if (load > hload || high->cs_cpu == -1) {
652176735Sjeff					hload = load;
653176735Sjeff					*high = hgroup;
654176735Sjeff				}
655176735Sjeff		}
656176735Sjeff	} else {
657176735Sjeff		int cpu;
658176735Sjeff
659176735Sjeff		CPUMASK_FOREACH(cpu, cg->cg_mask)
660176735Sjeff			total += cpu_compare(cpu, low, high, match);
661176735Sjeff	}
662176735Sjeff	return (total);
663176735Sjeff}
664176735Sjeff
665176735Sjeff/*
666176735Sjeff * cpu_search instantiations must pass constants to maintain the inline
667176735Sjeff * optimization.
668176735Sjeff */
669176735Sjeffint
670176735Sjeffcpu_search_lowest(struct cpu_group *cg, struct cpu_search *low)
671176735Sjeff{
672176735Sjeff	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
673176735Sjeff}
674176735Sjeff
675176735Sjeffint
676176735Sjeffcpu_search_highest(struct cpu_group *cg, struct cpu_search *high)
677176735Sjeff{
678176735Sjeff	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
679176735Sjeff}
680176735Sjeff
681176735Sjeffint
682176735Sjeffcpu_search_both(struct cpu_group *cg, struct cpu_search *low,
683176735Sjeff    struct cpu_search *high)
684176735Sjeff{
685176735Sjeff	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
686176735Sjeff}
687176735Sjeff
688176735Sjeff/*
689176735Sjeff * Find the cpu with the least load via the least loaded path that has a
690176735Sjeff * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
691176735Sjeff * acceptable.
692176735Sjeff */
693176735Sjeffstatic inline int
694176735Sjeffsched_lowest(struct cpu_group *cg, cpumask_t mask, int pri)
695176735Sjeff{
696176735Sjeff	struct cpu_search low;
697176735Sjeff
698176735Sjeff	low.cs_cpu = -1;
699176735Sjeff	low.cs_load = -1;
700176735Sjeff	low.cs_mask = mask;
701176735Sjeff	low.cs_limit = pri;
702176735Sjeff	cpu_search_lowest(cg, &low);
703176735Sjeff	return low.cs_cpu;
704176735Sjeff}
705176735Sjeff
706176735Sjeff/*
707176735Sjeff * Find the cpu with the highest load via the highest loaded path.
708176735Sjeff */
709176735Sjeffstatic inline int
710176735Sjeffsched_highest(struct cpu_group *cg, cpumask_t mask, int minload)
711176735Sjeff{
712176735Sjeff	struct cpu_search high;
713176735Sjeff
714176735Sjeff	high.cs_cpu = -1;
715176735Sjeff	high.cs_load = 0;
716176735Sjeff	high.cs_mask = mask;
717176735Sjeff	high.cs_limit = minload;
718176735Sjeff	cpu_search_highest(cg, &high);
719176735Sjeff	return high.cs_cpu;
720176735Sjeff}
721176735Sjeff
722176735Sjeff/*
723176735Sjeff * Simultaneously find the highest and lowest loaded cpu reachable via
724176735Sjeff * cg.
725176735Sjeff */
726176735Sjeffstatic inline void
727176735Sjeffsched_both(struct cpu_group *cg, cpumask_t mask, int *lowcpu, int *highcpu)
728176735Sjeff{
729176735Sjeff	struct cpu_search high;
730176735Sjeff	struct cpu_search low;
731176735Sjeff
732176735Sjeff	low.cs_cpu = -1;
733176735Sjeff	low.cs_limit = -1;
734176735Sjeff	low.cs_load = -1;
735176735Sjeff	low.cs_mask = mask;
736176735Sjeff	high.cs_load = 0;
737176735Sjeff	high.cs_cpu = -1;
738176735Sjeff	high.cs_limit = -1;
739176735Sjeff	high.cs_mask = mask;
740176735Sjeff	cpu_search_both(cg, &low, &high);
741176735Sjeff	*lowcpu = low.cs_cpu;
742176735Sjeff	*highcpu = high.cs_cpu;
743176735Sjeff	return;
744176735Sjeff}
745176735Sjeff
746121790Sjeffstatic void
747176735Sjeffsched_balance_group(struct cpu_group *cg)
748116069Sjeff{
749176735Sjeff	cpumask_t mask;
750176735Sjeff	int high;
751176735Sjeff	int low;
752123487Sjeff	int i;
753123487Sjeff
754176735Sjeff	mask = -1;
755176735Sjeff	for (;;) {
756176735Sjeff		sched_both(cg, mask, &low, &high);
757176735Sjeff		if (low == high || low == -1 || high == -1)
758176735Sjeff			break;
759176735Sjeff		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low)))
760176735Sjeff			break;
761123487Sjeff		/*
762176735Sjeff		 * If we failed to move any threads determine which cpu
763176735Sjeff		 * to kick out of the set and try again.
764176735Sjeff	 	 */
765176735Sjeff		if (TDQ_CPU(high)->tdq_transferable == 0)
766176735Sjeff			mask &= ~(1 << high);
767176735Sjeff		else
768176735Sjeff			mask &= ~(1 << low);
769123487Sjeff	}
770176735Sjeff
771176735Sjeff	for (i = 0; i < cg->cg_children; i++)
772176735Sjeff		sched_balance_group(&cg->cg_child[i]);
773123487Sjeff}
774123487Sjeff
775123487Sjeffstatic void
776176735Sjeffsched_balance()
777123487Sjeff{
778172409Sjeff	struct tdq *tdq;
779123487Sjeff
780172409Sjeff	/*
781172409Sjeff	 * Select a random time between .5 * balance_interval and
782172409Sjeff	 * 1.5 * balance_interval.
783172409Sjeff	 */
784176735Sjeff	balance_ticks = max(balance_interval / 2, 1);
785176735Sjeff	balance_ticks += random() % balance_interval;
786171482Sjeff	if (smp_started == 0 || rebalance == 0)
787171482Sjeff		return;
788172409Sjeff	tdq = TDQ_SELF();
789172409Sjeff	TDQ_UNLOCK(tdq);
790176735Sjeff	sched_balance_group(cpu_top);
791172409Sjeff	TDQ_LOCK(tdq);
792123487Sjeff}
793123487Sjeff
794171482Sjeff/*
795171482Sjeff * Lock two thread queues using their address to maintain lock order.
796171482Sjeff */
797123487Sjeffstatic void
798171482Sjefftdq_lock_pair(struct tdq *one, struct tdq *two)
799171482Sjeff{
800171482Sjeff	if (one < two) {
801171482Sjeff		TDQ_LOCK(one);
802171482Sjeff		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
803171482Sjeff	} else {
804171482Sjeff		TDQ_LOCK(two);
805171482Sjeff		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
806171482Sjeff	}
807171482Sjeff}
808171482Sjeff
809171482Sjeff/*
810172409Sjeff * Unlock two thread queues.  Order is not important here.
811172409Sjeff */
812172409Sjeffstatic void
813172409Sjefftdq_unlock_pair(struct tdq *one, struct tdq *two)
814172409Sjeff{
815172409Sjeff	TDQ_UNLOCK(one);
816172409Sjeff	TDQ_UNLOCK(two);
817172409Sjeff}
818172409Sjeff
819172409Sjeff/*
820171482Sjeff * Transfer load between two imbalanced thread queues.
821171482Sjeff */
822176735Sjeffstatic int
823164936Sjuliansched_balance_pair(struct tdq *high, struct tdq *low)
824123487Sjeff{
825123433Sjeff	int transferable;
826116069Sjeff	int high_load;
827116069Sjeff	int low_load;
828176735Sjeff	int moved;
829116069Sjeff	int move;
830116069Sjeff	int diff;
831116069Sjeff	int i;
832116069Sjeff
833171482Sjeff	tdq_lock_pair(high, low);
834176735Sjeff	transferable = high->tdq_transferable;
835176735Sjeff	high_load = high->tdq_load;
836176735Sjeff	low_load = low->tdq_load;
837176735Sjeff	moved = 0;
838116069Sjeff	/*
839122744Sjeff	 * Determine what the imbalance is and then adjust that to how many
840165620Sjeff	 * threads we actually have to give up (transferable).
841122744Sjeff	 */
842171482Sjeff	if (transferable != 0) {
843171482Sjeff		diff = high_load - low_load;
844171482Sjeff		move = diff / 2;
845171482Sjeff		if (diff & 0x1)
846171482Sjeff			move++;
847171482Sjeff		move = min(move, transferable);
848171482Sjeff		for (i = 0; i < move; i++)
849176735Sjeff			moved += tdq_move(high, low);
850172293Sjeff		/*
851172293Sjeff		 * IPI the target cpu to force it to reschedule with the new
852172293Sjeff		 * workload.
853172293Sjeff		 */
854172293Sjeff		ipi_selected(1 << TDQ_ID(low), IPI_PREEMPT);
855171482Sjeff	}
856172409Sjeff	tdq_unlock_pair(high, low);
857176735Sjeff	return (moved);
858116069Sjeff}
859116069Sjeff
860171482Sjeff/*
861171482Sjeff * Move a thread from one thread queue to another.
862171482Sjeff */
863176735Sjeffstatic int
864171482Sjefftdq_move(struct tdq *from, struct tdq *to)
865116069Sjeff{
866171482Sjeff	struct td_sched *ts;
867171482Sjeff	struct thread *td;
868164936Sjulian	struct tdq *tdq;
869171482Sjeff	int cpu;
870116069Sjeff
871172409Sjeff	TDQ_LOCK_ASSERT(from, MA_OWNED);
872172409Sjeff	TDQ_LOCK_ASSERT(to, MA_OWNED);
873172409Sjeff
874164936Sjulian	tdq = from;
875171482Sjeff	cpu = TDQ_ID(to);
876177435Sjeff	td = tdq_steal(tdq, cpu);
877177435Sjeff	if (td == NULL)
878176735Sjeff		return (0);
879177435Sjeff	ts = td->td_sched;
880171482Sjeff	/*
881171482Sjeff	 * Although the run queue is locked the thread may be blocked.  Lock
882172409Sjeff	 * it to clear this and acquire the run-queue lock.
883171482Sjeff	 */
884171482Sjeff	thread_lock(td);
885172409Sjeff	/* Drop recursive lock on from acquired via thread_lock(). */
886171482Sjeff	TDQ_UNLOCK(from);
887171482Sjeff	sched_rem(td);
888166108Sjeff	ts->ts_cpu = cpu;
889171482Sjeff	td->td_lock = TDQ_LOCKPTR(to);
890171482Sjeff	tdq_add(to, td, SRQ_YIELDING);
891176735Sjeff	return (1);
892116069Sjeff}
893110267Sjeff
894171482Sjeff/*
895171482Sjeff * This tdq has idled.  Try to steal a thread from another cpu and switch
896171482Sjeff * to it.
897171482Sjeff */
898123433Sjeffstatic int
899164936Sjuliantdq_idled(struct tdq *tdq)
900121790Sjeff{
901176735Sjeff	struct cpu_group *cg;
902164936Sjulian	struct tdq *steal;
903176735Sjeff	cpumask_t mask;
904176735Sjeff	int thresh;
905171482Sjeff	int cpu;
906123433Sjeff
907172484Sjeff	if (smp_started == 0 || steal_idle == 0)
908172484Sjeff		return (1);
909176735Sjeff	mask = -1;
910176735Sjeff	mask &= ~PCPU_GET(cpumask);
911176735Sjeff	/* We don't want to be preempted while we're iterating. */
912171482Sjeff	spinlock_enter();
913176735Sjeff	for (cg = tdq->tdq_cg; cg != NULL; ) {
914191643Sjeff		if ((cg->cg_flags & CG_FLAG_THREAD) == 0)
915176735Sjeff			thresh = steal_thresh;
916176735Sjeff		else
917176735Sjeff			thresh = 1;
918176735Sjeff		cpu = sched_highest(cg, mask, thresh);
919176735Sjeff		if (cpu == -1) {
920176735Sjeff			cg = cg->cg_parent;
921176735Sjeff			continue;
922166108Sjeff		}
923176735Sjeff		steal = TDQ_CPU(cpu);
924176735Sjeff		mask &= ~(1 << cpu);
925176735Sjeff		tdq_lock_pair(tdq, steal);
926176735Sjeff		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
927176735Sjeff			tdq_unlock_pair(tdq, steal);
928176735Sjeff			continue;
929171482Sjeff		}
930176735Sjeff		/*
931176735Sjeff		 * If a thread was added while interrupts were disabled don't
932176735Sjeff		 * steal one here.  If we fail to acquire one due to affinity
933176735Sjeff		 * restrictions loop again with this cpu removed from the
934176735Sjeff		 * set.
935176735Sjeff		 */
936176735Sjeff		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
937176735Sjeff			tdq_unlock_pair(tdq, steal);
938176735Sjeff			continue;
939176735Sjeff		}
940176735Sjeff		spinlock_exit();
941176735Sjeff		TDQ_UNLOCK(steal);
942178272Sjeff		mi_switch(SW_VOL | SWT_IDLE, NULL);
943176735Sjeff		thread_unlock(curthread);
944176735Sjeff
945176735Sjeff		return (0);
946123433Sjeff	}
947171482Sjeff	spinlock_exit();
948123433Sjeff	return (1);
949121790Sjeff}
950121790Sjeff
951171482Sjeff/*
952171482Sjeff * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
953171482Sjeff */
954121790Sjeffstatic void
955177435Sjefftdq_notify(struct tdq *tdq, struct thread *td)
956121790Sjeff{
957185047Sjhb	struct thread *ctd;
958166247Sjeff	int pri;
959166108Sjeff	int cpu;
960121790Sjeff
961177005Sjeff	if (tdq->tdq_ipipending)
962177005Sjeff		return;
963177435Sjeff	cpu = td->td_sched->ts_cpu;
964177435Sjeff	pri = td->td_priority;
965185047Sjhb	ctd = pcpu_find(cpu)->pc_curthread;
966185047Sjhb	if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
967166137Sjeff		return;
968185047Sjhb	if (TD_IS_IDLETHREAD(ctd)) {
969178277Sjeff		/*
970178471Sjeff		 * If the MD code has an idle wakeup routine try that before
971178471Sjeff		 * falling back to IPI.
972178471Sjeff		 */
973178471Sjeff		if (cpu_idle_wakeup(cpu))
974178471Sjeff			return;
975178277Sjeff	}
976177005Sjeff	tdq->tdq_ipipending = 1;
977171482Sjeff	ipi_selected(1 << cpu, IPI_PREEMPT);
978121790Sjeff}
979121790Sjeff
980171482Sjeff/*
981171482Sjeff * Steals load from a timeshare queue.  Honors the rotating queue head
982171482Sjeff * index.
983171482Sjeff */
984177435Sjeffstatic struct thread *
985176735Sjeffrunq_steal_from(struct runq *rq, int cpu, u_char start)
986171482Sjeff{
987171482Sjeff	struct rqbits *rqb;
988171482Sjeff	struct rqhead *rqh;
989177435Sjeff	struct thread *td;
990171482Sjeff	int first;
991171482Sjeff	int bit;
992171482Sjeff	int pri;
993171482Sjeff	int i;
994171482Sjeff
995171482Sjeff	rqb = &rq->rq_status;
996171482Sjeff	bit = start & (RQB_BPW -1);
997171482Sjeff	pri = 0;
998171482Sjeff	first = 0;
999171482Sjeffagain:
1000171482Sjeff	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1001171482Sjeff		if (rqb->rqb_bits[i] == 0)
1002171482Sjeff			continue;
1003171482Sjeff		if (bit != 0) {
1004171482Sjeff			for (pri = bit; pri < RQB_BPW; pri++)
1005171482Sjeff				if (rqb->rqb_bits[i] & (1ul << pri))
1006171482Sjeff					break;
1007171482Sjeff			if (pri >= RQB_BPW)
1008171482Sjeff				continue;
1009171482Sjeff		} else
1010171482Sjeff			pri = RQB_FFS(rqb->rqb_bits[i]);
1011171482Sjeff		pri += (i << RQB_L2BPW);
1012171482Sjeff		rqh = &rq->rq_queues[pri];
1013177435Sjeff		TAILQ_FOREACH(td, rqh, td_runq) {
1014177435Sjeff			if (first && THREAD_CAN_MIGRATE(td) &&
1015177435Sjeff			    THREAD_CAN_SCHED(td, cpu))
1016177435Sjeff				return (td);
1017171482Sjeff			first = 1;
1018171482Sjeff		}
1019171482Sjeff	}
1020171482Sjeff	if (start != 0) {
1021171482Sjeff		start = 0;
1022171482Sjeff		goto again;
1023171482Sjeff	}
1024171482Sjeff
1025171482Sjeff	return (NULL);
1026171482Sjeff}
1027171482Sjeff
1028171482Sjeff/*
1029171482Sjeff * Steals load from a standard linear queue.
1030171482Sjeff */
1031177435Sjeffstatic struct thread *
1032176735Sjeffrunq_steal(struct runq *rq, int cpu)
1033121790Sjeff{
1034121790Sjeff	struct rqhead *rqh;
1035121790Sjeff	struct rqbits *rqb;
1036177435Sjeff	struct thread *td;
1037121790Sjeff	int word;
1038121790Sjeff	int bit;
1039121790Sjeff
1040121790Sjeff	rqb = &rq->rq_status;
1041121790Sjeff	for (word = 0; word < RQB_LEN; word++) {
1042121790Sjeff		if (rqb->rqb_bits[word] == 0)
1043121790Sjeff			continue;
1044121790Sjeff		for (bit = 0; bit < RQB_BPW; bit++) {
1045123231Speter			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
1046121790Sjeff				continue;
1047121790Sjeff			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
1048177435Sjeff			TAILQ_FOREACH(td, rqh, td_runq)
1049177435Sjeff				if (THREAD_CAN_MIGRATE(td) &&
1050177435Sjeff				    THREAD_CAN_SCHED(td, cpu))
1051177435Sjeff					return (td);
1052121790Sjeff		}
1053121790Sjeff	}
1054121790Sjeff	return (NULL);
1055121790Sjeff}
1056121790Sjeff
1057171482Sjeff/*
1058171482Sjeff * Attempt to steal a thread in priority order from a thread queue.
1059171482Sjeff */
1060177435Sjeffstatic struct thread *
1061176735Sjefftdq_steal(struct tdq *tdq, int cpu)
1062121790Sjeff{
1063177435Sjeff	struct thread *td;
1064121790Sjeff
1065171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1066177435Sjeff	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
1067177435Sjeff		return (td);
1068177435Sjeff	if ((td = runq_steal_from(&tdq->tdq_timeshare,
1069177435Sjeff	    cpu, tdq->tdq_ridx)) != NULL)
1070177435Sjeff		return (td);
1071176735Sjeff	return (runq_steal(&tdq->tdq_idle, cpu));
1072121790Sjeff}
1073123433Sjeff
1074171482Sjeff/*
1075171482Sjeff * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
1076172409Sjeff * current lock and returns with the assigned queue locked.
1077171482Sjeff */
1078171482Sjeffstatic inline struct tdq *
1079177435Sjeffsched_setcpu(struct thread *td, int cpu, int flags)
1080123433Sjeff{
1081177435Sjeff
1082171482Sjeff	struct tdq *tdq;
1083123433Sjeff
1084177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1085171482Sjeff	tdq = TDQ_CPU(cpu);
1086177435Sjeff	td->td_sched->ts_cpu = cpu;
1087177435Sjeff	/*
1088177435Sjeff	 * If the lock matches just return the queue.
1089177435Sjeff	 */
1090171482Sjeff	if (td->td_lock == TDQ_LOCKPTR(tdq))
1091171482Sjeff		return (tdq);
1092171482Sjeff#ifdef notyet
1093123433Sjeff	/*
1094172293Sjeff	 * If the thread isn't running its lockptr is a
1095171482Sjeff	 * turnstile or a sleepqueue.  We can just lock_set without
1096171482Sjeff	 * blocking.
1097123685Sjeff	 */
1098171482Sjeff	if (TD_CAN_RUN(td)) {
1099171482Sjeff		TDQ_LOCK(tdq);
1100171482Sjeff		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1101171482Sjeff		return (tdq);
1102171482Sjeff	}
1103171482Sjeff#endif
1104166108Sjeff	/*
1105171482Sjeff	 * The hard case, migration, we need to block the thread first to
1106171482Sjeff	 * prevent order reversals with other cpus locks.
1107166108Sjeff	 */
1108171482Sjeff	thread_lock_block(td);
1109171482Sjeff	TDQ_LOCK(tdq);
1110171713Sjeff	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1111171482Sjeff	return (tdq);
1112166108Sjeff}
1113166108Sjeff
1114178272SjeffSCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
1115178272SjeffSCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
1116178272SjeffSCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
1117178272SjeffSCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
1118178272SjeffSCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
1119178272SjeffSCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
1120178272Sjeff
1121166108Sjeffstatic int
1122177435Sjeffsched_pickcpu(struct thread *td, int flags)
1123171482Sjeff{
1124176735Sjeff	struct cpu_group *cg;
1125177435Sjeff	struct td_sched *ts;
1126171482Sjeff	struct tdq *tdq;
1127176735Sjeff	cpumask_t mask;
1128166108Sjeff	int self;
1129166108Sjeff	int pri;
1130166108Sjeff	int cpu;
1131166108Sjeff
1132176735Sjeff	self = PCPU_GET(cpuid);
1133177435Sjeff	ts = td->td_sched;
1134166108Sjeff	if (smp_started == 0)
1135166108Sjeff		return (self);
1136171506Sjeff	/*
1137171506Sjeff	 * Don't migrate a running thread from sched_switch().
1138171506Sjeff	 */
1139176735Sjeff	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1140176735Sjeff		return (ts->ts_cpu);
1141166108Sjeff	/*
1142176735Sjeff	 * Prefer to run interrupt threads on the processors that generate
1143176735Sjeff	 * the interrupt.
1144166108Sjeff	 */
1145176735Sjeff	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1146178272Sjeff	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
1147178272Sjeff		SCHED_STAT_INC(pickcpu_intrbind);
1148176735Sjeff		ts->ts_cpu = self;
1149178272Sjeff	}
1150166108Sjeff	/*
1151176735Sjeff	 * If the thread can run on the last cpu and the affinity has not
1152176735Sjeff	 * expired or it is idle run it there.
1153166108Sjeff	 */
1154176735Sjeff	pri = td->td_priority;
1155176735Sjeff	tdq = TDQ_CPU(ts->ts_cpu);
1156176735Sjeff	if (THREAD_CAN_SCHED(td, ts->ts_cpu)) {
1157178272Sjeff		if (tdq->tdq_lowpri > PRI_MIN_IDLE) {
1158178272Sjeff			SCHED_STAT_INC(pickcpu_idle_affinity);
1159176735Sjeff			return (ts->ts_cpu);
1160178272Sjeff		}
1161178272Sjeff		if (SCHED_AFFINITY(ts, CG_SHARE_L2) && tdq->tdq_lowpri > pri) {
1162178272Sjeff			SCHED_STAT_INC(pickcpu_affinity);
1163176735Sjeff			return (ts->ts_cpu);
1164178272Sjeff		}
1165139334Sjeff	}
1166123433Sjeff	/*
1167176735Sjeff	 * Search for the highest level in the tree that still has affinity.
1168123433Sjeff	 */
1169176735Sjeff	cg = NULL;
1170176735Sjeff	for (cg = tdq->tdq_cg; cg != NULL; cg = cg->cg_parent)
1171176735Sjeff		if (SCHED_AFFINITY(ts, cg->cg_level))
1172176735Sjeff			break;
1173176735Sjeff	cpu = -1;
1174176735Sjeff	mask = td->td_cpuset->cs_mask.__bits[0];
1175176735Sjeff	if (cg)
1176176735Sjeff		cpu = sched_lowest(cg, mask, pri);
1177176735Sjeff	if (cpu == -1)
1178176735Sjeff		cpu = sched_lowest(cpu_top, mask, -1);
1179171506Sjeff	/*
1180176735Sjeff	 * Compare the lowest loaded cpu to current cpu.
1181171506Sjeff	 */
1182177005Sjeff	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
1183178272Sjeff	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE) {
1184178272Sjeff		SCHED_STAT_INC(pickcpu_local);
1185177005Sjeff		cpu = self;
1186178272Sjeff	} else
1187178272Sjeff		SCHED_STAT_INC(pickcpu_lowest);
1188178272Sjeff	if (cpu != ts->ts_cpu)
1189178272Sjeff		SCHED_STAT_INC(pickcpu_migration);
1190177005Sjeff	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1191171482Sjeff	return (cpu);
1192123433Sjeff}
1193176735Sjeff#endif
1194123433Sjeff
1195117326Sjeff/*
1196121790Sjeff * Pick the highest priority task we have and return it.
1197117326Sjeff */
1198177435Sjeffstatic struct thread *
1199164936Sjuliantdq_choose(struct tdq *tdq)
1200110267Sjeff{
1201177435Sjeff	struct thread *td;
1202110267Sjeff
1203171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1204177435Sjeff	td = runq_choose(&tdq->tdq_realtime);
1205177435Sjeff	if (td != NULL)
1206177435Sjeff		return (td);
1207177435Sjeff	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1208177435Sjeff	if (td != NULL) {
1209177435Sjeff		KASSERT(td->td_priority >= PRI_MIN_TIMESHARE,
1210165762Sjeff		    ("tdq_choose: Invalid priority on timeshare queue %d",
1211177435Sjeff		    td->td_priority));
1212177435Sjeff		return (td);
1213165762Sjeff	}
1214177435Sjeff	td = runq_choose(&tdq->tdq_idle);
1215177435Sjeff	if (td != NULL) {
1216177435Sjeff		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1217165762Sjeff		    ("tdq_choose: Invalid priority on idle queue %d",
1218177435Sjeff		    td->td_priority));
1219177435Sjeff		return (td);
1220165762Sjeff	}
1221165762Sjeff
1222165762Sjeff	return (NULL);
1223110267Sjeff}
1224110267Sjeff
1225171482Sjeff/*
1226171482Sjeff * Initialize a thread queue.
1227171482Sjeff */
1228109864Sjeffstatic void
1229164936Sjuliantdq_setup(struct tdq *tdq)
1230110028Sjeff{
1231171482Sjeff
1232171713Sjeff	if (bootverbose)
1233171713Sjeff		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1234165762Sjeff	runq_init(&tdq->tdq_realtime);
1235165762Sjeff	runq_init(&tdq->tdq_timeshare);
1236165620Sjeff	runq_init(&tdq->tdq_idle);
1237176735Sjeff	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1238176735Sjeff	    "sched lock %d", (int)TDQ_ID(tdq));
1239176735Sjeff	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1240176735Sjeff	    MTX_SPIN | MTX_RECURSE);
1241187357Sjeff#ifdef KTR
1242187357Sjeff	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
1243187357Sjeff	    "CPU %d load", (int)TDQ_ID(tdq));
1244187357Sjeff#endif
1245110028Sjeff}
1246110028Sjeff
1247171713Sjeff#ifdef SMP
1248110028Sjeffstatic void
1249171713Sjeffsched_setup_smp(void)
1250171713Sjeff{
1251171713Sjeff	struct tdq *tdq;
1252171713Sjeff	int i;
1253171713Sjeff
1254176735Sjeff	cpu_top = smp_topo();
1255176735Sjeff	for (i = 0; i < MAXCPU; i++) {
1256171713Sjeff		if (CPU_ABSENT(i))
1257171713Sjeff			continue;
1258176735Sjeff		tdq = TDQ_CPU(i);
1259171713Sjeff		tdq_setup(tdq);
1260176735Sjeff		tdq->tdq_cg = smp_topo_find(cpu_top, i);
1261176735Sjeff		if (tdq->tdq_cg == NULL)
1262176735Sjeff			panic("Can't find cpu group for %d\n", i);
1263123433Sjeff	}
1264176735Sjeff	balance_tdq = TDQ_SELF();
1265176735Sjeff	sched_balance();
1266171713Sjeff}
1267171713Sjeff#endif
1268171713Sjeff
1269171713Sjeff/*
1270171713Sjeff * Setup the thread queues and initialize the topology based on MD
1271171713Sjeff * information.
1272171713Sjeff */
1273171713Sjeffstatic void
1274171713Sjeffsched_setup(void *dummy)
1275171713Sjeff{
1276171713Sjeff	struct tdq *tdq;
1277171713Sjeff
1278171713Sjeff	tdq = TDQ_SELF();
1279171713Sjeff#ifdef SMP
1280176734Sjeff	sched_setup_smp();
1281117237Sjeff#else
1282171713Sjeff	tdq_setup(tdq);
1283116069Sjeff#endif
1284171482Sjeff	/*
1285171482Sjeff	 * To avoid divide-by-zero, we set realstathz a dummy value
1286171482Sjeff	 * in case which sched_clock() called before sched_initticks().
1287171482Sjeff	 */
1288171482Sjeff	realstathz = hz;
1289171482Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1290171482Sjeff	tickincr = 1 << SCHED_TICK_SHIFT;
1291171482Sjeff
1292171482Sjeff	/* Add thread0's load since it's running. */
1293171482Sjeff	TDQ_LOCK(tdq);
1294171713Sjeff	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1295177435Sjeff	tdq_load_add(tdq, &thread0);
1296176735Sjeff	tdq->tdq_lowpri = thread0.td_priority;
1297171482Sjeff	TDQ_UNLOCK(tdq);
1298109864Sjeff}
1299109864Sjeff
1300171482Sjeff/*
1301171482Sjeff * This routine determines the tickincr after stathz and hz are setup.
1302171482Sjeff */
1303153533Sdavidxu/* ARGSUSED */
1304153533Sdavidxustatic void
1305153533Sdavidxusched_initticks(void *dummy)
1306153533Sdavidxu{
1307171482Sjeff	int incr;
1308171482Sjeff
1309153533Sdavidxu	realstathz = stathz ? stathz : hz;
1310166229Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1311153533Sdavidxu
1312153533Sdavidxu	/*
1313165762Sjeff	 * tickincr is shifted out by 10 to avoid rounding errors due to
1314165766Sjeff	 * hz not being evenly divisible by stathz on all platforms.
1315153533Sdavidxu	 */
1316171482Sjeff	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1317165762Sjeff	/*
1318165762Sjeff	 * This does not work for values of stathz that are more than
1319165762Sjeff	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1320165762Sjeff	 */
1321171482Sjeff	if (incr == 0)
1322171482Sjeff		incr = 1;
1323171482Sjeff	tickincr = incr;
1324166108Sjeff#ifdef SMP
1325171899Sjeff	/*
1326172409Sjeff	 * Set the default balance interval now that we know
1327172409Sjeff	 * what realstathz is.
1328172409Sjeff	 */
1329172409Sjeff	balance_interval = realstathz;
1330172409Sjeff	/*
1331189787Sjeff	 * Set steal thresh to roughly log2(mp_ncpu) but no greater than 4.
1332189787Sjeff	 * This prevents excess thrashing on large machines and excess idle
1333189787Sjeff	 * on smaller machines.
1334171899Sjeff	 */
1335189787Sjeff	steal_thresh = min(fls(mp_ncpus) - 1, 3);
1336166108Sjeff	affinity = SCHED_AFFINITY_DEFAULT;
1337166108Sjeff#endif
1338153533Sdavidxu}
1339153533Sdavidxu
1340153533Sdavidxu
1341109864Sjeff/*
1342171482Sjeff * This is the core of the interactivity algorithm.  Determines a score based
1343171482Sjeff * on past behavior.  It is the ratio of sleep time to run time scaled to
1344171482Sjeff * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1345171482Sjeff * differs from the cpu usage because it does not account for time spent
1346171482Sjeff * waiting on a run-queue.  Would be prettier if we had floating point.
1347171482Sjeff */
1348171482Sjeffstatic int
1349171482Sjeffsched_interact_score(struct thread *td)
1350171482Sjeff{
1351171482Sjeff	struct td_sched *ts;
1352171482Sjeff	int div;
1353171482Sjeff
1354171482Sjeff	ts = td->td_sched;
1355171482Sjeff	/*
1356171482Sjeff	 * The score is only needed if this is likely to be an interactive
1357171482Sjeff	 * task.  Don't go through the expense of computing it if there's
1358171482Sjeff	 * no chance.
1359171482Sjeff	 */
1360171482Sjeff	if (sched_interact <= SCHED_INTERACT_HALF &&
1361171482Sjeff		ts->ts_runtime >= ts->ts_slptime)
1362171482Sjeff			return (SCHED_INTERACT_HALF);
1363171482Sjeff
1364171482Sjeff	if (ts->ts_runtime > ts->ts_slptime) {
1365171482Sjeff		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1366171482Sjeff		return (SCHED_INTERACT_HALF +
1367171482Sjeff		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1368171482Sjeff	}
1369171482Sjeff	if (ts->ts_slptime > ts->ts_runtime) {
1370171482Sjeff		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1371171482Sjeff		return (ts->ts_runtime / div);
1372171482Sjeff	}
1373171482Sjeff	/* runtime == slptime */
1374171482Sjeff	if (ts->ts_runtime)
1375171482Sjeff		return (SCHED_INTERACT_HALF);
1376171482Sjeff
1377171482Sjeff	/*
1378171482Sjeff	 * This can happen if slptime and runtime are 0.
1379171482Sjeff	 */
1380171482Sjeff	return (0);
1381171482Sjeff
1382171482Sjeff}
1383171482Sjeff
1384171482Sjeff/*
1385109864Sjeff * Scale the scheduling priority according to the "interactivity" of this
1386109864Sjeff * process.
1387109864Sjeff */
1388113357Sjeffstatic void
1389163709Sjbsched_priority(struct thread *td)
1390109864Sjeff{
1391165762Sjeff	int score;
1392109864Sjeff	int pri;
1393109864Sjeff
1394163709Sjb	if (td->td_pri_class != PRI_TIMESHARE)
1395113357Sjeff		return;
1396112966Sjeff	/*
1397165762Sjeff	 * If the score is interactive we place the thread in the realtime
1398165762Sjeff	 * queue with a priority that is less than kernel and interrupt
1399165762Sjeff	 * priorities.  These threads are not subject to nice restrictions.
1400112966Sjeff	 *
1401171482Sjeff	 * Scores greater than this are placed on the normal timeshare queue
1402165762Sjeff	 * where the priority is partially decided by the most recent cpu
1403165762Sjeff	 * utilization and the rest is decided by nice value.
1404172293Sjeff	 *
1405172293Sjeff	 * The nice value of the process has a linear effect on the calculated
1406172293Sjeff	 * score.  Negative nice values make it easier for a thread to be
1407172293Sjeff	 * considered interactive.
1408112966Sjeff	 */
1409172308Sjeff	score = imax(0, sched_interact_score(td) - td->td_proc->p_nice);
1410165762Sjeff	if (score < sched_interact) {
1411165762Sjeff		pri = PRI_MIN_REALTIME;
1412165762Sjeff		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1413165762Sjeff		    * score;
1414165762Sjeff		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1415166208Sjeff		    ("sched_priority: invalid interactive priority %d score %d",
1416166208Sjeff		    pri, score));
1417165762Sjeff	} else {
1418165762Sjeff		pri = SCHED_PRI_MIN;
1419165762Sjeff		if (td->td_sched->ts_ticks)
1420165762Sjeff			pri += SCHED_PRI_TICKS(td->td_sched);
1421165762Sjeff		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1422171482Sjeff		KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1423171482Sjeff		    ("sched_priority: invalid priority %d: nice %d, "
1424171482Sjeff		    "ticks %d ftick %d ltick %d tick pri %d",
1425171482Sjeff		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1426171482Sjeff		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1427171482Sjeff		    SCHED_PRI_TICKS(td->td_sched)));
1428165762Sjeff	}
1429165762Sjeff	sched_user_prio(td, pri);
1430112966Sjeff
1431112966Sjeff	return;
1432109864Sjeff}
1433109864Sjeff
1434121868Sjeff/*
1435121868Sjeff * This routine enforces a maximum limit on the amount of scheduling history
1436171482Sjeff * kept.  It is called after either the slptime or runtime is adjusted.  This
1437171482Sjeff * function is ugly due to integer math.
1438121868Sjeff */
1439116463Sjeffstatic void
1440163709Sjbsched_interact_update(struct thread *td)
1441116463Sjeff{
1442165819Sjeff	struct td_sched *ts;
1443166208Sjeff	u_int sum;
1444121605Sjeff
1445165819Sjeff	ts = td->td_sched;
1446171482Sjeff	sum = ts->ts_runtime + ts->ts_slptime;
1447121868Sjeff	if (sum < SCHED_SLP_RUN_MAX)
1448121868Sjeff		return;
1449121868Sjeff	/*
1450165819Sjeff	 * This only happens from two places:
1451165819Sjeff	 * 1) We have added an unusual amount of run time from fork_exit.
1452165819Sjeff	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1453165819Sjeff	 */
1454165819Sjeff	if (sum > SCHED_SLP_RUN_MAX * 2) {
1455171482Sjeff		if (ts->ts_runtime > ts->ts_slptime) {
1456171482Sjeff			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1457171482Sjeff			ts->ts_slptime = 1;
1458165819Sjeff		} else {
1459171482Sjeff			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1460171482Sjeff			ts->ts_runtime = 1;
1461165819Sjeff		}
1462165819Sjeff		return;
1463165819Sjeff	}
1464165819Sjeff	/*
1465121868Sjeff	 * If we have exceeded by more than 1/5th then the algorithm below
1466121868Sjeff	 * will not bring us back into range.  Dividing by two here forces
1467133427Sjeff	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1468121868Sjeff	 */
1469127850Sjeff	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1470171482Sjeff		ts->ts_runtime /= 2;
1471171482Sjeff		ts->ts_slptime /= 2;
1472121868Sjeff		return;
1473116463Sjeff	}
1474171482Sjeff	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1475171482Sjeff	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1476116463Sjeff}
1477116463Sjeff
1478171482Sjeff/*
1479171482Sjeff * Scale back the interactivity history when a child thread is created.  The
1480171482Sjeff * history is inherited from the parent but the thread may behave totally
1481171482Sjeff * differently.  For example, a shell spawning a compiler process.  We want
1482171482Sjeff * to learn that the compiler is behaving badly very quickly.
1483171482Sjeff */
1484121868Sjeffstatic void
1485163709Sjbsched_interact_fork(struct thread *td)
1486121868Sjeff{
1487121868Sjeff	int ratio;
1488121868Sjeff	int sum;
1489121868Sjeff
1490171482Sjeff	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1491121868Sjeff	if (sum > SCHED_SLP_RUN_FORK) {
1492121868Sjeff		ratio = sum / SCHED_SLP_RUN_FORK;
1493171482Sjeff		td->td_sched->ts_runtime /= ratio;
1494171482Sjeff		td->td_sched->ts_slptime /= ratio;
1495121868Sjeff	}
1496121868Sjeff}
1497121868Sjeff
1498113357Sjeff/*
1499171482Sjeff * Called from proc0_init() to setup the scheduler fields.
1500134791Sjulian */
1501134791Sjulianvoid
1502134791Sjulianschedinit(void)
1503134791Sjulian{
1504165762Sjeff
1505134791Sjulian	/*
1506134791Sjulian	 * Set up the scheduler specific parts of proc0.
1507134791Sjulian	 */
1508136167Sjulian	proc0.p_sched = NULL; /* XXX */
1509164936Sjulian	thread0.td_sched = &td_sched0;
1510165762Sjeff	td_sched0.ts_ltick = ticks;
1511165796Sjeff	td_sched0.ts_ftick = ticks;
1512177009Sjeff	td_sched0.ts_slice = sched_slice;
1513134791Sjulian}
1514134791Sjulian
1515134791Sjulian/*
1516113357Sjeff * This is only somewhat accurate since given many processes of the same
1517113357Sjeff * priority they will switch when their slices run out, which will be
1518165762Sjeff * at most sched_slice stathz ticks.
1519113357Sjeff */
1520109864Sjeffint
1521109864Sjeffsched_rr_interval(void)
1522109864Sjeff{
1523165762Sjeff
1524165762Sjeff	/* Convert sched_slice to hz */
1525165762Sjeff	return (hz/(realstathz/sched_slice));
1526109864Sjeff}
1527109864Sjeff
1528171482Sjeff/*
1529171482Sjeff * Update the percent cpu tracking information when it is requested or
1530171482Sjeff * the total history exceeds the maximum.  We keep a sliding history of
1531171482Sjeff * tick counts that slowly decays.  This is less precise than the 4BSD
1532171482Sjeff * mechanism since it happens with less regular and frequent events.
1533171482Sjeff */
1534121790Sjeffstatic void
1535164936Sjuliansched_pctcpu_update(struct td_sched *ts)
1536109864Sjeff{
1537165762Sjeff
1538165762Sjeff	if (ts->ts_ticks == 0)
1539165762Sjeff		return;
1540165796Sjeff	if (ticks - (hz / 10) < ts->ts_ltick &&
1541165796Sjeff	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1542165796Sjeff		return;
1543109864Sjeff	/*
1544109864Sjeff	 * Adjust counters and watermark for pctcpu calc.
1545116365Sjeff	 */
1546165762Sjeff	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1547164936Sjulian		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1548165762Sjeff			    SCHED_TICK_TARG;
1549165762Sjeff	else
1550164936Sjulian		ts->ts_ticks = 0;
1551164936Sjulian	ts->ts_ltick = ticks;
1552165762Sjeff	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1553109864Sjeff}
1554109864Sjeff
1555171482Sjeff/*
1556171482Sjeff * Adjust the priority of a thread.  Move it to the appropriate run-queue
1557171482Sjeff * if necessary.  This is the back-end for several priority related
1558171482Sjeff * functions.
1559171482Sjeff */
1560165762Sjeffstatic void
1561139453Sjhbsched_thread_priority(struct thread *td, u_char prio)
1562109864Sjeff{
1563164936Sjulian	struct td_sched *ts;
1564177009Sjeff	struct tdq *tdq;
1565177009Sjeff	int oldpri;
1566109864Sjeff
1567187357Sjeff	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
1568187357Sjeff	    "prio:%d", td->td_priority, "new prio:%d", prio,
1569187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(curthread));
1570187357Sjeff	if (td != curthread && prio > td->td_priority) {
1571187357Sjeff		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
1572187357Sjeff		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
1573187357Sjeff		    prio, KTR_ATTR_LINKED, sched_tdname(td));
1574187357Sjeff	}
1575164936Sjulian	ts = td->td_sched;
1576170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1577139453Sjhb	if (td->td_priority == prio)
1578139453Sjhb		return;
1579177376Sjeff	/*
1580177376Sjeff	 * If the priority has been elevated due to priority
1581177376Sjeff	 * propagation, we may have to move ourselves to a new
1582177376Sjeff	 * queue.  This could be optimized to not re-add in some
1583177376Sjeff	 * cases.
1584177376Sjeff	 */
1585165766Sjeff	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1586165762Sjeff		sched_rem(td);
1587165762Sjeff		td->td_priority = prio;
1588171482Sjeff		sched_add(td, SRQ_BORROWING);
1589177009Sjeff		return;
1590177009Sjeff	}
1591177376Sjeff	/*
1592177376Sjeff	 * If the thread is currently running we may have to adjust the lowpri
1593177376Sjeff	 * information so other cpus are aware of our current priority.
1594177376Sjeff	 */
1595177009Sjeff	if (TD_IS_RUNNING(td)) {
1596177376Sjeff		tdq = TDQ_CPU(ts->ts_cpu);
1597177376Sjeff		oldpri = td->td_priority;
1598177376Sjeff		td->td_priority = prio;
1599176735Sjeff		if (prio < tdq->tdq_lowpri)
1600171482Sjeff			tdq->tdq_lowpri = prio;
1601176735Sjeff		else if (tdq->tdq_lowpri == oldpri)
1602176735Sjeff			tdq_setlowpri(tdq, td);
1603177376Sjeff		return;
1604177009Sjeff	}
1605177376Sjeff	td->td_priority = prio;
1606109864Sjeff}
1607109864Sjeff
1608139453Sjhb/*
1609139453Sjhb * Update a thread's priority when it is lent another thread's
1610139453Sjhb * priority.
1611139453Sjhb */
1612109864Sjeffvoid
1613139453Sjhbsched_lend_prio(struct thread *td, u_char prio)
1614139453Sjhb{
1615139453Sjhb
1616139453Sjhb	td->td_flags |= TDF_BORROWING;
1617139453Sjhb	sched_thread_priority(td, prio);
1618139453Sjhb}
1619139453Sjhb
1620139453Sjhb/*
1621139453Sjhb * Restore a thread's priority when priority propagation is
1622139453Sjhb * over.  The prio argument is the minimum priority the thread
1623139453Sjhb * needs to have to satisfy other possible priority lending
1624139453Sjhb * requests.  If the thread's regular priority is less
1625139453Sjhb * important than prio, the thread will keep a priority boost
1626139453Sjhb * of prio.
1627139453Sjhb */
1628139453Sjhbvoid
1629139453Sjhbsched_unlend_prio(struct thread *td, u_char prio)
1630139453Sjhb{
1631139453Sjhb	u_char base_pri;
1632139453Sjhb
1633139453Sjhb	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1634139453Sjhb	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1635163709Sjb		base_pri = td->td_user_pri;
1636139453Sjhb	else
1637139453Sjhb		base_pri = td->td_base_pri;
1638139453Sjhb	if (prio >= base_pri) {
1639139455Sjhb		td->td_flags &= ~TDF_BORROWING;
1640139453Sjhb		sched_thread_priority(td, base_pri);
1641139453Sjhb	} else
1642139453Sjhb		sched_lend_prio(td, prio);
1643139453Sjhb}
1644139453Sjhb
1645171482Sjeff/*
1646171482Sjeff * Standard entry for setting the priority to an absolute value.
1647171482Sjeff */
1648139453Sjhbvoid
1649139453Sjhbsched_prio(struct thread *td, u_char prio)
1650139453Sjhb{
1651139453Sjhb	u_char oldprio;
1652139453Sjhb
1653139453Sjhb	/* First, update the base priority. */
1654139453Sjhb	td->td_base_pri = prio;
1655139453Sjhb
1656139453Sjhb	/*
1657139455Sjhb	 * If the thread is borrowing another thread's priority, don't
1658139453Sjhb	 * ever lower the priority.
1659139453Sjhb	 */
1660139453Sjhb	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1661139453Sjhb		return;
1662139453Sjhb
1663139453Sjhb	/* Change the real priority. */
1664139453Sjhb	oldprio = td->td_priority;
1665139453Sjhb	sched_thread_priority(td, prio);
1666139453Sjhb
1667139453Sjhb	/*
1668139453Sjhb	 * If the thread is on a turnstile, then let the turnstile update
1669139453Sjhb	 * its state.
1670139453Sjhb	 */
1671139453Sjhb	if (TD_ON_LOCK(td) && oldprio != prio)
1672139453Sjhb		turnstile_adjust(td, oldprio);
1673139453Sjhb}
1674139455Sjhb
1675171482Sjeff/*
1676171482Sjeff * Set the base user priority, does not effect current running priority.
1677171482Sjeff */
1678139453Sjhbvoid
1679163709Sjbsched_user_prio(struct thread *td, u_char prio)
1680161599Sdavidxu{
1681161599Sdavidxu	u_char oldprio;
1682161599Sdavidxu
1683163709Sjb	td->td_base_user_pri = prio;
1684164939Sjulian	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1685164939Sjulian                return;
1686163709Sjb	oldprio = td->td_user_pri;
1687163709Sjb	td->td_user_pri = prio;
1688161599Sdavidxu}
1689161599Sdavidxu
1690161599Sdavidxuvoid
1691161599Sdavidxusched_lend_user_prio(struct thread *td, u_char prio)
1692161599Sdavidxu{
1693161599Sdavidxu	u_char oldprio;
1694161599Sdavidxu
1695174536Sdavidxu	THREAD_LOCK_ASSERT(td, MA_OWNED);
1696161599Sdavidxu	td->td_flags |= TDF_UBORROWING;
1697164091Smaxim	oldprio = td->td_user_pri;
1698163709Sjb	td->td_user_pri = prio;
1699161599Sdavidxu}
1700161599Sdavidxu
1701161599Sdavidxuvoid
1702161599Sdavidxusched_unlend_user_prio(struct thread *td, u_char prio)
1703161599Sdavidxu{
1704161599Sdavidxu	u_char base_pri;
1705161599Sdavidxu
1706174536Sdavidxu	THREAD_LOCK_ASSERT(td, MA_OWNED);
1707163709Sjb	base_pri = td->td_base_user_pri;
1708161599Sdavidxu	if (prio >= base_pri) {
1709161599Sdavidxu		td->td_flags &= ~TDF_UBORROWING;
1710163709Sjb		sched_user_prio(td, base_pri);
1711174536Sdavidxu	} else {
1712161599Sdavidxu		sched_lend_user_prio(td, prio);
1713174536Sdavidxu	}
1714161599Sdavidxu}
1715161599Sdavidxu
1716171482Sjeff/*
1717174847Swkoszek * Block a thread for switching.  Similar to thread_block() but does not
1718174847Swkoszek * bump the spin count.
1719174847Swkoszek */
1720174847Swkoszekstatic inline struct mtx *
1721174847Swkoszekthread_block_switch(struct thread *td)
1722174847Swkoszek{
1723174847Swkoszek	struct mtx *lock;
1724174847Swkoszek
1725174847Swkoszek	THREAD_LOCK_ASSERT(td, MA_OWNED);
1726174847Swkoszek	lock = td->td_lock;
1727174847Swkoszek	td->td_lock = &blocked_lock;
1728174847Swkoszek	mtx_unlock_spin(lock);
1729174847Swkoszek
1730174847Swkoszek	return (lock);
1731174847Swkoszek}
1732174847Swkoszek
1733174847Swkoszek/*
1734171713Sjeff * Handle migration from sched_switch().  This happens only for
1735171713Sjeff * cpu binding.
1736171713Sjeff */
1737171713Sjeffstatic struct mtx *
1738171713Sjeffsched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1739171713Sjeff{
1740171713Sjeff	struct tdq *tdn;
1741171713Sjeff
1742171713Sjeff	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1743171713Sjeff#ifdef SMP
1744177435Sjeff	tdq_load_rem(tdq, td);
1745171713Sjeff	/*
1746171713Sjeff	 * Do the lock dance required to avoid LOR.  We grab an extra
1747171713Sjeff	 * spinlock nesting to prevent preemption while we're
1748171713Sjeff	 * not holding either run-queue lock.
1749171713Sjeff	 */
1750171713Sjeff	spinlock_enter();
1751171713Sjeff	thread_block_switch(td);	/* This releases the lock on tdq. */
1752171713Sjeff	TDQ_LOCK(tdn);
1753171713Sjeff	tdq_add(tdn, td, flags);
1754177435Sjeff	tdq_notify(tdn, td);
1755171713Sjeff	/*
1756171713Sjeff	 * After we unlock tdn the new cpu still can't switch into this
1757171713Sjeff	 * thread until we've unblocked it in cpu_switch().  The lock
1758171713Sjeff	 * pointers may match in the case of HTT cores.  Don't unlock here
1759171713Sjeff	 * or we can deadlock when the other CPU runs the IPI handler.
1760171713Sjeff	 */
1761171713Sjeff	if (TDQ_LOCKPTR(tdn) != TDQ_LOCKPTR(tdq)) {
1762171713Sjeff		TDQ_UNLOCK(tdn);
1763171713Sjeff		TDQ_LOCK(tdq);
1764171713Sjeff	}
1765171713Sjeff	spinlock_exit();
1766171713Sjeff#endif
1767171713Sjeff	return (TDQ_LOCKPTR(tdn));
1768171713Sjeff}
1769171713Sjeff
1770171713Sjeff/*
1771171482Sjeff * Release a thread that was blocked with thread_block_switch().
1772171482Sjeff */
1773171482Sjeffstatic inline void
1774171482Sjeffthread_unblock_switch(struct thread *td, struct mtx *mtx)
1775171482Sjeff{
1776171482Sjeff	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1777171482Sjeff	    (uintptr_t)mtx);
1778171482Sjeff}
1779171482Sjeff
1780171482Sjeff/*
1781171482Sjeff * Switch threads.  This function has to handle threads coming in while
1782171482Sjeff * blocked for some reason, running, or idle.  It also must deal with
1783171482Sjeff * migrating a thread from one queue to another as running threads may
1784171482Sjeff * be assigned elsewhere via binding.
1785171482Sjeff */
1786161599Sdavidxuvoid
1787135051Sjuliansched_switch(struct thread *td, struct thread *newtd, int flags)
1788109864Sjeff{
1789165627Sjeff	struct tdq *tdq;
1790164936Sjulian	struct td_sched *ts;
1791171482Sjeff	struct mtx *mtx;
1792171713Sjeff	int srqflag;
1793171482Sjeff	int cpuid;
1794109864Sjeff
1795170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1796177376Sjeff	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
1797109864Sjeff
1798171482Sjeff	cpuid = PCPU_GET(cpuid);
1799171482Sjeff	tdq = TDQ_CPU(cpuid);
1800164936Sjulian	ts = td->td_sched;
1801171713Sjeff	mtx = td->td_lock;
1802171482Sjeff	ts->ts_rltick = ticks;
1803133555Sjeff	td->td_lastcpu = td->td_oncpu;
1804113339Sjulian	td->td_oncpu = NOCPU;
1805132266Sjhb	td->td_flags &= ~TDF_NEEDRESCHED;
1806144777Sups	td->td_owepreempt = 0;
1807178277Sjeff	tdq->tdq_switchcnt++;
1808123434Sjeff	/*
1809171482Sjeff	 * The lock pointer in an idle thread should never change.  Reset it
1810171482Sjeff	 * to CAN_RUN as well.
1811123434Sjeff	 */
1812167327Sjulian	if (TD_IS_IDLETHREAD(td)) {
1813171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1814139334Sjeff		TD_SET_CAN_RUN(td);
1815170293Sjeff	} else if (TD_IS_RUNNING(td)) {
1816171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1817171713Sjeff		srqflag = (flags & SW_PREEMPT) ?
1818170293Sjeff		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1819171713Sjeff		    SRQ_OURSELF|SRQ_YIELDING;
1820171713Sjeff		if (ts->ts_cpu == cpuid)
1821177435Sjeff			tdq_runq_add(tdq, td, srqflag);
1822171713Sjeff		else
1823171713Sjeff			mtx = sched_switch_migrate(tdq, td, srqflag);
1824171482Sjeff	} else {
1825171482Sjeff		/* This thread must be going to sleep. */
1826171482Sjeff		TDQ_LOCK(tdq);
1827171482Sjeff		mtx = thread_block_switch(td);
1828177435Sjeff		tdq_load_rem(tdq, td);
1829171482Sjeff	}
1830171482Sjeff	/*
1831171482Sjeff	 * We enter here with the thread blocked and assigned to the
1832171482Sjeff	 * appropriate cpu run-queue or sleep-queue and with the current
1833171482Sjeff	 * thread-queue locked.
1834171482Sjeff	 */
1835171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1836171482Sjeff	newtd = choosethread();
1837171482Sjeff	/*
1838171482Sjeff	 * Call the MD code to switch contexts if necessary.
1839171482Sjeff	 */
1840145256Sjkoshy	if (td != newtd) {
1841145256Sjkoshy#ifdef	HWPMC_HOOKS
1842145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1843145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1844145256Sjkoshy#endif
1845174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1846172411Sjeff		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1847179297Sjb
1848179297Sjb#ifdef KDTRACE_HOOKS
1849179297Sjb		/*
1850179297Sjb		 * If DTrace has set the active vtime enum to anything
1851179297Sjb		 * other than INACTIVE (0), then it should have set the
1852179297Sjb		 * function to call.
1853179297Sjb		 */
1854179297Sjb		if (dtrace_vtime_active)
1855179297Sjb			(*dtrace_vtime_switch_func)(newtd);
1856179297Sjb#endif
1857179297Sjb
1858171482Sjeff		cpu_switch(td, newtd, mtx);
1859171482Sjeff		/*
1860171482Sjeff		 * We may return from cpu_switch on a different cpu.  However,
1861171482Sjeff		 * we always return with td_lock pointing to the current cpu's
1862171482Sjeff		 * run queue lock.
1863171482Sjeff		 */
1864171482Sjeff		cpuid = PCPU_GET(cpuid);
1865171482Sjeff		tdq = TDQ_CPU(cpuid);
1866174629Sjeff		lock_profile_obtain_lock_success(
1867174629Sjeff		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1868145256Sjkoshy#ifdef	HWPMC_HOOKS
1869145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1870145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1871145256Sjkoshy#endif
1872171482Sjeff	} else
1873171482Sjeff		thread_unblock_switch(td, mtx);
1874171482Sjeff	/*
1875171482Sjeff	 * Assert that all went well and return.
1876171482Sjeff	 */
1877171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1878171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1879171482Sjeff	td->td_oncpu = cpuid;
1880109864Sjeff}
1881109864Sjeff
1882171482Sjeff/*
1883171482Sjeff * Adjust thread priorities as a result of a nice request.
1884171482Sjeff */
1885109864Sjeffvoid
1886130551Sjuliansched_nice(struct proc *p, int nice)
1887109864Sjeff{
1888109864Sjeff	struct thread *td;
1889109864Sjeff
1890130551Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
1891165762Sjeff
1892130551Sjulian	p->p_nice = nice;
1893163709Sjb	FOREACH_THREAD_IN_PROC(p, td) {
1894170293Sjeff		thread_lock(td);
1895163709Sjb		sched_priority(td);
1896165762Sjeff		sched_prio(td, td->td_base_user_pri);
1897170293Sjeff		thread_unlock(td);
1898130551Sjulian	}
1899109864Sjeff}
1900109864Sjeff
1901171482Sjeff/*
1902171482Sjeff * Record the sleep time for the interactivity scorer.
1903171482Sjeff */
1904109864Sjeffvoid
1905177085Sjeffsched_sleep(struct thread *td, int prio)
1906109864Sjeff{
1907165762Sjeff
1908170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1909109864Sjeff
1910172264Sjeff	td->td_slptick = ticks;
1911177085Sjeff	if (TD_IS_SUSPENDED(td) || prio <= PSOCK)
1912177085Sjeff		td->td_flags |= TDF_CANSWAP;
1913177903Sjeff	if (static_boost == 1 && prio)
1914177085Sjeff		sched_prio(td, prio);
1915177903Sjeff	else if (static_boost && td->td_priority > static_boost)
1916177903Sjeff		sched_prio(td, static_boost);
1917109864Sjeff}
1918109864Sjeff
1919171482Sjeff/*
1920171482Sjeff * Schedule a thread to resume execution and record how long it voluntarily
1921171482Sjeff * slept.  We also update the pctcpu, interactivity, and priority.
1922171482Sjeff */
1923109864Sjeffvoid
1924109864Sjeffsched_wakeup(struct thread *td)
1925109864Sjeff{
1926166229Sjeff	struct td_sched *ts;
1927171482Sjeff	int slptick;
1928165762Sjeff
1929170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1930166229Sjeff	ts = td->td_sched;
1931177085Sjeff	td->td_flags &= ~TDF_CANSWAP;
1932109864Sjeff	/*
1933165762Sjeff	 * If we slept for more than a tick update our interactivity and
1934165762Sjeff	 * priority.
1935109864Sjeff	 */
1936172264Sjeff	slptick = td->td_slptick;
1937172264Sjeff	td->td_slptick = 0;
1938171482Sjeff	if (slptick && slptick != ticks) {
1939166208Sjeff		u_int hzticks;
1940109864Sjeff
1941171482Sjeff		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1942171482Sjeff		ts->ts_slptime += hzticks;
1943165819Sjeff		sched_interact_update(td);
1944166229Sjeff		sched_pctcpu_update(ts);
1945109864Sjeff	}
1946166229Sjeff	/* Reset the slice value after we sleep. */
1947166229Sjeff	ts->ts_slice = sched_slice;
1948166190Sjeff	sched_add(td, SRQ_BORING);
1949109864Sjeff}
1950109864Sjeff
1951109864Sjeff/*
1952109864Sjeff * Penalize the parent for creating a new child and initialize the child's
1953109864Sjeff * priority.
1954109864Sjeff */
1955109864Sjeffvoid
1956163709Sjbsched_fork(struct thread *td, struct thread *child)
1957109864Sjeff{
1958170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1959164936Sjulian	sched_fork_thread(td, child);
1960165762Sjeff	/*
1961165762Sjeff	 * Penalize the parent and child for forking.
1962165762Sjeff	 */
1963165762Sjeff	sched_interact_fork(child);
1964165762Sjeff	sched_priority(child);
1965171482Sjeff	td->td_sched->ts_runtime += tickincr;
1966165762Sjeff	sched_interact_update(td);
1967165762Sjeff	sched_priority(td);
1968164936Sjulian}
1969109864Sjeff
1970171482Sjeff/*
1971171482Sjeff * Fork a new thread, may be within the same process.
1972171482Sjeff */
1973164936Sjulianvoid
1974164936Sjuliansched_fork_thread(struct thread *td, struct thread *child)
1975164936Sjulian{
1976164936Sjulian	struct td_sched *ts;
1977164936Sjulian	struct td_sched *ts2;
1978164936Sjulian
1979177426Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1980165762Sjeff	/*
1981165762Sjeff	 * Initialize child.
1982165762Sjeff	 */
1983177426Sjeff	ts = td->td_sched;
1984177426Sjeff	ts2 = child->td_sched;
1985171482Sjeff	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1986176735Sjeff	child->td_cpuset = cpuset_ref(td->td_cpuset);
1987164936Sjulian	ts2->ts_cpu = ts->ts_cpu;
1988177426Sjeff	ts2->ts_flags = 0;
1989165762Sjeff	/*
1990165762Sjeff	 * Grab our parents cpu estimation information and priority.
1991165762Sjeff	 */
1992164936Sjulian	ts2->ts_ticks = ts->ts_ticks;
1993164936Sjulian	ts2->ts_ltick = ts->ts_ltick;
1994164936Sjulian	ts2->ts_ftick = ts->ts_ftick;
1995165762Sjeff	child->td_user_pri = td->td_user_pri;
1996165762Sjeff	child->td_base_user_pri = td->td_base_user_pri;
1997165762Sjeff	/*
1998165762Sjeff	 * And update interactivity score.
1999165762Sjeff	 */
2000171482Sjeff	ts2->ts_slptime = ts->ts_slptime;
2001171482Sjeff	ts2->ts_runtime = ts->ts_runtime;
2002165762Sjeff	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
2003187357Sjeff#ifdef KTR
2004187357Sjeff	bzero(ts2->ts_name, sizeof(ts2->ts_name));
2005187357Sjeff#endif
2006113357Sjeff}
2007113357Sjeff
2008171482Sjeff/*
2009171482Sjeff * Adjust the priority class of a thread.
2010171482Sjeff */
2011113357Sjeffvoid
2012163709Sjbsched_class(struct thread *td, int class)
2013113357Sjeff{
2014113357Sjeff
2015170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2016163709Sjb	if (td->td_pri_class == class)
2017113357Sjeff		return;
2018163709Sjb	td->td_pri_class = class;
2019109864Sjeff}
2020109864Sjeff
2021109864Sjeff/*
2022109864Sjeff * Return some of the child's priority and interactivity to the parent.
2023109864Sjeff */
2024109864Sjeffvoid
2025164939Sjuliansched_exit(struct proc *p, struct thread *child)
2026109864Sjeff{
2027165762Sjeff	struct thread *td;
2028113372Sjeff
2029187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2030187357Sjeff	    "prio:td", child->td_priority);
2031177368Sjeff	PROC_LOCK_ASSERT(p, MA_OWNED);
2032165762Sjeff	td = FIRST_THREAD_IN_PROC(p);
2033165762Sjeff	sched_exit_thread(td, child);
2034113372Sjeff}
2035113372Sjeff
2036171482Sjeff/*
2037171482Sjeff * Penalize another thread for the time spent on this one.  This helps to
2038171482Sjeff * worsen the priority and interactivity of processes which schedule batch
2039171482Sjeff * jobs such as make.  This has little effect on the make process itself but
2040171482Sjeff * causes new processes spawned by it to receive worse scores immediately.
2041171482Sjeff */
2042113372Sjeffvoid
2043164939Sjuliansched_exit_thread(struct thread *td, struct thread *child)
2044164936Sjulian{
2045165762Sjeff
2046187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2047187357Sjeff	    "prio:td", child->td_priority);
2048165762Sjeff	/*
2049165762Sjeff	 * Give the child's runtime to the parent without returning the
2050165762Sjeff	 * sleep time as a penalty to the parent.  This causes shells that
2051165762Sjeff	 * launch expensive things to mark their children as expensive.
2052165762Sjeff	 */
2053170293Sjeff	thread_lock(td);
2054171482Sjeff	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2055164939Sjulian	sched_interact_update(td);
2056165762Sjeff	sched_priority(td);
2057170293Sjeff	thread_unlock(td);
2058164936Sjulian}
2059164936Sjulian
2060177005Sjeffvoid
2061177005Sjeffsched_preempt(struct thread *td)
2062177005Sjeff{
2063177005Sjeff	struct tdq *tdq;
2064177005Sjeff
2065177005Sjeff	thread_lock(td);
2066177005Sjeff	tdq = TDQ_SELF();
2067177005Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2068177005Sjeff	tdq->tdq_ipipending = 0;
2069177005Sjeff	if (td->td_priority > tdq->tdq_lowpri) {
2070178272Sjeff		int flags;
2071178272Sjeff
2072178272Sjeff		flags = SW_INVOL | SW_PREEMPT;
2073177005Sjeff		if (td->td_critnest > 1)
2074177005Sjeff			td->td_owepreempt = 1;
2075178272Sjeff		else if (TD_IS_IDLETHREAD(td))
2076178272Sjeff			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2077177005Sjeff		else
2078178272Sjeff			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2079177005Sjeff	}
2080177005Sjeff	thread_unlock(td);
2081177005Sjeff}
2082177005Sjeff
2083171482Sjeff/*
2084171482Sjeff * Fix priorities on return to user-space.  Priorities may be elevated due
2085171482Sjeff * to static priorities in msleep() or similar.
2086171482Sjeff */
2087164936Sjulianvoid
2088164936Sjuliansched_userret(struct thread *td)
2089164936Sjulian{
2090164936Sjulian	/*
2091164936Sjulian	 * XXX we cheat slightly on the locking here to avoid locking in
2092164936Sjulian	 * the usual case.  Setting td_priority here is essentially an
2093164936Sjulian	 * incomplete workaround for not setting it properly elsewhere.
2094164936Sjulian	 * Now that some interrupt handlers are threads, not setting it
2095164936Sjulian	 * properly elsewhere can clobber it in the window between setting
2096164936Sjulian	 * it here and returning to user mode, so don't waste time setting
2097164936Sjulian	 * it perfectly here.
2098164936Sjulian	 */
2099164936Sjulian	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2100164936Sjulian	    ("thread with borrowed priority returning to userland"));
2101164936Sjulian	if (td->td_priority != td->td_user_pri) {
2102170293Sjeff		thread_lock(td);
2103164936Sjulian		td->td_priority = td->td_user_pri;
2104164936Sjulian		td->td_base_pri = td->td_user_pri;
2105177005Sjeff		tdq_setlowpri(TDQ_SELF(), td);
2106170293Sjeff		thread_unlock(td);
2107164936Sjulian        }
2108164936Sjulian}
2109164936Sjulian
2110171482Sjeff/*
2111171482Sjeff * Handle a stathz tick.  This is really only relevant for timeshare
2112171482Sjeff * threads.
2113171482Sjeff */
2114164936Sjulianvoid
2115121127Sjeffsched_clock(struct thread *td)
2116109864Sjeff{
2117164936Sjulian	struct tdq *tdq;
2118164936Sjulian	struct td_sched *ts;
2119109864Sjeff
2120171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2121164936Sjulian	tdq = TDQ_SELF();
2122172409Sjeff#ifdef SMP
2123133427Sjeff	/*
2124172409Sjeff	 * We run the long term load balancer infrequently on the first cpu.
2125172409Sjeff	 */
2126172409Sjeff	if (balance_tdq == tdq) {
2127172409Sjeff		if (balance_ticks && --balance_ticks == 0)
2128172409Sjeff			sched_balance();
2129172409Sjeff	}
2130172409Sjeff#endif
2131172409Sjeff	/*
2132178277Sjeff	 * Save the old switch count so we have a record of the last ticks
2133178277Sjeff	 * activity.   Initialize the new switch count based on our load.
2134178277Sjeff	 * If there is some activity seed it to reflect that.
2135178277Sjeff	 */
2136178277Sjeff	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
2137178471Sjeff	tdq->tdq_switchcnt = tdq->tdq_load;
2138178277Sjeff	/*
2139165766Sjeff	 * Advance the insert index once for each tick to ensure that all
2140165766Sjeff	 * threads get a chance to run.
2141133427Sjeff	 */
2142165766Sjeff	if (tdq->tdq_idx == tdq->tdq_ridx) {
2143165766Sjeff		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2144165766Sjeff		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2145165766Sjeff			tdq->tdq_ridx = tdq->tdq_idx;
2146165766Sjeff	}
2147165766Sjeff	ts = td->td_sched;
2148175104Sjeff	if (td->td_pri_class & PRI_FIFO_BIT)
2149113357Sjeff		return;
2150175104Sjeff	if (td->td_pri_class == PRI_TIMESHARE) {
2151175104Sjeff		/*
2152175104Sjeff		 * We used a tick; charge it to the thread so
2153175104Sjeff		 * that we can compute our interactivity.
2154175104Sjeff		 */
2155175104Sjeff		td->td_sched->ts_runtime += tickincr;
2156175104Sjeff		sched_interact_update(td);
2157177009Sjeff		sched_priority(td);
2158175104Sjeff	}
2159113357Sjeff	/*
2160109864Sjeff	 * We used up one time slice.
2161109864Sjeff	 */
2162164936Sjulian	if (--ts->ts_slice > 0)
2163113357Sjeff		return;
2164109864Sjeff	/*
2165177009Sjeff	 * We're out of time, force a requeue at userret().
2166109864Sjeff	 */
2167177009Sjeff	ts->ts_slice = sched_slice;
2168113357Sjeff	td->td_flags |= TDF_NEEDRESCHED;
2169109864Sjeff}
2170109864Sjeff
2171171482Sjeff/*
2172171482Sjeff * Called once per hz tick.  Used for cpu utilization information.  This
2173171482Sjeff * is easier than trying to scale based on stathz.
2174171482Sjeff */
2175171482Sjeffvoid
2176171482Sjeffsched_tick(void)
2177171482Sjeff{
2178171482Sjeff	struct td_sched *ts;
2179171482Sjeff
2180171482Sjeff	ts = curthread->td_sched;
2181180607Sjeff	/*
2182180607Sjeff	 * Ticks is updated asynchronously on a single cpu.  Check here to
2183180607Sjeff	 * avoid incrementing ts_ticks multiple times in a single tick.
2184180607Sjeff	 */
2185180607Sjeff	if (ts->ts_ltick == ticks)
2186180607Sjeff		return;
2187171482Sjeff	/* Adjust ticks for pctcpu */
2188171482Sjeff	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2189171482Sjeff	ts->ts_ltick = ticks;
2190171482Sjeff	/*
2191171482Sjeff	 * Update if we've exceeded our desired tick threshhold by over one
2192171482Sjeff	 * second.
2193171482Sjeff	 */
2194171482Sjeff	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2195171482Sjeff		sched_pctcpu_update(ts);
2196171482Sjeff}
2197171482Sjeff
2198171482Sjeff/*
2199171482Sjeff * Return whether the current CPU has runnable tasks.  Used for in-kernel
2200171482Sjeff * cooperative idle threads.
2201171482Sjeff */
2202109864Sjeffint
2203109864Sjeffsched_runnable(void)
2204109864Sjeff{
2205164936Sjulian	struct tdq *tdq;
2206115998Sjeff	int load;
2207109864Sjeff
2208115998Sjeff	load = 1;
2209115998Sjeff
2210164936Sjulian	tdq = TDQ_SELF();
2211121605Sjeff	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2212165620Sjeff		if (tdq->tdq_load > 0)
2213121605Sjeff			goto out;
2214121605Sjeff	} else
2215165620Sjeff		if (tdq->tdq_load - 1 > 0)
2216121605Sjeff			goto out;
2217115998Sjeff	load = 0;
2218115998Sjeffout:
2219115998Sjeff	return (load);
2220109864Sjeff}
2221109864Sjeff
2222171482Sjeff/*
2223171482Sjeff * Choose the highest priority thread to run.  The thread is removed from
2224171482Sjeff * the run-queue while running however the load remains.  For SMP we set
2225171482Sjeff * the tdq in the global idle bitmask if it idles here.
2226171482Sjeff */
2227166190Sjeffstruct thread *
2228109970Sjeffsched_choose(void)
2229109970Sjeff{
2230177435Sjeff	struct thread *td;
2231164936Sjulian	struct tdq *tdq;
2232109970Sjeff
2233164936Sjulian	tdq = TDQ_SELF();
2234171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2235177435Sjeff	td = tdq_choose(tdq);
2236177435Sjeff	if (td) {
2237177435Sjeff		td->td_sched->ts_ltick = ticks;
2238177435Sjeff		tdq_runq_rem(tdq, td);
2239177903Sjeff		tdq->tdq_lowpri = td->td_priority;
2240177435Sjeff		return (td);
2241109864Sjeff	}
2242177903Sjeff	tdq->tdq_lowpri = PRI_MAX_IDLE;
2243176735Sjeff	return (PCPU_GET(idlethread));
2244109864Sjeff}
2245109864Sjeff
2246171482Sjeff/*
2247171482Sjeff * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2248171482Sjeff * we always request it once we exit a critical section.
2249171482Sjeff */
2250171482Sjeffstatic inline void
2251171482Sjeffsched_setpreempt(struct thread *td)
2252166190Sjeff{
2253166190Sjeff	struct thread *ctd;
2254166190Sjeff	int cpri;
2255166190Sjeff	int pri;
2256166190Sjeff
2257177005Sjeff	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2258177005Sjeff
2259166190Sjeff	ctd = curthread;
2260166190Sjeff	pri = td->td_priority;
2261166190Sjeff	cpri = ctd->td_priority;
2262177005Sjeff	if (pri < cpri)
2263177005Sjeff		ctd->td_flags |= TDF_NEEDRESCHED;
2264166190Sjeff	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2265171482Sjeff		return;
2266177005Sjeff	if (!sched_shouldpreempt(pri, cpri, 0))
2267171482Sjeff		return;
2268171482Sjeff	ctd->td_owepreempt = 1;
2269166190Sjeff}
2270166190Sjeff
2271171482Sjeff/*
2272177009Sjeff * Add a thread to a thread queue.  Select the appropriate runq and add the
2273177009Sjeff * thread to it.  This is the internal function called when the tdq is
2274177009Sjeff * predetermined.
2275171482Sjeff */
2276109864Sjeffvoid
2277171482Sjefftdq_add(struct tdq *tdq, struct thread *td, int flags)
2278109864Sjeff{
2279109864Sjeff
2280171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2281166190Sjeff	KASSERT((td->td_inhibitors == 0),
2282166190Sjeff	    ("sched_add: trying to run inhibited thread"));
2283166190Sjeff	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2284166190Sjeff	    ("sched_add: bad thread state"));
2285172207Sjeff	KASSERT(td->td_flags & TDF_INMEM,
2286172207Sjeff	    ("sched_add: thread swapped out"));
2287171482Sjeff
2288171482Sjeff	if (td->td_priority < tdq->tdq_lowpri)
2289171482Sjeff		tdq->tdq_lowpri = td->td_priority;
2290177435Sjeff	tdq_runq_add(tdq, td, flags);
2291177435Sjeff	tdq_load_add(tdq, td);
2292171482Sjeff}
2293171482Sjeff
2294171482Sjeff/*
2295171482Sjeff * Select the target thread queue and add a thread to it.  Request
2296171482Sjeff * preemption or IPI a remote processor if required.
2297171482Sjeff */
2298171482Sjeffvoid
2299171482Sjeffsched_add(struct thread *td, int flags)
2300171482Sjeff{
2301171482Sjeff	struct tdq *tdq;
2302171482Sjeff#ifdef SMP
2303171482Sjeff	int cpu;
2304171482Sjeff#endif
2305187357Sjeff
2306187357Sjeff	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
2307187357Sjeff	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
2308187357Sjeff	    sched_tdname(curthread));
2309187357Sjeff	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
2310187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(td));
2311171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2312166108Sjeff	/*
2313171482Sjeff	 * Recalculate the priority before we select the target cpu or
2314171482Sjeff	 * run-queue.
2315166108Sjeff	 */
2316171482Sjeff	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2317171482Sjeff		sched_priority(td);
2318171482Sjeff#ifdef SMP
2319171482Sjeff	/*
2320171482Sjeff	 * Pick the destination cpu and if it isn't ours transfer to the
2321171482Sjeff	 * target cpu.
2322171482Sjeff	 */
2323177435Sjeff	cpu = sched_pickcpu(td, flags);
2324177435Sjeff	tdq = sched_setcpu(td, cpu, flags);
2325171482Sjeff	tdq_add(tdq, td, flags);
2326177009Sjeff	if (cpu != PCPU_GET(cpuid)) {
2327177435Sjeff		tdq_notify(tdq, td);
2328166108Sjeff		return;
2329166108Sjeff	}
2330171482Sjeff#else
2331171482Sjeff	tdq = TDQ_SELF();
2332171482Sjeff	TDQ_LOCK(tdq);
2333171482Sjeff	/*
2334171482Sjeff	 * Now that the thread is moving to the run-queue, set the lock
2335171482Sjeff	 * to the scheduler's lock.
2336171482Sjeff	 */
2337171482Sjeff	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2338171482Sjeff	tdq_add(tdq, td, flags);
2339166108Sjeff#endif
2340171482Sjeff	if (!(flags & SRQ_YIELDING))
2341171482Sjeff		sched_setpreempt(td);
2342109864Sjeff}
2343109864Sjeff
2344171482Sjeff/*
2345171482Sjeff * Remove a thread from a run-queue without running it.  This is used
2346171482Sjeff * when we're stealing a thread from a remote queue.  Otherwise all threads
2347171482Sjeff * exit by calling sched_exit_thread() and sched_throw() themselves.
2348171482Sjeff */
2349109864Sjeffvoid
2350121127Sjeffsched_rem(struct thread *td)
2351109864Sjeff{
2352164936Sjulian	struct tdq *tdq;
2353113357Sjeff
2354187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
2355187357Sjeff	    "prio:%d", td->td_priority);
2356177435Sjeff	tdq = TDQ_CPU(td->td_sched->ts_cpu);
2357171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2358171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2359166190Sjeff	KASSERT(TD_ON_RUNQ(td),
2360164936Sjulian	    ("sched_rem: thread not on run queue"));
2361177435Sjeff	tdq_runq_rem(tdq, td);
2362177435Sjeff	tdq_load_rem(tdq, td);
2363166190Sjeff	TD_SET_CAN_RUN(td);
2364176735Sjeff	if (td->td_priority == tdq->tdq_lowpri)
2365176735Sjeff		tdq_setlowpri(tdq, NULL);
2366109864Sjeff}
2367109864Sjeff
2368171482Sjeff/*
2369171482Sjeff * Fetch cpu utilization information.  Updates on demand.
2370171482Sjeff */
2371109864Sjefffixpt_t
2372121127Sjeffsched_pctcpu(struct thread *td)
2373109864Sjeff{
2374109864Sjeff	fixpt_t pctcpu;
2375164936Sjulian	struct td_sched *ts;
2376109864Sjeff
2377109864Sjeff	pctcpu = 0;
2378164936Sjulian	ts = td->td_sched;
2379164936Sjulian	if (ts == NULL)
2380121290Sjeff		return (0);
2381109864Sjeff
2382170293Sjeff	thread_lock(td);
2383164936Sjulian	if (ts->ts_ticks) {
2384109864Sjeff		int rtick;
2385109864Sjeff
2386165796Sjeff		sched_pctcpu_update(ts);
2387109864Sjeff		/* How many rtick per second ? */
2388165762Sjeff		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2389165762Sjeff		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2390109864Sjeff	}
2391170293Sjeff	thread_unlock(td);
2392109864Sjeff
2393109864Sjeff	return (pctcpu);
2394109864Sjeff}
2395109864Sjeff
2396176735Sjeff/*
2397176735Sjeff * Enforce affinity settings for a thread.  Called after adjustments to
2398176735Sjeff * cpumask.
2399176735Sjeff */
2400176729Sjeffvoid
2401176729Sjeffsched_affinity(struct thread *td)
2402176729Sjeff{
2403176735Sjeff#ifdef SMP
2404176735Sjeff	struct td_sched *ts;
2405176735Sjeff	int cpu;
2406176735Sjeff
2407176735Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2408176735Sjeff	ts = td->td_sched;
2409176735Sjeff	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2410176735Sjeff		return;
2411189787Sjeff	if (TD_ON_RUNQ(td)) {
2412189787Sjeff		sched_rem(td);
2413189787Sjeff		sched_add(td, SRQ_BORING);
2414189787Sjeff		return;
2415189787Sjeff	}
2416176735Sjeff	if (!TD_IS_RUNNING(td))
2417176735Sjeff		return;
2418176735Sjeff	td->td_flags |= TDF_NEEDRESCHED;
2419176735Sjeff	if (!THREAD_CAN_MIGRATE(td))
2420176735Sjeff		return;
2421176735Sjeff	/*
2422176735Sjeff	 * Assign the new cpu and force a switch before returning to
2423176735Sjeff	 * userspace.  If the target thread is not running locally send
2424176735Sjeff	 * an ipi to force the issue.
2425176735Sjeff	 */
2426176735Sjeff	cpu = ts->ts_cpu;
2427177435Sjeff	ts->ts_cpu = sched_pickcpu(td, 0);
2428176735Sjeff	if (cpu != PCPU_GET(cpuid))
2429176735Sjeff		ipi_selected(1 << cpu, IPI_PREEMPT);
2430176735Sjeff#endif
2431176729Sjeff}
2432176729Sjeff
2433171482Sjeff/*
2434171482Sjeff * Bind a thread to a target cpu.
2435171482Sjeff */
2436122038Sjeffvoid
2437122038Sjeffsched_bind(struct thread *td, int cpu)
2438122038Sjeff{
2439164936Sjulian	struct td_sched *ts;
2440122038Sjeff
2441171713Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2442164936Sjulian	ts = td->td_sched;
2443166137Sjeff	if (ts->ts_flags & TSF_BOUND)
2444166152Sjeff		sched_unbind(td);
2445164936Sjulian	ts->ts_flags |= TSF_BOUND;
2446166137Sjeff	sched_pin();
2447123433Sjeff	if (PCPU_GET(cpuid) == cpu)
2448122038Sjeff		return;
2449166137Sjeff	ts->ts_cpu = cpu;
2450122038Sjeff	/* When we return from mi_switch we'll be on the correct cpu. */
2451131527Sphk	mi_switch(SW_VOL, NULL);
2452122038Sjeff}
2453122038Sjeff
2454171482Sjeff/*
2455171482Sjeff * Release a bound thread.
2456171482Sjeff */
2457122038Sjeffvoid
2458122038Sjeffsched_unbind(struct thread *td)
2459122038Sjeff{
2460165762Sjeff	struct td_sched *ts;
2461165762Sjeff
2462170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2463165762Sjeff	ts = td->td_sched;
2464166137Sjeff	if ((ts->ts_flags & TSF_BOUND) == 0)
2465166137Sjeff		return;
2466165762Sjeff	ts->ts_flags &= ~TSF_BOUND;
2467165762Sjeff	sched_unpin();
2468122038Sjeff}
2469122038Sjeff
2470109864Sjeffint
2471145256Sjkoshysched_is_bound(struct thread *td)
2472145256Sjkoshy{
2473170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2474164936Sjulian	return (td->td_sched->ts_flags & TSF_BOUND);
2475145256Sjkoshy}
2476145256Sjkoshy
2477171482Sjeff/*
2478171482Sjeff * Basic yield call.
2479171482Sjeff */
2480159630Sdavidxuvoid
2481159630Sdavidxusched_relinquish(struct thread *td)
2482159630Sdavidxu{
2483170293Sjeff	thread_lock(td);
2484178272Sjeff	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
2485170293Sjeff	thread_unlock(td);
2486159630Sdavidxu}
2487159630Sdavidxu
2488171482Sjeff/*
2489171482Sjeff * Return the total system load.
2490171482Sjeff */
2491145256Sjkoshyint
2492125289Sjeffsched_load(void)
2493125289Sjeff{
2494125289Sjeff#ifdef SMP
2495125289Sjeff	int total;
2496125289Sjeff	int i;
2497125289Sjeff
2498125289Sjeff	total = 0;
2499176735Sjeff	for (i = 0; i <= mp_maxid; i++)
2500176735Sjeff		total += TDQ_CPU(i)->tdq_sysload;
2501125289Sjeff	return (total);
2502125289Sjeff#else
2503165620Sjeff	return (TDQ_SELF()->tdq_sysload);
2504125289Sjeff#endif
2505125289Sjeff}
2506125289Sjeff
2507125289Sjeffint
2508109864Sjeffsched_sizeof_proc(void)
2509109864Sjeff{
2510109864Sjeff	return (sizeof(struct proc));
2511109864Sjeff}
2512109864Sjeff
2513109864Sjeffint
2514109864Sjeffsched_sizeof_thread(void)
2515109864Sjeff{
2516109864Sjeff	return (sizeof(struct thread) + sizeof(struct td_sched));
2517109864Sjeff}
2518159570Sdavidxu
2519191676Sjeff#ifdef SMP
2520191676Sjeff#define	TDQ_IDLESPIN(tdq)						\
2521191676Sjeff    ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
2522191676Sjeff#else
2523191676Sjeff#define	TDQ_IDLESPIN(tdq)	1
2524191676Sjeff#endif
2525191676Sjeff
2526166190Sjeff/*
2527166190Sjeff * The actual idle process.
2528166190Sjeff */
2529166190Sjeffvoid
2530166190Sjeffsched_idletd(void *dummy)
2531166190Sjeff{
2532166190Sjeff	struct thread *td;
2533171482Sjeff	struct tdq *tdq;
2534178277Sjeff	int switchcnt;
2535178277Sjeff	int i;
2536166190Sjeff
2537191643Sjeff	mtx_assert(&Giant, MA_NOTOWNED);
2538166190Sjeff	td = curthread;
2539171482Sjeff	tdq = TDQ_SELF();
2540171482Sjeff	for (;;) {
2541171482Sjeff#ifdef SMP
2542178277Sjeff		if (tdq_idled(tdq) == 0)
2543178277Sjeff			continue;
2544171482Sjeff#endif
2545178277Sjeff		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2546178277Sjeff		/*
2547178277Sjeff		 * If we're switching very frequently, spin while checking
2548178277Sjeff		 * for load rather than entering a low power state that
2549191643Sjeff		 * may require an IPI.  However, don't do any busy
2550191643Sjeff		 * loops while on SMT machines as this simply steals
2551191643Sjeff		 * cycles from cores doing useful work.
2552178277Sjeff		 */
2553191676Sjeff		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
2554178277Sjeff			for (i = 0; i < sched_idlespins; i++) {
2555178277Sjeff				if (tdq->tdq_load)
2556178277Sjeff					break;
2557178277Sjeff				cpu_spinwait();
2558178277Sjeff			}
2559178277Sjeff		}
2560191643Sjeff		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2561191643Sjeff		if (tdq->tdq_load == 0)
2562191643Sjeff			cpu_idle(switchcnt > 1);
2563178277Sjeff		if (tdq->tdq_load) {
2564178277Sjeff			thread_lock(td);
2565178277Sjeff			mi_switch(SW_VOL | SWT_IDLE, NULL);
2566178277Sjeff			thread_unlock(td);
2567178277Sjeff		}
2568171482Sjeff	}
2569166190Sjeff}
2570166190Sjeff
2571170293Sjeff/*
2572170293Sjeff * A CPU is entering for the first time or a thread is exiting.
2573170293Sjeff */
2574170293Sjeffvoid
2575170293Sjeffsched_throw(struct thread *td)
2576170293Sjeff{
2577172411Sjeff	struct thread *newtd;
2578171482Sjeff	struct tdq *tdq;
2579171482Sjeff
2580171482Sjeff	tdq = TDQ_SELF();
2581170293Sjeff	if (td == NULL) {
2582171482Sjeff		/* Correct spinlock nesting and acquire the correct lock. */
2583171482Sjeff		TDQ_LOCK(tdq);
2584170293Sjeff		spinlock_exit();
2585170293Sjeff	} else {
2586171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2587177435Sjeff		tdq_load_rem(tdq, td);
2588174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2589170293Sjeff	}
2590170293Sjeff	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2591172411Sjeff	newtd = choosethread();
2592172411Sjeff	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2593170293Sjeff	PCPU_SET(switchtime, cpu_ticks());
2594170293Sjeff	PCPU_SET(switchticks, ticks);
2595172411Sjeff	cpu_throw(td, newtd);		/* doesn't return */
2596170293Sjeff}
2597170293Sjeff
2598171482Sjeff/*
2599171482Sjeff * This is called from fork_exit().  Just acquire the correct locks and
2600171482Sjeff * let fork do the rest of the work.
2601171482Sjeff */
2602170293Sjeffvoid
2603170600Sjeffsched_fork_exit(struct thread *td)
2604170293Sjeff{
2605171482Sjeff	struct td_sched *ts;
2606171482Sjeff	struct tdq *tdq;
2607171482Sjeff	int cpuid;
2608170293Sjeff
2609170293Sjeff	/*
2610170293Sjeff	 * Finish setting up thread glue so that it begins execution in a
2611171482Sjeff	 * non-nested critical section with the scheduler lock held.
2612170293Sjeff	 */
2613171482Sjeff	cpuid = PCPU_GET(cpuid);
2614171482Sjeff	tdq = TDQ_CPU(cpuid);
2615171482Sjeff	ts = td->td_sched;
2616171482Sjeff	if (TD_IS_IDLETHREAD(td))
2617171482Sjeff		td->td_lock = TDQ_LOCKPTR(tdq);
2618171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2619171482Sjeff	td->td_oncpu = cpuid;
2620172411Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2621174629Sjeff	lock_profile_obtain_lock_success(
2622174629Sjeff	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2623170293Sjeff}
2624170293Sjeff
2625187357Sjeff/*
2626187357Sjeff * Create on first use to catch odd startup conditons.
2627187357Sjeff */
2628187357Sjeffchar *
2629187357Sjeffsched_tdname(struct thread *td)
2630187357Sjeff{
2631187357Sjeff#ifdef KTR
2632187357Sjeff	struct td_sched *ts;
2633187357Sjeff
2634187357Sjeff	ts = td->td_sched;
2635187357Sjeff	if (ts->ts_name[0] == '\0')
2636187357Sjeff		snprintf(ts->ts_name, sizeof(ts->ts_name),
2637187357Sjeff		    "%s tid %d", td->td_name, td->td_tid);
2638187357Sjeff	return (ts->ts_name);
2639187357Sjeff#else
2640187357Sjeff	return (td->td_name);
2641187357Sjeff#endif
2642187357Sjeff}
2643187357Sjeff
2644184439Sivoras#ifdef SMP
2645184439Sivoras
2646184439Sivoras/*
2647184439Sivoras * Build the CPU topology dump string. Is recursively called to collect
2648184439Sivoras * the topology tree.
2649184439Sivoras */
2650184439Sivorasstatic int
2651184439Sivorassysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
2652184439Sivoras    int indent)
2653184439Sivoras{
2654184439Sivoras	int i, first;
2655184439Sivoras
2656184439Sivoras	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
2657184439Sivoras	    "", indent, cg->cg_level);
2658184439Sivoras	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"0x%x\">", indent, "",
2659184439Sivoras	    cg->cg_count, cg->cg_mask);
2660184439Sivoras	first = TRUE;
2661184439Sivoras	for (i = 0; i < MAXCPU; i++) {
2662184439Sivoras		if ((cg->cg_mask & (1 << i)) != 0) {
2663184439Sivoras			if (!first)
2664184439Sivoras				sbuf_printf(sb, ", ");
2665184439Sivoras			else
2666184439Sivoras				first = FALSE;
2667184439Sivoras			sbuf_printf(sb, "%d", i);
2668184439Sivoras		}
2669184439Sivoras	}
2670184439Sivoras	sbuf_printf(sb, "</cpu>\n");
2671184439Sivoras
2672184439Sivoras	sbuf_printf(sb, "%*s <flags>", indent, "");
2673184439Sivoras	if (cg->cg_flags != 0) {
2674184439Sivoras		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
2675186435Sivoras			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>\n");
2676191643Sjeff		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
2677186435Sivoras			sbuf_printf(sb, "<flag name=\"THREAD\">SMT group</flag>\n");
2678184439Sivoras	}
2679184439Sivoras	sbuf_printf(sb, "</flags>\n");
2680184439Sivoras
2681184439Sivoras	if (cg->cg_children > 0) {
2682184439Sivoras		sbuf_printf(sb, "%*s <children>\n", indent, "");
2683184439Sivoras		for (i = 0; i < cg->cg_children; i++)
2684184439Sivoras			sysctl_kern_sched_topology_spec_internal(sb,
2685184439Sivoras			    &cg->cg_child[i], indent+2);
2686184439Sivoras		sbuf_printf(sb, "%*s </children>\n", indent, "");
2687184439Sivoras	}
2688184439Sivoras	sbuf_printf(sb, "%*s</group>\n", indent, "");
2689184439Sivoras	return (0);
2690184439Sivoras}
2691184439Sivoras
2692184439Sivoras/*
2693184439Sivoras * Sysctl handler for retrieving topology dump. It's a wrapper for
2694184439Sivoras * the recursive sysctl_kern_smp_topology_spec_internal().
2695184439Sivoras */
2696184439Sivorasstatic int
2697184439Sivorassysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
2698184439Sivoras{
2699184439Sivoras	struct sbuf *topo;
2700184439Sivoras	int err;
2701184439Sivoras
2702184439Sivoras	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
2703184439Sivoras
2704184570Sivoras	topo = sbuf_new(NULL, NULL, 500, SBUF_AUTOEXTEND);
2705184439Sivoras	if (topo == NULL)
2706184439Sivoras		return (ENOMEM);
2707184439Sivoras
2708184439Sivoras	sbuf_printf(topo, "<groups>\n");
2709184439Sivoras	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
2710184439Sivoras	sbuf_printf(topo, "</groups>\n");
2711184439Sivoras
2712184439Sivoras	if (err == 0) {
2713184439Sivoras		sbuf_finish(topo);
2714184439Sivoras		err = SYSCTL_OUT(req, sbuf_data(topo), sbuf_len(topo));
2715184439Sivoras	}
2716184439Sivoras	sbuf_delete(topo);
2717184439Sivoras	return (err);
2718184439Sivoras}
2719184439Sivoras#endif
2720184439Sivoras
2721177435SjeffSYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2722171482SjeffSYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2723165762Sjeff    "Scheduler name");
2724171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2725171482Sjeff    "Slice size for timeshare threads");
2726171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2727171482Sjeff     "Interactivity score threshold");
2728171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2729171482Sjeff     0,"Min priority for preemption, lower priorities have greater precedence");
2730177085SjeffSYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost,
2731177085Sjeff     0,"Controls whether static kernel priorities are assigned to sleeping threads.");
2732178277SjeffSYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins,
2733178277Sjeff     0,"Number of times idle will spin waiting for new work.");
2734178277SjeffSYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW, &sched_idlespinthresh,
2735178277Sjeff     0,"Threshold before we will permit idle spinning.");
2736166108Sjeff#ifdef SMP
2737171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2738171482Sjeff    "Number of hz ticks to keep thread affinity for");
2739171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2740171482Sjeff    "Enables the long-term load balancer");
2741172409SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2742172409Sjeff    &balance_interval, 0,
2743172409Sjeff    "Average frequency in stathz ticks to run the long-term balancer");
2744171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2745171482Sjeff    "Steals work from another hyper-threaded core on idle");
2746171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2747171482Sjeff    "Attempts to steal work from other cores before idling");
2748171506SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2749171506Sjeff    "Minimum load on remote cpu before we'll steal");
2750184439Sivoras
2751184439Sivoras/* Retrieve SMP topology */
2752184439SivorasSYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
2753184439Sivoras    CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
2754184439Sivoras    "XML dump of detected CPU topology");
2755166108Sjeff#endif
2756165762Sjeff
2757172264Sjeff/* ps compat.  All cpu percentages from ULE are weighted. */
2758172293Sjeffstatic int ccpu = 0;
2759165762SjeffSYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2760