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: releng/11.0/sys/kern/sched_ule.c 301456 2016-06-05 17:04:03Z kib $");
40116182Sobrien
41147565Speter#include "opt_hwpmc_hooks.h"
42147565Speter#include "opt_sched.h"
43134649Sscottl
44109864Sjeff#include <sys/param.h>
45109864Sjeff#include <sys/systm.h>
46131929Smarcel#include <sys/kdb.h>
47109864Sjeff#include <sys/kernel.h>
48109864Sjeff#include <sys/ktr.h>
49263324Sattilio#include <sys/limits.h>
50109864Sjeff#include <sys/lock.h>
51109864Sjeff#include <sys/mutex.h>
52109864Sjeff#include <sys/proc.h>
53112966Sjeff#include <sys/resource.h>
54122038Sjeff#include <sys/resourcevar.h>
55109864Sjeff#include <sys/sched.h>
56235459Srstone#include <sys/sdt.h>
57109864Sjeff#include <sys/smp.h>
58109864Sjeff#include <sys/sx.h>
59109864Sjeff#include <sys/sysctl.h>
60109864Sjeff#include <sys/sysproto.h>
61139453Sjhb#include <sys/turnstile.h>
62161599Sdavidxu#include <sys/umtx.h>
63109864Sjeff#include <sys/vmmeter.h>
64176735Sjeff#include <sys/cpuset.h>
65184439Sivoras#include <sys/sbuf.h>
66109864Sjeff
67145256Sjkoshy#ifdef HWPMC_HOOKS
68145256Sjkoshy#include <sys/pmckern.h>
69145256Sjkoshy#endif
70145256Sjkoshy
71179297Sjb#ifdef KDTRACE_HOOKS
72179297Sjb#include <sys/dtrace_bsd.h>
73179297Sjbint				dtrace_vtime_active;
74179297Sjbdtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
75179297Sjb#endif
76179297Sjb
77109864Sjeff#include <machine/cpu.h>
78121790Sjeff#include <machine/smp.h>
79109864Sjeff
80171482Sjeff#define	KTR_ULE	0
81166137Sjeff
82187679Sjeff#define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
83187679Sjeff#define	TDQ_NAME_LEN	(sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
84224221Sattilio#define	TDQ_LOADNAME_LEN	(sizeof("CPU ") + sizeof(__XSTRING(MAXCPU)) - 1 + sizeof(" load"))
85187357Sjeff
86166137Sjeff/*
87171482Sjeff * Thread scheduler specific section.  All fields are protected
88171482Sjeff * by the thread lock.
89146954Sjeff */
90164936Sjulianstruct td_sched {
91171482Sjeff	struct runq	*ts_runq;	/* Run-queue we're queued on. */
92171482Sjeff	short		ts_flags;	/* TSF_* flags. */
93273266Sadrian	int		ts_cpu;		/* CPU that we have affinity for. */
94177009Sjeff	int		ts_rltick;	/* Real last tick, for affinity. */
95171482Sjeff	int		ts_slice;	/* Ticks of slice remaining. */
96171482Sjeff	u_int		ts_slptime;	/* Number of ticks we vol. slept */
97171482Sjeff	u_int		ts_runtime;	/* Number of ticks we were running */
98164936Sjulian	int		ts_ltick;	/* Last tick that we were running on */
99164936Sjulian	int		ts_ftick;	/* First tick that we were running on */
100164936Sjulian	int		ts_ticks;	/* Tick count */
101187357Sjeff#ifdef KTR
102187357Sjeff	char		ts_name[TS_NAME_LEN];
103187357Sjeff#endif
104134791Sjulian};
105164936Sjulian/* flags kept in ts_flags */
106166108Sjeff#define	TSF_BOUND	0x0001		/* Thread can not migrate. */
107166108Sjeff#define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
108121790Sjeff
109176735Sjeff#define	THREAD_CAN_MIGRATE(td)	((td)->td_pinned == 0)
110176735Sjeff#define	THREAD_CAN_SCHED(td, cpu)	\
111176735Sjeff    CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
112176735Sjeff
113301456Skib_Static_assert(sizeof(struct thread) + sizeof(struct td_sched) <=
114301456Skib    sizeof(struct thread0_storage),
115301456Skib    "increase struct thread0_storage.t0st_sched size");
116301456Skib
117109864Sjeff/*
118217351Sjhb * Priority ranges used for interactive and non-interactive timeshare
119217410Sjhb * threads.  The timeshare priorities are split up into four ranges.
120217410Sjhb * The first range handles interactive threads.  The last three ranges
121217410Sjhb * (NHALF, x, and NHALF) handle non-interactive threads with the outer
122217410Sjhb * ranges supporting nice values.
123217351Sjhb */
124217410Sjhb#define	PRI_TIMESHARE_RANGE	(PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
125217410Sjhb#define	PRI_INTERACT_RANGE	((PRI_TIMESHARE_RANGE - SCHED_PRI_NRESV) / 2)
126228718Savg#define	PRI_BATCH_RANGE		(PRI_TIMESHARE_RANGE - PRI_INTERACT_RANGE)
127217410Sjhb
128217410Sjhb#define	PRI_MIN_INTERACT	PRI_MIN_TIMESHARE
129217410Sjhb#define	PRI_MAX_INTERACT	(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE - 1)
130217410Sjhb#define	PRI_MIN_BATCH		(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE)
131217351Sjhb#define	PRI_MAX_BATCH		PRI_MAX_TIMESHARE
132217351Sjhb
133217351Sjhb/*
134165762Sjeff * Cpu percentage computation macros and defines.
135111857Sjeff *
136165762Sjeff * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
137165762Sjeff * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
138165796Sjeff * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
139165762Sjeff * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
140165762Sjeff * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
141165762Sjeff * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
142165762Sjeff */
143165762Sjeff#define	SCHED_TICK_SECS		10
144165762Sjeff#define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
145165796Sjeff#define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
146165762Sjeff#define	SCHED_TICK_SHIFT	10
147165762Sjeff#define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
148165830Sjeff#define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
149165762Sjeff
150165762Sjeff/*
151165762Sjeff * These macros determine priorities for non-interactive threads.  They are
152165762Sjeff * assigned a priority based on their recent cpu utilization as expressed
153165762Sjeff * by the ratio of ticks to the tick total.  NHALF priorities at the start
154165762Sjeff * and end of the MIN to MAX timeshare range are only reachable with negative
155165762Sjeff * or positive nice respectively.
156165762Sjeff *
157165762Sjeff * PRI_RANGE:	Priority range for utilization dependent priorities.
158116642Sjeff * PRI_NRESV:	Number of nice values.
159165762Sjeff * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
160165762Sjeff * PRI_NICE:	Determines the part of the priority inherited from nice.
161109864Sjeff */
162165762Sjeff#define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
163121869Sjeff#define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
164217351Sjhb#define	SCHED_PRI_MIN		(PRI_MIN_BATCH + SCHED_PRI_NHALF)
165217351Sjhb#define	SCHED_PRI_MAX		(PRI_MAX_BATCH - SCHED_PRI_NHALF)
166217237Sjhb#define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN + 1)
167165762Sjeff#define	SCHED_PRI_TICKS(ts)						\
168165762Sjeff    (SCHED_TICK_HZ((ts)) /						\
169165827Sjeff    (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
170165762Sjeff#define	SCHED_PRI_NICE(nice)	(nice)
171109864Sjeff
172109864Sjeff/*
173165762Sjeff * These determine the interactivity of a process.  Interactivity differs from
174165762Sjeff * cpu utilization in that it expresses the voluntary time slept vs time ran
175165762Sjeff * while cpu utilization includes all time not running.  This more accurately
176165762Sjeff * models the intent of the thread.
177109864Sjeff *
178110645Sjeff * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
179110645Sjeff *		before throttling back.
180121868Sjeff * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
181116365Sjeff * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
182215102Sattilio * INTERACT_THRESH:	Threshold for placement on the current runq.
183109864Sjeff */
184165762Sjeff#define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
185165762Sjeff#define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
186116365Sjeff#define	SCHED_INTERACT_MAX	(100)
187116365Sjeff#define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
188121126Sjeff#define	SCHED_INTERACT_THRESH	(30)
189111857Sjeff
190242736Sjeff/*
191242736Sjeff * These parameters determine the slice behavior for batch work.
192242736Sjeff */
193242736Sjeff#define	SCHED_SLICE_DEFAULT_DIVISOR	10	/* ~94 ms, 12 stathz ticks. */
194242736Sjeff#define	SCHED_SLICE_MIN_DIVISOR		6	/* DEFAULT/MIN = ~16 ms. */
195242736Sjeff
196239157Smav/* Flags kept in td_flags. */
197239157Smav#define	TDF_SLICEEND	TDF_SCHED2	/* Thread time slice is over. */
198239157Smav
199109864Sjeff/*
200165762Sjeff * tickincr:		Converts a stathz tick into a hz domain scaled by
201165762Sjeff *			the shift factor.  Without the shift the error rate
202165762Sjeff *			due to rounding would be unacceptably high.
203165762Sjeff * realstathz:		stathz is sometimes 0 and run off of hz.
204165762Sjeff * sched_slice:		Runtime of each thread before rescheduling.
205171482Sjeff * preempt_thresh:	Priority threshold for preemption and remote IPIs.
206109864Sjeff */
207165762Sjeffstatic int sched_interact = SCHED_INTERACT_THRESH;
208241844Seadlerstatic int tickincr = 8 << SCHED_TICK_SHIFT;
209242736Sjeffstatic int realstathz = 127;	/* reset during boot. */
210242736Sjeffstatic int sched_slice = 10;	/* reset during boot. */
211242736Sjeffstatic int sched_slice_min = 1;	/* reset during boot. */
212172345Sjeff#ifdef PREEMPTION
213172345Sjeff#ifdef FULL_PREEMPTION
214172345Sjeffstatic int preempt_thresh = PRI_MAX_IDLE;
215172345Sjeff#else
216171482Sjeffstatic int preempt_thresh = PRI_MIN_KERN;
217172345Sjeff#endif
218172345Sjeff#else
219172345Sjeffstatic int preempt_thresh = 0;
220172345Sjeff#endif
221217351Sjhbstatic int static_boost = PRI_MIN_BATCH;
222178277Sjeffstatic int sched_idlespins = 10000;
223232740Smavstatic int sched_idlespinthresh = -1;
224109864Sjeff
225109864Sjeff/*
226171482Sjeff * tdq - per processor runqs and statistics.  All fields are protected by the
227171482Sjeff * tdq_lock.  The load and lowpri may be accessed without to avoid excess
228171482Sjeff * locking in sched_pickcpu();
229109864Sjeff */
230164936Sjulianstruct tdq {
231242014Sjimharris	/*
232242014Sjimharris	 * Ordered to improve efficiency of cpu_search() and switch().
233242014Sjimharris	 * tdq_lock is padded to avoid false sharing with tdq_load and
234242014Sjimharris	 * tdq_cpu_idle.
235242014Sjimharris	 */
236242402Sattilio	struct mtx_padalign tdq_lock;		/* run queue lock. */
237176735Sjeff	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
238178277Sjeff	volatile int	tdq_load;		/* Aggregate load. */
239212416Smav	volatile int	tdq_cpu_idle;		/* cpu_idle() is active. */
240176735Sjeff	int		tdq_sysload;		/* For loadavg, !ITHD load. */
241177009Sjeff	int		tdq_transferable;	/* Transferable thread count. */
242178277Sjeff	short		tdq_switchcnt;		/* Switches this tick. */
243178277Sjeff	short		tdq_oldswitchcnt;	/* Switches last tick. */
244177009Sjeff	u_char		tdq_lowpri;		/* Lowest priority thread. */
245177009Sjeff	u_char		tdq_ipipending;		/* IPI pending. */
246166557Sjeff	u_char		tdq_idx;		/* Current insert index. */
247166557Sjeff	u_char		tdq_ridx;		/* Current removal index. */
248177009Sjeff	struct runq	tdq_realtime;		/* real-time run queue. */
249177009Sjeff	struct runq	tdq_timeshare;		/* timeshare run queue. */
250177009Sjeff	struct runq	tdq_idle;		/* Queue of IDLE threads. */
251187357Sjeff	char		tdq_name[TDQ_NAME_LEN];
252187357Sjeff#ifdef KTR
253187357Sjeff	char		tdq_loadname[TDQ_LOADNAME_LEN];
254187357Sjeff#endif
255171482Sjeff} __aligned(64);
256109864Sjeff
257178277Sjeff/* Idle thread states and config. */
258178277Sjeff#define	TDQ_RUNNING	1
259178277Sjeff#define	TDQ_IDLE	2
260166108Sjeff
261123433Sjeff#ifdef SMP
262184439Sivorasstruct cpu_group *cpu_top;		/* CPU topology */
263123433Sjeff
264176735Sjeff#define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
265176735Sjeff#define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
266166108Sjeff
267123433Sjeff/*
268166108Sjeff * Run-time tunables.
269166108Sjeff */
270171506Sjeffstatic int rebalance = 1;
271172409Sjeffstatic int balance_interval = 128;	/* Default set in sched_initticks(). */
272166108Sjeffstatic int affinity;
273171506Sjeffstatic int steal_idle = 1;
274171506Sjeffstatic int steal_thresh = 2;
275166108Sjeff
276166108Sjeff/*
277165620Sjeff * One thread queue per processor.
278109864Sjeff */
279164936Sjulianstatic struct tdq	tdq_cpu[MAXCPU];
280172409Sjeffstatic struct tdq	*balance_tdq;
281172409Sjeffstatic int balance_ticks;
282232207Smavstatic DPCPU_DEFINE(uint32_t, randomval);
283129982Sjeff
284164936Sjulian#define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
285164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu[(x)])
286171713Sjeff#define	TDQ_ID(x)	((int)((x) - tdq_cpu))
287123433Sjeff#else	/* !SMP */
288164936Sjulianstatic struct tdq	tdq_cpu;
289129982Sjeff
290170315Sjeff#define	TDQ_ID(x)	(0)
291164936Sjulian#define	TDQ_SELF()	(&tdq_cpu)
292164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu)
293110028Sjeff#endif
294109864Sjeff
295171482Sjeff#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
296171482Sjeff#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
297171482Sjeff#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
298171482Sjeff#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
299242402Sattilio#define	TDQ_LOCKPTR(t)		((struct mtx *)(&(t)->tdq_lock))
300171482Sjeff
301163709Sjbstatic void sched_priority(struct thread *);
302146954Sjeffstatic void sched_thread_priority(struct thread *, u_char);
303163709Sjbstatic int sched_interact_score(struct thread *);
304163709Sjbstatic void sched_interact_update(struct thread *);
305163709Sjbstatic void sched_interact_fork(struct thread *);
306232917Smavstatic void sched_pctcpu_update(struct td_sched *, int);
307109864Sjeff
308110267Sjeff/* Operations on per processor queues */
309177435Sjeffstatic struct thread *tdq_choose(struct tdq *);
310164936Sjulianstatic void tdq_setup(struct tdq *);
311177435Sjeffstatic void tdq_load_add(struct tdq *, struct thread *);
312177435Sjeffstatic void tdq_load_rem(struct tdq *, struct thread *);
313177435Sjeffstatic __inline void tdq_runq_add(struct tdq *, struct thread *, int);
314177435Sjeffstatic __inline void tdq_runq_rem(struct tdq *, struct thread *);
315177005Sjeffstatic inline int sched_shouldpreempt(int, int, int);
316164936Sjulianvoid tdq_print(int cpu);
317165762Sjeffstatic void runq_print(struct runq *rq);
318171482Sjeffstatic void tdq_add(struct tdq *, struct thread *, int);
319110267Sjeff#ifdef SMP
320176735Sjeffstatic int tdq_move(struct tdq *, struct tdq *);
321171482Sjeffstatic int tdq_idled(struct tdq *);
322177435Sjeffstatic void tdq_notify(struct tdq *, struct thread *);
323177435Sjeffstatic struct thread *tdq_steal(struct tdq *, int);
324177435Sjeffstatic struct thread *runq_steal(struct runq *, int);
325177435Sjeffstatic int sched_pickcpu(struct thread *, int);
326172409Sjeffstatic void sched_balance(void);
327176735Sjeffstatic int sched_balance_pair(struct tdq *, struct tdq *);
328177435Sjeffstatic inline struct tdq *sched_setcpu(struct thread *, int, int);
329171482Sjeffstatic inline void thread_unblock_switch(struct thread *, struct mtx *);
330171713Sjeffstatic struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
331184439Sivorasstatic int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
332184439Sivorasstatic int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
333184439Sivoras    struct cpu_group *cg, int indent);
334121790Sjeff#endif
335110028Sjeff
336165762Sjeffstatic void sched_setup(void *dummy);
337177253SrwatsonSYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
338165762Sjeff
339165762Sjeffstatic void sched_initticks(void *dummy);
340177253SrwatsonSYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
341177253Srwatson    NULL);
342165762Sjeff
343235459SrstoneSDT_PROVIDER_DEFINE(sched);
344235459Srstone
345258622SavgSDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
346235459Srstone    "struct proc *", "uint8_t");
347258622SavgSDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
348235459Srstone    "struct proc *", "void *");
349258622SavgSDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
350235459Srstone    "struct proc *", "void *", "int");
351258622SavgSDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
352235459Srstone    "struct proc *", "uint8_t", "struct thread *");
353258622SavgSDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
354258622SavgSDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
355235459Srstone    "struct proc *");
356258622SavgSDT_PROBE_DEFINE(sched, , , on__cpu);
357258622SavgSDT_PROBE_DEFINE(sched, , , remain__cpu);
358258622SavgSDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
359235459Srstone    "struct proc *");
360235459Srstone
361171482Sjeff/*
362171482Sjeff * Print the threads waiting on a run-queue.
363171482Sjeff */
364165762Sjeffstatic void
365165762Sjeffrunq_print(struct runq *rq)
366165762Sjeff{
367165762Sjeff	struct rqhead *rqh;
368177435Sjeff	struct thread *td;
369165762Sjeff	int pri;
370165762Sjeff	int j;
371165762Sjeff	int i;
372165762Sjeff
373165762Sjeff	for (i = 0; i < RQB_LEN; i++) {
374165762Sjeff		printf("\t\trunq bits %d 0x%zx\n",
375165762Sjeff		    i, rq->rq_status.rqb_bits[i]);
376165762Sjeff		for (j = 0; j < RQB_BPW; j++)
377165762Sjeff			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
378165762Sjeff				pri = j + (i << RQB_L2BPW);
379165762Sjeff				rqh = &rq->rq_queues[pri];
380177435Sjeff				TAILQ_FOREACH(td, rqh, td_runq) {
381165762Sjeff					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
382177435Sjeff					    td, td->td_name, td->td_priority,
383177435Sjeff					    td->td_rqindex, pri);
384165762Sjeff				}
385165762Sjeff			}
386165762Sjeff	}
387165762Sjeff}
388165762Sjeff
389171482Sjeff/*
390171482Sjeff * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
391171482Sjeff */
392113357Sjeffvoid
393164936Sjuliantdq_print(int cpu)
394110267Sjeff{
395164936Sjulian	struct tdq *tdq;
396112994Sjeff
397164936Sjulian	tdq = TDQ_CPU(cpu);
398112994Sjeff
399171713Sjeff	printf("tdq %d:\n", TDQ_ID(tdq));
400176735Sjeff	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
401176735Sjeff	printf("\tLock name:      %s\n", tdq->tdq_name);
402165620Sjeff	printf("\tload:           %d\n", tdq->tdq_load);
403178277Sjeff	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
404178277Sjeff	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
405171482Sjeff	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
406165766Sjeff	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
407178277Sjeff	printf("\tload transferable: %d\n", tdq->tdq_transferable);
408178277Sjeff	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
409165762Sjeff	printf("\trealtime runq:\n");
410165762Sjeff	runq_print(&tdq->tdq_realtime);
411165762Sjeff	printf("\ttimeshare runq:\n");
412165762Sjeff	runq_print(&tdq->tdq_timeshare);
413165762Sjeff	printf("\tidle runq:\n");
414165762Sjeff	runq_print(&tdq->tdq_idle);
415113357Sjeff}
416112994Sjeff
417177005Sjeffstatic inline int
418177005Sjeffsched_shouldpreempt(int pri, int cpri, int remote)
419177005Sjeff{
420177005Sjeff	/*
421177005Sjeff	 * If the new priority is not better than the current priority there is
422177005Sjeff	 * nothing to do.
423177005Sjeff	 */
424177005Sjeff	if (pri >= cpri)
425177005Sjeff		return (0);
426177005Sjeff	/*
427177005Sjeff	 * Always preempt idle.
428177005Sjeff	 */
429177005Sjeff	if (cpri >= PRI_MIN_IDLE)
430177005Sjeff		return (1);
431177005Sjeff	/*
432177005Sjeff	 * If preemption is disabled don't preempt others.
433177005Sjeff	 */
434177005Sjeff	if (preempt_thresh == 0)
435177005Sjeff		return (0);
436177005Sjeff	/*
437177005Sjeff	 * Preempt if we exceed the threshold.
438177005Sjeff	 */
439177005Sjeff	if (pri <= preempt_thresh)
440177005Sjeff		return (1);
441177005Sjeff	/*
442217351Sjhb	 * If we're interactive or better and there is non-interactive
443217351Sjhb	 * or worse running preempt only remote processors.
444177005Sjeff	 */
445217351Sjhb	if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
446177005Sjeff		return (1);
447177005Sjeff	return (0);
448177005Sjeff}
449177005Sjeff
450171482Sjeff/*
451171482Sjeff * Add a thread to the actual run-queue.  Keeps transferable counts up to
452171482Sjeff * date with what is actually on the run-queue.  Selects the correct
453171482Sjeff * queue position for timeshare threads.
454171482Sjeff */
455122744Sjeffstatic __inline void
456177435Sjefftdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
457122744Sjeff{
458177435Sjeff	struct td_sched *ts;
459177042Sjeff	u_char pri;
460177042Sjeff
461171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
462177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
463177009Sjeff
464177435Sjeff	pri = td->td_priority;
465301456Skib	ts = td_get_sched(td);
466177435Sjeff	TD_SET_RUNQ(td);
467177435Sjeff	if (THREAD_CAN_MIGRATE(td)) {
468165620Sjeff		tdq->tdq_transferable++;
469164936Sjulian		ts->ts_flags |= TSF_XFERABLE;
470123433Sjeff	}
471217351Sjhb	if (pri < PRI_MIN_BATCH) {
472177042Sjeff		ts->ts_runq = &tdq->tdq_realtime;
473217351Sjhb	} else if (pri <= PRI_MAX_BATCH) {
474177042Sjeff		ts->ts_runq = &tdq->tdq_timeshare;
475217351Sjhb		KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
476165762Sjeff			("Invalid priority %d on timeshare runq", pri));
477165762Sjeff		/*
478165762Sjeff		 * This queue contains only priorities between MIN and MAX
479165762Sjeff		 * realtime.  Use the whole queue to represent these values.
480165762Sjeff		 */
481171713Sjeff		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
482228718Savg			pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
483165762Sjeff			pri = (pri + tdq->tdq_idx) % RQ_NQS;
484165766Sjeff			/*
485165766Sjeff			 * This effectively shortens the queue by one so we
486165766Sjeff			 * can have a one slot difference between idx and
487165766Sjeff			 * ridx while we wait for threads to drain.
488165766Sjeff			 */
489165766Sjeff			if (tdq->tdq_ridx != tdq->tdq_idx &&
490165766Sjeff			    pri == tdq->tdq_ridx)
491167664Sjeff				pri = (unsigned char)(pri - 1) % RQ_NQS;
492165762Sjeff		} else
493165766Sjeff			pri = tdq->tdq_ridx;
494177435Sjeff		runq_add_pri(ts->ts_runq, td, pri, flags);
495177042Sjeff		return;
496165762Sjeff	} else
497177009Sjeff		ts->ts_runq = &tdq->tdq_idle;
498177435Sjeff	runq_add(ts->ts_runq, td, flags);
499177009Sjeff}
500177009Sjeff
501171482Sjeff/*
502171482Sjeff * Remove a thread from a run-queue.  This typically happens when a thread
503171482Sjeff * is selected to run.  Running threads are not on the queue and the
504171482Sjeff * transferable count does not reflect them.
505171482Sjeff */
506122744Sjeffstatic __inline void
507177435Sjefftdq_runq_rem(struct tdq *tdq, struct thread *td)
508122744Sjeff{
509177435Sjeff	struct td_sched *ts;
510177435Sjeff
511301456Skib	ts = td_get_sched(td);
512171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
513171482Sjeff	KASSERT(ts->ts_runq != NULL,
514177435Sjeff	    ("tdq_runq_remove: thread %p null ts_runq", td));
515164936Sjulian	if (ts->ts_flags & TSF_XFERABLE) {
516165620Sjeff		tdq->tdq_transferable--;
517164936Sjulian		ts->ts_flags &= ~TSF_XFERABLE;
518123433Sjeff	}
519165766Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
520165766Sjeff		if (tdq->tdq_idx != tdq->tdq_ridx)
521177435Sjeff			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
522165766Sjeff		else
523177435Sjeff			runq_remove_idx(ts->ts_runq, td, NULL);
524165766Sjeff	} else
525177435Sjeff		runq_remove(ts->ts_runq, td);
526122744Sjeff}
527122744Sjeff
528171482Sjeff/*
529171482Sjeff * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
530171482Sjeff * for this thread to the referenced thread queue.
531171482Sjeff */
532113357Sjeffstatic void
533177435Sjefftdq_load_add(struct tdq *tdq, struct thread *td)
534113357Sjeff{
535171482Sjeff
536171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
537177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
538177902Sjeff
539165620Sjeff	tdq->tdq_load++;
540198854Sattilio	if ((td->td_flags & TDF_NOLOAD) == 0)
541177902Sjeff		tdq->tdq_sysload++;
542187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
543258622Savg	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
544110267Sjeff}
545113357Sjeff
546171482Sjeff/*
547171482Sjeff * Remove the load from a thread that is transitioning to a sleep state or
548171482Sjeff * exiting.
549171482Sjeff */
550112994Sjeffstatic void
551177435Sjefftdq_load_rem(struct tdq *tdq, struct thread *td)
552110267Sjeff{
553171482Sjeff
554177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
555171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
556171482Sjeff	KASSERT(tdq->tdq_load != 0,
557171713Sjeff	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
558177902Sjeff
559165620Sjeff	tdq->tdq_load--;
560198854Sattilio	if ((td->td_flags & TDF_NOLOAD) == 0)
561177902Sjeff		tdq->tdq_sysload--;
562187357Sjeff	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
563258622Savg	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
564110267Sjeff}
565110267Sjeff
566176735Sjeff/*
567242736Sjeff * Bound timeshare latency by decreasing slice size as load increases.  We
568242736Sjeff * consider the maximum latency as the sum of the threads waiting to run
569242736Sjeff * aside from curthread and target no more than sched_slice latency but
570242736Sjeff * no less than sched_slice_min runtime.
571242736Sjeff */
572242736Sjeffstatic inline int
573242736Sjefftdq_slice(struct tdq *tdq)
574242736Sjeff{
575242736Sjeff	int load;
576242736Sjeff
577242736Sjeff	/*
578242736Sjeff	 * It is safe to use sys_load here because this is called from
579242736Sjeff	 * contexts where timeshare threads are running and so there
580242736Sjeff	 * cannot be higher priority load in the system.
581242736Sjeff	 */
582242736Sjeff	load = tdq->tdq_sysload - 1;
583242736Sjeff	if (load >= SCHED_SLICE_MIN_DIVISOR)
584242736Sjeff		return (sched_slice_min);
585242736Sjeff	if (load <= 1)
586242736Sjeff		return (sched_slice);
587242736Sjeff	return (sched_slice / load);
588242736Sjeff}
589242736Sjeff
590242736Sjeff/*
591176735Sjeff * Set lowpri to its exact value by searching the run-queue and
592176735Sjeff * evaluating curthread.  curthread may be passed as an optimization.
593176735Sjeff */
594176735Sjeffstatic void
595176735Sjefftdq_setlowpri(struct tdq *tdq, struct thread *ctd)
596176735Sjeff{
597176735Sjeff	struct thread *td;
598176735Sjeff
599176735Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
600176735Sjeff	if (ctd == NULL)
601176735Sjeff		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
602177435Sjeff	td = tdq_choose(tdq);
603177435Sjeff	if (td == NULL || td->td_priority > ctd->td_priority)
604176735Sjeff		tdq->tdq_lowpri = ctd->td_priority;
605176735Sjeff	else
606176735Sjeff		tdq->tdq_lowpri = td->td_priority;
607176735Sjeff}
608176735Sjeff
609113357Sjeff#ifdef SMP
610285243Spfg/*
611285243Spfg * We need some randomness. Implement a classic Linear Congruential
612285243Spfg * Generator X_{n+1}=(aX_n+c) mod m. These values are optimized for
613285243Spfg * m = 2^32, a = 69069 and c = 5. We only return the upper 16 bits
614285243Spfg * of the random state (in the low bits of our answer) to keep
615285243Spfg * the maximum randomness.
616285243Spfg */
617285243Spfgstatic uint32_t
618285243Spfgsched_random(void)
619285243Spfg{
620285243Spfg	uint32_t *rndptr;
621285243Spfg
622285243Spfg	rndptr = DPCPU_PTR(randomval);
623285243Spfg	*rndptr = *rndptr * 69069 + 5;
624285243Spfg
625285243Spfg	return (*rndptr >> 16);
626285243Spfg}
627285243Spfg
628176735Sjeffstruct cpu_search {
629194779Sjeff	cpuset_t cs_mask;
630232207Smav	u_int	cs_prefer;
631232207Smav	int	cs_pri;		/* Min priority for low. */
632232207Smav	int	cs_limit;	/* Max load for low, min load for high. */
633232207Smav	int	cs_cpu;
634232207Smav	int	cs_load;
635176735Sjeff};
636176735Sjeff
637176735Sjeff#define	CPU_SEARCH_LOWEST	0x1
638176735Sjeff#define	CPU_SEARCH_HIGHEST	0x2
639176735Sjeff#define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
640176735Sjeff
641194779Sjeff#define	CPUSET_FOREACH(cpu, mask)				\
642194779Sjeff	for ((cpu) = 0; (cpu) <= mp_maxid; (cpu)++)		\
643222813Sattilio		if (CPU_ISSET(cpu, &mask))
644176735Sjeff
645268211Skibstatic __always_inline int cpu_search(const struct cpu_group *cg,
646268211Skib    struct cpu_search *low, struct cpu_search *high, const int match);
647268211Skibint __noinline cpu_search_lowest(const struct cpu_group *cg,
648268211Skib    struct cpu_search *low);
649268211Skibint __noinline cpu_search_highest(const struct cpu_group *cg,
650176735Sjeff    struct cpu_search *high);
651268211Skibint __noinline cpu_search_both(const struct cpu_group *cg,
652268211Skib    struct cpu_search *low, struct cpu_search *high);
653176735Sjeff
654116069Sjeff/*
655176735Sjeff * Search the tree of cpu_groups for the lowest or highest loaded cpu
656176735Sjeff * according to the match argument.  This routine actually compares the
657176735Sjeff * load on all paths through the tree and finds the least loaded cpu on
658176735Sjeff * the least loaded path, which may differ from the least loaded cpu in
659176735Sjeff * the system.  This balances work among caches and busses.
660116069Sjeff *
661176735Sjeff * This inline is instantiated in three forms below using constants for the
662176735Sjeff * match argument.  It is reduced to the minimum set for each case.  It is
663176735Sjeff * also recursive to the depth of the tree.
664116069Sjeff */
665268211Skibstatic __always_inline int
666232207Smavcpu_search(const struct cpu_group *cg, struct cpu_search *low,
667176735Sjeff    struct cpu_search *high, const int match)
668176735Sjeff{
669232207Smav	struct cpu_search lgroup;
670232207Smav	struct cpu_search hgroup;
671232207Smav	cpuset_t cpumask;
672232207Smav	struct cpu_group *child;
673232207Smav	struct tdq *tdq;
674279349Simp	int cpu, i, hload, lload, load, total, rnd;
675176735Sjeff
676176735Sjeff	total = 0;
677232207Smav	cpumask = cg->cg_mask;
678232207Smav	if (match & CPU_SEARCH_LOWEST) {
679232207Smav		lload = INT_MAX;
680232207Smav		lgroup = *low;
681232207Smav	}
682232207Smav	if (match & CPU_SEARCH_HIGHEST) {
683234066Smav		hload = INT_MIN;
684232207Smav		hgroup = *high;
685232207Smav	}
686176735Sjeff
687232207Smav	/* Iterate through the child CPU groups and then remaining CPUs. */
688255363Smav	for (i = cg->cg_children, cpu = mp_maxid; ; ) {
689234066Smav		if (i == 0) {
690255363Smav#ifdef HAVE_INLINE_FFSL
691255363Smav			cpu = CPU_FFS(&cpumask) - 1;
692255363Smav#else
693234066Smav			while (cpu >= 0 && !CPU_ISSET(cpu, &cpumask))
694234066Smav				cpu--;
695255363Smav#endif
696234066Smav			if (cpu < 0)
697232207Smav				break;
698232207Smav			child = NULL;
699232207Smav		} else
700234066Smav			child = &cg->cg_child[i - 1];
701232207Smav
702234066Smav		if (match & CPU_SEARCH_LOWEST)
703234066Smav			lgroup.cs_cpu = -1;
704234066Smav		if (match & CPU_SEARCH_HIGHEST)
705234066Smav			hgroup.cs_cpu = -1;
706232207Smav		if (child) {			/* Handle child CPU group. */
707232207Smav			CPU_NAND(&cpumask, &child->cg_mask);
708176735Sjeff			switch (match) {
709176735Sjeff			case CPU_SEARCH_LOWEST:
710176735Sjeff				load = cpu_search_lowest(child, &lgroup);
711176735Sjeff				break;
712176735Sjeff			case CPU_SEARCH_HIGHEST:
713176735Sjeff				load = cpu_search_highest(child, &hgroup);
714176735Sjeff				break;
715176735Sjeff			case CPU_SEARCH_BOTH:
716176735Sjeff				load = cpu_search_both(child, &lgroup, &hgroup);
717176735Sjeff				break;
718176735Sjeff			}
719232207Smav		} else {			/* Handle child CPU. */
720255363Smav			CPU_CLR(cpu, &cpumask);
721232207Smav			tdq = TDQ_CPU(cpu);
722232207Smav			load = tdq->tdq_load * 256;
723279373Simp			rnd = sched_random() % 32;
724232207Smav			if (match & CPU_SEARCH_LOWEST) {
725232207Smav				if (cpu == low->cs_prefer)
726232207Smav					load -= 64;
727232207Smav				/* If that CPU is allowed and get data. */
728234066Smav				if (tdq->tdq_lowpri > lgroup.cs_pri &&
729234066Smav				    tdq->tdq_load <= lgroup.cs_limit &&
730234066Smav				    CPU_ISSET(cpu, &lgroup.cs_mask)) {
731232207Smav					lgroup.cs_cpu = cpu;
732232207Smav					lgroup.cs_load = load - rnd;
733176735Sjeff				}
734232207Smav			}
735232207Smav			if (match & CPU_SEARCH_HIGHEST)
736234066Smav				if (tdq->tdq_load >= hgroup.cs_limit &&
737234066Smav				    tdq->tdq_transferable &&
738234066Smav				    CPU_ISSET(cpu, &hgroup.cs_mask)) {
739232207Smav					hgroup.cs_cpu = cpu;
740232207Smav					hgroup.cs_load = load - rnd;
741176735Sjeff				}
742176735Sjeff		}
743232207Smav		total += load;
744176735Sjeff
745232207Smav		/* We have info about child item. Compare it. */
746232207Smav		if (match & CPU_SEARCH_LOWEST) {
747234066Smav			if (lgroup.cs_cpu >= 0 &&
748232454Smav			    (load < lload ||
749232454Smav			     (load == lload && lgroup.cs_load < low->cs_load))) {
750232207Smav				lload = load;
751232207Smav				low->cs_cpu = lgroup.cs_cpu;
752232207Smav				low->cs_load = lgroup.cs_load;
753232207Smav			}
754232207Smav		}
755232207Smav		if (match & CPU_SEARCH_HIGHEST)
756234066Smav			if (hgroup.cs_cpu >= 0 &&
757232454Smav			    (load > hload ||
758232454Smav			     (load == hload && hgroup.cs_load > high->cs_load))) {
759232207Smav				hload = load;
760232207Smav				high->cs_cpu = hgroup.cs_cpu;
761232207Smav				high->cs_load = hgroup.cs_load;
762232207Smav			}
763234066Smav		if (child) {
764234066Smav			i--;
765234066Smav			if (i == 0 && CPU_EMPTY(&cpumask))
766234066Smav				break;
767255363Smav		}
768255363Smav#ifndef HAVE_INLINE_FFSL
769255363Smav		else
770234066Smav			cpu--;
771255363Smav#endif
772176735Sjeff	}
773176735Sjeff	return (total);
774176735Sjeff}
775176735Sjeff
776176735Sjeff/*
777176735Sjeff * cpu_search instantiations must pass constants to maintain the inline
778176735Sjeff * optimization.
779176735Sjeff */
780176735Sjeffint
781232207Smavcpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low)
782176735Sjeff{
783176735Sjeff	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
784176735Sjeff}
785176735Sjeff
786176735Sjeffint
787232207Smavcpu_search_highest(const struct cpu_group *cg, struct cpu_search *high)
788176735Sjeff{
789176735Sjeff	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
790176735Sjeff}
791176735Sjeff
792176735Sjeffint
793232207Smavcpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
794176735Sjeff    struct cpu_search *high)
795176735Sjeff{
796176735Sjeff	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
797176735Sjeff}
798176735Sjeff
799176735Sjeff/*
800176735Sjeff * Find the cpu with the least load via the least loaded path that has a
801176735Sjeff * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
802176735Sjeff * acceptable.
803176735Sjeff */
804176735Sjeffstatic inline int
805232207Smavsched_lowest(const struct cpu_group *cg, cpuset_t mask, int pri, int maxload,
806232207Smav    int prefer)
807176735Sjeff{
808176735Sjeff	struct cpu_search low;
809176735Sjeff
810176735Sjeff	low.cs_cpu = -1;
811232207Smav	low.cs_prefer = prefer;
812176735Sjeff	low.cs_mask = mask;
813232207Smav	low.cs_pri = pri;
814232207Smav	low.cs_limit = maxload;
815176735Sjeff	cpu_search_lowest(cg, &low);
816176735Sjeff	return low.cs_cpu;
817176735Sjeff}
818176735Sjeff
819176735Sjeff/*
820176735Sjeff * Find the cpu with the highest load via the highest loaded path.
821176735Sjeff */
822176735Sjeffstatic inline int
823232207Smavsched_highest(const struct cpu_group *cg, cpuset_t mask, int minload)
824176735Sjeff{
825176735Sjeff	struct cpu_search high;
826176735Sjeff
827176735Sjeff	high.cs_cpu = -1;
828176735Sjeff	high.cs_mask = mask;
829176735Sjeff	high.cs_limit = minload;
830176735Sjeff	cpu_search_highest(cg, &high);
831176735Sjeff	return high.cs_cpu;
832176735Sjeff}
833176735Sjeff
834121790Sjeffstatic void
835176735Sjeffsched_balance_group(struct cpu_group *cg)
836116069Sjeff{
837232207Smav	cpuset_t hmask, lmask;
838232207Smav	int high, low, anylow;
839123487Sjeff
840232207Smav	CPU_FILL(&hmask);
841176735Sjeff	for (;;) {
842232207Smav		high = sched_highest(cg, hmask, 1);
843232207Smav		/* Stop if there is no more CPU with transferrable threads. */
844232207Smav		if (high == -1)
845176735Sjeff			break;
846232207Smav		CPU_CLR(high, &hmask);
847232207Smav		CPU_COPY(&hmask, &lmask);
848232207Smav		/* Stop if there is no more CPU left for low. */
849232207Smav		if (CPU_EMPTY(&lmask))
850176735Sjeff			break;
851232207Smav		anylow = 1;
852232207Smavnextlow:
853232207Smav		low = sched_lowest(cg, lmask, -1,
854232207Smav		    TDQ_CPU(high)->tdq_load - 1, high);
855232207Smav		/* Stop if we looked well and found no less loaded CPU. */
856232207Smav		if (anylow && low == -1)
857232207Smav			break;
858232207Smav		/* Go to next high if we found no less loaded CPU. */
859232207Smav		if (low == -1)
860232207Smav			continue;
861232207Smav		/* Transfer thread from high to low. */
862232207Smav		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low))) {
863232207Smav			/* CPU that got thread can no longer be a donor. */
864232207Smav			CPU_CLR(low, &hmask);
865232207Smav		} else {
866232207Smav			/*
867232207Smav			 * If failed, then there is no threads on high
868232207Smav			 * that can run on this low. Drop low from low
869232207Smav			 * mask and look for different one.
870232207Smav			 */
871232207Smav			CPU_CLR(low, &lmask);
872232207Smav			anylow = 0;
873232207Smav			goto nextlow;
874232207Smav		}
875123487Sjeff	}
876123487Sjeff}
877123487Sjeff
878123487Sjeffstatic void
879201148Sedsched_balance(void)
880123487Sjeff{
881172409Sjeff	struct tdq *tdq;
882123487Sjeff
883171482Sjeff	if (smp_started == 0 || rebalance == 0)
884171482Sjeff		return;
885279349Simp
886279349Simp	balance_ticks = max(balance_interval / 2, 1) +
887279373Simp	    (sched_random() % balance_interval);
888172409Sjeff	tdq = TDQ_SELF();
889172409Sjeff	TDQ_UNLOCK(tdq);
890176735Sjeff	sched_balance_group(cpu_top);
891172409Sjeff	TDQ_LOCK(tdq);
892123487Sjeff}
893123487Sjeff
894171482Sjeff/*
895171482Sjeff * Lock two thread queues using their address to maintain lock order.
896171482Sjeff */
897123487Sjeffstatic void
898171482Sjefftdq_lock_pair(struct tdq *one, struct tdq *two)
899171482Sjeff{
900171482Sjeff	if (one < two) {
901171482Sjeff		TDQ_LOCK(one);
902171482Sjeff		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
903171482Sjeff	} else {
904171482Sjeff		TDQ_LOCK(two);
905171482Sjeff		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
906171482Sjeff	}
907171482Sjeff}
908171482Sjeff
909171482Sjeff/*
910172409Sjeff * Unlock two thread queues.  Order is not important here.
911172409Sjeff */
912172409Sjeffstatic void
913172409Sjefftdq_unlock_pair(struct tdq *one, struct tdq *two)
914172409Sjeff{
915172409Sjeff	TDQ_UNLOCK(one);
916172409Sjeff	TDQ_UNLOCK(two);
917172409Sjeff}
918172409Sjeff
919172409Sjeff/*
920171482Sjeff * Transfer load between two imbalanced thread queues.
921171482Sjeff */
922176735Sjeffstatic int
923164936Sjuliansched_balance_pair(struct tdq *high, struct tdq *low)
924123487Sjeff{
925176735Sjeff	int moved;
926226057Smarius	int cpu;
927116069Sjeff
928171482Sjeff	tdq_lock_pair(high, low);
929176735Sjeff	moved = 0;
930116069Sjeff	/*
931122744Sjeff	 * Determine what the imbalance is and then adjust that to how many
932165620Sjeff	 * threads we actually have to give up (transferable).
933122744Sjeff	 */
934232207Smav	if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load &&
935232207Smav	    (moved = tdq_move(high, low)) > 0) {
936172293Sjeff		/*
937226057Smarius		 * In case the target isn't the current cpu IPI it to force a
938226057Smarius		 * reschedule with the new workload.
939172293Sjeff		 */
940226057Smarius		cpu = TDQ_ID(low);
941226057Smarius		if (cpu != PCPU_GET(cpuid))
942226057Smarius			ipi_cpu(cpu, IPI_PREEMPT);
943171482Sjeff	}
944172409Sjeff	tdq_unlock_pair(high, low);
945176735Sjeff	return (moved);
946116069Sjeff}
947116069Sjeff
948171482Sjeff/*
949171482Sjeff * Move a thread from one thread queue to another.
950171482Sjeff */
951176735Sjeffstatic int
952171482Sjefftdq_move(struct tdq *from, struct tdq *to)
953116069Sjeff{
954171482Sjeff	struct td_sched *ts;
955171482Sjeff	struct thread *td;
956164936Sjulian	struct tdq *tdq;
957171482Sjeff	int cpu;
958116069Sjeff
959172409Sjeff	TDQ_LOCK_ASSERT(from, MA_OWNED);
960172409Sjeff	TDQ_LOCK_ASSERT(to, MA_OWNED);
961172409Sjeff
962164936Sjulian	tdq = from;
963171482Sjeff	cpu = TDQ_ID(to);
964177435Sjeff	td = tdq_steal(tdq, cpu);
965177435Sjeff	if (td == NULL)
966176735Sjeff		return (0);
967301456Skib	ts = td_get_sched(td);
968171482Sjeff	/*
969171482Sjeff	 * Although the run queue is locked the thread may be blocked.  Lock
970172409Sjeff	 * it to clear this and acquire the run-queue lock.
971171482Sjeff	 */
972171482Sjeff	thread_lock(td);
973172409Sjeff	/* Drop recursive lock on from acquired via thread_lock(). */
974171482Sjeff	TDQ_UNLOCK(from);
975171482Sjeff	sched_rem(td);
976166108Sjeff	ts->ts_cpu = cpu;
977171482Sjeff	td->td_lock = TDQ_LOCKPTR(to);
978171482Sjeff	tdq_add(to, td, SRQ_YIELDING);
979176735Sjeff	return (1);
980116069Sjeff}
981110267Sjeff
982171482Sjeff/*
983171482Sjeff * This tdq has idled.  Try to steal a thread from another cpu and switch
984171482Sjeff * to it.
985171482Sjeff */
986123433Sjeffstatic int
987164936Sjuliantdq_idled(struct tdq *tdq)
988121790Sjeff{
989176735Sjeff	struct cpu_group *cg;
990164936Sjulian	struct tdq *steal;
991194779Sjeff	cpuset_t mask;
992176735Sjeff	int thresh;
993171482Sjeff	int cpu;
994123433Sjeff
995172484Sjeff	if (smp_started == 0 || steal_idle == 0)
996172484Sjeff		return (1);
997194779Sjeff	CPU_FILL(&mask);
998194779Sjeff	CPU_CLR(PCPU_GET(cpuid), &mask);
999176735Sjeff	/* We don't want to be preempted while we're iterating. */
1000171482Sjeff	spinlock_enter();
1001176735Sjeff	for (cg = tdq->tdq_cg; cg != NULL; ) {
1002191643Sjeff		if ((cg->cg_flags & CG_FLAG_THREAD) == 0)
1003176735Sjeff			thresh = steal_thresh;
1004176735Sjeff		else
1005176735Sjeff			thresh = 1;
1006176735Sjeff		cpu = sched_highest(cg, mask, thresh);
1007176735Sjeff		if (cpu == -1) {
1008176735Sjeff			cg = cg->cg_parent;
1009176735Sjeff			continue;
1010166108Sjeff		}
1011176735Sjeff		steal = TDQ_CPU(cpu);
1012194779Sjeff		CPU_CLR(cpu, &mask);
1013176735Sjeff		tdq_lock_pair(tdq, steal);
1014176735Sjeff		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
1015176735Sjeff			tdq_unlock_pair(tdq, steal);
1016176735Sjeff			continue;
1017171482Sjeff		}
1018176735Sjeff		/*
1019176735Sjeff		 * If a thread was added while interrupts were disabled don't
1020176735Sjeff		 * steal one here.  If we fail to acquire one due to affinity
1021176735Sjeff		 * restrictions loop again with this cpu removed from the
1022176735Sjeff		 * set.
1023176735Sjeff		 */
1024176735Sjeff		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
1025176735Sjeff			tdq_unlock_pair(tdq, steal);
1026176735Sjeff			continue;
1027176735Sjeff		}
1028176735Sjeff		spinlock_exit();
1029176735Sjeff		TDQ_UNLOCK(steal);
1030178272Sjeff		mi_switch(SW_VOL | SWT_IDLE, NULL);
1031176735Sjeff		thread_unlock(curthread);
1032176735Sjeff
1033176735Sjeff		return (0);
1034123433Sjeff	}
1035171482Sjeff	spinlock_exit();
1036123433Sjeff	return (1);
1037121790Sjeff}
1038121790Sjeff
1039171482Sjeff/*
1040171482Sjeff * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
1041171482Sjeff */
1042121790Sjeffstatic void
1043177435Sjefftdq_notify(struct tdq *tdq, struct thread *td)
1044121790Sjeff{
1045185047Sjhb	struct thread *ctd;
1046166247Sjeff	int pri;
1047166108Sjeff	int cpu;
1048121790Sjeff
1049177005Sjeff	if (tdq->tdq_ipipending)
1050177005Sjeff		return;
1051301456Skib	cpu = td_get_sched(td)->ts_cpu;
1052177435Sjeff	pri = td->td_priority;
1053185047Sjhb	ctd = pcpu_find(cpu)->pc_curthread;
1054185047Sjhb	if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
1055166137Sjeff		return;
1056271616Smav
1057271616Smav	/*
1058271713Smav	 * Make sure that our caller's earlier update to tdq_load is
1059271713Smav	 * globally visible before we read tdq_cpu_idle.  Idle thread
1060271616Smav	 * accesses both of them without locks, and the order is important.
1061271616Smav	 */
1062285353Skib	atomic_thread_fence_seq_cst();
1063271616Smav
1064185047Sjhb	if (TD_IS_IDLETHREAD(ctd)) {
1065178277Sjeff		/*
1066178471Sjeff		 * If the MD code has an idle wakeup routine try that before
1067178471Sjeff		 * falling back to IPI.
1068178471Sjeff		 */
1069212416Smav		if (!tdq->tdq_cpu_idle || cpu_idle_wakeup(cpu))
1070178471Sjeff			return;
1071178277Sjeff	}
1072177005Sjeff	tdq->tdq_ipipending = 1;
1073210939Sjhb	ipi_cpu(cpu, IPI_PREEMPT);
1074121790Sjeff}
1075121790Sjeff
1076171482Sjeff/*
1077171482Sjeff * Steals load from a timeshare queue.  Honors the rotating queue head
1078171482Sjeff * index.
1079171482Sjeff */
1080177435Sjeffstatic struct thread *
1081176735Sjeffrunq_steal_from(struct runq *rq, int cpu, u_char start)
1082171482Sjeff{
1083171482Sjeff	struct rqbits *rqb;
1084171482Sjeff	struct rqhead *rqh;
1085232207Smav	struct thread *td, *first;
1086171482Sjeff	int bit;
1087171482Sjeff	int i;
1088171482Sjeff
1089171482Sjeff	rqb = &rq->rq_status;
1090171482Sjeff	bit = start & (RQB_BPW -1);
1091232207Smav	first = NULL;
1092171482Sjeffagain:
1093171482Sjeff	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1094171482Sjeff		if (rqb->rqb_bits[i] == 0)
1095171482Sjeff			continue;
1096262917Sjeff		if (bit == 0)
1097262917Sjeff			bit = RQB_FFS(rqb->rqb_bits[i]);
1098262917Sjeff		for (; bit < RQB_BPW; bit++) {
1099262917Sjeff			if ((rqb->rqb_bits[i] & (1ul << bit)) == 0)
1100171482Sjeff				continue;
1101262917Sjeff			rqh = &rq->rq_queues[bit + (i << RQB_L2BPW)];
1102262917Sjeff			TAILQ_FOREACH(td, rqh, td_runq) {
1103262917Sjeff				if (first && THREAD_CAN_MIGRATE(td) &&
1104262917Sjeff				    THREAD_CAN_SCHED(td, cpu))
1105262917Sjeff					return (td);
1106262917Sjeff				first = td;
1107262917Sjeff			}
1108171482Sjeff		}
1109171482Sjeff	}
1110171482Sjeff	if (start != 0) {
1111171482Sjeff		start = 0;
1112171482Sjeff		goto again;
1113171482Sjeff	}
1114171482Sjeff
1115232207Smav	if (first && THREAD_CAN_MIGRATE(first) &&
1116232207Smav	    THREAD_CAN_SCHED(first, cpu))
1117232207Smav		return (first);
1118171482Sjeff	return (NULL);
1119171482Sjeff}
1120171482Sjeff
1121171482Sjeff/*
1122171482Sjeff * Steals load from a standard linear queue.
1123171482Sjeff */
1124177435Sjeffstatic struct thread *
1125176735Sjeffrunq_steal(struct runq *rq, int cpu)
1126121790Sjeff{
1127121790Sjeff	struct rqhead *rqh;
1128121790Sjeff	struct rqbits *rqb;
1129177435Sjeff	struct thread *td;
1130121790Sjeff	int word;
1131121790Sjeff	int bit;
1132121790Sjeff
1133121790Sjeff	rqb = &rq->rq_status;
1134121790Sjeff	for (word = 0; word < RQB_LEN; word++) {
1135121790Sjeff		if (rqb->rqb_bits[word] == 0)
1136121790Sjeff			continue;
1137121790Sjeff		for (bit = 0; bit < RQB_BPW; bit++) {
1138123231Speter			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
1139121790Sjeff				continue;
1140121790Sjeff			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
1141177435Sjeff			TAILQ_FOREACH(td, rqh, td_runq)
1142177435Sjeff				if (THREAD_CAN_MIGRATE(td) &&
1143177435Sjeff				    THREAD_CAN_SCHED(td, cpu))
1144177435Sjeff					return (td);
1145121790Sjeff		}
1146121790Sjeff	}
1147121790Sjeff	return (NULL);
1148121790Sjeff}
1149121790Sjeff
1150171482Sjeff/*
1151171482Sjeff * Attempt to steal a thread in priority order from a thread queue.
1152171482Sjeff */
1153177435Sjeffstatic struct thread *
1154176735Sjefftdq_steal(struct tdq *tdq, int cpu)
1155121790Sjeff{
1156177435Sjeff	struct thread *td;
1157121790Sjeff
1158171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1159177435Sjeff	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
1160177435Sjeff		return (td);
1161177435Sjeff	if ((td = runq_steal_from(&tdq->tdq_timeshare,
1162177435Sjeff	    cpu, tdq->tdq_ridx)) != NULL)
1163177435Sjeff		return (td);
1164176735Sjeff	return (runq_steal(&tdq->tdq_idle, cpu));
1165121790Sjeff}
1166123433Sjeff
1167171482Sjeff/*
1168171482Sjeff * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
1169172409Sjeff * current lock and returns with the assigned queue locked.
1170171482Sjeff */
1171171482Sjeffstatic inline struct tdq *
1172177435Sjeffsched_setcpu(struct thread *td, int cpu, int flags)
1173123433Sjeff{
1174177435Sjeff
1175171482Sjeff	struct tdq *tdq;
1176123433Sjeff
1177177435Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1178171482Sjeff	tdq = TDQ_CPU(cpu);
1179301456Skib	td_get_sched(td)->ts_cpu = cpu;
1180177435Sjeff	/*
1181177435Sjeff	 * If the lock matches just return the queue.
1182177435Sjeff	 */
1183171482Sjeff	if (td->td_lock == TDQ_LOCKPTR(tdq))
1184171482Sjeff		return (tdq);
1185171482Sjeff#ifdef notyet
1186123433Sjeff	/*
1187172293Sjeff	 * If the thread isn't running its lockptr is a
1188171482Sjeff	 * turnstile or a sleepqueue.  We can just lock_set without
1189171482Sjeff	 * blocking.
1190123685Sjeff	 */
1191171482Sjeff	if (TD_CAN_RUN(td)) {
1192171482Sjeff		TDQ_LOCK(tdq);
1193171482Sjeff		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1194171482Sjeff		return (tdq);
1195171482Sjeff	}
1196171482Sjeff#endif
1197166108Sjeff	/*
1198171482Sjeff	 * The hard case, migration, we need to block the thread first to
1199171482Sjeff	 * prevent order reversals with other cpus locks.
1200166108Sjeff	 */
1201202889Sattilio	spinlock_enter();
1202171482Sjeff	thread_lock_block(td);
1203171482Sjeff	TDQ_LOCK(tdq);
1204171713Sjeff	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1205202889Sattilio	spinlock_exit();
1206171482Sjeff	return (tdq);
1207166108Sjeff}
1208166108Sjeff
1209178272SjeffSCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
1210178272SjeffSCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
1211178272SjeffSCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
1212178272SjeffSCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
1213178272SjeffSCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
1214178272SjeffSCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
1215178272Sjeff
1216166108Sjeffstatic int
1217177435Sjeffsched_pickcpu(struct thread *td, int flags)
1218171482Sjeff{
1219232207Smav	struct cpu_group *cg, *ccg;
1220177435Sjeff	struct td_sched *ts;
1221171482Sjeff	struct tdq *tdq;
1222194779Sjeff	cpuset_t mask;
1223232207Smav	int cpu, pri, self;
1224166108Sjeff
1225176735Sjeff	self = PCPU_GET(cpuid);
1226301456Skib	ts = td_get_sched(td);
1227166108Sjeff	if (smp_started == 0)
1228166108Sjeff		return (self);
1229171506Sjeff	/*
1230171506Sjeff	 * Don't migrate a running thread from sched_switch().
1231171506Sjeff	 */
1232176735Sjeff	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1233176735Sjeff		return (ts->ts_cpu);
1234166108Sjeff	/*
1235176735Sjeff	 * Prefer to run interrupt threads on the processors that generate
1236176735Sjeff	 * the interrupt.
1237166108Sjeff	 */
1238232207Smav	pri = td->td_priority;
1239176735Sjeff	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1240178272Sjeff	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
1241178272Sjeff		SCHED_STAT_INC(pickcpu_intrbind);
1242176735Sjeff		ts->ts_cpu = self;
1243232207Smav		if (TDQ_CPU(self)->tdq_lowpri > pri) {
1244232207Smav			SCHED_STAT_INC(pickcpu_affinity);
1245232207Smav			return (ts->ts_cpu);
1246232207Smav		}
1247178272Sjeff	}
1248166108Sjeff	/*
1249176735Sjeff	 * If the thread can run on the last cpu and the affinity has not
1250176735Sjeff	 * expired or it is idle run it there.
1251166108Sjeff	 */
1252176735Sjeff	tdq = TDQ_CPU(ts->ts_cpu);
1253232207Smav	cg = tdq->tdq_cg;
1254232207Smav	if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
1255232207Smav	    tdq->tdq_lowpri >= PRI_MIN_IDLE &&
1256232207Smav	    SCHED_AFFINITY(ts, CG_SHARE_L2)) {
1257232207Smav		if (cg->cg_flags & CG_FLAG_THREAD) {
1258232207Smav			CPUSET_FOREACH(cpu, cg->cg_mask) {
1259232207Smav				if (TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE)
1260232207Smav					break;
1261232207Smav			}
1262232207Smav		} else
1263232207Smav			cpu = INT_MAX;
1264232207Smav		if (cpu > mp_maxid) {
1265178272Sjeff			SCHED_STAT_INC(pickcpu_idle_affinity);
1266176735Sjeff			return (ts->ts_cpu);
1267178272Sjeff		}
1268139334Sjeff	}
1269123433Sjeff	/*
1270232207Smav	 * Search for the last level cache CPU group in the tree.
1271232207Smav	 * Skip caches with expired affinity time and SMT groups.
1272232207Smav	 * Affinity to higher level caches will be handled less aggressively.
1273123433Sjeff	 */
1274232207Smav	for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
1275232207Smav		if (cg->cg_flags & CG_FLAG_THREAD)
1276232207Smav			continue;
1277232207Smav		if (!SCHED_AFFINITY(ts, cg->cg_level))
1278232207Smav			continue;
1279232207Smav		ccg = cg;
1280232207Smav	}
1281232207Smav	if (ccg != NULL)
1282232207Smav		cg = ccg;
1283176735Sjeff	cpu = -1;
1284232207Smav	/* Search the group for the less loaded idle CPU we can run now. */
1285194779Sjeff	mask = td->td_cpuset->cs_mask;
1286232207Smav	if (cg != NULL && cg != cpu_top &&
1287232207Smav	    CPU_CMP(&cg->cg_mask, &cpu_top->cg_mask) != 0)
1288232207Smav		cpu = sched_lowest(cg, mask, max(pri, PRI_MAX_TIMESHARE),
1289232207Smav		    INT_MAX, ts->ts_cpu);
1290232207Smav	/* Search globally for the less loaded CPU we can run now. */
1291176735Sjeff	if (cpu == -1)
1292232207Smav		cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu);
1293232207Smav	/* Search globally for the less loaded CPU. */
1294232207Smav	if (cpu == -1)
1295232207Smav		cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu);
1296232454Smav	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1297171506Sjeff	/*
1298176735Sjeff	 * Compare the lowest loaded cpu to current cpu.
1299171506Sjeff	 */
1300177005Sjeff	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
1301232207Smav	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE &&
1302232207Smav	    TDQ_CPU(self)->tdq_load <= TDQ_CPU(cpu)->tdq_load + 1) {
1303178272Sjeff		SCHED_STAT_INC(pickcpu_local);
1304177005Sjeff		cpu = self;
1305178272Sjeff	} else
1306178272Sjeff		SCHED_STAT_INC(pickcpu_lowest);
1307178272Sjeff	if (cpu != ts->ts_cpu)
1308178272Sjeff		SCHED_STAT_INC(pickcpu_migration);
1309171482Sjeff	return (cpu);
1310123433Sjeff}
1311176735Sjeff#endif
1312123433Sjeff
1313117326Sjeff/*
1314121790Sjeff * Pick the highest priority task we have and return it.
1315117326Sjeff */
1316177435Sjeffstatic struct thread *
1317164936Sjuliantdq_choose(struct tdq *tdq)
1318110267Sjeff{
1319177435Sjeff	struct thread *td;
1320110267Sjeff
1321171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1322177435Sjeff	td = runq_choose(&tdq->tdq_realtime);
1323177435Sjeff	if (td != NULL)
1324177435Sjeff		return (td);
1325177435Sjeff	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1326177435Sjeff	if (td != NULL) {
1327217351Sjhb		KASSERT(td->td_priority >= PRI_MIN_BATCH,
1328165762Sjeff		    ("tdq_choose: Invalid priority on timeshare queue %d",
1329177435Sjeff		    td->td_priority));
1330177435Sjeff		return (td);
1331165762Sjeff	}
1332177435Sjeff	td = runq_choose(&tdq->tdq_idle);
1333177435Sjeff	if (td != NULL) {
1334177435Sjeff		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1335165762Sjeff		    ("tdq_choose: Invalid priority on idle queue %d",
1336177435Sjeff		    td->td_priority));
1337177435Sjeff		return (td);
1338165762Sjeff	}
1339165762Sjeff
1340165762Sjeff	return (NULL);
1341110267Sjeff}
1342110267Sjeff
1343171482Sjeff/*
1344171482Sjeff * Initialize a thread queue.
1345171482Sjeff */
1346109864Sjeffstatic void
1347164936Sjuliantdq_setup(struct tdq *tdq)
1348110028Sjeff{
1349171482Sjeff
1350171713Sjeff	if (bootverbose)
1351171713Sjeff		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1352165762Sjeff	runq_init(&tdq->tdq_realtime);
1353165762Sjeff	runq_init(&tdq->tdq_timeshare);
1354165620Sjeff	runq_init(&tdq->tdq_idle);
1355176735Sjeff	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1356176735Sjeff	    "sched lock %d", (int)TDQ_ID(tdq));
1357176735Sjeff	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1358176735Sjeff	    MTX_SPIN | MTX_RECURSE);
1359187357Sjeff#ifdef KTR
1360187357Sjeff	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
1361187357Sjeff	    "CPU %d load", (int)TDQ_ID(tdq));
1362187357Sjeff#endif
1363110028Sjeff}
1364110028Sjeff
1365171713Sjeff#ifdef SMP
1366110028Sjeffstatic void
1367171713Sjeffsched_setup_smp(void)
1368171713Sjeff{
1369171713Sjeff	struct tdq *tdq;
1370171713Sjeff	int i;
1371171713Sjeff
1372176735Sjeff	cpu_top = smp_topo();
1373209059Sjhb	CPU_FOREACH(i) {
1374176735Sjeff		tdq = TDQ_CPU(i);
1375171713Sjeff		tdq_setup(tdq);
1376176735Sjeff		tdq->tdq_cg = smp_topo_find(cpu_top, i);
1377176735Sjeff		if (tdq->tdq_cg == NULL)
1378176735Sjeff			panic("Can't find cpu group for %d\n", i);
1379123433Sjeff	}
1380176735Sjeff	balance_tdq = TDQ_SELF();
1381176735Sjeff	sched_balance();
1382171713Sjeff}
1383171713Sjeff#endif
1384171713Sjeff
1385171713Sjeff/*
1386171713Sjeff * Setup the thread queues and initialize the topology based on MD
1387171713Sjeff * information.
1388171713Sjeff */
1389171713Sjeffstatic void
1390171713Sjeffsched_setup(void *dummy)
1391171713Sjeff{
1392171713Sjeff	struct tdq *tdq;
1393171713Sjeff
1394171713Sjeff	tdq = TDQ_SELF();
1395171713Sjeff#ifdef SMP
1396176734Sjeff	sched_setup_smp();
1397117237Sjeff#else
1398171713Sjeff	tdq_setup(tdq);
1399116069Sjeff#endif
1400171482Sjeff
1401171482Sjeff	/* Add thread0's load since it's running. */
1402171482Sjeff	TDQ_LOCK(tdq);
1403171713Sjeff	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1404177435Sjeff	tdq_load_add(tdq, &thread0);
1405176735Sjeff	tdq->tdq_lowpri = thread0.td_priority;
1406171482Sjeff	TDQ_UNLOCK(tdq);
1407109864Sjeff}
1408109864Sjeff
1409171482Sjeff/*
1410239185Smav * This routine determines time constants after stathz and hz are setup.
1411171482Sjeff */
1412153533Sdavidxu/* ARGSUSED */
1413153533Sdavidxustatic void
1414153533Sdavidxusched_initticks(void *dummy)
1415153533Sdavidxu{
1416171482Sjeff	int incr;
1417171482Sjeff
1418153533Sdavidxu	realstathz = stathz ? stathz : hz;
1419242736Sjeff	sched_slice = realstathz / SCHED_SLICE_DEFAULT_DIVISOR;
1420242736Sjeff	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
1421239196Smav	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
1422239196Smav	    realstathz);
1423153533Sdavidxu
1424153533Sdavidxu	/*
1425165762Sjeff	 * tickincr is shifted out by 10 to avoid rounding errors due to
1426165766Sjeff	 * hz not being evenly divisible by stathz on all platforms.
1427153533Sdavidxu	 */
1428171482Sjeff	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1429165762Sjeff	/*
1430165762Sjeff	 * This does not work for values of stathz that are more than
1431165762Sjeff	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1432165762Sjeff	 */
1433171482Sjeff	if (incr == 0)
1434171482Sjeff		incr = 1;
1435171482Sjeff	tickincr = incr;
1436166108Sjeff#ifdef SMP
1437171899Sjeff	/*
1438172409Sjeff	 * Set the default balance interval now that we know
1439172409Sjeff	 * what realstathz is.
1440172409Sjeff	 */
1441172409Sjeff	balance_interval = realstathz;
1442166108Sjeff	affinity = SCHED_AFFINITY_DEFAULT;
1443166108Sjeff#endif
1444232740Smav	if (sched_idlespinthresh < 0)
1445242852Smav		sched_idlespinthresh = 2 * max(10000, 6 * hz) / realstathz;
1446153533Sdavidxu}
1447153533Sdavidxu
1448153533Sdavidxu
1449109864Sjeff/*
1450171482Sjeff * This is the core of the interactivity algorithm.  Determines a score based
1451171482Sjeff * on past behavior.  It is the ratio of sleep time to run time scaled to
1452171482Sjeff * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1453171482Sjeff * differs from the cpu usage because it does not account for time spent
1454171482Sjeff * waiting on a run-queue.  Would be prettier if we had floating point.
1455287166Sgnn *
1456287166Sgnn * When a thread's sleep time is greater than its run time the
1457287166Sgnn * calculation is:
1458287166Sgnn *
1459287166Sgnn *                           scaling factor
1460287166Sgnn * interactivity score =  ---------------------
1461287166Sgnn *                        sleep time / run time
1462287166Sgnn *
1463287166Sgnn *
1464287166Sgnn * When a thread's run time is greater than its sleep time the
1465287166Sgnn * calculation is:
1466287166Sgnn *
1467287166Sgnn *                           scaling factor
1468287166Sgnn * interactivity score =  ---------------------    + scaling factor
1469287166Sgnn *                        run time / sleep time
1470171482Sjeff */
1471171482Sjeffstatic int
1472171482Sjeffsched_interact_score(struct thread *td)
1473171482Sjeff{
1474171482Sjeff	struct td_sched *ts;
1475171482Sjeff	int div;
1476171482Sjeff
1477301456Skib	ts = td_get_sched(td);
1478171482Sjeff	/*
1479171482Sjeff	 * The score is only needed if this is likely to be an interactive
1480171482Sjeff	 * task.  Don't go through the expense of computing it if there's
1481171482Sjeff	 * no chance.
1482171482Sjeff	 */
1483171482Sjeff	if (sched_interact <= SCHED_INTERACT_HALF &&
1484171482Sjeff		ts->ts_runtime >= ts->ts_slptime)
1485171482Sjeff			return (SCHED_INTERACT_HALF);
1486171482Sjeff
1487171482Sjeff	if (ts->ts_runtime > ts->ts_slptime) {
1488171482Sjeff		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1489171482Sjeff		return (SCHED_INTERACT_HALF +
1490171482Sjeff		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1491171482Sjeff	}
1492171482Sjeff	if (ts->ts_slptime > ts->ts_runtime) {
1493171482Sjeff		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1494171482Sjeff		return (ts->ts_runtime / div);
1495171482Sjeff	}
1496171482Sjeff	/* runtime == slptime */
1497171482Sjeff	if (ts->ts_runtime)
1498171482Sjeff		return (SCHED_INTERACT_HALF);
1499171482Sjeff
1500171482Sjeff	/*
1501171482Sjeff	 * This can happen if slptime and runtime are 0.
1502171482Sjeff	 */
1503171482Sjeff	return (0);
1504171482Sjeff
1505171482Sjeff}
1506171482Sjeff
1507171482Sjeff/*
1508109864Sjeff * Scale the scheduling priority according to the "interactivity" of this
1509109864Sjeff * process.
1510109864Sjeff */
1511113357Sjeffstatic void
1512163709Sjbsched_priority(struct thread *td)
1513109864Sjeff{
1514165762Sjeff	int score;
1515109864Sjeff	int pri;
1516109864Sjeff
1517217291Sjhb	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
1518113357Sjeff		return;
1519112966Sjeff	/*
1520165762Sjeff	 * If the score is interactive we place the thread in the realtime
1521165762Sjeff	 * queue with a priority that is less than kernel and interrupt
1522165762Sjeff	 * priorities.  These threads are not subject to nice restrictions.
1523112966Sjeff	 *
1524171482Sjeff	 * Scores greater than this are placed on the normal timeshare queue
1525165762Sjeff	 * where the priority is partially decided by the most recent cpu
1526165762Sjeff	 * utilization and the rest is decided by nice value.
1527172293Sjeff	 *
1528172293Sjeff	 * The nice value of the process has a linear effect on the calculated
1529172293Sjeff	 * score.  Negative nice values make it easier for a thread to be
1530172293Sjeff	 * considered interactive.
1531112966Sjeff	 */
1532198126Sjhb	score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1533165762Sjeff	if (score < sched_interact) {
1534217351Sjhb		pri = PRI_MIN_INTERACT;
1535217351Sjhb		pri += ((PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) /
1536217237Sjhb		    sched_interact) * score;
1537217351Sjhb		KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
1538166208Sjeff		    ("sched_priority: invalid interactive priority %d score %d",
1539166208Sjeff		    pri, score));
1540165762Sjeff	} else {
1541165762Sjeff		pri = SCHED_PRI_MIN;
1542301456Skib		if (td_get_sched(td)->ts_ticks)
1543301456Skib			pri += min(SCHED_PRI_TICKS(td_get_sched(td)),
1544258869Sjhb			    SCHED_PRI_RANGE - 1);
1545165762Sjeff		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1546217351Sjhb		KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
1547171482Sjeff		    ("sched_priority: invalid priority %d: nice %d, "
1548171482Sjeff		    "ticks %d ftick %d ltick %d tick pri %d",
1549301456Skib		    pri, td->td_proc->p_nice, td_get_sched(td)->ts_ticks,
1550301456Skib		    td_get_sched(td)->ts_ftick, td_get_sched(td)->ts_ltick,
1551301456Skib		    SCHED_PRI_TICKS(td_get_sched(td))));
1552165762Sjeff	}
1553165762Sjeff	sched_user_prio(td, pri);
1554112966Sjeff
1555112966Sjeff	return;
1556109864Sjeff}
1557109864Sjeff
1558121868Sjeff/*
1559121868Sjeff * This routine enforces a maximum limit on the amount of scheduling history
1560171482Sjeff * kept.  It is called after either the slptime or runtime is adjusted.  This
1561171482Sjeff * function is ugly due to integer math.
1562121868Sjeff */
1563116463Sjeffstatic void
1564163709Sjbsched_interact_update(struct thread *td)
1565116463Sjeff{
1566165819Sjeff	struct td_sched *ts;
1567166208Sjeff	u_int sum;
1568121605Sjeff
1569301456Skib	ts = td_get_sched(td);
1570171482Sjeff	sum = ts->ts_runtime + ts->ts_slptime;
1571121868Sjeff	if (sum < SCHED_SLP_RUN_MAX)
1572121868Sjeff		return;
1573121868Sjeff	/*
1574165819Sjeff	 * This only happens from two places:
1575165819Sjeff	 * 1) We have added an unusual amount of run time from fork_exit.
1576165819Sjeff	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1577165819Sjeff	 */
1578165819Sjeff	if (sum > SCHED_SLP_RUN_MAX * 2) {
1579171482Sjeff		if (ts->ts_runtime > ts->ts_slptime) {
1580171482Sjeff			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1581171482Sjeff			ts->ts_slptime = 1;
1582165819Sjeff		} else {
1583171482Sjeff			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1584171482Sjeff			ts->ts_runtime = 1;
1585165819Sjeff		}
1586165819Sjeff		return;
1587165819Sjeff	}
1588165819Sjeff	/*
1589121868Sjeff	 * If we have exceeded by more than 1/5th then the algorithm below
1590121868Sjeff	 * will not bring us back into range.  Dividing by two here forces
1591133427Sjeff	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1592121868Sjeff	 */
1593127850Sjeff	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1594171482Sjeff		ts->ts_runtime /= 2;
1595171482Sjeff		ts->ts_slptime /= 2;
1596121868Sjeff		return;
1597116463Sjeff	}
1598171482Sjeff	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1599171482Sjeff	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1600116463Sjeff}
1601116463Sjeff
1602171482Sjeff/*
1603171482Sjeff * Scale back the interactivity history when a child thread is created.  The
1604171482Sjeff * history is inherited from the parent but the thread may behave totally
1605171482Sjeff * differently.  For example, a shell spawning a compiler process.  We want
1606171482Sjeff * to learn that the compiler is behaving badly very quickly.
1607171482Sjeff */
1608121868Sjeffstatic void
1609163709Sjbsched_interact_fork(struct thread *td)
1610121868Sjeff{
1611301456Skib	struct td_sched *ts;
1612121868Sjeff	int ratio;
1613121868Sjeff	int sum;
1614121868Sjeff
1615301456Skib	ts = td_get_sched(td);
1616301456Skib	sum = ts->ts_runtime + ts->ts_slptime;
1617121868Sjeff	if (sum > SCHED_SLP_RUN_FORK) {
1618121868Sjeff		ratio = sum / SCHED_SLP_RUN_FORK;
1619301456Skib		ts->ts_runtime /= ratio;
1620301456Skib		ts->ts_slptime /= ratio;
1621121868Sjeff	}
1622121868Sjeff}
1623121868Sjeff
1624113357Sjeff/*
1625171482Sjeff * Called from proc0_init() to setup the scheduler fields.
1626134791Sjulian */
1627134791Sjulianvoid
1628134791Sjulianschedinit(void)
1629134791Sjulian{
1630301456Skib	struct td_sched *ts0;
1631165762Sjeff
1632134791Sjulian	/*
1633301456Skib	 * Set up the scheduler specific parts of thread0.
1634134791Sjulian	 */
1635301456Skib	ts0 = td_get_sched(&thread0);
1636301456Skib	ts0->ts_ltick = ticks;
1637301456Skib	ts0->ts_ftick = ticks;
1638301456Skib	ts0->ts_slice = 0;
1639134791Sjulian}
1640134791Sjulian
1641134791Sjulian/*
1642113357Sjeff * This is only somewhat accurate since given many processes of the same
1643113357Sjeff * priority they will switch when their slices run out, which will be
1644165762Sjeff * at most sched_slice stathz ticks.
1645113357Sjeff */
1646109864Sjeffint
1647109864Sjeffsched_rr_interval(void)
1648109864Sjeff{
1649165762Sjeff
1650239185Smav	/* Convert sched_slice from stathz to hz. */
1651239196Smav	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
1652109864Sjeff}
1653109864Sjeff
1654171482Sjeff/*
1655171482Sjeff * Update the percent cpu tracking information when it is requested or
1656171482Sjeff * the total history exceeds the maximum.  We keep a sliding history of
1657171482Sjeff * tick counts that slowly decays.  This is less precise than the 4BSD
1658171482Sjeff * mechanism since it happens with less regular and frequent events.
1659171482Sjeff */
1660121790Sjeffstatic void
1661232917Smavsched_pctcpu_update(struct td_sched *ts, int run)
1662109864Sjeff{
1663232917Smav	int t = ticks;
1664165762Sjeff
1665232917Smav	if (t - ts->ts_ltick >= SCHED_TICK_TARG) {
1666164936Sjulian		ts->ts_ticks = 0;
1667232917Smav		ts->ts_ftick = t - SCHED_TICK_TARG;
1668232917Smav	} else if (t - ts->ts_ftick >= SCHED_TICK_MAX) {
1669232917Smav		ts->ts_ticks = (ts->ts_ticks / (ts->ts_ltick - ts->ts_ftick)) *
1670232917Smav		    (ts->ts_ltick - (t - SCHED_TICK_TARG));
1671232917Smav		ts->ts_ftick = t - SCHED_TICK_TARG;
1672232917Smav	}
1673232917Smav	if (run)
1674232917Smav		ts->ts_ticks += (t - ts->ts_ltick) << SCHED_TICK_SHIFT;
1675232917Smav	ts->ts_ltick = t;
1676109864Sjeff}
1677109864Sjeff
1678171482Sjeff/*
1679171482Sjeff * Adjust the priority of a thread.  Move it to the appropriate run-queue
1680171482Sjeff * if necessary.  This is the back-end for several priority related
1681171482Sjeff * functions.
1682171482Sjeff */
1683165762Sjeffstatic void
1684139453Sjhbsched_thread_priority(struct thread *td, u_char prio)
1685109864Sjeff{
1686164936Sjulian	struct td_sched *ts;
1687177009Sjeff	struct tdq *tdq;
1688177009Sjeff	int oldpri;
1689109864Sjeff
1690187357Sjeff	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
1691187357Sjeff	    "prio:%d", td->td_priority, "new prio:%d", prio,
1692187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(curthread));
1693258622Savg	SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
1694240513Savg	if (td != curthread && prio < td->td_priority) {
1695187357Sjeff		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
1696187357Sjeff		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
1697187357Sjeff		    prio, KTR_ATTR_LINKED, sched_tdname(td));
1698258622Savg		SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
1699235459Srstone		    curthread);
1700187357Sjeff	}
1701301456Skib	ts = td_get_sched(td);
1702170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1703139453Sjhb	if (td->td_priority == prio)
1704139453Sjhb		return;
1705177376Sjeff	/*
1706177376Sjeff	 * If the priority has been elevated due to priority
1707177376Sjeff	 * propagation, we may have to move ourselves to a new
1708177376Sjeff	 * queue.  This could be optimized to not re-add in some
1709177376Sjeff	 * cases.
1710177376Sjeff	 */
1711165766Sjeff	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1712165762Sjeff		sched_rem(td);
1713165762Sjeff		td->td_priority = prio;
1714171482Sjeff		sched_add(td, SRQ_BORROWING);
1715177009Sjeff		return;
1716177009Sjeff	}
1717177376Sjeff	/*
1718177376Sjeff	 * If the thread is currently running we may have to adjust the lowpri
1719177376Sjeff	 * information so other cpus are aware of our current priority.
1720177376Sjeff	 */
1721177009Sjeff	if (TD_IS_RUNNING(td)) {
1722177376Sjeff		tdq = TDQ_CPU(ts->ts_cpu);
1723177376Sjeff		oldpri = td->td_priority;
1724177376Sjeff		td->td_priority = prio;
1725176735Sjeff		if (prio < tdq->tdq_lowpri)
1726171482Sjeff			tdq->tdq_lowpri = prio;
1727176735Sjeff		else if (tdq->tdq_lowpri == oldpri)
1728176735Sjeff			tdq_setlowpri(tdq, td);
1729177376Sjeff		return;
1730177009Sjeff	}
1731177376Sjeff	td->td_priority = prio;
1732109864Sjeff}
1733109864Sjeff
1734139453Sjhb/*
1735139453Sjhb * Update a thread's priority when it is lent another thread's
1736139453Sjhb * priority.
1737139453Sjhb */
1738109864Sjeffvoid
1739139453Sjhbsched_lend_prio(struct thread *td, u_char prio)
1740139453Sjhb{
1741139453Sjhb
1742139453Sjhb	td->td_flags |= TDF_BORROWING;
1743139453Sjhb	sched_thread_priority(td, prio);
1744139453Sjhb}
1745139453Sjhb
1746139453Sjhb/*
1747139453Sjhb * Restore a thread's priority when priority propagation is
1748139453Sjhb * over.  The prio argument is the minimum priority the thread
1749139453Sjhb * needs to have to satisfy other possible priority lending
1750139453Sjhb * requests.  If the thread's regular priority is less
1751139453Sjhb * important than prio, the thread will keep a priority boost
1752139453Sjhb * of prio.
1753139453Sjhb */
1754139453Sjhbvoid
1755139453Sjhbsched_unlend_prio(struct thread *td, u_char prio)
1756139453Sjhb{
1757139453Sjhb	u_char base_pri;
1758139453Sjhb
1759139453Sjhb	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1760139453Sjhb	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1761163709Sjb		base_pri = td->td_user_pri;
1762139453Sjhb	else
1763139453Sjhb		base_pri = td->td_base_pri;
1764139453Sjhb	if (prio >= base_pri) {
1765139455Sjhb		td->td_flags &= ~TDF_BORROWING;
1766139453Sjhb		sched_thread_priority(td, base_pri);
1767139453Sjhb	} else
1768139453Sjhb		sched_lend_prio(td, prio);
1769139453Sjhb}
1770139453Sjhb
1771171482Sjeff/*
1772171482Sjeff * Standard entry for setting the priority to an absolute value.
1773171482Sjeff */
1774139453Sjhbvoid
1775139453Sjhbsched_prio(struct thread *td, u_char prio)
1776139453Sjhb{
1777139453Sjhb	u_char oldprio;
1778139453Sjhb
1779139453Sjhb	/* First, update the base priority. */
1780139453Sjhb	td->td_base_pri = prio;
1781139453Sjhb
1782139453Sjhb	/*
1783139455Sjhb	 * If the thread is borrowing another thread's priority, don't
1784139453Sjhb	 * ever lower the priority.
1785139453Sjhb	 */
1786139453Sjhb	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1787139453Sjhb		return;
1788139453Sjhb
1789139453Sjhb	/* Change the real priority. */
1790139453Sjhb	oldprio = td->td_priority;
1791139453Sjhb	sched_thread_priority(td, prio);
1792139453Sjhb
1793139453Sjhb	/*
1794139453Sjhb	 * If the thread is on a turnstile, then let the turnstile update
1795139453Sjhb	 * its state.
1796139453Sjhb	 */
1797139453Sjhb	if (TD_ON_LOCK(td) && oldprio != prio)
1798139453Sjhb		turnstile_adjust(td, oldprio);
1799139453Sjhb}
1800139455Sjhb
1801171482Sjeff/*
1802171482Sjeff * Set the base user priority, does not effect current running priority.
1803171482Sjeff */
1804139453Sjhbvoid
1805163709Sjbsched_user_prio(struct thread *td, u_char prio)
1806161599Sdavidxu{
1807161599Sdavidxu
1808163709Sjb	td->td_base_user_pri = prio;
1809216313Sdavidxu	if (td->td_lend_user_pri <= prio)
1810216313Sdavidxu		return;
1811163709Sjb	td->td_user_pri = prio;
1812161599Sdavidxu}
1813161599Sdavidxu
1814161599Sdavidxuvoid
1815161599Sdavidxusched_lend_user_prio(struct thread *td, u_char prio)
1816161599Sdavidxu{
1817161599Sdavidxu
1818174536Sdavidxu	THREAD_LOCK_ASSERT(td, MA_OWNED);
1819216313Sdavidxu	td->td_lend_user_pri = prio;
1820216791Sdavidxu	td->td_user_pri = min(prio, td->td_base_user_pri);
1821216791Sdavidxu	if (td->td_priority > td->td_user_pri)
1822216791Sdavidxu		sched_prio(td, td->td_user_pri);
1823216791Sdavidxu	else if (td->td_priority != td->td_user_pri)
1824216791Sdavidxu		td->td_flags |= TDF_NEEDRESCHED;
1825161599Sdavidxu}
1826161599Sdavidxu
1827171482Sjeff/*
1828171713Sjeff * Handle migration from sched_switch().  This happens only for
1829171713Sjeff * cpu binding.
1830171713Sjeff */
1831171713Sjeffstatic struct mtx *
1832171713Sjeffsched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1833171713Sjeff{
1834171713Sjeff	struct tdq *tdn;
1835171713Sjeff
1836301456Skib	tdn = TDQ_CPU(td_get_sched(td)->ts_cpu);
1837171713Sjeff#ifdef SMP
1838177435Sjeff	tdq_load_rem(tdq, td);
1839171713Sjeff	/*
1840171713Sjeff	 * Do the lock dance required to avoid LOR.  We grab an extra
1841171713Sjeff	 * spinlock nesting to prevent preemption while we're
1842171713Sjeff	 * not holding either run-queue lock.
1843171713Sjeff	 */
1844171713Sjeff	spinlock_enter();
1845202889Sattilio	thread_lock_block(td);	/* This releases the lock on tdq. */
1846197223Sattilio
1847197223Sattilio	/*
1848197223Sattilio	 * Acquire both run-queue locks before placing the thread on the new
1849197223Sattilio	 * run-queue to avoid deadlocks created by placing a thread with a
1850197223Sattilio	 * blocked lock on the run-queue of a remote processor.  The deadlock
1851197223Sattilio	 * occurs when a third processor attempts to lock the two queues in
1852197223Sattilio	 * question while the target processor is spinning with its own
1853197223Sattilio	 * run-queue lock held while waiting for the blocked lock to clear.
1854197223Sattilio	 */
1855197223Sattilio	tdq_lock_pair(tdn, tdq);
1856171713Sjeff	tdq_add(tdn, td, flags);
1857177435Sjeff	tdq_notify(tdn, td);
1858197223Sattilio	TDQ_UNLOCK(tdn);
1859171713Sjeff	spinlock_exit();
1860171713Sjeff#endif
1861171713Sjeff	return (TDQ_LOCKPTR(tdn));
1862171713Sjeff}
1863171713Sjeff
1864171713Sjeff/*
1865202889Sattilio * Variadic version of thread_lock_unblock() that does not assume td_lock
1866202889Sattilio * is blocked.
1867171482Sjeff */
1868171482Sjeffstatic inline void
1869171482Sjeffthread_unblock_switch(struct thread *td, struct mtx *mtx)
1870171482Sjeff{
1871171482Sjeff	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1872171482Sjeff	    (uintptr_t)mtx);
1873171482Sjeff}
1874171482Sjeff
1875171482Sjeff/*
1876171482Sjeff * Switch threads.  This function has to handle threads coming in while
1877171482Sjeff * blocked for some reason, running, or idle.  It also must deal with
1878171482Sjeff * migrating a thread from one queue to another as running threads may
1879171482Sjeff * be assigned elsewhere via binding.
1880171482Sjeff */
1881161599Sdavidxuvoid
1882135051Sjuliansched_switch(struct thread *td, struct thread *newtd, int flags)
1883109864Sjeff{
1884165627Sjeff	struct tdq *tdq;
1885164936Sjulian	struct td_sched *ts;
1886171482Sjeff	struct mtx *mtx;
1887171713Sjeff	int srqflag;
1888239157Smav	int cpuid, preempted;
1889109864Sjeff
1890170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1891177376Sjeff	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
1892109864Sjeff
1893171482Sjeff	cpuid = PCPU_GET(cpuid);
1894171482Sjeff	tdq = TDQ_CPU(cpuid);
1895301456Skib	ts = td_get_sched(td);
1896171713Sjeff	mtx = td->td_lock;
1897232917Smav	sched_pctcpu_update(ts, 1);
1898171482Sjeff	ts->ts_rltick = ticks;
1899133555Sjeff	td->td_lastcpu = td->td_oncpu;
1900113339Sjulian	td->td_oncpu = NOCPU;
1901270423Smav	preempted = !((td->td_flags & TDF_SLICEEND) ||
1902270423Smav	    (flags & SWT_RELINQUISH));
1903239157Smav	td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
1904144777Sups	td->td_owepreempt = 0;
1905242852Smav	if (!TD_IS_IDLETHREAD(td))
1906242852Smav		tdq->tdq_switchcnt++;
1907123434Sjeff	/*
1908171482Sjeff	 * The lock pointer in an idle thread should never change.  Reset it
1909171482Sjeff	 * to CAN_RUN as well.
1910123434Sjeff	 */
1911167327Sjulian	if (TD_IS_IDLETHREAD(td)) {
1912171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1913139334Sjeff		TD_SET_CAN_RUN(td);
1914170293Sjeff	} else if (TD_IS_RUNNING(td)) {
1915171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1916239157Smav		srqflag = preempted ?
1917170293Sjeff		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1918171713Sjeff		    SRQ_OURSELF|SRQ_YIELDING;
1919212153Smdf#ifdef SMP
1920212115Smdf		if (THREAD_CAN_MIGRATE(td) && !THREAD_CAN_SCHED(td, ts->ts_cpu))
1921212115Smdf			ts->ts_cpu = sched_pickcpu(td, 0);
1922212153Smdf#endif
1923171713Sjeff		if (ts->ts_cpu == cpuid)
1924177435Sjeff			tdq_runq_add(tdq, td, srqflag);
1925212115Smdf		else {
1926212115Smdf			KASSERT(THREAD_CAN_MIGRATE(td) ||
1927212115Smdf			    (ts->ts_flags & TSF_BOUND) != 0,
1928212115Smdf			    ("Thread %p shouldn't migrate", td));
1929171713Sjeff			mtx = sched_switch_migrate(tdq, td, srqflag);
1930212115Smdf		}
1931171482Sjeff	} else {
1932171482Sjeff		/* This thread must be going to sleep. */
1933171482Sjeff		TDQ_LOCK(tdq);
1934202889Sattilio		mtx = thread_lock_block(td);
1935177435Sjeff		tdq_load_rem(tdq, td);
1936171482Sjeff	}
1937171482Sjeff	/*
1938171482Sjeff	 * We enter here with the thread blocked and assigned to the
1939171482Sjeff	 * appropriate cpu run-queue or sleep-queue and with the current
1940171482Sjeff	 * thread-queue locked.
1941171482Sjeff	 */
1942171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1943171482Sjeff	newtd = choosethread();
1944171482Sjeff	/*
1945171482Sjeff	 * Call the MD code to switch contexts if necessary.
1946171482Sjeff	 */
1947145256Sjkoshy	if (td != newtd) {
1948145256Sjkoshy#ifdef	HWPMC_HOOKS
1949145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1950145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1951145256Sjkoshy#endif
1952258622Savg		SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
1953174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1954172411Sjeff		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1955301456Skib		sched_pctcpu_update(td_get_sched(newtd), 0);
1956179297Sjb
1957179297Sjb#ifdef KDTRACE_HOOKS
1958179297Sjb		/*
1959179297Sjb		 * If DTrace has set the active vtime enum to anything
1960179297Sjb		 * other than INACTIVE (0), then it should have set the
1961179297Sjb		 * function to call.
1962179297Sjb		 */
1963179297Sjb		if (dtrace_vtime_active)
1964179297Sjb			(*dtrace_vtime_switch_func)(newtd);
1965179297Sjb#endif
1966179297Sjb
1967171482Sjeff		cpu_switch(td, newtd, mtx);
1968171482Sjeff		/*
1969171482Sjeff		 * We may return from cpu_switch on a different cpu.  However,
1970171482Sjeff		 * we always return with td_lock pointing to the current cpu's
1971171482Sjeff		 * run queue lock.
1972171482Sjeff		 */
1973171482Sjeff		cpuid = PCPU_GET(cpuid);
1974171482Sjeff		tdq = TDQ_CPU(cpuid);
1975174629Sjeff		lock_profile_obtain_lock_success(
1976174629Sjeff		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1977235459Srstone
1978258622Savg		SDT_PROBE0(sched, , , on__cpu);
1979145256Sjkoshy#ifdef	HWPMC_HOOKS
1980145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1981145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1982145256Sjkoshy#endif
1983235459Srstone	} else {
1984171482Sjeff		thread_unblock_switch(td, mtx);
1985258622Savg		SDT_PROBE0(sched, , , remain__cpu);
1986235459Srstone	}
1987171482Sjeff	/*
1988171482Sjeff	 * Assert that all went well and return.
1989171482Sjeff	 */
1990171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1991171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1992171482Sjeff	td->td_oncpu = cpuid;
1993109864Sjeff}
1994109864Sjeff
1995171482Sjeff/*
1996171482Sjeff * Adjust thread priorities as a result of a nice request.
1997171482Sjeff */
1998109864Sjeffvoid
1999130551Sjuliansched_nice(struct proc *p, int nice)
2000109864Sjeff{
2001109864Sjeff	struct thread *td;
2002109864Sjeff
2003130551Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
2004165762Sjeff
2005130551Sjulian	p->p_nice = nice;
2006163709Sjb	FOREACH_THREAD_IN_PROC(p, td) {
2007170293Sjeff		thread_lock(td);
2008163709Sjb		sched_priority(td);
2009165762Sjeff		sched_prio(td, td->td_base_user_pri);
2010170293Sjeff		thread_unlock(td);
2011130551Sjulian	}
2012109864Sjeff}
2013109864Sjeff
2014171482Sjeff/*
2015171482Sjeff * Record the sleep time for the interactivity scorer.
2016171482Sjeff */
2017109864Sjeffvoid
2018177085Sjeffsched_sleep(struct thread *td, int prio)
2019109864Sjeff{
2020165762Sjeff
2021170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2022109864Sjeff
2023172264Sjeff	td->td_slptick = ticks;
2024201347Skib	if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
2025177085Sjeff		td->td_flags |= TDF_CANSWAP;
2026217410Sjhb	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
2027217410Sjhb		return;
2028177903Sjeff	if (static_boost == 1 && prio)
2029177085Sjeff		sched_prio(td, prio);
2030177903Sjeff	else if (static_boost && td->td_priority > static_boost)
2031177903Sjeff		sched_prio(td, static_boost);
2032109864Sjeff}
2033109864Sjeff
2034171482Sjeff/*
2035171482Sjeff * Schedule a thread to resume execution and record how long it voluntarily
2036171482Sjeff * slept.  We also update the pctcpu, interactivity, and priority.
2037171482Sjeff */
2038109864Sjeffvoid
2039109864Sjeffsched_wakeup(struct thread *td)
2040109864Sjeff{
2041166229Sjeff	struct td_sched *ts;
2042171482Sjeff	int slptick;
2043165762Sjeff
2044170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2045301456Skib	ts = td_get_sched(td);
2046177085Sjeff	td->td_flags &= ~TDF_CANSWAP;
2047109864Sjeff	/*
2048165762Sjeff	 * If we slept for more than a tick update our interactivity and
2049165762Sjeff	 * priority.
2050109864Sjeff	 */
2051172264Sjeff	slptick = td->td_slptick;
2052172264Sjeff	td->td_slptick = 0;
2053171482Sjeff	if (slptick && slptick != ticks) {
2054232917Smav		ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
2055165819Sjeff		sched_interact_update(td);
2056232917Smav		sched_pctcpu_update(ts, 0);
2057109864Sjeff	}
2058242736Sjeff	/*
2059242736Sjeff	 * Reset the slice value since we slept and advanced the round-robin.
2060242736Sjeff	 */
2061242736Sjeff	ts->ts_slice = 0;
2062166190Sjeff	sched_add(td, SRQ_BORING);
2063109864Sjeff}
2064109864Sjeff
2065109864Sjeff/*
2066109864Sjeff * Penalize the parent for creating a new child and initialize the child's
2067109864Sjeff * priority.
2068109864Sjeff */
2069109864Sjeffvoid
2070163709Sjbsched_fork(struct thread *td, struct thread *child)
2071109864Sjeff{
2072170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2073301456Skib	sched_pctcpu_update(td_get_sched(td), 1);
2074164936Sjulian	sched_fork_thread(td, child);
2075165762Sjeff	/*
2076165762Sjeff	 * Penalize the parent and child for forking.
2077165762Sjeff	 */
2078165762Sjeff	sched_interact_fork(child);
2079165762Sjeff	sched_priority(child);
2080301456Skib	td_get_sched(td)->ts_runtime += tickincr;
2081165762Sjeff	sched_interact_update(td);
2082165762Sjeff	sched_priority(td);
2083164936Sjulian}
2084109864Sjeff
2085171482Sjeff/*
2086171482Sjeff * Fork a new thread, may be within the same process.
2087171482Sjeff */
2088164936Sjulianvoid
2089164936Sjuliansched_fork_thread(struct thread *td, struct thread *child)
2090164936Sjulian{
2091164936Sjulian	struct td_sched *ts;
2092164936Sjulian	struct td_sched *ts2;
2093242736Sjeff	struct tdq *tdq;
2094164936Sjulian
2095242736Sjeff	tdq = TDQ_SELF();
2096177426Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2097165762Sjeff	/*
2098165762Sjeff	 * Initialize child.
2099165762Sjeff	 */
2100301456Skib	ts = td_get_sched(td);
2101301456Skib	ts2 = td_get_sched(child);
2102286256Sjhb	child->td_oncpu = NOCPU;
2103286256Sjhb	child->td_lastcpu = NOCPU;
2104242736Sjeff	child->td_lock = TDQ_LOCKPTR(tdq);
2105176735Sjeff	child->td_cpuset = cpuset_ref(td->td_cpuset);
2106164936Sjulian	ts2->ts_cpu = ts->ts_cpu;
2107177426Sjeff	ts2->ts_flags = 0;
2108165762Sjeff	/*
2109217078Sjhb	 * Grab our parents cpu estimation information.
2110165762Sjeff	 */
2111164936Sjulian	ts2->ts_ticks = ts->ts_ticks;
2112164936Sjulian	ts2->ts_ltick = ts->ts_ltick;
2113164936Sjulian	ts2->ts_ftick = ts->ts_ftick;
2114165762Sjeff	/*
2115217078Sjhb	 * Do not inherit any borrowed priority from the parent.
2116217078Sjhb	 */
2117217078Sjhb	child->td_priority = child->td_base_pri;
2118217078Sjhb	/*
2119165762Sjeff	 * And update interactivity score.
2120165762Sjeff	 */
2121171482Sjeff	ts2->ts_slptime = ts->ts_slptime;
2122171482Sjeff	ts2->ts_runtime = ts->ts_runtime;
2123242736Sjeff	/* Attempt to quickly learn interactivity. */
2124242736Sjeff	ts2->ts_slice = tdq_slice(tdq) - sched_slice_min;
2125187357Sjeff#ifdef KTR
2126187357Sjeff	bzero(ts2->ts_name, sizeof(ts2->ts_name));
2127187357Sjeff#endif
2128113357Sjeff}
2129113357Sjeff
2130171482Sjeff/*
2131171482Sjeff * Adjust the priority class of a thread.
2132171482Sjeff */
2133113357Sjeffvoid
2134163709Sjbsched_class(struct thread *td, int class)
2135113357Sjeff{
2136113357Sjeff
2137170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2138163709Sjb	if (td->td_pri_class == class)
2139113357Sjeff		return;
2140163709Sjb	td->td_pri_class = class;
2141109864Sjeff}
2142109864Sjeff
2143109864Sjeff/*
2144109864Sjeff * Return some of the child's priority and interactivity to the parent.
2145109864Sjeff */
2146109864Sjeffvoid
2147164939Sjuliansched_exit(struct proc *p, struct thread *child)
2148109864Sjeff{
2149165762Sjeff	struct thread *td;
2150113372Sjeff
2151187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2152225199Sdelphij	    "prio:%d", child->td_priority);
2153177368Sjeff	PROC_LOCK_ASSERT(p, MA_OWNED);
2154165762Sjeff	td = FIRST_THREAD_IN_PROC(p);
2155165762Sjeff	sched_exit_thread(td, child);
2156113372Sjeff}
2157113372Sjeff
2158171482Sjeff/*
2159171482Sjeff * Penalize another thread for the time spent on this one.  This helps to
2160171482Sjeff * worsen the priority and interactivity of processes which schedule batch
2161171482Sjeff * jobs such as make.  This has little effect on the make process itself but
2162171482Sjeff * causes new processes spawned by it to receive worse scores immediately.
2163171482Sjeff */
2164113372Sjeffvoid
2165164939Sjuliansched_exit_thread(struct thread *td, struct thread *child)
2166164936Sjulian{
2167165762Sjeff
2168187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2169225199Sdelphij	    "prio:%d", child->td_priority);
2170165762Sjeff	/*
2171165762Sjeff	 * Give the child's runtime to the parent without returning the
2172165762Sjeff	 * sleep time as a penalty to the parent.  This causes shells that
2173165762Sjeff	 * launch expensive things to mark their children as expensive.
2174165762Sjeff	 */
2175170293Sjeff	thread_lock(td);
2176301456Skib	td_get_sched(td)->ts_runtime += td_get_sched(child)->ts_runtime;
2177164939Sjulian	sched_interact_update(td);
2178165762Sjeff	sched_priority(td);
2179170293Sjeff	thread_unlock(td);
2180164936Sjulian}
2181164936Sjulian
2182177005Sjeffvoid
2183177005Sjeffsched_preempt(struct thread *td)
2184177005Sjeff{
2185177005Sjeff	struct tdq *tdq;
2186177005Sjeff
2187235459Srstone	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
2188235459Srstone
2189177005Sjeff	thread_lock(td);
2190177005Sjeff	tdq = TDQ_SELF();
2191177005Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2192177005Sjeff	tdq->tdq_ipipending = 0;
2193177005Sjeff	if (td->td_priority > tdq->tdq_lowpri) {
2194178272Sjeff		int flags;
2195178272Sjeff
2196178272Sjeff		flags = SW_INVOL | SW_PREEMPT;
2197177005Sjeff		if (td->td_critnest > 1)
2198177005Sjeff			td->td_owepreempt = 1;
2199178272Sjeff		else if (TD_IS_IDLETHREAD(td))
2200178272Sjeff			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2201177005Sjeff		else
2202178272Sjeff			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2203177005Sjeff	}
2204177005Sjeff	thread_unlock(td);
2205177005Sjeff}
2206177005Sjeff
2207171482Sjeff/*
2208171482Sjeff * Fix priorities on return to user-space.  Priorities may be elevated due
2209171482Sjeff * to static priorities in msleep() or similar.
2210171482Sjeff */
2211164936Sjulianvoid
2212164936Sjuliansched_userret(struct thread *td)
2213164936Sjulian{
2214164936Sjulian	/*
2215164936Sjulian	 * XXX we cheat slightly on the locking here to avoid locking in
2216164936Sjulian	 * the usual case.  Setting td_priority here is essentially an
2217164936Sjulian	 * incomplete workaround for not setting it properly elsewhere.
2218164936Sjulian	 * Now that some interrupt handlers are threads, not setting it
2219164936Sjulian	 * properly elsewhere can clobber it in the window between setting
2220164936Sjulian	 * it here and returning to user mode, so don't waste time setting
2221164936Sjulian	 * it perfectly here.
2222164936Sjulian	 */
2223164936Sjulian	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2224164936Sjulian	    ("thread with borrowed priority returning to userland"));
2225164936Sjulian	if (td->td_priority != td->td_user_pri) {
2226170293Sjeff		thread_lock(td);
2227164936Sjulian		td->td_priority = td->td_user_pri;
2228164936Sjulian		td->td_base_pri = td->td_user_pri;
2229177005Sjeff		tdq_setlowpri(TDQ_SELF(), td);
2230170293Sjeff		thread_unlock(td);
2231164936Sjulian        }
2232164936Sjulian}
2233164936Sjulian
2234171482Sjeff/*
2235171482Sjeff * Handle a stathz tick.  This is really only relevant for timeshare
2236171482Sjeff * threads.
2237171482Sjeff */
2238164936Sjulianvoid
2239121127Sjeffsched_clock(struct thread *td)
2240109864Sjeff{
2241164936Sjulian	struct tdq *tdq;
2242164936Sjulian	struct td_sched *ts;
2243109864Sjeff
2244171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2245164936Sjulian	tdq = TDQ_SELF();
2246172409Sjeff#ifdef SMP
2247133427Sjeff	/*
2248172409Sjeff	 * We run the long term load balancer infrequently on the first cpu.
2249172409Sjeff	 */
2250172409Sjeff	if (balance_tdq == tdq) {
2251172409Sjeff		if (balance_ticks && --balance_ticks == 0)
2252172409Sjeff			sched_balance();
2253172409Sjeff	}
2254172409Sjeff#endif
2255172409Sjeff	/*
2256178277Sjeff	 * Save the old switch count so we have a record of the last ticks
2257178277Sjeff	 * activity.   Initialize the new switch count based on our load.
2258178277Sjeff	 * If there is some activity seed it to reflect that.
2259178277Sjeff	 */
2260178277Sjeff	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
2261178471Sjeff	tdq->tdq_switchcnt = tdq->tdq_load;
2262178277Sjeff	/*
2263165766Sjeff	 * Advance the insert index once for each tick to ensure that all
2264165766Sjeff	 * threads get a chance to run.
2265133427Sjeff	 */
2266165766Sjeff	if (tdq->tdq_idx == tdq->tdq_ridx) {
2267165766Sjeff		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2268165766Sjeff		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2269165766Sjeff			tdq->tdq_ridx = tdq->tdq_idx;
2270165766Sjeff	}
2271301456Skib	ts = td_get_sched(td);
2272232917Smav	sched_pctcpu_update(ts, 1);
2273175104Sjeff	if (td->td_pri_class & PRI_FIFO_BIT)
2274113357Sjeff		return;
2275217291Sjhb	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2276175104Sjeff		/*
2277175104Sjeff		 * We used a tick; charge it to the thread so
2278175104Sjeff		 * that we can compute our interactivity.
2279175104Sjeff		 */
2280301456Skib		td_get_sched(td)->ts_runtime += tickincr;
2281175104Sjeff		sched_interact_update(td);
2282177009Sjeff		sched_priority(td);
2283175104Sjeff	}
2284239185Smav
2285113357Sjeff	/*
2286239185Smav	 * Force a context switch if the current thread has used up a full
2287239185Smav	 * time slice (default is 100ms).
2288109864Sjeff	 */
2289242736Sjeff	if (!TD_IS_IDLETHREAD(td) && ++ts->ts_slice >= tdq_slice(tdq)) {
2290242736Sjeff		ts->ts_slice = 0;
2291239185Smav		td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
2292239185Smav	}
2293109864Sjeff}
2294109864Sjeff
2295298145Skibu_int
2296298145Skibsched_estcpu(struct thread *td __unused)
2297171482Sjeff{
2298171482Sjeff
2299298145Skib	return (0);
2300171482Sjeff}
2301171482Sjeff
2302171482Sjeff/*
2303171482Sjeff * Return whether the current CPU has runnable tasks.  Used for in-kernel
2304171482Sjeff * cooperative idle threads.
2305171482Sjeff */
2306109864Sjeffint
2307109864Sjeffsched_runnable(void)
2308109864Sjeff{
2309164936Sjulian	struct tdq *tdq;
2310115998Sjeff	int load;
2311109864Sjeff
2312115998Sjeff	load = 1;
2313115998Sjeff
2314164936Sjulian	tdq = TDQ_SELF();
2315121605Sjeff	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2316165620Sjeff		if (tdq->tdq_load > 0)
2317121605Sjeff			goto out;
2318121605Sjeff	} else
2319165620Sjeff		if (tdq->tdq_load - 1 > 0)
2320121605Sjeff			goto out;
2321115998Sjeff	load = 0;
2322115998Sjeffout:
2323115998Sjeff	return (load);
2324109864Sjeff}
2325109864Sjeff
2326171482Sjeff/*
2327171482Sjeff * Choose the highest priority thread to run.  The thread is removed from
2328171482Sjeff * the run-queue while running however the load remains.  For SMP we set
2329171482Sjeff * the tdq in the global idle bitmask if it idles here.
2330171482Sjeff */
2331166190Sjeffstruct thread *
2332109970Sjeffsched_choose(void)
2333109970Sjeff{
2334177435Sjeff	struct thread *td;
2335164936Sjulian	struct tdq *tdq;
2336109970Sjeff
2337164936Sjulian	tdq = TDQ_SELF();
2338171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2339177435Sjeff	td = tdq_choose(tdq);
2340177435Sjeff	if (td) {
2341177435Sjeff		tdq_runq_rem(tdq, td);
2342177903Sjeff		tdq->tdq_lowpri = td->td_priority;
2343177435Sjeff		return (td);
2344109864Sjeff	}
2345177903Sjeff	tdq->tdq_lowpri = PRI_MAX_IDLE;
2346176735Sjeff	return (PCPU_GET(idlethread));
2347109864Sjeff}
2348109864Sjeff
2349171482Sjeff/*
2350171482Sjeff * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2351171482Sjeff * we always request it once we exit a critical section.
2352171482Sjeff */
2353171482Sjeffstatic inline void
2354171482Sjeffsched_setpreempt(struct thread *td)
2355166190Sjeff{
2356166190Sjeff	struct thread *ctd;
2357166190Sjeff	int cpri;
2358166190Sjeff	int pri;
2359166190Sjeff
2360177005Sjeff	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2361177005Sjeff
2362166190Sjeff	ctd = curthread;
2363166190Sjeff	pri = td->td_priority;
2364166190Sjeff	cpri = ctd->td_priority;
2365177005Sjeff	if (pri < cpri)
2366177005Sjeff		ctd->td_flags |= TDF_NEEDRESCHED;
2367166190Sjeff	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2368171482Sjeff		return;
2369177005Sjeff	if (!sched_shouldpreempt(pri, cpri, 0))
2370171482Sjeff		return;
2371171482Sjeff	ctd->td_owepreempt = 1;
2372166190Sjeff}
2373166190Sjeff
2374171482Sjeff/*
2375177009Sjeff * Add a thread to a thread queue.  Select the appropriate runq and add the
2376177009Sjeff * thread to it.  This is the internal function called when the tdq is
2377177009Sjeff * predetermined.
2378171482Sjeff */
2379109864Sjeffvoid
2380171482Sjefftdq_add(struct tdq *tdq, struct thread *td, int flags)
2381109864Sjeff{
2382109864Sjeff
2383171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2384166190Sjeff	KASSERT((td->td_inhibitors == 0),
2385166190Sjeff	    ("sched_add: trying to run inhibited thread"));
2386166190Sjeff	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2387166190Sjeff	    ("sched_add: bad thread state"));
2388172207Sjeff	KASSERT(td->td_flags & TDF_INMEM,
2389172207Sjeff	    ("sched_add: thread swapped out"));
2390171482Sjeff
2391171482Sjeff	if (td->td_priority < tdq->tdq_lowpri)
2392171482Sjeff		tdq->tdq_lowpri = td->td_priority;
2393177435Sjeff	tdq_runq_add(tdq, td, flags);
2394177435Sjeff	tdq_load_add(tdq, td);
2395171482Sjeff}
2396171482Sjeff
2397171482Sjeff/*
2398171482Sjeff * Select the target thread queue and add a thread to it.  Request
2399171482Sjeff * preemption or IPI a remote processor if required.
2400171482Sjeff */
2401171482Sjeffvoid
2402171482Sjeffsched_add(struct thread *td, int flags)
2403171482Sjeff{
2404171482Sjeff	struct tdq *tdq;
2405171482Sjeff#ifdef SMP
2406171482Sjeff	int cpu;
2407171482Sjeff#endif
2408187357Sjeff
2409187357Sjeff	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
2410187357Sjeff	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
2411187357Sjeff	    sched_tdname(curthread));
2412187357Sjeff	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
2413187357Sjeff	    KTR_ATTR_LINKED, sched_tdname(td));
2414235459Srstone	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
2415235459Srstone	    flags & SRQ_PREEMPTED);
2416171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2417166108Sjeff	/*
2418171482Sjeff	 * Recalculate the priority before we select the target cpu or
2419171482Sjeff	 * run-queue.
2420166108Sjeff	 */
2421171482Sjeff	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2422171482Sjeff		sched_priority(td);
2423171482Sjeff#ifdef SMP
2424171482Sjeff	/*
2425171482Sjeff	 * Pick the destination cpu and if it isn't ours transfer to the
2426171482Sjeff	 * target cpu.
2427171482Sjeff	 */
2428177435Sjeff	cpu = sched_pickcpu(td, flags);
2429177435Sjeff	tdq = sched_setcpu(td, cpu, flags);
2430171482Sjeff	tdq_add(tdq, td, flags);
2431177009Sjeff	if (cpu != PCPU_GET(cpuid)) {
2432177435Sjeff		tdq_notify(tdq, td);
2433166108Sjeff		return;
2434166108Sjeff	}
2435171482Sjeff#else
2436171482Sjeff	tdq = TDQ_SELF();
2437171482Sjeff	TDQ_LOCK(tdq);
2438171482Sjeff	/*
2439171482Sjeff	 * Now that the thread is moving to the run-queue, set the lock
2440171482Sjeff	 * to the scheduler's lock.
2441171482Sjeff	 */
2442171482Sjeff	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2443171482Sjeff	tdq_add(tdq, td, flags);
2444166108Sjeff#endif
2445171482Sjeff	if (!(flags & SRQ_YIELDING))
2446171482Sjeff		sched_setpreempt(td);
2447109864Sjeff}
2448109864Sjeff
2449171482Sjeff/*
2450171482Sjeff * Remove a thread from a run-queue without running it.  This is used
2451171482Sjeff * when we're stealing a thread from a remote queue.  Otherwise all threads
2452171482Sjeff * exit by calling sched_exit_thread() and sched_throw() themselves.
2453171482Sjeff */
2454109864Sjeffvoid
2455121127Sjeffsched_rem(struct thread *td)
2456109864Sjeff{
2457164936Sjulian	struct tdq *tdq;
2458113357Sjeff
2459187357Sjeff	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
2460187357Sjeff	    "prio:%d", td->td_priority);
2461235459Srstone	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
2462301456Skib	tdq = TDQ_CPU(td_get_sched(td)->ts_cpu);
2463171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2464171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2465166190Sjeff	KASSERT(TD_ON_RUNQ(td),
2466164936Sjulian	    ("sched_rem: thread not on run queue"));
2467177435Sjeff	tdq_runq_rem(tdq, td);
2468177435Sjeff	tdq_load_rem(tdq, td);
2469166190Sjeff	TD_SET_CAN_RUN(td);
2470176735Sjeff	if (td->td_priority == tdq->tdq_lowpri)
2471176735Sjeff		tdq_setlowpri(tdq, NULL);
2472109864Sjeff}
2473109864Sjeff
2474171482Sjeff/*
2475171482Sjeff * Fetch cpu utilization information.  Updates on demand.
2476171482Sjeff */
2477109864Sjefffixpt_t
2478121127Sjeffsched_pctcpu(struct thread *td)
2479109864Sjeff{
2480109864Sjeff	fixpt_t pctcpu;
2481164936Sjulian	struct td_sched *ts;
2482109864Sjeff
2483109864Sjeff	pctcpu = 0;
2484301456Skib	ts = td_get_sched(td);
2485109864Sjeff
2486208787Sjhb	THREAD_LOCK_ASSERT(td, MA_OWNED);
2487232917Smav	sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2488164936Sjulian	if (ts->ts_ticks) {
2489109864Sjeff		int rtick;
2490109864Sjeff
2491109864Sjeff		/* How many rtick per second ? */
2492165762Sjeff		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2493165762Sjeff		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2494109864Sjeff	}
2495109864Sjeff
2496109864Sjeff	return (pctcpu);
2497109864Sjeff}
2498109864Sjeff
2499176735Sjeff/*
2500176735Sjeff * Enforce affinity settings for a thread.  Called after adjustments to
2501176735Sjeff * cpumask.
2502176735Sjeff */
2503176729Sjeffvoid
2504176729Sjeffsched_affinity(struct thread *td)
2505176729Sjeff{
2506176735Sjeff#ifdef SMP
2507176735Sjeff	struct td_sched *ts;
2508176735Sjeff
2509176735Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2510301456Skib	ts = td_get_sched(td);
2511176735Sjeff	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2512176735Sjeff		return;
2513189787Sjeff	if (TD_ON_RUNQ(td)) {
2514189787Sjeff		sched_rem(td);
2515189787Sjeff		sched_add(td, SRQ_BORING);
2516189787Sjeff		return;
2517189787Sjeff	}
2518176735Sjeff	if (!TD_IS_RUNNING(td))
2519176735Sjeff		return;
2520176735Sjeff	/*
2521212115Smdf	 * Force a switch before returning to userspace.  If the
2522212115Smdf	 * target thread is not running locally send an ipi to force
2523212115Smdf	 * the issue.
2524176735Sjeff	 */
2525212974Sjhb	td->td_flags |= TDF_NEEDRESCHED;
2526212115Smdf	if (td != curthread)
2527212115Smdf		ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
2528176735Sjeff#endif
2529176729Sjeff}
2530176729Sjeff
2531171482Sjeff/*
2532171482Sjeff * Bind a thread to a target cpu.
2533171482Sjeff */
2534122038Sjeffvoid
2535122038Sjeffsched_bind(struct thread *td, int cpu)
2536122038Sjeff{
2537164936Sjulian	struct td_sched *ts;
2538122038Sjeff
2539171713Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2540208391Sjhb	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
2541301456Skib	ts = td_get_sched(td);
2542166137Sjeff	if (ts->ts_flags & TSF_BOUND)
2543166152Sjeff		sched_unbind(td);
2544212115Smdf	KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2545164936Sjulian	ts->ts_flags |= TSF_BOUND;
2546166137Sjeff	sched_pin();
2547123433Sjeff	if (PCPU_GET(cpuid) == cpu)
2548122038Sjeff		return;
2549166137Sjeff	ts->ts_cpu = cpu;
2550122038Sjeff	/* When we return from mi_switch we'll be on the correct cpu. */
2551131527Sphk	mi_switch(SW_VOL, NULL);
2552122038Sjeff}
2553122038Sjeff
2554171482Sjeff/*
2555171482Sjeff * Release a bound thread.
2556171482Sjeff */
2557122038Sjeffvoid
2558122038Sjeffsched_unbind(struct thread *td)
2559122038Sjeff{
2560165762Sjeff	struct td_sched *ts;
2561165762Sjeff
2562170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2563208391Sjhb	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
2564301456Skib	ts = td_get_sched(td);
2565166137Sjeff	if ((ts->ts_flags & TSF_BOUND) == 0)
2566166137Sjeff		return;
2567165762Sjeff	ts->ts_flags &= ~TSF_BOUND;
2568165762Sjeff	sched_unpin();
2569122038Sjeff}
2570122038Sjeff
2571109864Sjeffint
2572145256Sjkoshysched_is_bound(struct thread *td)
2573145256Sjkoshy{
2574170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2575301456Skib	return (td_get_sched(td)->ts_flags & TSF_BOUND);
2576145256Sjkoshy}
2577145256Sjkoshy
2578171482Sjeff/*
2579171482Sjeff * Basic yield call.
2580171482Sjeff */
2581159630Sdavidxuvoid
2582159630Sdavidxusched_relinquish(struct thread *td)
2583159630Sdavidxu{
2584170293Sjeff	thread_lock(td);
2585178272Sjeff	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
2586170293Sjeff	thread_unlock(td);
2587159630Sdavidxu}
2588159630Sdavidxu
2589171482Sjeff/*
2590171482Sjeff * Return the total system load.
2591171482Sjeff */
2592145256Sjkoshyint
2593125289Sjeffsched_load(void)
2594125289Sjeff{
2595125289Sjeff#ifdef SMP
2596125289Sjeff	int total;
2597125289Sjeff	int i;
2598125289Sjeff
2599125289Sjeff	total = 0;
2600209059Sjhb	CPU_FOREACH(i)
2601176735Sjeff		total += TDQ_CPU(i)->tdq_sysload;
2602125289Sjeff	return (total);
2603125289Sjeff#else
2604165620Sjeff	return (TDQ_SELF()->tdq_sysload);
2605125289Sjeff#endif
2606125289Sjeff}
2607125289Sjeff
2608125289Sjeffint
2609109864Sjeffsched_sizeof_proc(void)
2610109864Sjeff{
2611109864Sjeff	return (sizeof(struct proc));
2612109864Sjeff}
2613109864Sjeff
2614109864Sjeffint
2615109864Sjeffsched_sizeof_thread(void)
2616109864Sjeff{
2617109864Sjeff	return (sizeof(struct thread) + sizeof(struct td_sched));
2618109864Sjeff}
2619159570Sdavidxu
2620191676Sjeff#ifdef SMP
2621191676Sjeff#define	TDQ_IDLESPIN(tdq)						\
2622191676Sjeff    ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
2623191676Sjeff#else
2624191676Sjeff#define	TDQ_IDLESPIN(tdq)	1
2625191676Sjeff#endif
2626191676Sjeff
2627166190Sjeff/*
2628166190Sjeff * The actual idle process.
2629166190Sjeff */
2630166190Sjeffvoid
2631166190Sjeffsched_idletd(void *dummy)
2632166190Sjeff{
2633166190Sjeff	struct thread *td;
2634171482Sjeff	struct tdq *tdq;
2635242852Smav	int oldswitchcnt, switchcnt;
2636178277Sjeff	int i;
2637166190Sjeff
2638191643Sjeff	mtx_assert(&Giant, MA_NOTOWNED);
2639166190Sjeff	td = curthread;
2640171482Sjeff	tdq = TDQ_SELF();
2641239585Sjhb	THREAD_NO_SLEEPING();
2642242852Smav	oldswitchcnt = -1;
2643171482Sjeff	for (;;) {
2644242852Smav		if (tdq->tdq_load) {
2645242852Smav			thread_lock(td);
2646242852Smav			mi_switch(SW_VOL | SWT_IDLE, NULL);
2647242852Smav			thread_unlock(td);
2648242852Smav		}
2649242852Smav		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2650171482Sjeff#ifdef SMP
2651242852Smav		if (switchcnt != oldswitchcnt) {
2652242852Smav			oldswitchcnt = switchcnt;
2653242852Smav			if (tdq_idled(tdq) == 0)
2654242852Smav				continue;
2655242852Smav		}
2656243069Smav		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2657243069Smav#else
2658243069Smav		oldswitchcnt = switchcnt;
2659171482Sjeff#endif
2660178277Sjeff		/*
2661178277Sjeff		 * If we're switching very frequently, spin while checking
2662178277Sjeff		 * for load rather than entering a low power state that
2663191643Sjeff		 * may require an IPI.  However, don't do any busy
2664191643Sjeff		 * loops while on SMT machines as this simply steals
2665191643Sjeff		 * cycles from cores doing useful work.
2666178277Sjeff		 */
2667191676Sjeff		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
2668178277Sjeff			for (i = 0; i < sched_idlespins; i++) {
2669178277Sjeff				if (tdq->tdq_load)
2670178277Sjeff					break;
2671178277Sjeff				cpu_spinwait();
2672178277Sjeff			}
2673178277Sjeff		}
2674242852Smav
2675242852Smav		/* If there was context switch during spin, restart it. */
2676191643Sjeff		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2677242852Smav		if (tdq->tdq_load != 0 || switchcnt != oldswitchcnt)
2678242852Smav			continue;
2679242852Smav
2680242852Smav		/* Run main MD idle handler. */
2681242852Smav		tdq->tdq_cpu_idle = 1;
2682271616Smav		/*
2683271616Smav		 * Make sure that tdq_cpu_idle update is globally visible
2684271616Smav		 * before cpu_idle() read tdq_load.  The order is important
2685271616Smav		 * to avoid race with tdq_notify.
2686271616Smav		 */
2687285353Skib		atomic_thread_fence_seq_cst();
2688242852Smav		cpu_idle(switchcnt * 4 > sched_idlespinthresh);
2689242852Smav		tdq->tdq_cpu_idle = 0;
2690242852Smav
2691242852Smav		/*
2692242852Smav		 * Account thread-less hardware interrupts and
2693242852Smav		 * other wakeup reasons equal to context switches.
2694242852Smav		 */
2695242852Smav		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2696242852Smav		if (switchcnt != oldswitchcnt)
2697242852Smav			continue;
2698242852Smav		tdq->tdq_switchcnt++;
2699242852Smav		oldswitchcnt++;
2700171482Sjeff	}
2701166190Sjeff}
2702166190Sjeff
2703170293Sjeff/*
2704170293Sjeff * A CPU is entering for the first time or a thread is exiting.
2705170293Sjeff */
2706170293Sjeffvoid
2707170293Sjeffsched_throw(struct thread *td)
2708170293Sjeff{
2709172411Sjeff	struct thread *newtd;
2710171482Sjeff	struct tdq *tdq;
2711171482Sjeff
2712171482Sjeff	tdq = TDQ_SELF();
2713170293Sjeff	if (td == NULL) {
2714171482Sjeff		/* Correct spinlock nesting and acquire the correct lock. */
2715171482Sjeff		TDQ_LOCK(tdq);
2716170293Sjeff		spinlock_exit();
2717229429Sjhb		PCPU_SET(switchtime, cpu_ticks());
2718229429Sjhb		PCPU_SET(switchticks, ticks);
2719170293Sjeff	} else {
2720171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2721177435Sjeff		tdq_load_rem(tdq, td);
2722174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2723286256Sjhb		td->td_lastcpu = td->td_oncpu;
2724286256Sjhb		td->td_oncpu = NOCPU;
2725170293Sjeff	}
2726170293Sjeff	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2727172411Sjeff	newtd = choosethread();
2728172411Sjeff	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2729172411Sjeff	cpu_throw(td, newtd);		/* doesn't return */
2730170293Sjeff}
2731170293Sjeff
2732171482Sjeff/*
2733171482Sjeff * This is called from fork_exit().  Just acquire the correct locks and
2734171482Sjeff * let fork do the rest of the work.
2735171482Sjeff */
2736170293Sjeffvoid
2737170600Sjeffsched_fork_exit(struct thread *td)
2738170293Sjeff{
2739171482Sjeff	struct tdq *tdq;
2740171482Sjeff	int cpuid;
2741170293Sjeff
2742170293Sjeff	/*
2743170293Sjeff	 * Finish setting up thread glue so that it begins execution in a
2744171482Sjeff	 * non-nested critical section with the scheduler lock held.
2745170293Sjeff	 */
2746171482Sjeff	cpuid = PCPU_GET(cpuid);
2747171482Sjeff	tdq = TDQ_CPU(cpuid);
2748171482Sjeff	if (TD_IS_IDLETHREAD(td))
2749171482Sjeff		td->td_lock = TDQ_LOCKPTR(tdq);
2750171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2751171482Sjeff	td->td_oncpu = cpuid;
2752172411Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2753174629Sjeff	lock_profile_obtain_lock_success(
2754174629Sjeff	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2755170293Sjeff}
2756170293Sjeff
2757187357Sjeff/*
2758187357Sjeff * Create on first use to catch odd startup conditons.
2759187357Sjeff */
2760187357Sjeffchar *
2761187357Sjeffsched_tdname(struct thread *td)
2762187357Sjeff{
2763187357Sjeff#ifdef KTR
2764187357Sjeff	struct td_sched *ts;
2765187357Sjeff
2766301456Skib	ts = td_get_sched(td);
2767187357Sjeff	if (ts->ts_name[0] == '\0')
2768187357Sjeff		snprintf(ts->ts_name, sizeof(ts->ts_name),
2769187357Sjeff		    "%s tid %d", td->td_name, td->td_tid);
2770187357Sjeff	return (ts->ts_name);
2771187357Sjeff#else
2772187357Sjeff	return (td->td_name);
2773187357Sjeff#endif
2774187357Sjeff}
2775187357Sjeff
2776232700Sjhb#ifdef KTR
2777232700Sjhbvoid
2778232700Sjhbsched_clear_tdname(struct thread *td)
2779232700Sjhb{
2780232700Sjhb	struct td_sched *ts;
2781232700Sjhb
2782301456Skib	ts = td_get_sched(td);
2783232700Sjhb	ts->ts_name[0] = '\0';
2784232700Sjhb}
2785232700Sjhb#endif
2786232700Sjhb
2787184439Sivoras#ifdef SMP
2788184439Sivoras
2789184439Sivoras/*
2790184439Sivoras * Build the CPU topology dump string. Is recursively called to collect
2791184439Sivoras * the topology tree.
2792184439Sivoras */
2793184439Sivorasstatic int
2794184439Sivorassysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
2795184439Sivoras    int indent)
2796184439Sivoras{
2797222813Sattilio	char cpusetbuf[CPUSETBUFSIZ];
2798184439Sivoras	int i, first;
2799184439Sivoras
2800184439Sivoras	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
2801212821Savg	    "", 1 + indent / 2, cg->cg_level);
2802222813Sattilio	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
2803222813Sattilio	    cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
2804184439Sivoras	first = TRUE;
2805184439Sivoras	for (i = 0; i < MAXCPU; i++) {
2806222813Sattilio		if (CPU_ISSET(i, &cg->cg_mask)) {
2807184439Sivoras			if (!first)
2808184439Sivoras				sbuf_printf(sb, ", ");
2809184439Sivoras			else
2810184439Sivoras				first = FALSE;
2811184439Sivoras			sbuf_printf(sb, "%d", i);
2812184439Sivoras		}
2813184439Sivoras	}
2814184439Sivoras	sbuf_printf(sb, "</cpu>\n");
2815184439Sivoras
2816184439Sivoras	if (cg->cg_flags != 0) {
2817210117Sivoras		sbuf_printf(sb, "%*s <flags>", indent, "");
2818184439Sivoras		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
2819208982Sivoras			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
2820208983Sivoras		if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
2821208983Sivoras			sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
2822191643Sjeff		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
2823208983Sivoras			sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
2824210117Sivoras		sbuf_printf(sb, "</flags>\n");
2825184439Sivoras	}
2826184439Sivoras
2827184439Sivoras	if (cg->cg_children > 0) {
2828184439Sivoras		sbuf_printf(sb, "%*s <children>\n", indent, "");
2829184439Sivoras		for (i = 0; i < cg->cg_children; i++)
2830184439Sivoras			sysctl_kern_sched_topology_spec_internal(sb,
2831184439Sivoras			    &cg->cg_child[i], indent+2);
2832184439Sivoras		sbuf_printf(sb, "%*s </children>\n", indent, "");
2833184439Sivoras	}
2834184439Sivoras	sbuf_printf(sb, "%*s</group>\n", indent, "");
2835184439Sivoras	return (0);
2836184439Sivoras}
2837184439Sivoras
2838184439Sivoras/*
2839184439Sivoras * Sysctl handler for retrieving topology dump. It's a wrapper for
2840184439Sivoras * the recursive sysctl_kern_smp_topology_spec_internal().
2841184439Sivoras */
2842184439Sivorasstatic int
2843184439Sivorassysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
2844184439Sivoras{
2845184439Sivoras	struct sbuf *topo;
2846184439Sivoras	int err;
2847184439Sivoras
2848184439Sivoras	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
2849184439Sivoras
2850279999Sian	topo = sbuf_new_for_sysctl(NULL, NULL, 512, req);
2851184439Sivoras	if (topo == NULL)
2852184439Sivoras		return (ENOMEM);
2853184439Sivoras
2854184439Sivoras	sbuf_printf(topo, "<groups>\n");
2855184439Sivoras	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
2856184439Sivoras	sbuf_printf(topo, "</groups>\n");
2857184439Sivoras
2858184439Sivoras	if (err == 0) {
2859279999Sian		err = sbuf_finish(topo);
2860184439Sivoras	}
2861184439Sivoras	sbuf_delete(topo);
2862184439Sivoras	return (err);
2863184439Sivoras}
2864214510Sdavidxu
2865184439Sivoras#endif
2866184439Sivoras
2867239185Smavstatic int
2868239185Smavsysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
2869239185Smav{
2870239185Smav	int error, new_val, period;
2871239185Smav
2872239185Smav	period = 1000000 / realstathz;
2873239185Smav	new_val = period * sched_slice;
2874239185Smav	error = sysctl_handle_int(oidp, &new_val, 0, req);
2875239196Smav	if (error != 0 || req->newptr == NULL)
2876239185Smav		return (error);
2877239185Smav	if (new_val <= 0)
2878239185Smav		return (EINVAL);
2879239196Smav	sched_slice = imax(1, (new_val + period / 2) / period);
2880242736Sjeff	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
2881239196Smav	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
2882239196Smav	    realstathz);
2883239185Smav	return (0);
2884239185Smav}
2885239185Smav
2886177435SjeffSYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2887171482SjeffSYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2888165762Sjeff    "Scheduler name");
2889239185SmavSYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
2890239185Smav    NULL, 0, sysctl_kern_quantum, "I",
2891239196Smav    "Quantum for timeshare threads in microseconds");
2892171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2893239196Smav    "Quantum for timeshare threads in stathz ticks");
2894171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2895239196Smav    "Interactivity score threshold");
2896239196SmavSYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW,
2897239196Smav    &preempt_thresh, 0,
2898239196Smav    "Maximal (lowest) priority for preemption");
2899239196SmavSYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost, 0,
2900239196Smav    "Assign static kernel priorities to sleeping threads");
2901239196SmavSYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins, 0,
2902239196Smav    "Number of times idle thread will spin waiting for new work");
2903239196SmavSYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW,
2904239196Smav    &sched_idlespinthresh, 0,
2905239196Smav    "Threshold before we will permit idle thread spinning");
2906166108Sjeff#ifdef SMP
2907171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2908171482Sjeff    "Number of hz ticks to keep thread affinity for");
2909171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2910171482Sjeff    "Enables the long-term load balancer");
2911172409SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2912172409Sjeff    &balance_interval, 0,
2913239185Smav    "Average period in stathz ticks to run the long-term balancer");
2914171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2915171482Sjeff    "Attempts to steal work from other cores before idling");
2916171506SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2917239196Smav    "Minimum load on remote CPU before we'll steal");
2918184439SivorasSYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
2919239185Smav    CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
2920184439Sivoras    "XML dump of detected CPU topology");
2921166108Sjeff#endif
2922165762Sjeff
2923172264Sjeff/* ps compat.  All cpu percentages from ULE are weighted. */
2924172293Sjeffstatic int ccpu = 0;
2925165762SjeffSYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2926