xref: /freebsd/sys/kern/sched_ule.c (revision 4d846d260e2b9a3d4d0a701462568268cbfe7a5b)
135e6168fSJeff Roberson /*-
2*4d846d26SWarner Losh  * SPDX-License-Identifier: BSD-2-Clause
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 /*
22911484ad8SMark Johnston  * tdq - per processor runqs and statistics.  A mutex synchronizes access to
23011484ad8SMark Johnston  * most fields.  Some fields are loaded or modified without the mutex.
23111484ad8SMark Johnston  *
23211484ad8SMark Johnston  * Locking protocols:
23311484ad8SMark Johnston  * (c)  constant after initialization
23411484ad8SMark Johnston  * (f)  flag, set with the tdq lock held, cleared on local CPU
23511484ad8SMark Johnston  * (l)  all accesses are CPU-local
23611484ad8SMark Johnston  * (ls) stores are performed by the local CPU, loads may be lockless
23711484ad8SMark Johnston  * (t)  all accesses are protected by the tdq mutex
23811484ad8SMark Johnston  * (ts) stores are serialized by the tdq mutex, loads may be lockless
23935e6168fSJeff Roberson  */
240ad1e7d28SJulian Elischer struct tdq {
24139f819e2SJim Harris 	/*
24239f819e2SJim Harris 	 * Ordered to improve efficiency of cpu_search() and switch().
24339f819e2SJim Harris 	 * tdq_lock is padded to avoid false sharing with tdq_load and
24439f819e2SJim Harris 	 * tdq_cpu_idle.
24539f819e2SJim Harris 	 */
2464ceaf45dSAttilio Rao 	struct mtx_padalign tdq_lock;	/* run queue lock. */
24711484ad8SMark Johnston 	struct cpu_group *tdq_cg;	/* (c) Pointer to cpu topology. */
24811484ad8SMark Johnston 	struct thread	*tdq_curthread;	/* (t) Current executing thread. */
24911484ad8SMark Johnston 	int		tdq_load;	/* (ts) Aggregate load. */
25011484ad8SMark Johnston 	int		tdq_sysload;	/* (ts) For loadavg, !ITHD load. */
25111484ad8SMark Johnston 	int		tdq_cpu_idle;	/* (ls) cpu_idle() is active. */
25211484ad8SMark Johnston 	int		tdq_transferable; /* (ts) Transferable thread count. */
25311484ad8SMark Johnston 	short		tdq_switchcnt;	/* (l) Switches this tick. */
25411484ad8SMark Johnston 	short		tdq_oldswitchcnt; /* (l) Switches last tick. */
25511484ad8SMark Johnston 	u_char		tdq_lowpri;	/* (ts) Lowest priority thread. */
25611484ad8SMark Johnston 	u_char		tdq_owepreempt;	/* (f) Remote preemption pending. */
25711484ad8SMark Johnston 	u_char		tdq_idx;	/* (t) Current insert index. */
25811484ad8SMark Johnston 	u_char		tdq_ridx;	/* (t) Current removal index. */
25911484ad8SMark Johnston 	int		tdq_id;		/* (c) cpuid. */
26011484ad8SMark Johnston 	struct runq	tdq_realtime;	/* (t) real-time run queue. */
26111484ad8SMark Johnston 	struct runq	tdq_timeshare;	/* (t) timeshare run queue. */
26211484ad8SMark Johnston 	struct runq	tdq_idle;	/* (t) Queue of IDLE threads. */
2638f51ad55SJeff Roberson 	char		tdq_name[TDQ_NAME_LEN];
2648f51ad55SJeff Roberson #ifdef KTR
2658f51ad55SJeff Roberson 	char		tdq_loadname[TDQ_LOADNAME_LEN];
2668f51ad55SJeff Roberson #endif
26711484ad8SMark Johnston };
26835e6168fSJeff Roberson 
2691690c6c1SJeff Roberson /* Idle thread states and config. */
2701690c6c1SJeff Roberson #define	TDQ_RUNNING	1
2711690c6c1SJeff Roberson #define	TDQ_IDLE	2
2727b8bfa0dSJeff Roberson 
27311484ad8SMark Johnston /* Lockless accessors. */
27411484ad8SMark Johnston #define	TDQ_LOAD(tdq)		atomic_load_int(&(tdq)->tdq_load)
27511484ad8SMark Johnston #define	TDQ_TRANSFERABLE(tdq)	atomic_load_int(&(tdq)->tdq_transferable)
27611484ad8SMark Johnston #define	TDQ_SWITCHCNT(tdq)	(atomic_load_short(&(tdq)->tdq_switchcnt) + \
27711484ad8SMark Johnston 				 atomic_load_short(&(tdq)->tdq_oldswitchcnt))
27811484ad8SMark Johnston #define	TDQ_SWITCHCNT_INC(tdq)	(atomic_store_short(&(tdq)->tdq_switchcnt, \
27911484ad8SMark Johnston 				 atomic_load_short(&(tdq)->tdq_switchcnt) + 1))
28011484ad8SMark Johnston 
28180f86c9fSJeff Roberson #ifdef SMP
28261322a0aSAlexander Motin struct cpu_group __read_mostly *cpu_top;		/* CPU topology */
2837b8bfa0dSJeff Roberson 
28462fa74d9SJeff Roberson #define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
28562fa74d9SJeff Roberson #define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
2867b8bfa0dSJeff Roberson 
2877b8bfa0dSJeff Roberson /*
2887b8bfa0dSJeff Roberson  * Run-time tunables.
2897b8bfa0dSJeff Roberson  */
29028994a58SJeff Roberson static int rebalance = 1;
2917fcf154aSJeff Roberson static int balance_interval = 128;	/* Default set in sched_initticks(). */
29261322a0aSAlexander Motin static int __read_mostly affinity;
29361322a0aSAlexander Motin static int __read_mostly steal_idle = 1;
29461322a0aSAlexander Motin static int __read_mostly steal_thresh = 2;
29561322a0aSAlexander Motin static int __read_mostly always_steal = 0;
29661322a0aSAlexander Motin static int __read_mostly trysteal_limit = 2;
29780f86c9fSJeff Roberson 
29835e6168fSJeff Roberson /*
299d2ad694cSJeff Roberson  * One thread queue per processor.
30035e6168fSJeff Roberson  */
30161322a0aSAlexander Motin static struct tdq __read_mostly *balance_tdq;
3027fcf154aSJeff Roberson static int balance_ticks;
303018ff686SJeff Roberson DPCPU_DEFINE_STATIC(struct tdq, tdq);
3042bf95012SAndrew Turner DPCPU_DEFINE_STATIC(uint32_t, randomval);
305dc03363dSJeff Roberson 
306018ff686SJeff Roberson #define	TDQ_SELF()	((struct tdq *)PCPU_GET(sched))
307018ff686SJeff Roberson #define	TDQ_CPU(x)	(DPCPU_ID_PTR((x), tdq))
308018ff686SJeff Roberson #define	TDQ_ID(x)	((x)->tdq_id)
30980f86c9fSJeff Roberson #else	/* !SMP */
310ad1e7d28SJulian Elischer static struct tdq	tdq_cpu;
311dc03363dSJeff Roberson 
31236b36916SJeff Roberson #define	TDQ_ID(x)	(0)
313ad1e7d28SJulian Elischer #define	TDQ_SELF()	(&tdq_cpu)
314ad1e7d28SJulian Elischer #define	TDQ_CPU(x)	(&tdq_cpu)
3150a016a05SJeff Roberson #endif
31635e6168fSJeff Roberson 
317ae7a6b38SJeff Roberson #define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
318ae7a6b38SJeff Roberson #define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
319ae7a6b38SJeff Roberson #define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
3208bb173fbSAlexander Motin #define	TDQ_TRYLOCK(t)		mtx_trylock_spin(TDQ_LOCKPTR((t)))
3218bb173fbSAlexander Motin #define	TDQ_TRYLOCK_FLAGS(t, f)	mtx_trylock_spin_flags(TDQ_LOCKPTR((t)), (f))
322ae7a6b38SJeff Roberson #define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
3234ceaf45dSAttilio Rao #define	TDQ_LOCKPTR(t)		((struct mtx *)(&(t)->tdq_lock))
324ae7a6b38SJeff Roberson 
3250927ff78SMark Johnston static void sched_setpreempt(int);
3268460a577SJohn Birrell static void sched_priority(struct thread *);
32721381d1bSJeff Roberson static void sched_thread_priority(struct thread *, u_char);
3288460a577SJohn Birrell static int sched_interact_score(struct thread *);
3298460a577SJohn Birrell static void sched_interact_update(struct thread *);
3308460a577SJohn Birrell static void sched_interact_fork(struct thread *);
3317295465eSAlexander Motin static void sched_pctcpu_update(struct td_sched *, int);
33235e6168fSJeff Roberson 
3335d7ef00cSJeff Roberson /* Operations on per processor queues */
3349727e637SJeff Roberson static struct thread *tdq_choose(struct tdq *);
335018ff686SJeff Roberson static void tdq_setup(struct tdq *, int i);
3369727e637SJeff Roberson static void tdq_load_add(struct tdq *, struct thread *);
3379727e637SJeff Roberson static void tdq_load_rem(struct tdq *, struct thread *);
3389727e637SJeff Roberson static __inline void tdq_runq_add(struct tdq *, struct thread *, int);
3399727e637SJeff Roberson static __inline void tdq_runq_rem(struct tdq *, struct thread *);
340ff256d9cSJeff Roberson static inline int sched_shouldpreempt(int, int, int);
34111484ad8SMark Johnston static void tdq_print(int cpu);
342e7d50326SJeff Roberson static void runq_print(struct runq *rq);
3436d3f74a1SMark Johnston static int tdq_add(struct tdq *, struct thread *, int);
3445d7ef00cSJeff Roberson #ifdef SMP
3456d3f74a1SMark Johnston static int tdq_move(struct tdq *, struct tdq *);
346ad1e7d28SJulian Elischer static int tdq_idled(struct tdq *);
3476d3f74a1SMark Johnston static void tdq_notify(struct tdq *, int lowpri);
3489727e637SJeff Roberson static struct thread *tdq_steal(struct tdq *, int);
3499727e637SJeff Roberson static struct thread *runq_steal(struct runq *, int);
3509727e637SJeff Roberson static int sched_pickcpu(struct thread *, int);
3517fcf154aSJeff Roberson static void sched_balance(void);
3526d3f74a1SMark Johnston static bool sched_balance_pair(struct tdq *, struct tdq *);
3539727e637SJeff Roberson static inline struct tdq *sched_setcpu(struct thread *, int, int);
354ae7a6b38SJeff Roberson static inline void thread_unblock_switch(struct thread *, struct mtx *);
35507095abfSIvan Voras static int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
35607095abfSIvan Voras static int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
35707095abfSIvan Voras     struct cpu_group *cg, int indent);
3585d7ef00cSJeff Roberson #endif
3595d7ef00cSJeff Roberson 
360e7d50326SJeff Roberson static void sched_setup(void *dummy);
361237fdd78SRobert Watson SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
362e7d50326SJeff Roberson 
363e7d50326SJeff Roberson static void sched_initticks(void *dummy);
364237fdd78SRobert Watson SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
365237fdd78SRobert Watson     NULL);
366e7d50326SJeff Roberson 
367b3e9e682SRyan Stone SDT_PROVIDER_DEFINE(sched);
368b3e9e682SRyan Stone 
369d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
370b3e9e682SRyan Stone     "struct proc *", "uint8_t");
371d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
372b3e9e682SRyan Stone     "struct proc *", "void *");
373d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
374b3e9e682SRyan Stone     "struct proc *", "void *", "int");
375d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
376b3e9e682SRyan Stone     "struct proc *", "uint8_t", "struct thread *");
377d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
378d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
379b3e9e682SRyan Stone     "struct proc *");
380d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , on__cpu);
381d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , remain__cpu);
382d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
383b3e9e682SRyan Stone     "struct proc *");
384b3e9e682SRyan Stone 
3850567b6ccSWarner Losh /*
386ae7a6b38SJeff Roberson  * Print the threads waiting on a run-queue.
387ae7a6b38SJeff Roberson  */
388e7d50326SJeff Roberson static void
389e7d50326SJeff Roberson runq_print(struct runq *rq)
390e7d50326SJeff Roberson {
391e7d50326SJeff Roberson 	struct rqhead *rqh;
3929727e637SJeff Roberson 	struct thread *td;
393e7d50326SJeff Roberson 	int pri;
394e7d50326SJeff Roberson 	int j;
395e7d50326SJeff Roberson 	int i;
396e7d50326SJeff Roberson 
397e7d50326SJeff Roberson 	for (i = 0; i < RQB_LEN; i++) {
398e7d50326SJeff Roberson 		printf("\t\trunq bits %d 0x%zx\n",
399e7d50326SJeff Roberson 		    i, rq->rq_status.rqb_bits[i]);
400e7d50326SJeff Roberson 		for (j = 0; j < RQB_BPW; j++)
401e7d50326SJeff Roberson 			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
402e7d50326SJeff Roberson 				pri = j + (i << RQB_L2BPW);
403e7d50326SJeff Roberson 				rqh = &rq->rq_queues[pri];
4049727e637SJeff Roberson 				TAILQ_FOREACH(td, rqh, td_runq) {
405e7d50326SJeff Roberson 					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
4069727e637SJeff Roberson 					    td, td->td_name, td->td_priority,
4079727e637SJeff Roberson 					    td->td_rqindex, pri);
408e7d50326SJeff Roberson 				}
409e7d50326SJeff Roberson 			}
410e7d50326SJeff Roberson 	}
411e7d50326SJeff Roberson }
412e7d50326SJeff Roberson 
413ae7a6b38SJeff Roberson /*
414ae7a6b38SJeff Roberson  * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
415ae7a6b38SJeff Roberson  */
41611484ad8SMark Johnston static void __unused
417ad1e7d28SJulian Elischer tdq_print(int cpu)
41815dc847eSJeff Roberson {
419ad1e7d28SJulian Elischer 	struct tdq *tdq;
42015dc847eSJeff Roberson 
421ad1e7d28SJulian Elischer 	tdq = TDQ_CPU(cpu);
42215dc847eSJeff Roberson 
423c47f202bSJeff Roberson 	printf("tdq %d:\n", TDQ_ID(tdq));
42462fa74d9SJeff Roberson 	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
42562fa74d9SJeff Roberson 	printf("\tLock name:      %s\n", tdq->tdq_name);
426d2ad694cSJeff Roberson 	printf("\tload:           %d\n", tdq->tdq_load);
4271690c6c1SJeff Roberson 	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
4281690c6c1SJeff Roberson 	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
429e7d50326SJeff Roberson 	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
4303f872f85SJeff Roberson 	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
4311690c6c1SJeff Roberson 	printf("\tload transferable: %d\n", tdq->tdq_transferable);
4321690c6c1SJeff Roberson 	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
433e7d50326SJeff Roberson 	printf("\trealtime runq:\n");
434e7d50326SJeff Roberson 	runq_print(&tdq->tdq_realtime);
435e7d50326SJeff Roberson 	printf("\ttimeshare runq:\n");
436e7d50326SJeff Roberson 	runq_print(&tdq->tdq_timeshare);
437e7d50326SJeff Roberson 	printf("\tidle runq:\n");
438e7d50326SJeff Roberson 	runq_print(&tdq->tdq_idle);
43915dc847eSJeff Roberson }
44015dc847eSJeff Roberson 
441ff256d9cSJeff Roberson static inline int
442ff256d9cSJeff Roberson sched_shouldpreempt(int pri, int cpri, int remote)
443ff256d9cSJeff Roberson {
444ff256d9cSJeff Roberson 	/*
445ff256d9cSJeff Roberson 	 * If the new priority is not better than the current priority there is
446ff256d9cSJeff Roberson 	 * nothing to do.
447ff256d9cSJeff Roberson 	 */
448ff256d9cSJeff Roberson 	if (pri >= cpri)
449ff256d9cSJeff Roberson 		return (0);
450ff256d9cSJeff Roberson 	/*
451ff256d9cSJeff Roberson 	 * Always preempt idle.
452ff256d9cSJeff Roberson 	 */
453ff256d9cSJeff Roberson 	if (cpri >= PRI_MIN_IDLE)
454ff256d9cSJeff Roberson 		return (1);
455ff256d9cSJeff Roberson 	/*
456ff256d9cSJeff Roberson 	 * If preemption is disabled don't preempt others.
457ff256d9cSJeff Roberson 	 */
458ff256d9cSJeff Roberson 	if (preempt_thresh == 0)
459ff256d9cSJeff Roberson 		return (0);
460ff256d9cSJeff Roberson 	/*
461ff256d9cSJeff Roberson 	 * Preempt if we exceed the threshold.
462ff256d9cSJeff Roberson 	 */
463ff256d9cSJeff Roberson 	if (pri <= preempt_thresh)
464ff256d9cSJeff Roberson 		return (1);
465ff256d9cSJeff Roberson 	/*
46612d56c0fSJohn Baldwin 	 * If we're interactive or better and there is non-interactive
46712d56c0fSJohn Baldwin 	 * or worse running preempt only remote processors.
468ff256d9cSJeff Roberson 	 */
46912d56c0fSJohn Baldwin 	if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
470ff256d9cSJeff Roberson 		return (1);
471ff256d9cSJeff Roberson 	return (0);
472ff256d9cSJeff Roberson }
473ff256d9cSJeff Roberson 
474ae7a6b38SJeff Roberson /*
475ae7a6b38SJeff Roberson  * Add a thread to the actual run-queue.  Keeps transferable counts up to
476ae7a6b38SJeff Roberson  * date with what is actually on the run-queue.  Selects the correct
477ae7a6b38SJeff Roberson  * queue position for timeshare threads.
478ae7a6b38SJeff Roberson  */
479155b9987SJeff Roberson static __inline void
4809727e637SJeff Roberson tdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
481155b9987SJeff Roberson {
4829727e637SJeff Roberson 	struct td_sched *ts;
483c143ac21SJeff Roberson 	u_char pri;
484c143ac21SJeff Roberson 
485ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
48661a74c5cSJeff Roberson 	THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
48773daf66fSJeff Roberson 
4889727e637SJeff Roberson 	pri = td->td_priority;
48993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
4909727e637SJeff Roberson 	TD_SET_RUNQ(td);
4919727e637SJeff Roberson 	if (THREAD_CAN_MIGRATE(td)) {
492d2ad694cSJeff Roberson 		tdq->tdq_transferable++;
493ad1e7d28SJulian Elischer 		ts->ts_flags |= TSF_XFERABLE;
49480f86c9fSJeff Roberson 	}
49512d56c0fSJohn Baldwin 	if (pri < PRI_MIN_BATCH) {
496c143ac21SJeff Roberson 		ts->ts_runq = &tdq->tdq_realtime;
49712d56c0fSJohn Baldwin 	} else if (pri <= PRI_MAX_BATCH) {
498c143ac21SJeff Roberson 		ts->ts_runq = &tdq->tdq_timeshare;
49912d56c0fSJohn Baldwin 		KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
500e7d50326SJeff Roberson 			("Invalid priority %d on timeshare runq", pri));
501e7d50326SJeff Roberson 		/*
502e7d50326SJeff Roberson 		 * This queue contains only priorities between MIN and MAX
503ba71333fSMark Johnston 		 * batch.  Use the whole queue to represent these values.
504e7d50326SJeff Roberson 		 */
505c47f202bSJeff Roberson 		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
50616705791SAndriy Gapon 			pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
507e7d50326SJeff Roberson 			pri = (pri + tdq->tdq_idx) % RQ_NQS;
5083f872f85SJeff Roberson 			/*
5093f872f85SJeff Roberson 			 * This effectively shortens the queue by one so we
5103f872f85SJeff Roberson 			 * can have a one slot difference between idx and
5113f872f85SJeff Roberson 			 * ridx while we wait for threads to drain.
5123f872f85SJeff Roberson 			 */
5133f872f85SJeff Roberson 			if (tdq->tdq_ridx != tdq->tdq_idx &&
5143f872f85SJeff Roberson 			    pri == tdq->tdq_ridx)
5154499aff6SJeff Roberson 				pri = (unsigned char)(pri - 1) % RQ_NQS;
516e7d50326SJeff Roberson 		} else
5173f872f85SJeff Roberson 			pri = tdq->tdq_ridx;
5189727e637SJeff Roberson 		runq_add_pri(ts->ts_runq, td, pri, flags);
519c143ac21SJeff Roberson 		return;
520e7d50326SJeff Roberson 	} else
52173daf66fSJeff Roberson 		ts->ts_runq = &tdq->tdq_idle;
5229727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
52373daf66fSJeff Roberson }
52473daf66fSJeff Roberson 
52573daf66fSJeff Roberson /*
526ae7a6b38SJeff Roberson  * Remove a thread from a run-queue.  This typically happens when a thread
527ae7a6b38SJeff Roberson  * is selected to run.  Running threads are not on the queue and the
528ae7a6b38SJeff Roberson  * transferable count does not reflect them.
529ae7a6b38SJeff Roberson  */
530155b9987SJeff Roberson static __inline void
5319727e637SJeff Roberson tdq_runq_rem(struct tdq *tdq, struct thread *td)
532155b9987SJeff Roberson {
5339727e637SJeff Roberson 	struct td_sched *ts;
5349727e637SJeff Roberson 
53593ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
536ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
53761a74c5cSJeff Roberson 	THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
538ae7a6b38SJeff Roberson 	KASSERT(ts->ts_runq != NULL,
5399727e637SJeff Roberson 	    ("tdq_runq_remove: thread %p null ts_runq", td));
540ad1e7d28SJulian Elischer 	if (ts->ts_flags & TSF_XFERABLE) {
541d2ad694cSJeff Roberson 		tdq->tdq_transferable--;
542ad1e7d28SJulian Elischer 		ts->ts_flags &= ~TSF_XFERABLE;
54380f86c9fSJeff Roberson 	}
5443f872f85SJeff Roberson 	if (ts->ts_runq == &tdq->tdq_timeshare) {
5453f872f85SJeff Roberson 		if (tdq->tdq_idx != tdq->tdq_ridx)
5469727e637SJeff Roberson 			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
547e7d50326SJeff Roberson 		else
5489727e637SJeff Roberson 			runq_remove_idx(ts->ts_runq, td, NULL);
5493f872f85SJeff Roberson 	} else
5509727e637SJeff Roberson 		runq_remove(ts->ts_runq, td);
551155b9987SJeff Roberson }
552155b9987SJeff Roberson 
553ae7a6b38SJeff Roberson /*
554ae7a6b38SJeff Roberson  * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
555ae7a6b38SJeff Roberson  * for this thread to the referenced thread queue.
556ae7a6b38SJeff Roberson  */
557a8949de2SJeff Roberson static void
5589727e637SJeff Roberson tdq_load_add(struct tdq *tdq, struct thread *td)
5595d7ef00cSJeff Roberson {
560ae7a6b38SJeff Roberson 
561ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
56261a74c5cSJeff Roberson 	THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
56303d17db7SJeff Roberson 
564d2ad694cSJeff Roberson 	tdq->tdq_load++;
5651b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
566d2ad694cSJeff Roberson 		tdq->tdq_sysload++;
5678f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
568d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
5695d7ef00cSJeff Roberson }
57015dc847eSJeff Roberson 
571ae7a6b38SJeff Roberson /*
572ae7a6b38SJeff Roberson  * Remove the load from a thread that is transitioning to a sleep state or
573ae7a6b38SJeff Roberson  * exiting.
574ae7a6b38SJeff Roberson  */
575a8949de2SJeff Roberson static void
5769727e637SJeff Roberson tdq_load_rem(struct tdq *tdq, struct thread *td)
5775d7ef00cSJeff Roberson {
578ae7a6b38SJeff Roberson 
579ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
58061a74c5cSJeff Roberson 	THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
581ae7a6b38SJeff Roberson 	KASSERT(tdq->tdq_load != 0,
582c47f202bSJeff Roberson 	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
58303d17db7SJeff Roberson 
584d2ad694cSJeff Roberson 	tdq->tdq_load--;
5851b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
58603d17db7SJeff Roberson 		tdq->tdq_sysload--;
5878f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
588d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
58915dc847eSJeff Roberson }
59015dc847eSJeff Roberson 
591356500a3SJeff Roberson /*
5925e5c3873SJeff Roberson  * Bound timeshare latency by decreasing slice size as load increases.  We
5935e5c3873SJeff Roberson  * consider the maximum latency as the sum of the threads waiting to run
5945e5c3873SJeff Roberson  * aside from curthread and target no more than sched_slice latency but
5955e5c3873SJeff Roberson  * no less than sched_slice_min runtime.
5965e5c3873SJeff Roberson  */
5975e5c3873SJeff Roberson static inline int
5985e5c3873SJeff Roberson tdq_slice(struct tdq *tdq)
5995e5c3873SJeff Roberson {
6005e5c3873SJeff Roberson 	int load;
6015e5c3873SJeff Roberson 
6025e5c3873SJeff Roberson 	/*
6035e5c3873SJeff Roberson 	 * It is safe to use sys_load here because this is called from
6045e5c3873SJeff Roberson 	 * contexts where timeshare threads are running and so there
6055e5c3873SJeff Roberson 	 * cannot be higher priority load in the system.
6065e5c3873SJeff Roberson 	 */
6075e5c3873SJeff Roberson 	load = tdq->tdq_sysload - 1;
6085e5c3873SJeff Roberson 	if (load >= SCHED_SLICE_MIN_DIVISOR)
6095e5c3873SJeff Roberson 		return (sched_slice_min);
6105e5c3873SJeff Roberson 	if (load <= 1)
6115e5c3873SJeff Roberson 		return (sched_slice);
6125e5c3873SJeff Roberson 	return (sched_slice / load);
6135e5c3873SJeff Roberson }
6145e5c3873SJeff Roberson 
6155e5c3873SJeff Roberson /*
61662fa74d9SJeff Roberson  * Set lowpri to its exact value by searching the run-queue and
61762fa74d9SJeff Roberson  * evaluating curthread.  curthread may be passed as an optimization.
618356500a3SJeff Roberson  */
61922bf7d9aSJeff Roberson static void
62062fa74d9SJeff Roberson tdq_setlowpri(struct tdq *tdq, struct thread *ctd)
62162fa74d9SJeff Roberson {
62262fa74d9SJeff Roberson 	struct thread *td;
62362fa74d9SJeff Roberson 
62462fa74d9SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
62562fa74d9SJeff Roberson 	if (ctd == NULL)
62611484ad8SMark Johnston 		ctd = tdq->tdq_curthread;
6279727e637SJeff Roberson 	td = tdq_choose(tdq);
6289727e637SJeff Roberson 	if (td == NULL || td->td_priority > ctd->td_priority)
62962fa74d9SJeff Roberson 		tdq->tdq_lowpri = ctd->td_priority;
63062fa74d9SJeff Roberson 	else
63162fa74d9SJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
63262fa74d9SJeff Roberson }
63362fa74d9SJeff Roberson 
63462fa74d9SJeff Roberson #ifdef SMP
6359129dd59SPedro F. Giffuni /*
6369129dd59SPedro F. Giffuni  * We need some randomness. Implement a classic Linear Congruential
6379129dd59SPedro F. Giffuni  * Generator X_{n+1}=(aX_n+c) mod m. These values are optimized for
6389129dd59SPedro F. Giffuni  * m = 2^32, a = 69069 and c = 5. We only return the upper 16 bits
6399129dd59SPedro F. Giffuni  * of the random state (in the low bits of our answer) to keep
6409129dd59SPedro F. Giffuni  * the maximum randomness.
6419129dd59SPedro F. Giffuni  */
6429129dd59SPedro F. Giffuni static uint32_t
6439129dd59SPedro F. Giffuni sched_random(void)
6449129dd59SPedro F. Giffuni {
6459129dd59SPedro F. Giffuni 	uint32_t *rndptr;
6469129dd59SPedro F. Giffuni 
6479129dd59SPedro F. Giffuni 	rndptr = DPCPU_PTR(randomval);
6489129dd59SPedro F. Giffuni 	*rndptr = *rndptr * 69069 + 5;
6499129dd59SPedro F. Giffuni 
6509129dd59SPedro F. Giffuni 	return (*rndptr >> 16);
6519129dd59SPedro F. Giffuni }
6529129dd59SPedro F. Giffuni 
65362fa74d9SJeff Roberson struct cpu_search {
654e745d729SAlexander Motin 	cpuset_t *cs_mask;	/* The mask of allowed CPUs to choose from. */
655e745d729SAlexander Motin 	int	cs_prefer;	/* Prefer this CPU and groups including it. */
656e745d729SAlexander Motin 	int	cs_running;	/* The thread is now running at cs_prefer. */
65736acfc65SAlexander Motin 	int	cs_pri;		/* Min priority for low. */
65808063e9fSAlexander Motin 	int	cs_load;	/* Max load for low, min load for high. */
65908063e9fSAlexander Motin 	int	cs_trans;	/* Min transferable load for high. */
660aefe0a8cSAlexander Motin };
661aefe0a8cSAlexander Motin 
662aefe0a8cSAlexander Motin struct cpu_search_res {
66308063e9fSAlexander Motin 	int	csr_cpu;	/* The best CPU found. */
66408063e9fSAlexander Motin 	int	csr_load;	/* The load of cs_cpu. */
66562fa74d9SJeff Roberson };
66662fa74d9SJeff Roberson 
66762fa74d9SJeff Roberson /*
668aefe0a8cSAlexander Motin  * Search the tree of cpu_groups for the lowest or highest loaded CPU.
669aefe0a8cSAlexander Motin  * These routines actually compare the load on all paths through the tree
670aefe0a8cSAlexander Motin  * and find the least loaded cpu on the least loaded path, which may differ
671aefe0a8cSAlexander Motin  * from the least loaded cpu in the system.  This balances work among caches
672aefe0a8cSAlexander Motin  * and buses.
67362fa74d9SJeff Roberson  */
674aefe0a8cSAlexander Motin static int
675aefe0a8cSAlexander Motin cpu_search_lowest(const struct cpu_group *cg, const struct cpu_search *s,
676aefe0a8cSAlexander Motin     struct cpu_search_res *r)
67762fa74d9SJeff Roberson {
678aefe0a8cSAlexander Motin 	struct cpu_search_res lr;
67936acfc65SAlexander Motin 	struct tdq *tdq;
680e745d729SAlexander Motin 	int c, bload, l, load, p, total;
68162fa74d9SJeff Roberson 
68236acfc65SAlexander Motin 	total = 0;
683aefe0a8cSAlexander Motin 	bload = INT_MAX;
68408063e9fSAlexander Motin 	r->csr_cpu = -1;
68536acfc65SAlexander Motin 
686aefe0a8cSAlexander Motin 	/* Loop through children CPU groups if there are any. */
687aefe0a8cSAlexander Motin 	if (cg->cg_children > 0) {
688aefe0a8cSAlexander Motin 		for (c = cg->cg_children - 1; c >= 0; c--) {
689aefe0a8cSAlexander Motin 			load = cpu_search_lowest(&cg->cg_child[c], s, &lr);
69036acfc65SAlexander Motin 			total += load;
691e745d729SAlexander Motin 
692e745d729SAlexander Motin 			/*
693e745d729SAlexander Motin 			 * When balancing do not prefer SMT groups with load >1.
694e745d729SAlexander Motin 			 * It allows round-robin between SMT groups with equal
695e745d729SAlexander Motin 			 * load within parent group for more fair scheduling.
696e745d729SAlexander Motin 			 */
697e745d729SAlexander Motin 			if (__predict_false(s->cs_running) &&
698e745d729SAlexander Motin 			    (cg->cg_child[c].cg_flags & CG_FLAG_THREAD) &&
699e745d729SAlexander Motin 			    load >= 128 && (load & 128) != 0)
700e745d729SAlexander Motin 				load += 128;
701e745d729SAlexander Motin 
70208063e9fSAlexander Motin 			if (lr.csr_cpu >= 0 && (load < bload ||
70308063e9fSAlexander Motin 			    (load == bload && lr.csr_load < r->csr_load))) {
704aefe0a8cSAlexander Motin 				bload = load;
70508063e9fSAlexander Motin 				r->csr_cpu = lr.csr_cpu;
70608063e9fSAlexander Motin 				r->csr_load = lr.csr_load;
70736acfc65SAlexander Motin 			}
70836acfc65SAlexander Motin 		}
70962fa74d9SJeff Roberson 		return (total);
71062fa74d9SJeff Roberson 	}
71162fa74d9SJeff Roberson 
712aefe0a8cSAlexander Motin 	/* Loop through children CPUs otherwise. */
713aefe0a8cSAlexander Motin 	for (c = cg->cg_last; c >= cg->cg_first; c--) {
714aefe0a8cSAlexander Motin 		if (!CPU_ISSET(c, &cg->cg_mask))
715aefe0a8cSAlexander Motin 			continue;
716aefe0a8cSAlexander Motin 		tdq = TDQ_CPU(c);
71711484ad8SMark Johnston 		l = TDQ_LOAD(tdq);
718e745d729SAlexander Motin 		if (c == s->cs_prefer) {
719e745d729SAlexander Motin 			if (__predict_false(s->cs_running))
720e745d729SAlexander Motin 				l--;
721e745d729SAlexander Motin 			p = 128;
722e745d729SAlexander Motin 		} else
723e745d729SAlexander Motin 			p = 0;
724aefe0a8cSAlexander Motin 		load = l * 256;
725e745d729SAlexander Motin 		total += load - p;
726e745d729SAlexander Motin 
727e745d729SAlexander Motin 		/*
728e745d729SAlexander Motin 		 * Check this CPU is acceptable.
729e745d729SAlexander Motin 		 * If the threads is already on the CPU, don't look on the TDQ
730e745d729SAlexander Motin 		 * priority, since it can be the priority of the thread itself.
731e745d729SAlexander Motin 		 */
73211484ad8SMark Johnston 		if (l > s->cs_load ||
73311484ad8SMark Johnston 		    (atomic_load_char(&tdq->tdq_lowpri) <= s->cs_pri &&
734e745d729SAlexander Motin 		     (!s->cs_running || c != s->cs_prefer)) ||
735aefe0a8cSAlexander Motin 		    !CPU_ISSET(c, s->cs_mask))
736aefe0a8cSAlexander Motin 			continue;
737e745d729SAlexander Motin 
738e745d729SAlexander Motin 		/*
739e745d729SAlexander Motin 		 * When balancing do not prefer CPUs with load > 1.
740e745d729SAlexander Motin 		 * It allows round-robin between CPUs with equal load
741e745d729SAlexander Motin 		 * within the CPU group for more fair scheduling.
742e745d729SAlexander Motin 		 */
743e745d729SAlexander Motin 		if (__predict_false(s->cs_running) && l > 0)
744e745d729SAlexander Motin 			p = 0;
745e745d729SAlexander Motin 
746aefe0a8cSAlexander Motin 		load -= sched_random() % 128;
747e745d729SAlexander Motin 		if (bload > load - p) {
748e745d729SAlexander Motin 			bload = load - p;
74908063e9fSAlexander Motin 			r->csr_cpu = c;
75008063e9fSAlexander Motin 			r->csr_load = load;
751aefe0a8cSAlexander Motin 		}
752aefe0a8cSAlexander Motin 	}
753aefe0a8cSAlexander Motin 	return (total);
75462fa74d9SJeff Roberson }
75562fa74d9SJeff Roberson 
756aefe0a8cSAlexander Motin static int
757aefe0a8cSAlexander Motin cpu_search_highest(const struct cpu_group *cg, const struct cpu_search *s,
758aefe0a8cSAlexander Motin     struct cpu_search_res *r)
75962fa74d9SJeff Roberson {
760aefe0a8cSAlexander Motin 	struct cpu_search_res lr;
761aefe0a8cSAlexander Motin 	struct tdq *tdq;
762aefe0a8cSAlexander Motin 	int c, bload, l, load, total;
763aefe0a8cSAlexander Motin 
764aefe0a8cSAlexander Motin 	total = 0;
765aefe0a8cSAlexander Motin 	bload = INT_MIN;
76608063e9fSAlexander Motin 	r->csr_cpu = -1;
767aefe0a8cSAlexander Motin 
768aefe0a8cSAlexander Motin 	/* Loop through children CPU groups if there are any. */
769aefe0a8cSAlexander Motin 	if (cg->cg_children > 0) {
770aefe0a8cSAlexander Motin 		for (c = cg->cg_children - 1; c >= 0; c--) {
771aefe0a8cSAlexander Motin 			load = cpu_search_highest(&cg->cg_child[c], s, &lr);
772aefe0a8cSAlexander Motin 			total += load;
77308063e9fSAlexander Motin 			if (lr.csr_cpu >= 0 && (load > bload ||
77408063e9fSAlexander Motin 			    (load == bload && lr.csr_load > r->csr_load))) {
775aefe0a8cSAlexander Motin 				bload = load;
77608063e9fSAlexander Motin 				r->csr_cpu = lr.csr_cpu;
77708063e9fSAlexander Motin 				r->csr_load = lr.csr_load;
778aefe0a8cSAlexander Motin 			}
779aefe0a8cSAlexander Motin 		}
780aefe0a8cSAlexander Motin 		return (total);
78162fa74d9SJeff Roberson 	}
78262fa74d9SJeff Roberson 
783aefe0a8cSAlexander Motin 	/* Loop through children CPUs otherwise. */
784aefe0a8cSAlexander Motin 	for (c = cg->cg_last; c >= cg->cg_first; c--) {
785aefe0a8cSAlexander Motin 		if (!CPU_ISSET(c, &cg->cg_mask))
786aefe0a8cSAlexander Motin 			continue;
787aefe0a8cSAlexander Motin 		tdq = TDQ_CPU(c);
78811484ad8SMark Johnston 		l = TDQ_LOAD(tdq);
789aefe0a8cSAlexander Motin 		load = l * 256;
790aefe0a8cSAlexander Motin 		total += load;
791e745d729SAlexander Motin 
792e745d729SAlexander Motin 		/*
793e745d729SAlexander Motin 		 * Check this CPU is acceptable.
794e745d729SAlexander Motin 		 */
79511484ad8SMark Johnston 		if (l < s->cs_load || TDQ_TRANSFERABLE(tdq) < s->cs_trans ||
796aefe0a8cSAlexander Motin 		    !CPU_ISSET(c, s->cs_mask))
797aefe0a8cSAlexander Motin 			continue;
798e745d729SAlexander Motin 
799ca34553bSAlexander Motin 		load -= sched_random() % 256;
800aefe0a8cSAlexander Motin 		if (load > bload) {
801aefe0a8cSAlexander Motin 			bload = load;
80208063e9fSAlexander Motin 			r->csr_cpu = c;
803aefe0a8cSAlexander Motin 		}
804aefe0a8cSAlexander Motin 	}
80508063e9fSAlexander Motin 	r->csr_load = bload;
806aefe0a8cSAlexander Motin 	return (total);
80762fa74d9SJeff Roberson }
80862fa74d9SJeff Roberson 
80962fa74d9SJeff Roberson /*
81062fa74d9SJeff Roberson  * Find the cpu with the least load via the least loaded path that has a
81162fa74d9SJeff Roberson  * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
81262fa74d9SJeff Roberson  * acceptable.
81362fa74d9SJeff Roberson  */
81462fa74d9SJeff Roberson static inline int
815aefe0a8cSAlexander Motin sched_lowest(const struct cpu_group *cg, cpuset_t *mask, int pri, int maxload,
816e745d729SAlexander Motin     int prefer, int running)
81762fa74d9SJeff Roberson {
818aefe0a8cSAlexander Motin 	struct cpu_search s;
819aefe0a8cSAlexander Motin 	struct cpu_search_res r;
82062fa74d9SJeff Roberson 
821aefe0a8cSAlexander Motin 	s.cs_prefer = prefer;
822e745d729SAlexander Motin 	s.cs_running = running;
823aefe0a8cSAlexander Motin 	s.cs_mask = mask;
824aefe0a8cSAlexander Motin 	s.cs_pri = pri;
82508063e9fSAlexander Motin 	s.cs_load = maxload;
826aefe0a8cSAlexander Motin 	cpu_search_lowest(cg, &s, &r);
82708063e9fSAlexander Motin 	return (r.csr_cpu);
82862fa74d9SJeff Roberson }
82962fa74d9SJeff Roberson 
83062fa74d9SJeff Roberson /*
83162fa74d9SJeff Roberson  * Find the cpu with the highest load via the highest loaded path.
83262fa74d9SJeff Roberson  */
83362fa74d9SJeff Roberson static inline int
83408063e9fSAlexander Motin sched_highest(const struct cpu_group *cg, cpuset_t *mask, int minload,
83508063e9fSAlexander Motin     int mintrans)
83662fa74d9SJeff Roberson {
837aefe0a8cSAlexander Motin 	struct cpu_search s;
838aefe0a8cSAlexander Motin 	struct cpu_search_res r;
83962fa74d9SJeff Roberson 
840aefe0a8cSAlexander Motin 	s.cs_mask = mask;
84108063e9fSAlexander Motin 	s.cs_load = minload;
84208063e9fSAlexander Motin 	s.cs_trans = mintrans;
843aefe0a8cSAlexander Motin 	cpu_search_highest(cg, &s, &r);
84408063e9fSAlexander Motin 	return (r.csr_cpu);
84562fa74d9SJeff Roberson }
84662fa74d9SJeff Roberson 
84762fa74d9SJeff Roberson static void
84862fa74d9SJeff Roberson sched_balance_group(struct cpu_group *cg)
84962fa74d9SJeff Roberson {
850018ff686SJeff Roberson 	struct tdq *tdq;
851e745d729SAlexander Motin 	struct thread *td;
85236acfc65SAlexander Motin 	cpuset_t hmask, lmask;
85336acfc65SAlexander Motin 	int high, low, anylow;
85462fa74d9SJeff Roberson 
85536acfc65SAlexander Motin 	CPU_FILL(&hmask);
85662fa74d9SJeff Roberson 	for (;;) {
85708063e9fSAlexander Motin 		high = sched_highest(cg, &hmask, 1, 0);
85836acfc65SAlexander Motin 		/* Stop if there is no more CPU with transferrable threads. */
85936acfc65SAlexander Motin 		if (high == -1)
86062fa74d9SJeff Roberson 			break;
86136acfc65SAlexander Motin 		CPU_CLR(high, &hmask);
86236acfc65SAlexander Motin 		CPU_COPY(&hmask, &lmask);
86336acfc65SAlexander Motin 		/* Stop if there is no more CPU left for low. */
86436acfc65SAlexander Motin 		if (CPU_EMPTY(&lmask))
86562fa74d9SJeff Roberson 			break;
866018ff686SJeff Roberson 		tdq = TDQ_CPU(high);
86711484ad8SMark Johnston 		if (TDQ_LOAD(tdq) == 1) {
868e745d729SAlexander Motin 			/*
869e745d729SAlexander Motin 			 * There is only one running thread.  We can't move
870e745d729SAlexander Motin 			 * it from here, so tell it to pick new CPU by itself.
871e745d729SAlexander Motin 			 */
872e745d729SAlexander Motin 			TDQ_LOCK(tdq);
87311484ad8SMark Johnston 			td = tdq->tdq_curthread;
874bd980ca8SMark Johnston 			if (td->td_lock == TDQ_LOCKPTR(tdq) &&
875bd980ca8SMark Johnston 			    (td->td_flags & TDF_IDLETD) == 0 &&
876e745d729SAlexander Motin 			    THREAD_CAN_MIGRATE(td)) {
877c6d31b83SKonstantin Belousov 				td->td_flags |= TDF_PICKCPU;
878c6d31b83SKonstantin Belousov 				ast_sched_locked(td, TDA_SCHED);
879e745d729SAlexander Motin 				if (high != curcpu)
880e745d729SAlexander Motin 					ipi_cpu(high, IPI_AST);
881e745d729SAlexander Motin 			}
882e745d729SAlexander Motin 			TDQ_UNLOCK(tdq);
883e745d729SAlexander Motin 			break;
884e745d729SAlexander Motin 		}
885e745d729SAlexander Motin 		anylow = 1;
88636acfc65SAlexander Motin nextlow:
88711484ad8SMark Johnston 		if (TDQ_TRANSFERABLE(tdq) == 0)
888e745d729SAlexander Motin 			continue;
88911484ad8SMark Johnston 		low = sched_lowest(cg, &lmask, -1, TDQ_LOAD(tdq) - 1, high, 1);
89036acfc65SAlexander Motin 		/* Stop if we looked well and found no less loaded CPU. */
89136acfc65SAlexander Motin 		if (anylow && low == -1)
89236acfc65SAlexander Motin 			break;
89336acfc65SAlexander Motin 		/* Go to next high if we found no less loaded CPU. */
89436acfc65SAlexander Motin 		if (low == -1)
89536acfc65SAlexander Motin 			continue;
89636acfc65SAlexander Motin 		/* Transfer thread from high to low. */
897018ff686SJeff Roberson 		if (sched_balance_pair(tdq, TDQ_CPU(low))) {
89836acfc65SAlexander Motin 			/* CPU that got thread can no longer be a donor. */
89936acfc65SAlexander Motin 			CPU_CLR(low, &hmask);
90036acfc65SAlexander Motin 		} else {
90162fa74d9SJeff Roberson 			/*
90236acfc65SAlexander Motin 			 * If failed, then there is no threads on high
90336acfc65SAlexander Motin 			 * that can run on this low. Drop low from low
90436acfc65SAlexander Motin 			 * mask and look for different one.
90562fa74d9SJeff Roberson 			 */
90636acfc65SAlexander Motin 			CPU_CLR(low, &lmask);
90736acfc65SAlexander Motin 			anylow = 0;
90836acfc65SAlexander Motin 			goto nextlow;
90962fa74d9SJeff Roberson 		}
91036acfc65SAlexander Motin 	}
91162fa74d9SJeff Roberson }
91262fa74d9SJeff Roberson 
91362fa74d9SJeff Roberson static void
91462375ca8SEd Schouten sched_balance(void)
915356500a3SJeff Roberson {
9167fcf154aSJeff Roberson 	struct tdq *tdq;
917356500a3SJeff Roberson 
9180567b6ccSWarner Losh 	balance_ticks = max(balance_interval / 2, 1) +
919b250ad34SWarner Losh 	    (sched_random() % balance_interval);
9207fcf154aSJeff Roberson 	tdq = TDQ_SELF();
9217fcf154aSJeff Roberson 	TDQ_UNLOCK(tdq);
92262fa74d9SJeff Roberson 	sched_balance_group(cpu_top);
9237fcf154aSJeff Roberson 	TDQ_LOCK(tdq);
924cac77d04SJeff Roberson }
92586f8ae96SJeff Roberson 
926ae7a6b38SJeff Roberson /*
927ae7a6b38SJeff Roberson  * Lock two thread queues using their address to maintain lock order.
928ae7a6b38SJeff Roberson  */
929ae7a6b38SJeff Roberson static void
930ae7a6b38SJeff Roberson tdq_lock_pair(struct tdq *one, struct tdq *two)
931ae7a6b38SJeff Roberson {
932ae7a6b38SJeff Roberson 	if (one < two) {
933ae7a6b38SJeff Roberson 		TDQ_LOCK(one);
934ae7a6b38SJeff Roberson 		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
935ae7a6b38SJeff Roberson 	} else {
936ae7a6b38SJeff Roberson 		TDQ_LOCK(two);
937ae7a6b38SJeff Roberson 		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
938ae7a6b38SJeff Roberson 	}
939ae7a6b38SJeff Roberson }
940ae7a6b38SJeff Roberson 
941ae7a6b38SJeff Roberson /*
9427fcf154aSJeff Roberson  * Unlock two thread queues.  Order is not important here.
9437fcf154aSJeff Roberson  */
9447fcf154aSJeff Roberson static void
9457fcf154aSJeff Roberson tdq_unlock_pair(struct tdq *one, struct tdq *two)
9467fcf154aSJeff Roberson {
9477fcf154aSJeff Roberson 	TDQ_UNLOCK(one);
9487fcf154aSJeff Roberson 	TDQ_UNLOCK(two);
9497fcf154aSJeff Roberson }
9507fcf154aSJeff Roberson 
9517fcf154aSJeff Roberson /*
9526d3f74a1SMark Johnston  * Transfer load between two imbalanced thread queues.  Returns true if a thread
9536d3f74a1SMark Johnston  * was moved between the queues, and false otherwise.
954ae7a6b38SJeff Roberson  */
9556d3f74a1SMark Johnston static bool
956ad1e7d28SJulian Elischer sched_balance_pair(struct tdq *high, struct tdq *low)
957cac77d04SJeff Roberson {
9586d3f74a1SMark Johnston 	int cpu, lowpri;
9596d3f74a1SMark Johnston 	bool ret;
960cac77d04SJeff Roberson 
9616d3f74a1SMark Johnston 	ret = false;
962ae7a6b38SJeff Roberson 	tdq_lock_pair(high, low);
9636d3f74a1SMark Johnston 
964155b9987SJeff Roberson 	/*
96597e9382dSDon Lewis 	 * Transfer a thread from high to low.
966155b9987SJeff Roberson 	 */
9676d3f74a1SMark Johnston 	if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load) {
9686d3f74a1SMark Johnston 		lowpri = tdq_move(high, low);
9696d3f74a1SMark Johnston 		if (lowpri != -1) {
970a5423ea3SJeff Roberson 			/*
9710927ff78SMark Johnston 			 * In case the target isn't the current CPU notify it of
9726d3f74a1SMark Johnston 			 * the new load, possibly sending an IPI to force it to
9730927ff78SMark Johnston 			 * reschedule.  Otherwise maybe schedule a preemption.
974a5423ea3SJeff Roberson 			 */
975880bf8b9SMarius Strobl 			cpu = TDQ_ID(low);
976880bf8b9SMarius Strobl 			if (cpu != PCPU_GET(cpuid))
9776d3f74a1SMark Johnston 				tdq_notify(low, lowpri);
9780927ff78SMark Johnston 			else
9790927ff78SMark Johnston 				sched_setpreempt(low->tdq_lowpri);
9806d3f74a1SMark Johnston 			ret = true;
9816d3f74a1SMark Johnston 		}
982ae7a6b38SJeff Roberson 	}
9837fcf154aSJeff Roberson 	tdq_unlock_pair(high, low);
9846d3f74a1SMark Johnston 	return (ret);
985356500a3SJeff Roberson }
986356500a3SJeff Roberson 
987ae7a6b38SJeff Roberson /*
9886d3f74a1SMark Johnston  * Move a thread from one thread queue to another.  Returns -1 if the source
9896d3f74a1SMark Johnston  * queue was empty, else returns the maximum priority of all threads in
9906d3f74a1SMark Johnston  * the destination queue prior to the addition of the new thread.  In the latter
9916d3f74a1SMark Johnston  * case, this priority can be used to determine whether an IPI needs to be
9926d3f74a1SMark Johnston  * delivered.
993ae7a6b38SJeff Roberson  */
9946d3f74a1SMark Johnston static int
995ae7a6b38SJeff Roberson tdq_move(struct tdq *from, struct tdq *to)
996356500a3SJeff Roberson {
997ae7a6b38SJeff Roberson 	struct thread *td;
998ae7a6b38SJeff Roberson 	int cpu;
999356500a3SJeff Roberson 
10007fcf154aSJeff Roberson 	TDQ_LOCK_ASSERT(from, MA_OWNED);
10017fcf154aSJeff Roberson 	TDQ_LOCK_ASSERT(to, MA_OWNED);
10027fcf154aSJeff Roberson 
1003ae7a6b38SJeff Roberson 	cpu = TDQ_ID(to);
100435dd6d6cSMark Johnston 	td = tdq_steal(from, cpu);
10059727e637SJeff Roberson 	if (td == NULL)
10066d3f74a1SMark Johnston 		return (-1);
100761a74c5cSJeff Roberson 
1008ae7a6b38SJeff Roberson 	/*
100961a74c5cSJeff Roberson 	 * Although the run queue is locked the thread may be
101061a74c5cSJeff Roberson 	 * blocked.  We can not set the lock until it is unblocked.
1011ae7a6b38SJeff Roberson 	 */
101261a74c5cSJeff Roberson 	thread_lock_block_wait(td);
1013ae7a6b38SJeff Roberson 	sched_rem(td);
101461a74c5cSJeff Roberson 	THREAD_LOCKPTR_ASSERT(td, TDQ_LOCKPTR(from));
1015ae7a6b38SJeff Roberson 	td->td_lock = TDQ_LOCKPTR(to);
101661a74c5cSJeff Roberson 	td_get_sched(td)->ts_cpu = cpu;
10176d3f74a1SMark Johnston 	return (tdq_add(to, td, SRQ_YIELDING));
1018356500a3SJeff Roberson }
101922bf7d9aSJeff Roberson 
1020ae7a6b38SJeff Roberson /*
1021ae7a6b38SJeff Roberson  * This tdq has idled.  Try to steal a thread from another cpu and switch
1022ae7a6b38SJeff Roberson  * to it.
1023ae7a6b38SJeff Roberson  */
102480f86c9fSJeff Roberson static int
1025ad1e7d28SJulian Elischer tdq_idled(struct tdq *tdq)
102622bf7d9aSJeff Roberson {
10272668bb2aSAlexander Motin 	struct cpu_group *cg, *parent;
1028ad1e7d28SJulian Elischer 	struct tdq *steal;
1029c76ee827SJeff Roberson 	cpuset_t mask;
10302668bb2aSAlexander Motin 	int cpu, switchcnt, goup;
103180f86c9fSJeff Roberson 
103297e9382dSDon Lewis 	if (smp_started == 0 || steal_idle == 0 || tdq->tdq_cg == NULL)
103388f530ccSJeff Roberson 		return (1);
1034c76ee827SJeff Roberson 	CPU_FILL(&mask);
1035c76ee827SJeff Roberson 	CPU_CLR(PCPU_GET(cpuid), &mask);
103697e9382dSDon Lewis restart:
103711484ad8SMark Johnston 	switchcnt = TDQ_SWITCHCNT(tdq);
10382668bb2aSAlexander Motin 	for (cg = tdq->tdq_cg, goup = 0; ; ) {
103908063e9fSAlexander Motin 		cpu = sched_highest(cg, &mask, steal_thresh, 1);
104097e9382dSDon Lewis 		/*
104197e9382dSDon Lewis 		 * We were assigned a thread but not preempted.  Returning
104297e9382dSDon Lewis 		 * 0 here will cause our caller to switch to it.
104397e9382dSDon Lewis 		 */
104411484ad8SMark Johnston 		if (TDQ_LOAD(tdq))
104597e9382dSDon Lewis 			return (0);
10462668bb2aSAlexander Motin 
10472668bb2aSAlexander Motin 		/*
10482668bb2aSAlexander Motin 		 * We found no CPU to steal from in this group.  Escalate to
10492668bb2aSAlexander Motin 		 * the parent and repeat.  But if parent has only two children
10502668bb2aSAlexander Motin 		 * groups we can avoid searching this group again by searching
10512668bb2aSAlexander Motin 		 * the other one specifically and then escalating two levels.
10522668bb2aSAlexander Motin 		 */
105362fa74d9SJeff Roberson 		if (cpu == -1) {
10542668bb2aSAlexander Motin 			if (goup) {
105562fa74d9SJeff Roberson 				cg = cg->cg_parent;
10562668bb2aSAlexander Motin 				goup = 0;
10572668bb2aSAlexander Motin 			}
10582668bb2aSAlexander Motin 			parent = cg->cg_parent;
10592668bb2aSAlexander Motin 			if (parent == NULL)
106097e9382dSDon Lewis 				return (1);
10612668bb2aSAlexander Motin 			if (parent->cg_children == 2) {
10622668bb2aSAlexander Motin 				if (cg == &parent->cg_child[0])
10632668bb2aSAlexander Motin 					cg = &parent->cg_child[1];
10642668bb2aSAlexander Motin 				else
10652668bb2aSAlexander Motin 					cg = &parent->cg_child[0];
10662668bb2aSAlexander Motin 				goup = 1;
10672668bb2aSAlexander Motin 			} else
10682668bb2aSAlexander Motin 				cg = parent;
106980f86c9fSJeff Roberson 			continue;
10707b8bfa0dSJeff Roberson 		}
10717b8bfa0dSJeff Roberson 		steal = TDQ_CPU(cpu);
107297e9382dSDon Lewis 		/*
107397e9382dSDon Lewis 		 * The data returned by sched_highest() is stale and
107497e9382dSDon Lewis 		 * the chosen CPU no longer has an eligible thread.
107597e9382dSDon Lewis 		 *
107697e9382dSDon Lewis 		 * Testing this ahead of tdq_lock_pair() only catches
107797e9382dSDon Lewis 		 * this situation about 20% of the time on an 8 core
107897e9382dSDon Lewis 		 * 16 thread Ryzen 7, but it still helps performance.
107997e9382dSDon Lewis 		 */
108011484ad8SMark Johnston 		if (TDQ_LOAD(steal) < steal_thresh ||
108111484ad8SMark Johnston 		    TDQ_TRANSFERABLE(steal) == 0)
108297e9382dSDon Lewis 			goto restart;
108397e9382dSDon Lewis 		/*
10848bb173fbSAlexander Motin 		 * Try to lock both queues. If we are assigned a thread while
10858bb173fbSAlexander Motin 		 * waited for the lock, switch to it now instead of stealing.
10868bb173fbSAlexander Motin 		 * If we can't get the lock, then somebody likely got there
10878bb173fbSAlexander Motin 		 * first so continue searching.
108897e9382dSDon Lewis 		 */
10898bb173fbSAlexander Motin 		TDQ_LOCK(tdq);
10908bb173fbSAlexander Motin 		if (tdq->tdq_load > 0) {
10918bb173fbSAlexander Motin 			mi_switch(SW_VOL | SWT_IDLE);
10928bb173fbSAlexander Motin 			return (0);
10938bb173fbSAlexander Motin 		}
10948bb173fbSAlexander Motin 		if (TDQ_TRYLOCK_FLAGS(steal, MTX_DUPOK) == 0) {
10958bb173fbSAlexander Motin 			TDQ_UNLOCK(tdq);
10968bb173fbSAlexander Motin 			CPU_CLR(cpu, &mask);
10978bb173fbSAlexander Motin 			continue;
10988bb173fbSAlexander Motin 		}
109997e9382dSDon Lewis 		/*
110097e9382dSDon Lewis 		 * The data returned by sched_highest() is stale and
110197e9382dSDon Lewis 		 * the chosen CPU no longer has an eligible thread, or
110297e9382dSDon Lewis 		 * we were preempted and the CPU loading info may be out
110397e9382dSDon Lewis 		 * of date.  The latter is rare.  In either case restart
110497e9382dSDon Lewis 		 * the search.
110597e9382dSDon Lewis 		 */
110611484ad8SMark Johnston 		if (TDQ_LOAD(steal) < steal_thresh ||
110711484ad8SMark Johnston 		    TDQ_TRANSFERABLE(steal) == 0 ||
110811484ad8SMark Johnston 		    switchcnt != TDQ_SWITCHCNT(tdq)) {
11097fcf154aSJeff Roberson 			tdq_unlock_pair(tdq, steal);
111097e9382dSDon Lewis 			goto restart;
111162fa74d9SJeff Roberson 		}
111262fa74d9SJeff Roberson 		/*
111397e9382dSDon Lewis 		 * Steal the thread and switch to it.
111462fa74d9SJeff Roberson 		 */
11156d3f74a1SMark Johnston 		if (tdq_move(steal, tdq) != -1)
111697e9382dSDon Lewis 			break;
111797e9382dSDon Lewis 		/*
111897e9382dSDon Lewis 		 * We failed to acquire a thread even though it looked
111997e9382dSDon Lewis 		 * like one was available.  This could be due to affinity
112097e9382dSDon Lewis 		 * restrictions or for other reasons.  Loop again after
112197e9382dSDon Lewis 		 * removing this CPU from the set.  The restart logic
112297e9382dSDon Lewis 		 * above does not restore this CPU to the set due to the
112397e9382dSDon Lewis 		 * likelyhood of failing here again.
112497e9382dSDon Lewis 		 */
112597e9382dSDon Lewis 		CPU_CLR(cpu, &mask);
112662fa74d9SJeff Roberson 		tdq_unlock_pair(tdq, steal);
112780f86c9fSJeff Roberson 	}
1128ae7a6b38SJeff Roberson 	TDQ_UNLOCK(steal);
1129686bcb5cSJeff Roberson 	mi_switch(SW_VOL | SWT_IDLE);
11307b8bfa0dSJeff Roberson 	return (0);
113122bf7d9aSJeff Roberson }
113222bf7d9aSJeff Roberson 
1133ae7a6b38SJeff Roberson /*
1134ae7a6b38SJeff Roberson  * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
11356d3f74a1SMark Johnston  *
11366d3f74a1SMark Johnston  * "lowpri" is the minimum scheduling priority among all threads on
11376d3f74a1SMark Johnston  * the queue prior to the addition of the new thread.
1138ae7a6b38SJeff Roberson  */
113922bf7d9aSJeff Roberson static void
11406d3f74a1SMark Johnston tdq_notify(struct tdq *tdq, int lowpri)
114122bf7d9aSJeff Roberson {
11427b8bfa0dSJeff Roberson 	int cpu;
114322bf7d9aSJeff Roberson 
11446d3f74a1SMark Johnston 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
11456d3f74a1SMark Johnston 	KASSERT(tdq->tdq_lowpri <= lowpri,
11466d3f74a1SMark Johnston 	    ("tdq_notify: lowpri %d > tdq_lowpri %d", lowpri, tdq->tdq_lowpri));
11476d3f74a1SMark Johnston 
11487789ab32SMark Johnston 	if (tdq->tdq_owepreempt)
1149ff256d9cSJeff Roberson 		return;
11506d3f74a1SMark Johnston 
11516d3f74a1SMark Johnston 	/*
11526d3f74a1SMark Johnston 	 * Check to see if the newly added thread should preempt the one
11536d3f74a1SMark Johnston 	 * currently running.
11546d3f74a1SMark Johnston 	 */
11556d3f74a1SMark Johnston 	if (!sched_shouldpreempt(tdq->tdq_lowpri, lowpri, 1))
11566b2f763fSJeff Roberson 		return;
115779654969SAlexander Motin 
115879654969SAlexander Motin 	/*
1159ae9e9b4fSAlexander Motin 	 * Make sure that our caller's earlier update to tdq_load is
1160ae9e9b4fSAlexander Motin 	 * globally visible before we read tdq_cpu_idle.  Idle thread
116179654969SAlexander Motin 	 * accesses both of them without locks, and the order is important.
116279654969SAlexander Motin 	 */
1163e8677f38SKonstantin Belousov 	atomic_thread_fence_seq_cst();
116479654969SAlexander Motin 
11651690c6c1SJeff Roberson 	/*
11666d3f74a1SMark Johnston 	 * Try to figure out if we can signal the idle thread instead of sending
11676d3f74a1SMark Johnston 	 * an IPI.  This check is racy; at worst, we will deliever an IPI
11686d3f74a1SMark Johnston 	 * unnecessarily.
11696c47aaaeSJeff Roberson 	 */
11706d3f74a1SMark Johnston 	cpu = TDQ_ID(tdq);
11716d3f74a1SMark Johnston 	if (TD_IS_IDLETHREAD(tdq->tdq_curthread) &&
117211484ad8SMark Johnston 	    (atomic_load_int(&tdq->tdq_cpu_idle) == 0 || cpu_idle_wakeup(cpu)))
11736c47aaaeSJeff Roberson 		return;
11747789ab32SMark Johnston 
11757789ab32SMark Johnston 	/*
11767789ab32SMark Johnston 	 * The run queues have been updated, so any switch on the remote CPU
11777789ab32SMark Johnston 	 * will satisfy the preemption request.
11787789ab32SMark Johnston 	 */
11797789ab32SMark Johnston 	tdq->tdq_owepreempt = 1;
1180d9d8d144SJohn Baldwin 	ipi_cpu(cpu, IPI_PREEMPT);
118122bf7d9aSJeff Roberson }
118222bf7d9aSJeff Roberson 
1183ae7a6b38SJeff Roberson /*
1184ae7a6b38SJeff Roberson  * Steals load from a timeshare queue.  Honors the rotating queue head
1185ae7a6b38SJeff Roberson  * index.
1186ae7a6b38SJeff Roberson  */
11879727e637SJeff Roberson static struct thread *
118862fa74d9SJeff Roberson runq_steal_from(struct runq *rq, int cpu, u_char start)
1189ae7a6b38SJeff Roberson {
1190ae7a6b38SJeff Roberson 	struct rqbits *rqb;
1191ae7a6b38SJeff Roberson 	struct rqhead *rqh;
119236acfc65SAlexander Motin 	struct thread *td, *first;
1193ae7a6b38SJeff Roberson 	int bit;
1194ae7a6b38SJeff Roberson 	int i;
1195ae7a6b38SJeff Roberson 
1196ae7a6b38SJeff Roberson 	rqb = &rq->rq_status;
1197ae7a6b38SJeff Roberson 	bit = start & (RQB_BPW -1);
119836acfc65SAlexander Motin 	first = NULL;
1199ae7a6b38SJeff Roberson again:
1200ae7a6b38SJeff Roberson 	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1201ae7a6b38SJeff Roberson 		if (rqb->rqb_bits[i] == 0)
1202ae7a6b38SJeff Roberson 			continue;
12038bc713f6SJeff Roberson 		if (bit == 0)
12048bc713f6SJeff Roberson 			bit = RQB_FFS(rqb->rqb_bits[i]);
12058bc713f6SJeff Roberson 		for (; bit < RQB_BPW; bit++) {
12068bc713f6SJeff Roberson 			if ((rqb->rqb_bits[i] & (1ul << bit)) == 0)
1207ae7a6b38SJeff Roberson 				continue;
12088bc713f6SJeff Roberson 			rqh = &rq->rq_queues[bit + (i << RQB_L2BPW)];
12099727e637SJeff Roberson 			TAILQ_FOREACH(td, rqh, td_runq) {
1210bd84094aSAlexander Motin 				if (first) {
1211bd84094aSAlexander Motin 					if (THREAD_CAN_MIGRATE(td) &&
12129727e637SJeff Roberson 					    THREAD_CAN_SCHED(td, cpu))
12139727e637SJeff Roberson 						return (td);
1214bd84094aSAlexander Motin 				} else
121536acfc65SAlexander Motin 					first = td;
1216ae7a6b38SJeff Roberson 			}
1217ae7a6b38SJeff Roberson 		}
12188bc713f6SJeff Roberson 	}
1219ae7a6b38SJeff Roberson 	if (start != 0) {
1220ae7a6b38SJeff Roberson 		start = 0;
1221ae7a6b38SJeff Roberson 		goto again;
1222ae7a6b38SJeff Roberson 	}
1223ae7a6b38SJeff Roberson 
122436acfc65SAlexander Motin 	if (first && THREAD_CAN_MIGRATE(first) &&
122536acfc65SAlexander Motin 	    THREAD_CAN_SCHED(first, cpu))
122636acfc65SAlexander Motin 		return (first);
1227ae7a6b38SJeff Roberson 	return (NULL);
1228ae7a6b38SJeff Roberson }
1229ae7a6b38SJeff Roberson 
1230ae7a6b38SJeff Roberson /*
1231ae7a6b38SJeff Roberson  * Steals load from a standard linear queue.
1232ae7a6b38SJeff Roberson  */
12339727e637SJeff Roberson static struct thread *
123462fa74d9SJeff Roberson runq_steal(struct runq *rq, int cpu)
123522bf7d9aSJeff Roberson {
123622bf7d9aSJeff Roberson 	struct rqhead *rqh;
123722bf7d9aSJeff Roberson 	struct rqbits *rqb;
12389727e637SJeff Roberson 	struct thread *td;
123922bf7d9aSJeff Roberson 	int word;
124022bf7d9aSJeff Roberson 	int bit;
124122bf7d9aSJeff Roberson 
124222bf7d9aSJeff Roberson 	rqb = &rq->rq_status;
124322bf7d9aSJeff Roberson 	for (word = 0; word < RQB_LEN; word++) {
124422bf7d9aSJeff Roberson 		if (rqb->rqb_bits[word] == 0)
124522bf7d9aSJeff Roberson 			continue;
124622bf7d9aSJeff Roberson 		for (bit = 0; bit < RQB_BPW; bit++) {
1247a2640c9bSPeter Wemm 			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
124822bf7d9aSJeff Roberson 				continue;
124922bf7d9aSJeff Roberson 			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
12509727e637SJeff Roberson 			TAILQ_FOREACH(td, rqh, td_runq)
12519727e637SJeff Roberson 				if (THREAD_CAN_MIGRATE(td) &&
12529727e637SJeff Roberson 				    THREAD_CAN_SCHED(td, cpu))
12539727e637SJeff Roberson 					return (td);
125422bf7d9aSJeff Roberson 		}
125522bf7d9aSJeff Roberson 	}
125622bf7d9aSJeff Roberson 	return (NULL);
125722bf7d9aSJeff Roberson }
125822bf7d9aSJeff Roberson 
1259ae7a6b38SJeff Roberson /*
1260ae7a6b38SJeff Roberson  * Attempt to steal a thread in priority order from a thread queue.
1261ae7a6b38SJeff Roberson  */
12629727e637SJeff Roberson static struct thread *
126362fa74d9SJeff Roberson tdq_steal(struct tdq *tdq, int cpu)
126422bf7d9aSJeff Roberson {
12659727e637SJeff Roberson 	struct thread *td;
126622bf7d9aSJeff Roberson 
1267ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
12689727e637SJeff Roberson 	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
12699727e637SJeff Roberson 		return (td);
12709727e637SJeff Roberson 	if ((td = runq_steal_from(&tdq->tdq_timeshare,
12719727e637SJeff Roberson 	    cpu, tdq->tdq_ridx)) != NULL)
12729727e637SJeff Roberson 		return (td);
127362fa74d9SJeff Roberson 	return (runq_steal(&tdq->tdq_idle, cpu));
127422bf7d9aSJeff Roberson }
127580f86c9fSJeff Roberson 
1276ae7a6b38SJeff Roberson /*
1277ae7a6b38SJeff Roberson  * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
12787fcf154aSJeff Roberson  * current lock and returns with the assigned queue locked.
1279ae7a6b38SJeff Roberson  */
1280ae7a6b38SJeff Roberson static inline struct tdq *
12819727e637SJeff Roberson sched_setcpu(struct thread *td, int cpu, int flags)
128280f86c9fSJeff Roberson {
12839727e637SJeff Roberson 
1284ae7a6b38SJeff Roberson 	struct tdq *tdq;
128561a74c5cSJeff Roberson 	struct mtx *mtx;
128680f86c9fSJeff Roberson 
12879727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1288ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpu);
128993ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_cpu = cpu;
12909727e637SJeff Roberson 	/*
12919727e637SJeff Roberson 	 * If the lock matches just return the queue.
12929727e637SJeff Roberson 	 */
129361a74c5cSJeff Roberson 	if (td->td_lock == TDQ_LOCKPTR(tdq)) {
129461a74c5cSJeff Roberson 		KASSERT((flags & SRQ_HOLD) == 0,
129561a74c5cSJeff Roberson 		    ("sched_setcpu: Invalid lock for SRQ_HOLD"));
1296ae7a6b38SJeff Roberson 		return (tdq);
1297ae7a6b38SJeff Roberson 	}
129861a74c5cSJeff Roberson 
129980f86c9fSJeff Roberson 	/*
1300ae7a6b38SJeff Roberson 	 * The hard case, migration, we need to block the thread first to
1301ae7a6b38SJeff Roberson 	 * prevent order reversals with other cpus locks.
13027b8bfa0dSJeff Roberson 	 */
1303b0b9dee5SAttilio Rao 	spinlock_enter();
130461a74c5cSJeff Roberson 	mtx = thread_lock_block(td);
130561a74c5cSJeff Roberson 	if ((flags & SRQ_HOLD) == 0)
130661a74c5cSJeff Roberson 		mtx_unlock_spin(mtx);
1307ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
1308ae7a6b38SJeff Roberson 	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1309b0b9dee5SAttilio Rao 	spinlock_exit();
1310ae7a6b38SJeff Roberson 	return (tdq);
131180f86c9fSJeff Roberson }
13122454aaf5SJeff Roberson 
13138df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
13148df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
13158df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
13168df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
13178df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
13188df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
13198df78c41SJeff Roberson 
1320ae7a6b38SJeff Roberson static int
13219727e637SJeff Roberson sched_pickcpu(struct thread *td, int flags)
1322ae7a6b38SJeff Roberson {
132336acfc65SAlexander Motin 	struct cpu_group *cg, *ccg;
13249727e637SJeff Roberson 	struct td_sched *ts;
1325ae7a6b38SJeff Roberson 	struct tdq *tdq;
1326aefe0a8cSAlexander Motin 	cpuset_t *mask;
1327e745d729SAlexander Motin 	int cpu, pri, r, self, intr;
13287b8bfa0dSJeff Roberson 
132962fa74d9SJeff Roberson 	self = PCPU_GET(cpuid);
133093ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1331efe67753SNathan Whitehorn 	KASSERT(!CPU_ABSENT(ts->ts_cpu), ("sched_pickcpu: Start scheduler on "
1332efe67753SNathan Whitehorn 	    "absent CPU %d for thread %s.", ts->ts_cpu, td->td_name));
13337b8bfa0dSJeff Roberson 	if (smp_started == 0)
13347b8bfa0dSJeff Roberson 		return (self);
133528994a58SJeff Roberson 	/*
133628994a58SJeff Roberson 	 * Don't migrate a running thread from sched_switch().
133728994a58SJeff Roberson 	 */
133862fa74d9SJeff Roberson 	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
133962fa74d9SJeff Roberson 		return (ts->ts_cpu);
13407b8bfa0dSJeff Roberson 	/*
134162fa74d9SJeff Roberson 	 * Prefer to run interrupt threads on the processors that generate
134262fa74d9SJeff Roberson 	 * the interrupt.
13437b8bfa0dSJeff Roberson 	 */
134462fa74d9SJeff Roberson 	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1345c9205e35SAlexander Motin 	    curthread->td_intr_nesting_level) {
1346c55dc51cSAlexander Motin 		tdq = TDQ_SELF();
1347c55dc51cSAlexander Motin 		if (tdq->tdq_lowpri >= PRI_MIN_IDLE) {
1348c55dc51cSAlexander Motin 			SCHED_STAT_INC(pickcpu_idle_affinity);
1349c55dc51cSAlexander Motin 			return (self);
1350c55dc51cSAlexander Motin 		}
135162fa74d9SJeff Roberson 		ts->ts_cpu = self;
1352c9205e35SAlexander Motin 		intr = 1;
1353c55dc51cSAlexander Motin 		cg = tdq->tdq_cg;
1354c55dc51cSAlexander Motin 		goto llc;
1355c55dc51cSAlexander Motin 	} else {
1356c9205e35SAlexander Motin 		intr = 0;
1357c55dc51cSAlexander Motin 		tdq = TDQ_CPU(ts->ts_cpu);
1358c55dc51cSAlexander Motin 		cg = tdq->tdq_cg;
1359c55dc51cSAlexander Motin 	}
13607b8bfa0dSJeff Roberson 	/*
136136acfc65SAlexander Motin 	 * If the thread can run on the last cpu and the affinity has not
13620127914cSEric van Gyzen 	 * expired and it is idle, run it there.
13637b8bfa0dSJeff Roberson 	 */
136436acfc65SAlexander Motin 	if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
13656cbc4cebSMark Johnston 	    atomic_load_char(&tdq->tdq_lowpri) >= PRI_MIN_IDLE &&
136636acfc65SAlexander Motin 	    SCHED_AFFINITY(ts, CG_SHARE_L2)) {
1367c55dc51cSAlexander Motin 		if (cg->cg_flags & CG_FLAG_THREAD) {
1368176dd236SAlexander Motin 			/* Check all SMT threads for being idle. */
1369aefe0a8cSAlexander Motin 			for (cpu = cg->cg_first; cpu <= cg->cg_last; cpu++) {
137011484ad8SMark Johnston 				pri =
137111484ad8SMark Johnston 				    atomic_load_char(&TDQ_CPU(cpu)->tdq_lowpri);
1372176dd236SAlexander Motin 				if (CPU_ISSET(cpu, &cg->cg_mask) &&
137311484ad8SMark Johnston 				    pri < PRI_MIN_IDLE)
137462fa74d9SJeff Roberson 					break;
1375aefe0a8cSAlexander Motin 			}
1376aefe0a8cSAlexander Motin 			if (cpu > cg->cg_last) {
1377176dd236SAlexander Motin 				SCHED_STAT_INC(pickcpu_idle_affinity);
1378176dd236SAlexander Motin 				return (ts->ts_cpu);
137936acfc65SAlexander Motin 			}
1380176dd236SAlexander Motin 		} else {
138136acfc65SAlexander Motin 			SCHED_STAT_INC(pickcpu_idle_affinity);
138236acfc65SAlexander Motin 			return (ts->ts_cpu);
138336acfc65SAlexander Motin 		}
138436acfc65SAlexander Motin 	}
1385c55dc51cSAlexander Motin llc:
138636acfc65SAlexander Motin 	/*
138736acfc65SAlexander Motin 	 * Search for the last level cache CPU group in the tree.
1388c9205e35SAlexander Motin 	 * Skip SMT, identical groups and caches with expired affinity.
1389c9205e35SAlexander Motin 	 * Interrupt threads affinity is explicit and never expires.
139036acfc65SAlexander Motin 	 */
139136acfc65SAlexander Motin 	for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
139236acfc65SAlexander Motin 		if (cg->cg_flags & CG_FLAG_THREAD)
139336acfc65SAlexander Motin 			continue;
1394c9205e35SAlexander Motin 		if (cg->cg_children == 1 || cg->cg_count == 1)
1395c9205e35SAlexander Motin 			continue;
1396c9205e35SAlexander Motin 		if (cg->cg_level == CG_SHARE_NONE ||
1397c9205e35SAlexander Motin 		    (!intr && !SCHED_AFFINITY(ts, cg->cg_level)))
139836acfc65SAlexander Motin 			continue;
139936acfc65SAlexander Motin 		ccg = cg;
140036acfc65SAlexander Motin 	}
1401c9205e35SAlexander Motin 	/* Found LLC shared by all CPUs, so do a global search. */
1402c9205e35SAlexander Motin 	if (ccg == cpu_top)
1403c9205e35SAlexander Motin 		ccg = NULL;
140462fa74d9SJeff Roberson 	cpu = -1;
1405aefe0a8cSAlexander Motin 	mask = &td->td_cpuset->cs_mask;
1406c9205e35SAlexander Motin 	pri = td->td_priority;
1407e745d729SAlexander Motin 	r = TD_IS_RUNNING(td);
1408c9205e35SAlexander Motin 	/*
1409c9205e35SAlexander Motin 	 * Try hard to keep interrupts within found LLC.  Search the LLC for
1410c9205e35SAlexander Motin 	 * the least loaded CPU we can run now.  For NUMA systems it should
1411c9205e35SAlexander Motin 	 * be within target domain, and it also reduces scheduling overhead.
1412c9205e35SAlexander Motin 	 */
1413c9205e35SAlexander Motin 	if (ccg != NULL && intr) {
1414e745d729SAlexander Motin 		cpu = sched_lowest(ccg, mask, pri, INT_MAX, ts->ts_cpu, r);
1415c9205e35SAlexander Motin 		if (cpu >= 0)
1416c9205e35SAlexander Motin 			SCHED_STAT_INC(pickcpu_intrbind);
1417c9205e35SAlexander Motin 	} else
1418c9205e35SAlexander Motin 	/* Search the LLC for the least loaded idle CPU we can run now. */
1419c9205e35SAlexander Motin 	if (ccg != NULL) {
1420c9205e35SAlexander Motin 		cpu = sched_lowest(ccg, mask, max(pri, PRI_MAX_TIMESHARE),
1421e745d729SAlexander Motin 		    INT_MAX, ts->ts_cpu, r);
1422c9205e35SAlexander Motin 		if (cpu >= 0)
1423c9205e35SAlexander Motin 			SCHED_STAT_INC(pickcpu_affinity);
1424c9205e35SAlexander Motin 	}
1425c9205e35SAlexander Motin 	/* Search globally for the least loaded CPU we can run now. */
1426c9205e35SAlexander Motin 	if (cpu < 0) {
1427e745d729SAlexander Motin 		cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu, r);
1428c9205e35SAlexander Motin 		if (cpu >= 0)
1429c9205e35SAlexander Motin 			SCHED_STAT_INC(pickcpu_lowest);
1430c9205e35SAlexander Motin 	}
1431c9205e35SAlexander Motin 	/* Search globally for the least loaded CPU. */
1432c9205e35SAlexander Motin 	if (cpu < 0) {
1433e745d729SAlexander Motin 		cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu, r);
1434c9205e35SAlexander Motin 		if (cpu >= 0)
1435c9205e35SAlexander Motin 			SCHED_STAT_INC(pickcpu_lowest);
1436c9205e35SAlexander Motin 	}
1437bb3dfc6aSAlexander Motin 	KASSERT(cpu >= 0, ("sched_pickcpu: Failed to find a cpu."));
1438efe67753SNathan Whitehorn 	KASSERT(!CPU_ABSENT(cpu), ("sched_pickcpu: Picked absent CPU %d.", cpu));
143962fa74d9SJeff Roberson 	/*
144062fa74d9SJeff Roberson 	 * Compare the lowest loaded cpu to current cpu.
144162fa74d9SJeff Roberson 	 */
1442018ff686SJeff Roberson 	tdq = TDQ_CPU(cpu);
1443018ff686SJeff Roberson 	if (THREAD_CAN_SCHED(td, self) && TDQ_SELF()->tdq_lowpri > pri &&
144411484ad8SMark Johnston 	    atomic_load_char(&tdq->tdq_lowpri) < PRI_MIN_IDLE &&
144511484ad8SMark Johnston 	    TDQ_LOAD(TDQ_SELF()) <= TDQ_LOAD(tdq) + 1) {
14468df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_local);
144762fa74d9SJeff Roberson 		cpu = self;
1448c9205e35SAlexander Motin 	}
14498df78c41SJeff Roberson 	if (cpu != ts->ts_cpu)
14508df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_migration);
1451ae7a6b38SJeff Roberson 	return (cpu);
145280f86c9fSJeff Roberson }
145362fa74d9SJeff Roberson #endif
145422bf7d9aSJeff Roberson 
145522bf7d9aSJeff Roberson /*
145622bf7d9aSJeff Roberson  * Pick the highest priority task we have and return it.
14570c0a98b2SJeff Roberson  */
14589727e637SJeff Roberson static struct thread *
1459ad1e7d28SJulian Elischer tdq_choose(struct tdq *tdq)
14605d7ef00cSJeff Roberson {
14619727e637SJeff Roberson 	struct thread *td;
14625d7ef00cSJeff Roberson 
1463ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
14649727e637SJeff Roberson 	td = runq_choose(&tdq->tdq_realtime);
14659727e637SJeff Roberson 	if (td != NULL)
14669727e637SJeff Roberson 		return (td);
14679727e637SJeff Roberson 	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
14689727e637SJeff Roberson 	if (td != NULL) {
146912d56c0fSJohn Baldwin 		KASSERT(td->td_priority >= PRI_MIN_BATCH,
1470e7d50326SJeff Roberson 		    ("tdq_choose: Invalid priority on timeshare queue %d",
14719727e637SJeff Roberson 		    td->td_priority));
14729727e637SJeff Roberson 		return (td);
147315dc847eSJeff Roberson 	}
14749727e637SJeff Roberson 	td = runq_choose(&tdq->tdq_idle);
14759727e637SJeff Roberson 	if (td != NULL) {
14769727e637SJeff Roberson 		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1477e7d50326SJeff Roberson 		    ("tdq_choose: Invalid priority on idle queue %d",
14789727e637SJeff Roberson 		    td->td_priority));
14799727e637SJeff Roberson 		return (td);
1480e7d50326SJeff Roberson 	}
1481e7d50326SJeff Roberson 
1482e7d50326SJeff Roberson 	return (NULL);
1483245f3abfSJeff Roberson }
14840a016a05SJeff Roberson 
1485ae7a6b38SJeff Roberson /*
1486ae7a6b38SJeff Roberson  * Initialize a thread queue.
1487ae7a6b38SJeff Roberson  */
14880a016a05SJeff Roberson static void
1489018ff686SJeff Roberson tdq_setup(struct tdq *tdq, int id)
14900a016a05SJeff Roberson {
1491ae7a6b38SJeff Roberson 
1492c47f202bSJeff Roberson 	if (bootverbose)
1493018ff686SJeff Roberson 		printf("ULE: setup cpu %d\n", id);
1494e7d50326SJeff Roberson 	runq_init(&tdq->tdq_realtime);
1495e7d50326SJeff Roberson 	runq_init(&tdq->tdq_timeshare);
1496d2ad694cSJeff Roberson 	runq_init(&tdq->tdq_idle);
1497018ff686SJeff Roberson 	tdq->tdq_id = id;
149862fa74d9SJeff Roberson 	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
149962fa74d9SJeff Roberson 	    "sched lock %d", (int)TDQ_ID(tdq));
150061a74c5cSJeff Roberson 	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock", MTX_SPIN);
15018f51ad55SJeff Roberson #ifdef KTR
15028f51ad55SJeff Roberson 	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
15038f51ad55SJeff Roberson 	    "CPU %d load", (int)TDQ_ID(tdq));
15048f51ad55SJeff Roberson #endif
15050a016a05SJeff Roberson }
15060a016a05SJeff Roberson 
1507c47f202bSJeff Roberson #ifdef SMP
1508c47f202bSJeff Roberson static void
1509c47f202bSJeff Roberson sched_setup_smp(void)
1510c47f202bSJeff Roberson {
1511c47f202bSJeff Roberson 	struct tdq *tdq;
1512c47f202bSJeff Roberson 	int i;
1513c47f202bSJeff Roberson 
151462fa74d9SJeff Roberson 	cpu_top = smp_topo();
15153aa6d94eSJohn Baldwin 	CPU_FOREACH(i) {
1516018ff686SJeff Roberson 		tdq = DPCPU_ID_PTR(i, tdq);
1517018ff686SJeff Roberson 		tdq_setup(tdq, i);
151862fa74d9SJeff Roberson 		tdq->tdq_cg = smp_topo_find(cpu_top, i);
151962fa74d9SJeff Roberson 		if (tdq->tdq_cg == NULL)
152062fa74d9SJeff Roberson 			panic("Can't find cpu group for %d\n", i);
1521ca34553bSAlexander Motin 		DPCPU_ID_SET(i, randomval, i * 69069 + 5);
1522c47f202bSJeff Roberson 	}
1523018ff686SJeff Roberson 	PCPU_SET(sched, DPCPU_PTR(tdq));
152462fa74d9SJeff Roberson 	balance_tdq = TDQ_SELF();
1525c47f202bSJeff Roberson }
1526c47f202bSJeff Roberson #endif
1527c47f202bSJeff Roberson 
1528ae7a6b38SJeff Roberson /*
1529ae7a6b38SJeff Roberson  * Setup the thread queues and initialize the topology based on MD
1530ae7a6b38SJeff Roberson  * information.
1531ae7a6b38SJeff Roberson  */
153235e6168fSJeff Roberson static void
153335e6168fSJeff Roberson sched_setup(void *dummy)
153435e6168fSJeff Roberson {
1535ae7a6b38SJeff Roberson 	struct tdq *tdq;
1536c47f202bSJeff Roberson 
15370ec896fdSJeff Roberson #ifdef SMP
1538c47f202bSJeff Roberson 	sched_setup_smp();
1539749d01b0SJeff Roberson #else
1540018ff686SJeff Roberson 	tdq_setup(TDQ_SELF(), 0);
1541356500a3SJeff Roberson #endif
1542018ff686SJeff Roberson 	tdq = TDQ_SELF();
1543ae7a6b38SJeff Roberson 
1544ae7a6b38SJeff Roberson 	/* Add thread0's load since it's running. */
1545ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
1546e1504695SJeff Roberson 	thread0.td_lock = TDQ_LOCKPTR(tdq);
15479727e637SJeff Roberson 	tdq_load_add(tdq, &thread0);
15486d3f74a1SMark Johnston 	tdq->tdq_curthread = &thread0;
154962fa74d9SJeff Roberson 	tdq->tdq_lowpri = thread0.td_priority;
1550ae7a6b38SJeff Roberson 	TDQ_UNLOCK(tdq);
155135e6168fSJeff Roberson }
155235e6168fSJeff Roberson 
1553ae7a6b38SJeff Roberson /*
1554579895dfSAlexander Motin  * This routine determines time constants after stathz and hz are setup.
1555ae7a6b38SJeff Roberson  */
1556a1d4fe69SDavid Xu /* ARGSUSED */
1557a1d4fe69SDavid Xu static void
1558a1d4fe69SDavid Xu sched_initticks(void *dummy)
1559a1d4fe69SDavid Xu {
1560ae7a6b38SJeff Roberson 	int incr;
1561ae7a6b38SJeff Roberson 
1562a1d4fe69SDavid Xu 	realstathz = stathz ? stathz : hz;
15635e5c3873SJeff Roberson 	sched_slice = realstathz / SCHED_SLICE_DEFAULT_DIVISOR;
15645e5c3873SJeff Roberson 	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
156537f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
156637f4e025SAlexander Motin 	    realstathz);
1567a1d4fe69SDavid Xu 
1568a1d4fe69SDavid Xu 	/*
1569e7d50326SJeff Roberson 	 * tickincr is shifted out by 10 to avoid rounding errors due to
15703f872f85SJeff Roberson 	 * hz not being evenly divisible by stathz on all platforms.
1571e7d50326SJeff Roberson 	 */
1572ae7a6b38SJeff Roberson 	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1573e7d50326SJeff Roberson 	/*
1574e7d50326SJeff Roberson 	 * This does not work for values of stathz that are more than
1575e7d50326SJeff Roberson 	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1576a1d4fe69SDavid Xu 	 */
1577ae7a6b38SJeff Roberson 	if (incr == 0)
1578ae7a6b38SJeff Roberson 		incr = 1;
1579ae7a6b38SJeff Roberson 	tickincr = incr;
15807b8bfa0dSJeff Roberson #ifdef SMP
15819862717aSJeff Roberson 	/*
15827fcf154aSJeff Roberson 	 * Set the default balance interval now that we know
15837fcf154aSJeff Roberson 	 * what realstathz is.
15847fcf154aSJeff Roberson 	 */
15857fcf154aSJeff Roberson 	balance_interval = realstathz;
1586290d9060SDon Lewis 	balance_ticks = balance_interval;
15877b8bfa0dSJeff Roberson 	affinity = SCHED_AFFINITY_DEFAULT;
15887b8bfa0dSJeff Roberson #endif
1589b3f40a41SAlexander Motin 	if (sched_idlespinthresh < 0)
15902c27cb3aSAlexander Motin 		sched_idlespinthresh = 2 * max(10000, 6 * hz) / realstathz;
1591a1d4fe69SDavid Xu }
1592a1d4fe69SDavid Xu 
159335e6168fSJeff Roberson /*
1594ae7a6b38SJeff Roberson  * This is the core of the interactivity algorithm.  Determines a score based
1595ae7a6b38SJeff Roberson  * on past behavior.  It is the ratio of sleep time to run time scaled to
1596ae7a6b38SJeff Roberson  * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1597ae7a6b38SJeff Roberson  * differs from the cpu usage because it does not account for time spent
1598ae7a6b38SJeff Roberson  * waiting on a run-queue.  Would be prettier if we had floating point.
159957031f79SGeorge V. Neville-Neil  *
160057031f79SGeorge V. Neville-Neil  * When a thread's sleep time is greater than its run time the
160157031f79SGeorge V. Neville-Neil  * calculation is:
160257031f79SGeorge V. Neville-Neil  *
160357031f79SGeorge V. Neville-Neil  *                           scaling factor
160457031f79SGeorge V. Neville-Neil  * interactivity score =  ---------------------
160557031f79SGeorge V. Neville-Neil  *                        sleep time / run time
160657031f79SGeorge V. Neville-Neil  *
160757031f79SGeorge V. Neville-Neil  *
160857031f79SGeorge V. Neville-Neil  * When a thread's run time is greater than its sleep time the
160957031f79SGeorge V. Neville-Neil  * calculation is:
161057031f79SGeorge V. Neville-Neil  *
161157031f79SGeorge V. Neville-Neil  *                                                 scaling factor
161243521b46Swiklam  * interactivity score = 2 * scaling factor  -  ---------------------
161357031f79SGeorge V. Neville-Neil  *                                              run time / sleep time
1614ae7a6b38SJeff Roberson  */
1615ae7a6b38SJeff Roberson static int
1616ae7a6b38SJeff Roberson sched_interact_score(struct thread *td)
1617ae7a6b38SJeff Roberson {
1618ae7a6b38SJeff Roberson 	struct td_sched *ts;
1619ae7a6b38SJeff Roberson 	int div;
1620ae7a6b38SJeff Roberson 
162193ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1622ae7a6b38SJeff Roberson 	/*
1623ae7a6b38SJeff Roberson 	 * The score is only needed if this is likely to be an interactive
1624ae7a6b38SJeff Roberson 	 * task.  Don't go through the expense of computing it if there's
1625ae7a6b38SJeff Roberson 	 * no chance.
1626ae7a6b38SJeff Roberson 	 */
1627ae7a6b38SJeff Roberson 	if (sched_interact <= SCHED_INTERACT_HALF &&
1628ae7a6b38SJeff Roberson 		ts->ts_runtime >= ts->ts_slptime)
1629ae7a6b38SJeff Roberson 			return (SCHED_INTERACT_HALF);
1630ae7a6b38SJeff Roberson 
1631ae7a6b38SJeff Roberson 	if (ts->ts_runtime > ts->ts_slptime) {
1632ae7a6b38SJeff Roberson 		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1633ae7a6b38SJeff Roberson 		return (SCHED_INTERACT_HALF +
1634ae7a6b38SJeff Roberson 		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1635ae7a6b38SJeff Roberson 	}
1636ae7a6b38SJeff Roberson 	if (ts->ts_slptime > ts->ts_runtime) {
1637ae7a6b38SJeff Roberson 		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1638ae7a6b38SJeff Roberson 		return (ts->ts_runtime / div);
1639ae7a6b38SJeff Roberson 	}
1640ae7a6b38SJeff Roberson 	/* runtime == slptime */
1641ae7a6b38SJeff Roberson 	if (ts->ts_runtime)
1642ae7a6b38SJeff Roberson 		return (SCHED_INTERACT_HALF);
1643ae7a6b38SJeff Roberson 
1644ae7a6b38SJeff Roberson 	/*
1645ae7a6b38SJeff Roberson 	 * This can happen if slptime and runtime are 0.
1646ae7a6b38SJeff Roberson 	 */
1647ae7a6b38SJeff Roberson 	return (0);
1648ae7a6b38SJeff Roberson 
1649ae7a6b38SJeff Roberson }
1650ae7a6b38SJeff Roberson 
1651ae7a6b38SJeff Roberson /*
165235e6168fSJeff Roberson  * Scale the scheduling priority according to the "interactivity" of this
165335e6168fSJeff Roberson  * process.
165435e6168fSJeff Roberson  */
165515dc847eSJeff Roberson static void
16568460a577SJohn Birrell sched_priority(struct thread *td)
165735e6168fSJeff Roberson {
16581c119e17SAlexander Motin 	u_int pri, score;
165935e6168fSJeff Roberson 
1660c9a8cba4SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
166115dc847eSJeff Roberson 		return;
1662e7d50326SJeff Roberson 	/*
1663e7d50326SJeff Roberson 	 * If the score is interactive we place the thread in the realtime
1664e7d50326SJeff Roberson 	 * queue with a priority that is less than kernel and interrupt
1665e7d50326SJeff Roberson 	 * priorities.  These threads are not subject to nice restrictions.
1666e7d50326SJeff Roberson 	 *
1667ae7a6b38SJeff Roberson 	 * Scores greater than this are placed on the normal timeshare queue
1668e7d50326SJeff Roberson 	 * where the priority is partially decided by the most recent cpu
1669e7d50326SJeff Roberson 	 * utilization and the rest is decided by nice value.
1670a5423ea3SJeff Roberson 	 *
1671a5423ea3SJeff Roberson 	 * The nice value of the process has a linear effect on the calculated
1672a5423ea3SJeff Roberson 	 * score.  Negative nice values make it easier for a thread to be
1673a5423ea3SJeff Roberson 	 * considered interactive.
1674e7d50326SJeff Roberson 	 */
1675a0f15352SJohn Baldwin 	score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1676e7d50326SJeff Roberson 	if (score < sched_interact) {
167712d56c0fSJohn Baldwin 		pri = PRI_MIN_INTERACT;
16781c119e17SAlexander Motin 		pri += (PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) * score /
16791c119e17SAlexander Motin 		    sched_interact;
168012d56c0fSJohn Baldwin 		KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
16811c119e17SAlexander Motin 		    ("sched_priority: invalid interactive priority %u score %u",
16829a93305aSJeff Roberson 		    pri, score));
1683e7d50326SJeff Roberson 	} else {
1684e7d50326SJeff Roberson 		pri = SCHED_PRI_MIN;
168593ccd6bfSKonstantin Belousov 		if (td_get_sched(td)->ts_ticks)
168693ccd6bfSKonstantin Belousov 			pri += min(SCHED_PRI_TICKS(td_get_sched(td)),
16875457fa23SJohn Baldwin 			    SCHED_PRI_RANGE - 1);
1688e7d50326SJeff Roberson 		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
168912d56c0fSJohn Baldwin 		KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
16901c119e17SAlexander Motin 		    ("sched_priority: invalid priority %u: nice %d, "
1691ae7a6b38SJeff Roberson 		    "ticks %d ftick %d ltick %d tick pri %d",
169293ccd6bfSKonstantin Belousov 		    pri, td->td_proc->p_nice, td_get_sched(td)->ts_ticks,
169393ccd6bfSKonstantin Belousov 		    td_get_sched(td)->ts_ftick, td_get_sched(td)->ts_ltick,
169493ccd6bfSKonstantin Belousov 		    SCHED_PRI_TICKS(td_get_sched(td))));
1695e7d50326SJeff Roberson 	}
16968460a577SJohn Birrell 	sched_user_prio(td, pri);
169735e6168fSJeff Roberson 
169815dc847eSJeff Roberson 	return;
169935e6168fSJeff Roberson }
170035e6168fSJeff Roberson 
170135e6168fSJeff Roberson /*
1702d322132cSJeff Roberson  * This routine enforces a maximum limit on the amount of scheduling history
1703ae7a6b38SJeff Roberson  * kept.  It is called after either the slptime or runtime is adjusted.  This
1704ae7a6b38SJeff Roberson  * function is ugly due to integer math.
1705d322132cSJeff Roberson  */
17064b60e324SJeff Roberson static void
17078460a577SJohn Birrell sched_interact_update(struct thread *td)
17084b60e324SJeff Roberson {
1709155b6ca1SJeff Roberson 	struct td_sched *ts;
17109a93305aSJeff Roberson 	u_int sum;
17113f741ca1SJeff Roberson 
171293ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1713ae7a6b38SJeff Roberson 	sum = ts->ts_runtime + ts->ts_slptime;
1714d322132cSJeff Roberson 	if (sum < SCHED_SLP_RUN_MAX)
1715d322132cSJeff Roberson 		return;
1716d322132cSJeff Roberson 	/*
1717155b6ca1SJeff Roberson 	 * This only happens from two places:
1718155b6ca1SJeff Roberson 	 * 1) We have added an unusual amount of run time from fork_exit.
1719155b6ca1SJeff Roberson 	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1720155b6ca1SJeff Roberson 	 */
1721155b6ca1SJeff Roberson 	if (sum > SCHED_SLP_RUN_MAX * 2) {
1722ae7a6b38SJeff Roberson 		if (ts->ts_runtime > ts->ts_slptime) {
1723ae7a6b38SJeff Roberson 			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1724ae7a6b38SJeff Roberson 			ts->ts_slptime = 1;
1725155b6ca1SJeff Roberson 		} else {
1726ae7a6b38SJeff Roberson 			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1727ae7a6b38SJeff Roberson 			ts->ts_runtime = 1;
1728155b6ca1SJeff Roberson 		}
1729155b6ca1SJeff Roberson 		return;
1730155b6ca1SJeff Roberson 	}
1731155b6ca1SJeff Roberson 	/*
1732d322132cSJeff Roberson 	 * If we have exceeded by more than 1/5th then the algorithm below
1733d322132cSJeff Roberson 	 * will not bring us back into range.  Dividing by two here forces
17342454aaf5SJeff Roberson 	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1735d322132cSJeff Roberson 	 */
173637a35e4aSJeff Roberson 	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1737ae7a6b38SJeff Roberson 		ts->ts_runtime /= 2;
1738ae7a6b38SJeff Roberson 		ts->ts_slptime /= 2;
1739d322132cSJeff Roberson 		return;
1740d322132cSJeff Roberson 	}
1741ae7a6b38SJeff Roberson 	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1742ae7a6b38SJeff Roberson 	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1743d322132cSJeff Roberson }
1744d322132cSJeff Roberson 
1745ae7a6b38SJeff Roberson /*
1746ae7a6b38SJeff Roberson  * Scale back the interactivity history when a child thread is created.  The
1747ae7a6b38SJeff Roberson  * history is inherited from the parent but the thread may behave totally
1748ae7a6b38SJeff Roberson  * differently.  For example, a shell spawning a compiler process.  We want
1749ae7a6b38SJeff Roberson  * to learn that the compiler is behaving badly very quickly.
1750ae7a6b38SJeff Roberson  */
1751d322132cSJeff Roberson static void
17528460a577SJohn Birrell sched_interact_fork(struct thread *td)
1753d322132cSJeff Roberson {
175493ccd6bfSKonstantin Belousov 	struct td_sched *ts;
1755d322132cSJeff Roberson 	int ratio;
1756d322132cSJeff Roberson 	int sum;
1757d322132cSJeff Roberson 
175893ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
175993ccd6bfSKonstantin Belousov 	sum = ts->ts_runtime + ts->ts_slptime;
1760d322132cSJeff Roberson 	if (sum > SCHED_SLP_RUN_FORK) {
1761d322132cSJeff Roberson 		ratio = sum / SCHED_SLP_RUN_FORK;
176293ccd6bfSKonstantin Belousov 		ts->ts_runtime /= ratio;
176393ccd6bfSKonstantin Belousov 		ts->ts_slptime /= ratio;
17644b60e324SJeff Roberson 	}
17654b60e324SJeff Roberson }
17664b60e324SJeff Roberson 
176715dc847eSJeff Roberson /*
1768ae7a6b38SJeff Roberson  * Called from proc0_init() to setup the scheduler fields.
1769ed062c8dSJulian Elischer  */
1770ed062c8dSJulian Elischer void
1771ed062c8dSJulian Elischer schedinit(void)
1772ed062c8dSJulian Elischer {
177393ccd6bfSKonstantin Belousov 	struct td_sched *ts0;
1774e7d50326SJeff Roberson 
1775ed062c8dSJulian Elischer 	/*
177693ccd6bfSKonstantin Belousov 	 * Set up the scheduler specific parts of thread0.
1777ed062c8dSJulian Elischer 	 */
177893ccd6bfSKonstantin Belousov 	ts0 = td_get_sched(&thread0);
177993ccd6bfSKonstantin Belousov 	ts0->ts_ltick = ticks;
178093ccd6bfSKonstantin Belousov 	ts0->ts_ftick = ticks;
178193ccd6bfSKonstantin Belousov 	ts0->ts_slice = 0;
17821408b84aSHans Petter Selasky 	ts0->ts_cpu = curcpu;	/* set valid CPU number */
1783ed062c8dSJulian Elischer }
1784ed062c8dSJulian Elischer 
1785ed062c8dSJulian Elischer /*
1786589aed00SKyle Evans  * schedinit_ap() is needed prior to calling sched_throw(NULL) to ensure that
1787589aed00SKyle Evans  * the pcpu requirements are met for any calls in the period between curthread
1788589aed00SKyle Evans  * initialization and sched_throw().  One can safely add threads to the queue
1789589aed00SKyle Evans  * before sched_throw(), for instance, as long as the thread lock is setup
1790589aed00SKyle Evans  * correctly.
1791589aed00SKyle Evans  *
1792589aed00SKyle Evans  * TDQ_SELF() relies on the below sched pcpu setting; it may be used only
1793589aed00SKyle Evans  * after schedinit_ap().
1794589aed00SKyle Evans  */
1795589aed00SKyle Evans void
1796589aed00SKyle Evans schedinit_ap(void)
1797589aed00SKyle Evans {
1798589aed00SKyle Evans 
1799589aed00SKyle Evans #ifdef SMP
1800589aed00SKyle Evans 	PCPU_SET(sched, DPCPU_PTR(tdq));
1801589aed00SKyle Evans #endif
1802589aed00SKyle Evans 	PCPU_GET(idlethread)->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1803589aed00SKyle Evans }
1804589aed00SKyle Evans 
1805589aed00SKyle Evans /*
180615dc847eSJeff Roberson  * This is only somewhat accurate since given many processes of the same
180715dc847eSJeff Roberson  * priority they will switch when their slices run out, which will be
1808e7d50326SJeff Roberson  * at most sched_slice stathz ticks.
180915dc847eSJeff Roberson  */
181035e6168fSJeff Roberson int
181135e6168fSJeff Roberson sched_rr_interval(void)
181235e6168fSJeff Roberson {
1813e7d50326SJeff Roberson 
1814579895dfSAlexander Motin 	/* Convert sched_slice from stathz to hz. */
181537f4e025SAlexander Motin 	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
181635e6168fSJeff Roberson }
181735e6168fSJeff Roberson 
1818ae7a6b38SJeff Roberson /*
1819ae7a6b38SJeff Roberson  * Update the percent cpu tracking information when it is requested or
1820ae7a6b38SJeff Roberson  * the total history exceeds the maximum.  We keep a sliding history of
1821ae7a6b38SJeff Roberson  * tick counts that slowly decays.  This is less precise than the 4BSD
1822ae7a6b38SJeff Roberson  * mechanism since it happens with less regular and frequent events.
1823ae7a6b38SJeff Roberson  */
182422bf7d9aSJeff Roberson static void
18257295465eSAlexander Motin sched_pctcpu_update(struct td_sched *ts, int run)
182635e6168fSJeff Roberson {
18277295465eSAlexander Motin 	int t = ticks;
1828e7d50326SJeff Roberson 
182978133024SMark Johnston 	/*
183078133024SMark Johnston 	 * The signed difference may be negative if the thread hasn't run for
183178133024SMark Johnston 	 * over half of the ticks rollover period.
183278133024SMark Johnston 	 */
183378133024SMark Johnston 	if ((u_int)(t - ts->ts_ltick) >= SCHED_TICK_TARG) {
1834ad1e7d28SJulian Elischer 		ts->ts_ticks = 0;
18357295465eSAlexander Motin 		ts->ts_ftick = t - SCHED_TICK_TARG;
18367295465eSAlexander Motin 	} else if (t - ts->ts_ftick >= SCHED_TICK_MAX) {
18377295465eSAlexander Motin 		ts->ts_ticks = (ts->ts_ticks / (ts->ts_ltick - ts->ts_ftick)) *
18387295465eSAlexander Motin 		    (ts->ts_ltick - (t - SCHED_TICK_TARG));
18397295465eSAlexander Motin 		ts->ts_ftick = t - SCHED_TICK_TARG;
18407295465eSAlexander Motin 	}
18417295465eSAlexander Motin 	if (run)
18427295465eSAlexander Motin 		ts->ts_ticks += (t - ts->ts_ltick) << SCHED_TICK_SHIFT;
18437295465eSAlexander Motin 	ts->ts_ltick = t;
184435e6168fSJeff Roberson }
184535e6168fSJeff Roberson 
1846ae7a6b38SJeff Roberson /*
1847ae7a6b38SJeff Roberson  * Adjust the priority of a thread.  Move it to the appropriate run-queue
1848ae7a6b38SJeff Roberson  * if necessary.  This is the back-end for several priority related
1849ae7a6b38SJeff Roberson  * functions.
1850ae7a6b38SJeff Roberson  */
1851e7d50326SJeff Roberson static void
1852f5c157d9SJohn Baldwin sched_thread_priority(struct thread *td, u_char prio)
185335e6168fSJeff Roberson {
185473daf66fSJeff Roberson 	struct tdq *tdq;
185573daf66fSJeff Roberson 	int oldpri;
185635e6168fSJeff Roberson 
18578f51ad55SJeff Roberson 	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
18588f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, "new prio:%d", prio,
18598f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(curthread));
1860d9fae5abSAndriy Gapon 	SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
1861e87fc7cfSAndriy Gapon 	if (td != curthread && prio < td->td_priority) {
18628f51ad55SJeff Roberson 		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
18638f51ad55SJeff Roberson 		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
18648f51ad55SJeff Roberson 		    prio, KTR_ATTR_LINKED, sched_tdname(td));
1865d9fae5abSAndriy Gapon 		SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
1866b3e9e682SRyan Stone 		    curthread);
18678f51ad55SJeff Roberson 	}
18687b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1869f5c157d9SJohn Baldwin 	if (td->td_priority == prio)
1870f5c157d9SJohn Baldwin 		return;
18713f741ca1SJeff Roberson 	/*
18723f741ca1SJeff Roberson 	 * If the priority has been elevated due to priority
18733f741ca1SJeff Roberson 	 * propagation, we may have to move ourselves to a new
1874e7d50326SJeff Roberson 	 * queue.  This could be optimized to not re-add in some
1875e7d50326SJeff Roberson 	 * cases.
1876f2b74cbfSJeff Roberson 	 */
18776d55b3ecSJeff Roberson 	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1878e7d50326SJeff Roberson 		sched_rem(td);
1879e7d50326SJeff Roberson 		td->td_priority = prio;
188061a74c5cSJeff Roberson 		sched_add(td, SRQ_BORROWING | SRQ_HOLDTD);
188173daf66fSJeff Roberson 		return;
188273daf66fSJeff Roberson 	}
18836d55b3ecSJeff Roberson 	/*
18846d55b3ecSJeff Roberson 	 * If the thread is currently running we may have to adjust the lowpri
18856d55b3ecSJeff Roberson 	 * information so other cpus are aware of our current priority.
18866d55b3ecSJeff Roberson 	 */
18876d55b3ecSJeff Roberson 	if (TD_IS_RUNNING(td)) {
18884aec1984SJohn Baldwin 		tdq = TDQ_CPU(td_get_sched(td)->ts_cpu);
188962fa74d9SJeff Roberson 		oldpri = td->td_priority;
18903f741ca1SJeff Roberson 		td->td_priority = prio;
189162fa74d9SJeff Roberson 		if (prio < tdq->tdq_lowpri)
189262fa74d9SJeff Roberson 			tdq->tdq_lowpri = prio;
189362fa74d9SJeff Roberson 		else if (tdq->tdq_lowpri == oldpri)
189462fa74d9SJeff Roberson 			tdq_setlowpri(tdq, td);
18956d55b3ecSJeff Roberson 		return;
189673daf66fSJeff Roberson 	}
18976d55b3ecSJeff Roberson 	td->td_priority = prio;
1898ae7a6b38SJeff Roberson }
189935e6168fSJeff Roberson 
1900f5c157d9SJohn Baldwin /*
1901f5c157d9SJohn Baldwin  * Update a thread's priority when it is lent another thread's
1902f5c157d9SJohn Baldwin  * priority.
1903f5c157d9SJohn Baldwin  */
1904f5c157d9SJohn Baldwin void
1905f5c157d9SJohn Baldwin sched_lend_prio(struct thread *td, u_char prio)
1906f5c157d9SJohn Baldwin {
1907f5c157d9SJohn Baldwin 
1908f5c157d9SJohn Baldwin 	td->td_flags |= TDF_BORROWING;
1909f5c157d9SJohn Baldwin 	sched_thread_priority(td, prio);
1910f5c157d9SJohn Baldwin }
1911f5c157d9SJohn Baldwin 
1912f5c157d9SJohn Baldwin /*
1913f5c157d9SJohn Baldwin  * Restore a thread's priority when priority propagation is
1914f5c157d9SJohn Baldwin  * over.  The prio argument is the minimum priority the thread
1915f5c157d9SJohn Baldwin  * needs to have to satisfy other possible priority lending
1916f5c157d9SJohn Baldwin  * requests.  If the thread's regular priority is less
1917f5c157d9SJohn Baldwin  * important than prio, the thread will keep a priority boost
1918f5c157d9SJohn Baldwin  * of prio.
1919f5c157d9SJohn Baldwin  */
1920f5c157d9SJohn Baldwin void
1921f5c157d9SJohn Baldwin sched_unlend_prio(struct thread *td, u_char prio)
1922f5c157d9SJohn Baldwin {
1923f5c157d9SJohn Baldwin 	u_char base_pri;
1924f5c157d9SJohn Baldwin 
1925f5c157d9SJohn Baldwin 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1926f5c157d9SJohn Baldwin 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
19278460a577SJohn Birrell 		base_pri = td->td_user_pri;
1928f5c157d9SJohn Baldwin 	else
1929f5c157d9SJohn Baldwin 		base_pri = td->td_base_pri;
1930f5c157d9SJohn Baldwin 	if (prio >= base_pri) {
1931f5c157d9SJohn Baldwin 		td->td_flags &= ~TDF_BORROWING;
1932f5c157d9SJohn Baldwin 		sched_thread_priority(td, base_pri);
1933f5c157d9SJohn Baldwin 	} else
1934f5c157d9SJohn Baldwin 		sched_lend_prio(td, prio);
1935f5c157d9SJohn Baldwin }
1936f5c157d9SJohn Baldwin 
1937ae7a6b38SJeff Roberson /*
1938ae7a6b38SJeff Roberson  * Standard entry for setting the priority to an absolute value.
1939ae7a6b38SJeff Roberson  */
1940f5c157d9SJohn Baldwin void
1941f5c157d9SJohn Baldwin sched_prio(struct thread *td, u_char prio)
1942f5c157d9SJohn Baldwin {
1943f5c157d9SJohn Baldwin 	u_char oldprio;
1944f5c157d9SJohn Baldwin 
1945f5c157d9SJohn Baldwin 	/* First, update the base priority. */
1946f5c157d9SJohn Baldwin 	td->td_base_pri = prio;
1947f5c157d9SJohn Baldwin 
1948f5c157d9SJohn Baldwin 	/*
194950aaa791SJohn Baldwin 	 * If the thread is borrowing another thread's priority, don't
1950f5c157d9SJohn Baldwin 	 * ever lower the priority.
1951f5c157d9SJohn Baldwin 	 */
1952f5c157d9SJohn Baldwin 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1953f5c157d9SJohn Baldwin 		return;
1954f5c157d9SJohn Baldwin 
1955f5c157d9SJohn Baldwin 	/* Change the real priority. */
1956f5c157d9SJohn Baldwin 	oldprio = td->td_priority;
1957f5c157d9SJohn Baldwin 	sched_thread_priority(td, prio);
1958f5c157d9SJohn Baldwin 
1959f5c157d9SJohn Baldwin 	/*
1960f5c157d9SJohn Baldwin 	 * If the thread is on a turnstile, then let the turnstile update
1961f5c157d9SJohn Baldwin 	 * its state.
1962f5c157d9SJohn Baldwin 	 */
1963f5c157d9SJohn Baldwin 	if (TD_ON_LOCK(td) && oldprio != prio)
1964f5c157d9SJohn Baldwin 		turnstile_adjust(td, oldprio);
1965f5c157d9SJohn Baldwin }
1966f5c157d9SJohn Baldwin 
1967ae7a6b38SJeff Roberson /*
1968fea89a28SJohn Baldwin  * Set the base interrupt thread priority.
1969fea89a28SJohn Baldwin  */
1970fea89a28SJohn Baldwin void
1971fea89a28SJohn Baldwin sched_ithread_prio(struct thread *td, u_char prio)
1972fea89a28SJohn Baldwin {
1973fea89a28SJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1974fea89a28SJohn Baldwin 	MPASS(td->td_pri_class == PRI_ITHD);
1975fea89a28SJohn Baldwin 	td->td_base_ithread_pri = prio;
1976fea89a28SJohn Baldwin 	sched_prio(td, prio);
1977fea89a28SJohn Baldwin }
1978fea89a28SJohn Baldwin 
1979fea89a28SJohn Baldwin /*
1980ae7a6b38SJeff Roberson  * Set the base user priority, does not effect current running priority.
1981ae7a6b38SJeff Roberson  */
198235e6168fSJeff Roberson void
19838460a577SJohn Birrell sched_user_prio(struct thread *td, u_char prio)
19843db720fdSDavid Xu {
19853db720fdSDavid Xu 
19868460a577SJohn Birrell 	td->td_base_user_pri = prio;
1987acbe332aSDavid Xu 	if (td->td_lend_user_pri <= prio)
1988fc6c30f6SJulian Elischer 		return;
19898460a577SJohn Birrell 	td->td_user_pri = prio;
19903db720fdSDavid Xu }
19913db720fdSDavid Xu 
19923db720fdSDavid Xu void
19933db720fdSDavid Xu sched_lend_user_prio(struct thread *td, u_char prio)
19943db720fdSDavid Xu {
19953db720fdSDavid Xu 
1996435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1997acbe332aSDavid Xu 	td->td_lend_user_pri = prio;
1998c8e368a9SDavid Xu 	td->td_user_pri = min(prio, td->td_base_user_pri);
1999c8e368a9SDavid Xu 	if (td->td_priority > td->td_user_pri)
2000c8e368a9SDavid Xu 		sched_prio(td, td->td_user_pri);
2001c8e368a9SDavid Xu 	else if (td->td_priority != td->td_user_pri)
2002c6d31b83SKonstantin Belousov 		ast_sched_locked(td, TDA_SCHED);
2003435806d3SDavid Xu }
20043db720fdSDavid Xu 
2005ac97da9aSMateusz Guzik /*
2006ac97da9aSMateusz Guzik  * Like the above but first check if there is anything to do.
2007ac97da9aSMateusz Guzik  */
2008ac97da9aSMateusz Guzik void
2009ac97da9aSMateusz Guzik sched_lend_user_prio_cond(struct thread *td, u_char prio)
2010ac97da9aSMateusz Guzik {
2011ac97da9aSMateusz Guzik 
2012ac97da9aSMateusz Guzik 	if (td->td_lend_user_pri != prio)
2013ac97da9aSMateusz Guzik 		goto lend;
2014ac97da9aSMateusz Guzik 	if (td->td_user_pri != min(prio, td->td_base_user_pri))
2015ac97da9aSMateusz Guzik 		goto lend;
2016b77594bbSMateusz Guzik 	if (td->td_priority != td->td_user_pri)
2017ac97da9aSMateusz Guzik 		goto lend;
2018ac97da9aSMateusz Guzik 	return;
2019ac97da9aSMateusz Guzik 
2020ac97da9aSMateusz Guzik lend:
2021ac97da9aSMateusz Guzik 	thread_lock(td);
2022ac97da9aSMateusz Guzik 	sched_lend_user_prio(td, prio);
2023ac97da9aSMateusz Guzik 	thread_unlock(td);
2024ac97da9aSMateusz Guzik }
2025ac97da9aSMateusz Guzik 
20264c8a8cfcSKonstantin Belousov #ifdef SMP
2027ae7a6b38SJeff Roberson /*
202897e9382dSDon Lewis  * This tdq is about to idle.  Try to steal a thread from another CPU before
202997e9382dSDon Lewis  * choosing the idle thread.
203097e9382dSDon Lewis  */
203197e9382dSDon Lewis static void
203297e9382dSDon Lewis tdq_trysteal(struct tdq *tdq)
203397e9382dSDon Lewis {
20342668bb2aSAlexander Motin 	struct cpu_group *cg, *parent;
203597e9382dSDon Lewis 	struct tdq *steal;
203697e9382dSDon Lewis 	cpuset_t mask;
20372668bb2aSAlexander Motin 	int cpu, i, goup;
203897e9382dSDon Lewis 
203908063e9fSAlexander Motin 	if (smp_started == 0 || steal_idle == 0 || trysteal_limit == 0 ||
204008063e9fSAlexander Motin 	    tdq->tdq_cg == NULL)
204197e9382dSDon Lewis 		return;
204297e9382dSDon Lewis 	CPU_FILL(&mask);
204397e9382dSDon Lewis 	CPU_CLR(PCPU_GET(cpuid), &mask);
204497e9382dSDon Lewis 	/* We don't want to be preempted while we're iterating. */
204597e9382dSDon Lewis 	spinlock_enter();
204697e9382dSDon Lewis 	TDQ_UNLOCK(tdq);
20472668bb2aSAlexander Motin 	for (i = 1, cg = tdq->tdq_cg, goup = 0; ; ) {
204808063e9fSAlexander Motin 		cpu = sched_highest(cg, &mask, steal_thresh, 1);
204997e9382dSDon Lewis 		/*
205097e9382dSDon Lewis 		 * If a thread was added while interrupts were disabled don't
205197e9382dSDon Lewis 		 * steal one here.
205297e9382dSDon Lewis 		 */
205311484ad8SMark Johnston 		if (TDQ_LOAD(tdq) > 0) {
205497e9382dSDon Lewis 			TDQ_LOCK(tdq);
205597e9382dSDon Lewis 			break;
205697e9382dSDon Lewis 		}
20572668bb2aSAlexander Motin 
20582668bb2aSAlexander Motin 		/*
20592668bb2aSAlexander Motin 		 * We found no CPU to steal from in this group.  Escalate to
20602668bb2aSAlexander Motin 		 * the parent and repeat.  But if parent has only two children
20612668bb2aSAlexander Motin 		 * groups we can avoid searching this group again by searching
20622668bb2aSAlexander Motin 		 * the other one specifically and then escalating two levels.
20632668bb2aSAlexander Motin 		 */
206497e9382dSDon Lewis 		if (cpu == -1) {
20652668bb2aSAlexander Motin 			if (goup) {
206697e9382dSDon Lewis 				cg = cg->cg_parent;
20672668bb2aSAlexander Motin 				goup = 0;
20682668bb2aSAlexander Motin 			}
20692668bb2aSAlexander Motin 			if (++i > trysteal_limit) {
207097e9382dSDon Lewis 				TDQ_LOCK(tdq);
207197e9382dSDon Lewis 				break;
207297e9382dSDon Lewis 			}
20732668bb2aSAlexander Motin 			parent = cg->cg_parent;
20742668bb2aSAlexander Motin 			if (parent == NULL) {
20752668bb2aSAlexander Motin 				TDQ_LOCK(tdq);
20762668bb2aSAlexander Motin 				break;
20772668bb2aSAlexander Motin 			}
20782668bb2aSAlexander Motin 			if (parent->cg_children == 2) {
20792668bb2aSAlexander Motin 				if (cg == &parent->cg_child[0])
20802668bb2aSAlexander Motin 					cg = &parent->cg_child[1];
20812668bb2aSAlexander Motin 				else
20822668bb2aSAlexander Motin 					cg = &parent->cg_child[0];
20832668bb2aSAlexander Motin 				goup = 1;
20842668bb2aSAlexander Motin 			} else
20852668bb2aSAlexander Motin 				cg = parent;
208697e9382dSDon Lewis 			continue;
208797e9382dSDon Lewis 		}
208897e9382dSDon Lewis 		steal = TDQ_CPU(cpu);
208997e9382dSDon Lewis 		/*
209097e9382dSDon Lewis 		 * The data returned by sched_highest() is stale and
209197e9382dSDon Lewis 		 * the chosen CPU no longer has an eligible thread.
209215b5c347SGordon Bergling 		 * At this point unconditionally exit the loop to bound
209308063e9fSAlexander Motin 		 * the time spent in the critcal section.
209497e9382dSDon Lewis 		 */
209511484ad8SMark Johnston 		if (TDQ_LOAD(steal) < steal_thresh ||
209611484ad8SMark Johnston 		    TDQ_TRANSFERABLE(steal) == 0)
209797e9382dSDon Lewis 			continue;
209897e9382dSDon Lewis 		/*
20998bb173fbSAlexander Motin 		 * Try to lock both queues. If we are assigned a thread while
21008bb173fbSAlexander Motin 		 * waited for the lock, switch to it now instead of stealing.
21018bb173fbSAlexander Motin 		 * If we can't get the lock, then somebody likely got there
210208063e9fSAlexander Motin 		 * first.
210397e9382dSDon Lewis 		 */
21048bb173fbSAlexander Motin 		TDQ_LOCK(tdq);
21058bb173fbSAlexander Motin 		if (tdq->tdq_load > 0)
210697e9382dSDon Lewis 			break;
21078bb173fbSAlexander Motin 		if (TDQ_TRYLOCK_FLAGS(steal, MTX_DUPOK) == 0)
21088bb173fbSAlexander Motin 			break;
210997e9382dSDon Lewis 		/*
211097e9382dSDon Lewis 		 * The data returned by sched_highest() is stale and
211197e9382dSDon Lewis                  * the chosen CPU no longer has an eligible thread.
211297e9382dSDon Lewis 		 */
211311484ad8SMark Johnston 		if (TDQ_LOAD(steal) < steal_thresh ||
211411484ad8SMark Johnston 		    TDQ_TRANSFERABLE(steal) == 0) {
211597e9382dSDon Lewis 			TDQ_UNLOCK(steal);
211697e9382dSDon Lewis 			break;
211797e9382dSDon Lewis 		}
211897e9382dSDon Lewis 		/*
211997e9382dSDon Lewis 		 * If we fail to acquire one due to affinity restrictions,
212097e9382dSDon Lewis 		 * bail out and let the idle thread to a more complete search
212197e9382dSDon Lewis 		 * outside of a critical section.
212297e9382dSDon Lewis 		 */
21236d3f74a1SMark Johnston 		if (tdq_move(steal, tdq) == -1) {
212497e9382dSDon Lewis 			TDQ_UNLOCK(steal);
212597e9382dSDon Lewis 			break;
212697e9382dSDon Lewis 		}
212797e9382dSDon Lewis 		TDQ_UNLOCK(steal);
212897e9382dSDon Lewis 		break;
212997e9382dSDon Lewis 	}
213097e9382dSDon Lewis 	spinlock_exit();
213197e9382dSDon Lewis }
21324c8a8cfcSKonstantin Belousov #endif
213397e9382dSDon Lewis 
213497e9382dSDon Lewis /*
2135c47f202bSJeff Roberson  * Handle migration from sched_switch().  This happens only for
2136c47f202bSJeff Roberson  * cpu binding.
2137c47f202bSJeff Roberson  */
2138c47f202bSJeff Roberson static struct mtx *
2139c47f202bSJeff Roberson sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
2140c47f202bSJeff Roberson {
2141c47f202bSJeff Roberson 	struct tdq *tdn;
21426eeba7dbSMateusz Guzik #ifdef SMP
21436d3f74a1SMark Johnston 	int lowpri;
21446eeba7dbSMateusz Guzik #endif
2145c47f202bSJeff Roberson 
2146686bcb5cSJeff Roberson 	KASSERT(THREAD_CAN_MIGRATE(td) ||
2147686bcb5cSJeff Roberson 	    (td_get_sched(td)->ts_flags & TSF_BOUND) != 0,
2148686bcb5cSJeff Roberson 	    ("Thread %p shouldn't migrate", td));
2149efe67753SNathan Whitehorn 	KASSERT(!CPU_ABSENT(td_get_sched(td)->ts_cpu), ("sched_switch_migrate: "
2150efe67753SNathan Whitehorn 	    "thread %s queued on absent CPU %d.", td->td_name,
2151efe67753SNathan Whitehorn 	    td_get_sched(td)->ts_cpu));
215293ccd6bfSKonstantin Belousov 	tdn = TDQ_CPU(td_get_sched(td)->ts_cpu);
2153c47f202bSJeff Roberson #ifdef SMP
21549727e637SJeff Roberson 	tdq_load_rem(tdq, td);
2155c47f202bSJeff Roberson 	/*
2156686bcb5cSJeff Roberson 	 * Do the lock dance required to avoid LOR.  We have an
2157686bcb5cSJeff Roberson 	 * extra spinlock nesting from sched_switch() which will
2158686bcb5cSJeff Roberson 	 * prevent preemption while we're holding neither run-queue lock.
2159c47f202bSJeff Roberson 	 */
2160686bcb5cSJeff Roberson 	TDQ_UNLOCK(tdq);
2161686bcb5cSJeff Roberson 	TDQ_LOCK(tdn);
21626d3f74a1SMark Johnston 	lowpri = tdq_add(tdn, td, flags);
21636d3f74a1SMark Johnston 	tdq_notify(tdn, lowpri);
2164c47f202bSJeff Roberson 	TDQ_UNLOCK(tdn);
2165686bcb5cSJeff Roberson 	TDQ_LOCK(tdq);
2166c47f202bSJeff Roberson #endif
2167c47f202bSJeff Roberson 	return (TDQ_LOCKPTR(tdn));
2168c47f202bSJeff Roberson }
2169c47f202bSJeff Roberson 
2170c47f202bSJeff Roberson /*
217161a74c5cSJeff Roberson  * thread_lock_unblock() that does not assume td_lock is blocked.
2172ae7a6b38SJeff Roberson  */
2173ae7a6b38SJeff Roberson static inline void
2174ae7a6b38SJeff Roberson thread_unblock_switch(struct thread *td, struct mtx *mtx)
2175ae7a6b38SJeff Roberson {
2176ae7a6b38SJeff Roberson 	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
2177ae7a6b38SJeff Roberson 	    (uintptr_t)mtx);
2178ae7a6b38SJeff Roberson }
2179ae7a6b38SJeff Roberson 
2180ae7a6b38SJeff Roberson /*
2181ae7a6b38SJeff Roberson  * Switch threads.  This function has to handle threads coming in while
2182ae7a6b38SJeff Roberson  * blocked for some reason, running, or idle.  It also must deal with
2183ae7a6b38SJeff Roberson  * migrating a thread from one queue to another as running threads may
2184ae7a6b38SJeff Roberson  * be assigned elsewhere via binding.
2185ae7a6b38SJeff Roberson  */
21863db720fdSDavid Xu void
2187686bcb5cSJeff Roberson sched_switch(struct thread *td, int flags)
218835e6168fSJeff Roberson {
2189686bcb5cSJeff Roberson 	struct thread *newtd;
2190c02bbb43SJeff Roberson 	struct tdq *tdq;
2191ad1e7d28SJulian Elischer 	struct td_sched *ts;
2192ae7a6b38SJeff Roberson 	struct mtx *mtx;
2193c47f202bSJeff Roberson 	int srqflag;
21948db16699SAlexander Motin 	int cpuid, preempted;
21958db16699SAlexander Motin #ifdef SMP
21968db16699SAlexander Motin 	int pickcpu;
21978db16699SAlexander Motin #endif
219835e6168fSJeff Roberson 
21997b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
220035e6168fSJeff Roberson 
2201ae7a6b38SJeff Roberson 	cpuid = PCPU_GET(cpuid);
2202018ff686SJeff Roberson 	tdq = TDQ_SELF();
220393ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
22047295465eSAlexander Motin 	sched_pctcpu_update(ts, 1);
22058db16699SAlexander Motin #ifdef SMP
2206e745d729SAlexander Motin 	pickcpu = (td->td_flags & TDF_PICKCPU) != 0;
2207e745d729SAlexander Motin 	if (pickcpu)
2208e745d729SAlexander Motin 		ts->ts_rltick = ticks - affinity * MAX_CACHE_LEVELS;
2209e745d729SAlexander Motin 	else
2210ae7a6b38SJeff Roberson 		ts->ts_rltick = ticks;
22118db16699SAlexander Motin #endif
2212060563ecSJulian Elischer 	td->td_lastcpu = td->td_oncpu;
2213ad9dadc4SAndriy Gapon 	preempted = (td->td_flags & TDF_SLICEEND) == 0 &&
2214ad9dadc4SAndriy Gapon 	    (flags & SW_PREEMPT) != 0;
2215c6d31b83SKonstantin Belousov 	td->td_flags &= ~(TDF_PICKCPU | TDF_SLICEEND);
2216c6d31b83SKonstantin Belousov 	ast_unsched_locked(td, TDA_SCHED);
221777918643SStephan Uphoff 	td->td_owepreempt = 0;
221811484ad8SMark Johnston 	atomic_store_char(&tdq->tdq_owepreempt, 0);
22192c27cb3aSAlexander Motin 	if (!TD_IS_IDLETHREAD(td))
222011484ad8SMark Johnston 		TDQ_SWITCHCNT_INC(tdq);
22217789ab32SMark Johnston 
2222b11fdad0SJeff Roberson 	/*
2223686bcb5cSJeff Roberson 	 * Always block the thread lock so we can drop the tdq lock early.
2224b11fdad0SJeff Roberson 	 */
2225686bcb5cSJeff Roberson 	mtx = thread_lock_block(td);
2226686bcb5cSJeff Roberson 	spinlock_enter();
2227486a9414SJulian Elischer 	if (TD_IS_IDLETHREAD(td)) {
2228686bcb5cSJeff Roberson 		MPASS(mtx == TDQ_LOCKPTR(tdq));
2229bf0acc27SJohn Baldwin 		TD_SET_CAN_RUN(td);
22307b20fb19SJeff Roberson 	} else if (TD_IS_RUNNING(td)) {
2231686bcb5cSJeff Roberson 		MPASS(mtx == TDQ_LOCKPTR(tdq));
22323d7f4117SAlexander Motin 		srqflag = preempted ?
2233598b368dSJeff Roberson 		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
2234c47f202bSJeff Roberson 		    SRQ_OURSELF|SRQ_YIELDING;
2235ba4932b5SMatthew D Fleming #ifdef SMP
2236e745d729SAlexander Motin 		if (THREAD_CAN_MIGRATE(td) && (!THREAD_CAN_SCHED(td, ts->ts_cpu)
2237e745d729SAlexander Motin 		    || pickcpu))
22380f7a0ebdSMatthew D Fleming 			ts->ts_cpu = sched_pickcpu(td, 0);
2239ba4932b5SMatthew D Fleming #endif
2240c47f202bSJeff Roberson 		if (ts->ts_cpu == cpuid)
22419727e637SJeff Roberson 			tdq_runq_add(tdq, td, srqflag);
2242686bcb5cSJeff Roberson 		else
2243c47f202bSJeff Roberson 			mtx = sched_switch_migrate(tdq, td, srqflag);
2244ae7a6b38SJeff Roberson 	} else {
2245ae7a6b38SJeff Roberson 		/* This thread must be going to sleep. */
224661a74c5cSJeff Roberson 		if (mtx != TDQ_LOCKPTR(tdq)) {
224761a74c5cSJeff Roberson 			mtx_unlock_spin(mtx);
224861a74c5cSJeff Roberson 			TDQ_LOCK(tdq);
224961a74c5cSJeff Roberson 		}
22509727e637SJeff Roberson 		tdq_load_rem(tdq, td);
22514c8a8cfcSKonstantin Belousov #ifdef SMP
225297e9382dSDon Lewis 		if (tdq->tdq_load == 0)
225397e9382dSDon Lewis 			tdq_trysteal(tdq);
22544c8a8cfcSKonstantin Belousov #endif
2255ae7a6b38SJeff Roberson 	}
2256afa0a46cSAndriy Gapon 
2257afa0a46cSAndriy Gapon #if (KTR_COMPILE & KTR_SCHED) != 0
2258afa0a46cSAndriy Gapon 	if (TD_IS_IDLETHREAD(td))
2259afa0a46cSAndriy Gapon 		KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle",
2260afa0a46cSAndriy Gapon 		    "prio:%d", td->td_priority);
2261afa0a46cSAndriy Gapon 	else
2262afa0a46cSAndriy Gapon 		KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td),
2263afa0a46cSAndriy Gapon 		    "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg,
2264afa0a46cSAndriy Gapon 		    "lockname:\"%s\"", td->td_lockname);
2265afa0a46cSAndriy Gapon #endif
2266afa0a46cSAndriy Gapon 
2267ae7a6b38SJeff Roberson 	/*
2268ae7a6b38SJeff Roberson 	 * We enter here with the thread blocked and assigned to the
2269ae7a6b38SJeff Roberson 	 * appropriate cpu run-queue or sleep-queue and with the current
2270ae7a6b38SJeff Roberson 	 * thread-queue locked.
2271ae7a6b38SJeff Roberson 	 */
2272ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
22736d3f74a1SMark Johnston 	MPASS(td == tdq->tdq_curthread);
22742454aaf5SJeff Roberson 	newtd = choosethread();
2275686bcb5cSJeff Roberson 	sched_pctcpu_update(td_get_sched(newtd), 0);
2276686bcb5cSJeff Roberson 	TDQ_UNLOCK(tdq);
2277686bcb5cSJeff Roberson 
2278ae7a6b38SJeff Roberson 	/*
2279ae7a6b38SJeff Roberson 	 * Call the MD code to switch contexts if necessary.
2280ae7a6b38SJeff Roberson 	 */
2281ebccf1e3SJoseph Koshy 	if (td != newtd) {
2282ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
2283ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
2284ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
2285ebccf1e3SJoseph Koshy #endif
2286d9fae5abSAndriy Gapon 		SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
22876f5f25e5SJohn Birrell 
22886f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
22896f5f25e5SJohn Birrell 		/*
22906f5f25e5SJohn Birrell 		 * If DTrace has set the active vtime enum to anything
22916f5f25e5SJohn Birrell 		 * other than INACTIVE (0), then it should have set the
22926f5f25e5SJohn Birrell 		 * function to call.
22936f5f25e5SJohn Birrell 		 */
22946f5f25e5SJohn Birrell 		if (dtrace_vtime_active)
22956f5f25e5SJohn Birrell 			(*dtrace_vtime_switch_func)(newtd);
22966f5f25e5SJohn Birrell #endif
2297686bcb5cSJeff Roberson 		td->td_oncpu = NOCPU;
2298ae7a6b38SJeff Roberson 		cpu_switch(td, newtd, mtx);
2299a89c2c8cSMark Johnston 		cpuid = td->td_oncpu = PCPU_GET(cpuid);
2300b3e9e682SRyan Stone 
2301d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , on__cpu);
2302ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
2303ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
2304ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
2305ebccf1e3SJoseph Koshy #endif
2306b3e9e682SRyan Stone 	} else {
2307ae7a6b38SJeff Roberson 		thread_unblock_switch(td, mtx);
2308d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , remain__cpu);
2309b3e9e682SRyan Stone 	}
2310686bcb5cSJeff Roberson 	KASSERT(curthread->td_md.md_spinlock_count == 1,
2311686bcb5cSJeff Roberson 	    ("invalid count %d", curthread->td_md.md_spinlock_count));
2312afa0a46cSAndriy Gapon 
2313afa0a46cSAndriy Gapon 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
2314afa0a46cSAndriy Gapon 	    "prio:%d", td->td_priority);
231535e6168fSJeff Roberson }
231635e6168fSJeff Roberson 
2317ae7a6b38SJeff Roberson /*
2318ae7a6b38SJeff Roberson  * Adjust thread priorities as a result of a nice request.
2319ae7a6b38SJeff Roberson  */
232035e6168fSJeff Roberson void
2321fa885116SJulian Elischer sched_nice(struct proc *p, int nice)
232235e6168fSJeff Roberson {
232335e6168fSJeff Roberson 	struct thread *td;
232435e6168fSJeff Roberson 
2325fa885116SJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
2326e7d50326SJeff Roberson 
2327fa885116SJulian Elischer 	p->p_nice = nice;
23288460a577SJohn Birrell 	FOREACH_THREAD_IN_PROC(p, td) {
23297b20fb19SJeff Roberson 		thread_lock(td);
23308460a577SJohn Birrell 		sched_priority(td);
2331e7d50326SJeff Roberson 		sched_prio(td, td->td_base_user_pri);
23327b20fb19SJeff Roberson 		thread_unlock(td);
233335e6168fSJeff Roberson 	}
2334fa885116SJulian Elischer }
233535e6168fSJeff Roberson 
2336ae7a6b38SJeff Roberson /*
2337ae7a6b38SJeff Roberson  * Record the sleep time for the interactivity scorer.
2338ae7a6b38SJeff Roberson  */
233935e6168fSJeff Roberson void
2340c5aa6b58SJeff Roberson sched_sleep(struct thread *td, int prio)
234135e6168fSJeff Roberson {
2342e7d50326SJeff Roberson 
23437b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
234435e6168fSJeff Roberson 
234554b0e65fSJeff Roberson 	td->td_slptick = ticks;
234617c4c356SKonstantin Belousov 	if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
2347c5aa6b58SJeff Roberson 		td->td_flags |= TDF_CANSWAP;
23482dc29adbSJohn Baldwin 	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
23492dc29adbSJohn Baldwin 		return;
23500502fe2eSJeff Roberson 	if (static_boost == 1 && prio)
2351c5aa6b58SJeff Roberson 		sched_prio(td, prio);
23520502fe2eSJeff Roberson 	else if (static_boost && td->td_priority > static_boost)
23530502fe2eSJeff Roberson 		sched_prio(td, static_boost);
235435e6168fSJeff Roberson }
235535e6168fSJeff Roberson 
2356ae7a6b38SJeff Roberson /*
2357ae7a6b38SJeff Roberson  * Schedule a thread to resume execution and record how long it voluntarily
2358ae7a6b38SJeff Roberson  * slept.  We also update the pctcpu, interactivity, and priority.
235961a74c5cSJeff Roberson  *
236061a74c5cSJeff Roberson  * Requires the thread lock on entry, drops on exit.
2361ae7a6b38SJeff Roberson  */
236235e6168fSJeff Roberson void
236361a74c5cSJeff Roberson sched_wakeup(struct thread *td, int srqflags)
236435e6168fSJeff Roberson {
236514618990SJeff Roberson 	struct td_sched *ts;
2366ae7a6b38SJeff Roberson 	int slptick;
2367e7d50326SJeff Roberson 
23687b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
236993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
2370c5aa6b58SJeff Roberson 	td->td_flags &= ~TDF_CANSWAP;
237161a74c5cSJeff Roberson 
237235e6168fSJeff Roberson 	/*
2373e7d50326SJeff Roberson 	 * If we slept for more than a tick update our interactivity and
2374e7d50326SJeff Roberson 	 * priority.
237535e6168fSJeff Roberson 	 */
237654b0e65fSJeff Roberson 	slptick = td->td_slptick;
237754b0e65fSJeff Roberson 	td->td_slptick = 0;
2378ae7a6b38SJeff Roberson 	if (slptick && slptick != ticks) {
23797295465eSAlexander Motin 		ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
23808460a577SJohn Birrell 		sched_interact_update(td);
23817295465eSAlexander Motin 		sched_pctcpu_update(ts, 0);
2382f1e8dc4aSJeff Roberson 	}
2383954cffe9SJohn Baldwin 
2384954cffe9SJohn Baldwin 	/*
2385954cffe9SJohn Baldwin 	 * When resuming an idle ithread, restore its base ithread
2386954cffe9SJohn Baldwin 	 * priority.
2387954cffe9SJohn Baldwin 	 */
2388954cffe9SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) == PRI_ITHD &&
2389954cffe9SJohn Baldwin 	    td->td_priority != td->td_base_ithread_pri)
2390954cffe9SJohn Baldwin 		sched_prio(td, td->td_base_ithread_pri);
2391954cffe9SJohn Baldwin 
23925e5c3873SJeff Roberson 	/*
23935e5c3873SJeff Roberson 	 * Reset the slice value since we slept and advanced the round-robin.
23945e5c3873SJeff Roberson 	 */
23955e5c3873SJeff Roberson 	ts->ts_slice = 0;
239661a74c5cSJeff Roberson 	sched_add(td, SRQ_BORING | srqflags);
239735e6168fSJeff Roberson }
239835e6168fSJeff Roberson 
239935e6168fSJeff Roberson /*
240035e6168fSJeff Roberson  * Penalize the parent for creating a new child and initialize the child's
240135e6168fSJeff Roberson  * priority.
240235e6168fSJeff Roberson  */
240335e6168fSJeff Roberson void
24048460a577SJohn Birrell sched_fork(struct thread *td, struct thread *child)
240515dc847eSJeff Roberson {
24067b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
240793ccd6bfSKonstantin Belousov 	sched_pctcpu_update(td_get_sched(td), 1);
2408ad1e7d28SJulian Elischer 	sched_fork_thread(td, child);
2409e7d50326SJeff Roberson 	/*
2410e7d50326SJeff Roberson 	 * Penalize the parent and child for forking.
2411e7d50326SJeff Roberson 	 */
2412e7d50326SJeff Roberson 	sched_interact_fork(child);
2413e7d50326SJeff Roberson 	sched_priority(child);
241493ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_runtime += tickincr;
2415e7d50326SJeff Roberson 	sched_interact_update(td);
2416e7d50326SJeff Roberson 	sched_priority(td);
2417ad1e7d28SJulian Elischer }
2418ad1e7d28SJulian Elischer 
2419ae7a6b38SJeff Roberson /*
2420ae7a6b38SJeff Roberson  * Fork a new thread, may be within the same process.
2421ae7a6b38SJeff Roberson  */
2422ad1e7d28SJulian Elischer void
2423ad1e7d28SJulian Elischer sched_fork_thread(struct thread *td, struct thread *child)
2424ad1e7d28SJulian Elischer {
2425ad1e7d28SJulian Elischer 	struct td_sched *ts;
2426ad1e7d28SJulian Elischer 	struct td_sched *ts2;
24275e5c3873SJeff Roberson 	struct tdq *tdq;
24288460a577SJohn Birrell 
24295e5c3873SJeff Roberson 	tdq = TDQ_SELF();
24308b16c208SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2431e7d50326SJeff Roberson 	/*
2432e7d50326SJeff Roberson 	 * Initialize child.
2433e7d50326SJeff Roberson 	 */
243493ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
243593ccd6bfSKonstantin Belousov 	ts2 = td_get_sched(child);
243692de34dfSJohn Baldwin 	child->td_oncpu = NOCPU;
243792de34dfSJohn Baldwin 	child->td_lastcpu = NOCPU;
24385e5c3873SJeff Roberson 	child->td_lock = TDQ_LOCKPTR(tdq);
24398b16c208SJeff Roberson 	child->td_cpuset = cpuset_ref(td->td_cpuset);
24403f289c3fSJeff Roberson 	child->td_domain.dr_policy = td->td_cpuset->cs_domain;
2441ad1e7d28SJulian Elischer 	ts2->ts_cpu = ts->ts_cpu;
24428b16c208SJeff Roberson 	ts2->ts_flags = 0;
2443e7d50326SJeff Roberson 	/*
244422d19207SJohn Baldwin 	 * Grab our parents cpu estimation information.
2445e7d50326SJeff Roberson 	 */
2446ad1e7d28SJulian Elischer 	ts2->ts_ticks = ts->ts_ticks;
2447ad1e7d28SJulian Elischer 	ts2->ts_ltick = ts->ts_ltick;
2448ad1e7d28SJulian Elischer 	ts2->ts_ftick = ts->ts_ftick;
244922d19207SJohn Baldwin 	/*
245022d19207SJohn Baldwin 	 * Do not inherit any borrowed priority from the parent.
245122d19207SJohn Baldwin 	 */
245222d19207SJohn Baldwin 	child->td_priority = child->td_base_pri;
2453e7d50326SJeff Roberson 	/*
2454e7d50326SJeff Roberson 	 * And update interactivity score.
2455e7d50326SJeff Roberson 	 */
2456ae7a6b38SJeff Roberson 	ts2->ts_slptime = ts->ts_slptime;
2457ae7a6b38SJeff Roberson 	ts2->ts_runtime = ts->ts_runtime;
24585e5c3873SJeff Roberson 	/* Attempt to quickly learn interactivity. */
24595e5c3873SJeff Roberson 	ts2->ts_slice = tdq_slice(tdq) - sched_slice_min;
24608f51ad55SJeff Roberson #ifdef KTR
24618f51ad55SJeff Roberson 	bzero(ts2->ts_name, sizeof(ts2->ts_name));
24628f51ad55SJeff Roberson #endif
246315dc847eSJeff Roberson }
246415dc847eSJeff Roberson 
2465ae7a6b38SJeff Roberson /*
2466ae7a6b38SJeff Roberson  * Adjust the priority class of a thread.
2467ae7a6b38SJeff Roberson  */
246815dc847eSJeff Roberson void
24698460a577SJohn Birrell sched_class(struct thread *td, int class)
247015dc847eSJeff Roberson {
247115dc847eSJeff Roberson 
24727b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
24738460a577SJohn Birrell 	if (td->td_pri_class == class)
247415dc847eSJeff Roberson 		return;
24758460a577SJohn Birrell 	td->td_pri_class = class;
247635e6168fSJeff Roberson }
247735e6168fSJeff Roberson 
247835e6168fSJeff Roberson /*
247935e6168fSJeff Roberson  * Return some of the child's priority and interactivity to the parent.
248035e6168fSJeff Roberson  */
248135e6168fSJeff Roberson void
2482fc6c30f6SJulian Elischer sched_exit(struct proc *p, struct thread *child)
248335e6168fSJeff Roberson {
2484e7d50326SJeff Roberson 	struct thread *td;
2485141ad61cSJeff Roberson 
24868f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2487cd39bb09SXin LI 	    "prio:%d", child->td_priority);
2488374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
2489e7d50326SJeff Roberson 	td = FIRST_THREAD_IN_PROC(p);
2490e7d50326SJeff Roberson 	sched_exit_thread(td, child);
2491ad1e7d28SJulian Elischer }
2492ad1e7d28SJulian Elischer 
2493ae7a6b38SJeff Roberson /*
2494ae7a6b38SJeff Roberson  * Penalize another thread for the time spent on this one.  This helps to
2495ae7a6b38SJeff Roberson  * worsen the priority and interactivity of processes which schedule batch
2496ae7a6b38SJeff Roberson  * jobs such as make.  This has little effect on the make process itself but
2497ae7a6b38SJeff Roberson  * causes new processes spawned by it to receive worse scores immediately.
2498ae7a6b38SJeff Roberson  */
2499ad1e7d28SJulian Elischer void
2500fc6c30f6SJulian Elischer sched_exit_thread(struct thread *td, struct thread *child)
2501ad1e7d28SJulian Elischer {
2502fc6c30f6SJulian Elischer 
25038f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2504cd39bb09SXin LI 	    "prio:%d", child->td_priority);
2505e7d50326SJeff Roberson 	/*
2506e7d50326SJeff Roberson 	 * Give the child's runtime to the parent without returning the
2507e7d50326SJeff Roberson 	 * sleep time as a penalty to the parent.  This causes shells that
2508e7d50326SJeff Roberson 	 * launch expensive things to mark their children as expensive.
2509e7d50326SJeff Roberson 	 */
25107b20fb19SJeff Roberson 	thread_lock(td);
251193ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_runtime += td_get_sched(child)->ts_runtime;
2512fc6c30f6SJulian Elischer 	sched_interact_update(td);
2513e7d50326SJeff Roberson 	sched_priority(td);
25147b20fb19SJeff Roberson 	thread_unlock(td);
2515ad1e7d28SJulian Elischer }
2516ad1e7d28SJulian Elischer 
2517ff256d9cSJeff Roberson void
2518ff256d9cSJeff Roberson sched_preempt(struct thread *td)
2519ff256d9cSJeff Roberson {
2520ff256d9cSJeff Roberson 	struct tdq *tdq;
2521686bcb5cSJeff Roberson 	int flags;
2522ff256d9cSJeff Roberson 
2523b3e9e682SRyan Stone 	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
2524b3e9e682SRyan Stone 
2525ff256d9cSJeff Roberson 	thread_lock(td);
2526ff256d9cSJeff Roberson 	tdq = TDQ_SELF();
2527ff256d9cSJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2528ff256d9cSJeff Roberson 	if (td->td_priority > tdq->tdq_lowpri) {
2529686bcb5cSJeff Roberson 		if (td->td_critnest == 1) {
25308df78c41SJeff Roberson 			flags = SW_INVOL | SW_PREEMPT;
2531686bcb5cSJeff Roberson 			flags |= TD_IS_IDLETHREAD(td) ? SWT_REMOTEWAKEIDLE :
2532686bcb5cSJeff Roberson 			    SWT_REMOTEPREEMPT;
2533686bcb5cSJeff Roberson 			mi_switch(flags);
2534686bcb5cSJeff Roberson 			/* Switch dropped thread lock. */
2535686bcb5cSJeff Roberson 			return;
2536686bcb5cSJeff Roberson 		}
2537ff256d9cSJeff Roberson 		td->td_owepreempt = 1;
25387789ab32SMark Johnston 	} else {
25397789ab32SMark Johnston 		tdq->tdq_owepreempt = 0;
2540ff256d9cSJeff Roberson 	}
2541ff256d9cSJeff Roberson 	thread_unlock(td);
2542ff256d9cSJeff Roberson }
2543ff256d9cSJeff Roberson 
2544ae7a6b38SJeff Roberson /*
2545ae7a6b38SJeff Roberson  * Fix priorities on return to user-space.  Priorities may be elevated due
2546ae7a6b38SJeff Roberson  * to static priorities in msleep() or similar.
2547ae7a6b38SJeff Roberson  */
2548ad1e7d28SJulian Elischer void
254928240885SMateusz Guzik sched_userret_slowpath(struct thread *td)
2550ad1e7d28SJulian Elischer {
255128240885SMateusz Guzik 
25527b20fb19SJeff Roberson 	thread_lock(td);
2553ad1e7d28SJulian Elischer 	td->td_priority = td->td_user_pri;
2554ad1e7d28SJulian Elischer 	td->td_base_pri = td->td_user_pri;
255562fa74d9SJeff Roberson 	tdq_setlowpri(TDQ_SELF(), td);
25567b20fb19SJeff Roberson 	thread_unlock(td);
2557ad1e7d28SJulian Elischer }
255835e6168fSJeff Roberson 
2559954cffe9SJohn Baldwin SCHED_STAT_DEFINE(ithread_demotions, "Interrupt thread priority demotions");
2560954cffe9SJohn Baldwin SCHED_STAT_DEFINE(ithread_preemptions,
2561954cffe9SJohn Baldwin     "Interrupt thread preemptions due to time-sharing");
2562954cffe9SJohn Baldwin 
2563954cffe9SJohn Baldwin /*
2564954cffe9SJohn Baldwin  * Return time slice for a given thread.  For ithreads this is
2565954cffe9SJohn Baldwin  * sched_slice.  For other threads it is tdq_slice(tdq).
2566954cffe9SJohn Baldwin  */
2567954cffe9SJohn Baldwin static inline int
2568954cffe9SJohn Baldwin td_slice(struct thread *td, struct tdq *tdq)
2569954cffe9SJohn Baldwin {
2570954cffe9SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) == PRI_ITHD)
2571954cffe9SJohn Baldwin 		return (sched_slice);
2572954cffe9SJohn Baldwin 	return (tdq_slice(tdq));
2573954cffe9SJohn Baldwin }
2574954cffe9SJohn Baldwin 
2575ae7a6b38SJeff Roberson /*
2576ae7a6b38SJeff Roberson  * Handle a stathz tick.  This is really only relevant for timeshare
2577954cffe9SJohn Baldwin  * and interrupt threads.
2578ae7a6b38SJeff Roberson  */
257935e6168fSJeff Roberson void
2580c3cccf95SJeff Roberson sched_clock(struct thread *td, int cnt)
258135e6168fSJeff Roberson {
2582ad1e7d28SJulian Elischer 	struct tdq *tdq;
2583ad1e7d28SJulian Elischer 	struct td_sched *ts;
258435e6168fSJeff Roberson 
2585ae7a6b38SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
25863f872f85SJeff Roberson 	tdq = TDQ_SELF();
25877fcf154aSJeff Roberson #ifdef SMP
25887fcf154aSJeff Roberson 	/*
25897fcf154aSJeff Roberson 	 * We run the long term load balancer infrequently on the first cpu.
25907fcf154aSJeff Roberson 	 */
2591c3cccf95SJeff Roberson 	if (balance_tdq == tdq && smp_started != 0 && rebalance != 0 &&
2592c3cccf95SJeff Roberson 	    balance_ticks != 0) {
2593c3cccf95SJeff Roberson 		balance_ticks -= cnt;
2594c3cccf95SJeff Roberson 		if (balance_ticks <= 0)
25957fcf154aSJeff Roberson 			sched_balance();
25967fcf154aSJeff Roberson 	}
25977fcf154aSJeff Roberson #endif
25983f872f85SJeff Roberson 	/*
25991690c6c1SJeff Roberson 	 * Save the old switch count so we have a record of the last ticks
26001690c6c1SJeff Roberson 	 * activity.   Initialize the new switch count based on our load.
26011690c6c1SJeff Roberson 	 * If there is some activity seed it to reflect that.
26021690c6c1SJeff Roberson 	 */
26031690c6c1SJeff Roberson 	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
26046c47aaaeSJeff Roberson 	tdq->tdq_switchcnt = tdq->tdq_load;
260511484ad8SMark Johnston 
26061690c6c1SJeff Roberson 	/*
26073f872f85SJeff Roberson 	 * Advance the insert index once for each tick to ensure that all
26083f872f85SJeff Roberson 	 * threads get a chance to run.
26093f872f85SJeff Roberson 	 */
26103f872f85SJeff Roberson 	if (tdq->tdq_idx == tdq->tdq_ridx) {
26113f872f85SJeff Roberson 		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
26123f872f85SJeff Roberson 		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
26133f872f85SJeff Roberson 			tdq->tdq_ridx = tdq->tdq_idx;
26143f872f85SJeff Roberson 	}
261593ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
26167295465eSAlexander Motin 	sched_pctcpu_update(ts, 1);
2617c3cccf95SJeff Roberson 	if ((td->td_pri_class & PRI_FIFO_BIT) || TD_IS_IDLETHREAD(td))
2618a8949de2SJeff Roberson 		return;
2619c3cccf95SJeff Roberson 
2620c9a8cba4SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2621a8949de2SJeff Roberson 		/*
2622fd0b8c78SJeff Roberson 		 * We used a tick; charge it to the thread so
2623fd0b8c78SJeff Roberson 		 * that we can compute our interactivity.
262415dc847eSJeff Roberson 		 */
2625c3cccf95SJeff Roberson 		td_get_sched(td)->ts_runtime += tickincr * cnt;
26268460a577SJohn Birrell 		sched_interact_update(td);
262773daf66fSJeff Roberson 		sched_priority(td);
2628fd0b8c78SJeff Roberson 	}
2629579895dfSAlexander Motin 
263035e6168fSJeff Roberson 	/*
2631579895dfSAlexander Motin 	 * Force a context switch if the current thread has used up a full
2632579895dfSAlexander Motin 	 * time slice (default is 100ms).
263335e6168fSJeff Roberson 	 */
2634c3cccf95SJeff Roberson 	ts->ts_slice += cnt;
2635954cffe9SJohn Baldwin 	if (ts->ts_slice >= td_slice(td, tdq)) {
26365e5c3873SJeff Roberson 		ts->ts_slice = 0;
2637954cffe9SJohn Baldwin 
2638954cffe9SJohn Baldwin 		/*
2639954cffe9SJohn Baldwin 		 * If an ithread uses a full quantum, demote its
2640954cffe9SJohn Baldwin 		 * priority and preempt it.
2641954cffe9SJohn Baldwin 		 */
2642954cffe9SJohn Baldwin 		if (PRI_BASE(td->td_pri_class) == PRI_ITHD) {
2643954cffe9SJohn Baldwin 			SCHED_STAT_INC(ithread_preemptions);
2644954cffe9SJohn Baldwin 			td->td_owepreempt = 1;
2645954cffe9SJohn Baldwin 			if (td->td_base_pri + RQ_PPQ < PRI_MAX_ITHD) {
2646954cffe9SJohn Baldwin 				SCHED_STAT_INC(ithread_demotions);
2647954cffe9SJohn Baldwin 				sched_prio(td, td->td_base_pri + RQ_PPQ);
2648954cffe9SJohn Baldwin 			}
2649c6d31b83SKonstantin Belousov 		} else {
2650c6d31b83SKonstantin Belousov 			ast_sched_locked(td, TDA_SCHED);
2651c6d31b83SKonstantin Belousov 			td->td_flags |= TDF_SLICEEND;
2652c6d31b83SKonstantin Belousov 		}
265335e6168fSJeff Roberson 	}
2654579895dfSAlexander Motin }
265535e6168fSJeff Roberson 
2656ccd0ec40SKonstantin Belousov u_int
2657ccd0ec40SKonstantin Belousov sched_estcpu(struct thread *td __unused)
2658ae7a6b38SJeff Roberson {
2659ae7a6b38SJeff Roberson 
2660ccd0ec40SKonstantin Belousov 	return (0);
2661ae7a6b38SJeff Roberson }
2662ae7a6b38SJeff Roberson 
2663ae7a6b38SJeff Roberson /*
2664ae7a6b38SJeff Roberson  * Return whether the current CPU has runnable tasks.  Used for in-kernel
2665ae7a6b38SJeff Roberson  * cooperative idle threads.
2666ae7a6b38SJeff Roberson  */
266735e6168fSJeff Roberson int
266835e6168fSJeff Roberson sched_runnable(void)
266935e6168fSJeff Roberson {
2670ad1e7d28SJulian Elischer 	struct tdq *tdq;
2671b90816f1SJeff Roberson 	int load;
267235e6168fSJeff Roberson 
2673b90816f1SJeff Roberson 	load = 1;
2674b90816f1SJeff Roberson 
2675ad1e7d28SJulian Elischer 	tdq = TDQ_SELF();
26763f741ca1SJeff Roberson 	if ((curthread->td_flags & TDF_IDLETD) != 0) {
267711484ad8SMark Johnston 		if (TDQ_LOAD(tdq) > 0)
26783f741ca1SJeff Roberson 			goto out;
26793f741ca1SJeff Roberson 	} else
268011484ad8SMark Johnston 		if (TDQ_LOAD(tdq) - 1 > 0)
2681b90816f1SJeff Roberson 			goto out;
2682b90816f1SJeff Roberson 	load = 0;
2683b90816f1SJeff Roberson out:
2684b90816f1SJeff Roberson 	return (load);
268535e6168fSJeff Roberson }
268635e6168fSJeff Roberson 
2687ae7a6b38SJeff Roberson /*
2688ae7a6b38SJeff Roberson  * Choose the highest priority thread to run.  The thread is removed from
2689ef80894cSMark Johnston  * the run-queue while running however the load remains.
2690ae7a6b38SJeff Roberson  */
26917a5e5e2aSJeff Roberson struct thread *
2692c9f25d8fSJeff Roberson sched_choose(void)
2693c9f25d8fSJeff Roberson {
26949727e637SJeff Roberson 	struct thread *td;
2695ae7a6b38SJeff Roberson 	struct tdq *tdq;
2696ae7a6b38SJeff Roberson 
2697ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2698ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
26999727e637SJeff Roberson 	td = tdq_choose(tdq);
27006d3f74a1SMark Johnston 	if (td != NULL) {
27019727e637SJeff Roberson 		tdq_runq_rem(tdq, td);
27020502fe2eSJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
27036d3f74a1SMark Johnston 	} else {
27040502fe2eSJeff Roberson 		tdq->tdq_lowpri = PRI_MAX_IDLE;
27056d3f74a1SMark Johnston 		td = PCPU_GET(idlethread);
27066d3f74a1SMark Johnston 	}
27076d3f74a1SMark Johnston 	tdq->tdq_curthread = td;
27086d3f74a1SMark Johnston 	return (td);
27097a5e5e2aSJeff Roberson }
27107a5e5e2aSJeff Roberson 
2711ae7a6b38SJeff Roberson /*
27120927ff78SMark Johnston  * Set owepreempt if the currently running thread has lower priority than "pri".
27130927ff78SMark Johnston  * Preemption never happens directly in ULE, we always request it once we exit a
27140927ff78SMark Johnston  * critical section.
2715ae7a6b38SJeff Roberson  */
27160927ff78SMark Johnston static void
27170927ff78SMark Johnston sched_setpreempt(int pri)
27187a5e5e2aSJeff Roberson {
27197a5e5e2aSJeff Roberson 	struct thread *ctd;
27207a5e5e2aSJeff Roberson 	int cpri;
2721ff256d9cSJeff Roberson 
27227a5e5e2aSJeff Roberson 	ctd = curthread;
27230927ff78SMark Johnston 	THREAD_LOCK_ASSERT(ctd, MA_OWNED);
27240927ff78SMark Johnston 
27257a5e5e2aSJeff Roberson 	cpri = ctd->td_priority;
2726ff256d9cSJeff Roberson 	if (pri < cpri)
2727c6d31b83SKonstantin Belousov 		ast_sched_locked(ctd, TDA_SCHED);
2728879e0604SMateusz Guzik 	if (KERNEL_PANICKED() || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2729ae7a6b38SJeff Roberson 		return;
2730ff256d9cSJeff Roberson 	if (!sched_shouldpreempt(pri, cpri, 0))
2731ae7a6b38SJeff Roberson 		return;
27327a5e5e2aSJeff Roberson 	ctd->td_owepreempt = 1;
273335e6168fSJeff Roberson }
273435e6168fSJeff Roberson 
2735ae7a6b38SJeff Roberson /*
273673daf66fSJeff Roberson  * Add a thread to a thread queue.  Select the appropriate runq and add the
273773daf66fSJeff Roberson  * thread to it.  This is the internal function called when the tdq is
273873daf66fSJeff Roberson  * predetermined.
2739ae7a6b38SJeff Roberson  */
27406d3f74a1SMark Johnston static int
2741ae7a6b38SJeff Roberson tdq_add(struct tdq *tdq, struct thread *td, int flags)
274235e6168fSJeff Roberson {
27436d3f74a1SMark Johnston 	int lowpri;
2744c9f25d8fSJeff Roberson 
2745ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
274661a74c5cSJeff Roberson 	THREAD_LOCK_BLOCKED_ASSERT(td, MA_OWNED);
27477a5e5e2aSJeff Roberson 	KASSERT((td->td_inhibitors == 0),
27487a5e5e2aSJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
27497a5e5e2aSJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
27507a5e5e2aSJeff Roberson 	    ("sched_add: bad thread state"));
2751b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
2752b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
2753ae7a6b38SJeff Roberson 
27546d3f74a1SMark Johnston 	lowpri = tdq->tdq_lowpri;
27556d3f74a1SMark Johnston 	if (td->td_priority < lowpri)
2756ae7a6b38SJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
27579727e637SJeff Roberson 	tdq_runq_add(tdq, td, flags);
27589727e637SJeff Roberson 	tdq_load_add(tdq, td);
27596d3f74a1SMark Johnston 	return (lowpri);
2760ae7a6b38SJeff Roberson }
2761ae7a6b38SJeff Roberson 
2762ae7a6b38SJeff Roberson /*
2763ae7a6b38SJeff Roberson  * Select the target thread queue and add a thread to it.  Request
2764ae7a6b38SJeff Roberson  * preemption or IPI a remote processor if required.
276561a74c5cSJeff Roberson  *
276661a74c5cSJeff Roberson  * Requires the thread lock on entry, drops on exit.
2767ae7a6b38SJeff Roberson  */
2768ae7a6b38SJeff Roberson void
2769ae7a6b38SJeff Roberson sched_add(struct thread *td, int flags)
2770ae7a6b38SJeff Roberson {
2771ae7a6b38SJeff Roberson 	struct tdq *tdq;
27727b8bfa0dSJeff Roberson #ifdef SMP
27736d3f74a1SMark Johnston 	int cpu, lowpri;
2774ae7a6b38SJeff Roberson #endif
27758f51ad55SJeff Roberson 
27768f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
27778f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
27788f51ad55SJeff Roberson 	    sched_tdname(curthread));
27798f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
27808f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
2781b3e9e682SRyan Stone 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
2782b3e9e682SRyan Stone 	    flags & SRQ_PREEMPTED);
2783ae7a6b38SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2784ae7a6b38SJeff Roberson 	/*
2785ae7a6b38SJeff Roberson 	 * Recalculate the priority before we select the target cpu or
2786ae7a6b38SJeff Roberson 	 * run-queue.
2787ae7a6b38SJeff Roberson 	 */
2788ae7a6b38SJeff Roberson 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2789ae7a6b38SJeff Roberson 		sched_priority(td);
2790ae7a6b38SJeff Roberson #ifdef SMP
2791ae7a6b38SJeff Roberson 	/*
2792ae7a6b38SJeff Roberson 	 * Pick the destination cpu and if it isn't ours transfer to the
2793ae7a6b38SJeff Roberson 	 * target cpu.
2794ae7a6b38SJeff Roberson 	 */
27959727e637SJeff Roberson 	cpu = sched_pickcpu(td, flags);
27969727e637SJeff Roberson 	tdq = sched_setcpu(td, cpu, flags);
27976d3f74a1SMark Johnston 	lowpri = tdq_add(tdq, td, flags);
279861a74c5cSJeff Roberson 	if (cpu != PCPU_GET(cpuid))
27996d3f74a1SMark Johnston 		tdq_notify(tdq, lowpri);
280061a74c5cSJeff Roberson 	else if (!(flags & SRQ_YIELDING))
28010927ff78SMark Johnston 		sched_setpreempt(td->td_priority);
2802ae7a6b38SJeff Roberson #else
2803ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2804ae7a6b38SJeff Roberson 	/*
2805ae7a6b38SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
2806ae7a6b38SJeff Roberson 	 * to the scheduler's lock.
2807ae7a6b38SJeff Roberson 	 */
2808e4894505SMark Johnston 	if (td->td_lock != TDQ_LOCKPTR(tdq)) {
2809e4894505SMark Johnston 		TDQ_LOCK(tdq);
281061a74c5cSJeff Roberson 		if ((flags & SRQ_HOLD) != 0)
281161a74c5cSJeff Roberson 			td->td_lock = TDQ_LOCKPTR(tdq);
281261a74c5cSJeff Roberson 		else
2813ae7a6b38SJeff Roberson 			thread_lock_set(td, TDQ_LOCKPTR(tdq));
2814e4894505SMark Johnston 	}
28156d3f74a1SMark Johnston 	(void)tdq_add(tdq, td, flags);
2816ae7a6b38SJeff Roberson 	if (!(flags & SRQ_YIELDING))
28170927ff78SMark Johnston 		sched_setpreempt(td->td_priority);
281861a74c5cSJeff Roberson #endif
281961a74c5cSJeff Roberson 	if (!(flags & SRQ_HOLDTD))
282061a74c5cSJeff Roberson 		thread_unlock(td);
282135e6168fSJeff Roberson }
282235e6168fSJeff Roberson 
2823ae7a6b38SJeff Roberson /*
2824ae7a6b38SJeff Roberson  * Remove a thread from a run-queue without running it.  This is used
2825ae7a6b38SJeff Roberson  * when we're stealing a thread from a remote queue.  Otherwise all threads
2826ae7a6b38SJeff Roberson  * exit by calling sched_exit_thread() and sched_throw() themselves.
2827ae7a6b38SJeff Roberson  */
282835e6168fSJeff Roberson void
28297cf90fb3SJeff Roberson sched_rem(struct thread *td)
283035e6168fSJeff Roberson {
2831ad1e7d28SJulian Elischer 	struct tdq *tdq;
28327cf90fb3SJeff Roberson 
28338f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
28348f51ad55SJeff Roberson 	    "prio:%d", td->td_priority);
2835b3e9e682SRyan Stone 	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
283693ccd6bfSKonstantin Belousov 	tdq = TDQ_CPU(td_get_sched(td)->ts_cpu);
2837ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2838ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
28397a5e5e2aSJeff Roberson 	KASSERT(TD_ON_RUNQ(td),
2840ad1e7d28SJulian Elischer 	    ("sched_rem: thread not on run queue"));
28419727e637SJeff Roberson 	tdq_runq_rem(tdq, td);
28429727e637SJeff Roberson 	tdq_load_rem(tdq, td);
28437a5e5e2aSJeff Roberson 	TD_SET_CAN_RUN(td);
284462fa74d9SJeff Roberson 	if (td->td_priority == tdq->tdq_lowpri)
284562fa74d9SJeff Roberson 		tdq_setlowpri(tdq, NULL);
284635e6168fSJeff Roberson }
284735e6168fSJeff Roberson 
2848ae7a6b38SJeff Roberson /*
2849ae7a6b38SJeff Roberson  * Fetch cpu utilization information.  Updates on demand.
2850ae7a6b38SJeff Roberson  */
285135e6168fSJeff Roberson fixpt_t
28527cf90fb3SJeff Roberson sched_pctcpu(struct thread *td)
285335e6168fSJeff Roberson {
285435e6168fSJeff Roberson 	fixpt_t pctcpu;
2855ad1e7d28SJulian Elischer 	struct td_sched *ts;
285635e6168fSJeff Roberson 
285735e6168fSJeff Roberson 	pctcpu = 0;
285893ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
285935e6168fSJeff Roberson 
28603da35a0aSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
28617295465eSAlexander Motin 	sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2862ad1e7d28SJulian Elischer 	if (ts->ts_ticks) {
286335e6168fSJeff Roberson 		int rtick;
286435e6168fSJeff Roberson 
286535e6168fSJeff Roberson 		/* How many rtick per second ? */
2866e7d50326SJeff Roberson 		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2867e7d50326SJeff Roberson 		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
286835e6168fSJeff Roberson 	}
286935e6168fSJeff Roberson 
287035e6168fSJeff Roberson 	return (pctcpu);
287135e6168fSJeff Roberson }
287235e6168fSJeff Roberson 
287362fa74d9SJeff Roberson /*
287462fa74d9SJeff Roberson  * Enforce affinity settings for a thread.  Called after adjustments to
287562fa74d9SJeff Roberson  * cpumask.
287662fa74d9SJeff Roberson  */
2877885d51a3SJeff Roberson void
2878885d51a3SJeff Roberson sched_affinity(struct thread *td)
2879885d51a3SJeff Roberson {
288062fa74d9SJeff Roberson #ifdef SMP
288162fa74d9SJeff Roberson 	struct td_sched *ts;
288262fa74d9SJeff Roberson 
288362fa74d9SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
288493ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
288562fa74d9SJeff Roberson 	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
288662fa74d9SJeff Roberson 		return;
288753a6c8b3SJeff Roberson 	if (TD_ON_RUNQ(td)) {
288853a6c8b3SJeff Roberson 		sched_rem(td);
2889d8d5f036SJeff Roberson 		sched_add(td, SRQ_BORING | SRQ_HOLDTD);
289053a6c8b3SJeff Roberson 		return;
289153a6c8b3SJeff Roberson 	}
289262fa74d9SJeff Roberson 	if (!TD_IS_RUNNING(td))
289362fa74d9SJeff Roberson 		return;
289462fa74d9SJeff Roberson 	/*
28950f7a0ebdSMatthew D Fleming 	 * Force a switch before returning to userspace.  If the
28960f7a0ebdSMatthew D Fleming 	 * target thread is not running locally send an ipi to force
28970f7a0ebdSMatthew D Fleming 	 * the issue.
289862fa74d9SJeff Roberson 	 */
2899c6d31b83SKonstantin Belousov 	ast_sched_locked(td, TDA_SCHED);
29000f7a0ebdSMatthew D Fleming 	if (td != curthread)
29010f7a0ebdSMatthew D Fleming 		ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
290262fa74d9SJeff Roberson #endif
2903885d51a3SJeff Roberson }
2904885d51a3SJeff Roberson 
2905ae7a6b38SJeff Roberson /*
2906ae7a6b38SJeff Roberson  * Bind a thread to a target cpu.
2907ae7a6b38SJeff Roberson  */
29089bacd788SJeff Roberson void
29099bacd788SJeff Roberson sched_bind(struct thread *td, int cpu)
29109bacd788SJeff Roberson {
2911ad1e7d28SJulian Elischer 	struct td_sched *ts;
29129bacd788SJeff Roberson 
2913c47f202bSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
29141d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
291593ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
29166b2f763fSJeff Roberson 	if (ts->ts_flags & TSF_BOUND)
2917c95d2db2SJeff Roberson 		sched_unbind(td);
29180f7a0ebdSMatthew D Fleming 	KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2919ad1e7d28SJulian Elischer 	ts->ts_flags |= TSF_BOUND;
29206b2f763fSJeff Roberson 	sched_pin();
292180f86c9fSJeff Roberson 	if (PCPU_GET(cpuid) == cpu)
29229bacd788SJeff Roberson 		return;
29236b2f763fSJeff Roberson 	ts->ts_cpu = cpu;
29249bacd788SJeff Roberson 	/* When we return from mi_switch we'll be on the correct cpu. */
29251029dab6SMitchell Horne 	mi_switch(SW_VOL | SWT_BIND);
2926686bcb5cSJeff Roberson 	thread_lock(td);
29279bacd788SJeff Roberson }
29289bacd788SJeff Roberson 
2929ae7a6b38SJeff Roberson /*
2930ae7a6b38SJeff Roberson  * Release a bound thread.
2931ae7a6b38SJeff Roberson  */
29329bacd788SJeff Roberson void
29339bacd788SJeff Roberson sched_unbind(struct thread *td)
29349bacd788SJeff Roberson {
2935e7d50326SJeff Roberson 	struct td_sched *ts;
2936e7d50326SJeff Roberson 
29377b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
29381d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
293993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
29406b2f763fSJeff Roberson 	if ((ts->ts_flags & TSF_BOUND) == 0)
29416b2f763fSJeff Roberson 		return;
2942e7d50326SJeff Roberson 	ts->ts_flags &= ~TSF_BOUND;
2943e7d50326SJeff Roberson 	sched_unpin();
29449bacd788SJeff Roberson }
29459bacd788SJeff Roberson 
294635e6168fSJeff Roberson int
2947ebccf1e3SJoseph Koshy sched_is_bound(struct thread *td)
2948ebccf1e3SJoseph Koshy {
29497b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
295093ccd6bfSKonstantin Belousov 	return (td_get_sched(td)->ts_flags & TSF_BOUND);
2951ebccf1e3SJoseph Koshy }
2952ebccf1e3SJoseph Koshy 
2953ae7a6b38SJeff Roberson /*
2954ae7a6b38SJeff Roberson  * Basic yield call.
2955ae7a6b38SJeff Roberson  */
295636ec198bSDavid Xu void
295736ec198bSDavid Xu sched_relinquish(struct thread *td)
295836ec198bSDavid Xu {
29597b20fb19SJeff Roberson 	thread_lock(td);
2960686bcb5cSJeff Roberson 	mi_switch(SW_VOL | SWT_RELINQUISH);
296136ec198bSDavid Xu }
296236ec198bSDavid Xu 
2963ae7a6b38SJeff Roberson /*
2964ae7a6b38SJeff Roberson  * Return the total system load.
2965ae7a6b38SJeff Roberson  */
2966ebccf1e3SJoseph Koshy int
296733916c36SJeff Roberson sched_load(void)
296833916c36SJeff Roberson {
296933916c36SJeff Roberson #ifdef SMP
297033916c36SJeff Roberson 	int total;
297133916c36SJeff Roberson 	int i;
297233916c36SJeff Roberson 
297333916c36SJeff Roberson 	total = 0;
29743aa6d94eSJohn Baldwin 	CPU_FOREACH(i)
297511484ad8SMark Johnston 		total += atomic_load_int(&TDQ_CPU(i)->tdq_sysload);
297633916c36SJeff Roberson 	return (total);
297733916c36SJeff Roberson #else
297811484ad8SMark Johnston 	return (atomic_load_int(&TDQ_SELF()->tdq_sysload));
297933916c36SJeff Roberson #endif
298033916c36SJeff Roberson }
298133916c36SJeff Roberson 
298233916c36SJeff Roberson int
298335e6168fSJeff Roberson sched_sizeof_proc(void)
298435e6168fSJeff Roberson {
298535e6168fSJeff Roberson 	return (sizeof(struct proc));
298635e6168fSJeff Roberson }
298735e6168fSJeff Roberson 
298835e6168fSJeff Roberson int
298935e6168fSJeff Roberson sched_sizeof_thread(void)
299035e6168fSJeff Roberson {
299135e6168fSJeff Roberson 	return (sizeof(struct thread) + sizeof(struct td_sched));
299235e6168fSJeff Roberson }
2993b41f1452SDavid Xu 
299409c8a4ccSJeff Roberson #ifdef SMP
299509c8a4ccSJeff Roberson #define	TDQ_IDLESPIN(tdq)						\
299609c8a4ccSJeff Roberson     ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
299709c8a4ccSJeff Roberson #else
299809c8a4ccSJeff Roberson #define	TDQ_IDLESPIN(tdq)	1
299909c8a4ccSJeff Roberson #endif
300009c8a4ccSJeff Roberson 
30017a5e5e2aSJeff Roberson /*
30027a5e5e2aSJeff Roberson  * The actual idle process.
30037a5e5e2aSJeff Roberson  */
30047a5e5e2aSJeff Roberson void
30057a5e5e2aSJeff Roberson sched_idletd(void *dummy)
30067a5e5e2aSJeff Roberson {
30077a5e5e2aSJeff Roberson 	struct thread *td;
3008ae7a6b38SJeff Roberson 	struct tdq *tdq;
30092c27cb3aSAlexander Motin 	int oldswitchcnt, switchcnt;
30101690c6c1SJeff Roberson 	int i;
30117a5e5e2aSJeff Roberson 
30127b55ab05SJeff Roberson 	mtx_assert(&Giant, MA_NOTOWNED);
30137a5e5e2aSJeff Roberson 	td = curthread;
3014ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
3015ba96d2d8SJohn Baldwin 	THREAD_NO_SLEEPING();
30162c27cb3aSAlexander Motin 	oldswitchcnt = -1;
3017ae7a6b38SJeff Roberson 	for (;;) {
301811484ad8SMark Johnston 		if (TDQ_LOAD(tdq)) {
30192c27cb3aSAlexander Motin 			thread_lock(td);
3020686bcb5cSJeff Roberson 			mi_switch(SW_VOL | SWT_IDLE);
30212c27cb3aSAlexander Motin 		}
302211484ad8SMark Johnston 		switchcnt = TDQ_SWITCHCNT(tdq);
3023ae7a6b38SJeff Roberson #ifdef SMP
302497e9382dSDon Lewis 		if (always_steal || switchcnt != oldswitchcnt) {
30252c27cb3aSAlexander Motin 			oldswitchcnt = switchcnt;
30261690c6c1SJeff Roberson 			if (tdq_idled(tdq) == 0)
30271690c6c1SJeff Roberson 				continue;
30282c27cb3aSAlexander Motin 		}
302911484ad8SMark Johnston 		switchcnt = TDQ_SWITCHCNT(tdq);
30302fd4047fSAlexander Motin #else
30312fd4047fSAlexander Motin 		oldswitchcnt = switchcnt;
30322fd4047fSAlexander Motin #endif
30331690c6c1SJeff Roberson 		/*
30341690c6c1SJeff Roberson 		 * If we're switching very frequently, spin while checking
30351690c6c1SJeff Roberson 		 * for load rather than entering a low power state that
30367b55ab05SJeff Roberson 		 * may require an IPI.  However, don't do any busy
30377b55ab05SJeff Roberson 		 * loops while on SMT machines as this simply steals
30387b55ab05SJeff Roberson 		 * cycles from cores doing useful work.
30391690c6c1SJeff Roberson 		 */
304009c8a4ccSJeff Roberson 		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
30411690c6c1SJeff Roberson 			for (i = 0; i < sched_idlespins; i++) {
304211484ad8SMark Johnston 				if (TDQ_LOAD(tdq))
30431690c6c1SJeff Roberson 					break;
30441690c6c1SJeff Roberson 				cpu_spinwait();
30451690c6c1SJeff Roberson 			}
30461690c6c1SJeff Roberson 		}
30472c27cb3aSAlexander Motin 
30482c27cb3aSAlexander Motin 		/* If there was context switch during spin, restart it. */
304911484ad8SMark Johnston 		switchcnt = TDQ_SWITCHCNT(tdq);
305011484ad8SMark Johnston 		if (TDQ_LOAD(tdq) != 0 || switchcnt != oldswitchcnt)
30512c27cb3aSAlexander Motin 			continue;
30522c27cb3aSAlexander Motin 
30532c27cb3aSAlexander Motin 		/* Run main MD idle handler. */
305411484ad8SMark Johnston 		atomic_store_int(&tdq->tdq_cpu_idle, 1);
305579654969SAlexander Motin 		/*
30566d3f74a1SMark Johnston 		 * Make sure that the tdq_cpu_idle update is globally visible
30576d3f74a1SMark Johnston 		 * before cpu_idle() reads tdq_load.  The order is important
30586d3f74a1SMark Johnston 		 * to avoid races with tdq_notify().
305979654969SAlexander Motin 		 */
3060e8677f38SKonstantin Belousov 		atomic_thread_fence_seq_cst();
306197e9382dSDon Lewis 		/*
306297e9382dSDon Lewis 		 * Checking for again after the fence picks up assigned
306397e9382dSDon Lewis 		 * threads often enough to make it worthwhile to do so in
306497e9382dSDon Lewis 		 * order to avoid calling cpu_idle().
306597e9382dSDon Lewis 		 */
306611484ad8SMark Johnston 		if (TDQ_LOAD(tdq) != 0) {
306711484ad8SMark Johnston 			atomic_store_int(&tdq->tdq_cpu_idle, 0);
306897e9382dSDon Lewis 			continue;
306997e9382dSDon Lewis 		}
30702c27cb3aSAlexander Motin 		cpu_idle(switchcnt * 4 > sched_idlespinthresh);
307111484ad8SMark Johnston 		atomic_store_int(&tdq->tdq_cpu_idle, 0);
30722c27cb3aSAlexander Motin 
30732c27cb3aSAlexander Motin 		/*
30742c27cb3aSAlexander Motin 		 * Account thread-less hardware interrupts and
30752c27cb3aSAlexander Motin 		 * other wakeup reasons equal to context switches.
30762c27cb3aSAlexander Motin 		 */
307711484ad8SMark Johnston 		switchcnt = TDQ_SWITCHCNT(tdq);
30782c27cb3aSAlexander Motin 		if (switchcnt != oldswitchcnt)
30792c27cb3aSAlexander Motin 			continue;
308011484ad8SMark Johnston 		TDQ_SWITCHCNT_INC(tdq);
30812c27cb3aSAlexander Motin 		oldswitchcnt++;
3082ae7a6b38SJeff Roberson 	}
3083b41f1452SDavid Xu }
3084e7d50326SJeff Roberson 
30857b20fb19SJeff Roberson /*
30866a8ea6d1SKyle Evans  * sched_throw_grab() chooses a thread from the queue to switch to
30876a8ea6d1SKyle Evans  * next.  It returns with the tdq lock dropped in a spinlock section to
30886a8ea6d1SKyle Evans  * keep interrupts disabled until the CPU is running in a proper threaded
30896a8ea6d1SKyle Evans  * context.
30906a8ea6d1SKyle Evans  */
30916a8ea6d1SKyle Evans static struct thread *
30926a8ea6d1SKyle Evans sched_throw_grab(struct tdq *tdq)
30936a8ea6d1SKyle Evans {
30946a8ea6d1SKyle Evans 	struct thread *newtd;
30956a8ea6d1SKyle Evans 
30966a8ea6d1SKyle Evans 	newtd = choosethread();
30976a8ea6d1SKyle Evans 	spinlock_enter();
30986a8ea6d1SKyle Evans 	TDQ_UNLOCK(tdq);
30996a8ea6d1SKyle Evans 	KASSERT(curthread->td_md.md_spinlock_count == 1,
31006a8ea6d1SKyle Evans 	    ("invalid count %d", curthread->td_md.md_spinlock_count));
31016a8ea6d1SKyle Evans 	return (newtd);
31026a8ea6d1SKyle Evans }
31036a8ea6d1SKyle Evans 
31046a8ea6d1SKyle Evans /*
31056a8ea6d1SKyle Evans  * A CPU is entering for the first time.
31066a8ea6d1SKyle Evans  */
31076a8ea6d1SKyle Evans void
31086a8ea6d1SKyle Evans sched_ap_entry(void)
31096a8ea6d1SKyle Evans {
31106a8ea6d1SKyle Evans 	struct thread *newtd;
31116a8ea6d1SKyle Evans 	struct tdq *tdq;
31126a8ea6d1SKyle Evans 
31136a8ea6d1SKyle Evans 	tdq = TDQ_SELF();
31146a8ea6d1SKyle Evans 
31156a8ea6d1SKyle Evans 	/* This should have been setup in schedinit_ap(). */
31166a8ea6d1SKyle Evans 	THREAD_LOCKPTR_ASSERT(curthread, TDQ_LOCKPTR(tdq));
31176a8ea6d1SKyle Evans 
31186a8ea6d1SKyle Evans 	TDQ_LOCK(tdq);
31196a8ea6d1SKyle Evans 	/* Correct spinlock nesting. */
31206a8ea6d1SKyle Evans 	spinlock_exit();
31216a8ea6d1SKyle Evans 	PCPU_SET(switchtime, cpu_ticks());
31226a8ea6d1SKyle Evans 	PCPU_SET(switchticks, ticks);
31236a8ea6d1SKyle Evans 
31246a8ea6d1SKyle Evans 	newtd = sched_throw_grab(tdq);
31256a8ea6d1SKyle Evans 
31266a8ea6d1SKyle Evans 	/* doesn't return */
31276a8ea6d1SKyle Evans 	cpu_throw(NULL, newtd);
31286a8ea6d1SKyle Evans }
31296a8ea6d1SKyle Evans 
31306a8ea6d1SKyle Evans /*
31316a8ea6d1SKyle Evans  * A thread is exiting.
31327b20fb19SJeff Roberson  */
31337b20fb19SJeff Roberson void
31347b20fb19SJeff Roberson sched_throw(struct thread *td)
31357b20fb19SJeff Roberson {
313659c68134SJeff Roberson 	struct thread *newtd;
3137ae7a6b38SJeff Roberson 	struct tdq *tdq;
3138ae7a6b38SJeff Roberson 
3139018ff686SJeff Roberson 	tdq = TDQ_SELF();
31406a8ea6d1SKyle Evans 
31416a8ea6d1SKyle Evans 	MPASS(td != NULL);
3142686bcb5cSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
3143686bcb5cSJeff Roberson 	THREAD_LOCKPTR_ASSERT(td, TDQ_LOCKPTR(tdq));
31446a8ea6d1SKyle Evans 
31459727e637SJeff Roberson 	tdq_load_rem(tdq, td);
314692de34dfSJohn Baldwin 	td->td_lastcpu = td->td_oncpu;
314792de34dfSJohn Baldwin 	td->td_oncpu = NOCPU;
31481eb13fceSJeff Roberson 	thread_lock_block(td);
31496a8ea6d1SKyle Evans 
31506a8ea6d1SKyle Evans 	newtd = sched_throw_grab(tdq);
31516a8ea6d1SKyle Evans 
31521eb13fceSJeff Roberson 	/* doesn't return */
31531eb13fceSJeff Roberson 	cpu_switch(td, newtd, TDQ_LOCKPTR(tdq));
31547b20fb19SJeff Roberson }
31557b20fb19SJeff Roberson 
3156ae7a6b38SJeff Roberson /*
3157ae7a6b38SJeff Roberson  * This is called from fork_exit().  Just acquire the correct locks and
3158ae7a6b38SJeff Roberson  * let fork do the rest of the work.
3159ae7a6b38SJeff Roberson  */
31607b20fb19SJeff Roberson void
3161fe54587fSJeff Roberson sched_fork_exit(struct thread *td)
31627b20fb19SJeff Roberson {
3163ae7a6b38SJeff Roberson 	struct tdq *tdq;
3164ae7a6b38SJeff Roberson 	int cpuid;
31657b20fb19SJeff Roberson 
31667b20fb19SJeff Roberson 	/*
31677b20fb19SJeff Roberson 	 * Finish setting up thread glue so that it begins execution in a
3168ae7a6b38SJeff Roberson 	 * non-nested critical section with the scheduler lock held.
31697b20fb19SJeff Roberson 	 */
3170686bcb5cSJeff Roberson 	KASSERT(curthread->td_md.md_spinlock_count == 1,
3171686bcb5cSJeff Roberson 	    ("invalid count %d", curthread->td_md.md_spinlock_count));
3172ae7a6b38SJeff Roberson 	cpuid = PCPU_GET(cpuid);
3173018ff686SJeff Roberson 	tdq = TDQ_SELF();
3174686bcb5cSJeff Roberson 	TDQ_LOCK(tdq);
3175686bcb5cSJeff Roberson 	spinlock_exit();
3176ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
3177ae7a6b38SJeff Roberson 	td->td_oncpu = cpuid;
317828ef18b8SAndriy Gapon 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
317928ef18b8SAndriy Gapon 	    "prio:%d", td->td_priority);
318028ef18b8SAndriy Gapon 	SDT_PROBE0(sched, , , on__cpu);
31817b20fb19SJeff Roberson }
31827b20fb19SJeff Roberson 
31838f51ad55SJeff Roberson /*
318415b5c347SGordon Bergling  * Create on first use to catch odd startup conditions.
31858f51ad55SJeff Roberson  */
31868f51ad55SJeff Roberson char *
31878f51ad55SJeff Roberson sched_tdname(struct thread *td)
31888f51ad55SJeff Roberson {
31898f51ad55SJeff Roberson #ifdef KTR
31908f51ad55SJeff Roberson 	struct td_sched *ts;
31918f51ad55SJeff Roberson 
319293ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
31938f51ad55SJeff Roberson 	if (ts->ts_name[0] == '\0')
31948f51ad55SJeff Roberson 		snprintf(ts->ts_name, sizeof(ts->ts_name),
31958f51ad55SJeff Roberson 		    "%s tid %d", td->td_name, td->td_tid);
31968f51ad55SJeff Roberson 	return (ts->ts_name);
31978f51ad55SJeff Roberson #else
31988f51ad55SJeff Roberson 	return (td->td_name);
31998f51ad55SJeff Roberson #endif
32008f51ad55SJeff Roberson }
32018f51ad55SJeff Roberson 
320244ad5475SJohn Baldwin #ifdef KTR
320344ad5475SJohn Baldwin void
320444ad5475SJohn Baldwin sched_clear_tdname(struct thread *td)
320544ad5475SJohn Baldwin {
320644ad5475SJohn Baldwin 	struct td_sched *ts;
320744ad5475SJohn Baldwin 
320893ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
320944ad5475SJohn Baldwin 	ts->ts_name[0] = '\0';
321044ad5475SJohn Baldwin }
321144ad5475SJohn Baldwin #endif
321244ad5475SJohn Baldwin 
321307095abfSIvan Voras #ifdef SMP
321407095abfSIvan Voras 
321507095abfSIvan Voras /*
321607095abfSIvan Voras  * Build the CPU topology dump string. Is recursively called to collect
321707095abfSIvan Voras  * the topology tree.
321807095abfSIvan Voras  */
321907095abfSIvan Voras static int
322007095abfSIvan Voras sysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
322107095abfSIvan Voras     int indent)
322207095abfSIvan Voras {
322371a19bdcSAttilio Rao 	char cpusetbuf[CPUSETBUFSIZ];
322407095abfSIvan Voras 	int i, first;
322507095abfSIvan Voras 
322607095abfSIvan Voras 	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
322719b8a6dbSAndriy Gapon 	    "", 1 + indent / 2, cg->cg_level);
322871a19bdcSAttilio Rao 	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
322971a19bdcSAttilio Rao 	    cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
323007095abfSIvan Voras 	first = TRUE;
3231aefe0a8cSAlexander Motin 	for (i = cg->cg_first; i <= cg->cg_last; i++) {
323271a19bdcSAttilio Rao 		if (CPU_ISSET(i, &cg->cg_mask)) {
323307095abfSIvan Voras 			if (!first)
323407095abfSIvan Voras 				sbuf_printf(sb, ", ");
323507095abfSIvan Voras 			else
323607095abfSIvan Voras 				first = FALSE;
323707095abfSIvan Voras 			sbuf_printf(sb, "%d", i);
323807095abfSIvan Voras 		}
323907095abfSIvan Voras 	}
324007095abfSIvan Voras 	sbuf_printf(sb, "</cpu>\n");
324107095abfSIvan Voras 
324207095abfSIvan Voras 	if (cg->cg_flags != 0) {
3243611daf7eSIvan Voras 		sbuf_printf(sb, "%*s <flags>", indent, "");
324407095abfSIvan Voras 		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
32455368befbSIvan Voras 			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
3246a401f2d0SIvan Voras 		if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
3247a401f2d0SIvan Voras 			sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
32487b55ab05SJeff Roberson 		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
3249a401f2d0SIvan Voras 			sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
3250ef50d5fbSAlexander Motin 		if ((cg->cg_flags & CG_FLAG_NODE) != 0)
3251ef50d5fbSAlexander Motin 			sbuf_printf(sb, "<flag name=\"NODE\">NUMA node</flag>");
325207095abfSIvan Voras 		sbuf_printf(sb, "</flags>\n");
3253611daf7eSIvan Voras 	}
325407095abfSIvan Voras 
325507095abfSIvan Voras 	if (cg->cg_children > 0) {
325607095abfSIvan Voras 		sbuf_printf(sb, "%*s <children>\n", indent, "");
325707095abfSIvan Voras 		for (i = 0; i < cg->cg_children; i++)
325807095abfSIvan Voras 			sysctl_kern_sched_topology_spec_internal(sb,
325907095abfSIvan Voras 			    &cg->cg_child[i], indent+2);
326007095abfSIvan Voras 		sbuf_printf(sb, "%*s </children>\n", indent, "");
326107095abfSIvan Voras 	}
326207095abfSIvan Voras 	sbuf_printf(sb, "%*s</group>\n", indent, "");
326307095abfSIvan Voras 	return (0);
326407095abfSIvan Voras }
326507095abfSIvan Voras 
326607095abfSIvan Voras /*
326707095abfSIvan Voras  * Sysctl handler for retrieving topology dump. It's a wrapper for
326807095abfSIvan Voras  * the recursive sysctl_kern_smp_topology_spec_internal().
326907095abfSIvan Voras  */
327007095abfSIvan Voras static int
327107095abfSIvan Voras sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
327207095abfSIvan Voras {
327307095abfSIvan Voras 	struct sbuf *topo;
327407095abfSIvan Voras 	int err;
327507095abfSIvan Voras 
327607095abfSIvan Voras 	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
327707095abfSIvan Voras 
3278b97fa22cSIan Lepore 	topo = sbuf_new_for_sysctl(NULL, NULL, 512, req);
327907095abfSIvan Voras 	if (topo == NULL)
328007095abfSIvan Voras 		return (ENOMEM);
328107095abfSIvan Voras 
328207095abfSIvan Voras 	sbuf_printf(topo, "<groups>\n");
328307095abfSIvan Voras 	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
328407095abfSIvan Voras 	sbuf_printf(topo, "</groups>\n");
328507095abfSIvan Voras 
328607095abfSIvan Voras 	if (err == 0) {
3287b97fa22cSIan Lepore 		err = sbuf_finish(topo);
328807095abfSIvan Voras 	}
328907095abfSIvan Voras 	sbuf_delete(topo);
329007095abfSIvan Voras 	return (err);
329107095abfSIvan Voras }
3292b67cc292SDavid Xu 
329307095abfSIvan Voras #endif
329407095abfSIvan Voras 
3295579895dfSAlexander Motin static int
3296579895dfSAlexander Motin sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
3297579895dfSAlexander Motin {
3298579895dfSAlexander Motin 	int error, new_val, period;
3299579895dfSAlexander Motin 
3300579895dfSAlexander Motin 	period = 1000000 / realstathz;
3301579895dfSAlexander Motin 	new_val = period * sched_slice;
3302579895dfSAlexander Motin 	error = sysctl_handle_int(oidp, &new_val, 0, req);
3303579895dfSAlexander Motin 	if (error != 0 || req->newptr == NULL)
3304579895dfSAlexander Motin 		return (error);
3305579895dfSAlexander Motin 	if (new_val <= 0)
3306579895dfSAlexander Motin 		return (EINVAL);
330737f4e025SAlexander Motin 	sched_slice = imax(1, (new_val + period / 2) / period);
33085e5c3873SJeff Roberson 	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
330937f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
331037f4e025SAlexander Motin 	    realstathz);
3311579895dfSAlexander Motin 	return (0);
3312579895dfSAlexander Motin }
3313579895dfSAlexander Motin 
33147029da5cSPawel Biernacki SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
33157029da5cSPawel Biernacki     "Scheduler");
3316ae7a6b38SJeff Roberson SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
3317e7d50326SJeff Roberson     "Scheduler name");
33187029da5cSPawel Biernacki SYSCTL_PROC(_kern_sched, OID_AUTO, quantum,
33197029da5cSPawel Biernacki     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
33207029da5cSPawel Biernacki     sysctl_kern_quantum, "I",
332137f4e025SAlexander Motin     "Quantum for timeshare threads in microseconds");
3322ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
332337f4e025SAlexander Motin     "Quantum for timeshare threads in stathz ticks");
33241c119e17SAlexander Motin SYSCTL_UINT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
3325ae7a6b38SJeff Roberson     "Interactivity score threshold");
332637f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW,
332737f4e025SAlexander Motin     &preempt_thresh, 0,
332837f4e025SAlexander Motin     "Maximal (lowest) priority for preemption");
332937f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost, 0,
333037f4e025SAlexander Motin     "Assign static kernel priorities to sleeping threads");
333137f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins, 0,
333237f4e025SAlexander Motin     "Number of times idle thread will spin waiting for new work");
333337f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW,
333437f4e025SAlexander Motin     &sched_idlespinthresh, 0,
333537f4e025SAlexander Motin     "Threshold before we will permit idle thread spinning");
33367b8bfa0dSJeff Roberson #ifdef SMP
3337ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
3338ae7a6b38SJeff Roberson     "Number of hz ticks to keep thread affinity for");
3339ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
3340ae7a6b38SJeff Roberson     "Enables the long-term load balancer");
33417fcf154aSJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
33427fcf154aSJeff Roberson     &balance_interval, 0,
3343579895dfSAlexander Motin     "Average period in stathz ticks to run the long-term balancer");
3344ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
3345ae7a6b38SJeff Roberson     "Attempts to steal work from other cores before idling");
334628994a58SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
334737f4e025SAlexander Motin     "Minimum load on remote CPU before we'll steal");
334897e9382dSDon Lewis SYSCTL_INT(_kern_sched, OID_AUTO, trysteal_limit, CTLFLAG_RW, &trysteal_limit,
334997e9382dSDon Lewis     0, "Topological distance limit for stealing threads in sched_switch()");
335097e9382dSDon Lewis SYSCTL_INT(_kern_sched, OID_AUTO, always_steal, CTLFLAG_RW, &always_steal, 0,
335197e9382dSDon Lewis     "Always run the stealer from the idle thread");
335207095abfSIvan Voras SYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
3353c69a1a50SMateusz Guzik     CTLFLAG_MPSAFE | CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
335407095abfSIvan Voras     "XML dump of detected CPU topology");
33557b8bfa0dSJeff Roberson #endif
3356e7d50326SJeff Roberson 
335754b0e65fSJeff Roberson /* ps compat.  All cpu percentages from ULE are weighted. */
3358a5423ea3SJeff Roberson static int ccpu = 0;
3359b05ca429SPawel Biernacki SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0,
3360b05ca429SPawel Biernacki     "Decay factor used for updating %CPU in 4BSD scheduler");
3361