xref: /freebsd/sys/kern/sched_ule.c (revision 7295465e33dbb21d4bc5f55d6664ef1776a86d76)
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>
5635e6168fSJeff Roberson #include <sys/smp.h>
5735e6168fSJeff Roberson #include <sys/sx.h>
5835e6168fSJeff Roberson #include <sys/sysctl.h>
5935e6168fSJeff Roberson #include <sys/sysproto.h>
60f5c157d9SJohn Baldwin #include <sys/turnstile.h>
613db720fdSDavid Xu #include <sys/umtx.h>
6235e6168fSJeff Roberson #include <sys/vmmeter.h>
6362fa74d9SJeff Roberson #include <sys/cpuset.h>
6407095abfSIvan Voras #include <sys/sbuf.h>
6535e6168fSJeff Roberson 
66ebccf1e3SJoseph Koshy #ifdef HWPMC_HOOKS
67ebccf1e3SJoseph Koshy #include <sys/pmckern.h>
68ebccf1e3SJoseph Koshy #endif
69ebccf1e3SJoseph Koshy 
706f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
716f5f25e5SJohn Birrell #include <sys/dtrace_bsd.h>
726f5f25e5SJohn Birrell int				dtrace_vtime_active;
736f5f25e5SJohn Birrell dtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
746f5f25e5SJohn Birrell #endif
756f5f25e5SJohn Birrell 
7635e6168fSJeff Roberson #include <machine/cpu.h>
7722bf7d9aSJeff Roberson #include <machine/smp.h>
7835e6168fSJeff Roberson 
79880bf8b9SMarius Strobl #if defined(__powerpc__) && defined(E500)
8002e2d6b4SJeff Roberson #error "This architecture is not currently compatible with ULE"
817a5e5e2aSJeff Roberson #endif
827a5e5e2aSJeff Roberson 
83ae7a6b38SJeff Roberson #define	KTR_ULE	0
8414618990SJeff Roberson 
850d2cf837SJeff Roberson #define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
860d2cf837SJeff Roberson #define	TDQ_NAME_LEN	(sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
876338c579SAttilio Rao #define	TDQ_LOADNAME_LEN	(sizeof("CPU ") + sizeof(__XSTRING(MAXCPU)) - 1 + sizeof(" load"))
888f51ad55SJeff Roberson 
896b2f763fSJeff Roberson /*
90ae7a6b38SJeff Roberson  * Thread scheduler specific section.  All fields are protected
91ae7a6b38SJeff Roberson  * by the thread lock.
92ed062c8dSJulian Elischer  */
93ad1e7d28SJulian Elischer struct td_sched {
94ae7a6b38SJeff Roberson 	struct runq	*ts_runq;	/* Run-queue we're queued on. */
95ae7a6b38SJeff Roberson 	short		ts_flags;	/* TSF_* flags. */
96ad1e7d28SJulian Elischer 	u_char		ts_cpu;		/* CPU that we have affinity for. */
9773daf66fSJeff Roberson 	int		ts_rltick;	/* Real last tick, for affinity. */
98ae7a6b38SJeff Roberson 	int		ts_slice;	/* Ticks of slice remaining. */
99ae7a6b38SJeff Roberson 	u_int		ts_slptime;	/* Number of ticks we vol. slept */
100ae7a6b38SJeff Roberson 	u_int		ts_runtime;	/* Number of ticks we were running */
101ad1e7d28SJulian Elischer 	int		ts_ltick;	/* Last tick that we were running on */
102ad1e7d28SJulian Elischer 	int		ts_ftick;	/* First tick that we were running on */
103ad1e7d28SJulian Elischer 	int		ts_ticks;	/* Tick count */
1048f51ad55SJeff Roberson #ifdef KTR
1058f51ad55SJeff Roberson 	char		ts_name[TS_NAME_LEN];
1068f51ad55SJeff Roberson #endif
107ed062c8dSJulian Elischer };
108ad1e7d28SJulian Elischer /* flags kept in ts_flags */
1097b8bfa0dSJeff Roberson #define	TSF_BOUND	0x0001		/* Thread can not migrate. */
1107b8bfa0dSJeff Roberson #define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
11135e6168fSJeff Roberson 
112ad1e7d28SJulian Elischer static struct td_sched td_sched0;
11335e6168fSJeff Roberson 
11462fa74d9SJeff Roberson #define	THREAD_CAN_MIGRATE(td)	((td)->td_pinned == 0)
11562fa74d9SJeff Roberson #define	THREAD_CAN_SCHED(td, cpu)	\
11662fa74d9SJeff Roberson     CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
11762fa74d9SJeff Roberson 
11835e6168fSJeff Roberson /*
11912d56c0fSJohn Baldwin  * Priority ranges used for interactive and non-interactive timeshare
1202dc29adbSJohn Baldwin  * threads.  The timeshare priorities are split up into four ranges.
1212dc29adbSJohn Baldwin  * The first range handles interactive threads.  The last three ranges
1222dc29adbSJohn Baldwin  * (NHALF, x, and NHALF) handle non-interactive threads with the outer
1232dc29adbSJohn Baldwin  * ranges supporting nice values.
12412d56c0fSJohn Baldwin  */
1252dc29adbSJohn Baldwin #define	PRI_TIMESHARE_RANGE	(PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
1262dc29adbSJohn Baldwin #define	PRI_INTERACT_RANGE	((PRI_TIMESHARE_RANGE - SCHED_PRI_NRESV) / 2)
12716705791SAndriy Gapon #define	PRI_BATCH_RANGE		(PRI_TIMESHARE_RANGE - PRI_INTERACT_RANGE)
1282dc29adbSJohn Baldwin 
1292dc29adbSJohn Baldwin #define	PRI_MIN_INTERACT	PRI_MIN_TIMESHARE
1302dc29adbSJohn Baldwin #define	PRI_MAX_INTERACT	(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE - 1)
1312dc29adbSJohn Baldwin #define	PRI_MIN_BATCH		(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE)
13212d56c0fSJohn Baldwin #define	PRI_MAX_BATCH		PRI_MAX_TIMESHARE
13312d56c0fSJohn Baldwin 
13412d56c0fSJohn Baldwin /*
135e7d50326SJeff Roberson  * Cpu percentage computation macros and defines.
136e1f89c22SJeff Roberson  *
137e7d50326SJeff Roberson  * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
138e7d50326SJeff Roberson  * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
1398ab80cf0SJeff Roberson  * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
140e7d50326SJeff Roberson  * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
141e7d50326SJeff Roberson  * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
142e7d50326SJeff Roberson  * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
14335e6168fSJeff Roberson  */
144e7d50326SJeff Roberson #define	SCHED_TICK_SECS		10
145e7d50326SJeff Roberson #define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
1468ab80cf0SJeff Roberson #define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
147e7d50326SJeff Roberson #define	SCHED_TICK_SHIFT	10
148e7d50326SJeff Roberson #define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
149eddb4efaSJeff Roberson #define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
15035e6168fSJeff Roberson 
15135e6168fSJeff Roberson /*
152e7d50326SJeff Roberson  * These macros determine priorities for non-interactive threads.  They are
153e7d50326SJeff Roberson  * assigned a priority based on their recent cpu utilization as expressed
154e7d50326SJeff Roberson  * by the ratio of ticks to the tick total.  NHALF priorities at the start
155e7d50326SJeff Roberson  * and end of the MIN to MAX timeshare range are only reachable with negative
156e7d50326SJeff Roberson  * or positive nice respectively.
157e7d50326SJeff Roberson  *
158e7d50326SJeff Roberson  * PRI_RANGE:	Priority range for utilization dependent priorities.
159e7d50326SJeff Roberson  * PRI_NRESV:	Number of nice values.
160e7d50326SJeff Roberson  * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
161e7d50326SJeff Roberson  * PRI_NICE:	Determines the part of the priority inherited from nice.
162e7d50326SJeff Roberson  */
163e7d50326SJeff Roberson #define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
164e7d50326SJeff Roberson #define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
16512d56c0fSJohn Baldwin #define	SCHED_PRI_MIN		(PRI_MIN_BATCH + SCHED_PRI_NHALF)
16612d56c0fSJohn Baldwin #define	SCHED_PRI_MAX		(PRI_MAX_BATCH - SCHED_PRI_NHALF)
16778920008SJohn Baldwin #define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN + 1)
168e7d50326SJeff Roberson #define	SCHED_PRI_TICKS(ts)						\
169e7d50326SJeff Roberson     (SCHED_TICK_HZ((ts)) /						\
1701e516cf5SJeff Roberson     (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
171e7d50326SJeff Roberson #define	SCHED_PRI_NICE(nice)	(nice)
172e7d50326SJeff Roberson 
173e7d50326SJeff Roberson /*
174e7d50326SJeff Roberson  * These determine the interactivity of a process.  Interactivity differs from
175e7d50326SJeff Roberson  * cpu utilization in that it expresses the voluntary time slept vs time ran
176e7d50326SJeff Roberson  * while cpu utilization includes all time not running.  This more accurately
177e7d50326SJeff Roberson  * models the intent of the thread.
17835e6168fSJeff Roberson  *
179407b0157SJeff Roberson  * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
180407b0157SJeff Roberson  *		before throttling back.
181d322132cSJeff Roberson  * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
182210491d3SJeff Roberson  * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
1839f518f20SAttilio Rao  * INTERACT_THRESH:	Threshold for placement on the current runq.
18435e6168fSJeff Roberson  */
185e7d50326SJeff Roberson #define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
186e7d50326SJeff Roberson #define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
187210491d3SJeff Roberson #define	SCHED_INTERACT_MAX	(100)
188210491d3SJeff Roberson #define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
1894c9612c6SJeff Roberson #define	SCHED_INTERACT_THRESH	(30)
190e1f89c22SJeff Roberson 
19135e6168fSJeff Roberson /*
192e7d50326SJeff Roberson  * tickincr:		Converts a stathz tick into a hz domain scaled by
193e7d50326SJeff Roberson  *			the shift factor.  Without the shift the error rate
194e7d50326SJeff Roberson  *			due to rounding would be unacceptably high.
195e7d50326SJeff Roberson  * realstathz:		stathz is sometimes 0 and run off of hz.
196e7d50326SJeff Roberson  * sched_slice:		Runtime of each thread before rescheduling.
197ae7a6b38SJeff Roberson  * preempt_thresh:	Priority threshold for preemption and remote IPIs.
19835e6168fSJeff Roberson  */
199e7d50326SJeff Roberson static int sched_interact = SCHED_INTERACT_THRESH;
200e7d50326SJeff Roberson static int realstathz;
201e7d50326SJeff Roberson static int tickincr;
20273daf66fSJeff Roberson static int sched_slice = 1;
20302e2d6b4SJeff Roberson #ifdef PREEMPTION
20402e2d6b4SJeff Roberson #ifdef FULL_PREEMPTION
20502e2d6b4SJeff Roberson static int preempt_thresh = PRI_MAX_IDLE;
20602e2d6b4SJeff Roberson #else
207ae7a6b38SJeff Roberson static int preempt_thresh = PRI_MIN_KERN;
20802e2d6b4SJeff Roberson #endif
20902e2d6b4SJeff Roberson #else
21002e2d6b4SJeff Roberson static int preempt_thresh = 0;
21102e2d6b4SJeff Roberson #endif
21212d56c0fSJohn Baldwin static int static_boost = PRI_MIN_BATCH;
2131690c6c1SJeff Roberson static int sched_idlespins = 10000;
214b3f40a41SAlexander Motin static int sched_idlespinthresh = -1;
215ae7a6b38SJeff Roberson 
21635e6168fSJeff Roberson /*
217ae7a6b38SJeff Roberson  * tdq - per processor runqs and statistics.  All fields are protected by the
218ae7a6b38SJeff Roberson  * tdq_lock.  The load and lowpri may be accessed without to avoid excess
219ae7a6b38SJeff Roberson  * locking in sched_pickcpu();
22035e6168fSJeff Roberson  */
221ad1e7d28SJulian Elischer struct tdq {
22273daf66fSJeff Roberson 	/* Ordered to improve efficiency of cpu_search() and switch(). */
22362fa74d9SJeff Roberson 	struct mtx	tdq_lock;		/* run queue lock. */
22473daf66fSJeff Roberson 	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
2251690c6c1SJeff Roberson 	volatile int	tdq_load;		/* Aggregate load. */
2269f9ad565SAlexander Motin 	volatile int	tdq_cpu_idle;		/* cpu_idle() is active. */
22773daf66fSJeff Roberson 	int		tdq_sysload;		/* For loadavg, !ITHD load. */
22873daf66fSJeff Roberson 	int		tdq_transferable;	/* Transferable thread count. */
2291690c6c1SJeff Roberson 	short		tdq_switchcnt;		/* Switches this tick. */
2301690c6c1SJeff Roberson 	short		tdq_oldswitchcnt;	/* Switches last tick. */
23173daf66fSJeff Roberson 	u_char		tdq_lowpri;		/* Lowest priority thread. */
23273daf66fSJeff Roberson 	u_char		tdq_ipipending;		/* IPI pending. */
23373daf66fSJeff Roberson 	u_char		tdq_idx;		/* Current insert index. */
23473daf66fSJeff Roberson 	u_char		tdq_ridx;		/* Current removal index. */
235e7d50326SJeff Roberson 	struct runq	tdq_realtime;		/* real-time run queue. */
236ae7a6b38SJeff Roberson 	struct runq	tdq_timeshare;		/* timeshare run queue. */
237ae7a6b38SJeff Roberson 	struct runq	tdq_idle;		/* Queue of IDLE threads. */
2388f51ad55SJeff Roberson 	char		tdq_name[TDQ_NAME_LEN];
2398f51ad55SJeff Roberson #ifdef KTR
2408f51ad55SJeff Roberson 	char		tdq_loadname[TDQ_LOADNAME_LEN];
2418f51ad55SJeff Roberson #endif
242ae7a6b38SJeff Roberson } __aligned(64);
24335e6168fSJeff Roberson 
2441690c6c1SJeff Roberson /* Idle thread states and config. */
2451690c6c1SJeff Roberson #define	TDQ_RUNNING	1
2461690c6c1SJeff Roberson #define	TDQ_IDLE	2
2477b8bfa0dSJeff Roberson 
24880f86c9fSJeff Roberson #ifdef SMP
24907095abfSIvan Voras struct cpu_group *cpu_top;		/* CPU topology */
2507b8bfa0dSJeff Roberson 
25162fa74d9SJeff Roberson #define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
25262fa74d9SJeff Roberson #define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
2537b8bfa0dSJeff Roberson 
2547b8bfa0dSJeff Roberson /*
2557b8bfa0dSJeff Roberson  * Run-time tunables.
2567b8bfa0dSJeff Roberson  */
25728994a58SJeff Roberson static int rebalance = 1;
2587fcf154aSJeff Roberson static int balance_interval = 128;	/* Default set in sched_initticks(). */
2597b8bfa0dSJeff Roberson static int affinity;
26028994a58SJeff Roberson static int steal_idle = 1;
26128994a58SJeff Roberson static int steal_thresh = 2;
26280f86c9fSJeff Roberson 
26335e6168fSJeff Roberson /*
264d2ad694cSJeff Roberson  * One thread queue per processor.
26535e6168fSJeff Roberson  */
266ad1e7d28SJulian Elischer static struct tdq	tdq_cpu[MAXCPU];
2677fcf154aSJeff Roberson static struct tdq	*balance_tdq;
2687fcf154aSJeff Roberson static int balance_ticks;
26936acfc65SAlexander Motin static DPCPU_DEFINE(uint32_t, randomval);
270dc03363dSJeff Roberson 
271ad1e7d28SJulian Elischer #define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
272ad1e7d28SJulian Elischer #define	TDQ_CPU(x)	(&tdq_cpu[(x)])
273c47f202bSJeff Roberson #define	TDQ_ID(x)	((int)((x) - tdq_cpu))
27480f86c9fSJeff Roberson #else	/* !SMP */
275ad1e7d28SJulian Elischer static struct tdq	tdq_cpu;
276dc03363dSJeff Roberson 
27736b36916SJeff Roberson #define	TDQ_ID(x)	(0)
278ad1e7d28SJulian Elischer #define	TDQ_SELF()	(&tdq_cpu)
279ad1e7d28SJulian Elischer #define	TDQ_CPU(x)	(&tdq_cpu)
2800a016a05SJeff Roberson #endif
28135e6168fSJeff Roberson 
282ae7a6b38SJeff Roberson #define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
283ae7a6b38SJeff Roberson #define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
284ae7a6b38SJeff Roberson #define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
285ae7a6b38SJeff Roberson #define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
28662fa74d9SJeff Roberson #define	TDQ_LOCKPTR(t)		(&(t)->tdq_lock)
287ae7a6b38SJeff Roberson 
2888460a577SJohn Birrell static void sched_priority(struct thread *);
28921381d1bSJeff Roberson static void sched_thread_priority(struct thread *, u_char);
2908460a577SJohn Birrell static int sched_interact_score(struct thread *);
2918460a577SJohn Birrell static void sched_interact_update(struct thread *);
2928460a577SJohn Birrell static void sched_interact_fork(struct thread *);
293*7295465eSAlexander Motin static void sched_pctcpu_update(struct td_sched *, int);
29435e6168fSJeff Roberson 
2955d7ef00cSJeff Roberson /* Operations on per processor queues */
2969727e637SJeff Roberson static struct thread *tdq_choose(struct tdq *);
297ad1e7d28SJulian Elischer static void tdq_setup(struct tdq *);
2989727e637SJeff Roberson static void tdq_load_add(struct tdq *, struct thread *);
2999727e637SJeff Roberson static void tdq_load_rem(struct tdq *, struct thread *);
3009727e637SJeff Roberson static __inline void tdq_runq_add(struct tdq *, struct thread *, int);
3019727e637SJeff Roberson static __inline void tdq_runq_rem(struct tdq *, struct thread *);
302ff256d9cSJeff Roberson static inline int sched_shouldpreempt(int, int, int);
303ad1e7d28SJulian Elischer void tdq_print(int cpu);
304e7d50326SJeff Roberson static void runq_print(struct runq *rq);
305ae7a6b38SJeff Roberson static void tdq_add(struct tdq *, struct thread *, int);
3065d7ef00cSJeff Roberson #ifdef SMP
30762fa74d9SJeff Roberson static int tdq_move(struct tdq *, struct tdq *);
308ad1e7d28SJulian Elischer static int tdq_idled(struct tdq *);
3099727e637SJeff Roberson static void tdq_notify(struct tdq *, struct thread *);
3109727e637SJeff Roberson static struct thread *tdq_steal(struct tdq *, int);
3119727e637SJeff Roberson static struct thread *runq_steal(struct runq *, int);
3129727e637SJeff Roberson static int sched_pickcpu(struct thread *, int);
3137fcf154aSJeff Roberson static void sched_balance(void);
31462fa74d9SJeff Roberson static int sched_balance_pair(struct tdq *, struct tdq *);
3159727e637SJeff Roberson static inline struct tdq *sched_setcpu(struct thread *, int, int);
316ae7a6b38SJeff Roberson static inline void thread_unblock_switch(struct thread *, struct mtx *);
317c47f202bSJeff Roberson static struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
31807095abfSIvan Voras static int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
31907095abfSIvan Voras static int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
32007095abfSIvan Voras     struct cpu_group *cg, int indent);
3215d7ef00cSJeff Roberson #endif
3225d7ef00cSJeff Roberson 
323e7d50326SJeff Roberson static void sched_setup(void *dummy);
324237fdd78SRobert Watson SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
325e7d50326SJeff Roberson 
326e7d50326SJeff Roberson static void sched_initticks(void *dummy);
327237fdd78SRobert Watson SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
328237fdd78SRobert Watson     NULL);
329e7d50326SJeff Roberson 
330ae7a6b38SJeff Roberson /*
331ae7a6b38SJeff Roberson  * Print the threads waiting on a run-queue.
332ae7a6b38SJeff Roberson  */
333e7d50326SJeff Roberson static void
334e7d50326SJeff Roberson runq_print(struct runq *rq)
335e7d50326SJeff Roberson {
336e7d50326SJeff Roberson 	struct rqhead *rqh;
3379727e637SJeff Roberson 	struct thread *td;
338e7d50326SJeff Roberson 	int pri;
339e7d50326SJeff Roberson 	int j;
340e7d50326SJeff Roberson 	int i;
341e7d50326SJeff Roberson 
342e7d50326SJeff Roberson 	for (i = 0; i < RQB_LEN; i++) {
343e7d50326SJeff Roberson 		printf("\t\trunq bits %d 0x%zx\n",
344e7d50326SJeff Roberson 		    i, rq->rq_status.rqb_bits[i]);
345e7d50326SJeff Roberson 		for (j = 0; j < RQB_BPW; j++)
346e7d50326SJeff Roberson 			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
347e7d50326SJeff Roberson 				pri = j + (i << RQB_L2BPW);
348e7d50326SJeff Roberson 				rqh = &rq->rq_queues[pri];
3499727e637SJeff Roberson 				TAILQ_FOREACH(td, rqh, td_runq) {
350e7d50326SJeff Roberson 					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
3519727e637SJeff Roberson 					    td, td->td_name, td->td_priority,
3529727e637SJeff Roberson 					    td->td_rqindex, pri);
353e7d50326SJeff Roberson 				}
354e7d50326SJeff Roberson 			}
355e7d50326SJeff Roberson 	}
356e7d50326SJeff Roberson }
357e7d50326SJeff Roberson 
358ae7a6b38SJeff Roberson /*
359ae7a6b38SJeff Roberson  * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
360ae7a6b38SJeff Roberson  */
36115dc847eSJeff Roberson void
362ad1e7d28SJulian Elischer tdq_print(int cpu)
36315dc847eSJeff Roberson {
364ad1e7d28SJulian Elischer 	struct tdq *tdq;
36515dc847eSJeff Roberson 
366ad1e7d28SJulian Elischer 	tdq = TDQ_CPU(cpu);
36715dc847eSJeff Roberson 
368c47f202bSJeff Roberson 	printf("tdq %d:\n", TDQ_ID(tdq));
36962fa74d9SJeff Roberson 	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
37062fa74d9SJeff Roberson 	printf("\tLock name:      %s\n", tdq->tdq_name);
371d2ad694cSJeff Roberson 	printf("\tload:           %d\n", tdq->tdq_load);
3721690c6c1SJeff Roberson 	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
3731690c6c1SJeff Roberson 	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
374e7d50326SJeff Roberson 	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
3753f872f85SJeff Roberson 	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
3761690c6c1SJeff Roberson 	printf("\tload transferable: %d\n", tdq->tdq_transferable);
3771690c6c1SJeff Roberson 	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
378e7d50326SJeff Roberson 	printf("\trealtime runq:\n");
379e7d50326SJeff Roberson 	runq_print(&tdq->tdq_realtime);
380e7d50326SJeff Roberson 	printf("\ttimeshare runq:\n");
381e7d50326SJeff Roberson 	runq_print(&tdq->tdq_timeshare);
382e7d50326SJeff Roberson 	printf("\tidle runq:\n");
383e7d50326SJeff Roberson 	runq_print(&tdq->tdq_idle);
38415dc847eSJeff Roberson }
38515dc847eSJeff Roberson 
386ff256d9cSJeff Roberson static inline int
387ff256d9cSJeff Roberson sched_shouldpreempt(int pri, int cpri, int remote)
388ff256d9cSJeff Roberson {
389ff256d9cSJeff Roberson 	/*
390ff256d9cSJeff Roberson 	 * If the new priority is not better than the current priority there is
391ff256d9cSJeff Roberson 	 * nothing to do.
392ff256d9cSJeff Roberson 	 */
393ff256d9cSJeff Roberson 	if (pri >= cpri)
394ff256d9cSJeff Roberson 		return (0);
395ff256d9cSJeff Roberson 	/*
396ff256d9cSJeff Roberson 	 * Always preempt idle.
397ff256d9cSJeff Roberson 	 */
398ff256d9cSJeff Roberson 	if (cpri >= PRI_MIN_IDLE)
399ff256d9cSJeff Roberson 		return (1);
400ff256d9cSJeff Roberson 	/*
401ff256d9cSJeff Roberson 	 * If preemption is disabled don't preempt others.
402ff256d9cSJeff Roberson 	 */
403ff256d9cSJeff Roberson 	if (preempt_thresh == 0)
404ff256d9cSJeff Roberson 		return (0);
405ff256d9cSJeff Roberson 	/*
406ff256d9cSJeff Roberson 	 * Preempt if we exceed the threshold.
407ff256d9cSJeff Roberson 	 */
408ff256d9cSJeff Roberson 	if (pri <= preempt_thresh)
409ff256d9cSJeff Roberson 		return (1);
410ff256d9cSJeff Roberson 	/*
41112d56c0fSJohn Baldwin 	 * If we're interactive or better and there is non-interactive
41212d56c0fSJohn Baldwin 	 * or worse running preempt only remote processors.
413ff256d9cSJeff Roberson 	 */
41412d56c0fSJohn Baldwin 	if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
415ff256d9cSJeff Roberson 		return (1);
416ff256d9cSJeff Roberson 	return (0);
417ff256d9cSJeff Roberson }
418ff256d9cSJeff Roberson 
419ae7a6b38SJeff Roberson /*
420ae7a6b38SJeff Roberson  * Add a thread to the actual run-queue.  Keeps transferable counts up to
421ae7a6b38SJeff Roberson  * date with what is actually on the run-queue.  Selects the correct
422ae7a6b38SJeff Roberson  * queue position for timeshare threads.
423ae7a6b38SJeff Roberson  */
424155b9987SJeff Roberson static __inline void
4259727e637SJeff Roberson tdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
426155b9987SJeff Roberson {
4279727e637SJeff Roberson 	struct td_sched *ts;
428c143ac21SJeff Roberson 	u_char pri;
429c143ac21SJeff Roberson 
430ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
4319727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
43273daf66fSJeff Roberson 
4339727e637SJeff Roberson 	pri = td->td_priority;
4349727e637SJeff Roberson 	ts = td->td_sched;
4359727e637SJeff Roberson 	TD_SET_RUNQ(td);
4369727e637SJeff Roberson 	if (THREAD_CAN_MIGRATE(td)) {
437d2ad694cSJeff Roberson 		tdq->tdq_transferable++;
438ad1e7d28SJulian Elischer 		ts->ts_flags |= TSF_XFERABLE;
43980f86c9fSJeff Roberson 	}
44012d56c0fSJohn Baldwin 	if (pri < PRI_MIN_BATCH) {
441c143ac21SJeff Roberson 		ts->ts_runq = &tdq->tdq_realtime;
44212d56c0fSJohn Baldwin 	} else if (pri <= PRI_MAX_BATCH) {
443c143ac21SJeff Roberson 		ts->ts_runq = &tdq->tdq_timeshare;
44412d56c0fSJohn Baldwin 		KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
445e7d50326SJeff Roberson 			("Invalid priority %d on timeshare runq", pri));
446e7d50326SJeff Roberson 		/*
447e7d50326SJeff Roberson 		 * This queue contains only priorities between MIN and MAX
448e7d50326SJeff Roberson 		 * realtime.  Use the whole queue to represent these values.
449e7d50326SJeff Roberson 		 */
450c47f202bSJeff Roberson 		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
45116705791SAndriy Gapon 			pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
452e7d50326SJeff Roberson 			pri = (pri + tdq->tdq_idx) % RQ_NQS;
4533f872f85SJeff Roberson 			/*
4543f872f85SJeff Roberson 			 * This effectively shortens the queue by one so we
4553f872f85SJeff Roberson 			 * can have a one slot difference between idx and
4563f872f85SJeff Roberson 			 * ridx while we wait for threads to drain.
4573f872f85SJeff Roberson 			 */
4583f872f85SJeff Roberson 			if (tdq->tdq_ridx != tdq->tdq_idx &&
4593f872f85SJeff Roberson 			    pri == tdq->tdq_ridx)
4604499aff6SJeff Roberson 				pri = (unsigned char)(pri - 1) % RQ_NQS;
461e7d50326SJeff Roberson 		} else
4623f872f85SJeff Roberson 			pri = tdq->tdq_ridx;
4639727e637SJeff Roberson 		runq_add_pri(ts->ts_runq, td, pri, flags);
464c143ac21SJeff Roberson 		return;
465e7d50326SJeff Roberson 	} else
46673daf66fSJeff Roberson 		ts->ts_runq = &tdq->tdq_idle;
4679727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
46873daf66fSJeff Roberson }
46973daf66fSJeff Roberson 
47073daf66fSJeff Roberson /*
471ae7a6b38SJeff Roberson  * Remove a thread from a run-queue.  This typically happens when a thread
472ae7a6b38SJeff Roberson  * is selected to run.  Running threads are not on the queue and the
473ae7a6b38SJeff Roberson  * transferable count does not reflect them.
474ae7a6b38SJeff Roberson  */
475155b9987SJeff Roberson static __inline void
4769727e637SJeff Roberson tdq_runq_rem(struct tdq *tdq, struct thread *td)
477155b9987SJeff Roberson {
4789727e637SJeff Roberson 	struct td_sched *ts;
4799727e637SJeff Roberson 
4809727e637SJeff Roberson 	ts = td->td_sched;
481ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
482ae7a6b38SJeff Roberson 	KASSERT(ts->ts_runq != NULL,
4839727e637SJeff Roberson 	    ("tdq_runq_remove: thread %p null ts_runq", td));
484ad1e7d28SJulian Elischer 	if (ts->ts_flags & TSF_XFERABLE) {
485d2ad694cSJeff Roberson 		tdq->tdq_transferable--;
486ad1e7d28SJulian Elischer 		ts->ts_flags &= ~TSF_XFERABLE;
48780f86c9fSJeff Roberson 	}
4883f872f85SJeff Roberson 	if (ts->ts_runq == &tdq->tdq_timeshare) {
4893f872f85SJeff Roberson 		if (tdq->tdq_idx != tdq->tdq_ridx)
4909727e637SJeff Roberson 			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
491e7d50326SJeff Roberson 		else
4929727e637SJeff Roberson 			runq_remove_idx(ts->ts_runq, td, NULL);
4933f872f85SJeff Roberson 	} else
4949727e637SJeff Roberson 		runq_remove(ts->ts_runq, td);
495155b9987SJeff Roberson }
496155b9987SJeff Roberson 
497ae7a6b38SJeff Roberson /*
498ae7a6b38SJeff Roberson  * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
499ae7a6b38SJeff Roberson  * for this thread to the referenced thread queue.
500ae7a6b38SJeff Roberson  */
501a8949de2SJeff Roberson static void
5029727e637SJeff Roberson tdq_load_add(struct tdq *tdq, struct thread *td)
5035d7ef00cSJeff Roberson {
504ae7a6b38SJeff Roberson 
505ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
5069727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
50703d17db7SJeff Roberson 
508d2ad694cSJeff Roberson 	tdq->tdq_load++;
5091b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
510d2ad694cSJeff Roberson 		tdq->tdq_sysload++;
5118f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
5125d7ef00cSJeff Roberson }
51315dc847eSJeff Roberson 
514ae7a6b38SJeff Roberson /*
515ae7a6b38SJeff Roberson  * Remove the load from a thread that is transitioning to a sleep state or
516ae7a6b38SJeff Roberson  * exiting.
517ae7a6b38SJeff Roberson  */
518a8949de2SJeff Roberson static void
5199727e637SJeff Roberson tdq_load_rem(struct tdq *tdq, struct thread *td)
5205d7ef00cSJeff Roberson {
521ae7a6b38SJeff Roberson 
5229727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
523ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
524ae7a6b38SJeff Roberson 	KASSERT(tdq->tdq_load != 0,
525c47f202bSJeff Roberson 	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
52603d17db7SJeff Roberson 
527d2ad694cSJeff Roberson 	tdq->tdq_load--;
5281b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
52903d17db7SJeff Roberson 		tdq->tdq_sysload--;
5308f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
53115dc847eSJeff Roberson }
53215dc847eSJeff Roberson 
533356500a3SJeff Roberson /*
53462fa74d9SJeff Roberson  * Set lowpri to its exact value by searching the run-queue and
53562fa74d9SJeff Roberson  * evaluating curthread.  curthread may be passed as an optimization.
536356500a3SJeff Roberson  */
53722bf7d9aSJeff Roberson static void
53862fa74d9SJeff Roberson tdq_setlowpri(struct tdq *tdq, struct thread *ctd)
53962fa74d9SJeff Roberson {
54062fa74d9SJeff Roberson 	struct thread *td;
54162fa74d9SJeff Roberson 
54262fa74d9SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
54362fa74d9SJeff Roberson 	if (ctd == NULL)
54462fa74d9SJeff Roberson 		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
5459727e637SJeff Roberson 	td = tdq_choose(tdq);
5469727e637SJeff Roberson 	if (td == NULL || td->td_priority > ctd->td_priority)
54762fa74d9SJeff Roberson 		tdq->tdq_lowpri = ctd->td_priority;
54862fa74d9SJeff Roberson 	else
54962fa74d9SJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
55062fa74d9SJeff Roberson }
55162fa74d9SJeff Roberson 
55262fa74d9SJeff Roberson #ifdef SMP
55362fa74d9SJeff Roberson struct cpu_search {
554c76ee827SJeff Roberson 	cpuset_t cs_mask;
55536acfc65SAlexander Motin 	u_int	cs_prefer;
55636acfc65SAlexander Motin 	int	cs_pri;		/* Min priority for low. */
55736acfc65SAlexander Motin 	int	cs_limit;	/* Max load for low, min load for high. */
55836acfc65SAlexander Motin 	int	cs_cpu;
55936acfc65SAlexander Motin 	int	cs_load;
56062fa74d9SJeff Roberson };
56162fa74d9SJeff Roberson 
56262fa74d9SJeff Roberson #define	CPU_SEARCH_LOWEST	0x1
56362fa74d9SJeff Roberson #define	CPU_SEARCH_HIGHEST	0x2
56462fa74d9SJeff Roberson #define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
56562fa74d9SJeff Roberson 
566c76ee827SJeff Roberson #define	CPUSET_FOREACH(cpu, mask)				\
567c76ee827SJeff Roberson 	for ((cpu) = 0; (cpu) <= mp_maxid; (cpu)++)		\
56871a19bdcSAttilio Rao 		if (CPU_ISSET(cpu, &mask))
56962fa74d9SJeff Roberson 
57036acfc65SAlexander Motin static __inline int cpu_search(const struct cpu_group *cg, struct cpu_search *low,
57162fa74d9SJeff Roberson     struct cpu_search *high, const int match);
57236acfc65SAlexander Motin int cpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low);
57336acfc65SAlexander Motin int cpu_search_highest(const struct cpu_group *cg, struct cpu_search *high);
57436acfc65SAlexander Motin int cpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
57562fa74d9SJeff Roberson     struct cpu_search *high);
57662fa74d9SJeff Roberson 
57762fa74d9SJeff Roberson /*
57862fa74d9SJeff Roberson  * Search the tree of cpu_groups for the lowest or highest loaded cpu
57962fa74d9SJeff Roberson  * according to the match argument.  This routine actually compares the
58062fa74d9SJeff Roberson  * load on all paths through the tree and finds the least loaded cpu on
58162fa74d9SJeff Roberson  * the least loaded path, which may differ from the least loaded cpu in
58262fa74d9SJeff Roberson  * the system.  This balances work among caches and busses.
58362fa74d9SJeff Roberson  *
58462fa74d9SJeff Roberson  * This inline is instantiated in three forms below using constants for the
58562fa74d9SJeff Roberson  * match argument.  It is reduced to the minimum set for each case.  It is
58662fa74d9SJeff Roberson  * also recursive to the depth of the tree.
58762fa74d9SJeff Roberson  */
588d628fbfaSJohn Baldwin static __inline int
58936acfc65SAlexander Motin cpu_search(const struct cpu_group *cg, struct cpu_search *low,
59062fa74d9SJeff Roberson     struct cpu_search *high, const int match)
59162fa74d9SJeff Roberson {
59262fa74d9SJeff Roberson 	struct cpu_search lgroup;
59362fa74d9SJeff Roberson 	struct cpu_search hgroup;
59436acfc65SAlexander Motin 	cpuset_t cpumask;
59562fa74d9SJeff Roberson 	struct cpu_group *child;
59636acfc65SAlexander Motin 	struct tdq *tdq;
59736acfc65SAlexander Motin 	int cpu, i, hload, lload, load, total, rnd;
59862fa74d9SJeff Roberson 
59936acfc65SAlexander Motin 	total = 0;
60036acfc65SAlexander Motin 	cpumask = cg->cg_mask;
60162fa74d9SJeff Roberson 	if (match & CPU_SEARCH_LOWEST) {
60236acfc65SAlexander Motin 		lload = INT_MAX;
60336acfc65SAlexander Motin 		low->cs_load = INT_MAX;
60462fa74d9SJeff Roberson 		lgroup = *low;
60562fa74d9SJeff Roberson 	}
60662fa74d9SJeff Roberson 	if (match & CPU_SEARCH_HIGHEST) {
60736acfc65SAlexander Motin 		hload = -1;
60836acfc65SAlexander Motin 		high->cs_load = -1;
60962fa74d9SJeff Roberson 		hgroup = *high;
61062fa74d9SJeff Roberson 	}
61136acfc65SAlexander Motin 
61236acfc65SAlexander Motin 	/* Iterate through the child CPU groups and then remaining CPUs. */
61336acfc65SAlexander Motin 	for (i = 0, cpu = 0; i <= cg->cg_children; ) {
61436acfc65SAlexander Motin 		if (i >= cg->cg_children) {
61536acfc65SAlexander Motin 			while (cpu <= mp_maxid && !CPU_ISSET(cpu, &cpumask))
61636acfc65SAlexander Motin 				cpu++;
61736acfc65SAlexander Motin 			if (cpu > mp_maxid)
61836acfc65SAlexander Motin 				break;
61936acfc65SAlexander Motin 			child = NULL;
62036acfc65SAlexander Motin 		} else
62136acfc65SAlexander Motin 			child = &cg->cg_child[i];
62236acfc65SAlexander Motin 
62336acfc65SAlexander Motin 		if (child) {			/* Handle child CPU group. */
62436acfc65SAlexander Motin 			CPU_NAND(&cpumask, &child->cg_mask);
62562fa74d9SJeff Roberson 			switch (match) {
62662fa74d9SJeff Roberson 			case CPU_SEARCH_LOWEST:
62762fa74d9SJeff Roberson 				load = cpu_search_lowest(child, &lgroup);
62862fa74d9SJeff Roberson 				break;
62962fa74d9SJeff Roberson 			case CPU_SEARCH_HIGHEST:
63062fa74d9SJeff Roberson 				load = cpu_search_highest(child, &hgroup);
63162fa74d9SJeff Roberson 				break;
63262fa74d9SJeff Roberson 			case CPU_SEARCH_BOTH:
63362fa74d9SJeff Roberson 				load = cpu_search_both(child, &lgroup, &hgroup);
63462fa74d9SJeff Roberson 				break;
63562fa74d9SJeff Roberson 			}
63636acfc65SAlexander Motin 		} else {			/* Handle child CPU. */
63736acfc65SAlexander Motin 			tdq = TDQ_CPU(cpu);
63836acfc65SAlexander Motin 			load = tdq->tdq_load * 256;
63936acfc65SAlexander Motin 			rnd = DPCPU_SET(randomval,
64036acfc65SAlexander Motin 			    DPCPU_GET(randomval) * 69069 + 5) >> 26;
64136acfc65SAlexander Motin 			if (match & CPU_SEARCH_LOWEST) {
64236acfc65SAlexander Motin 				if (cpu == low->cs_prefer)
64336acfc65SAlexander Motin 					load -= 64;
64436acfc65SAlexander Motin 				/* If that CPU is allowed and get data. */
64536acfc65SAlexander Motin 				if (CPU_ISSET(cpu, &lgroup.cs_mask) &&
64636acfc65SAlexander Motin 				    tdq->tdq_lowpri > lgroup.cs_pri &&
64736acfc65SAlexander Motin 				    tdq->tdq_load <= lgroup.cs_limit) {
64836acfc65SAlexander Motin 					lgroup.cs_cpu = cpu;
64936acfc65SAlexander Motin 					lgroup.cs_load = load - rnd;
65036acfc65SAlexander Motin 				}
65162fa74d9SJeff Roberson 			}
65262fa74d9SJeff Roberson 			if (match & CPU_SEARCH_HIGHEST)
65336acfc65SAlexander Motin 				if (CPU_ISSET(cpu, &hgroup.cs_mask) &&
65436acfc65SAlexander Motin 				    tdq->tdq_load >= hgroup.cs_limit &&
65536acfc65SAlexander Motin 				    tdq->tdq_transferable) {
65636acfc65SAlexander Motin 					hgroup.cs_cpu = cpu;
65736acfc65SAlexander Motin 					hgroup.cs_load = load - rnd;
65862fa74d9SJeff Roberson 				}
65962fa74d9SJeff Roberson 		}
66036acfc65SAlexander Motin 		total += load;
66162fa74d9SJeff Roberson 
66236acfc65SAlexander Motin 		/* We have info about child item. Compare it. */
66336acfc65SAlexander Motin 		if (match & CPU_SEARCH_LOWEST) {
6646022f0bcSAlexander Motin 			if (lgroup.cs_load != INT_MAX &&
6656022f0bcSAlexander Motin 			    (load < lload ||
6666022f0bcSAlexander Motin 			     (load == lload && lgroup.cs_load < low->cs_load))) {
66736acfc65SAlexander Motin 				lload = load;
66836acfc65SAlexander Motin 				low->cs_cpu = lgroup.cs_cpu;
66936acfc65SAlexander Motin 				low->cs_load = lgroup.cs_load;
67036acfc65SAlexander Motin 			}
67136acfc65SAlexander Motin 		}
67236acfc65SAlexander Motin 		if (match & CPU_SEARCH_HIGHEST)
673*7295465eSAlexander Motin 			if (hgroup.cs_load >= 0 &&
6746022f0bcSAlexander Motin 			    (load > hload ||
6756022f0bcSAlexander Motin 			     (load == hload && hgroup.cs_load > high->cs_load))) {
67636acfc65SAlexander Motin 				hload = load;
67736acfc65SAlexander Motin 				high->cs_cpu = hgroup.cs_cpu;
67836acfc65SAlexander Motin 				high->cs_load = hgroup.cs_load;
67936acfc65SAlexander Motin 			}
68036acfc65SAlexander Motin 		if (child)
68136acfc65SAlexander Motin 			i++;
68236acfc65SAlexander Motin 		else
68336acfc65SAlexander Motin 			cpu++;
68462fa74d9SJeff Roberson 	}
68562fa74d9SJeff Roberson 	return (total);
68662fa74d9SJeff Roberson }
68762fa74d9SJeff Roberson 
68862fa74d9SJeff Roberson /*
68962fa74d9SJeff Roberson  * cpu_search instantiations must pass constants to maintain the inline
69062fa74d9SJeff Roberson  * optimization.
69162fa74d9SJeff Roberson  */
69262fa74d9SJeff Roberson int
69336acfc65SAlexander Motin cpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low)
69462fa74d9SJeff Roberson {
69562fa74d9SJeff Roberson 	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
69662fa74d9SJeff Roberson }
69762fa74d9SJeff Roberson 
69862fa74d9SJeff Roberson int
69936acfc65SAlexander Motin cpu_search_highest(const struct cpu_group *cg, struct cpu_search *high)
70062fa74d9SJeff Roberson {
70162fa74d9SJeff Roberson 	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
70262fa74d9SJeff Roberson }
70362fa74d9SJeff Roberson 
70462fa74d9SJeff Roberson int
70536acfc65SAlexander Motin cpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
70662fa74d9SJeff Roberson     struct cpu_search *high)
70762fa74d9SJeff Roberson {
70862fa74d9SJeff Roberson 	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
70962fa74d9SJeff Roberson }
71062fa74d9SJeff Roberson 
71162fa74d9SJeff Roberson /*
71262fa74d9SJeff Roberson  * Find the cpu with the least load via the least loaded path that has a
71362fa74d9SJeff Roberson  * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
71462fa74d9SJeff Roberson  * acceptable.
71562fa74d9SJeff Roberson  */
71662fa74d9SJeff Roberson static inline int
71736acfc65SAlexander Motin sched_lowest(const struct cpu_group *cg, cpuset_t mask, int pri, int maxload,
71836acfc65SAlexander Motin     int prefer)
71962fa74d9SJeff Roberson {
72062fa74d9SJeff Roberson 	struct cpu_search low;
72162fa74d9SJeff Roberson 
72262fa74d9SJeff Roberson 	low.cs_cpu = -1;
72336acfc65SAlexander Motin 	low.cs_prefer = prefer;
72462fa74d9SJeff Roberson 	low.cs_mask = mask;
72536acfc65SAlexander Motin 	low.cs_pri = pri;
72636acfc65SAlexander Motin 	low.cs_limit = maxload;
72762fa74d9SJeff Roberson 	cpu_search_lowest(cg, &low);
72862fa74d9SJeff Roberson 	return low.cs_cpu;
72962fa74d9SJeff Roberson }
73062fa74d9SJeff Roberson 
73162fa74d9SJeff Roberson /*
73262fa74d9SJeff Roberson  * Find the cpu with the highest load via the highest loaded path.
73362fa74d9SJeff Roberson  */
73462fa74d9SJeff Roberson static inline int
73536acfc65SAlexander Motin sched_highest(const struct cpu_group *cg, cpuset_t mask, int minload)
73662fa74d9SJeff Roberson {
73762fa74d9SJeff Roberson 	struct cpu_search high;
73862fa74d9SJeff Roberson 
73962fa74d9SJeff Roberson 	high.cs_cpu = -1;
74062fa74d9SJeff Roberson 	high.cs_mask = mask;
74162fa74d9SJeff Roberson 	high.cs_limit = minload;
74262fa74d9SJeff Roberson 	cpu_search_highest(cg, &high);
74362fa74d9SJeff Roberson 	return high.cs_cpu;
74462fa74d9SJeff Roberson }
74562fa74d9SJeff Roberson 
74662fa74d9SJeff Roberson /*
74762fa74d9SJeff Roberson  * Simultaneously find the highest and lowest loaded cpu reachable via
74862fa74d9SJeff Roberson  * cg.
74962fa74d9SJeff Roberson  */
75062fa74d9SJeff Roberson static inline void
75136acfc65SAlexander Motin sched_both(const struct cpu_group *cg, cpuset_t mask, int *lowcpu, int *highcpu)
75262fa74d9SJeff Roberson {
75362fa74d9SJeff Roberson 	struct cpu_search high;
75462fa74d9SJeff Roberson 	struct cpu_search low;
75562fa74d9SJeff Roberson 
75662fa74d9SJeff Roberson 	low.cs_cpu = -1;
75736acfc65SAlexander Motin 	low.cs_prefer = -1;
75836acfc65SAlexander Motin 	low.cs_pri = -1;
75936acfc65SAlexander Motin 	low.cs_limit = INT_MAX;
76062fa74d9SJeff Roberson 	low.cs_mask = mask;
76162fa74d9SJeff Roberson 	high.cs_cpu = -1;
76262fa74d9SJeff Roberson 	high.cs_limit = -1;
76362fa74d9SJeff Roberson 	high.cs_mask = mask;
76462fa74d9SJeff Roberson 	cpu_search_both(cg, &low, &high);
76562fa74d9SJeff Roberson 	*lowcpu = low.cs_cpu;
76662fa74d9SJeff Roberson 	*highcpu = high.cs_cpu;
76762fa74d9SJeff Roberson 	return;
76862fa74d9SJeff Roberson }
76962fa74d9SJeff Roberson 
77062fa74d9SJeff Roberson static void
77162fa74d9SJeff Roberson sched_balance_group(struct cpu_group *cg)
77262fa74d9SJeff Roberson {
77336acfc65SAlexander Motin 	cpuset_t hmask, lmask;
77436acfc65SAlexander Motin 	int high, low, anylow;
77562fa74d9SJeff Roberson 
77636acfc65SAlexander Motin 	CPU_FILL(&hmask);
77762fa74d9SJeff Roberson 	for (;;) {
77836acfc65SAlexander Motin 		high = sched_highest(cg, hmask, 1);
77936acfc65SAlexander Motin 		/* Stop if there is no more CPU with transferrable threads. */
78036acfc65SAlexander Motin 		if (high == -1)
78162fa74d9SJeff Roberson 			break;
78236acfc65SAlexander Motin 		CPU_CLR(high, &hmask);
78336acfc65SAlexander Motin 		CPU_COPY(&hmask, &lmask);
78436acfc65SAlexander Motin 		/* Stop if there is no more CPU left for low. */
78536acfc65SAlexander Motin 		if (CPU_EMPTY(&lmask))
78662fa74d9SJeff Roberson 			break;
78736acfc65SAlexander Motin 		anylow = 1;
78836acfc65SAlexander Motin nextlow:
78936acfc65SAlexander Motin 		low = sched_lowest(cg, lmask, -1,
79036acfc65SAlexander Motin 		    TDQ_CPU(high)->tdq_load - 1, high);
79136acfc65SAlexander Motin 		/* Stop if we looked well and found no less loaded CPU. */
79236acfc65SAlexander Motin 		if (anylow && low == -1)
79336acfc65SAlexander Motin 			break;
79436acfc65SAlexander Motin 		/* Go to next high if we found no less loaded CPU. */
79536acfc65SAlexander Motin 		if (low == -1)
79636acfc65SAlexander Motin 			continue;
79736acfc65SAlexander Motin 		/* Transfer thread from high to low. */
79836acfc65SAlexander Motin 		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low))) {
79936acfc65SAlexander Motin 			/* CPU that got thread can no longer be a donor. */
80036acfc65SAlexander Motin 			CPU_CLR(low, &hmask);
80136acfc65SAlexander Motin 		} else {
80262fa74d9SJeff Roberson 			/*
80336acfc65SAlexander Motin 			 * If failed, then there is no threads on high
80436acfc65SAlexander Motin 			 * that can run on this low. Drop low from low
80536acfc65SAlexander Motin 			 * mask and look for different one.
80662fa74d9SJeff Roberson 			 */
80736acfc65SAlexander Motin 			CPU_CLR(low, &lmask);
80836acfc65SAlexander Motin 			anylow = 0;
80936acfc65SAlexander Motin 			goto nextlow;
81062fa74d9SJeff Roberson 		}
81136acfc65SAlexander Motin 	}
81262fa74d9SJeff Roberson }
81362fa74d9SJeff Roberson 
81462fa74d9SJeff Roberson static void
81562375ca8SEd Schouten sched_balance(void)
816356500a3SJeff Roberson {
8177fcf154aSJeff Roberson 	struct tdq *tdq;
818356500a3SJeff Roberson 
8197fcf154aSJeff Roberson 	/*
8207fcf154aSJeff Roberson 	 * Select a random time between .5 * balance_interval and
8217fcf154aSJeff Roberson 	 * 1.5 * balance_interval.
8227fcf154aSJeff Roberson 	 */
8237fcf154aSJeff Roberson 	balance_ticks = max(balance_interval / 2, 1);
8247fcf154aSJeff Roberson 	balance_ticks += random() % balance_interval;
825ae7a6b38SJeff Roberson 	if (smp_started == 0 || rebalance == 0)
826598b368dSJeff Roberson 		return;
8277fcf154aSJeff Roberson 	tdq = TDQ_SELF();
8287fcf154aSJeff Roberson 	TDQ_UNLOCK(tdq);
82962fa74d9SJeff Roberson 	sched_balance_group(cpu_top);
8307fcf154aSJeff Roberson 	TDQ_LOCK(tdq);
831cac77d04SJeff Roberson }
83286f8ae96SJeff Roberson 
833ae7a6b38SJeff Roberson /*
834ae7a6b38SJeff Roberson  * Lock two thread queues using their address to maintain lock order.
835ae7a6b38SJeff Roberson  */
836ae7a6b38SJeff Roberson static void
837ae7a6b38SJeff Roberson tdq_lock_pair(struct tdq *one, struct tdq *two)
838ae7a6b38SJeff Roberson {
839ae7a6b38SJeff Roberson 	if (one < two) {
840ae7a6b38SJeff Roberson 		TDQ_LOCK(one);
841ae7a6b38SJeff Roberson 		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
842ae7a6b38SJeff Roberson 	} else {
843ae7a6b38SJeff Roberson 		TDQ_LOCK(two);
844ae7a6b38SJeff Roberson 		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
845ae7a6b38SJeff Roberson 	}
846ae7a6b38SJeff Roberson }
847ae7a6b38SJeff Roberson 
848ae7a6b38SJeff Roberson /*
8497fcf154aSJeff Roberson  * Unlock two thread queues.  Order is not important here.
8507fcf154aSJeff Roberson  */
8517fcf154aSJeff Roberson static void
8527fcf154aSJeff Roberson tdq_unlock_pair(struct tdq *one, struct tdq *two)
8537fcf154aSJeff Roberson {
8547fcf154aSJeff Roberson 	TDQ_UNLOCK(one);
8557fcf154aSJeff Roberson 	TDQ_UNLOCK(two);
8567fcf154aSJeff Roberson }
8577fcf154aSJeff Roberson 
8587fcf154aSJeff Roberson /*
859ae7a6b38SJeff Roberson  * Transfer load between two imbalanced thread queues.
860ae7a6b38SJeff Roberson  */
86162fa74d9SJeff Roberson static int
862ad1e7d28SJulian Elischer sched_balance_pair(struct tdq *high, struct tdq *low)
863cac77d04SJeff Roberson {
86462fa74d9SJeff Roberson 	int moved;
865880bf8b9SMarius Strobl 	int cpu;
866cac77d04SJeff Roberson 
867ae7a6b38SJeff Roberson 	tdq_lock_pair(high, low);
86862fa74d9SJeff Roberson 	moved = 0;
869155b9987SJeff Roberson 	/*
870155b9987SJeff Roberson 	 * Determine what the imbalance is and then adjust that to how many
871d2ad694cSJeff Roberson 	 * threads we actually have to give up (transferable).
872155b9987SJeff Roberson 	 */
87336acfc65SAlexander Motin 	if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load &&
87436acfc65SAlexander Motin 	    (moved = tdq_move(high, low)) > 0) {
875a5423ea3SJeff Roberson 		/*
876880bf8b9SMarius Strobl 		 * In case the target isn't the current cpu IPI it to force a
877880bf8b9SMarius Strobl 		 * reschedule with the new workload.
878a5423ea3SJeff Roberson 		 */
879880bf8b9SMarius Strobl 		cpu = TDQ_ID(low);
880880bf8b9SMarius Strobl 		sched_pin();
881880bf8b9SMarius Strobl 		if (cpu != PCPU_GET(cpuid))
882880bf8b9SMarius Strobl 			ipi_cpu(cpu, IPI_PREEMPT);
883880bf8b9SMarius Strobl 		sched_unpin();
884ae7a6b38SJeff Roberson 	}
8857fcf154aSJeff Roberson 	tdq_unlock_pair(high, low);
88662fa74d9SJeff Roberson 	return (moved);
887356500a3SJeff Roberson }
888356500a3SJeff Roberson 
889ae7a6b38SJeff Roberson /*
890ae7a6b38SJeff Roberson  * Move a thread from one thread queue to another.
891ae7a6b38SJeff Roberson  */
89262fa74d9SJeff Roberson static int
893ae7a6b38SJeff Roberson tdq_move(struct tdq *from, struct tdq *to)
894356500a3SJeff Roberson {
895ad1e7d28SJulian Elischer 	struct td_sched *ts;
896ae7a6b38SJeff Roberson 	struct thread *td;
897ae7a6b38SJeff Roberson 	struct tdq *tdq;
898ae7a6b38SJeff Roberson 	int cpu;
899356500a3SJeff Roberson 
9007fcf154aSJeff Roberson 	TDQ_LOCK_ASSERT(from, MA_OWNED);
9017fcf154aSJeff Roberson 	TDQ_LOCK_ASSERT(to, MA_OWNED);
9027fcf154aSJeff Roberson 
903ad1e7d28SJulian Elischer 	tdq = from;
904ae7a6b38SJeff Roberson 	cpu = TDQ_ID(to);
9059727e637SJeff Roberson 	td = tdq_steal(tdq, cpu);
9069727e637SJeff Roberson 	if (td == NULL)
90762fa74d9SJeff Roberson 		return (0);
9089727e637SJeff Roberson 	ts = td->td_sched;
909ae7a6b38SJeff Roberson 	/*
910ae7a6b38SJeff Roberson 	 * Although the run queue is locked the thread may be blocked.  Lock
9117fcf154aSJeff Roberson 	 * it to clear this and acquire the run-queue lock.
912ae7a6b38SJeff Roberson 	 */
913ae7a6b38SJeff Roberson 	thread_lock(td);
9147fcf154aSJeff Roberson 	/* Drop recursive lock on from acquired via thread_lock(). */
915ae7a6b38SJeff Roberson 	TDQ_UNLOCK(from);
916ae7a6b38SJeff Roberson 	sched_rem(td);
9177b8bfa0dSJeff Roberson 	ts->ts_cpu = cpu;
918ae7a6b38SJeff Roberson 	td->td_lock = TDQ_LOCKPTR(to);
919ae7a6b38SJeff Roberson 	tdq_add(to, td, SRQ_YIELDING);
92062fa74d9SJeff Roberson 	return (1);
921356500a3SJeff Roberson }
92222bf7d9aSJeff Roberson 
923ae7a6b38SJeff Roberson /*
924ae7a6b38SJeff Roberson  * This tdq has idled.  Try to steal a thread from another cpu and switch
925ae7a6b38SJeff Roberson  * to it.
926ae7a6b38SJeff Roberson  */
92780f86c9fSJeff Roberson static int
928ad1e7d28SJulian Elischer tdq_idled(struct tdq *tdq)
92922bf7d9aSJeff Roberson {
93062fa74d9SJeff Roberson 	struct cpu_group *cg;
931ad1e7d28SJulian Elischer 	struct tdq *steal;
932c76ee827SJeff Roberson 	cpuset_t mask;
93362fa74d9SJeff Roberson 	int thresh;
934ae7a6b38SJeff Roberson 	int cpu;
93580f86c9fSJeff Roberson 
93688f530ccSJeff Roberson 	if (smp_started == 0 || steal_idle == 0)
93788f530ccSJeff Roberson 		return (1);
938c76ee827SJeff Roberson 	CPU_FILL(&mask);
939c76ee827SJeff Roberson 	CPU_CLR(PCPU_GET(cpuid), &mask);
94062fa74d9SJeff Roberson 	/* We don't want to be preempted while we're iterating. */
941ae7a6b38SJeff Roberson 	spinlock_enter();
94262fa74d9SJeff Roberson 	for (cg = tdq->tdq_cg; cg != NULL; ) {
9437b55ab05SJeff Roberson 		if ((cg->cg_flags & CG_FLAG_THREAD) == 0)
94462fa74d9SJeff Roberson 			thresh = steal_thresh;
94562fa74d9SJeff Roberson 		else
94662fa74d9SJeff Roberson 			thresh = 1;
94762fa74d9SJeff Roberson 		cpu = sched_highest(cg, mask, thresh);
94862fa74d9SJeff Roberson 		if (cpu == -1) {
94962fa74d9SJeff Roberson 			cg = cg->cg_parent;
95080f86c9fSJeff Roberson 			continue;
9517b8bfa0dSJeff Roberson 		}
9527b8bfa0dSJeff Roberson 		steal = TDQ_CPU(cpu);
953c76ee827SJeff Roberson 		CPU_CLR(cpu, &mask);
9547fcf154aSJeff Roberson 		tdq_lock_pair(tdq, steal);
95562fa74d9SJeff Roberson 		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
9567fcf154aSJeff Roberson 			tdq_unlock_pair(tdq, steal);
95762fa74d9SJeff Roberson 			continue;
95862fa74d9SJeff Roberson 		}
95962fa74d9SJeff Roberson 		/*
96062fa74d9SJeff Roberson 		 * If a thread was added while interrupts were disabled don't
96162fa74d9SJeff Roberson 		 * steal one here.  If we fail to acquire one due to affinity
96262fa74d9SJeff Roberson 		 * restrictions loop again with this cpu removed from the
96362fa74d9SJeff Roberson 		 * set.
96462fa74d9SJeff Roberson 		 */
96562fa74d9SJeff Roberson 		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
96662fa74d9SJeff Roberson 			tdq_unlock_pair(tdq, steal);
96762fa74d9SJeff Roberson 			continue;
96880f86c9fSJeff Roberson 		}
969ae7a6b38SJeff Roberson 		spinlock_exit();
970ae7a6b38SJeff Roberson 		TDQ_UNLOCK(steal);
9718df78c41SJeff Roberson 		mi_switch(SW_VOL | SWT_IDLE, NULL);
972ae7a6b38SJeff Roberson 		thread_unlock(curthread);
9737b8bfa0dSJeff Roberson 
9747b8bfa0dSJeff Roberson 		return (0);
97522bf7d9aSJeff Roberson 	}
97662fa74d9SJeff Roberson 	spinlock_exit();
97762fa74d9SJeff Roberson 	return (1);
97862fa74d9SJeff Roberson }
97922bf7d9aSJeff Roberson 
980ae7a6b38SJeff Roberson /*
981ae7a6b38SJeff Roberson  * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
982ae7a6b38SJeff Roberson  */
98322bf7d9aSJeff Roberson static void
9849727e637SJeff Roberson tdq_notify(struct tdq *tdq, struct thread *td)
98522bf7d9aSJeff Roberson {
98602f0ff6dSJohn Baldwin 	struct thread *ctd;
987fc3a97dcSJeff Roberson 	int pri;
9887b8bfa0dSJeff Roberson 	int cpu;
98922bf7d9aSJeff Roberson 
990ff256d9cSJeff Roberson 	if (tdq->tdq_ipipending)
991ff256d9cSJeff Roberson 		return;
9929727e637SJeff Roberson 	cpu = td->td_sched->ts_cpu;
9939727e637SJeff Roberson 	pri = td->td_priority;
99402f0ff6dSJohn Baldwin 	ctd = pcpu_find(cpu)->pc_curthread;
99502f0ff6dSJohn Baldwin 	if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
9966b2f763fSJeff Roberson 		return;
99702f0ff6dSJohn Baldwin 	if (TD_IS_IDLETHREAD(ctd)) {
9981690c6c1SJeff Roberson 		/*
9996c47aaaeSJeff Roberson 		 * If the MD code has an idle wakeup routine try that before
10006c47aaaeSJeff Roberson 		 * falling back to IPI.
10016c47aaaeSJeff Roberson 		 */
10029f9ad565SAlexander Motin 		if (!tdq->tdq_cpu_idle || cpu_idle_wakeup(cpu))
10036c47aaaeSJeff Roberson 			return;
10041690c6c1SJeff Roberson 	}
1005ff256d9cSJeff Roberson 	tdq->tdq_ipipending = 1;
1006d9d8d144SJohn Baldwin 	ipi_cpu(cpu, IPI_PREEMPT);
100722bf7d9aSJeff Roberson }
100822bf7d9aSJeff Roberson 
1009ae7a6b38SJeff Roberson /*
1010ae7a6b38SJeff Roberson  * Steals load from a timeshare queue.  Honors the rotating queue head
1011ae7a6b38SJeff Roberson  * index.
1012ae7a6b38SJeff Roberson  */
10139727e637SJeff Roberson static struct thread *
101462fa74d9SJeff Roberson runq_steal_from(struct runq *rq, int cpu, u_char start)
1015ae7a6b38SJeff Roberson {
1016ae7a6b38SJeff Roberson 	struct rqbits *rqb;
1017ae7a6b38SJeff Roberson 	struct rqhead *rqh;
101836acfc65SAlexander Motin 	struct thread *td, *first;
1019ae7a6b38SJeff Roberson 	int bit;
1020ae7a6b38SJeff Roberson 	int pri;
1021ae7a6b38SJeff Roberson 	int i;
1022ae7a6b38SJeff Roberson 
1023ae7a6b38SJeff Roberson 	rqb = &rq->rq_status;
1024ae7a6b38SJeff Roberson 	bit = start & (RQB_BPW -1);
1025ae7a6b38SJeff Roberson 	pri = 0;
102636acfc65SAlexander Motin 	first = NULL;
1027ae7a6b38SJeff Roberson again:
1028ae7a6b38SJeff Roberson 	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1029ae7a6b38SJeff Roberson 		if (rqb->rqb_bits[i] == 0)
1030ae7a6b38SJeff Roberson 			continue;
1031ae7a6b38SJeff Roberson 		if (bit != 0) {
1032ae7a6b38SJeff Roberson 			for (pri = bit; pri < RQB_BPW; pri++)
1033ae7a6b38SJeff Roberson 				if (rqb->rqb_bits[i] & (1ul << pri))
1034ae7a6b38SJeff Roberson 					break;
1035ae7a6b38SJeff Roberson 			if (pri >= RQB_BPW)
1036ae7a6b38SJeff Roberson 				continue;
1037ae7a6b38SJeff Roberson 		} else
1038ae7a6b38SJeff Roberson 			pri = RQB_FFS(rqb->rqb_bits[i]);
1039ae7a6b38SJeff Roberson 		pri += (i << RQB_L2BPW);
1040ae7a6b38SJeff Roberson 		rqh = &rq->rq_queues[pri];
10419727e637SJeff Roberson 		TAILQ_FOREACH(td, rqh, td_runq) {
10429727e637SJeff Roberson 			if (first && THREAD_CAN_MIGRATE(td) &&
10439727e637SJeff Roberson 			    THREAD_CAN_SCHED(td, cpu))
10449727e637SJeff Roberson 				return (td);
104536acfc65SAlexander Motin 			first = td;
1046ae7a6b38SJeff Roberson 		}
1047ae7a6b38SJeff Roberson 	}
1048ae7a6b38SJeff Roberson 	if (start != 0) {
1049ae7a6b38SJeff Roberson 		start = 0;
1050ae7a6b38SJeff Roberson 		goto again;
1051ae7a6b38SJeff Roberson 	}
1052ae7a6b38SJeff Roberson 
105336acfc65SAlexander Motin 	if (first && THREAD_CAN_MIGRATE(first) &&
105436acfc65SAlexander Motin 	    THREAD_CAN_SCHED(first, cpu))
105536acfc65SAlexander Motin 		return (first);
1056ae7a6b38SJeff Roberson 	return (NULL);
1057ae7a6b38SJeff Roberson }
1058ae7a6b38SJeff Roberson 
1059ae7a6b38SJeff Roberson /*
1060ae7a6b38SJeff Roberson  * Steals load from a standard linear queue.
1061ae7a6b38SJeff Roberson  */
10629727e637SJeff Roberson static struct thread *
106362fa74d9SJeff Roberson runq_steal(struct runq *rq, int cpu)
106422bf7d9aSJeff Roberson {
106522bf7d9aSJeff Roberson 	struct rqhead *rqh;
106622bf7d9aSJeff Roberson 	struct rqbits *rqb;
10679727e637SJeff Roberson 	struct thread *td;
106822bf7d9aSJeff Roberson 	int word;
106922bf7d9aSJeff Roberson 	int bit;
107022bf7d9aSJeff Roberson 
107122bf7d9aSJeff Roberson 	rqb = &rq->rq_status;
107222bf7d9aSJeff Roberson 	for (word = 0; word < RQB_LEN; word++) {
107322bf7d9aSJeff Roberson 		if (rqb->rqb_bits[word] == 0)
107422bf7d9aSJeff Roberson 			continue;
107522bf7d9aSJeff Roberson 		for (bit = 0; bit < RQB_BPW; bit++) {
1076a2640c9bSPeter Wemm 			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
107722bf7d9aSJeff Roberson 				continue;
107822bf7d9aSJeff Roberson 			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
10799727e637SJeff Roberson 			TAILQ_FOREACH(td, rqh, td_runq)
10809727e637SJeff Roberson 				if (THREAD_CAN_MIGRATE(td) &&
10819727e637SJeff Roberson 				    THREAD_CAN_SCHED(td, cpu))
10829727e637SJeff Roberson 					return (td);
108322bf7d9aSJeff Roberson 		}
108422bf7d9aSJeff Roberson 	}
108522bf7d9aSJeff Roberson 	return (NULL);
108622bf7d9aSJeff Roberson }
108722bf7d9aSJeff Roberson 
1088ae7a6b38SJeff Roberson /*
1089ae7a6b38SJeff Roberson  * Attempt to steal a thread in priority order from a thread queue.
1090ae7a6b38SJeff Roberson  */
10919727e637SJeff Roberson static struct thread *
109262fa74d9SJeff Roberson tdq_steal(struct tdq *tdq, int cpu)
109322bf7d9aSJeff Roberson {
10949727e637SJeff Roberson 	struct thread *td;
109522bf7d9aSJeff Roberson 
1096ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
10979727e637SJeff Roberson 	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
10989727e637SJeff Roberson 		return (td);
10999727e637SJeff Roberson 	if ((td = runq_steal_from(&tdq->tdq_timeshare,
11009727e637SJeff Roberson 	    cpu, tdq->tdq_ridx)) != NULL)
11019727e637SJeff Roberson 		return (td);
110262fa74d9SJeff Roberson 	return (runq_steal(&tdq->tdq_idle, cpu));
110322bf7d9aSJeff Roberson }
110480f86c9fSJeff Roberson 
1105ae7a6b38SJeff Roberson /*
1106ae7a6b38SJeff Roberson  * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
11077fcf154aSJeff Roberson  * current lock and returns with the assigned queue locked.
1108ae7a6b38SJeff Roberson  */
1109ae7a6b38SJeff Roberson static inline struct tdq *
11109727e637SJeff Roberson sched_setcpu(struct thread *td, int cpu, int flags)
111180f86c9fSJeff Roberson {
11129727e637SJeff Roberson 
1113ae7a6b38SJeff Roberson 	struct tdq *tdq;
111480f86c9fSJeff Roberson 
11159727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1116ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpu);
11179727e637SJeff Roberson 	td->td_sched->ts_cpu = cpu;
11189727e637SJeff Roberson 	/*
11199727e637SJeff Roberson 	 * If the lock matches just return the queue.
11209727e637SJeff Roberson 	 */
1121ae7a6b38SJeff Roberson 	if (td->td_lock == TDQ_LOCKPTR(tdq))
1122ae7a6b38SJeff Roberson 		return (tdq);
1123ae7a6b38SJeff Roberson #ifdef notyet
112480f86c9fSJeff Roberson 	/*
1125a5423ea3SJeff Roberson 	 * If the thread isn't running its lockptr is a
1126ae7a6b38SJeff Roberson 	 * turnstile or a sleepqueue.  We can just lock_set without
1127ae7a6b38SJeff Roberson 	 * blocking.
1128670c524fSJeff Roberson 	 */
1129ae7a6b38SJeff Roberson 	if (TD_CAN_RUN(td)) {
1130ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
1131ae7a6b38SJeff Roberson 		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1132ae7a6b38SJeff Roberson 		return (tdq);
1133ae7a6b38SJeff Roberson 	}
1134ae7a6b38SJeff Roberson #endif
113580f86c9fSJeff Roberson 	/*
1136ae7a6b38SJeff Roberson 	 * The hard case, migration, we need to block the thread first to
1137ae7a6b38SJeff Roberson 	 * prevent order reversals with other cpus locks.
11387b8bfa0dSJeff Roberson 	 */
1139b0b9dee5SAttilio Rao 	spinlock_enter();
1140ae7a6b38SJeff Roberson 	thread_lock_block(td);
1141ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
1142ae7a6b38SJeff Roberson 	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1143b0b9dee5SAttilio Rao 	spinlock_exit();
1144ae7a6b38SJeff Roberson 	return (tdq);
114580f86c9fSJeff Roberson }
11462454aaf5SJeff Roberson 
11478df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
11488df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
11498df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
11508df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
11518df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
11528df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
11538df78c41SJeff Roberson 
1154ae7a6b38SJeff Roberson static int
11559727e637SJeff Roberson sched_pickcpu(struct thread *td, int flags)
1156ae7a6b38SJeff Roberson {
115736acfc65SAlexander Motin 	struct cpu_group *cg, *ccg;
11589727e637SJeff Roberson 	struct td_sched *ts;
1159ae7a6b38SJeff Roberson 	struct tdq *tdq;
1160c76ee827SJeff Roberson 	cpuset_t mask;
116136acfc65SAlexander Motin 	int cpu, pri, self;
11627b8bfa0dSJeff Roberson 
116362fa74d9SJeff Roberson 	self = PCPU_GET(cpuid);
11649727e637SJeff Roberson 	ts = td->td_sched;
11657b8bfa0dSJeff Roberson 	if (smp_started == 0)
11667b8bfa0dSJeff Roberson 		return (self);
116728994a58SJeff Roberson 	/*
116828994a58SJeff Roberson 	 * Don't migrate a running thread from sched_switch().
116928994a58SJeff Roberson 	 */
117062fa74d9SJeff Roberson 	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
117162fa74d9SJeff Roberson 		return (ts->ts_cpu);
11727b8bfa0dSJeff Roberson 	/*
117362fa74d9SJeff Roberson 	 * Prefer to run interrupt threads on the processors that generate
117462fa74d9SJeff Roberson 	 * the interrupt.
11757b8bfa0dSJeff Roberson 	 */
117636acfc65SAlexander Motin 	pri = td->td_priority;
117762fa74d9SJeff Roberson 	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
11788df78c41SJeff Roberson 	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
11798df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_intrbind);
118062fa74d9SJeff Roberson 		ts->ts_cpu = self;
118136acfc65SAlexander Motin 		if (TDQ_CPU(self)->tdq_lowpri > pri) {
11828df78c41SJeff Roberson 			SCHED_STAT_INC(pickcpu_affinity);
11837b8bfa0dSJeff Roberson 			return (ts->ts_cpu);
11847b8bfa0dSJeff Roberson 		}
11858df78c41SJeff Roberson 	}
11867b8bfa0dSJeff Roberson 	/*
118736acfc65SAlexander Motin 	 * If the thread can run on the last cpu and the affinity has not
118836acfc65SAlexander Motin 	 * expired or it is idle run it there.
11897b8bfa0dSJeff Roberson 	 */
119036acfc65SAlexander Motin 	tdq = TDQ_CPU(ts->ts_cpu);
119136acfc65SAlexander Motin 	cg = tdq->tdq_cg;
119236acfc65SAlexander Motin 	if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
119336acfc65SAlexander Motin 	    tdq->tdq_lowpri >= PRI_MIN_IDLE &&
119436acfc65SAlexander Motin 	    SCHED_AFFINITY(ts, CG_SHARE_L2)) {
119536acfc65SAlexander Motin 		if (cg->cg_flags & CG_FLAG_THREAD) {
119636acfc65SAlexander Motin 			CPUSET_FOREACH(cpu, cg->cg_mask) {
119736acfc65SAlexander Motin 				if (TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE)
119862fa74d9SJeff Roberson 					break;
119936acfc65SAlexander Motin 			}
120036acfc65SAlexander Motin 		} else
120136acfc65SAlexander Motin 			cpu = INT_MAX;
120236acfc65SAlexander Motin 		if (cpu > mp_maxid) {
120336acfc65SAlexander Motin 			SCHED_STAT_INC(pickcpu_idle_affinity);
120436acfc65SAlexander Motin 			return (ts->ts_cpu);
120536acfc65SAlexander Motin 		}
120636acfc65SAlexander Motin 	}
120736acfc65SAlexander Motin 	/*
120836acfc65SAlexander Motin 	 * Search for the last level cache CPU group in the tree.
120936acfc65SAlexander Motin 	 * Skip caches with expired affinity time and SMT groups.
121036acfc65SAlexander Motin 	 * Affinity to higher level caches will be handled less aggressively.
121136acfc65SAlexander Motin 	 */
121236acfc65SAlexander Motin 	for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
121336acfc65SAlexander Motin 		if (cg->cg_flags & CG_FLAG_THREAD)
121436acfc65SAlexander Motin 			continue;
121536acfc65SAlexander Motin 		if (!SCHED_AFFINITY(ts, cg->cg_level))
121636acfc65SAlexander Motin 			continue;
121736acfc65SAlexander Motin 		ccg = cg;
121836acfc65SAlexander Motin 	}
121936acfc65SAlexander Motin 	if (ccg != NULL)
122036acfc65SAlexander Motin 		cg = ccg;
122162fa74d9SJeff Roberson 	cpu = -1;
122236acfc65SAlexander Motin 	/* Search the group for the less loaded idle CPU we can run now. */
1223c76ee827SJeff Roberson 	mask = td->td_cpuset->cs_mask;
122436acfc65SAlexander Motin 	if (cg != NULL && cg != cpu_top &&
122536acfc65SAlexander Motin 	    CPU_CMP(&cg->cg_mask, &cpu_top->cg_mask) != 0)
122636acfc65SAlexander Motin 		cpu = sched_lowest(cg, mask, max(pri, PRI_MAX_TIMESHARE),
122736acfc65SAlexander Motin 		    INT_MAX, ts->ts_cpu);
122836acfc65SAlexander Motin 	/* Search globally for the less loaded CPU we can run now. */
122962fa74d9SJeff Roberson 	if (cpu == -1)
123036acfc65SAlexander Motin 		cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu);
123136acfc65SAlexander Motin 	/* Search globally for the less loaded CPU. */
123236acfc65SAlexander Motin 	if (cpu == -1)
123336acfc65SAlexander Motin 		cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu);
12346022f0bcSAlexander Motin 	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
123562fa74d9SJeff Roberson 	/*
123662fa74d9SJeff Roberson 	 * Compare the lowest loaded cpu to current cpu.
123762fa74d9SJeff Roberson 	 */
1238ff256d9cSJeff Roberson 	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
123936acfc65SAlexander Motin 	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE &&
124036acfc65SAlexander Motin 	    TDQ_CPU(self)->tdq_load <= TDQ_CPU(cpu)->tdq_load + 1) {
12418df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_local);
124262fa74d9SJeff Roberson 		cpu = self;
12438df78c41SJeff Roberson 	} else
12448df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_lowest);
12458df78c41SJeff Roberson 	if (cpu != ts->ts_cpu)
12468df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_migration);
1247ae7a6b38SJeff Roberson 	return (cpu);
124880f86c9fSJeff Roberson }
124962fa74d9SJeff Roberson #endif
125022bf7d9aSJeff Roberson 
125122bf7d9aSJeff Roberson /*
125222bf7d9aSJeff Roberson  * Pick the highest priority task we have and return it.
12530c0a98b2SJeff Roberson  */
12549727e637SJeff Roberson static struct thread *
1255ad1e7d28SJulian Elischer tdq_choose(struct tdq *tdq)
12565d7ef00cSJeff Roberson {
12579727e637SJeff Roberson 	struct thread *td;
12585d7ef00cSJeff Roberson 
1259ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
12609727e637SJeff Roberson 	td = runq_choose(&tdq->tdq_realtime);
12619727e637SJeff Roberson 	if (td != NULL)
12629727e637SJeff Roberson 		return (td);
12639727e637SJeff Roberson 	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
12649727e637SJeff Roberson 	if (td != NULL) {
126512d56c0fSJohn Baldwin 		KASSERT(td->td_priority >= PRI_MIN_BATCH,
1266e7d50326SJeff Roberson 		    ("tdq_choose: Invalid priority on timeshare queue %d",
12679727e637SJeff Roberson 		    td->td_priority));
12689727e637SJeff Roberson 		return (td);
126915dc847eSJeff Roberson 	}
12709727e637SJeff Roberson 	td = runq_choose(&tdq->tdq_idle);
12719727e637SJeff Roberson 	if (td != NULL) {
12729727e637SJeff Roberson 		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1273e7d50326SJeff Roberson 		    ("tdq_choose: Invalid priority on idle queue %d",
12749727e637SJeff Roberson 		    td->td_priority));
12759727e637SJeff Roberson 		return (td);
1276e7d50326SJeff Roberson 	}
1277e7d50326SJeff Roberson 
1278e7d50326SJeff Roberson 	return (NULL);
1279245f3abfSJeff Roberson }
12800a016a05SJeff Roberson 
1281ae7a6b38SJeff Roberson /*
1282ae7a6b38SJeff Roberson  * Initialize a thread queue.
1283ae7a6b38SJeff Roberson  */
12840a016a05SJeff Roberson static void
1285ad1e7d28SJulian Elischer tdq_setup(struct tdq *tdq)
12860a016a05SJeff Roberson {
1287ae7a6b38SJeff Roberson 
1288c47f202bSJeff Roberson 	if (bootverbose)
1289c47f202bSJeff Roberson 		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1290e7d50326SJeff Roberson 	runq_init(&tdq->tdq_realtime);
1291e7d50326SJeff Roberson 	runq_init(&tdq->tdq_timeshare);
1292d2ad694cSJeff Roberson 	runq_init(&tdq->tdq_idle);
129362fa74d9SJeff Roberson 	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
129462fa74d9SJeff Roberson 	    "sched lock %d", (int)TDQ_ID(tdq));
129562fa74d9SJeff Roberson 	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
129662fa74d9SJeff Roberson 	    MTX_SPIN | MTX_RECURSE);
12978f51ad55SJeff Roberson #ifdef KTR
12988f51ad55SJeff Roberson 	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
12998f51ad55SJeff Roberson 	    "CPU %d load", (int)TDQ_ID(tdq));
13008f51ad55SJeff Roberson #endif
13010a016a05SJeff Roberson }
13020a016a05SJeff Roberson 
1303c47f202bSJeff Roberson #ifdef SMP
1304c47f202bSJeff Roberson static void
1305c47f202bSJeff Roberson sched_setup_smp(void)
1306c47f202bSJeff Roberson {
1307c47f202bSJeff Roberson 	struct tdq *tdq;
1308c47f202bSJeff Roberson 	int i;
1309c47f202bSJeff Roberson 
131062fa74d9SJeff Roberson 	cpu_top = smp_topo();
13113aa6d94eSJohn Baldwin 	CPU_FOREACH(i) {
131262fa74d9SJeff Roberson 		tdq = TDQ_CPU(i);
1313c47f202bSJeff Roberson 		tdq_setup(tdq);
131462fa74d9SJeff Roberson 		tdq->tdq_cg = smp_topo_find(cpu_top, i);
131562fa74d9SJeff Roberson 		if (tdq->tdq_cg == NULL)
131662fa74d9SJeff Roberson 			panic("Can't find cpu group for %d\n", i);
1317c47f202bSJeff Roberson 	}
131862fa74d9SJeff Roberson 	balance_tdq = TDQ_SELF();
131962fa74d9SJeff Roberson 	sched_balance();
1320c47f202bSJeff Roberson }
1321c47f202bSJeff Roberson #endif
1322c47f202bSJeff Roberson 
1323ae7a6b38SJeff Roberson /*
1324ae7a6b38SJeff Roberson  * Setup the thread queues and initialize the topology based on MD
1325ae7a6b38SJeff Roberson  * information.
1326ae7a6b38SJeff Roberson  */
132735e6168fSJeff Roberson static void
132835e6168fSJeff Roberson sched_setup(void *dummy)
132935e6168fSJeff Roberson {
1330ae7a6b38SJeff Roberson 	struct tdq *tdq;
1331c47f202bSJeff Roberson 
1332c47f202bSJeff Roberson 	tdq = TDQ_SELF();
13330ec896fdSJeff Roberson #ifdef SMP
1334c47f202bSJeff Roberson 	sched_setup_smp();
1335749d01b0SJeff Roberson #else
1336c47f202bSJeff Roberson 	tdq_setup(tdq);
1337356500a3SJeff Roberson #endif
1338ae7a6b38SJeff Roberson 	/*
1339ae7a6b38SJeff Roberson 	 * To avoid divide-by-zero, we set realstathz a dummy value
1340ae7a6b38SJeff Roberson 	 * in case which sched_clock() called before sched_initticks().
1341ae7a6b38SJeff Roberson 	 */
1342ae7a6b38SJeff Roberson 	realstathz = hz;
1343ae7a6b38SJeff Roberson 	sched_slice = (realstathz/10);	/* ~100ms */
1344ae7a6b38SJeff Roberson 	tickincr = 1 << SCHED_TICK_SHIFT;
1345ae7a6b38SJeff Roberson 
1346ae7a6b38SJeff Roberson 	/* Add thread0's load since it's running. */
1347ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
1348c47f202bSJeff Roberson 	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
13499727e637SJeff Roberson 	tdq_load_add(tdq, &thread0);
135062fa74d9SJeff Roberson 	tdq->tdq_lowpri = thread0.td_priority;
1351ae7a6b38SJeff Roberson 	TDQ_UNLOCK(tdq);
135235e6168fSJeff Roberson }
135335e6168fSJeff Roberson 
1354ae7a6b38SJeff Roberson /*
1355ae7a6b38SJeff Roberson  * This routine determines the tickincr after stathz and hz are setup.
1356ae7a6b38SJeff Roberson  */
1357a1d4fe69SDavid Xu /* ARGSUSED */
1358a1d4fe69SDavid Xu static void
1359a1d4fe69SDavid Xu sched_initticks(void *dummy)
1360a1d4fe69SDavid Xu {
1361ae7a6b38SJeff Roberson 	int incr;
1362ae7a6b38SJeff Roberson 
1363a1d4fe69SDavid Xu 	realstathz = stathz ? stathz : hz;
136414618990SJeff Roberson 	sched_slice = (realstathz/10);	/* ~100ms */
1365a1d4fe69SDavid Xu 
1366a1d4fe69SDavid Xu 	/*
1367e7d50326SJeff Roberson 	 * tickincr is shifted out by 10 to avoid rounding errors due to
13683f872f85SJeff Roberson 	 * hz not being evenly divisible by stathz on all platforms.
1369e7d50326SJeff Roberson 	 */
1370ae7a6b38SJeff Roberson 	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1371e7d50326SJeff Roberson 	/*
1372e7d50326SJeff Roberson 	 * This does not work for values of stathz that are more than
1373e7d50326SJeff Roberson 	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1374a1d4fe69SDavid Xu 	 */
1375ae7a6b38SJeff Roberson 	if (incr == 0)
1376ae7a6b38SJeff Roberson 		incr = 1;
1377ae7a6b38SJeff Roberson 	tickincr = incr;
13787b8bfa0dSJeff Roberson #ifdef SMP
13799862717aSJeff Roberson 	/*
13807fcf154aSJeff Roberson 	 * Set the default balance interval now that we know
13817fcf154aSJeff Roberson 	 * what realstathz is.
13827fcf154aSJeff Roberson 	 */
13837fcf154aSJeff Roberson 	balance_interval = realstathz;
13847fcf154aSJeff Roberson 	/*
138553a6c8b3SJeff Roberson 	 * Set steal thresh to roughly log2(mp_ncpu) but no greater than 4.
138653a6c8b3SJeff Roberson 	 * This prevents excess thrashing on large machines and excess idle
138753a6c8b3SJeff Roberson 	 * on smaller machines.
13889862717aSJeff Roberson 	 */
138953a6c8b3SJeff Roberson 	steal_thresh = min(fls(mp_ncpus) - 1, 3);
13907b8bfa0dSJeff Roberson 	affinity = SCHED_AFFINITY_DEFAULT;
13917b8bfa0dSJeff Roberson #endif
1392b3f40a41SAlexander Motin 	if (sched_idlespinthresh < 0)
1393b3f40a41SAlexander Motin 		sched_idlespinthresh = max(16, 2 * hz / realstathz);
1394a1d4fe69SDavid Xu }
1395a1d4fe69SDavid Xu 
1396a1d4fe69SDavid Xu 
139735e6168fSJeff Roberson /*
1398ae7a6b38SJeff Roberson  * This is the core of the interactivity algorithm.  Determines a score based
1399ae7a6b38SJeff Roberson  * on past behavior.  It is the ratio of sleep time to run time scaled to
1400ae7a6b38SJeff Roberson  * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1401ae7a6b38SJeff Roberson  * differs from the cpu usage because it does not account for time spent
1402ae7a6b38SJeff Roberson  * waiting on a run-queue.  Would be prettier if we had floating point.
1403ae7a6b38SJeff Roberson  */
1404ae7a6b38SJeff Roberson static int
1405ae7a6b38SJeff Roberson sched_interact_score(struct thread *td)
1406ae7a6b38SJeff Roberson {
1407ae7a6b38SJeff Roberson 	struct td_sched *ts;
1408ae7a6b38SJeff Roberson 	int div;
1409ae7a6b38SJeff Roberson 
1410ae7a6b38SJeff Roberson 	ts = td->td_sched;
1411ae7a6b38SJeff Roberson 	/*
1412ae7a6b38SJeff Roberson 	 * The score is only needed if this is likely to be an interactive
1413ae7a6b38SJeff Roberson 	 * task.  Don't go through the expense of computing it if there's
1414ae7a6b38SJeff Roberson 	 * no chance.
1415ae7a6b38SJeff Roberson 	 */
1416ae7a6b38SJeff Roberson 	if (sched_interact <= SCHED_INTERACT_HALF &&
1417ae7a6b38SJeff Roberson 		ts->ts_runtime >= ts->ts_slptime)
1418ae7a6b38SJeff Roberson 			return (SCHED_INTERACT_HALF);
1419ae7a6b38SJeff Roberson 
1420ae7a6b38SJeff Roberson 	if (ts->ts_runtime > ts->ts_slptime) {
1421ae7a6b38SJeff Roberson 		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1422ae7a6b38SJeff Roberson 		return (SCHED_INTERACT_HALF +
1423ae7a6b38SJeff Roberson 		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1424ae7a6b38SJeff Roberson 	}
1425ae7a6b38SJeff Roberson 	if (ts->ts_slptime > ts->ts_runtime) {
1426ae7a6b38SJeff Roberson 		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1427ae7a6b38SJeff Roberson 		return (ts->ts_runtime / div);
1428ae7a6b38SJeff Roberson 	}
1429ae7a6b38SJeff Roberson 	/* runtime == slptime */
1430ae7a6b38SJeff Roberson 	if (ts->ts_runtime)
1431ae7a6b38SJeff Roberson 		return (SCHED_INTERACT_HALF);
1432ae7a6b38SJeff Roberson 
1433ae7a6b38SJeff Roberson 	/*
1434ae7a6b38SJeff Roberson 	 * This can happen if slptime and runtime are 0.
1435ae7a6b38SJeff Roberson 	 */
1436ae7a6b38SJeff Roberson 	return (0);
1437ae7a6b38SJeff Roberson 
1438ae7a6b38SJeff Roberson }
1439ae7a6b38SJeff Roberson 
1440ae7a6b38SJeff Roberson /*
144135e6168fSJeff Roberson  * Scale the scheduling priority according to the "interactivity" of this
144235e6168fSJeff Roberson  * process.
144335e6168fSJeff Roberson  */
144415dc847eSJeff Roberson static void
14458460a577SJohn Birrell sched_priority(struct thread *td)
144635e6168fSJeff Roberson {
1447e7d50326SJeff Roberson 	int score;
144835e6168fSJeff Roberson 	int pri;
144935e6168fSJeff Roberson 
1450c9a8cba4SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
145115dc847eSJeff Roberson 		return;
1452e7d50326SJeff Roberson 	/*
1453e7d50326SJeff Roberson 	 * If the score is interactive we place the thread in the realtime
1454e7d50326SJeff Roberson 	 * queue with a priority that is less than kernel and interrupt
1455e7d50326SJeff Roberson 	 * priorities.  These threads are not subject to nice restrictions.
1456e7d50326SJeff Roberson 	 *
1457ae7a6b38SJeff Roberson 	 * Scores greater than this are placed on the normal timeshare queue
1458e7d50326SJeff Roberson 	 * where the priority is partially decided by the most recent cpu
1459e7d50326SJeff Roberson 	 * utilization and the rest is decided by nice value.
1460a5423ea3SJeff Roberson 	 *
1461a5423ea3SJeff Roberson 	 * The nice value of the process has a linear effect on the calculated
1462a5423ea3SJeff Roberson 	 * score.  Negative nice values make it easier for a thread to be
1463a5423ea3SJeff Roberson 	 * considered interactive.
1464e7d50326SJeff Roberson 	 */
1465a0f15352SJohn Baldwin 	score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1466e7d50326SJeff Roberson 	if (score < sched_interact) {
146712d56c0fSJohn Baldwin 		pri = PRI_MIN_INTERACT;
146812d56c0fSJohn Baldwin 		pri += ((PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) /
146978920008SJohn Baldwin 		    sched_interact) * score;
147012d56c0fSJohn Baldwin 		KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
14719a93305aSJeff Roberson 		    ("sched_priority: invalid interactive priority %d score %d",
14729a93305aSJeff Roberson 		    pri, score));
1473e7d50326SJeff Roberson 	} else {
1474e7d50326SJeff Roberson 		pri = SCHED_PRI_MIN;
1475e7d50326SJeff Roberson 		if (td->td_sched->ts_ticks)
14760c0d27d5SJohn Baldwin 			pri += min(SCHED_PRI_TICKS(td->td_sched),
14770c0d27d5SJohn Baldwin 			    SCHED_PRI_RANGE);
1478e7d50326SJeff Roberson 		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
147912d56c0fSJohn Baldwin 		KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
1480ae7a6b38SJeff Roberson 		    ("sched_priority: invalid priority %d: nice %d, "
1481ae7a6b38SJeff Roberson 		    "ticks %d ftick %d ltick %d tick pri %d",
1482ae7a6b38SJeff Roberson 		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1483ae7a6b38SJeff Roberson 		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1484ae7a6b38SJeff Roberson 		    SCHED_PRI_TICKS(td->td_sched)));
1485e7d50326SJeff Roberson 	}
14868460a577SJohn Birrell 	sched_user_prio(td, pri);
148735e6168fSJeff Roberson 
148815dc847eSJeff Roberson 	return;
148935e6168fSJeff Roberson }
149035e6168fSJeff Roberson 
149135e6168fSJeff Roberson /*
1492d322132cSJeff Roberson  * This routine enforces a maximum limit on the amount of scheduling history
1493ae7a6b38SJeff Roberson  * kept.  It is called after either the slptime or runtime is adjusted.  This
1494ae7a6b38SJeff Roberson  * function is ugly due to integer math.
1495d322132cSJeff Roberson  */
14964b60e324SJeff Roberson static void
14978460a577SJohn Birrell sched_interact_update(struct thread *td)
14984b60e324SJeff Roberson {
1499155b6ca1SJeff Roberson 	struct td_sched *ts;
15009a93305aSJeff Roberson 	u_int sum;
15013f741ca1SJeff Roberson 
1502155b6ca1SJeff Roberson 	ts = td->td_sched;
1503ae7a6b38SJeff Roberson 	sum = ts->ts_runtime + ts->ts_slptime;
1504d322132cSJeff Roberson 	if (sum < SCHED_SLP_RUN_MAX)
1505d322132cSJeff Roberson 		return;
1506d322132cSJeff Roberson 	/*
1507155b6ca1SJeff Roberson 	 * This only happens from two places:
1508155b6ca1SJeff Roberson 	 * 1) We have added an unusual amount of run time from fork_exit.
1509155b6ca1SJeff Roberson 	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1510155b6ca1SJeff Roberson 	 */
1511155b6ca1SJeff Roberson 	if (sum > SCHED_SLP_RUN_MAX * 2) {
1512ae7a6b38SJeff Roberson 		if (ts->ts_runtime > ts->ts_slptime) {
1513ae7a6b38SJeff Roberson 			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1514ae7a6b38SJeff Roberson 			ts->ts_slptime = 1;
1515155b6ca1SJeff Roberson 		} else {
1516ae7a6b38SJeff Roberson 			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1517ae7a6b38SJeff Roberson 			ts->ts_runtime = 1;
1518155b6ca1SJeff Roberson 		}
1519155b6ca1SJeff Roberson 		return;
1520155b6ca1SJeff Roberson 	}
1521155b6ca1SJeff Roberson 	/*
1522d322132cSJeff Roberson 	 * If we have exceeded by more than 1/5th then the algorithm below
1523d322132cSJeff Roberson 	 * will not bring us back into range.  Dividing by two here forces
15242454aaf5SJeff Roberson 	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1525d322132cSJeff Roberson 	 */
152637a35e4aSJeff Roberson 	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1527ae7a6b38SJeff Roberson 		ts->ts_runtime /= 2;
1528ae7a6b38SJeff Roberson 		ts->ts_slptime /= 2;
1529d322132cSJeff Roberson 		return;
1530d322132cSJeff Roberson 	}
1531ae7a6b38SJeff Roberson 	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1532ae7a6b38SJeff Roberson 	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1533d322132cSJeff Roberson }
1534d322132cSJeff Roberson 
1535ae7a6b38SJeff Roberson /*
1536ae7a6b38SJeff Roberson  * Scale back the interactivity history when a child thread is created.  The
1537ae7a6b38SJeff Roberson  * history is inherited from the parent but the thread may behave totally
1538ae7a6b38SJeff Roberson  * differently.  For example, a shell spawning a compiler process.  We want
1539ae7a6b38SJeff Roberson  * to learn that the compiler is behaving badly very quickly.
1540ae7a6b38SJeff Roberson  */
1541d322132cSJeff Roberson static void
15428460a577SJohn Birrell sched_interact_fork(struct thread *td)
1543d322132cSJeff Roberson {
1544d322132cSJeff Roberson 	int ratio;
1545d322132cSJeff Roberson 	int sum;
1546d322132cSJeff Roberson 
1547ae7a6b38SJeff Roberson 	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1548d322132cSJeff Roberson 	if (sum > SCHED_SLP_RUN_FORK) {
1549d322132cSJeff Roberson 		ratio = sum / SCHED_SLP_RUN_FORK;
1550ae7a6b38SJeff Roberson 		td->td_sched->ts_runtime /= ratio;
1551ae7a6b38SJeff Roberson 		td->td_sched->ts_slptime /= ratio;
15524b60e324SJeff Roberson 	}
15534b60e324SJeff Roberson }
15544b60e324SJeff Roberson 
155515dc847eSJeff Roberson /*
1556ae7a6b38SJeff Roberson  * Called from proc0_init() to setup the scheduler fields.
1557ed062c8dSJulian Elischer  */
1558ed062c8dSJulian Elischer void
1559ed062c8dSJulian Elischer schedinit(void)
1560ed062c8dSJulian Elischer {
1561e7d50326SJeff Roberson 
1562ed062c8dSJulian Elischer 	/*
1563ed062c8dSJulian Elischer 	 * Set up the scheduler specific parts of proc0.
1564ed062c8dSJulian Elischer 	 */
1565ed062c8dSJulian Elischer 	proc0.p_sched = NULL; /* XXX */
1566ad1e7d28SJulian Elischer 	thread0.td_sched = &td_sched0;
1567e7d50326SJeff Roberson 	td_sched0.ts_ltick = ticks;
15688ab80cf0SJeff Roberson 	td_sched0.ts_ftick = ticks;
156973daf66fSJeff Roberson 	td_sched0.ts_slice = sched_slice;
1570ed062c8dSJulian Elischer }
1571ed062c8dSJulian Elischer 
1572ed062c8dSJulian Elischer /*
157315dc847eSJeff Roberson  * This is only somewhat accurate since given many processes of the same
157415dc847eSJeff Roberson  * priority they will switch when their slices run out, which will be
1575e7d50326SJeff Roberson  * at most sched_slice stathz ticks.
157615dc847eSJeff Roberson  */
157735e6168fSJeff Roberson int
157835e6168fSJeff Roberson sched_rr_interval(void)
157935e6168fSJeff Roberson {
1580e7d50326SJeff Roberson 
1581e7d50326SJeff Roberson 	/* Convert sched_slice to hz */
1582e7d50326SJeff Roberson 	return (hz/(realstathz/sched_slice));
158335e6168fSJeff Roberson }
158435e6168fSJeff Roberson 
1585ae7a6b38SJeff Roberson /*
1586ae7a6b38SJeff Roberson  * Update the percent cpu tracking information when it is requested or
1587ae7a6b38SJeff Roberson  * the total history exceeds the maximum.  We keep a sliding history of
1588ae7a6b38SJeff Roberson  * tick counts that slowly decays.  This is less precise than the 4BSD
1589ae7a6b38SJeff Roberson  * mechanism since it happens with less regular and frequent events.
1590ae7a6b38SJeff Roberson  */
159122bf7d9aSJeff Roberson static void
1592*7295465eSAlexander Motin sched_pctcpu_update(struct td_sched *ts, int run)
159335e6168fSJeff Roberson {
1594*7295465eSAlexander Motin 	int t = ticks;
1595e7d50326SJeff Roberson 
1596*7295465eSAlexander Motin 	if (t - ts->ts_ltick >= SCHED_TICK_TARG) {
1597ad1e7d28SJulian Elischer 		ts->ts_ticks = 0;
1598*7295465eSAlexander Motin 		ts->ts_ftick = t - SCHED_TICK_TARG;
1599*7295465eSAlexander Motin 	} else if (t - ts->ts_ftick >= SCHED_TICK_MAX) {
1600*7295465eSAlexander Motin 		ts->ts_ticks = (ts->ts_ticks / (ts->ts_ltick - ts->ts_ftick)) *
1601*7295465eSAlexander Motin 		    (ts->ts_ltick - (t - SCHED_TICK_TARG));
1602*7295465eSAlexander Motin 		ts->ts_ftick = t - SCHED_TICK_TARG;
1603*7295465eSAlexander Motin 	}
1604*7295465eSAlexander Motin 	if (run)
1605*7295465eSAlexander Motin 		ts->ts_ticks += (t - ts->ts_ltick) << SCHED_TICK_SHIFT;
1606*7295465eSAlexander Motin 	ts->ts_ltick = t;
160735e6168fSJeff Roberson }
160835e6168fSJeff Roberson 
1609ae7a6b38SJeff Roberson /*
1610ae7a6b38SJeff Roberson  * Adjust the priority of a thread.  Move it to the appropriate run-queue
1611ae7a6b38SJeff Roberson  * if necessary.  This is the back-end for several priority related
1612ae7a6b38SJeff Roberson  * functions.
1613ae7a6b38SJeff Roberson  */
1614e7d50326SJeff Roberson static void
1615f5c157d9SJohn Baldwin sched_thread_priority(struct thread *td, u_char prio)
161635e6168fSJeff Roberson {
1617ad1e7d28SJulian Elischer 	struct td_sched *ts;
161873daf66fSJeff Roberson 	struct tdq *tdq;
161973daf66fSJeff Roberson 	int oldpri;
162035e6168fSJeff Roberson 
16218f51ad55SJeff Roberson 	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
16228f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, "new prio:%d", prio,
16238f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(curthread));
16248f51ad55SJeff Roberson 	if (td != curthread && prio > td->td_priority) {
16258f51ad55SJeff Roberson 		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
16268f51ad55SJeff Roberson 		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
16278f51ad55SJeff Roberson 		    prio, KTR_ATTR_LINKED, sched_tdname(td));
16288f51ad55SJeff Roberson 	}
1629ad1e7d28SJulian Elischer 	ts = td->td_sched;
16307b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1631f5c157d9SJohn Baldwin 	if (td->td_priority == prio)
1632f5c157d9SJohn Baldwin 		return;
16333f741ca1SJeff Roberson 	/*
16343f741ca1SJeff Roberson 	 * If the priority has been elevated due to priority
16353f741ca1SJeff Roberson 	 * propagation, we may have to move ourselves to a new
1636e7d50326SJeff Roberson 	 * queue.  This could be optimized to not re-add in some
1637e7d50326SJeff Roberson 	 * cases.
1638f2b74cbfSJeff Roberson 	 */
16396d55b3ecSJeff Roberson 	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1640e7d50326SJeff Roberson 		sched_rem(td);
1641e7d50326SJeff Roberson 		td->td_priority = prio;
1642ae7a6b38SJeff Roberson 		sched_add(td, SRQ_BORROWING);
164373daf66fSJeff Roberson 		return;
164473daf66fSJeff Roberson 	}
16456d55b3ecSJeff Roberson 	/*
16466d55b3ecSJeff Roberson 	 * If the thread is currently running we may have to adjust the lowpri
16476d55b3ecSJeff Roberson 	 * information so other cpus are aware of our current priority.
16486d55b3ecSJeff Roberson 	 */
16496d55b3ecSJeff Roberson 	if (TD_IS_RUNNING(td)) {
1650ae7a6b38SJeff Roberson 		tdq = TDQ_CPU(ts->ts_cpu);
165162fa74d9SJeff Roberson 		oldpri = td->td_priority;
16523f741ca1SJeff Roberson 		td->td_priority = prio;
165362fa74d9SJeff Roberson 		if (prio < tdq->tdq_lowpri)
165462fa74d9SJeff Roberson 			tdq->tdq_lowpri = prio;
165562fa74d9SJeff Roberson 		else if (tdq->tdq_lowpri == oldpri)
165662fa74d9SJeff Roberson 			tdq_setlowpri(tdq, td);
16576d55b3ecSJeff Roberson 		return;
165873daf66fSJeff Roberson 	}
16596d55b3ecSJeff Roberson 	td->td_priority = prio;
1660ae7a6b38SJeff Roberson }
166135e6168fSJeff Roberson 
1662f5c157d9SJohn Baldwin /*
1663f5c157d9SJohn Baldwin  * Update a thread's priority when it is lent another thread's
1664f5c157d9SJohn Baldwin  * priority.
1665f5c157d9SJohn Baldwin  */
1666f5c157d9SJohn Baldwin void
1667f5c157d9SJohn Baldwin sched_lend_prio(struct thread *td, u_char prio)
1668f5c157d9SJohn Baldwin {
1669f5c157d9SJohn Baldwin 
1670f5c157d9SJohn Baldwin 	td->td_flags |= TDF_BORROWING;
1671f5c157d9SJohn Baldwin 	sched_thread_priority(td, prio);
1672f5c157d9SJohn Baldwin }
1673f5c157d9SJohn Baldwin 
1674f5c157d9SJohn Baldwin /*
1675f5c157d9SJohn Baldwin  * Restore a thread's priority when priority propagation is
1676f5c157d9SJohn Baldwin  * over.  The prio argument is the minimum priority the thread
1677f5c157d9SJohn Baldwin  * needs to have to satisfy other possible priority lending
1678f5c157d9SJohn Baldwin  * requests.  If the thread's regular priority is less
1679f5c157d9SJohn Baldwin  * important than prio, the thread will keep a priority boost
1680f5c157d9SJohn Baldwin  * of prio.
1681f5c157d9SJohn Baldwin  */
1682f5c157d9SJohn Baldwin void
1683f5c157d9SJohn Baldwin sched_unlend_prio(struct thread *td, u_char prio)
1684f5c157d9SJohn Baldwin {
1685f5c157d9SJohn Baldwin 	u_char base_pri;
1686f5c157d9SJohn Baldwin 
1687f5c157d9SJohn Baldwin 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1688f5c157d9SJohn Baldwin 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
16898460a577SJohn Birrell 		base_pri = td->td_user_pri;
1690f5c157d9SJohn Baldwin 	else
1691f5c157d9SJohn Baldwin 		base_pri = td->td_base_pri;
1692f5c157d9SJohn Baldwin 	if (prio >= base_pri) {
1693f5c157d9SJohn Baldwin 		td->td_flags &= ~TDF_BORROWING;
1694f5c157d9SJohn Baldwin 		sched_thread_priority(td, base_pri);
1695f5c157d9SJohn Baldwin 	} else
1696f5c157d9SJohn Baldwin 		sched_lend_prio(td, prio);
1697f5c157d9SJohn Baldwin }
1698f5c157d9SJohn Baldwin 
1699ae7a6b38SJeff Roberson /*
1700ae7a6b38SJeff Roberson  * Standard entry for setting the priority to an absolute value.
1701ae7a6b38SJeff Roberson  */
1702f5c157d9SJohn Baldwin void
1703f5c157d9SJohn Baldwin sched_prio(struct thread *td, u_char prio)
1704f5c157d9SJohn Baldwin {
1705f5c157d9SJohn Baldwin 	u_char oldprio;
1706f5c157d9SJohn Baldwin 
1707f5c157d9SJohn Baldwin 	/* First, update the base priority. */
1708f5c157d9SJohn Baldwin 	td->td_base_pri = prio;
1709f5c157d9SJohn Baldwin 
1710f5c157d9SJohn Baldwin 	/*
171150aaa791SJohn Baldwin 	 * If the thread is borrowing another thread's priority, don't
1712f5c157d9SJohn Baldwin 	 * ever lower the priority.
1713f5c157d9SJohn Baldwin 	 */
1714f5c157d9SJohn Baldwin 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1715f5c157d9SJohn Baldwin 		return;
1716f5c157d9SJohn Baldwin 
1717f5c157d9SJohn Baldwin 	/* Change the real priority. */
1718f5c157d9SJohn Baldwin 	oldprio = td->td_priority;
1719f5c157d9SJohn Baldwin 	sched_thread_priority(td, prio);
1720f5c157d9SJohn Baldwin 
1721f5c157d9SJohn Baldwin 	/*
1722f5c157d9SJohn Baldwin 	 * If the thread is on a turnstile, then let the turnstile update
1723f5c157d9SJohn Baldwin 	 * its state.
1724f5c157d9SJohn Baldwin 	 */
1725f5c157d9SJohn Baldwin 	if (TD_ON_LOCK(td) && oldprio != prio)
1726f5c157d9SJohn Baldwin 		turnstile_adjust(td, oldprio);
1727f5c157d9SJohn Baldwin }
1728f5c157d9SJohn Baldwin 
1729ae7a6b38SJeff Roberson /*
1730ae7a6b38SJeff Roberson  * Set the base user priority, does not effect current running priority.
1731ae7a6b38SJeff Roberson  */
173235e6168fSJeff Roberson void
17338460a577SJohn Birrell sched_user_prio(struct thread *td, u_char prio)
17343db720fdSDavid Xu {
17353db720fdSDavid Xu 
17368460a577SJohn Birrell 	td->td_base_user_pri = prio;
1737acbe332aSDavid Xu 	if (td->td_lend_user_pri <= prio)
1738fc6c30f6SJulian Elischer 		return;
17398460a577SJohn Birrell 	td->td_user_pri = prio;
17403db720fdSDavid Xu }
17413db720fdSDavid Xu 
17423db720fdSDavid Xu void
17433db720fdSDavid Xu sched_lend_user_prio(struct thread *td, u_char prio)
17443db720fdSDavid Xu {
17453db720fdSDavid Xu 
1746435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1747acbe332aSDavid Xu 	td->td_lend_user_pri = prio;
1748c8e368a9SDavid Xu 	td->td_user_pri = min(prio, td->td_base_user_pri);
1749c8e368a9SDavid Xu 	if (td->td_priority > td->td_user_pri)
1750c8e368a9SDavid Xu 		sched_prio(td, td->td_user_pri);
1751c8e368a9SDavid Xu 	else if (td->td_priority != td->td_user_pri)
1752c8e368a9SDavid Xu 		td->td_flags |= TDF_NEEDRESCHED;
1753435806d3SDavid Xu }
17543db720fdSDavid Xu 
1755ae7a6b38SJeff Roberson /*
1756c47f202bSJeff Roberson  * Handle migration from sched_switch().  This happens only for
1757c47f202bSJeff Roberson  * cpu binding.
1758c47f202bSJeff Roberson  */
1759c47f202bSJeff Roberson static struct mtx *
1760c47f202bSJeff Roberson sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1761c47f202bSJeff Roberson {
1762c47f202bSJeff Roberson 	struct tdq *tdn;
1763c47f202bSJeff Roberson 
1764c47f202bSJeff Roberson 	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1765c47f202bSJeff Roberson #ifdef SMP
17669727e637SJeff Roberson 	tdq_load_rem(tdq, td);
1767c47f202bSJeff Roberson 	/*
1768c47f202bSJeff Roberson 	 * Do the lock dance required to avoid LOR.  We grab an extra
1769c47f202bSJeff Roberson 	 * spinlock nesting to prevent preemption while we're
1770c47f202bSJeff Roberson 	 * not holding either run-queue lock.
1771c47f202bSJeff Roberson 	 */
1772c47f202bSJeff Roberson 	spinlock_enter();
1773b0b9dee5SAttilio Rao 	thread_lock_block(td);	/* This releases the lock on tdq. */
1774435068aaSAttilio Rao 
1775435068aaSAttilio Rao 	/*
1776435068aaSAttilio Rao 	 * Acquire both run-queue locks before placing the thread on the new
1777435068aaSAttilio Rao 	 * run-queue to avoid deadlocks created by placing a thread with a
1778435068aaSAttilio Rao 	 * blocked lock on the run-queue of a remote processor.  The deadlock
1779435068aaSAttilio Rao 	 * occurs when a third processor attempts to lock the two queues in
1780435068aaSAttilio Rao 	 * question while the target processor is spinning with its own
1781435068aaSAttilio Rao 	 * run-queue lock held while waiting for the blocked lock to clear.
1782435068aaSAttilio Rao 	 */
1783435068aaSAttilio Rao 	tdq_lock_pair(tdn, tdq);
1784c47f202bSJeff Roberson 	tdq_add(tdn, td, flags);
17859727e637SJeff Roberson 	tdq_notify(tdn, td);
1786c47f202bSJeff Roberson 	TDQ_UNLOCK(tdn);
1787c47f202bSJeff Roberson 	spinlock_exit();
1788c47f202bSJeff Roberson #endif
1789c47f202bSJeff Roberson 	return (TDQ_LOCKPTR(tdn));
1790c47f202bSJeff Roberson }
1791c47f202bSJeff Roberson 
1792c47f202bSJeff Roberson /*
1793b0b9dee5SAttilio Rao  * Variadic version of thread_lock_unblock() that does not assume td_lock
1794b0b9dee5SAttilio Rao  * is blocked.
1795ae7a6b38SJeff Roberson  */
1796ae7a6b38SJeff Roberson static inline void
1797ae7a6b38SJeff Roberson thread_unblock_switch(struct thread *td, struct mtx *mtx)
1798ae7a6b38SJeff Roberson {
1799ae7a6b38SJeff Roberson 	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1800ae7a6b38SJeff Roberson 	    (uintptr_t)mtx);
1801ae7a6b38SJeff Roberson }
1802ae7a6b38SJeff Roberson 
1803ae7a6b38SJeff Roberson /*
1804ae7a6b38SJeff Roberson  * Switch threads.  This function has to handle threads coming in while
1805ae7a6b38SJeff Roberson  * blocked for some reason, running, or idle.  It also must deal with
1806ae7a6b38SJeff Roberson  * migrating a thread from one queue to another as running threads may
1807ae7a6b38SJeff Roberson  * be assigned elsewhere via binding.
1808ae7a6b38SJeff Roberson  */
18093db720fdSDavid Xu void
18103389af30SJulian Elischer sched_switch(struct thread *td, struct thread *newtd, int flags)
181135e6168fSJeff Roberson {
1812c02bbb43SJeff Roberson 	struct tdq *tdq;
1813ad1e7d28SJulian Elischer 	struct td_sched *ts;
1814ae7a6b38SJeff Roberson 	struct mtx *mtx;
1815c47f202bSJeff Roberson 	int srqflag;
1816ae7a6b38SJeff Roberson 	int cpuid;
181735e6168fSJeff Roberson 
18187b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
18196d55b3ecSJeff Roberson 	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
182035e6168fSJeff Roberson 
1821ae7a6b38SJeff Roberson 	cpuid = PCPU_GET(cpuid);
1822ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpuid);
1823e7d50326SJeff Roberson 	ts = td->td_sched;
1824c47f202bSJeff Roberson 	mtx = td->td_lock;
1825*7295465eSAlexander Motin 	sched_pctcpu_update(ts, 1);
1826ae7a6b38SJeff Roberson 	ts->ts_rltick = ticks;
1827060563ecSJulian Elischer 	td->td_lastcpu = td->td_oncpu;
1828060563ecSJulian Elischer 	td->td_oncpu = NOCPU;
1829586cb6ecSFabien Thomas 	if (!(flags & SW_PREEMPT))
183052eb8464SJohn Baldwin 		td->td_flags &= ~TDF_NEEDRESCHED;
183177918643SStephan Uphoff 	td->td_owepreempt = 0;
18321690c6c1SJeff Roberson 	tdq->tdq_switchcnt++;
1833b11fdad0SJeff Roberson 	/*
1834ae7a6b38SJeff Roberson 	 * The lock pointer in an idle thread should never change.  Reset it
1835ae7a6b38SJeff Roberson 	 * to CAN_RUN as well.
1836b11fdad0SJeff Roberson 	 */
1837486a9414SJulian Elischer 	if (TD_IS_IDLETHREAD(td)) {
1838ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1839bf0acc27SJohn Baldwin 		TD_SET_CAN_RUN(td);
18407b20fb19SJeff Roberson 	} else if (TD_IS_RUNNING(td)) {
1841ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1842c47f202bSJeff Roberson 		srqflag = (flags & SW_PREEMPT) ?
1843598b368dSJeff Roberson 		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1844c47f202bSJeff Roberson 		    SRQ_OURSELF|SRQ_YIELDING;
1845ba4932b5SMatthew D Fleming #ifdef SMP
18460f7a0ebdSMatthew D Fleming 		if (THREAD_CAN_MIGRATE(td) && !THREAD_CAN_SCHED(td, ts->ts_cpu))
18470f7a0ebdSMatthew D Fleming 			ts->ts_cpu = sched_pickcpu(td, 0);
1848ba4932b5SMatthew D Fleming #endif
1849c47f202bSJeff Roberson 		if (ts->ts_cpu == cpuid)
18509727e637SJeff Roberson 			tdq_runq_add(tdq, td, srqflag);
18510f7a0ebdSMatthew D Fleming 		else {
18520f7a0ebdSMatthew D Fleming 			KASSERT(THREAD_CAN_MIGRATE(td) ||
18530f7a0ebdSMatthew D Fleming 			    (ts->ts_flags & TSF_BOUND) != 0,
18540f7a0ebdSMatthew D Fleming 			    ("Thread %p shouldn't migrate", td));
1855c47f202bSJeff Roberson 			mtx = sched_switch_migrate(tdq, td, srqflag);
18560f7a0ebdSMatthew D Fleming 		}
1857ae7a6b38SJeff Roberson 	} else {
1858ae7a6b38SJeff Roberson 		/* This thread must be going to sleep. */
1859ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
1860b0b9dee5SAttilio Rao 		mtx = thread_lock_block(td);
18619727e637SJeff Roberson 		tdq_load_rem(tdq, td);
1862ae7a6b38SJeff Roberson 	}
1863ae7a6b38SJeff Roberson 	/*
1864ae7a6b38SJeff Roberson 	 * We enter here with the thread blocked and assigned to the
1865ae7a6b38SJeff Roberson 	 * appropriate cpu run-queue or sleep-queue and with the current
1866ae7a6b38SJeff Roberson 	 * thread-queue locked.
1867ae7a6b38SJeff Roberson 	 */
1868ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
18692454aaf5SJeff Roberson 	newtd = choosethread();
1870ae7a6b38SJeff Roberson 	/*
1871ae7a6b38SJeff Roberson 	 * Call the MD code to switch contexts if necessary.
1872ae7a6b38SJeff Roberson 	 */
1873ebccf1e3SJoseph Koshy 	if (td != newtd) {
1874ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1875ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1876ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1877ebccf1e3SJoseph Koshy #endif
1878eea4f254SJeff Roberson 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
187959c68134SJeff Roberson 		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1880*7295465eSAlexander Motin 		sched_pctcpu_update(newtd->td_sched, 0);
18816f5f25e5SJohn Birrell 
18826f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
18836f5f25e5SJohn Birrell 		/*
18846f5f25e5SJohn Birrell 		 * If DTrace has set the active vtime enum to anything
18856f5f25e5SJohn Birrell 		 * other than INACTIVE (0), then it should have set the
18866f5f25e5SJohn Birrell 		 * function to call.
18876f5f25e5SJohn Birrell 		 */
18886f5f25e5SJohn Birrell 		if (dtrace_vtime_active)
18896f5f25e5SJohn Birrell 			(*dtrace_vtime_switch_func)(newtd);
18906f5f25e5SJohn Birrell #endif
18916f5f25e5SJohn Birrell 
1892ae7a6b38SJeff Roberson 		cpu_switch(td, newtd, mtx);
1893ae7a6b38SJeff Roberson 		/*
1894ae7a6b38SJeff Roberson 		 * We may return from cpu_switch on a different cpu.  However,
1895ae7a6b38SJeff Roberson 		 * we always return with td_lock pointing to the current cpu's
1896ae7a6b38SJeff Roberson 		 * run queue lock.
1897ae7a6b38SJeff Roberson 		 */
1898ae7a6b38SJeff Roberson 		cpuid = PCPU_GET(cpuid);
1899ae7a6b38SJeff Roberson 		tdq = TDQ_CPU(cpuid);
1900eea4f254SJeff Roberson 		lock_profile_obtain_lock_success(
1901eea4f254SJeff Roberson 		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
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_IN);
1905ebccf1e3SJoseph Koshy #endif
1906ae7a6b38SJeff Roberson 	} else
1907ae7a6b38SJeff Roberson 		thread_unblock_switch(td, mtx);
1908ae7a6b38SJeff Roberson 	/*
1909ae7a6b38SJeff Roberson 	 * Assert that all went well and return.
1910ae7a6b38SJeff Roberson 	 */
1911ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1912ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1913ae7a6b38SJeff Roberson 	td->td_oncpu = cpuid;
191435e6168fSJeff Roberson }
191535e6168fSJeff Roberson 
1916ae7a6b38SJeff Roberson /*
1917ae7a6b38SJeff Roberson  * Adjust thread priorities as a result of a nice request.
1918ae7a6b38SJeff Roberson  */
191935e6168fSJeff Roberson void
1920fa885116SJulian Elischer sched_nice(struct proc *p, int nice)
192135e6168fSJeff Roberson {
192235e6168fSJeff Roberson 	struct thread *td;
192335e6168fSJeff Roberson 
1924fa885116SJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
1925e7d50326SJeff Roberson 
1926fa885116SJulian Elischer 	p->p_nice = nice;
19278460a577SJohn Birrell 	FOREACH_THREAD_IN_PROC(p, td) {
19287b20fb19SJeff Roberson 		thread_lock(td);
19298460a577SJohn Birrell 		sched_priority(td);
1930e7d50326SJeff Roberson 		sched_prio(td, td->td_base_user_pri);
19317b20fb19SJeff Roberson 		thread_unlock(td);
193235e6168fSJeff Roberson 	}
1933fa885116SJulian Elischer }
193435e6168fSJeff Roberson 
1935ae7a6b38SJeff Roberson /*
1936ae7a6b38SJeff Roberson  * Record the sleep time for the interactivity scorer.
1937ae7a6b38SJeff Roberson  */
193835e6168fSJeff Roberson void
1939c5aa6b58SJeff Roberson sched_sleep(struct thread *td, int prio)
194035e6168fSJeff Roberson {
1941e7d50326SJeff Roberson 
19427b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
194335e6168fSJeff Roberson 
194454b0e65fSJeff Roberson 	td->td_slptick = ticks;
194517c4c356SKonstantin Belousov 	if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
1946c5aa6b58SJeff Roberson 		td->td_flags |= TDF_CANSWAP;
19472dc29adbSJohn Baldwin 	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
19482dc29adbSJohn Baldwin 		return;
19490502fe2eSJeff Roberson 	if (static_boost == 1 && prio)
1950c5aa6b58SJeff Roberson 		sched_prio(td, prio);
19510502fe2eSJeff Roberson 	else if (static_boost && td->td_priority > static_boost)
19520502fe2eSJeff Roberson 		sched_prio(td, static_boost);
195335e6168fSJeff Roberson }
195435e6168fSJeff Roberson 
1955ae7a6b38SJeff Roberson /*
1956ae7a6b38SJeff Roberson  * Schedule a thread to resume execution and record how long it voluntarily
1957ae7a6b38SJeff Roberson  * slept.  We also update the pctcpu, interactivity, and priority.
1958ae7a6b38SJeff Roberson  */
195935e6168fSJeff Roberson void
196035e6168fSJeff Roberson sched_wakeup(struct thread *td)
196135e6168fSJeff Roberson {
196214618990SJeff Roberson 	struct td_sched *ts;
1963ae7a6b38SJeff Roberson 	int slptick;
1964e7d50326SJeff Roberson 
19657b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
196614618990SJeff Roberson 	ts = td->td_sched;
1967c5aa6b58SJeff Roberson 	td->td_flags &= ~TDF_CANSWAP;
196835e6168fSJeff Roberson 	/*
1969e7d50326SJeff Roberson 	 * If we slept for more than a tick update our interactivity and
1970e7d50326SJeff Roberson 	 * priority.
197135e6168fSJeff Roberson 	 */
197254b0e65fSJeff Roberson 	slptick = td->td_slptick;
197354b0e65fSJeff Roberson 	td->td_slptick = 0;
1974ae7a6b38SJeff Roberson 	if (slptick && slptick != ticks) {
1975*7295465eSAlexander Motin 		ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
19768460a577SJohn Birrell 		sched_interact_update(td);
1977*7295465eSAlexander Motin 		sched_pctcpu_update(ts, 0);
1978f1e8dc4aSJeff Roberson 	}
197914618990SJeff Roberson 	/* Reset the slice value after we sleep. */
198014618990SJeff Roberson 	ts->ts_slice = sched_slice;
19817a5e5e2aSJeff Roberson 	sched_add(td, SRQ_BORING);
198235e6168fSJeff Roberson }
198335e6168fSJeff Roberson 
198435e6168fSJeff Roberson /*
198535e6168fSJeff Roberson  * Penalize the parent for creating a new child and initialize the child's
198635e6168fSJeff Roberson  * priority.
198735e6168fSJeff Roberson  */
198835e6168fSJeff Roberson void
19898460a577SJohn Birrell sched_fork(struct thread *td, struct thread *child)
199015dc847eSJeff Roberson {
19917b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1992*7295465eSAlexander Motin 	sched_pctcpu_update(td->td_sched, 1);
1993ad1e7d28SJulian Elischer 	sched_fork_thread(td, child);
1994e7d50326SJeff Roberson 	/*
1995e7d50326SJeff Roberson 	 * Penalize the parent and child for forking.
1996e7d50326SJeff Roberson 	 */
1997e7d50326SJeff Roberson 	sched_interact_fork(child);
1998e7d50326SJeff Roberson 	sched_priority(child);
1999ae7a6b38SJeff Roberson 	td->td_sched->ts_runtime += tickincr;
2000e7d50326SJeff Roberson 	sched_interact_update(td);
2001e7d50326SJeff Roberson 	sched_priority(td);
2002ad1e7d28SJulian Elischer }
2003ad1e7d28SJulian Elischer 
2004ae7a6b38SJeff Roberson /*
2005ae7a6b38SJeff Roberson  * Fork a new thread, may be within the same process.
2006ae7a6b38SJeff Roberson  */
2007ad1e7d28SJulian Elischer void
2008ad1e7d28SJulian Elischer sched_fork_thread(struct thread *td, struct thread *child)
2009ad1e7d28SJulian Elischer {
2010ad1e7d28SJulian Elischer 	struct td_sched *ts;
2011ad1e7d28SJulian Elischer 	struct td_sched *ts2;
20128460a577SJohn Birrell 
20138b16c208SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2014e7d50326SJeff Roberson 	/*
2015e7d50326SJeff Roberson 	 * Initialize child.
2016e7d50326SJeff Roberson 	 */
2017ad1e7d28SJulian Elischer 	ts = td->td_sched;
2018ad1e7d28SJulian Elischer 	ts2 = child->td_sched;
20198b16c208SJeff Roberson 	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
20208b16c208SJeff Roberson 	child->td_cpuset = cpuset_ref(td->td_cpuset);
2021ad1e7d28SJulian Elischer 	ts2->ts_cpu = ts->ts_cpu;
20228b16c208SJeff Roberson 	ts2->ts_flags = 0;
2023e7d50326SJeff Roberson 	/*
202422d19207SJohn Baldwin 	 * Grab our parents cpu estimation information.
2025e7d50326SJeff Roberson 	 */
2026ad1e7d28SJulian Elischer 	ts2->ts_ticks = ts->ts_ticks;
2027ad1e7d28SJulian Elischer 	ts2->ts_ltick = ts->ts_ltick;
2028ad1e7d28SJulian Elischer 	ts2->ts_ftick = ts->ts_ftick;
202922d19207SJohn Baldwin 	/*
203022d19207SJohn Baldwin 	 * Do not inherit any borrowed priority from the parent.
203122d19207SJohn Baldwin 	 */
203222d19207SJohn Baldwin 	child->td_priority = child->td_base_pri;
2033e7d50326SJeff Roberson 	/*
2034e7d50326SJeff Roberson 	 * And update interactivity score.
2035e7d50326SJeff Roberson 	 */
2036ae7a6b38SJeff Roberson 	ts2->ts_slptime = ts->ts_slptime;
2037ae7a6b38SJeff Roberson 	ts2->ts_runtime = ts->ts_runtime;
2038e7d50326SJeff Roberson 	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
20398f51ad55SJeff Roberson #ifdef KTR
20408f51ad55SJeff Roberson 	bzero(ts2->ts_name, sizeof(ts2->ts_name));
20418f51ad55SJeff Roberson #endif
204215dc847eSJeff Roberson }
204315dc847eSJeff Roberson 
2044ae7a6b38SJeff Roberson /*
2045ae7a6b38SJeff Roberson  * Adjust the priority class of a thread.
2046ae7a6b38SJeff Roberson  */
204715dc847eSJeff Roberson void
20488460a577SJohn Birrell sched_class(struct thread *td, int class)
204915dc847eSJeff Roberson {
205015dc847eSJeff Roberson 
20517b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
20528460a577SJohn Birrell 	if (td->td_pri_class == class)
205315dc847eSJeff Roberson 		return;
20548460a577SJohn Birrell 	td->td_pri_class = class;
205535e6168fSJeff Roberson }
205635e6168fSJeff Roberson 
205735e6168fSJeff Roberson /*
205835e6168fSJeff Roberson  * Return some of the child's priority and interactivity to the parent.
205935e6168fSJeff Roberson  */
206035e6168fSJeff Roberson void
2061fc6c30f6SJulian Elischer sched_exit(struct proc *p, struct thread *child)
206235e6168fSJeff Roberson {
2063e7d50326SJeff Roberson 	struct thread *td;
2064141ad61cSJeff Roberson 
20658f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2066cd39bb09SXin LI 	    "prio:%d", child->td_priority);
2067374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
2068e7d50326SJeff Roberson 	td = FIRST_THREAD_IN_PROC(p);
2069e7d50326SJeff Roberson 	sched_exit_thread(td, child);
2070ad1e7d28SJulian Elischer }
2071ad1e7d28SJulian Elischer 
2072ae7a6b38SJeff Roberson /*
2073ae7a6b38SJeff Roberson  * Penalize another thread for the time spent on this one.  This helps to
2074ae7a6b38SJeff Roberson  * worsen the priority and interactivity of processes which schedule batch
2075ae7a6b38SJeff Roberson  * jobs such as make.  This has little effect on the make process itself but
2076ae7a6b38SJeff Roberson  * causes new processes spawned by it to receive worse scores immediately.
2077ae7a6b38SJeff Roberson  */
2078ad1e7d28SJulian Elischer void
2079fc6c30f6SJulian Elischer sched_exit_thread(struct thread *td, struct thread *child)
2080ad1e7d28SJulian Elischer {
2081fc6c30f6SJulian Elischer 
20828f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2083cd39bb09SXin LI 	    "prio:%d", child->td_priority);
2084e7d50326SJeff Roberson 	/*
2085e7d50326SJeff Roberson 	 * Give the child's runtime to the parent without returning the
2086e7d50326SJeff Roberson 	 * sleep time as a penalty to the parent.  This causes shells that
2087e7d50326SJeff Roberson 	 * launch expensive things to mark their children as expensive.
2088e7d50326SJeff Roberson 	 */
20897b20fb19SJeff Roberson 	thread_lock(td);
2090ae7a6b38SJeff Roberson 	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2091fc6c30f6SJulian Elischer 	sched_interact_update(td);
2092e7d50326SJeff Roberson 	sched_priority(td);
20937b20fb19SJeff Roberson 	thread_unlock(td);
2094ad1e7d28SJulian Elischer }
2095ad1e7d28SJulian Elischer 
2096ff256d9cSJeff Roberson void
2097ff256d9cSJeff Roberson sched_preempt(struct thread *td)
2098ff256d9cSJeff Roberson {
2099ff256d9cSJeff Roberson 	struct tdq *tdq;
2100ff256d9cSJeff Roberson 
2101ff256d9cSJeff Roberson 	thread_lock(td);
2102ff256d9cSJeff Roberson 	tdq = TDQ_SELF();
2103ff256d9cSJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2104ff256d9cSJeff Roberson 	tdq->tdq_ipipending = 0;
2105ff256d9cSJeff Roberson 	if (td->td_priority > tdq->tdq_lowpri) {
21068df78c41SJeff Roberson 		int flags;
21078df78c41SJeff Roberson 
21088df78c41SJeff Roberson 		flags = SW_INVOL | SW_PREEMPT;
2109ff256d9cSJeff Roberson 		if (td->td_critnest > 1)
2110ff256d9cSJeff Roberson 			td->td_owepreempt = 1;
21118df78c41SJeff Roberson 		else if (TD_IS_IDLETHREAD(td))
21128df78c41SJeff Roberson 			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2113ff256d9cSJeff Roberson 		else
21148df78c41SJeff Roberson 			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2115ff256d9cSJeff Roberson 	}
2116ff256d9cSJeff Roberson 	thread_unlock(td);
2117ff256d9cSJeff Roberson }
2118ff256d9cSJeff Roberson 
2119ae7a6b38SJeff Roberson /*
2120ae7a6b38SJeff Roberson  * Fix priorities on return to user-space.  Priorities may be elevated due
2121ae7a6b38SJeff Roberson  * to static priorities in msleep() or similar.
2122ae7a6b38SJeff Roberson  */
2123ad1e7d28SJulian Elischer void
2124ad1e7d28SJulian Elischer sched_userret(struct thread *td)
2125ad1e7d28SJulian Elischer {
2126ad1e7d28SJulian Elischer 	/*
2127ad1e7d28SJulian Elischer 	 * XXX we cheat slightly on the locking here to avoid locking in
2128ad1e7d28SJulian Elischer 	 * the usual case.  Setting td_priority here is essentially an
2129ad1e7d28SJulian Elischer 	 * incomplete workaround for not setting it properly elsewhere.
2130ad1e7d28SJulian Elischer 	 * Now that some interrupt handlers are threads, not setting it
2131ad1e7d28SJulian Elischer 	 * properly elsewhere can clobber it in the window between setting
2132ad1e7d28SJulian Elischer 	 * it here and returning to user mode, so don't waste time setting
2133ad1e7d28SJulian Elischer 	 * it perfectly here.
2134ad1e7d28SJulian Elischer 	 */
2135ad1e7d28SJulian Elischer 	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2136ad1e7d28SJulian Elischer 	    ("thread with borrowed priority returning to userland"));
2137ad1e7d28SJulian Elischer 	if (td->td_priority != td->td_user_pri) {
21387b20fb19SJeff Roberson 		thread_lock(td);
2139ad1e7d28SJulian Elischer 		td->td_priority = td->td_user_pri;
2140ad1e7d28SJulian Elischer 		td->td_base_pri = td->td_user_pri;
214162fa74d9SJeff Roberson 		tdq_setlowpri(TDQ_SELF(), td);
21427b20fb19SJeff Roberson 		thread_unlock(td);
2143ad1e7d28SJulian Elischer         }
214435e6168fSJeff Roberson }
214535e6168fSJeff Roberson 
2146ae7a6b38SJeff Roberson /*
2147ae7a6b38SJeff Roberson  * Handle a stathz tick.  This is really only relevant for timeshare
2148ae7a6b38SJeff Roberson  * threads.
2149ae7a6b38SJeff Roberson  */
215035e6168fSJeff Roberson void
21517cf90fb3SJeff Roberson sched_clock(struct thread *td)
215235e6168fSJeff Roberson {
2153ad1e7d28SJulian Elischer 	struct tdq *tdq;
2154ad1e7d28SJulian Elischer 	struct td_sched *ts;
215535e6168fSJeff Roberson 
2156ae7a6b38SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
21573f872f85SJeff Roberson 	tdq = TDQ_SELF();
21587fcf154aSJeff Roberson #ifdef SMP
21597fcf154aSJeff Roberson 	/*
21607fcf154aSJeff Roberson 	 * We run the long term load balancer infrequently on the first cpu.
21617fcf154aSJeff Roberson 	 */
21627fcf154aSJeff Roberson 	if (balance_tdq == tdq) {
21637fcf154aSJeff Roberson 		if (balance_ticks && --balance_ticks == 0)
21647fcf154aSJeff Roberson 			sched_balance();
21657fcf154aSJeff Roberson 	}
21667fcf154aSJeff Roberson #endif
21673f872f85SJeff Roberson 	/*
21681690c6c1SJeff Roberson 	 * Save the old switch count so we have a record of the last ticks
21691690c6c1SJeff Roberson 	 * activity.   Initialize the new switch count based on our load.
21701690c6c1SJeff Roberson 	 * If there is some activity seed it to reflect that.
21711690c6c1SJeff Roberson 	 */
21721690c6c1SJeff Roberson 	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
21736c47aaaeSJeff Roberson 	tdq->tdq_switchcnt = tdq->tdq_load;
21741690c6c1SJeff Roberson 	/*
21753f872f85SJeff Roberson 	 * Advance the insert index once for each tick to ensure that all
21763f872f85SJeff Roberson 	 * threads get a chance to run.
21773f872f85SJeff Roberson 	 */
21783f872f85SJeff Roberson 	if (tdq->tdq_idx == tdq->tdq_ridx) {
21793f872f85SJeff Roberson 		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
21803f872f85SJeff Roberson 		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
21813f872f85SJeff Roberson 			tdq->tdq_ridx = tdq->tdq_idx;
21823f872f85SJeff Roberson 	}
21833f872f85SJeff Roberson 	ts = td->td_sched;
2184*7295465eSAlexander Motin 	sched_pctcpu_update(ts, 1);
2185fd0b8c78SJeff Roberson 	if (td->td_pri_class & PRI_FIFO_BIT)
2186a8949de2SJeff Roberson 		return;
2187c9a8cba4SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2188a8949de2SJeff Roberson 		/*
2189fd0b8c78SJeff Roberson 		 * We used a tick; charge it to the thread so
2190fd0b8c78SJeff Roberson 		 * that we can compute our interactivity.
219115dc847eSJeff Roberson 		 */
2192ae7a6b38SJeff Roberson 		td->td_sched->ts_runtime += tickincr;
21938460a577SJohn Birrell 		sched_interact_update(td);
219473daf66fSJeff Roberson 		sched_priority(td);
2195fd0b8c78SJeff Roberson 	}
219635e6168fSJeff Roberson 	/*
219735e6168fSJeff Roberson 	 * We used up one time slice.
219835e6168fSJeff Roberson 	 */
2199ad1e7d28SJulian Elischer 	if (--ts->ts_slice > 0)
220015dc847eSJeff Roberson 		return;
220135e6168fSJeff Roberson 	/*
220273daf66fSJeff Roberson 	 * We're out of time, force a requeue at userret().
220335e6168fSJeff Roberson 	 */
220473daf66fSJeff Roberson 	ts->ts_slice = sched_slice;
22054a338afdSJulian Elischer 	td->td_flags |= TDF_NEEDRESCHED;
220635e6168fSJeff Roberson }
220735e6168fSJeff Roberson 
2208ae7a6b38SJeff Roberson /*
2209*7295465eSAlexander Motin  * Called once per hz tick.
2210ae7a6b38SJeff Roberson  */
2211ae7a6b38SJeff Roberson void
2212a157e425SAlexander Motin sched_tick(int cnt)
2213ae7a6b38SJeff Roberson {
2214ae7a6b38SJeff Roberson 
2215ae7a6b38SJeff Roberson }
2216ae7a6b38SJeff Roberson 
2217ae7a6b38SJeff Roberson /*
2218ae7a6b38SJeff Roberson  * Return whether the current CPU has runnable tasks.  Used for in-kernel
2219ae7a6b38SJeff Roberson  * cooperative idle threads.
2220ae7a6b38SJeff Roberson  */
222135e6168fSJeff Roberson int
222235e6168fSJeff Roberson sched_runnable(void)
222335e6168fSJeff Roberson {
2224ad1e7d28SJulian Elischer 	struct tdq *tdq;
2225b90816f1SJeff Roberson 	int load;
222635e6168fSJeff Roberson 
2227b90816f1SJeff Roberson 	load = 1;
2228b90816f1SJeff Roberson 
2229ad1e7d28SJulian Elischer 	tdq = TDQ_SELF();
22303f741ca1SJeff Roberson 	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2231d2ad694cSJeff Roberson 		if (tdq->tdq_load > 0)
22323f741ca1SJeff Roberson 			goto out;
22333f741ca1SJeff Roberson 	} else
2234d2ad694cSJeff Roberson 		if (tdq->tdq_load - 1 > 0)
2235b90816f1SJeff Roberson 			goto out;
2236b90816f1SJeff Roberson 	load = 0;
2237b90816f1SJeff Roberson out:
2238b90816f1SJeff Roberson 	return (load);
223935e6168fSJeff Roberson }
224035e6168fSJeff Roberson 
2241ae7a6b38SJeff Roberson /*
2242ae7a6b38SJeff Roberson  * Choose the highest priority thread to run.  The thread is removed from
2243ae7a6b38SJeff Roberson  * the run-queue while running however the load remains.  For SMP we set
2244ae7a6b38SJeff Roberson  * the tdq in the global idle bitmask if it idles here.
2245ae7a6b38SJeff Roberson  */
22467a5e5e2aSJeff Roberson struct thread *
2247c9f25d8fSJeff Roberson sched_choose(void)
2248c9f25d8fSJeff Roberson {
22499727e637SJeff Roberson 	struct thread *td;
2250ae7a6b38SJeff Roberson 	struct tdq *tdq;
2251ae7a6b38SJeff Roberson 
2252ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2253ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
22549727e637SJeff Roberson 	td = tdq_choose(tdq);
22559727e637SJeff Roberson 	if (td) {
22569727e637SJeff Roberson 		tdq_runq_rem(tdq, td);
22570502fe2eSJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
22589727e637SJeff Roberson 		return (td);
225935e6168fSJeff Roberson 	}
22600502fe2eSJeff Roberson 	tdq->tdq_lowpri = PRI_MAX_IDLE;
226162fa74d9SJeff Roberson 	return (PCPU_GET(idlethread));
22627a5e5e2aSJeff Roberson }
22637a5e5e2aSJeff Roberson 
2264ae7a6b38SJeff Roberson /*
2265ae7a6b38SJeff Roberson  * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2266ae7a6b38SJeff Roberson  * we always request it once we exit a critical section.
2267ae7a6b38SJeff Roberson  */
2268ae7a6b38SJeff Roberson static inline void
2269ae7a6b38SJeff Roberson sched_setpreempt(struct thread *td)
22707a5e5e2aSJeff Roberson {
22717a5e5e2aSJeff Roberson 	struct thread *ctd;
22727a5e5e2aSJeff Roberson 	int cpri;
22737a5e5e2aSJeff Roberson 	int pri;
22747a5e5e2aSJeff Roberson 
2275ff256d9cSJeff Roberson 	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2276ff256d9cSJeff Roberson 
22777a5e5e2aSJeff Roberson 	ctd = curthread;
22787a5e5e2aSJeff Roberson 	pri = td->td_priority;
22797a5e5e2aSJeff Roberson 	cpri = ctd->td_priority;
2280ff256d9cSJeff Roberson 	if (pri < cpri)
2281ff256d9cSJeff Roberson 		ctd->td_flags |= TDF_NEEDRESCHED;
22827a5e5e2aSJeff Roberson 	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2283ae7a6b38SJeff Roberson 		return;
2284ff256d9cSJeff Roberson 	if (!sched_shouldpreempt(pri, cpri, 0))
2285ae7a6b38SJeff Roberson 		return;
22867a5e5e2aSJeff Roberson 	ctd->td_owepreempt = 1;
228735e6168fSJeff Roberson }
228835e6168fSJeff Roberson 
2289ae7a6b38SJeff Roberson /*
229073daf66fSJeff Roberson  * Add a thread to a thread queue.  Select the appropriate runq and add the
229173daf66fSJeff Roberson  * thread to it.  This is the internal function called when the tdq is
229273daf66fSJeff Roberson  * predetermined.
2293ae7a6b38SJeff Roberson  */
229435e6168fSJeff Roberson void
2295ae7a6b38SJeff Roberson tdq_add(struct tdq *tdq, struct thread *td, int flags)
229635e6168fSJeff Roberson {
2297c9f25d8fSJeff Roberson 
2298ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
22997a5e5e2aSJeff Roberson 	KASSERT((td->td_inhibitors == 0),
23007a5e5e2aSJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
23017a5e5e2aSJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
23027a5e5e2aSJeff Roberson 	    ("sched_add: bad thread state"));
2303b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
2304b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
2305ae7a6b38SJeff Roberson 
2306ae7a6b38SJeff Roberson 	if (td->td_priority < tdq->tdq_lowpri)
2307ae7a6b38SJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
23089727e637SJeff Roberson 	tdq_runq_add(tdq, td, flags);
23099727e637SJeff Roberson 	tdq_load_add(tdq, td);
2310ae7a6b38SJeff Roberson }
2311ae7a6b38SJeff Roberson 
2312ae7a6b38SJeff Roberson /*
2313ae7a6b38SJeff Roberson  * Select the target thread queue and add a thread to it.  Request
2314ae7a6b38SJeff Roberson  * preemption or IPI a remote processor if required.
2315ae7a6b38SJeff Roberson  */
2316ae7a6b38SJeff Roberson void
2317ae7a6b38SJeff Roberson sched_add(struct thread *td, int flags)
2318ae7a6b38SJeff Roberson {
2319ae7a6b38SJeff Roberson 	struct tdq *tdq;
23207b8bfa0dSJeff Roberson #ifdef SMP
2321ae7a6b38SJeff Roberson 	int cpu;
2322ae7a6b38SJeff Roberson #endif
23238f51ad55SJeff Roberson 
23248f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
23258f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
23268f51ad55SJeff Roberson 	    sched_tdname(curthread));
23278f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
23288f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
2329ae7a6b38SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2330ae7a6b38SJeff Roberson 	/*
2331ae7a6b38SJeff Roberson 	 * Recalculate the priority before we select the target cpu or
2332ae7a6b38SJeff Roberson 	 * run-queue.
2333ae7a6b38SJeff Roberson 	 */
2334ae7a6b38SJeff Roberson 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2335ae7a6b38SJeff Roberson 		sched_priority(td);
2336ae7a6b38SJeff Roberson #ifdef SMP
2337ae7a6b38SJeff Roberson 	/*
2338ae7a6b38SJeff Roberson 	 * Pick the destination cpu and if it isn't ours transfer to the
2339ae7a6b38SJeff Roberson 	 * target cpu.
2340ae7a6b38SJeff Roberson 	 */
23419727e637SJeff Roberson 	cpu = sched_pickcpu(td, flags);
23429727e637SJeff Roberson 	tdq = sched_setcpu(td, cpu, flags);
2343ae7a6b38SJeff Roberson 	tdq_add(tdq, td, flags);
234473daf66fSJeff Roberson 	if (cpu != PCPU_GET(cpuid)) {
23459727e637SJeff Roberson 		tdq_notify(tdq, td);
23467b8bfa0dSJeff Roberson 		return;
23477b8bfa0dSJeff Roberson 	}
2348ae7a6b38SJeff Roberson #else
2349ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2350ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
2351ae7a6b38SJeff Roberson 	/*
2352ae7a6b38SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
2353ae7a6b38SJeff Roberson 	 * to the scheduler's lock.
2354ae7a6b38SJeff Roberson 	 */
2355ae7a6b38SJeff Roberson 	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2356ae7a6b38SJeff Roberson 	tdq_add(tdq, td, flags);
23577b8bfa0dSJeff Roberson #endif
2358ae7a6b38SJeff Roberson 	if (!(flags & SRQ_YIELDING))
2359ae7a6b38SJeff Roberson 		sched_setpreempt(td);
236035e6168fSJeff Roberson }
236135e6168fSJeff Roberson 
2362ae7a6b38SJeff Roberson /*
2363ae7a6b38SJeff Roberson  * Remove a thread from a run-queue without running it.  This is used
2364ae7a6b38SJeff Roberson  * when we're stealing a thread from a remote queue.  Otherwise all threads
2365ae7a6b38SJeff Roberson  * exit by calling sched_exit_thread() and sched_throw() themselves.
2366ae7a6b38SJeff Roberson  */
236735e6168fSJeff Roberson void
23687cf90fb3SJeff Roberson sched_rem(struct thread *td)
236935e6168fSJeff Roberson {
2370ad1e7d28SJulian Elischer 	struct tdq *tdq;
23717cf90fb3SJeff Roberson 
23728f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
23738f51ad55SJeff Roberson 	    "prio:%d", td->td_priority);
23749727e637SJeff Roberson 	tdq = TDQ_CPU(td->td_sched->ts_cpu);
2375ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2376ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
23777a5e5e2aSJeff Roberson 	KASSERT(TD_ON_RUNQ(td),
2378ad1e7d28SJulian Elischer 	    ("sched_rem: thread not on run queue"));
23799727e637SJeff Roberson 	tdq_runq_rem(tdq, td);
23809727e637SJeff Roberson 	tdq_load_rem(tdq, td);
23817a5e5e2aSJeff Roberson 	TD_SET_CAN_RUN(td);
238262fa74d9SJeff Roberson 	if (td->td_priority == tdq->tdq_lowpri)
238362fa74d9SJeff Roberson 		tdq_setlowpri(tdq, NULL);
238435e6168fSJeff Roberson }
238535e6168fSJeff Roberson 
2386ae7a6b38SJeff Roberson /*
2387ae7a6b38SJeff Roberson  * Fetch cpu utilization information.  Updates on demand.
2388ae7a6b38SJeff Roberson  */
238935e6168fSJeff Roberson fixpt_t
23907cf90fb3SJeff Roberson sched_pctcpu(struct thread *td)
239135e6168fSJeff Roberson {
239235e6168fSJeff Roberson 	fixpt_t pctcpu;
2393ad1e7d28SJulian Elischer 	struct td_sched *ts;
239435e6168fSJeff Roberson 
239535e6168fSJeff Roberson 	pctcpu = 0;
2396ad1e7d28SJulian Elischer 	ts = td->td_sched;
2397ad1e7d28SJulian Elischer 	if (ts == NULL)
2398484288deSJeff Roberson 		return (0);
239935e6168fSJeff Roberson 
24003da35a0aSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2401*7295465eSAlexander Motin 	sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2402ad1e7d28SJulian Elischer 	if (ts->ts_ticks) {
240335e6168fSJeff Roberson 		int rtick;
240435e6168fSJeff Roberson 
240535e6168fSJeff Roberson 		/* How many rtick per second ? */
2406e7d50326SJeff Roberson 		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2407e7d50326SJeff Roberson 		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
240835e6168fSJeff Roberson 	}
240935e6168fSJeff Roberson 
241035e6168fSJeff Roberson 	return (pctcpu);
241135e6168fSJeff Roberson }
241235e6168fSJeff Roberson 
241362fa74d9SJeff Roberson /*
241462fa74d9SJeff Roberson  * Enforce affinity settings for a thread.  Called after adjustments to
241562fa74d9SJeff Roberson  * cpumask.
241662fa74d9SJeff Roberson  */
2417885d51a3SJeff Roberson void
2418885d51a3SJeff Roberson sched_affinity(struct thread *td)
2419885d51a3SJeff Roberson {
242062fa74d9SJeff Roberson #ifdef SMP
242162fa74d9SJeff Roberson 	struct td_sched *ts;
242262fa74d9SJeff Roberson 
242362fa74d9SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
242462fa74d9SJeff Roberson 	ts = td->td_sched;
242562fa74d9SJeff Roberson 	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
242662fa74d9SJeff Roberson 		return;
242753a6c8b3SJeff Roberson 	if (TD_ON_RUNQ(td)) {
242853a6c8b3SJeff Roberson 		sched_rem(td);
242953a6c8b3SJeff Roberson 		sched_add(td, SRQ_BORING);
243053a6c8b3SJeff Roberson 		return;
243153a6c8b3SJeff Roberson 	}
243262fa74d9SJeff Roberson 	if (!TD_IS_RUNNING(td))
243362fa74d9SJeff Roberson 		return;
243462fa74d9SJeff Roberson 	/*
24350f7a0ebdSMatthew D Fleming 	 * Force a switch before returning to userspace.  If the
24360f7a0ebdSMatthew D Fleming 	 * target thread is not running locally send an ipi to force
24370f7a0ebdSMatthew D Fleming 	 * the issue.
243862fa74d9SJeff Roberson 	 */
2439a8103ae8SJohn Baldwin 	td->td_flags |= TDF_NEEDRESCHED;
24400f7a0ebdSMatthew D Fleming 	if (td != curthread)
24410f7a0ebdSMatthew D Fleming 		ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
244262fa74d9SJeff Roberson #endif
2443885d51a3SJeff Roberson }
2444885d51a3SJeff Roberson 
2445ae7a6b38SJeff Roberson /*
2446ae7a6b38SJeff Roberson  * Bind a thread to a target cpu.
2447ae7a6b38SJeff Roberson  */
24489bacd788SJeff Roberson void
24499bacd788SJeff Roberson sched_bind(struct thread *td, int cpu)
24509bacd788SJeff Roberson {
2451ad1e7d28SJulian Elischer 	struct td_sched *ts;
24529bacd788SJeff Roberson 
2453c47f202bSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
24541d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
2455ad1e7d28SJulian Elischer 	ts = td->td_sched;
24566b2f763fSJeff Roberson 	if (ts->ts_flags & TSF_BOUND)
2457c95d2db2SJeff Roberson 		sched_unbind(td);
24580f7a0ebdSMatthew D Fleming 	KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2459ad1e7d28SJulian Elischer 	ts->ts_flags |= TSF_BOUND;
24606b2f763fSJeff Roberson 	sched_pin();
246180f86c9fSJeff Roberson 	if (PCPU_GET(cpuid) == cpu)
24629bacd788SJeff Roberson 		return;
24636b2f763fSJeff Roberson 	ts->ts_cpu = cpu;
24649bacd788SJeff Roberson 	/* When we return from mi_switch we'll be on the correct cpu. */
2465279f949eSPoul-Henning Kamp 	mi_switch(SW_VOL, NULL);
24669bacd788SJeff Roberson }
24679bacd788SJeff Roberson 
2468ae7a6b38SJeff Roberson /*
2469ae7a6b38SJeff Roberson  * Release a bound thread.
2470ae7a6b38SJeff Roberson  */
24719bacd788SJeff Roberson void
24729bacd788SJeff Roberson sched_unbind(struct thread *td)
24739bacd788SJeff Roberson {
2474e7d50326SJeff Roberson 	struct td_sched *ts;
2475e7d50326SJeff Roberson 
24767b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
24771d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
2478e7d50326SJeff Roberson 	ts = td->td_sched;
24796b2f763fSJeff Roberson 	if ((ts->ts_flags & TSF_BOUND) == 0)
24806b2f763fSJeff Roberson 		return;
2481e7d50326SJeff Roberson 	ts->ts_flags &= ~TSF_BOUND;
2482e7d50326SJeff Roberson 	sched_unpin();
24839bacd788SJeff Roberson }
24849bacd788SJeff Roberson 
248535e6168fSJeff Roberson int
2486ebccf1e3SJoseph Koshy sched_is_bound(struct thread *td)
2487ebccf1e3SJoseph Koshy {
24887b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2489ad1e7d28SJulian Elischer 	return (td->td_sched->ts_flags & TSF_BOUND);
2490ebccf1e3SJoseph Koshy }
2491ebccf1e3SJoseph Koshy 
2492ae7a6b38SJeff Roberson /*
2493ae7a6b38SJeff Roberson  * Basic yield call.
2494ae7a6b38SJeff Roberson  */
249536ec198bSDavid Xu void
249636ec198bSDavid Xu sched_relinquish(struct thread *td)
249736ec198bSDavid Xu {
24987b20fb19SJeff Roberson 	thread_lock(td);
24998df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
25007b20fb19SJeff Roberson 	thread_unlock(td);
250136ec198bSDavid Xu }
250236ec198bSDavid Xu 
2503ae7a6b38SJeff Roberson /*
2504ae7a6b38SJeff Roberson  * Return the total system load.
2505ae7a6b38SJeff Roberson  */
2506ebccf1e3SJoseph Koshy int
250733916c36SJeff Roberson sched_load(void)
250833916c36SJeff Roberson {
250933916c36SJeff Roberson #ifdef SMP
251033916c36SJeff Roberson 	int total;
251133916c36SJeff Roberson 	int i;
251233916c36SJeff Roberson 
251333916c36SJeff Roberson 	total = 0;
25143aa6d94eSJohn Baldwin 	CPU_FOREACH(i)
251562fa74d9SJeff Roberson 		total += TDQ_CPU(i)->tdq_sysload;
251633916c36SJeff Roberson 	return (total);
251733916c36SJeff Roberson #else
2518d2ad694cSJeff Roberson 	return (TDQ_SELF()->tdq_sysload);
251933916c36SJeff Roberson #endif
252033916c36SJeff Roberson }
252133916c36SJeff Roberson 
252233916c36SJeff Roberson int
252335e6168fSJeff Roberson sched_sizeof_proc(void)
252435e6168fSJeff Roberson {
252535e6168fSJeff Roberson 	return (sizeof(struct proc));
252635e6168fSJeff Roberson }
252735e6168fSJeff Roberson 
252835e6168fSJeff Roberson int
252935e6168fSJeff Roberson sched_sizeof_thread(void)
253035e6168fSJeff Roberson {
253135e6168fSJeff Roberson 	return (sizeof(struct thread) + sizeof(struct td_sched));
253235e6168fSJeff Roberson }
2533b41f1452SDavid Xu 
253409c8a4ccSJeff Roberson #ifdef SMP
253509c8a4ccSJeff Roberson #define	TDQ_IDLESPIN(tdq)						\
253609c8a4ccSJeff Roberson     ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
253709c8a4ccSJeff Roberson #else
253809c8a4ccSJeff Roberson #define	TDQ_IDLESPIN(tdq)	1
253909c8a4ccSJeff Roberson #endif
254009c8a4ccSJeff Roberson 
25417a5e5e2aSJeff Roberson /*
25427a5e5e2aSJeff Roberson  * The actual idle process.
25437a5e5e2aSJeff Roberson  */
25447a5e5e2aSJeff Roberson void
25457a5e5e2aSJeff Roberson sched_idletd(void *dummy)
25467a5e5e2aSJeff Roberson {
25477a5e5e2aSJeff Roberson 	struct thread *td;
2548ae7a6b38SJeff Roberson 	struct tdq *tdq;
25491690c6c1SJeff Roberson 	int switchcnt;
25501690c6c1SJeff Roberson 	int i;
25517a5e5e2aSJeff Roberson 
25527b55ab05SJeff Roberson 	mtx_assert(&Giant, MA_NOTOWNED);
25537a5e5e2aSJeff Roberson 	td = curthread;
2554ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2555ae7a6b38SJeff Roberson 	for (;;) {
2556ae7a6b38SJeff Roberson #ifdef SMP
25571690c6c1SJeff Roberson 		if (tdq_idled(tdq) == 0)
25581690c6c1SJeff Roberson 			continue;
2559ae7a6b38SJeff Roberson #endif
25601690c6c1SJeff Roberson 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
25611690c6c1SJeff Roberson 		/*
25621690c6c1SJeff Roberson 		 * If we're switching very frequently, spin while checking
25631690c6c1SJeff Roberson 		 * for load rather than entering a low power state that
25647b55ab05SJeff Roberson 		 * may require an IPI.  However, don't do any busy
25657b55ab05SJeff Roberson 		 * loops while on SMT machines as this simply steals
25667b55ab05SJeff Roberson 		 * cycles from cores doing useful work.
25671690c6c1SJeff Roberson 		 */
256809c8a4ccSJeff Roberson 		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
25691690c6c1SJeff Roberson 			for (i = 0; i < sched_idlespins; i++) {
25701690c6c1SJeff Roberson 				if (tdq->tdq_load)
25711690c6c1SJeff Roberson 					break;
25721690c6c1SJeff Roberson 				cpu_spinwait();
25731690c6c1SJeff Roberson 			}
25741690c6c1SJeff Roberson 		}
25756c47aaaeSJeff Roberson 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
25769f9ad565SAlexander Motin 		if (tdq->tdq_load == 0) {
25779f9ad565SAlexander Motin 			tdq->tdq_cpu_idle = 1;
25789f9ad565SAlexander Motin 			if (tdq->tdq_load == 0) {
2579a157e425SAlexander Motin 				cpu_idle(switchcnt > sched_idlespinthresh * 4);
25809f9ad565SAlexander Motin 				tdq->tdq_switchcnt++;
25819f9ad565SAlexander Motin 			}
25829f9ad565SAlexander Motin 			tdq->tdq_cpu_idle = 0;
25839f9ad565SAlexander Motin 		}
25841690c6c1SJeff Roberson 		if (tdq->tdq_load) {
25851690c6c1SJeff Roberson 			thread_lock(td);
25861690c6c1SJeff Roberson 			mi_switch(SW_VOL | SWT_IDLE, NULL);
25871690c6c1SJeff Roberson 			thread_unlock(td);
25881690c6c1SJeff Roberson 		}
2589ae7a6b38SJeff Roberson 	}
2590b41f1452SDavid Xu }
2591e7d50326SJeff Roberson 
25927b20fb19SJeff Roberson /*
25937b20fb19SJeff Roberson  * A CPU is entering for the first time or a thread is exiting.
25947b20fb19SJeff Roberson  */
25957b20fb19SJeff Roberson void
25967b20fb19SJeff Roberson sched_throw(struct thread *td)
25977b20fb19SJeff Roberson {
259859c68134SJeff Roberson 	struct thread *newtd;
2599ae7a6b38SJeff Roberson 	struct tdq *tdq;
2600ae7a6b38SJeff Roberson 
2601ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
26027b20fb19SJeff Roberson 	if (td == NULL) {
2603ae7a6b38SJeff Roberson 		/* Correct spinlock nesting and acquire the correct lock. */
2604ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
26057b20fb19SJeff Roberson 		spinlock_exit();
26067e3a96eaSJohn Baldwin 		PCPU_SET(switchtime, cpu_ticks());
26077e3a96eaSJohn Baldwin 		PCPU_SET(switchticks, ticks);
26087b20fb19SJeff Roberson 	} else {
2609ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
26109727e637SJeff Roberson 		tdq_load_rem(tdq, td);
2611eea4f254SJeff Roberson 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
26127b20fb19SJeff Roberson 	}
26137b20fb19SJeff Roberson 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
261459c68134SJeff Roberson 	newtd = choosethread();
261559c68134SJeff Roberson 	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
261659c68134SJeff Roberson 	cpu_throw(td, newtd);		/* doesn't return */
26177b20fb19SJeff Roberson }
26187b20fb19SJeff Roberson 
2619ae7a6b38SJeff Roberson /*
2620ae7a6b38SJeff Roberson  * This is called from fork_exit().  Just acquire the correct locks and
2621ae7a6b38SJeff Roberson  * let fork do the rest of the work.
2622ae7a6b38SJeff Roberson  */
26237b20fb19SJeff Roberson void
2624fe54587fSJeff Roberson sched_fork_exit(struct thread *td)
26257b20fb19SJeff Roberson {
2626ae7a6b38SJeff Roberson 	struct td_sched *ts;
2627ae7a6b38SJeff Roberson 	struct tdq *tdq;
2628ae7a6b38SJeff Roberson 	int cpuid;
26297b20fb19SJeff Roberson 
26307b20fb19SJeff Roberson 	/*
26317b20fb19SJeff Roberson 	 * Finish setting up thread glue so that it begins execution in a
2632ae7a6b38SJeff Roberson 	 * non-nested critical section with the scheduler lock held.
26337b20fb19SJeff Roberson 	 */
2634ae7a6b38SJeff Roberson 	cpuid = PCPU_GET(cpuid);
2635ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpuid);
2636ae7a6b38SJeff Roberson 	ts = td->td_sched;
2637ae7a6b38SJeff Roberson 	if (TD_IS_IDLETHREAD(td))
2638ae7a6b38SJeff Roberson 		td->td_lock = TDQ_LOCKPTR(tdq);
2639ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2640ae7a6b38SJeff Roberson 	td->td_oncpu = cpuid;
264159c68134SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2642eea4f254SJeff Roberson 	lock_profile_obtain_lock_success(
2643eea4f254SJeff Roberson 	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
26447b20fb19SJeff Roberson }
26457b20fb19SJeff Roberson 
26468f51ad55SJeff Roberson /*
26478f51ad55SJeff Roberson  * Create on first use to catch odd startup conditons.
26488f51ad55SJeff Roberson  */
26498f51ad55SJeff Roberson char *
26508f51ad55SJeff Roberson sched_tdname(struct thread *td)
26518f51ad55SJeff Roberson {
26528f51ad55SJeff Roberson #ifdef KTR
26538f51ad55SJeff Roberson 	struct td_sched *ts;
26548f51ad55SJeff Roberson 
26558f51ad55SJeff Roberson 	ts = td->td_sched;
26568f51ad55SJeff Roberson 	if (ts->ts_name[0] == '\0')
26578f51ad55SJeff Roberson 		snprintf(ts->ts_name, sizeof(ts->ts_name),
26588f51ad55SJeff Roberson 		    "%s tid %d", td->td_name, td->td_tid);
26598f51ad55SJeff Roberson 	return (ts->ts_name);
26608f51ad55SJeff Roberson #else
26618f51ad55SJeff Roberson 	return (td->td_name);
26628f51ad55SJeff Roberson #endif
26638f51ad55SJeff Roberson }
26648f51ad55SJeff Roberson 
266544ad5475SJohn Baldwin #ifdef KTR
266644ad5475SJohn Baldwin void
266744ad5475SJohn Baldwin sched_clear_tdname(struct thread *td)
266844ad5475SJohn Baldwin {
266944ad5475SJohn Baldwin 	struct td_sched *ts;
267044ad5475SJohn Baldwin 
267144ad5475SJohn Baldwin 	ts = td->td_sched;
267244ad5475SJohn Baldwin 	ts->ts_name[0] = '\0';
267344ad5475SJohn Baldwin }
267444ad5475SJohn Baldwin #endif
267544ad5475SJohn Baldwin 
267607095abfSIvan Voras #ifdef SMP
267707095abfSIvan Voras 
267807095abfSIvan Voras /*
267907095abfSIvan Voras  * Build the CPU topology dump string. Is recursively called to collect
268007095abfSIvan Voras  * the topology tree.
268107095abfSIvan Voras  */
268207095abfSIvan Voras static int
268307095abfSIvan Voras sysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
268407095abfSIvan Voras     int indent)
268507095abfSIvan Voras {
268671a19bdcSAttilio Rao 	char cpusetbuf[CPUSETBUFSIZ];
268707095abfSIvan Voras 	int i, first;
268807095abfSIvan Voras 
268907095abfSIvan Voras 	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
269019b8a6dbSAndriy Gapon 	    "", 1 + indent / 2, cg->cg_level);
269171a19bdcSAttilio Rao 	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
269271a19bdcSAttilio Rao 	    cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
269307095abfSIvan Voras 	first = TRUE;
269407095abfSIvan Voras 	for (i = 0; i < MAXCPU; i++) {
269571a19bdcSAttilio Rao 		if (CPU_ISSET(i, &cg->cg_mask)) {
269607095abfSIvan Voras 			if (!first)
269707095abfSIvan Voras 				sbuf_printf(sb, ", ");
269807095abfSIvan Voras 			else
269907095abfSIvan Voras 				first = FALSE;
270007095abfSIvan Voras 			sbuf_printf(sb, "%d", i);
270107095abfSIvan Voras 		}
270207095abfSIvan Voras 	}
270307095abfSIvan Voras 	sbuf_printf(sb, "</cpu>\n");
270407095abfSIvan Voras 
270507095abfSIvan Voras 	if (cg->cg_flags != 0) {
2706611daf7eSIvan Voras 		sbuf_printf(sb, "%*s <flags>", indent, "");
270707095abfSIvan Voras 		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
27085368befbSIvan Voras 			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
2709a401f2d0SIvan Voras 		if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
2710a401f2d0SIvan Voras 			sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
27117b55ab05SJeff Roberson 		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
2712a401f2d0SIvan Voras 			sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
271307095abfSIvan Voras 		sbuf_printf(sb, "</flags>\n");
2714611daf7eSIvan Voras 	}
271507095abfSIvan Voras 
271607095abfSIvan Voras 	if (cg->cg_children > 0) {
271707095abfSIvan Voras 		sbuf_printf(sb, "%*s <children>\n", indent, "");
271807095abfSIvan Voras 		for (i = 0; i < cg->cg_children; i++)
271907095abfSIvan Voras 			sysctl_kern_sched_topology_spec_internal(sb,
272007095abfSIvan Voras 			    &cg->cg_child[i], indent+2);
272107095abfSIvan Voras 		sbuf_printf(sb, "%*s </children>\n", indent, "");
272207095abfSIvan Voras 	}
272307095abfSIvan Voras 	sbuf_printf(sb, "%*s</group>\n", indent, "");
272407095abfSIvan Voras 	return (0);
272507095abfSIvan Voras }
272607095abfSIvan Voras 
272707095abfSIvan Voras /*
272807095abfSIvan Voras  * Sysctl handler for retrieving topology dump. It's a wrapper for
272907095abfSIvan Voras  * the recursive sysctl_kern_smp_topology_spec_internal().
273007095abfSIvan Voras  */
273107095abfSIvan Voras static int
273207095abfSIvan Voras sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
273307095abfSIvan Voras {
273407095abfSIvan Voras 	struct sbuf *topo;
273507095abfSIvan Voras 	int err;
273607095abfSIvan Voras 
273707095abfSIvan Voras 	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
273807095abfSIvan Voras 
2739aa880b90SIvan Voras 	topo = sbuf_new(NULL, NULL, 500, SBUF_AUTOEXTEND);
274007095abfSIvan Voras 	if (topo == NULL)
274107095abfSIvan Voras 		return (ENOMEM);
274207095abfSIvan Voras 
274307095abfSIvan Voras 	sbuf_printf(topo, "<groups>\n");
274407095abfSIvan Voras 	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
274507095abfSIvan Voras 	sbuf_printf(topo, "</groups>\n");
274607095abfSIvan Voras 
274707095abfSIvan Voras 	if (err == 0) {
274807095abfSIvan Voras 		sbuf_finish(topo);
274907095abfSIvan Voras 		err = SYSCTL_OUT(req, sbuf_data(topo), sbuf_len(topo));
275007095abfSIvan Voras 	}
275107095abfSIvan Voras 	sbuf_delete(topo);
275207095abfSIvan Voras 	return (err);
275307095abfSIvan Voras }
2754b67cc292SDavid Xu 
275507095abfSIvan Voras #endif
275607095abfSIvan Voras 
27579727e637SJeff Roberson SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2758ae7a6b38SJeff Roberson SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2759e7d50326SJeff Roberson     "Scheduler name");
2760ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2761ae7a6b38SJeff Roberson     "Slice size for timeshare threads");
2762ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2763ae7a6b38SJeff Roberson      "Interactivity score threshold");
2764ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2765ae7a6b38SJeff Roberson      0,"Min priority for preemption, lower priorities have greater precedence");
2766c5aa6b58SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost,
2767c5aa6b58SJeff Roberson      0,"Controls whether static kernel priorities are assigned to sleeping threads.");
27681690c6c1SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins,
27691690c6c1SJeff Roberson      0,"Number of times idle will spin waiting for new work.");
27701690c6c1SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW, &sched_idlespinthresh,
27711690c6c1SJeff Roberson      0,"Threshold before we will permit idle spinning.");
27727b8bfa0dSJeff Roberson #ifdef SMP
2773ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2774ae7a6b38SJeff Roberson     "Number of hz ticks to keep thread affinity for");
2775ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2776ae7a6b38SJeff Roberson     "Enables the long-term load balancer");
27777fcf154aSJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
27787fcf154aSJeff Roberson     &balance_interval, 0,
27797fcf154aSJeff Roberson     "Average frequency in stathz ticks to run the long-term balancer");
2780ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2781ae7a6b38SJeff Roberson     "Attempts to steal work from other cores before idling");
278228994a58SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
278328994a58SJeff Roberson     "Minimum load on remote cpu before we'll steal");
278407095abfSIvan Voras 
278507095abfSIvan Voras /* Retrieve SMP topology */
278607095abfSIvan Voras SYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
278707095abfSIvan Voras     CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
278807095abfSIvan Voras     "XML dump of detected CPU topology");
2789b67cc292SDavid Xu 
27907b8bfa0dSJeff Roberson #endif
2791e7d50326SJeff Roberson 
279254b0e65fSJeff Roberson /* ps compat.  All cpu percentages from ULE are weighted. */
2793a5423ea3SJeff Roberson static int ccpu = 0;
2794e7d50326SJeff Roberson SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2795