xref: /freebsd/sys/kern/sched_ule.c (revision b3e9e682cf2d37fd8310fa054e56c959fe8b664e)
135e6168fSJeff Roberson /*-
2e7d50326SJeff Roberson  * Copyright (c) 2002-2007, Jeffrey Roberson <jeff@freebsd.org>
335e6168fSJeff Roberson  * All rights reserved.
435e6168fSJeff Roberson  *
535e6168fSJeff Roberson  * Redistribution and use in source and binary forms, with or without
635e6168fSJeff Roberson  * modification, are permitted provided that the following conditions
735e6168fSJeff Roberson  * are met:
835e6168fSJeff Roberson  * 1. Redistributions of source code must retain the above copyright
935e6168fSJeff Roberson  *    notice unmodified, this list of conditions, and the following
1035e6168fSJeff Roberson  *    disclaimer.
1135e6168fSJeff Roberson  * 2. Redistributions in binary form must reproduce the above copyright
1235e6168fSJeff Roberson  *    notice, this list of conditions and the following disclaimer in the
1335e6168fSJeff Roberson  *    documentation and/or other materials provided with the distribution.
1435e6168fSJeff Roberson  *
1535e6168fSJeff Roberson  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1635e6168fSJeff Roberson  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1735e6168fSJeff Roberson  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1835e6168fSJeff Roberson  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
1935e6168fSJeff Roberson  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
2035e6168fSJeff Roberson  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2135e6168fSJeff Roberson  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2235e6168fSJeff Roberson  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2335e6168fSJeff Roberson  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
2435e6168fSJeff Roberson  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2535e6168fSJeff Roberson  */
2635e6168fSJeff Roberson 
27ae7a6b38SJeff Roberson /*
28ae7a6b38SJeff Roberson  * This file implements the ULE scheduler.  ULE supports independent CPU
29ae7a6b38SJeff Roberson  * run queues and fine grain locking.  It has superior interactive
30ae7a6b38SJeff Roberson  * performance under load even on uni-processor systems.
31ae7a6b38SJeff Roberson  *
32ae7a6b38SJeff Roberson  * etymology:
33a5423ea3SJeff Roberson  *   ULE is the last three letters in schedule.  It owes its name to a
34ae7a6b38SJeff Roberson  * generic user created for a scheduling system by Paul Mikesell at
35ae7a6b38SJeff Roberson  * Isilon Systems and a general lack of creativity on the part of the author.
36ae7a6b38SJeff Roberson  */
37ae7a6b38SJeff Roberson 
38677b542eSDavid E. O'Brien #include <sys/cdefs.h>
39113dda8aSJeff Roberson __FBSDID("$FreeBSD$");
40677b542eSDavid E. O'Brien 
414da0d332SPeter Wemm #include "opt_hwpmc_hooks.h"
426f5f25e5SJohn Birrell #include "opt_kdtrace.h"
434da0d332SPeter Wemm #include "opt_sched.h"
449923b511SScott Long 
4535e6168fSJeff Roberson #include <sys/param.h>
4635e6168fSJeff Roberson #include <sys/systm.h>
472c3490b1SMarcel Moolenaar #include <sys/kdb.h>
4835e6168fSJeff Roberson #include <sys/kernel.h>
4935e6168fSJeff Roberson #include <sys/ktr.h>
5035e6168fSJeff Roberson #include <sys/lock.h>
5135e6168fSJeff Roberson #include <sys/mutex.h>
5235e6168fSJeff Roberson #include <sys/proc.h>
53245f3abfSJeff Roberson #include <sys/resource.h>
549bacd788SJeff Roberson #include <sys/resourcevar.h>
5535e6168fSJeff Roberson #include <sys/sched.h>
56*b3e9e682SRyan Stone #include <sys/sdt.h>
5735e6168fSJeff Roberson #include <sys/smp.h>
5835e6168fSJeff Roberson #include <sys/sx.h>
5935e6168fSJeff Roberson #include <sys/sysctl.h>
6035e6168fSJeff Roberson #include <sys/sysproto.h>
61f5c157d9SJohn Baldwin #include <sys/turnstile.h>
623db720fdSDavid Xu #include <sys/umtx.h>
6335e6168fSJeff Roberson #include <sys/vmmeter.h>
6462fa74d9SJeff Roberson #include <sys/cpuset.h>
6507095abfSIvan Voras #include <sys/sbuf.h>
6635e6168fSJeff Roberson 
67ebccf1e3SJoseph Koshy #ifdef HWPMC_HOOKS
68ebccf1e3SJoseph Koshy #include <sys/pmckern.h>
69ebccf1e3SJoseph Koshy #endif
70ebccf1e3SJoseph Koshy 
716f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
726f5f25e5SJohn Birrell #include <sys/dtrace_bsd.h>
736f5f25e5SJohn Birrell int				dtrace_vtime_active;
746f5f25e5SJohn Birrell dtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
756f5f25e5SJohn Birrell #endif
766f5f25e5SJohn Birrell 
7735e6168fSJeff Roberson #include <machine/cpu.h>
7822bf7d9aSJeff Roberson #include <machine/smp.h>
7935e6168fSJeff Roberson 
80880bf8b9SMarius Strobl #if defined(__powerpc__) && defined(E500)
8102e2d6b4SJeff Roberson #error "This architecture is not currently compatible with ULE"
827a5e5e2aSJeff Roberson #endif
837a5e5e2aSJeff Roberson 
84ae7a6b38SJeff Roberson #define	KTR_ULE	0
8514618990SJeff Roberson 
860d2cf837SJeff Roberson #define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
870d2cf837SJeff Roberson #define	TDQ_NAME_LEN	(sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
886338c579SAttilio Rao #define	TDQ_LOADNAME_LEN	(sizeof("CPU ") + sizeof(__XSTRING(MAXCPU)) - 1 + sizeof(" load"))
898f51ad55SJeff Roberson 
906b2f763fSJeff Roberson /*
91ae7a6b38SJeff Roberson  * Thread scheduler specific section.  All fields are protected
92ae7a6b38SJeff Roberson  * by the thread lock.
93ed062c8dSJulian Elischer  */
94ad1e7d28SJulian Elischer struct td_sched {
95ae7a6b38SJeff Roberson 	struct runq	*ts_runq;	/* Run-queue we're queued on. */
96ae7a6b38SJeff Roberson 	short		ts_flags;	/* TSF_* flags. */
97ad1e7d28SJulian Elischer 	u_char		ts_cpu;		/* CPU that we have affinity for. */
9873daf66fSJeff Roberson 	int		ts_rltick;	/* Real last tick, for affinity. */
99ae7a6b38SJeff Roberson 	int		ts_slice;	/* Ticks of slice remaining. */
100ae7a6b38SJeff Roberson 	u_int		ts_slptime;	/* Number of ticks we vol. slept */
101ae7a6b38SJeff Roberson 	u_int		ts_runtime;	/* Number of ticks we were running */
102ad1e7d28SJulian Elischer 	int		ts_ltick;	/* Last tick that we were running on */
103ad1e7d28SJulian Elischer 	int		ts_ftick;	/* First tick that we were running on */
104ad1e7d28SJulian Elischer 	int		ts_ticks;	/* Tick count */
1058f51ad55SJeff Roberson #ifdef KTR
1068f51ad55SJeff Roberson 	char		ts_name[TS_NAME_LEN];
1078f51ad55SJeff Roberson #endif
108ed062c8dSJulian Elischer };
109ad1e7d28SJulian Elischer /* flags kept in ts_flags */
1107b8bfa0dSJeff Roberson #define	TSF_BOUND	0x0001		/* Thread can not migrate. */
1117b8bfa0dSJeff Roberson #define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
11235e6168fSJeff Roberson 
113ad1e7d28SJulian Elischer static struct td_sched td_sched0;
11435e6168fSJeff Roberson 
11562fa74d9SJeff Roberson #define	THREAD_CAN_MIGRATE(td)	((td)->td_pinned == 0)
11662fa74d9SJeff Roberson #define	THREAD_CAN_SCHED(td, cpu)	\
11762fa74d9SJeff Roberson     CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
11862fa74d9SJeff Roberson 
11935e6168fSJeff Roberson /*
12012d56c0fSJohn Baldwin  * Priority ranges used for interactive and non-interactive timeshare
1212dc29adbSJohn Baldwin  * threads.  The timeshare priorities are split up into four ranges.
1222dc29adbSJohn Baldwin  * The first range handles interactive threads.  The last three ranges
1232dc29adbSJohn Baldwin  * (NHALF, x, and NHALF) handle non-interactive threads with the outer
1242dc29adbSJohn Baldwin  * ranges supporting nice values.
12512d56c0fSJohn Baldwin  */
1262dc29adbSJohn Baldwin #define	PRI_TIMESHARE_RANGE	(PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
1272dc29adbSJohn Baldwin #define	PRI_INTERACT_RANGE	((PRI_TIMESHARE_RANGE - SCHED_PRI_NRESV) / 2)
12816705791SAndriy Gapon #define	PRI_BATCH_RANGE		(PRI_TIMESHARE_RANGE - PRI_INTERACT_RANGE)
1292dc29adbSJohn Baldwin 
1302dc29adbSJohn Baldwin #define	PRI_MIN_INTERACT	PRI_MIN_TIMESHARE
1312dc29adbSJohn Baldwin #define	PRI_MAX_INTERACT	(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE - 1)
1322dc29adbSJohn Baldwin #define	PRI_MIN_BATCH		(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE)
13312d56c0fSJohn Baldwin #define	PRI_MAX_BATCH		PRI_MAX_TIMESHARE
13412d56c0fSJohn Baldwin 
13512d56c0fSJohn Baldwin /*
136e7d50326SJeff Roberson  * Cpu percentage computation macros and defines.
137e1f89c22SJeff Roberson  *
138e7d50326SJeff Roberson  * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
139e7d50326SJeff Roberson  * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
1408ab80cf0SJeff Roberson  * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
141e7d50326SJeff Roberson  * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
142e7d50326SJeff Roberson  * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
143e7d50326SJeff Roberson  * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
14435e6168fSJeff Roberson  */
145e7d50326SJeff Roberson #define	SCHED_TICK_SECS		10
146e7d50326SJeff Roberson #define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
1478ab80cf0SJeff Roberson #define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
148e7d50326SJeff Roberson #define	SCHED_TICK_SHIFT	10
149e7d50326SJeff Roberson #define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
150eddb4efaSJeff Roberson #define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
15135e6168fSJeff Roberson 
15235e6168fSJeff Roberson /*
153e7d50326SJeff Roberson  * These macros determine priorities for non-interactive threads.  They are
154e7d50326SJeff Roberson  * assigned a priority based on their recent cpu utilization as expressed
155e7d50326SJeff Roberson  * by the ratio of ticks to the tick total.  NHALF priorities at the start
156e7d50326SJeff Roberson  * and end of the MIN to MAX timeshare range are only reachable with negative
157e7d50326SJeff Roberson  * or positive nice respectively.
158e7d50326SJeff Roberson  *
159e7d50326SJeff Roberson  * PRI_RANGE:	Priority range for utilization dependent priorities.
160e7d50326SJeff Roberson  * PRI_NRESV:	Number of nice values.
161e7d50326SJeff Roberson  * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
162e7d50326SJeff Roberson  * PRI_NICE:	Determines the part of the priority inherited from nice.
163e7d50326SJeff Roberson  */
164e7d50326SJeff Roberson #define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
165e7d50326SJeff Roberson #define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
16612d56c0fSJohn Baldwin #define	SCHED_PRI_MIN		(PRI_MIN_BATCH + SCHED_PRI_NHALF)
16712d56c0fSJohn Baldwin #define	SCHED_PRI_MAX		(PRI_MAX_BATCH - SCHED_PRI_NHALF)
16878920008SJohn Baldwin #define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN + 1)
169e7d50326SJeff Roberson #define	SCHED_PRI_TICKS(ts)						\
170e7d50326SJeff Roberson     (SCHED_TICK_HZ((ts)) /						\
1711e516cf5SJeff Roberson     (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
172e7d50326SJeff Roberson #define	SCHED_PRI_NICE(nice)	(nice)
173e7d50326SJeff Roberson 
174e7d50326SJeff Roberson /*
175e7d50326SJeff Roberson  * These determine the interactivity of a process.  Interactivity differs from
176e7d50326SJeff Roberson  * cpu utilization in that it expresses the voluntary time slept vs time ran
177e7d50326SJeff Roberson  * while cpu utilization includes all time not running.  This more accurately
178e7d50326SJeff Roberson  * models the intent of the thread.
17935e6168fSJeff Roberson  *
180407b0157SJeff Roberson  * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
181407b0157SJeff Roberson  *		before throttling back.
182d322132cSJeff Roberson  * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
183210491d3SJeff Roberson  * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
1849f518f20SAttilio Rao  * INTERACT_THRESH:	Threshold for placement on the current runq.
18535e6168fSJeff Roberson  */
186e7d50326SJeff Roberson #define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
187e7d50326SJeff Roberson #define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
188210491d3SJeff Roberson #define	SCHED_INTERACT_MAX	(100)
189210491d3SJeff Roberson #define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
1904c9612c6SJeff Roberson #define	SCHED_INTERACT_THRESH	(30)
191e1f89c22SJeff Roberson 
19235e6168fSJeff Roberson /*
193e7d50326SJeff Roberson  * tickincr:		Converts a stathz tick into a hz domain scaled by
194e7d50326SJeff Roberson  *			the shift factor.  Without the shift the error rate
195e7d50326SJeff Roberson  *			due to rounding would be unacceptably high.
196e7d50326SJeff Roberson  * realstathz:		stathz is sometimes 0 and run off of hz.
197e7d50326SJeff Roberson  * sched_slice:		Runtime of each thread before rescheduling.
198ae7a6b38SJeff Roberson  * preempt_thresh:	Priority threshold for preemption and remote IPIs.
19935e6168fSJeff Roberson  */
200e7d50326SJeff Roberson static int sched_interact = SCHED_INTERACT_THRESH;
201e7d50326SJeff Roberson static int realstathz;
202e7d50326SJeff Roberson static int tickincr;
20373daf66fSJeff Roberson static int sched_slice = 1;
20402e2d6b4SJeff Roberson #ifdef PREEMPTION
20502e2d6b4SJeff Roberson #ifdef FULL_PREEMPTION
20602e2d6b4SJeff Roberson static int preempt_thresh = PRI_MAX_IDLE;
20702e2d6b4SJeff Roberson #else
208ae7a6b38SJeff Roberson static int preempt_thresh = PRI_MIN_KERN;
20902e2d6b4SJeff Roberson #endif
21002e2d6b4SJeff Roberson #else
21102e2d6b4SJeff Roberson static int preempt_thresh = 0;
21202e2d6b4SJeff Roberson #endif
21312d56c0fSJohn Baldwin static int static_boost = PRI_MIN_BATCH;
2141690c6c1SJeff Roberson static int sched_idlespins = 10000;
215b3f40a41SAlexander Motin static int sched_idlespinthresh = -1;
216ae7a6b38SJeff Roberson 
21735e6168fSJeff Roberson /*
218ae7a6b38SJeff Roberson  * tdq - per processor runqs and statistics.  All fields are protected by the
219ae7a6b38SJeff Roberson  * tdq_lock.  The load and lowpri may be accessed without to avoid excess
220ae7a6b38SJeff Roberson  * locking in sched_pickcpu();
22135e6168fSJeff Roberson  */
222ad1e7d28SJulian Elischer struct tdq {
22373daf66fSJeff Roberson 	/* Ordered to improve efficiency of cpu_search() and switch(). */
22462fa74d9SJeff Roberson 	struct mtx	tdq_lock;		/* run queue lock. */
22573daf66fSJeff Roberson 	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
2261690c6c1SJeff Roberson 	volatile int	tdq_load;		/* Aggregate load. */
2279f9ad565SAlexander Motin 	volatile int	tdq_cpu_idle;		/* cpu_idle() is active. */
22873daf66fSJeff Roberson 	int		tdq_sysload;		/* For loadavg, !ITHD load. */
22973daf66fSJeff Roberson 	int		tdq_transferable;	/* Transferable thread count. */
2301690c6c1SJeff Roberson 	short		tdq_switchcnt;		/* Switches this tick. */
2311690c6c1SJeff Roberson 	short		tdq_oldswitchcnt;	/* Switches last tick. */
23273daf66fSJeff Roberson 	u_char		tdq_lowpri;		/* Lowest priority thread. */
23373daf66fSJeff Roberson 	u_char		tdq_ipipending;		/* IPI pending. */
23473daf66fSJeff Roberson 	u_char		tdq_idx;		/* Current insert index. */
23573daf66fSJeff Roberson 	u_char		tdq_ridx;		/* Current removal index. */
236e7d50326SJeff Roberson 	struct runq	tdq_realtime;		/* real-time run queue. */
237ae7a6b38SJeff Roberson 	struct runq	tdq_timeshare;		/* timeshare run queue. */
238ae7a6b38SJeff Roberson 	struct runq	tdq_idle;		/* Queue of IDLE threads. */
2398f51ad55SJeff Roberson 	char		tdq_name[TDQ_NAME_LEN];
2408f51ad55SJeff Roberson #ifdef KTR
2418f51ad55SJeff Roberson 	char		tdq_loadname[TDQ_LOADNAME_LEN];
2428f51ad55SJeff Roberson #endif
243ae7a6b38SJeff Roberson } __aligned(64);
24435e6168fSJeff Roberson 
2451690c6c1SJeff Roberson /* Idle thread states and config. */
2461690c6c1SJeff Roberson #define	TDQ_RUNNING	1
2471690c6c1SJeff Roberson #define	TDQ_IDLE	2
2487b8bfa0dSJeff Roberson 
24980f86c9fSJeff Roberson #ifdef SMP
25007095abfSIvan Voras struct cpu_group *cpu_top;		/* CPU topology */
2517b8bfa0dSJeff Roberson 
25262fa74d9SJeff Roberson #define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
25362fa74d9SJeff Roberson #define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
2547b8bfa0dSJeff Roberson 
2557b8bfa0dSJeff Roberson /*
2567b8bfa0dSJeff Roberson  * Run-time tunables.
2577b8bfa0dSJeff Roberson  */
25828994a58SJeff Roberson static int rebalance = 1;
2597fcf154aSJeff Roberson static int balance_interval = 128;	/* Default set in sched_initticks(). */
2607b8bfa0dSJeff Roberson static int affinity;
26128994a58SJeff Roberson static int steal_idle = 1;
26228994a58SJeff Roberson static int steal_thresh = 2;
26380f86c9fSJeff Roberson 
26435e6168fSJeff Roberson /*
265d2ad694cSJeff Roberson  * One thread queue per processor.
26635e6168fSJeff Roberson  */
267ad1e7d28SJulian Elischer static struct tdq	tdq_cpu[MAXCPU];
2687fcf154aSJeff Roberson static struct tdq	*balance_tdq;
2697fcf154aSJeff Roberson static int balance_ticks;
27036acfc65SAlexander Motin static DPCPU_DEFINE(uint32_t, randomval);
271dc03363dSJeff Roberson 
272ad1e7d28SJulian Elischer #define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
273ad1e7d28SJulian Elischer #define	TDQ_CPU(x)	(&tdq_cpu[(x)])
274c47f202bSJeff Roberson #define	TDQ_ID(x)	((int)((x) - tdq_cpu))
27580f86c9fSJeff Roberson #else	/* !SMP */
276ad1e7d28SJulian Elischer static struct tdq	tdq_cpu;
277dc03363dSJeff Roberson 
27836b36916SJeff Roberson #define	TDQ_ID(x)	(0)
279ad1e7d28SJulian Elischer #define	TDQ_SELF()	(&tdq_cpu)
280ad1e7d28SJulian Elischer #define	TDQ_CPU(x)	(&tdq_cpu)
2810a016a05SJeff Roberson #endif
28235e6168fSJeff Roberson 
283ae7a6b38SJeff Roberson #define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
284ae7a6b38SJeff Roberson #define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
285ae7a6b38SJeff Roberson #define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
286ae7a6b38SJeff Roberson #define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
28762fa74d9SJeff Roberson #define	TDQ_LOCKPTR(t)		(&(t)->tdq_lock)
288ae7a6b38SJeff Roberson 
2898460a577SJohn Birrell static void sched_priority(struct thread *);
29021381d1bSJeff Roberson static void sched_thread_priority(struct thread *, u_char);
2918460a577SJohn Birrell static int sched_interact_score(struct thread *);
2928460a577SJohn Birrell static void sched_interact_update(struct thread *);
2938460a577SJohn Birrell static void sched_interact_fork(struct thread *);
2947295465eSAlexander Motin static void sched_pctcpu_update(struct td_sched *, int);
29535e6168fSJeff Roberson 
2965d7ef00cSJeff Roberson /* Operations on per processor queues */
2979727e637SJeff Roberson static struct thread *tdq_choose(struct tdq *);
298ad1e7d28SJulian Elischer static void tdq_setup(struct tdq *);
2999727e637SJeff Roberson static void tdq_load_add(struct tdq *, struct thread *);
3009727e637SJeff Roberson static void tdq_load_rem(struct tdq *, struct thread *);
3019727e637SJeff Roberson static __inline void tdq_runq_add(struct tdq *, struct thread *, int);
3029727e637SJeff Roberson static __inline void tdq_runq_rem(struct tdq *, struct thread *);
303ff256d9cSJeff Roberson static inline int sched_shouldpreempt(int, int, int);
304ad1e7d28SJulian Elischer void tdq_print(int cpu);
305e7d50326SJeff Roberson static void runq_print(struct runq *rq);
306ae7a6b38SJeff Roberson static void tdq_add(struct tdq *, struct thread *, int);
3075d7ef00cSJeff Roberson #ifdef SMP
30862fa74d9SJeff Roberson static int tdq_move(struct tdq *, struct tdq *);
309ad1e7d28SJulian Elischer static int tdq_idled(struct tdq *);
3109727e637SJeff Roberson static void tdq_notify(struct tdq *, struct thread *);
3119727e637SJeff Roberson static struct thread *tdq_steal(struct tdq *, int);
3129727e637SJeff Roberson static struct thread *runq_steal(struct runq *, int);
3139727e637SJeff Roberson static int sched_pickcpu(struct thread *, int);
3147fcf154aSJeff Roberson static void sched_balance(void);
31562fa74d9SJeff Roberson static int sched_balance_pair(struct tdq *, struct tdq *);
3169727e637SJeff Roberson static inline struct tdq *sched_setcpu(struct thread *, int, int);
317ae7a6b38SJeff Roberson static inline void thread_unblock_switch(struct thread *, struct mtx *);
318c47f202bSJeff Roberson static struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
31907095abfSIvan Voras static int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
32007095abfSIvan Voras static int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
32107095abfSIvan Voras     struct cpu_group *cg, int indent);
3225d7ef00cSJeff Roberson #endif
3235d7ef00cSJeff Roberson 
324e7d50326SJeff Roberson static void sched_setup(void *dummy);
325237fdd78SRobert Watson SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
326e7d50326SJeff Roberson 
327e7d50326SJeff Roberson static void sched_initticks(void *dummy);
328237fdd78SRobert Watson SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
329237fdd78SRobert Watson     NULL);
330e7d50326SJeff Roberson 
331*b3e9e682SRyan Stone SDT_PROVIDER_DEFINE(sched);
332*b3e9e682SRyan Stone 
333*b3e9e682SRyan Stone SDT_PROBE_DEFINE3(sched, , , change_pri, change-pri, "struct thread *",
334*b3e9e682SRyan Stone     "struct proc *", "uint8_t");
335*b3e9e682SRyan Stone SDT_PROBE_DEFINE3(sched, , , dequeue, dequeue, "struct thread *",
336*b3e9e682SRyan Stone     "struct proc *", "void *");
337*b3e9e682SRyan Stone SDT_PROBE_DEFINE4(sched, , , enqueue, enqueue, "struct thread *",
338*b3e9e682SRyan Stone     "struct proc *", "void *", "int");
339*b3e9e682SRyan Stone SDT_PROBE_DEFINE4(sched, , , lend_pri, lend-pri, "struct thread *",
340*b3e9e682SRyan Stone     "struct proc *", "uint8_t", "struct thread *");
341*b3e9e682SRyan Stone SDT_PROBE_DEFINE2(sched, , , load_change, load-change, "int", "int");
342*b3e9e682SRyan Stone SDT_PROBE_DEFINE2(sched, , , off_cpu, off-cpu, "struct thread *",
343*b3e9e682SRyan Stone     "struct proc *");
344*b3e9e682SRyan Stone SDT_PROBE_DEFINE(sched, , , on_cpu, on-cpu);
345*b3e9e682SRyan Stone SDT_PROBE_DEFINE(sched, , , remain_cpu, remain-cpu);
346*b3e9e682SRyan Stone SDT_PROBE_DEFINE2(sched, , , surrender, surrender, "struct thread *",
347*b3e9e682SRyan Stone     "struct proc *");
348*b3e9e682SRyan Stone 
349ae7a6b38SJeff Roberson /*
350ae7a6b38SJeff Roberson  * Print the threads waiting on a run-queue.
351ae7a6b38SJeff Roberson  */
352e7d50326SJeff Roberson static void
353e7d50326SJeff Roberson runq_print(struct runq *rq)
354e7d50326SJeff Roberson {
355e7d50326SJeff Roberson 	struct rqhead *rqh;
3569727e637SJeff Roberson 	struct thread *td;
357e7d50326SJeff Roberson 	int pri;
358e7d50326SJeff Roberson 	int j;
359e7d50326SJeff Roberson 	int i;
360e7d50326SJeff Roberson 
361e7d50326SJeff Roberson 	for (i = 0; i < RQB_LEN; i++) {
362e7d50326SJeff Roberson 		printf("\t\trunq bits %d 0x%zx\n",
363e7d50326SJeff Roberson 		    i, rq->rq_status.rqb_bits[i]);
364e7d50326SJeff Roberson 		for (j = 0; j < RQB_BPW; j++)
365e7d50326SJeff Roberson 			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
366e7d50326SJeff Roberson 				pri = j + (i << RQB_L2BPW);
367e7d50326SJeff Roberson 				rqh = &rq->rq_queues[pri];
3689727e637SJeff Roberson 				TAILQ_FOREACH(td, rqh, td_runq) {
369e7d50326SJeff Roberson 					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
3709727e637SJeff Roberson 					    td, td->td_name, td->td_priority,
3719727e637SJeff Roberson 					    td->td_rqindex, pri);
372e7d50326SJeff Roberson 				}
373e7d50326SJeff Roberson 			}
374e7d50326SJeff Roberson 	}
375e7d50326SJeff Roberson }
376e7d50326SJeff Roberson 
377ae7a6b38SJeff Roberson /*
378ae7a6b38SJeff Roberson  * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
379ae7a6b38SJeff Roberson  */
38015dc847eSJeff Roberson void
381ad1e7d28SJulian Elischer tdq_print(int cpu)
38215dc847eSJeff Roberson {
383ad1e7d28SJulian Elischer 	struct tdq *tdq;
38415dc847eSJeff Roberson 
385ad1e7d28SJulian Elischer 	tdq = TDQ_CPU(cpu);
38615dc847eSJeff Roberson 
387c47f202bSJeff Roberson 	printf("tdq %d:\n", TDQ_ID(tdq));
38862fa74d9SJeff Roberson 	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
38962fa74d9SJeff Roberson 	printf("\tLock name:      %s\n", tdq->tdq_name);
390d2ad694cSJeff Roberson 	printf("\tload:           %d\n", tdq->tdq_load);
3911690c6c1SJeff Roberson 	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
3921690c6c1SJeff Roberson 	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
393e7d50326SJeff Roberson 	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
3943f872f85SJeff Roberson 	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
3951690c6c1SJeff Roberson 	printf("\tload transferable: %d\n", tdq->tdq_transferable);
3961690c6c1SJeff Roberson 	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
397e7d50326SJeff Roberson 	printf("\trealtime runq:\n");
398e7d50326SJeff Roberson 	runq_print(&tdq->tdq_realtime);
399e7d50326SJeff Roberson 	printf("\ttimeshare runq:\n");
400e7d50326SJeff Roberson 	runq_print(&tdq->tdq_timeshare);
401e7d50326SJeff Roberson 	printf("\tidle runq:\n");
402e7d50326SJeff Roberson 	runq_print(&tdq->tdq_idle);
40315dc847eSJeff Roberson }
40415dc847eSJeff Roberson 
405ff256d9cSJeff Roberson static inline int
406ff256d9cSJeff Roberson sched_shouldpreempt(int pri, int cpri, int remote)
407ff256d9cSJeff Roberson {
408ff256d9cSJeff Roberson 	/*
409ff256d9cSJeff Roberson 	 * If the new priority is not better than the current priority there is
410ff256d9cSJeff Roberson 	 * nothing to do.
411ff256d9cSJeff Roberson 	 */
412ff256d9cSJeff Roberson 	if (pri >= cpri)
413ff256d9cSJeff Roberson 		return (0);
414ff256d9cSJeff Roberson 	/*
415ff256d9cSJeff Roberson 	 * Always preempt idle.
416ff256d9cSJeff Roberson 	 */
417ff256d9cSJeff Roberson 	if (cpri >= PRI_MIN_IDLE)
418ff256d9cSJeff Roberson 		return (1);
419ff256d9cSJeff Roberson 	/*
420ff256d9cSJeff Roberson 	 * If preemption is disabled don't preempt others.
421ff256d9cSJeff Roberson 	 */
422ff256d9cSJeff Roberson 	if (preempt_thresh == 0)
423ff256d9cSJeff Roberson 		return (0);
424ff256d9cSJeff Roberson 	/*
425ff256d9cSJeff Roberson 	 * Preempt if we exceed the threshold.
426ff256d9cSJeff Roberson 	 */
427ff256d9cSJeff Roberson 	if (pri <= preempt_thresh)
428ff256d9cSJeff Roberson 		return (1);
429ff256d9cSJeff Roberson 	/*
43012d56c0fSJohn Baldwin 	 * If we're interactive or better and there is non-interactive
43112d56c0fSJohn Baldwin 	 * or worse running preempt only remote processors.
432ff256d9cSJeff Roberson 	 */
43312d56c0fSJohn Baldwin 	if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
434ff256d9cSJeff Roberson 		return (1);
435ff256d9cSJeff Roberson 	return (0);
436ff256d9cSJeff Roberson }
437ff256d9cSJeff Roberson 
438ae7a6b38SJeff Roberson /*
439ae7a6b38SJeff Roberson  * Add a thread to the actual run-queue.  Keeps transferable counts up to
440ae7a6b38SJeff Roberson  * date with what is actually on the run-queue.  Selects the correct
441ae7a6b38SJeff Roberson  * queue position for timeshare threads.
442ae7a6b38SJeff Roberson  */
443155b9987SJeff Roberson static __inline void
4449727e637SJeff Roberson tdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
445155b9987SJeff Roberson {
4469727e637SJeff Roberson 	struct td_sched *ts;
447c143ac21SJeff Roberson 	u_char pri;
448c143ac21SJeff Roberson 
449ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
4509727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
45173daf66fSJeff Roberson 
4529727e637SJeff Roberson 	pri = td->td_priority;
4539727e637SJeff Roberson 	ts = td->td_sched;
4549727e637SJeff Roberson 	TD_SET_RUNQ(td);
4559727e637SJeff Roberson 	if (THREAD_CAN_MIGRATE(td)) {
456d2ad694cSJeff Roberson 		tdq->tdq_transferable++;
457ad1e7d28SJulian Elischer 		ts->ts_flags |= TSF_XFERABLE;
45880f86c9fSJeff Roberson 	}
45912d56c0fSJohn Baldwin 	if (pri < PRI_MIN_BATCH) {
460c143ac21SJeff Roberson 		ts->ts_runq = &tdq->tdq_realtime;
46112d56c0fSJohn Baldwin 	} else if (pri <= PRI_MAX_BATCH) {
462c143ac21SJeff Roberson 		ts->ts_runq = &tdq->tdq_timeshare;
46312d56c0fSJohn Baldwin 		KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
464e7d50326SJeff Roberson 			("Invalid priority %d on timeshare runq", pri));
465e7d50326SJeff Roberson 		/*
466e7d50326SJeff Roberson 		 * This queue contains only priorities between MIN and MAX
467e7d50326SJeff Roberson 		 * realtime.  Use the whole queue to represent these values.
468e7d50326SJeff Roberson 		 */
469c47f202bSJeff Roberson 		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
47016705791SAndriy Gapon 			pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
471e7d50326SJeff Roberson 			pri = (pri + tdq->tdq_idx) % RQ_NQS;
4723f872f85SJeff Roberson 			/*
4733f872f85SJeff Roberson 			 * This effectively shortens the queue by one so we
4743f872f85SJeff Roberson 			 * can have a one slot difference between idx and
4753f872f85SJeff Roberson 			 * ridx while we wait for threads to drain.
4763f872f85SJeff Roberson 			 */
4773f872f85SJeff Roberson 			if (tdq->tdq_ridx != tdq->tdq_idx &&
4783f872f85SJeff Roberson 			    pri == tdq->tdq_ridx)
4794499aff6SJeff Roberson 				pri = (unsigned char)(pri - 1) % RQ_NQS;
480e7d50326SJeff Roberson 		} else
4813f872f85SJeff Roberson 			pri = tdq->tdq_ridx;
4829727e637SJeff Roberson 		runq_add_pri(ts->ts_runq, td, pri, flags);
483c143ac21SJeff Roberson 		return;
484e7d50326SJeff Roberson 	} else
48573daf66fSJeff Roberson 		ts->ts_runq = &tdq->tdq_idle;
4869727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
48773daf66fSJeff Roberson }
48873daf66fSJeff Roberson 
48973daf66fSJeff Roberson /*
490ae7a6b38SJeff Roberson  * Remove a thread from a run-queue.  This typically happens when a thread
491ae7a6b38SJeff Roberson  * is selected to run.  Running threads are not on the queue and the
492ae7a6b38SJeff Roberson  * transferable count does not reflect them.
493ae7a6b38SJeff Roberson  */
494155b9987SJeff Roberson static __inline void
4959727e637SJeff Roberson tdq_runq_rem(struct tdq *tdq, struct thread *td)
496155b9987SJeff Roberson {
4979727e637SJeff Roberson 	struct td_sched *ts;
4989727e637SJeff Roberson 
4999727e637SJeff Roberson 	ts = td->td_sched;
500ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
501ae7a6b38SJeff Roberson 	KASSERT(ts->ts_runq != NULL,
5029727e637SJeff Roberson 	    ("tdq_runq_remove: thread %p null ts_runq", td));
503ad1e7d28SJulian Elischer 	if (ts->ts_flags & TSF_XFERABLE) {
504d2ad694cSJeff Roberson 		tdq->tdq_transferable--;
505ad1e7d28SJulian Elischer 		ts->ts_flags &= ~TSF_XFERABLE;
50680f86c9fSJeff Roberson 	}
5073f872f85SJeff Roberson 	if (ts->ts_runq == &tdq->tdq_timeshare) {
5083f872f85SJeff Roberson 		if (tdq->tdq_idx != tdq->tdq_ridx)
5099727e637SJeff Roberson 			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
510e7d50326SJeff Roberson 		else
5119727e637SJeff Roberson 			runq_remove_idx(ts->ts_runq, td, NULL);
5123f872f85SJeff Roberson 	} else
5139727e637SJeff Roberson 		runq_remove(ts->ts_runq, td);
514155b9987SJeff Roberson }
515155b9987SJeff Roberson 
516ae7a6b38SJeff Roberson /*
517ae7a6b38SJeff Roberson  * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
518ae7a6b38SJeff Roberson  * for this thread to the referenced thread queue.
519ae7a6b38SJeff Roberson  */
520a8949de2SJeff Roberson static void
5219727e637SJeff Roberson tdq_load_add(struct tdq *tdq, struct thread *td)
5225d7ef00cSJeff Roberson {
523ae7a6b38SJeff Roberson 
524ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
5259727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
52603d17db7SJeff Roberson 
527d2ad694cSJeff Roberson 	tdq->tdq_load++;
5281b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
529d2ad694cSJeff Roberson 		tdq->tdq_sysload++;
5308f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
531*b3e9e682SRyan Stone 	SDT_PROBE2(sched, , , load_change, (int)TDQ_ID(tdq), tdq->tdq_load);
5325d7ef00cSJeff Roberson }
53315dc847eSJeff Roberson 
534ae7a6b38SJeff Roberson /*
535ae7a6b38SJeff Roberson  * Remove the load from a thread that is transitioning to a sleep state or
536ae7a6b38SJeff Roberson  * exiting.
537ae7a6b38SJeff Roberson  */
538a8949de2SJeff Roberson static void
5399727e637SJeff Roberson tdq_load_rem(struct tdq *tdq, struct thread *td)
5405d7ef00cSJeff Roberson {
541ae7a6b38SJeff Roberson 
5429727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
543ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
544ae7a6b38SJeff Roberson 	KASSERT(tdq->tdq_load != 0,
545c47f202bSJeff Roberson 	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
54603d17db7SJeff Roberson 
547d2ad694cSJeff Roberson 	tdq->tdq_load--;
5481b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
54903d17db7SJeff Roberson 		tdq->tdq_sysload--;
5508f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
551*b3e9e682SRyan Stone 	SDT_PROBE2(sched, , , load_change, (int)TDQ_ID(tdq), tdq->tdq_load);
55215dc847eSJeff Roberson }
55315dc847eSJeff Roberson 
554356500a3SJeff Roberson /*
55562fa74d9SJeff Roberson  * Set lowpri to its exact value by searching the run-queue and
55662fa74d9SJeff Roberson  * evaluating curthread.  curthread may be passed as an optimization.
557356500a3SJeff Roberson  */
55822bf7d9aSJeff Roberson static void
55962fa74d9SJeff Roberson tdq_setlowpri(struct tdq *tdq, struct thread *ctd)
56062fa74d9SJeff Roberson {
56162fa74d9SJeff Roberson 	struct thread *td;
56262fa74d9SJeff Roberson 
56362fa74d9SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
56462fa74d9SJeff Roberson 	if (ctd == NULL)
56562fa74d9SJeff Roberson 		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
5669727e637SJeff Roberson 	td = tdq_choose(tdq);
5679727e637SJeff Roberson 	if (td == NULL || td->td_priority > ctd->td_priority)
56862fa74d9SJeff Roberson 		tdq->tdq_lowpri = ctd->td_priority;
56962fa74d9SJeff Roberson 	else
57062fa74d9SJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
57162fa74d9SJeff Roberson }
57262fa74d9SJeff Roberson 
57362fa74d9SJeff Roberson #ifdef SMP
57462fa74d9SJeff Roberson struct cpu_search {
575c76ee827SJeff Roberson 	cpuset_t cs_mask;
57636acfc65SAlexander Motin 	u_int	cs_prefer;
57736acfc65SAlexander Motin 	int	cs_pri;		/* Min priority for low. */
57836acfc65SAlexander Motin 	int	cs_limit;	/* Max load for low, min load for high. */
57936acfc65SAlexander Motin 	int	cs_cpu;
58036acfc65SAlexander Motin 	int	cs_load;
58162fa74d9SJeff Roberson };
58262fa74d9SJeff Roberson 
58362fa74d9SJeff Roberson #define	CPU_SEARCH_LOWEST	0x1
58462fa74d9SJeff Roberson #define	CPU_SEARCH_HIGHEST	0x2
58562fa74d9SJeff Roberson #define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
58662fa74d9SJeff Roberson 
587c76ee827SJeff Roberson #define	CPUSET_FOREACH(cpu, mask)				\
588c76ee827SJeff Roberson 	for ((cpu) = 0; (cpu) <= mp_maxid; (cpu)++)		\
58971a19bdcSAttilio Rao 		if (CPU_ISSET(cpu, &mask))
59062fa74d9SJeff Roberson 
59136acfc65SAlexander Motin static __inline int cpu_search(const struct cpu_group *cg, struct cpu_search *low,
59262fa74d9SJeff Roberson     struct cpu_search *high, const int match);
59336acfc65SAlexander Motin int cpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low);
59436acfc65SAlexander Motin int cpu_search_highest(const struct cpu_group *cg, struct cpu_search *high);
59536acfc65SAlexander Motin int cpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
59662fa74d9SJeff Roberson     struct cpu_search *high);
59762fa74d9SJeff Roberson 
59862fa74d9SJeff Roberson /*
59962fa74d9SJeff Roberson  * Search the tree of cpu_groups for the lowest or highest loaded cpu
60062fa74d9SJeff Roberson  * according to the match argument.  This routine actually compares the
60162fa74d9SJeff Roberson  * load on all paths through the tree and finds the least loaded cpu on
60262fa74d9SJeff Roberson  * the least loaded path, which may differ from the least loaded cpu in
60362fa74d9SJeff Roberson  * the system.  This balances work among caches and busses.
60462fa74d9SJeff Roberson  *
60562fa74d9SJeff Roberson  * This inline is instantiated in three forms below using constants for the
60662fa74d9SJeff Roberson  * match argument.  It is reduced to the minimum set for each case.  It is
60762fa74d9SJeff Roberson  * also recursive to the depth of the tree.
60862fa74d9SJeff Roberson  */
609d628fbfaSJohn Baldwin static __inline int
61036acfc65SAlexander Motin cpu_search(const struct cpu_group *cg, struct cpu_search *low,
61162fa74d9SJeff Roberson     struct cpu_search *high, const int match)
61262fa74d9SJeff Roberson {
61362fa74d9SJeff Roberson 	struct cpu_search lgroup;
61462fa74d9SJeff Roberson 	struct cpu_search hgroup;
61536acfc65SAlexander Motin 	cpuset_t cpumask;
61662fa74d9SJeff Roberson 	struct cpu_group *child;
61736acfc65SAlexander Motin 	struct tdq *tdq;
61870801abeSAlexander Motin 	int cpu, i, hload, lload, load, total, rnd, *rndptr;
61962fa74d9SJeff Roberson 
62036acfc65SAlexander Motin 	total = 0;
62136acfc65SAlexander Motin 	cpumask = cg->cg_mask;
62262fa74d9SJeff Roberson 	if (match & CPU_SEARCH_LOWEST) {
62336acfc65SAlexander Motin 		lload = INT_MAX;
62462fa74d9SJeff Roberson 		lgroup = *low;
62562fa74d9SJeff Roberson 	}
62662fa74d9SJeff Roberson 	if (match & CPU_SEARCH_HIGHEST) {
62770801abeSAlexander Motin 		hload = INT_MIN;
62862fa74d9SJeff Roberson 		hgroup = *high;
62962fa74d9SJeff Roberson 	}
63036acfc65SAlexander Motin 
63136acfc65SAlexander Motin 	/* Iterate through the child CPU groups and then remaining CPUs. */
63270801abeSAlexander Motin 	for (i = cg->cg_children, cpu = mp_maxid; i >= 0; ) {
63370801abeSAlexander Motin 		if (i == 0) {
63470801abeSAlexander Motin 			while (cpu >= 0 && !CPU_ISSET(cpu, &cpumask))
63570801abeSAlexander Motin 				cpu--;
63670801abeSAlexander Motin 			if (cpu < 0)
63736acfc65SAlexander Motin 				break;
63836acfc65SAlexander Motin 			child = NULL;
63936acfc65SAlexander Motin 		} else
64070801abeSAlexander Motin 			child = &cg->cg_child[i - 1];
64136acfc65SAlexander Motin 
64270801abeSAlexander Motin 		if (match & CPU_SEARCH_LOWEST)
64370801abeSAlexander Motin 			lgroup.cs_cpu = -1;
64470801abeSAlexander Motin 		if (match & CPU_SEARCH_HIGHEST)
64570801abeSAlexander Motin 			hgroup.cs_cpu = -1;
64636acfc65SAlexander Motin 		if (child) {			/* Handle child CPU group. */
64736acfc65SAlexander Motin 			CPU_NAND(&cpumask, &child->cg_mask);
64862fa74d9SJeff Roberson 			switch (match) {
64962fa74d9SJeff Roberson 			case CPU_SEARCH_LOWEST:
65062fa74d9SJeff Roberson 				load = cpu_search_lowest(child, &lgroup);
65162fa74d9SJeff Roberson 				break;
65262fa74d9SJeff Roberson 			case CPU_SEARCH_HIGHEST:
65362fa74d9SJeff Roberson 				load = cpu_search_highest(child, &hgroup);
65462fa74d9SJeff Roberson 				break;
65562fa74d9SJeff Roberson 			case CPU_SEARCH_BOTH:
65662fa74d9SJeff Roberson 				load = cpu_search_both(child, &lgroup, &hgroup);
65762fa74d9SJeff Roberson 				break;
65862fa74d9SJeff Roberson 			}
65936acfc65SAlexander Motin 		} else {			/* Handle child CPU. */
66036acfc65SAlexander Motin 			tdq = TDQ_CPU(cpu);
66136acfc65SAlexander Motin 			load = tdq->tdq_load * 256;
66270801abeSAlexander Motin 			rndptr = DPCPU_PTR(randomval);
66370801abeSAlexander Motin 			rnd = (*rndptr = *rndptr * 69069 + 5) >> 26;
66436acfc65SAlexander Motin 			if (match & CPU_SEARCH_LOWEST) {
66536acfc65SAlexander Motin 				if (cpu == low->cs_prefer)
66636acfc65SAlexander Motin 					load -= 64;
66736acfc65SAlexander Motin 				/* If that CPU is allowed and get data. */
66870801abeSAlexander Motin 				if (tdq->tdq_lowpri > lgroup.cs_pri &&
66970801abeSAlexander Motin 				    tdq->tdq_load <= lgroup.cs_limit &&
67070801abeSAlexander Motin 				    CPU_ISSET(cpu, &lgroup.cs_mask)) {
67136acfc65SAlexander Motin 					lgroup.cs_cpu = cpu;
67236acfc65SAlexander Motin 					lgroup.cs_load = load - rnd;
67336acfc65SAlexander Motin 				}
67462fa74d9SJeff Roberson 			}
67562fa74d9SJeff Roberson 			if (match & CPU_SEARCH_HIGHEST)
67670801abeSAlexander Motin 				if (tdq->tdq_load >= hgroup.cs_limit &&
67770801abeSAlexander Motin 				    tdq->tdq_transferable &&
67870801abeSAlexander Motin 				    CPU_ISSET(cpu, &hgroup.cs_mask)) {
67936acfc65SAlexander Motin 					hgroup.cs_cpu = cpu;
68036acfc65SAlexander Motin 					hgroup.cs_load = load - rnd;
68162fa74d9SJeff Roberson 				}
68262fa74d9SJeff Roberson 		}
68336acfc65SAlexander Motin 		total += load;
68462fa74d9SJeff Roberson 
68536acfc65SAlexander Motin 		/* We have info about child item. Compare it. */
68636acfc65SAlexander Motin 		if (match & CPU_SEARCH_LOWEST) {
68770801abeSAlexander Motin 			if (lgroup.cs_cpu >= 0 &&
6886022f0bcSAlexander Motin 			    (load < lload ||
6896022f0bcSAlexander Motin 			     (load == lload && lgroup.cs_load < low->cs_load))) {
69036acfc65SAlexander Motin 				lload = load;
69136acfc65SAlexander Motin 				low->cs_cpu = lgroup.cs_cpu;
69236acfc65SAlexander Motin 				low->cs_load = lgroup.cs_load;
69336acfc65SAlexander Motin 			}
69436acfc65SAlexander Motin 		}
69536acfc65SAlexander Motin 		if (match & CPU_SEARCH_HIGHEST)
69670801abeSAlexander Motin 			if (hgroup.cs_cpu >= 0 &&
6976022f0bcSAlexander Motin 			    (load > hload ||
6986022f0bcSAlexander Motin 			     (load == hload && hgroup.cs_load > high->cs_load))) {
69936acfc65SAlexander Motin 				hload = load;
70036acfc65SAlexander Motin 				high->cs_cpu = hgroup.cs_cpu;
70136acfc65SAlexander Motin 				high->cs_load = hgroup.cs_load;
70236acfc65SAlexander Motin 			}
70370801abeSAlexander Motin 		if (child) {
70470801abeSAlexander Motin 			i--;
70570801abeSAlexander Motin 			if (i == 0 && CPU_EMPTY(&cpumask))
70670801abeSAlexander Motin 				break;
70770801abeSAlexander Motin 		} else
70870801abeSAlexander Motin 			cpu--;
70962fa74d9SJeff Roberson 	}
71062fa74d9SJeff Roberson 	return (total);
71162fa74d9SJeff Roberson }
71262fa74d9SJeff Roberson 
71362fa74d9SJeff Roberson /*
71462fa74d9SJeff Roberson  * cpu_search instantiations must pass constants to maintain the inline
71562fa74d9SJeff Roberson  * optimization.
71662fa74d9SJeff Roberson  */
71762fa74d9SJeff Roberson int
71836acfc65SAlexander Motin cpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low)
71962fa74d9SJeff Roberson {
72062fa74d9SJeff Roberson 	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
72162fa74d9SJeff Roberson }
72262fa74d9SJeff Roberson 
72362fa74d9SJeff Roberson int
72436acfc65SAlexander Motin cpu_search_highest(const struct cpu_group *cg, struct cpu_search *high)
72562fa74d9SJeff Roberson {
72662fa74d9SJeff Roberson 	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
72762fa74d9SJeff Roberson }
72862fa74d9SJeff Roberson 
72962fa74d9SJeff Roberson int
73036acfc65SAlexander Motin cpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
73162fa74d9SJeff Roberson     struct cpu_search *high)
73262fa74d9SJeff Roberson {
73362fa74d9SJeff Roberson 	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
73462fa74d9SJeff Roberson }
73562fa74d9SJeff Roberson 
73662fa74d9SJeff Roberson /*
73762fa74d9SJeff Roberson  * Find the cpu with the least load via the least loaded path that has a
73862fa74d9SJeff Roberson  * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
73962fa74d9SJeff Roberson  * acceptable.
74062fa74d9SJeff Roberson  */
74162fa74d9SJeff Roberson static inline int
74236acfc65SAlexander Motin sched_lowest(const struct cpu_group *cg, cpuset_t mask, int pri, int maxload,
74336acfc65SAlexander Motin     int prefer)
74462fa74d9SJeff Roberson {
74562fa74d9SJeff Roberson 	struct cpu_search low;
74662fa74d9SJeff Roberson 
74762fa74d9SJeff Roberson 	low.cs_cpu = -1;
74836acfc65SAlexander Motin 	low.cs_prefer = prefer;
74962fa74d9SJeff Roberson 	low.cs_mask = mask;
75036acfc65SAlexander Motin 	low.cs_pri = pri;
75136acfc65SAlexander Motin 	low.cs_limit = maxload;
75262fa74d9SJeff Roberson 	cpu_search_lowest(cg, &low);
75362fa74d9SJeff Roberson 	return low.cs_cpu;
75462fa74d9SJeff Roberson }
75562fa74d9SJeff Roberson 
75662fa74d9SJeff Roberson /*
75762fa74d9SJeff Roberson  * Find the cpu with the highest load via the highest loaded path.
75862fa74d9SJeff Roberson  */
75962fa74d9SJeff Roberson static inline int
76036acfc65SAlexander Motin sched_highest(const struct cpu_group *cg, cpuset_t mask, int minload)
76162fa74d9SJeff Roberson {
76262fa74d9SJeff Roberson 	struct cpu_search high;
76362fa74d9SJeff Roberson 
76462fa74d9SJeff Roberson 	high.cs_cpu = -1;
76562fa74d9SJeff Roberson 	high.cs_mask = mask;
76662fa74d9SJeff Roberson 	high.cs_limit = minload;
76762fa74d9SJeff Roberson 	cpu_search_highest(cg, &high);
76862fa74d9SJeff Roberson 	return high.cs_cpu;
76962fa74d9SJeff Roberson }
77062fa74d9SJeff Roberson 
77162fa74d9SJeff Roberson /*
77262fa74d9SJeff Roberson  * Simultaneously find the highest and lowest loaded cpu reachable via
77362fa74d9SJeff Roberson  * cg.
77462fa74d9SJeff Roberson  */
77562fa74d9SJeff Roberson static inline void
77636acfc65SAlexander Motin sched_both(const struct cpu_group *cg, cpuset_t mask, int *lowcpu, int *highcpu)
77762fa74d9SJeff Roberson {
77862fa74d9SJeff Roberson 	struct cpu_search high;
77962fa74d9SJeff Roberson 	struct cpu_search low;
78062fa74d9SJeff Roberson 
78162fa74d9SJeff Roberson 	low.cs_cpu = -1;
78236acfc65SAlexander Motin 	low.cs_prefer = -1;
78336acfc65SAlexander Motin 	low.cs_pri = -1;
78436acfc65SAlexander Motin 	low.cs_limit = INT_MAX;
78562fa74d9SJeff Roberson 	low.cs_mask = mask;
78662fa74d9SJeff Roberson 	high.cs_cpu = -1;
78762fa74d9SJeff Roberson 	high.cs_limit = -1;
78862fa74d9SJeff Roberson 	high.cs_mask = mask;
78962fa74d9SJeff Roberson 	cpu_search_both(cg, &low, &high);
79062fa74d9SJeff Roberson 	*lowcpu = low.cs_cpu;
79162fa74d9SJeff Roberson 	*highcpu = high.cs_cpu;
79262fa74d9SJeff Roberson 	return;
79362fa74d9SJeff Roberson }
79462fa74d9SJeff Roberson 
79562fa74d9SJeff Roberson static void
79662fa74d9SJeff Roberson sched_balance_group(struct cpu_group *cg)
79762fa74d9SJeff Roberson {
79836acfc65SAlexander Motin 	cpuset_t hmask, lmask;
79936acfc65SAlexander Motin 	int high, low, anylow;
80062fa74d9SJeff Roberson 
80136acfc65SAlexander Motin 	CPU_FILL(&hmask);
80262fa74d9SJeff Roberson 	for (;;) {
80336acfc65SAlexander Motin 		high = sched_highest(cg, hmask, 1);
80436acfc65SAlexander Motin 		/* Stop if there is no more CPU with transferrable threads. */
80536acfc65SAlexander Motin 		if (high == -1)
80662fa74d9SJeff Roberson 			break;
80736acfc65SAlexander Motin 		CPU_CLR(high, &hmask);
80836acfc65SAlexander Motin 		CPU_COPY(&hmask, &lmask);
80936acfc65SAlexander Motin 		/* Stop if there is no more CPU left for low. */
81036acfc65SAlexander Motin 		if (CPU_EMPTY(&lmask))
81162fa74d9SJeff Roberson 			break;
81236acfc65SAlexander Motin 		anylow = 1;
81336acfc65SAlexander Motin nextlow:
81436acfc65SAlexander Motin 		low = sched_lowest(cg, lmask, -1,
81536acfc65SAlexander Motin 		    TDQ_CPU(high)->tdq_load - 1, high);
81636acfc65SAlexander Motin 		/* Stop if we looked well and found no less loaded CPU. */
81736acfc65SAlexander Motin 		if (anylow && low == -1)
81836acfc65SAlexander Motin 			break;
81936acfc65SAlexander Motin 		/* Go to next high if we found no less loaded CPU. */
82036acfc65SAlexander Motin 		if (low == -1)
82136acfc65SAlexander Motin 			continue;
82236acfc65SAlexander Motin 		/* Transfer thread from high to low. */
82336acfc65SAlexander Motin 		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low))) {
82436acfc65SAlexander Motin 			/* CPU that got thread can no longer be a donor. */
82536acfc65SAlexander Motin 			CPU_CLR(low, &hmask);
82636acfc65SAlexander Motin 		} else {
82762fa74d9SJeff Roberson 			/*
82836acfc65SAlexander Motin 			 * If failed, then there is no threads on high
82936acfc65SAlexander Motin 			 * that can run on this low. Drop low from low
83036acfc65SAlexander Motin 			 * mask and look for different one.
83162fa74d9SJeff Roberson 			 */
83236acfc65SAlexander Motin 			CPU_CLR(low, &lmask);
83336acfc65SAlexander Motin 			anylow = 0;
83436acfc65SAlexander Motin 			goto nextlow;
83562fa74d9SJeff Roberson 		}
83636acfc65SAlexander Motin 	}
83762fa74d9SJeff Roberson }
83862fa74d9SJeff Roberson 
83962fa74d9SJeff Roberson static void
84062375ca8SEd Schouten sched_balance(void)
841356500a3SJeff Roberson {
8427fcf154aSJeff Roberson 	struct tdq *tdq;
843356500a3SJeff Roberson 
8447fcf154aSJeff Roberson 	/*
8457fcf154aSJeff Roberson 	 * Select a random time between .5 * balance_interval and
8467fcf154aSJeff Roberson 	 * 1.5 * balance_interval.
8477fcf154aSJeff Roberson 	 */
8487fcf154aSJeff Roberson 	balance_ticks = max(balance_interval / 2, 1);
8497fcf154aSJeff Roberson 	balance_ticks += random() % balance_interval;
850ae7a6b38SJeff Roberson 	if (smp_started == 0 || rebalance == 0)
851598b368dSJeff Roberson 		return;
8527fcf154aSJeff Roberson 	tdq = TDQ_SELF();
8537fcf154aSJeff Roberson 	TDQ_UNLOCK(tdq);
85462fa74d9SJeff Roberson 	sched_balance_group(cpu_top);
8557fcf154aSJeff Roberson 	TDQ_LOCK(tdq);
856cac77d04SJeff Roberson }
85786f8ae96SJeff Roberson 
858ae7a6b38SJeff Roberson /*
859ae7a6b38SJeff Roberson  * Lock two thread queues using their address to maintain lock order.
860ae7a6b38SJeff Roberson  */
861ae7a6b38SJeff Roberson static void
862ae7a6b38SJeff Roberson tdq_lock_pair(struct tdq *one, struct tdq *two)
863ae7a6b38SJeff Roberson {
864ae7a6b38SJeff Roberson 	if (one < two) {
865ae7a6b38SJeff Roberson 		TDQ_LOCK(one);
866ae7a6b38SJeff Roberson 		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
867ae7a6b38SJeff Roberson 	} else {
868ae7a6b38SJeff Roberson 		TDQ_LOCK(two);
869ae7a6b38SJeff Roberson 		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
870ae7a6b38SJeff Roberson 	}
871ae7a6b38SJeff Roberson }
872ae7a6b38SJeff Roberson 
873ae7a6b38SJeff Roberson /*
8747fcf154aSJeff Roberson  * Unlock two thread queues.  Order is not important here.
8757fcf154aSJeff Roberson  */
8767fcf154aSJeff Roberson static void
8777fcf154aSJeff Roberson tdq_unlock_pair(struct tdq *one, struct tdq *two)
8787fcf154aSJeff Roberson {
8797fcf154aSJeff Roberson 	TDQ_UNLOCK(one);
8807fcf154aSJeff Roberson 	TDQ_UNLOCK(two);
8817fcf154aSJeff Roberson }
8827fcf154aSJeff Roberson 
8837fcf154aSJeff Roberson /*
884ae7a6b38SJeff Roberson  * Transfer load between two imbalanced thread queues.
885ae7a6b38SJeff Roberson  */
88662fa74d9SJeff Roberson static int
887ad1e7d28SJulian Elischer sched_balance_pair(struct tdq *high, struct tdq *low)
888cac77d04SJeff Roberson {
88962fa74d9SJeff Roberson 	int moved;
890880bf8b9SMarius Strobl 	int cpu;
891cac77d04SJeff Roberson 
892ae7a6b38SJeff Roberson 	tdq_lock_pair(high, low);
89362fa74d9SJeff Roberson 	moved = 0;
894155b9987SJeff Roberson 	/*
895155b9987SJeff Roberson 	 * Determine what the imbalance is and then adjust that to how many
896d2ad694cSJeff Roberson 	 * threads we actually have to give up (transferable).
897155b9987SJeff Roberson 	 */
89836acfc65SAlexander Motin 	if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load &&
89936acfc65SAlexander Motin 	    (moved = tdq_move(high, low)) > 0) {
900a5423ea3SJeff Roberson 		/*
901880bf8b9SMarius Strobl 		 * In case the target isn't the current cpu IPI it to force a
902880bf8b9SMarius Strobl 		 * reschedule with the new workload.
903a5423ea3SJeff Roberson 		 */
904880bf8b9SMarius Strobl 		cpu = TDQ_ID(low);
905880bf8b9SMarius Strobl 		sched_pin();
906880bf8b9SMarius Strobl 		if (cpu != PCPU_GET(cpuid))
907880bf8b9SMarius Strobl 			ipi_cpu(cpu, IPI_PREEMPT);
908880bf8b9SMarius Strobl 		sched_unpin();
909ae7a6b38SJeff Roberson 	}
9107fcf154aSJeff Roberson 	tdq_unlock_pair(high, low);
91162fa74d9SJeff Roberson 	return (moved);
912356500a3SJeff Roberson }
913356500a3SJeff Roberson 
914ae7a6b38SJeff Roberson /*
915ae7a6b38SJeff Roberson  * Move a thread from one thread queue to another.
916ae7a6b38SJeff Roberson  */
91762fa74d9SJeff Roberson static int
918ae7a6b38SJeff Roberson tdq_move(struct tdq *from, struct tdq *to)
919356500a3SJeff Roberson {
920ad1e7d28SJulian Elischer 	struct td_sched *ts;
921ae7a6b38SJeff Roberson 	struct thread *td;
922ae7a6b38SJeff Roberson 	struct tdq *tdq;
923ae7a6b38SJeff Roberson 	int cpu;
924356500a3SJeff Roberson 
9257fcf154aSJeff Roberson 	TDQ_LOCK_ASSERT(from, MA_OWNED);
9267fcf154aSJeff Roberson 	TDQ_LOCK_ASSERT(to, MA_OWNED);
9277fcf154aSJeff Roberson 
928ad1e7d28SJulian Elischer 	tdq = from;
929ae7a6b38SJeff Roberson 	cpu = TDQ_ID(to);
9309727e637SJeff Roberson 	td = tdq_steal(tdq, cpu);
9319727e637SJeff Roberson 	if (td == NULL)
93262fa74d9SJeff Roberson 		return (0);
9339727e637SJeff Roberson 	ts = td->td_sched;
934ae7a6b38SJeff Roberson 	/*
935ae7a6b38SJeff Roberson 	 * Although the run queue is locked the thread may be blocked.  Lock
9367fcf154aSJeff Roberson 	 * it to clear this and acquire the run-queue lock.
937ae7a6b38SJeff Roberson 	 */
938ae7a6b38SJeff Roberson 	thread_lock(td);
9397fcf154aSJeff Roberson 	/* Drop recursive lock on from acquired via thread_lock(). */
940ae7a6b38SJeff Roberson 	TDQ_UNLOCK(from);
941ae7a6b38SJeff Roberson 	sched_rem(td);
9427b8bfa0dSJeff Roberson 	ts->ts_cpu = cpu;
943ae7a6b38SJeff Roberson 	td->td_lock = TDQ_LOCKPTR(to);
944ae7a6b38SJeff Roberson 	tdq_add(to, td, SRQ_YIELDING);
94562fa74d9SJeff Roberson 	return (1);
946356500a3SJeff Roberson }
94722bf7d9aSJeff Roberson 
948ae7a6b38SJeff Roberson /*
949ae7a6b38SJeff Roberson  * This tdq has idled.  Try to steal a thread from another cpu and switch
950ae7a6b38SJeff Roberson  * to it.
951ae7a6b38SJeff Roberson  */
95280f86c9fSJeff Roberson static int
953ad1e7d28SJulian Elischer tdq_idled(struct tdq *tdq)
95422bf7d9aSJeff Roberson {
95562fa74d9SJeff Roberson 	struct cpu_group *cg;
956ad1e7d28SJulian Elischer 	struct tdq *steal;
957c76ee827SJeff Roberson 	cpuset_t mask;
95862fa74d9SJeff Roberson 	int thresh;
959ae7a6b38SJeff Roberson 	int cpu;
96080f86c9fSJeff Roberson 
96188f530ccSJeff Roberson 	if (smp_started == 0 || steal_idle == 0)
96288f530ccSJeff Roberson 		return (1);
963c76ee827SJeff Roberson 	CPU_FILL(&mask);
964c76ee827SJeff Roberson 	CPU_CLR(PCPU_GET(cpuid), &mask);
96562fa74d9SJeff Roberson 	/* We don't want to be preempted while we're iterating. */
966ae7a6b38SJeff Roberson 	spinlock_enter();
96762fa74d9SJeff Roberson 	for (cg = tdq->tdq_cg; cg != NULL; ) {
9687b55ab05SJeff Roberson 		if ((cg->cg_flags & CG_FLAG_THREAD) == 0)
96962fa74d9SJeff Roberson 			thresh = steal_thresh;
97062fa74d9SJeff Roberson 		else
97162fa74d9SJeff Roberson 			thresh = 1;
97262fa74d9SJeff Roberson 		cpu = sched_highest(cg, mask, thresh);
97362fa74d9SJeff Roberson 		if (cpu == -1) {
97462fa74d9SJeff Roberson 			cg = cg->cg_parent;
97580f86c9fSJeff Roberson 			continue;
9767b8bfa0dSJeff Roberson 		}
9777b8bfa0dSJeff Roberson 		steal = TDQ_CPU(cpu);
978c76ee827SJeff Roberson 		CPU_CLR(cpu, &mask);
9797fcf154aSJeff Roberson 		tdq_lock_pair(tdq, steal);
98062fa74d9SJeff Roberson 		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
9817fcf154aSJeff Roberson 			tdq_unlock_pair(tdq, steal);
98262fa74d9SJeff Roberson 			continue;
98362fa74d9SJeff Roberson 		}
98462fa74d9SJeff Roberson 		/*
98562fa74d9SJeff Roberson 		 * If a thread was added while interrupts were disabled don't
98662fa74d9SJeff Roberson 		 * steal one here.  If we fail to acquire one due to affinity
98762fa74d9SJeff Roberson 		 * restrictions loop again with this cpu removed from the
98862fa74d9SJeff Roberson 		 * set.
98962fa74d9SJeff Roberson 		 */
99062fa74d9SJeff Roberson 		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
99162fa74d9SJeff Roberson 			tdq_unlock_pair(tdq, steal);
99262fa74d9SJeff Roberson 			continue;
99380f86c9fSJeff Roberson 		}
994ae7a6b38SJeff Roberson 		spinlock_exit();
995ae7a6b38SJeff Roberson 		TDQ_UNLOCK(steal);
9968df78c41SJeff Roberson 		mi_switch(SW_VOL | SWT_IDLE, NULL);
997ae7a6b38SJeff Roberson 		thread_unlock(curthread);
9987b8bfa0dSJeff Roberson 
9997b8bfa0dSJeff Roberson 		return (0);
100022bf7d9aSJeff Roberson 	}
100162fa74d9SJeff Roberson 	spinlock_exit();
100262fa74d9SJeff Roberson 	return (1);
100362fa74d9SJeff Roberson }
100422bf7d9aSJeff Roberson 
1005ae7a6b38SJeff Roberson /*
1006ae7a6b38SJeff Roberson  * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
1007ae7a6b38SJeff Roberson  */
100822bf7d9aSJeff Roberson static void
10099727e637SJeff Roberson tdq_notify(struct tdq *tdq, struct thread *td)
101022bf7d9aSJeff Roberson {
101102f0ff6dSJohn Baldwin 	struct thread *ctd;
1012fc3a97dcSJeff Roberson 	int pri;
10137b8bfa0dSJeff Roberson 	int cpu;
101422bf7d9aSJeff Roberson 
1015ff256d9cSJeff Roberson 	if (tdq->tdq_ipipending)
1016ff256d9cSJeff Roberson 		return;
10179727e637SJeff Roberson 	cpu = td->td_sched->ts_cpu;
10189727e637SJeff Roberson 	pri = td->td_priority;
101902f0ff6dSJohn Baldwin 	ctd = pcpu_find(cpu)->pc_curthread;
102002f0ff6dSJohn Baldwin 	if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
10216b2f763fSJeff Roberson 		return;
102202f0ff6dSJohn Baldwin 	if (TD_IS_IDLETHREAD(ctd)) {
10231690c6c1SJeff Roberson 		/*
10246c47aaaeSJeff Roberson 		 * If the MD code has an idle wakeup routine try that before
10256c47aaaeSJeff Roberson 		 * falling back to IPI.
10266c47aaaeSJeff Roberson 		 */
10279f9ad565SAlexander Motin 		if (!tdq->tdq_cpu_idle || cpu_idle_wakeup(cpu))
10286c47aaaeSJeff Roberson 			return;
10291690c6c1SJeff Roberson 	}
1030ff256d9cSJeff Roberson 	tdq->tdq_ipipending = 1;
1031d9d8d144SJohn Baldwin 	ipi_cpu(cpu, IPI_PREEMPT);
103222bf7d9aSJeff Roberson }
103322bf7d9aSJeff Roberson 
1034ae7a6b38SJeff Roberson /*
1035ae7a6b38SJeff Roberson  * Steals load from a timeshare queue.  Honors the rotating queue head
1036ae7a6b38SJeff Roberson  * index.
1037ae7a6b38SJeff Roberson  */
10389727e637SJeff Roberson static struct thread *
103962fa74d9SJeff Roberson runq_steal_from(struct runq *rq, int cpu, u_char start)
1040ae7a6b38SJeff Roberson {
1041ae7a6b38SJeff Roberson 	struct rqbits *rqb;
1042ae7a6b38SJeff Roberson 	struct rqhead *rqh;
104336acfc65SAlexander Motin 	struct thread *td, *first;
1044ae7a6b38SJeff Roberson 	int bit;
1045ae7a6b38SJeff Roberson 	int pri;
1046ae7a6b38SJeff Roberson 	int i;
1047ae7a6b38SJeff Roberson 
1048ae7a6b38SJeff Roberson 	rqb = &rq->rq_status;
1049ae7a6b38SJeff Roberson 	bit = start & (RQB_BPW -1);
1050ae7a6b38SJeff Roberson 	pri = 0;
105136acfc65SAlexander Motin 	first = NULL;
1052ae7a6b38SJeff Roberson again:
1053ae7a6b38SJeff Roberson 	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1054ae7a6b38SJeff Roberson 		if (rqb->rqb_bits[i] == 0)
1055ae7a6b38SJeff Roberson 			continue;
1056ae7a6b38SJeff Roberson 		if (bit != 0) {
1057ae7a6b38SJeff Roberson 			for (pri = bit; pri < RQB_BPW; pri++)
1058ae7a6b38SJeff Roberson 				if (rqb->rqb_bits[i] & (1ul << pri))
1059ae7a6b38SJeff Roberson 					break;
1060ae7a6b38SJeff Roberson 			if (pri >= RQB_BPW)
1061ae7a6b38SJeff Roberson 				continue;
1062ae7a6b38SJeff Roberson 		} else
1063ae7a6b38SJeff Roberson 			pri = RQB_FFS(rqb->rqb_bits[i]);
1064ae7a6b38SJeff Roberson 		pri += (i << RQB_L2BPW);
1065ae7a6b38SJeff Roberson 		rqh = &rq->rq_queues[pri];
10669727e637SJeff Roberson 		TAILQ_FOREACH(td, rqh, td_runq) {
10679727e637SJeff Roberson 			if (first && THREAD_CAN_MIGRATE(td) &&
10689727e637SJeff Roberson 			    THREAD_CAN_SCHED(td, cpu))
10699727e637SJeff Roberson 				return (td);
107036acfc65SAlexander Motin 			first = td;
1071ae7a6b38SJeff Roberson 		}
1072ae7a6b38SJeff Roberson 	}
1073ae7a6b38SJeff Roberson 	if (start != 0) {
1074ae7a6b38SJeff Roberson 		start = 0;
1075ae7a6b38SJeff Roberson 		goto again;
1076ae7a6b38SJeff Roberson 	}
1077ae7a6b38SJeff Roberson 
107836acfc65SAlexander Motin 	if (first && THREAD_CAN_MIGRATE(first) &&
107936acfc65SAlexander Motin 	    THREAD_CAN_SCHED(first, cpu))
108036acfc65SAlexander Motin 		return (first);
1081ae7a6b38SJeff Roberson 	return (NULL);
1082ae7a6b38SJeff Roberson }
1083ae7a6b38SJeff Roberson 
1084ae7a6b38SJeff Roberson /*
1085ae7a6b38SJeff Roberson  * Steals load from a standard linear queue.
1086ae7a6b38SJeff Roberson  */
10879727e637SJeff Roberson static struct thread *
108862fa74d9SJeff Roberson runq_steal(struct runq *rq, int cpu)
108922bf7d9aSJeff Roberson {
109022bf7d9aSJeff Roberson 	struct rqhead *rqh;
109122bf7d9aSJeff Roberson 	struct rqbits *rqb;
10929727e637SJeff Roberson 	struct thread *td;
109322bf7d9aSJeff Roberson 	int word;
109422bf7d9aSJeff Roberson 	int bit;
109522bf7d9aSJeff Roberson 
109622bf7d9aSJeff Roberson 	rqb = &rq->rq_status;
109722bf7d9aSJeff Roberson 	for (word = 0; word < RQB_LEN; word++) {
109822bf7d9aSJeff Roberson 		if (rqb->rqb_bits[word] == 0)
109922bf7d9aSJeff Roberson 			continue;
110022bf7d9aSJeff Roberson 		for (bit = 0; bit < RQB_BPW; bit++) {
1101a2640c9bSPeter Wemm 			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
110222bf7d9aSJeff Roberson 				continue;
110322bf7d9aSJeff Roberson 			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
11049727e637SJeff Roberson 			TAILQ_FOREACH(td, rqh, td_runq)
11059727e637SJeff Roberson 				if (THREAD_CAN_MIGRATE(td) &&
11069727e637SJeff Roberson 				    THREAD_CAN_SCHED(td, cpu))
11079727e637SJeff Roberson 					return (td);
110822bf7d9aSJeff Roberson 		}
110922bf7d9aSJeff Roberson 	}
111022bf7d9aSJeff Roberson 	return (NULL);
111122bf7d9aSJeff Roberson }
111222bf7d9aSJeff Roberson 
1113ae7a6b38SJeff Roberson /*
1114ae7a6b38SJeff Roberson  * Attempt to steal a thread in priority order from a thread queue.
1115ae7a6b38SJeff Roberson  */
11169727e637SJeff Roberson static struct thread *
111762fa74d9SJeff Roberson tdq_steal(struct tdq *tdq, int cpu)
111822bf7d9aSJeff Roberson {
11199727e637SJeff Roberson 	struct thread *td;
112022bf7d9aSJeff Roberson 
1121ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
11229727e637SJeff Roberson 	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
11239727e637SJeff Roberson 		return (td);
11249727e637SJeff Roberson 	if ((td = runq_steal_from(&tdq->tdq_timeshare,
11259727e637SJeff Roberson 	    cpu, tdq->tdq_ridx)) != NULL)
11269727e637SJeff Roberson 		return (td);
112762fa74d9SJeff Roberson 	return (runq_steal(&tdq->tdq_idle, cpu));
112822bf7d9aSJeff Roberson }
112980f86c9fSJeff Roberson 
1130ae7a6b38SJeff Roberson /*
1131ae7a6b38SJeff Roberson  * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
11327fcf154aSJeff Roberson  * current lock and returns with the assigned queue locked.
1133ae7a6b38SJeff Roberson  */
1134ae7a6b38SJeff Roberson static inline struct tdq *
11359727e637SJeff Roberson sched_setcpu(struct thread *td, int cpu, int flags)
113680f86c9fSJeff Roberson {
11379727e637SJeff Roberson 
1138ae7a6b38SJeff Roberson 	struct tdq *tdq;
113980f86c9fSJeff Roberson 
11409727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1141ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpu);
11429727e637SJeff Roberson 	td->td_sched->ts_cpu = cpu;
11439727e637SJeff Roberson 	/*
11449727e637SJeff Roberson 	 * If the lock matches just return the queue.
11459727e637SJeff Roberson 	 */
1146ae7a6b38SJeff Roberson 	if (td->td_lock == TDQ_LOCKPTR(tdq))
1147ae7a6b38SJeff Roberson 		return (tdq);
1148ae7a6b38SJeff Roberson #ifdef notyet
114980f86c9fSJeff Roberson 	/*
1150a5423ea3SJeff Roberson 	 * If the thread isn't running its lockptr is a
1151ae7a6b38SJeff Roberson 	 * turnstile or a sleepqueue.  We can just lock_set without
1152ae7a6b38SJeff Roberson 	 * blocking.
1153670c524fSJeff Roberson 	 */
1154ae7a6b38SJeff Roberson 	if (TD_CAN_RUN(td)) {
1155ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
1156ae7a6b38SJeff Roberson 		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1157ae7a6b38SJeff Roberson 		return (tdq);
1158ae7a6b38SJeff Roberson 	}
1159ae7a6b38SJeff Roberson #endif
116080f86c9fSJeff Roberson 	/*
1161ae7a6b38SJeff Roberson 	 * The hard case, migration, we need to block the thread first to
1162ae7a6b38SJeff Roberson 	 * prevent order reversals with other cpus locks.
11637b8bfa0dSJeff Roberson 	 */
1164b0b9dee5SAttilio Rao 	spinlock_enter();
1165ae7a6b38SJeff Roberson 	thread_lock_block(td);
1166ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
1167ae7a6b38SJeff Roberson 	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1168b0b9dee5SAttilio Rao 	spinlock_exit();
1169ae7a6b38SJeff Roberson 	return (tdq);
117080f86c9fSJeff Roberson }
11712454aaf5SJeff Roberson 
11728df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
11738df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
11748df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
11758df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
11768df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
11778df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
11788df78c41SJeff Roberson 
1179ae7a6b38SJeff Roberson static int
11809727e637SJeff Roberson sched_pickcpu(struct thread *td, int flags)
1181ae7a6b38SJeff Roberson {
118236acfc65SAlexander Motin 	struct cpu_group *cg, *ccg;
11839727e637SJeff Roberson 	struct td_sched *ts;
1184ae7a6b38SJeff Roberson 	struct tdq *tdq;
1185c76ee827SJeff Roberson 	cpuset_t mask;
118636acfc65SAlexander Motin 	int cpu, pri, self;
11877b8bfa0dSJeff Roberson 
118862fa74d9SJeff Roberson 	self = PCPU_GET(cpuid);
11899727e637SJeff Roberson 	ts = td->td_sched;
11907b8bfa0dSJeff Roberson 	if (smp_started == 0)
11917b8bfa0dSJeff Roberson 		return (self);
119228994a58SJeff Roberson 	/*
119328994a58SJeff Roberson 	 * Don't migrate a running thread from sched_switch().
119428994a58SJeff Roberson 	 */
119562fa74d9SJeff Roberson 	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
119662fa74d9SJeff Roberson 		return (ts->ts_cpu);
11977b8bfa0dSJeff Roberson 	/*
119862fa74d9SJeff Roberson 	 * Prefer to run interrupt threads on the processors that generate
119962fa74d9SJeff Roberson 	 * the interrupt.
12007b8bfa0dSJeff Roberson 	 */
120136acfc65SAlexander Motin 	pri = td->td_priority;
120262fa74d9SJeff Roberson 	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
12038df78c41SJeff Roberson 	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
12048df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_intrbind);
120562fa74d9SJeff Roberson 		ts->ts_cpu = self;
120636acfc65SAlexander Motin 		if (TDQ_CPU(self)->tdq_lowpri > pri) {
12078df78c41SJeff Roberson 			SCHED_STAT_INC(pickcpu_affinity);
12087b8bfa0dSJeff Roberson 			return (ts->ts_cpu);
12097b8bfa0dSJeff Roberson 		}
12108df78c41SJeff Roberson 	}
12117b8bfa0dSJeff Roberson 	/*
121236acfc65SAlexander Motin 	 * If the thread can run on the last cpu and the affinity has not
121336acfc65SAlexander Motin 	 * expired or it is idle run it there.
12147b8bfa0dSJeff Roberson 	 */
121536acfc65SAlexander Motin 	tdq = TDQ_CPU(ts->ts_cpu);
121636acfc65SAlexander Motin 	cg = tdq->tdq_cg;
121736acfc65SAlexander Motin 	if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
121836acfc65SAlexander Motin 	    tdq->tdq_lowpri >= PRI_MIN_IDLE &&
121936acfc65SAlexander Motin 	    SCHED_AFFINITY(ts, CG_SHARE_L2)) {
122036acfc65SAlexander Motin 		if (cg->cg_flags & CG_FLAG_THREAD) {
122136acfc65SAlexander Motin 			CPUSET_FOREACH(cpu, cg->cg_mask) {
122236acfc65SAlexander Motin 				if (TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE)
122362fa74d9SJeff Roberson 					break;
122436acfc65SAlexander Motin 			}
122536acfc65SAlexander Motin 		} else
122636acfc65SAlexander Motin 			cpu = INT_MAX;
122736acfc65SAlexander Motin 		if (cpu > mp_maxid) {
122836acfc65SAlexander Motin 			SCHED_STAT_INC(pickcpu_idle_affinity);
122936acfc65SAlexander Motin 			return (ts->ts_cpu);
123036acfc65SAlexander Motin 		}
123136acfc65SAlexander Motin 	}
123236acfc65SAlexander Motin 	/*
123336acfc65SAlexander Motin 	 * Search for the last level cache CPU group in the tree.
123436acfc65SAlexander Motin 	 * Skip caches with expired affinity time and SMT groups.
123536acfc65SAlexander Motin 	 * Affinity to higher level caches will be handled less aggressively.
123636acfc65SAlexander Motin 	 */
123736acfc65SAlexander Motin 	for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
123836acfc65SAlexander Motin 		if (cg->cg_flags & CG_FLAG_THREAD)
123936acfc65SAlexander Motin 			continue;
124036acfc65SAlexander Motin 		if (!SCHED_AFFINITY(ts, cg->cg_level))
124136acfc65SAlexander Motin 			continue;
124236acfc65SAlexander Motin 		ccg = cg;
124336acfc65SAlexander Motin 	}
124436acfc65SAlexander Motin 	if (ccg != NULL)
124536acfc65SAlexander Motin 		cg = ccg;
124662fa74d9SJeff Roberson 	cpu = -1;
124736acfc65SAlexander Motin 	/* Search the group for the less loaded idle CPU we can run now. */
1248c76ee827SJeff Roberson 	mask = td->td_cpuset->cs_mask;
124936acfc65SAlexander Motin 	if (cg != NULL && cg != cpu_top &&
125036acfc65SAlexander Motin 	    CPU_CMP(&cg->cg_mask, &cpu_top->cg_mask) != 0)
125136acfc65SAlexander Motin 		cpu = sched_lowest(cg, mask, max(pri, PRI_MAX_TIMESHARE),
125236acfc65SAlexander Motin 		    INT_MAX, ts->ts_cpu);
125336acfc65SAlexander Motin 	/* Search globally for the less loaded CPU we can run now. */
125462fa74d9SJeff Roberson 	if (cpu == -1)
125536acfc65SAlexander Motin 		cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu);
125636acfc65SAlexander Motin 	/* Search globally for the less loaded CPU. */
125736acfc65SAlexander Motin 	if (cpu == -1)
125836acfc65SAlexander Motin 		cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu);
12596022f0bcSAlexander Motin 	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
126062fa74d9SJeff Roberson 	/*
126162fa74d9SJeff Roberson 	 * Compare the lowest loaded cpu to current cpu.
126262fa74d9SJeff Roberson 	 */
1263ff256d9cSJeff Roberson 	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
126436acfc65SAlexander Motin 	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE &&
126536acfc65SAlexander Motin 	    TDQ_CPU(self)->tdq_load <= TDQ_CPU(cpu)->tdq_load + 1) {
12668df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_local);
126762fa74d9SJeff Roberson 		cpu = self;
12688df78c41SJeff Roberson 	} else
12698df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_lowest);
12708df78c41SJeff Roberson 	if (cpu != ts->ts_cpu)
12718df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_migration);
1272ae7a6b38SJeff Roberson 	return (cpu);
127380f86c9fSJeff Roberson }
127462fa74d9SJeff Roberson #endif
127522bf7d9aSJeff Roberson 
127622bf7d9aSJeff Roberson /*
127722bf7d9aSJeff Roberson  * Pick the highest priority task we have and return it.
12780c0a98b2SJeff Roberson  */
12799727e637SJeff Roberson static struct thread *
1280ad1e7d28SJulian Elischer tdq_choose(struct tdq *tdq)
12815d7ef00cSJeff Roberson {
12829727e637SJeff Roberson 	struct thread *td;
12835d7ef00cSJeff Roberson 
1284ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
12859727e637SJeff Roberson 	td = runq_choose(&tdq->tdq_realtime);
12869727e637SJeff Roberson 	if (td != NULL)
12879727e637SJeff Roberson 		return (td);
12889727e637SJeff Roberson 	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
12899727e637SJeff Roberson 	if (td != NULL) {
129012d56c0fSJohn Baldwin 		KASSERT(td->td_priority >= PRI_MIN_BATCH,
1291e7d50326SJeff Roberson 		    ("tdq_choose: Invalid priority on timeshare queue %d",
12929727e637SJeff Roberson 		    td->td_priority));
12939727e637SJeff Roberson 		return (td);
129415dc847eSJeff Roberson 	}
12959727e637SJeff Roberson 	td = runq_choose(&tdq->tdq_idle);
12969727e637SJeff Roberson 	if (td != NULL) {
12979727e637SJeff Roberson 		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1298e7d50326SJeff Roberson 		    ("tdq_choose: Invalid priority on idle queue %d",
12999727e637SJeff Roberson 		    td->td_priority));
13009727e637SJeff Roberson 		return (td);
1301e7d50326SJeff Roberson 	}
1302e7d50326SJeff Roberson 
1303e7d50326SJeff Roberson 	return (NULL);
1304245f3abfSJeff Roberson }
13050a016a05SJeff Roberson 
1306ae7a6b38SJeff Roberson /*
1307ae7a6b38SJeff Roberson  * Initialize a thread queue.
1308ae7a6b38SJeff Roberson  */
13090a016a05SJeff Roberson static void
1310ad1e7d28SJulian Elischer tdq_setup(struct tdq *tdq)
13110a016a05SJeff Roberson {
1312ae7a6b38SJeff Roberson 
1313c47f202bSJeff Roberson 	if (bootverbose)
1314c47f202bSJeff Roberson 		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1315e7d50326SJeff Roberson 	runq_init(&tdq->tdq_realtime);
1316e7d50326SJeff Roberson 	runq_init(&tdq->tdq_timeshare);
1317d2ad694cSJeff Roberson 	runq_init(&tdq->tdq_idle);
131862fa74d9SJeff Roberson 	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
131962fa74d9SJeff Roberson 	    "sched lock %d", (int)TDQ_ID(tdq));
132062fa74d9SJeff Roberson 	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
132162fa74d9SJeff Roberson 	    MTX_SPIN | MTX_RECURSE);
13228f51ad55SJeff Roberson #ifdef KTR
13238f51ad55SJeff Roberson 	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
13248f51ad55SJeff Roberson 	    "CPU %d load", (int)TDQ_ID(tdq));
13258f51ad55SJeff Roberson #endif
13260a016a05SJeff Roberson }
13270a016a05SJeff Roberson 
1328c47f202bSJeff Roberson #ifdef SMP
1329c47f202bSJeff Roberson static void
1330c47f202bSJeff Roberson sched_setup_smp(void)
1331c47f202bSJeff Roberson {
1332c47f202bSJeff Roberson 	struct tdq *tdq;
1333c47f202bSJeff Roberson 	int i;
1334c47f202bSJeff Roberson 
133562fa74d9SJeff Roberson 	cpu_top = smp_topo();
13363aa6d94eSJohn Baldwin 	CPU_FOREACH(i) {
133762fa74d9SJeff Roberson 		tdq = TDQ_CPU(i);
1338c47f202bSJeff Roberson 		tdq_setup(tdq);
133962fa74d9SJeff Roberson 		tdq->tdq_cg = smp_topo_find(cpu_top, i);
134062fa74d9SJeff Roberson 		if (tdq->tdq_cg == NULL)
134162fa74d9SJeff Roberson 			panic("Can't find cpu group for %d\n", i);
1342c47f202bSJeff Roberson 	}
134362fa74d9SJeff Roberson 	balance_tdq = TDQ_SELF();
134462fa74d9SJeff Roberson 	sched_balance();
1345c47f202bSJeff Roberson }
1346c47f202bSJeff Roberson #endif
1347c47f202bSJeff Roberson 
1348ae7a6b38SJeff Roberson /*
1349ae7a6b38SJeff Roberson  * Setup the thread queues and initialize the topology based on MD
1350ae7a6b38SJeff Roberson  * information.
1351ae7a6b38SJeff Roberson  */
135235e6168fSJeff Roberson static void
135335e6168fSJeff Roberson sched_setup(void *dummy)
135435e6168fSJeff Roberson {
1355ae7a6b38SJeff Roberson 	struct tdq *tdq;
1356c47f202bSJeff Roberson 
1357c47f202bSJeff Roberson 	tdq = TDQ_SELF();
13580ec896fdSJeff Roberson #ifdef SMP
1359c47f202bSJeff Roberson 	sched_setup_smp();
1360749d01b0SJeff Roberson #else
1361c47f202bSJeff Roberson 	tdq_setup(tdq);
1362356500a3SJeff Roberson #endif
1363ae7a6b38SJeff Roberson 	/*
1364ae7a6b38SJeff Roberson 	 * To avoid divide-by-zero, we set realstathz a dummy value
1365ae7a6b38SJeff Roberson 	 * in case which sched_clock() called before sched_initticks().
1366ae7a6b38SJeff Roberson 	 */
1367ae7a6b38SJeff Roberson 	realstathz = hz;
1368ae7a6b38SJeff Roberson 	sched_slice = (realstathz/10);	/* ~100ms */
1369ae7a6b38SJeff Roberson 	tickincr = 1 << SCHED_TICK_SHIFT;
1370ae7a6b38SJeff Roberson 
1371ae7a6b38SJeff Roberson 	/* Add thread0's load since it's running. */
1372ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
1373c47f202bSJeff Roberson 	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
13749727e637SJeff Roberson 	tdq_load_add(tdq, &thread0);
137562fa74d9SJeff Roberson 	tdq->tdq_lowpri = thread0.td_priority;
1376ae7a6b38SJeff Roberson 	TDQ_UNLOCK(tdq);
137735e6168fSJeff Roberson }
137835e6168fSJeff Roberson 
1379ae7a6b38SJeff Roberson /*
1380ae7a6b38SJeff Roberson  * This routine determines the tickincr after stathz and hz are setup.
1381ae7a6b38SJeff Roberson  */
1382a1d4fe69SDavid Xu /* ARGSUSED */
1383a1d4fe69SDavid Xu static void
1384a1d4fe69SDavid Xu sched_initticks(void *dummy)
1385a1d4fe69SDavid Xu {
1386ae7a6b38SJeff Roberson 	int incr;
1387ae7a6b38SJeff Roberson 
1388a1d4fe69SDavid Xu 	realstathz = stathz ? stathz : hz;
138914618990SJeff Roberson 	sched_slice = (realstathz/10);	/* ~100ms */
1390a1d4fe69SDavid Xu 
1391a1d4fe69SDavid Xu 	/*
1392e7d50326SJeff Roberson 	 * tickincr is shifted out by 10 to avoid rounding errors due to
13933f872f85SJeff Roberson 	 * hz not being evenly divisible by stathz on all platforms.
1394e7d50326SJeff Roberson 	 */
1395ae7a6b38SJeff Roberson 	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1396e7d50326SJeff Roberson 	/*
1397e7d50326SJeff Roberson 	 * This does not work for values of stathz that are more than
1398e7d50326SJeff Roberson 	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1399a1d4fe69SDavid Xu 	 */
1400ae7a6b38SJeff Roberson 	if (incr == 0)
1401ae7a6b38SJeff Roberson 		incr = 1;
1402ae7a6b38SJeff Roberson 	tickincr = incr;
14037b8bfa0dSJeff Roberson #ifdef SMP
14049862717aSJeff Roberson 	/*
14057fcf154aSJeff Roberson 	 * Set the default balance interval now that we know
14067fcf154aSJeff Roberson 	 * what realstathz is.
14077fcf154aSJeff Roberson 	 */
14087fcf154aSJeff Roberson 	balance_interval = realstathz;
14097fcf154aSJeff Roberson 	/*
141053a6c8b3SJeff Roberson 	 * Set steal thresh to roughly log2(mp_ncpu) but no greater than 4.
141153a6c8b3SJeff Roberson 	 * This prevents excess thrashing on large machines and excess idle
141253a6c8b3SJeff Roberson 	 * on smaller machines.
14139862717aSJeff Roberson 	 */
141453a6c8b3SJeff Roberson 	steal_thresh = min(fls(mp_ncpus) - 1, 3);
14157b8bfa0dSJeff Roberson 	affinity = SCHED_AFFINITY_DEFAULT;
14167b8bfa0dSJeff Roberson #endif
1417b3f40a41SAlexander Motin 	if (sched_idlespinthresh < 0)
1418b3f40a41SAlexander Motin 		sched_idlespinthresh = max(16, 2 * hz / realstathz);
1419a1d4fe69SDavid Xu }
1420a1d4fe69SDavid Xu 
1421a1d4fe69SDavid Xu 
142235e6168fSJeff Roberson /*
1423ae7a6b38SJeff Roberson  * This is the core of the interactivity algorithm.  Determines a score based
1424ae7a6b38SJeff Roberson  * on past behavior.  It is the ratio of sleep time to run time scaled to
1425ae7a6b38SJeff Roberson  * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1426ae7a6b38SJeff Roberson  * differs from the cpu usage because it does not account for time spent
1427ae7a6b38SJeff Roberson  * waiting on a run-queue.  Would be prettier if we had floating point.
1428ae7a6b38SJeff Roberson  */
1429ae7a6b38SJeff Roberson static int
1430ae7a6b38SJeff Roberson sched_interact_score(struct thread *td)
1431ae7a6b38SJeff Roberson {
1432ae7a6b38SJeff Roberson 	struct td_sched *ts;
1433ae7a6b38SJeff Roberson 	int div;
1434ae7a6b38SJeff Roberson 
1435ae7a6b38SJeff Roberson 	ts = td->td_sched;
1436ae7a6b38SJeff Roberson 	/*
1437ae7a6b38SJeff Roberson 	 * The score is only needed if this is likely to be an interactive
1438ae7a6b38SJeff Roberson 	 * task.  Don't go through the expense of computing it if there's
1439ae7a6b38SJeff Roberson 	 * no chance.
1440ae7a6b38SJeff Roberson 	 */
1441ae7a6b38SJeff Roberson 	if (sched_interact <= SCHED_INTERACT_HALF &&
1442ae7a6b38SJeff Roberson 		ts->ts_runtime >= ts->ts_slptime)
1443ae7a6b38SJeff Roberson 			return (SCHED_INTERACT_HALF);
1444ae7a6b38SJeff Roberson 
1445ae7a6b38SJeff Roberson 	if (ts->ts_runtime > ts->ts_slptime) {
1446ae7a6b38SJeff Roberson 		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1447ae7a6b38SJeff Roberson 		return (SCHED_INTERACT_HALF +
1448ae7a6b38SJeff Roberson 		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1449ae7a6b38SJeff Roberson 	}
1450ae7a6b38SJeff Roberson 	if (ts->ts_slptime > ts->ts_runtime) {
1451ae7a6b38SJeff Roberson 		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1452ae7a6b38SJeff Roberson 		return (ts->ts_runtime / div);
1453ae7a6b38SJeff Roberson 	}
1454ae7a6b38SJeff Roberson 	/* runtime == slptime */
1455ae7a6b38SJeff Roberson 	if (ts->ts_runtime)
1456ae7a6b38SJeff Roberson 		return (SCHED_INTERACT_HALF);
1457ae7a6b38SJeff Roberson 
1458ae7a6b38SJeff Roberson 	/*
1459ae7a6b38SJeff Roberson 	 * This can happen if slptime and runtime are 0.
1460ae7a6b38SJeff Roberson 	 */
1461ae7a6b38SJeff Roberson 	return (0);
1462ae7a6b38SJeff Roberson 
1463ae7a6b38SJeff Roberson }
1464ae7a6b38SJeff Roberson 
1465ae7a6b38SJeff Roberson /*
146635e6168fSJeff Roberson  * Scale the scheduling priority according to the "interactivity" of this
146735e6168fSJeff Roberson  * process.
146835e6168fSJeff Roberson  */
146915dc847eSJeff Roberson static void
14708460a577SJohn Birrell sched_priority(struct thread *td)
147135e6168fSJeff Roberson {
1472e7d50326SJeff Roberson 	int score;
147335e6168fSJeff Roberson 	int pri;
147435e6168fSJeff Roberson 
1475c9a8cba4SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
147615dc847eSJeff Roberson 		return;
1477e7d50326SJeff Roberson 	/*
1478e7d50326SJeff Roberson 	 * If the score is interactive we place the thread in the realtime
1479e7d50326SJeff Roberson 	 * queue with a priority that is less than kernel and interrupt
1480e7d50326SJeff Roberson 	 * priorities.  These threads are not subject to nice restrictions.
1481e7d50326SJeff Roberson 	 *
1482ae7a6b38SJeff Roberson 	 * Scores greater than this are placed on the normal timeshare queue
1483e7d50326SJeff Roberson 	 * where the priority is partially decided by the most recent cpu
1484e7d50326SJeff Roberson 	 * utilization and the rest is decided by nice value.
1485a5423ea3SJeff Roberson 	 *
1486a5423ea3SJeff Roberson 	 * The nice value of the process has a linear effect on the calculated
1487a5423ea3SJeff Roberson 	 * score.  Negative nice values make it easier for a thread to be
1488a5423ea3SJeff Roberson 	 * considered interactive.
1489e7d50326SJeff Roberson 	 */
1490a0f15352SJohn Baldwin 	score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1491e7d50326SJeff Roberson 	if (score < sched_interact) {
149212d56c0fSJohn Baldwin 		pri = PRI_MIN_INTERACT;
149312d56c0fSJohn Baldwin 		pri += ((PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) /
149478920008SJohn Baldwin 		    sched_interact) * score;
149512d56c0fSJohn Baldwin 		KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
14969a93305aSJeff Roberson 		    ("sched_priority: invalid interactive priority %d score %d",
14979a93305aSJeff Roberson 		    pri, score));
1498e7d50326SJeff Roberson 	} else {
1499e7d50326SJeff Roberson 		pri = SCHED_PRI_MIN;
1500e7d50326SJeff Roberson 		if (td->td_sched->ts_ticks)
15010c0d27d5SJohn Baldwin 			pri += min(SCHED_PRI_TICKS(td->td_sched),
15020c0d27d5SJohn Baldwin 			    SCHED_PRI_RANGE);
1503e7d50326SJeff Roberson 		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
150412d56c0fSJohn Baldwin 		KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
1505ae7a6b38SJeff Roberson 		    ("sched_priority: invalid priority %d: nice %d, "
1506ae7a6b38SJeff Roberson 		    "ticks %d ftick %d ltick %d tick pri %d",
1507ae7a6b38SJeff Roberson 		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1508ae7a6b38SJeff Roberson 		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1509ae7a6b38SJeff Roberson 		    SCHED_PRI_TICKS(td->td_sched)));
1510e7d50326SJeff Roberson 	}
15118460a577SJohn Birrell 	sched_user_prio(td, pri);
151235e6168fSJeff Roberson 
151315dc847eSJeff Roberson 	return;
151435e6168fSJeff Roberson }
151535e6168fSJeff Roberson 
151635e6168fSJeff Roberson /*
1517d322132cSJeff Roberson  * This routine enforces a maximum limit on the amount of scheduling history
1518ae7a6b38SJeff Roberson  * kept.  It is called after either the slptime or runtime is adjusted.  This
1519ae7a6b38SJeff Roberson  * function is ugly due to integer math.
1520d322132cSJeff Roberson  */
15214b60e324SJeff Roberson static void
15228460a577SJohn Birrell sched_interact_update(struct thread *td)
15234b60e324SJeff Roberson {
1524155b6ca1SJeff Roberson 	struct td_sched *ts;
15259a93305aSJeff Roberson 	u_int sum;
15263f741ca1SJeff Roberson 
1527155b6ca1SJeff Roberson 	ts = td->td_sched;
1528ae7a6b38SJeff Roberson 	sum = ts->ts_runtime + ts->ts_slptime;
1529d322132cSJeff Roberson 	if (sum < SCHED_SLP_RUN_MAX)
1530d322132cSJeff Roberson 		return;
1531d322132cSJeff Roberson 	/*
1532155b6ca1SJeff Roberson 	 * This only happens from two places:
1533155b6ca1SJeff Roberson 	 * 1) We have added an unusual amount of run time from fork_exit.
1534155b6ca1SJeff Roberson 	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1535155b6ca1SJeff Roberson 	 */
1536155b6ca1SJeff Roberson 	if (sum > SCHED_SLP_RUN_MAX * 2) {
1537ae7a6b38SJeff Roberson 		if (ts->ts_runtime > ts->ts_slptime) {
1538ae7a6b38SJeff Roberson 			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1539ae7a6b38SJeff Roberson 			ts->ts_slptime = 1;
1540155b6ca1SJeff Roberson 		} else {
1541ae7a6b38SJeff Roberson 			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1542ae7a6b38SJeff Roberson 			ts->ts_runtime = 1;
1543155b6ca1SJeff Roberson 		}
1544155b6ca1SJeff Roberson 		return;
1545155b6ca1SJeff Roberson 	}
1546155b6ca1SJeff Roberson 	/*
1547d322132cSJeff Roberson 	 * If we have exceeded by more than 1/5th then the algorithm below
1548d322132cSJeff Roberson 	 * will not bring us back into range.  Dividing by two here forces
15492454aaf5SJeff Roberson 	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1550d322132cSJeff Roberson 	 */
155137a35e4aSJeff Roberson 	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1552ae7a6b38SJeff Roberson 		ts->ts_runtime /= 2;
1553ae7a6b38SJeff Roberson 		ts->ts_slptime /= 2;
1554d322132cSJeff Roberson 		return;
1555d322132cSJeff Roberson 	}
1556ae7a6b38SJeff Roberson 	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1557ae7a6b38SJeff Roberson 	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1558d322132cSJeff Roberson }
1559d322132cSJeff Roberson 
1560ae7a6b38SJeff Roberson /*
1561ae7a6b38SJeff Roberson  * Scale back the interactivity history when a child thread is created.  The
1562ae7a6b38SJeff Roberson  * history is inherited from the parent but the thread may behave totally
1563ae7a6b38SJeff Roberson  * differently.  For example, a shell spawning a compiler process.  We want
1564ae7a6b38SJeff Roberson  * to learn that the compiler is behaving badly very quickly.
1565ae7a6b38SJeff Roberson  */
1566d322132cSJeff Roberson static void
15678460a577SJohn Birrell sched_interact_fork(struct thread *td)
1568d322132cSJeff Roberson {
1569d322132cSJeff Roberson 	int ratio;
1570d322132cSJeff Roberson 	int sum;
1571d322132cSJeff Roberson 
1572ae7a6b38SJeff Roberson 	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1573d322132cSJeff Roberson 	if (sum > SCHED_SLP_RUN_FORK) {
1574d322132cSJeff Roberson 		ratio = sum / SCHED_SLP_RUN_FORK;
1575ae7a6b38SJeff Roberson 		td->td_sched->ts_runtime /= ratio;
1576ae7a6b38SJeff Roberson 		td->td_sched->ts_slptime /= ratio;
15774b60e324SJeff Roberson 	}
15784b60e324SJeff Roberson }
15794b60e324SJeff Roberson 
158015dc847eSJeff Roberson /*
1581ae7a6b38SJeff Roberson  * Called from proc0_init() to setup the scheduler fields.
1582ed062c8dSJulian Elischer  */
1583ed062c8dSJulian Elischer void
1584ed062c8dSJulian Elischer schedinit(void)
1585ed062c8dSJulian Elischer {
1586e7d50326SJeff Roberson 
1587ed062c8dSJulian Elischer 	/*
1588ed062c8dSJulian Elischer 	 * Set up the scheduler specific parts of proc0.
1589ed062c8dSJulian Elischer 	 */
1590ed062c8dSJulian Elischer 	proc0.p_sched = NULL; /* XXX */
1591ad1e7d28SJulian Elischer 	thread0.td_sched = &td_sched0;
1592e7d50326SJeff Roberson 	td_sched0.ts_ltick = ticks;
15938ab80cf0SJeff Roberson 	td_sched0.ts_ftick = ticks;
159473daf66fSJeff Roberson 	td_sched0.ts_slice = sched_slice;
1595ed062c8dSJulian Elischer }
1596ed062c8dSJulian Elischer 
1597ed062c8dSJulian Elischer /*
159815dc847eSJeff Roberson  * This is only somewhat accurate since given many processes of the same
159915dc847eSJeff Roberson  * priority they will switch when their slices run out, which will be
1600e7d50326SJeff Roberson  * at most sched_slice stathz ticks.
160115dc847eSJeff Roberson  */
160235e6168fSJeff Roberson int
160335e6168fSJeff Roberson sched_rr_interval(void)
160435e6168fSJeff Roberson {
1605e7d50326SJeff Roberson 
1606e7d50326SJeff Roberson 	/* Convert sched_slice to hz */
1607e7d50326SJeff Roberson 	return (hz/(realstathz/sched_slice));
160835e6168fSJeff Roberson }
160935e6168fSJeff Roberson 
1610ae7a6b38SJeff Roberson /*
1611ae7a6b38SJeff Roberson  * Update the percent cpu tracking information when it is requested or
1612ae7a6b38SJeff Roberson  * the total history exceeds the maximum.  We keep a sliding history of
1613ae7a6b38SJeff Roberson  * tick counts that slowly decays.  This is less precise than the 4BSD
1614ae7a6b38SJeff Roberson  * mechanism since it happens with less regular and frequent events.
1615ae7a6b38SJeff Roberson  */
161622bf7d9aSJeff Roberson static void
16177295465eSAlexander Motin sched_pctcpu_update(struct td_sched *ts, int run)
161835e6168fSJeff Roberson {
16197295465eSAlexander Motin 	int t = ticks;
1620e7d50326SJeff Roberson 
16217295465eSAlexander Motin 	if (t - ts->ts_ltick >= SCHED_TICK_TARG) {
1622ad1e7d28SJulian Elischer 		ts->ts_ticks = 0;
16237295465eSAlexander Motin 		ts->ts_ftick = t - SCHED_TICK_TARG;
16247295465eSAlexander Motin 	} else if (t - ts->ts_ftick >= SCHED_TICK_MAX) {
16257295465eSAlexander Motin 		ts->ts_ticks = (ts->ts_ticks / (ts->ts_ltick - ts->ts_ftick)) *
16267295465eSAlexander Motin 		    (ts->ts_ltick - (t - SCHED_TICK_TARG));
16277295465eSAlexander Motin 		ts->ts_ftick = t - SCHED_TICK_TARG;
16287295465eSAlexander Motin 	}
16297295465eSAlexander Motin 	if (run)
16307295465eSAlexander Motin 		ts->ts_ticks += (t - ts->ts_ltick) << SCHED_TICK_SHIFT;
16317295465eSAlexander Motin 	ts->ts_ltick = t;
163235e6168fSJeff Roberson }
163335e6168fSJeff Roberson 
1634ae7a6b38SJeff Roberson /*
1635ae7a6b38SJeff Roberson  * Adjust the priority of a thread.  Move it to the appropriate run-queue
1636ae7a6b38SJeff Roberson  * if necessary.  This is the back-end for several priority related
1637ae7a6b38SJeff Roberson  * functions.
1638ae7a6b38SJeff Roberson  */
1639e7d50326SJeff Roberson static void
1640f5c157d9SJohn Baldwin sched_thread_priority(struct thread *td, u_char prio)
164135e6168fSJeff Roberson {
1642ad1e7d28SJulian Elischer 	struct td_sched *ts;
164373daf66fSJeff Roberson 	struct tdq *tdq;
164473daf66fSJeff Roberson 	int oldpri;
164535e6168fSJeff Roberson 
16468f51ad55SJeff Roberson 	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
16478f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, "new prio:%d", prio,
16488f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(curthread));
1649*b3e9e682SRyan Stone 	SDT_PROBE3(sched, , , change_pri, td, td->td_proc, prio);
16508f51ad55SJeff Roberson 	if (td != curthread && prio > td->td_priority) {
16518f51ad55SJeff Roberson 		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
16528f51ad55SJeff Roberson 		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
16538f51ad55SJeff Roberson 		    prio, KTR_ATTR_LINKED, sched_tdname(td));
1654*b3e9e682SRyan Stone 		SDT_PROBE4(sched, , , lend_pri, td, td->td_proc, prio,
1655*b3e9e682SRyan Stone 		    curthread);
16568f51ad55SJeff Roberson 	}
1657ad1e7d28SJulian Elischer 	ts = td->td_sched;
16587b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1659f5c157d9SJohn Baldwin 	if (td->td_priority == prio)
1660f5c157d9SJohn Baldwin 		return;
16613f741ca1SJeff Roberson 	/*
16623f741ca1SJeff Roberson 	 * If the priority has been elevated due to priority
16633f741ca1SJeff Roberson 	 * propagation, we may have to move ourselves to a new
1664e7d50326SJeff Roberson 	 * queue.  This could be optimized to not re-add in some
1665e7d50326SJeff Roberson 	 * cases.
1666f2b74cbfSJeff Roberson 	 */
16676d55b3ecSJeff Roberson 	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1668e7d50326SJeff Roberson 		sched_rem(td);
1669e7d50326SJeff Roberson 		td->td_priority = prio;
1670ae7a6b38SJeff Roberson 		sched_add(td, SRQ_BORROWING);
167173daf66fSJeff Roberson 		return;
167273daf66fSJeff Roberson 	}
16736d55b3ecSJeff Roberson 	/*
16746d55b3ecSJeff Roberson 	 * If the thread is currently running we may have to adjust the lowpri
16756d55b3ecSJeff Roberson 	 * information so other cpus are aware of our current priority.
16766d55b3ecSJeff Roberson 	 */
16776d55b3ecSJeff Roberson 	if (TD_IS_RUNNING(td)) {
1678ae7a6b38SJeff Roberson 		tdq = TDQ_CPU(ts->ts_cpu);
167962fa74d9SJeff Roberson 		oldpri = td->td_priority;
16803f741ca1SJeff Roberson 		td->td_priority = prio;
168162fa74d9SJeff Roberson 		if (prio < tdq->tdq_lowpri)
168262fa74d9SJeff Roberson 			tdq->tdq_lowpri = prio;
168362fa74d9SJeff Roberson 		else if (tdq->tdq_lowpri == oldpri)
168462fa74d9SJeff Roberson 			tdq_setlowpri(tdq, td);
16856d55b3ecSJeff Roberson 		return;
168673daf66fSJeff Roberson 	}
16876d55b3ecSJeff Roberson 	td->td_priority = prio;
1688ae7a6b38SJeff Roberson }
168935e6168fSJeff Roberson 
1690f5c157d9SJohn Baldwin /*
1691f5c157d9SJohn Baldwin  * Update a thread's priority when it is lent another thread's
1692f5c157d9SJohn Baldwin  * priority.
1693f5c157d9SJohn Baldwin  */
1694f5c157d9SJohn Baldwin void
1695f5c157d9SJohn Baldwin sched_lend_prio(struct thread *td, u_char prio)
1696f5c157d9SJohn Baldwin {
1697f5c157d9SJohn Baldwin 
1698f5c157d9SJohn Baldwin 	td->td_flags |= TDF_BORROWING;
1699f5c157d9SJohn Baldwin 	sched_thread_priority(td, prio);
1700f5c157d9SJohn Baldwin }
1701f5c157d9SJohn Baldwin 
1702f5c157d9SJohn Baldwin /*
1703f5c157d9SJohn Baldwin  * Restore a thread's priority when priority propagation is
1704f5c157d9SJohn Baldwin  * over.  The prio argument is the minimum priority the thread
1705f5c157d9SJohn Baldwin  * needs to have to satisfy other possible priority lending
1706f5c157d9SJohn Baldwin  * requests.  If the thread's regular priority is less
1707f5c157d9SJohn Baldwin  * important than prio, the thread will keep a priority boost
1708f5c157d9SJohn Baldwin  * of prio.
1709f5c157d9SJohn Baldwin  */
1710f5c157d9SJohn Baldwin void
1711f5c157d9SJohn Baldwin sched_unlend_prio(struct thread *td, u_char prio)
1712f5c157d9SJohn Baldwin {
1713f5c157d9SJohn Baldwin 	u_char base_pri;
1714f5c157d9SJohn Baldwin 
1715f5c157d9SJohn Baldwin 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1716f5c157d9SJohn Baldwin 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
17178460a577SJohn Birrell 		base_pri = td->td_user_pri;
1718f5c157d9SJohn Baldwin 	else
1719f5c157d9SJohn Baldwin 		base_pri = td->td_base_pri;
1720f5c157d9SJohn Baldwin 	if (prio >= base_pri) {
1721f5c157d9SJohn Baldwin 		td->td_flags &= ~TDF_BORROWING;
1722f5c157d9SJohn Baldwin 		sched_thread_priority(td, base_pri);
1723f5c157d9SJohn Baldwin 	} else
1724f5c157d9SJohn Baldwin 		sched_lend_prio(td, prio);
1725f5c157d9SJohn Baldwin }
1726f5c157d9SJohn Baldwin 
1727ae7a6b38SJeff Roberson /*
1728ae7a6b38SJeff Roberson  * Standard entry for setting the priority to an absolute value.
1729ae7a6b38SJeff Roberson  */
1730f5c157d9SJohn Baldwin void
1731f5c157d9SJohn Baldwin sched_prio(struct thread *td, u_char prio)
1732f5c157d9SJohn Baldwin {
1733f5c157d9SJohn Baldwin 	u_char oldprio;
1734f5c157d9SJohn Baldwin 
1735f5c157d9SJohn Baldwin 	/* First, update the base priority. */
1736f5c157d9SJohn Baldwin 	td->td_base_pri = prio;
1737f5c157d9SJohn Baldwin 
1738f5c157d9SJohn Baldwin 	/*
173950aaa791SJohn Baldwin 	 * If the thread is borrowing another thread's priority, don't
1740f5c157d9SJohn Baldwin 	 * ever lower the priority.
1741f5c157d9SJohn Baldwin 	 */
1742f5c157d9SJohn Baldwin 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1743f5c157d9SJohn Baldwin 		return;
1744f5c157d9SJohn Baldwin 
1745f5c157d9SJohn Baldwin 	/* Change the real priority. */
1746f5c157d9SJohn Baldwin 	oldprio = td->td_priority;
1747f5c157d9SJohn Baldwin 	sched_thread_priority(td, prio);
1748f5c157d9SJohn Baldwin 
1749f5c157d9SJohn Baldwin 	/*
1750f5c157d9SJohn Baldwin 	 * If the thread is on a turnstile, then let the turnstile update
1751f5c157d9SJohn Baldwin 	 * its state.
1752f5c157d9SJohn Baldwin 	 */
1753f5c157d9SJohn Baldwin 	if (TD_ON_LOCK(td) && oldprio != prio)
1754f5c157d9SJohn Baldwin 		turnstile_adjust(td, oldprio);
1755f5c157d9SJohn Baldwin }
1756f5c157d9SJohn Baldwin 
1757ae7a6b38SJeff Roberson /*
1758ae7a6b38SJeff Roberson  * Set the base user priority, does not effect current running priority.
1759ae7a6b38SJeff Roberson  */
176035e6168fSJeff Roberson void
17618460a577SJohn Birrell sched_user_prio(struct thread *td, u_char prio)
17623db720fdSDavid Xu {
17633db720fdSDavid Xu 
17648460a577SJohn Birrell 	td->td_base_user_pri = prio;
1765acbe332aSDavid Xu 	if (td->td_lend_user_pri <= prio)
1766fc6c30f6SJulian Elischer 		return;
17678460a577SJohn Birrell 	td->td_user_pri = prio;
17683db720fdSDavid Xu }
17693db720fdSDavid Xu 
17703db720fdSDavid Xu void
17713db720fdSDavid Xu sched_lend_user_prio(struct thread *td, u_char prio)
17723db720fdSDavid Xu {
17733db720fdSDavid Xu 
1774435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1775acbe332aSDavid Xu 	td->td_lend_user_pri = prio;
1776c8e368a9SDavid Xu 	td->td_user_pri = min(prio, td->td_base_user_pri);
1777c8e368a9SDavid Xu 	if (td->td_priority > td->td_user_pri)
1778c8e368a9SDavid Xu 		sched_prio(td, td->td_user_pri);
1779c8e368a9SDavid Xu 	else if (td->td_priority != td->td_user_pri)
1780c8e368a9SDavid Xu 		td->td_flags |= TDF_NEEDRESCHED;
1781435806d3SDavid Xu }
17823db720fdSDavid Xu 
1783ae7a6b38SJeff Roberson /*
1784c47f202bSJeff Roberson  * Handle migration from sched_switch().  This happens only for
1785c47f202bSJeff Roberson  * cpu binding.
1786c47f202bSJeff Roberson  */
1787c47f202bSJeff Roberson static struct mtx *
1788c47f202bSJeff Roberson sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1789c47f202bSJeff Roberson {
1790c47f202bSJeff Roberson 	struct tdq *tdn;
1791c47f202bSJeff Roberson 
1792c47f202bSJeff Roberson 	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1793c47f202bSJeff Roberson #ifdef SMP
17949727e637SJeff Roberson 	tdq_load_rem(tdq, td);
1795c47f202bSJeff Roberson 	/*
1796c47f202bSJeff Roberson 	 * Do the lock dance required to avoid LOR.  We grab an extra
1797c47f202bSJeff Roberson 	 * spinlock nesting to prevent preemption while we're
1798c47f202bSJeff Roberson 	 * not holding either run-queue lock.
1799c47f202bSJeff Roberson 	 */
1800c47f202bSJeff Roberson 	spinlock_enter();
1801b0b9dee5SAttilio Rao 	thread_lock_block(td);	/* This releases the lock on tdq. */
1802435068aaSAttilio Rao 
1803435068aaSAttilio Rao 	/*
1804435068aaSAttilio Rao 	 * Acquire both run-queue locks before placing the thread on the new
1805435068aaSAttilio Rao 	 * run-queue to avoid deadlocks created by placing a thread with a
1806435068aaSAttilio Rao 	 * blocked lock on the run-queue of a remote processor.  The deadlock
1807435068aaSAttilio Rao 	 * occurs when a third processor attempts to lock the two queues in
1808435068aaSAttilio Rao 	 * question while the target processor is spinning with its own
1809435068aaSAttilio Rao 	 * run-queue lock held while waiting for the blocked lock to clear.
1810435068aaSAttilio Rao 	 */
1811435068aaSAttilio Rao 	tdq_lock_pair(tdn, tdq);
1812c47f202bSJeff Roberson 	tdq_add(tdn, td, flags);
18139727e637SJeff Roberson 	tdq_notify(tdn, td);
1814c47f202bSJeff Roberson 	TDQ_UNLOCK(tdn);
1815c47f202bSJeff Roberson 	spinlock_exit();
1816c47f202bSJeff Roberson #endif
1817c47f202bSJeff Roberson 	return (TDQ_LOCKPTR(tdn));
1818c47f202bSJeff Roberson }
1819c47f202bSJeff Roberson 
1820c47f202bSJeff Roberson /*
1821b0b9dee5SAttilio Rao  * Variadic version of thread_lock_unblock() that does not assume td_lock
1822b0b9dee5SAttilio Rao  * is blocked.
1823ae7a6b38SJeff Roberson  */
1824ae7a6b38SJeff Roberson static inline void
1825ae7a6b38SJeff Roberson thread_unblock_switch(struct thread *td, struct mtx *mtx)
1826ae7a6b38SJeff Roberson {
1827ae7a6b38SJeff Roberson 	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1828ae7a6b38SJeff Roberson 	    (uintptr_t)mtx);
1829ae7a6b38SJeff Roberson }
1830ae7a6b38SJeff Roberson 
1831ae7a6b38SJeff Roberson /*
1832ae7a6b38SJeff Roberson  * Switch threads.  This function has to handle threads coming in while
1833ae7a6b38SJeff Roberson  * blocked for some reason, running, or idle.  It also must deal with
1834ae7a6b38SJeff Roberson  * migrating a thread from one queue to another as running threads may
1835ae7a6b38SJeff Roberson  * be assigned elsewhere via binding.
1836ae7a6b38SJeff Roberson  */
18373db720fdSDavid Xu void
18383389af30SJulian Elischer sched_switch(struct thread *td, struct thread *newtd, int flags)
183935e6168fSJeff Roberson {
1840c02bbb43SJeff Roberson 	struct tdq *tdq;
1841ad1e7d28SJulian Elischer 	struct td_sched *ts;
1842ae7a6b38SJeff Roberson 	struct mtx *mtx;
1843c47f202bSJeff Roberson 	int srqflag;
1844ae7a6b38SJeff Roberson 	int cpuid;
184535e6168fSJeff Roberson 
18467b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
18476d55b3ecSJeff Roberson 	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
184835e6168fSJeff Roberson 
1849ae7a6b38SJeff Roberson 	cpuid = PCPU_GET(cpuid);
1850ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpuid);
1851e7d50326SJeff Roberson 	ts = td->td_sched;
1852c47f202bSJeff Roberson 	mtx = td->td_lock;
18537295465eSAlexander Motin 	sched_pctcpu_update(ts, 1);
1854ae7a6b38SJeff Roberson 	ts->ts_rltick = ticks;
1855060563ecSJulian Elischer 	td->td_lastcpu = td->td_oncpu;
1856060563ecSJulian Elischer 	td->td_oncpu = NOCPU;
1857586cb6ecSFabien Thomas 	if (!(flags & SW_PREEMPT))
185852eb8464SJohn Baldwin 		td->td_flags &= ~TDF_NEEDRESCHED;
185977918643SStephan Uphoff 	td->td_owepreempt = 0;
18601690c6c1SJeff Roberson 	tdq->tdq_switchcnt++;
1861b11fdad0SJeff Roberson 	/*
1862ae7a6b38SJeff Roberson 	 * The lock pointer in an idle thread should never change.  Reset it
1863ae7a6b38SJeff Roberson 	 * to CAN_RUN as well.
1864b11fdad0SJeff Roberson 	 */
1865486a9414SJulian Elischer 	if (TD_IS_IDLETHREAD(td)) {
1866ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1867bf0acc27SJohn Baldwin 		TD_SET_CAN_RUN(td);
18687b20fb19SJeff Roberson 	} else if (TD_IS_RUNNING(td)) {
1869ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1870c47f202bSJeff Roberson 		srqflag = (flags & SW_PREEMPT) ?
1871598b368dSJeff Roberson 		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1872c47f202bSJeff Roberson 		    SRQ_OURSELF|SRQ_YIELDING;
1873ba4932b5SMatthew D Fleming #ifdef SMP
18740f7a0ebdSMatthew D Fleming 		if (THREAD_CAN_MIGRATE(td) && !THREAD_CAN_SCHED(td, ts->ts_cpu))
18750f7a0ebdSMatthew D Fleming 			ts->ts_cpu = sched_pickcpu(td, 0);
1876ba4932b5SMatthew D Fleming #endif
1877c47f202bSJeff Roberson 		if (ts->ts_cpu == cpuid)
18789727e637SJeff Roberson 			tdq_runq_add(tdq, td, srqflag);
18790f7a0ebdSMatthew D Fleming 		else {
18800f7a0ebdSMatthew D Fleming 			KASSERT(THREAD_CAN_MIGRATE(td) ||
18810f7a0ebdSMatthew D Fleming 			    (ts->ts_flags & TSF_BOUND) != 0,
18820f7a0ebdSMatthew D Fleming 			    ("Thread %p shouldn't migrate", td));
1883c47f202bSJeff Roberson 			mtx = sched_switch_migrate(tdq, td, srqflag);
18840f7a0ebdSMatthew D Fleming 		}
1885ae7a6b38SJeff Roberson 	} else {
1886ae7a6b38SJeff Roberson 		/* This thread must be going to sleep. */
1887ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
1888b0b9dee5SAttilio Rao 		mtx = thread_lock_block(td);
18899727e637SJeff Roberson 		tdq_load_rem(tdq, td);
1890ae7a6b38SJeff Roberson 	}
1891ae7a6b38SJeff Roberson 	/*
1892ae7a6b38SJeff Roberson 	 * We enter here with the thread blocked and assigned to the
1893ae7a6b38SJeff Roberson 	 * appropriate cpu run-queue or sleep-queue and with the current
1894ae7a6b38SJeff Roberson 	 * thread-queue locked.
1895ae7a6b38SJeff Roberson 	 */
1896ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
18972454aaf5SJeff Roberson 	newtd = choosethread();
1898ae7a6b38SJeff Roberson 	/*
1899ae7a6b38SJeff Roberson 	 * Call the MD code to switch contexts if necessary.
1900ae7a6b38SJeff Roberson 	 */
1901ebccf1e3SJoseph Koshy 	if (td != newtd) {
1902ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1903ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1904ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1905ebccf1e3SJoseph Koshy #endif
1906*b3e9e682SRyan Stone 		SDT_PROBE2(sched, , , off_cpu, td, td->td_proc);
1907eea4f254SJeff Roberson 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
190859c68134SJeff Roberson 		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
19097295465eSAlexander Motin 		sched_pctcpu_update(newtd->td_sched, 0);
19106f5f25e5SJohn Birrell 
19116f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
19126f5f25e5SJohn Birrell 		/*
19136f5f25e5SJohn Birrell 		 * If DTrace has set the active vtime enum to anything
19146f5f25e5SJohn Birrell 		 * other than INACTIVE (0), then it should have set the
19156f5f25e5SJohn Birrell 		 * function to call.
19166f5f25e5SJohn Birrell 		 */
19176f5f25e5SJohn Birrell 		if (dtrace_vtime_active)
19186f5f25e5SJohn Birrell 			(*dtrace_vtime_switch_func)(newtd);
19196f5f25e5SJohn Birrell #endif
19206f5f25e5SJohn Birrell 
1921ae7a6b38SJeff Roberson 		cpu_switch(td, newtd, mtx);
1922ae7a6b38SJeff Roberson 		/*
1923ae7a6b38SJeff Roberson 		 * We may return from cpu_switch on a different cpu.  However,
1924ae7a6b38SJeff Roberson 		 * we always return with td_lock pointing to the current cpu's
1925ae7a6b38SJeff Roberson 		 * run queue lock.
1926ae7a6b38SJeff Roberson 		 */
1927ae7a6b38SJeff Roberson 		cpuid = PCPU_GET(cpuid);
1928ae7a6b38SJeff Roberson 		tdq = TDQ_CPU(cpuid);
1929eea4f254SJeff Roberson 		lock_profile_obtain_lock_success(
1930eea4f254SJeff Roberson 		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1931*b3e9e682SRyan Stone 
1932*b3e9e682SRyan Stone 		SDT_PROBE0(sched, , , on_cpu);
1933ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1934ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1935ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1936ebccf1e3SJoseph Koshy #endif
1937*b3e9e682SRyan Stone 	} else {
1938ae7a6b38SJeff Roberson 		thread_unblock_switch(td, mtx);
1939*b3e9e682SRyan Stone 		SDT_PROBE0(sched, , , remain_cpu);
1940*b3e9e682SRyan Stone 	}
1941ae7a6b38SJeff Roberson 	/*
1942ae7a6b38SJeff Roberson 	 * Assert that all went well and return.
1943ae7a6b38SJeff Roberson 	 */
1944ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1945ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1946ae7a6b38SJeff Roberson 	td->td_oncpu = cpuid;
194735e6168fSJeff Roberson }
194835e6168fSJeff Roberson 
1949ae7a6b38SJeff Roberson /*
1950ae7a6b38SJeff Roberson  * Adjust thread priorities as a result of a nice request.
1951ae7a6b38SJeff Roberson  */
195235e6168fSJeff Roberson void
1953fa885116SJulian Elischer sched_nice(struct proc *p, int nice)
195435e6168fSJeff Roberson {
195535e6168fSJeff Roberson 	struct thread *td;
195635e6168fSJeff Roberson 
1957fa885116SJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
1958e7d50326SJeff Roberson 
1959fa885116SJulian Elischer 	p->p_nice = nice;
19608460a577SJohn Birrell 	FOREACH_THREAD_IN_PROC(p, td) {
19617b20fb19SJeff Roberson 		thread_lock(td);
19628460a577SJohn Birrell 		sched_priority(td);
1963e7d50326SJeff Roberson 		sched_prio(td, td->td_base_user_pri);
19647b20fb19SJeff Roberson 		thread_unlock(td);
196535e6168fSJeff Roberson 	}
1966fa885116SJulian Elischer }
196735e6168fSJeff Roberson 
1968ae7a6b38SJeff Roberson /*
1969ae7a6b38SJeff Roberson  * Record the sleep time for the interactivity scorer.
1970ae7a6b38SJeff Roberson  */
197135e6168fSJeff Roberson void
1972c5aa6b58SJeff Roberson sched_sleep(struct thread *td, int prio)
197335e6168fSJeff Roberson {
1974e7d50326SJeff Roberson 
19757b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
197635e6168fSJeff Roberson 
197754b0e65fSJeff Roberson 	td->td_slptick = ticks;
197817c4c356SKonstantin Belousov 	if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
1979c5aa6b58SJeff Roberson 		td->td_flags |= TDF_CANSWAP;
19802dc29adbSJohn Baldwin 	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
19812dc29adbSJohn Baldwin 		return;
19820502fe2eSJeff Roberson 	if (static_boost == 1 && prio)
1983c5aa6b58SJeff Roberson 		sched_prio(td, prio);
19840502fe2eSJeff Roberson 	else if (static_boost && td->td_priority > static_boost)
19850502fe2eSJeff Roberson 		sched_prio(td, static_boost);
198635e6168fSJeff Roberson }
198735e6168fSJeff Roberson 
1988ae7a6b38SJeff Roberson /*
1989ae7a6b38SJeff Roberson  * Schedule a thread to resume execution and record how long it voluntarily
1990ae7a6b38SJeff Roberson  * slept.  We also update the pctcpu, interactivity, and priority.
1991ae7a6b38SJeff Roberson  */
199235e6168fSJeff Roberson void
199335e6168fSJeff Roberson sched_wakeup(struct thread *td)
199435e6168fSJeff Roberson {
199514618990SJeff Roberson 	struct td_sched *ts;
1996ae7a6b38SJeff Roberson 	int slptick;
1997e7d50326SJeff Roberson 
19987b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
199914618990SJeff Roberson 	ts = td->td_sched;
2000c5aa6b58SJeff Roberson 	td->td_flags &= ~TDF_CANSWAP;
200135e6168fSJeff Roberson 	/*
2002e7d50326SJeff Roberson 	 * If we slept for more than a tick update our interactivity and
2003e7d50326SJeff Roberson 	 * priority.
200435e6168fSJeff Roberson 	 */
200554b0e65fSJeff Roberson 	slptick = td->td_slptick;
200654b0e65fSJeff Roberson 	td->td_slptick = 0;
2007ae7a6b38SJeff Roberson 	if (slptick && slptick != ticks) {
20087295465eSAlexander Motin 		ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
20098460a577SJohn Birrell 		sched_interact_update(td);
20107295465eSAlexander Motin 		sched_pctcpu_update(ts, 0);
2011f1e8dc4aSJeff Roberson 	}
201214618990SJeff Roberson 	/* Reset the slice value after we sleep. */
201314618990SJeff Roberson 	ts->ts_slice = sched_slice;
20147a5e5e2aSJeff Roberson 	sched_add(td, SRQ_BORING);
201535e6168fSJeff Roberson }
201635e6168fSJeff Roberson 
201735e6168fSJeff Roberson /*
201835e6168fSJeff Roberson  * Penalize the parent for creating a new child and initialize the child's
201935e6168fSJeff Roberson  * priority.
202035e6168fSJeff Roberson  */
202135e6168fSJeff Roberson void
20228460a577SJohn Birrell sched_fork(struct thread *td, struct thread *child)
202315dc847eSJeff Roberson {
20247b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
20257295465eSAlexander Motin 	sched_pctcpu_update(td->td_sched, 1);
2026ad1e7d28SJulian Elischer 	sched_fork_thread(td, child);
2027e7d50326SJeff Roberson 	/*
2028e7d50326SJeff Roberson 	 * Penalize the parent and child for forking.
2029e7d50326SJeff Roberson 	 */
2030e7d50326SJeff Roberson 	sched_interact_fork(child);
2031e7d50326SJeff Roberson 	sched_priority(child);
2032ae7a6b38SJeff Roberson 	td->td_sched->ts_runtime += tickincr;
2033e7d50326SJeff Roberson 	sched_interact_update(td);
2034e7d50326SJeff Roberson 	sched_priority(td);
2035ad1e7d28SJulian Elischer }
2036ad1e7d28SJulian Elischer 
2037ae7a6b38SJeff Roberson /*
2038ae7a6b38SJeff Roberson  * Fork a new thread, may be within the same process.
2039ae7a6b38SJeff Roberson  */
2040ad1e7d28SJulian Elischer void
2041ad1e7d28SJulian Elischer sched_fork_thread(struct thread *td, struct thread *child)
2042ad1e7d28SJulian Elischer {
2043ad1e7d28SJulian Elischer 	struct td_sched *ts;
2044ad1e7d28SJulian Elischer 	struct td_sched *ts2;
20458460a577SJohn Birrell 
20468b16c208SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2047e7d50326SJeff Roberson 	/*
2048e7d50326SJeff Roberson 	 * Initialize child.
2049e7d50326SJeff Roberson 	 */
2050ad1e7d28SJulian Elischer 	ts = td->td_sched;
2051ad1e7d28SJulian Elischer 	ts2 = child->td_sched;
20528b16c208SJeff Roberson 	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
20538b16c208SJeff Roberson 	child->td_cpuset = cpuset_ref(td->td_cpuset);
2054ad1e7d28SJulian Elischer 	ts2->ts_cpu = ts->ts_cpu;
20558b16c208SJeff Roberson 	ts2->ts_flags = 0;
2056e7d50326SJeff Roberson 	/*
205722d19207SJohn Baldwin 	 * Grab our parents cpu estimation information.
2058e7d50326SJeff Roberson 	 */
2059ad1e7d28SJulian Elischer 	ts2->ts_ticks = ts->ts_ticks;
2060ad1e7d28SJulian Elischer 	ts2->ts_ltick = ts->ts_ltick;
2061ad1e7d28SJulian Elischer 	ts2->ts_ftick = ts->ts_ftick;
206222d19207SJohn Baldwin 	/*
206322d19207SJohn Baldwin 	 * Do not inherit any borrowed priority from the parent.
206422d19207SJohn Baldwin 	 */
206522d19207SJohn Baldwin 	child->td_priority = child->td_base_pri;
2066e7d50326SJeff Roberson 	/*
2067e7d50326SJeff Roberson 	 * And update interactivity score.
2068e7d50326SJeff Roberson 	 */
2069ae7a6b38SJeff Roberson 	ts2->ts_slptime = ts->ts_slptime;
2070ae7a6b38SJeff Roberson 	ts2->ts_runtime = ts->ts_runtime;
2071e7d50326SJeff Roberson 	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
20728f51ad55SJeff Roberson #ifdef KTR
20738f51ad55SJeff Roberson 	bzero(ts2->ts_name, sizeof(ts2->ts_name));
20748f51ad55SJeff Roberson #endif
207515dc847eSJeff Roberson }
207615dc847eSJeff Roberson 
2077ae7a6b38SJeff Roberson /*
2078ae7a6b38SJeff Roberson  * Adjust the priority class of a thread.
2079ae7a6b38SJeff Roberson  */
208015dc847eSJeff Roberson void
20818460a577SJohn Birrell sched_class(struct thread *td, int class)
208215dc847eSJeff Roberson {
208315dc847eSJeff Roberson 
20847b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
20858460a577SJohn Birrell 	if (td->td_pri_class == class)
208615dc847eSJeff Roberson 		return;
20878460a577SJohn Birrell 	td->td_pri_class = class;
208835e6168fSJeff Roberson }
208935e6168fSJeff Roberson 
209035e6168fSJeff Roberson /*
209135e6168fSJeff Roberson  * Return some of the child's priority and interactivity to the parent.
209235e6168fSJeff Roberson  */
209335e6168fSJeff Roberson void
2094fc6c30f6SJulian Elischer sched_exit(struct proc *p, struct thread *child)
209535e6168fSJeff Roberson {
2096e7d50326SJeff Roberson 	struct thread *td;
2097141ad61cSJeff Roberson 
20988f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2099cd39bb09SXin LI 	    "prio:%d", child->td_priority);
2100374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
2101e7d50326SJeff Roberson 	td = FIRST_THREAD_IN_PROC(p);
2102e7d50326SJeff Roberson 	sched_exit_thread(td, child);
2103ad1e7d28SJulian Elischer }
2104ad1e7d28SJulian Elischer 
2105ae7a6b38SJeff Roberson /*
2106ae7a6b38SJeff Roberson  * Penalize another thread for the time spent on this one.  This helps to
2107ae7a6b38SJeff Roberson  * worsen the priority and interactivity of processes which schedule batch
2108ae7a6b38SJeff Roberson  * jobs such as make.  This has little effect on the make process itself but
2109ae7a6b38SJeff Roberson  * causes new processes spawned by it to receive worse scores immediately.
2110ae7a6b38SJeff Roberson  */
2111ad1e7d28SJulian Elischer void
2112fc6c30f6SJulian Elischer sched_exit_thread(struct thread *td, struct thread *child)
2113ad1e7d28SJulian Elischer {
2114fc6c30f6SJulian Elischer 
21158f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2116cd39bb09SXin LI 	    "prio:%d", child->td_priority);
2117e7d50326SJeff Roberson 	/*
2118e7d50326SJeff Roberson 	 * Give the child's runtime to the parent without returning the
2119e7d50326SJeff Roberson 	 * sleep time as a penalty to the parent.  This causes shells that
2120e7d50326SJeff Roberson 	 * launch expensive things to mark their children as expensive.
2121e7d50326SJeff Roberson 	 */
21227b20fb19SJeff Roberson 	thread_lock(td);
2123ae7a6b38SJeff Roberson 	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2124fc6c30f6SJulian Elischer 	sched_interact_update(td);
2125e7d50326SJeff Roberson 	sched_priority(td);
21267b20fb19SJeff Roberson 	thread_unlock(td);
2127ad1e7d28SJulian Elischer }
2128ad1e7d28SJulian Elischer 
2129ff256d9cSJeff Roberson void
2130ff256d9cSJeff Roberson sched_preempt(struct thread *td)
2131ff256d9cSJeff Roberson {
2132ff256d9cSJeff Roberson 	struct tdq *tdq;
2133ff256d9cSJeff Roberson 
2134*b3e9e682SRyan Stone 	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
2135*b3e9e682SRyan Stone 
2136ff256d9cSJeff Roberson 	thread_lock(td);
2137ff256d9cSJeff Roberson 	tdq = TDQ_SELF();
2138ff256d9cSJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2139ff256d9cSJeff Roberson 	tdq->tdq_ipipending = 0;
2140ff256d9cSJeff Roberson 	if (td->td_priority > tdq->tdq_lowpri) {
21418df78c41SJeff Roberson 		int flags;
21428df78c41SJeff Roberson 
21438df78c41SJeff Roberson 		flags = SW_INVOL | SW_PREEMPT;
2144ff256d9cSJeff Roberson 		if (td->td_critnest > 1)
2145ff256d9cSJeff Roberson 			td->td_owepreempt = 1;
21468df78c41SJeff Roberson 		else if (TD_IS_IDLETHREAD(td))
21478df78c41SJeff Roberson 			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2148ff256d9cSJeff Roberson 		else
21498df78c41SJeff Roberson 			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2150ff256d9cSJeff Roberson 	}
2151ff256d9cSJeff Roberson 	thread_unlock(td);
2152ff256d9cSJeff Roberson }
2153ff256d9cSJeff Roberson 
2154ae7a6b38SJeff Roberson /*
2155ae7a6b38SJeff Roberson  * Fix priorities on return to user-space.  Priorities may be elevated due
2156ae7a6b38SJeff Roberson  * to static priorities in msleep() or similar.
2157ae7a6b38SJeff Roberson  */
2158ad1e7d28SJulian Elischer void
2159ad1e7d28SJulian Elischer sched_userret(struct thread *td)
2160ad1e7d28SJulian Elischer {
2161ad1e7d28SJulian Elischer 	/*
2162ad1e7d28SJulian Elischer 	 * XXX we cheat slightly on the locking here to avoid locking in
2163ad1e7d28SJulian Elischer 	 * the usual case.  Setting td_priority here is essentially an
2164ad1e7d28SJulian Elischer 	 * incomplete workaround for not setting it properly elsewhere.
2165ad1e7d28SJulian Elischer 	 * Now that some interrupt handlers are threads, not setting it
2166ad1e7d28SJulian Elischer 	 * properly elsewhere can clobber it in the window between setting
2167ad1e7d28SJulian Elischer 	 * it here and returning to user mode, so don't waste time setting
2168ad1e7d28SJulian Elischer 	 * it perfectly here.
2169ad1e7d28SJulian Elischer 	 */
2170ad1e7d28SJulian Elischer 	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2171ad1e7d28SJulian Elischer 	    ("thread with borrowed priority returning to userland"));
2172ad1e7d28SJulian Elischer 	if (td->td_priority != td->td_user_pri) {
21737b20fb19SJeff Roberson 		thread_lock(td);
2174ad1e7d28SJulian Elischer 		td->td_priority = td->td_user_pri;
2175ad1e7d28SJulian Elischer 		td->td_base_pri = td->td_user_pri;
217662fa74d9SJeff Roberson 		tdq_setlowpri(TDQ_SELF(), td);
21777b20fb19SJeff Roberson 		thread_unlock(td);
2178ad1e7d28SJulian Elischer         }
217935e6168fSJeff Roberson }
218035e6168fSJeff Roberson 
2181ae7a6b38SJeff Roberson /*
2182ae7a6b38SJeff Roberson  * Handle a stathz tick.  This is really only relevant for timeshare
2183ae7a6b38SJeff Roberson  * threads.
2184ae7a6b38SJeff Roberson  */
218535e6168fSJeff Roberson void
21867cf90fb3SJeff Roberson sched_clock(struct thread *td)
218735e6168fSJeff Roberson {
2188ad1e7d28SJulian Elischer 	struct tdq *tdq;
2189ad1e7d28SJulian Elischer 	struct td_sched *ts;
219035e6168fSJeff Roberson 
2191ae7a6b38SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
21923f872f85SJeff Roberson 	tdq = TDQ_SELF();
21937fcf154aSJeff Roberson #ifdef SMP
21947fcf154aSJeff Roberson 	/*
21957fcf154aSJeff Roberson 	 * We run the long term load balancer infrequently on the first cpu.
21967fcf154aSJeff Roberson 	 */
21977fcf154aSJeff Roberson 	if (balance_tdq == tdq) {
21987fcf154aSJeff Roberson 		if (balance_ticks && --balance_ticks == 0)
21997fcf154aSJeff Roberson 			sched_balance();
22007fcf154aSJeff Roberson 	}
22017fcf154aSJeff Roberson #endif
22023f872f85SJeff Roberson 	/*
22031690c6c1SJeff Roberson 	 * Save the old switch count so we have a record of the last ticks
22041690c6c1SJeff Roberson 	 * activity.   Initialize the new switch count based on our load.
22051690c6c1SJeff Roberson 	 * If there is some activity seed it to reflect that.
22061690c6c1SJeff Roberson 	 */
22071690c6c1SJeff Roberson 	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
22086c47aaaeSJeff Roberson 	tdq->tdq_switchcnt = tdq->tdq_load;
22091690c6c1SJeff Roberson 	/*
22103f872f85SJeff Roberson 	 * Advance the insert index once for each tick to ensure that all
22113f872f85SJeff Roberson 	 * threads get a chance to run.
22123f872f85SJeff Roberson 	 */
22133f872f85SJeff Roberson 	if (tdq->tdq_idx == tdq->tdq_ridx) {
22143f872f85SJeff Roberson 		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
22153f872f85SJeff Roberson 		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
22163f872f85SJeff Roberson 			tdq->tdq_ridx = tdq->tdq_idx;
22173f872f85SJeff Roberson 	}
22183f872f85SJeff Roberson 	ts = td->td_sched;
22197295465eSAlexander Motin 	sched_pctcpu_update(ts, 1);
2220fd0b8c78SJeff Roberson 	if (td->td_pri_class & PRI_FIFO_BIT)
2221a8949de2SJeff Roberson 		return;
2222c9a8cba4SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2223a8949de2SJeff Roberson 		/*
2224fd0b8c78SJeff Roberson 		 * We used a tick; charge it to the thread so
2225fd0b8c78SJeff Roberson 		 * that we can compute our interactivity.
222615dc847eSJeff Roberson 		 */
2227ae7a6b38SJeff Roberson 		td->td_sched->ts_runtime += tickincr;
22288460a577SJohn Birrell 		sched_interact_update(td);
222973daf66fSJeff Roberson 		sched_priority(td);
2230fd0b8c78SJeff Roberson 	}
223135e6168fSJeff Roberson 	/*
223235e6168fSJeff Roberson 	 * We used up one time slice.
223335e6168fSJeff Roberson 	 */
2234ad1e7d28SJulian Elischer 	if (--ts->ts_slice > 0)
223515dc847eSJeff Roberson 		return;
223635e6168fSJeff Roberson 	/*
223773daf66fSJeff Roberson 	 * We're out of time, force a requeue at userret().
223835e6168fSJeff Roberson 	 */
223973daf66fSJeff Roberson 	ts->ts_slice = sched_slice;
22404a338afdSJulian Elischer 	td->td_flags |= TDF_NEEDRESCHED;
224135e6168fSJeff Roberson }
224235e6168fSJeff Roberson 
2243ae7a6b38SJeff Roberson /*
22447295465eSAlexander Motin  * Called once per hz tick.
2245ae7a6b38SJeff Roberson  */
2246ae7a6b38SJeff Roberson void
2247a157e425SAlexander Motin sched_tick(int cnt)
2248ae7a6b38SJeff Roberson {
2249ae7a6b38SJeff Roberson 
2250ae7a6b38SJeff Roberson }
2251ae7a6b38SJeff Roberson 
2252ae7a6b38SJeff Roberson /*
2253ae7a6b38SJeff Roberson  * Return whether the current CPU has runnable tasks.  Used for in-kernel
2254ae7a6b38SJeff Roberson  * cooperative idle threads.
2255ae7a6b38SJeff Roberson  */
225635e6168fSJeff Roberson int
225735e6168fSJeff Roberson sched_runnable(void)
225835e6168fSJeff Roberson {
2259ad1e7d28SJulian Elischer 	struct tdq *tdq;
2260b90816f1SJeff Roberson 	int load;
226135e6168fSJeff Roberson 
2262b90816f1SJeff Roberson 	load = 1;
2263b90816f1SJeff Roberson 
2264ad1e7d28SJulian Elischer 	tdq = TDQ_SELF();
22653f741ca1SJeff Roberson 	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2266d2ad694cSJeff Roberson 		if (tdq->tdq_load > 0)
22673f741ca1SJeff Roberson 			goto out;
22683f741ca1SJeff Roberson 	} else
2269d2ad694cSJeff Roberson 		if (tdq->tdq_load - 1 > 0)
2270b90816f1SJeff Roberson 			goto out;
2271b90816f1SJeff Roberson 	load = 0;
2272b90816f1SJeff Roberson out:
2273b90816f1SJeff Roberson 	return (load);
227435e6168fSJeff Roberson }
227535e6168fSJeff Roberson 
2276ae7a6b38SJeff Roberson /*
2277ae7a6b38SJeff Roberson  * Choose the highest priority thread to run.  The thread is removed from
2278ae7a6b38SJeff Roberson  * the run-queue while running however the load remains.  For SMP we set
2279ae7a6b38SJeff Roberson  * the tdq in the global idle bitmask if it idles here.
2280ae7a6b38SJeff Roberson  */
22817a5e5e2aSJeff Roberson struct thread *
2282c9f25d8fSJeff Roberson sched_choose(void)
2283c9f25d8fSJeff Roberson {
22849727e637SJeff Roberson 	struct thread *td;
2285ae7a6b38SJeff Roberson 	struct tdq *tdq;
2286ae7a6b38SJeff Roberson 
2287ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2288ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
22899727e637SJeff Roberson 	td = tdq_choose(tdq);
22909727e637SJeff Roberson 	if (td) {
22919727e637SJeff Roberson 		tdq_runq_rem(tdq, td);
22920502fe2eSJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
22939727e637SJeff Roberson 		return (td);
229435e6168fSJeff Roberson 	}
22950502fe2eSJeff Roberson 	tdq->tdq_lowpri = PRI_MAX_IDLE;
229662fa74d9SJeff Roberson 	return (PCPU_GET(idlethread));
22977a5e5e2aSJeff Roberson }
22987a5e5e2aSJeff Roberson 
2299ae7a6b38SJeff Roberson /*
2300ae7a6b38SJeff Roberson  * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2301ae7a6b38SJeff Roberson  * we always request it once we exit a critical section.
2302ae7a6b38SJeff Roberson  */
2303ae7a6b38SJeff Roberson static inline void
2304ae7a6b38SJeff Roberson sched_setpreempt(struct thread *td)
23057a5e5e2aSJeff Roberson {
23067a5e5e2aSJeff Roberson 	struct thread *ctd;
23077a5e5e2aSJeff Roberson 	int cpri;
23087a5e5e2aSJeff Roberson 	int pri;
23097a5e5e2aSJeff Roberson 
2310ff256d9cSJeff Roberson 	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2311ff256d9cSJeff Roberson 
23127a5e5e2aSJeff Roberson 	ctd = curthread;
23137a5e5e2aSJeff Roberson 	pri = td->td_priority;
23147a5e5e2aSJeff Roberson 	cpri = ctd->td_priority;
2315ff256d9cSJeff Roberson 	if (pri < cpri)
2316ff256d9cSJeff Roberson 		ctd->td_flags |= TDF_NEEDRESCHED;
23177a5e5e2aSJeff Roberson 	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2318ae7a6b38SJeff Roberson 		return;
2319ff256d9cSJeff Roberson 	if (!sched_shouldpreempt(pri, cpri, 0))
2320ae7a6b38SJeff Roberson 		return;
23217a5e5e2aSJeff Roberson 	ctd->td_owepreempt = 1;
232235e6168fSJeff Roberson }
232335e6168fSJeff Roberson 
2324ae7a6b38SJeff Roberson /*
232573daf66fSJeff Roberson  * Add a thread to a thread queue.  Select the appropriate runq and add the
232673daf66fSJeff Roberson  * thread to it.  This is the internal function called when the tdq is
232773daf66fSJeff Roberson  * predetermined.
2328ae7a6b38SJeff Roberson  */
232935e6168fSJeff Roberson void
2330ae7a6b38SJeff Roberson tdq_add(struct tdq *tdq, struct thread *td, int flags)
233135e6168fSJeff Roberson {
2332c9f25d8fSJeff Roberson 
2333ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
23347a5e5e2aSJeff Roberson 	KASSERT((td->td_inhibitors == 0),
23357a5e5e2aSJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
23367a5e5e2aSJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
23377a5e5e2aSJeff Roberson 	    ("sched_add: bad thread state"));
2338b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
2339b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
2340ae7a6b38SJeff Roberson 
2341ae7a6b38SJeff Roberson 	if (td->td_priority < tdq->tdq_lowpri)
2342ae7a6b38SJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
23439727e637SJeff Roberson 	tdq_runq_add(tdq, td, flags);
23449727e637SJeff Roberson 	tdq_load_add(tdq, td);
2345ae7a6b38SJeff Roberson }
2346ae7a6b38SJeff Roberson 
2347ae7a6b38SJeff Roberson /*
2348ae7a6b38SJeff Roberson  * Select the target thread queue and add a thread to it.  Request
2349ae7a6b38SJeff Roberson  * preemption or IPI a remote processor if required.
2350ae7a6b38SJeff Roberson  */
2351ae7a6b38SJeff Roberson void
2352ae7a6b38SJeff Roberson sched_add(struct thread *td, int flags)
2353ae7a6b38SJeff Roberson {
2354ae7a6b38SJeff Roberson 	struct tdq *tdq;
23557b8bfa0dSJeff Roberson #ifdef SMP
2356ae7a6b38SJeff Roberson 	int cpu;
2357ae7a6b38SJeff Roberson #endif
23588f51ad55SJeff Roberson 
23598f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
23608f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
23618f51ad55SJeff Roberson 	    sched_tdname(curthread));
23628f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
23638f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
2364*b3e9e682SRyan Stone 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
2365*b3e9e682SRyan Stone 	    flags & SRQ_PREEMPTED);
2366ae7a6b38SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2367ae7a6b38SJeff Roberson 	/*
2368ae7a6b38SJeff Roberson 	 * Recalculate the priority before we select the target cpu or
2369ae7a6b38SJeff Roberson 	 * run-queue.
2370ae7a6b38SJeff Roberson 	 */
2371ae7a6b38SJeff Roberson 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2372ae7a6b38SJeff Roberson 		sched_priority(td);
2373ae7a6b38SJeff Roberson #ifdef SMP
2374ae7a6b38SJeff Roberson 	/*
2375ae7a6b38SJeff Roberson 	 * Pick the destination cpu and if it isn't ours transfer to the
2376ae7a6b38SJeff Roberson 	 * target cpu.
2377ae7a6b38SJeff Roberson 	 */
23789727e637SJeff Roberson 	cpu = sched_pickcpu(td, flags);
23799727e637SJeff Roberson 	tdq = sched_setcpu(td, cpu, flags);
2380ae7a6b38SJeff Roberson 	tdq_add(tdq, td, flags);
238173daf66fSJeff Roberson 	if (cpu != PCPU_GET(cpuid)) {
23829727e637SJeff Roberson 		tdq_notify(tdq, td);
23837b8bfa0dSJeff Roberson 		return;
23847b8bfa0dSJeff Roberson 	}
2385ae7a6b38SJeff Roberson #else
2386ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2387ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
2388ae7a6b38SJeff Roberson 	/*
2389ae7a6b38SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
2390ae7a6b38SJeff Roberson 	 * to the scheduler's lock.
2391ae7a6b38SJeff Roberson 	 */
2392ae7a6b38SJeff Roberson 	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2393ae7a6b38SJeff Roberson 	tdq_add(tdq, td, flags);
23947b8bfa0dSJeff Roberson #endif
2395ae7a6b38SJeff Roberson 	if (!(flags & SRQ_YIELDING))
2396ae7a6b38SJeff Roberson 		sched_setpreempt(td);
239735e6168fSJeff Roberson }
239835e6168fSJeff Roberson 
2399ae7a6b38SJeff Roberson /*
2400ae7a6b38SJeff Roberson  * Remove a thread from a run-queue without running it.  This is used
2401ae7a6b38SJeff Roberson  * when we're stealing a thread from a remote queue.  Otherwise all threads
2402ae7a6b38SJeff Roberson  * exit by calling sched_exit_thread() and sched_throw() themselves.
2403ae7a6b38SJeff Roberson  */
240435e6168fSJeff Roberson void
24057cf90fb3SJeff Roberson sched_rem(struct thread *td)
240635e6168fSJeff Roberson {
2407ad1e7d28SJulian Elischer 	struct tdq *tdq;
24087cf90fb3SJeff Roberson 
24098f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
24108f51ad55SJeff Roberson 	    "prio:%d", td->td_priority);
2411*b3e9e682SRyan Stone 	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
24129727e637SJeff Roberson 	tdq = TDQ_CPU(td->td_sched->ts_cpu);
2413ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2414ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
24157a5e5e2aSJeff Roberson 	KASSERT(TD_ON_RUNQ(td),
2416ad1e7d28SJulian Elischer 	    ("sched_rem: thread not on run queue"));
24179727e637SJeff Roberson 	tdq_runq_rem(tdq, td);
24189727e637SJeff Roberson 	tdq_load_rem(tdq, td);
24197a5e5e2aSJeff Roberson 	TD_SET_CAN_RUN(td);
242062fa74d9SJeff Roberson 	if (td->td_priority == tdq->tdq_lowpri)
242162fa74d9SJeff Roberson 		tdq_setlowpri(tdq, NULL);
242235e6168fSJeff Roberson }
242335e6168fSJeff Roberson 
2424ae7a6b38SJeff Roberson /*
2425ae7a6b38SJeff Roberson  * Fetch cpu utilization information.  Updates on demand.
2426ae7a6b38SJeff Roberson  */
242735e6168fSJeff Roberson fixpt_t
24287cf90fb3SJeff Roberson sched_pctcpu(struct thread *td)
242935e6168fSJeff Roberson {
243035e6168fSJeff Roberson 	fixpt_t pctcpu;
2431ad1e7d28SJulian Elischer 	struct td_sched *ts;
243235e6168fSJeff Roberson 
243335e6168fSJeff Roberson 	pctcpu = 0;
2434ad1e7d28SJulian Elischer 	ts = td->td_sched;
2435ad1e7d28SJulian Elischer 	if (ts == NULL)
2436484288deSJeff Roberson 		return (0);
243735e6168fSJeff Roberson 
24383da35a0aSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
24397295465eSAlexander Motin 	sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2440ad1e7d28SJulian Elischer 	if (ts->ts_ticks) {
244135e6168fSJeff Roberson 		int rtick;
244235e6168fSJeff Roberson 
244335e6168fSJeff Roberson 		/* How many rtick per second ? */
2444e7d50326SJeff Roberson 		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2445e7d50326SJeff Roberson 		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
244635e6168fSJeff Roberson 	}
244735e6168fSJeff Roberson 
244835e6168fSJeff Roberson 	return (pctcpu);
244935e6168fSJeff Roberson }
245035e6168fSJeff Roberson 
245162fa74d9SJeff Roberson /*
245262fa74d9SJeff Roberson  * Enforce affinity settings for a thread.  Called after adjustments to
245362fa74d9SJeff Roberson  * cpumask.
245462fa74d9SJeff Roberson  */
2455885d51a3SJeff Roberson void
2456885d51a3SJeff Roberson sched_affinity(struct thread *td)
2457885d51a3SJeff Roberson {
245862fa74d9SJeff Roberson #ifdef SMP
245962fa74d9SJeff Roberson 	struct td_sched *ts;
246062fa74d9SJeff Roberson 
246162fa74d9SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
246262fa74d9SJeff Roberson 	ts = td->td_sched;
246362fa74d9SJeff Roberson 	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
246462fa74d9SJeff Roberson 		return;
246553a6c8b3SJeff Roberson 	if (TD_ON_RUNQ(td)) {
246653a6c8b3SJeff Roberson 		sched_rem(td);
246753a6c8b3SJeff Roberson 		sched_add(td, SRQ_BORING);
246853a6c8b3SJeff Roberson 		return;
246953a6c8b3SJeff Roberson 	}
247062fa74d9SJeff Roberson 	if (!TD_IS_RUNNING(td))
247162fa74d9SJeff Roberson 		return;
247262fa74d9SJeff Roberson 	/*
24730f7a0ebdSMatthew D Fleming 	 * Force a switch before returning to userspace.  If the
24740f7a0ebdSMatthew D Fleming 	 * target thread is not running locally send an ipi to force
24750f7a0ebdSMatthew D Fleming 	 * the issue.
247662fa74d9SJeff Roberson 	 */
2477a8103ae8SJohn Baldwin 	td->td_flags |= TDF_NEEDRESCHED;
24780f7a0ebdSMatthew D Fleming 	if (td != curthread)
24790f7a0ebdSMatthew D Fleming 		ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
248062fa74d9SJeff Roberson #endif
2481885d51a3SJeff Roberson }
2482885d51a3SJeff Roberson 
2483ae7a6b38SJeff Roberson /*
2484ae7a6b38SJeff Roberson  * Bind a thread to a target cpu.
2485ae7a6b38SJeff Roberson  */
24869bacd788SJeff Roberson void
24879bacd788SJeff Roberson sched_bind(struct thread *td, int cpu)
24889bacd788SJeff Roberson {
2489ad1e7d28SJulian Elischer 	struct td_sched *ts;
24909bacd788SJeff Roberson 
2491c47f202bSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
24921d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
2493ad1e7d28SJulian Elischer 	ts = td->td_sched;
24946b2f763fSJeff Roberson 	if (ts->ts_flags & TSF_BOUND)
2495c95d2db2SJeff Roberson 		sched_unbind(td);
24960f7a0ebdSMatthew D Fleming 	KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2497ad1e7d28SJulian Elischer 	ts->ts_flags |= TSF_BOUND;
24986b2f763fSJeff Roberson 	sched_pin();
249980f86c9fSJeff Roberson 	if (PCPU_GET(cpuid) == cpu)
25009bacd788SJeff Roberson 		return;
25016b2f763fSJeff Roberson 	ts->ts_cpu = cpu;
25029bacd788SJeff Roberson 	/* When we return from mi_switch we'll be on the correct cpu. */
2503279f949eSPoul-Henning Kamp 	mi_switch(SW_VOL, NULL);
25049bacd788SJeff Roberson }
25059bacd788SJeff Roberson 
2506ae7a6b38SJeff Roberson /*
2507ae7a6b38SJeff Roberson  * Release a bound thread.
2508ae7a6b38SJeff Roberson  */
25099bacd788SJeff Roberson void
25109bacd788SJeff Roberson sched_unbind(struct thread *td)
25119bacd788SJeff Roberson {
2512e7d50326SJeff Roberson 	struct td_sched *ts;
2513e7d50326SJeff Roberson 
25147b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
25151d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
2516e7d50326SJeff Roberson 	ts = td->td_sched;
25176b2f763fSJeff Roberson 	if ((ts->ts_flags & TSF_BOUND) == 0)
25186b2f763fSJeff Roberson 		return;
2519e7d50326SJeff Roberson 	ts->ts_flags &= ~TSF_BOUND;
2520e7d50326SJeff Roberson 	sched_unpin();
25219bacd788SJeff Roberson }
25229bacd788SJeff Roberson 
252335e6168fSJeff Roberson int
2524ebccf1e3SJoseph Koshy sched_is_bound(struct thread *td)
2525ebccf1e3SJoseph Koshy {
25267b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2527ad1e7d28SJulian Elischer 	return (td->td_sched->ts_flags & TSF_BOUND);
2528ebccf1e3SJoseph Koshy }
2529ebccf1e3SJoseph Koshy 
2530ae7a6b38SJeff Roberson /*
2531ae7a6b38SJeff Roberson  * Basic yield call.
2532ae7a6b38SJeff Roberson  */
253336ec198bSDavid Xu void
253436ec198bSDavid Xu sched_relinquish(struct thread *td)
253536ec198bSDavid Xu {
25367b20fb19SJeff Roberson 	thread_lock(td);
25378df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
25387b20fb19SJeff Roberson 	thread_unlock(td);
253936ec198bSDavid Xu }
254036ec198bSDavid Xu 
2541ae7a6b38SJeff Roberson /*
2542ae7a6b38SJeff Roberson  * Return the total system load.
2543ae7a6b38SJeff Roberson  */
2544ebccf1e3SJoseph Koshy int
254533916c36SJeff Roberson sched_load(void)
254633916c36SJeff Roberson {
254733916c36SJeff Roberson #ifdef SMP
254833916c36SJeff Roberson 	int total;
254933916c36SJeff Roberson 	int i;
255033916c36SJeff Roberson 
255133916c36SJeff Roberson 	total = 0;
25523aa6d94eSJohn Baldwin 	CPU_FOREACH(i)
255362fa74d9SJeff Roberson 		total += TDQ_CPU(i)->tdq_sysload;
255433916c36SJeff Roberson 	return (total);
255533916c36SJeff Roberson #else
2556d2ad694cSJeff Roberson 	return (TDQ_SELF()->tdq_sysload);
255733916c36SJeff Roberson #endif
255833916c36SJeff Roberson }
255933916c36SJeff Roberson 
256033916c36SJeff Roberson int
256135e6168fSJeff Roberson sched_sizeof_proc(void)
256235e6168fSJeff Roberson {
256335e6168fSJeff Roberson 	return (sizeof(struct proc));
256435e6168fSJeff Roberson }
256535e6168fSJeff Roberson 
256635e6168fSJeff Roberson int
256735e6168fSJeff Roberson sched_sizeof_thread(void)
256835e6168fSJeff Roberson {
256935e6168fSJeff Roberson 	return (sizeof(struct thread) + sizeof(struct td_sched));
257035e6168fSJeff Roberson }
2571b41f1452SDavid Xu 
257209c8a4ccSJeff Roberson #ifdef SMP
257309c8a4ccSJeff Roberson #define	TDQ_IDLESPIN(tdq)						\
257409c8a4ccSJeff Roberson     ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
257509c8a4ccSJeff Roberson #else
257609c8a4ccSJeff Roberson #define	TDQ_IDLESPIN(tdq)	1
257709c8a4ccSJeff Roberson #endif
257809c8a4ccSJeff Roberson 
25797a5e5e2aSJeff Roberson /*
25807a5e5e2aSJeff Roberson  * The actual idle process.
25817a5e5e2aSJeff Roberson  */
25827a5e5e2aSJeff Roberson void
25837a5e5e2aSJeff Roberson sched_idletd(void *dummy)
25847a5e5e2aSJeff Roberson {
25857a5e5e2aSJeff Roberson 	struct thread *td;
2586ae7a6b38SJeff Roberson 	struct tdq *tdq;
25871690c6c1SJeff Roberson 	int switchcnt;
25881690c6c1SJeff Roberson 	int i;
25897a5e5e2aSJeff Roberson 
25907b55ab05SJeff Roberson 	mtx_assert(&Giant, MA_NOTOWNED);
25917a5e5e2aSJeff Roberson 	td = curthread;
2592ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2593ae7a6b38SJeff Roberson 	for (;;) {
2594ae7a6b38SJeff Roberson #ifdef SMP
25951690c6c1SJeff Roberson 		if (tdq_idled(tdq) == 0)
25961690c6c1SJeff Roberson 			continue;
2597ae7a6b38SJeff Roberson #endif
25981690c6c1SJeff Roberson 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
25991690c6c1SJeff Roberson 		/*
26001690c6c1SJeff Roberson 		 * If we're switching very frequently, spin while checking
26011690c6c1SJeff Roberson 		 * for load rather than entering a low power state that
26027b55ab05SJeff Roberson 		 * may require an IPI.  However, don't do any busy
26037b55ab05SJeff Roberson 		 * loops while on SMT machines as this simply steals
26047b55ab05SJeff Roberson 		 * cycles from cores doing useful work.
26051690c6c1SJeff Roberson 		 */
260609c8a4ccSJeff Roberson 		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
26071690c6c1SJeff Roberson 			for (i = 0; i < sched_idlespins; i++) {
26081690c6c1SJeff Roberson 				if (tdq->tdq_load)
26091690c6c1SJeff Roberson 					break;
26101690c6c1SJeff Roberson 				cpu_spinwait();
26111690c6c1SJeff Roberson 			}
26121690c6c1SJeff Roberson 		}
26136c47aaaeSJeff Roberson 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
26149f9ad565SAlexander Motin 		if (tdq->tdq_load == 0) {
26159f9ad565SAlexander Motin 			tdq->tdq_cpu_idle = 1;
26169f9ad565SAlexander Motin 			if (tdq->tdq_load == 0) {
2617a157e425SAlexander Motin 				cpu_idle(switchcnt > sched_idlespinthresh * 4);
26189f9ad565SAlexander Motin 				tdq->tdq_switchcnt++;
26199f9ad565SAlexander Motin 			}
26209f9ad565SAlexander Motin 			tdq->tdq_cpu_idle = 0;
26219f9ad565SAlexander Motin 		}
26221690c6c1SJeff Roberson 		if (tdq->tdq_load) {
26231690c6c1SJeff Roberson 			thread_lock(td);
26241690c6c1SJeff Roberson 			mi_switch(SW_VOL | SWT_IDLE, NULL);
26251690c6c1SJeff Roberson 			thread_unlock(td);
26261690c6c1SJeff Roberson 		}
2627ae7a6b38SJeff Roberson 	}
2628b41f1452SDavid Xu }
2629e7d50326SJeff Roberson 
26307b20fb19SJeff Roberson /*
26317b20fb19SJeff Roberson  * A CPU is entering for the first time or a thread is exiting.
26327b20fb19SJeff Roberson  */
26337b20fb19SJeff Roberson void
26347b20fb19SJeff Roberson sched_throw(struct thread *td)
26357b20fb19SJeff Roberson {
263659c68134SJeff Roberson 	struct thread *newtd;
2637ae7a6b38SJeff Roberson 	struct tdq *tdq;
2638ae7a6b38SJeff Roberson 
2639ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
26407b20fb19SJeff Roberson 	if (td == NULL) {
2641ae7a6b38SJeff Roberson 		/* Correct spinlock nesting and acquire the correct lock. */
2642ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
26437b20fb19SJeff Roberson 		spinlock_exit();
26447e3a96eaSJohn Baldwin 		PCPU_SET(switchtime, cpu_ticks());
26457e3a96eaSJohn Baldwin 		PCPU_SET(switchticks, ticks);
26467b20fb19SJeff Roberson 	} else {
2647ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
26489727e637SJeff Roberson 		tdq_load_rem(tdq, td);
2649eea4f254SJeff Roberson 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
26507b20fb19SJeff Roberson 	}
26517b20fb19SJeff Roberson 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
265259c68134SJeff Roberson 	newtd = choosethread();
265359c68134SJeff Roberson 	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
265459c68134SJeff Roberson 	cpu_throw(td, newtd);		/* doesn't return */
26557b20fb19SJeff Roberson }
26567b20fb19SJeff Roberson 
2657ae7a6b38SJeff Roberson /*
2658ae7a6b38SJeff Roberson  * This is called from fork_exit().  Just acquire the correct locks and
2659ae7a6b38SJeff Roberson  * let fork do the rest of the work.
2660ae7a6b38SJeff Roberson  */
26617b20fb19SJeff Roberson void
2662fe54587fSJeff Roberson sched_fork_exit(struct thread *td)
26637b20fb19SJeff Roberson {
2664ae7a6b38SJeff Roberson 	struct td_sched *ts;
2665ae7a6b38SJeff Roberson 	struct tdq *tdq;
2666ae7a6b38SJeff Roberson 	int cpuid;
26677b20fb19SJeff Roberson 
26687b20fb19SJeff Roberson 	/*
26697b20fb19SJeff Roberson 	 * Finish setting up thread glue so that it begins execution in a
2670ae7a6b38SJeff Roberson 	 * non-nested critical section with the scheduler lock held.
26717b20fb19SJeff Roberson 	 */
2672ae7a6b38SJeff Roberson 	cpuid = PCPU_GET(cpuid);
2673ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpuid);
2674ae7a6b38SJeff Roberson 	ts = td->td_sched;
2675ae7a6b38SJeff Roberson 	if (TD_IS_IDLETHREAD(td))
2676ae7a6b38SJeff Roberson 		td->td_lock = TDQ_LOCKPTR(tdq);
2677ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2678ae7a6b38SJeff Roberson 	td->td_oncpu = cpuid;
267959c68134SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2680eea4f254SJeff Roberson 	lock_profile_obtain_lock_success(
2681eea4f254SJeff Roberson 	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
26827b20fb19SJeff Roberson }
26837b20fb19SJeff Roberson 
26848f51ad55SJeff Roberson /*
26858f51ad55SJeff Roberson  * Create on first use to catch odd startup conditons.
26868f51ad55SJeff Roberson  */
26878f51ad55SJeff Roberson char *
26888f51ad55SJeff Roberson sched_tdname(struct thread *td)
26898f51ad55SJeff Roberson {
26908f51ad55SJeff Roberson #ifdef KTR
26918f51ad55SJeff Roberson 	struct td_sched *ts;
26928f51ad55SJeff Roberson 
26938f51ad55SJeff Roberson 	ts = td->td_sched;
26948f51ad55SJeff Roberson 	if (ts->ts_name[0] == '\0')
26958f51ad55SJeff Roberson 		snprintf(ts->ts_name, sizeof(ts->ts_name),
26968f51ad55SJeff Roberson 		    "%s tid %d", td->td_name, td->td_tid);
26978f51ad55SJeff Roberson 	return (ts->ts_name);
26988f51ad55SJeff Roberson #else
26998f51ad55SJeff Roberson 	return (td->td_name);
27008f51ad55SJeff Roberson #endif
27018f51ad55SJeff Roberson }
27028f51ad55SJeff Roberson 
270344ad5475SJohn Baldwin #ifdef KTR
270444ad5475SJohn Baldwin void
270544ad5475SJohn Baldwin sched_clear_tdname(struct thread *td)
270644ad5475SJohn Baldwin {
270744ad5475SJohn Baldwin 	struct td_sched *ts;
270844ad5475SJohn Baldwin 
270944ad5475SJohn Baldwin 	ts = td->td_sched;
271044ad5475SJohn Baldwin 	ts->ts_name[0] = '\0';
271144ad5475SJohn Baldwin }
271244ad5475SJohn Baldwin #endif
271344ad5475SJohn Baldwin 
271407095abfSIvan Voras #ifdef SMP
271507095abfSIvan Voras 
271607095abfSIvan Voras /*
271707095abfSIvan Voras  * Build the CPU topology dump string. Is recursively called to collect
271807095abfSIvan Voras  * the topology tree.
271907095abfSIvan Voras  */
272007095abfSIvan Voras static int
272107095abfSIvan Voras sysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
272207095abfSIvan Voras     int indent)
272307095abfSIvan Voras {
272471a19bdcSAttilio Rao 	char cpusetbuf[CPUSETBUFSIZ];
272507095abfSIvan Voras 	int i, first;
272607095abfSIvan Voras 
272707095abfSIvan Voras 	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
272819b8a6dbSAndriy Gapon 	    "", 1 + indent / 2, cg->cg_level);
272971a19bdcSAttilio Rao 	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
273071a19bdcSAttilio Rao 	    cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
273107095abfSIvan Voras 	first = TRUE;
273207095abfSIvan Voras 	for (i = 0; i < MAXCPU; i++) {
273371a19bdcSAttilio Rao 		if (CPU_ISSET(i, &cg->cg_mask)) {
273407095abfSIvan Voras 			if (!first)
273507095abfSIvan Voras 				sbuf_printf(sb, ", ");
273607095abfSIvan Voras 			else
273707095abfSIvan Voras 				first = FALSE;
273807095abfSIvan Voras 			sbuf_printf(sb, "%d", i);
273907095abfSIvan Voras 		}
274007095abfSIvan Voras 	}
274107095abfSIvan Voras 	sbuf_printf(sb, "</cpu>\n");
274207095abfSIvan Voras 
274307095abfSIvan Voras 	if (cg->cg_flags != 0) {
2744611daf7eSIvan Voras 		sbuf_printf(sb, "%*s <flags>", indent, "");
274507095abfSIvan Voras 		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
27465368befbSIvan Voras 			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
2747a401f2d0SIvan Voras 		if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
2748a401f2d0SIvan Voras 			sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
27497b55ab05SJeff Roberson 		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
2750a401f2d0SIvan Voras 			sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
275107095abfSIvan Voras 		sbuf_printf(sb, "</flags>\n");
2752611daf7eSIvan Voras 	}
275307095abfSIvan Voras 
275407095abfSIvan Voras 	if (cg->cg_children > 0) {
275507095abfSIvan Voras 		sbuf_printf(sb, "%*s <children>\n", indent, "");
275607095abfSIvan Voras 		for (i = 0; i < cg->cg_children; i++)
275707095abfSIvan Voras 			sysctl_kern_sched_topology_spec_internal(sb,
275807095abfSIvan Voras 			    &cg->cg_child[i], indent+2);
275907095abfSIvan Voras 		sbuf_printf(sb, "%*s </children>\n", indent, "");
276007095abfSIvan Voras 	}
276107095abfSIvan Voras 	sbuf_printf(sb, "%*s</group>\n", indent, "");
276207095abfSIvan Voras 	return (0);
276307095abfSIvan Voras }
276407095abfSIvan Voras 
276507095abfSIvan Voras /*
276607095abfSIvan Voras  * Sysctl handler for retrieving topology dump. It's a wrapper for
276707095abfSIvan Voras  * the recursive sysctl_kern_smp_topology_spec_internal().
276807095abfSIvan Voras  */
276907095abfSIvan Voras static int
277007095abfSIvan Voras sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
277107095abfSIvan Voras {
277207095abfSIvan Voras 	struct sbuf *topo;
277307095abfSIvan Voras 	int err;
277407095abfSIvan Voras 
277507095abfSIvan Voras 	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
277607095abfSIvan Voras 
2777aa880b90SIvan Voras 	topo = sbuf_new(NULL, NULL, 500, SBUF_AUTOEXTEND);
277807095abfSIvan Voras 	if (topo == NULL)
277907095abfSIvan Voras 		return (ENOMEM);
278007095abfSIvan Voras 
278107095abfSIvan Voras 	sbuf_printf(topo, "<groups>\n");
278207095abfSIvan Voras 	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
278307095abfSIvan Voras 	sbuf_printf(topo, "</groups>\n");
278407095abfSIvan Voras 
278507095abfSIvan Voras 	if (err == 0) {
278607095abfSIvan Voras 		sbuf_finish(topo);
278707095abfSIvan Voras 		err = SYSCTL_OUT(req, sbuf_data(topo), sbuf_len(topo));
278807095abfSIvan Voras 	}
278907095abfSIvan Voras 	sbuf_delete(topo);
279007095abfSIvan Voras 	return (err);
279107095abfSIvan Voras }
2792b67cc292SDavid Xu 
279307095abfSIvan Voras #endif
279407095abfSIvan Voras 
27959727e637SJeff Roberson SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2796ae7a6b38SJeff Roberson SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2797e7d50326SJeff Roberson     "Scheduler name");
2798ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2799ae7a6b38SJeff Roberson     "Slice size for timeshare threads");
2800ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2801ae7a6b38SJeff Roberson      "Interactivity score threshold");
2802ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2803ae7a6b38SJeff Roberson      0,"Min priority for preemption, lower priorities have greater precedence");
2804c5aa6b58SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost,
2805c5aa6b58SJeff Roberson      0,"Controls whether static kernel priorities are assigned to sleeping threads.");
28061690c6c1SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins,
28071690c6c1SJeff Roberson      0,"Number of times idle will spin waiting for new work.");
28081690c6c1SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW, &sched_idlespinthresh,
28091690c6c1SJeff Roberson      0,"Threshold before we will permit idle spinning.");
28107b8bfa0dSJeff Roberson #ifdef SMP
2811ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2812ae7a6b38SJeff Roberson     "Number of hz ticks to keep thread affinity for");
2813ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2814ae7a6b38SJeff Roberson     "Enables the long-term load balancer");
28157fcf154aSJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
28167fcf154aSJeff Roberson     &balance_interval, 0,
28177fcf154aSJeff Roberson     "Average frequency in stathz ticks to run the long-term balancer");
2818ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2819ae7a6b38SJeff Roberson     "Attempts to steal work from other cores before idling");
282028994a58SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
282128994a58SJeff Roberson     "Minimum load on remote cpu before we'll steal");
282207095abfSIvan Voras 
282307095abfSIvan Voras /* Retrieve SMP topology */
282407095abfSIvan Voras SYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
282507095abfSIvan Voras     CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
282607095abfSIvan Voras     "XML dump of detected CPU topology");
2827b67cc292SDavid Xu 
28287b8bfa0dSJeff Roberson #endif
2829e7d50326SJeff Roberson 
283054b0e65fSJeff Roberson /* ps compat.  All cpu percentages from ULE are weighted. */
2831a5423ea3SJeff Roberson static int ccpu = 0;
2832e7d50326SJeff Roberson SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2833