xref: /freebsd/sys/kern/sched_ule.c (revision 2824088536acef4b85fc0ad93c595deccbedb3af)
135e6168fSJeff Roberson /*-
28a36da99SPedro F. Giffuni  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
38a36da99SPedro F. Giffuni  *
4e7d50326SJeff Roberson  * Copyright (c) 2002-2007, Jeffrey Roberson <jeff@freebsd.org>
535e6168fSJeff Roberson  * All rights reserved.
635e6168fSJeff Roberson  *
735e6168fSJeff Roberson  * Redistribution and use in source and binary forms, with or without
835e6168fSJeff Roberson  * modification, are permitted provided that the following conditions
935e6168fSJeff Roberson  * are met:
1035e6168fSJeff Roberson  * 1. Redistributions of source code must retain the above copyright
1135e6168fSJeff Roberson  *    notice unmodified, this list of conditions, and the following
1235e6168fSJeff Roberson  *    disclaimer.
1335e6168fSJeff Roberson  * 2. Redistributions in binary form must reproduce the above copyright
1435e6168fSJeff Roberson  *    notice, this list of conditions and the following disclaimer in the
1535e6168fSJeff Roberson  *    documentation and/or other materials provided with the distribution.
1635e6168fSJeff Roberson  *
1735e6168fSJeff Roberson  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1835e6168fSJeff Roberson  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1935e6168fSJeff Roberson  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
2035e6168fSJeff Roberson  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
2135e6168fSJeff Roberson  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
2235e6168fSJeff Roberson  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2335e6168fSJeff Roberson  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2435e6168fSJeff Roberson  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2535e6168fSJeff Roberson  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
2635e6168fSJeff Roberson  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2735e6168fSJeff Roberson  */
2835e6168fSJeff Roberson 
29ae7a6b38SJeff Roberson /*
30ae7a6b38SJeff Roberson  * This file implements the ULE scheduler.  ULE supports independent CPU
31ae7a6b38SJeff Roberson  * run queues and fine grain locking.  It has superior interactive
32ae7a6b38SJeff Roberson  * performance under load even on uni-processor systems.
33ae7a6b38SJeff Roberson  *
34ae7a6b38SJeff Roberson  * etymology:
35a5423ea3SJeff Roberson  *   ULE is the last three letters in schedule.  It owes its name to a
36ae7a6b38SJeff Roberson  * generic user created for a scheduling system by Paul Mikesell at
37ae7a6b38SJeff Roberson  * Isilon Systems and a general lack of creativity on the part of the author.
38ae7a6b38SJeff Roberson  */
39ae7a6b38SJeff Roberson 
40677b542eSDavid E. O'Brien #include <sys/cdefs.h>
41113dda8aSJeff Roberson __FBSDID("$FreeBSD$");
42677b542eSDavid E. O'Brien 
434da0d332SPeter Wemm #include "opt_hwpmc_hooks.h"
444da0d332SPeter Wemm #include "opt_sched.h"
459923b511SScott Long 
4635e6168fSJeff Roberson #include <sys/param.h>
4735e6168fSJeff Roberson #include <sys/systm.h>
482c3490b1SMarcel Moolenaar #include <sys/kdb.h>
4935e6168fSJeff Roberson #include <sys/kernel.h>
5035e6168fSJeff Roberson #include <sys/ktr.h>
51c149e542SAttilio Rao #include <sys/limits.h>
5235e6168fSJeff Roberson #include <sys/lock.h>
5335e6168fSJeff Roberson #include <sys/mutex.h>
5435e6168fSJeff Roberson #include <sys/proc.h>
55245f3abfSJeff Roberson #include <sys/resource.h>
569bacd788SJeff Roberson #include <sys/resourcevar.h>
5735e6168fSJeff Roberson #include <sys/sched.h>
58b3e9e682SRyan Stone #include <sys/sdt.h>
5935e6168fSJeff Roberson #include <sys/smp.h>
6035e6168fSJeff Roberson #include <sys/sx.h>
6135e6168fSJeff Roberson #include <sys/sysctl.h>
6235e6168fSJeff Roberson #include <sys/sysproto.h>
63f5c157d9SJohn Baldwin #include <sys/turnstile.h>
643db720fdSDavid Xu #include <sys/umtx.h>
6535e6168fSJeff Roberson #include <sys/vmmeter.h>
6662fa74d9SJeff Roberson #include <sys/cpuset.h>
6707095abfSIvan Voras #include <sys/sbuf.h>
6835e6168fSJeff Roberson 
69ebccf1e3SJoseph Koshy #ifdef HWPMC_HOOKS
70ebccf1e3SJoseph Koshy #include <sys/pmckern.h>
71ebccf1e3SJoseph Koshy #endif
72ebccf1e3SJoseph Koshy 
736f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
746f5f25e5SJohn Birrell #include <sys/dtrace_bsd.h>
756f5f25e5SJohn Birrell int				dtrace_vtime_active;
766f5f25e5SJohn Birrell dtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
776f5f25e5SJohn Birrell #endif
786f5f25e5SJohn Birrell 
7935e6168fSJeff Roberson #include <machine/cpu.h>
8022bf7d9aSJeff Roberson #include <machine/smp.h>
8135e6168fSJeff Roberson 
82ae7a6b38SJeff Roberson #define	KTR_ULE	0
8314618990SJeff Roberson 
840d2cf837SJeff Roberson #define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
850d2cf837SJeff Roberson #define	TDQ_NAME_LEN	(sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
866338c579SAttilio Rao #define	TDQ_LOADNAME_LEN	(sizeof("CPU ") + sizeof(__XSTRING(MAXCPU)) - 1 + sizeof(" load"))
878f51ad55SJeff Roberson 
886b2f763fSJeff Roberson /*
89ae7a6b38SJeff Roberson  * Thread scheduler specific section.  All fields are protected
90ae7a6b38SJeff Roberson  * by the thread lock.
91ed062c8dSJulian Elischer  */
92ad1e7d28SJulian Elischer struct td_sched {
93ae7a6b38SJeff Roberson 	struct runq	*ts_runq;	/* Run-queue we're queued on. */
94ae7a6b38SJeff Roberson 	short		ts_flags;	/* TSF_* flags. */
95e77f9fedSAdrian Chadd 	int		ts_cpu;		/* CPU that we have affinity for. */
9673daf66fSJeff Roberson 	int		ts_rltick;	/* Real last tick, for affinity. */
97ae7a6b38SJeff Roberson 	int		ts_slice;	/* Ticks of slice remaining. */
98ae7a6b38SJeff Roberson 	u_int		ts_slptime;	/* Number of ticks we vol. slept */
99ae7a6b38SJeff Roberson 	u_int		ts_runtime;	/* Number of ticks we were running */
100ad1e7d28SJulian Elischer 	int		ts_ltick;	/* Last tick that we were running on */
101ad1e7d28SJulian Elischer 	int		ts_ftick;	/* First tick that we were running on */
102ad1e7d28SJulian Elischer 	int		ts_ticks;	/* Tick count */
1038f51ad55SJeff Roberson #ifdef KTR
1048f51ad55SJeff Roberson 	char		ts_name[TS_NAME_LEN];
1058f51ad55SJeff Roberson #endif
106ed062c8dSJulian Elischer };
107ad1e7d28SJulian Elischer /* flags kept in ts_flags */
1087b8bfa0dSJeff Roberson #define	TSF_BOUND	0x0001		/* Thread can not migrate. */
1097b8bfa0dSJeff Roberson #define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
11035e6168fSJeff Roberson 
11162fa74d9SJeff Roberson #define	THREAD_CAN_MIGRATE(td)	((td)->td_pinned == 0)
11262fa74d9SJeff Roberson #define	THREAD_CAN_SCHED(td, cpu)	\
11362fa74d9SJeff Roberson     CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
11462fa74d9SJeff Roberson 
11593ccd6bfSKonstantin Belousov _Static_assert(sizeof(struct thread) + sizeof(struct td_sched) <=
11693ccd6bfSKonstantin Belousov     sizeof(struct thread0_storage),
11793ccd6bfSKonstantin Belousov     "increase struct thread0_storage.t0st_sched size");
11893ccd6bfSKonstantin Belousov 
11935e6168fSJeff Roberson /*
12012d56c0fSJohn Baldwin  * Priority ranges used for interactive and non-interactive timeshare
1212dc29adbSJohn Baldwin  * threads.  The timeshare priorities are split up into four ranges.
1222dc29adbSJohn Baldwin  * The first range handles interactive threads.  The last three ranges
1232dc29adbSJohn Baldwin  * (NHALF, x, and NHALF) handle non-interactive threads with the outer
1242dc29adbSJohn Baldwin  * ranges supporting nice values.
12512d56c0fSJohn Baldwin  */
1262dc29adbSJohn Baldwin #define	PRI_TIMESHARE_RANGE	(PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
1272dc29adbSJohn Baldwin #define	PRI_INTERACT_RANGE	((PRI_TIMESHARE_RANGE - SCHED_PRI_NRESV) / 2)
12816705791SAndriy Gapon #define	PRI_BATCH_RANGE		(PRI_TIMESHARE_RANGE - PRI_INTERACT_RANGE)
1292dc29adbSJohn Baldwin 
1302dc29adbSJohn Baldwin #define	PRI_MIN_INTERACT	PRI_MIN_TIMESHARE
1312dc29adbSJohn Baldwin #define	PRI_MAX_INTERACT	(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE - 1)
1322dc29adbSJohn Baldwin #define	PRI_MIN_BATCH		(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE)
13312d56c0fSJohn Baldwin #define	PRI_MAX_BATCH		PRI_MAX_TIMESHARE
13412d56c0fSJohn Baldwin 
13512d56c0fSJohn Baldwin /*
136e7d50326SJeff Roberson  * Cpu percentage computation macros and defines.
137e1f89c22SJeff Roberson  *
138e7d50326SJeff Roberson  * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
139e7d50326SJeff Roberson  * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
1408ab80cf0SJeff Roberson  * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
141e7d50326SJeff Roberson  * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
142e7d50326SJeff Roberson  * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
143e7d50326SJeff Roberson  * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
14435e6168fSJeff Roberson  */
145e7d50326SJeff Roberson #define	SCHED_TICK_SECS		10
146e7d50326SJeff Roberson #define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
1478ab80cf0SJeff Roberson #define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
148e7d50326SJeff Roberson #define	SCHED_TICK_SHIFT	10
149e7d50326SJeff Roberson #define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
150eddb4efaSJeff Roberson #define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
15135e6168fSJeff Roberson 
15235e6168fSJeff Roberson /*
153e7d50326SJeff Roberson  * These macros determine priorities for non-interactive threads.  They are
154e7d50326SJeff Roberson  * assigned a priority based on their recent cpu utilization as expressed
155e7d50326SJeff Roberson  * by the ratio of ticks to the tick total.  NHALF priorities at the start
156e7d50326SJeff Roberson  * and end of the MIN to MAX timeshare range are only reachable with negative
157e7d50326SJeff Roberson  * or positive nice respectively.
158e7d50326SJeff Roberson  *
159e7d50326SJeff Roberson  * PRI_RANGE:	Priority range for utilization dependent priorities.
160e7d50326SJeff Roberson  * PRI_NRESV:	Number of nice values.
161e7d50326SJeff Roberson  * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
162e7d50326SJeff Roberson  * PRI_NICE:	Determines the part of the priority inherited from nice.
163e7d50326SJeff Roberson  */
164e7d50326SJeff Roberson #define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
165e7d50326SJeff Roberson #define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
16612d56c0fSJohn Baldwin #define	SCHED_PRI_MIN		(PRI_MIN_BATCH + SCHED_PRI_NHALF)
16712d56c0fSJohn Baldwin #define	SCHED_PRI_MAX		(PRI_MAX_BATCH - SCHED_PRI_NHALF)
16878920008SJohn Baldwin #define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN + 1)
169e7d50326SJeff Roberson #define	SCHED_PRI_TICKS(ts)						\
170e7d50326SJeff Roberson     (SCHED_TICK_HZ((ts)) /						\
1711e516cf5SJeff Roberson     (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
172e7d50326SJeff Roberson #define	SCHED_PRI_NICE(nice)	(nice)
173e7d50326SJeff Roberson 
174e7d50326SJeff Roberson /*
175e7d50326SJeff Roberson  * These determine the interactivity of a process.  Interactivity differs from
176e7d50326SJeff Roberson  * cpu utilization in that it expresses the voluntary time slept vs time ran
177e7d50326SJeff Roberson  * while cpu utilization includes all time not running.  This more accurately
178e7d50326SJeff Roberson  * models the intent of the thread.
17935e6168fSJeff Roberson  *
180407b0157SJeff Roberson  * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
181407b0157SJeff Roberson  *		before throttling back.
182d322132cSJeff Roberson  * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
183210491d3SJeff Roberson  * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
1849f518f20SAttilio Rao  * INTERACT_THRESH:	Threshold for placement on the current runq.
18535e6168fSJeff Roberson  */
186e7d50326SJeff Roberson #define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
187e7d50326SJeff Roberson #define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
188210491d3SJeff Roberson #define	SCHED_INTERACT_MAX	(100)
189210491d3SJeff Roberson #define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
1904c9612c6SJeff Roberson #define	SCHED_INTERACT_THRESH	(30)
191e1f89c22SJeff Roberson 
1925e5c3873SJeff Roberson /*
1935e5c3873SJeff Roberson  * These parameters determine the slice behavior for batch work.
1945e5c3873SJeff Roberson  */
1955e5c3873SJeff Roberson #define	SCHED_SLICE_DEFAULT_DIVISOR	10	/* ~94 ms, 12 stathz ticks. */
1965e5c3873SJeff Roberson #define	SCHED_SLICE_MIN_DIVISOR		6	/* DEFAULT/MIN = ~16 ms. */
1975e5c3873SJeff Roberson 
1983d7f4117SAlexander Motin /* Flags kept in td_flags. */
1993d7f4117SAlexander Motin #define	TDF_SLICEEND	TDF_SCHED2	/* Thread time slice is over. */
2003d7f4117SAlexander Motin 
20135e6168fSJeff Roberson /*
202e7d50326SJeff Roberson  * tickincr:		Converts a stathz tick into a hz domain scaled by
203e7d50326SJeff Roberson  *			the shift factor.  Without the shift the error rate
204e7d50326SJeff Roberson  *			due to rounding would be unacceptably high.
205e7d50326SJeff Roberson  * realstathz:		stathz is sometimes 0 and run off of hz.
206e7d50326SJeff Roberson  * sched_slice:		Runtime of each thread before rescheduling.
207ae7a6b38SJeff Roberson  * preempt_thresh:	Priority threshold for preemption and remote IPIs.
20835e6168fSJeff Roberson  */
209e7d50326SJeff Roberson static int sched_interact = SCHED_INTERACT_THRESH;
210db702c59SEitan Adler static int tickincr = 8 << SCHED_TICK_SHIFT;
2115e5c3873SJeff Roberson static int realstathz = 127;	/* reset during boot. */
2125e5c3873SJeff Roberson static int sched_slice = 10;	/* reset during boot. */
2135e5c3873SJeff Roberson static int sched_slice_min = 1;	/* reset during boot. */
21402e2d6b4SJeff Roberson #ifdef PREEMPTION
21502e2d6b4SJeff Roberson #ifdef FULL_PREEMPTION
21602e2d6b4SJeff Roberson static int preempt_thresh = PRI_MAX_IDLE;
21702e2d6b4SJeff Roberson #else
218ae7a6b38SJeff Roberson static int preempt_thresh = PRI_MIN_KERN;
21902e2d6b4SJeff Roberson #endif
22002e2d6b4SJeff Roberson #else
22102e2d6b4SJeff Roberson static int preempt_thresh = 0;
22202e2d6b4SJeff Roberson #endif
22312d56c0fSJohn Baldwin static int static_boost = PRI_MIN_BATCH;
2241690c6c1SJeff Roberson static int sched_idlespins = 10000;
225b3f40a41SAlexander Motin static int sched_idlespinthresh = -1;
226ae7a6b38SJeff Roberson 
22735e6168fSJeff Roberson /*
228ae7a6b38SJeff Roberson  * tdq - per processor runqs and statistics.  All fields are protected by the
229ae7a6b38SJeff Roberson  * tdq_lock.  The load and lowpri may be accessed without to avoid excess
230ae7a6b38SJeff Roberson  * locking in sched_pickcpu();
23135e6168fSJeff Roberson  */
232ad1e7d28SJulian Elischer struct tdq {
23339f819e2SJim Harris 	/*
23439f819e2SJim Harris 	 * Ordered to improve efficiency of cpu_search() and switch().
23539f819e2SJim Harris 	 * tdq_lock is padded to avoid false sharing with tdq_load and
23639f819e2SJim Harris 	 * tdq_cpu_idle.
23739f819e2SJim Harris 	 */
2384ceaf45dSAttilio Rao 	struct mtx_padalign tdq_lock;		/* run queue lock. */
23973daf66fSJeff Roberson 	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
2401690c6c1SJeff Roberson 	volatile int	tdq_load;		/* Aggregate load. */
2419f9ad565SAlexander Motin 	volatile int	tdq_cpu_idle;		/* cpu_idle() is active. */
24273daf66fSJeff Roberson 	int		tdq_sysload;		/* For loadavg, !ITHD load. */
24397e9382dSDon Lewis 	volatile int	tdq_transferable;	/* Transferable thread count. */
24497e9382dSDon Lewis 	volatile short	tdq_switchcnt;		/* Switches this tick. */
24597e9382dSDon Lewis 	volatile short	tdq_oldswitchcnt;	/* Switches last tick. */
24673daf66fSJeff Roberson 	u_char		tdq_lowpri;		/* Lowest priority thread. */
24773daf66fSJeff Roberson 	u_char		tdq_ipipending;		/* IPI pending. */
24873daf66fSJeff Roberson 	u_char		tdq_idx;		/* Current insert index. */
24973daf66fSJeff Roberson 	u_char		tdq_ridx;		/* Current removal index. */
250e7d50326SJeff Roberson 	struct runq	tdq_realtime;		/* real-time run queue. */
251ae7a6b38SJeff Roberson 	struct runq	tdq_timeshare;		/* timeshare run queue. */
252ae7a6b38SJeff Roberson 	struct runq	tdq_idle;		/* Queue of IDLE threads. */
2538f51ad55SJeff Roberson 	char		tdq_name[TDQ_NAME_LEN];
2548f51ad55SJeff Roberson #ifdef KTR
2558f51ad55SJeff Roberson 	char		tdq_loadname[TDQ_LOADNAME_LEN];
2568f51ad55SJeff Roberson #endif
257ae7a6b38SJeff Roberson } __aligned(64);
25835e6168fSJeff Roberson 
2591690c6c1SJeff Roberson /* Idle thread states and config. */
2601690c6c1SJeff Roberson #define	TDQ_RUNNING	1
2611690c6c1SJeff Roberson #define	TDQ_IDLE	2
2627b8bfa0dSJeff Roberson 
26380f86c9fSJeff Roberson #ifdef SMP
26407095abfSIvan Voras struct cpu_group *cpu_top;		/* CPU topology */
2657b8bfa0dSJeff Roberson 
26662fa74d9SJeff Roberson #define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
26762fa74d9SJeff Roberson #define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
2687b8bfa0dSJeff Roberson 
2697b8bfa0dSJeff Roberson /*
2707b8bfa0dSJeff Roberson  * Run-time tunables.
2717b8bfa0dSJeff Roberson  */
27228994a58SJeff Roberson static int rebalance = 1;
2737fcf154aSJeff Roberson static int balance_interval = 128;	/* Default set in sched_initticks(). */
2747b8bfa0dSJeff Roberson static int affinity;
27528994a58SJeff Roberson static int steal_idle = 1;
27628994a58SJeff Roberson static int steal_thresh = 2;
27797e9382dSDon Lewis static int always_steal = 0;
27897e9382dSDon Lewis static int trysteal_limit = 2;
27980f86c9fSJeff Roberson 
28035e6168fSJeff Roberson /*
281d2ad694cSJeff Roberson  * One thread queue per processor.
28235e6168fSJeff Roberson  */
283ad1e7d28SJulian Elischer static struct tdq	tdq_cpu[MAXCPU];
2847fcf154aSJeff Roberson static struct tdq	*balance_tdq;
2857fcf154aSJeff Roberson static int balance_ticks;
28636acfc65SAlexander Motin static DPCPU_DEFINE(uint32_t, randomval);
287dc03363dSJeff Roberson 
288ad1e7d28SJulian Elischer #define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
289ad1e7d28SJulian Elischer #define	TDQ_CPU(x)	(&tdq_cpu[(x)])
290c47f202bSJeff Roberson #define	TDQ_ID(x)	((int)((x) - tdq_cpu))
29180f86c9fSJeff Roberson #else	/* !SMP */
292ad1e7d28SJulian Elischer static struct tdq	tdq_cpu;
293dc03363dSJeff Roberson 
29436b36916SJeff Roberson #define	TDQ_ID(x)	(0)
295ad1e7d28SJulian Elischer #define	TDQ_SELF()	(&tdq_cpu)
296ad1e7d28SJulian Elischer #define	TDQ_CPU(x)	(&tdq_cpu)
2970a016a05SJeff Roberson #endif
29835e6168fSJeff Roberson 
299ae7a6b38SJeff Roberson #define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
300ae7a6b38SJeff Roberson #define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
301ae7a6b38SJeff Roberson #define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
302ae7a6b38SJeff Roberson #define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
3034ceaf45dSAttilio Rao #define	TDQ_LOCKPTR(t)		((struct mtx *)(&(t)->tdq_lock))
304ae7a6b38SJeff Roberson 
3058460a577SJohn Birrell static void sched_priority(struct thread *);
30621381d1bSJeff Roberson static void sched_thread_priority(struct thread *, u_char);
3078460a577SJohn Birrell static int sched_interact_score(struct thread *);
3088460a577SJohn Birrell static void sched_interact_update(struct thread *);
3098460a577SJohn Birrell static void sched_interact_fork(struct thread *);
3107295465eSAlexander Motin static void sched_pctcpu_update(struct td_sched *, int);
31135e6168fSJeff Roberson 
3125d7ef00cSJeff Roberson /* Operations on per processor queues */
3139727e637SJeff Roberson static struct thread *tdq_choose(struct tdq *);
314ad1e7d28SJulian Elischer static void tdq_setup(struct tdq *);
3159727e637SJeff Roberson static void tdq_load_add(struct tdq *, struct thread *);
3169727e637SJeff Roberson static void tdq_load_rem(struct tdq *, struct thread *);
3179727e637SJeff Roberson static __inline void tdq_runq_add(struct tdq *, struct thread *, int);
3189727e637SJeff Roberson static __inline void tdq_runq_rem(struct tdq *, struct thread *);
319ff256d9cSJeff Roberson static inline int sched_shouldpreempt(int, int, int);
320ad1e7d28SJulian Elischer void tdq_print(int cpu);
321e7d50326SJeff Roberson static void runq_print(struct runq *rq);
322ae7a6b38SJeff Roberson static void tdq_add(struct tdq *, struct thread *, int);
3235d7ef00cSJeff Roberson #ifdef SMP
32497e9382dSDon Lewis static struct thread *tdq_move(struct tdq *, struct tdq *);
325ad1e7d28SJulian Elischer static int tdq_idled(struct tdq *);
32627ee18adSRyan Stone static void tdq_notify(struct tdq *, struct thread *);
3279727e637SJeff Roberson static struct thread *tdq_steal(struct tdq *, int);
3289727e637SJeff Roberson static struct thread *runq_steal(struct runq *, int);
3299727e637SJeff Roberson static int sched_pickcpu(struct thread *, int);
3307fcf154aSJeff Roberson static void sched_balance(void);
33162fa74d9SJeff Roberson static int sched_balance_pair(struct tdq *, struct tdq *);
3329727e637SJeff Roberson static inline struct tdq *sched_setcpu(struct thread *, int, int);
333ae7a6b38SJeff Roberson static inline void thread_unblock_switch(struct thread *, struct mtx *);
334c47f202bSJeff Roberson static struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
33507095abfSIvan Voras static int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
33607095abfSIvan Voras static int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
33707095abfSIvan Voras     struct cpu_group *cg, int indent);
3385d7ef00cSJeff Roberson #endif
3395d7ef00cSJeff Roberson 
340e7d50326SJeff Roberson static void sched_setup(void *dummy);
341237fdd78SRobert Watson SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
342e7d50326SJeff Roberson 
343e7d50326SJeff Roberson static void sched_initticks(void *dummy);
344237fdd78SRobert Watson SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
345237fdd78SRobert Watson     NULL);
346e7d50326SJeff Roberson 
347b3e9e682SRyan Stone SDT_PROVIDER_DEFINE(sched);
348b3e9e682SRyan Stone 
349d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
350b3e9e682SRyan Stone     "struct proc *", "uint8_t");
351d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
352b3e9e682SRyan Stone     "struct proc *", "void *");
353d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
354b3e9e682SRyan Stone     "struct proc *", "void *", "int");
355d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
356b3e9e682SRyan Stone     "struct proc *", "uint8_t", "struct thread *");
357d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
358d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
359b3e9e682SRyan Stone     "struct proc *");
360d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , on__cpu);
361d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , remain__cpu);
362d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
363b3e9e682SRyan Stone     "struct proc *");
364b3e9e682SRyan Stone 
3650567b6ccSWarner Losh /*
366ae7a6b38SJeff Roberson  * Print the threads waiting on a run-queue.
367ae7a6b38SJeff Roberson  */
368e7d50326SJeff Roberson static void
369e7d50326SJeff Roberson runq_print(struct runq *rq)
370e7d50326SJeff Roberson {
371e7d50326SJeff Roberson 	struct rqhead *rqh;
3729727e637SJeff Roberson 	struct thread *td;
373e7d50326SJeff Roberson 	int pri;
374e7d50326SJeff Roberson 	int j;
375e7d50326SJeff Roberson 	int i;
376e7d50326SJeff Roberson 
377e7d50326SJeff Roberson 	for (i = 0; i < RQB_LEN; i++) {
378e7d50326SJeff Roberson 		printf("\t\trunq bits %d 0x%zx\n",
379e7d50326SJeff Roberson 		    i, rq->rq_status.rqb_bits[i]);
380e7d50326SJeff Roberson 		for (j = 0; j < RQB_BPW; j++)
381e7d50326SJeff Roberson 			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
382e7d50326SJeff Roberson 				pri = j + (i << RQB_L2BPW);
383e7d50326SJeff Roberson 				rqh = &rq->rq_queues[pri];
3849727e637SJeff Roberson 				TAILQ_FOREACH(td, rqh, td_runq) {
385e7d50326SJeff Roberson 					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
3869727e637SJeff Roberson 					    td, td->td_name, td->td_priority,
3879727e637SJeff Roberson 					    td->td_rqindex, pri);
388e7d50326SJeff Roberson 				}
389e7d50326SJeff Roberson 			}
390e7d50326SJeff Roberson 	}
391e7d50326SJeff Roberson }
392e7d50326SJeff Roberson 
393ae7a6b38SJeff Roberson /*
394ae7a6b38SJeff Roberson  * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
395ae7a6b38SJeff Roberson  */
39615dc847eSJeff Roberson void
397ad1e7d28SJulian Elischer tdq_print(int cpu)
39815dc847eSJeff Roberson {
399ad1e7d28SJulian Elischer 	struct tdq *tdq;
40015dc847eSJeff Roberson 
401ad1e7d28SJulian Elischer 	tdq = TDQ_CPU(cpu);
40215dc847eSJeff Roberson 
403c47f202bSJeff Roberson 	printf("tdq %d:\n", TDQ_ID(tdq));
40462fa74d9SJeff Roberson 	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
40562fa74d9SJeff Roberson 	printf("\tLock name:      %s\n", tdq->tdq_name);
406d2ad694cSJeff Roberson 	printf("\tload:           %d\n", tdq->tdq_load);
4071690c6c1SJeff Roberson 	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
4081690c6c1SJeff Roberson 	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
409e7d50326SJeff Roberson 	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
4103f872f85SJeff Roberson 	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
4111690c6c1SJeff Roberson 	printf("\tload transferable: %d\n", tdq->tdq_transferable);
4121690c6c1SJeff Roberson 	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
413e7d50326SJeff Roberson 	printf("\trealtime runq:\n");
414e7d50326SJeff Roberson 	runq_print(&tdq->tdq_realtime);
415e7d50326SJeff Roberson 	printf("\ttimeshare runq:\n");
416e7d50326SJeff Roberson 	runq_print(&tdq->tdq_timeshare);
417e7d50326SJeff Roberson 	printf("\tidle runq:\n");
418e7d50326SJeff Roberson 	runq_print(&tdq->tdq_idle);
41915dc847eSJeff Roberson }
42015dc847eSJeff Roberson 
421ff256d9cSJeff Roberson static inline int
422ff256d9cSJeff Roberson sched_shouldpreempt(int pri, int cpri, int remote)
423ff256d9cSJeff Roberson {
424ff256d9cSJeff Roberson 	/*
425ff256d9cSJeff Roberson 	 * If the new priority is not better than the current priority there is
426ff256d9cSJeff Roberson 	 * nothing to do.
427ff256d9cSJeff Roberson 	 */
428ff256d9cSJeff Roberson 	if (pri >= cpri)
429ff256d9cSJeff Roberson 		return (0);
430ff256d9cSJeff Roberson 	/*
431ff256d9cSJeff Roberson 	 * Always preempt idle.
432ff256d9cSJeff Roberson 	 */
433ff256d9cSJeff Roberson 	if (cpri >= PRI_MIN_IDLE)
434ff256d9cSJeff Roberson 		return (1);
435ff256d9cSJeff Roberson 	/*
436ff256d9cSJeff Roberson 	 * If preemption is disabled don't preempt others.
437ff256d9cSJeff Roberson 	 */
438ff256d9cSJeff Roberson 	if (preempt_thresh == 0)
439ff256d9cSJeff Roberson 		return (0);
440ff256d9cSJeff Roberson 	/*
441ff256d9cSJeff Roberson 	 * Preempt if we exceed the threshold.
442ff256d9cSJeff Roberson 	 */
443ff256d9cSJeff Roberson 	if (pri <= preempt_thresh)
444ff256d9cSJeff Roberson 		return (1);
445ff256d9cSJeff Roberson 	/*
44612d56c0fSJohn Baldwin 	 * If we're interactive or better and there is non-interactive
44712d56c0fSJohn Baldwin 	 * or worse running preempt only remote processors.
448ff256d9cSJeff Roberson 	 */
44912d56c0fSJohn Baldwin 	if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
450ff256d9cSJeff Roberson 		return (1);
451ff256d9cSJeff Roberson 	return (0);
452ff256d9cSJeff Roberson }
453ff256d9cSJeff Roberson 
454ae7a6b38SJeff Roberson /*
455ae7a6b38SJeff Roberson  * Add a thread to the actual run-queue.  Keeps transferable counts up to
456ae7a6b38SJeff Roberson  * date with what is actually on the run-queue.  Selects the correct
457ae7a6b38SJeff Roberson  * queue position for timeshare threads.
458ae7a6b38SJeff Roberson  */
459155b9987SJeff Roberson static __inline void
4609727e637SJeff Roberson tdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
461155b9987SJeff Roberson {
4629727e637SJeff Roberson 	struct td_sched *ts;
463c143ac21SJeff Roberson 	u_char pri;
464c143ac21SJeff Roberson 
465ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
4669727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
46773daf66fSJeff Roberson 
4689727e637SJeff Roberson 	pri = td->td_priority;
46993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
4709727e637SJeff Roberson 	TD_SET_RUNQ(td);
4719727e637SJeff Roberson 	if (THREAD_CAN_MIGRATE(td)) {
472d2ad694cSJeff Roberson 		tdq->tdq_transferable++;
473ad1e7d28SJulian Elischer 		ts->ts_flags |= TSF_XFERABLE;
47480f86c9fSJeff Roberson 	}
47512d56c0fSJohn Baldwin 	if (pri < PRI_MIN_BATCH) {
476c143ac21SJeff Roberson 		ts->ts_runq = &tdq->tdq_realtime;
47712d56c0fSJohn Baldwin 	} else if (pri <= PRI_MAX_BATCH) {
478c143ac21SJeff Roberson 		ts->ts_runq = &tdq->tdq_timeshare;
47912d56c0fSJohn Baldwin 		KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
480e7d50326SJeff Roberson 			("Invalid priority %d on timeshare runq", pri));
481e7d50326SJeff Roberson 		/*
482e7d50326SJeff Roberson 		 * This queue contains only priorities between MIN and MAX
483e7d50326SJeff Roberson 		 * realtime.  Use the whole queue to represent these values.
484e7d50326SJeff Roberson 		 */
485c47f202bSJeff Roberson 		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
48616705791SAndriy Gapon 			pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
487e7d50326SJeff Roberson 			pri = (pri + tdq->tdq_idx) % RQ_NQS;
4883f872f85SJeff Roberson 			/*
4893f872f85SJeff Roberson 			 * This effectively shortens the queue by one so we
4903f872f85SJeff Roberson 			 * can have a one slot difference between idx and
4913f872f85SJeff Roberson 			 * ridx while we wait for threads to drain.
4923f872f85SJeff Roberson 			 */
4933f872f85SJeff Roberson 			if (tdq->tdq_ridx != tdq->tdq_idx &&
4943f872f85SJeff Roberson 			    pri == tdq->tdq_ridx)
4954499aff6SJeff Roberson 				pri = (unsigned char)(pri - 1) % RQ_NQS;
496e7d50326SJeff Roberson 		} else
4973f872f85SJeff Roberson 			pri = tdq->tdq_ridx;
4989727e637SJeff Roberson 		runq_add_pri(ts->ts_runq, td, pri, flags);
499c143ac21SJeff Roberson 		return;
500e7d50326SJeff Roberson 	} else
50173daf66fSJeff Roberson 		ts->ts_runq = &tdq->tdq_idle;
5029727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
50373daf66fSJeff Roberson }
50473daf66fSJeff Roberson 
50573daf66fSJeff Roberson /*
506ae7a6b38SJeff Roberson  * Remove a thread from a run-queue.  This typically happens when a thread
507ae7a6b38SJeff Roberson  * is selected to run.  Running threads are not on the queue and the
508ae7a6b38SJeff Roberson  * transferable count does not reflect them.
509ae7a6b38SJeff Roberson  */
510155b9987SJeff Roberson static __inline void
5119727e637SJeff Roberson tdq_runq_rem(struct tdq *tdq, struct thread *td)
512155b9987SJeff Roberson {
5139727e637SJeff Roberson 	struct td_sched *ts;
5149727e637SJeff Roberson 
51593ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
516ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
517ae7a6b38SJeff Roberson 	KASSERT(ts->ts_runq != NULL,
5189727e637SJeff Roberson 	    ("tdq_runq_remove: thread %p null ts_runq", td));
519ad1e7d28SJulian Elischer 	if (ts->ts_flags & TSF_XFERABLE) {
520d2ad694cSJeff Roberson 		tdq->tdq_transferable--;
521ad1e7d28SJulian Elischer 		ts->ts_flags &= ~TSF_XFERABLE;
52280f86c9fSJeff Roberson 	}
5233f872f85SJeff Roberson 	if (ts->ts_runq == &tdq->tdq_timeshare) {
5243f872f85SJeff Roberson 		if (tdq->tdq_idx != tdq->tdq_ridx)
5259727e637SJeff Roberson 			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
526e7d50326SJeff Roberson 		else
5279727e637SJeff Roberson 			runq_remove_idx(ts->ts_runq, td, NULL);
5283f872f85SJeff Roberson 	} else
5299727e637SJeff Roberson 		runq_remove(ts->ts_runq, td);
530155b9987SJeff Roberson }
531155b9987SJeff Roberson 
532ae7a6b38SJeff Roberson /*
533ae7a6b38SJeff Roberson  * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
534ae7a6b38SJeff Roberson  * for this thread to the referenced thread queue.
535ae7a6b38SJeff Roberson  */
536a8949de2SJeff Roberson static void
5379727e637SJeff Roberson tdq_load_add(struct tdq *tdq, struct thread *td)
5385d7ef00cSJeff Roberson {
539ae7a6b38SJeff Roberson 
540ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
5419727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
54203d17db7SJeff Roberson 
543d2ad694cSJeff Roberson 	tdq->tdq_load++;
5441b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
545d2ad694cSJeff Roberson 		tdq->tdq_sysload++;
5468f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
547d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
5485d7ef00cSJeff Roberson }
54915dc847eSJeff Roberson 
550ae7a6b38SJeff Roberson /*
551ae7a6b38SJeff Roberson  * Remove the load from a thread that is transitioning to a sleep state or
552ae7a6b38SJeff Roberson  * exiting.
553ae7a6b38SJeff Roberson  */
554a8949de2SJeff Roberson static void
5559727e637SJeff Roberson tdq_load_rem(struct tdq *tdq, struct thread *td)
5565d7ef00cSJeff Roberson {
557ae7a6b38SJeff Roberson 
5589727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
559ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
560ae7a6b38SJeff Roberson 	KASSERT(tdq->tdq_load != 0,
561c47f202bSJeff Roberson 	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
56203d17db7SJeff Roberson 
563d2ad694cSJeff Roberson 	tdq->tdq_load--;
5641b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
56503d17db7SJeff Roberson 		tdq->tdq_sysload--;
5668f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
567d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
56815dc847eSJeff Roberson }
56915dc847eSJeff Roberson 
570356500a3SJeff Roberson /*
5715e5c3873SJeff Roberson  * Bound timeshare latency by decreasing slice size as load increases.  We
5725e5c3873SJeff Roberson  * consider the maximum latency as the sum of the threads waiting to run
5735e5c3873SJeff Roberson  * aside from curthread and target no more than sched_slice latency but
5745e5c3873SJeff Roberson  * no less than sched_slice_min runtime.
5755e5c3873SJeff Roberson  */
5765e5c3873SJeff Roberson static inline int
5775e5c3873SJeff Roberson tdq_slice(struct tdq *tdq)
5785e5c3873SJeff Roberson {
5795e5c3873SJeff Roberson 	int load;
5805e5c3873SJeff Roberson 
5815e5c3873SJeff Roberson 	/*
5825e5c3873SJeff Roberson 	 * It is safe to use sys_load here because this is called from
5835e5c3873SJeff Roberson 	 * contexts where timeshare threads are running and so there
5845e5c3873SJeff Roberson 	 * cannot be higher priority load in the system.
5855e5c3873SJeff Roberson 	 */
5865e5c3873SJeff Roberson 	load = tdq->tdq_sysload - 1;
5875e5c3873SJeff Roberson 	if (load >= SCHED_SLICE_MIN_DIVISOR)
5885e5c3873SJeff Roberson 		return (sched_slice_min);
5895e5c3873SJeff Roberson 	if (load <= 1)
5905e5c3873SJeff Roberson 		return (sched_slice);
5915e5c3873SJeff Roberson 	return (sched_slice / load);
5925e5c3873SJeff Roberson }
5935e5c3873SJeff Roberson 
5945e5c3873SJeff Roberson /*
59562fa74d9SJeff Roberson  * Set lowpri to its exact value by searching the run-queue and
59662fa74d9SJeff Roberson  * evaluating curthread.  curthread may be passed as an optimization.
597356500a3SJeff Roberson  */
59822bf7d9aSJeff Roberson static void
59962fa74d9SJeff Roberson tdq_setlowpri(struct tdq *tdq, struct thread *ctd)
60062fa74d9SJeff Roberson {
60162fa74d9SJeff Roberson 	struct thread *td;
60262fa74d9SJeff Roberson 
60362fa74d9SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
60462fa74d9SJeff Roberson 	if (ctd == NULL)
60562fa74d9SJeff Roberson 		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
6069727e637SJeff Roberson 	td = tdq_choose(tdq);
6079727e637SJeff Roberson 	if (td == NULL || td->td_priority > ctd->td_priority)
60862fa74d9SJeff Roberson 		tdq->tdq_lowpri = ctd->td_priority;
60962fa74d9SJeff Roberson 	else
61062fa74d9SJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
61162fa74d9SJeff Roberson }
61262fa74d9SJeff Roberson 
61362fa74d9SJeff Roberson #ifdef SMP
6149129dd59SPedro F. Giffuni /*
6159129dd59SPedro F. Giffuni  * We need some randomness. Implement a classic Linear Congruential
6169129dd59SPedro F. Giffuni  * Generator X_{n+1}=(aX_n+c) mod m. These values are optimized for
6179129dd59SPedro F. Giffuni  * m = 2^32, a = 69069 and c = 5. We only return the upper 16 bits
6189129dd59SPedro F. Giffuni  * of the random state (in the low bits of our answer) to keep
6199129dd59SPedro F. Giffuni  * the maximum randomness.
6209129dd59SPedro F. Giffuni  */
6219129dd59SPedro F. Giffuni static uint32_t
6229129dd59SPedro F. Giffuni sched_random(void)
6239129dd59SPedro F. Giffuni {
6249129dd59SPedro F. Giffuni 	uint32_t *rndptr;
6259129dd59SPedro F. Giffuni 
6269129dd59SPedro F. Giffuni 	rndptr = DPCPU_PTR(randomval);
6279129dd59SPedro F. Giffuni 	*rndptr = *rndptr * 69069 + 5;
6289129dd59SPedro F. Giffuni 
6299129dd59SPedro F. Giffuni 	return (*rndptr >> 16);
6309129dd59SPedro F. Giffuni }
6319129dd59SPedro F. Giffuni 
63262fa74d9SJeff Roberson struct cpu_search {
633c76ee827SJeff Roberson 	cpuset_t cs_mask;
63436acfc65SAlexander Motin 	u_int	cs_prefer;
63536acfc65SAlexander Motin 	int	cs_pri;		/* Min priority for low. */
63636acfc65SAlexander Motin 	int	cs_limit;	/* Max load for low, min load for high. */
63736acfc65SAlexander Motin 	int	cs_cpu;
63836acfc65SAlexander Motin 	int	cs_load;
63962fa74d9SJeff Roberson };
64062fa74d9SJeff Roberson 
64162fa74d9SJeff Roberson #define	CPU_SEARCH_LOWEST	0x1
64262fa74d9SJeff Roberson #define	CPU_SEARCH_HIGHEST	0x2
64362fa74d9SJeff Roberson #define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
64462fa74d9SJeff Roberson 
645c76ee827SJeff Roberson #define	CPUSET_FOREACH(cpu, mask)				\
646c76ee827SJeff Roberson 	for ((cpu) = 0; (cpu) <= mp_maxid; (cpu)++)		\
64771a19bdcSAttilio Rao 		if (CPU_ISSET(cpu, &mask))
64862fa74d9SJeff Roberson 
6492499a5ccSKonstantin Belousov static __always_inline int cpu_search(const struct cpu_group *cg,
6502499a5ccSKonstantin Belousov     struct cpu_search *low, struct cpu_search *high, const int match);
6512499a5ccSKonstantin Belousov int __noinline cpu_search_lowest(const struct cpu_group *cg,
6522499a5ccSKonstantin Belousov     struct cpu_search *low);
6532499a5ccSKonstantin Belousov int __noinline cpu_search_highest(const struct cpu_group *cg,
65462fa74d9SJeff Roberson     struct cpu_search *high);
6552499a5ccSKonstantin Belousov int __noinline cpu_search_both(const struct cpu_group *cg,
6562499a5ccSKonstantin Belousov     struct cpu_search *low, struct cpu_search *high);
65762fa74d9SJeff Roberson 
65862fa74d9SJeff Roberson /*
65962fa74d9SJeff Roberson  * Search the tree of cpu_groups for the lowest or highest loaded cpu
66062fa74d9SJeff Roberson  * according to the match argument.  This routine actually compares the
66162fa74d9SJeff Roberson  * load on all paths through the tree and finds the least loaded cpu on
66262fa74d9SJeff Roberson  * the least loaded path, which may differ from the least loaded cpu in
663db4fcadfSConrad Meyer  * the system.  This balances work among caches and buses.
66462fa74d9SJeff Roberson  *
66562fa74d9SJeff Roberson  * This inline is instantiated in three forms below using constants for the
66662fa74d9SJeff Roberson  * match argument.  It is reduced to the minimum set for each case.  It is
66762fa74d9SJeff Roberson  * also recursive to the depth of the tree.
66862fa74d9SJeff Roberson  */
6692499a5ccSKonstantin Belousov static __always_inline int
67036acfc65SAlexander Motin cpu_search(const struct cpu_group *cg, struct cpu_search *low,
67162fa74d9SJeff Roberson     struct cpu_search *high, const int match)
67262fa74d9SJeff Roberson {
67362fa74d9SJeff Roberson 	struct cpu_search lgroup;
67462fa74d9SJeff Roberson 	struct cpu_search hgroup;
67536acfc65SAlexander Motin 	cpuset_t cpumask;
67662fa74d9SJeff Roberson 	struct cpu_group *child;
67736acfc65SAlexander Motin 	struct tdq *tdq;
6780567b6ccSWarner Losh 	int cpu, i, hload, lload, load, total, rnd;
67962fa74d9SJeff Roberson 
68036acfc65SAlexander Motin 	total = 0;
68136acfc65SAlexander Motin 	cpumask = cg->cg_mask;
68262fa74d9SJeff Roberson 	if (match & CPU_SEARCH_LOWEST) {
68336acfc65SAlexander Motin 		lload = INT_MAX;
68462fa74d9SJeff Roberson 		lgroup = *low;
68562fa74d9SJeff Roberson 	}
68662fa74d9SJeff Roberson 	if (match & CPU_SEARCH_HIGHEST) {
68770801abeSAlexander Motin 		hload = INT_MIN;
68862fa74d9SJeff Roberson 		hgroup = *high;
68962fa74d9SJeff Roberson 	}
69036acfc65SAlexander Motin 
69136acfc65SAlexander Motin 	/* Iterate through the child CPU groups and then remaining CPUs. */
69258909b74SAlexander Motin 	for (i = cg->cg_children, cpu = mp_maxid; ; ) {
69370801abeSAlexander Motin 		if (i == 0) {
69458909b74SAlexander Motin #ifdef HAVE_INLINE_FFSL
69558909b74SAlexander Motin 			cpu = CPU_FFS(&cpumask) - 1;
69658909b74SAlexander Motin #else
69770801abeSAlexander Motin 			while (cpu >= 0 && !CPU_ISSET(cpu, &cpumask))
69870801abeSAlexander Motin 				cpu--;
69958909b74SAlexander Motin #endif
70070801abeSAlexander Motin 			if (cpu < 0)
70136acfc65SAlexander Motin 				break;
70236acfc65SAlexander Motin 			child = NULL;
70336acfc65SAlexander Motin 		} else
70470801abeSAlexander Motin 			child = &cg->cg_child[i - 1];
70536acfc65SAlexander Motin 
70670801abeSAlexander Motin 		if (match & CPU_SEARCH_LOWEST)
70770801abeSAlexander Motin 			lgroup.cs_cpu = -1;
70870801abeSAlexander Motin 		if (match & CPU_SEARCH_HIGHEST)
70970801abeSAlexander Motin 			hgroup.cs_cpu = -1;
71036acfc65SAlexander Motin 		if (child) {			/* Handle child CPU group. */
71136acfc65SAlexander Motin 			CPU_NAND(&cpumask, &child->cg_mask);
71262fa74d9SJeff Roberson 			switch (match) {
71362fa74d9SJeff Roberson 			case CPU_SEARCH_LOWEST:
71462fa74d9SJeff Roberson 				load = cpu_search_lowest(child, &lgroup);
71562fa74d9SJeff Roberson 				break;
71662fa74d9SJeff Roberson 			case CPU_SEARCH_HIGHEST:
71762fa74d9SJeff Roberson 				load = cpu_search_highest(child, &hgroup);
71862fa74d9SJeff Roberson 				break;
71962fa74d9SJeff Roberson 			case CPU_SEARCH_BOTH:
72062fa74d9SJeff Roberson 				load = cpu_search_both(child, &lgroup, &hgroup);
72162fa74d9SJeff Roberson 				break;
72262fa74d9SJeff Roberson 			}
72336acfc65SAlexander Motin 		} else {			/* Handle child CPU. */
72458909b74SAlexander Motin 			CPU_CLR(cpu, &cpumask);
72536acfc65SAlexander Motin 			tdq = TDQ_CPU(cpu);
72636acfc65SAlexander Motin 			load = tdq->tdq_load * 256;
727b250ad34SWarner Losh 			rnd = sched_random() % 32;
72836acfc65SAlexander Motin 			if (match & CPU_SEARCH_LOWEST) {
72936acfc65SAlexander Motin 				if (cpu == low->cs_prefer)
73036acfc65SAlexander Motin 					load -= 64;
73136acfc65SAlexander Motin 				/* If that CPU is allowed and get data. */
73270801abeSAlexander Motin 				if (tdq->tdq_lowpri > lgroup.cs_pri &&
73370801abeSAlexander Motin 				    tdq->tdq_load <= lgroup.cs_limit &&
73470801abeSAlexander Motin 				    CPU_ISSET(cpu, &lgroup.cs_mask)) {
73536acfc65SAlexander Motin 					lgroup.cs_cpu = cpu;
73636acfc65SAlexander Motin 					lgroup.cs_load = load - rnd;
73736acfc65SAlexander Motin 				}
73862fa74d9SJeff Roberson 			}
73962fa74d9SJeff Roberson 			if (match & CPU_SEARCH_HIGHEST)
74070801abeSAlexander Motin 				if (tdq->tdq_load >= hgroup.cs_limit &&
74170801abeSAlexander Motin 				    tdq->tdq_transferable &&
74270801abeSAlexander Motin 				    CPU_ISSET(cpu, &hgroup.cs_mask)) {
74336acfc65SAlexander Motin 					hgroup.cs_cpu = cpu;
74436acfc65SAlexander Motin 					hgroup.cs_load = load - rnd;
74562fa74d9SJeff Roberson 				}
74662fa74d9SJeff Roberson 		}
74736acfc65SAlexander Motin 		total += load;
74862fa74d9SJeff Roberson 
74936acfc65SAlexander Motin 		/* We have info about child item. Compare it. */
75036acfc65SAlexander Motin 		if (match & CPU_SEARCH_LOWEST) {
75170801abeSAlexander Motin 			if (lgroup.cs_cpu >= 0 &&
7526022f0bcSAlexander Motin 			    (load < lload ||
7536022f0bcSAlexander Motin 			     (load == lload && lgroup.cs_load < low->cs_load))) {
75436acfc65SAlexander Motin 				lload = load;
75536acfc65SAlexander Motin 				low->cs_cpu = lgroup.cs_cpu;
75636acfc65SAlexander Motin 				low->cs_load = lgroup.cs_load;
75736acfc65SAlexander Motin 			}
75836acfc65SAlexander Motin 		}
75936acfc65SAlexander Motin 		if (match & CPU_SEARCH_HIGHEST)
76070801abeSAlexander Motin 			if (hgroup.cs_cpu >= 0 &&
7616022f0bcSAlexander Motin 			    (load > hload ||
7626022f0bcSAlexander Motin 			     (load == hload && hgroup.cs_load > high->cs_load))) {
76336acfc65SAlexander Motin 				hload = load;
76436acfc65SAlexander Motin 				high->cs_cpu = hgroup.cs_cpu;
76536acfc65SAlexander Motin 				high->cs_load = hgroup.cs_load;
76636acfc65SAlexander Motin 			}
76770801abeSAlexander Motin 		if (child) {
76870801abeSAlexander Motin 			i--;
76970801abeSAlexander Motin 			if (i == 0 && CPU_EMPTY(&cpumask))
77070801abeSAlexander Motin 				break;
77158909b74SAlexander Motin 		}
77258909b74SAlexander Motin #ifndef HAVE_INLINE_FFSL
77358909b74SAlexander Motin 		else
77470801abeSAlexander Motin 			cpu--;
77558909b74SAlexander Motin #endif
77662fa74d9SJeff Roberson 	}
77762fa74d9SJeff Roberson 	return (total);
77862fa74d9SJeff Roberson }
77962fa74d9SJeff Roberson 
78062fa74d9SJeff Roberson /*
78162fa74d9SJeff Roberson  * cpu_search instantiations must pass constants to maintain the inline
78262fa74d9SJeff Roberson  * optimization.
78362fa74d9SJeff Roberson  */
78462fa74d9SJeff Roberson int
78536acfc65SAlexander Motin cpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low)
78662fa74d9SJeff Roberson {
78762fa74d9SJeff Roberson 	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
78862fa74d9SJeff Roberson }
78962fa74d9SJeff Roberson 
79062fa74d9SJeff Roberson int
79136acfc65SAlexander Motin cpu_search_highest(const struct cpu_group *cg, struct cpu_search *high)
79262fa74d9SJeff Roberson {
79362fa74d9SJeff Roberson 	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
79462fa74d9SJeff Roberson }
79562fa74d9SJeff Roberson 
79662fa74d9SJeff Roberson int
79736acfc65SAlexander Motin cpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
79862fa74d9SJeff Roberson     struct cpu_search *high)
79962fa74d9SJeff Roberson {
80062fa74d9SJeff Roberson 	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
80162fa74d9SJeff Roberson }
80262fa74d9SJeff Roberson 
80362fa74d9SJeff Roberson /*
80462fa74d9SJeff Roberson  * Find the cpu with the least load via the least loaded path that has a
80562fa74d9SJeff Roberson  * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
80662fa74d9SJeff Roberson  * acceptable.
80762fa74d9SJeff Roberson  */
80862fa74d9SJeff Roberson static inline int
80936acfc65SAlexander Motin sched_lowest(const struct cpu_group *cg, cpuset_t mask, int pri, int maxload,
81036acfc65SAlexander Motin     int prefer)
81162fa74d9SJeff Roberson {
81262fa74d9SJeff Roberson 	struct cpu_search low;
81362fa74d9SJeff Roberson 
81462fa74d9SJeff Roberson 	low.cs_cpu = -1;
81536acfc65SAlexander Motin 	low.cs_prefer = prefer;
81662fa74d9SJeff Roberson 	low.cs_mask = mask;
81736acfc65SAlexander Motin 	low.cs_pri = pri;
81836acfc65SAlexander Motin 	low.cs_limit = maxload;
81962fa74d9SJeff Roberson 	cpu_search_lowest(cg, &low);
82062fa74d9SJeff Roberson 	return low.cs_cpu;
82162fa74d9SJeff Roberson }
82262fa74d9SJeff Roberson 
82362fa74d9SJeff Roberson /*
82462fa74d9SJeff Roberson  * Find the cpu with the highest load via the highest loaded path.
82562fa74d9SJeff Roberson  */
82662fa74d9SJeff Roberson static inline int
82736acfc65SAlexander Motin sched_highest(const struct cpu_group *cg, cpuset_t mask, int minload)
82862fa74d9SJeff Roberson {
82962fa74d9SJeff Roberson 	struct cpu_search high;
83062fa74d9SJeff Roberson 
83162fa74d9SJeff Roberson 	high.cs_cpu = -1;
83262fa74d9SJeff Roberson 	high.cs_mask = mask;
83362fa74d9SJeff Roberson 	high.cs_limit = minload;
83462fa74d9SJeff Roberson 	cpu_search_highest(cg, &high);
83562fa74d9SJeff Roberson 	return high.cs_cpu;
83662fa74d9SJeff Roberson }
83762fa74d9SJeff Roberson 
83862fa74d9SJeff Roberson static void
83962fa74d9SJeff Roberson sched_balance_group(struct cpu_group *cg)
84062fa74d9SJeff Roberson {
84136acfc65SAlexander Motin 	cpuset_t hmask, lmask;
84236acfc65SAlexander Motin 	int high, low, anylow;
84362fa74d9SJeff Roberson 
84436acfc65SAlexander Motin 	CPU_FILL(&hmask);
84562fa74d9SJeff Roberson 	for (;;) {
84697e9382dSDon Lewis 		high = sched_highest(cg, hmask, 2);
84736acfc65SAlexander Motin 		/* Stop if there is no more CPU with transferrable threads. */
84836acfc65SAlexander Motin 		if (high == -1)
84962fa74d9SJeff Roberson 			break;
85036acfc65SAlexander Motin 		CPU_CLR(high, &hmask);
85136acfc65SAlexander Motin 		CPU_COPY(&hmask, &lmask);
85236acfc65SAlexander Motin 		/* Stop if there is no more CPU left for low. */
85336acfc65SAlexander Motin 		if (CPU_EMPTY(&lmask))
85462fa74d9SJeff Roberson 			break;
85536acfc65SAlexander Motin 		anylow = 1;
85636acfc65SAlexander Motin nextlow:
85736acfc65SAlexander Motin 		low = sched_lowest(cg, lmask, -1,
85836acfc65SAlexander Motin 		    TDQ_CPU(high)->tdq_load - 1, high);
85936acfc65SAlexander Motin 		/* Stop if we looked well and found no less loaded CPU. */
86036acfc65SAlexander Motin 		if (anylow && low == -1)
86136acfc65SAlexander Motin 			break;
86236acfc65SAlexander Motin 		/* Go to next high if we found no less loaded CPU. */
86336acfc65SAlexander Motin 		if (low == -1)
86436acfc65SAlexander Motin 			continue;
86536acfc65SAlexander Motin 		/* Transfer thread from high to low. */
86636acfc65SAlexander Motin 		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low))) {
86736acfc65SAlexander Motin 			/* CPU that got thread can no longer be a donor. */
86836acfc65SAlexander Motin 			CPU_CLR(low, &hmask);
86936acfc65SAlexander Motin 		} else {
87062fa74d9SJeff Roberson 			/*
87136acfc65SAlexander Motin 			 * If failed, then there is no threads on high
87236acfc65SAlexander Motin 			 * that can run on this low. Drop low from low
87336acfc65SAlexander Motin 			 * mask and look for different one.
87462fa74d9SJeff Roberson 			 */
87536acfc65SAlexander Motin 			CPU_CLR(low, &lmask);
87636acfc65SAlexander Motin 			anylow = 0;
87736acfc65SAlexander Motin 			goto nextlow;
87862fa74d9SJeff Roberson 		}
87936acfc65SAlexander Motin 	}
88062fa74d9SJeff Roberson }
88162fa74d9SJeff Roberson 
88262fa74d9SJeff Roberson static void
88362375ca8SEd Schouten sched_balance(void)
884356500a3SJeff Roberson {
8857fcf154aSJeff Roberson 	struct tdq *tdq;
886356500a3SJeff Roberson 
887ae7a6b38SJeff Roberson 	if (smp_started == 0 || rebalance == 0)
888598b368dSJeff Roberson 		return;
8890567b6ccSWarner Losh 
8900567b6ccSWarner Losh 	balance_ticks = max(balance_interval / 2, 1) +
891b250ad34SWarner Losh 	    (sched_random() % balance_interval);
8927fcf154aSJeff Roberson 	tdq = TDQ_SELF();
8937fcf154aSJeff Roberson 	TDQ_UNLOCK(tdq);
89462fa74d9SJeff Roberson 	sched_balance_group(cpu_top);
8957fcf154aSJeff Roberson 	TDQ_LOCK(tdq);
896cac77d04SJeff Roberson }
89786f8ae96SJeff Roberson 
898ae7a6b38SJeff Roberson /*
899ae7a6b38SJeff Roberson  * Lock two thread queues using their address to maintain lock order.
900ae7a6b38SJeff Roberson  */
901ae7a6b38SJeff Roberson static void
902ae7a6b38SJeff Roberson tdq_lock_pair(struct tdq *one, struct tdq *two)
903ae7a6b38SJeff Roberson {
904ae7a6b38SJeff Roberson 	if (one < two) {
905ae7a6b38SJeff Roberson 		TDQ_LOCK(one);
906ae7a6b38SJeff Roberson 		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
907ae7a6b38SJeff Roberson 	} else {
908ae7a6b38SJeff Roberson 		TDQ_LOCK(two);
909ae7a6b38SJeff Roberson 		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
910ae7a6b38SJeff Roberson 	}
911ae7a6b38SJeff Roberson }
912ae7a6b38SJeff Roberson 
913ae7a6b38SJeff Roberson /*
9147fcf154aSJeff Roberson  * Unlock two thread queues.  Order is not important here.
9157fcf154aSJeff Roberson  */
9167fcf154aSJeff Roberson static void
9177fcf154aSJeff Roberson tdq_unlock_pair(struct tdq *one, struct tdq *two)
9187fcf154aSJeff Roberson {
9197fcf154aSJeff Roberson 	TDQ_UNLOCK(one);
9207fcf154aSJeff Roberson 	TDQ_UNLOCK(two);
9217fcf154aSJeff Roberson }
9227fcf154aSJeff Roberson 
9237fcf154aSJeff Roberson /*
924ae7a6b38SJeff Roberson  * Transfer load between two imbalanced thread queues.
925ae7a6b38SJeff Roberson  */
92662fa74d9SJeff Roberson static int
927ad1e7d28SJulian Elischer sched_balance_pair(struct tdq *high, struct tdq *low)
928cac77d04SJeff Roberson {
92997e9382dSDon Lewis 	struct thread *td;
930880bf8b9SMarius Strobl 	int cpu;
931cac77d04SJeff Roberson 
932ae7a6b38SJeff Roberson 	tdq_lock_pair(high, low);
93397e9382dSDon Lewis 	td = NULL;
934155b9987SJeff Roberson 	/*
93597e9382dSDon Lewis 	 * Transfer a thread from high to low.
936155b9987SJeff Roberson 	 */
93736acfc65SAlexander Motin 	if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load &&
93897e9382dSDon Lewis 	    (td = tdq_move(high, low)) != NULL) {
939a5423ea3SJeff Roberson 		/*
94097e9382dSDon Lewis 		 * In case the target isn't the current cpu notify it of the
94197e9382dSDon Lewis 		 * new load, possibly sending an IPI to force it to reschedule.
942a5423ea3SJeff Roberson 		 */
943880bf8b9SMarius Strobl 		cpu = TDQ_ID(low);
944880bf8b9SMarius Strobl 		if (cpu != PCPU_GET(cpuid))
94597e9382dSDon Lewis 			tdq_notify(low, td);
946ae7a6b38SJeff Roberson 	}
9477fcf154aSJeff Roberson 	tdq_unlock_pair(high, low);
94897e9382dSDon Lewis 	return (td != NULL);
949356500a3SJeff Roberson }
950356500a3SJeff Roberson 
951ae7a6b38SJeff Roberson /*
952ae7a6b38SJeff Roberson  * Move a thread from one thread queue to another.
953ae7a6b38SJeff Roberson  */
95497e9382dSDon Lewis static struct thread *
955ae7a6b38SJeff Roberson tdq_move(struct tdq *from, struct tdq *to)
956356500a3SJeff Roberson {
957ad1e7d28SJulian Elischer 	struct td_sched *ts;
958ae7a6b38SJeff Roberson 	struct thread *td;
959ae7a6b38SJeff Roberson 	struct tdq *tdq;
960ae7a6b38SJeff Roberson 	int cpu;
961356500a3SJeff Roberson 
9627fcf154aSJeff Roberson 	TDQ_LOCK_ASSERT(from, MA_OWNED);
9637fcf154aSJeff Roberson 	TDQ_LOCK_ASSERT(to, MA_OWNED);
9647fcf154aSJeff Roberson 
965ad1e7d28SJulian Elischer 	tdq = from;
966ae7a6b38SJeff Roberson 	cpu = TDQ_ID(to);
9679727e637SJeff Roberson 	td = tdq_steal(tdq, cpu);
9689727e637SJeff Roberson 	if (td == NULL)
96997e9382dSDon Lewis 		return (NULL);
97093ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
971ae7a6b38SJeff Roberson 	/*
972ae7a6b38SJeff Roberson 	 * Although the run queue is locked the thread may be blocked.  Lock
9737fcf154aSJeff Roberson 	 * it to clear this and acquire the run-queue lock.
974ae7a6b38SJeff Roberson 	 */
975ae7a6b38SJeff Roberson 	thread_lock(td);
9767fcf154aSJeff Roberson 	/* Drop recursive lock on from acquired via thread_lock(). */
977ae7a6b38SJeff Roberson 	TDQ_UNLOCK(from);
978ae7a6b38SJeff Roberson 	sched_rem(td);
9797b8bfa0dSJeff Roberson 	ts->ts_cpu = cpu;
980ae7a6b38SJeff Roberson 	td->td_lock = TDQ_LOCKPTR(to);
981ae7a6b38SJeff Roberson 	tdq_add(to, td, SRQ_YIELDING);
98297e9382dSDon Lewis 	return (td);
983356500a3SJeff Roberson }
98422bf7d9aSJeff Roberson 
985ae7a6b38SJeff Roberson /*
986ae7a6b38SJeff Roberson  * This tdq has idled.  Try to steal a thread from another cpu and switch
987ae7a6b38SJeff Roberson  * to it.
988ae7a6b38SJeff Roberson  */
98980f86c9fSJeff Roberson static int
990ad1e7d28SJulian Elischer tdq_idled(struct tdq *tdq)
99122bf7d9aSJeff Roberson {
99262fa74d9SJeff Roberson 	struct cpu_group *cg;
993ad1e7d28SJulian Elischer 	struct tdq *steal;
994c76ee827SJeff Roberson 	cpuset_t mask;
99597e9382dSDon Lewis 	int cpu, switchcnt;
99680f86c9fSJeff Roberson 
99797e9382dSDon Lewis 	if (smp_started == 0 || steal_idle == 0 || tdq->tdq_cg == NULL)
99888f530ccSJeff Roberson 		return (1);
999c76ee827SJeff Roberson 	CPU_FILL(&mask);
1000c76ee827SJeff Roberson 	CPU_CLR(PCPU_GET(cpuid), &mask);
100197e9382dSDon Lewis     restart:
100297e9382dSDon Lewis 	switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
100397e9382dSDon Lewis 	for (cg = tdq->tdq_cg; ; ) {
100497e9382dSDon Lewis 		cpu = sched_highest(cg, mask, steal_thresh);
100597e9382dSDon Lewis 		/*
100697e9382dSDon Lewis 		 * We were assigned a thread but not preempted.  Returning
100797e9382dSDon Lewis 		 * 0 here will cause our caller to switch to it.
100897e9382dSDon Lewis 		 */
100997e9382dSDon Lewis 		if (tdq->tdq_load)
101097e9382dSDon Lewis 			return (0);
101162fa74d9SJeff Roberson 		if (cpu == -1) {
101262fa74d9SJeff Roberson 			cg = cg->cg_parent;
101397e9382dSDon Lewis 			if (cg == NULL)
101497e9382dSDon Lewis 				return (1);
101580f86c9fSJeff Roberson 			continue;
10167b8bfa0dSJeff Roberson 		}
10177b8bfa0dSJeff Roberson 		steal = TDQ_CPU(cpu);
101897e9382dSDon Lewis 		/*
101997e9382dSDon Lewis 		 * The data returned by sched_highest() is stale and
102097e9382dSDon Lewis 		 * the chosen CPU no longer has an eligible thread.
102197e9382dSDon Lewis 		 *
102297e9382dSDon Lewis 		 * Testing this ahead of tdq_lock_pair() only catches
102397e9382dSDon Lewis 		 * this situation about 20% of the time on an 8 core
102497e9382dSDon Lewis 		 * 16 thread Ryzen 7, but it still helps performance.
102597e9382dSDon Lewis 		 */
102697e9382dSDon Lewis 		if (steal->tdq_load < steal_thresh ||
102797e9382dSDon Lewis 		    steal->tdq_transferable == 0)
102897e9382dSDon Lewis 			goto restart;
10297fcf154aSJeff Roberson 		tdq_lock_pair(tdq, steal);
103097e9382dSDon Lewis 		/*
103197e9382dSDon Lewis 		 * We were assigned a thread while waiting for the locks.
103297e9382dSDon Lewis 		 * Switch to it now instead of stealing a thread.
103397e9382dSDon Lewis 		 */
103497e9382dSDon Lewis 		if (tdq->tdq_load)
103597e9382dSDon Lewis 			break;
103697e9382dSDon Lewis 		/*
103797e9382dSDon Lewis 		 * The data returned by sched_highest() is stale and
103897e9382dSDon Lewis 		 * the chosen CPU no longer has an eligible thread, or
103997e9382dSDon Lewis 		 * we were preempted and the CPU loading info may be out
104097e9382dSDon Lewis 		 * of date.  The latter is rare.  In either case restart
104197e9382dSDon Lewis 		 * the search.
104297e9382dSDon Lewis 		 */
104397e9382dSDon Lewis 		if (steal->tdq_load < steal_thresh ||
104497e9382dSDon Lewis 		    steal->tdq_transferable == 0 ||
104597e9382dSDon Lewis 		    switchcnt != tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt) {
10467fcf154aSJeff Roberson 			tdq_unlock_pair(tdq, steal);
104797e9382dSDon Lewis 			goto restart;
104862fa74d9SJeff Roberson 		}
104962fa74d9SJeff Roberson 		/*
105097e9382dSDon Lewis 		 * Steal the thread and switch to it.
105162fa74d9SJeff Roberson 		 */
105297e9382dSDon Lewis 		if (tdq_move(steal, tdq) != NULL)
105397e9382dSDon Lewis 			break;
105497e9382dSDon Lewis 		/*
105597e9382dSDon Lewis 		 * We failed to acquire a thread even though it looked
105697e9382dSDon Lewis 		 * like one was available.  This could be due to affinity
105797e9382dSDon Lewis 		 * restrictions or for other reasons.  Loop again after
105897e9382dSDon Lewis 		 * removing this CPU from the set.  The restart logic
105997e9382dSDon Lewis 		 * above does not restore this CPU to the set due to the
106097e9382dSDon Lewis 		 * likelyhood of failing here again.
106197e9382dSDon Lewis 		 */
106297e9382dSDon Lewis 		CPU_CLR(cpu, &mask);
106362fa74d9SJeff Roberson 		tdq_unlock_pair(tdq, steal);
106480f86c9fSJeff Roberson 	}
1065ae7a6b38SJeff Roberson 	TDQ_UNLOCK(steal);
10668df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_IDLE, NULL);
1067ae7a6b38SJeff Roberson 	thread_unlock(curthread);
10687b8bfa0dSJeff Roberson 	return (0);
106922bf7d9aSJeff Roberson }
107022bf7d9aSJeff Roberson 
1071ae7a6b38SJeff Roberson /*
1072ae7a6b38SJeff Roberson  * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
1073ae7a6b38SJeff Roberson  */
107422bf7d9aSJeff Roberson static void
107527ee18adSRyan Stone tdq_notify(struct tdq *tdq, struct thread *td)
107622bf7d9aSJeff Roberson {
107702f0ff6dSJohn Baldwin 	struct thread *ctd;
107827ee18adSRyan Stone 	int pri;
10797b8bfa0dSJeff Roberson 	int cpu;
108022bf7d9aSJeff Roberson 
1081ff256d9cSJeff Roberson 	if (tdq->tdq_ipipending)
1082ff256d9cSJeff Roberson 		return;
108327ee18adSRyan Stone 	cpu = td_get_sched(td)->ts_cpu;
108427ee18adSRyan Stone 	pri = td->td_priority;
108502f0ff6dSJohn Baldwin 	ctd = pcpu_find(cpu)->pc_curthread;
108602f0ff6dSJohn Baldwin 	if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
10876b2f763fSJeff Roberson 		return;
108879654969SAlexander Motin 
108979654969SAlexander Motin 	/*
1090ae9e9b4fSAlexander Motin 	 * Make sure that our caller's earlier update to tdq_load is
1091ae9e9b4fSAlexander Motin 	 * globally visible before we read tdq_cpu_idle.  Idle thread
109279654969SAlexander Motin 	 * accesses both of them without locks, and the order is important.
109379654969SAlexander Motin 	 */
1094e8677f38SKonstantin Belousov 	atomic_thread_fence_seq_cst();
109579654969SAlexander Motin 
109602f0ff6dSJohn Baldwin 	if (TD_IS_IDLETHREAD(ctd)) {
10971690c6c1SJeff Roberson 		/*
10986c47aaaeSJeff Roberson 		 * If the MD code has an idle wakeup routine try that before
10996c47aaaeSJeff Roberson 		 * falling back to IPI.
11006c47aaaeSJeff Roberson 		 */
11019f9ad565SAlexander Motin 		if (!tdq->tdq_cpu_idle || cpu_idle_wakeup(cpu))
11026c47aaaeSJeff Roberson 			return;
11031690c6c1SJeff Roberson 	}
1104ff256d9cSJeff Roberson 	tdq->tdq_ipipending = 1;
1105d9d8d144SJohn Baldwin 	ipi_cpu(cpu, IPI_PREEMPT);
110622bf7d9aSJeff Roberson }
110722bf7d9aSJeff Roberson 
1108ae7a6b38SJeff Roberson /*
1109ae7a6b38SJeff Roberson  * Steals load from a timeshare queue.  Honors the rotating queue head
1110ae7a6b38SJeff Roberson  * index.
1111ae7a6b38SJeff Roberson  */
11129727e637SJeff Roberson static struct thread *
111362fa74d9SJeff Roberson runq_steal_from(struct runq *rq, int cpu, u_char start)
1114ae7a6b38SJeff Roberson {
1115ae7a6b38SJeff Roberson 	struct rqbits *rqb;
1116ae7a6b38SJeff Roberson 	struct rqhead *rqh;
111736acfc65SAlexander Motin 	struct thread *td, *first;
1118ae7a6b38SJeff Roberson 	int bit;
1119ae7a6b38SJeff Roberson 	int i;
1120ae7a6b38SJeff Roberson 
1121ae7a6b38SJeff Roberson 	rqb = &rq->rq_status;
1122ae7a6b38SJeff Roberson 	bit = start & (RQB_BPW -1);
112336acfc65SAlexander Motin 	first = NULL;
1124ae7a6b38SJeff Roberson again:
1125ae7a6b38SJeff Roberson 	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1126ae7a6b38SJeff Roberson 		if (rqb->rqb_bits[i] == 0)
1127ae7a6b38SJeff Roberson 			continue;
11288bc713f6SJeff Roberson 		if (bit == 0)
11298bc713f6SJeff Roberson 			bit = RQB_FFS(rqb->rqb_bits[i]);
11308bc713f6SJeff Roberson 		for (; bit < RQB_BPW; bit++) {
11318bc713f6SJeff Roberson 			if ((rqb->rqb_bits[i] & (1ul << bit)) == 0)
1132ae7a6b38SJeff Roberson 				continue;
11338bc713f6SJeff Roberson 			rqh = &rq->rq_queues[bit + (i << RQB_L2BPW)];
11349727e637SJeff Roberson 			TAILQ_FOREACH(td, rqh, td_runq) {
11359727e637SJeff Roberson 				if (first && THREAD_CAN_MIGRATE(td) &&
11369727e637SJeff Roberson 				    THREAD_CAN_SCHED(td, cpu))
11379727e637SJeff Roberson 					return (td);
113836acfc65SAlexander Motin 				first = td;
1139ae7a6b38SJeff Roberson 			}
1140ae7a6b38SJeff Roberson 		}
11418bc713f6SJeff Roberson 	}
1142ae7a6b38SJeff Roberson 	if (start != 0) {
1143ae7a6b38SJeff Roberson 		start = 0;
1144ae7a6b38SJeff Roberson 		goto again;
1145ae7a6b38SJeff Roberson 	}
1146ae7a6b38SJeff Roberson 
114736acfc65SAlexander Motin 	if (first && THREAD_CAN_MIGRATE(first) &&
114836acfc65SAlexander Motin 	    THREAD_CAN_SCHED(first, cpu))
114936acfc65SAlexander Motin 		return (first);
1150ae7a6b38SJeff Roberson 	return (NULL);
1151ae7a6b38SJeff Roberson }
1152ae7a6b38SJeff Roberson 
1153ae7a6b38SJeff Roberson /*
1154ae7a6b38SJeff Roberson  * Steals load from a standard linear queue.
1155ae7a6b38SJeff Roberson  */
11569727e637SJeff Roberson static struct thread *
115762fa74d9SJeff Roberson runq_steal(struct runq *rq, int cpu)
115822bf7d9aSJeff Roberson {
115922bf7d9aSJeff Roberson 	struct rqhead *rqh;
116022bf7d9aSJeff Roberson 	struct rqbits *rqb;
11619727e637SJeff Roberson 	struct thread *td;
116222bf7d9aSJeff Roberson 	int word;
116322bf7d9aSJeff Roberson 	int bit;
116422bf7d9aSJeff Roberson 
116522bf7d9aSJeff Roberson 	rqb = &rq->rq_status;
116622bf7d9aSJeff Roberson 	for (word = 0; word < RQB_LEN; word++) {
116722bf7d9aSJeff Roberson 		if (rqb->rqb_bits[word] == 0)
116822bf7d9aSJeff Roberson 			continue;
116922bf7d9aSJeff Roberson 		for (bit = 0; bit < RQB_BPW; bit++) {
1170a2640c9bSPeter Wemm 			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
117122bf7d9aSJeff Roberson 				continue;
117222bf7d9aSJeff Roberson 			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
11739727e637SJeff Roberson 			TAILQ_FOREACH(td, rqh, td_runq)
11749727e637SJeff Roberson 				if (THREAD_CAN_MIGRATE(td) &&
11759727e637SJeff Roberson 				    THREAD_CAN_SCHED(td, cpu))
11769727e637SJeff Roberson 					return (td);
117722bf7d9aSJeff Roberson 		}
117822bf7d9aSJeff Roberson 	}
117922bf7d9aSJeff Roberson 	return (NULL);
118022bf7d9aSJeff Roberson }
118122bf7d9aSJeff Roberson 
1182ae7a6b38SJeff Roberson /*
1183ae7a6b38SJeff Roberson  * Attempt to steal a thread in priority order from a thread queue.
1184ae7a6b38SJeff Roberson  */
11859727e637SJeff Roberson static struct thread *
118662fa74d9SJeff Roberson tdq_steal(struct tdq *tdq, int cpu)
118722bf7d9aSJeff Roberson {
11889727e637SJeff Roberson 	struct thread *td;
118922bf7d9aSJeff Roberson 
1190ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
11919727e637SJeff Roberson 	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
11929727e637SJeff Roberson 		return (td);
11939727e637SJeff Roberson 	if ((td = runq_steal_from(&tdq->tdq_timeshare,
11949727e637SJeff Roberson 	    cpu, tdq->tdq_ridx)) != NULL)
11959727e637SJeff Roberson 		return (td);
119662fa74d9SJeff Roberson 	return (runq_steal(&tdq->tdq_idle, cpu));
119722bf7d9aSJeff Roberson }
119880f86c9fSJeff Roberson 
1199ae7a6b38SJeff Roberson /*
1200ae7a6b38SJeff Roberson  * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
12017fcf154aSJeff Roberson  * current lock and returns with the assigned queue locked.
1202ae7a6b38SJeff Roberson  */
1203ae7a6b38SJeff Roberson static inline struct tdq *
12049727e637SJeff Roberson sched_setcpu(struct thread *td, int cpu, int flags)
120580f86c9fSJeff Roberson {
12069727e637SJeff Roberson 
1207ae7a6b38SJeff Roberson 	struct tdq *tdq;
120880f86c9fSJeff Roberson 
12099727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1210ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpu);
121193ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_cpu = cpu;
12129727e637SJeff Roberson 	/*
12139727e637SJeff Roberson 	 * If the lock matches just return the queue.
12149727e637SJeff Roberson 	 */
1215ae7a6b38SJeff Roberson 	if (td->td_lock == TDQ_LOCKPTR(tdq))
1216ae7a6b38SJeff Roberson 		return (tdq);
1217ae7a6b38SJeff Roberson #ifdef notyet
121880f86c9fSJeff Roberson 	/*
1219a5423ea3SJeff Roberson 	 * If the thread isn't running its lockptr is a
1220ae7a6b38SJeff Roberson 	 * turnstile or a sleepqueue.  We can just lock_set without
1221ae7a6b38SJeff Roberson 	 * blocking.
1222670c524fSJeff Roberson 	 */
1223ae7a6b38SJeff Roberson 	if (TD_CAN_RUN(td)) {
1224ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
1225ae7a6b38SJeff Roberson 		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1226ae7a6b38SJeff Roberson 		return (tdq);
1227ae7a6b38SJeff Roberson 	}
1228ae7a6b38SJeff Roberson #endif
122980f86c9fSJeff Roberson 	/*
1230ae7a6b38SJeff Roberson 	 * The hard case, migration, we need to block the thread first to
1231ae7a6b38SJeff Roberson 	 * prevent order reversals with other cpus locks.
12327b8bfa0dSJeff Roberson 	 */
1233b0b9dee5SAttilio Rao 	spinlock_enter();
1234ae7a6b38SJeff Roberson 	thread_lock_block(td);
1235ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
1236ae7a6b38SJeff Roberson 	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1237b0b9dee5SAttilio Rao 	spinlock_exit();
1238ae7a6b38SJeff Roberson 	return (tdq);
123980f86c9fSJeff Roberson }
12402454aaf5SJeff Roberson 
12418df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
12428df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
12438df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
12448df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
12458df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
12468df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
12478df78c41SJeff Roberson 
1248ae7a6b38SJeff Roberson static int
12499727e637SJeff Roberson sched_pickcpu(struct thread *td, int flags)
1250ae7a6b38SJeff Roberson {
125136acfc65SAlexander Motin 	struct cpu_group *cg, *ccg;
12529727e637SJeff Roberson 	struct td_sched *ts;
1253ae7a6b38SJeff Roberson 	struct tdq *tdq;
1254c76ee827SJeff Roberson 	cpuset_t mask;
125536acfc65SAlexander Motin 	int cpu, pri, self;
12567b8bfa0dSJeff Roberson 
125762fa74d9SJeff Roberson 	self = PCPU_GET(cpuid);
125893ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1259efe67753SNathan Whitehorn 	KASSERT(!CPU_ABSENT(ts->ts_cpu), ("sched_pickcpu: Start scheduler on "
1260efe67753SNathan Whitehorn 	    "absent CPU %d for thread %s.", ts->ts_cpu, td->td_name));
12617b8bfa0dSJeff Roberson 	if (smp_started == 0)
12627b8bfa0dSJeff Roberson 		return (self);
126328994a58SJeff Roberson 	/*
126428994a58SJeff Roberson 	 * Don't migrate a running thread from sched_switch().
126528994a58SJeff Roberson 	 */
126662fa74d9SJeff Roberson 	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
126762fa74d9SJeff Roberson 		return (ts->ts_cpu);
12687b8bfa0dSJeff Roberson 	/*
126962fa74d9SJeff Roberson 	 * Prefer to run interrupt threads on the processors that generate
127062fa74d9SJeff Roberson 	 * the interrupt.
12717b8bfa0dSJeff Roberson 	 */
127236acfc65SAlexander Motin 	pri = td->td_priority;
127362fa74d9SJeff Roberson 	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
12748df78c41SJeff Roberson 	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
12758df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_intrbind);
127662fa74d9SJeff Roberson 		ts->ts_cpu = self;
127736acfc65SAlexander Motin 		if (TDQ_CPU(self)->tdq_lowpri > pri) {
12788df78c41SJeff Roberson 			SCHED_STAT_INC(pickcpu_affinity);
12797b8bfa0dSJeff Roberson 			return (ts->ts_cpu);
12807b8bfa0dSJeff Roberson 		}
12818df78c41SJeff Roberson 	}
12827b8bfa0dSJeff Roberson 	/*
128336acfc65SAlexander Motin 	 * If the thread can run on the last cpu and the affinity has not
12840127914cSEric van Gyzen 	 * expired and it is idle, run it there.
12857b8bfa0dSJeff Roberson 	 */
128636acfc65SAlexander Motin 	tdq = TDQ_CPU(ts->ts_cpu);
128736acfc65SAlexander Motin 	cg = tdq->tdq_cg;
128836acfc65SAlexander Motin 	if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
128936acfc65SAlexander Motin 	    tdq->tdq_lowpri >= PRI_MIN_IDLE &&
129036acfc65SAlexander Motin 	    SCHED_AFFINITY(ts, CG_SHARE_L2)) {
129136acfc65SAlexander Motin 		if (cg->cg_flags & CG_FLAG_THREAD) {
129236acfc65SAlexander Motin 			CPUSET_FOREACH(cpu, cg->cg_mask) {
129336acfc65SAlexander Motin 				if (TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE)
129462fa74d9SJeff Roberson 					break;
129536acfc65SAlexander Motin 			}
129636acfc65SAlexander Motin 		} else
129736acfc65SAlexander Motin 			cpu = INT_MAX;
129836acfc65SAlexander Motin 		if (cpu > mp_maxid) {
129936acfc65SAlexander Motin 			SCHED_STAT_INC(pickcpu_idle_affinity);
130036acfc65SAlexander Motin 			return (ts->ts_cpu);
130136acfc65SAlexander Motin 		}
130236acfc65SAlexander Motin 	}
130336acfc65SAlexander Motin 	/*
130436acfc65SAlexander Motin 	 * Search for the last level cache CPU group in the tree.
130536acfc65SAlexander Motin 	 * Skip caches with expired affinity time and SMT groups.
130636acfc65SAlexander Motin 	 * Affinity to higher level caches will be handled less aggressively.
130736acfc65SAlexander Motin 	 */
130836acfc65SAlexander Motin 	for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
130936acfc65SAlexander Motin 		if (cg->cg_flags & CG_FLAG_THREAD)
131036acfc65SAlexander Motin 			continue;
131136acfc65SAlexander Motin 		if (!SCHED_AFFINITY(ts, cg->cg_level))
131236acfc65SAlexander Motin 			continue;
131336acfc65SAlexander Motin 		ccg = cg;
131436acfc65SAlexander Motin 	}
131536acfc65SAlexander Motin 	if (ccg != NULL)
131636acfc65SAlexander Motin 		cg = ccg;
131762fa74d9SJeff Roberson 	cpu = -1;
131836acfc65SAlexander Motin 	/* Search the group for the less loaded idle CPU we can run now. */
1319c76ee827SJeff Roberson 	mask = td->td_cpuset->cs_mask;
132036acfc65SAlexander Motin 	if (cg != NULL && cg != cpu_top &&
132136acfc65SAlexander Motin 	    CPU_CMP(&cg->cg_mask, &cpu_top->cg_mask) != 0)
132236acfc65SAlexander Motin 		cpu = sched_lowest(cg, mask, max(pri, PRI_MAX_TIMESHARE),
132336acfc65SAlexander Motin 		    INT_MAX, ts->ts_cpu);
132436acfc65SAlexander Motin 	/* Search globally for the less loaded CPU we can run now. */
132562fa74d9SJeff Roberson 	if (cpu == -1)
132636acfc65SAlexander Motin 		cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu);
132736acfc65SAlexander Motin 	/* Search globally for the less loaded CPU. */
132836acfc65SAlexander Motin 	if (cpu == -1)
132936acfc65SAlexander Motin 		cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu);
13306022f0bcSAlexander Motin 	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1331efe67753SNathan Whitehorn 	KASSERT(!CPU_ABSENT(cpu), ("sched_pickcpu: Picked absent CPU %d.", cpu));
133262fa74d9SJeff Roberson 	/*
133362fa74d9SJeff Roberson 	 * Compare the lowest loaded cpu to current cpu.
133462fa74d9SJeff Roberson 	 */
1335ff256d9cSJeff Roberson 	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
133636acfc65SAlexander Motin 	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE &&
133736acfc65SAlexander Motin 	    TDQ_CPU(self)->tdq_load <= TDQ_CPU(cpu)->tdq_load + 1) {
13388df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_local);
133962fa74d9SJeff Roberson 		cpu = self;
13408df78c41SJeff Roberson 	} else
13418df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_lowest);
13428df78c41SJeff Roberson 	if (cpu != ts->ts_cpu)
13438df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_migration);
1344ae7a6b38SJeff Roberson 	return (cpu);
134580f86c9fSJeff Roberson }
134662fa74d9SJeff Roberson #endif
134722bf7d9aSJeff Roberson 
134822bf7d9aSJeff Roberson /*
134922bf7d9aSJeff Roberson  * Pick the highest priority task we have and return it.
13500c0a98b2SJeff Roberson  */
13519727e637SJeff Roberson static struct thread *
1352ad1e7d28SJulian Elischer tdq_choose(struct tdq *tdq)
13535d7ef00cSJeff Roberson {
13549727e637SJeff Roberson 	struct thread *td;
13555d7ef00cSJeff Roberson 
1356ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
13579727e637SJeff Roberson 	td = runq_choose(&tdq->tdq_realtime);
13589727e637SJeff Roberson 	if (td != NULL)
13599727e637SJeff Roberson 		return (td);
13609727e637SJeff Roberson 	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
13619727e637SJeff Roberson 	if (td != NULL) {
136212d56c0fSJohn Baldwin 		KASSERT(td->td_priority >= PRI_MIN_BATCH,
1363e7d50326SJeff Roberson 		    ("tdq_choose: Invalid priority on timeshare queue %d",
13649727e637SJeff Roberson 		    td->td_priority));
13659727e637SJeff Roberson 		return (td);
136615dc847eSJeff Roberson 	}
13679727e637SJeff Roberson 	td = runq_choose(&tdq->tdq_idle);
13689727e637SJeff Roberson 	if (td != NULL) {
13699727e637SJeff Roberson 		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1370e7d50326SJeff Roberson 		    ("tdq_choose: Invalid priority on idle queue %d",
13719727e637SJeff Roberson 		    td->td_priority));
13729727e637SJeff Roberson 		return (td);
1373e7d50326SJeff Roberson 	}
1374e7d50326SJeff Roberson 
1375e7d50326SJeff Roberson 	return (NULL);
1376245f3abfSJeff Roberson }
13770a016a05SJeff Roberson 
1378ae7a6b38SJeff Roberson /*
1379ae7a6b38SJeff Roberson  * Initialize a thread queue.
1380ae7a6b38SJeff Roberson  */
13810a016a05SJeff Roberson static void
1382ad1e7d28SJulian Elischer tdq_setup(struct tdq *tdq)
13830a016a05SJeff Roberson {
1384ae7a6b38SJeff Roberson 
1385c47f202bSJeff Roberson 	if (bootverbose)
1386c47f202bSJeff Roberson 		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1387e7d50326SJeff Roberson 	runq_init(&tdq->tdq_realtime);
1388e7d50326SJeff Roberson 	runq_init(&tdq->tdq_timeshare);
1389d2ad694cSJeff Roberson 	runq_init(&tdq->tdq_idle);
139062fa74d9SJeff Roberson 	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
139162fa74d9SJeff Roberson 	    "sched lock %d", (int)TDQ_ID(tdq));
139262fa74d9SJeff Roberson 	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
139362fa74d9SJeff Roberson 	    MTX_SPIN | MTX_RECURSE);
13948f51ad55SJeff Roberson #ifdef KTR
13958f51ad55SJeff Roberson 	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
13968f51ad55SJeff Roberson 	    "CPU %d load", (int)TDQ_ID(tdq));
13978f51ad55SJeff Roberson #endif
13980a016a05SJeff Roberson }
13990a016a05SJeff Roberson 
1400c47f202bSJeff Roberson #ifdef SMP
1401c47f202bSJeff Roberson static void
1402c47f202bSJeff Roberson sched_setup_smp(void)
1403c47f202bSJeff Roberson {
1404c47f202bSJeff Roberson 	struct tdq *tdq;
1405c47f202bSJeff Roberson 	int i;
1406c47f202bSJeff Roberson 
140762fa74d9SJeff Roberson 	cpu_top = smp_topo();
14083aa6d94eSJohn Baldwin 	CPU_FOREACH(i) {
140962fa74d9SJeff Roberson 		tdq = TDQ_CPU(i);
1410c47f202bSJeff Roberson 		tdq_setup(tdq);
141162fa74d9SJeff Roberson 		tdq->tdq_cg = smp_topo_find(cpu_top, i);
141262fa74d9SJeff Roberson 		if (tdq->tdq_cg == NULL)
141362fa74d9SJeff Roberson 			panic("Can't find cpu group for %d\n", i);
1414c47f202bSJeff Roberson 	}
141562fa74d9SJeff Roberson 	balance_tdq = TDQ_SELF();
141662fa74d9SJeff Roberson 	sched_balance();
1417c47f202bSJeff Roberson }
1418c47f202bSJeff Roberson #endif
1419c47f202bSJeff Roberson 
1420ae7a6b38SJeff Roberson /*
1421ae7a6b38SJeff Roberson  * Setup the thread queues and initialize the topology based on MD
1422ae7a6b38SJeff Roberson  * information.
1423ae7a6b38SJeff Roberson  */
142435e6168fSJeff Roberson static void
142535e6168fSJeff Roberson sched_setup(void *dummy)
142635e6168fSJeff Roberson {
1427ae7a6b38SJeff Roberson 	struct tdq *tdq;
1428c47f202bSJeff Roberson 
1429c47f202bSJeff Roberson 	tdq = TDQ_SELF();
14300ec896fdSJeff Roberson #ifdef SMP
1431c47f202bSJeff Roberson 	sched_setup_smp();
1432749d01b0SJeff Roberson #else
1433c47f202bSJeff Roberson 	tdq_setup(tdq);
1434356500a3SJeff Roberson #endif
1435ae7a6b38SJeff Roberson 
1436ae7a6b38SJeff Roberson 	/* Add thread0's load since it's running. */
1437ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
1438c47f202bSJeff Roberson 	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
14399727e637SJeff Roberson 	tdq_load_add(tdq, &thread0);
144062fa74d9SJeff Roberson 	tdq->tdq_lowpri = thread0.td_priority;
1441ae7a6b38SJeff Roberson 	TDQ_UNLOCK(tdq);
144235e6168fSJeff Roberson }
144335e6168fSJeff Roberson 
1444ae7a6b38SJeff Roberson /*
1445579895dfSAlexander Motin  * This routine determines time constants after stathz and hz are setup.
1446ae7a6b38SJeff Roberson  */
1447a1d4fe69SDavid Xu /* ARGSUSED */
1448a1d4fe69SDavid Xu static void
1449a1d4fe69SDavid Xu sched_initticks(void *dummy)
1450a1d4fe69SDavid Xu {
1451ae7a6b38SJeff Roberson 	int incr;
1452ae7a6b38SJeff Roberson 
1453a1d4fe69SDavid Xu 	realstathz = stathz ? stathz : hz;
14545e5c3873SJeff Roberson 	sched_slice = realstathz / SCHED_SLICE_DEFAULT_DIVISOR;
14555e5c3873SJeff Roberson 	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
145637f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
145737f4e025SAlexander Motin 	    realstathz);
1458a1d4fe69SDavid Xu 
1459a1d4fe69SDavid Xu 	/*
1460e7d50326SJeff Roberson 	 * tickincr is shifted out by 10 to avoid rounding errors due to
14613f872f85SJeff Roberson 	 * hz not being evenly divisible by stathz on all platforms.
1462e7d50326SJeff Roberson 	 */
1463ae7a6b38SJeff Roberson 	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1464e7d50326SJeff Roberson 	/*
1465e7d50326SJeff Roberson 	 * This does not work for values of stathz that are more than
1466e7d50326SJeff Roberson 	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1467a1d4fe69SDavid Xu 	 */
1468ae7a6b38SJeff Roberson 	if (incr == 0)
1469ae7a6b38SJeff Roberson 		incr = 1;
1470ae7a6b38SJeff Roberson 	tickincr = incr;
14717b8bfa0dSJeff Roberson #ifdef SMP
14729862717aSJeff Roberson 	/*
14737fcf154aSJeff Roberson 	 * Set the default balance interval now that we know
14747fcf154aSJeff Roberson 	 * what realstathz is.
14757fcf154aSJeff Roberson 	 */
14767fcf154aSJeff Roberson 	balance_interval = realstathz;
14777b8bfa0dSJeff Roberson 	affinity = SCHED_AFFINITY_DEFAULT;
14787b8bfa0dSJeff Roberson #endif
1479b3f40a41SAlexander Motin 	if (sched_idlespinthresh < 0)
14802c27cb3aSAlexander Motin 		sched_idlespinthresh = 2 * max(10000, 6 * hz) / realstathz;
1481a1d4fe69SDavid Xu }
1482a1d4fe69SDavid Xu 
1483a1d4fe69SDavid Xu 
148435e6168fSJeff Roberson /*
1485ae7a6b38SJeff Roberson  * This is the core of the interactivity algorithm.  Determines a score based
1486ae7a6b38SJeff Roberson  * on past behavior.  It is the ratio of sleep time to run time scaled to
1487ae7a6b38SJeff Roberson  * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1488ae7a6b38SJeff Roberson  * differs from the cpu usage because it does not account for time spent
1489ae7a6b38SJeff Roberson  * waiting on a run-queue.  Would be prettier if we had floating point.
149057031f79SGeorge V. Neville-Neil  *
149157031f79SGeorge V. Neville-Neil  * When a thread's sleep time is greater than its run time the
149257031f79SGeorge V. Neville-Neil  * calculation is:
149357031f79SGeorge V. Neville-Neil  *
149457031f79SGeorge V. Neville-Neil  *                           scaling factor
149557031f79SGeorge V. Neville-Neil  * interactivity score =  ---------------------
149657031f79SGeorge V. Neville-Neil  *                        sleep time / run time
149757031f79SGeorge V. Neville-Neil  *
149857031f79SGeorge V. Neville-Neil  *
149957031f79SGeorge V. Neville-Neil  * When a thread's run time is greater than its sleep time the
150057031f79SGeorge V. Neville-Neil  * calculation is:
150157031f79SGeorge V. Neville-Neil  *
150257031f79SGeorge V. Neville-Neil  *                           scaling factor
150357031f79SGeorge V. Neville-Neil  * interactivity score =  ---------------------    + scaling factor
150457031f79SGeorge V. Neville-Neil  *                        run time / sleep time
1505ae7a6b38SJeff Roberson  */
1506ae7a6b38SJeff Roberson static int
1507ae7a6b38SJeff Roberson sched_interact_score(struct thread *td)
1508ae7a6b38SJeff Roberson {
1509ae7a6b38SJeff Roberson 	struct td_sched *ts;
1510ae7a6b38SJeff Roberson 	int div;
1511ae7a6b38SJeff Roberson 
151293ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1513ae7a6b38SJeff Roberson 	/*
1514ae7a6b38SJeff Roberson 	 * The score is only needed if this is likely to be an interactive
1515ae7a6b38SJeff Roberson 	 * task.  Don't go through the expense of computing it if there's
1516ae7a6b38SJeff Roberson 	 * no chance.
1517ae7a6b38SJeff Roberson 	 */
1518ae7a6b38SJeff Roberson 	if (sched_interact <= SCHED_INTERACT_HALF &&
1519ae7a6b38SJeff Roberson 		ts->ts_runtime >= ts->ts_slptime)
1520ae7a6b38SJeff Roberson 			return (SCHED_INTERACT_HALF);
1521ae7a6b38SJeff Roberson 
1522ae7a6b38SJeff Roberson 	if (ts->ts_runtime > ts->ts_slptime) {
1523ae7a6b38SJeff Roberson 		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1524ae7a6b38SJeff Roberson 		return (SCHED_INTERACT_HALF +
1525ae7a6b38SJeff Roberson 		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1526ae7a6b38SJeff Roberson 	}
1527ae7a6b38SJeff Roberson 	if (ts->ts_slptime > ts->ts_runtime) {
1528ae7a6b38SJeff Roberson 		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1529ae7a6b38SJeff Roberson 		return (ts->ts_runtime / div);
1530ae7a6b38SJeff Roberson 	}
1531ae7a6b38SJeff Roberson 	/* runtime == slptime */
1532ae7a6b38SJeff Roberson 	if (ts->ts_runtime)
1533ae7a6b38SJeff Roberson 		return (SCHED_INTERACT_HALF);
1534ae7a6b38SJeff Roberson 
1535ae7a6b38SJeff Roberson 	/*
1536ae7a6b38SJeff Roberson 	 * This can happen if slptime and runtime are 0.
1537ae7a6b38SJeff Roberson 	 */
1538ae7a6b38SJeff Roberson 	return (0);
1539ae7a6b38SJeff Roberson 
1540ae7a6b38SJeff Roberson }
1541ae7a6b38SJeff Roberson 
1542ae7a6b38SJeff Roberson /*
154335e6168fSJeff Roberson  * Scale the scheduling priority according to the "interactivity" of this
154435e6168fSJeff Roberson  * process.
154535e6168fSJeff Roberson  */
154615dc847eSJeff Roberson static void
15478460a577SJohn Birrell sched_priority(struct thread *td)
154835e6168fSJeff Roberson {
1549e7d50326SJeff Roberson 	int score;
155035e6168fSJeff Roberson 	int pri;
155135e6168fSJeff Roberson 
1552c9a8cba4SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
155315dc847eSJeff Roberson 		return;
1554e7d50326SJeff Roberson 	/*
1555e7d50326SJeff Roberson 	 * If the score is interactive we place the thread in the realtime
1556e7d50326SJeff Roberson 	 * queue with a priority that is less than kernel and interrupt
1557e7d50326SJeff Roberson 	 * priorities.  These threads are not subject to nice restrictions.
1558e7d50326SJeff Roberson 	 *
1559ae7a6b38SJeff Roberson 	 * Scores greater than this are placed on the normal timeshare queue
1560e7d50326SJeff Roberson 	 * where the priority is partially decided by the most recent cpu
1561e7d50326SJeff Roberson 	 * utilization and the rest is decided by nice value.
1562a5423ea3SJeff Roberson 	 *
1563a5423ea3SJeff Roberson 	 * The nice value of the process has a linear effect on the calculated
1564a5423ea3SJeff Roberson 	 * score.  Negative nice values make it easier for a thread to be
1565a5423ea3SJeff Roberson 	 * considered interactive.
1566e7d50326SJeff Roberson 	 */
1567a0f15352SJohn Baldwin 	score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1568e7d50326SJeff Roberson 	if (score < sched_interact) {
156912d56c0fSJohn Baldwin 		pri = PRI_MIN_INTERACT;
157012d56c0fSJohn Baldwin 		pri += ((PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) /
157178920008SJohn Baldwin 		    sched_interact) * score;
157212d56c0fSJohn Baldwin 		KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
15739a93305aSJeff Roberson 		    ("sched_priority: invalid interactive priority %d score %d",
15749a93305aSJeff Roberson 		    pri, score));
1575e7d50326SJeff Roberson 	} else {
1576e7d50326SJeff Roberson 		pri = SCHED_PRI_MIN;
157793ccd6bfSKonstantin Belousov 		if (td_get_sched(td)->ts_ticks)
157893ccd6bfSKonstantin Belousov 			pri += min(SCHED_PRI_TICKS(td_get_sched(td)),
15795457fa23SJohn Baldwin 			    SCHED_PRI_RANGE - 1);
1580e7d50326SJeff Roberson 		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
158112d56c0fSJohn Baldwin 		KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
1582ae7a6b38SJeff Roberson 		    ("sched_priority: invalid priority %d: nice %d, "
1583ae7a6b38SJeff Roberson 		    "ticks %d ftick %d ltick %d tick pri %d",
158493ccd6bfSKonstantin Belousov 		    pri, td->td_proc->p_nice, td_get_sched(td)->ts_ticks,
158593ccd6bfSKonstantin Belousov 		    td_get_sched(td)->ts_ftick, td_get_sched(td)->ts_ltick,
158693ccd6bfSKonstantin Belousov 		    SCHED_PRI_TICKS(td_get_sched(td))));
1587e7d50326SJeff Roberson 	}
15888460a577SJohn Birrell 	sched_user_prio(td, pri);
158935e6168fSJeff Roberson 
159015dc847eSJeff Roberson 	return;
159135e6168fSJeff Roberson }
159235e6168fSJeff Roberson 
159335e6168fSJeff Roberson /*
1594d322132cSJeff Roberson  * This routine enforces a maximum limit on the amount of scheduling history
1595ae7a6b38SJeff Roberson  * kept.  It is called after either the slptime or runtime is adjusted.  This
1596ae7a6b38SJeff Roberson  * function is ugly due to integer math.
1597d322132cSJeff Roberson  */
15984b60e324SJeff Roberson static void
15998460a577SJohn Birrell sched_interact_update(struct thread *td)
16004b60e324SJeff Roberson {
1601155b6ca1SJeff Roberson 	struct td_sched *ts;
16029a93305aSJeff Roberson 	u_int sum;
16033f741ca1SJeff Roberson 
160493ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1605ae7a6b38SJeff Roberson 	sum = ts->ts_runtime + ts->ts_slptime;
1606d322132cSJeff Roberson 	if (sum < SCHED_SLP_RUN_MAX)
1607d322132cSJeff Roberson 		return;
1608d322132cSJeff Roberson 	/*
1609155b6ca1SJeff Roberson 	 * This only happens from two places:
1610155b6ca1SJeff Roberson 	 * 1) We have added an unusual amount of run time from fork_exit.
1611155b6ca1SJeff Roberson 	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1612155b6ca1SJeff Roberson 	 */
1613155b6ca1SJeff Roberson 	if (sum > SCHED_SLP_RUN_MAX * 2) {
1614ae7a6b38SJeff Roberson 		if (ts->ts_runtime > ts->ts_slptime) {
1615ae7a6b38SJeff Roberson 			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1616ae7a6b38SJeff Roberson 			ts->ts_slptime = 1;
1617155b6ca1SJeff Roberson 		} else {
1618ae7a6b38SJeff Roberson 			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1619ae7a6b38SJeff Roberson 			ts->ts_runtime = 1;
1620155b6ca1SJeff Roberson 		}
1621155b6ca1SJeff Roberson 		return;
1622155b6ca1SJeff Roberson 	}
1623155b6ca1SJeff Roberson 	/*
1624d322132cSJeff Roberson 	 * If we have exceeded by more than 1/5th then the algorithm below
1625d322132cSJeff Roberson 	 * will not bring us back into range.  Dividing by two here forces
16262454aaf5SJeff Roberson 	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1627d322132cSJeff Roberson 	 */
162837a35e4aSJeff Roberson 	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1629ae7a6b38SJeff Roberson 		ts->ts_runtime /= 2;
1630ae7a6b38SJeff Roberson 		ts->ts_slptime /= 2;
1631d322132cSJeff Roberson 		return;
1632d322132cSJeff Roberson 	}
1633ae7a6b38SJeff Roberson 	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1634ae7a6b38SJeff Roberson 	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1635d322132cSJeff Roberson }
1636d322132cSJeff Roberson 
1637ae7a6b38SJeff Roberson /*
1638ae7a6b38SJeff Roberson  * Scale back the interactivity history when a child thread is created.  The
1639ae7a6b38SJeff Roberson  * history is inherited from the parent but the thread may behave totally
1640ae7a6b38SJeff Roberson  * differently.  For example, a shell spawning a compiler process.  We want
1641ae7a6b38SJeff Roberson  * to learn that the compiler is behaving badly very quickly.
1642ae7a6b38SJeff Roberson  */
1643d322132cSJeff Roberson static void
16448460a577SJohn Birrell sched_interact_fork(struct thread *td)
1645d322132cSJeff Roberson {
164693ccd6bfSKonstantin Belousov 	struct td_sched *ts;
1647d322132cSJeff Roberson 	int ratio;
1648d322132cSJeff Roberson 	int sum;
1649d322132cSJeff Roberson 
165093ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
165193ccd6bfSKonstantin Belousov 	sum = ts->ts_runtime + ts->ts_slptime;
1652d322132cSJeff Roberson 	if (sum > SCHED_SLP_RUN_FORK) {
1653d322132cSJeff Roberson 		ratio = sum / SCHED_SLP_RUN_FORK;
165493ccd6bfSKonstantin Belousov 		ts->ts_runtime /= ratio;
165593ccd6bfSKonstantin Belousov 		ts->ts_slptime /= ratio;
16564b60e324SJeff Roberson 	}
16574b60e324SJeff Roberson }
16584b60e324SJeff Roberson 
165915dc847eSJeff Roberson /*
1660ae7a6b38SJeff Roberson  * Called from proc0_init() to setup the scheduler fields.
1661ed062c8dSJulian Elischer  */
1662ed062c8dSJulian Elischer void
1663ed062c8dSJulian Elischer schedinit(void)
1664ed062c8dSJulian Elischer {
166593ccd6bfSKonstantin Belousov 	struct td_sched *ts0;
1666e7d50326SJeff Roberson 
1667ed062c8dSJulian Elischer 	/*
166893ccd6bfSKonstantin Belousov 	 * Set up the scheduler specific parts of thread0.
1669ed062c8dSJulian Elischer 	 */
167093ccd6bfSKonstantin Belousov 	ts0 = td_get_sched(&thread0);
167193ccd6bfSKonstantin Belousov 	ts0->ts_ltick = ticks;
167293ccd6bfSKonstantin Belousov 	ts0->ts_ftick = ticks;
167393ccd6bfSKonstantin Belousov 	ts0->ts_slice = 0;
16741408b84aSHans Petter Selasky 	ts0->ts_cpu = curcpu;	/* set valid CPU number */
1675ed062c8dSJulian Elischer }
1676ed062c8dSJulian Elischer 
1677ed062c8dSJulian Elischer /*
167815dc847eSJeff Roberson  * This is only somewhat accurate since given many processes of the same
167915dc847eSJeff Roberson  * priority they will switch when their slices run out, which will be
1680e7d50326SJeff Roberson  * at most sched_slice stathz ticks.
168115dc847eSJeff Roberson  */
168235e6168fSJeff Roberson int
168335e6168fSJeff Roberson sched_rr_interval(void)
168435e6168fSJeff Roberson {
1685e7d50326SJeff Roberson 
1686579895dfSAlexander Motin 	/* Convert sched_slice from stathz to hz. */
168737f4e025SAlexander Motin 	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
168835e6168fSJeff Roberson }
168935e6168fSJeff Roberson 
1690ae7a6b38SJeff Roberson /*
1691ae7a6b38SJeff Roberson  * Update the percent cpu tracking information when it is requested or
1692ae7a6b38SJeff Roberson  * the total history exceeds the maximum.  We keep a sliding history of
1693ae7a6b38SJeff Roberson  * tick counts that slowly decays.  This is less precise than the 4BSD
1694ae7a6b38SJeff Roberson  * mechanism since it happens with less regular and frequent events.
1695ae7a6b38SJeff Roberson  */
169622bf7d9aSJeff Roberson static void
16977295465eSAlexander Motin sched_pctcpu_update(struct td_sched *ts, int run)
169835e6168fSJeff Roberson {
16997295465eSAlexander Motin 	int t = ticks;
1700e7d50326SJeff Roberson 
170178133024SMark Johnston 	/*
170278133024SMark Johnston 	 * The signed difference may be negative if the thread hasn't run for
170378133024SMark Johnston 	 * over half of the ticks rollover period.
170478133024SMark Johnston 	 */
170578133024SMark Johnston 	if ((u_int)(t - ts->ts_ltick) >= SCHED_TICK_TARG) {
1706ad1e7d28SJulian Elischer 		ts->ts_ticks = 0;
17077295465eSAlexander Motin 		ts->ts_ftick = t - SCHED_TICK_TARG;
17087295465eSAlexander Motin 	} else if (t - ts->ts_ftick >= SCHED_TICK_MAX) {
17097295465eSAlexander Motin 		ts->ts_ticks = (ts->ts_ticks / (ts->ts_ltick - ts->ts_ftick)) *
17107295465eSAlexander Motin 		    (ts->ts_ltick - (t - SCHED_TICK_TARG));
17117295465eSAlexander Motin 		ts->ts_ftick = t - SCHED_TICK_TARG;
17127295465eSAlexander Motin 	}
17137295465eSAlexander Motin 	if (run)
17147295465eSAlexander Motin 		ts->ts_ticks += (t - ts->ts_ltick) << SCHED_TICK_SHIFT;
17157295465eSAlexander Motin 	ts->ts_ltick = t;
171635e6168fSJeff Roberson }
171735e6168fSJeff Roberson 
1718ae7a6b38SJeff Roberson /*
1719ae7a6b38SJeff Roberson  * Adjust the priority of a thread.  Move it to the appropriate run-queue
1720ae7a6b38SJeff Roberson  * if necessary.  This is the back-end for several priority related
1721ae7a6b38SJeff Roberson  * functions.
1722ae7a6b38SJeff Roberson  */
1723e7d50326SJeff Roberson static void
1724f5c157d9SJohn Baldwin sched_thread_priority(struct thread *td, u_char prio)
172535e6168fSJeff Roberson {
1726ad1e7d28SJulian Elischer 	struct td_sched *ts;
172773daf66fSJeff Roberson 	struct tdq *tdq;
172873daf66fSJeff Roberson 	int oldpri;
172935e6168fSJeff Roberson 
17308f51ad55SJeff Roberson 	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
17318f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, "new prio:%d", prio,
17328f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(curthread));
1733d9fae5abSAndriy Gapon 	SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
1734e87fc7cfSAndriy Gapon 	if (td != curthread && prio < td->td_priority) {
17358f51ad55SJeff Roberson 		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
17368f51ad55SJeff Roberson 		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
17378f51ad55SJeff Roberson 		    prio, KTR_ATTR_LINKED, sched_tdname(td));
1738d9fae5abSAndriy Gapon 		SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
1739b3e9e682SRyan Stone 		    curthread);
17408f51ad55SJeff Roberson 	}
174193ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
17427b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1743f5c157d9SJohn Baldwin 	if (td->td_priority == prio)
1744f5c157d9SJohn Baldwin 		return;
17453f741ca1SJeff Roberson 	/*
17463f741ca1SJeff Roberson 	 * If the priority has been elevated due to priority
17473f741ca1SJeff Roberson 	 * propagation, we may have to move ourselves to a new
1748e7d50326SJeff Roberson 	 * queue.  This could be optimized to not re-add in some
1749e7d50326SJeff Roberson 	 * cases.
1750f2b74cbfSJeff Roberson 	 */
17516d55b3ecSJeff Roberson 	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1752e7d50326SJeff Roberson 		sched_rem(td);
1753e7d50326SJeff Roberson 		td->td_priority = prio;
1754ae7a6b38SJeff Roberson 		sched_add(td, SRQ_BORROWING);
175573daf66fSJeff Roberson 		return;
175673daf66fSJeff Roberson 	}
17576d55b3ecSJeff Roberson 	/*
17586d55b3ecSJeff Roberson 	 * If the thread is currently running we may have to adjust the lowpri
17596d55b3ecSJeff Roberson 	 * information so other cpus are aware of our current priority.
17606d55b3ecSJeff Roberson 	 */
17616d55b3ecSJeff Roberson 	if (TD_IS_RUNNING(td)) {
1762ae7a6b38SJeff Roberson 		tdq = TDQ_CPU(ts->ts_cpu);
176362fa74d9SJeff Roberson 		oldpri = td->td_priority;
17643f741ca1SJeff Roberson 		td->td_priority = prio;
176562fa74d9SJeff Roberson 		if (prio < tdq->tdq_lowpri)
176662fa74d9SJeff Roberson 			tdq->tdq_lowpri = prio;
176762fa74d9SJeff Roberson 		else if (tdq->tdq_lowpri == oldpri)
176862fa74d9SJeff Roberson 			tdq_setlowpri(tdq, td);
17696d55b3ecSJeff Roberson 		return;
177073daf66fSJeff Roberson 	}
17716d55b3ecSJeff Roberson 	td->td_priority = prio;
1772ae7a6b38SJeff Roberson }
177335e6168fSJeff Roberson 
1774f5c157d9SJohn Baldwin /*
1775f5c157d9SJohn Baldwin  * Update a thread's priority when it is lent another thread's
1776f5c157d9SJohn Baldwin  * priority.
1777f5c157d9SJohn Baldwin  */
1778f5c157d9SJohn Baldwin void
1779f5c157d9SJohn Baldwin sched_lend_prio(struct thread *td, u_char prio)
1780f5c157d9SJohn Baldwin {
1781f5c157d9SJohn Baldwin 
1782f5c157d9SJohn Baldwin 	td->td_flags |= TDF_BORROWING;
1783f5c157d9SJohn Baldwin 	sched_thread_priority(td, prio);
1784f5c157d9SJohn Baldwin }
1785f5c157d9SJohn Baldwin 
1786f5c157d9SJohn Baldwin /*
1787f5c157d9SJohn Baldwin  * Restore a thread's priority when priority propagation is
1788f5c157d9SJohn Baldwin  * over.  The prio argument is the minimum priority the thread
1789f5c157d9SJohn Baldwin  * needs to have to satisfy other possible priority lending
1790f5c157d9SJohn Baldwin  * requests.  If the thread's regular priority is less
1791f5c157d9SJohn Baldwin  * important than prio, the thread will keep a priority boost
1792f5c157d9SJohn Baldwin  * of prio.
1793f5c157d9SJohn Baldwin  */
1794f5c157d9SJohn Baldwin void
1795f5c157d9SJohn Baldwin sched_unlend_prio(struct thread *td, u_char prio)
1796f5c157d9SJohn Baldwin {
1797f5c157d9SJohn Baldwin 	u_char base_pri;
1798f5c157d9SJohn Baldwin 
1799f5c157d9SJohn Baldwin 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1800f5c157d9SJohn Baldwin 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
18018460a577SJohn Birrell 		base_pri = td->td_user_pri;
1802f5c157d9SJohn Baldwin 	else
1803f5c157d9SJohn Baldwin 		base_pri = td->td_base_pri;
1804f5c157d9SJohn Baldwin 	if (prio >= base_pri) {
1805f5c157d9SJohn Baldwin 		td->td_flags &= ~TDF_BORROWING;
1806f5c157d9SJohn Baldwin 		sched_thread_priority(td, base_pri);
1807f5c157d9SJohn Baldwin 	} else
1808f5c157d9SJohn Baldwin 		sched_lend_prio(td, prio);
1809f5c157d9SJohn Baldwin }
1810f5c157d9SJohn Baldwin 
1811ae7a6b38SJeff Roberson /*
1812ae7a6b38SJeff Roberson  * Standard entry for setting the priority to an absolute value.
1813ae7a6b38SJeff Roberson  */
1814f5c157d9SJohn Baldwin void
1815f5c157d9SJohn Baldwin sched_prio(struct thread *td, u_char prio)
1816f5c157d9SJohn Baldwin {
1817f5c157d9SJohn Baldwin 	u_char oldprio;
1818f5c157d9SJohn Baldwin 
1819f5c157d9SJohn Baldwin 	/* First, update the base priority. */
1820f5c157d9SJohn Baldwin 	td->td_base_pri = prio;
1821f5c157d9SJohn Baldwin 
1822f5c157d9SJohn Baldwin 	/*
182350aaa791SJohn Baldwin 	 * If the thread is borrowing another thread's priority, don't
1824f5c157d9SJohn Baldwin 	 * ever lower the priority.
1825f5c157d9SJohn Baldwin 	 */
1826f5c157d9SJohn Baldwin 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1827f5c157d9SJohn Baldwin 		return;
1828f5c157d9SJohn Baldwin 
1829f5c157d9SJohn Baldwin 	/* Change the real priority. */
1830f5c157d9SJohn Baldwin 	oldprio = td->td_priority;
1831f5c157d9SJohn Baldwin 	sched_thread_priority(td, prio);
1832f5c157d9SJohn Baldwin 
1833f5c157d9SJohn Baldwin 	/*
1834f5c157d9SJohn Baldwin 	 * If the thread is on a turnstile, then let the turnstile update
1835f5c157d9SJohn Baldwin 	 * its state.
1836f5c157d9SJohn Baldwin 	 */
1837f5c157d9SJohn Baldwin 	if (TD_ON_LOCK(td) && oldprio != prio)
1838f5c157d9SJohn Baldwin 		turnstile_adjust(td, oldprio);
1839f5c157d9SJohn Baldwin }
1840f5c157d9SJohn Baldwin 
1841ae7a6b38SJeff Roberson /*
1842ae7a6b38SJeff Roberson  * Set the base user priority, does not effect current running priority.
1843ae7a6b38SJeff Roberson  */
184435e6168fSJeff Roberson void
18458460a577SJohn Birrell sched_user_prio(struct thread *td, u_char prio)
18463db720fdSDavid Xu {
18473db720fdSDavid Xu 
18488460a577SJohn Birrell 	td->td_base_user_pri = prio;
1849acbe332aSDavid Xu 	if (td->td_lend_user_pri <= prio)
1850fc6c30f6SJulian Elischer 		return;
18518460a577SJohn Birrell 	td->td_user_pri = prio;
18523db720fdSDavid Xu }
18533db720fdSDavid Xu 
18543db720fdSDavid Xu void
18553db720fdSDavid Xu sched_lend_user_prio(struct thread *td, u_char prio)
18563db720fdSDavid Xu {
18573db720fdSDavid Xu 
1858435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1859acbe332aSDavid Xu 	td->td_lend_user_pri = prio;
1860c8e368a9SDavid Xu 	td->td_user_pri = min(prio, td->td_base_user_pri);
1861c8e368a9SDavid Xu 	if (td->td_priority > td->td_user_pri)
1862c8e368a9SDavid Xu 		sched_prio(td, td->td_user_pri);
1863c8e368a9SDavid Xu 	else if (td->td_priority != td->td_user_pri)
1864c8e368a9SDavid Xu 		td->td_flags |= TDF_NEEDRESCHED;
1865435806d3SDavid Xu }
18663db720fdSDavid Xu 
18674c8a8cfcSKonstantin Belousov #ifdef SMP
1868ae7a6b38SJeff Roberson /*
186997e9382dSDon Lewis  * This tdq is about to idle.  Try to steal a thread from another CPU before
187097e9382dSDon Lewis  * choosing the idle thread.
187197e9382dSDon Lewis  */
187297e9382dSDon Lewis static void
187397e9382dSDon Lewis tdq_trysteal(struct tdq *tdq)
187497e9382dSDon Lewis {
187597e9382dSDon Lewis 	struct cpu_group *cg;
187697e9382dSDon Lewis 	struct tdq *steal;
187797e9382dSDon Lewis 	cpuset_t mask;
187897e9382dSDon Lewis 	int cpu, i;
187997e9382dSDon Lewis 
188097e9382dSDon Lewis 	if (smp_started == 0 || trysteal_limit == 0 || tdq->tdq_cg == NULL)
188197e9382dSDon Lewis 		return;
188297e9382dSDon Lewis 	CPU_FILL(&mask);
188397e9382dSDon Lewis 	CPU_CLR(PCPU_GET(cpuid), &mask);
188497e9382dSDon Lewis 	/* We don't want to be preempted while we're iterating. */
188597e9382dSDon Lewis 	spinlock_enter();
188697e9382dSDon Lewis 	TDQ_UNLOCK(tdq);
188797e9382dSDon Lewis 	for (i = 1, cg = tdq->tdq_cg; ; ) {
188897e9382dSDon Lewis 		cpu = sched_highest(cg, mask, steal_thresh);
188997e9382dSDon Lewis 		/*
189097e9382dSDon Lewis 		 * If a thread was added while interrupts were disabled don't
189197e9382dSDon Lewis 		 * steal one here.
189297e9382dSDon Lewis 		 */
189397e9382dSDon Lewis 		if (tdq->tdq_load > 0) {
189497e9382dSDon Lewis 			TDQ_LOCK(tdq);
189597e9382dSDon Lewis 			break;
189697e9382dSDon Lewis 		}
189797e9382dSDon Lewis 		if (cpu == -1) {
189897e9382dSDon Lewis 			i++;
189997e9382dSDon Lewis 			cg = cg->cg_parent;
190097e9382dSDon Lewis 			if (cg == NULL || i > trysteal_limit) {
190197e9382dSDon Lewis 				TDQ_LOCK(tdq);
190297e9382dSDon Lewis 				break;
190397e9382dSDon Lewis 			}
190497e9382dSDon Lewis 			continue;
190597e9382dSDon Lewis 		}
190697e9382dSDon Lewis 		steal = TDQ_CPU(cpu);
190797e9382dSDon Lewis 		/*
190897e9382dSDon Lewis 		 * The data returned by sched_highest() is stale and
190997e9382dSDon Lewis                  * the chosen CPU no longer has an eligible thread.
191097e9382dSDon Lewis 		 */
191197e9382dSDon Lewis 		if (steal->tdq_load < steal_thresh ||
191297e9382dSDon Lewis 		    steal->tdq_transferable == 0)
191397e9382dSDon Lewis 			continue;
191497e9382dSDon Lewis 		tdq_lock_pair(tdq, steal);
191597e9382dSDon Lewis 		/*
191697e9382dSDon Lewis 		 * If we get to this point, unconditonally exit the loop
191797e9382dSDon Lewis 		 * to bound the time spent in the critcal section.
191897e9382dSDon Lewis 		 *
191997e9382dSDon Lewis 		 * If a thread was added while interrupts were disabled don't
192097e9382dSDon Lewis 		 * steal one here.
192197e9382dSDon Lewis 		 */
192297e9382dSDon Lewis 		if (tdq->tdq_load > 0) {
192397e9382dSDon Lewis 			TDQ_UNLOCK(steal);
192497e9382dSDon Lewis 			break;
192597e9382dSDon Lewis 		}
192697e9382dSDon Lewis 		/*
192797e9382dSDon Lewis 		 * The data returned by sched_highest() is stale and
192897e9382dSDon Lewis                  * the chosen CPU no longer has an eligible thread.
192997e9382dSDon Lewis 		 */
193097e9382dSDon Lewis 		if (steal->tdq_load < steal_thresh ||
193197e9382dSDon Lewis 		    steal->tdq_transferable == 0) {
193297e9382dSDon Lewis 			TDQ_UNLOCK(steal);
193397e9382dSDon Lewis 			break;
193497e9382dSDon Lewis 		}
193597e9382dSDon Lewis 		/*
193697e9382dSDon Lewis 		 * If we fail to acquire one due to affinity restrictions,
193797e9382dSDon Lewis 		 * bail out and let the idle thread to a more complete search
193897e9382dSDon Lewis 		 * outside of a critical section.
193997e9382dSDon Lewis 		 */
194097e9382dSDon Lewis 		if (tdq_move(steal, tdq) == NULL) {
194197e9382dSDon Lewis 			TDQ_UNLOCK(steal);
194297e9382dSDon Lewis 			break;
194397e9382dSDon Lewis 		}
194497e9382dSDon Lewis 		TDQ_UNLOCK(steal);
194597e9382dSDon Lewis 		break;
194697e9382dSDon Lewis 	}
194797e9382dSDon Lewis 	spinlock_exit();
194897e9382dSDon Lewis }
19494c8a8cfcSKonstantin Belousov #endif
195097e9382dSDon Lewis 
195197e9382dSDon Lewis /*
1952c47f202bSJeff Roberson  * Handle migration from sched_switch().  This happens only for
1953c47f202bSJeff Roberson  * cpu binding.
1954c47f202bSJeff Roberson  */
1955c47f202bSJeff Roberson static struct mtx *
1956c47f202bSJeff Roberson sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1957c47f202bSJeff Roberson {
1958c47f202bSJeff Roberson 	struct tdq *tdn;
1959c47f202bSJeff Roberson 
1960efe67753SNathan Whitehorn 	KASSERT(!CPU_ABSENT(td_get_sched(td)->ts_cpu), ("sched_switch_migrate: "
1961efe67753SNathan Whitehorn 	    "thread %s queued on absent CPU %d.", td->td_name,
1962efe67753SNathan Whitehorn 	    td_get_sched(td)->ts_cpu));
196393ccd6bfSKonstantin Belousov 	tdn = TDQ_CPU(td_get_sched(td)->ts_cpu);
1964c47f202bSJeff Roberson #ifdef SMP
19659727e637SJeff Roberson 	tdq_load_rem(tdq, td);
1966c47f202bSJeff Roberson 	/*
1967c47f202bSJeff Roberson 	 * Do the lock dance required to avoid LOR.  We grab an extra
1968c47f202bSJeff Roberson 	 * spinlock nesting to prevent preemption while we're
1969c47f202bSJeff Roberson 	 * not holding either run-queue lock.
1970c47f202bSJeff Roberson 	 */
1971c47f202bSJeff Roberson 	spinlock_enter();
1972b0b9dee5SAttilio Rao 	thread_lock_block(td);	/* This releases the lock on tdq. */
1973435068aaSAttilio Rao 
1974435068aaSAttilio Rao 	/*
1975435068aaSAttilio Rao 	 * Acquire both run-queue locks before placing the thread on the new
1976435068aaSAttilio Rao 	 * run-queue to avoid deadlocks created by placing a thread with a
1977435068aaSAttilio Rao 	 * blocked lock on the run-queue of a remote processor.  The deadlock
1978435068aaSAttilio Rao 	 * occurs when a third processor attempts to lock the two queues in
1979435068aaSAttilio Rao 	 * question while the target processor is spinning with its own
1980435068aaSAttilio Rao 	 * run-queue lock held while waiting for the blocked lock to clear.
1981435068aaSAttilio Rao 	 */
1982435068aaSAttilio Rao 	tdq_lock_pair(tdn, tdq);
1983c47f202bSJeff Roberson 	tdq_add(tdn, td, flags);
198427ee18adSRyan Stone 	tdq_notify(tdn, td);
1985c47f202bSJeff Roberson 	TDQ_UNLOCK(tdn);
1986c47f202bSJeff Roberson 	spinlock_exit();
1987c47f202bSJeff Roberson #endif
1988c47f202bSJeff Roberson 	return (TDQ_LOCKPTR(tdn));
1989c47f202bSJeff Roberson }
1990c47f202bSJeff Roberson 
1991c47f202bSJeff Roberson /*
1992b0b9dee5SAttilio Rao  * Variadic version of thread_lock_unblock() that does not assume td_lock
1993b0b9dee5SAttilio Rao  * is blocked.
1994ae7a6b38SJeff Roberson  */
1995ae7a6b38SJeff Roberson static inline void
1996ae7a6b38SJeff Roberson thread_unblock_switch(struct thread *td, struct mtx *mtx)
1997ae7a6b38SJeff Roberson {
1998ae7a6b38SJeff Roberson 	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1999ae7a6b38SJeff Roberson 	    (uintptr_t)mtx);
2000ae7a6b38SJeff Roberson }
2001ae7a6b38SJeff Roberson 
2002ae7a6b38SJeff Roberson /*
2003ae7a6b38SJeff Roberson  * Switch threads.  This function has to handle threads coming in while
2004ae7a6b38SJeff Roberson  * blocked for some reason, running, or idle.  It also must deal with
2005ae7a6b38SJeff Roberson  * migrating a thread from one queue to another as running threads may
2006ae7a6b38SJeff Roberson  * be assigned elsewhere via binding.
2007ae7a6b38SJeff Roberson  */
20083db720fdSDavid Xu void
20093389af30SJulian Elischer sched_switch(struct thread *td, struct thread *newtd, int flags)
201035e6168fSJeff Roberson {
2011c02bbb43SJeff Roberson 	struct tdq *tdq;
2012ad1e7d28SJulian Elischer 	struct td_sched *ts;
2013ae7a6b38SJeff Roberson 	struct mtx *mtx;
2014c47f202bSJeff Roberson 	int srqflag;
20153d7f4117SAlexander Motin 	int cpuid, preempted;
201635e6168fSJeff Roberson 
20177b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
20186d55b3ecSJeff Roberson 	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
201935e6168fSJeff Roberson 
2020ae7a6b38SJeff Roberson 	cpuid = PCPU_GET(cpuid);
2021ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpuid);
202293ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
2023c47f202bSJeff Roberson 	mtx = td->td_lock;
20247295465eSAlexander Motin 	sched_pctcpu_update(ts, 1);
2025ae7a6b38SJeff Roberson 	ts->ts_rltick = ticks;
2026060563ecSJulian Elischer 	td->td_lastcpu = td->td_oncpu;
2027060563ecSJulian Elischer 	td->td_oncpu = NOCPU;
2028ad9dadc4SAndriy Gapon 	preempted = (td->td_flags & TDF_SLICEEND) == 0 &&
2029ad9dadc4SAndriy Gapon 	    (flags & SW_PREEMPT) != 0;
20303d7f4117SAlexander Motin 	td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
203177918643SStephan Uphoff 	td->td_owepreempt = 0;
20322c27cb3aSAlexander Motin 	if (!TD_IS_IDLETHREAD(td))
20331690c6c1SJeff Roberson 		tdq->tdq_switchcnt++;
2034b11fdad0SJeff Roberson 	/*
2035ae7a6b38SJeff Roberson 	 * The lock pointer in an idle thread should never change.  Reset it
2036ae7a6b38SJeff Roberson 	 * to CAN_RUN as well.
2037b11fdad0SJeff Roberson 	 */
2038486a9414SJulian Elischer 	if (TD_IS_IDLETHREAD(td)) {
2039ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2040bf0acc27SJohn Baldwin 		TD_SET_CAN_RUN(td);
20417b20fb19SJeff Roberson 	} else if (TD_IS_RUNNING(td)) {
2042ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
20433d7f4117SAlexander Motin 		srqflag = preempted ?
2044598b368dSJeff Roberson 		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
2045c47f202bSJeff Roberson 		    SRQ_OURSELF|SRQ_YIELDING;
2046ba4932b5SMatthew D Fleming #ifdef SMP
20470f7a0ebdSMatthew D Fleming 		if (THREAD_CAN_MIGRATE(td) && !THREAD_CAN_SCHED(td, ts->ts_cpu))
20480f7a0ebdSMatthew D Fleming 			ts->ts_cpu = sched_pickcpu(td, 0);
2049ba4932b5SMatthew D Fleming #endif
2050c47f202bSJeff Roberson 		if (ts->ts_cpu == cpuid)
20519727e637SJeff Roberson 			tdq_runq_add(tdq, td, srqflag);
20520f7a0ebdSMatthew D Fleming 		else {
20530f7a0ebdSMatthew D Fleming 			KASSERT(THREAD_CAN_MIGRATE(td) ||
20540f7a0ebdSMatthew D Fleming 			    (ts->ts_flags & TSF_BOUND) != 0,
20550f7a0ebdSMatthew D Fleming 			    ("Thread %p shouldn't migrate", td));
2056c47f202bSJeff Roberson 			mtx = sched_switch_migrate(tdq, td, srqflag);
20570f7a0ebdSMatthew D Fleming 		}
2058ae7a6b38SJeff Roberson 	} else {
2059ae7a6b38SJeff Roberson 		/* This thread must be going to sleep. */
2060ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
2061b0b9dee5SAttilio Rao 		mtx = thread_lock_block(td);
20629727e637SJeff Roberson 		tdq_load_rem(tdq, td);
20634c8a8cfcSKonstantin Belousov #ifdef SMP
206497e9382dSDon Lewis 		if (tdq->tdq_load == 0)
206597e9382dSDon Lewis 			tdq_trysteal(tdq);
20664c8a8cfcSKonstantin Belousov #endif
2067ae7a6b38SJeff Roberson 	}
2068afa0a46cSAndriy Gapon 
2069afa0a46cSAndriy Gapon #if (KTR_COMPILE & KTR_SCHED) != 0
2070afa0a46cSAndriy Gapon 	if (TD_IS_IDLETHREAD(td))
2071afa0a46cSAndriy Gapon 		KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle",
2072afa0a46cSAndriy Gapon 		    "prio:%d", td->td_priority);
2073afa0a46cSAndriy Gapon 	else
2074afa0a46cSAndriy Gapon 		KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td),
2075afa0a46cSAndriy Gapon 		    "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg,
2076afa0a46cSAndriy Gapon 		    "lockname:\"%s\"", td->td_lockname);
2077afa0a46cSAndriy Gapon #endif
2078afa0a46cSAndriy Gapon 
2079ae7a6b38SJeff Roberson 	/*
2080ae7a6b38SJeff Roberson 	 * We enter here with the thread blocked and assigned to the
2081ae7a6b38SJeff Roberson 	 * appropriate cpu run-queue or sleep-queue and with the current
2082ae7a6b38SJeff Roberson 	 * thread-queue locked.
2083ae7a6b38SJeff Roberson 	 */
2084ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
20852454aaf5SJeff Roberson 	newtd = choosethread();
2086ae7a6b38SJeff Roberson 	/*
2087ae7a6b38SJeff Roberson 	 * Call the MD code to switch contexts if necessary.
2088ae7a6b38SJeff Roberson 	 */
2089ebccf1e3SJoseph Koshy 	if (td != newtd) {
2090ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
2091ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
2092ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
2093ebccf1e3SJoseph Koshy #endif
2094d9fae5abSAndriy Gapon 		SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
2095eea4f254SJeff Roberson 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
209659c68134SJeff Roberson 		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
209793ccd6bfSKonstantin Belousov 		sched_pctcpu_update(td_get_sched(newtd), 0);
20986f5f25e5SJohn Birrell 
20996f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
21006f5f25e5SJohn Birrell 		/*
21016f5f25e5SJohn Birrell 		 * If DTrace has set the active vtime enum to anything
21026f5f25e5SJohn Birrell 		 * other than INACTIVE (0), then it should have set the
21036f5f25e5SJohn Birrell 		 * function to call.
21046f5f25e5SJohn Birrell 		 */
21056f5f25e5SJohn Birrell 		if (dtrace_vtime_active)
21066f5f25e5SJohn Birrell 			(*dtrace_vtime_switch_func)(newtd);
21076f5f25e5SJohn Birrell #endif
21086f5f25e5SJohn Birrell 
2109ae7a6b38SJeff Roberson 		cpu_switch(td, newtd, mtx);
2110ae7a6b38SJeff Roberson 		/*
2111ae7a6b38SJeff Roberson 		 * We may return from cpu_switch on a different cpu.  However,
2112ae7a6b38SJeff Roberson 		 * we always return with td_lock pointing to the current cpu's
2113ae7a6b38SJeff Roberson 		 * run queue lock.
2114ae7a6b38SJeff Roberson 		 */
2115ae7a6b38SJeff Roberson 		cpuid = PCPU_GET(cpuid);
2116ae7a6b38SJeff Roberson 		tdq = TDQ_CPU(cpuid);
2117eea4f254SJeff Roberson 		lock_profile_obtain_lock_success(
2118eea4f254SJeff Roberson 		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2119b3e9e682SRyan Stone 
2120d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , on__cpu);
2121ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
2122ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
2123ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
2124ebccf1e3SJoseph Koshy #endif
2125b3e9e682SRyan Stone 	} else {
2126ae7a6b38SJeff Roberson 		thread_unblock_switch(td, mtx);
2127d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , remain__cpu);
2128b3e9e682SRyan Stone 	}
2129afa0a46cSAndriy Gapon 
2130afa0a46cSAndriy Gapon 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
2131afa0a46cSAndriy Gapon 	    "prio:%d", td->td_priority);
2132afa0a46cSAndriy Gapon 
2133ae7a6b38SJeff Roberson 	/*
2134ae7a6b38SJeff Roberson 	 * Assert that all went well and return.
2135ae7a6b38SJeff Roberson 	 */
2136ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
2137ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2138ae7a6b38SJeff Roberson 	td->td_oncpu = cpuid;
213935e6168fSJeff Roberson }
214035e6168fSJeff Roberson 
2141ae7a6b38SJeff Roberson /*
2142ae7a6b38SJeff Roberson  * Adjust thread priorities as a result of a nice request.
2143ae7a6b38SJeff Roberson  */
214435e6168fSJeff Roberson void
2145fa885116SJulian Elischer sched_nice(struct proc *p, int nice)
214635e6168fSJeff Roberson {
214735e6168fSJeff Roberson 	struct thread *td;
214835e6168fSJeff Roberson 
2149fa885116SJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
2150e7d50326SJeff Roberson 
2151fa885116SJulian Elischer 	p->p_nice = nice;
21528460a577SJohn Birrell 	FOREACH_THREAD_IN_PROC(p, td) {
21537b20fb19SJeff Roberson 		thread_lock(td);
21548460a577SJohn Birrell 		sched_priority(td);
2155e7d50326SJeff Roberson 		sched_prio(td, td->td_base_user_pri);
21567b20fb19SJeff Roberson 		thread_unlock(td);
215735e6168fSJeff Roberson 	}
2158fa885116SJulian Elischer }
215935e6168fSJeff Roberson 
2160ae7a6b38SJeff Roberson /*
2161ae7a6b38SJeff Roberson  * Record the sleep time for the interactivity scorer.
2162ae7a6b38SJeff Roberson  */
216335e6168fSJeff Roberson void
2164c5aa6b58SJeff Roberson sched_sleep(struct thread *td, int prio)
216535e6168fSJeff Roberson {
2166e7d50326SJeff Roberson 
21677b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
216835e6168fSJeff Roberson 
216954b0e65fSJeff Roberson 	td->td_slptick = ticks;
217017c4c356SKonstantin Belousov 	if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
2171c5aa6b58SJeff Roberson 		td->td_flags |= TDF_CANSWAP;
21722dc29adbSJohn Baldwin 	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
21732dc29adbSJohn Baldwin 		return;
21740502fe2eSJeff Roberson 	if (static_boost == 1 && prio)
2175c5aa6b58SJeff Roberson 		sched_prio(td, prio);
21760502fe2eSJeff Roberson 	else if (static_boost && td->td_priority > static_boost)
21770502fe2eSJeff Roberson 		sched_prio(td, static_boost);
217835e6168fSJeff Roberson }
217935e6168fSJeff Roberson 
2180ae7a6b38SJeff Roberson /*
2181ae7a6b38SJeff Roberson  * Schedule a thread to resume execution and record how long it voluntarily
2182ae7a6b38SJeff Roberson  * slept.  We also update the pctcpu, interactivity, and priority.
2183ae7a6b38SJeff Roberson  */
218435e6168fSJeff Roberson void
218535e6168fSJeff Roberson sched_wakeup(struct thread *td)
218635e6168fSJeff Roberson {
218714618990SJeff Roberson 	struct td_sched *ts;
2188ae7a6b38SJeff Roberson 	int slptick;
2189e7d50326SJeff Roberson 
21907b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
219193ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
2192c5aa6b58SJeff Roberson 	td->td_flags &= ~TDF_CANSWAP;
219335e6168fSJeff Roberson 	/*
2194e7d50326SJeff Roberson 	 * If we slept for more than a tick update our interactivity and
2195e7d50326SJeff Roberson 	 * priority.
219635e6168fSJeff Roberson 	 */
219754b0e65fSJeff Roberson 	slptick = td->td_slptick;
219854b0e65fSJeff Roberson 	td->td_slptick = 0;
2199ae7a6b38SJeff Roberson 	if (slptick && slptick != ticks) {
22007295465eSAlexander Motin 		ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
22018460a577SJohn Birrell 		sched_interact_update(td);
22027295465eSAlexander Motin 		sched_pctcpu_update(ts, 0);
2203f1e8dc4aSJeff Roberson 	}
22045e5c3873SJeff Roberson 	/*
22055e5c3873SJeff Roberson 	 * Reset the slice value since we slept and advanced the round-robin.
22065e5c3873SJeff Roberson 	 */
22075e5c3873SJeff Roberson 	ts->ts_slice = 0;
22087a5e5e2aSJeff Roberson 	sched_add(td, SRQ_BORING);
220935e6168fSJeff Roberson }
221035e6168fSJeff Roberson 
221135e6168fSJeff Roberson /*
221235e6168fSJeff Roberson  * Penalize the parent for creating a new child and initialize the child's
221335e6168fSJeff Roberson  * priority.
221435e6168fSJeff Roberson  */
221535e6168fSJeff Roberson void
22168460a577SJohn Birrell sched_fork(struct thread *td, struct thread *child)
221715dc847eSJeff Roberson {
22187b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
221993ccd6bfSKonstantin Belousov 	sched_pctcpu_update(td_get_sched(td), 1);
2220ad1e7d28SJulian Elischer 	sched_fork_thread(td, child);
2221e7d50326SJeff Roberson 	/*
2222e7d50326SJeff Roberson 	 * Penalize the parent and child for forking.
2223e7d50326SJeff Roberson 	 */
2224e7d50326SJeff Roberson 	sched_interact_fork(child);
2225e7d50326SJeff Roberson 	sched_priority(child);
222693ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_runtime += tickincr;
2227e7d50326SJeff Roberson 	sched_interact_update(td);
2228e7d50326SJeff Roberson 	sched_priority(td);
2229ad1e7d28SJulian Elischer }
2230ad1e7d28SJulian Elischer 
2231ae7a6b38SJeff Roberson /*
2232ae7a6b38SJeff Roberson  * Fork a new thread, may be within the same process.
2233ae7a6b38SJeff Roberson  */
2234ad1e7d28SJulian Elischer void
2235ad1e7d28SJulian Elischer sched_fork_thread(struct thread *td, struct thread *child)
2236ad1e7d28SJulian Elischer {
2237ad1e7d28SJulian Elischer 	struct td_sched *ts;
2238ad1e7d28SJulian Elischer 	struct td_sched *ts2;
22395e5c3873SJeff Roberson 	struct tdq *tdq;
22408460a577SJohn Birrell 
22415e5c3873SJeff Roberson 	tdq = TDQ_SELF();
22428b16c208SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2243e7d50326SJeff Roberson 	/*
2244e7d50326SJeff Roberson 	 * Initialize child.
2245e7d50326SJeff Roberson 	 */
224693ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
224793ccd6bfSKonstantin Belousov 	ts2 = td_get_sched(child);
224892de34dfSJohn Baldwin 	child->td_oncpu = NOCPU;
224992de34dfSJohn Baldwin 	child->td_lastcpu = NOCPU;
22505e5c3873SJeff Roberson 	child->td_lock = TDQ_LOCKPTR(tdq);
22518b16c208SJeff Roberson 	child->td_cpuset = cpuset_ref(td->td_cpuset);
22523f289c3fSJeff Roberson 	child->td_domain.dr_policy = td->td_cpuset->cs_domain;
2253ad1e7d28SJulian Elischer 	ts2->ts_cpu = ts->ts_cpu;
22548b16c208SJeff Roberson 	ts2->ts_flags = 0;
2255e7d50326SJeff Roberson 	/*
225622d19207SJohn Baldwin 	 * Grab our parents cpu estimation information.
2257e7d50326SJeff Roberson 	 */
2258ad1e7d28SJulian Elischer 	ts2->ts_ticks = ts->ts_ticks;
2259ad1e7d28SJulian Elischer 	ts2->ts_ltick = ts->ts_ltick;
2260ad1e7d28SJulian Elischer 	ts2->ts_ftick = ts->ts_ftick;
226122d19207SJohn Baldwin 	/*
226222d19207SJohn Baldwin 	 * Do not inherit any borrowed priority from the parent.
226322d19207SJohn Baldwin 	 */
226422d19207SJohn Baldwin 	child->td_priority = child->td_base_pri;
2265e7d50326SJeff Roberson 	/*
2266e7d50326SJeff Roberson 	 * And update interactivity score.
2267e7d50326SJeff Roberson 	 */
2268ae7a6b38SJeff Roberson 	ts2->ts_slptime = ts->ts_slptime;
2269ae7a6b38SJeff Roberson 	ts2->ts_runtime = ts->ts_runtime;
22705e5c3873SJeff Roberson 	/* Attempt to quickly learn interactivity. */
22715e5c3873SJeff Roberson 	ts2->ts_slice = tdq_slice(tdq) - sched_slice_min;
22728f51ad55SJeff Roberson #ifdef KTR
22738f51ad55SJeff Roberson 	bzero(ts2->ts_name, sizeof(ts2->ts_name));
22748f51ad55SJeff Roberson #endif
227515dc847eSJeff Roberson }
227615dc847eSJeff Roberson 
2277ae7a6b38SJeff Roberson /*
2278ae7a6b38SJeff Roberson  * Adjust the priority class of a thread.
2279ae7a6b38SJeff Roberson  */
228015dc847eSJeff Roberson void
22818460a577SJohn Birrell sched_class(struct thread *td, int class)
228215dc847eSJeff Roberson {
228315dc847eSJeff Roberson 
22847b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
22858460a577SJohn Birrell 	if (td->td_pri_class == class)
228615dc847eSJeff Roberson 		return;
22878460a577SJohn Birrell 	td->td_pri_class = class;
228835e6168fSJeff Roberson }
228935e6168fSJeff Roberson 
229035e6168fSJeff Roberson /*
229135e6168fSJeff Roberson  * Return some of the child's priority and interactivity to the parent.
229235e6168fSJeff Roberson  */
229335e6168fSJeff Roberson void
2294fc6c30f6SJulian Elischer sched_exit(struct proc *p, struct thread *child)
229535e6168fSJeff Roberson {
2296e7d50326SJeff Roberson 	struct thread *td;
2297141ad61cSJeff Roberson 
22988f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2299cd39bb09SXin LI 	    "prio:%d", child->td_priority);
2300374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
2301e7d50326SJeff Roberson 	td = FIRST_THREAD_IN_PROC(p);
2302e7d50326SJeff Roberson 	sched_exit_thread(td, child);
2303ad1e7d28SJulian Elischer }
2304ad1e7d28SJulian Elischer 
2305ae7a6b38SJeff Roberson /*
2306ae7a6b38SJeff Roberson  * Penalize another thread for the time spent on this one.  This helps to
2307ae7a6b38SJeff Roberson  * worsen the priority and interactivity of processes which schedule batch
2308ae7a6b38SJeff Roberson  * jobs such as make.  This has little effect on the make process itself but
2309ae7a6b38SJeff Roberson  * causes new processes spawned by it to receive worse scores immediately.
2310ae7a6b38SJeff Roberson  */
2311ad1e7d28SJulian Elischer void
2312fc6c30f6SJulian Elischer sched_exit_thread(struct thread *td, struct thread *child)
2313ad1e7d28SJulian Elischer {
2314fc6c30f6SJulian Elischer 
23158f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2316cd39bb09SXin LI 	    "prio:%d", child->td_priority);
2317e7d50326SJeff Roberson 	/*
2318e7d50326SJeff Roberson 	 * Give the child's runtime to the parent without returning the
2319e7d50326SJeff Roberson 	 * sleep time as a penalty to the parent.  This causes shells that
2320e7d50326SJeff Roberson 	 * launch expensive things to mark their children as expensive.
2321e7d50326SJeff Roberson 	 */
23227b20fb19SJeff Roberson 	thread_lock(td);
232393ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_runtime += td_get_sched(child)->ts_runtime;
2324fc6c30f6SJulian Elischer 	sched_interact_update(td);
2325e7d50326SJeff Roberson 	sched_priority(td);
23267b20fb19SJeff Roberson 	thread_unlock(td);
2327ad1e7d28SJulian Elischer }
2328ad1e7d28SJulian Elischer 
2329ff256d9cSJeff Roberson void
2330ff256d9cSJeff Roberson sched_preempt(struct thread *td)
2331ff256d9cSJeff Roberson {
2332ff256d9cSJeff Roberson 	struct tdq *tdq;
2333ff256d9cSJeff Roberson 
2334b3e9e682SRyan Stone 	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
2335b3e9e682SRyan Stone 
2336ff256d9cSJeff Roberson 	thread_lock(td);
2337ff256d9cSJeff Roberson 	tdq = TDQ_SELF();
2338ff256d9cSJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2339ff256d9cSJeff Roberson 	tdq->tdq_ipipending = 0;
2340ff256d9cSJeff Roberson 	if (td->td_priority > tdq->tdq_lowpri) {
23418df78c41SJeff Roberson 		int flags;
23428df78c41SJeff Roberson 
23438df78c41SJeff Roberson 		flags = SW_INVOL | SW_PREEMPT;
2344ff256d9cSJeff Roberson 		if (td->td_critnest > 1)
2345ff256d9cSJeff Roberson 			td->td_owepreempt = 1;
23468df78c41SJeff Roberson 		else if (TD_IS_IDLETHREAD(td))
23478df78c41SJeff Roberson 			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2348ff256d9cSJeff Roberson 		else
23498df78c41SJeff Roberson 			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2350ff256d9cSJeff Roberson 	}
2351ff256d9cSJeff Roberson 	thread_unlock(td);
2352ff256d9cSJeff Roberson }
2353ff256d9cSJeff Roberson 
2354ae7a6b38SJeff Roberson /*
2355ae7a6b38SJeff Roberson  * Fix priorities on return to user-space.  Priorities may be elevated due
2356ae7a6b38SJeff Roberson  * to static priorities in msleep() or similar.
2357ae7a6b38SJeff Roberson  */
2358ad1e7d28SJulian Elischer void
2359*28240885SMateusz Guzik sched_userret_slowpath(struct thread *td)
2360ad1e7d28SJulian Elischer {
2361*28240885SMateusz Guzik 
23627b20fb19SJeff Roberson 	thread_lock(td);
2363ad1e7d28SJulian Elischer 	td->td_priority = td->td_user_pri;
2364ad1e7d28SJulian Elischer 	td->td_base_pri = td->td_user_pri;
236562fa74d9SJeff Roberson 	tdq_setlowpri(TDQ_SELF(), td);
23667b20fb19SJeff Roberson 	thread_unlock(td);
2367ad1e7d28SJulian Elischer }
236835e6168fSJeff Roberson 
2369ae7a6b38SJeff Roberson /*
2370ae7a6b38SJeff Roberson  * Handle a stathz tick.  This is really only relevant for timeshare
2371ae7a6b38SJeff Roberson  * threads.
2372ae7a6b38SJeff Roberson  */
237335e6168fSJeff Roberson void
23747cf90fb3SJeff Roberson sched_clock(struct thread *td)
237535e6168fSJeff Roberson {
2376ad1e7d28SJulian Elischer 	struct tdq *tdq;
2377ad1e7d28SJulian Elischer 	struct td_sched *ts;
237835e6168fSJeff Roberson 
2379ae7a6b38SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
23803f872f85SJeff Roberson 	tdq = TDQ_SELF();
23817fcf154aSJeff Roberson #ifdef SMP
23827fcf154aSJeff Roberson 	/*
23837fcf154aSJeff Roberson 	 * We run the long term load balancer infrequently on the first cpu.
23847fcf154aSJeff Roberson 	 */
23857fcf154aSJeff Roberson 	if (balance_tdq == tdq) {
23867fcf154aSJeff Roberson 		if (balance_ticks && --balance_ticks == 0)
23877fcf154aSJeff Roberson 			sched_balance();
23887fcf154aSJeff Roberson 	}
23897fcf154aSJeff Roberson #endif
23903f872f85SJeff Roberson 	/*
23911690c6c1SJeff Roberson 	 * Save the old switch count so we have a record of the last ticks
23921690c6c1SJeff Roberson 	 * activity.   Initialize the new switch count based on our load.
23931690c6c1SJeff Roberson 	 * If there is some activity seed it to reflect that.
23941690c6c1SJeff Roberson 	 */
23951690c6c1SJeff Roberson 	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
23966c47aaaeSJeff Roberson 	tdq->tdq_switchcnt = tdq->tdq_load;
23971690c6c1SJeff Roberson 	/*
23983f872f85SJeff Roberson 	 * Advance the insert index once for each tick to ensure that all
23993f872f85SJeff Roberson 	 * threads get a chance to run.
24003f872f85SJeff Roberson 	 */
24013f872f85SJeff Roberson 	if (tdq->tdq_idx == tdq->tdq_ridx) {
24023f872f85SJeff Roberson 		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
24033f872f85SJeff Roberson 		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
24043f872f85SJeff Roberson 			tdq->tdq_ridx = tdq->tdq_idx;
24053f872f85SJeff Roberson 	}
240693ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
24077295465eSAlexander Motin 	sched_pctcpu_update(ts, 1);
2408fd0b8c78SJeff Roberson 	if (td->td_pri_class & PRI_FIFO_BIT)
2409a8949de2SJeff Roberson 		return;
2410c9a8cba4SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2411a8949de2SJeff Roberson 		/*
2412fd0b8c78SJeff Roberson 		 * We used a tick; charge it to the thread so
2413fd0b8c78SJeff Roberson 		 * that we can compute our interactivity.
241415dc847eSJeff Roberson 		 */
241593ccd6bfSKonstantin Belousov 		td_get_sched(td)->ts_runtime += tickincr;
24168460a577SJohn Birrell 		sched_interact_update(td);
241773daf66fSJeff Roberson 		sched_priority(td);
2418fd0b8c78SJeff Roberson 	}
2419579895dfSAlexander Motin 
242035e6168fSJeff Roberson 	/*
2421579895dfSAlexander Motin 	 * Force a context switch if the current thread has used up a full
2422579895dfSAlexander Motin 	 * time slice (default is 100ms).
242335e6168fSJeff Roberson 	 */
24245e5c3873SJeff Roberson 	if (!TD_IS_IDLETHREAD(td) && ++ts->ts_slice >= tdq_slice(tdq)) {
24255e5c3873SJeff Roberson 		ts->ts_slice = 0;
24263d7f4117SAlexander Motin 		td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
242735e6168fSJeff Roberson 	}
2428579895dfSAlexander Motin }
242935e6168fSJeff Roberson 
2430ccd0ec40SKonstantin Belousov u_int
2431ccd0ec40SKonstantin Belousov sched_estcpu(struct thread *td __unused)
2432ae7a6b38SJeff Roberson {
2433ae7a6b38SJeff Roberson 
2434ccd0ec40SKonstantin Belousov 	return (0);
2435ae7a6b38SJeff Roberson }
2436ae7a6b38SJeff Roberson 
2437ae7a6b38SJeff Roberson /*
2438ae7a6b38SJeff Roberson  * Return whether the current CPU has runnable tasks.  Used for in-kernel
2439ae7a6b38SJeff Roberson  * cooperative idle threads.
2440ae7a6b38SJeff Roberson  */
244135e6168fSJeff Roberson int
244235e6168fSJeff Roberson sched_runnable(void)
244335e6168fSJeff Roberson {
2444ad1e7d28SJulian Elischer 	struct tdq *tdq;
2445b90816f1SJeff Roberson 	int load;
244635e6168fSJeff Roberson 
2447b90816f1SJeff Roberson 	load = 1;
2448b90816f1SJeff Roberson 
2449ad1e7d28SJulian Elischer 	tdq = TDQ_SELF();
24503f741ca1SJeff Roberson 	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2451d2ad694cSJeff Roberson 		if (tdq->tdq_load > 0)
24523f741ca1SJeff Roberson 			goto out;
24533f741ca1SJeff Roberson 	} else
2454d2ad694cSJeff Roberson 		if (tdq->tdq_load - 1 > 0)
2455b90816f1SJeff Roberson 			goto out;
2456b90816f1SJeff Roberson 	load = 0;
2457b90816f1SJeff Roberson out:
2458b90816f1SJeff Roberson 	return (load);
245935e6168fSJeff Roberson }
246035e6168fSJeff Roberson 
2461ae7a6b38SJeff Roberson /*
2462ae7a6b38SJeff Roberson  * Choose the highest priority thread to run.  The thread is removed from
2463ae7a6b38SJeff Roberson  * the run-queue while running however the load remains.  For SMP we set
2464ae7a6b38SJeff Roberson  * the tdq in the global idle bitmask if it idles here.
2465ae7a6b38SJeff Roberson  */
24667a5e5e2aSJeff Roberson struct thread *
2467c9f25d8fSJeff Roberson sched_choose(void)
2468c9f25d8fSJeff Roberson {
24699727e637SJeff Roberson 	struct thread *td;
2470ae7a6b38SJeff Roberson 	struct tdq *tdq;
2471ae7a6b38SJeff Roberson 
2472ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2473ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
24749727e637SJeff Roberson 	td = tdq_choose(tdq);
24759727e637SJeff Roberson 	if (td) {
24769727e637SJeff Roberson 		tdq_runq_rem(tdq, td);
24770502fe2eSJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
24789727e637SJeff Roberson 		return (td);
247935e6168fSJeff Roberson 	}
24800502fe2eSJeff Roberson 	tdq->tdq_lowpri = PRI_MAX_IDLE;
248162fa74d9SJeff Roberson 	return (PCPU_GET(idlethread));
24827a5e5e2aSJeff Roberson }
24837a5e5e2aSJeff Roberson 
2484ae7a6b38SJeff Roberson /*
2485ae7a6b38SJeff Roberson  * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2486ae7a6b38SJeff Roberson  * we always request it once we exit a critical section.
2487ae7a6b38SJeff Roberson  */
2488ae7a6b38SJeff Roberson static inline void
2489ae7a6b38SJeff Roberson sched_setpreempt(struct thread *td)
24907a5e5e2aSJeff Roberson {
24917a5e5e2aSJeff Roberson 	struct thread *ctd;
24927a5e5e2aSJeff Roberson 	int cpri;
24937a5e5e2aSJeff Roberson 	int pri;
24947a5e5e2aSJeff Roberson 
2495ff256d9cSJeff Roberson 	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2496ff256d9cSJeff Roberson 
24977a5e5e2aSJeff Roberson 	ctd = curthread;
24987a5e5e2aSJeff Roberson 	pri = td->td_priority;
24997a5e5e2aSJeff Roberson 	cpri = ctd->td_priority;
2500ff256d9cSJeff Roberson 	if (pri < cpri)
2501ff256d9cSJeff Roberson 		ctd->td_flags |= TDF_NEEDRESCHED;
25027a5e5e2aSJeff Roberson 	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2503ae7a6b38SJeff Roberson 		return;
2504ff256d9cSJeff Roberson 	if (!sched_shouldpreempt(pri, cpri, 0))
2505ae7a6b38SJeff Roberson 		return;
25067a5e5e2aSJeff Roberson 	ctd->td_owepreempt = 1;
250735e6168fSJeff Roberson }
250835e6168fSJeff Roberson 
2509ae7a6b38SJeff Roberson /*
251073daf66fSJeff Roberson  * Add a thread to a thread queue.  Select the appropriate runq and add the
251173daf66fSJeff Roberson  * thread to it.  This is the internal function called when the tdq is
251273daf66fSJeff Roberson  * predetermined.
2513ae7a6b38SJeff Roberson  */
251435e6168fSJeff Roberson void
2515ae7a6b38SJeff Roberson tdq_add(struct tdq *tdq, struct thread *td, int flags)
251635e6168fSJeff Roberson {
2517c9f25d8fSJeff Roberson 
2518ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
25197a5e5e2aSJeff Roberson 	KASSERT((td->td_inhibitors == 0),
25207a5e5e2aSJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
25217a5e5e2aSJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
25227a5e5e2aSJeff Roberson 	    ("sched_add: bad thread state"));
2523b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
2524b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
2525ae7a6b38SJeff Roberson 
2526ae7a6b38SJeff Roberson 	if (td->td_priority < tdq->tdq_lowpri)
2527ae7a6b38SJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
25289727e637SJeff Roberson 	tdq_runq_add(tdq, td, flags);
25299727e637SJeff Roberson 	tdq_load_add(tdq, td);
2530ae7a6b38SJeff Roberson }
2531ae7a6b38SJeff Roberson 
2532ae7a6b38SJeff Roberson /*
2533ae7a6b38SJeff Roberson  * Select the target thread queue and add a thread to it.  Request
2534ae7a6b38SJeff Roberson  * preemption or IPI a remote processor if required.
2535ae7a6b38SJeff Roberson  */
2536ae7a6b38SJeff Roberson void
2537ae7a6b38SJeff Roberson sched_add(struct thread *td, int flags)
2538ae7a6b38SJeff Roberson {
2539ae7a6b38SJeff Roberson 	struct tdq *tdq;
25407b8bfa0dSJeff Roberson #ifdef SMP
2541ae7a6b38SJeff Roberson 	int cpu;
2542ae7a6b38SJeff Roberson #endif
25438f51ad55SJeff Roberson 
25448f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
25458f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
25468f51ad55SJeff Roberson 	    sched_tdname(curthread));
25478f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
25488f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
2549b3e9e682SRyan Stone 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
2550b3e9e682SRyan Stone 	    flags & SRQ_PREEMPTED);
2551ae7a6b38SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2552ae7a6b38SJeff Roberson 	/*
2553ae7a6b38SJeff Roberson 	 * Recalculate the priority before we select the target cpu or
2554ae7a6b38SJeff Roberson 	 * run-queue.
2555ae7a6b38SJeff Roberson 	 */
2556ae7a6b38SJeff Roberson 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2557ae7a6b38SJeff Roberson 		sched_priority(td);
2558ae7a6b38SJeff Roberson #ifdef SMP
2559ae7a6b38SJeff Roberson 	/*
2560ae7a6b38SJeff Roberson 	 * Pick the destination cpu and if it isn't ours transfer to the
2561ae7a6b38SJeff Roberson 	 * target cpu.
2562ae7a6b38SJeff Roberson 	 */
25639727e637SJeff Roberson 	cpu = sched_pickcpu(td, flags);
25649727e637SJeff Roberson 	tdq = sched_setcpu(td, cpu, flags);
2565ae7a6b38SJeff Roberson 	tdq_add(tdq, td, flags);
256673daf66fSJeff Roberson 	if (cpu != PCPU_GET(cpuid)) {
256727ee18adSRyan Stone 		tdq_notify(tdq, td);
25687b8bfa0dSJeff Roberson 		return;
25697b8bfa0dSJeff Roberson 	}
2570ae7a6b38SJeff Roberson #else
2571ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2572ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
2573ae7a6b38SJeff Roberson 	/*
2574ae7a6b38SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
2575ae7a6b38SJeff Roberson 	 * to the scheduler's lock.
2576ae7a6b38SJeff Roberson 	 */
2577ae7a6b38SJeff Roberson 	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2578ae7a6b38SJeff Roberson 	tdq_add(tdq, td, flags);
25797b8bfa0dSJeff Roberson #endif
2580ae7a6b38SJeff Roberson 	if (!(flags & SRQ_YIELDING))
2581ae7a6b38SJeff Roberson 		sched_setpreempt(td);
258235e6168fSJeff Roberson }
258335e6168fSJeff Roberson 
2584ae7a6b38SJeff Roberson /*
2585ae7a6b38SJeff Roberson  * Remove a thread from a run-queue without running it.  This is used
2586ae7a6b38SJeff Roberson  * when we're stealing a thread from a remote queue.  Otherwise all threads
2587ae7a6b38SJeff Roberson  * exit by calling sched_exit_thread() and sched_throw() themselves.
2588ae7a6b38SJeff Roberson  */
258935e6168fSJeff Roberson void
25907cf90fb3SJeff Roberson sched_rem(struct thread *td)
259135e6168fSJeff Roberson {
2592ad1e7d28SJulian Elischer 	struct tdq *tdq;
25937cf90fb3SJeff Roberson 
25948f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
25958f51ad55SJeff Roberson 	    "prio:%d", td->td_priority);
2596b3e9e682SRyan Stone 	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
259793ccd6bfSKonstantin Belousov 	tdq = TDQ_CPU(td_get_sched(td)->ts_cpu);
2598ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2599ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
26007a5e5e2aSJeff Roberson 	KASSERT(TD_ON_RUNQ(td),
2601ad1e7d28SJulian Elischer 	    ("sched_rem: thread not on run queue"));
26029727e637SJeff Roberson 	tdq_runq_rem(tdq, td);
26039727e637SJeff Roberson 	tdq_load_rem(tdq, td);
26047a5e5e2aSJeff Roberson 	TD_SET_CAN_RUN(td);
260562fa74d9SJeff Roberson 	if (td->td_priority == tdq->tdq_lowpri)
260662fa74d9SJeff Roberson 		tdq_setlowpri(tdq, NULL);
260735e6168fSJeff Roberson }
260835e6168fSJeff Roberson 
2609ae7a6b38SJeff Roberson /*
2610ae7a6b38SJeff Roberson  * Fetch cpu utilization information.  Updates on demand.
2611ae7a6b38SJeff Roberson  */
261235e6168fSJeff Roberson fixpt_t
26137cf90fb3SJeff Roberson sched_pctcpu(struct thread *td)
261435e6168fSJeff Roberson {
261535e6168fSJeff Roberson 	fixpt_t pctcpu;
2616ad1e7d28SJulian Elischer 	struct td_sched *ts;
261735e6168fSJeff Roberson 
261835e6168fSJeff Roberson 	pctcpu = 0;
261993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
262035e6168fSJeff Roberson 
26213da35a0aSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
26227295465eSAlexander Motin 	sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2623ad1e7d28SJulian Elischer 	if (ts->ts_ticks) {
262435e6168fSJeff Roberson 		int rtick;
262535e6168fSJeff Roberson 
262635e6168fSJeff Roberson 		/* How many rtick per second ? */
2627e7d50326SJeff Roberson 		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2628e7d50326SJeff Roberson 		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
262935e6168fSJeff Roberson 	}
263035e6168fSJeff Roberson 
263135e6168fSJeff Roberson 	return (pctcpu);
263235e6168fSJeff Roberson }
263335e6168fSJeff Roberson 
263462fa74d9SJeff Roberson /*
263562fa74d9SJeff Roberson  * Enforce affinity settings for a thread.  Called after adjustments to
263662fa74d9SJeff Roberson  * cpumask.
263762fa74d9SJeff Roberson  */
2638885d51a3SJeff Roberson void
2639885d51a3SJeff Roberson sched_affinity(struct thread *td)
2640885d51a3SJeff Roberson {
264162fa74d9SJeff Roberson #ifdef SMP
264262fa74d9SJeff Roberson 	struct td_sched *ts;
264362fa74d9SJeff Roberson 
264462fa74d9SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
264593ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
264662fa74d9SJeff Roberson 	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
264762fa74d9SJeff Roberson 		return;
264853a6c8b3SJeff Roberson 	if (TD_ON_RUNQ(td)) {
264953a6c8b3SJeff Roberson 		sched_rem(td);
265053a6c8b3SJeff Roberson 		sched_add(td, SRQ_BORING);
265153a6c8b3SJeff Roberson 		return;
265253a6c8b3SJeff Roberson 	}
265362fa74d9SJeff Roberson 	if (!TD_IS_RUNNING(td))
265462fa74d9SJeff Roberson 		return;
265562fa74d9SJeff Roberson 	/*
26560f7a0ebdSMatthew D Fleming 	 * Force a switch before returning to userspace.  If the
26570f7a0ebdSMatthew D Fleming 	 * target thread is not running locally send an ipi to force
26580f7a0ebdSMatthew D Fleming 	 * the issue.
265962fa74d9SJeff Roberson 	 */
2660a8103ae8SJohn Baldwin 	td->td_flags |= TDF_NEEDRESCHED;
26610f7a0ebdSMatthew D Fleming 	if (td != curthread)
26620f7a0ebdSMatthew D Fleming 		ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
266362fa74d9SJeff Roberson #endif
2664885d51a3SJeff Roberson }
2665885d51a3SJeff Roberson 
2666ae7a6b38SJeff Roberson /*
2667ae7a6b38SJeff Roberson  * Bind a thread to a target cpu.
2668ae7a6b38SJeff Roberson  */
26699bacd788SJeff Roberson void
26709bacd788SJeff Roberson sched_bind(struct thread *td, int cpu)
26719bacd788SJeff Roberson {
2672ad1e7d28SJulian Elischer 	struct td_sched *ts;
26739bacd788SJeff Roberson 
2674c47f202bSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
26751d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
267693ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
26776b2f763fSJeff Roberson 	if (ts->ts_flags & TSF_BOUND)
2678c95d2db2SJeff Roberson 		sched_unbind(td);
26790f7a0ebdSMatthew D Fleming 	KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2680ad1e7d28SJulian Elischer 	ts->ts_flags |= TSF_BOUND;
26816b2f763fSJeff Roberson 	sched_pin();
268280f86c9fSJeff Roberson 	if (PCPU_GET(cpuid) == cpu)
26839bacd788SJeff Roberson 		return;
26846b2f763fSJeff Roberson 	ts->ts_cpu = cpu;
26859bacd788SJeff Roberson 	/* When we return from mi_switch we'll be on the correct cpu. */
2686279f949eSPoul-Henning Kamp 	mi_switch(SW_VOL, NULL);
26879bacd788SJeff Roberson }
26889bacd788SJeff Roberson 
2689ae7a6b38SJeff Roberson /*
2690ae7a6b38SJeff Roberson  * Release a bound thread.
2691ae7a6b38SJeff Roberson  */
26929bacd788SJeff Roberson void
26939bacd788SJeff Roberson sched_unbind(struct thread *td)
26949bacd788SJeff Roberson {
2695e7d50326SJeff Roberson 	struct td_sched *ts;
2696e7d50326SJeff Roberson 
26977b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
26981d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
269993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
27006b2f763fSJeff Roberson 	if ((ts->ts_flags & TSF_BOUND) == 0)
27016b2f763fSJeff Roberson 		return;
2702e7d50326SJeff Roberson 	ts->ts_flags &= ~TSF_BOUND;
2703e7d50326SJeff Roberson 	sched_unpin();
27049bacd788SJeff Roberson }
27059bacd788SJeff Roberson 
270635e6168fSJeff Roberson int
2707ebccf1e3SJoseph Koshy sched_is_bound(struct thread *td)
2708ebccf1e3SJoseph Koshy {
27097b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
271093ccd6bfSKonstantin Belousov 	return (td_get_sched(td)->ts_flags & TSF_BOUND);
2711ebccf1e3SJoseph Koshy }
2712ebccf1e3SJoseph Koshy 
2713ae7a6b38SJeff Roberson /*
2714ae7a6b38SJeff Roberson  * Basic yield call.
2715ae7a6b38SJeff Roberson  */
271636ec198bSDavid Xu void
271736ec198bSDavid Xu sched_relinquish(struct thread *td)
271836ec198bSDavid Xu {
27197b20fb19SJeff Roberson 	thread_lock(td);
27208df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
27217b20fb19SJeff Roberson 	thread_unlock(td);
272236ec198bSDavid Xu }
272336ec198bSDavid Xu 
2724ae7a6b38SJeff Roberson /*
2725ae7a6b38SJeff Roberson  * Return the total system load.
2726ae7a6b38SJeff Roberson  */
2727ebccf1e3SJoseph Koshy int
272833916c36SJeff Roberson sched_load(void)
272933916c36SJeff Roberson {
273033916c36SJeff Roberson #ifdef SMP
273133916c36SJeff Roberson 	int total;
273233916c36SJeff Roberson 	int i;
273333916c36SJeff Roberson 
273433916c36SJeff Roberson 	total = 0;
27353aa6d94eSJohn Baldwin 	CPU_FOREACH(i)
273662fa74d9SJeff Roberson 		total += TDQ_CPU(i)->tdq_sysload;
273733916c36SJeff Roberson 	return (total);
273833916c36SJeff Roberson #else
2739d2ad694cSJeff Roberson 	return (TDQ_SELF()->tdq_sysload);
274033916c36SJeff Roberson #endif
274133916c36SJeff Roberson }
274233916c36SJeff Roberson 
274333916c36SJeff Roberson int
274435e6168fSJeff Roberson sched_sizeof_proc(void)
274535e6168fSJeff Roberson {
274635e6168fSJeff Roberson 	return (sizeof(struct proc));
274735e6168fSJeff Roberson }
274835e6168fSJeff Roberson 
274935e6168fSJeff Roberson int
275035e6168fSJeff Roberson sched_sizeof_thread(void)
275135e6168fSJeff Roberson {
275235e6168fSJeff Roberson 	return (sizeof(struct thread) + sizeof(struct td_sched));
275335e6168fSJeff Roberson }
2754b41f1452SDavid Xu 
275509c8a4ccSJeff Roberson #ifdef SMP
275609c8a4ccSJeff Roberson #define	TDQ_IDLESPIN(tdq)						\
275709c8a4ccSJeff Roberson     ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
275809c8a4ccSJeff Roberson #else
275909c8a4ccSJeff Roberson #define	TDQ_IDLESPIN(tdq)	1
276009c8a4ccSJeff Roberson #endif
276109c8a4ccSJeff Roberson 
27627a5e5e2aSJeff Roberson /*
27637a5e5e2aSJeff Roberson  * The actual idle process.
27647a5e5e2aSJeff Roberson  */
27657a5e5e2aSJeff Roberson void
27667a5e5e2aSJeff Roberson sched_idletd(void *dummy)
27677a5e5e2aSJeff Roberson {
27687a5e5e2aSJeff Roberson 	struct thread *td;
2769ae7a6b38SJeff Roberson 	struct tdq *tdq;
27702c27cb3aSAlexander Motin 	int oldswitchcnt, switchcnt;
27711690c6c1SJeff Roberson 	int i;
27727a5e5e2aSJeff Roberson 
27737b55ab05SJeff Roberson 	mtx_assert(&Giant, MA_NOTOWNED);
27747a5e5e2aSJeff Roberson 	td = curthread;
2775ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2776ba96d2d8SJohn Baldwin 	THREAD_NO_SLEEPING();
27772c27cb3aSAlexander Motin 	oldswitchcnt = -1;
2778ae7a6b38SJeff Roberson 	for (;;) {
27792c27cb3aSAlexander Motin 		if (tdq->tdq_load) {
27802c27cb3aSAlexander Motin 			thread_lock(td);
27812c27cb3aSAlexander Motin 			mi_switch(SW_VOL | SWT_IDLE, NULL);
27822c27cb3aSAlexander Motin 			thread_unlock(td);
27832c27cb3aSAlexander Motin 		}
27842c27cb3aSAlexander Motin 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2785ae7a6b38SJeff Roberson #ifdef SMP
278697e9382dSDon Lewis 		if (always_steal || switchcnt != oldswitchcnt) {
27872c27cb3aSAlexander Motin 			oldswitchcnt = switchcnt;
27881690c6c1SJeff Roberson 			if (tdq_idled(tdq) == 0)
27891690c6c1SJeff Roberson 				continue;
27902c27cb3aSAlexander Motin 		}
27911690c6c1SJeff Roberson 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
27922fd4047fSAlexander Motin #else
27932fd4047fSAlexander Motin 		oldswitchcnt = switchcnt;
27942fd4047fSAlexander Motin #endif
27951690c6c1SJeff Roberson 		/*
27961690c6c1SJeff Roberson 		 * If we're switching very frequently, spin while checking
27971690c6c1SJeff Roberson 		 * for load rather than entering a low power state that
27987b55ab05SJeff Roberson 		 * may require an IPI.  However, don't do any busy
27997b55ab05SJeff Roberson 		 * loops while on SMT machines as this simply steals
28007b55ab05SJeff Roberson 		 * cycles from cores doing useful work.
28011690c6c1SJeff Roberson 		 */
280209c8a4ccSJeff Roberson 		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
28031690c6c1SJeff Roberson 			for (i = 0; i < sched_idlespins; i++) {
28041690c6c1SJeff Roberson 				if (tdq->tdq_load)
28051690c6c1SJeff Roberson 					break;
28061690c6c1SJeff Roberson 				cpu_spinwait();
28071690c6c1SJeff Roberson 			}
28081690c6c1SJeff Roberson 		}
28092c27cb3aSAlexander Motin 
28102c27cb3aSAlexander Motin 		/* If there was context switch during spin, restart it. */
28116c47aaaeSJeff Roberson 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
28122c27cb3aSAlexander Motin 		if (tdq->tdq_load != 0 || switchcnt != oldswitchcnt)
28132c27cb3aSAlexander Motin 			continue;
28142c27cb3aSAlexander Motin 
28152c27cb3aSAlexander Motin 		/* Run main MD idle handler. */
28169f9ad565SAlexander Motin 		tdq->tdq_cpu_idle = 1;
281779654969SAlexander Motin 		/*
281879654969SAlexander Motin 		 * Make sure that tdq_cpu_idle update is globally visible
281979654969SAlexander Motin 		 * before cpu_idle() read tdq_load.  The order is important
282079654969SAlexander Motin 		 * to avoid race with tdq_notify.
282179654969SAlexander Motin 		 */
2822e8677f38SKonstantin Belousov 		atomic_thread_fence_seq_cst();
282397e9382dSDon Lewis 		/*
282497e9382dSDon Lewis 		 * Checking for again after the fence picks up assigned
282597e9382dSDon Lewis 		 * threads often enough to make it worthwhile to do so in
282697e9382dSDon Lewis 		 * order to avoid calling cpu_idle().
282797e9382dSDon Lewis 		 */
282897e9382dSDon Lewis 		if (tdq->tdq_load != 0) {
282997e9382dSDon Lewis 			tdq->tdq_cpu_idle = 0;
283097e9382dSDon Lewis 			continue;
283197e9382dSDon Lewis 		}
28322c27cb3aSAlexander Motin 		cpu_idle(switchcnt * 4 > sched_idlespinthresh);
28339f9ad565SAlexander Motin 		tdq->tdq_cpu_idle = 0;
28342c27cb3aSAlexander Motin 
28352c27cb3aSAlexander Motin 		/*
28362c27cb3aSAlexander Motin 		 * Account thread-less hardware interrupts and
28372c27cb3aSAlexander Motin 		 * other wakeup reasons equal to context switches.
28382c27cb3aSAlexander Motin 		 */
28392c27cb3aSAlexander Motin 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
28402c27cb3aSAlexander Motin 		if (switchcnt != oldswitchcnt)
28412c27cb3aSAlexander Motin 			continue;
28422c27cb3aSAlexander Motin 		tdq->tdq_switchcnt++;
28432c27cb3aSAlexander Motin 		oldswitchcnt++;
2844ae7a6b38SJeff Roberson 	}
2845b41f1452SDavid Xu }
2846e7d50326SJeff Roberson 
28477b20fb19SJeff Roberson /*
28487b20fb19SJeff Roberson  * A CPU is entering for the first time or a thread is exiting.
28497b20fb19SJeff Roberson  */
28507b20fb19SJeff Roberson void
28517b20fb19SJeff Roberson sched_throw(struct thread *td)
28527b20fb19SJeff Roberson {
285359c68134SJeff Roberson 	struct thread *newtd;
2854ae7a6b38SJeff Roberson 	struct tdq *tdq;
2855ae7a6b38SJeff Roberson 
2856ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
28577b20fb19SJeff Roberson 	if (td == NULL) {
2858ae7a6b38SJeff Roberson 		/* Correct spinlock nesting and acquire the correct lock. */
2859ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
28607b20fb19SJeff Roberson 		spinlock_exit();
28617e3a96eaSJohn Baldwin 		PCPU_SET(switchtime, cpu_ticks());
28627e3a96eaSJohn Baldwin 		PCPU_SET(switchticks, ticks);
28637b20fb19SJeff Roberson 	} else {
2864ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
28659727e637SJeff Roberson 		tdq_load_rem(tdq, td);
2866eea4f254SJeff Roberson 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
286792de34dfSJohn Baldwin 		td->td_lastcpu = td->td_oncpu;
286892de34dfSJohn Baldwin 		td->td_oncpu = NOCPU;
28697b20fb19SJeff Roberson 	}
28707b20fb19SJeff Roberson 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
287159c68134SJeff Roberson 	newtd = choosethread();
287259c68134SJeff Roberson 	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
287359c68134SJeff Roberson 	cpu_throw(td, newtd);		/* doesn't return */
28747b20fb19SJeff Roberson }
28757b20fb19SJeff Roberson 
2876ae7a6b38SJeff Roberson /*
2877ae7a6b38SJeff Roberson  * This is called from fork_exit().  Just acquire the correct locks and
2878ae7a6b38SJeff Roberson  * let fork do the rest of the work.
2879ae7a6b38SJeff Roberson  */
28807b20fb19SJeff Roberson void
2881fe54587fSJeff Roberson sched_fork_exit(struct thread *td)
28827b20fb19SJeff Roberson {
2883ae7a6b38SJeff Roberson 	struct tdq *tdq;
2884ae7a6b38SJeff Roberson 	int cpuid;
28857b20fb19SJeff Roberson 
28867b20fb19SJeff Roberson 	/*
28877b20fb19SJeff Roberson 	 * Finish setting up thread glue so that it begins execution in a
2888ae7a6b38SJeff Roberson 	 * non-nested critical section with the scheduler lock held.
28897b20fb19SJeff Roberson 	 */
2890ae7a6b38SJeff Roberson 	cpuid = PCPU_GET(cpuid);
2891ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpuid);
2892ae7a6b38SJeff Roberson 	if (TD_IS_IDLETHREAD(td))
2893ae7a6b38SJeff Roberson 		td->td_lock = TDQ_LOCKPTR(tdq);
2894ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2895ae7a6b38SJeff Roberson 	td->td_oncpu = cpuid;
289659c68134SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2897eea4f254SJeff Roberson 	lock_profile_obtain_lock_success(
2898eea4f254SJeff Roberson 	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
289928ef18b8SAndriy Gapon 
290028ef18b8SAndriy Gapon 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
290128ef18b8SAndriy Gapon 	    "prio:%d", td->td_priority);
290228ef18b8SAndriy Gapon 	SDT_PROBE0(sched, , , on__cpu);
29037b20fb19SJeff Roberson }
29047b20fb19SJeff Roberson 
29058f51ad55SJeff Roberson /*
29068f51ad55SJeff Roberson  * Create on first use to catch odd startup conditons.
29078f51ad55SJeff Roberson  */
29088f51ad55SJeff Roberson char *
29098f51ad55SJeff Roberson sched_tdname(struct thread *td)
29108f51ad55SJeff Roberson {
29118f51ad55SJeff Roberson #ifdef KTR
29128f51ad55SJeff Roberson 	struct td_sched *ts;
29138f51ad55SJeff Roberson 
291493ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
29158f51ad55SJeff Roberson 	if (ts->ts_name[0] == '\0')
29168f51ad55SJeff Roberson 		snprintf(ts->ts_name, sizeof(ts->ts_name),
29178f51ad55SJeff Roberson 		    "%s tid %d", td->td_name, td->td_tid);
29188f51ad55SJeff Roberson 	return (ts->ts_name);
29198f51ad55SJeff Roberson #else
29208f51ad55SJeff Roberson 	return (td->td_name);
29218f51ad55SJeff Roberson #endif
29228f51ad55SJeff Roberson }
29238f51ad55SJeff Roberson 
292444ad5475SJohn Baldwin #ifdef KTR
292544ad5475SJohn Baldwin void
292644ad5475SJohn Baldwin sched_clear_tdname(struct thread *td)
292744ad5475SJohn Baldwin {
292844ad5475SJohn Baldwin 	struct td_sched *ts;
292944ad5475SJohn Baldwin 
293093ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
293144ad5475SJohn Baldwin 	ts->ts_name[0] = '\0';
293244ad5475SJohn Baldwin }
293344ad5475SJohn Baldwin #endif
293444ad5475SJohn Baldwin 
293507095abfSIvan Voras #ifdef SMP
293607095abfSIvan Voras 
293707095abfSIvan Voras /*
293807095abfSIvan Voras  * Build the CPU topology dump string. Is recursively called to collect
293907095abfSIvan Voras  * the topology tree.
294007095abfSIvan Voras  */
294107095abfSIvan Voras static int
294207095abfSIvan Voras sysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
294307095abfSIvan Voras     int indent)
294407095abfSIvan Voras {
294571a19bdcSAttilio Rao 	char cpusetbuf[CPUSETBUFSIZ];
294607095abfSIvan Voras 	int i, first;
294707095abfSIvan Voras 
294807095abfSIvan Voras 	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
294919b8a6dbSAndriy Gapon 	    "", 1 + indent / 2, cg->cg_level);
295071a19bdcSAttilio Rao 	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
295171a19bdcSAttilio Rao 	    cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
295207095abfSIvan Voras 	first = TRUE;
295307095abfSIvan Voras 	for (i = 0; i < MAXCPU; i++) {
295471a19bdcSAttilio Rao 		if (CPU_ISSET(i, &cg->cg_mask)) {
295507095abfSIvan Voras 			if (!first)
295607095abfSIvan Voras 				sbuf_printf(sb, ", ");
295707095abfSIvan Voras 			else
295807095abfSIvan Voras 				first = FALSE;
295907095abfSIvan Voras 			sbuf_printf(sb, "%d", i);
296007095abfSIvan Voras 		}
296107095abfSIvan Voras 	}
296207095abfSIvan Voras 	sbuf_printf(sb, "</cpu>\n");
296307095abfSIvan Voras 
296407095abfSIvan Voras 	if (cg->cg_flags != 0) {
2965611daf7eSIvan Voras 		sbuf_printf(sb, "%*s <flags>", indent, "");
296607095abfSIvan Voras 		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
29675368befbSIvan Voras 			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
2968a401f2d0SIvan Voras 		if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
2969a401f2d0SIvan Voras 			sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
29707b55ab05SJeff Roberson 		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
2971a401f2d0SIvan Voras 			sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
297207095abfSIvan Voras 		sbuf_printf(sb, "</flags>\n");
2973611daf7eSIvan Voras 	}
297407095abfSIvan Voras 
297507095abfSIvan Voras 	if (cg->cg_children > 0) {
297607095abfSIvan Voras 		sbuf_printf(sb, "%*s <children>\n", indent, "");
297707095abfSIvan Voras 		for (i = 0; i < cg->cg_children; i++)
297807095abfSIvan Voras 			sysctl_kern_sched_topology_spec_internal(sb,
297907095abfSIvan Voras 			    &cg->cg_child[i], indent+2);
298007095abfSIvan Voras 		sbuf_printf(sb, "%*s </children>\n", indent, "");
298107095abfSIvan Voras 	}
298207095abfSIvan Voras 	sbuf_printf(sb, "%*s</group>\n", indent, "");
298307095abfSIvan Voras 	return (0);
298407095abfSIvan Voras }
298507095abfSIvan Voras 
298607095abfSIvan Voras /*
298707095abfSIvan Voras  * Sysctl handler for retrieving topology dump. It's a wrapper for
298807095abfSIvan Voras  * the recursive sysctl_kern_smp_topology_spec_internal().
298907095abfSIvan Voras  */
299007095abfSIvan Voras static int
299107095abfSIvan Voras sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
299207095abfSIvan Voras {
299307095abfSIvan Voras 	struct sbuf *topo;
299407095abfSIvan Voras 	int err;
299507095abfSIvan Voras 
299607095abfSIvan Voras 	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
299707095abfSIvan Voras 
2998b97fa22cSIan Lepore 	topo = sbuf_new_for_sysctl(NULL, NULL, 512, req);
299907095abfSIvan Voras 	if (topo == NULL)
300007095abfSIvan Voras 		return (ENOMEM);
300107095abfSIvan Voras 
300207095abfSIvan Voras 	sbuf_printf(topo, "<groups>\n");
300307095abfSIvan Voras 	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
300407095abfSIvan Voras 	sbuf_printf(topo, "</groups>\n");
300507095abfSIvan Voras 
300607095abfSIvan Voras 	if (err == 0) {
3007b97fa22cSIan Lepore 		err = sbuf_finish(topo);
300807095abfSIvan Voras 	}
300907095abfSIvan Voras 	sbuf_delete(topo);
301007095abfSIvan Voras 	return (err);
301107095abfSIvan Voras }
3012b67cc292SDavid Xu 
301307095abfSIvan Voras #endif
301407095abfSIvan Voras 
3015579895dfSAlexander Motin static int
3016579895dfSAlexander Motin sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
3017579895dfSAlexander Motin {
3018579895dfSAlexander Motin 	int error, new_val, period;
3019579895dfSAlexander Motin 
3020579895dfSAlexander Motin 	period = 1000000 / realstathz;
3021579895dfSAlexander Motin 	new_val = period * sched_slice;
3022579895dfSAlexander Motin 	error = sysctl_handle_int(oidp, &new_val, 0, req);
3023579895dfSAlexander Motin 	if (error != 0 || req->newptr == NULL)
3024579895dfSAlexander Motin 		return (error);
3025579895dfSAlexander Motin 	if (new_val <= 0)
3026579895dfSAlexander Motin 		return (EINVAL);
302737f4e025SAlexander Motin 	sched_slice = imax(1, (new_val + period / 2) / period);
30285e5c3873SJeff Roberson 	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
302937f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
303037f4e025SAlexander Motin 	    realstathz);
3031579895dfSAlexander Motin 	return (0);
3032579895dfSAlexander Motin }
3033579895dfSAlexander Motin 
30349727e637SJeff Roberson SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
3035ae7a6b38SJeff Roberson SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
3036e7d50326SJeff Roberson     "Scheduler name");
3037579895dfSAlexander Motin SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
3038579895dfSAlexander Motin     NULL, 0, sysctl_kern_quantum, "I",
303937f4e025SAlexander Motin     "Quantum for timeshare threads in microseconds");
3040ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
304137f4e025SAlexander Motin     "Quantum for timeshare threads in stathz ticks");
3042ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
3043ae7a6b38SJeff Roberson     "Interactivity score threshold");
304437f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW,
304537f4e025SAlexander Motin     &preempt_thresh, 0,
304637f4e025SAlexander Motin     "Maximal (lowest) priority for preemption");
304737f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost, 0,
304837f4e025SAlexander Motin     "Assign static kernel priorities to sleeping threads");
304937f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins, 0,
305037f4e025SAlexander Motin     "Number of times idle thread will spin waiting for new work");
305137f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW,
305237f4e025SAlexander Motin     &sched_idlespinthresh, 0,
305337f4e025SAlexander Motin     "Threshold before we will permit idle thread spinning");
30547b8bfa0dSJeff Roberson #ifdef SMP
3055ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
3056ae7a6b38SJeff Roberson     "Number of hz ticks to keep thread affinity for");
3057ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
3058ae7a6b38SJeff Roberson     "Enables the long-term load balancer");
30597fcf154aSJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
30607fcf154aSJeff Roberson     &balance_interval, 0,
3061579895dfSAlexander Motin     "Average period in stathz ticks to run the long-term balancer");
3062ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
3063ae7a6b38SJeff Roberson     "Attempts to steal work from other cores before idling");
306428994a58SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
306537f4e025SAlexander Motin     "Minimum load on remote CPU before we'll steal");
306697e9382dSDon Lewis SYSCTL_INT(_kern_sched, OID_AUTO, trysteal_limit, CTLFLAG_RW, &trysteal_limit,
306797e9382dSDon Lewis     0, "Topological distance limit for stealing threads in sched_switch()");
306897e9382dSDon Lewis SYSCTL_INT(_kern_sched, OID_AUTO, always_steal, CTLFLAG_RW, &always_steal, 0,
306997e9382dSDon Lewis     "Always run the stealer from the idle thread");
307007095abfSIvan Voras SYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
3071c69a1a50SMateusz Guzik     CTLFLAG_MPSAFE | CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
307207095abfSIvan Voras     "XML dump of detected CPU topology");
30737b8bfa0dSJeff Roberson #endif
3074e7d50326SJeff Roberson 
307554b0e65fSJeff Roberson /* ps compat.  All cpu percentages from ULE are weighted. */
3076a5423ea3SJeff Roberson static int ccpu = 0;
3077e7d50326SJeff Roberson SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
3078