xref: /freebsd/sys/kern/sched_ule.c (revision 589aed00e36c22733d3fd9c9016deccf074830b1)
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>
64af29f399SDmitry Chagin #include <sys/umtxvar.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>
7561322a0aSAlexander Motin int __read_mostly		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. */
199e745d729SAlexander Motin #define	TDF_PICKCPU	TDF_SCHED0	/* Thread should pick new CPU. */
2003d7f4117SAlexander Motin #define	TDF_SLICEEND	TDF_SCHED2	/* Thread time slice is over. */
2013d7f4117SAlexander Motin 
20235e6168fSJeff Roberson /*
203e7d50326SJeff Roberson  * tickincr:		Converts a stathz tick into a hz domain scaled by
204e7d50326SJeff Roberson  *			the shift factor.  Without the shift the error rate
205e7d50326SJeff Roberson  *			due to rounding would be unacceptably high.
206e7d50326SJeff Roberson  * realstathz:		stathz is sometimes 0 and run off of hz.
207e7d50326SJeff Roberson  * sched_slice:		Runtime of each thread before rescheduling.
208ae7a6b38SJeff Roberson  * preempt_thresh:	Priority threshold for preemption and remote IPIs.
20935e6168fSJeff Roberson  */
2101c119e17SAlexander Motin static u_int __read_mostly sched_interact = SCHED_INTERACT_THRESH;
21161322a0aSAlexander Motin static int __read_mostly tickincr = 8 << SCHED_TICK_SHIFT;
21261322a0aSAlexander Motin static int __read_mostly realstathz = 127;	/* reset during boot. */
21361322a0aSAlexander Motin static int __read_mostly sched_slice = 10;	/* reset during boot. */
21461322a0aSAlexander Motin static int __read_mostly sched_slice_min = 1;	/* reset during boot. */
21502e2d6b4SJeff Roberson #ifdef PREEMPTION
21602e2d6b4SJeff Roberson #ifdef FULL_PREEMPTION
21761322a0aSAlexander Motin static int __read_mostly preempt_thresh = PRI_MAX_IDLE;
21802e2d6b4SJeff Roberson #else
21961322a0aSAlexander Motin static int __read_mostly preempt_thresh = PRI_MIN_KERN;
22002e2d6b4SJeff Roberson #endif
22102e2d6b4SJeff Roberson #else
22261322a0aSAlexander Motin static int __read_mostly preempt_thresh = 0;
22302e2d6b4SJeff Roberson #endif
22461322a0aSAlexander Motin static int __read_mostly static_boost = PRI_MIN_BATCH;
22561322a0aSAlexander Motin static int __read_mostly sched_idlespins = 10000;
22661322a0aSAlexander Motin static int __read_mostly sched_idlespinthresh = -1;
227ae7a6b38SJeff Roberson 
22835e6168fSJeff Roberson /*
229ae7a6b38SJeff Roberson  * tdq - per processor runqs and statistics.  All fields are protected by the
230ae7a6b38SJeff Roberson  * tdq_lock.  The load and lowpri may be accessed without to avoid excess
231ae7a6b38SJeff Roberson  * locking in sched_pickcpu();
23235e6168fSJeff Roberson  */
233ad1e7d28SJulian Elischer struct tdq {
23439f819e2SJim Harris 	/*
23539f819e2SJim Harris 	 * Ordered to improve efficiency of cpu_search() and switch().
23639f819e2SJim Harris 	 * tdq_lock is padded to avoid false sharing with tdq_load and
23739f819e2SJim Harris 	 * tdq_cpu_idle.
23839f819e2SJim Harris 	 */
2394ceaf45dSAttilio Rao 	struct mtx_padalign tdq_lock;		/* run queue lock. */
24073daf66fSJeff Roberson 	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
2411690c6c1SJeff Roberson 	volatile int	tdq_load;		/* Aggregate load. */
2429f9ad565SAlexander Motin 	volatile int	tdq_cpu_idle;		/* cpu_idle() is active. */
24373daf66fSJeff Roberson 	int		tdq_sysload;		/* For loadavg, !ITHD load. */
24497e9382dSDon Lewis 	volatile int	tdq_transferable;	/* Transferable thread count. */
24597e9382dSDon Lewis 	volatile short	tdq_switchcnt;		/* Switches this tick. */
24697e9382dSDon Lewis 	volatile short	tdq_oldswitchcnt;	/* Switches last tick. */
24773daf66fSJeff Roberson 	u_char		tdq_lowpri;		/* Lowest priority thread. */
2487789ab32SMark Johnston 	u_char		tdq_owepreempt;		/* Remote preemption pending. */
24973daf66fSJeff Roberson 	u_char		tdq_idx;		/* Current insert index. */
25073daf66fSJeff Roberson 	u_char		tdq_ridx;		/* Current removal index. */
251018ff686SJeff Roberson 	int		tdq_id;			/* cpuid. */
252e7d50326SJeff Roberson 	struct runq	tdq_realtime;		/* real-time run queue. */
253ae7a6b38SJeff Roberson 	struct runq	tdq_timeshare;		/* timeshare run queue. */
254ae7a6b38SJeff Roberson 	struct runq	tdq_idle;		/* Queue of IDLE threads. */
2558f51ad55SJeff Roberson 	char		tdq_name[TDQ_NAME_LEN];
2568f51ad55SJeff Roberson #ifdef KTR
2578f51ad55SJeff Roberson 	char		tdq_loadname[TDQ_LOADNAME_LEN];
2588f51ad55SJeff Roberson #endif
259ae7a6b38SJeff Roberson } __aligned(64);
26035e6168fSJeff Roberson 
2611690c6c1SJeff Roberson /* Idle thread states and config. */
2621690c6c1SJeff Roberson #define	TDQ_RUNNING	1
2631690c6c1SJeff Roberson #define	TDQ_IDLE	2
2647b8bfa0dSJeff Roberson 
26580f86c9fSJeff Roberson #ifdef SMP
26661322a0aSAlexander Motin struct cpu_group __read_mostly *cpu_top;		/* CPU topology */
2677b8bfa0dSJeff Roberson 
26862fa74d9SJeff Roberson #define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
26962fa74d9SJeff Roberson #define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
2707b8bfa0dSJeff Roberson 
2717b8bfa0dSJeff Roberson /*
2727b8bfa0dSJeff Roberson  * Run-time tunables.
2737b8bfa0dSJeff Roberson  */
27428994a58SJeff Roberson static int rebalance = 1;
2757fcf154aSJeff Roberson static int balance_interval = 128;	/* Default set in sched_initticks(). */
27661322a0aSAlexander Motin static int __read_mostly affinity;
27761322a0aSAlexander Motin static int __read_mostly steal_idle = 1;
27861322a0aSAlexander Motin static int __read_mostly steal_thresh = 2;
27961322a0aSAlexander Motin static int __read_mostly always_steal = 0;
28061322a0aSAlexander Motin static int __read_mostly trysteal_limit = 2;
28180f86c9fSJeff Roberson 
28235e6168fSJeff Roberson /*
283d2ad694cSJeff Roberson  * One thread queue per processor.
28435e6168fSJeff Roberson  */
28561322a0aSAlexander Motin static struct tdq __read_mostly *balance_tdq;
2867fcf154aSJeff Roberson static int balance_ticks;
287018ff686SJeff Roberson DPCPU_DEFINE_STATIC(struct tdq, tdq);
2882bf95012SAndrew Turner DPCPU_DEFINE_STATIC(uint32_t, randomval);
289dc03363dSJeff Roberson 
290018ff686SJeff Roberson #define	TDQ_SELF()	((struct tdq *)PCPU_GET(sched))
291018ff686SJeff Roberson #define	TDQ_CPU(x)	(DPCPU_ID_PTR((x), tdq))
292018ff686SJeff Roberson #define	TDQ_ID(x)	((x)->tdq_id)
29380f86c9fSJeff Roberson #else	/* !SMP */
294ad1e7d28SJulian Elischer static struct tdq	tdq_cpu;
295dc03363dSJeff Roberson 
29636b36916SJeff Roberson #define	TDQ_ID(x)	(0)
297ad1e7d28SJulian Elischer #define	TDQ_SELF()	(&tdq_cpu)
298ad1e7d28SJulian Elischer #define	TDQ_CPU(x)	(&tdq_cpu)
2990a016a05SJeff Roberson #endif
30035e6168fSJeff Roberson 
301ae7a6b38SJeff Roberson #define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
302ae7a6b38SJeff Roberson #define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
303ae7a6b38SJeff Roberson #define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
3048bb173fbSAlexander Motin #define	TDQ_TRYLOCK(t)		mtx_trylock_spin(TDQ_LOCKPTR((t)))
3058bb173fbSAlexander Motin #define	TDQ_TRYLOCK_FLAGS(t, f)	mtx_trylock_spin_flags(TDQ_LOCKPTR((t)), (f))
306ae7a6b38SJeff Roberson #define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
3074ceaf45dSAttilio Rao #define	TDQ_LOCKPTR(t)		((struct mtx *)(&(t)->tdq_lock))
308ae7a6b38SJeff Roberson 
3098460a577SJohn Birrell static void sched_priority(struct thread *);
31021381d1bSJeff Roberson static void sched_thread_priority(struct thread *, u_char);
3118460a577SJohn Birrell static int sched_interact_score(struct thread *);
3128460a577SJohn Birrell static void sched_interact_update(struct thread *);
3138460a577SJohn Birrell static void sched_interact_fork(struct thread *);
3147295465eSAlexander Motin static void sched_pctcpu_update(struct td_sched *, int);
31535e6168fSJeff Roberson 
3165d7ef00cSJeff Roberson /* Operations on per processor queues */
3179727e637SJeff Roberson static struct thread *tdq_choose(struct tdq *);
318018ff686SJeff Roberson static void tdq_setup(struct tdq *, int i);
3199727e637SJeff Roberson static void tdq_load_add(struct tdq *, struct thread *);
3209727e637SJeff Roberson static void tdq_load_rem(struct tdq *, struct thread *);
3219727e637SJeff Roberson static __inline void tdq_runq_add(struct tdq *, struct thread *, int);
3229727e637SJeff Roberson static __inline void tdq_runq_rem(struct tdq *, struct thread *);
323ff256d9cSJeff Roberson static inline int sched_shouldpreempt(int, int, int);
324ad1e7d28SJulian Elischer void tdq_print(int cpu);
325e7d50326SJeff Roberson static void runq_print(struct runq *rq);
326ae7a6b38SJeff Roberson static void tdq_add(struct tdq *, struct thread *, int);
3275d7ef00cSJeff Roberson #ifdef SMP
32897e9382dSDon Lewis static struct thread *tdq_move(struct tdq *, struct tdq *);
329ad1e7d28SJulian Elischer static int tdq_idled(struct tdq *);
33027ee18adSRyan Stone static void tdq_notify(struct tdq *, struct thread *);
3319727e637SJeff Roberson static struct thread *tdq_steal(struct tdq *, int);
3329727e637SJeff Roberson static struct thread *runq_steal(struct runq *, int);
3339727e637SJeff Roberson static int sched_pickcpu(struct thread *, int);
3347fcf154aSJeff Roberson static void sched_balance(void);
33562fa74d9SJeff Roberson static int sched_balance_pair(struct tdq *, struct tdq *);
3369727e637SJeff Roberson static inline struct tdq *sched_setcpu(struct thread *, int, int);
337ae7a6b38SJeff Roberson static inline void thread_unblock_switch(struct thread *, struct mtx *);
33807095abfSIvan Voras static int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
33907095abfSIvan Voras static int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
34007095abfSIvan Voras     struct cpu_group *cg, int indent);
3415d7ef00cSJeff Roberson #endif
3425d7ef00cSJeff Roberson 
343e7d50326SJeff Roberson static void sched_setup(void *dummy);
344237fdd78SRobert Watson SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
345e7d50326SJeff Roberson 
346e7d50326SJeff Roberson static void sched_initticks(void *dummy);
347237fdd78SRobert Watson SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
348237fdd78SRobert Watson     NULL);
349e7d50326SJeff Roberson 
350b3e9e682SRyan Stone SDT_PROVIDER_DEFINE(sched);
351b3e9e682SRyan Stone 
352d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
353b3e9e682SRyan Stone     "struct proc *", "uint8_t");
354d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
355b3e9e682SRyan Stone     "struct proc *", "void *");
356d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
357b3e9e682SRyan Stone     "struct proc *", "void *", "int");
358d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
359b3e9e682SRyan Stone     "struct proc *", "uint8_t", "struct thread *");
360d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
361d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
362b3e9e682SRyan Stone     "struct proc *");
363d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , on__cpu);
364d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , remain__cpu);
365d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
366b3e9e682SRyan Stone     "struct proc *");
367b3e9e682SRyan Stone 
3680567b6ccSWarner Losh /*
369ae7a6b38SJeff Roberson  * Print the threads waiting on a run-queue.
370ae7a6b38SJeff Roberson  */
371e7d50326SJeff Roberson static void
372e7d50326SJeff Roberson runq_print(struct runq *rq)
373e7d50326SJeff Roberson {
374e7d50326SJeff Roberson 	struct rqhead *rqh;
3759727e637SJeff Roberson 	struct thread *td;
376e7d50326SJeff Roberson 	int pri;
377e7d50326SJeff Roberson 	int j;
378e7d50326SJeff Roberson 	int i;
379e7d50326SJeff Roberson 
380e7d50326SJeff Roberson 	for (i = 0; i < RQB_LEN; i++) {
381e7d50326SJeff Roberson 		printf("\t\trunq bits %d 0x%zx\n",
382e7d50326SJeff Roberson 		    i, rq->rq_status.rqb_bits[i]);
383e7d50326SJeff Roberson 		for (j = 0; j < RQB_BPW; j++)
384e7d50326SJeff Roberson 			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
385e7d50326SJeff Roberson 				pri = j + (i << RQB_L2BPW);
386e7d50326SJeff Roberson 				rqh = &rq->rq_queues[pri];
3879727e637SJeff Roberson 				TAILQ_FOREACH(td, rqh, td_runq) {
388e7d50326SJeff Roberson 					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
3899727e637SJeff Roberson 					    td, td->td_name, td->td_priority,
3909727e637SJeff Roberson 					    td->td_rqindex, pri);
391e7d50326SJeff Roberson 				}
392e7d50326SJeff Roberson 			}
393e7d50326SJeff Roberson 	}
394e7d50326SJeff Roberson }
395e7d50326SJeff Roberson 
396ae7a6b38SJeff Roberson /*
397ae7a6b38SJeff Roberson  * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
398ae7a6b38SJeff Roberson  */
39915dc847eSJeff Roberson void
400ad1e7d28SJulian Elischer tdq_print(int cpu)
40115dc847eSJeff Roberson {
402ad1e7d28SJulian Elischer 	struct tdq *tdq;
40315dc847eSJeff Roberson 
404ad1e7d28SJulian Elischer 	tdq = TDQ_CPU(cpu);
40515dc847eSJeff Roberson 
406c47f202bSJeff Roberson 	printf("tdq %d:\n", TDQ_ID(tdq));
40762fa74d9SJeff Roberson 	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
40862fa74d9SJeff Roberson 	printf("\tLock name:      %s\n", tdq->tdq_name);
409d2ad694cSJeff Roberson 	printf("\tload:           %d\n", tdq->tdq_load);
4101690c6c1SJeff Roberson 	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
4111690c6c1SJeff Roberson 	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
412e7d50326SJeff Roberson 	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
4133f872f85SJeff Roberson 	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
4141690c6c1SJeff Roberson 	printf("\tload transferable: %d\n", tdq->tdq_transferable);
4151690c6c1SJeff Roberson 	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
416e7d50326SJeff Roberson 	printf("\trealtime runq:\n");
417e7d50326SJeff Roberson 	runq_print(&tdq->tdq_realtime);
418e7d50326SJeff Roberson 	printf("\ttimeshare runq:\n");
419e7d50326SJeff Roberson 	runq_print(&tdq->tdq_timeshare);
420e7d50326SJeff Roberson 	printf("\tidle runq:\n");
421e7d50326SJeff Roberson 	runq_print(&tdq->tdq_idle);
42215dc847eSJeff Roberson }
42315dc847eSJeff Roberson 
424ff256d9cSJeff Roberson static inline int
425ff256d9cSJeff Roberson sched_shouldpreempt(int pri, int cpri, int remote)
426ff256d9cSJeff Roberson {
427ff256d9cSJeff Roberson 	/*
428ff256d9cSJeff Roberson 	 * If the new priority is not better than the current priority there is
429ff256d9cSJeff Roberson 	 * nothing to do.
430ff256d9cSJeff Roberson 	 */
431ff256d9cSJeff Roberson 	if (pri >= cpri)
432ff256d9cSJeff Roberson 		return (0);
433ff256d9cSJeff Roberson 	/*
434ff256d9cSJeff Roberson 	 * Always preempt idle.
435ff256d9cSJeff Roberson 	 */
436ff256d9cSJeff Roberson 	if (cpri >= PRI_MIN_IDLE)
437ff256d9cSJeff Roberson 		return (1);
438ff256d9cSJeff Roberson 	/*
439ff256d9cSJeff Roberson 	 * If preemption is disabled don't preempt others.
440ff256d9cSJeff Roberson 	 */
441ff256d9cSJeff Roberson 	if (preempt_thresh == 0)
442ff256d9cSJeff Roberson 		return (0);
443ff256d9cSJeff Roberson 	/*
444ff256d9cSJeff Roberson 	 * Preempt if we exceed the threshold.
445ff256d9cSJeff Roberson 	 */
446ff256d9cSJeff Roberson 	if (pri <= preempt_thresh)
447ff256d9cSJeff Roberson 		return (1);
448ff256d9cSJeff Roberson 	/*
44912d56c0fSJohn Baldwin 	 * If we're interactive or better and there is non-interactive
45012d56c0fSJohn Baldwin 	 * or worse running preempt only remote processors.
451ff256d9cSJeff Roberson 	 */
45212d56c0fSJohn Baldwin 	if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
453ff256d9cSJeff Roberson 		return (1);
454ff256d9cSJeff Roberson 	return (0);
455ff256d9cSJeff Roberson }
456ff256d9cSJeff Roberson 
457ae7a6b38SJeff Roberson /*
458ae7a6b38SJeff Roberson  * Add a thread to the actual run-queue.  Keeps transferable counts up to
459ae7a6b38SJeff Roberson  * date with what is actually on the run-queue.  Selects the correct
460ae7a6b38SJeff Roberson  * queue position for timeshare threads.
461ae7a6b38SJeff Roberson  */
462155b9987SJeff Roberson static __inline void
4639727e637SJeff Roberson tdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
464155b9987SJeff Roberson {
4659727e637SJeff Roberson 	struct td_sched *ts;
466c143ac21SJeff Roberson 	u_char pri;
467c143ac21SJeff Roberson 
468ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
46961a74c5cSJeff Roberson 	THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
47073daf66fSJeff Roberson 
4719727e637SJeff Roberson 	pri = td->td_priority;
47293ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
4739727e637SJeff Roberson 	TD_SET_RUNQ(td);
4749727e637SJeff Roberson 	if (THREAD_CAN_MIGRATE(td)) {
475d2ad694cSJeff Roberson 		tdq->tdq_transferable++;
476ad1e7d28SJulian Elischer 		ts->ts_flags |= TSF_XFERABLE;
47780f86c9fSJeff Roberson 	}
47812d56c0fSJohn Baldwin 	if (pri < PRI_MIN_BATCH) {
479c143ac21SJeff Roberson 		ts->ts_runq = &tdq->tdq_realtime;
48012d56c0fSJohn Baldwin 	} else if (pri <= PRI_MAX_BATCH) {
481c143ac21SJeff Roberson 		ts->ts_runq = &tdq->tdq_timeshare;
48212d56c0fSJohn Baldwin 		KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
483e7d50326SJeff Roberson 			("Invalid priority %d on timeshare runq", pri));
484e7d50326SJeff Roberson 		/*
485e7d50326SJeff Roberson 		 * This queue contains only priorities between MIN and MAX
486e7d50326SJeff Roberson 		 * realtime.  Use the whole queue to represent these values.
487e7d50326SJeff Roberson 		 */
488c47f202bSJeff Roberson 		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
48916705791SAndriy Gapon 			pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
490e7d50326SJeff Roberson 			pri = (pri + tdq->tdq_idx) % RQ_NQS;
4913f872f85SJeff Roberson 			/*
4923f872f85SJeff Roberson 			 * This effectively shortens the queue by one so we
4933f872f85SJeff Roberson 			 * can have a one slot difference between idx and
4943f872f85SJeff Roberson 			 * ridx while we wait for threads to drain.
4953f872f85SJeff Roberson 			 */
4963f872f85SJeff Roberson 			if (tdq->tdq_ridx != tdq->tdq_idx &&
4973f872f85SJeff Roberson 			    pri == tdq->tdq_ridx)
4984499aff6SJeff Roberson 				pri = (unsigned char)(pri - 1) % RQ_NQS;
499e7d50326SJeff Roberson 		} else
5003f872f85SJeff Roberson 			pri = tdq->tdq_ridx;
5019727e637SJeff Roberson 		runq_add_pri(ts->ts_runq, td, pri, flags);
502c143ac21SJeff Roberson 		return;
503e7d50326SJeff Roberson 	} else
50473daf66fSJeff Roberson 		ts->ts_runq = &tdq->tdq_idle;
5059727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
50673daf66fSJeff Roberson }
50773daf66fSJeff Roberson 
50873daf66fSJeff Roberson /*
509ae7a6b38SJeff Roberson  * Remove a thread from a run-queue.  This typically happens when a thread
510ae7a6b38SJeff Roberson  * is selected to run.  Running threads are not on the queue and the
511ae7a6b38SJeff Roberson  * transferable count does not reflect them.
512ae7a6b38SJeff Roberson  */
513155b9987SJeff Roberson static __inline void
5149727e637SJeff Roberson tdq_runq_rem(struct tdq *tdq, struct thread *td)
515155b9987SJeff Roberson {
5169727e637SJeff Roberson 	struct td_sched *ts;
5179727e637SJeff Roberson 
51893ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
519ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
52061a74c5cSJeff Roberson 	THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
521ae7a6b38SJeff Roberson 	KASSERT(ts->ts_runq != NULL,
5229727e637SJeff Roberson 	    ("tdq_runq_remove: thread %p null ts_runq", td));
523ad1e7d28SJulian Elischer 	if (ts->ts_flags & TSF_XFERABLE) {
524d2ad694cSJeff Roberson 		tdq->tdq_transferable--;
525ad1e7d28SJulian Elischer 		ts->ts_flags &= ~TSF_XFERABLE;
52680f86c9fSJeff Roberson 	}
5273f872f85SJeff Roberson 	if (ts->ts_runq == &tdq->tdq_timeshare) {
5283f872f85SJeff Roberson 		if (tdq->tdq_idx != tdq->tdq_ridx)
5299727e637SJeff Roberson 			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
530e7d50326SJeff Roberson 		else
5319727e637SJeff Roberson 			runq_remove_idx(ts->ts_runq, td, NULL);
5323f872f85SJeff Roberson 	} else
5339727e637SJeff Roberson 		runq_remove(ts->ts_runq, td);
534155b9987SJeff Roberson }
535155b9987SJeff Roberson 
536ae7a6b38SJeff Roberson /*
537ae7a6b38SJeff Roberson  * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
538ae7a6b38SJeff Roberson  * for this thread to the referenced thread queue.
539ae7a6b38SJeff Roberson  */
540a8949de2SJeff Roberson static void
5419727e637SJeff Roberson tdq_load_add(struct tdq *tdq, struct thread *td)
5425d7ef00cSJeff Roberson {
543ae7a6b38SJeff Roberson 
544ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
54561a74c5cSJeff Roberson 	THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
54603d17db7SJeff Roberson 
547d2ad694cSJeff Roberson 	tdq->tdq_load++;
5481b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
549d2ad694cSJeff Roberson 		tdq->tdq_sysload++;
5508f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
551d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
5525d7ef00cSJeff Roberson }
55315dc847eSJeff Roberson 
554ae7a6b38SJeff Roberson /*
555ae7a6b38SJeff Roberson  * Remove the load from a thread that is transitioning to a sleep state or
556ae7a6b38SJeff Roberson  * exiting.
557ae7a6b38SJeff Roberson  */
558a8949de2SJeff Roberson static void
5599727e637SJeff Roberson tdq_load_rem(struct tdq *tdq, struct thread *td)
5605d7ef00cSJeff Roberson {
561ae7a6b38SJeff Roberson 
562ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
56361a74c5cSJeff Roberson 	THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
564ae7a6b38SJeff Roberson 	KASSERT(tdq->tdq_load != 0,
565c47f202bSJeff Roberson 	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
56603d17db7SJeff Roberson 
567d2ad694cSJeff Roberson 	tdq->tdq_load--;
5681b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
56903d17db7SJeff Roberson 		tdq->tdq_sysload--;
5708f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
571d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
57215dc847eSJeff Roberson }
57315dc847eSJeff Roberson 
574356500a3SJeff Roberson /*
5755e5c3873SJeff Roberson  * Bound timeshare latency by decreasing slice size as load increases.  We
5765e5c3873SJeff Roberson  * consider the maximum latency as the sum of the threads waiting to run
5775e5c3873SJeff Roberson  * aside from curthread and target no more than sched_slice latency but
5785e5c3873SJeff Roberson  * no less than sched_slice_min runtime.
5795e5c3873SJeff Roberson  */
5805e5c3873SJeff Roberson static inline int
5815e5c3873SJeff Roberson tdq_slice(struct tdq *tdq)
5825e5c3873SJeff Roberson {
5835e5c3873SJeff Roberson 	int load;
5845e5c3873SJeff Roberson 
5855e5c3873SJeff Roberson 	/*
5865e5c3873SJeff Roberson 	 * It is safe to use sys_load here because this is called from
5875e5c3873SJeff Roberson 	 * contexts where timeshare threads are running and so there
5885e5c3873SJeff Roberson 	 * cannot be higher priority load in the system.
5895e5c3873SJeff Roberson 	 */
5905e5c3873SJeff Roberson 	load = tdq->tdq_sysload - 1;
5915e5c3873SJeff Roberson 	if (load >= SCHED_SLICE_MIN_DIVISOR)
5925e5c3873SJeff Roberson 		return (sched_slice_min);
5935e5c3873SJeff Roberson 	if (load <= 1)
5945e5c3873SJeff Roberson 		return (sched_slice);
5955e5c3873SJeff Roberson 	return (sched_slice / load);
5965e5c3873SJeff Roberson }
5975e5c3873SJeff Roberson 
5985e5c3873SJeff Roberson /*
59962fa74d9SJeff Roberson  * Set lowpri to its exact value by searching the run-queue and
60062fa74d9SJeff Roberson  * evaluating curthread.  curthread may be passed as an optimization.
601356500a3SJeff Roberson  */
60222bf7d9aSJeff Roberson static void
60362fa74d9SJeff Roberson tdq_setlowpri(struct tdq *tdq, struct thread *ctd)
60462fa74d9SJeff Roberson {
60562fa74d9SJeff Roberson 	struct thread *td;
60662fa74d9SJeff Roberson 
60762fa74d9SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
60862fa74d9SJeff Roberson 	if (ctd == NULL)
60962fa74d9SJeff Roberson 		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
6109727e637SJeff Roberson 	td = tdq_choose(tdq);
6119727e637SJeff Roberson 	if (td == NULL || td->td_priority > ctd->td_priority)
61262fa74d9SJeff Roberson 		tdq->tdq_lowpri = ctd->td_priority;
61362fa74d9SJeff Roberson 	else
61462fa74d9SJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
61562fa74d9SJeff Roberson }
61662fa74d9SJeff Roberson 
61762fa74d9SJeff Roberson #ifdef SMP
6189129dd59SPedro F. Giffuni /*
6199129dd59SPedro F. Giffuni  * We need some randomness. Implement a classic Linear Congruential
6209129dd59SPedro F. Giffuni  * Generator X_{n+1}=(aX_n+c) mod m. These values are optimized for
6219129dd59SPedro F. Giffuni  * m = 2^32, a = 69069 and c = 5. We only return the upper 16 bits
6229129dd59SPedro F. Giffuni  * of the random state (in the low bits of our answer) to keep
6239129dd59SPedro F. Giffuni  * the maximum randomness.
6249129dd59SPedro F. Giffuni  */
6259129dd59SPedro F. Giffuni static uint32_t
6269129dd59SPedro F. Giffuni sched_random(void)
6279129dd59SPedro F. Giffuni {
6289129dd59SPedro F. Giffuni 	uint32_t *rndptr;
6299129dd59SPedro F. Giffuni 
6309129dd59SPedro F. Giffuni 	rndptr = DPCPU_PTR(randomval);
6319129dd59SPedro F. Giffuni 	*rndptr = *rndptr * 69069 + 5;
6329129dd59SPedro F. Giffuni 
6339129dd59SPedro F. Giffuni 	return (*rndptr >> 16);
6349129dd59SPedro F. Giffuni }
6359129dd59SPedro F. Giffuni 
63662fa74d9SJeff Roberson struct cpu_search {
637e745d729SAlexander Motin 	cpuset_t *cs_mask;	/* The mask of allowed CPUs to choose from. */
638e745d729SAlexander Motin 	int	cs_prefer;	/* Prefer this CPU and groups including it. */
639e745d729SAlexander Motin 	int	cs_running;	/* The thread is now running at cs_prefer. */
64036acfc65SAlexander Motin 	int	cs_pri;		/* Min priority for low. */
64108063e9fSAlexander Motin 	int	cs_load;	/* Max load for low, min load for high. */
64208063e9fSAlexander Motin 	int	cs_trans;	/* Min transferable load for high. */
643aefe0a8cSAlexander Motin };
644aefe0a8cSAlexander Motin 
645aefe0a8cSAlexander Motin struct cpu_search_res {
64608063e9fSAlexander Motin 	int	csr_cpu;	/* The best CPU found. */
64708063e9fSAlexander Motin 	int	csr_load;	/* The load of cs_cpu. */
64862fa74d9SJeff Roberson };
64962fa74d9SJeff Roberson 
65062fa74d9SJeff Roberson /*
651aefe0a8cSAlexander Motin  * Search the tree of cpu_groups for the lowest or highest loaded CPU.
652aefe0a8cSAlexander Motin  * These routines actually compare the load on all paths through the tree
653aefe0a8cSAlexander Motin  * and find the least loaded cpu on the least loaded path, which may differ
654aefe0a8cSAlexander Motin  * from the least loaded cpu in the system.  This balances work among caches
655aefe0a8cSAlexander Motin  * and buses.
65662fa74d9SJeff Roberson  */
657aefe0a8cSAlexander Motin static int
658aefe0a8cSAlexander Motin cpu_search_lowest(const struct cpu_group *cg, const struct cpu_search *s,
659aefe0a8cSAlexander Motin     struct cpu_search_res *r)
66062fa74d9SJeff Roberson {
661aefe0a8cSAlexander Motin 	struct cpu_search_res lr;
66236acfc65SAlexander Motin 	struct tdq *tdq;
663e745d729SAlexander Motin 	int c, bload, l, load, p, total;
66462fa74d9SJeff Roberson 
66536acfc65SAlexander Motin 	total = 0;
666aefe0a8cSAlexander Motin 	bload = INT_MAX;
66708063e9fSAlexander Motin 	r->csr_cpu = -1;
66836acfc65SAlexander Motin 
669aefe0a8cSAlexander Motin 	/* Loop through children CPU groups if there are any. */
670aefe0a8cSAlexander Motin 	if (cg->cg_children > 0) {
671aefe0a8cSAlexander Motin 		for (c = cg->cg_children - 1; c >= 0; c--) {
672aefe0a8cSAlexander Motin 			load = cpu_search_lowest(&cg->cg_child[c], s, &lr);
67336acfc65SAlexander Motin 			total += load;
674e745d729SAlexander Motin 
675e745d729SAlexander Motin 			/*
676e745d729SAlexander Motin 			 * When balancing do not prefer SMT groups with load >1.
677e745d729SAlexander Motin 			 * It allows round-robin between SMT groups with equal
678e745d729SAlexander Motin 			 * load within parent group for more fair scheduling.
679e745d729SAlexander Motin 			 */
680e745d729SAlexander Motin 			if (__predict_false(s->cs_running) &&
681e745d729SAlexander Motin 			    (cg->cg_child[c].cg_flags & CG_FLAG_THREAD) &&
682e745d729SAlexander Motin 			    load >= 128 && (load & 128) != 0)
683e745d729SAlexander Motin 				load += 128;
684e745d729SAlexander Motin 
68508063e9fSAlexander Motin 			if (lr.csr_cpu >= 0 && (load < bload ||
68608063e9fSAlexander Motin 			    (load == bload && lr.csr_load < r->csr_load))) {
687aefe0a8cSAlexander Motin 				bload = load;
68808063e9fSAlexander Motin 				r->csr_cpu = lr.csr_cpu;
68908063e9fSAlexander Motin 				r->csr_load = lr.csr_load;
69036acfc65SAlexander Motin 			}
69136acfc65SAlexander Motin 		}
69262fa74d9SJeff Roberson 		return (total);
69362fa74d9SJeff Roberson 	}
69462fa74d9SJeff Roberson 
695aefe0a8cSAlexander Motin 	/* Loop through children CPUs otherwise. */
696aefe0a8cSAlexander Motin 	for (c = cg->cg_last; c >= cg->cg_first; c--) {
697aefe0a8cSAlexander Motin 		if (!CPU_ISSET(c, &cg->cg_mask))
698aefe0a8cSAlexander Motin 			continue;
699aefe0a8cSAlexander Motin 		tdq = TDQ_CPU(c);
700aefe0a8cSAlexander Motin 		l = tdq->tdq_load;
701e745d729SAlexander Motin 		if (c == s->cs_prefer) {
702e745d729SAlexander Motin 			if (__predict_false(s->cs_running))
703e745d729SAlexander Motin 				l--;
704e745d729SAlexander Motin 			p = 128;
705e745d729SAlexander Motin 		} else
706e745d729SAlexander Motin 			p = 0;
707aefe0a8cSAlexander Motin 		load = l * 256;
708e745d729SAlexander Motin 		total += load - p;
709e745d729SAlexander Motin 
710e745d729SAlexander Motin 		/*
711e745d729SAlexander Motin 		 * Check this CPU is acceptable.
712e745d729SAlexander Motin 		 * If the threads is already on the CPU, don't look on the TDQ
713e745d729SAlexander Motin 		 * priority, since it can be the priority of the thread itself.
714e745d729SAlexander Motin 		 */
71508063e9fSAlexander Motin 		if (l > s->cs_load || (tdq->tdq_lowpri <= s->cs_pri &&
716e745d729SAlexander Motin 		     (!s->cs_running || c != s->cs_prefer)) ||
717aefe0a8cSAlexander Motin 		    !CPU_ISSET(c, s->cs_mask))
718aefe0a8cSAlexander Motin 			continue;
719e745d729SAlexander Motin 
720e745d729SAlexander Motin 		/*
721e745d729SAlexander Motin 		 * When balancing do not prefer CPUs with load > 1.
722e745d729SAlexander Motin 		 * It allows round-robin between CPUs with equal load
723e745d729SAlexander Motin 		 * within the CPU group for more fair scheduling.
724e745d729SAlexander Motin 		 */
725e745d729SAlexander Motin 		if (__predict_false(s->cs_running) && l > 0)
726e745d729SAlexander Motin 			p = 0;
727e745d729SAlexander Motin 
728aefe0a8cSAlexander Motin 		load -= sched_random() % 128;
729e745d729SAlexander Motin 		if (bload > load - p) {
730e745d729SAlexander Motin 			bload = load - p;
73108063e9fSAlexander Motin 			r->csr_cpu = c;
73208063e9fSAlexander Motin 			r->csr_load = load;
733aefe0a8cSAlexander Motin 		}
734aefe0a8cSAlexander Motin 	}
735aefe0a8cSAlexander Motin 	return (total);
73662fa74d9SJeff Roberson }
73762fa74d9SJeff Roberson 
738aefe0a8cSAlexander Motin static int
739aefe0a8cSAlexander Motin cpu_search_highest(const struct cpu_group *cg, const struct cpu_search *s,
740aefe0a8cSAlexander Motin     struct cpu_search_res *r)
74162fa74d9SJeff Roberson {
742aefe0a8cSAlexander Motin 	struct cpu_search_res lr;
743aefe0a8cSAlexander Motin 	struct tdq *tdq;
744aefe0a8cSAlexander Motin 	int c, bload, l, load, total;
745aefe0a8cSAlexander Motin 
746aefe0a8cSAlexander Motin 	total = 0;
747aefe0a8cSAlexander Motin 	bload = INT_MIN;
74808063e9fSAlexander Motin 	r->csr_cpu = -1;
749aefe0a8cSAlexander Motin 
750aefe0a8cSAlexander Motin 	/* Loop through children CPU groups if there are any. */
751aefe0a8cSAlexander Motin 	if (cg->cg_children > 0) {
752aefe0a8cSAlexander Motin 		for (c = cg->cg_children - 1; c >= 0; c--) {
753aefe0a8cSAlexander Motin 			load = cpu_search_highest(&cg->cg_child[c], s, &lr);
754aefe0a8cSAlexander Motin 			total += load;
75508063e9fSAlexander Motin 			if (lr.csr_cpu >= 0 && (load > bload ||
75608063e9fSAlexander Motin 			    (load == bload && lr.csr_load > r->csr_load))) {
757aefe0a8cSAlexander Motin 				bload = load;
75808063e9fSAlexander Motin 				r->csr_cpu = lr.csr_cpu;
75908063e9fSAlexander Motin 				r->csr_load = lr.csr_load;
760aefe0a8cSAlexander Motin 			}
761aefe0a8cSAlexander Motin 		}
762aefe0a8cSAlexander Motin 		return (total);
76362fa74d9SJeff Roberson 	}
76462fa74d9SJeff Roberson 
765aefe0a8cSAlexander Motin 	/* Loop through children CPUs otherwise. */
766aefe0a8cSAlexander Motin 	for (c = cg->cg_last; c >= cg->cg_first; c--) {
767aefe0a8cSAlexander Motin 		if (!CPU_ISSET(c, &cg->cg_mask))
768aefe0a8cSAlexander Motin 			continue;
769aefe0a8cSAlexander Motin 		tdq = TDQ_CPU(c);
770aefe0a8cSAlexander Motin 		l = tdq->tdq_load;
771aefe0a8cSAlexander Motin 		load = l * 256;
772aefe0a8cSAlexander Motin 		total += load;
773e745d729SAlexander Motin 
774e745d729SAlexander Motin 		/*
775e745d729SAlexander Motin 		 * Check this CPU is acceptable.
776e745d729SAlexander Motin 		 */
77708063e9fSAlexander Motin 		if (l < s->cs_load || (tdq->tdq_transferable < s->cs_trans) ||
778aefe0a8cSAlexander Motin 		    !CPU_ISSET(c, s->cs_mask))
779aefe0a8cSAlexander Motin 			continue;
780e745d729SAlexander Motin 
781ca34553bSAlexander Motin 		load -= sched_random() % 256;
782aefe0a8cSAlexander Motin 		if (load > bload) {
783aefe0a8cSAlexander Motin 			bload = load;
78408063e9fSAlexander Motin 			r->csr_cpu = c;
785aefe0a8cSAlexander Motin 		}
786aefe0a8cSAlexander Motin 	}
78708063e9fSAlexander Motin 	r->csr_load = bload;
788aefe0a8cSAlexander Motin 	return (total);
78962fa74d9SJeff Roberson }
79062fa74d9SJeff Roberson 
79162fa74d9SJeff Roberson /*
79262fa74d9SJeff Roberson  * Find the cpu with the least load via the least loaded path that has a
79362fa74d9SJeff Roberson  * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
79462fa74d9SJeff Roberson  * acceptable.
79562fa74d9SJeff Roberson  */
79662fa74d9SJeff Roberson static inline int
797aefe0a8cSAlexander Motin sched_lowest(const struct cpu_group *cg, cpuset_t *mask, int pri, int maxload,
798e745d729SAlexander Motin     int prefer, int running)
79962fa74d9SJeff Roberson {
800aefe0a8cSAlexander Motin 	struct cpu_search s;
801aefe0a8cSAlexander Motin 	struct cpu_search_res r;
80262fa74d9SJeff Roberson 
803aefe0a8cSAlexander Motin 	s.cs_prefer = prefer;
804e745d729SAlexander Motin 	s.cs_running = running;
805aefe0a8cSAlexander Motin 	s.cs_mask = mask;
806aefe0a8cSAlexander Motin 	s.cs_pri = pri;
80708063e9fSAlexander Motin 	s.cs_load = maxload;
808aefe0a8cSAlexander Motin 	cpu_search_lowest(cg, &s, &r);
80908063e9fSAlexander Motin 	return (r.csr_cpu);
81062fa74d9SJeff Roberson }
81162fa74d9SJeff Roberson 
81262fa74d9SJeff Roberson /*
81362fa74d9SJeff Roberson  * Find the cpu with the highest load via the highest loaded path.
81462fa74d9SJeff Roberson  */
81562fa74d9SJeff Roberson static inline int
81608063e9fSAlexander Motin sched_highest(const struct cpu_group *cg, cpuset_t *mask, int minload,
81708063e9fSAlexander Motin     int mintrans)
81862fa74d9SJeff Roberson {
819aefe0a8cSAlexander Motin 	struct cpu_search s;
820aefe0a8cSAlexander Motin 	struct cpu_search_res r;
82162fa74d9SJeff Roberson 
822aefe0a8cSAlexander Motin 	s.cs_mask = mask;
82308063e9fSAlexander Motin 	s.cs_load = minload;
82408063e9fSAlexander Motin 	s.cs_trans = mintrans;
825aefe0a8cSAlexander Motin 	cpu_search_highest(cg, &s, &r);
82608063e9fSAlexander Motin 	return (r.csr_cpu);
82762fa74d9SJeff Roberson }
82862fa74d9SJeff Roberson 
82962fa74d9SJeff Roberson static void
83062fa74d9SJeff Roberson sched_balance_group(struct cpu_group *cg)
83162fa74d9SJeff Roberson {
832018ff686SJeff Roberson 	struct tdq *tdq;
833e745d729SAlexander Motin 	struct thread *td;
83436acfc65SAlexander Motin 	cpuset_t hmask, lmask;
83536acfc65SAlexander Motin 	int high, low, anylow;
83662fa74d9SJeff Roberson 
83736acfc65SAlexander Motin 	CPU_FILL(&hmask);
83862fa74d9SJeff Roberson 	for (;;) {
83908063e9fSAlexander Motin 		high = sched_highest(cg, &hmask, 1, 0);
84036acfc65SAlexander Motin 		/* Stop if there is no more CPU with transferrable threads. */
84136acfc65SAlexander Motin 		if (high == -1)
84262fa74d9SJeff Roberson 			break;
84336acfc65SAlexander Motin 		CPU_CLR(high, &hmask);
84436acfc65SAlexander Motin 		CPU_COPY(&hmask, &lmask);
84536acfc65SAlexander Motin 		/* Stop if there is no more CPU left for low. */
84636acfc65SAlexander Motin 		if (CPU_EMPTY(&lmask))
84762fa74d9SJeff Roberson 			break;
848018ff686SJeff Roberson 		tdq = TDQ_CPU(high);
849e745d729SAlexander Motin 		if (tdq->tdq_load == 1) {
850e745d729SAlexander Motin 			/*
851e745d729SAlexander Motin 			 * There is only one running thread.  We can't move
852e745d729SAlexander Motin 			 * it from here, so tell it to pick new CPU by itself.
853e745d729SAlexander Motin 			 */
854e745d729SAlexander Motin 			TDQ_LOCK(tdq);
855e745d729SAlexander Motin 			td = pcpu_find(high)->pc_curthread;
856e745d729SAlexander Motin 			if ((td->td_flags & TDF_IDLETD) == 0 &&
857e745d729SAlexander Motin 			    THREAD_CAN_MIGRATE(td)) {
858e745d729SAlexander Motin 				td->td_flags |= TDF_NEEDRESCHED | TDF_PICKCPU;
859e745d729SAlexander Motin 				if (high != curcpu)
860e745d729SAlexander Motin 					ipi_cpu(high, IPI_AST);
861e745d729SAlexander Motin 			}
862e745d729SAlexander Motin 			TDQ_UNLOCK(tdq);
863e745d729SAlexander Motin 			break;
864e745d729SAlexander Motin 		}
865e745d729SAlexander Motin 		anylow = 1;
86636acfc65SAlexander Motin nextlow:
867e745d729SAlexander Motin 		if (tdq->tdq_transferable == 0)
868e745d729SAlexander Motin 			continue;
869e745d729SAlexander Motin 		low = sched_lowest(cg, &lmask, -1, tdq->tdq_load - 1, high, 1);
87036acfc65SAlexander Motin 		/* Stop if we looked well and found no less loaded CPU. */
87136acfc65SAlexander Motin 		if (anylow && low == -1)
87236acfc65SAlexander Motin 			break;
87336acfc65SAlexander Motin 		/* Go to next high if we found no less loaded CPU. */
87436acfc65SAlexander Motin 		if (low == -1)
87536acfc65SAlexander Motin 			continue;
87636acfc65SAlexander Motin 		/* Transfer thread from high to low. */
877018ff686SJeff Roberson 		if (sched_balance_pair(tdq, TDQ_CPU(low))) {
87836acfc65SAlexander Motin 			/* CPU that got thread can no longer be a donor. */
87936acfc65SAlexander Motin 			CPU_CLR(low, &hmask);
88036acfc65SAlexander Motin 		} else {
88162fa74d9SJeff Roberson 			/*
88236acfc65SAlexander Motin 			 * If failed, then there is no threads on high
88336acfc65SAlexander Motin 			 * that can run on this low. Drop low from low
88436acfc65SAlexander Motin 			 * mask and look for different one.
88562fa74d9SJeff Roberson 			 */
88636acfc65SAlexander Motin 			CPU_CLR(low, &lmask);
88736acfc65SAlexander Motin 			anylow = 0;
88836acfc65SAlexander Motin 			goto nextlow;
88962fa74d9SJeff Roberson 		}
89036acfc65SAlexander Motin 	}
89162fa74d9SJeff Roberson }
89262fa74d9SJeff Roberson 
89362fa74d9SJeff Roberson static void
89462375ca8SEd Schouten sched_balance(void)
895356500a3SJeff Roberson {
8967fcf154aSJeff Roberson 	struct tdq *tdq;
897356500a3SJeff Roberson 
8980567b6ccSWarner Losh 	balance_ticks = max(balance_interval / 2, 1) +
899b250ad34SWarner Losh 	    (sched_random() % balance_interval);
9007fcf154aSJeff Roberson 	tdq = TDQ_SELF();
9017fcf154aSJeff Roberson 	TDQ_UNLOCK(tdq);
90262fa74d9SJeff Roberson 	sched_balance_group(cpu_top);
9037fcf154aSJeff Roberson 	TDQ_LOCK(tdq);
904cac77d04SJeff Roberson }
90586f8ae96SJeff Roberson 
906ae7a6b38SJeff Roberson /*
907ae7a6b38SJeff Roberson  * Lock two thread queues using their address to maintain lock order.
908ae7a6b38SJeff Roberson  */
909ae7a6b38SJeff Roberson static void
910ae7a6b38SJeff Roberson tdq_lock_pair(struct tdq *one, struct tdq *two)
911ae7a6b38SJeff Roberson {
912ae7a6b38SJeff Roberson 	if (one < two) {
913ae7a6b38SJeff Roberson 		TDQ_LOCK(one);
914ae7a6b38SJeff Roberson 		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
915ae7a6b38SJeff Roberson 	} else {
916ae7a6b38SJeff Roberson 		TDQ_LOCK(two);
917ae7a6b38SJeff Roberson 		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
918ae7a6b38SJeff Roberson 	}
919ae7a6b38SJeff Roberson }
920ae7a6b38SJeff Roberson 
921ae7a6b38SJeff Roberson /*
9227fcf154aSJeff Roberson  * Unlock two thread queues.  Order is not important here.
9237fcf154aSJeff Roberson  */
9247fcf154aSJeff Roberson static void
9257fcf154aSJeff Roberson tdq_unlock_pair(struct tdq *one, struct tdq *two)
9267fcf154aSJeff Roberson {
9277fcf154aSJeff Roberson 	TDQ_UNLOCK(one);
9287fcf154aSJeff Roberson 	TDQ_UNLOCK(two);
9297fcf154aSJeff Roberson }
9307fcf154aSJeff Roberson 
9317fcf154aSJeff Roberson /*
932ae7a6b38SJeff Roberson  * Transfer load between two imbalanced thread queues.
933ae7a6b38SJeff Roberson  */
93462fa74d9SJeff Roberson static int
935ad1e7d28SJulian Elischer sched_balance_pair(struct tdq *high, struct tdq *low)
936cac77d04SJeff Roberson {
93797e9382dSDon Lewis 	struct thread *td;
938880bf8b9SMarius Strobl 	int cpu;
939cac77d04SJeff Roberson 
940ae7a6b38SJeff Roberson 	tdq_lock_pair(high, low);
94197e9382dSDon Lewis 	td = NULL;
942155b9987SJeff Roberson 	/*
94397e9382dSDon Lewis 	 * Transfer a thread from high to low.
944155b9987SJeff Roberson 	 */
94536acfc65SAlexander Motin 	if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load &&
94697e9382dSDon Lewis 	    (td = tdq_move(high, low)) != NULL) {
947a5423ea3SJeff Roberson 		/*
94897e9382dSDon Lewis 		 * In case the target isn't the current cpu notify it of the
94997e9382dSDon Lewis 		 * new load, possibly sending an IPI to force it to reschedule.
950a5423ea3SJeff Roberson 		 */
951880bf8b9SMarius Strobl 		cpu = TDQ_ID(low);
952880bf8b9SMarius Strobl 		if (cpu != PCPU_GET(cpuid))
95397e9382dSDon Lewis 			tdq_notify(low, td);
954ae7a6b38SJeff Roberson 	}
9557fcf154aSJeff Roberson 	tdq_unlock_pair(high, low);
95697e9382dSDon Lewis 	return (td != NULL);
957356500a3SJeff Roberson }
958356500a3SJeff Roberson 
959ae7a6b38SJeff Roberson /*
960ae7a6b38SJeff Roberson  * Move a thread from one thread queue to another.
961ae7a6b38SJeff Roberson  */
96297e9382dSDon Lewis static struct thread *
963ae7a6b38SJeff Roberson tdq_move(struct tdq *from, struct tdq *to)
964356500a3SJeff Roberson {
965ae7a6b38SJeff Roberson 	struct thread *td;
966ae7a6b38SJeff Roberson 	struct tdq *tdq;
967ae7a6b38SJeff Roberson 	int cpu;
968356500a3SJeff Roberson 
9697fcf154aSJeff Roberson 	TDQ_LOCK_ASSERT(from, MA_OWNED);
9707fcf154aSJeff Roberson 	TDQ_LOCK_ASSERT(to, MA_OWNED);
9717fcf154aSJeff Roberson 
972ad1e7d28SJulian Elischer 	tdq = from;
973ae7a6b38SJeff Roberson 	cpu = TDQ_ID(to);
9749727e637SJeff Roberson 	td = tdq_steal(tdq, cpu);
9759727e637SJeff Roberson 	if (td == NULL)
97697e9382dSDon Lewis 		return (NULL);
97761a74c5cSJeff Roberson 
978ae7a6b38SJeff Roberson 	/*
97961a74c5cSJeff Roberson 	 * Although the run queue is locked the thread may be
98061a74c5cSJeff Roberson 	 * blocked.  We can not set the lock until it is unblocked.
981ae7a6b38SJeff Roberson 	 */
98261a74c5cSJeff Roberson 	thread_lock_block_wait(td);
983ae7a6b38SJeff Roberson 	sched_rem(td);
98461a74c5cSJeff Roberson 	THREAD_LOCKPTR_ASSERT(td, TDQ_LOCKPTR(from));
985ae7a6b38SJeff Roberson 	td->td_lock = TDQ_LOCKPTR(to);
98661a74c5cSJeff Roberson 	td_get_sched(td)->ts_cpu = cpu;
987ae7a6b38SJeff Roberson 	tdq_add(to, td, SRQ_YIELDING);
98861a74c5cSJeff Roberson 
98997e9382dSDon Lewis 	return (td);
990356500a3SJeff Roberson }
99122bf7d9aSJeff Roberson 
992ae7a6b38SJeff Roberson /*
993ae7a6b38SJeff Roberson  * This tdq has idled.  Try to steal a thread from another cpu and switch
994ae7a6b38SJeff Roberson  * to it.
995ae7a6b38SJeff Roberson  */
99680f86c9fSJeff Roberson static int
997ad1e7d28SJulian Elischer tdq_idled(struct tdq *tdq)
99822bf7d9aSJeff Roberson {
9992668bb2aSAlexander Motin 	struct cpu_group *cg, *parent;
1000ad1e7d28SJulian Elischer 	struct tdq *steal;
1001c76ee827SJeff Roberson 	cpuset_t mask;
10022668bb2aSAlexander Motin 	int cpu, switchcnt, goup;
100380f86c9fSJeff Roberson 
100497e9382dSDon Lewis 	if (smp_started == 0 || steal_idle == 0 || tdq->tdq_cg == NULL)
100588f530ccSJeff Roberson 		return (1);
1006c76ee827SJeff Roberson 	CPU_FILL(&mask);
1007c76ee827SJeff Roberson 	CPU_CLR(PCPU_GET(cpuid), &mask);
100897e9382dSDon Lewis     restart:
100997e9382dSDon Lewis 	switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
10102668bb2aSAlexander Motin 	for (cg = tdq->tdq_cg, goup = 0; ; ) {
101108063e9fSAlexander Motin 		cpu = sched_highest(cg, &mask, steal_thresh, 1);
101297e9382dSDon Lewis 		/*
101397e9382dSDon Lewis 		 * We were assigned a thread but not preempted.  Returning
101497e9382dSDon Lewis 		 * 0 here will cause our caller to switch to it.
101597e9382dSDon Lewis 		 */
101697e9382dSDon Lewis 		if (tdq->tdq_load)
101797e9382dSDon Lewis 			return (0);
10182668bb2aSAlexander Motin 
10192668bb2aSAlexander Motin 		/*
10202668bb2aSAlexander Motin 		 * We found no CPU to steal from in this group.  Escalate to
10212668bb2aSAlexander Motin 		 * the parent and repeat.  But if parent has only two children
10222668bb2aSAlexander Motin 		 * groups we can avoid searching this group again by searching
10232668bb2aSAlexander Motin 		 * the other one specifically and then escalating two levels.
10242668bb2aSAlexander Motin 		 */
102562fa74d9SJeff Roberson 		if (cpu == -1) {
10262668bb2aSAlexander Motin 			if (goup) {
102762fa74d9SJeff Roberson 				cg = cg->cg_parent;
10282668bb2aSAlexander Motin 				goup = 0;
10292668bb2aSAlexander Motin 			}
10302668bb2aSAlexander Motin 			parent = cg->cg_parent;
10312668bb2aSAlexander Motin 			if (parent == NULL)
103297e9382dSDon Lewis 				return (1);
10332668bb2aSAlexander Motin 			if (parent->cg_children == 2) {
10342668bb2aSAlexander Motin 				if (cg == &parent->cg_child[0])
10352668bb2aSAlexander Motin 					cg = &parent->cg_child[1];
10362668bb2aSAlexander Motin 				else
10372668bb2aSAlexander Motin 					cg = &parent->cg_child[0];
10382668bb2aSAlexander Motin 				goup = 1;
10392668bb2aSAlexander Motin 			} else
10402668bb2aSAlexander Motin 				cg = parent;
104180f86c9fSJeff Roberson 			continue;
10427b8bfa0dSJeff Roberson 		}
10437b8bfa0dSJeff Roberson 		steal = TDQ_CPU(cpu);
104497e9382dSDon Lewis 		/*
104597e9382dSDon Lewis 		 * The data returned by sched_highest() is stale and
104697e9382dSDon Lewis 		 * the chosen CPU no longer has an eligible thread.
104797e9382dSDon Lewis 		 *
104897e9382dSDon Lewis 		 * Testing this ahead of tdq_lock_pair() only catches
104997e9382dSDon Lewis 		 * this situation about 20% of the time on an 8 core
105097e9382dSDon Lewis 		 * 16 thread Ryzen 7, but it still helps performance.
105197e9382dSDon Lewis 		 */
105297e9382dSDon Lewis 		if (steal->tdq_load < steal_thresh ||
105397e9382dSDon Lewis 		    steal->tdq_transferable == 0)
105497e9382dSDon Lewis 			goto restart;
105597e9382dSDon Lewis 		/*
10568bb173fbSAlexander Motin 		 * Try to lock both queues. If we are assigned a thread while
10578bb173fbSAlexander Motin 		 * waited for the lock, switch to it now instead of stealing.
10588bb173fbSAlexander Motin 		 * If we can't get the lock, then somebody likely got there
10598bb173fbSAlexander Motin 		 * first so continue searching.
106097e9382dSDon Lewis 		 */
10618bb173fbSAlexander Motin 		TDQ_LOCK(tdq);
10628bb173fbSAlexander Motin 		if (tdq->tdq_load > 0) {
10638bb173fbSAlexander Motin 			mi_switch(SW_VOL | SWT_IDLE);
10648bb173fbSAlexander Motin 			return (0);
10658bb173fbSAlexander Motin 		}
10668bb173fbSAlexander Motin 		if (TDQ_TRYLOCK_FLAGS(steal, MTX_DUPOK) == 0) {
10678bb173fbSAlexander Motin 			TDQ_UNLOCK(tdq);
10688bb173fbSAlexander Motin 			CPU_CLR(cpu, &mask);
10698bb173fbSAlexander Motin 			continue;
10708bb173fbSAlexander Motin 		}
107197e9382dSDon Lewis 		/*
107297e9382dSDon Lewis 		 * The data returned by sched_highest() is stale and
107397e9382dSDon Lewis 		 * the chosen CPU no longer has an eligible thread, or
107497e9382dSDon Lewis 		 * we were preempted and the CPU loading info may be out
107597e9382dSDon Lewis 		 * of date.  The latter is rare.  In either case restart
107697e9382dSDon Lewis 		 * the search.
107797e9382dSDon Lewis 		 */
107897e9382dSDon Lewis 		if (steal->tdq_load < steal_thresh ||
107997e9382dSDon Lewis 		    steal->tdq_transferable == 0 ||
108097e9382dSDon Lewis 		    switchcnt != tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt) {
10817fcf154aSJeff Roberson 			tdq_unlock_pair(tdq, steal);
108297e9382dSDon Lewis 			goto restart;
108362fa74d9SJeff Roberson 		}
108462fa74d9SJeff Roberson 		/*
108597e9382dSDon Lewis 		 * Steal the thread and switch to it.
108662fa74d9SJeff Roberson 		 */
108797e9382dSDon Lewis 		if (tdq_move(steal, tdq) != NULL)
108897e9382dSDon Lewis 			break;
108997e9382dSDon Lewis 		/*
109097e9382dSDon Lewis 		 * We failed to acquire a thread even though it looked
109197e9382dSDon Lewis 		 * like one was available.  This could be due to affinity
109297e9382dSDon Lewis 		 * restrictions or for other reasons.  Loop again after
109397e9382dSDon Lewis 		 * removing this CPU from the set.  The restart logic
109497e9382dSDon Lewis 		 * above does not restore this CPU to the set due to the
109597e9382dSDon Lewis 		 * likelyhood of failing here again.
109697e9382dSDon Lewis 		 */
109797e9382dSDon Lewis 		CPU_CLR(cpu, &mask);
109862fa74d9SJeff Roberson 		tdq_unlock_pair(tdq, steal);
109980f86c9fSJeff Roberson 	}
1100ae7a6b38SJeff Roberson 	TDQ_UNLOCK(steal);
1101686bcb5cSJeff Roberson 	mi_switch(SW_VOL | SWT_IDLE);
11027b8bfa0dSJeff Roberson 	return (0);
110322bf7d9aSJeff Roberson }
110422bf7d9aSJeff Roberson 
1105ae7a6b38SJeff Roberson /*
1106ae7a6b38SJeff Roberson  * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
1107ae7a6b38SJeff Roberson  */
110822bf7d9aSJeff Roberson static void
110927ee18adSRyan Stone tdq_notify(struct tdq *tdq, struct thread *td)
111022bf7d9aSJeff Roberson {
111102f0ff6dSJohn Baldwin 	struct thread *ctd;
111227ee18adSRyan Stone 	int pri;
11137b8bfa0dSJeff Roberson 	int cpu;
111422bf7d9aSJeff Roberson 
11157789ab32SMark Johnston 	if (tdq->tdq_owepreempt)
1116ff256d9cSJeff Roberson 		return;
111727ee18adSRyan Stone 	cpu = td_get_sched(td)->ts_cpu;
111827ee18adSRyan Stone 	pri = td->td_priority;
111902f0ff6dSJohn Baldwin 	ctd = pcpu_find(cpu)->pc_curthread;
112002f0ff6dSJohn Baldwin 	if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
11216b2f763fSJeff Roberson 		return;
112279654969SAlexander Motin 
112379654969SAlexander Motin 	/*
1124ae9e9b4fSAlexander Motin 	 * Make sure that our caller's earlier update to tdq_load is
1125ae9e9b4fSAlexander Motin 	 * globally visible before we read tdq_cpu_idle.  Idle thread
112679654969SAlexander Motin 	 * accesses both of them without locks, and the order is important.
112779654969SAlexander Motin 	 */
1128e8677f38SKonstantin Belousov 	atomic_thread_fence_seq_cst();
112979654969SAlexander Motin 
113002f0ff6dSJohn Baldwin 	if (TD_IS_IDLETHREAD(ctd)) {
11311690c6c1SJeff Roberson 		/*
11326c47aaaeSJeff Roberson 		 * If the MD code has an idle wakeup routine try that before
11336c47aaaeSJeff Roberson 		 * falling back to IPI.
11346c47aaaeSJeff Roberson 		 */
11359f9ad565SAlexander Motin 		if (!tdq->tdq_cpu_idle || cpu_idle_wakeup(cpu))
11366c47aaaeSJeff Roberson 			return;
11371690c6c1SJeff Roberson 	}
11387789ab32SMark Johnston 
11397789ab32SMark Johnston 	/*
11407789ab32SMark Johnston 	 * The run queues have been updated, so any switch on the remote CPU
11417789ab32SMark Johnston 	 * will satisfy the preemption request.
11427789ab32SMark Johnston 	 */
11437789ab32SMark Johnston 	tdq->tdq_owepreempt = 1;
1144d9d8d144SJohn Baldwin 	ipi_cpu(cpu, IPI_PREEMPT);
114522bf7d9aSJeff Roberson }
114622bf7d9aSJeff Roberson 
1147ae7a6b38SJeff Roberson /*
1148ae7a6b38SJeff Roberson  * Steals load from a timeshare queue.  Honors the rotating queue head
1149ae7a6b38SJeff Roberson  * index.
1150ae7a6b38SJeff Roberson  */
11519727e637SJeff Roberson static struct thread *
115262fa74d9SJeff Roberson runq_steal_from(struct runq *rq, int cpu, u_char start)
1153ae7a6b38SJeff Roberson {
1154ae7a6b38SJeff Roberson 	struct rqbits *rqb;
1155ae7a6b38SJeff Roberson 	struct rqhead *rqh;
115636acfc65SAlexander Motin 	struct thread *td, *first;
1157ae7a6b38SJeff Roberson 	int bit;
1158ae7a6b38SJeff Roberson 	int i;
1159ae7a6b38SJeff Roberson 
1160ae7a6b38SJeff Roberson 	rqb = &rq->rq_status;
1161ae7a6b38SJeff Roberson 	bit = start & (RQB_BPW -1);
116236acfc65SAlexander Motin 	first = NULL;
1163ae7a6b38SJeff Roberson again:
1164ae7a6b38SJeff Roberson 	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1165ae7a6b38SJeff Roberson 		if (rqb->rqb_bits[i] == 0)
1166ae7a6b38SJeff Roberson 			continue;
11678bc713f6SJeff Roberson 		if (bit == 0)
11688bc713f6SJeff Roberson 			bit = RQB_FFS(rqb->rqb_bits[i]);
11698bc713f6SJeff Roberson 		for (; bit < RQB_BPW; bit++) {
11708bc713f6SJeff Roberson 			if ((rqb->rqb_bits[i] & (1ul << bit)) == 0)
1171ae7a6b38SJeff Roberson 				continue;
11728bc713f6SJeff Roberson 			rqh = &rq->rq_queues[bit + (i << RQB_L2BPW)];
11739727e637SJeff Roberson 			TAILQ_FOREACH(td, rqh, td_runq) {
1174bd84094aSAlexander Motin 				if (first) {
1175bd84094aSAlexander Motin 					if (THREAD_CAN_MIGRATE(td) &&
11769727e637SJeff Roberson 					    THREAD_CAN_SCHED(td, cpu))
11779727e637SJeff Roberson 						return (td);
1178bd84094aSAlexander Motin 				} else
117936acfc65SAlexander Motin 					first = td;
1180ae7a6b38SJeff Roberson 			}
1181ae7a6b38SJeff Roberson 		}
11828bc713f6SJeff Roberson 	}
1183ae7a6b38SJeff Roberson 	if (start != 0) {
1184ae7a6b38SJeff Roberson 		start = 0;
1185ae7a6b38SJeff Roberson 		goto again;
1186ae7a6b38SJeff Roberson 	}
1187ae7a6b38SJeff Roberson 
118836acfc65SAlexander Motin 	if (first && THREAD_CAN_MIGRATE(first) &&
118936acfc65SAlexander Motin 	    THREAD_CAN_SCHED(first, cpu))
119036acfc65SAlexander Motin 		return (first);
1191ae7a6b38SJeff Roberson 	return (NULL);
1192ae7a6b38SJeff Roberson }
1193ae7a6b38SJeff Roberson 
1194ae7a6b38SJeff Roberson /*
1195ae7a6b38SJeff Roberson  * Steals load from a standard linear queue.
1196ae7a6b38SJeff Roberson  */
11979727e637SJeff Roberson static struct thread *
119862fa74d9SJeff Roberson runq_steal(struct runq *rq, int cpu)
119922bf7d9aSJeff Roberson {
120022bf7d9aSJeff Roberson 	struct rqhead *rqh;
120122bf7d9aSJeff Roberson 	struct rqbits *rqb;
12029727e637SJeff Roberson 	struct thread *td;
120322bf7d9aSJeff Roberson 	int word;
120422bf7d9aSJeff Roberson 	int bit;
120522bf7d9aSJeff Roberson 
120622bf7d9aSJeff Roberson 	rqb = &rq->rq_status;
120722bf7d9aSJeff Roberson 	for (word = 0; word < RQB_LEN; word++) {
120822bf7d9aSJeff Roberson 		if (rqb->rqb_bits[word] == 0)
120922bf7d9aSJeff Roberson 			continue;
121022bf7d9aSJeff Roberson 		for (bit = 0; bit < RQB_BPW; bit++) {
1211a2640c9bSPeter Wemm 			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
121222bf7d9aSJeff Roberson 				continue;
121322bf7d9aSJeff Roberson 			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
12149727e637SJeff Roberson 			TAILQ_FOREACH(td, rqh, td_runq)
12159727e637SJeff Roberson 				if (THREAD_CAN_MIGRATE(td) &&
12169727e637SJeff Roberson 				    THREAD_CAN_SCHED(td, cpu))
12179727e637SJeff Roberson 					return (td);
121822bf7d9aSJeff Roberson 		}
121922bf7d9aSJeff Roberson 	}
122022bf7d9aSJeff Roberson 	return (NULL);
122122bf7d9aSJeff Roberson }
122222bf7d9aSJeff Roberson 
1223ae7a6b38SJeff Roberson /*
1224ae7a6b38SJeff Roberson  * Attempt to steal a thread in priority order from a thread queue.
1225ae7a6b38SJeff Roberson  */
12269727e637SJeff Roberson static struct thread *
122762fa74d9SJeff Roberson tdq_steal(struct tdq *tdq, int cpu)
122822bf7d9aSJeff Roberson {
12299727e637SJeff Roberson 	struct thread *td;
123022bf7d9aSJeff Roberson 
1231ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
12329727e637SJeff Roberson 	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
12339727e637SJeff Roberson 		return (td);
12349727e637SJeff Roberson 	if ((td = runq_steal_from(&tdq->tdq_timeshare,
12359727e637SJeff Roberson 	    cpu, tdq->tdq_ridx)) != NULL)
12369727e637SJeff Roberson 		return (td);
123762fa74d9SJeff Roberson 	return (runq_steal(&tdq->tdq_idle, cpu));
123822bf7d9aSJeff Roberson }
123980f86c9fSJeff Roberson 
1240ae7a6b38SJeff Roberson /*
1241ae7a6b38SJeff Roberson  * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
12427fcf154aSJeff Roberson  * current lock and returns with the assigned queue locked.
1243ae7a6b38SJeff Roberson  */
1244ae7a6b38SJeff Roberson static inline struct tdq *
12459727e637SJeff Roberson sched_setcpu(struct thread *td, int cpu, int flags)
124680f86c9fSJeff Roberson {
12479727e637SJeff Roberson 
1248ae7a6b38SJeff Roberson 	struct tdq *tdq;
124961a74c5cSJeff Roberson 	struct mtx *mtx;
125080f86c9fSJeff Roberson 
12519727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1252ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpu);
125393ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_cpu = cpu;
12549727e637SJeff Roberson 	/*
12559727e637SJeff Roberson 	 * If the lock matches just return the queue.
12569727e637SJeff Roberson 	 */
125761a74c5cSJeff Roberson 	if (td->td_lock == TDQ_LOCKPTR(tdq)) {
125861a74c5cSJeff Roberson 		KASSERT((flags & SRQ_HOLD) == 0,
125961a74c5cSJeff Roberson 		    ("sched_setcpu: Invalid lock for SRQ_HOLD"));
1260ae7a6b38SJeff Roberson 		return (tdq);
1261ae7a6b38SJeff Roberson 	}
126261a74c5cSJeff Roberson 
126380f86c9fSJeff Roberson 	/*
1264ae7a6b38SJeff Roberson 	 * The hard case, migration, we need to block the thread first to
1265ae7a6b38SJeff Roberson 	 * prevent order reversals with other cpus locks.
12667b8bfa0dSJeff Roberson 	 */
1267b0b9dee5SAttilio Rao 	spinlock_enter();
126861a74c5cSJeff Roberson 	mtx = thread_lock_block(td);
126961a74c5cSJeff Roberson 	if ((flags & SRQ_HOLD) == 0)
127061a74c5cSJeff Roberson 		mtx_unlock_spin(mtx);
1271ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
1272ae7a6b38SJeff Roberson 	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1273b0b9dee5SAttilio Rao 	spinlock_exit();
1274ae7a6b38SJeff Roberson 	return (tdq);
127580f86c9fSJeff Roberson }
12762454aaf5SJeff Roberson 
12778df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
12788df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
12798df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
12808df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
12818df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
12828df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
12838df78c41SJeff Roberson 
1284ae7a6b38SJeff Roberson static int
12859727e637SJeff Roberson sched_pickcpu(struct thread *td, int flags)
1286ae7a6b38SJeff Roberson {
128736acfc65SAlexander Motin 	struct cpu_group *cg, *ccg;
12889727e637SJeff Roberson 	struct td_sched *ts;
1289ae7a6b38SJeff Roberson 	struct tdq *tdq;
1290aefe0a8cSAlexander Motin 	cpuset_t *mask;
1291e745d729SAlexander Motin 	int cpu, pri, r, self, intr;
12927b8bfa0dSJeff Roberson 
129362fa74d9SJeff Roberson 	self = PCPU_GET(cpuid);
129493ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1295efe67753SNathan Whitehorn 	KASSERT(!CPU_ABSENT(ts->ts_cpu), ("sched_pickcpu: Start scheduler on "
1296efe67753SNathan Whitehorn 	    "absent CPU %d for thread %s.", ts->ts_cpu, td->td_name));
12977b8bfa0dSJeff Roberson 	if (smp_started == 0)
12987b8bfa0dSJeff Roberson 		return (self);
129928994a58SJeff Roberson 	/*
130028994a58SJeff Roberson 	 * Don't migrate a running thread from sched_switch().
130128994a58SJeff Roberson 	 */
130262fa74d9SJeff Roberson 	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
130362fa74d9SJeff Roberson 		return (ts->ts_cpu);
13047b8bfa0dSJeff Roberson 	/*
130562fa74d9SJeff Roberson 	 * Prefer to run interrupt threads on the processors that generate
130662fa74d9SJeff Roberson 	 * the interrupt.
13077b8bfa0dSJeff Roberson 	 */
130862fa74d9SJeff Roberson 	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1309c9205e35SAlexander Motin 	    curthread->td_intr_nesting_level) {
1310c55dc51cSAlexander Motin 		tdq = TDQ_SELF();
1311c55dc51cSAlexander Motin 		if (tdq->tdq_lowpri >= PRI_MIN_IDLE) {
1312c55dc51cSAlexander Motin 			SCHED_STAT_INC(pickcpu_idle_affinity);
1313c55dc51cSAlexander Motin 			return (self);
1314c55dc51cSAlexander Motin 		}
131562fa74d9SJeff Roberson 		ts->ts_cpu = self;
1316c9205e35SAlexander Motin 		intr = 1;
1317c55dc51cSAlexander Motin 		cg = tdq->tdq_cg;
1318c55dc51cSAlexander Motin 		goto llc;
1319c55dc51cSAlexander Motin 	} else {
1320c9205e35SAlexander Motin 		intr = 0;
1321c55dc51cSAlexander Motin 		tdq = TDQ_CPU(ts->ts_cpu);
1322c55dc51cSAlexander Motin 		cg = tdq->tdq_cg;
1323c55dc51cSAlexander Motin 	}
13247b8bfa0dSJeff Roberson 	/*
132536acfc65SAlexander Motin 	 * If the thread can run on the last cpu and the affinity has not
13260127914cSEric van Gyzen 	 * expired and it is idle, run it there.
13277b8bfa0dSJeff Roberson 	 */
132836acfc65SAlexander Motin 	if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
132936acfc65SAlexander Motin 	    tdq->tdq_lowpri >= PRI_MIN_IDLE &&
133036acfc65SAlexander Motin 	    SCHED_AFFINITY(ts, CG_SHARE_L2)) {
1331c55dc51cSAlexander Motin 		if (cg->cg_flags & CG_FLAG_THREAD) {
1332176dd236SAlexander Motin 			/* Check all SMT threads for being idle. */
1333aefe0a8cSAlexander Motin 			for (cpu = cg->cg_first; cpu <= cg->cg_last; cpu++) {
1334176dd236SAlexander Motin 				if (CPU_ISSET(cpu, &cg->cg_mask) &&
1335176dd236SAlexander Motin 				    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE)
133662fa74d9SJeff Roberson 					break;
1337aefe0a8cSAlexander Motin 			}
1338aefe0a8cSAlexander Motin 			if (cpu > cg->cg_last) {
1339176dd236SAlexander Motin 				SCHED_STAT_INC(pickcpu_idle_affinity);
1340176dd236SAlexander Motin 				return (ts->ts_cpu);
134136acfc65SAlexander Motin 			}
1342176dd236SAlexander Motin 		} else {
134336acfc65SAlexander Motin 			SCHED_STAT_INC(pickcpu_idle_affinity);
134436acfc65SAlexander Motin 			return (ts->ts_cpu);
134536acfc65SAlexander Motin 		}
134636acfc65SAlexander Motin 	}
1347c55dc51cSAlexander Motin llc:
134836acfc65SAlexander Motin 	/*
134936acfc65SAlexander Motin 	 * Search for the last level cache CPU group in the tree.
1350c9205e35SAlexander Motin 	 * Skip SMT, identical groups and caches with expired affinity.
1351c9205e35SAlexander Motin 	 * Interrupt threads affinity is explicit and never expires.
135236acfc65SAlexander Motin 	 */
135336acfc65SAlexander Motin 	for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
135436acfc65SAlexander Motin 		if (cg->cg_flags & CG_FLAG_THREAD)
135536acfc65SAlexander Motin 			continue;
1356c9205e35SAlexander Motin 		if (cg->cg_children == 1 || cg->cg_count == 1)
1357c9205e35SAlexander Motin 			continue;
1358c9205e35SAlexander Motin 		if (cg->cg_level == CG_SHARE_NONE ||
1359c9205e35SAlexander Motin 		    (!intr && !SCHED_AFFINITY(ts, cg->cg_level)))
136036acfc65SAlexander Motin 			continue;
136136acfc65SAlexander Motin 		ccg = cg;
136236acfc65SAlexander Motin 	}
1363c9205e35SAlexander Motin 	/* Found LLC shared by all CPUs, so do a global search. */
1364c9205e35SAlexander Motin 	if (ccg == cpu_top)
1365c9205e35SAlexander Motin 		ccg = NULL;
136662fa74d9SJeff Roberson 	cpu = -1;
1367aefe0a8cSAlexander Motin 	mask = &td->td_cpuset->cs_mask;
1368c9205e35SAlexander Motin 	pri = td->td_priority;
1369e745d729SAlexander Motin 	r = TD_IS_RUNNING(td);
1370c9205e35SAlexander Motin 	/*
1371c9205e35SAlexander Motin 	 * Try hard to keep interrupts within found LLC.  Search the LLC for
1372c9205e35SAlexander Motin 	 * the least loaded CPU we can run now.  For NUMA systems it should
1373c9205e35SAlexander Motin 	 * be within target domain, and it also reduces scheduling overhead.
1374c9205e35SAlexander Motin 	 */
1375c9205e35SAlexander Motin 	if (ccg != NULL && intr) {
1376e745d729SAlexander Motin 		cpu = sched_lowest(ccg, mask, pri, INT_MAX, ts->ts_cpu, r);
1377c9205e35SAlexander Motin 		if (cpu >= 0)
1378c9205e35SAlexander Motin 			SCHED_STAT_INC(pickcpu_intrbind);
1379c9205e35SAlexander Motin 	} else
1380c9205e35SAlexander Motin 	/* Search the LLC for the least loaded idle CPU we can run now. */
1381c9205e35SAlexander Motin 	if (ccg != NULL) {
1382c9205e35SAlexander Motin 		cpu = sched_lowest(ccg, mask, max(pri, PRI_MAX_TIMESHARE),
1383e745d729SAlexander Motin 		    INT_MAX, ts->ts_cpu, r);
1384c9205e35SAlexander Motin 		if (cpu >= 0)
1385c9205e35SAlexander Motin 			SCHED_STAT_INC(pickcpu_affinity);
1386c9205e35SAlexander Motin 	}
1387c9205e35SAlexander Motin 	/* Search globally for the least loaded CPU we can run now. */
1388c9205e35SAlexander Motin 	if (cpu < 0) {
1389e745d729SAlexander Motin 		cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu, r);
1390c9205e35SAlexander Motin 		if (cpu >= 0)
1391c9205e35SAlexander Motin 			SCHED_STAT_INC(pickcpu_lowest);
1392c9205e35SAlexander Motin 	}
1393c9205e35SAlexander Motin 	/* Search globally for the least loaded CPU. */
1394c9205e35SAlexander Motin 	if (cpu < 0) {
1395e745d729SAlexander Motin 		cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu, r);
1396c9205e35SAlexander Motin 		if (cpu >= 0)
1397c9205e35SAlexander Motin 			SCHED_STAT_INC(pickcpu_lowest);
1398c9205e35SAlexander Motin 	}
1399bb3dfc6aSAlexander Motin 	KASSERT(cpu >= 0, ("sched_pickcpu: Failed to find a cpu."));
1400efe67753SNathan Whitehorn 	KASSERT(!CPU_ABSENT(cpu), ("sched_pickcpu: Picked absent CPU %d.", cpu));
140162fa74d9SJeff Roberson 	/*
140262fa74d9SJeff Roberson 	 * Compare the lowest loaded cpu to current cpu.
140362fa74d9SJeff Roberson 	 */
1404018ff686SJeff Roberson 	tdq = TDQ_CPU(cpu);
1405018ff686SJeff Roberson 	if (THREAD_CAN_SCHED(td, self) && TDQ_SELF()->tdq_lowpri > pri &&
1406018ff686SJeff Roberson 	    tdq->tdq_lowpri < PRI_MIN_IDLE &&
1407018ff686SJeff Roberson 	    TDQ_SELF()->tdq_load <= tdq->tdq_load + 1) {
14088df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_local);
140962fa74d9SJeff Roberson 		cpu = self;
1410c9205e35SAlexander Motin 	}
14118df78c41SJeff Roberson 	if (cpu != ts->ts_cpu)
14128df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_migration);
1413ae7a6b38SJeff Roberson 	return (cpu);
141480f86c9fSJeff Roberson }
141562fa74d9SJeff Roberson #endif
141622bf7d9aSJeff Roberson 
141722bf7d9aSJeff Roberson /*
141822bf7d9aSJeff Roberson  * Pick the highest priority task we have and return it.
14190c0a98b2SJeff Roberson  */
14209727e637SJeff Roberson static struct thread *
1421ad1e7d28SJulian Elischer tdq_choose(struct tdq *tdq)
14225d7ef00cSJeff Roberson {
14239727e637SJeff Roberson 	struct thread *td;
14245d7ef00cSJeff Roberson 
1425ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
14269727e637SJeff Roberson 	td = runq_choose(&tdq->tdq_realtime);
14279727e637SJeff Roberson 	if (td != NULL)
14289727e637SJeff Roberson 		return (td);
14299727e637SJeff Roberson 	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
14309727e637SJeff Roberson 	if (td != NULL) {
143112d56c0fSJohn Baldwin 		KASSERT(td->td_priority >= PRI_MIN_BATCH,
1432e7d50326SJeff Roberson 		    ("tdq_choose: Invalid priority on timeshare queue %d",
14339727e637SJeff Roberson 		    td->td_priority));
14349727e637SJeff Roberson 		return (td);
143515dc847eSJeff Roberson 	}
14369727e637SJeff Roberson 	td = runq_choose(&tdq->tdq_idle);
14379727e637SJeff Roberson 	if (td != NULL) {
14389727e637SJeff Roberson 		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1439e7d50326SJeff Roberson 		    ("tdq_choose: Invalid priority on idle queue %d",
14409727e637SJeff Roberson 		    td->td_priority));
14419727e637SJeff Roberson 		return (td);
1442e7d50326SJeff Roberson 	}
1443e7d50326SJeff Roberson 
1444e7d50326SJeff Roberson 	return (NULL);
1445245f3abfSJeff Roberson }
14460a016a05SJeff Roberson 
1447ae7a6b38SJeff Roberson /*
1448ae7a6b38SJeff Roberson  * Initialize a thread queue.
1449ae7a6b38SJeff Roberson  */
14500a016a05SJeff Roberson static void
1451018ff686SJeff Roberson tdq_setup(struct tdq *tdq, int id)
14520a016a05SJeff Roberson {
1453ae7a6b38SJeff Roberson 
1454c47f202bSJeff Roberson 	if (bootverbose)
1455018ff686SJeff Roberson 		printf("ULE: setup cpu %d\n", id);
1456e7d50326SJeff Roberson 	runq_init(&tdq->tdq_realtime);
1457e7d50326SJeff Roberson 	runq_init(&tdq->tdq_timeshare);
1458d2ad694cSJeff Roberson 	runq_init(&tdq->tdq_idle);
1459018ff686SJeff Roberson 	tdq->tdq_id = id;
146062fa74d9SJeff Roberson 	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
146162fa74d9SJeff Roberson 	    "sched lock %d", (int)TDQ_ID(tdq));
146261a74c5cSJeff Roberson 	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock", MTX_SPIN);
14638f51ad55SJeff Roberson #ifdef KTR
14648f51ad55SJeff Roberson 	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
14658f51ad55SJeff Roberson 	    "CPU %d load", (int)TDQ_ID(tdq));
14668f51ad55SJeff Roberson #endif
14670a016a05SJeff Roberson }
14680a016a05SJeff Roberson 
1469c47f202bSJeff Roberson #ifdef SMP
1470c47f202bSJeff Roberson static void
1471c47f202bSJeff Roberson sched_setup_smp(void)
1472c47f202bSJeff Roberson {
1473c47f202bSJeff Roberson 	struct tdq *tdq;
1474c47f202bSJeff Roberson 	int i;
1475c47f202bSJeff Roberson 
147662fa74d9SJeff Roberson 	cpu_top = smp_topo();
14773aa6d94eSJohn Baldwin 	CPU_FOREACH(i) {
1478018ff686SJeff Roberson 		tdq = DPCPU_ID_PTR(i, tdq);
1479018ff686SJeff Roberson 		tdq_setup(tdq, i);
148062fa74d9SJeff Roberson 		tdq->tdq_cg = smp_topo_find(cpu_top, i);
148162fa74d9SJeff Roberson 		if (tdq->tdq_cg == NULL)
148262fa74d9SJeff Roberson 			panic("Can't find cpu group for %d\n", i);
1483ca34553bSAlexander Motin 		DPCPU_ID_SET(i, randomval, i * 69069 + 5);
1484c47f202bSJeff Roberson 	}
1485018ff686SJeff Roberson 	PCPU_SET(sched, DPCPU_PTR(tdq));
148662fa74d9SJeff Roberson 	balance_tdq = TDQ_SELF();
1487c47f202bSJeff Roberson }
1488c47f202bSJeff Roberson #endif
1489c47f202bSJeff Roberson 
1490ae7a6b38SJeff Roberson /*
1491ae7a6b38SJeff Roberson  * Setup the thread queues and initialize the topology based on MD
1492ae7a6b38SJeff Roberson  * information.
1493ae7a6b38SJeff Roberson  */
149435e6168fSJeff Roberson static void
149535e6168fSJeff Roberson sched_setup(void *dummy)
149635e6168fSJeff Roberson {
1497ae7a6b38SJeff Roberson 	struct tdq *tdq;
1498c47f202bSJeff Roberson 
14990ec896fdSJeff Roberson #ifdef SMP
1500c47f202bSJeff Roberson 	sched_setup_smp();
1501749d01b0SJeff Roberson #else
1502018ff686SJeff Roberson 	tdq_setup(TDQ_SELF(), 0);
1503356500a3SJeff Roberson #endif
1504018ff686SJeff Roberson 	tdq = TDQ_SELF();
1505ae7a6b38SJeff Roberson 
1506ae7a6b38SJeff Roberson 	/* Add thread0's load since it's running. */
1507ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
1508e1504695SJeff Roberson 	thread0.td_lock = TDQ_LOCKPTR(tdq);
15099727e637SJeff Roberson 	tdq_load_add(tdq, &thread0);
151062fa74d9SJeff Roberson 	tdq->tdq_lowpri = thread0.td_priority;
1511ae7a6b38SJeff Roberson 	TDQ_UNLOCK(tdq);
151235e6168fSJeff Roberson }
151335e6168fSJeff Roberson 
1514ae7a6b38SJeff Roberson /*
1515579895dfSAlexander Motin  * This routine determines time constants after stathz and hz are setup.
1516ae7a6b38SJeff Roberson  */
1517a1d4fe69SDavid Xu /* ARGSUSED */
1518a1d4fe69SDavid Xu static void
1519a1d4fe69SDavid Xu sched_initticks(void *dummy)
1520a1d4fe69SDavid Xu {
1521ae7a6b38SJeff Roberson 	int incr;
1522ae7a6b38SJeff Roberson 
1523a1d4fe69SDavid Xu 	realstathz = stathz ? stathz : hz;
15245e5c3873SJeff Roberson 	sched_slice = realstathz / SCHED_SLICE_DEFAULT_DIVISOR;
15255e5c3873SJeff Roberson 	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
152637f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
152737f4e025SAlexander Motin 	    realstathz);
1528a1d4fe69SDavid Xu 
1529a1d4fe69SDavid Xu 	/*
1530e7d50326SJeff Roberson 	 * tickincr is shifted out by 10 to avoid rounding errors due to
15313f872f85SJeff Roberson 	 * hz not being evenly divisible by stathz on all platforms.
1532e7d50326SJeff Roberson 	 */
1533ae7a6b38SJeff Roberson 	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1534e7d50326SJeff Roberson 	/*
1535e7d50326SJeff Roberson 	 * This does not work for values of stathz that are more than
1536e7d50326SJeff Roberson 	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1537a1d4fe69SDavid Xu 	 */
1538ae7a6b38SJeff Roberson 	if (incr == 0)
1539ae7a6b38SJeff Roberson 		incr = 1;
1540ae7a6b38SJeff Roberson 	tickincr = incr;
15417b8bfa0dSJeff Roberson #ifdef SMP
15429862717aSJeff Roberson 	/*
15437fcf154aSJeff Roberson 	 * Set the default balance interval now that we know
15447fcf154aSJeff Roberson 	 * what realstathz is.
15457fcf154aSJeff Roberson 	 */
15467fcf154aSJeff Roberson 	balance_interval = realstathz;
1547290d9060SDon Lewis 	balance_ticks = balance_interval;
15487b8bfa0dSJeff Roberson 	affinity = SCHED_AFFINITY_DEFAULT;
15497b8bfa0dSJeff Roberson #endif
1550b3f40a41SAlexander Motin 	if (sched_idlespinthresh < 0)
15512c27cb3aSAlexander Motin 		sched_idlespinthresh = 2 * max(10000, 6 * hz) / realstathz;
1552a1d4fe69SDavid Xu }
1553a1d4fe69SDavid Xu 
155435e6168fSJeff Roberson /*
1555ae7a6b38SJeff Roberson  * This is the core of the interactivity algorithm.  Determines a score based
1556ae7a6b38SJeff Roberson  * on past behavior.  It is the ratio of sleep time to run time scaled to
1557ae7a6b38SJeff Roberson  * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1558ae7a6b38SJeff Roberson  * differs from the cpu usage because it does not account for time spent
1559ae7a6b38SJeff Roberson  * waiting on a run-queue.  Would be prettier if we had floating point.
156057031f79SGeorge V. Neville-Neil  *
156157031f79SGeorge V. Neville-Neil  * When a thread's sleep time is greater than its run time the
156257031f79SGeorge V. Neville-Neil  * calculation is:
156357031f79SGeorge V. Neville-Neil  *
156457031f79SGeorge V. Neville-Neil  *                           scaling factor
156557031f79SGeorge V. Neville-Neil  * interactivity score =  ---------------------
156657031f79SGeorge V. Neville-Neil  *                        sleep time / run time
156757031f79SGeorge V. Neville-Neil  *
156857031f79SGeorge V. Neville-Neil  *
156957031f79SGeorge V. Neville-Neil  * When a thread's run time is greater than its sleep time the
157057031f79SGeorge V. Neville-Neil  * calculation is:
157157031f79SGeorge V. Neville-Neil  *
157257031f79SGeorge V. Neville-Neil  *                                                 scaling factor
157343521b46Swiklam  * interactivity score = 2 * scaling factor  -  ---------------------
157457031f79SGeorge V. Neville-Neil  *                                              run time / sleep time
1575ae7a6b38SJeff Roberson  */
1576ae7a6b38SJeff Roberson static int
1577ae7a6b38SJeff Roberson sched_interact_score(struct thread *td)
1578ae7a6b38SJeff Roberson {
1579ae7a6b38SJeff Roberson 	struct td_sched *ts;
1580ae7a6b38SJeff Roberson 	int div;
1581ae7a6b38SJeff Roberson 
158293ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1583ae7a6b38SJeff Roberson 	/*
1584ae7a6b38SJeff Roberson 	 * The score is only needed if this is likely to be an interactive
1585ae7a6b38SJeff Roberson 	 * task.  Don't go through the expense of computing it if there's
1586ae7a6b38SJeff Roberson 	 * no chance.
1587ae7a6b38SJeff Roberson 	 */
1588ae7a6b38SJeff Roberson 	if (sched_interact <= SCHED_INTERACT_HALF &&
1589ae7a6b38SJeff Roberson 		ts->ts_runtime >= ts->ts_slptime)
1590ae7a6b38SJeff Roberson 			return (SCHED_INTERACT_HALF);
1591ae7a6b38SJeff Roberson 
1592ae7a6b38SJeff Roberson 	if (ts->ts_runtime > ts->ts_slptime) {
1593ae7a6b38SJeff Roberson 		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1594ae7a6b38SJeff Roberson 		return (SCHED_INTERACT_HALF +
1595ae7a6b38SJeff Roberson 		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1596ae7a6b38SJeff Roberson 	}
1597ae7a6b38SJeff Roberson 	if (ts->ts_slptime > ts->ts_runtime) {
1598ae7a6b38SJeff Roberson 		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1599ae7a6b38SJeff Roberson 		return (ts->ts_runtime / div);
1600ae7a6b38SJeff Roberson 	}
1601ae7a6b38SJeff Roberson 	/* runtime == slptime */
1602ae7a6b38SJeff Roberson 	if (ts->ts_runtime)
1603ae7a6b38SJeff Roberson 		return (SCHED_INTERACT_HALF);
1604ae7a6b38SJeff Roberson 
1605ae7a6b38SJeff Roberson 	/*
1606ae7a6b38SJeff Roberson 	 * This can happen if slptime and runtime are 0.
1607ae7a6b38SJeff Roberson 	 */
1608ae7a6b38SJeff Roberson 	return (0);
1609ae7a6b38SJeff Roberson 
1610ae7a6b38SJeff Roberson }
1611ae7a6b38SJeff Roberson 
1612ae7a6b38SJeff Roberson /*
161335e6168fSJeff Roberson  * Scale the scheduling priority according to the "interactivity" of this
161435e6168fSJeff Roberson  * process.
161535e6168fSJeff Roberson  */
161615dc847eSJeff Roberson static void
16178460a577SJohn Birrell sched_priority(struct thread *td)
161835e6168fSJeff Roberson {
16191c119e17SAlexander Motin 	u_int pri, score;
162035e6168fSJeff Roberson 
1621c9a8cba4SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
162215dc847eSJeff Roberson 		return;
1623e7d50326SJeff Roberson 	/*
1624e7d50326SJeff Roberson 	 * If the score is interactive we place the thread in the realtime
1625e7d50326SJeff Roberson 	 * queue with a priority that is less than kernel and interrupt
1626e7d50326SJeff Roberson 	 * priorities.  These threads are not subject to nice restrictions.
1627e7d50326SJeff Roberson 	 *
1628ae7a6b38SJeff Roberson 	 * Scores greater than this are placed on the normal timeshare queue
1629e7d50326SJeff Roberson 	 * where the priority is partially decided by the most recent cpu
1630e7d50326SJeff Roberson 	 * utilization and the rest is decided by nice value.
1631a5423ea3SJeff Roberson 	 *
1632a5423ea3SJeff Roberson 	 * The nice value of the process has a linear effect on the calculated
1633a5423ea3SJeff Roberson 	 * score.  Negative nice values make it easier for a thread to be
1634a5423ea3SJeff Roberson 	 * considered interactive.
1635e7d50326SJeff Roberson 	 */
1636a0f15352SJohn Baldwin 	score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1637e7d50326SJeff Roberson 	if (score < sched_interact) {
163812d56c0fSJohn Baldwin 		pri = PRI_MIN_INTERACT;
16391c119e17SAlexander Motin 		pri += (PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) * score /
16401c119e17SAlexander Motin 		    sched_interact;
164112d56c0fSJohn Baldwin 		KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
16421c119e17SAlexander Motin 		    ("sched_priority: invalid interactive priority %u score %u",
16439a93305aSJeff Roberson 		    pri, score));
1644e7d50326SJeff Roberson 	} else {
1645e7d50326SJeff Roberson 		pri = SCHED_PRI_MIN;
164693ccd6bfSKonstantin Belousov 		if (td_get_sched(td)->ts_ticks)
164793ccd6bfSKonstantin Belousov 			pri += min(SCHED_PRI_TICKS(td_get_sched(td)),
16485457fa23SJohn Baldwin 			    SCHED_PRI_RANGE - 1);
1649e7d50326SJeff Roberson 		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
165012d56c0fSJohn Baldwin 		KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
16511c119e17SAlexander Motin 		    ("sched_priority: invalid priority %u: nice %d, "
1652ae7a6b38SJeff Roberson 		    "ticks %d ftick %d ltick %d tick pri %d",
165393ccd6bfSKonstantin Belousov 		    pri, td->td_proc->p_nice, td_get_sched(td)->ts_ticks,
165493ccd6bfSKonstantin Belousov 		    td_get_sched(td)->ts_ftick, td_get_sched(td)->ts_ltick,
165593ccd6bfSKonstantin Belousov 		    SCHED_PRI_TICKS(td_get_sched(td))));
1656e7d50326SJeff Roberson 	}
16578460a577SJohn Birrell 	sched_user_prio(td, pri);
165835e6168fSJeff Roberson 
165915dc847eSJeff Roberson 	return;
166035e6168fSJeff Roberson }
166135e6168fSJeff Roberson 
166235e6168fSJeff Roberson /*
1663d322132cSJeff Roberson  * This routine enforces a maximum limit on the amount of scheduling history
1664ae7a6b38SJeff Roberson  * kept.  It is called after either the slptime or runtime is adjusted.  This
1665ae7a6b38SJeff Roberson  * function is ugly due to integer math.
1666d322132cSJeff Roberson  */
16674b60e324SJeff Roberson static void
16688460a577SJohn Birrell sched_interact_update(struct thread *td)
16694b60e324SJeff Roberson {
1670155b6ca1SJeff Roberson 	struct td_sched *ts;
16719a93305aSJeff Roberson 	u_int sum;
16723f741ca1SJeff Roberson 
167393ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1674ae7a6b38SJeff Roberson 	sum = ts->ts_runtime + ts->ts_slptime;
1675d322132cSJeff Roberson 	if (sum < SCHED_SLP_RUN_MAX)
1676d322132cSJeff Roberson 		return;
1677d322132cSJeff Roberson 	/*
1678155b6ca1SJeff Roberson 	 * This only happens from two places:
1679155b6ca1SJeff Roberson 	 * 1) We have added an unusual amount of run time from fork_exit.
1680155b6ca1SJeff Roberson 	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1681155b6ca1SJeff Roberson 	 */
1682155b6ca1SJeff Roberson 	if (sum > SCHED_SLP_RUN_MAX * 2) {
1683ae7a6b38SJeff Roberson 		if (ts->ts_runtime > ts->ts_slptime) {
1684ae7a6b38SJeff Roberson 			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1685ae7a6b38SJeff Roberson 			ts->ts_slptime = 1;
1686155b6ca1SJeff Roberson 		} else {
1687ae7a6b38SJeff Roberson 			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1688ae7a6b38SJeff Roberson 			ts->ts_runtime = 1;
1689155b6ca1SJeff Roberson 		}
1690155b6ca1SJeff Roberson 		return;
1691155b6ca1SJeff Roberson 	}
1692155b6ca1SJeff Roberson 	/*
1693d322132cSJeff Roberson 	 * If we have exceeded by more than 1/5th then the algorithm below
1694d322132cSJeff Roberson 	 * will not bring us back into range.  Dividing by two here forces
16952454aaf5SJeff Roberson 	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1696d322132cSJeff Roberson 	 */
169737a35e4aSJeff Roberson 	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1698ae7a6b38SJeff Roberson 		ts->ts_runtime /= 2;
1699ae7a6b38SJeff Roberson 		ts->ts_slptime /= 2;
1700d322132cSJeff Roberson 		return;
1701d322132cSJeff Roberson 	}
1702ae7a6b38SJeff Roberson 	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1703ae7a6b38SJeff Roberson 	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1704d322132cSJeff Roberson }
1705d322132cSJeff Roberson 
1706ae7a6b38SJeff Roberson /*
1707ae7a6b38SJeff Roberson  * Scale back the interactivity history when a child thread is created.  The
1708ae7a6b38SJeff Roberson  * history is inherited from the parent but the thread may behave totally
1709ae7a6b38SJeff Roberson  * differently.  For example, a shell spawning a compiler process.  We want
1710ae7a6b38SJeff Roberson  * to learn that the compiler is behaving badly very quickly.
1711ae7a6b38SJeff Roberson  */
1712d322132cSJeff Roberson static void
17138460a577SJohn Birrell sched_interact_fork(struct thread *td)
1714d322132cSJeff Roberson {
171593ccd6bfSKonstantin Belousov 	struct td_sched *ts;
1716d322132cSJeff Roberson 	int ratio;
1717d322132cSJeff Roberson 	int sum;
1718d322132cSJeff Roberson 
171993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
172093ccd6bfSKonstantin Belousov 	sum = ts->ts_runtime + ts->ts_slptime;
1721d322132cSJeff Roberson 	if (sum > SCHED_SLP_RUN_FORK) {
1722d322132cSJeff Roberson 		ratio = sum / SCHED_SLP_RUN_FORK;
172393ccd6bfSKonstantin Belousov 		ts->ts_runtime /= ratio;
172493ccd6bfSKonstantin Belousov 		ts->ts_slptime /= ratio;
17254b60e324SJeff Roberson 	}
17264b60e324SJeff Roberson }
17274b60e324SJeff Roberson 
172815dc847eSJeff Roberson /*
1729ae7a6b38SJeff Roberson  * Called from proc0_init() to setup the scheduler fields.
1730ed062c8dSJulian Elischer  */
1731ed062c8dSJulian Elischer void
1732ed062c8dSJulian Elischer schedinit(void)
1733ed062c8dSJulian Elischer {
173493ccd6bfSKonstantin Belousov 	struct td_sched *ts0;
1735e7d50326SJeff Roberson 
1736ed062c8dSJulian Elischer 	/*
173793ccd6bfSKonstantin Belousov 	 * Set up the scheduler specific parts of thread0.
1738ed062c8dSJulian Elischer 	 */
173993ccd6bfSKonstantin Belousov 	ts0 = td_get_sched(&thread0);
174093ccd6bfSKonstantin Belousov 	ts0->ts_ltick = ticks;
174193ccd6bfSKonstantin Belousov 	ts0->ts_ftick = ticks;
174293ccd6bfSKonstantin Belousov 	ts0->ts_slice = 0;
17431408b84aSHans Petter Selasky 	ts0->ts_cpu = curcpu;	/* set valid CPU number */
1744ed062c8dSJulian Elischer }
1745ed062c8dSJulian Elischer 
1746ed062c8dSJulian Elischer /*
1747*589aed00SKyle Evans  * schedinit_ap() is needed prior to calling sched_throw(NULL) to ensure that
1748*589aed00SKyle Evans  * the pcpu requirements are met for any calls in the period between curthread
1749*589aed00SKyle Evans  * initialization and sched_throw().  One can safely add threads to the queue
1750*589aed00SKyle Evans  * before sched_throw(), for instance, as long as the thread lock is setup
1751*589aed00SKyle Evans  * correctly.
1752*589aed00SKyle Evans  *
1753*589aed00SKyle Evans  * TDQ_SELF() relies on the below sched pcpu setting; it may be used only
1754*589aed00SKyle Evans  * after schedinit_ap().
1755*589aed00SKyle Evans  */
1756*589aed00SKyle Evans void
1757*589aed00SKyle Evans schedinit_ap(void)
1758*589aed00SKyle Evans {
1759*589aed00SKyle Evans 
1760*589aed00SKyle Evans #ifdef SMP
1761*589aed00SKyle Evans 	PCPU_SET(sched, DPCPU_PTR(tdq));
1762*589aed00SKyle Evans #endif
1763*589aed00SKyle Evans 	PCPU_GET(idlethread)->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1764*589aed00SKyle Evans }
1765*589aed00SKyle Evans 
1766*589aed00SKyle Evans /*
176715dc847eSJeff Roberson  * This is only somewhat accurate since given many processes of the same
176815dc847eSJeff Roberson  * priority they will switch when their slices run out, which will be
1769e7d50326SJeff Roberson  * at most sched_slice stathz ticks.
177015dc847eSJeff Roberson  */
177135e6168fSJeff Roberson int
177235e6168fSJeff Roberson sched_rr_interval(void)
177335e6168fSJeff Roberson {
1774e7d50326SJeff Roberson 
1775579895dfSAlexander Motin 	/* Convert sched_slice from stathz to hz. */
177637f4e025SAlexander Motin 	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
177735e6168fSJeff Roberson }
177835e6168fSJeff Roberson 
1779ae7a6b38SJeff Roberson /*
1780ae7a6b38SJeff Roberson  * Update the percent cpu tracking information when it is requested or
1781ae7a6b38SJeff Roberson  * the total history exceeds the maximum.  We keep a sliding history of
1782ae7a6b38SJeff Roberson  * tick counts that slowly decays.  This is less precise than the 4BSD
1783ae7a6b38SJeff Roberson  * mechanism since it happens with less regular and frequent events.
1784ae7a6b38SJeff Roberson  */
178522bf7d9aSJeff Roberson static void
17867295465eSAlexander Motin sched_pctcpu_update(struct td_sched *ts, int run)
178735e6168fSJeff Roberson {
17887295465eSAlexander Motin 	int t = ticks;
1789e7d50326SJeff Roberson 
179078133024SMark Johnston 	/*
179178133024SMark Johnston 	 * The signed difference may be negative if the thread hasn't run for
179278133024SMark Johnston 	 * over half of the ticks rollover period.
179378133024SMark Johnston 	 */
179478133024SMark Johnston 	if ((u_int)(t - ts->ts_ltick) >= SCHED_TICK_TARG) {
1795ad1e7d28SJulian Elischer 		ts->ts_ticks = 0;
17967295465eSAlexander Motin 		ts->ts_ftick = t - SCHED_TICK_TARG;
17977295465eSAlexander Motin 	} else if (t - ts->ts_ftick >= SCHED_TICK_MAX) {
17987295465eSAlexander Motin 		ts->ts_ticks = (ts->ts_ticks / (ts->ts_ltick - ts->ts_ftick)) *
17997295465eSAlexander Motin 		    (ts->ts_ltick - (t - SCHED_TICK_TARG));
18007295465eSAlexander Motin 		ts->ts_ftick = t - SCHED_TICK_TARG;
18017295465eSAlexander Motin 	}
18027295465eSAlexander Motin 	if (run)
18037295465eSAlexander Motin 		ts->ts_ticks += (t - ts->ts_ltick) << SCHED_TICK_SHIFT;
18047295465eSAlexander Motin 	ts->ts_ltick = t;
180535e6168fSJeff Roberson }
180635e6168fSJeff Roberson 
1807ae7a6b38SJeff Roberson /*
1808ae7a6b38SJeff Roberson  * Adjust the priority of a thread.  Move it to the appropriate run-queue
1809ae7a6b38SJeff Roberson  * if necessary.  This is the back-end for several priority related
1810ae7a6b38SJeff Roberson  * functions.
1811ae7a6b38SJeff Roberson  */
1812e7d50326SJeff Roberson static void
1813f5c157d9SJohn Baldwin sched_thread_priority(struct thread *td, u_char prio)
181435e6168fSJeff Roberson {
1815ad1e7d28SJulian Elischer 	struct td_sched *ts;
181673daf66fSJeff Roberson 	struct tdq *tdq;
181773daf66fSJeff Roberson 	int oldpri;
181835e6168fSJeff Roberson 
18198f51ad55SJeff Roberson 	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
18208f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, "new prio:%d", prio,
18218f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(curthread));
1822d9fae5abSAndriy Gapon 	SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
1823e87fc7cfSAndriy Gapon 	if (td != curthread && prio < td->td_priority) {
18248f51ad55SJeff Roberson 		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
18258f51ad55SJeff Roberson 		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
18268f51ad55SJeff Roberson 		    prio, KTR_ATTR_LINKED, sched_tdname(td));
1827d9fae5abSAndriy Gapon 		SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
1828b3e9e682SRyan Stone 		    curthread);
18298f51ad55SJeff Roberson 	}
183093ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
18317b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1832f5c157d9SJohn Baldwin 	if (td->td_priority == prio)
1833f5c157d9SJohn Baldwin 		return;
18343f741ca1SJeff Roberson 	/*
18353f741ca1SJeff Roberson 	 * If the priority has been elevated due to priority
18363f741ca1SJeff Roberson 	 * propagation, we may have to move ourselves to a new
1837e7d50326SJeff Roberson 	 * queue.  This could be optimized to not re-add in some
1838e7d50326SJeff Roberson 	 * cases.
1839f2b74cbfSJeff Roberson 	 */
18406d55b3ecSJeff Roberson 	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1841e7d50326SJeff Roberson 		sched_rem(td);
1842e7d50326SJeff Roberson 		td->td_priority = prio;
184361a74c5cSJeff Roberson 		sched_add(td, SRQ_BORROWING | SRQ_HOLDTD);
184473daf66fSJeff Roberson 		return;
184573daf66fSJeff Roberson 	}
18466d55b3ecSJeff Roberson 	/*
18476d55b3ecSJeff Roberson 	 * If the thread is currently running we may have to adjust the lowpri
18486d55b3ecSJeff Roberson 	 * information so other cpus are aware of our current priority.
18496d55b3ecSJeff Roberson 	 */
18506d55b3ecSJeff Roberson 	if (TD_IS_RUNNING(td)) {
1851ae7a6b38SJeff Roberson 		tdq = TDQ_CPU(ts->ts_cpu);
185262fa74d9SJeff Roberson 		oldpri = td->td_priority;
18533f741ca1SJeff Roberson 		td->td_priority = prio;
185462fa74d9SJeff Roberson 		if (prio < tdq->tdq_lowpri)
185562fa74d9SJeff Roberson 			tdq->tdq_lowpri = prio;
185662fa74d9SJeff Roberson 		else if (tdq->tdq_lowpri == oldpri)
185762fa74d9SJeff Roberson 			tdq_setlowpri(tdq, td);
18586d55b3ecSJeff Roberson 		return;
185973daf66fSJeff Roberson 	}
18606d55b3ecSJeff Roberson 	td->td_priority = prio;
1861ae7a6b38SJeff Roberson }
186235e6168fSJeff Roberson 
1863f5c157d9SJohn Baldwin /*
1864f5c157d9SJohn Baldwin  * Update a thread's priority when it is lent another thread's
1865f5c157d9SJohn Baldwin  * priority.
1866f5c157d9SJohn Baldwin  */
1867f5c157d9SJohn Baldwin void
1868f5c157d9SJohn Baldwin sched_lend_prio(struct thread *td, u_char prio)
1869f5c157d9SJohn Baldwin {
1870f5c157d9SJohn Baldwin 
1871f5c157d9SJohn Baldwin 	td->td_flags |= TDF_BORROWING;
1872f5c157d9SJohn Baldwin 	sched_thread_priority(td, prio);
1873f5c157d9SJohn Baldwin }
1874f5c157d9SJohn Baldwin 
1875f5c157d9SJohn Baldwin /*
1876f5c157d9SJohn Baldwin  * Restore a thread's priority when priority propagation is
1877f5c157d9SJohn Baldwin  * over.  The prio argument is the minimum priority the thread
1878f5c157d9SJohn Baldwin  * needs to have to satisfy other possible priority lending
1879f5c157d9SJohn Baldwin  * requests.  If the thread's regular priority is less
1880f5c157d9SJohn Baldwin  * important than prio, the thread will keep a priority boost
1881f5c157d9SJohn Baldwin  * of prio.
1882f5c157d9SJohn Baldwin  */
1883f5c157d9SJohn Baldwin void
1884f5c157d9SJohn Baldwin sched_unlend_prio(struct thread *td, u_char prio)
1885f5c157d9SJohn Baldwin {
1886f5c157d9SJohn Baldwin 	u_char base_pri;
1887f5c157d9SJohn Baldwin 
1888f5c157d9SJohn Baldwin 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1889f5c157d9SJohn Baldwin 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
18908460a577SJohn Birrell 		base_pri = td->td_user_pri;
1891f5c157d9SJohn Baldwin 	else
1892f5c157d9SJohn Baldwin 		base_pri = td->td_base_pri;
1893f5c157d9SJohn Baldwin 	if (prio >= base_pri) {
1894f5c157d9SJohn Baldwin 		td->td_flags &= ~TDF_BORROWING;
1895f5c157d9SJohn Baldwin 		sched_thread_priority(td, base_pri);
1896f5c157d9SJohn Baldwin 	} else
1897f5c157d9SJohn Baldwin 		sched_lend_prio(td, prio);
1898f5c157d9SJohn Baldwin }
1899f5c157d9SJohn Baldwin 
1900ae7a6b38SJeff Roberson /*
1901ae7a6b38SJeff Roberson  * Standard entry for setting the priority to an absolute value.
1902ae7a6b38SJeff Roberson  */
1903f5c157d9SJohn Baldwin void
1904f5c157d9SJohn Baldwin sched_prio(struct thread *td, u_char prio)
1905f5c157d9SJohn Baldwin {
1906f5c157d9SJohn Baldwin 	u_char oldprio;
1907f5c157d9SJohn Baldwin 
1908f5c157d9SJohn Baldwin 	/* First, update the base priority. */
1909f5c157d9SJohn Baldwin 	td->td_base_pri = prio;
1910f5c157d9SJohn Baldwin 
1911f5c157d9SJohn Baldwin 	/*
191250aaa791SJohn Baldwin 	 * If the thread is borrowing another thread's priority, don't
1913f5c157d9SJohn Baldwin 	 * ever lower the priority.
1914f5c157d9SJohn Baldwin 	 */
1915f5c157d9SJohn Baldwin 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1916f5c157d9SJohn Baldwin 		return;
1917f5c157d9SJohn Baldwin 
1918f5c157d9SJohn Baldwin 	/* Change the real priority. */
1919f5c157d9SJohn Baldwin 	oldprio = td->td_priority;
1920f5c157d9SJohn Baldwin 	sched_thread_priority(td, prio);
1921f5c157d9SJohn Baldwin 
1922f5c157d9SJohn Baldwin 	/*
1923f5c157d9SJohn Baldwin 	 * If the thread is on a turnstile, then let the turnstile update
1924f5c157d9SJohn Baldwin 	 * its state.
1925f5c157d9SJohn Baldwin 	 */
1926f5c157d9SJohn Baldwin 	if (TD_ON_LOCK(td) && oldprio != prio)
1927f5c157d9SJohn Baldwin 		turnstile_adjust(td, oldprio);
1928f5c157d9SJohn Baldwin }
1929f5c157d9SJohn Baldwin 
1930ae7a6b38SJeff Roberson /*
1931ae7a6b38SJeff Roberson  * Set the base user priority, does not effect current running priority.
1932ae7a6b38SJeff Roberson  */
193335e6168fSJeff Roberson void
19348460a577SJohn Birrell sched_user_prio(struct thread *td, u_char prio)
19353db720fdSDavid Xu {
19363db720fdSDavid Xu 
19378460a577SJohn Birrell 	td->td_base_user_pri = prio;
1938acbe332aSDavid Xu 	if (td->td_lend_user_pri <= prio)
1939fc6c30f6SJulian Elischer 		return;
19408460a577SJohn Birrell 	td->td_user_pri = prio;
19413db720fdSDavid Xu }
19423db720fdSDavid Xu 
19433db720fdSDavid Xu void
19443db720fdSDavid Xu sched_lend_user_prio(struct thread *td, u_char prio)
19453db720fdSDavid Xu {
19463db720fdSDavid Xu 
1947435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1948acbe332aSDavid Xu 	td->td_lend_user_pri = prio;
1949c8e368a9SDavid Xu 	td->td_user_pri = min(prio, td->td_base_user_pri);
1950c8e368a9SDavid Xu 	if (td->td_priority > td->td_user_pri)
1951c8e368a9SDavid Xu 		sched_prio(td, td->td_user_pri);
1952c8e368a9SDavid Xu 	else if (td->td_priority != td->td_user_pri)
1953c8e368a9SDavid Xu 		td->td_flags |= TDF_NEEDRESCHED;
1954435806d3SDavid Xu }
19553db720fdSDavid Xu 
1956ac97da9aSMateusz Guzik /*
1957ac97da9aSMateusz Guzik  * Like the above but first check if there is anything to do.
1958ac97da9aSMateusz Guzik  */
1959ac97da9aSMateusz Guzik void
1960ac97da9aSMateusz Guzik sched_lend_user_prio_cond(struct thread *td, u_char prio)
1961ac97da9aSMateusz Guzik {
1962ac97da9aSMateusz Guzik 
1963ac97da9aSMateusz Guzik 	if (td->td_lend_user_pri != prio)
1964ac97da9aSMateusz Guzik 		goto lend;
1965ac97da9aSMateusz Guzik 	if (td->td_user_pri != min(prio, td->td_base_user_pri))
1966ac97da9aSMateusz Guzik 		goto lend;
1967b77594bbSMateusz Guzik 	if (td->td_priority != td->td_user_pri)
1968ac97da9aSMateusz Guzik 		goto lend;
1969ac97da9aSMateusz Guzik 	return;
1970ac97da9aSMateusz Guzik 
1971ac97da9aSMateusz Guzik lend:
1972ac97da9aSMateusz Guzik 	thread_lock(td);
1973ac97da9aSMateusz Guzik 	sched_lend_user_prio(td, prio);
1974ac97da9aSMateusz Guzik 	thread_unlock(td);
1975ac97da9aSMateusz Guzik }
1976ac97da9aSMateusz Guzik 
19774c8a8cfcSKonstantin Belousov #ifdef SMP
1978ae7a6b38SJeff Roberson /*
197997e9382dSDon Lewis  * This tdq is about to idle.  Try to steal a thread from another CPU before
198097e9382dSDon Lewis  * choosing the idle thread.
198197e9382dSDon Lewis  */
198297e9382dSDon Lewis static void
198397e9382dSDon Lewis tdq_trysteal(struct tdq *tdq)
198497e9382dSDon Lewis {
19852668bb2aSAlexander Motin 	struct cpu_group *cg, *parent;
198697e9382dSDon Lewis 	struct tdq *steal;
198797e9382dSDon Lewis 	cpuset_t mask;
19882668bb2aSAlexander Motin 	int cpu, i, goup;
198997e9382dSDon Lewis 
199008063e9fSAlexander Motin 	if (smp_started == 0 || steal_idle == 0 || trysteal_limit == 0 ||
199108063e9fSAlexander Motin 	    tdq->tdq_cg == NULL)
199297e9382dSDon Lewis 		return;
199397e9382dSDon Lewis 	CPU_FILL(&mask);
199497e9382dSDon Lewis 	CPU_CLR(PCPU_GET(cpuid), &mask);
199597e9382dSDon Lewis 	/* We don't want to be preempted while we're iterating. */
199697e9382dSDon Lewis 	spinlock_enter();
199797e9382dSDon Lewis 	TDQ_UNLOCK(tdq);
19982668bb2aSAlexander Motin 	for (i = 1, cg = tdq->tdq_cg, goup = 0; ; ) {
199908063e9fSAlexander Motin 		cpu = sched_highest(cg, &mask, steal_thresh, 1);
200097e9382dSDon Lewis 		/*
200197e9382dSDon Lewis 		 * If a thread was added while interrupts were disabled don't
200297e9382dSDon Lewis 		 * steal one here.
200397e9382dSDon Lewis 		 */
200497e9382dSDon Lewis 		if (tdq->tdq_load > 0) {
200597e9382dSDon Lewis 			TDQ_LOCK(tdq);
200697e9382dSDon Lewis 			break;
200797e9382dSDon Lewis 		}
20082668bb2aSAlexander Motin 
20092668bb2aSAlexander Motin 		/*
20102668bb2aSAlexander Motin 		 * We found no CPU to steal from in this group.  Escalate to
20112668bb2aSAlexander Motin 		 * the parent and repeat.  But if parent has only two children
20122668bb2aSAlexander Motin 		 * groups we can avoid searching this group again by searching
20132668bb2aSAlexander Motin 		 * the other one specifically and then escalating two levels.
20142668bb2aSAlexander Motin 		 */
201597e9382dSDon Lewis 		if (cpu == -1) {
20162668bb2aSAlexander Motin 			if (goup) {
201797e9382dSDon Lewis 				cg = cg->cg_parent;
20182668bb2aSAlexander Motin 				goup = 0;
20192668bb2aSAlexander Motin 			}
20202668bb2aSAlexander Motin 			if (++i > trysteal_limit) {
202197e9382dSDon Lewis 				TDQ_LOCK(tdq);
202297e9382dSDon Lewis 				break;
202397e9382dSDon Lewis 			}
20242668bb2aSAlexander Motin 			parent = cg->cg_parent;
20252668bb2aSAlexander Motin 			if (parent == NULL) {
20262668bb2aSAlexander Motin 				TDQ_LOCK(tdq);
20272668bb2aSAlexander Motin 				break;
20282668bb2aSAlexander Motin 			}
20292668bb2aSAlexander Motin 			if (parent->cg_children == 2) {
20302668bb2aSAlexander Motin 				if (cg == &parent->cg_child[0])
20312668bb2aSAlexander Motin 					cg = &parent->cg_child[1];
20322668bb2aSAlexander Motin 				else
20332668bb2aSAlexander Motin 					cg = &parent->cg_child[0];
20342668bb2aSAlexander Motin 				goup = 1;
20352668bb2aSAlexander Motin 			} else
20362668bb2aSAlexander Motin 				cg = parent;
203797e9382dSDon Lewis 			continue;
203897e9382dSDon Lewis 		}
203997e9382dSDon Lewis 		steal = TDQ_CPU(cpu);
204097e9382dSDon Lewis 		/*
204197e9382dSDon Lewis 		 * The data returned by sched_highest() is stale and
204297e9382dSDon Lewis 		 * the chosen CPU no longer has an eligible thread.
204308063e9fSAlexander Motin 		 * At this point unconditonally exit the loop to bound
204408063e9fSAlexander Motin 		 * the time spent in the critcal section.
204597e9382dSDon Lewis 		 */
204697e9382dSDon Lewis 		if (steal->tdq_load < steal_thresh ||
204797e9382dSDon Lewis 		    steal->tdq_transferable == 0)
204897e9382dSDon Lewis 			continue;
204997e9382dSDon Lewis 		/*
20508bb173fbSAlexander Motin 		 * Try to lock both queues. If we are assigned a thread while
20518bb173fbSAlexander Motin 		 * waited for the lock, switch to it now instead of stealing.
20528bb173fbSAlexander Motin 		 * If we can't get the lock, then somebody likely got there
205308063e9fSAlexander Motin 		 * first.
205497e9382dSDon Lewis 		 */
20558bb173fbSAlexander Motin 		TDQ_LOCK(tdq);
20568bb173fbSAlexander Motin 		if (tdq->tdq_load > 0)
205797e9382dSDon Lewis 			break;
20588bb173fbSAlexander Motin 		if (TDQ_TRYLOCK_FLAGS(steal, MTX_DUPOK) == 0)
20598bb173fbSAlexander Motin 			break;
206097e9382dSDon Lewis 		/*
206197e9382dSDon Lewis 		 * The data returned by sched_highest() is stale and
206297e9382dSDon Lewis                  * the chosen CPU no longer has an eligible thread.
206397e9382dSDon Lewis 		 */
206497e9382dSDon Lewis 		if (steal->tdq_load < steal_thresh ||
206597e9382dSDon Lewis 		    steal->tdq_transferable == 0) {
206697e9382dSDon Lewis 			TDQ_UNLOCK(steal);
206797e9382dSDon Lewis 			break;
206897e9382dSDon Lewis 		}
206997e9382dSDon Lewis 		/*
207097e9382dSDon Lewis 		 * If we fail to acquire one due to affinity restrictions,
207197e9382dSDon Lewis 		 * bail out and let the idle thread to a more complete search
207297e9382dSDon Lewis 		 * outside of a critical section.
207397e9382dSDon Lewis 		 */
207497e9382dSDon Lewis 		if (tdq_move(steal, tdq) == NULL) {
207597e9382dSDon Lewis 			TDQ_UNLOCK(steal);
207697e9382dSDon Lewis 			break;
207797e9382dSDon Lewis 		}
207897e9382dSDon Lewis 		TDQ_UNLOCK(steal);
207997e9382dSDon Lewis 		break;
208097e9382dSDon Lewis 	}
208197e9382dSDon Lewis 	spinlock_exit();
208297e9382dSDon Lewis }
20834c8a8cfcSKonstantin Belousov #endif
208497e9382dSDon Lewis 
208597e9382dSDon Lewis /*
2086c47f202bSJeff Roberson  * Handle migration from sched_switch().  This happens only for
2087c47f202bSJeff Roberson  * cpu binding.
2088c47f202bSJeff Roberson  */
2089c47f202bSJeff Roberson static struct mtx *
2090c47f202bSJeff Roberson sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
2091c47f202bSJeff Roberson {
2092c47f202bSJeff Roberson 	struct tdq *tdn;
2093c47f202bSJeff Roberson 
2094686bcb5cSJeff Roberson 	KASSERT(THREAD_CAN_MIGRATE(td) ||
2095686bcb5cSJeff Roberson 	    (td_get_sched(td)->ts_flags & TSF_BOUND) != 0,
2096686bcb5cSJeff Roberson 	    ("Thread %p shouldn't migrate", td));
2097efe67753SNathan Whitehorn 	KASSERT(!CPU_ABSENT(td_get_sched(td)->ts_cpu), ("sched_switch_migrate: "
2098efe67753SNathan Whitehorn 	    "thread %s queued on absent CPU %d.", td->td_name,
2099efe67753SNathan Whitehorn 	    td_get_sched(td)->ts_cpu));
210093ccd6bfSKonstantin Belousov 	tdn = TDQ_CPU(td_get_sched(td)->ts_cpu);
2101c47f202bSJeff Roberson #ifdef SMP
21029727e637SJeff Roberson 	tdq_load_rem(tdq, td);
2103c47f202bSJeff Roberson 	/*
2104686bcb5cSJeff Roberson 	 * Do the lock dance required to avoid LOR.  We have an
2105686bcb5cSJeff Roberson 	 * extra spinlock nesting from sched_switch() which will
2106686bcb5cSJeff Roberson 	 * prevent preemption while we're holding neither run-queue lock.
2107c47f202bSJeff Roberson 	 */
2108686bcb5cSJeff Roberson 	TDQ_UNLOCK(tdq);
2109686bcb5cSJeff Roberson 	TDQ_LOCK(tdn);
2110c47f202bSJeff Roberson 	tdq_add(tdn, td, flags);
211127ee18adSRyan Stone 	tdq_notify(tdn, td);
2112c47f202bSJeff Roberson 	TDQ_UNLOCK(tdn);
2113686bcb5cSJeff Roberson 	TDQ_LOCK(tdq);
2114c47f202bSJeff Roberson #endif
2115c47f202bSJeff Roberson 	return (TDQ_LOCKPTR(tdn));
2116c47f202bSJeff Roberson }
2117c47f202bSJeff Roberson 
2118c47f202bSJeff Roberson /*
211961a74c5cSJeff Roberson  * thread_lock_unblock() that does not assume td_lock is blocked.
2120ae7a6b38SJeff Roberson  */
2121ae7a6b38SJeff Roberson static inline void
2122ae7a6b38SJeff Roberson thread_unblock_switch(struct thread *td, struct mtx *mtx)
2123ae7a6b38SJeff Roberson {
2124ae7a6b38SJeff Roberson 	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
2125ae7a6b38SJeff Roberson 	    (uintptr_t)mtx);
2126ae7a6b38SJeff Roberson }
2127ae7a6b38SJeff Roberson 
2128ae7a6b38SJeff Roberson /*
2129ae7a6b38SJeff Roberson  * Switch threads.  This function has to handle threads coming in while
2130ae7a6b38SJeff Roberson  * blocked for some reason, running, or idle.  It also must deal with
2131ae7a6b38SJeff Roberson  * migrating a thread from one queue to another as running threads may
2132ae7a6b38SJeff Roberson  * be assigned elsewhere via binding.
2133ae7a6b38SJeff Roberson  */
21343db720fdSDavid Xu void
2135686bcb5cSJeff Roberson sched_switch(struct thread *td, int flags)
213635e6168fSJeff Roberson {
2137686bcb5cSJeff Roberson 	struct thread *newtd;
2138c02bbb43SJeff Roberson 	struct tdq *tdq;
2139ad1e7d28SJulian Elischer 	struct td_sched *ts;
2140ae7a6b38SJeff Roberson 	struct mtx *mtx;
2141c47f202bSJeff Roberson 	int srqflag;
21428db16699SAlexander Motin 	int cpuid, preempted;
21438db16699SAlexander Motin #ifdef SMP
21448db16699SAlexander Motin 	int pickcpu;
21458db16699SAlexander Motin #endif
214635e6168fSJeff Roberson 
21477b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
214835e6168fSJeff Roberson 
2149ae7a6b38SJeff Roberson 	cpuid = PCPU_GET(cpuid);
2150018ff686SJeff Roberson 	tdq = TDQ_SELF();
215193ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
21527295465eSAlexander Motin 	sched_pctcpu_update(ts, 1);
21538db16699SAlexander Motin #ifdef SMP
2154e745d729SAlexander Motin 	pickcpu = (td->td_flags & TDF_PICKCPU) != 0;
2155e745d729SAlexander Motin 	if (pickcpu)
2156e745d729SAlexander Motin 		ts->ts_rltick = ticks - affinity * MAX_CACHE_LEVELS;
2157e745d729SAlexander Motin 	else
2158ae7a6b38SJeff Roberson 		ts->ts_rltick = ticks;
21598db16699SAlexander Motin #endif
2160060563ecSJulian Elischer 	td->td_lastcpu = td->td_oncpu;
2161ad9dadc4SAndriy Gapon 	preempted = (td->td_flags & TDF_SLICEEND) == 0 &&
2162ad9dadc4SAndriy Gapon 	    (flags & SW_PREEMPT) != 0;
2163e745d729SAlexander Motin 	td->td_flags &= ~(TDF_NEEDRESCHED | TDF_PICKCPU | TDF_SLICEEND);
216477918643SStephan Uphoff 	td->td_owepreempt = 0;
21657789ab32SMark Johnston 	tdq->tdq_owepreempt = 0;
21662c27cb3aSAlexander Motin 	if (!TD_IS_IDLETHREAD(td))
21671690c6c1SJeff Roberson 		tdq->tdq_switchcnt++;
21687789ab32SMark Johnston 
2169b11fdad0SJeff Roberson 	/*
2170686bcb5cSJeff Roberson 	 * Always block the thread lock so we can drop the tdq lock early.
2171b11fdad0SJeff Roberson 	 */
2172686bcb5cSJeff Roberson 	mtx = thread_lock_block(td);
2173686bcb5cSJeff Roberson 	spinlock_enter();
2174486a9414SJulian Elischer 	if (TD_IS_IDLETHREAD(td)) {
2175686bcb5cSJeff Roberson 		MPASS(mtx == TDQ_LOCKPTR(tdq));
2176bf0acc27SJohn Baldwin 		TD_SET_CAN_RUN(td);
21777b20fb19SJeff Roberson 	} else if (TD_IS_RUNNING(td)) {
2178686bcb5cSJeff Roberson 		MPASS(mtx == TDQ_LOCKPTR(tdq));
21793d7f4117SAlexander Motin 		srqflag = preempted ?
2180598b368dSJeff Roberson 		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
2181c47f202bSJeff Roberson 		    SRQ_OURSELF|SRQ_YIELDING;
2182ba4932b5SMatthew D Fleming #ifdef SMP
2183e745d729SAlexander Motin 		if (THREAD_CAN_MIGRATE(td) && (!THREAD_CAN_SCHED(td, ts->ts_cpu)
2184e745d729SAlexander Motin 		    || pickcpu))
21850f7a0ebdSMatthew D Fleming 			ts->ts_cpu = sched_pickcpu(td, 0);
2186ba4932b5SMatthew D Fleming #endif
2187c47f202bSJeff Roberson 		if (ts->ts_cpu == cpuid)
21889727e637SJeff Roberson 			tdq_runq_add(tdq, td, srqflag);
2189686bcb5cSJeff Roberson 		else
2190c47f202bSJeff Roberson 			mtx = sched_switch_migrate(tdq, td, srqflag);
2191ae7a6b38SJeff Roberson 	} else {
2192ae7a6b38SJeff Roberson 		/* This thread must be going to sleep. */
219361a74c5cSJeff Roberson 		if (mtx != TDQ_LOCKPTR(tdq)) {
219461a74c5cSJeff Roberson 			mtx_unlock_spin(mtx);
219561a74c5cSJeff Roberson 			TDQ_LOCK(tdq);
219661a74c5cSJeff Roberson 		}
21979727e637SJeff Roberson 		tdq_load_rem(tdq, td);
21984c8a8cfcSKonstantin Belousov #ifdef SMP
219997e9382dSDon Lewis 		if (tdq->tdq_load == 0)
220097e9382dSDon Lewis 			tdq_trysteal(tdq);
22014c8a8cfcSKonstantin Belousov #endif
2202ae7a6b38SJeff Roberson 	}
2203afa0a46cSAndriy Gapon 
2204afa0a46cSAndriy Gapon #if (KTR_COMPILE & KTR_SCHED) != 0
2205afa0a46cSAndriy Gapon 	if (TD_IS_IDLETHREAD(td))
2206afa0a46cSAndriy Gapon 		KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle",
2207afa0a46cSAndriy Gapon 		    "prio:%d", td->td_priority);
2208afa0a46cSAndriy Gapon 	else
2209afa0a46cSAndriy Gapon 		KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td),
2210afa0a46cSAndriy Gapon 		    "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg,
2211afa0a46cSAndriy Gapon 		    "lockname:\"%s\"", td->td_lockname);
2212afa0a46cSAndriy Gapon #endif
2213afa0a46cSAndriy Gapon 
2214ae7a6b38SJeff Roberson 	/*
2215ae7a6b38SJeff Roberson 	 * We enter here with the thread blocked and assigned to the
2216ae7a6b38SJeff Roberson 	 * appropriate cpu run-queue or sleep-queue and with the current
2217ae7a6b38SJeff Roberson 	 * thread-queue locked.
2218ae7a6b38SJeff Roberson 	 */
2219ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
22202454aaf5SJeff Roberson 	newtd = choosethread();
2221686bcb5cSJeff Roberson 	sched_pctcpu_update(td_get_sched(newtd), 0);
2222686bcb5cSJeff Roberson 	TDQ_UNLOCK(tdq);
2223686bcb5cSJeff Roberson 
2224ae7a6b38SJeff Roberson 	/*
2225ae7a6b38SJeff Roberson 	 * Call the MD code to switch contexts if necessary.
2226ae7a6b38SJeff Roberson 	 */
2227ebccf1e3SJoseph Koshy 	if (td != newtd) {
2228ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
2229ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
2230ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
2231ebccf1e3SJoseph Koshy #endif
2232d9fae5abSAndriy Gapon 		SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
22336f5f25e5SJohn Birrell 
22346f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
22356f5f25e5SJohn Birrell 		/*
22366f5f25e5SJohn Birrell 		 * If DTrace has set the active vtime enum to anything
22376f5f25e5SJohn Birrell 		 * other than INACTIVE (0), then it should have set the
22386f5f25e5SJohn Birrell 		 * function to call.
22396f5f25e5SJohn Birrell 		 */
22406f5f25e5SJohn Birrell 		if (dtrace_vtime_active)
22416f5f25e5SJohn Birrell 			(*dtrace_vtime_switch_func)(newtd);
22426f5f25e5SJohn Birrell #endif
2243686bcb5cSJeff Roberson 		td->td_oncpu = NOCPU;
2244ae7a6b38SJeff Roberson 		cpu_switch(td, newtd, mtx);
2245a89c2c8cSMark Johnston 		cpuid = td->td_oncpu = PCPU_GET(cpuid);
2246b3e9e682SRyan Stone 
2247d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , on__cpu);
2248ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
2249ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
2250ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
2251ebccf1e3SJoseph Koshy #endif
2252b3e9e682SRyan Stone 	} else {
2253ae7a6b38SJeff Roberson 		thread_unblock_switch(td, mtx);
2254d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , remain__cpu);
2255b3e9e682SRyan Stone 	}
2256686bcb5cSJeff Roberson 	KASSERT(curthread->td_md.md_spinlock_count == 1,
2257686bcb5cSJeff Roberson 	    ("invalid count %d", curthread->td_md.md_spinlock_count));
2258afa0a46cSAndriy Gapon 
2259afa0a46cSAndriy Gapon 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
2260afa0a46cSAndriy Gapon 	    "prio:%d", td->td_priority);
226135e6168fSJeff Roberson }
226235e6168fSJeff Roberson 
2263ae7a6b38SJeff Roberson /*
2264ae7a6b38SJeff Roberson  * Adjust thread priorities as a result of a nice request.
2265ae7a6b38SJeff Roberson  */
226635e6168fSJeff Roberson void
2267fa885116SJulian Elischer sched_nice(struct proc *p, int nice)
226835e6168fSJeff Roberson {
226935e6168fSJeff Roberson 	struct thread *td;
227035e6168fSJeff Roberson 
2271fa885116SJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
2272e7d50326SJeff Roberson 
2273fa885116SJulian Elischer 	p->p_nice = nice;
22748460a577SJohn Birrell 	FOREACH_THREAD_IN_PROC(p, td) {
22757b20fb19SJeff Roberson 		thread_lock(td);
22768460a577SJohn Birrell 		sched_priority(td);
2277e7d50326SJeff Roberson 		sched_prio(td, td->td_base_user_pri);
22787b20fb19SJeff Roberson 		thread_unlock(td);
227935e6168fSJeff Roberson 	}
2280fa885116SJulian Elischer }
228135e6168fSJeff Roberson 
2282ae7a6b38SJeff Roberson /*
2283ae7a6b38SJeff Roberson  * Record the sleep time for the interactivity scorer.
2284ae7a6b38SJeff Roberson  */
228535e6168fSJeff Roberson void
2286c5aa6b58SJeff Roberson sched_sleep(struct thread *td, int prio)
228735e6168fSJeff Roberson {
2288e7d50326SJeff Roberson 
22897b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
229035e6168fSJeff Roberson 
229154b0e65fSJeff Roberson 	td->td_slptick = ticks;
229217c4c356SKonstantin Belousov 	if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
2293c5aa6b58SJeff Roberson 		td->td_flags |= TDF_CANSWAP;
22942dc29adbSJohn Baldwin 	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
22952dc29adbSJohn Baldwin 		return;
22960502fe2eSJeff Roberson 	if (static_boost == 1 && prio)
2297c5aa6b58SJeff Roberson 		sched_prio(td, prio);
22980502fe2eSJeff Roberson 	else if (static_boost && td->td_priority > static_boost)
22990502fe2eSJeff Roberson 		sched_prio(td, static_boost);
230035e6168fSJeff Roberson }
230135e6168fSJeff Roberson 
2302ae7a6b38SJeff Roberson /*
2303ae7a6b38SJeff Roberson  * Schedule a thread to resume execution and record how long it voluntarily
2304ae7a6b38SJeff Roberson  * slept.  We also update the pctcpu, interactivity, and priority.
230561a74c5cSJeff Roberson  *
230661a74c5cSJeff Roberson  * Requires the thread lock on entry, drops on exit.
2307ae7a6b38SJeff Roberson  */
230835e6168fSJeff Roberson void
230961a74c5cSJeff Roberson sched_wakeup(struct thread *td, int srqflags)
231035e6168fSJeff Roberson {
231114618990SJeff Roberson 	struct td_sched *ts;
2312ae7a6b38SJeff Roberson 	int slptick;
2313e7d50326SJeff Roberson 
23147b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
231593ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
2316c5aa6b58SJeff Roberson 	td->td_flags &= ~TDF_CANSWAP;
231761a74c5cSJeff Roberson 
231835e6168fSJeff Roberson 	/*
2319e7d50326SJeff Roberson 	 * If we slept for more than a tick update our interactivity and
2320e7d50326SJeff Roberson 	 * priority.
232135e6168fSJeff Roberson 	 */
232254b0e65fSJeff Roberson 	slptick = td->td_slptick;
232354b0e65fSJeff Roberson 	td->td_slptick = 0;
2324ae7a6b38SJeff Roberson 	if (slptick && slptick != ticks) {
23257295465eSAlexander Motin 		ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
23268460a577SJohn Birrell 		sched_interact_update(td);
23277295465eSAlexander Motin 		sched_pctcpu_update(ts, 0);
2328f1e8dc4aSJeff Roberson 	}
23295e5c3873SJeff Roberson 	/*
23305e5c3873SJeff Roberson 	 * Reset the slice value since we slept and advanced the round-robin.
23315e5c3873SJeff Roberson 	 */
23325e5c3873SJeff Roberson 	ts->ts_slice = 0;
233361a74c5cSJeff Roberson 	sched_add(td, SRQ_BORING | srqflags);
233435e6168fSJeff Roberson }
233535e6168fSJeff Roberson 
233635e6168fSJeff Roberson /*
233735e6168fSJeff Roberson  * Penalize the parent for creating a new child and initialize the child's
233835e6168fSJeff Roberson  * priority.
233935e6168fSJeff Roberson  */
234035e6168fSJeff Roberson void
23418460a577SJohn Birrell sched_fork(struct thread *td, struct thread *child)
234215dc847eSJeff Roberson {
23437b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
234493ccd6bfSKonstantin Belousov 	sched_pctcpu_update(td_get_sched(td), 1);
2345ad1e7d28SJulian Elischer 	sched_fork_thread(td, child);
2346e7d50326SJeff Roberson 	/*
2347e7d50326SJeff Roberson 	 * Penalize the parent and child for forking.
2348e7d50326SJeff Roberson 	 */
2349e7d50326SJeff Roberson 	sched_interact_fork(child);
2350e7d50326SJeff Roberson 	sched_priority(child);
235193ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_runtime += tickincr;
2352e7d50326SJeff Roberson 	sched_interact_update(td);
2353e7d50326SJeff Roberson 	sched_priority(td);
2354ad1e7d28SJulian Elischer }
2355ad1e7d28SJulian Elischer 
2356ae7a6b38SJeff Roberson /*
2357ae7a6b38SJeff Roberson  * Fork a new thread, may be within the same process.
2358ae7a6b38SJeff Roberson  */
2359ad1e7d28SJulian Elischer void
2360ad1e7d28SJulian Elischer sched_fork_thread(struct thread *td, struct thread *child)
2361ad1e7d28SJulian Elischer {
2362ad1e7d28SJulian Elischer 	struct td_sched *ts;
2363ad1e7d28SJulian Elischer 	struct td_sched *ts2;
23645e5c3873SJeff Roberson 	struct tdq *tdq;
23658460a577SJohn Birrell 
23665e5c3873SJeff Roberson 	tdq = TDQ_SELF();
23678b16c208SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2368e7d50326SJeff Roberson 	/*
2369e7d50326SJeff Roberson 	 * Initialize child.
2370e7d50326SJeff Roberson 	 */
237193ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
237293ccd6bfSKonstantin Belousov 	ts2 = td_get_sched(child);
237392de34dfSJohn Baldwin 	child->td_oncpu = NOCPU;
237492de34dfSJohn Baldwin 	child->td_lastcpu = NOCPU;
23755e5c3873SJeff Roberson 	child->td_lock = TDQ_LOCKPTR(tdq);
23768b16c208SJeff Roberson 	child->td_cpuset = cpuset_ref(td->td_cpuset);
23773f289c3fSJeff Roberson 	child->td_domain.dr_policy = td->td_cpuset->cs_domain;
2378ad1e7d28SJulian Elischer 	ts2->ts_cpu = ts->ts_cpu;
23798b16c208SJeff Roberson 	ts2->ts_flags = 0;
2380e7d50326SJeff Roberson 	/*
238122d19207SJohn Baldwin 	 * Grab our parents cpu estimation information.
2382e7d50326SJeff Roberson 	 */
2383ad1e7d28SJulian Elischer 	ts2->ts_ticks = ts->ts_ticks;
2384ad1e7d28SJulian Elischer 	ts2->ts_ltick = ts->ts_ltick;
2385ad1e7d28SJulian Elischer 	ts2->ts_ftick = ts->ts_ftick;
238622d19207SJohn Baldwin 	/*
238722d19207SJohn Baldwin 	 * Do not inherit any borrowed priority from the parent.
238822d19207SJohn Baldwin 	 */
238922d19207SJohn Baldwin 	child->td_priority = child->td_base_pri;
2390e7d50326SJeff Roberson 	/*
2391e7d50326SJeff Roberson 	 * And update interactivity score.
2392e7d50326SJeff Roberson 	 */
2393ae7a6b38SJeff Roberson 	ts2->ts_slptime = ts->ts_slptime;
2394ae7a6b38SJeff Roberson 	ts2->ts_runtime = ts->ts_runtime;
23955e5c3873SJeff Roberson 	/* Attempt to quickly learn interactivity. */
23965e5c3873SJeff Roberson 	ts2->ts_slice = tdq_slice(tdq) - sched_slice_min;
23978f51ad55SJeff Roberson #ifdef KTR
23988f51ad55SJeff Roberson 	bzero(ts2->ts_name, sizeof(ts2->ts_name));
23998f51ad55SJeff Roberson #endif
240015dc847eSJeff Roberson }
240115dc847eSJeff Roberson 
2402ae7a6b38SJeff Roberson /*
2403ae7a6b38SJeff Roberson  * Adjust the priority class of a thread.
2404ae7a6b38SJeff Roberson  */
240515dc847eSJeff Roberson void
24068460a577SJohn Birrell sched_class(struct thread *td, int class)
240715dc847eSJeff Roberson {
240815dc847eSJeff Roberson 
24097b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
24108460a577SJohn Birrell 	if (td->td_pri_class == class)
241115dc847eSJeff Roberson 		return;
24128460a577SJohn Birrell 	td->td_pri_class = class;
241335e6168fSJeff Roberson }
241435e6168fSJeff Roberson 
241535e6168fSJeff Roberson /*
241635e6168fSJeff Roberson  * Return some of the child's priority and interactivity to the parent.
241735e6168fSJeff Roberson  */
241835e6168fSJeff Roberson void
2419fc6c30f6SJulian Elischer sched_exit(struct proc *p, struct thread *child)
242035e6168fSJeff Roberson {
2421e7d50326SJeff Roberson 	struct thread *td;
2422141ad61cSJeff Roberson 
24238f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2424cd39bb09SXin LI 	    "prio:%d", child->td_priority);
2425374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
2426e7d50326SJeff Roberson 	td = FIRST_THREAD_IN_PROC(p);
2427e7d50326SJeff Roberson 	sched_exit_thread(td, child);
2428ad1e7d28SJulian Elischer }
2429ad1e7d28SJulian Elischer 
2430ae7a6b38SJeff Roberson /*
2431ae7a6b38SJeff Roberson  * Penalize another thread for the time spent on this one.  This helps to
2432ae7a6b38SJeff Roberson  * worsen the priority and interactivity of processes which schedule batch
2433ae7a6b38SJeff Roberson  * jobs such as make.  This has little effect on the make process itself but
2434ae7a6b38SJeff Roberson  * causes new processes spawned by it to receive worse scores immediately.
2435ae7a6b38SJeff Roberson  */
2436ad1e7d28SJulian Elischer void
2437fc6c30f6SJulian Elischer sched_exit_thread(struct thread *td, struct thread *child)
2438ad1e7d28SJulian Elischer {
2439fc6c30f6SJulian Elischer 
24408f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2441cd39bb09SXin LI 	    "prio:%d", child->td_priority);
2442e7d50326SJeff Roberson 	/*
2443e7d50326SJeff Roberson 	 * Give the child's runtime to the parent without returning the
2444e7d50326SJeff Roberson 	 * sleep time as a penalty to the parent.  This causes shells that
2445e7d50326SJeff Roberson 	 * launch expensive things to mark their children as expensive.
2446e7d50326SJeff Roberson 	 */
24477b20fb19SJeff Roberson 	thread_lock(td);
244893ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_runtime += td_get_sched(child)->ts_runtime;
2449fc6c30f6SJulian Elischer 	sched_interact_update(td);
2450e7d50326SJeff Roberson 	sched_priority(td);
24517b20fb19SJeff Roberson 	thread_unlock(td);
2452ad1e7d28SJulian Elischer }
2453ad1e7d28SJulian Elischer 
2454ff256d9cSJeff Roberson void
2455ff256d9cSJeff Roberson sched_preempt(struct thread *td)
2456ff256d9cSJeff Roberson {
2457ff256d9cSJeff Roberson 	struct tdq *tdq;
2458686bcb5cSJeff Roberson 	int flags;
2459ff256d9cSJeff Roberson 
2460b3e9e682SRyan Stone 	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
2461b3e9e682SRyan Stone 
2462ff256d9cSJeff Roberson 	thread_lock(td);
2463ff256d9cSJeff Roberson 	tdq = TDQ_SELF();
2464ff256d9cSJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2465ff256d9cSJeff Roberson 	if (td->td_priority > tdq->tdq_lowpri) {
2466686bcb5cSJeff Roberson 		if (td->td_critnest == 1) {
24678df78c41SJeff Roberson 			flags = SW_INVOL | SW_PREEMPT;
2468686bcb5cSJeff Roberson 			flags |= TD_IS_IDLETHREAD(td) ? SWT_REMOTEWAKEIDLE :
2469686bcb5cSJeff Roberson 			    SWT_REMOTEPREEMPT;
2470686bcb5cSJeff Roberson 			mi_switch(flags);
2471686bcb5cSJeff Roberson 			/* Switch dropped thread lock. */
2472686bcb5cSJeff Roberson 			return;
2473686bcb5cSJeff Roberson 		}
2474ff256d9cSJeff Roberson 		td->td_owepreempt = 1;
24757789ab32SMark Johnston 	} else {
24767789ab32SMark Johnston 		tdq->tdq_owepreempt = 0;
2477ff256d9cSJeff Roberson 	}
2478ff256d9cSJeff Roberson 	thread_unlock(td);
2479ff256d9cSJeff Roberson }
2480ff256d9cSJeff Roberson 
2481ae7a6b38SJeff Roberson /*
2482ae7a6b38SJeff Roberson  * Fix priorities on return to user-space.  Priorities may be elevated due
2483ae7a6b38SJeff Roberson  * to static priorities in msleep() or similar.
2484ae7a6b38SJeff Roberson  */
2485ad1e7d28SJulian Elischer void
248628240885SMateusz Guzik sched_userret_slowpath(struct thread *td)
2487ad1e7d28SJulian Elischer {
248828240885SMateusz Guzik 
24897b20fb19SJeff Roberson 	thread_lock(td);
2490ad1e7d28SJulian Elischer 	td->td_priority = td->td_user_pri;
2491ad1e7d28SJulian Elischer 	td->td_base_pri = td->td_user_pri;
249262fa74d9SJeff Roberson 	tdq_setlowpri(TDQ_SELF(), td);
24937b20fb19SJeff Roberson 	thread_unlock(td);
2494ad1e7d28SJulian Elischer }
249535e6168fSJeff Roberson 
2496ae7a6b38SJeff Roberson /*
2497ae7a6b38SJeff Roberson  * Handle a stathz tick.  This is really only relevant for timeshare
2498ae7a6b38SJeff Roberson  * threads.
2499ae7a6b38SJeff Roberson  */
250035e6168fSJeff Roberson void
2501c3cccf95SJeff Roberson sched_clock(struct thread *td, int cnt)
250235e6168fSJeff Roberson {
2503ad1e7d28SJulian Elischer 	struct tdq *tdq;
2504ad1e7d28SJulian Elischer 	struct td_sched *ts;
250535e6168fSJeff Roberson 
2506ae7a6b38SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
25073f872f85SJeff Roberson 	tdq = TDQ_SELF();
25087fcf154aSJeff Roberson #ifdef SMP
25097fcf154aSJeff Roberson 	/*
25107fcf154aSJeff Roberson 	 * We run the long term load balancer infrequently on the first cpu.
25117fcf154aSJeff Roberson 	 */
2512c3cccf95SJeff Roberson 	if (balance_tdq == tdq && smp_started != 0 && rebalance != 0 &&
2513c3cccf95SJeff Roberson 	    balance_ticks != 0) {
2514c3cccf95SJeff Roberson 		balance_ticks -= cnt;
2515c3cccf95SJeff Roberson 		if (balance_ticks <= 0)
25167fcf154aSJeff Roberson 			sched_balance();
25177fcf154aSJeff Roberson 	}
25187fcf154aSJeff Roberson #endif
25193f872f85SJeff Roberson 	/*
25201690c6c1SJeff Roberson 	 * Save the old switch count so we have a record of the last ticks
25211690c6c1SJeff Roberson 	 * activity.   Initialize the new switch count based on our load.
25221690c6c1SJeff Roberson 	 * If there is some activity seed it to reflect that.
25231690c6c1SJeff Roberson 	 */
25241690c6c1SJeff Roberson 	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
25256c47aaaeSJeff Roberson 	tdq->tdq_switchcnt = tdq->tdq_load;
25261690c6c1SJeff Roberson 	/*
25273f872f85SJeff Roberson 	 * Advance the insert index once for each tick to ensure that all
25283f872f85SJeff Roberson 	 * threads get a chance to run.
25293f872f85SJeff Roberson 	 */
25303f872f85SJeff Roberson 	if (tdq->tdq_idx == tdq->tdq_ridx) {
25313f872f85SJeff Roberson 		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
25323f872f85SJeff Roberson 		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
25333f872f85SJeff Roberson 			tdq->tdq_ridx = tdq->tdq_idx;
25343f872f85SJeff Roberson 	}
253593ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
25367295465eSAlexander Motin 	sched_pctcpu_update(ts, 1);
2537c3cccf95SJeff Roberson 	if ((td->td_pri_class & PRI_FIFO_BIT) || TD_IS_IDLETHREAD(td))
2538a8949de2SJeff Roberson 		return;
2539c3cccf95SJeff Roberson 
2540c9a8cba4SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2541a8949de2SJeff Roberson 		/*
2542fd0b8c78SJeff Roberson 		 * We used a tick; charge it to the thread so
2543fd0b8c78SJeff Roberson 		 * that we can compute our interactivity.
254415dc847eSJeff Roberson 		 */
2545c3cccf95SJeff Roberson 		td_get_sched(td)->ts_runtime += tickincr * cnt;
25468460a577SJohn Birrell 		sched_interact_update(td);
254773daf66fSJeff Roberson 		sched_priority(td);
2548fd0b8c78SJeff Roberson 	}
2549579895dfSAlexander Motin 
255035e6168fSJeff Roberson 	/*
2551579895dfSAlexander Motin 	 * Force a context switch if the current thread has used up a full
2552579895dfSAlexander Motin 	 * time slice (default is 100ms).
255335e6168fSJeff Roberson 	 */
2554c3cccf95SJeff Roberson 	ts->ts_slice += cnt;
2555c3cccf95SJeff Roberson 	if (ts->ts_slice >= tdq_slice(tdq)) {
25565e5c3873SJeff Roberson 		ts->ts_slice = 0;
25573d7f4117SAlexander Motin 		td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
255835e6168fSJeff Roberson 	}
2559579895dfSAlexander Motin }
256035e6168fSJeff Roberson 
2561ccd0ec40SKonstantin Belousov u_int
2562ccd0ec40SKonstantin Belousov sched_estcpu(struct thread *td __unused)
2563ae7a6b38SJeff Roberson {
2564ae7a6b38SJeff Roberson 
2565ccd0ec40SKonstantin Belousov 	return (0);
2566ae7a6b38SJeff Roberson }
2567ae7a6b38SJeff Roberson 
2568ae7a6b38SJeff Roberson /*
2569ae7a6b38SJeff Roberson  * Return whether the current CPU has runnable tasks.  Used for in-kernel
2570ae7a6b38SJeff Roberson  * cooperative idle threads.
2571ae7a6b38SJeff Roberson  */
257235e6168fSJeff Roberson int
257335e6168fSJeff Roberson sched_runnable(void)
257435e6168fSJeff Roberson {
2575ad1e7d28SJulian Elischer 	struct tdq *tdq;
2576b90816f1SJeff Roberson 	int load;
257735e6168fSJeff Roberson 
2578b90816f1SJeff Roberson 	load = 1;
2579b90816f1SJeff Roberson 
2580ad1e7d28SJulian Elischer 	tdq = TDQ_SELF();
25813f741ca1SJeff Roberson 	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2582d2ad694cSJeff Roberson 		if (tdq->tdq_load > 0)
25833f741ca1SJeff Roberson 			goto out;
25843f741ca1SJeff Roberson 	} else
2585d2ad694cSJeff Roberson 		if (tdq->tdq_load - 1 > 0)
2586b90816f1SJeff Roberson 			goto out;
2587b90816f1SJeff Roberson 	load = 0;
2588b90816f1SJeff Roberson out:
2589b90816f1SJeff Roberson 	return (load);
259035e6168fSJeff Roberson }
259135e6168fSJeff Roberson 
2592ae7a6b38SJeff Roberson /*
2593ae7a6b38SJeff Roberson  * Choose the highest priority thread to run.  The thread is removed from
2594ae7a6b38SJeff Roberson  * the run-queue while running however the load remains.  For SMP we set
2595ae7a6b38SJeff Roberson  * the tdq in the global idle bitmask if it idles here.
2596ae7a6b38SJeff Roberson  */
25977a5e5e2aSJeff Roberson struct thread *
2598c9f25d8fSJeff Roberson sched_choose(void)
2599c9f25d8fSJeff Roberson {
26009727e637SJeff Roberson 	struct thread *td;
2601ae7a6b38SJeff Roberson 	struct tdq *tdq;
2602ae7a6b38SJeff Roberson 
2603ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2604ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
26059727e637SJeff Roberson 	td = tdq_choose(tdq);
26069727e637SJeff Roberson 	if (td) {
26079727e637SJeff Roberson 		tdq_runq_rem(tdq, td);
26080502fe2eSJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
26099727e637SJeff Roberson 		return (td);
261035e6168fSJeff Roberson 	}
26110502fe2eSJeff Roberson 	tdq->tdq_lowpri = PRI_MAX_IDLE;
261262fa74d9SJeff Roberson 	return (PCPU_GET(idlethread));
26137a5e5e2aSJeff Roberson }
26147a5e5e2aSJeff Roberson 
2615ae7a6b38SJeff Roberson /*
2616ae7a6b38SJeff Roberson  * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2617ae7a6b38SJeff Roberson  * we always request it once we exit a critical section.
2618ae7a6b38SJeff Roberson  */
2619ae7a6b38SJeff Roberson static inline void
2620ae7a6b38SJeff Roberson sched_setpreempt(struct thread *td)
26217a5e5e2aSJeff Roberson {
26227a5e5e2aSJeff Roberson 	struct thread *ctd;
26237a5e5e2aSJeff Roberson 	int cpri;
26247a5e5e2aSJeff Roberson 	int pri;
26257a5e5e2aSJeff Roberson 
2626ff256d9cSJeff Roberson 	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2627ff256d9cSJeff Roberson 
26287a5e5e2aSJeff Roberson 	ctd = curthread;
26297a5e5e2aSJeff Roberson 	pri = td->td_priority;
26307a5e5e2aSJeff Roberson 	cpri = ctd->td_priority;
2631ff256d9cSJeff Roberson 	if (pri < cpri)
2632ff256d9cSJeff Roberson 		ctd->td_flags |= TDF_NEEDRESCHED;
2633879e0604SMateusz Guzik 	if (KERNEL_PANICKED() || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2634ae7a6b38SJeff Roberson 		return;
2635ff256d9cSJeff Roberson 	if (!sched_shouldpreempt(pri, cpri, 0))
2636ae7a6b38SJeff Roberson 		return;
26377a5e5e2aSJeff Roberson 	ctd->td_owepreempt = 1;
263835e6168fSJeff Roberson }
263935e6168fSJeff Roberson 
2640ae7a6b38SJeff Roberson /*
264173daf66fSJeff Roberson  * Add a thread to a thread queue.  Select the appropriate runq and add the
264273daf66fSJeff Roberson  * thread to it.  This is the internal function called when the tdq is
264373daf66fSJeff Roberson  * predetermined.
2644ae7a6b38SJeff Roberson  */
264535e6168fSJeff Roberson void
2646ae7a6b38SJeff Roberson tdq_add(struct tdq *tdq, struct thread *td, int flags)
264735e6168fSJeff Roberson {
2648c9f25d8fSJeff Roberson 
2649ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
265061a74c5cSJeff Roberson 	THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
26517a5e5e2aSJeff Roberson 	KASSERT((td->td_inhibitors == 0),
26527a5e5e2aSJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
26537a5e5e2aSJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
26547a5e5e2aSJeff Roberson 	    ("sched_add: bad thread state"));
2655b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
2656b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
2657ae7a6b38SJeff Roberson 
2658ae7a6b38SJeff Roberson 	if (td->td_priority < tdq->tdq_lowpri)
2659ae7a6b38SJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
26609727e637SJeff Roberson 	tdq_runq_add(tdq, td, flags);
26619727e637SJeff Roberson 	tdq_load_add(tdq, td);
2662ae7a6b38SJeff Roberson }
2663ae7a6b38SJeff Roberson 
2664ae7a6b38SJeff Roberson /*
2665ae7a6b38SJeff Roberson  * Select the target thread queue and add a thread to it.  Request
2666ae7a6b38SJeff Roberson  * preemption or IPI a remote processor if required.
266761a74c5cSJeff Roberson  *
266861a74c5cSJeff Roberson  * Requires the thread lock on entry, drops on exit.
2669ae7a6b38SJeff Roberson  */
2670ae7a6b38SJeff Roberson void
2671ae7a6b38SJeff Roberson sched_add(struct thread *td, int flags)
2672ae7a6b38SJeff Roberson {
2673ae7a6b38SJeff Roberson 	struct tdq *tdq;
26747b8bfa0dSJeff Roberson #ifdef SMP
2675ae7a6b38SJeff Roberson 	int cpu;
2676ae7a6b38SJeff Roberson #endif
26778f51ad55SJeff Roberson 
26788f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
26798f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
26808f51ad55SJeff Roberson 	    sched_tdname(curthread));
26818f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
26828f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
2683b3e9e682SRyan Stone 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
2684b3e9e682SRyan Stone 	    flags & SRQ_PREEMPTED);
2685ae7a6b38SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2686ae7a6b38SJeff Roberson 	/*
2687ae7a6b38SJeff Roberson 	 * Recalculate the priority before we select the target cpu or
2688ae7a6b38SJeff Roberson 	 * run-queue.
2689ae7a6b38SJeff Roberson 	 */
2690ae7a6b38SJeff Roberson 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2691ae7a6b38SJeff Roberson 		sched_priority(td);
2692ae7a6b38SJeff Roberson #ifdef SMP
2693ae7a6b38SJeff Roberson 	/*
2694ae7a6b38SJeff Roberson 	 * Pick the destination cpu and if it isn't ours transfer to the
2695ae7a6b38SJeff Roberson 	 * target cpu.
2696ae7a6b38SJeff Roberson 	 */
26979727e637SJeff Roberson 	cpu = sched_pickcpu(td, flags);
26989727e637SJeff Roberson 	tdq = sched_setcpu(td, cpu, flags);
2699ae7a6b38SJeff Roberson 	tdq_add(tdq, td, flags);
270061a74c5cSJeff Roberson 	if (cpu != PCPU_GET(cpuid))
270127ee18adSRyan Stone 		tdq_notify(tdq, td);
270261a74c5cSJeff Roberson 	else if (!(flags & SRQ_YIELDING))
270361a74c5cSJeff Roberson 		sched_setpreempt(td);
2704ae7a6b38SJeff Roberson #else
2705ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2706ae7a6b38SJeff Roberson 	/*
2707ae7a6b38SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
2708ae7a6b38SJeff Roberson 	 * to the scheduler's lock.
2709ae7a6b38SJeff Roberson 	 */
2710e4894505SMark Johnston 	if (td->td_lock != TDQ_LOCKPTR(tdq)) {
2711e4894505SMark Johnston 		TDQ_LOCK(tdq);
271261a74c5cSJeff Roberson 		if ((flags & SRQ_HOLD) != 0)
271361a74c5cSJeff Roberson 			td->td_lock = TDQ_LOCKPTR(tdq);
271461a74c5cSJeff Roberson 		else
2715ae7a6b38SJeff Roberson 			thread_lock_set(td, TDQ_LOCKPTR(tdq));
2716e4894505SMark Johnston 	}
2717ae7a6b38SJeff Roberson 	tdq_add(tdq, td, flags);
2718ae7a6b38SJeff Roberson 	if (!(flags & SRQ_YIELDING))
2719ae7a6b38SJeff Roberson 		sched_setpreempt(td);
272061a74c5cSJeff Roberson #endif
272161a74c5cSJeff Roberson 	if (!(flags & SRQ_HOLDTD))
272261a74c5cSJeff Roberson 		thread_unlock(td);
272335e6168fSJeff Roberson }
272435e6168fSJeff Roberson 
2725ae7a6b38SJeff Roberson /*
2726ae7a6b38SJeff Roberson  * Remove a thread from a run-queue without running it.  This is used
2727ae7a6b38SJeff Roberson  * when we're stealing a thread from a remote queue.  Otherwise all threads
2728ae7a6b38SJeff Roberson  * exit by calling sched_exit_thread() and sched_throw() themselves.
2729ae7a6b38SJeff Roberson  */
273035e6168fSJeff Roberson void
27317cf90fb3SJeff Roberson sched_rem(struct thread *td)
273235e6168fSJeff Roberson {
2733ad1e7d28SJulian Elischer 	struct tdq *tdq;
27347cf90fb3SJeff Roberson 
27358f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
27368f51ad55SJeff Roberson 	    "prio:%d", td->td_priority);
2737b3e9e682SRyan Stone 	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
273893ccd6bfSKonstantin Belousov 	tdq = TDQ_CPU(td_get_sched(td)->ts_cpu);
2739ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2740ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
27417a5e5e2aSJeff Roberson 	KASSERT(TD_ON_RUNQ(td),
2742ad1e7d28SJulian Elischer 	    ("sched_rem: thread not on run queue"));
27439727e637SJeff Roberson 	tdq_runq_rem(tdq, td);
27449727e637SJeff Roberson 	tdq_load_rem(tdq, td);
27457a5e5e2aSJeff Roberson 	TD_SET_CAN_RUN(td);
274662fa74d9SJeff Roberson 	if (td->td_priority == tdq->tdq_lowpri)
274762fa74d9SJeff Roberson 		tdq_setlowpri(tdq, NULL);
274835e6168fSJeff Roberson }
274935e6168fSJeff Roberson 
2750ae7a6b38SJeff Roberson /*
2751ae7a6b38SJeff Roberson  * Fetch cpu utilization information.  Updates on demand.
2752ae7a6b38SJeff Roberson  */
275335e6168fSJeff Roberson fixpt_t
27547cf90fb3SJeff Roberson sched_pctcpu(struct thread *td)
275535e6168fSJeff Roberson {
275635e6168fSJeff Roberson 	fixpt_t pctcpu;
2757ad1e7d28SJulian Elischer 	struct td_sched *ts;
275835e6168fSJeff Roberson 
275935e6168fSJeff Roberson 	pctcpu = 0;
276093ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
276135e6168fSJeff Roberson 
27623da35a0aSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
27637295465eSAlexander Motin 	sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2764ad1e7d28SJulian Elischer 	if (ts->ts_ticks) {
276535e6168fSJeff Roberson 		int rtick;
276635e6168fSJeff Roberson 
276735e6168fSJeff Roberson 		/* How many rtick per second ? */
2768e7d50326SJeff Roberson 		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2769e7d50326SJeff Roberson 		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
277035e6168fSJeff Roberson 	}
277135e6168fSJeff Roberson 
277235e6168fSJeff Roberson 	return (pctcpu);
277335e6168fSJeff Roberson }
277435e6168fSJeff Roberson 
277562fa74d9SJeff Roberson /*
277662fa74d9SJeff Roberson  * Enforce affinity settings for a thread.  Called after adjustments to
277762fa74d9SJeff Roberson  * cpumask.
277862fa74d9SJeff Roberson  */
2779885d51a3SJeff Roberson void
2780885d51a3SJeff Roberson sched_affinity(struct thread *td)
2781885d51a3SJeff Roberson {
278262fa74d9SJeff Roberson #ifdef SMP
278362fa74d9SJeff Roberson 	struct td_sched *ts;
278462fa74d9SJeff Roberson 
278562fa74d9SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
278693ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
278762fa74d9SJeff Roberson 	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
278862fa74d9SJeff Roberson 		return;
278953a6c8b3SJeff Roberson 	if (TD_ON_RUNQ(td)) {
279053a6c8b3SJeff Roberson 		sched_rem(td);
2791d8d5f036SJeff Roberson 		sched_add(td, SRQ_BORING | SRQ_HOLDTD);
279253a6c8b3SJeff Roberson 		return;
279353a6c8b3SJeff Roberson 	}
279462fa74d9SJeff Roberson 	if (!TD_IS_RUNNING(td))
279562fa74d9SJeff Roberson 		return;
279662fa74d9SJeff Roberson 	/*
27970f7a0ebdSMatthew D Fleming 	 * Force a switch before returning to userspace.  If the
27980f7a0ebdSMatthew D Fleming 	 * target thread is not running locally send an ipi to force
27990f7a0ebdSMatthew D Fleming 	 * the issue.
280062fa74d9SJeff Roberson 	 */
2801a8103ae8SJohn Baldwin 	td->td_flags |= TDF_NEEDRESCHED;
28020f7a0ebdSMatthew D Fleming 	if (td != curthread)
28030f7a0ebdSMatthew D Fleming 		ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
280462fa74d9SJeff Roberson #endif
2805885d51a3SJeff Roberson }
2806885d51a3SJeff Roberson 
2807ae7a6b38SJeff Roberson /*
2808ae7a6b38SJeff Roberson  * Bind a thread to a target cpu.
2809ae7a6b38SJeff Roberson  */
28109bacd788SJeff Roberson void
28119bacd788SJeff Roberson sched_bind(struct thread *td, int cpu)
28129bacd788SJeff Roberson {
2813ad1e7d28SJulian Elischer 	struct td_sched *ts;
28149bacd788SJeff Roberson 
2815c47f202bSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
28161d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
281793ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
28186b2f763fSJeff Roberson 	if (ts->ts_flags & TSF_BOUND)
2819c95d2db2SJeff Roberson 		sched_unbind(td);
28200f7a0ebdSMatthew D Fleming 	KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2821ad1e7d28SJulian Elischer 	ts->ts_flags |= TSF_BOUND;
28226b2f763fSJeff Roberson 	sched_pin();
282380f86c9fSJeff Roberson 	if (PCPU_GET(cpuid) == cpu)
28249bacd788SJeff Roberson 		return;
28256b2f763fSJeff Roberson 	ts->ts_cpu = cpu;
28269bacd788SJeff Roberson 	/* When we return from mi_switch we'll be on the correct cpu. */
2827686bcb5cSJeff Roberson 	mi_switch(SW_VOL);
2828686bcb5cSJeff Roberson 	thread_lock(td);
28299bacd788SJeff Roberson }
28309bacd788SJeff Roberson 
2831ae7a6b38SJeff Roberson /*
2832ae7a6b38SJeff Roberson  * Release a bound thread.
2833ae7a6b38SJeff Roberson  */
28349bacd788SJeff Roberson void
28359bacd788SJeff Roberson sched_unbind(struct thread *td)
28369bacd788SJeff Roberson {
2837e7d50326SJeff Roberson 	struct td_sched *ts;
2838e7d50326SJeff Roberson 
28397b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
28401d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
284193ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
28426b2f763fSJeff Roberson 	if ((ts->ts_flags & TSF_BOUND) == 0)
28436b2f763fSJeff Roberson 		return;
2844e7d50326SJeff Roberson 	ts->ts_flags &= ~TSF_BOUND;
2845e7d50326SJeff Roberson 	sched_unpin();
28469bacd788SJeff Roberson }
28479bacd788SJeff Roberson 
284835e6168fSJeff Roberson int
2849ebccf1e3SJoseph Koshy sched_is_bound(struct thread *td)
2850ebccf1e3SJoseph Koshy {
28517b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
285293ccd6bfSKonstantin Belousov 	return (td_get_sched(td)->ts_flags & TSF_BOUND);
2853ebccf1e3SJoseph Koshy }
2854ebccf1e3SJoseph Koshy 
2855ae7a6b38SJeff Roberson /*
2856ae7a6b38SJeff Roberson  * Basic yield call.
2857ae7a6b38SJeff Roberson  */
285836ec198bSDavid Xu void
285936ec198bSDavid Xu sched_relinquish(struct thread *td)
286036ec198bSDavid Xu {
28617b20fb19SJeff Roberson 	thread_lock(td);
2862686bcb5cSJeff Roberson 	mi_switch(SW_VOL | SWT_RELINQUISH);
286336ec198bSDavid Xu }
286436ec198bSDavid Xu 
2865ae7a6b38SJeff Roberson /*
2866ae7a6b38SJeff Roberson  * Return the total system load.
2867ae7a6b38SJeff Roberson  */
2868ebccf1e3SJoseph Koshy int
286933916c36SJeff Roberson sched_load(void)
287033916c36SJeff Roberson {
287133916c36SJeff Roberson #ifdef SMP
287233916c36SJeff Roberson 	int total;
287333916c36SJeff Roberson 	int i;
287433916c36SJeff Roberson 
287533916c36SJeff Roberson 	total = 0;
28763aa6d94eSJohn Baldwin 	CPU_FOREACH(i)
287762fa74d9SJeff Roberson 		total += TDQ_CPU(i)->tdq_sysload;
287833916c36SJeff Roberson 	return (total);
287933916c36SJeff Roberson #else
2880d2ad694cSJeff Roberson 	return (TDQ_SELF()->tdq_sysload);
288133916c36SJeff Roberson #endif
288233916c36SJeff Roberson }
288333916c36SJeff Roberson 
288433916c36SJeff Roberson int
288535e6168fSJeff Roberson sched_sizeof_proc(void)
288635e6168fSJeff Roberson {
288735e6168fSJeff Roberson 	return (sizeof(struct proc));
288835e6168fSJeff Roberson }
288935e6168fSJeff Roberson 
289035e6168fSJeff Roberson int
289135e6168fSJeff Roberson sched_sizeof_thread(void)
289235e6168fSJeff Roberson {
289335e6168fSJeff Roberson 	return (sizeof(struct thread) + sizeof(struct td_sched));
289435e6168fSJeff Roberson }
2895b41f1452SDavid Xu 
289609c8a4ccSJeff Roberson #ifdef SMP
289709c8a4ccSJeff Roberson #define	TDQ_IDLESPIN(tdq)						\
289809c8a4ccSJeff Roberson     ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
289909c8a4ccSJeff Roberson #else
290009c8a4ccSJeff Roberson #define	TDQ_IDLESPIN(tdq)	1
290109c8a4ccSJeff Roberson #endif
290209c8a4ccSJeff Roberson 
29037a5e5e2aSJeff Roberson /*
29047a5e5e2aSJeff Roberson  * The actual idle process.
29057a5e5e2aSJeff Roberson  */
29067a5e5e2aSJeff Roberson void
29077a5e5e2aSJeff Roberson sched_idletd(void *dummy)
29087a5e5e2aSJeff Roberson {
29097a5e5e2aSJeff Roberson 	struct thread *td;
2910ae7a6b38SJeff Roberson 	struct tdq *tdq;
29112c27cb3aSAlexander Motin 	int oldswitchcnt, switchcnt;
29121690c6c1SJeff Roberson 	int i;
29137a5e5e2aSJeff Roberson 
29147b55ab05SJeff Roberson 	mtx_assert(&Giant, MA_NOTOWNED);
29157a5e5e2aSJeff Roberson 	td = curthread;
2916ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2917ba96d2d8SJohn Baldwin 	THREAD_NO_SLEEPING();
29182c27cb3aSAlexander Motin 	oldswitchcnt = -1;
2919ae7a6b38SJeff Roberson 	for (;;) {
29202c27cb3aSAlexander Motin 		if (tdq->tdq_load) {
29212c27cb3aSAlexander Motin 			thread_lock(td);
2922686bcb5cSJeff Roberson 			mi_switch(SW_VOL | SWT_IDLE);
29232c27cb3aSAlexander Motin 		}
29242c27cb3aSAlexander Motin 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2925ae7a6b38SJeff Roberson #ifdef SMP
292697e9382dSDon Lewis 		if (always_steal || switchcnt != oldswitchcnt) {
29272c27cb3aSAlexander Motin 			oldswitchcnt = switchcnt;
29281690c6c1SJeff Roberson 			if (tdq_idled(tdq) == 0)
29291690c6c1SJeff Roberson 				continue;
29302c27cb3aSAlexander Motin 		}
29311690c6c1SJeff Roberson 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
29322fd4047fSAlexander Motin #else
29332fd4047fSAlexander Motin 		oldswitchcnt = switchcnt;
29342fd4047fSAlexander Motin #endif
29351690c6c1SJeff Roberson 		/*
29361690c6c1SJeff Roberson 		 * If we're switching very frequently, spin while checking
29371690c6c1SJeff Roberson 		 * for load rather than entering a low power state that
29387b55ab05SJeff Roberson 		 * may require an IPI.  However, don't do any busy
29397b55ab05SJeff Roberson 		 * loops while on SMT machines as this simply steals
29407b55ab05SJeff Roberson 		 * cycles from cores doing useful work.
29411690c6c1SJeff Roberson 		 */
294209c8a4ccSJeff Roberson 		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
29431690c6c1SJeff Roberson 			for (i = 0; i < sched_idlespins; i++) {
29441690c6c1SJeff Roberson 				if (tdq->tdq_load)
29451690c6c1SJeff Roberson 					break;
29461690c6c1SJeff Roberson 				cpu_spinwait();
29471690c6c1SJeff Roberson 			}
29481690c6c1SJeff Roberson 		}
29492c27cb3aSAlexander Motin 
29502c27cb3aSAlexander Motin 		/* If there was context switch during spin, restart it. */
29516c47aaaeSJeff Roberson 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
29522c27cb3aSAlexander Motin 		if (tdq->tdq_load != 0 || switchcnt != oldswitchcnt)
29532c27cb3aSAlexander Motin 			continue;
29542c27cb3aSAlexander Motin 
29552c27cb3aSAlexander Motin 		/* Run main MD idle handler. */
29569f9ad565SAlexander Motin 		tdq->tdq_cpu_idle = 1;
295779654969SAlexander Motin 		/*
295879654969SAlexander Motin 		 * Make sure that tdq_cpu_idle update is globally visible
295979654969SAlexander Motin 		 * before cpu_idle() read tdq_load.  The order is important
296079654969SAlexander Motin 		 * to avoid race with tdq_notify.
296179654969SAlexander Motin 		 */
2962e8677f38SKonstantin Belousov 		atomic_thread_fence_seq_cst();
296397e9382dSDon Lewis 		/*
296497e9382dSDon Lewis 		 * Checking for again after the fence picks up assigned
296597e9382dSDon Lewis 		 * threads often enough to make it worthwhile to do so in
296697e9382dSDon Lewis 		 * order to avoid calling cpu_idle().
296797e9382dSDon Lewis 		 */
296897e9382dSDon Lewis 		if (tdq->tdq_load != 0) {
296997e9382dSDon Lewis 			tdq->tdq_cpu_idle = 0;
297097e9382dSDon Lewis 			continue;
297197e9382dSDon Lewis 		}
29722c27cb3aSAlexander Motin 		cpu_idle(switchcnt * 4 > sched_idlespinthresh);
29739f9ad565SAlexander Motin 		tdq->tdq_cpu_idle = 0;
29742c27cb3aSAlexander Motin 
29752c27cb3aSAlexander Motin 		/*
29762c27cb3aSAlexander Motin 		 * Account thread-less hardware interrupts and
29772c27cb3aSAlexander Motin 		 * other wakeup reasons equal to context switches.
29782c27cb3aSAlexander Motin 		 */
29792c27cb3aSAlexander Motin 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
29802c27cb3aSAlexander Motin 		if (switchcnt != oldswitchcnt)
29812c27cb3aSAlexander Motin 			continue;
29822c27cb3aSAlexander Motin 		tdq->tdq_switchcnt++;
29832c27cb3aSAlexander Motin 		oldswitchcnt++;
2984ae7a6b38SJeff Roberson 	}
2985b41f1452SDavid Xu }
2986e7d50326SJeff Roberson 
29877b20fb19SJeff Roberson /*
29887b20fb19SJeff Roberson  * A CPU is entering for the first time or a thread is exiting.
29897b20fb19SJeff Roberson  */
29907b20fb19SJeff Roberson void
29917b20fb19SJeff Roberson sched_throw(struct thread *td)
29927b20fb19SJeff Roberson {
299359c68134SJeff Roberson 	struct thread *newtd;
2994ae7a6b38SJeff Roberson 	struct tdq *tdq;
2995ae7a6b38SJeff Roberson 
2996018ff686SJeff Roberson 	tdq = TDQ_SELF();
2997*589aed00SKyle Evans 	if (__predict_false(td == NULL)) {
2998ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
2999*589aed00SKyle Evans 		/* Correct spinlock nesting. */
30007b20fb19SJeff Roberson 		spinlock_exit();
30017e3a96eaSJohn Baldwin 		PCPU_SET(switchtime, cpu_ticks());
30027e3a96eaSJohn Baldwin 		PCPU_SET(switchticks, ticks);
30037b20fb19SJeff Roberson 	} else {
3004686bcb5cSJeff Roberson 		THREAD_LOCK_ASSERT(td, MA_OWNED);
3005686bcb5cSJeff Roberson 		THREAD_LOCKPTR_ASSERT(td, TDQ_LOCKPTR(tdq));
30069727e637SJeff Roberson 		tdq_load_rem(tdq, td);
300792de34dfSJohn Baldwin 		td->td_lastcpu = td->td_oncpu;
300892de34dfSJohn Baldwin 		td->td_oncpu = NOCPU;
30091eb13fceSJeff Roberson 		thread_lock_block(td);
30107b20fb19SJeff Roberson 	}
301159c68134SJeff Roberson 	newtd = choosethread();
3012686bcb5cSJeff Roberson 	spinlock_enter();
3013686bcb5cSJeff Roberson 	TDQ_UNLOCK(tdq);
3014686bcb5cSJeff Roberson 	KASSERT(curthread->td_md.md_spinlock_count == 1,
3015686bcb5cSJeff Roberson 	    ("invalid count %d", curthread->td_md.md_spinlock_count));
30161eb13fceSJeff Roberson 	/* doesn't return */
30171eb13fceSJeff Roberson 	if (__predict_false(td == NULL))
301859c68134SJeff Roberson 		cpu_throw(td, newtd);		/* doesn't return */
30191eb13fceSJeff Roberson 	else
30201eb13fceSJeff Roberson 		cpu_switch(td, newtd, TDQ_LOCKPTR(tdq));
30217b20fb19SJeff Roberson }
30227b20fb19SJeff Roberson 
3023ae7a6b38SJeff Roberson /*
3024ae7a6b38SJeff Roberson  * This is called from fork_exit().  Just acquire the correct locks and
3025ae7a6b38SJeff Roberson  * let fork do the rest of the work.
3026ae7a6b38SJeff Roberson  */
30277b20fb19SJeff Roberson void
3028fe54587fSJeff Roberson sched_fork_exit(struct thread *td)
30297b20fb19SJeff Roberson {
3030ae7a6b38SJeff Roberson 	struct tdq *tdq;
3031ae7a6b38SJeff Roberson 	int cpuid;
30327b20fb19SJeff Roberson 
30337b20fb19SJeff Roberson 	/*
30347b20fb19SJeff Roberson 	 * Finish setting up thread glue so that it begins execution in a
3035ae7a6b38SJeff Roberson 	 * non-nested critical section with the scheduler lock held.
30367b20fb19SJeff Roberson 	 */
3037686bcb5cSJeff Roberson 	KASSERT(curthread->td_md.md_spinlock_count == 1,
3038686bcb5cSJeff Roberson 	    ("invalid count %d", curthread->td_md.md_spinlock_count));
3039ae7a6b38SJeff Roberson 	cpuid = PCPU_GET(cpuid);
3040018ff686SJeff Roberson 	tdq = TDQ_SELF();
3041686bcb5cSJeff Roberson 	TDQ_LOCK(tdq);
3042686bcb5cSJeff Roberson 	spinlock_exit();
3043ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
3044ae7a6b38SJeff Roberson 	td->td_oncpu = cpuid;
304528ef18b8SAndriy Gapon 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
304628ef18b8SAndriy Gapon 	    "prio:%d", td->td_priority);
304728ef18b8SAndriy Gapon 	SDT_PROBE0(sched, , , on__cpu);
30487b20fb19SJeff Roberson }
30497b20fb19SJeff Roberson 
30508f51ad55SJeff Roberson /*
30518f51ad55SJeff Roberson  * Create on first use to catch odd startup conditons.
30528f51ad55SJeff Roberson  */
30538f51ad55SJeff Roberson char *
30548f51ad55SJeff Roberson sched_tdname(struct thread *td)
30558f51ad55SJeff Roberson {
30568f51ad55SJeff Roberson #ifdef KTR
30578f51ad55SJeff Roberson 	struct td_sched *ts;
30588f51ad55SJeff Roberson 
305993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
30608f51ad55SJeff Roberson 	if (ts->ts_name[0] == '\0')
30618f51ad55SJeff Roberson 		snprintf(ts->ts_name, sizeof(ts->ts_name),
30628f51ad55SJeff Roberson 		    "%s tid %d", td->td_name, td->td_tid);
30638f51ad55SJeff Roberson 	return (ts->ts_name);
30648f51ad55SJeff Roberson #else
30658f51ad55SJeff Roberson 	return (td->td_name);
30668f51ad55SJeff Roberson #endif
30678f51ad55SJeff Roberson }
30688f51ad55SJeff Roberson 
306944ad5475SJohn Baldwin #ifdef KTR
307044ad5475SJohn Baldwin void
307144ad5475SJohn Baldwin sched_clear_tdname(struct thread *td)
307244ad5475SJohn Baldwin {
307344ad5475SJohn Baldwin 	struct td_sched *ts;
307444ad5475SJohn Baldwin 
307593ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
307644ad5475SJohn Baldwin 	ts->ts_name[0] = '\0';
307744ad5475SJohn Baldwin }
307844ad5475SJohn Baldwin #endif
307944ad5475SJohn Baldwin 
308007095abfSIvan Voras #ifdef SMP
308107095abfSIvan Voras 
308207095abfSIvan Voras /*
308307095abfSIvan Voras  * Build the CPU topology dump string. Is recursively called to collect
308407095abfSIvan Voras  * the topology tree.
308507095abfSIvan Voras  */
308607095abfSIvan Voras static int
308707095abfSIvan Voras sysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
308807095abfSIvan Voras     int indent)
308907095abfSIvan Voras {
309071a19bdcSAttilio Rao 	char cpusetbuf[CPUSETBUFSIZ];
309107095abfSIvan Voras 	int i, first;
309207095abfSIvan Voras 
309307095abfSIvan Voras 	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
309419b8a6dbSAndriy Gapon 	    "", 1 + indent / 2, cg->cg_level);
309571a19bdcSAttilio Rao 	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
309671a19bdcSAttilio Rao 	    cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
309707095abfSIvan Voras 	first = TRUE;
3098aefe0a8cSAlexander Motin 	for (i = cg->cg_first; i <= cg->cg_last; i++) {
309971a19bdcSAttilio Rao 		if (CPU_ISSET(i, &cg->cg_mask)) {
310007095abfSIvan Voras 			if (!first)
310107095abfSIvan Voras 				sbuf_printf(sb, ", ");
310207095abfSIvan Voras 			else
310307095abfSIvan Voras 				first = FALSE;
310407095abfSIvan Voras 			sbuf_printf(sb, "%d", i);
310507095abfSIvan Voras 		}
310607095abfSIvan Voras 	}
310707095abfSIvan Voras 	sbuf_printf(sb, "</cpu>\n");
310807095abfSIvan Voras 
310907095abfSIvan Voras 	if (cg->cg_flags != 0) {
3110611daf7eSIvan Voras 		sbuf_printf(sb, "%*s <flags>", indent, "");
311107095abfSIvan Voras 		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
31125368befbSIvan Voras 			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
3113a401f2d0SIvan Voras 		if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
3114a401f2d0SIvan Voras 			sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
31157b55ab05SJeff Roberson 		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
3116a401f2d0SIvan Voras 			sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
3117ef50d5fbSAlexander Motin 		if ((cg->cg_flags & CG_FLAG_NODE) != 0)
3118ef50d5fbSAlexander Motin 			sbuf_printf(sb, "<flag name=\"NODE\">NUMA node</flag>");
311907095abfSIvan Voras 		sbuf_printf(sb, "</flags>\n");
3120611daf7eSIvan Voras 	}
312107095abfSIvan Voras 
312207095abfSIvan Voras 	if (cg->cg_children > 0) {
312307095abfSIvan Voras 		sbuf_printf(sb, "%*s <children>\n", indent, "");
312407095abfSIvan Voras 		for (i = 0; i < cg->cg_children; i++)
312507095abfSIvan Voras 			sysctl_kern_sched_topology_spec_internal(sb,
312607095abfSIvan Voras 			    &cg->cg_child[i], indent+2);
312707095abfSIvan Voras 		sbuf_printf(sb, "%*s </children>\n", indent, "");
312807095abfSIvan Voras 	}
312907095abfSIvan Voras 	sbuf_printf(sb, "%*s</group>\n", indent, "");
313007095abfSIvan Voras 	return (0);
313107095abfSIvan Voras }
313207095abfSIvan Voras 
313307095abfSIvan Voras /*
313407095abfSIvan Voras  * Sysctl handler for retrieving topology dump. It's a wrapper for
313507095abfSIvan Voras  * the recursive sysctl_kern_smp_topology_spec_internal().
313607095abfSIvan Voras  */
313707095abfSIvan Voras static int
313807095abfSIvan Voras sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
313907095abfSIvan Voras {
314007095abfSIvan Voras 	struct sbuf *topo;
314107095abfSIvan Voras 	int err;
314207095abfSIvan Voras 
314307095abfSIvan Voras 	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
314407095abfSIvan Voras 
3145b97fa22cSIan Lepore 	topo = sbuf_new_for_sysctl(NULL, NULL, 512, req);
314607095abfSIvan Voras 	if (topo == NULL)
314707095abfSIvan Voras 		return (ENOMEM);
314807095abfSIvan Voras 
314907095abfSIvan Voras 	sbuf_printf(topo, "<groups>\n");
315007095abfSIvan Voras 	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
315107095abfSIvan Voras 	sbuf_printf(topo, "</groups>\n");
315207095abfSIvan Voras 
315307095abfSIvan Voras 	if (err == 0) {
3154b97fa22cSIan Lepore 		err = sbuf_finish(topo);
315507095abfSIvan Voras 	}
315607095abfSIvan Voras 	sbuf_delete(topo);
315707095abfSIvan Voras 	return (err);
315807095abfSIvan Voras }
3159b67cc292SDavid Xu 
316007095abfSIvan Voras #endif
316107095abfSIvan Voras 
3162579895dfSAlexander Motin static int
3163579895dfSAlexander Motin sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
3164579895dfSAlexander Motin {
3165579895dfSAlexander Motin 	int error, new_val, period;
3166579895dfSAlexander Motin 
3167579895dfSAlexander Motin 	period = 1000000 / realstathz;
3168579895dfSAlexander Motin 	new_val = period * sched_slice;
3169579895dfSAlexander Motin 	error = sysctl_handle_int(oidp, &new_val, 0, req);
3170579895dfSAlexander Motin 	if (error != 0 || req->newptr == NULL)
3171579895dfSAlexander Motin 		return (error);
3172579895dfSAlexander Motin 	if (new_val <= 0)
3173579895dfSAlexander Motin 		return (EINVAL);
317437f4e025SAlexander Motin 	sched_slice = imax(1, (new_val + period / 2) / period);
31755e5c3873SJeff Roberson 	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
317637f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
317737f4e025SAlexander Motin 	    realstathz);
3178579895dfSAlexander Motin 	return (0);
3179579895dfSAlexander Motin }
3180579895dfSAlexander Motin 
31817029da5cSPawel Biernacki SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
31827029da5cSPawel Biernacki     "Scheduler");
3183ae7a6b38SJeff Roberson SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
3184e7d50326SJeff Roberson     "Scheduler name");
31857029da5cSPawel Biernacki SYSCTL_PROC(_kern_sched, OID_AUTO, quantum,
31867029da5cSPawel Biernacki     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
31877029da5cSPawel Biernacki     sysctl_kern_quantum, "I",
318837f4e025SAlexander Motin     "Quantum for timeshare threads in microseconds");
3189ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
319037f4e025SAlexander Motin     "Quantum for timeshare threads in stathz ticks");
31911c119e17SAlexander Motin SYSCTL_UINT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
3192ae7a6b38SJeff Roberson     "Interactivity score threshold");
319337f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW,
319437f4e025SAlexander Motin     &preempt_thresh, 0,
319537f4e025SAlexander Motin     "Maximal (lowest) priority for preemption");
319637f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost, 0,
319737f4e025SAlexander Motin     "Assign static kernel priorities to sleeping threads");
319837f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins, 0,
319937f4e025SAlexander Motin     "Number of times idle thread will spin waiting for new work");
320037f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW,
320137f4e025SAlexander Motin     &sched_idlespinthresh, 0,
320237f4e025SAlexander Motin     "Threshold before we will permit idle thread spinning");
32037b8bfa0dSJeff Roberson #ifdef SMP
3204ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
3205ae7a6b38SJeff Roberson     "Number of hz ticks to keep thread affinity for");
3206ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
3207ae7a6b38SJeff Roberson     "Enables the long-term load balancer");
32087fcf154aSJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
32097fcf154aSJeff Roberson     &balance_interval, 0,
3210579895dfSAlexander Motin     "Average period in stathz ticks to run the long-term balancer");
3211ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
3212ae7a6b38SJeff Roberson     "Attempts to steal work from other cores before idling");
321328994a58SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
321437f4e025SAlexander Motin     "Minimum load on remote CPU before we'll steal");
321597e9382dSDon Lewis SYSCTL_INT(_kern_sched, OID_AUTO, trysteal_limit, CTLFLAG_RW, &trysteal_limit,
321697e9382dSDon Lewis     0, "Topological distance limit for stealing threads in sched_switch()");
321797e9382dSDon Lewis SYSCTL_INT(_kern_sched, OID_AUTO, always_steal, CTLFLAG_RW, &always_steal, 0,
321897e9382dSDon Lewis     "Always run the stealer from the idle thread");
321907095abfSIvan Voras SYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
3220c69a1a50SMateusz Guzik     CTLFLAG_MPSAFE | CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
322107095abfSIvan Voras     "XML dump of detected CPU topology");
32227b8bfa0dSJeff Roberson #endif
3223e7d50326SJeff Roberson 
322454b0e65fSJeff Roberson /* ps compat.  All cpu percentages from ULE are weighted. */
3225a5423ea3SJeff Roberson static int ccpu = 0;
3226b05ca429SPawel Biernacki SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0,
3227b05ca429SPawel Biernacki     "Decay factor used for updating %CPU in 4BSD scheduler");
3228