sched_ule.c revision 242852
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 242852 2012-11-10 07:02:57Z mav $");
40116182Sobrien
41147565Speter#include "opt_hwpmc_hooks.h"
42179297Sjb#include "opt_kdtrace.h"
43147565Speter#include "opt_sched.h"
44134649Sscottl
45109864Sjeff#include <sys/param.h>
46109864Sjeff#include <sys/systm.h>
47131929Smarcel#include <sys/kdb.h>
48109864Sjeff#include <sys/kernel.h>
49109864Sjeff#include <sys/ktr.h>
50109864Sjeff#include <sys/lock.h>
51109864Sjeff#include <sys/mutex.h>
52109864Sjeff#include <sys/proc.h>
53112966Sjeff#include <sys/resource.h>
54122038Sjeff#include <sys/resourcevar.h>
55109864Sjeff#include <sys/sched.h>
56235459Srstone#include <sys/sdt.h>
57109864Sjeff#include <sys/smp.h>
58109864Sjeff#include <sys/sx.h>
59109864Sjeff#include <sys/sysctl.h>
60109864Sjeff#include <sys/sysproto.h>
61139453Sjhb#include <sys/turnstile.h>
62161599Sdavidxu#include <sys/umtx.h>
63109864Sjeff#include <sys/vmmeter.h>
64176735Sjeff#include <sys/cpuset.h>
65184439Sivoras#include <sys/sbuf.h>
66109864Sjeff
67145256Sjkoshy#ifdef HWPMC_HOOKS
68145256Sjkoshy#include <sys/pmckern.h>
69145256Sjkoshy#endif
70145256Sjkoshy
71179297Sjb#ifdef KDTRACE_HOOKS
72179297Sjb#include <sys/dtrace_bsd.h>
73179297Sjbint				dtrace_vtime_active;
74179297Sjbdtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
75179297Sjb#endif
76179297Sjb
77109864Sjeff#include <machine/cpu.h>
78121790Sjeff#include <machine/smp.h>
79109864Sjeff
80236141Sraj#if defined(__powerpc__) && defined(BOOKE_E500)
81172345Sjeff#error "This architecture is not currently compatible with ULE"
82166190Sjeff#endif
83166190Sjeff
84171482Sjeff#define	KTR_ULE	0
85166137Sjeff
86187679Sjeff#define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
87187679Sjeff#define	TDQ_NAME_LEN	(sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
88224221Sattilio#define	TDQ_LOADNAME_LEN	(sizeof("CPU ") + sizeof(__XSTRING(MAXCPU)) - 1 + sizeof(" load"))
89187357Sjeff
90166137Sjeff/*
91171482Sjeff * Thread scheduler specific section.  All fields are protected
92171482Sjeff * by the thread lock.
93146954Sjeff */
94164936Sjulianstruct td_sched {
95171482Sjeff	struct runq	*ts_runq;	/* Run-queue we're queued on. */
96171482Sjeff	short		ts_flags;	/* TSF_* flags. */
97164936Sjulian	u_char		ts_cpu;		/* CPU that we have affinity for. */
98177009Sjeff	int		ts_rltick;	/* Real last tick, for affinity. */
99171482Sjeff	int		ts_slice;	/* Ticks of slice remaining. */
100171482Sjeff	u_int		ts_slptime;	/* Number of ticks we vol. slept */
101171482Sjeff	u_int		ts_runtime;	/* Number of ticks we were running */
102164936Sjulian	int		ts_ltick;	/* Last tick that we were running on */
103164936Sjulian	int		ts_ftick;	/* First tick that we were running on */
104164936Sjulian	int		ts_ticks;	/* Tick count */
105187357Sjeff#ifdef KTR
106187357Sjeff	char		ts_name[TS_NAME_LEN];
107187357Sjeff#endif
108134791Sjulian};
109164936Sjulian/* flags kept in ts_flags */
110166108Sjeff#define	TSF_BOUND	0x0001		/* Thread can not migrate. */
111166108Sjeff#define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
112121790Sjeff
113164936Sjulianstatic struct td_sched td_sched0;
114109864Sjeff
115176735Sjeff#define	THREAD_CAN_MIGRATE(td)	((td)->td_pinned == 0)
116176735Sjeff#define	THREAD_CAN_SCHED(td, cpu)	\
117176735Sjeff    CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
118176735Sjeff
119109864Sjeff/*
120217351Sjhb * Priority ranges used for interactive and non-interactive timeshare
121217410Sjhb * threads.  The timeshare priorities are split up into four ranges.
122217410Sjhb * The first range handles interactive threads.  The last three ranges
123217410Sjhb * (NHALF, x, and NHALF) handle non-interactive threads with the outer
124217410Sjhb * ranges supporting nice values.
125217351Sjhb */
126217410Sjhb#define	PRI_TIMESHARE_RANGE	(PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
127217410Sjhb#define	PRI_INTERACT_RANGE	((PRI_TIMESHARE_RANGE - SCHED_PRI_NRESV) / 2)
128228718Savg#define	PRI_BATCH_RANGE		(PRI_TIMESHARE_RANGE - PRI_INTERACT_RANGE)
129217410Sjhb
130217410Sjhb#define	PRI_MIN_INTERACT	PRI_MIN_TIMESHARE
131217410Sjhb#define	PRI_MAX_INTERACT	(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE - 1)
132217410Sjhb#define	PRI_MIN_BATCH		(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE)
133217351Sjhb#define	PRI_MAX_BATCH		PRI_MAX_TIMESHARE
134217351Sjhb
135217351Sjhb/*
136165762Sjeff * Cpu percentage computation macros and defines.
137111857Sjeff *
138165762Sjeff * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
139165762Sjeff * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
140165796Sjeff * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
141165762Sjeff * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
142165762Sjeff * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
143165762Sjeff * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
144165762Sjeff */
145165762Sjeff#define	SCHED_TICK_SECS		10
146165762Sjeff#define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
147165796Sjeff#define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
148165762Sjeff#define	SCHED_TICK_SHIFT	10
149165762Sjeff#define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
150165830Sjeff#define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
151165762Sjeff
152165762Sjeff/*
153165762Sjeff * These macros determine priorities for non-interactive threads.  They are
154165762Sjeff * assigned a priority based on their recent cpu utilization as expressed
155165762Sjeff * by the ratio of ticks to the tick total.  NHALF priorities at the start
156165762Sjeff * and end of the MIN to MAX timeshare range are only reachable with negative
157165762Sjeff * or positive nice respectively.
158165762Sjeff *
159165762Sjeff * PRI_RANGE:	Priority range for utilization dependent priorities.
160116642Sjeff * PRI_NRESV:	Number of nice values.
161165762Sjeff * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
162165762Sjeff * PRI_NICE:	Determines the part of the priority inherited from nice.
163109864Sjeff */
164165762Sjeff#define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
165121869Sjeff#define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
166217351Sjhb#define	SCHED_PRI_MIN		(PRI_MIN_BATCH + SCHED_PRI_NHALF)
167217351Sjhb#define	SCHED_PRI_MAX		(PRI_MAX_BATCH - SCHED_PRI_NHALF)
168217237Sjhb#define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN + 1)
169165762Sjeff#define	SCHED_PRI_TICKS(ts)						\
170165762Sjeff    (SCHED_TICK_HZ((ts)) /						\
171165827Sjeff    (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
172165762Sjeff#define	SCHED_PRI_NICE(nice)	(nice)
173109864Sjeff
174109864Sjeff/*
175165762Sjeff * These determine the interactivity of a process.  Interactivity differs from
176165762Sjeff * cpu utilization in that it expresses the voluntary time slept vs time ran
177165762Sjeff * while cpu utilization includes all time not running.  This more accurately
178165762Sjeff * models the intent of the thread.
179109864Sjeff *
180110645Sjeff * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
181110645Sjeff *		before throttling back.
182121868Sjeff * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
183116365Sjeff * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
184215102Sattilio * INTERACT_THRESH:	Threshold for placement on the current runq.
185109864Sjeff */
186165762Sjeff#define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
187165762Sjeff#define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
188116365Sjeff#define	SCHED_INTERACT_MAX	(100)
189116365Sjeff#define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
190121126Sjeff#define	SCHED_INTERACT_THRESH	(30)
191111857Sjeff
192242736Sjeff/*
193242736Sjeff * These parameters determine the slice behavior for batch work.
194242736Sjeff */
195242736Sjeff#define	SCHED_SLICE_DEFAULT_DIVISOR	10	/* ~94 ms, 12 stathz ticks. */
196242736Sjeff#define	SCHED_SLICE_MIN_DIVISOR		6	/* DEFAULT/MIN = ~16 ms. */
197242736Sjeff
198239157Smav/* Flags kept in td_flags. */
199239157Smav#define	TDF_SLICEEND	TDF_SCHED2	/* Thread time slice is over. */
200239157Smav
201109864Sjeff/*
202165762Sjeff * tickincr:		Converts a stathz tick into a hz domain scaled by
203165762Sjeff *			the shift factor.  Without the shift the error rate
204165762Sjeff *			due to rounding would be unacceptably high.
205165762Sjeff * realstathz:		stathz is sometimes 0 and run off of hz.
206165762Sjeff * sched_slice:		Runtime of each thread before rescheduling.
207171482Sjeff * preempt_thresh:	Priority threshold for preemption and remote IPIs.
208109864Sjeff */
209165762Sjeffstatic int sched_interact = SCHED_INTERACT_THRESH;
210241844Seadlerstatic int tickincr = 8 << SCHED_TICK_SHIFT;
211242736Sjeffstatic int realstathz = 127;	/* reset during boot. */
212242736Sjeffstatic int sched_slice = 10;	/* reset during boot. */
213242736Sjeffstatic int sched_slice_min = 1;	/* reset during boot. */
214172345Sjeff#ifdef PREEMPTION
215172345Sjeff#ifdef FULL_PREEMPTION
216172345Sjeffstatic int preempt_thresh = PRI_MAX_IDLE;
217172345Sjeff#else
218171482Sjeffstatic int preempt_thresh = PRI_MIN_KERN;
219172345Sjeff#endif
220172345Sjeff#else
221172345Sjeffstatic int preempt_thresh = 0;
222172345Sjeff#endif
223217351Sjhbstatic int static_boost = PRI_MIN_BATCH;
224178277Sjeffstatic int sched_idlespins = 10000;
225232740Smavstatic int sched_idlespinthresh = -1;
226109864Sjeff
227109864Sjeff/*
228171482Sjeff * tdq - per processor runqs and statistics.  All fields are protected by the
229171482Sjeff * tdq_lock.  The load and lowpri may be accessed without to avoid excess
230171482Sjeff * locking in sched_pickcpu();
231109864Sjeff */
232164936Sjulianstruct tdq {
233242014Sjimharris	/*
234242014Sjimharris	 * Ordered to improve efficiency of cpu_search() and switch().
235242014Sjimharris	 * tdq_lock is padded to avoid false sharing with tdq_load and
236242014Sjimharris	 * tdq_cpu_idle.
237242014Sjimharris	 */
238242402Sattilio	struct mtx_padalign tdq_lock;		/* run queue lock. */
239176735Sjeff	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
240178277Sjeff	volatile int	tdq_load;		/* Aggregate load. */
241212416Smav	volatile int	tdq_cpu_idle;		/* cpu_idle() is active. */
242176735Sjeff	int		tdq_sysload;		/* For loadavg, !ITHD load. */
243177009Sjeff	int		tdq_transferable;	/* Transferable thread count. */
244178277Sjeff	short		tdq_switchcnt;		/* Switches this tick. */
245178277Sjeff	short		tdq_oldswitchcnt;	/* Switches last tick. */
246177009Sjeff	u_char		tdq_lowpri;		/* Lowest priority thread. */
247177009Sjeff	u_char		tdq_ipipending;		/* IPI pending. */
248166557Sjeff	u_char		tdq_idx;		/* Current insert index. */
249166557Sjeff	u_char		tdq_ridx;		/* Current removal index. */
250177009Sjeff	struct runq	tdq_realtime;		/* real-time run queue. */
251177009Sjeff	struct runq	tdq_timeshare;		/* timeshare run queue. */
252177009Sjeff	struct runq	tdq_idle;		/* Queue of IDLE threads. */
253187357Sjeff	char		tdq_name[TDQ_NAME_LEN];
254187357Sjeff#ifdef KTR
255187357Sjeff	char		tdq_loadname[TDQ_LOADNAME_LEN];
256187357Sjeff#endif
257171482Sjeff} __aligned(64);
258109864Sjeff
259178277Sjeff/* Idle thread states and config. */
260178277Sjeff#define	TDQ_RUNNING	1
261178277Sjeff#define	TDQ_IDLE	2
262166108Sjeff
263123433Sjeff#ifdef SMP
264184439Sivorasstruct cpu_group *cpu_top;		/* CPU topology */
265123433Sjeff
266176735Sjeff#define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
267176735Sjeff#define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
268166108Sjeff
269123433Sjeff/*
270166108Sjeff * Run-time tunables.
271166108Sjeff */
272171506Sjeffstatic int rebalance = 1;
273172409Sjeffstatic int balance_interval = 128;	/* Default set in sched_initticks(). */
274166108Sjeffstatic int affinity;
275171506Sjeffstatic int steal_idle = 1;
276171506Sjeffstatic int steal_thresh = 2;
277166108Sjeff
278166108Sjeff/*
279165620Sjeff * One thread queue per processor.
280109864Sjeff */
281164936Sjulianstatic struct tdq	tdq_cpu[MAXCPU];
282172409Sjeffstatic struct tdq	*balance_tdq;
283172409Sjeffstatic int balance_ticks;
284232207Smavstatic DPCPU_DEFINE(uint32_t, randomval);
285129982Sjeff
286164936Sjulian#define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
287164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu[(x)])
288171713Sjeff#define	TDQ_ID(x)	((int)((x) - tdq_cpu))
289123433Sjeff#else	/* !SMP */
290164936Sjulianstatic struct tdq	tdq_cpu;
291129982Sjeff
292170315Sjeff#define	TDQ_ID(x)	(0)
293164936Sjulian#define	TDQ_SELF()	(&tdq_cpu)
294164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu)
295110028Sjeff#endif
296109864Sjeff
297171482Sjeff#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
298171482Sjeff#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
299171482Sjeff#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
300171482Sjeff#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
301242402Sattilio#define	TDQ_LOCKPTR(t)		((struct mtx *)(&(t)->tdq_lock))
302171482Sjeff
303163709Sjbstatic void sched_priority(struct thread *);
304146954Sjeffstatic void sched_thread_priority(struct thread *, u_char);
305163709Sjbstatic int sched_interact_score(struct thread *);
306163709Sjbstatic void sched_interact_update(struct thread *);
307163709Sjbstatic void sched_interact_fork(struct thread *);
308232917Smavstatic void sched_pctcpu_update(struct td_sched *, int);
309109864Sjeff
310110267Sjeff/* Operations on per processor queues */
311177435Sjeffstatic struct thread *tdq_choose(struct tdq *);
312164936Sjulianstatic void tdq_setup(struct tdq *);
313177435Sjeffstatic void tdq_load_add(struct tdq *, struct thread *);
314177435Sjeffstatic void tdq_load_rem(struct tdq *, struct thread *);
315177435Sjeffstatic __inline void tdq_runq_add(struct tdq *, struct thread *, int);
316177435Sjeffstatic __inline void tdq_runq_rem(struct tdq *, struct thread *);
317177005Sjeffstatic inline int sched_shouldpreempt(int, int, int);
318164936Sjulianvoid tdq_print(int cpu);
319165762Sjeffstatic void runq_print(struct runq *rq);
320171482Sjeffstatic void tdq_add(struct tdq *, struct thread *, int);
321110267Sjeff#ifdef SMP
322176735Sjeffstatic int tdq_move(struct tdq *, struct tdq *);
323171482Sjeffstatic int tdq_idled(struct tdq *);
324177435Sjeffstatic void tdq_notify(struct tdq *, struct thread *);
325177435Sjeffstatic struct thread *tdq_steal(struct tdq *, int);
326177435Sjeffstatic struct thread *runq_steal(struct runq *, int);
327177435Sjeffstatic int sched_pickcpu(struct thread *, int);
328172409Sjeffstatic void sched_balance(void);
329176735Sjeffstatic int sched_balance_pair(struct tdq *, struct tdq *);
330177435Sjeffstatic inline struct tdq *sched_setcpu(struct thread *, int, int);
331171482Sjeffstatic inline void thread_unblock_switch(struct thread *, struct mtx *);
332171713Sjeffstatic struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
333184439Sivorasstatic int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
334184439Sivorasstatic int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
335184439Sivoras    struct cpu_group *cg, int indent);
336121790Sjeff#endif
337110028Sjeff
338165762Sjeffstatic void sched_setup(void *dummy);
339177253SrwatsonSYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
340165762Sjeff
341165762Sjeffstatic void sched_initticks(void *dummy);
342177253SrwatsonSYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
343177253Srwatson    NULL);
344165762Sjeff
345235459SrstoneSDT_PROVIDER_DEFINE(sched);
346235459Srstone
347235459SrstoneSDT_PROBE_DEFINE3(sched, , , change_pri, change-pri, "struct thread *",
348235459Srstone    "struct proc *", "uint8_t");
349235459SrstoneSDT_PROBE_DEFINE3(sched, , , dequeue, dequeue, "struct thread *",
350235459Srstone    "struct proc *", "void *");
351235459SrstoneSDT_PROBE_DEFINE4(sched, , , enqueue, enqueue, "struct thread *",
352235459Srstone    "struct proc *", "void *", "int");
353235459SrstoneSDT_PROBE_DEFINE4(sched, , , lend_pri, lend-pri, "struct thread *",
354235459Srstone    "struct proc *", "uint8_t", "struct thread *");
355235459SrstoneSDT_PROBE_DEFINE2(sched, , , load_change, load-change, "int", "int");
356235459SrstoneSDT_PROBE_DEFINE2(sched, , , off_cpu, off-cpu, "struct thread *",
357235459Srstone    "struct proc *");
358235459SrstoneSDT_PROBE_DEFINE(sched, , , on_cpu, on-cpu);
359235459SrstoneSDT_PROBE_DEFINE(sched, , , remain_cpu, remain-cpu);
360235459SrstoneSDT_PROBE_DEFINE2(sched, , , surrender, surrender, "struct thread *",
361235459Srstone    "struct proc *");
362235459Srstone
363171482Sjeff/*
364171482Sjeff * Print the threads waiting on a run-queue.
365171482Sjeff */
366165762Sjeffstatic void
367165762Sjeffrunq_print(struct runq *rq)
368165762Sjeff{
369165762Sjeff	struct rqhead *rqh;
370177435Sjeff	struct thread *td;
371165762Sjeff	int pri;
372165762Sjeff	int j;
373165762Sjeff	int i;
374165762Sjeff
375165762Sjeff	for (i = 0; i < RQB_LEN; i++) {
376165762Sjeff		printf("\t\trunq bits %d 0x%zx\n",
377165762Sjeff		    i, rq->rq_status.rqb_bits[i]);
378165762Sjeff		for (j = 0; j < RQB_BPW; j++)
379165762Sjeff			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
380165762Sjeff				pri = j + (i << RQB_L2BPW);
381165762Sjeff				rqh = &rq->rq_queues[pri];
382177435Sjeff				TAILQ_FOREACH(td, rqh, td_runq) {
383165762Sjeff					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
384177435Sjeff					    td, td->td_name, td->td_priority,
385177435Sjeff					    td->td_rqindex, pri);
386165762Sjeff				}
387165762Sjeff			}
388165762Sjeff	}
389165762Sjeff}
390165762Sjeff
391171482Sjeff/*
392171482Sjeff * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
393171482Sjeff */
394113357Sjeffvoid
395164936Sjuliantdq_print(int cpu)
396110267Sjeff{
397164936Sjulian	struct tdq *tdq;
398112994Sjeff
399164936Sjulian	tdq = TDQ_CPU(cpu);
400112994Sjeff
401171713Sjeff	printf("tdq %d:\n", TDQ_ID(tdq));
402176735Sjeff	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
403176735Sjeff	printf("\tLock name:      %s\n", tdq->tdq_name);
404165620Sjeff	printf("\tload:           %d\n", tdq->tdq_load);
405178277Sjeff	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
406178277Sjeff	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
407171482Sjeff	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
408165766Sjeff	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
409178277Sjeff	printf("\tload transferable: %d\n", tdq->tdq_transferable);
410178277Sjeff	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
411165762Sjeff	printf("\trealtime runq:\n");
412165762Sjeff	runq_print(&tdq->tdq_realtime);
413165762Sjeff	printf("\ttimeshare runq:\n");
414165762Sjeff	runq_print(&tdq->tdq_timeshare);
415165762Sjeff	printf("\tidle runq:\n");
416165762Sjeff	runq_print(&tdq->tdq_idle);
417113357Sjeff}
418112994Sjeff
419177005Sjeffstatic inline int
420177005Sjeffsched_shouldpreempt(int pri, int cpri, int remote)
421177005Sjeff{
422177005Sjeff	/*
423177005Sjeff	 * If the new priority is not better than the current priority there is
424177005Sjeff	 * nothing to do.
425177005Sjeff	 */
426177005Sjeff	if (pri >= cpri)
427177005Sjeff		return (0);
428177005Sjeff	/*
429177005Sjeff	 * Always preempt idle.
430177005Sjeff	 */
431177005Sjeff	if (cpri >= PRI_MIN_IDLE)
432177005Sjeff		return (1);
433177005Sjeff	/*
434177005Sjeff	 * If preemption is disabled don't preempt others.
435177005Sjeff	 */
436177005Sjeff	if (preempt_thresh == 0)
437177005Sjeff		return (0);
438177005Sjeff	/*
439177005Sjeff	 * Preempt if we exceed the threshold.
440177005Sjeff	 */
441177005Sjeff	if (pri <= preempt_thresh)
442177005Sjeff		return (1);
443177005Sjeff	/*
444217351Sjhb	 * If we're interactive or better and there is non-interactive
445217351Sjhb	 * or worse running preempt only remote processors.
446177005Sjeff	 */
447217351Sjhb	if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
448177005Sjeff		return (1);
449177005Sjeff	return (0);
450177005Sjeff}
451177005Sjeff
452171482Sjeff/*
453171482Sjeff * Add a thread to the actual run-queue.  Keeps transferable counts up to
454171482Sjeff * date with what is actually on the run-queue.  Selects the correct
455171482Sjeff * queue position for timeshare threads.
456171482Sjeff */
457122744Sjeffstatic __inline void
458177435Sjefftdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
459122744Sjeff{
460177435Sjeff	struct td_sched *ts;
461177042Sjeff	u_char pri;
462177042Sjeff
463171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
464177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
465177009Sjeff
466177435Sjeff	pri = td->td_priority;
467177435Sjeff	ts = td->td_sched;
468177435Sjeff	TD_SET_RUNQ(td);
469177435Sjeff	if (THREAD_CAN_MIGRATE(td)) {
470165620Sjeff		tdq->tdq_transferable++;
471164936Sjulian		ts->ts_flags |= TSF_XFERABLE;
472123433Sjeff	}
473217351Sjhb	if (pri < PRI_MIN_BATCH) {
474177042Sjeff		ts->ts_runq = &tdq->tdq_realtime;
475217351Sjhb	} else if (pri <= PRI_MAX_BATCH) {
476177042Sjeff		ts->ts_runq = &tdq->tdq_timeshare;
477217351Sjhb		KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
478165762Sjeff			("Invalid priority %d on timeshare runq", pri));
479165762Sjeff		/*
480165762Sjeff		 * This queue contains only priorities between MIN and MAX
481165762Sjeff		 * realtime.  Use the whole queue to represent these values.
482165762Sjeff		 */
483171713Sjeff		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
484228718Savg			pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
485165762Sjeff			pri = (pri + tdq->tdq_idx) % RQ_NQS;
486165766Sjeff			/*
487165766Sjeff			 * This effectively shortens the queue by one so we
488165766Sjeff			 * can have a one slot difference between idx and
489165766Sjeff			 * ridx while we wait for threads to drain.
490165766Sjeff			 */
491165766Sjeff			if (tdq->tdq_ridx != tdq->tdq_idx &&
492165766Sjeff			    pri == tdq->tdq_ridx)
493167664Sjeff				pri = (unsigned char)(pri - 1) % RQ_NQS;
494165762Sjeff		} else
495165766Sjeff			pri = tdq->tdq_ridx;
496177435Sjeff		runq_add_pri(ts->ts_runq, td, pri, flags);
497177042Sjeff		return;
498165762Sjeff	} else
499177009Sjeff		ts->ts_runq = &tdq->tdq_idle;
500177435Sjeff	runq_add(ts->ts_runq, td, flags);
501177009Sjeff}
502177009Sjeff
503171482Sjeff/*
504171482Sjeff * Remove a thread from a run-queue.  This typically happens when a thread
505171482Sjeff * is selected to run.  Running threads are not on the queue and the
506171482Sjeff * transferable count does not reflect them.
507171482Sjeff */
508122744Sjeffstatic __inline void
509177435Sjefftdq_runq_rem(struct tdq *tdq, struct thread *td)
510122744Sjeff{
511177435Sjeff	struct td_sched *ts;
512177435Sjeff
513177435Sjeff	ts = td->td_sched;
514171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
515171482Sjeff	KASSERT(ts->ts_runq != NULL,
516177435Sjeff	    ("tdq_runq_remove: thread %p null ts_runq", td));
517164936Sjulian	if (ts->ts_flags & TSF_XFERABLE) {
518165620Sjeff		tdq->tdq_transferable--;
519164936Sjulian		ts->ts_flags &= ~TSF_XFERABLE;
520123433Sjeff	}
521165766Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
522165766Sjeff		if (tdq->tdq_idx != tdq->tdq_ridx)
523177435Sjeff			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
524165766Sjeff		else
525177435Sjeff			runq_remove_idx(ts->ts_runq, td, NULL);
526165766Sjeff	} else
527177435Sjeff		runq_remove(ts->ts_runq, td);
528122744Sjeff}
529122744Sjeff
530171482Sjeff/*
531171482Sjeff * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
532171482Sjeff * for this thread to the referenced thread queue.
533171482Sjeff */
534113357Sjeffstatic void
535177435Sjefftdq_load_add(struct tdq *tdq, struct thread *td)
536113357Sjeff{
537171482Sjeff
538171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
539177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
540177902Sjeff
541165620Sjeff	tdq->tdq_load++;
542198854Sattilio	if ((td->td_flags & TDF_NOLOAD) == 0)
543177902Sjeff		tdq->tdq_sysload++;
544187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
545235459Srstone	SDT_PROBE2(sched, , , load_change, (int)TDQ_ID(tdq), tdq->tdq_load);
546110267Sjeff}
547113357Sjeff
548171482Sjeff/*
549171482Sjeff * Remove the load from a thread that is transitioning to a sleep state or
550171482Sjeff * exiting.
551171482Sjeff */
552112994Sjeffstatic void
553177435Sjefftdq_load_rem(struct tdq *tdq, struct thread *td)
554110267Sjeff{
555171482Sjeff
556177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
557171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
558171482Sjeff	KASSERT(tdq->tdq_load != 0,
559171713Sjeff	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
560177902Sjeff
561165620Sjeff	tdq->tdq_load--;
562198854Sattilio	if ((td->td_flags & TDF_NOLOAD) == 0)
563177902Sjeff		tdq->tdq_sysload--;
564187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
565235459Srstone	SDT_PROBE2(sched, , , load_change, (int)TDQ_ID(tdq), tdq->tdq_load);
566110267Sjeff}
567110267Sjeff
568176735Sjeff/*
569242736Sjeff * Bound timeshare latency by decreasing slice size as load increases.  We
570242736Sjeff * consider the maximum latency as the sum of the threads waiting to run
571242736Sjeff * aside from curthread and target no more than sched_slice latency but
572242736Sjeff * no less than sched_slice_min runtime.
573242736Sjeff */
574242736Sjeffstatic inline int
575242736Sjefftdq_slice(struct tdq *tdq)
576242736Sjeff{
577242736Sjeff	int load;
578242736Sjeff
579242736Sjeff	/*
580242736Sjeff	 * It is safe to use sys_load here because this is called from
581242736Sjeff	 * contexts where timeshare threads are running and so there
582242736Sjeff	 * cannot be higher priority load in the system.
583242736Sjeff	 */
584242736Sjeff	load = tdq->tdq_sysload - 1;
585242736Sjeff	if (load >= SCHED_SLICE_MIN_DIVISOR)
586242736Sjeff		return (sched_slice_min);
587242736Sjeff	if (load <= 1)
588242736Sjeff		return (sched_slice);
589242736Sjeff	return (sched_slice / load);
590242736Sjeff}
591242736Sjeff
592242736Sjeff/*
593176735Sjeff * Set lowpri to its exact value by searching the run-queue and
594176735Sjeff * evaluating curthread.  curthread may be passed as an optimization.
595176735Sjeff */
596176735Sjeffstatic void
597176735Sjefftdq_setlowpri(struct tdq *tdq, struct thread *ctd)
598176735Sjeff{
599176735Sjeff	struct thread *td;
600176735Sjeff
601176735Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
602176735Sjeff	if (ctd == NULL)
603176735Sjeff		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
604177435Sjeff	td = tdq_choose(tdq);
605177435Sjeff	if (td == NULL || td->td_priority > ctd->td_priority)
606176735Sjeff		tdq->tdq_lowpri = ctd->td_priority;
607176735Sjeff	else
608176735Sjeff		tdq->tdq_lowpri = td->td_priority;
609176735Sjeff}
610176735Sjeff
611113357Sjeff#ifdef SMP
612176735Sjeffstruct cpu_search {
613194779Sjeff	cpuset_t cs_mask;
614232207Smav	u_int	cs_prefer;
615232207Smav	int	cs_pri;		/* Min priority for low. */
616232207Smav	int	cs_limit;	/* Max load for low, min load for high. */
617232207Smav	int	cs_cpu;
618232207Smav	int	cs_load;
619176735Sjeff};
620176735Sjeff
621176735Sjeff#define	CPU_SEARCH_LOWEST	0x1
622176735Sjeff#define	CPU_SEARCH_HIGHEST	0x2
623176735Sjeff#define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
624176735Sjeff
625194779Sjeff#define	CPUSET_FOREACH(cpu, mask)				\
626194779Sjeff	for ((cpu) = 0; (cpu) <= mp_maxid; (cpu)++)		\
627222813Sattilio		if (CPU_ISSET(cpu, &mask))
628176735Sjeff
629232207Smavstatic __inline int cpu_search(const struct cpu_group *cg, struct cpu_search *low,
630176735Sjeff    struct cpu_search *high, const int match);
631232207Smavint cpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low);
632232207Smavint cpu_search_highest(const struct cpu_group *cg, struct cpu_search *high);
633232207Smavint cpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
634176735Sjeff    struct cpu_search *high);
635176735Sjeff
636116069Sjeff/*
637176735Sjeff * Search the tree of cpu_groups for the lowest or highest loaded cpu
638176735Sjeff * according to the match argument.  This routine actually compares the
639176735Sjeff * load on all paths through the tree and finds the least loaded cpu on
640176735Sjeff * the least loaded path, which may differ from the least loaded cpu in
641176735Sjeff * the system.  This balances work among caches and busses.
642116069Sjeff *
643176735Sjeff * This inline is instantiated in three forms below using constants for the
644176735Sjeff * match argument.  It is reduced to the minimum set for each case.  It is
645176735Sjeff * also recursive to the depth of the tree.
646116069Sjeff */
647177169Sjhbstatic __inline int
648232207Smavcpu_search(const struct cpu_group *cg, struct cpu_search *low,
649176735Sjeff    struct cpu_search *high, const int match)
650176735Sjeff{
651232207Smav	struct cpu_search lgroup;
652232207Smav	struct cpu_search hgroup;
653232207Smav	cpuset_t cpumask;
654232207Smav	struct cpu_group *child;
655232207Smav	struct tdq *tdq;
656234066Smav	int cpu, i, hload, lload, load, total, rnd, *rndptr;
657176735Sjeff
658176735Sjeff	total = 0;
659232207Smav	cpumask = cg->cg_mask;
660232207Smav	if (match & CPU_SEARCH_LOWEST) {
661232207Smav		lload = INT_MAX;
662232207Smav		lgroup = *low;
663232207Smav	}
664232207Smav	if (match & CPU_SEARCH_HIGHEST) {
665234066Smav		hload = INT_MIN;
666232207Smav		hgroup = *high;
667232207Smav	}
668176735Sjeff
669232207Smav	/* Iterate through the child CPU groups and then remaining CPUs. */
670234066Smav	for (i = cg->cg_children, cpu = mp_maxid; i >= 0; ) {
671234066Smav		if (i == 0) {
672234066Smav			while (cpu >= 0 && !CPU_ISSET(cpu, &cpumask))
673234066Smav				cpu--;
674234066Smav			if (cpu < 0)
675232207Smav				break;
676232207Smav			child = NULL;
677232207Smav		} else
678234066Smav			child = &cg->cg_child[i - 1];
679232207Smav
680234066Smav		if (match & CPU_SEARCH_LOWEST)
681234066Smav			lgroup.cs_cpu = -1;
682234066Smav		if (match & CPU_SEARCH_HIGHEST)
683234066Smav			hgroup.cs_cpu = -1;
684232207Smav		if (child) {			/* Handle child CPU group. */
685232207Smav			CPU_NAND(&cpumask, &child->cg_mask);
686176735Sjeff			switch (match) {
687176735Sjeff			case CPU_SEARCH_LOWEST:
688176735Sjeff				load = cpu_search_lowest(child, &lgroup);
689176735Sjeff				break;
690176735Sjeff			case CPU_SEARCH_HIGHEST:
691176735Sjeff				load = cpu_search_highest(child, &hgroup);
692176735Sjeff				break;
693176735Sjeff			case CPU_SEARCH_BOTH:
694176735Sjeff				load = cpu_search_both(child, &lgroup, &hgroup);
695176735Sjeff				break;
696176735Sjeff			}
697232207Smav		} else {			/* Handle child CPU. */
698232207Smav			tdq = TDQ_CPU(cpu);
699232207Smav			load = tdq->tdq_load * 256;
700234066Smav			rndptr = DPCPU_PTR(randomval);
701234066Smav			rnd = (*rndptr = *rndptr * 69069 + 5) >> 26;
702232207Smav			if (match & CPU_SEARCH_LOWEST) {
703232207Smav				if (cpu == low->cs_prefer)
704232207Smav					load -= 64;
705232207Smav				/* If that CPU is allowed and get data. */
706234066Smav				if (tdq->tdq_lowpri > lgroup.cs_pri &&
707234066Smav				    tdq->tdq_load <= lgroup.cs_limit &&
708234066Smav				    CPU_ISSET(cpu, &lgroup.cs_mask)) {
709232207Smav					lgroup.cs_cpu = cpu;
710232207Smav					lgroup.cs_load = load - rnd;
711176735Sjeff				}
712232207Smav			}
713232207Smav			if (match & CPU_SEARCH_HIGHEST)
714234066Smav				if (tdq->tdq_load >= hgroup.cs_limit &&
715234066Smav				    tdq->tdq_transferable &&
716234066Smav				    CPU_ISSET(cpu, &hgroup.cs_mask)) {
717232207Smav					hgroup.cs_cpu = cpu;
718232207Smav					hgroup.cs_load = load - rnd;
719176735Sjeff				}
720176735Sjeff		}
721232207Smav		total += load;
722176735Sjeff
723232207Smav		/* We have info about child item. Compare it. */
724232207Smav		if (match & CPU_SEARCH_LOWEST) {
725234066Smav			if (lgroup.cs_cpu >= 0 &&
726232454Smav			    (load < lload ||
727232454Smav			     (load == lload && lgroup.cs_load < low->cs_load))) {
728232207Smav				lload = load;
729232207Smav				low->cs_cpu = lgroup.cs_cpu;
730232207Smav				low->cs_load = lgroup.cs_load;
731232207Smav			}
732232207Smav		}
733232207Smav		if (match & CPU_SEARCH_HIGHEST)
734234066Smav			if (hgroup.cs_cpu >= 0 &&
735232454Smav			    (load > hload ||
736232454Smav			     (load == hload && hgroup.cs_load > high->cs_load))) {
737232207Smav				hload = load;
738232207Smav				high->cs_cpu = hgroup.cs_cpu;
739232207Smav				high->cs_load = hgroup.cs_load;
740232207Smav			}
741234066Smav		if (child) {
742234066Smav			i--;
743234066Smav			if (i == 0 && CPU_EMPTY(&cpumask))
744234066Smav				break;
745234066Smav		} else
746234066Smav			cpu--;
747176735Sjeff	}
748176735Sjeff	return (total);
749176735Sjeff}
750176735Sjeff
751176735Sjeff/*
752176735Sjeff * cpu_search instantiations must pass constants to maintain the inline
753176735Sjeff * optimization.
754176735Sjeff */
755176735Sjeffint
756232207Smavcpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low)
757176735Sjeff{
758176735Sjeff	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
759176735Sjeff}
760176735Sjeff
761176735Sjeffint
762232207Smavcpu_search_highest(const struct cpu_group *cg, struct cpu_search *high)
763176735Sjeff{
764176735Sjeff	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
765176735Sjeff}
766176735Sjeff
767176735Sjeffint
768232207Smavcpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
769176735Sjeff    struct cpu_search *high)
770176735Sjeff{
771176735Sjeff	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
772176735Sjeff}
773176735Sjeff
774176735Sjeff/*
775176735Sjeff * Find the cpu with the least load via the least loaded path that has a
776176735Sjeff * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
777176735Sjeff * acceptable.
778176735Sjeff */
779176735Sjeffstatic inline int
780232207Smavsched_lowest(const struct cpu_group *cg, cpuset_t mask, int pri, int maxload,
781232207Smav    int prefer)
782176735Sjeff{
783176735Sjeff	struct cpu_search low;
784176735Sjeff
785176735Sjeff	low.cs_cpu = -1;
786232207Smav	low.cs_prefer = prefer;
787176735Sjeff	low.cs_mask = mask;
788232207Smav	low.cs_pri = pri;
789232207Smav	low.cs_limit = maxload;
790176735Sjeff	cpu_search_lowest(cg, &low);
791176735Sjeff	return low.cs_cpu;
792176735Sjeff}
793176735Sjeff
794176735Sjeff/*
795176735Sjeff * Find the cpu with the highest load via the highest loaded path.
796176735Sjeff */
797176735Sjeffstatic inline int
798232207Smavsched_highest(const struct cpu_group *cg, cpuset_t mask, int minload)
799176735Sjeff{
800176735Sjeff	struct cpu_search high;
801176735Sjeff
802176735Sjeff	high.cs_cpu = -1;
803176735Sjeff	high.cs_mask = mask;
804176735Sjeff	high.cs_limit = minload;
805176735Sjeff	cpu_search_highest(cg, &high);
806176735Sjeff	return high.cs_cpu;
807176735Sjeff}
808176735Sjeff
809176735Sjeff/*
810176735Sjeff * Simultaneously find the highest and lowest loaded cpu reachable via
811176735Sjeff * cg.
812176735Sjeff */
813232207Smavstatic inline void
814232207Smavsched_both(const struct cpu_group *cg, cpuset_t mask, int *lowcpu, int *highcpu)
815176735Sjeff{
816176735Sjeff	struct cpu_search high;
817176735Sjeff	struct cpu_search low;
818176735Sjeff
819176735Sjeff	low.cs_cpu = -1;
820232207Smav	low.cs_prefer = -1;
821232207Smav	low.cs_pri = -1;
822232207Smav	low.cs_limit = INT_MAX;
823176735Sjeff	low.cs_mask = mask;
824176735Sjeff	high.cs_cpu = -1;
825176735Sjeff	high.cs_limit = -1;
826176735Sjeff	high.cs_mask = mask;
827176735Sjeff	cpu_search_both(cg, &low, &high);
828176735Sjeff	*lowcpu = low.cs_cpu;
829176735Sjeff	*highcpu = high.cs_cpu;
830176735Sjeff	return;
831176735Sjeff}
832176735Sjeff
833121790Sjeffstatic void
834176735Sjeffsched_balance_group(struct cpu_group *cg)
835116069Sjeff{
836232207Smav	cpuset_t hmask, lmask;
837232207Smav	int high, low, anylow;
838123487Sjeff
839232207Smav	CPU_FILL(&hmask);
840176735Sjeff	for (;;) {
841232207Smav		high = sched_highest(cg, hmask, 1);
842232207Smav		/* Stop if there is no more CPU with transferrable threads. */
843232207Smav		if (high == -1)
844176735Sjeff			break;
845232207Smav		CPU_CLR(high, &hmask);
846232207Smav		CPU_COPY(&hmask, &lmask);
847232207Smav		/* Stop if there is no more CPU left for low. */
848232207Smav		if (CPU_EMPTY(&lmask))
849176735Sjeff			break;
850232207Smav		anylow = 1;
851232207Smavnextlow:
852232207Smav		low = sched_lowest(cg, lmask, -1,
853232207Smav		    TDQ_CPU(high)->tdq_load - 1, high);
854232207Smav		/* Stop if we looked well and found no less loaded CPU. */
855232207Smav		if (anylow && low == -1)
856232207Smav			break;
857232207Smav		/* Go to next high if we found no less loaded CPU. */
858232207Smav		if (low == -1)
859232207Smav			continue;
860232207Smav		/* Transfer thread from high to low. */
861232207Smav		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low))) {
862232207Smav			/* CPU that got thread can no longer be a donor. */
863232207Smav			CPU_CLR(low, &hmask);
864232207Smav		} else {
865232207Smav			/*
866232207Smav			 * If failed, then there is no threads on high
867232207Smav			 * that can run on this low. Drop low from low
868232207Smav			 * mask and look for different one.
869232207Smav			 */
870232207Smav			CPU_CLR(low, &lmask);
871232207Smav			anylow = 0;
872232207Smav			goto nextlow;
873232207Smav		}
874123487Sjeff	}
875123487Sjeff}
876123487Sjeff
877123487Sjeffstatic void
878201148Sedsched_balance(void)
879123487Sjeff{
880172409Sjeff	struct tdq *tdq;
881123487Sjeff
882172409Sjeff	/*
883172409Sjeff	 * Select a random time between .5 * balance_interval and
884172409Sjeff	 * 1.5 * balance_interval.
885172409Sjeff	 */
886176735Sjeff	balance_ticks = max(balance_interval / 2, 1);
887176735Sjeff	balance_ticks += random() % balance_interval;
888171482Sjeff	if (smp_started == 0 || rebalance == 0)
889171482Sjeff		return;
890172409Sjeff	tdq = TDQ_SELF();
891172409Sjeff	TDQ_UNLOCK(tdq);
892176735Sjeff	sched_balance_group(cpu_top);
893172409Sjeff	TDQ_LOCK(tdq);
894123487Sjeff}
895123487Sjeff
896171482Sjeff/*
897171482Sjeff * Lock two thread queues using their address to maintain lock order.
898171482Sjeff */
899123487Sjeffstatic void
900171482Sjefftdq_lock_pair(struct tdq *one, struct tdq *two)
901171482Sjeff{
902171482Sjeff	if (one < two) {
903171482Sjeff		TDQ_LOCK(one);
904171482Sjeff		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
905171482Sjeff	} else {
906171482Sjeff		TDQ_LOCK(two);
907171482Sjeff		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
908171482Sjeff	}
909171482Sjeff}
910171482Sjeff
911171482Sjeff/*
912172409Sjeff * Unlock two thread queues.  Order is not important here.
913172409Sjeff */
914172409Sjeffstatic void
915172409Sjefftdq_unlock_pair(struct tdq *one, struct tdq *two)
916172409Sjeff{
917172409Sjeff	TDQ_UNLOCK(one);
918172409Sjeff	TDQ_UNLOCK(two);
919172409Sjeff}
920172409Sjeff
921172409Sjeff/*
922171482Sjeff * Transfer load between two imbalanced thread queues.
923171482Sjeff */
924176735Sjeffstatic int
925164936Sjuliansched_balance_pair(struct tdq *high, struct tdq *low)
926123487Sjeff{
927176735Sjeff	int moved;
928226057Smarius	int cpu;
929116069Sjeff
930171482Sjeff	tdq_lock_pair(high, low);
931176735Sjeff	moved = 0;
932116069Sjeff	/*
933122744Sjeff	 * Determine what the imbalance is and then adjust that to how many
934165620Sjeff	 * threads we actually have to give up (transferable).
935122744Sjeff	 */
936232207Smav	if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load &&
937232207Smav	    (moved = tdq_move(high, low)) > 0) {
938172293Sjeff		/*
939226057Smarius		 * In case the target isn't the current cpu IPI it to force a
940226057Smarius		 * reschedule with the new workload.
941172293Sjeff		 */
942226057Smarius		cpu = TDQ_ID(low);
943226057Smarius		if (cpu != PCPU_GET(cpuid))
944226057Smarius			ipi_cpu(cpu, IPI_PREEMPT);
945171482Sjeff	}
946172409Sjeff	tdq_unlock_pair(high, low);
947176735Sjeff	return (moved);
948116069Sjeff}
949116069Sjeff
950171482Sjeff/*
951171482Sjeff * Move a thread from one thread queue to another.
952171482Sjeff */
953176735Sjeffstatic int
954171482Sjefftdq_move(struct tdq *from, struct tdq *to)
955116069Sjeff{
956171482Sjeff	struct td_sched *ts;
957171482Sjeff	struct thread *td;
958164936Sjulian	struct tdq *tdq;
959171482Sjeff	int cpu;
960116069Sjeff
961172409Sjeff	TDQ_LOCK_ASSERT(from, MA_OWNED);
962172409Sjeff	TDQ_LOCK_ASSERT(to, MA_OWNED);
963172409Sjeff
964164936Sjulian	tdq = from;
965171482Sjeff	cpu = TDQ_ID(to);
966177435Sjeff	td = tdq_steal(tdq, cpu);
967177435Sjeff	if (td == NULL)
968176735Sjeff		return (0);
969177435Sjeff	ts = td->td_sched;
970171482Sjeff	/*
971171482Sjeff	 * Although the run queue is locked the thread may be blocked.  Lock
972172409Sjeff	 * it to clear this and acquire the run-queue lock.
973171482Sjeff	 */
974171482Sjeff	thread_lock(td);
975172409Sjeff	/* Drop recursive lock on from acquired via thread_lock(). */
976171482Sjeff	TDQ_UNLOCK(from);
977171482Sjeff	sched_rem(td);
978166108Sjeff	ts->ts_cpu = cpu;
979171482Sjeff	td->td_lock = TDQ_LOCKPTR(to);
980171482Sjeff	tdq_add(to, td, SRQ_YIELDING);
981176735Sjeff	return (1);
982116069Sjeff}
983110267Sjeff
984171482Sjeff/*
985171482Sjeff * This tdq has idled.  Try to steal a thread from another cpu and switch
986171482Sjeff * to it.
987171482Sjeff */
988123433Sjeffstatic int
989164936Sjuliantdq_idled(struct tdq *tdq)
990121790Sjeff{
991176735Sjeff	struct cpu_group *cg;
992164936Sjulian	struct tdq *steal;
993194779Sjeff	cpuset_t mask;
994176735Sjeff	int thresh;
995171482Sjeff	int cpu;
996123433Sjeff
997172484Sjeff	if (smp_started == 0 || steal_idle == 0)
998172484Sjeff		return (1);
999194779Sjeff	CPU_FILL(&mask);
1000194779Sjeff	CPU_CLR(PCPU_GET(cpuid), &mask);
1001176735Sjeff	/* We don't want to be preempted while we're iterating. */
1002171482Sjeff	spinlock_enter();
1003176735Sjeff	for (cg = tdq->tdq_cg; cg != NULL; ) {
1004191643Sjeff		if ((cg->cg_flags & CG_FLAG_THREAD) == 0)
1005176735Sjeff			thresh = steal_thresh;
1006176735Sjeff		else
1007176735Sjeff			thresh = 1;
1008176735Sjeff		cpu = sched_highest(cg, mask, thresh);
1009176735Sjeff		if (cpu == -1) {
1010176735Sjeff			cg = cg->cg_parent;
1011176735Sjeff			continue;
1012166108Sjeff		}
1013176735Sjeff		steal = TDQ_CPU(cpu);
1014194779Sjeff		CPU_CLR(cpu, &mask);
1015176735Sjeff		tdq_lock_pair(tdq, steal);
1016176735Sjeff		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
1017176735Sjeff			tdq_unlock_pair(tdq, steal);
1018176735Sjeff			continue;
1019171482Sjeff		}
1020176735Sjeff		/*
1021176735Sjeff		 * If a thread was added while interrupts were disabled don't
1022176735Sjeff		 * steal one here.  If we fail to acquire one due to affinity
1023176735Sjeff		 * restrictions loop again with this cpu removed from the
1024176735Sjeff		 * set.
1025176735Sjeff		 */
1026176735Sjeff		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
1027176735Sjeff			tdq_unlock_pair(tdq, steal);
1028176735Sjeff			continue;
1029176735Sjeff		}
1030176735Sjeff		spinlock_exit();
1031176735Sjeff		TDQ_UNLOCK(steal);
1032178272Sjeff		mi_switch(SW_VOL | SWT_IDLE, NULL);
1033176735Sjeff		thread_unlock(curthread);
1034176735Sjeff
1035176735Sjeff		return (0);
1036123433Sjeff	}
1037171482Sjeff	spinlock_exit();
1038123433Sjeff	return (1);
1039121790Sjeff}
1040121790Sjeff
1041171482Sjeff/*
1042171482Sjeff * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
1043171482Sjeff */
1044121790Sjeffstatic void
1045177435Sjefftdq_notify(struct tdq *tdq, struct thread *td)
1046121790Sjeff{
1047185047Sjhb	struct thread *ctd;
1048166247Sjeff	int pri;
1049166108Sjeff	int cpu;
1050121790Sjeff
1051177005Sjeff	if (tdq->tdq_ipipending)
1052177005Sjeff		return;
1053177435Sjeff	cpu = td->td_sched->ts_cpu;
1054177435Sjeff	pri = td->td_priority;
1055185047Sjhb	ctd = pcpu_find(cpu)->pc_curthread;
1056185047Sjhb	if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
1057166137Sjeff		return;
1058185047Sjhb	if (TD_IS_IDLETHREAD(ctd)) {
1059178277Sjeff		/*
1060178471Sjeff		 * If the MD code has an idle wakeup routine try that before
1061178471Sjeff		 * falling back to IPI.
1062178471Sjeff		 */
1063212416Smav		if (!tdq->tdq_cpu_idle || cpu_idle_wakeup(cpu))
1064178471Sjeff			return;
1065178277Sjeff	}
1066177005Sjeff	tdq->tdq_ipipending = 1;
1067210939Sjhb	ipi_cpu(cpu, IPI_PREEMPT);
1068121790Sjeff}
1069121790Sjeff
1070171482Sjeff/*
1071171482Sjeff * Steals load from a timeshare queue.  Honors the rotating queue head
1072171482Sjeff * index.
1073171482Sjeff */
1074177435Sjeffstatic struct thread *
1075176735Sjeffrunq_steal_from(struct runq *rq, int cpu, u_char start)
1076171482Sjeff{
1077171482Sjeff	struct rqbits *rqb;
1078171482Sjeff	struct rqhead *rqh;
1079232207Smav	struct thread *td, *first;
1080171482Sjeff	int bit;
1081171482Sjeff	int pri;
1082171482Sjeff	int i;
1083171482Sjeff
1084171482Sjeff	rqb = &rq->rq_status;
1085171482Sjeff	bit = start & (RQB_BPW -1);
1086171482Sjeff	pri = 0;
1087232207Smav	first = NULL;
1088171482Sjeffagain:
1089171482Sjeff	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1090171482Sjeff		if (rqb->rqb_bits[i] == 0)
1091171482Sjeff			continue;
1092171482Sjeff		if (bit != 0) {
1093171482Sjeff			for (pri = bit; pri < RQB_BPW; pri++)
1094171482Sjeff				if (rqb->rqb_bits[i] & (1ul << pri))
1095171482Sjeff					break;
1096171482Sjeff			if (pri >= RQB_BPW)
1097171482Sjeff				continue;
1098171482Sjeff		} else
1099171482Sjeff			pri = RQB_FFS(rqb->rqb_bits[i]);
1100171482Sjeff		pri += (i << RQB_L2BPW);
1101171482Sjeff		rqh = &rq->rq_queues[pri];
1102177435Sjeff		TAILQ_FOREACH(td, rqh, td_runq) {
1103177435Sjeff			if (first && THREAD_CAN_MIGRATE(td) &&
1104177435Sjeff			    THREAD_CAN_SCHED(td, cpu))
1105177435Sjeff				return (td);
1106232207Smav			first = td;
1107171482Sjeff		}
1108171482Sjeff	}
1109171482Sjeff	if (start != 0) {
1110171482Sjeff		start = 0;
1111171482Sjeff		goto again;
1112171482Sjeff	}
1113171482Sjeff
1114232207Smav	if (first && THREAD_CAN_MIGRATE(first) &&
1115232207Smav	    THREAD_CAN_SCHED(first, cpu))
1116232207Smav		return (first);
1117171482Sjeff	return (NULL);
1118171482Sjeff}
1119171482Sjeff
1120171482Sjeff/*
1121171482Sjeff * Steals load from a standard linear queue.
1122171482Sjeff */
1123177435Sjeffstatic struct thread *
1124176735Sjeffrunq_steal(struct runq *rq, int cpu)
1125121790Sjeff{
1126121790Sjeff	struct rqhead *rqh;
1127121790Sjeff	struct rqbits *rqb;
1128177435Sjeff	struct thread *td;
1129121790Sjeff	int word;
1130121790Sjeff	int bit;
1131121790Sjeff
1132121790Sjeff	rqb = &rq->rq_status;
1133121790Sjeff	for (word = 0; word < RQB_LEN; word++) {
1134121790Sjeff		if (rqb->rqb_bits[word] == 0)
1135121790Sjeff			continue;
1136121790Sjeff		for (bit = 0; bit < RQB_BPW; bit++) {
1137123231Speter			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
1138121790Sjeff				continue;
1139121790Sjeff			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
1140177435Sjeff			TAILQ_FOREACH(td, rqh, td_runq)
1141177435Sjeff				if (THREAD_CAN_MIGRATE(td) &&
1142177435Sjeff				    THREAD_CAN_SCHED(td, cpu))
1143177435Sjeff					return (td);
1144121790Sjeff		}
1145121790Sjeff	}
1146121790Sjeff	return (NULL);
1147121790Sjeff}
1148121790Sjeff
1149171482Sjeff/*
1150171482Sjeff * Attempt to steal a thread in priority order from a thread queue.
1151171482Sjeff */
1152177435Sjeffstatic struct thread *
1153176735Sjefftdq_steal(struct tdq *tdq, int cpu)
1154121790Sjeff{
1155177435Sjeff	struct thread *td;
1156121790Sjeff
1157171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1158177435Sjeff	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
1159177435Sjeff		return (td);
1160177435Sjeff	if ((td = runq_steal_from(&tdq->tdq_timeshare,
1161177435Sjeff	    cpu, tdq->tdq_ridx)) != NULL)
1162177435Sjeff		return (td);
1163176735Sjeff	return (runq_steal(&tdq->tdq_idle, cpu));
1164121790Sjeff}
1165123433Sjeff
1166171482Sjeff/*
1167171482Sjeff * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
1168172409Sjeff * current lock and returns with the assigned queue locked.
1169171482Sjeff */
1170171482Sjeffstatic inline struct tdq *
1171177435Sjeffsched_setcpu(struct thread *td, int cpu, int flags)
1172123433Sjeff{
1173177435Sjeff
1174171482Sjeff	struct tdq *tdq;
1175123433Sjeff
1176177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1177171482Sjeff	tdq = TDQ_CPU(cpu);
1178177435Sjeff	td->td_sched->ts_cpu = cpu;
1179177435Sjeff	/*
1180177435Sjeff	 * If the lock matches just return the queue.
1181177435Sjeff	 */
1182171482Sjeff	if (td->td_lock == TDQ_LOCKPTR(tdq))
1183171482Sjeff		return (tdq);
1184171482Sjeff#ifdef notyet
1185123433Sjeff	/*
1186172293Sjeff	 * If the thread isn't running its lockptr is a
1187171482Sjeff	 * turnstile or a sleepqueue.  We can just lock_set without
1188171482Sjeff	 * blocking.
1189123685Sjeff	 */
1190171482Sjeff	if (TD_CAN_RUN(td)) {
1191171482Sjeff		TDQ_LOCK(tdq);
1192171482Sjeff		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1193171482Sjeff		return (tdq);
1194171482Sjeff	}
1195171482Sjeff#endif
1196166108Sjeff	/*
1197171482Sjeff	 * The hard case, migration, we need to block the thread first to
1198171482Sjeff	 * prevent order reversals with other cpus locks.
1199166108Sjeff	 */
1200202889Sattilio	spinlock_enter();
1201171482Sjeff	thread_lock_block(td);
1202171482Sjeff	TDQ_LOCK(tdq);
1203171713Sjeff	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1204202889Sattilio	spinlock_exit();
1205171482Sjeff	return (tdq);
1206166108Sjeff}
1207166108Sjeff
1208178272SjeffSCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
1209178272SjeffSCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
1210178272SjeffSCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
1211178272SjeffSCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
1212178272SjeffSCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
1213178272SjeffSCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
1214178272Sjeff
1215166108Sjeffstatic int
1216177435Sjeffsched_pickcpu(struct thread *td, int flags)
1217171482Sjeff{
1218232207Smav	struct cpu_group *cg, *ccg;
1219177435Sjeff	struct td_sched *ts;
1220171482Sjeff	struct tdq *tdq;
1221194779Sjeff	cpuset_t mask;
1222232207Smav	int cpu, pri, self;
1223166108Sjeff
1224176735Sjeff	self = PCPU_GET(cpuid);
1225177435Sjeff	ts = td->td_sched;
1226166108Sjeff	if (smp_started == 0)
1227166108Sjeff		return (self);
1228171506Sjeff	/*
1229171506Sjeff	 * Don't migrate a running thread from sched_switch().
1230171506Sjeff	 */
1231176735Sjeff	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1232176735Sjeff		return (ts->ts_cpu);
1233166108Sjeff	/*
1234176735Sjeff	 * Prefer to run interrupt threads on the processors that generate
1235176735Sjeff	 * the interrupt.
1236166108Sjeff	 */
1237232207Smav	pri = td->td_priority;
1238176735Sjeff	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1239178272Sjeff	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
1240178272Sjeff		SCHED_STAT_INC(pickcpu_intrbind);
1241176735Sjeff		ts->ts_cpu = self;
1242232207Smav		if (TDQ_CPU(self)->tdq_lowpri > pri) {
1243232207Smav			SCHED_STAT_INC(pickcpu_affinity);
1244232207Smav			return (ts->ts_cpu);
1245232207Smav		}
1246178272Sjeff	}
1247166108Sjeff	/*
1248176735Sjeff	 * If the thread can run on the last cpu and the affinity has not
1249176735Sjeff	 * expired or it is idle run it there.
1250166108Sjeff	 */
1251176735Sjeff	tdq = TDQ_CPU(ts->ts_cpu);
1252232207Smav	cg = tdq->tdq_cg;
1253232207Smav	if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
1254232207Smav	    tdq->tdq_lowpri >= PRI_MIN_IDLE &&
1255232207Smav	    SCHED_AFFINITY(ts, CG_SHARE_L2)) {
1256232207Smav		if (cg->cg_flags & CG_FLAG_THREAD) {
1257232207Smav			CPUSET_FOREACH(cpu, cg->cg_mask) {
1258232207Smav				if (TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE)
1259232207Smav					break;
1260232207Smav			}
1261232207Smav		} else
1262232207Smav			cpu = INT_MAX;
1263232207Smav		if (cpu > mp_maxid) {
1264178272Sjeff			SCHED_STAT_INC(pickcpu_idle_affinity);
1265176735Sjeff			return (ts->ts_cpu);
1266178272Sjeff		}
1267139334Sjeff	}
1268123433Sjeff	/*
1269232207Smav	 * Search for the last level cache CPU group in the tree.
1270232207Smav	 * Skip caches with expired affinity time and SMT groups.
1271232207Smav	 * Affinity to higher level caches will be handled less aggressively.
1272123433Sjeff	 */
1273232207Smav	for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
1274232207Smav		if (cg->cg_flags & CG_FLAG_THREAD)
1275232207Smav			continue;
1276232207Smav		if (!SCHED_AFFINITY(ts, cg->cg_level))
1277232207Smav			continue;
1278232207Smav		ccg = cg;
1279232207Smav	}
1280232207Smav	if (ccg != NULL)
1281232207Smav		cg = ccg;
1282176735Sjeff	cpu = -1;
1283232207Smav	/* Search the group for the less loaded idle CPU we can run now. */
1284194779Sjeff	mask = td->td_cpuset->cs_mask;
1285232207Smav	if (cg != NULL && cg != cpu_top &&
1286232207Smav	    CPU_CMP(&cg->cg_mask, &cpu_top->cg_mask) != 0)
1287232207Smav		cpu = sched_lowest(cg, mask, max(pri, PRI_MAX_TIMESHARE),
1288232207Smav		    INT_MAX, ts->ts_cpu);
1289232207Smav	/* Search globally for the less loaded CPU we can run now. */
1290176735Sjeff	if (cpu == -1)
1291232207Smav		cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu);
1292232207Smav	/* Search globally for the less loaded CPU. */
1293232207Smav	if (cpu == -1)
1294232207Smav		cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu);
1295232454Smav	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1296171506Sjeff	/*
1297176735Sjeff	 * Compare the lowest loaded cpu to current cpu.
1298171506Sjeff	 */
1299177005Sjeff	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
1300232207Smav	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE &&
1301232207Smav	    TDQ_CPU(self)->tdq_load <= TDQ_CPU(cpu)->tdq_load + 1) {
1302178272Sjeff		SCHED_STAT_INC(pickcpu_local);
1303177005Sjeff		cpu = self;
1304178272Sjeff	} else
1305178272Sjeff		SCHED_STAT_INC(pickcpu_lowest);
1306178272Sjeff	if (cpu != ts->ts_cpu)
1307178272Sjeff		SCHED_STAT_INC(pickcpu_migration);
1308171482Sjeff	return (cpu);
1309123433Sjeff}
1310176735Sjeff#endif
1311123433Sjeff
1312117326Sjeff/*
1313121790Sjeff * Pick the highest priority task we have and return it.
1314117326Sjeff */
1315177435Sjeffstatic struct thread *
1316164936Sjuliantdq_choose(struct tdq *tdq)
1317110267Sjeff{
1318177435Sjeff	struct thread *td;
1319110267Sjeff
1320171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1321177435Sjeff	td = runq_choose(&tdq->tdq_realtime);
1322177435Sjeff	if (td != NULL)
1323177435Sjeff		return (td);
1324177435Sjeff	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1325177435Sjeff	if (td != NULL) {
1326217351Sjhb		KASSERT(td->td_priority >= PRI_MIN_BATCH,
1327165762Sjeff		    ("tdq_choose: Invalid priority on timeshare queue %d",
1328177435Sjeff		    td->td_priority));
1329177435Sjeff		return (td);
1330165762Sjeff	}
1331177435Sjeff	td = runq_choose(&tdq->tdq_idle);
1332177435Sjeff	if (td != NULL) {
1333177435Sjeff		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1334165762Sjeff		    ("tdq_choose: Invalid priority on idle queue %d",
1335177435Sjeff		    td->td_priority));
1336177435Sjeff		return (td);
1337165762Sjeff	}
1338165762Sjeff
1339165762Sjeff	return (NULL);
1340110267Sjeff}
1341110267Sjeff
1342171482Sjeff/*
1343171482Sjeff * Initialize a thread queue.
1344171482Sjeff */
1345109864Sjeffstatic void
1346164936Sjuliantdq_setup(struct tdq *tdq)
1347110028Sjeff{
1348171482Sjeff
1349171713Sjeff	if (bootverbose)
1350171713Sjeff		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1351165762Sjeff	runq_init(&tdq->tdq_realtime);
1352165762Sjeff	runq_init(&tdq->tdq_timeshare);
1353165620Sjeff	runq_init(&tdq->tdq_idle);
1354176735Sjeff	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1355176735Sjeff	    "sched lock %d", (int)TDQ_ID(tdq));
1356176735Sjeff	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1357176735Sjeff	    MTX_SPIN | MTX_RECURSE);
1358187357Sjeff#ifdef KTR
1359187357Sjeff	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
1360187357Sjeff	    "CPU %d load", (int)TDQ_ID(tdq));
1361187357Sjeff#endif
1362110028Sjeff}
1363110028Sjeff
1364171713Sjeff#ifdef SMP
1365110028Sjeffstatic void
1366171713Sjeffsched_setup_smp(void)
1367171713Sjeff{
1368171713Sjeff	struct tdq *tdq;
1369171713Sjeff	int i;
1370171713Sjeff
1371176735Sjeff	cpu_top = smp_topo();
1372209059Sjhb	CPU_FOREACH(i) {
1373176735Sjeff		tdq = TDQ_CPU(i);
1374171713Sjeff		tdq_setup(tdq);
1375176735Sjeff		tdq->tdq_cg = smp_topo_find(cpu_top, i);
1376176735Sjeff		if (tdq->tdq_cg == NULL)
1377176735Sjeff			panic("Can't find cpu group for %d\n", i);
1378123433Sjeff	}
1379176735Sjeff	balance_tdq = TDQ_SELF();
1380176735Sjeff	sched_balance();
1381171713Sjeff}
1382171713Sjeff#endif
1383171713Sjeff
1384171713Sjeff/*
1385171713Sjeff * Setup the thread queues and initialize the topology based on MD
1386171713Sjeff * information.
1387171713Sjeff */
1388171713Sjeffstatic void
1389171713Sjeffsched_setup(void *dummy)
1390171713Sjeff{
1391171713Sjeff	struct tdq *tdq;
1392171713Sjeff
1393171713Sjeff	tdq = TDQ_SELF();
1394171713Sjeff#ifdef SMP
1395176734Sjeff	sched_setup_smp();
1396117237Sjeff#else
1397171713Sjeff	tdq_setup(tdq);
1398116069Sjeff#endif
1399171482Sjeff
1400171482Sjeff	/* Add thread0's load since it's running. */
1401171482Sjeff	TDQ_LOCK(tdq);
1402171713Sjeff	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1403177435Sjeff	tdq_load_add(tdq, &thread0);
1404176735Sjeff	tdq->tdq_lowpri = thread0.td_priority;
1405171482Sjeff	TDQ_UNLOCK(tdq);
1406109864Sjeff}
1407109864Sjeff
1408171482Sjeff/*
1409239185Smav * This routine determines time constants after stathz and hz are setup.
1410171482Sjeff */
1411153533Sdavidxu/* ARGSUSED */
1412153533Sdavidxustatic void
1413153533Sdavidxusched_initticks(void *dummy)
1414153533Sdavidxu{
1415171482Sjeff	int incr;
1416171482Sjeff
1417153533Sdavidxu	realstathz = stathz ? stathz : hz;
1418242736Sjeff	sched_slice = realstathz / SCHED_SLICE_DEFAULT_DIVISOR;
1419242736Sjeff	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
1420239196Smav	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
1421239196Smav	    realstathz);
1422153533Sdavidxu
1423153533Sdavidxu	/*
1424165762Sjeff	 * tickincr is shifted out by 10 to avoid rounding errors due to
1425165766Sjeff	 * hz not being evenly divisible by stathz on all platforms.
1426153533Sdavidxu	 */
1427171482Sjeff	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1428165762Sjeff	/*
1429165762Sjeff	 * This does not work for values of stathz that are more than
1430165762Sjeff	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1431165762Sjeff	 */
1432171482Sjeff	if (incr == 0)
1433171482Sjeff		incr = 1;
1434171482Sjeff	tickincr = incr;
1435166108Sjeff#ifdef SMP
1436171899Sjeff	/*
1437172409Sjeff	 * Set the default balance interval now that we know
1438172409Sjeff	 * what realstathz is.
1439172409Sjeff	 */
1440172409Sjeff	balance_interval = realstathz;
1441166108Sjeff	affinity = SCHED_AFFINITY_DEFAULT;
1442166108Sjeff#endif
1443232740Smav	if (sched_idlespinthresh < 0)
1444242852Smav		sched_idlespinthresh = 2 * max(10000, 6 * hz) / realstathz;
1445153533Sdavidxu}
1446153533Sdavidxu
1447153533Sdavidxu
1448109864Sjeff/*
1449171482Sjeff * This is the core of the interactivity algorithm.  Determines a score based
1450171482Sjeff * on past behavior.  It is the ratio of sleep time to run time scaled to
1451171482Sjeff * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1452171482Sjeff * differs from the cpu usage because it does not account for time spent
1453171482Sjeff * waiting on a run-queue.  Would be prettier if we had floating point.
1454171482Sjeff */
1455171482Sjeffstatic int
1456171482Sjeffsched_interact_score(struct thread *td)
1457171482Sjeff{
1458171482Sjeff	struct td_sched *ts;
1459171482Sjeff	int div;
1460171482Sjeff
1461171482Sjeff	ts = td->td_sched;
1462171482Sjeff	/*
1463171482Sjeff	 * The score is only needed if this is likely to be an interactive
1464171482Sjeff	 * task.  Don't go through the expense of computing it if there's
1465171482Sjeff	 * no chance.
1466171482Sjeff	 */
1467171482Sjeff	if (sched_interact <= SCHED_INTERACT_HALF &&
1468171482Sjeff		ts->ts_runtime >= ts->ts_slptime)
1469171482Sjeff			return (SCHED_INTERACT_HALF);
1470171482Sjeff
1471171482Sjeff	if (ts->ts_runtime > ts->ts_slptime) {
1472171482Sjeff		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1473171482Sjeff		return (SCHED_INTERACT_HALF +
1474171482Sjeff		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1475171482Sjeff	}
1476171482Sjeff	if (ts->ts_slptime > ts->ts_runtime) {
1477171482Sjeff		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1478171482Sjeff		return (ts->ts_runtime / div);
1479171482Sjeff	}
1480171482Sjeff	/* runtime == slptime */
1481171482Sjeff	if (ts->ts_runtime)
1482171482Sjeff		return (SCHED_INTERACT_HALF);
1483171482Sjeff
1484171482Sjeff	/*
1485171482Sjeff	 * This can happen if slptime and runtime are 0.
1486171482Sjeff	 */
1487171482Sjeff	return (0);
1488171482Sjeff
1489171482Sjeff}
1490171482Sjeff
1491171482Sjeff/*
1492109864Sjeff * Scale the scheduling priority according to the "interactivity" of this
1493109864Sjeff * process.
1494109864Sjeff */
1495113357Sjeffstatic void
1496163709Sjbsched_priority(struct thread *td)
1497109864Sjeff{
1498165762Sjeff	int score;
1499109864Sjeff	int pri;
1500109864Sjeff
1501217291Sjhb	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
1502113357Sjeff		return;
1503112966Sjeff	/*
1504165762Sjeff	 * If the score is interactive we place the thread in the realtime
1505165762Sjeff	 * queue with a priority that is less than kernel and interrupt
1506165762Sjeff	 * priorities.  These threads are not subject to nice restrictions.
1507112966Sjeff	 *
1508171482Sjeff	 * Scores greater than this are placed on the normal timeshare queue
1509165762Sjeff	 * where the priority is partially decided by the most recent cpu
1510165762Sjeff	 * utilization and the rest is decided by nice value.
1511172293Sjeff	 *
1512172293Sjeff	 * The nice value of the process has a linear effect on the calculated
1513172293Sjeff	 * score.  Negative nice values make it easier for a thread to be
1514172293Sjeff	 * considered interactive.
1515112966Sjeff	 */
1516198126Sjhb	score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1517165762Sjeff	if (score < sched_interact) {
1518217351Sjhb		pri = PRI_MIN_INTERACT;
1519217351Sjhb		pri += ((PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) /
1520217237Sjhb		    sched_interact) * score;
1521217351Sjhb		KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
1522166208Sjeff		    ("sched_priority: invalid interactive priority %d score %d",
1523166208Sjeff		    pri, score));
1524165762Sjeff	} else {
1525165762Sjeff		pri = SCHED_PRI_MIN;
1526165762Sjeff		if (td->td_sched->ts_ticks)
1527228960Sjhb			pri += min(SCHED_PRI_TICKS(td->td_sched),
1528228960Sjhb			    SCHED_PRI_RANGE);
1529165762Sjeff		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1530217351Sjhb		KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
1531171482Sjeff		    ("sched_priority: invalid priority %d: nice %d, "
1532171482Sjeff		    "ticks %d ftick %d ltick %d tick pri %d",
1533171482Sjeff		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1534171482Sjeff		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1535171482Sjeff		    SCHED_PRI_TICKS(td->td_sched)));
1536165762Sjeff	}
1537165762Sjeff	sched_user_prio(td, pri);
1538112966Sjeff
1539112966Sjeff	return;
1540109864Sjeff}
1541109864Sjeff
1542121868Sjeff/*
1543121868Sjeff * This routine enforces a maximum limit on the amount of scheduling history
1544171482Sjeff * kept.  It is called after either the slptime or runtime is adjusted.  This
1545171482Sjeff * function is ugly due to integer math.
1546121868Sjeff */
1547116463Sjeffstatic void
1548163709Sjbsched_interact_update(struct thread *td)
1549116463Sjeff{
1550165819Sjeff	struct td_sched *ts;
1551166208Sjeff	u_int sum;
1552121605Sjeff
1553165819Sjeff	ts = td->td_sched;
1554171482Sjeff	sum = ts->ts_runtime + ts->ts_slptime;
1555121868Sjeff	if (sum < SCHED_SLP_RUN_MAX)
1556121868Sjeff		return;
1557121868Sjeff	/*
1558165819Sjeff	 * This only happens from two places:
1559165819Sjeff	 * 1) We have added an unusual amount of run time from fork_exit.
1560165819Sjeff	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1561165819Sjeff	 */
1562165819Sjeff	if (sum > SCHED_SLP_RUN_MAX * 2) {
1563171482Sjeff		if (ts->ts_runtime > ts->ts_slptime) {
1564171482Sjeff			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1565171482Sjeff			ts->ts_slptime = 1;
1566165819Sjeff		} else {
1567171482Sjeff			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1568171482Sjeff			ts->ts_runtime = 1;
1569165819Sjeff		}
1570165819Sjeff		return;
1571165819Sjeff	}
1572165819Sjeff	/*
1573121868Sjeff	 * If we have exceeded by more than 1/5th then the algorithm below
1574121868Sjeff	 * will not bring us back into range.  Dividing by two here forces
1575133427Sjeff	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1576121868Sjeff	 */
1577127850Sjeff	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1578171482Sjeff		ts->ts_runtime /= 2;
1579171482Sjeff		ts->ts_slptime /= 2;
1580121868Sjeff		return;
1581116463Sjeff	}
1582171482Sjeff	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1583171482Sjeff	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1584116463Sjeff}
1585116463Sjeff
1586171482Sjeff/*
1587171482Sjeff * Scale back the interactivity history when a child thread is created.  The
1588171482Sjeff * history is inherited from the parent but the thread may behave totally
1589171482Sjeff * differently.  For example, a shell spawning a compiler process.  We want
1590171482Sjeff * to learn that the compiler is behaving badly very quickly.
1591171482Sjeff */
1592121868Sjeffstatic void
1593163709Sjbsched_interact_fork(struct thread *td)
1594121868Sjeff{
1595121868Sjeff	int ratio;
1596121868Sjeff	int sum;
1597121868Sjeff
1598171482Sjeff	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1599121868Sjeff	if (sum > SCHED_SLP_RUN_FORK) {
1600121868Sjeff		ratio = sum / SCHED_SLP_RUN_FORK;
1601171482Sjeff		td->td_sched->ts_runtime /= ratio;
1602171482Sjeff		td->td_sched->ts_slptime /= ratio;
1603121868Sjeff	}
1604121868Sjeff}
1605121868Sjeff
1606113357Sjeff/*
1607171482Sjeff * Called from proc0_init() to setup the scheduler fields.
1608134791Sjulian */
1609134791Sjulianvoid
1610134791Sjulianschedinit(void)
1611134791Sjulian{
1612165762Sjeff
1613134791Sjulian	/*
1614134791Sjulian	 * Set up the scheduler specific parts of proc0.
1615134791Sjulian	 */
1616136167Sjulian	proc0.p_sched = NULL; /* XXX */
1617164936Sjulian	thread0.td_sched = &td_sched0;
1618165762Sjeff	td_sched0.ts_ltick = ticks;
1619165796Sjeff	td_sched0.ts_ftick = ticks;
1620242736Sjeff	td_sched0.ts_slice = 0;
1621134791Sjulian}
1622134791Sjulian
1623134791Sjulian/*
1624113357Sjeff * This is only somewhat accurate since given many processes of the same
1625113357Sjeff * priority they will switch when their slices run out, which will be
1626165762Sjeff * at most sched_slice stathz ticks.
1627113357Sjeff */
1628109864Sjeffint
1629109864Sjeffsched_rr_interval(void)
1630109864Sjeff{
1631165762Sjeff
1632239185Smav	/* Convert sched_slice from stathz to hz. */
1633239196Smav	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
1634109864Sjeff}
1635109864Sjeff
1636171482Sjeff/*
1637171482Sjeff * Update the percent cpu tracking information when it is requested or
1638171482Sjeff * the total history exceeds the maximum.  We keep a sliding history of
1639171482Sjeff * tick counts that slowly decays.  This is less precise than the 4BSD
1640171482Sjeff * mechanism since it happens with less regular and frequent events.
1641171482Sjeff */
1642121790Sjeffstatic void
1643232917Smavsched_pctcpu_update(struct td_sched *ts, int run)
1644109864Sjeff{
1645232917Smav	int t = ticks;
1646165762Sjeff
1647232917Smav	if (t - ts->ts_ltick >= SCHED_TICK_TARG) {
1648164936Sjulian		ts->ts_ticks = 0;
1649232917Smav		ts->ts_ftick = t - SCHED_TICK_TARG;
1650232917Smav	} else if (t - ts->ts_ftick >= SCHED_TICK_MAX) {
1651232917Smav		ts->ts_ticks = (ts->ts_ticks / (ts->ts_ltick - ts->ts_ftick)) *
1652232917Smav		    (ts->ts_ltick - (t - SCHED_TICK_TARG));
1653232917Smav		ts->ts_ftick = t - SCHED_TICK_TARG;
1654232917Smav	}
1655232917Smav	if (run)
1656232917Smav		ts->ts_ticks += (t - ts->ts_ltick) << SCHED_TICK_SHIFT;
1657232917Smav	ts->ts_ltick = t;
1658109864Sjeff}
1659109864Sjeff
1660171482Sjeff/*
1661171482Sjeff * Adjust the priority of a thread.  Move it to the appropriate run-queue
1662171482Sjeff * if necessary.  This is the back-end for several priority related
1663171482Sjeff * functions.
1664171482Sjeff */
1665165762Sjeffstatic void
1666139453Sjhbsched_thread_priority(struct thread *td, u_char prio)
1667109864Sjeff{
1668164936Sjulian	struct td_sched *ts;
1669177009Sjeff	struct tdq *tdq;
1670177009Sjeff	int oldpri;
1671109864Sjeff
1672187357Sjeff	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
1673187357Sjeff	    "prio:%d", td->td_priority, "new prio:%d", prio,
1674187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(curthread));
1675235459Srstone	SDT_PROBE3(sched, , , change_pri, td, td->td_proc, prio);
1676240513Savg	if (td != curthread && prio < td->td_priority) {
1677187357Sjeff		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
1678187357Sjeff		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
1679187357Sjeff		    prio, KTR_ATTR_LINKED, sched_tdname(td));
1680235459Srstone		SDT_PROBE4(sched, , , lend_pri, td, td->td_proc, prio,
1681235459Srstone		    curthread);
1682187357Sjeff	}
1683164936Sjulian	ts = td->td_sched;
1684170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1685139453Sjhb	if (td->td_priority == prio)
1686139453Sjhb		return;
1687177376Sjeff	/*
1688177376Sjeff	 * If the priority has been elevated due to priority
1689177376Sjeff	 * propagation, we may have to move ourselves to a new
1690177376Sjeff	 * queue.  This could be optimized to not re-add in some
1691177376Sjeff	 * cases.
1692177376Sjeff	 */
1693165766Sjeff	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1694165762Sjeff		sched_rem(td);
1695165762Sjeff		td->td_priority = prio;
1696171482Sjeff		sched_add(td, SRQ_BORROWING);
1697177009Sjeff		return;
1698177009Sjeff	}
1699177376Sjeff	/*
1700177376Sjeff	 * If the thread is currently running we may have to adjust the lowpri
1701177376Sjeff	 * information so other cpus are aware of our current priority.
1702177376Sjeff	 */
1703177009Sjeff	if (TD_IS_RUNNING(td)) {
1704177376Sjeff		tdq = TDQ_CPU(ts->ts_cpu);
1705177376Sjeff		oldpri = td->td_priority;
1706177376Sjeff		td->td_priority = prio;
1707176735Sjeff		if (prio < tdq->tdq_lowpri)
1708171482Sjeff			tdq->tdq_lowpri = prio;
1709176735Sjeff		else if (tdq->tdq_lowpri == oldpri)
1710176735Sjeff			tdq_setlowpri(tdq, td);
1711177376Sjeff		return;
1712177009Sjeff	}
1713177376Sjeff	td->td_priority = prio;
1714109864Sjeff}
1715109864Sjeff
1716139453Sjhb/*
1717139453Sjhb * Update a thread's priority when it is lent another thread's
1718139453Sjhb * priority.
1719139453Sjhb */
1720109864Sjeffvoid
1721139453Sjhbsched_lend_prio(struct thread *td, u_char prio)
1722139453Sjhb{
1723139453Sjhb
1724139453Sjhb	td->td_flags |= TDF_BORROWING;
1725139453Sjhb	sched_thread_priority(td, prio);
1726139453Sjhb}
1727139453Sjhb
1728139453Sjhb/*
1729139453Sjhb * Restore a thread's priority when priority propagation is
1730139453Sjhb * over.  The prio argument is the minimum priority the thread
1731139453Sjhb * needs to have to satisfy other possible priority lending
1732139453Sjhb * requests.  If the thread's regular priority is less
1733139453Sjhb * important than prio, the thread will keep a priority boost
1734139453Sjhb * of prio.
1735139453Sjhb */
1736139453Sjhbvoid
1737139453Sjhbsched_unlend_prio(struct thread *td, u_char prio)
1738139453Sjhb{
1739139453Sjhb	u_char base_pri;
1740139453Sjhb
1741139453Sjhb	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1742139453Sjhb	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1743163709Sjb		base_pri = td->td_user_pri;
1744139453Sjhb	else
1745139453Sjhb		base_pri = td->td_base_pri;
1746139453Sjhb	if (prio >= base_pri) {
1747139455Sjhb		td->td_flags &= ~TDF_BORROWING;
1748139453Sjhb		sched_thread_priority(td, base_pri);
1749139453Sjhb	} else
1750139453Sjhb		sched_lend_prio(td, prio);
1751139453Sjhb}
1752139453Sjhb
1753171482Sjeff/*
1754171482Sjeff * Standard entry for setting the priority to an absolute value.
1755171482Sjeff */
1756139453Sjhbvoid
1757139453Sjhbsched_prio(struct thread *td, u_char prio)
1758139453Sjhb{
1759139453Sjhb	u_char oldprio;
1760139453Sjhb
1761139453Sjhb	/* First, update the base priority. */
1762139453Sjhb	td->td_base_pri = prio;
1763139453Sjhb
1764139453Sjhb	/*
1765139455Sjhb	 * If the thread is borrowing another thread's priority, don't
1766139453Sjhb	 * ever lower the priority.
1767139453Sjhb	 */
1768139453Sjhb	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1769139453Sjhb		return;
1770139453Sjhb
1771139453Sjhb	/* Change the real priority. */
1772139453Sjhb	oldprio = td->td_priority;
1773139453Sjhb	sched_thread_priority(td, prio);
1774139453Sjhb
1775139453Sjhb	/*
1776139453Sjhb	 * If the thread is on a turnstile, then let the turnstile update
1777139453Sjhb	 * its state.
1778139453Sjhb	 */
1779139453Sjhb	if (TD_ON_LOCK(td) && oldprio != prio)
1780139453Sjhb		turnstile_adjust(td, oldprio);
1781139453Sjhb}
1782139455Sjhb
1783171482Sjeff/*
1784171482Sjeff * Set the base user priority, does not effect current running priority.
1785171482Sjeff */
1786139453Sjhbvoid
1787163709Sjbsched_user_prio(struct thread *td, u_char prio)
1788161599Sdavidxu{
1789161599Sdavidxu
1790163709Sjb	td->td_base_user_pri = prio;
1791216313Sdavidxu	if (td->td_lend_user_pri <= prio)
1792216313Sdavidxu		return;
1793163709Sjb	td->td_user_pri = prio;
1794161599Sdavidxu}
1795161599Sdavidxu
1796161599Sdavidxuvoid
1797161599Sdavidxusched_lend_user_prio(struct thread *td, u_char prio)
1798161599Sdavidxu{
1799161599Sdavidxu
1800174536Sdavidxu	THREAD_LOCK_ASSERT(td, MA_OWNED);
1801216313Sdavidxu	td->td_lend_user_pri = prio;
1802216791Sdavidxu	td->td_user_pri = min(prio, td->td_base_user_pri);
1803216791Sdavidxu	if (td->td_priority > td->td_user_pri)
1804216791Sdavidxu		sched_prio(td, td->td_user_pri);
1805216791Sdavidxu	else if (td->td_priority != td->td_user_pri)
1806216791Sdavidxu		td->td_flags |= TDF_NEEDRESCHED;
1807161599Sdavidxu}
1808161599Sdavidxu
1809171482Sjeff/*
1810171713Sjeff * Handle migration from sched_switch().  This happens only for
1811171713Sjeff * cpu binding.
1812171713Sjeff */
1813171713Sjeffstatic struct mtx *
1814171713Sjeffsched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1815171713Sjeff{
1816171713Sjeff	struct tdq *tdn;
1817171713Sjeff
1818171713Sjeff	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1819171713Sjeff#ifdef SMP
1820177435Sjeff	tdq_load_rem(tdq, td);
1821171713Sjeff	/*
1822171713Sjeff	 * Do the lock dance required to avoid LOR.  We grab an extra
1823171713Sjeff	 * spinlock nesting to prevent preemption while we're
1824171713Sjeff	 * not holding either run-queue lock.
1825171713Sjeff	 */
1826171713Sjeff	spinlock_enter();
1827202889Sattilio	thread_lock_block(td);	/* This releases the lock on tdq. */
1828197223Sattilio
1829197223Sattilio	/*
1830197223Sattilio	 * Acquire both run-queue locks before placing the thread on the new
1831197223Sattilio	 * run-queue to avoid deadlocks created by placing a thread with a
1832197223Sattilio	 * blocked lock on the run-queue of a remote processor.  The deadlock
1833197223Sattilio	 * occurs when a third processor attempts to lock the two queues in
1834197223Sattilio	 * question while the target processor is spinning with its own
1835197223Sattilio	 * run-queue lock held while waiting for the blocked lock to clear.
1836197223Sattilio	 */
1837197223Sattilio	tdq_lock_pair(tdn, tdq);
1838171713Sjeff	tdq_add(tdn, td, flags);
1839177435Sjeff	tdq_notify(tdn, td);
1840197223Sattilio	TDQ_UNLOCK(tdn);
1841171713Sjeff	spinlock_exit();
1842171713Sjeff#endif
1843171713Sjeff	return (TDQ_LOCKPTR(tdn));
1844171713Sjeff}
1845171713Sjeff
1846171713Sjeff/*
1847202889Sattilio * Variadic version of thread_lock_unblock() that does not assume td_lock
1848202889Sattilio * is blocked.
1849171482Sjeff */
1850171482Sjeffstatic inline void
1851171482Sjeffthread_unblock_switch(struct thread *td, struct mtx *mtx)
1852171482Sjeff{
1853171482Sjeff	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1854171482Sjeff	    (uintptr_t)mtx);
1855171482Sjeff}
1856171482Sjeff
1857171482Sjeff/*
1858171482Sjeff * Switch threads.  This function has to handle threads coming in while
1859171482Sjeff * blocked for some reason, running, or idle.  It also must deal with
1860171482Sjeff * migrating a thread from one queue to another as running threads may
1861171482Sjeff * be assigned elsewhere via binding.
1862171482Sjeff */
1863161599Sdavidxuvoid
1864135051Sjuliansched_switch(struct thread *td, struct thread *newtd, int flags)
1865109864Sjeff{
1866165627Sjeff	struct tdq *tdq;
1867164936Sjulian	struct td_sched *ts;
1868171482Sjeff	struct mtx *mtx;
1869171713Sjeff	int srqflag;
1870239157Smav	int cpuid, preempted;
1871109864Sjeff
1872170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1873177376Sjeff	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
1874109864Sjeff
1875171482Sjeff	cpuid = PCPU_GET(cpuid);
1876171482Sjeff	tdq = TDQ_CPU(cpuid);
1877164936Sjulian	ts = td->td_sched;
1878171713Sjeff	mtx = td->td_lock;
1879232917Smav	sched_pctcpu_update(ts, 1);
1880171482Sjeff	ts->ts_rltick = ticks;
1881133555Sjeff	td->td_lastcpu = td->td_oncpu;
1882113339Sjulian	td->td_oncpu = NOCPU;
1883239157Smav	preempted = !(td->td_flags & TDF_SLICEEND);
1884239157Smav	td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
1885144777Sups	td->td_owepreempt = 0;
1886242852Smav	if (!TD_IS_IDLETHREAD(td))
1887242852Smav		tdq->tdq_switchcnt++;
1888123434Sjeff	/*
1889171482Sjeff	 * The lock pointer in an idle thread should never change.  Reset it
1890171482Sjeff	 * to CAN_RUN as well.
1891123434Sjeff	 */
1892167327Sjulian	if (TD_IS_IDLETHREAD(td)) {
1893171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1894139334Sjeff		TD_SET_CAN_RUN(td);
1895170293Sjeff	} else if (TD_IS_RUNNING(td)) {
1896171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1897239157Smav		srqflag = preempted ?
1898170293Sjeff		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1899171713Sjeff		    SRQ_OURSELF|SRQ_YIELDING;
1900212153Smdf#ifdef SMP
1901212115Smdf		if (THREAD_CAN_MIGRATE(td) && !THREAD_CAN_SCHED(td, ts->ts_cpu))
1902212115Smdf			ts->ts_cpu = sched_pickcpu(td, 0);
1903212153Smdf#endif
1904171713Sjeff		if (ts->ts_cpu == cpuid)
1905177435Sjeff			tdq_runq_add(tdq, td, srqflag);
1906212115Smdf		else {
1907212115Smdf			KASSERT(THREAD_CAN_MIGRATE(td) ||
1908212115Smdf			    (ts->ts_flags & TSF_BOUND) != 0,
1909212115Smdf			    ("Thread %p shouldn't migrate", td));
1910171713Sjeff			mtx = sched_switch_migrate(tdq, td, srqflag);
1911212115Smdf		}
1912171482Sjeff	} else {
1913171482Sjeff		/* This thread must be going to sleep. */
1914171482Sjeff		TDQ_LOCK(tdq);
1915202889Sattilio		mtx = thread_lock_block(td);
1916177435Sjeff		tdq_load_rem(tdq, td);
1917171482Sjeff	}
1918171482Sjeff	/*
1919171482Sjeff	 * We enter here with the thread blocked and assigned to the
1920171482Sjeff	 * appropriate cpu run-queue or sleep-queue and with the current
1921171482Sjeff	 * thread-queue locked.
1922171482Sjeff	 */
1923171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1924171482Sjeff	newtd = choosethread();
1925171482Sjeff	/*
1926171482Sjeff	 * Call the MD code to switch contexts if necessary.
1927171482Sjeff	 */
1928145256Sjkoshy	if (td != newtd) {
1929145256Sjkoshy#ifdef	HWPMC_HOOKS
1930145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1931145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1932145256Sjkoshy#endif
1933235459Srstone		SDT_PROBE2(sched, , , off_cpu, td, td->td_proc);
1934174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1935172411Sjeff		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1936232917Smav		sched_pctcpu_update(newtd->td_sched, 0);
1937179297Sjb
1938179297Sjb#ifdef KDTRACE_HOOKS
1939179297Sjb		/*
1940179297Sjb		 * If DTrace has set the active vtime enum to anything
1941179297Sjb		 * other than INACTIVE (0), then it should have set the
1942179297Sjb		 * function to call.
1943179297Sjb		 */
1944179297Sjb		if (dtrace_vtime_active)
1945179297Sjb			(*dtrace_vtime_switch_func)(newtd);
1946179297Sjb#endif
1947179297Sjb
1948171482Sjeff		cpu_switch(td, newtd, mtx);
1949171482Sjeff		/*
1950171482Sjeff		 * We may return from cpu_switch on a different cpu.  However,
1951171482Sjeff		 * we always return with td_lock pointing to the current cpu's
1952171482Sjeff		 * run queue lock.
1953171482Sjeff		 */
1954171482Sjeff		cpuid = PCPU_GET(cpuid);
1955171482Sjeff		tdq = TDQ_CPU(cpuid);
1956174629Sjeff		lock_profile_obtain_lock_success(
1957174629Sjeff		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1958235459Srstone
1959235459Srstone		SDT_PROBE0(sched, , , on_cpu);
1960145256Sjkoshy#ifdef	HWPMC_HOOKS
1961145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1962145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1963145256Sjkoshy#endif
1964235459Srstone	} else {
1965171482Sjeff		thread_unblock_switch(td, mtx);
1966235459Srstone		SDT_PROBE0(sched, , , remain_cpu);
1967235459Srstone	}
1968171482Sjeff	/*
1969171482Sjeff	 * Assert that all went well and return.
1970171482Sjeff	 */
1971171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1972171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1973171482Sjeff	td->td_oncpu = cpuid;
1974109864Sjeff}
1975109864Sjeff
1976171482Sjeff/*
1977171482Sjeff * Adjust thread priorities as a result of a nice request.
1978171482Sjeff */
1979109864Sjeffvoid
1980130551Sjuliansched_nice(struct proc *p, int nice)
1981109864Sjeff{
1982109864Sjeff	struct thread *td;
1983109864Sjeff
1984130551Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
1985165762Sjeff
1986130551Sjulian	p->p_nice = nice;
1987163709Sjb	FOREACH_THREAD_IN_PROC(p, td) {
1988170293Sjeff		thread_lock(td);
1989163709Sjb		sched_priority(td);
1990165762Sjeff		sched_prio(td, td->td_base_user_pri);
1991170293Sjeff		thread_unlock(td);
1992130551Sjulian	}
1993109864Sjeff}
1994109864Sjeff
1995171482Sjeff/*
1996171482Sjeff * Record the sleep time for the interactivity scorer.
1997171482Sjeff */
1998109864Sjeffvoid
1999177085Sjeffsched_sleep(struct thread *td, int prio)
2000109864Sjeff{
2001165762Sjeff
2002170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2003109864Sjeff
2004172264Sjeff	td->td_slptick = ticks;
2005201347Skib	if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
2006177085Sjeff		td->td_flags |= TDF_CANSWAP;
2007217410Sjhb	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
2008217410Sjhb		return;
2009177903Sjeff	if (static_boost == 1 && prio)
2010177085Sjeff		sched_prio(td, prio);
2011177903Sjeff	else if (static_boost && td->td_priority > static_boost)
2012177903Sjeff		sched_prio(td, static_boost);
2013109864Sjeff}
2014109864Sjeff
2015171482Sjeff/*
2016171482Sjeff * Schedule a thread to resume execution and record how long it voluntarily
2017171482Sjeff * slept.  We also update the pctcpu, interactivity, and priority.
2018171482Sjeff */
2019109864Sjeffvoid
2020109864Sjeffsched_wakeup(struct thread *td)
2021109864Sjeff{
2022166229Sjeff	struct td_sched *ts;
2023171482Sjeff	int slptick;
2024165762Sjeff
2025170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2026166229Sjeff	ts = td->td_sched;
2027177085Sjeff	td->td_flags &= ~TDF_CANSWAP;
2028109864Sjeff	/*
2029165762Sjeff	 * If we slept for more than a tick update our interactivity and
2030165762Sjeff	 * priority.
2031109864Sjeff	 */
2032172264Sjeff	slptick = td->td_slptick;
2033172264Sjeff	td->td_slptick = 0;
2034171482Sjeff	if (slptick && slptick != ticks) {
2035232917Smav		ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
2036165819Sjeff		sched_interact_update(td);
2037232917Smav		sched_pctcpu_update(ts, 0);
2038109864Sjeff	}
2039242736Sjeff	/*
2040242736Sjeff	 * Reset the slice value since we slept and advanced the round-robin.
2041242736Sjeff	 */
2042242736Sjeff	ts->ts_slice = 0;
2043166190Sjeff	sched_add(td, SRQ_BORING);
2044109864Sjeff}
2045109864Sjeff
2046109864Sjeff/*
2047109864Sjeff * Penalize the parent for creating a new child and initialize the child's
2048109864Sjeff * priority.
2049109864Sjeff */
2050109864Sjeffvoid
2051163709Sjbsched_fork(struct thread *td, struct thread *child)
2052109864Sjeff{
2053170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2054232917Smav	sched_pctcpu_update(td->td_sched, 1);
2055164936Sjulian	sched_fork_thread(td, child);
2056165762Sjeff	/*
2057165762Sjeff	 * Penalize the parent and child for forking.
2058165762Sjeff	 */
2059165762Sjeff	sched_interact_fork(child);
2060165762Sjeff	sched_priority(child);
2061171482Sjeff	td->td_sched->ts_runtime += tickincr;
2062165762Sjeff	sched_interact_update(td);
2063165762Sjeff	sched_priority(td);
2064164936Sjulian}
2065109864Sjeff
2066171482Sjeff/*
2067171482Sjeff * Fork a new thread, may be within the same process.
2068171482Sjeff */
2069164936Sjulianvoid
2070164936Sjuliansched_fork_thread(struct thread *td, struct thread *child)
2071164936Sjulian{
2072164936Sjulian	struct td_sched *ts;
2073164936Sjulian	struct td_sched *ts2;
2074242736Sjeff	struct tdq *tdq;
2075164936Sjulian
2076242736Sjeff	tdq = TDQ_SELF();
2077177426Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2078165762Sjeff	/*
2079165762Sjeff	 * Initialize child.
2080165762Sjeff	 */
2081177426Sjeff	ts = td->td_sched;
2082177426Sjeff	ts2 = child->td_sched;
2083242736Sjeff	child->td_lock = TDQ_LOCKPTR(tdq);
2084176735Sjeff	child->td_cpuset = cpuset_ref(td->td_cpuset);
2085164936Sjulian	ts2->ts_cpu = ts->ts_cpu;
2086177426Sjeff	ts2->ts_flags = 0;
2087165762Sjeff	/*
2088217078Sjhb	 * Grab our parents cpu estimation information.
2089165762Sjeff	 */
2090164936Sjulian	ts2->ts_ticks = ts->ts_ticks;
2091164936Sjulian	ts2->ts_ltick = ts->ts_ltick;
2092164936Sjulian	ts2->ts_ftick = ts->ts_ftick;
2093165762Sjeff	/*
2094217078Sjhb	 * Do not inherit any borrowed priority from the parent.
2095217078Sjhb	 */
2096217078Sjhb	child->td_priority = child->td_base_pri;
2097217078Sjhb	/*
2098165762Sjeff	 * And update interactivity score.
2099165762Sjeff	 */
2100171482Sjeff	ts2->ts_slptime = ts->ts_slptime;
2101171482Sjeff	ts2->ts_runtime = ts->ts_runtime;
2102242736Sjeff	/* Attempt to quickly learn interactivity. */
2103242736Sjeff	ts2->ts_slice = tdq_slice(tdq) - sched_slice_min;
2104187357Sjeff#ifdef KTR
2105187357Sjeff	bzero(ts2->ts_name, sizeof(ts2->ts_name));
2106187357Sjeff#endif
2107113357Sjeff}
2108113357Sjeff
2109171482Sjeff/*
2110171482Sjeff * Adjust the priority class of a thread.
2111171482Sjeff */
2112113357Sjeffvoid
2113163709Sjbsched_class(struct thread *td, int class)
2114113357Sjeff{
2115113357Sjeff
2116170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2117163709Sjb	if (td->td_pri_class == class)
2118113357Sjeff		return;
2119163709Sjb	td->td_pri_class = class;
2120109864Sjeff}
2121109864Sjeff
2122109864Sjeff/*
2123109864Sjeff * Return some of the child's priority and interactivity to the parent.
2124109864Sjeff */
2125109864Sjeffvoid
2126164939Sjuliansched_exit(struct proc *p, struct thread *child)
2127109864Sjeff{
2128165762Sjeff	struct thread *td;
2129113372Sjeff
2130187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2131225199Sdelphij	    "prio:%d", child->td_priority);
2132177368Sjeff	PROC_LOCK_ASSERT(p, MA_OWNED);
2133165762Sjeff	td = FIRST_THREAD_IN_PROC(p);
2134165762Sjeff	sched_exit_thread(td, child);
2135113372Sjeff}
2136113372Sjeff
2137171482Sjeff/*
2138171482Sjeff * Penalize another thread for the time spent on this one.  This helps to
2139171482Sjeff * worsen the priority and interactivity of processes which schedule batch
2140171482Sjeff * jobs such as make.  This has little effect on the make process itself but
2141171482Sjeff * causes new processes spawned by it to receive worse scores immediately.
2142171482Sjeff */
2143113372Sjeffvoid
2144164939Sjuliansched_exit_thread(struct thread *td, struct thread *child)
2145164936Sjulian{
2146165762Sjeff
2147187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2148225199Sdelphij	    "prio:%d", child->td_priority);
2149165762Sjeff	/*
2150165762Sjeff	 * Give the child's runtime to the parent without returning the
2151165762Sjeff	 * sleep time as a penalty to the parent.  This causes shells that
2152165762Sjeff	 * launch expensive things to mark their children as expensive.
2153165762Sjeff	 */
2154170293Sjeff	thread_lock(td);
2155171482Sjeff	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2156164939Sjulian	sched_interact_update(td);
2157165762Sjeff	sched_priority(td);
2158170293Sjeff	thread_unlock(td);
2159164936Sjulian}
2160164936Sjulian
2161177005Sjeffvoid
2162177005Sjeffsched_preempt(struct thread *td)
2163177005Sjeff{
2164177005Sjeff	struct tdq *tdq;
2165177005Sjeff
2166235459Srstone	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
2167235459Srstone
2168177005Sjeff	thread_lock(td);
2169177005Sjeff	tdq = TDQ_SELF();
2170177005Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2171177005Sjeff	tdq->tdq_ipipending = 0;
2172177005Sjeff	if (td->td_priority > tdq->tdq_lowpri) {
2173178272Sjeff		int flags;
2174178272Sjeff
2175178272Sjeff		flags = SW_INVOL | SW_PREEMPT;
2176177005Sjeff		if (td->td_critnest > 1)
2177177005Sjeff			td->td_owepreempt = 1;
2178178272Sjeff		else if (TD_IS_IDLETHREAD(td))
2179178272Sjeff			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2180177005Sjeff		else
2181178272Sjeff			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2182177005Sjeff	}
2183177005Sjeff	thread_unlock(td);
2184177005Sjeff}
2185177005Sjeff
2186171482Sjeff/*
2187171482Sjeff * Fix priorities on return to user-space.  Priorities may be elevated due
2188171482Sjeff * to static priorities in msleep() or similar.
2189171482Sjeff */
2190164936Sjulianvoid
2191164936Sjuliansched_userret(struct thread *td)
2192164936Sjulian{
2193164936Sjulian	/*
2194164936Sjulian	 * XXX we cheat slightly on the locking here to avoid locking in
2195164936Sjulian	 * the usual case.  Setting td_priority here is essentially an
2196164936Sjulian	 * incomplete workaround for not setting it properly elsewhere.
2197164936Sjulian	 * Now that some interrupt handlers are threads, not setting it
2198164936Sjulian	 * properly elsewhere can clobber it in the window between setting
2199164936Sjulian	 * it here and returning to user mode, so don't waste time setting
2200164936Sjulian	 * it perfectly here.
2201164936Sjulian	 */
2202164936Sjulian	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2203164936Sjulian	    ("thread with borrowed priority returning to userland"));
2204164936Sjulian	if (td->td_priority != td->td_user_pri) {
2205170293Sjeff		thread_lock(td);
2206164936Sjulian		td->td_priority = td->td_user_pri;
2207164936Sjulian		td->td_base_pri = td->td_user_pri;
2208177005Sjeff		tdq_setlowpri(TDQ_SELF(), td);
2209170293Sjeff		thread_unlock(td);
2210164936Sjulian        }
2211164936Sjulian}
2212164936Sjulian
2213171482Sjeff/*
2214171482Sjeff * Handle a stathz tick.  This is really only relevant for timeshare
2215171482Sjeff * threads.
2216171482Sjeff */
2217164936Sjulianvoid
2218121127Sjeffsched_clock(struct thread *td)
2219109864Sjeff{
2220164936Sjulian	struct tdq *tdq;
2221164936Sjulian	struct td_sched *ts;
2222109864Sjeff
2223171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2224164936Sjulian	tdq = TDQ_SELF();
2225172409Sjeff#ifdef SMP
2226133427Sjeff	/*
2227172409Sjeff	 * We run the long term load balancer infrequently on the first cpu.
2228172409Sjeff	 */
2229172409Sjeff	if (balance_tdq == tdq) {
2230172409Sjeff		if (balance_ticks && --balance_ticks == 0)
2231172409Sjeff			sched_balance();
2232172409Sjeff	}
2233172409Sjeff#endif
2234172409Sjeff	/*
2235178277Sjeff	 * Save the old switch count so we have a record of the last ticks
2236178277Sjeff	 * activity.   Initialize the new switch count based on our load.
2237178277Sjeff	 * If there is some activity seed it to reflect that.
2238178277Sjeff	 */
2239178277Sjeff	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
2240178471Sjeff	tdq->tdq_switchcnt = tdq->tdq_load;
2241178277Sjeff	/*
2242165766Sjeff	 * Advance the insert index once for each tick to ensure that all
2243165766Sjeff	 * threads get a chance to run.
2244133427Sjeff	 */
2245165766Sjeff	if (tdq->tdq_idx == tdq->tdq_ridx) {
2246165766Sjeff		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2247165766Sjeff		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2248165766Sjeff			tdq->tdq_ridx = tdq->tdq_idx;
2249165766Sjeff	}
2250165766Sjeff	ts = td->td_sched;
2251232917Smav	sched_pctcpu_update(ts, 1);
2252175104Sjeff	if (td->td_pri_class & PRI_FIFO_BIT)
2253113357Sjeff		return;
2254217291Sjhb	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2255175104Sjeff		/*
2256175104Sjeff		 * We used a tick; charge it to the thread so
2257175104Sjeff		 * that we can compute our interactivity.
2258175104Sjeff		 */
2259175104Sjeff		td->td_sched->ts_runtime += tickincr;
2260175104Sjeff		sched_interact_update(td);
2261177009Sjeff		sched_priority(td);
2262175104Sjeff	}
2263239185Smav
2264113357Sjeff	/*
2265239185Smav	 * Force a context switch if the current thread has used up a full
2266239185Smav	 * time slice (default is 100ms).
2267109864Sjeff	 */
2268242736Sjeff	if (!TD_IS_IDLETHREAD(td) && ++ts->ts_slice >= tdq_slice(tdq)) {
2269242736Sjeff		ts->ts_slice = 0;
2270239185Smav		td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
2271239185Smav	}
2272109864Sjeff}
2273109864Sjeff
2274171482Sjeff/*
2275232917Smav * Called once per hz tick.
2276171482Sjeff */
2277171482Sjeffvoid
2278212541Smavsched_tick(int cnt)
2279171482Sjeff{
2280171482Sjeff
2281171482Sjeff}
2282171482Sjeff
2283171482Sjeff/*
2284171482Sjeff * Return whether the current CPU has runnable tasks.  Used for in-kernel
2285171482Sjeff * cooperative idle threads.
2286171482Sjeff */
2287109864Sjeffint
2288109864Sjeffsched_runnable(void)
2289109864Sjeff{
2290164936Sjulian	struct tdq *tdq;
2291115998Sjeff	int load;
2292109864Sjeff
2293115998Sjeff	load = 1;
2294115998Sjeff
2295164936Sjulian	tdq = TDQ_SELF();
2296121605Sjeff	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2297165620Sjeff		if (tdq->tdq_load > 0)
2298121605Sjeff			goto out;
2299121605Sjeff	} else
2300165620Sjeff		if (tdq->tdq_load - 1 > 0)
2301121605Sjeff			goto out;
2302115998Sjeff	load = 0;
2303115998Sjeffout:
2304115998Sjeff	return (load);
2305109864Sjeff}
2306109864Sjeff
2307171482Sjeff/*
2308171482Sjeff * Choose the highest priority thread to run.  The thread is removed from
2309171482Sjeff * the run-queue while running however the load remains.  For SMP we set
2310171482Sjeff * the tdq in the global idle bitmask if it idles here.
2311171482Sjeff */
2312166190Sjeffstruct thread *
2313109970Sjeffsched_choose(void)
2314109970Sjeff{
2315177435Sjeff	struct thread *td;
2316164936Sjulian	struct tdq *tdq;
2317109970Sjeff
2318164936Sjulian	tdq = TDQ_SELF();
2319171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2320177435Sjeff	td = tdq_choose(tdq);
2321177435Sjeff	if (td) {
2322177435Sjeff		tdq_runq_rem(tdq, td);
2323177903Sjeff		tdq->tdq_lowpri = td->td_priority;
2324177435Sjeff		return (td);
2325109864Sjeff	}
2326177903Sjeff	tdq->tdq_lowpri = PRI_MAX_IDLE;
2327176735Sjeff	return (PCPU_GET(idlethread));
2328109864Sjeff}
2329109864Sjeff
2330171482Sjeff/*
2331171482Sjeff * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2332171482Sjeff * we always request it once we exit a critical section.
2333171482Sjeff */
2334171482Sjeffstatic inline void
2335171482Sjeffsched_setpreempt(struct thread *td)
2336166190Sjeff{
2337166190Sjeff	struct thread *ctd;
2338166190Sjeff	int cpri;
2339166190Sjeff	int pri;
2340166190Sjeff
2341177005Sjeff	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2342177005Sjeff
2343166190Sjeff	ctd = curthread;
2344166190Sjeff	pri = td->td_priority;
2345166190Sjeff	cpri = ctd->td_priority;
2346177005Sjeff	if (pri < cpri)
2347177005Sjeff		ctd->td_flags |= TDF_NEEDRESCHED;
2348166190Sjeff	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2349171482Sjeff		return;
2350177005Sjeff	if (!sched_shouldpreempt(pri, cpri, 0))
2351171482Sjeff		return;
2352171482Sjeff	ctd->td_owepreempt = 1;
2353166190Sjeff}
2354166190Sjeff
2355171482Sjeff/*
2356177009Sjeff * Add a thread to a thread queue.  Select the appropriate runq and add the
2357177009Sjeff * thread to it.  This is the internal function called when the tdq is
2358177009Sjeff * predetermined.
2359171482Sjeff */
2360109864Sjeffvoid
2361171482Sjefftdq_add(struct tdq *tdq, struct thread *td, int flags)
2362109864Sjeff{
2363109864Sjeff
2364171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2365166190Sjeff	KASSERT((td->td_inhibitors == 0),
2366166190Sjeff	    ("sched_add: trying to run inhibited thread"));
2367166190Sjeff	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2368166190Sjeff	    ("sched_add: bad thread state"));
2369172207Sjeff	KASSERT(td->td_flags & TDF_INMEM,
2370172207Sjeff	    ("sched_add: thread swapped out"));
2371171482Sjeff
2372171482Sjeff	if (td->td_priority < tdq->tdq_lowpri)
2373171482Sjeff		tdq->tdq_lowpri = td->td_priority;
2374177435Sjeff	tdq_runq_add(tdq, td, flags);
2375177435Sjeff	tdq_load_add(tdq, td);
2376171482Sjeff}
2377171482Sjeff
2378171482Sjeff/*
2379171482Sjeff * Select the target thread queue and add a thread to it.  Request
2380171482Sjeff * preemption or IPI a remote processor if required.
2381171482Sjeff */
2382171482Sjeffvoid
2383171482Sjeffsched_add(struct thread *td, int flags)
2384171482Sjeff{
2385171482Sjeff	struct tdq *tdq;
2386171482Sjeff#ifdef SMP
2387171482Sjeff	int cpu;
2388171482Sjeff#endif
2389187357Sjeff
2390187357Sjeff	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
2391187357Sjeff	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
2392187357Sjeff	    sched_tdname(curthread));
2393187357Sjeff	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
2394187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(td));
2395235459Srstone	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
2396235459Srstone	    flags & SRQ_PREEMPTED);
2397171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2398166108Sjeff	/*
2399171482Sjeff	 * Recalculate the priority before we select the target cpu or
2400171482Sjeff	 * run-queue.
2401166108Sjeff	 */
2402171482Sjeff	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2403171482Sjeff		sched_priority(td);
2404171482Sjeff#ifdef SMP
2405171482Sjeff	/*
2406171482Sjeff	 * Pick the destination cpu and if it isn't ours transfer to the
2407171482Sjeff	 * target cpu.
2408171482Sjeff	 */
2409177435Sjeff	cpu = sched_pickcpu(td, flags);
2410177435Sjeff	tdq = sched_setcpu(td, cpu, flags);
2411171482Sjeff	tdq_add(tdq, td, flags);
2412177009Sjeff	if (cpu != PCPU_GET(cpuid)) {
2413177435Sjeff		tdq_notify(tdq, td);
2414166108Sjeff		return;
2415166108Sjeff	}
2416171482Sjeff#else
2417171482Sjeff	tdq = TDQ_SELF();
2418171482Sjeff	TDQ_LOCK(tdq);
2419171482Sjeff	/*
2420171482Sjeff	 * Now that the thread is moving to the run-queue, set the lock
2421171482Sjeff	 * to the scheduler's lock.
2422171482Sjeff	 */
2423171482Sjeff	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2424171482Sjeff	tdq_add(tdq, td, flags);
2425166108Sjeff#endif
2426171482Sjeff	if (!(flags & SRQ_YIELDING))
2427171482Sjeff		sched_setpreempt(td);
2428109864Sjeff}
2429109864Sjeff
2430171482Sjeff/*
2431171482Sjeff * Remove a thread from a run-queue without running it.  This is used
2432171482Sjeff * when we're stealing a thread from a remote queue.  Otherwise all threads
2433171482Sjeff * exit by calling sched_exit_thread() and sched_throw() themselves.
2434171482Sjeff */
2435109864Sjeffvoid
2436121127Sjeffsched_rem(struct thread *td)
2437109864Sjeff{
2438164936Sjulian	struct tdq *tdq;
2439113357Sjeff
2440187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
2441187357Sjeff	    "prio:%d", td->td_priority);
2442235459Srstone	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
2443177435Sjeff	tdq = TDQ_CPU(td->td_sched->ts_cpu);
2444171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2445171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2446166190Sjeff	KASSERT(TD_ON_RUNQ(td),
2447164936Sjulian	    ("sched_rem: thread not on run queue"));
2448177435Sjeff	tdq_runq_rem(tdq, td);
2449177435Sjeff	tdq_load_rem(tdq, td);
2450166190Sjeff	TD_SET_CAN_RUN(td);
2451176735Sjeff	if (td->td_priority == tdq->tdq_lowpri)
2452176735Sjeff		tdq_setlowpri(tdq, NULL);
2453109864Sjeff}
2454109864Sjeff
2455171482Sjeff/*
2456171482Sjeff * Fetch cpu utilization information.  Updates on demand.
2457171482Sjeff */
2458109864Sjefffixpt_t
2459121127Sjeffsched_pctcpu(struct thread *td)
2460109864Sjeff{
2461109864Sjeff	fixpt_t pctcpu;
2462164936Sjulian	struct td_sched *ts;
2463109864Sjeff
2464109864Sjeff	pctcpu = 0;
2465164936Sjulian	ts = td->td_sched;
2466164936Sjulian	if (ts == NULL)
2467121290Sjeff		return (0);
2468109864Sjeff
2469208787Sjhb	THREAD_LOCK_ASSERT(td, MA_OWNED);
2470232917Smav	sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2471164936Sjulian	if (ts->ts_ticks) {
2472109864Sjeff		int rtick;
2473109864Sjeff
2474109864Sjeff		/* How many rtick per second ? */
2475165762Sjeff		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2476165762Sjeff		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2477109864Sjeff	}
2478109864Sjeff
2479109864Sjeff	return (pctcpu);
2480109864Sjeff}
2481109864Sjeff
2482176735Sjeff/*
2483176735Sjeff * Enforce affinity settings for a thread.  Called after adjustments to
2484176735Sjeff * cpumask.
2485176735Sjeff */
2486176729Sjeffvoid
2487176729Sjeffsched_affinity(struct thread *td)
2488176729Sjeff{
2489176735Sjeff#ifdef SMP
2490176735Sjeff	struct td_sched *ts;
2491176735Sjeff
2492176735Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2493176735Sjeff	ts = td->td_sched;
2494176735Sjeff	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2495176735Sjeff		return;
2496189787Sjeff	if (TD_ON_RUNQ(td)) {
2497189787Sjeff		sched_rem(td);
2498189787Sjeff		sched_add(td, SRQ_BORING);
2499189787Sjeff		return;
2500189787Sjeff	}
2501176735Sjeff	if (!TD_IS_RUNNING(td))
2502176735Sjeff		return;
2503176735Sjeff	/*
2504212115Smdf	 * Force a switch before returning to userspace.  If the
2505212115Smdf	 * target thread is not running locally send an ipi to force
2506212115Smdf	 * the issue.
2507176735Sjeff	 */
2508212974Sjhb	td->td_flags |= TDF_NEEDRESCHED;
2509212115Smdf	if (td != curthread)
2510212115Smdf		ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
2511176735Sjeff#endif
2512176729Sjeff}
2513176729Sjeff
2514171482Sjeff/*
2515171482Sjeff * Bind a thread to a target cpu.
2516171482Sjeff */
2517122038Sjeffvoid
2518122038Sjeffsched_bind(struct thread *td, int cpu)
2519122038Sjeff{
2520164936Sjulian	struct td_sched *ts;
2521122038Sjeff
2522171713Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2523208391Sjhb	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
2524164936Sjulian	ts = td->td_sched;
2525166137Sjeff	if (ts->ts_flags & TSF_BOUND)
2526166152Sjeff		sched_unbind(td);
2527212115Smdf	KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2528164936Sjulian	ts->ts_flags |= TSF_BOUND;
2529166137Sjeff	sched_pin();
2530123433Sjeff	if (PCPU_GET(cpuid) == cpu)
2531122038Sjeff		return;
2532166137Sjeff	ts->ts_cpu = cpu;
2533122038Sjeff	/* When we return from mi_switch we'll be on the correct cpu. */
2534131527Sphk	mi_switch(SW_VOL, NULL);
2535122038Sjeff}
2536122038Sjeff
2537171482Sjeff/*
2538171482Sjeff * Release a bound thread.
2539171482Sjeff */
2540122038Sjeffvoid
2541122038Sjeffsched_unbind(struct thread *td)
2542122038Sjeff{
2543165762Sjeff	struct td_sched *ts;
2544165762Sjeff
2545170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2546208391Sjhb	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
2547165762Sjeff	ts = td->td_sched;
2548166137Sjeff	if ((ts->ts_flags & TSF_BOUND) == 0)
2549166137Sjeff		return;
2550165762Sjeff	ts->ts_flags &= ~TSF_BOUND;
2551165762Sjeff	sched_unpin();
2552122038Sjeff}
2553122038Sjeff
2554109864Sjeffint
2555145256Sjkoshysched_is_bound(struct thread *td)
2556145256Sjkoshy{
2557170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2558164936Sjulian	return (td->td_sched->ts_flags & TSF_BOUND);
2559145256Sjkoshy}
2560145256Sjkoshy
2561171482Sjeff/*
2562171482Sjeff * Basic yield call.
2563171482Sjeff */
2564159630Sdavidxuvoid
2565159630Sdavidxusched_relinquish(struct thread *td)
2566159630Sdavidxu{
2567170293Sjeff	thread_lock(td);
2568178272Sjeff	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
2569170293Sjeff	thread_unlock(td);
2570159630Sdavidxu}
2571159630Sdavidxu
2572171482Sjeff/*
2573171482Sjeff * Return the total system load.
2574171482Sjeff */
2575145256Sjkoshyint
2576125289Sjeffsched_load(void)
2577125289Sjeff{
2578125289Sjeff#ifdef SMP
2579125289Sjeff	int total;
2580125289Sjeff	int i;
2581125289Sjeff
2582125289Sjeff	total = 0;
2583209059Sjhb	CPU_FOREACH(i)
2584176735Sjeff		total += TDQ_CPU(i)->tdq_sysload;
2585125289Sjeff	return (total);
2586125289Sjeff#else
2587165620Sjeff	return (TDQ_SELF()->tdq_sysload);
2588125289Sjeff#endif
2589125289Sjeff}
2590125289Sjeff
2591125289Sjeffint
2592109864Sjeffsched_sizeof_proc(void)
2593109864Sjeff{
2594109864Sjeff	return (sizeof(struct proc));
2595109864Sjeff}
2596109864Sjeff
2597109864Sjeffint
2598109864Sjeffsched_sizeof_thread(void)
2599109864Sjeff{
2600109864Sjeff	return (sizeof(struct thread) + sizeof(struct td_sched));
2601109864Sjeff}
2602159570Sdavidxu
2603191676Sjeff#ifdef SMP
2604191676Sjeff#define	TDQ_IDLESPIN(tdq)						\
2605191676Sjeff    ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
2606191676Sjeff#else
2607191676Sjeff#define	TDQ_IDLESPIN(tdq)	1
2608191676Sjeff#endif
2609191676Sjeff
2610166190Sjeff/*
2611166190Sjeff * The actual idle process.
2612166190Sjeff */
2613166190Sjeffvoid
2614166190Sjeffsched_idletd(void *dummy)
2615166190Sjeff{
2616166190Sjeff	struct thread *td;
2617171482Sjeff	struct tdq *tdq;
2618242852Smav	int oldswitchcnt, switchcnt;
2619178277Sjeff	int i;
2620166190Sjeff
2621191643Sjeff	mtx_assert(&Giant, MA_NOTOWNED);
2622166190Sjeff	td = curthread;
2623171482Sjeff	tdq = TDQ_SELF();
2624239585Sjhb	THREAD_NO_SLEEPING();
2625242852Smav	oldswitchcnt = -1;
2626171482Sjeff	for (;;) {
2627242852Smav		if (tdq->tdq_load) {
2628242852Smav			thread_lock(td);
2629242852Smav			mi_switch(SW_VOL | SWT_IDLE, NULL);
2630242852Smav			thread_unlock(td);
2631242852Smav		}
2632242852Smav		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2633171482Sjeff#ifdef SMP
2634242852Smav		if (switchcnt != oldswitchcnt) {
2635242852Smav			oldswitchcnt = switchcnt;
2636242852Smav			if (tdq_idled(tdq) == 0)
2637242852Smav				continue;
2638242852Smav		}
2639171482Sjeff#endif
2640178277Sjeff		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2641178277Sjeff		/*
2642178277Sjeff		 * If we're switching very frequently, spin while checking
2643178277Sjeff		 * for load rather than entering a low power state that
2644191643Sjeff		 * may require an IPI.  However, don't do any busy
2645191643Sjeff		 * loops while on SMT machines as this simply steals
2646191643Sjeff		 * cycles from cores doing useful work.
2647178277Sjeff		 */
2648191676Sjeff		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
2649178277Sjeff			for (i = 0; i < sched_idlespins; i++) {
2650178277Sjeff				if (tdq->tdq_load)
2651178277Sjeff					break;
2652178277Sjeff				cpu_spinwait();
2653178277Sjeff			}
2654178277Sjeff		}
2655242852Smav
2656242852Smav		/* If there was context switch during spin, restart it. */
2657191643Sjeff		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2658242852Smav		if (tdq->tdq_load != 0 || switchcnt != oldswitchcnt)
2659242852Smav			continue;
2660242852Smav
2661242852Smav		/* Run main MD idle handler. */
2662242852Smav		tdq->tdq_cpu_idle = 1;
2663242852Smav		cpu_idle(switchcnt * 4 > sched_idlespinthresh);
2664242852Smav		tdq->tdq_cpu_idle = 0;
2665242852Smav
2666242852Smav		/*
2667242852Smav		 * Account thread-less hardware interrupts and
2668242852Smav		 * other wakeup reasons equal to context switches.
2669242852Smav		 */
2670242852Smav		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2671242852Smav		if (switchcnt != oldswitchcnt)
2672242852Smav			continue;
2673242852Smav		tdq->tdq_switchcnt++;
2674242852Smav		oldswitchcnt++;
2675171482Sjeff	}
2676166190Sjeff}
2677166190Sjeff
2678170293Sjeff/*
2679170293Sjeff * A CPU is entering for the first time or a thread is exiting.
2680170293Sjeff */
2681170293Sjeffvoid
2682170293Sjeffsched_throw(struct thread *td)
2683170293Sjeff{
2684172411Sjeff	struct thread *newtd;
2685171482Sjeff	struct tdq *tdq;
2686171482Sjeff
2687171482Sjeff	tdq = TDQ_SELF();
2688170293Sjeff	if (td == NULL) {
2689171482Sjeff		/* Correct spinlock nesting and acquire the correct lock. */
2690171482Sjeff		TDQ_LOCK(tdq);
2691170293Sjeff		spinlock_exit();
2692229429Sjhb		PCPU_SET(switchtime, cpu_ticks());
2693229429Sjhb		PCPU_SET(switchticks, ticks);
2694170293Sjeff	} else {
2695171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2696177435Sjeff		tdq_load_rem(tdq, td);
2697174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2698170293Sjeff	}
2699170293Sjeff	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2700172411Sjeff	newtd = choosethread();
2701172411Sjeff	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2702172411Sjeff	cpu_throw(td, newtd);		/* doesn't return */
2703170293Sjeff}
2704170293Sjeff
2705171482Sjeff/*
2706171482Sjeff * This is called from fork_exit().  Just acquire the correct locks and
2707171482Sjeff * let fork do the rest of the work.
2708171482Sjeff */
2709170293Sjeffvoid
2710170600Sjeffsched_fork_exit(struct thread *td)
2711170293Sjeff{
2712171482Sjeff	struct td_sched *ts;
2713171482Sjeff	struct tdq *tdq;
2714171482Sjeff	int cpuid;
2715170293Sjeff
2716170293Sjeff	/*
2717170293Sjeff	 * Finish setting up thread glue so that it begins execution in a
2718171482Sjeff	 * non-nested critical section with the scheduler lock held.
2719170293Sjeff	 */
2720171482Sjeff	cpuid = PCPU_GET(cpuid);
2721171482Sjeff	tdq = TDQ_CPU(cpuid);
2722171482Sjeff	ts = td->td_sched;
2723171482Sjeff	if (TD_IS_IDLETHREAD(td))
2724171482Sjeff		td->td_lock = TDQ_LOCKPTR(tdq);
2725171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2726171482Sjeff	td->td_oncpu = cpuid;
2727172411Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2728174629Sjeff	lock_profile_obtain_lock_success(
2729174629Sjeff	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2730170293Sjeff}
2731170293Sjeff
2732187357Sjeff/*
2733187357Sjeff * Create on first use to catch odd startup conditons.
2734187357Sjeff */
2735187357Sjeffchar *
2736187357Sjeffsched_tdname(struct thread *td)
2737187357Sjeff{
2738187357Sjeff#ifdef KTR
2739187357Sjeff	struct td_sched *ts;
2740187357Sjeff
2741187357Sjeff	ts = td->td_sched;
2742187357Sjeff	if (ts->ts_name[0] == '\0')
2743187357Sjeff		snprintf(ts->ts_name, sizeof(ts->ts_name),
2744187357Sjeff		    "%s tid %d", td->td_name, td->td_tid);
2745187357Sjeff	return (ts->ts_name);
2746187357Sjeff#else
2747187357Sjeff	return (td->td_name);
2748187357Sjeff#endif
2749187357Sjeff}
2750187357Sjeff
2751232700Sjhb#ifdef KTR
2752232700Sjhbvoid
2753232700Sjhbsched_clear_tdname(struct thread *td)
2754232700Sjhb{
2755232700Sjhb	struct td_sched *ts;
2756232700Sjhb
2757232700Sjhb	ts = td->td_sched;
2758232700Sjhb	ts->ts_name[0] = '\0';
2759232700Sjhb}
2760232700Sjhb#endif
2761232700Sjhb
2762184439Sivoras#ifdef SMP
2763184439Sivoras
2764184439Sivoras/*
2765184439Sivoras * Build the CPU topology dump string. Is recursively called to collect
2766184439Sivoras * the topology tree.
2767184439Sivoras */
2768184439Sivorasstatic int
2769184439Sivorassysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
2770184439Sivoras    int indent)
2771184439Sivoras{
2772222813Sattilio	char cpusetbuf[CPUSETBUFSIZ];
2773184439Sivoras	int i, first;
2774184439Sivoras
2775184439Sivoras	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
2776212821Savg	    "", 1 + indent / 2, cg->cg_level);
2777222813Sattilio	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
2778222813Sattilio	    cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
2779184439Sivoras	first = TRUE;
2780184439Sivoras	for (i = 0; i < MAXCPU; i++) {
2781222813Sattilio		if (CPU_ISSET(i, &cg->cg_mask)) {
2782184439Sivoras			if (!first)
2783184439Sivoras				sbuf_printf(sb, ", ");
2784184439Sivoras			else
2785184439Sivoras				first = FALSE;
2786184439Sivoras			sbuf_printf(sb, "%d", i);
2787184439Sivoras		}
2788184439Sivoras	}
2789184439Sivoras	sbuf_printf(sb, "</cpu>\n");
2790184439Sivoras
2791184439Sivoras	if (cg->cg_flags != 0) {
2792210117Sivoras		sbuf_printf(sb, "%*s <flags>", indent, "");
2793184439Sivoras		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
2794208982Sivoras			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
2795208983Sivoras		if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
2796208983Sivoras			sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
2797191643Sjeff		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
2798208983Sivoras			sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
2799210117Sivoras		sbuf_printf(sb, "</flags>\n");
2800184439Sivoras	}
2801184439Sivoras
2802184439Sivoras	if (cg->cg_children > 0) {
2803184439Sivoras		sbuf_printf(sb, "%*s <children>\n", indent, "");
2804184439Sivoras		for (i = 0; i < cg->cg_children; i++)
2805184439Sivoras			sysctl_kern_sched_topology_spec_internal(sb,
2806184439Sivoras			    &cg->cg_child[i], indent+2);
2807184439Sivoras		sbuf_printf(sb, "%*s </children>\n", indent, "");
2808184439Sivoras	}
2809184439Sivoras	sbuf_printf(sb, "%*s</group>\n", indent, "");
2810184439Sivoras	return (0);
2811184439Sivoras}
2812184439Sivoras
2813184439Sivoras/*
2814184439Sivoras * Sysctl handler for retrieving topology dump. It's a wrapper for
2815184439Sivoras * the recursive sysctl_kern_smp_topology_spec_internal().
2816184439Sivoras */
2817184439Sivorasstatic int
2818184439Sivorassysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
2819184439Sivoras{
2820184439Sivoras	struct sbuf *topo;
2821184439Sivoras	int err;
2822184439Sivoras
2823184439Sivoras	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
2824184439Sivoras
2825184570Sivoras	topo = sbuf_new(NULL, NULL, 500, SBUF_AUTOEXTEND);
2826184439Sivoras	if (topo == NULL)
2827184439Sivoras		return (ENOMEM);
2828184439Sivoras
2829184439Sivoras	sbuf_printf(topo, "<groups>\n");
2830184439Sivoras	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
2831184439Sivoras	sbuf_printf(topo, "</groups>\n");
2832184439Sivoras
2833184439Sivoras	if (err == 0) {
2834184439Sivoras		sbuf_finish(topo);
2835184439Sivoras		err = SYSCTL_OUT(req, sbuf_data(topo), sbuf_len(topo));
2836184439Sivoras	}
2837184439Sivoras	sbuf_delete(topo);
2838184439Sivoras	return (err);
2839184439Sivoras}
2840214510Sdavidxu
2841184439Sivoras#endif
2842184439Sivoras
2843239185Smavstatic int
2844239185Smavsysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
2845239185Smav{
2846239185Smav	int error, new_val, period;
2847239185Smav
2848239185Smav	period = 1000000 / realstathz;
2849239185Smav	new_val = period * sched_slice;
2850239185Smav	error = sysctl_handle_int(oidp, &new_val, 0, req);
2851239196Smav	if (error != 0 || req->newptr == NULL)
2852239185Smav		return (error);
2853239185Smav	if (new_val <= 0)
2854239185Smav		return (EINVAL);
2855239196Smav	sched_slice = imax(1, (new_val + period / 2) / period);
2856242736Sjeff	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
2857239196Smav	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
2858239196Smav	    realstathz);
2859239185Smav	return (0);
2860239185Smav}
2861239185Smav
2862177435SjeffSYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2863171482SjeffSYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2864165762Sjeff    "Scheduler name");
2865239185SmavSYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
2866239185Smav    NULL, 0, sysctl_kern_quantum, "I",
2867239196Smav    "Quantum for timeshare threads in microseconds");
2868171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2869239196Smav    "Quantum for timeshare threads in stathz ticks");
2870171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2871239196Smav    "Interactivity score threshold");
2872239196SmavSYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW,
2873239196Smav    &preempt_thresh, 0,
2874239196Smav    "Maximal (lowest) priority for preemption");
2875239196SmavSYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost, 0,
2876239196Smav    "Assign static kernel priorities to sleeping threads");
2877239196SmavSYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins, 0,
2878239196Smav    "Number of times idle thread will spin waiting for new work");
2879239196SmavSYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW,
2880239196Smav    &sched_idlespinthresh, 0,
2881239196Smav    "Threshold before we will permit idle thread spinning");
2882166108Sjeff#ifdef SMP
2883171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2884171482Sjeff    "Number of hz ticks to keep thread affinity for");
2885171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2886171482Sjeff    "Enables the long-term load balancer");
2887172409SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2888172409Sjeff    &balance_interval, 0,
2889239185Smav    "Average period in stathz ticks to run the long-term balancer");
2890171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2891171482Sjeff    "Attempts to steal work from other cores before idling");
2892171506SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2893239196Smav    "Minimum load on remote CPU before we'll steal");
2894184439SivorasSYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
2895239185Smav    CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
2896184439Sivoras    "XML dump of detected CPU topology");
2897166108Sjeff#endif
2898165762Sjeff
2899172264Sjeff/* ps compat.  All cpu percentages from ULE are weighted. */
2900172293Sjeffstatic int ccpu = 0;
2901165762SjeffSYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2902