xref: /freebsd/sys/kern/sched_ule.c (revision 8a36da99deb0e19363ec04e4d3facd869c1028f5)
135e6168fSJeff Roberson /*-
2*8a36da99SPedro F. Giffuni  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3*8a36da99SPedro F. Giffuni  *
4e7d50326SJeff Roberson  * Copyright (c) 2002-2007, Jeffrey Roberson <jeff@freebsd.org>
535e6168fSJeff Roberson  * All rights reserved.
635e6168fSJeff Roberson  *
735e6168fSJeff Roberson  * Redistribution and use in source and binary forms, with or without
835e6168fSJeff Roberson  * modification, are permitted provided that the following conditions
935e6168fSJeff Roberson  * are met:
1035e6168fSJeff Roberson  * 1. Redistributions of source code must retain the above copyright
1135e6168fSJeff Roberson  *    notice unmodified, this list of conditions, and the following
1235e6168fSJeff Roberson  *    disclaimer.
1335e6168fSJeff Roberson  * 2. Redistributions in binary form must reproduce the above copyright
1435e6168fSJeff Roberson  *    notice, this list of conditions and the following disclaimer in the
1535e6168fSJeff Roberson  *    documentation and/or other materials provided with the distribution.
1635e6168fSJeff Roberson  *
1735e6168fSJeff Roberson  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1835e6168fSJeff Roberson  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1935e6168fSJeff Roberson  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
2035e6168fSJeff Roberson  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
2135e6168fSJeff Roberson  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
2235e6168fSJeff Roberson  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2335e6168fSJeff Roberson  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2435e6168fSJeff Roberson  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2535e6168fSJeff Roberson  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
2635e6168fSJeff Roberson  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2735e6168fSJeff Roberson  */
2835e6168fSJeff Roberson 
29ae7a6b38SJeff Roberson /*
30ae7a6b38SJeff Roberson  * This file implements the ULE scheduler.  ULE supports independent CPU
31ae7a6b38SJeff Roberson  * run queues and fine grain locking.  It has superior interactive
32ae7a6b38SJeff Roberson  * performance under load even on uni-processor systems.
33ae7a6b38SJeff Roberson  *
34ae7a6b38SJeff Roberson  * etymology:
35a5423ea3SJeff Roberson  *   ULE is the last three letters in schedule.  It owes its name to a
36ae7a6b38SJeff Roberson  * generic user created for a scheduling system by Paul Mikesell at
37ae7a6b38SJeff Roberson  * Isilon Systems and a general lack of creativity on the part of the author.
38ae7a6b38SJeff Roberson  */
39ae7a6b38SJeff Roberson 
40677b542eSDavid E. O'Brien #include <sys/cdefs.h>
41113dda8aSJeff Roberson __FBSDID("$FreeBSD$");
42677b542eSDavid E. O'Brien 
434da0d332SPeter Wemm #include "opt_hwpmc_hooks.h"
444da0d332SPeter Wemm #include "opt_sched.h"
459923b511SScott Long 
4635e6168fSJeff Roberson #include <sys/param.h>
4735e6168fSJeff Roberson #include <sys/systm.h>
482c3490b1SMarcel Moolenaar #include <sys/kdb.h>
4935e6168fSJeff Roberson #include <sys/kernel.h>
5035e6168fSJeff Roberson #include <sys/ktr.h>
51c149e542SAttilio Rao #include <sys/limits.h>
5235e6168fSJeff Roberson #include <sys/lock.h>
5335e6168fSJeff Roberson #include <sys/mutex.h>
5435e6168fSJeff Roberson #include <sys/proc.h>
55245f3abfSJeff Roberson #include <sys/resource.h>
569bacd788SJeff Roberson #include <sys/resourcevar.h>
5735e6168fSJeff Roberson #include <sys/sched.h>
58b3e9e682SRyan Stone #include <sys/sdt.h>
5935e6168fSJeff Roberson #include <sys/smp.h>
6035e6168fSJeff Roberson #include <sys/sx.h>
6135e6168fSJeff Roberson #include <sys/sysctl.h>
6235e6168fSJeff Roberson #include <sys/sysproto.h>
63f5c157d9SJohn Baldwin #include <sys/turnstile.h>
643db720fdSDavid Xu #include <sys/umtx.h>
6535e6168fSJeff Roberson #include <sys/vmmeter.h>
6662fa74d9SJeff Roberson #include <sys/cpuset.h>
6707095abfSIvan Voras #include <sys/sbuf.h>
6835e6168fSJeff Roberson 
69ebccf1e3SJoseph Koshy #ifdef HWPMC_HOOKS
70ebccf1e3SJoseph Koshy #include <sys/pmckern.h>
71ebccf1e3SJoseph Koshy #endif
72ebccf1e3SJoseph Koshy 
736f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
746f5f25e5SJohn Birrell #include <sys/dtrace_bsd.h>
756f5f25e5SJohn Birrell int				dtrace_vtime_active;
766f5f25e5SJohn Birrell dtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
776f5f25e5SJohn Birrell #endif
786f5f25e5SJohn Birrell 
7935e6168fSJeff Roberson #include <machine/cpu.h>
8022bf7d9aSJeff Roberson #include <machine/smp.h>
8135e6168fSJeff Roberson 
82ae7a6b38SJeff Roberson #define	KTR_ULE	0
8314618990SJeff Roberson 
840d2cf837SJeff Roberson #define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
850d2cf837SJeff Roberson #define	TDQ_NAME_LEN	(sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
866338c579SAttilio Rao #define	TDQ_LOADNAME_LEN	(sizeof("CPU ") + sizeof(__XSTRING(MAXCPU)) - 1 + sizeof(" load"))
878f51ad55SJeff Roberson 
886b2f763fSJeff Roberson /*
89ae7a6b38SJeff Roberson  * Thread scheduler specific section.  All fields are protected
90ae7a6b38SJeff Roberson  * by the thread lock.
91ed062c8dSJulian Elischer  */
92ad1e7d28SJulian Elischer struct td_sched {
93ae7a6b38SJeff Roberson 	struct runq	*ts_runq;	/* Run-queue we're queued on. */
94ae7a6b38SJeff Roberson 	short		ts_flags;	/* TSF_* flags. */
95e77f9fedSAdrian Chadd 	int		ts_cpu;		/* CPU that we have affinity for. */
9673daf66fSJeff Roberson 	int		ts_rltick;	/* Real last tick, for affinity. */
97ae7a6b38SJeff Roberson 	int		ts_slice;	/* Ticks of slice remaining. */
98ae7a6b38SJeff Roberson 	u_int		ts_slptime;	/* Number of ticks we vol. slept */
99ae7a6b38SJeff Roberson 	u_int		ts_runtime;	/* Number of ticks we were running */
100ad1e7d28SJulian Elischer 	int		ts_ltick;	/* Last tick that we were running on */
101ad1e7d28SJulian Elischer 	int		ts_ftick;	/* First tick that we were running on */
102ad1e7d28SJulian Elischer 	int		ts_ticks;	/* Tick count */
1038f51ad55SJeff Roberson #ifdef KTR
1048f51ad55SJeff Roberson 	char		ts_name[TS_NAME_LEN];
1058f51ad55SJeff Roberson #endif
106ed062c8dSJulian Elischer };
107ad1e7d28SJulian Elischer /* flags kept in ts_flags */
1087b8bfa0dSJeff Roberson #define	TSF_BOUND	0x0001		/* Thread can not migrate. */
1097b8bfa0dSJeff Roberson #define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
11035e6168fSJeff Roberson 
11162fa74d9SJeff Roberson #define	THREAD_CAN_MIGRATE(td)	((td)->td_pinned == 0)
11262fa74d9SJeff Roberson #define	THREAD_CAN_SCHED(td, cpu)	\
11362fa74d9SJeff Roberson     CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
11462fa74d9SJeff Roberson 
11593ccd6bfSKonstantin Belousov _Static_assert(sizeof(struct thread) + sizeof(struct td_sched) <=
11693ccd6bfSKonstantin Belousov     sizeof(struct thread0_storage),
11793ccd6bfSKonstantin Belousov     "increase struct thread0_storage.t0st_sched size");
11893ccd6bfSKonstantin Belousov 
11935e6168fSJeff Roberson /*
12012d56c0fSJohn Baldwin  * Priority ranges used for interactive and non-interactive timeshare
1212dc29adbSJohn Baldwin  * threads.  The timeshare priorities are split up into four ranges.
1222dc29adbSJohn Baldwin  * The first range handles interactive threads.  The last three ranges
1232dc29adbSJohn Baldwin  * (NHALF, x, and NHALF) handle non-interactive threads with the outer
1242dc29adbSJohn Baldwin  * ranges supporting nice values.
12512d56c0fSJohn Baldwin  */
1262dc29adbSJohn Baldwin #define	PRI_TIMESHARE_RANGE	(PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
1272dc29adbSJohn Baldwin #define	PRI_INTERACT_RANGE	((PRI_TIMESHARE_RANGE - SCHED_PRI_NRESV) / 2)
12816705791SAndriy Gapon #define	PRI_BATCH_RANGE		(PRI_TIMESHARE_RANGE - PRI_INTERACT_RANGE)
1292dc29adbSJohn Baldwin 
1302dc29adbSJohn Baldwin #define	PRI_MIN_INTERACT	PRI_MIN_TIMESHARE
1312dc29adbSJohn Baldwin #define	PRI_MAX_INTERACT	(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE - 1)
1322dc29adbSJohn Baldwin #define	PRI_MIN_BATCH		(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE)
13312d56c0fSJohn Baldwin #define	PRI_MAX_BATCH		PRI_MAX_TIMESHARE
13412d56c0fSJohn Baldwin 
13512d56c0fSJohn Baldwin /*
136e7d50326SJeff Roberson  * Cpu percentage computation macros and defines.
137e1f89c22SJeff Roberson  *
138e7d50326SJeff Roberson  * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
139e7d50326SJeff Roberson  * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
1408ab80cf0SJeff Roberson  * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
141e7d50326SJeff Roberson  * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
142e7d50326SJeff Roberson  * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
143e7d50326SJeff Roberson  * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
14435e6168fSJeff Roberson  */
145e7d50326SJeff Roberson #define	SCHED_TICK_SECS		10
146e7d50326SJeff Roberson #define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
1478ab80cf0SJeff Roberson #define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
148e7d50326SJeff Roberson #define	SCHED_TICK_SHIFT	10
149e7d50326SJeff Roberson #define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
150eddb4efaSJeff Roberson #define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
15135e6168fSJeff Roberson 
15235e6168fSJeff Roberson /*
153e7d50326SJeff Roberson  * These macros determine priorities for non-interactive threads.  They are
154e7d50326SJeff Roberson  * assigned a priority based on their recent cpu utilization as expressed
155e7d50326SJeff Roberson  * by the ratio of ticks to the tick total.  NHALF priorities at the start
156e7d50326SJeff Roberson  * and end of the MIN to MAX timeshare range are only reachable with negative
157e7d50326SJeff Roberson  * or positive nice respectively.
158e7d50326SJeff Roberson  *
159e7d50326SJeff Roberson  * PRI_RANGE:	Priority range for utilization dependent priorities.
160e7d50326SJeff Roberson  * PRI_NRESV:	Number of nice values.
161e7d50326SJeff Roberson  * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
162e7d50326SJeff Roberson  * PRI_NICE:	Determines the part of the priority inherited from nice.
163e7d50326SJeff Roberson  */
164e7d50326SJeff Roberson #define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
165e7d50326SJeff Roberson #define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
16612d56c0fSJohn Baldwin #define	SCHED_PRI_MIN		(PRI_MIN_BATCH + SCHED_PRI_NHALF)
16712d56c0fSJohn Baldwin #define	SCHED_PRI_MAX		(PRI_MAX_BATCH - SCHED_PRI_NHALF)
16878920008SJohn Baldwin #define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN + 1)
169e7d50326SJeff Roberson #define	SCHED_PRI_TICKS(ts)						\
170e7d50326SJeff Roberson     (SCHED_TICK_HZ((ts)) /						\
1711e516cf5SJeff Roberson     (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
172e7d50326SJeff Roberson #define	SCHED_PRI_NICE(nice)	(nice)
173e7d50326SJeff Roberson 
174e7d50326SJeff Roberson /*
175e7d50326SJeff Roberson  * These determine the interactivity of a process.  Interactivity differs from
176e7d50326SJeff Roberson  * cpu utilization in that it expresses the voluntary time slept vs time ran
177e7d50326SJeff Roberson  * while cpu utilization includes all time not running.  This more accurately
178e7d50326SJeff Roberson  * models the intent of the thread.
17935e6168fSJeff Roberson  *
180407b0157SJeff Roberson  * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
181407b0157SJeff Roberson  *		before throttling back.
182d322132cSJeff Roberson  * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
183210491d3SJeff Roberson  * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
1849f518f20SAttilio Rao  * INTERACT_THRESH:	Threshold for placement on the current runq.
18535e6168fSJeff Roberson  */
186e7d50326SJeff Roberson #define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
187e7d50326SJeff Roberson #define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
188210491d3SJeff Roberson #define	SCHED_INTERACT_MAX	(100)
189210491d3SJeff Roberson #define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
1904c9612c6SJeff Roberson #define	SCHED_INTERACT_THRESH	(30)
191e1f89c22SJeff Roberson 
1925e5c3873SJeff Roberson /*
1935e5c3873SJeff Roberson  * These parameters determine the slice behavior for batch work.
1945e5c3873SJeff Roberson  */
1955e5c3873SJeff Roberson #define	SCHED_SLICE_DEFAULT_DIVISOR	10	/* ~94 ms, 12 stathz ticks. */
1965e5c3873SJeff Roberson #define	SCHED_SLICE_MIN_DIVISOR		6	/* DEFAULT/MIN = ~16 ms. */
1975e5c3873SJeff Roberson 
1983d7f4117SAlexander Motin /* Flags kept in td_flags. */
1993d7f4117SAlexander Motin #define	TDF_SLICEEND	TDF_SCHED2	/* Thread time slice is over. */
2003d7f4117SAlexander Motin 
20135e6168fSJeff Roberson /*
202e7d50326SJeff Roberson  * tickincr:		Converts a stathz tick into a hz domain scaled by
203e7d50326SJeff Roberson  *			the shift factor.  Without the shift the error rate
204e7d50326SJeff Roberson  *			due to rounding would be unacceptably high.
205e7d50326SJeff Roberson  * realstathz:		stathz is sometimes 0 and run off of hz.
206e7d50326SJeff Roberson  * sched_slice:		Runtime of each thread before rescheduling.
207ae7a6b38SJeff Roberson  * preempt_thresh:	Priority threshold for preemption and remote IPIs.
20835e6168fSJeff Roberson  */
209e7d50326SJeff Roberson static int sched_interact = SCHED_INTERACT_THRESH;
210db702c59SEitan Adler static int tickincr = 8 << SCHED_TICK_SHIFT;
2115e5c3873SJeff Roberson static int realstathz = 127;	/* reset during boot. */
2125e5c3873SJeff Roberson static int sched_slice = 10;	/* reset during boot. */
2135e5c3873SJeff Roberson static int sched_slice_min = 1;	/* reset during boot. */
21402e2d6b4SJeff Roberson #ifdef PREEMPTION
21502e2d6b4SJeff Roberson #ifdef FULL_PREEMPTION
21602e2d6b4SJeff Roberson static int preempt_thresh = PRI_MAX_IDLE;
21702e2d6b4SJeff Roberson #else
218ae7a6b38SJeff Roberson static int preempt_thresh = PRI_MIN_KERN;
21902e2d6b4SJeff Roberson #endif
22002e2d6b4SJeff Roberson #else
22102e2d6b4SJeff Roberson static int preempt_thresh = 0;
22202e2d6b4SJeff Roberson #endif
22312d56c0fSJohn Baldwin static int static_boost = PRI_MIN_BATCH;
2241690c6c1SJeff Roberson static int sched_idlespins = 10000;
225b3f40a41SAlexander Motin static int sched_idlespinthresh = -1;
226ae7a6b38SJeff Roberson 
22735e6168fSJeff Roberson /*
228ae7a6b38SJeff Roberson  * tdq - per processor runqs and statistics.  All fields are protected by the
229ae7a6b38SJeff Roberson  * tdq_lock.  The load and lowpri may be accessed without to avoid excess
230ae7a6b38SJeff Roberson  * locking in sched_pickcpu();
23135e6168fSJeff Roberson  */
232ad1e7d28SJulian Elischer struct tdq {
23339f819e2SJim Harris 	/*
23439f819e2SJim Harris 	 * Ordered to improve efficiency of cpu_search() and switch().
23539f819e2SJim Harris 	 * tdq_lock is padded to avoid false sharing with tdq_load and
23639f819e2SJim Harris 	 * tdq_cpu_idle.
23739f819e2SJim Harris 	 */
2384ceaf45dSAttilio Rao 	struct mtx_padalign tdq_lock;		/* run queue lock. */
23973daf66fSJeff Roberson 	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
2401690c6c1SJeff Roberson 	volatile int	tdq_load;		/* Aggregate load. */
2419f9ad565SAlexander Motin 	volatile int	tdq_cpu_idle;		/* cpu_idle() is active. */
24273daf66fSJeff Roberson 	int		tdq_sysload;		/* For loadavg, !ITHD load. */
24373daf66fSJeff Roberson 	int		tdq_transferable;	/* Transferable thread count. */
2441690c6c1SJeff Roberson 	short		tdq_switchcnt;		/* Switches this tick. */
2451690c6c1SJeff Roberson 	short		tdq_oldswitchcnt;	/* Switches last tick. */
24673daf66fSJeff Roberson 	u_char		tdq_lowpri;		/* Lowest priority thread. */
24773daf66fSJeff Roberson 	u_char		tdq_ipipending;		/* IPI pending. */
24873daf66fSJeff Roberson 	u_char		tdq_idx;		/* Current insert index. */
24973daf66fSJeff Roberson 	u_char		tdq_ridx;		/* Current removal index. */
250e7d50326SJeff Roberson 	struct runq	tdq_realtime;		/* real-time run queue. */
251ae7a6b38SJeff Roberson 	struct runq	tdq_timeshare;		/* timeshare run queue. */
252ae7a6b38SJeff Roberson 	struct runq	tdq_idle;		/* Queue of IDLE threads. */
2538f51ad55SJeff Roberson 	char		tdq_name[TDQ_NAME_LEN];
2548f51ad55SJeff Roberson #ifdef KTR
2558f51ad55SJeff Roberson 	char		tdq_loadname[TDQ_LOADNAME_LEN];
2568f51ad55SJeff Roberson #endif
257ae7a6b38SJeff Roberson } __aligned(64);
25835e6168fSJeff Roberson 
2591690c6c1SJeff Roberson /* Idle thread states and config. */
2601690c6c1SJeff Roberson #define	TDQ_RUNNING	1
2611690c6c1SJeff Roberson #define	TDQ_IDLE	2
2627b8bfa0dSJeff Roberson 
26380f86c9fSJeff Roberson #ifdef SMP
26407095abfSIvan Voras struct cpu_group *cpu_top;		/* CPU topology */
2657b8bfa0dSJeff Roberson 
26662fa74d9SJeff Roberson #define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
26762fa74d9SJeff Roberson #define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
2687b8bfa0dSJeff Roberson 
2697b8bfa0dSJeff Roberson /*
2707b8bfa0dSJeff Roberson  * Run-time tunables.
2717b8bfa0dSJeff Roberson  */
27228994a58SJeff Roberson static int rebalance = 1;
2737fcf154aSJeff Roberson static int balance_interval = 128;	/* Default set in sched_initticks(). */
2747b8bfa0dSJeff Roberson static int affinity;
27528994a58SJeff Roberson static int steal_idle = 1;
27628994a58SJeff Roberson static int steal_thresh = 2;
27780f86c9fSJeff Roberson 
27835e6168fSJeff Roberson /*
279d2ad694cSJeff Roberson  * One thread queue per processor.
28035e6168fSJeff Roberson  */
281ad1e7d28SJulian Elischer static struct tdq	tdq_cpu[MAXCPU];
2827fcf154aSJeff Roberson static struct tdq	*balance_tdq;
2837fcf154aSJeff Roberson static int balance_ticks;
28436acfc65SAlexander Motin static DPCPU_DEFINE(uint32_t, randomval);
285dc03363dSJeff Roberson 
286ad1e7d28SJulian Elischer #define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
287ad1e7d28SJulian Elischer #define	TDQ_CPU(x)	(&tdq_cpu[(x)])
288c47f202bSJeff Roberson #define	TDQ_ID(x)	((int)((x) - tdq_cpu))
28980f86c9fSJeff Roberson #else	/* !SMP */
290ad1e7d28SJulian Elischer static struct tdq	tdq_cpu;
291dc03363dSJeff Roberson 
29236b36916SJeff Roberson #define	TDQ_ID(x)	(0)
293ad1e7d28SJulian Elischer #define	TDQ_SELF()	(&tdq_cpu)
294ad1e7d28SJulian Elischer #define	TDQ_CPU(x)	(&tdq_cpu)
2950a016a05SJeff Roberson #endif
29635e6168fSJeff Roberson 
297ae7a6b38SJeff Roberson #define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
298ae7a6b38SJeff Roberson #define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
299ae7a6b38SJeff Roberson #define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
300ae7a6b38SJeff Roberson #define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
3014ceaf45dSAttilio Rao #define	TDQ_LOCKPTR(t)		((struct mtx *)(&(t)->tdq_lock))
302ae7a6b38SJeff Roberson 
3038460a577SJohn Birrell static void sched_priority(struct thread *);
30421381d1bSJeff Roberson static void sched_thread_priority(struct thread *, u_char);
3058460a577SJohn Birrell static int sched_interact_score(struct thread *);
3068460a577SJohn Birrell static void sched_interact_update(struct thread *);
3078460a577SJohn Birrell static void sched_interact_fork(struct thread *);
3087295465eSAlexander Motin static void sched_pctcpu_update(struct td_sched *, int);
30935e6168fSJeff Roberson 
3105d7ef00cSJeff Roberson /* Operations on per processor queues */
3119727e637SJeff Roberson static struct thread *tdq_choose(struct tdq *);
312ad1e7d28SJulian Elischer static void tdq_setup(struct tdq *);
3139727e637SJeff Roberson static void tdq_load_add(struct tdq *, struct thread *);
3149727e637SJeff Roberson static void tdq_load_rem(struct tdq *, struct thread *);
3159727e637SJeff Roberson static __inline void tdq_runq_add(struct tdq *, struct thread *, int);
3169727e637SJeff Roberson static __inline void tdq_runq_rem(struct tdq *, struct thread *);
317ff256d9cSJeff Roberson static inline int sched_shouldpreempt(int, int, int);
318ad1e7d28SJulian Elischer void tdq_print(int cpu);
319e7d50326SJeff Roberson static void runq_print(struct runq *rq);
320ae7a6b38SJeff Roberson static void tdq_add(struct tdq *, struct thread *, int);
3215d7ef00cSJeff Roberson #ifdef SMP
32262fa74d9SJeff Roberson static int tdq_move(struct tdq *, struct tdq *);
323ad1e7d28SJulian Elischer static int tdq_idled(struct tdq *);
32427ee18adSRyan Stone static void tdq_notify(struct tdq *, struct thread *);
3259727e637SJeff Roberson static struct thread *tdq_steal(struct tdq *, int);
3269727e637SJeff Roberson static struct thread *runq_steal(struct runq *, int);
3279727e637SJeff Roberson static int sched_pickcpu(struct thread *, int);
3287fcf154aSJeff Roberson static void sched_balance(void);
32962fa74d9SJeff Roberson static int sched_balance_pair(struct tdq *, struct tdq *);
3309727e637SJeff Roberson static inline struct tdq *sched_setcpu(struct thread *, int, int);
331ae7a6b38SJeff Roberson static inline void thread_unblock_switch(struct thread *, struct mtx *);
332c47f202bSJeff Roberson static struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
33307095abfSIvan Voras static int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
33407095abfSIvan Voras static int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
33507095abfSIvan Voras     struct cpu_group *cg, int indent);
3365d7ef00cSJeff Roberson #endif
3375d7ef00cSJeff Roberson 
338e7d50326SJeff Roberson static void sched_setup(void *dummy);
339237fdd78SRobert Watson SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
340e7d50326SJeff Roberson 
341e7d50326SJeff Roberson static void sched_initticks(void *dummy);
342237fdd78SRobert Watson SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
343237fdd78SRobert Watson     NULL);
344e7d50326SJeff Roberson 
345b3e9e682SRyan Stone SDT_PROVIDER_DEFINE(sched);
346b3e9e682SRyan Stone 
347d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
348b3e9e682SRyan Stone     "struct proc *", "uint8_t");
349d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
350b3e9e682SRyan Stone     "struct proc *", "void *");
351d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
352b3e9e682SRyan Stone     "struct proc *", "void *", "int");
353d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
354b3e9e682SRyan Stone     "struct proc *", "uint8_t", "struct thread *");
355d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
356d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
357b3e9e682SRyan Stone     "struct proc *");
358d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , on__cpu);
359d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , remain__cpu);
360d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
361b3e9e682SRyan Stone     "struct proc *");
362b3e9e682SRyan Stone 
3630567b6ccSWarner Losh /*
364ae7a6b38SJeff Roberson  * Print the threads waiting on a run-queue.
365ae7a6b38SJeff Roberson  */
366e7d50326SJeff Roberson static void
367e7d50326SJeff Roberson runq_print(struct runq *rq)
368e7d50326SJeff Roberson {
369e7d50326SJeff Roberson 	struct rqhead *rqh;
3709727e637SJeff Roberson 	struct thread *td;
371e7d50326SJeff Roberson 	int pri;
372e7d50326SJeff Roberson 	int j;
373e7d50326SJeff Roberson 	int i;
374e7d50326SJeff Roberson 
375e7d50326SJeff Roberson 	for (i = 0; i < RQB_LEN; i++) {
376e7d50326SJeff Roberson 		printf("\t\trunq bits %d 0x%zx\n",
377e7d50326SJeff Roberson 		    i, rq->rq_status.rqb_bits[i]);
378e7d50326SJeff Roberson 		for (j = 0; j < RQB_BPW; j++)
379e7d50326SJeff Roberson 			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
380e7d50326SJeff Roberson 				pri = j + (i << RQB_L2BPW);
381e7d50326SJeff Roberson 				rqh = &rq->rq_queues[pri];
3829727e637SJeff Roberson 				TAILQ_FOREACH(td, rqh, td_runq) {
383e7d50326SJeff Roberson 					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
3849727e637SJeff Roberson 					    td, td->td_name, td->td_priority,
3859727e637SJeff Roberson 					    td->td_rqindex, pri);
386e7d50326SJeff Roberson 				}
387e7d50326SJeff Roberson 			}
388e7d50326SJeff Roberson 	}
389e7d50326SJeff Roberson }
390e7d50326SJeff Roberson 
391ae7a6b38SJeff Roberson /*
392ae7a6b38SJeff Roberson  * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
393ae7a6b38SJeff Roberson  */
39415dc847eSJeff Roberson void
395ad1e7d28SJulian Elischer tdq_print(int cpu)
39615dc847eSJeff Roberson {
397ad1e7d28SJulian Elischer 	struct tdq *tdq;
39815dc847eSJeff Roberson 
399ad1e7d28SJulian Elischer 	tdq = TDQ_CPU(cpu);
40015dc847eSJeff Roberson 
401c47f202bSJeff Roberson 	printf("tdq %d:\n", TDQ_ID(tdq));
40262fa74d9SJeff Roberson 	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
40362fa74d9SJeff Roberson 	printf("\tLock name:      %s\n", tdq->tdq_name);
404d2ad694cSJeff Roberson 	printf("\tload:           %d\n", tdq->tdq_load);
4051690c6c1SJeff Roberson 	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
4061690c6c1SJeff Roberson 	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
407e7d50326SJeff Roberson 	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
4083f872f85SJeff Roberson 	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
4091690c6c1SJeff Roberson 	printf("\tload transferable: %d\n", tdq->tdq_transferable);
4101690c6c1SJeff Roberson 	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
411e7d50326SJeff Roberson 	printf("\trealtime runq:\n");
412e7d50326SJeff Roberson 	runq_print(&tdq->tdq_realtime);
413e7d50326SJeff Roberson 	printf("\ttimeshare runq:\n");
414e7d50326SJeff Roberson 	runq_print(&tdq->tdq_timeshare);
415e7d50326SJeff Roberson 	printf("\tidle runq:\n");
416e7d50326SJeff Roberson 	runq_print(&tdq->tdq_idle);
41715dc847eSJeff Roberson }
41815dc847eSJeff Roberson 
419ff256d9cSJeff Roberson static inline int
420ff256d9cSJeff Roberson sched_shouldpreempt(int pri, int cpri, int remote)
421ff256d9cSJeff Roberson {
422ff256d9cSJeff Roberson 	/*
423ff256d9cSJeff Roberson 	 * If the new priority is not better than the current priority there is
424ff256d9cSJeff Roberson 	 * nothing to do.
425ff256d9cSJeff Roberson 	 */
426ff256d9cSJeff Roberson 	if (pri >= cpri)
427ff256d9cSJeff Roberson 		return (0);
428ff256d9cSJeff Roberson 	/*
429ff256d9cSJeff Roberson 	 * Always preempt idle.
430ff256d9cSJeff Roberson 	 */
431ff256d9cSJeff Roberson 	if (cpri >= PRI_MIN_IDLE)
432ff256d9cSJeff Roberson 		return (1);
433ff256d9cSJeff Roberson 	/*
434ff256d9cSJeff Roberson 	 * If preemption is disabled don't preempt others.
435ff256d9cSJeff Roberson 	 */
436ff256d9cSJeff Roberson 	if (preempt_thresh == 0)
437ff256d9cSJeff Roberson 		return (0);
438ff256d9cSJeff Roberson 	/*
439ff256d9cSJeff Roberson 	 * Preempt if we exceed the threshold.
440ff256d9cSJeff Roberson 	 */
441ff256d9cSJeff Roberson 	if (pri <= preempt_thresh)
442ff256d9cSJeff Roberson 		return (1);
443ff256d9cSJeff Roberson 	/*
44412d56c0fSJohn Baldwin 	 * If we're interactive or better and there is non-interactive
44512d56c0fSJohn Baldwin 	 * or worse running preempt only remote processors.
446ff256d9cSJeff Roberson 	 */
44712d56c0fSJohn Baldwin 	if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
448ff256d9cSJeff Roberson 		return (1);
449ff256d9cSJeff Roberson 	return (0);
450ff256d9cSJeff Roberson }
451ff256d9cSJeff Roberson 
452ae7a6b38SJeff Roberson /*
453ae7a6b38SJeff Roberson  * Add a thread to the actual run-queue.  Keeps transferable counts up to
454ae7a6b38SJeff Roberson  * date with what is actually on the run-queue.  Selects the correct
455ae7a6b38SJeff Roberson  * queue position for timeshare threads.
456ae7a6b38SJeff Roberson  */
457155b9987SJeff Roberson static __inline void
4589727e637SJeff Roberson tdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
459155b9987SJeff Roberson {
4609727e637SJeff Roberson 	struct td_sched *ts;
461c143ac21SJeff Roberson 	u_char pri;
462c143ac21SJeff Roberson 
463ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
4649727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
46573daf66fSJeff Roberson 
4669727e637SJeff Roberson 	pri = td->td_priority;
46793ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
4689727e637SJeff Roberson 	TD_SET_RUNQ(td);
4699727e637SJeff Roberson 	if (THREAD_CAN_MIGRATE(td)) {
470d2ad694cSJeff Roberson 		tdq->tdq_transferable++;
471ad1e7d28SJulian Elischer 		ts->ts_flags |= TSF_XFERABLE;
47280f86c9fSJeff Roberson 	}
47312d56c0fSJohn Baldwin 	if (pri < PRI_MIN_BATCH) {
474c143ac21SJeff Roberson 		ts->ts_runq = &tdq->tdq_realtime;
47512d56c0fSJohn Baldwin 	} else if (pri <= PRI_MAX_BATCH) {
476c143ac21SJeff Roberson 		ts->ts_runq = &tdq->tdq_timeshare;
47712d56c0fSJohn Baldwin 		KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
478e7d50326SJeff Roberson 			("Invalid priority %d on timeshare runq", pri));
479e7d50326SJeff Roberson 		/*
480e7d50326SJeff Roberson 		 * This queue contains only priorities between MIN and MAX
481e7d50326SJeff Roberson 		 * realtime.  Use the whole queue to represent these values.
482e7d50326SJeff Roberson 		 */
483c47f202bSJeff Roberson 		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
48416705791SAndriy Gapon 			pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
485e7d50326SJeff Roberson 			pri = (pri + tdq->tdq_idx) % RQ_NQS;
4863f872f85SJeff Roberson 			/*
4873f872f85SJeff Roberson 			 * This effectively shortens the queue by one so we
4883f872f85SJeff Roberson 			 * can have a one slot difference between idx and
4893f872f85SJeff Roberson 			 * ridx while we wait for threads to drain.
4903f872f85SJeff Roberson 			 */
4913f872f85SJeff Roberson 			if (tdq->tdq_ridx != tdq->tdq_idx &&
4923f872f85SJeff Roberson 			    pri == tdq->tdq_ridx)
4934499aff6SJeff Roberson 				pri = (unsigned char)(pri - 1) % RQ_NQS;
494e7d50326SJeff Roberson 		} else
4953f872f85SJeff Roberson 			pri = tdq->tdq_ridx;
4969727e637SJeff Roberson 		runq_add_pri(ts->ts_runq, td, pri, flags);
497c143ac21SJeff Roberson 		return;
498e7d50326SJeff Roberson 	} else
49973daf66fSJeff Roberson 		ts->ts_runq = &tdq->tdq_idle;
5009727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
50173daf66fSJeff Roberson }
50273daf66fSJeff Roberson 
50373daf66fSJeff Roberson /*
504ae7a6b38SJeff Roberson  * Remove a thread from a run-queue.  This typically happens when a thread
505ae7a6b38SJeff Roberson  * is selected to run.  Running threads are not on the queue and the
506ae7a6b38SJeff Roberson  * transferable count does not reflect them.
507ae7a6b38SJeff Roberson  */
508155b9987SJeff Roberson static __inline void
5099727e637SJeff Roberson tdq_runq_rem(struct tdq *tdq, struct thread *td)
510155b9987SJeff Roberson {
5119727e637SJeff Roberson 	struct td_sched *ts;
5129727e637SJeff Roberson 
51393ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
514ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
515ae7a6b38SJeff Roberson 	KASSERT(ts->ts_runq != NULL,
5169727e637SJeff Roberson 	    ("tdq_runq_remove: thread %p null ts_runq", td));
517ad1e7d28SJulian Elischer 	if (ts->ts_flags & TSF_XFERABLE) {
518d2ad694cSJeff Roberson 		tdq->tdq_transferable--;
519ad1e7d28SJulian Elischer 		ts->ts_flags &= ~TSF_XFERABLE;
52080f86c9fSJeff Roberson 	}
5213f872f85SJeff Roberson 	if (ts->ts_runq == &tdq->tdq_timeshare) {
5223f872f85SJeff Roberson 		if (tdq->tdq_idx != tdq->tdq_ridx)
5239727e637SJeff Roberson 			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
524e7d50326SJeff Roberson 		else
5259727e637SJeff Roberson 			runq_remove_idx(ts->ts_runq, td, NULL);
5263f872f85SJeff Roberson 	} else
5279727e637SJeff Roberson 		runq_remove(ts->ts_runq, td);
528155b9987SJeff Roberson }
529155b9987SJeff Roberson 
530ae7a6b38SJeff Roberson /*
531ae7a6b38SJeff Roberson  * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
532ae7a6b38SJeff Roberson  * for this thread to the referenced thread queue.
533ae7a6b38SJeff Roberson  */
534a8949de2SJeff Roberson static void
5359727e637SJeff Roberson tdq_load_add(struct tdq *tdq, struct thread *td)
5365d7ef00cSJeff Roberson {
537ae7a6b38SJeff Roberson 
538ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
5399727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
54003d17db7SJeff Roberson 
541d2ad694cSJeff Roberson 	tdq->tdq_load++;
5421b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
543d2ad694cSJeff Roberson 		tdq->tdq_sysload++;
5448f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
545d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
5465d7ef00cSJeff Roberson }
54715dc847eSJeff Roberson 
548ae7a6b38SJeff Roberson /*
549ae7a6b38SJeff Roberson  * Remove the load from a thread that is transitioning to a sleep state or
550ae7a6b38SJeff Roberson  * exiting.
551ae7a6b38SJeff Roberson  */
552a8949de2SJeff Roberson static void
5539727e637SJeff Roberson tdq_load_rem(struct tdq *tdq, struct thread *td)
5545d7ef00cSJeff Roberson {
555ae7a6b38SJeff Roberson 
5569727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
557ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
558ae7a6b38SJeff Roberson 	KASSERT(tdq->tdq_load != 0,
559c47f202bSJeff Roberson 	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
56003d17db7SJeff Roberson 
561d2ad694cSJeff Roberson 	tdq->tdq_load--;
5621b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
56303d17db7SJeff Roberson 		tdq->tdq_sysload--;
5648f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
565d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
56615dc847eSJeff Roberson }
56715dc847eSJeff Roberson 
568356500a3SJeff Roberson /*
5695e5c3873SJeff Roberson  * Bound timeshare latency by decreasing slice size as load increases.  We
5705e5c3873SJeff Roberson  * consider the maximum latency as the sum of the threads waiting to run
5715e5c3873SJeff Roberson  * aside from curthread and target no more than sched_slice latency but
5725e5c3873SJeff Roberson  * no less than sched_slice_min runtime.
5735e5c3873SJeff Roberson  */
5745e5c3873SJeff Roberson static inline int
5755e5c3873SJeff Roberson tdq_slice(struct tdq *tdq)
5765e5c3873SJeff Roberson {
5775e5c3873SJeff Roberson 	int load;
5785e5c3873SJeff Roberson 
5795e5c3873SJeff Roberson 	/*
5805e5c3873SJeff Roberson 	 * It is safe to use sys_load here because this is called from
5815e5c3873SJeff Roberson 	 * contexts where timeshare threads are running and so there
5825e5c3873SJeff Roberson 	 * cannot be higher priority load in the system.
5835e5c3873SJeff Roberson 	 */
5845e5c3873SJeff Roberson 	load = tdq->tdq_sysload - 1;
5855e5c3873SJeff Roberson 	if (load >= SCHED_SLICE_MIN_DIVISOR)
5865e5c3873SJeff Roberson 		return (sched_slice_min);
5875e5c3873SJeff Roberson 	if (load <= 1)
5885e5c3873SJeff Roberson 		return (sched_slice);
5895e5c3873SJeff Roberson 	return (sched_slice / load);
5905e5c3873SJeff Roberson }
5915e5c3873SJeff Roberson 
5925e5c3873SJeff Roberson /*
59362fa74d9SJeff Roberson  * Set lowpri to its exact value by searching the run-queue and
59462fa74d9SJeff Roberson  * evaluating curthread.  curthread may be passed as an optimization.
595356500a3SJeff Roberson  */
59622bf7d9aSJeff Roberson static void
59762fa74d9SJeff Roberson tdq_setlowpri(struct tdq *tdq, struct thread *ctd)
59862fa74d9SJeff Roberson {
59962fa74d9SJeff Roberson 	struct thread *td;
60062fa74d9SJeff Roberson 
60162fa74d9SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
60262fa74d9SJeff Roberson 	if (ctd == NULL)
60362fa74d9SJeff Roberson 		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
6049727e637SJeff Roberson 	td = tdq_choose(tdq);
6059727e637SJeff Roberson 	if (td == NULL || td->td_priority > ctd->td_priority)
60662fa74d9SJeff Roberson 		tdq->tdq_lowpri = ctd->td_priority;
60762fa74d9SJeff Roberson 	else
60862fa74d9SJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
60962fa74d9SJeff Roberson }
61062fa74d9SJeff Roberson 
61162fa74d9SJeff Roberson #ifdef SMP
6129129dd59SPedro F. Giffuni /*
6139129dd59SPedro F. Giffuni  * We need some randomness. Implement a classic Linear Congruential
6149129dd59SPedro F. Giffuni  * Generator X_{n+1}=(aX_n+c) mod m. These values are optimized for
6159129dd59SPedro F. Giffuni  * m = 2^32, a = 69069 and c = 5. We only return the upper 16 bits
6169129dd59SPedro F. Giffuni  * of the random state (in the low bits of our answer) to keep
6179129dd59SPedro F. Giffuni  * the maximum randomness.
6189129dd59SPedro F. Giffuni  */
6199129dd59SPedro F. Giffuni static uint32_t
6209129dd59SPedro F. Giffuni sched_random(void)
6219129dd59SPedro F. Giffuni {
6229129dd59SPedro F. Giffuni 	uint32_t *rndptr;
6239129dd59SPedro F. Giffuni 
6249129dd59SPedro F. Giffuni 	rndptr = DPCPU_PTR(randomval);
6259129dd59SPedro F. Giffuni 	*rndptr = *rndptr * 69069 + 5;
6269129dd59SPedro F. Giffuni 
6279129dd59SPedro F. Giffuni 	return (*rndptr >> 16);
6289129dd59SPedro F. Giffuni }
6299129dd59SPedro F. Giffuni 
63062fa74d9SJeff Roberson struct cpu_search {
631c76ee827SJeff Roberson 	cpuset_t cs_mask;
63236acfc65SAlexander Motin 	u_int	cs_prefer;
63336acfc65SAlexander Motin 	int	cs_pri;		/* Min priority for low. */
63436acfc65SAlexander Motin 	int	cs_limit;	/* Max load for low, min load for high. */
63536acfc65SAlexander Motin 	int	cs_cpu;
63636acfc65SAlexander Motin 	int	cs_load;
63762fa74d9SJeff Roberson };
63862fa74d9SJeff Roberson 
63962fa74d9SJeff Roberson #define	CPU_SEARCH_LOWEST	0x1
64062fa74d9SJeff Roberson #define	CPU_SEARCH_HIGHEST	0x2
64162fa74d9SJeff Roberson #define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
64262fa74d9SJeff Roberson 
643c76ee827SJeff Roberson #define	CPUSET_FOREACH(cpu, mask)				\
644c76ee827SJeff Roberson 	for ((cpu) = 0; (cpu) <= mp_maxid; (cpu)++)		\
64571a19bdcSAttilio Rao 		if (CPU_ISSET(cpu, &mask))
64662fa74d9SJeff Roberson 
6472499a5ccSKonstantin Belousov static __always_inline int cpu_search(const struct cpu_group *cg,
6482499a5ccSKonstantin Belousov     struct cpu_search *low, struct cpu_search *high, const int match);
6492499a5ccSKonstantin Belousov int __noinline cpu_search_lowest(const struct cpu_group *cg,
6502499a5ccSKonstantin Belousov     struct cpu_search *low);
6512499a5ccSKonstantin Belousov int __noinline cpu_search_highest(const struct cpu_group *cg,
65262fa74d9SJeff Roberson     struct cpu_search *high);
6532499a5ccSKonstantin Belousov int __noinline cpu_search_both(const struct cpu_group *cg,
6542499a5ccSKonstantin Belousov     struct cpu_search *low, struct cpu_search *high);
65562fa74d9SJeff Roberson 
65662fa74d9SJeff Roberson /*
65762fa74d9SJeff Roberson  * Search the tree of cpu_groups for the lowest or highest loaded cpu
65862fa74d9SJeff Roberson  * according to the match argument.  This routine actually compares the
65962fa74d9SJeff Roberson  * load on all paths through the tree and finds the least loaded cpu on
66062fa74d9SJeff Roberson  * the least loaded path, which may differ from the least loaded cpu in
661db4fcadfSConrad Meyer  * the system.  This balances work among caches and buses.
66262fa74d9SJeff Roberson  *
66362fa74d9SJeff Roberson  * This inline is instantiated in three forms below using constants for the
66462fa74d9SJeff Roberson  * match argument.  It is reduced to the minimum set for each case.  It is
66562fa74d9SJeff Roberson  * also recursive to the depth of the tree.
66662fa74d9SJeff Roberson  */
6672499a5ccSKonstantin Belousov static __always_inline int
66836acfc65SAlexander Motin cpu_search(const struct cpu_group *cg, struct cpu_search *low,
66962fa74d9SJeff Roberson     struct cpu_search *high, const int match)
67062fa74d9SJeff Roberson {
67162fa74d9SJeff Roberson 	struct cpu_search lgroup;
67262fa74d9SJeff Roberson 	struct cpu_search hgroup;
67336acfc65SAlexander Motin 	cpuset_t cpumask;
67462fa74d9SJeff Roberson 	struct cpu_group *child;
67536acfc65SAlexander Motin 	struct tdq *tdq;
6760567b6ccSWarner Losh 	int cpu, i, hload, lload, load, total, rnd;
67762fa74d9SJeff Roberson 
67836acfc65SAlexander Motin 	total = 0;
67936acfc65SAlexander Motin 	cpumask = cg->cg_mask;
68062fa74d9SJeff Roberson 	if (match & CPU_SEARCH_LOWEST) {
68136acfc65SAlexander Motin 		lload = INT_MAX;
68262fa74d9SJeff Roberson 		lgroup = *low;
68362fa74d9SJeff Roberson 	}
68462fa74d9SJeff Roberson 	if (match & CPU_SEARCH_HIGHEST) {
68570801abeSAlexander Motin 		hload = INT_MIN;
68662fa74d9SJeff Roberson 		hgroup = *high;
68762fa74d9SJeff Roberson 	}
68836acfc65SAlexander Motin 
68936acfc65SAlexander Motin 	/* Iterate through the child CPU groups and then remaining CPUs. */
69058909b74SAlexander Motin 	for (i = cg->cg_children, cpu = mp_maxid; ; ) {
69170801abeSAlexander Motin 		if (i == 0) {
69258909b74SAlexander Motin #ifdef HAVE_INLINE_FFSL
69358909b74SAlexander Motin 			cpu = CPU_FFS(&cpumask) - 1;
69458909b74SAlexander Motin #else
69570801abeSAlexander Motin 			while (cpu >= 0 && !CPU_ISSET(cpu, &cpumask))
69670801abeSAlexander Motin 				cpu--;
69758909b74SAlexander Motin #endif
69870801abeSAlexander Motin 			if (cpu < 0)
69936acfc65SAlexander Motin 				break;
70036acfc65SAlexander Motin 			child = NULL;
70136acfc65SAlexander Motin 		} else
70270801abeSAlexander Motin 			child = &cg->cg_child[i - 1];
70336acfc65SAlexander Motin 
70470801abeSAlexander Motin 		if (match & CPU_SEARCH_LOWEST)
70570801abeSAlexander Motin 			lgroup.cs_cpu = -1;
70670801abeSAlexander Motin 		if (match & CPU_SEARCH_HIGHEST)
70770801abeSAlexander Motin 			hgroup.cs_cpu = -1;
70836acfc65SAlexander Motin 		if (child) {			/* Handle child CPU group. */
70936acfc65SAlexander Motin 			CPU_NAND(&cpumask, &child->cg_mask);
71062fa74d9SJeff Roberson 			switch (match) {
71162fa74d9SJeff Roberson 			case CPU_SEARCH_LOWEST:
71262fa74d9SJeff Roberson 				load = cpu_search_lowest(child, &lgroup);
71362fa74d9SJeff Roberson 				break;
71462fa74d9SJeff Roberson 			case CPU_SEARCH_HIGHEST:
71562fa74d9SJeff Roberson 				load = cpu_search_highest(child, &hgroup);
71662fa74d9SJeff Roberson 				break;
71762fa74d9SJeff Roberson 			case CPU_SEARCH_BOTH:
71862fa74d9SJeff Roberson 				load = cpu_search_both(child, &lgroup, &hgroup);
71962fa74d9SJeff Roberson 				break;
72062fa74d9SJeff Roberson 			}
72136acfc65SAlexander Motin 		} else {			/* Handle child CPU. */
72258909b74SAlexander Motin 			CPU_CLR(cpu, &cpumask);
72336acfc65SAlexander Motin 			tdq = TDQ_CPU(cpu);
72436acfc65SAlexander Motin 			load = tdq->tdq_load * 256;
725b250ad34SWarner Losh 			rnd = sched_random() % 32;
72636acfc65SAlexander Motin 			if (match & CPU_SEARCH_LOWEST) {
72736acfc65SAlexander Motin 				if (cpu == low->cs_prefer)
72836acfc65SAlexander Motin 					load -= 64;
72936acfc65SAlexander Motin 				/* If that CPU is allowed and get data. */
73070801abeSAlexander Motin 				if (tdq->tdq_lowpri > lgroup.cs_pri &&
73170801abeSAlexander Motin 				    tdq->tdq_load <= lgroup.cs_limit &&
73270801abeSAlexander Motin 				    CPU_ISSET(cpu, &lgroup.cs_mask)) {
73336acfc65SAlexander Motin 					lgroup.cs_cpu = cpu;
73436acfc65SAlexander Motin 					lgroup.cs_load = load - rnd;
73536acfc65SAlexander Motin 				}
73662fa74d9SJeff Roberson 			}
73762fa74d9SJeff Roberson 			if (match & CPU_SEARCH_HIGHEST)
73870801abeSAlexander Motin 				if (tdq->tdq_load >= hgroup.cs_limit &&
73970801abeSAlexander Motin 				    tdq->tdq_transferable &&
74070801abeSAlexander Motin 				    CPU_ISSET(cpu, &hgroup.cs_mask)) {
74136acfc65SAlexander Motin 					hgroup.cs_cpu = cpu;
74236acfc65SAlexander Motin 					hgroup.cs_load = load - rnd;
74362fa74d9SJeff Roberson 				}
74462fa74d9SJeff Roberson 		}
74536acfc65SAlexander Motin 		total += load;
74662fa74d9SJeff Roberson 
74736acfc65SAlexander Motin 		/* We have info about child item. Compare it. */
74836acfc65SAlexander Motin 		if (match & CPU_SEARCH_LOWEST) {
74970801abeSAlexander Motin 			if (lgroup.cs_cpu >= 0 &&
7506022f0bcSAlexander Motin 			    (load < lload ||
7516022f0bcSAlexander Motin 			     (load == lload && lgroup.cs_load < low->cs_load))) {
75236acfc65SAlexander Motin 				lload = load;
75336acfc65SAlexander Motin 				low->cs_cpu = lgroup.cs_cpu;
75436acfc65SAlexander Motin 				low->cs_load = lgroup.cs_load;
75536acfc65SAlexander Motin 			}
75636acfc65SAlexander Motin 		}
75736acfc65SAlexander Motin 		if (match & CPU_SEARCH_HIGHEST)
75870801abeSAlexander Motin 			if (hgroup.cs_cpu >= 0 &&
7596022f0bcSAlexander Motin 			    (load > hload ||
7606022f0bcSAlexander Motin 			     (load == hload && hgroup.cs_load > high->cs_load))) {
76136acfc65SAlexander Motin 				hload = load;
76236acfc65SAlexander Motin 				high->cs_cpu = hgroup.cs_cpu;
76336acfc65SAlexander Motin 				high->cs_load = hgroup.cs_load;
76436acfc65SAlexander Motin 			}
76570801abeSAlexander Motin 		if (child) {
76670801abeSAlexander Motin 			i--;
76770801abeSAlexander Motin 			if (i == 0 && CPU_EMPTY(&cpumask))
76870801abeSAlexander Motin 				break;
76958909b74SAlexander Motin 		}
77058909b74SAlexander Motin #ifndef HAVE_INLINE_FFSL
77158909b74SAlexander Motin 		else
77270801abeSAlexander Motin 			cpu--;
77358909b74SAlexander Motin #endif
77462fa74d9SJeff Roberson 	}
77562fa74d9SJeff Roberson 	return (total);
77662fa74d9SJeff Roberson }
77762fa74d9SJeff Roberson 
77862fa74d9SJeff Roberson /*
77962fa74d9SJeff Roberson  * cpu_search instantiations must pass constants to maintain the inline
78062fa74d9SJeff Roberson  * optimization.
78162fa74d9SJeff Roberson  */
78262fa74d9SJeff Roberson int
78336acfc65SAlexander Motin cpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low)
78462fa74d9SJeff Roberson {
78562fa74d9SJeff Roberson 	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
78662fa74d9SJeff Roberson }
78762fa74d9SJeff Roberson 
78862fa74d9SJeff Roberson int
78936acfc65SAlexander Motin cpu_search_highest(const struct cpu_group *cg, struct cpu_search *high)
79062fa74d9SJeff Roberson {
79162fa74d9SJeff Roberson 	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
79262fa74d9SJeff Roberson }
79362fa74d9SJeff Roberson 
79462fa74d9SJeff Roberson int
79536acfc65SAlexander Motin cpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
79662fa74d9SJeff Roberson     struct cpu_search *high)
79762fa74d9SJeff Roberson {
79862fa74d9SJeff Roberson 	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
79962fa74d9SJeff Roberson }
80062fa74d9SJeff Roberson 
80162fa74d9SJeff Roberson /*
80262fa74d9SJeff Roberson  * Find the cpu with the least load via the least loaded path that has a
80362fa74d9SJeff Roberson  * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
80462fa74d9SJeff Roberson  * acceptable.
80562fa74d9SJeff Roberson  */
80662fa74d9SJeff Roberson static inline int
80736acfc65SAlexander Motin sched_lowest(const struct cpu_group *cg, cpuset_t mask, int pri, int maxload,
80836acfc65SAlexander Motin     int prefer)
80962fa74d9SJeff Roberson {
81062fa74d9SJeff Roberson 	struct cpu_search low;
81162fa74d9SJeff Roberson 
81262fa74d9SJeff Roberson 	low.cs_cpu = -1;
81336acfc65SAlexander Motin 	low.cs_prefer = prefer;
81462fa74d9SJeff Roberson 	low.cs_mask = mask;
81536acfc65SAlexander Motin 	low.cs_pri = pri;
81636acfc65SAlexander Motin 	low.cs_limit = maxload;
81762fa74d9SJeff Roberson 	cpu_search_lowest(cg, &low);
81862fa74d9SJeff Roberson 	return low.cs_cpu;
81962fa74d9SJeff Roberson }
82062fa74d9SJeff Roberson 
82162fa74d9SJeff Roberson /*
82262fa74d9SJeff Roberson  * Find the cpu with the highest load via the highest loaded path.
82362fa74d9SJeff Roberson  */
82462fa74d9SJeff Roberson static inline int
82536acfc65SAlexander Motin sched_highest(const struct cpu_group *cg, cpuset_t mask, int minload)
82662fa74d9SJeff Roberson {
82762fa74d9SJeff Roberson 	struct cpu_search high;
82862fa74d9SJeff Roberson 
82962fa74d9SJeff Roberson 	high.cs_cpu = -1;
83062fa74d9SJeff Roberson 	high.cs_mask = mask;
83162fa74d9SJeff Roberson 	high.cs_limit = minload;
83262fa74d9SJeff Roberson 	cpu_search_highest(cg, &high);
83362fa74d9SJeff Roberson 	return high.cs_cpu;
83462fa74d9SJeff Roberson }
83562fa74d9SJeff Roberson 
83662fa74d9SJeff Roberson static void
83762fa74d9SJeff Roberson sched_balance_group(struct cpu_group *cg)
83862fa74d9SJeff Roberson {
83936acfc65SAlexander Motin 	cpuset_t hmask, lmask;
84036acfc65SAlexander Motin 	int high, low, anylow;
84162fa74d9SJeff Roberson 
84236acfc65SAlexander Motin 	CPU_FILL(&hmask);
84362fa74d9SJeff Roberson 	for (;;) {
84436acfc65SAlexander Motin 		high = sched_highest(cg, hmask, 1);
84536acfc65SAlexander Motin 		/* Stop if there is no more CPU with transferrable threads. */
84636acfc65SAlexander Motin 		if (high == -1)
84762fa74d9SJeff Roberson 			break;
84836acfc65SAlexander Motin 		CPU_CLR(high, &hmask);
84936acfc65SAlexander Motin 		CPU_COPY(&hmask, &lmask);
85036acfc65SAlexander Motin 		/* Stop if there is no more CPU left for low. */
85136acfc65SAlexander Motin 		if (CPU_EMPTY(&lmask))
85262fa74d9SJeff Roberson 			break;
85336acfc65SAlexander Motin 		anylow = 1;
85436acfc65SAlexander Motin nextlow:
85536acfc65SAlexander Motin 		low = sched_lowest(cg, lmask, -1,
85636acfc65SAlexander Motin 		    TDQ_CPU(high)->tdq_load - 1, high);
85736acfc65SAlexander Motin 		/* Stop if we looked well and found no less loaded CPU. */
85836acfc65SAlexander Motin 		if (anylow && low == -1)
85936acfc65SAlexander Motin 			break;
86036acfc65SAlexander Motin 		/* Go to next high if we found no less loaded CPU. */
86136acfc65SAlexander Motin 		if (low == -1)
86236acfc65SAlexander Motin 			continue;
86336acfc65SAlexander Motin 		/* Transfer thread from high to low. */
86436acfc65SAlexander Motin 		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low))) {
86536acfc65SAlexander Motin 			/* CPU that got thread can no longer be a donor. */
86636acfc65SAlexander Motin 			CPU_CLR(low, &hmask);
86736acfc65SAlexander Motin 		} else {
86862fa74d9SJeff Roberson 			/*
86936acfc65SAlexander Motin 			 * If failed, then there is no threads on high
87036acfc65SAlexander Motin 			 * that can run on this low. Drop low from low
87136acfc65SAlexander Motin 			 * mask and look for different one.
87262fa74d9SJeff Roberson 			 */
87336acfc65SAlexander Motin 			CPU_CLR(low, &lmask);
87436acfc65SAlexander Motin 			anylow = 0;
87536acfc65SAlexander Motin 			goto nextlow;
87662fa74d9SJeff Roberson 		}
87736acfc65SAlexander Motin 	}
87862fa74d9SJeff Roberson }
87962fa74d9SJeff Roberson 
88062fa74d9SJeff Roberson static void
88162375ca8SEd Schouten sched_balance(void)
882356500a3SJeff Roberson {
8837fcf154aSJeff Roberson 	struct tdq *tdq;
884356500a3SJeff Roberson 
885ae7a6b38SJeff Roberson 	if (smp_started == 0 || rebalance == 0)
886598b368dSJeff Roberson 		return;
8870567b6ccSWarner Losh 
8880567b6ccSWarner Losh 	balance_ticks = max(balance_interval / 2, 1) +
889b250ad34SWarner Losh 	    (sched_random() % balance_interval);
8907fcf154aSJeff Roberson 	tdq = TDQ_SELF();
8917fcf154aSJeff Roberson 	TDQ_UNLOCK(tdq);
89262fa74d9SJeff Roberson 	sched_balance_group(cpu_top);
8937fcf154aSJeff Roberson 	TDQ_LOCK(tdq);
894cac77d04SJeff Roberson }
89586f8ae96SJeff Roberson 
896ae7a6b38SJeff Roberson /*
897ae7a6b38SJeff Roberson  * Lock two thread queues using their address to maintain lock order.
898ae7a6b38SJeff Roberson  */
899ae7a6b38SJeff Roberson static void
900ae7a6b38SJeff Roberson tdq_lock_pair(struct tdq *one, struct tdq *two)
901ae7a6b38SJeff Roberson {
902ae7a6b38SJeff Roberson 	if (one < two) {
903ae7a6b38SJeff Roberson 		TDQ_LOCK(one);
904ae7a6b38SJeff Roberson 		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
905ae7a6b38SJeff Roberson 	} else {
906ae7a6b38SJeff Roberson 		TDQ_LOCK(two);
907ae7a6b38SJeff Roberson 		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
908ae7a6b38SJeff Roberson 	}
909ae7a6b38SJeff Roberson }
910ae7a6b38SJeff Roberson 
911ae7a6b38SJeff Roberson /*
9127fcf154aSJeff Roberson  * Unlock two thread queues.  Order is not important here.
9137fcf154aSJeff Roberson  */
9147fcf154aSJeff Roberson static void
9157fcf154aSJeff Roberson tdq_unlock_pair(struct tdq *one, struct tdq *two)
9167fcf154aSJeff Roberson {
9177fcf154aSJeff Roberson 	TDQ_UNLOCK(one);
9187fcf154aSJeff Roberson 	TDQ_UNLOCK(two);
9197fcf154aSJeff Roberson }
9207fcf154aSJeff Roberson 
9217fcf154aSJeff Roberson /*
922ae7a6b38SJeff Roberson  * Transfer load between two imbalanced thread queues.
923ae7a6b38SJeff Roberson  */
92462fa74d9SJeff Roberson static int
925ad1e7d28SJulian Elischer sched_balance_pair(struct tdq *high, struct tdq *low)
926cac77d04SJeff Roberson {
92762fa74d9SJeff Roberson 	int moved;
928880bf8b9SMarius Strobl 	int cpu;
929cac77d04SJeff Roberson 
930ae7a6b38SJeff Roberson 	tdq_lock_pair(high, low);
93162fa74d9SJeff Roberson 	moved = 0;
932155b9987SJeff Roberson 	/*
933155b9987SJeff Roberson 	 * Determine what the imbalance is and then adjust that to how many
934d2ad694cSJeff Roberson 	 * threads we actually have to give up (transferable).
935155b9987SJeff Roberson 	 */
93636acfc65SAlexander Motin 	if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load &&
93736acfc65SAlexander Motin 	    (moved = tdq_move(high, low)) > 0) {
938a5423ea3SJeff Roberson 		/*
939880bf8b9SMarius Strobl 		 * In case the target isn't the current cpu IPI it to force a
940880bf8b9SMarius Strobl 		 * reschedule with the new workload.
941a5423ea3SJeff Roberson 		 */
942880bf8b9SMarius Strobl 		cpu = TDQ_ID(low);
943880bf8b9SMarius Strobl 		if (cpu != PCPU_GET(cpuid))
944880bf8b9SMarius Strobl 			ipi_cpu(cpu, IPI_PREEMPT);
945ae7a6b38SJeff Roberson 	}
9467fcf154aSJeff Roberson 	tdq_unlock_pair(high, low);
94762fa74d9SJeff Roberson 	return (moved);
948356500a3SJeff Roberson }
949356500a3SJeff Roberson 
950ae7a6b38SJeff Roberson /*
951ae7a6b38SJeff Roberson  * Move a thread from one thread queue to another.
952ae7a6b38SJeff Roberson  */
95362fa74d9SJeff Roberson static int
954ae7a6b38SJeff Roberson tdq_move(struct tdq *from, struct tdq *to)
955356500a3SJeff Roberson {
956ad1e7d28SJulian Elischer 	struct td_sched *ts;
957ae7a6b38SJeff Roberson 	struct thread *td;
958ae7a6b38SJeff Roberson 	struct tdq *tdq;
959ae7a6b38SJeff Roberson 	int cpu;
960356500a3SJeff Roberson 
9617fcf154aSJeff Roberson 	TDQ_LOCK_ASSERT(from, MA_OWNED);
9627fcf154aSJeff Roberson 	TDQ_LOCK_ASSERT(to, MA_OWNED);
9637fcf154aSJeff Roberson 
964ad1e7d28SJulian Elischer 	tdq = from;
965ae7a6b38SJeff Roberson 	cpu = TDQ_ID(to);
9669727e637SJeff Roberson 	td = tdq_steal(tdq, cpu);
9679727e637SJeff Roberson 	if (td == NULL)
96862fa74d9SJeff Roberson 		return (0);
96993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
970ae7a6b38SJeff Roberson 	/*
971ae7a6b38SJeff Roberson 	 * Although the run queue is locked the thread may be blocked.  Lock
9727fcf154aSJeff Roberson 	 * it to clear this and acquire the run-queue lock.
973ae7a6b38SJeff Roberson 	 */
974ae7a6b38SJeff Roberson 	thread_lock(td);
9757fcf154aSJeff Roberson 	/* Drop recursive lock on from acquired via thread_lock(). */
976ae7a6b38SJeff Roberson 	TDQ_UNLOCK(from);
977ae7a6b38SJeff Roberson 	sched_rem(td);
9787b8bfa0dSJeff Roberson 	ts->ts_cpu = cpu;
979ae7a6b38SJeff Roberson 	td->td_lock = TDQ_LOCKPTR(to);
980ae7a6b38SJeff Roberson 	tdq_add(to, td, SRQ_YIELDING);
98162fa74d9SJeff Roberson 	return (1);
982356500a3SJeff Roberson }
98322bf7d9aSJeff Roberson 
984ae7a6b38SJeff Roberson /*
985ae7a6b38SJeff Roberson  * This tdq has idled.  Try to steal a thread from another cpu and switch
986ae7a6b38SJeff Roberson  * to it.
987ae7a6b38SJeff Roberson  */
98880f86c9fSJeff Roberson static int
989ad1e7d28SJulian Elischer tdq_idled(struct tdq *tdq)
99022bf7d9aSJeff Roberson {
99162fa74d9SJeff Roberson 	struct cpu_group *cg;
992ad1e7d28SJulian Elischer 	struct tdq *steal;
993c76ee827SJeff Roberson 	cpuset_t mask;
99462fa74d9SJeff Roberson 	int thresh;
995ae7a6b38SJeff Roberson 	int cpu;
99680f86c9fSJeff Roberson 
99788f530ccSJeff Roberson 	if (smp_started == 0 || steal_idle == 0)
99888f530ccSJeff Roberson 		return (1);
999c76ee827SJeff Roberson 	CPU_FILL(&mask);
1000c76ee827SJeff Roberson 	CPU_CLR(PCPU_GET(cpuid), &mask);
100162fa74d9SJeff Roberson 	/* We don't want to be preempted while we're iterating. */
1002ae7a6b38SJeff Roberson 	spinlock_enter();
100362fa74d9SJeff Roberson 	for (cg = tdq->tdq_cg; cg != NULL; ) {
10047b55ab05SJeff Roberson 		if ((cg->cg_flags & CG_FLAG_THREAD) == 0)
100562fa74d9SJeff Roberson 			thresh = steal_thresh;
100662fa74d9SJeff Roberson 		else
100762fa74d9SJeff Roberson 			thresh = 1;
100862fa74d9SJeff Roberson 		cpu = sched_highest(cg, mask, thresh);
100962fa74d9SJeff Roberson 		if (cpu == -1) {
101062fa74d9SJeff Roberson 			cg = cg->cg_parent;
101180f86c9fSJeff Roberson 			continue;
10127b8bfa0dSJeff Roberson 		}
10137b8bfa0dSJeff Roberson 		steal = TDQ_CPU(cpu);
1014c76ee827SJeff Roberson 		CPU_CLR(cpu, &mask);
10157fcf154aSJeff Roberson 		tdq_lock_pair(tdq, steal);
101662fa74d9SJeff Roberson 		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
10177fcf154aSJeff Roberson 			tdq_unlock_pair(tdq, steal);
101862fa74d9SJeff Roberson 			continue;
101962fa74d9SJeff Roberson 		}
102062fa74d9SJeff Roberson 		/*
102162fa74d9SJeff Roberson 		 * If a thread was added while interrupts were disabled don't
102262fa74d9SJeff Roberson 		 * steal one here.  If we fail to acquire one due to affinity
102362fa74d9SJeff Roberson 		 * restrictions loop again with this cpu removed from the
102462fa74d9SJeff Roberson 		 * set.
102562fa74d9SJeff Roberson 		 */
102662fa74d9SJeff Roberson 		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
102762fa74d9SJeff Roberson 			tdq_unlock_pair(tdq, steal);
102862fa74d9SJeff Roberson 			continue;
102980f86c9fSJeff Roberson 		}
1030ae7a6b38SJeff Roberson 		spinlock_exit();
1031ae7a6b38SJeff Roberson 		TDQ_UNLOCK(steal);
10328df78c41SJeff Roberson 		mi_switch(SW_VOL | SWT_IDLE, NULL);
1033ae7a6b38SJeff Roberson 		thread_unlock(curthread);
10347b8bfa0dSJeff Roberson 
10357b8bfa0dSJeff Roberson 		return (0);
103622bf7d9aSJeff Roberson 	}
103762fa74d9SJeff Roberson 	spinlock_exit();
103862fa74d9SJeff Roberson 	return (1);
103962fa74d9SJeff Roberson }
104022bf7d9aSJeff Roberson 
1041ae7a6b38SJeff Roberson /*
1042ae7a6b38SJeff Roberson  * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
1043ae7a6b38SJeff Roberson  */
104422bf7d9aSJeff Roberson static void
104527ee18adSRyan Stone tdq_notify(struct tdq *tdq, struct thread *td)
104622bf7d9aSJeff Roberson {
104702f0ff6dSJohn Baldwin 	struct thread *ctd;
104827ee18adSRyan Stone 	int pri;
10497b8bfa0dSJeff Roberson 	int cpu;
105022bf7d9aSJeff Roberson 
1051ff256d9cSJeff Roberson 	if (tdq->tdq_ipipending)
1052ff256d9cSJeff Roberson 		return;
105327ee18adSRyan Stone 	cpu = td_get_sched(td)->ts_cpu;
105427ee18adSRyan Stone 	pri = td->td_priority;
105502f0ff6dSJohn Baldwin 	ctd = pcpu_find(cpu)->pc_curthread;
105602f0ff6dSJohn Baldwin 	if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
10576b2f763fSJeff Roberson 		return;
105879654969SAlexander Motin 
105979654969SAlexander Motin 	/*
1060ae9e9b4fSAlexander Motin 	 * Make sure that our caller's earlier update to tdq_load is
1061ae9e9b4fSAlexander Motin 	 * globally visible before we read tdq_cpu_idle.  Idle thread
106279654969SAlexander Motin 	 * accesses both of them without locks, and the order is important.
106379654969SAlexander Motin 	 */
1064e8677f38SKonstantin Belousov 	atomic_thread_fence_seq_cst();
106579654969SAlexander Motin 
106602f0ff6dSJohn Baldwin 	if (TD_IS_IDLETHREAD(ctd)) {
10671690c6c1SJeff Roberson 		/*
10686c47aaaeSJeff Roberson 		 * If the MD code has an idle wakeup routine try that before
10696c47aaaeSJeff Roberson 		 * falling back to IPI.
10706c47aaaeSJeff Roberson 		 */
10719f9ad565SAlexander Motin 		if (!tdq->tdq_cpu_idle || cpu_idle_wakeup(cpu))
10726c47aaaeSJeff Roberson 			return;
10731690c6c1SJeff Roberson 	}
1074ff256d9cSJeff Roberson 	tdq->tdq_ipipending = 1;
1075d9d8d144SJohn Baldwin 	ipi_cpu(cpu, IPI_PREEMPT);
107622bf7d9aSJeff Roberson }
107722bf7d9aSJeff Roberson 
1078ae7a6b38SJeff Roberson /*
1079ae7a6b38SJeff Roberson  * Steals load from a timeshare queue.  Honors the rotating queue head
1080ae7a6b38SJeff Roberson  * index.
1081ae7a6b38SJeff Roberson  */
10829727e637SJeff Roberson static struct thread *
108362fa74d9SJeff Roberson runq_steal_from(struct runq *rq, int cpu, u_char start)
1084ae7a6b38SJeff Roberson {
1085ae7a6b38SJeff Roberson 	struct rqbits *rqb;
1086ae7a6b38SJeff Roberson 	struct rqhead *rqh;
108736acfc65SAlexander Motin 	struct thread *td, *first;
1088ae7a6b38SJeff Roberson 	int bit;
1089ae7a6b38SJeff Roberson 	int i;
1090ae7a6b38SJeff Roberson 
1091ae7a6b38SJeff Roberson 	rqb = &rq->rq_status;
1092ae7a6b38SJeff Roberson 	bit = start & (RQB_BPW -1);
109336acfc65SAlexander Motin 	first = NULL;
1094ae7a6b38SJeff Roberson again:
1095ae7a6b38SJeff Roberson 	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1096ae7a6b38SJeff Roberson 		if (rqb->rqb_bits[i] == 0)
1097ae7a6b38SJeff Roberson 			continue;
10988bc713f6SJeff Roberson 		if (bit == 0)
10998bc713f6SJeff Roberson 			bit = RQB_FFS(rqb->rqb_bits[i]);
11008bc713f6SJeff Roberson 		for (; bit < RQB_BPW; bit++) {
11018bc713f6SJeff Roberson 			if ((rqb->rqb_bits[i] & (1ul << bit)) == 0)
1102ae7a6b38SJeff Roberson 				continue;
11038bc713f6SJeff Roberson 			rqh = &rq->rq_queues[bit + (i << RQB_L2BPW)];
11049727e637SJeff Roberson 			TAILQ_FOREACH(td, rqh, td_runq) {
11059727e637SJeff Roberson 				if (first && THREAD_CAN_MIGRATE(td) &&
11069727e637SJeff Roberson 				    THREAD_CAN_SCHED(td, cpu))
11079727e637SJeff Roberson 					return (td);
110836acfc65SAlexander Motin 				first = td;
1109ae7a6b38SJeff Roberson 			}
1110ae7a6b38SJeff Roberson 		}
11118bc713f6SJeff Roberson 	}
1112ae7a6b38SJeff Roberson 	if (start != 0) {
1113ae7a6b38SJeff Roberson 		start = 0;
1114ae7a6b38SJeff Roberson 		goto again;
1115ae7a6b38SJeff Roberson 	}
1116ae7a6b38SJeff Roberson 
111736acfc65SAlexander Motin 	if (first && THREAD_CAN_MIGRATE(first) &&
111836acfc65SAlexander Motin 	    THREAD_CAN_SCHED(first, cpu))
111936acfc65SAlexander Motin 		return (first);
1120ae7a6b38SJeff Roberson 	return (NULL);
1121ae7a6b38SJeff Roberson }
1122ae7a6b38SJeff Roberson 
1123ae7a6b38SJeff Roberson /*
1124ae7a6b38SJeff Roberson  * Steals load from a standard linear queue.
1125ae7a6b38SJeff Roberson  */
11269727e637SJeff Roberson static struct thread *
112762fa74d9SJeff Roberson runq_steal(struct runq *rq, int cpu)
112822bf7d9aSJeff Roberson {
112922bf7d9aSJeff Roberson 	struct rqhead *rqh;
113022bf7d9aSJeff Roberson 	struct rqbits *rqb;
11319727e637SJeff Roberson 	struct thread *td;
113222bf7d9aSJeff Roberson 	int word;
113322bf7d9aSJeff Roberson 	int bit;
113422bf7d9aSJeff Roberson 
113522bf7d9aSJeff Roberson 	rqb = &rq->rq_status;
113622bf7d9aSJeff Roberson 	for (word = 0; word < RQB_LEN; word++) {
113722bf7d9aSJeff Roberson 		if (rqb->rqb_bits[word] == 0)
113822bf7d9aSJeff Roberson 			continue;
113922bf7d9aSJeff Roberson 		for (bit = 0; bit < RQB_BPW; bit++) {
1140a2640c9bSPeter Wemm 			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
114122bf7d9aSJeff Roberson 				continue;
114222bf7d9aSJeff Roberson 			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
11439727e637SJeff Roberson 			TAILQ_FOREACH(td, rqh, td_runq)
11449727e637SJeff Roberson 				if (THREAD_CAN_MIGRATE(td) &&
11459727e637SJeff Roberson 				    THREAD_CAN_SCHED(td, cpu))
11469727e637SJeff Roberson 					return (td);
114722bf7d9aSJeff Roberson 		}
114822bf7d9aSJeff Roberson 	}
114922bf7d9aSJeff Roberson 	return (NULL);
115022bf7d9aSJeff Roberson }
115122bf7d9aSJeff Roberson 
1152ae7a6b38SJeff Roberson /*
1153ae7a6b38SJeff Roberson  * Attempt to steal a thread in priority order from a thread queue.
1154ae7a6b38SJeff Roberson  */
11559727e637SJeff Roberson static struct thread *
115662fa74d9SJeff Roberson tdq_steal(struct tdq *tdq, int cpu)
115722bf7d9aSJeff Roberson {
11589727e637SJeff Roberson 	struct thread *td;
115922bf7d9aSJeff Roberson 
1160ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
11619727e637SJeff Roberson 	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
11629727e637SJeff Roberson 		return (td);
11639727e637SJeff Roberson 	if ((td = runq_steal_from(&tdq->tdq_timeshare,
11649727e637SJeff Roberson 	    cpu, tdq->tdq_ridx)) != NULL)
11659727e637SJeff Roberson 		return (td);
116662fa74d9SJeff Roberson 	return (runq_steal(&tdq->tdq_idle, cpu));
116722bf7d9aSJeff Roberson }
116880f86c9fSJeff Roberson 
1169ae7a6b38SJeff Roberson /*
1170ae7a6b38SJeff Roberson  * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
11717fcf154aSJeff Roberson  * current lock and returns with the assigned queue locked.
1172ae7a6b38SJeff Roberson  */
1173ae7a6b38SJeff Roberson static inline struct tdq *
11749727e637SJeff Roberson sched_setcpu(struct thread *td, int cpu, int flags)
117580f86c9fSJeff Roberson {
11769727e637SJeff Roberson 
1177ae7a6b38SJeff Roberson 	struct tdq *tdq;
117880f86c9fSJeff Roberson 
11799727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1180ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpu);
118193ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_cpu = cpu;
11829727e637SJeff Roberson 	/*
11839727e637SJeff Roberson 	 * If the lock matches just return the queue.
11849727e637SJeff Roberson 	 */
1185ae7a6b38SJeff Roberson 	if (td->td_lock == TDQ_LOCKPTR(tdq))
1186ae7a6b38SJeff Roberson 		return (tdq);
1187ae7a6b38SJeff Roberson #ifdef notyet
118880f86c9fSJeff Roberson 	/*
1189a5423ea3SJeff Roberson 	 * If the thread isn't running its lockptr is a
1190ae7a6b38SJeff Roberson 	 * turnstile or a sleepqueue.  We can just lock_set without
1191ae7a6b38SJeff Roberson 	 * blocking.
1192670c524fSJeff Roberson 	 */
1193ae7a6b38SJeff Roberson 	if (TD_CAN_RUN(td)) {
1194ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
1195ae7a6b38SJeff Roberson 		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1196ae7a6b38SJeff Roberson 		return (tdq);
1197ae7a6b38SJeff Roberson 	}
1198ae7a6b38SJeff Roberson #endif
119980f86c9fSJeff Roberson 	/*
1200ae7a6b38SJeff Roberson 	 * The hard case, migration, we need to block the thread first to
1201ae7a6b38SJeff Roberson 	 * prevent order reversals with other cpus locks.
12027b8bfa0dSJeff Roberson 	 */
1203b0b9dee5SAttilio Rao 	spinlock_enter();
1204ae7a6b38SJeff Roberson 	thread_lock_block(td);
1205ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
1206ae7a6b38SJeff Roberson 	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1207b0b9dee5SAttilio Rao 	spinlock_exit();
1208ae7a6b38SJeff Roberson 	return (tdq);
120980f86c9fSJeff Roberson }
12102454aaf5SJeff Roberson 
12118df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
12128df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
12138df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
12148df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
12158df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
12168df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
12178df78c41SJeff Roberson 
1218ae7a6b38SJeff Roberson static int
12199727e637SJeff Roberson sched_pickcpu(struct thread *td, int flags)
1220ae7a6b38SJeff Roberson {
122136acfc65SAlexander Motin 	struct cpu_group *cg, *ccg;
12229727e637SJeff Roberson 	struct td_sched *ts;
1223ae7a6b38SJeff Roberson 	struct tdq *tdq;
1224c76ee827SJeff Roberson 	cpuset_t mask;
122536acfc65SAlexander Motin 	int cpu, pri, self;
12267b8bfa0dSJeff Roberson 
122762fa74d9SJeff Roberson 	self = PCPU_GET(cpuid);
122893ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1229efe67753SNathan Whitehorn 	KASSERT(!CPU_ABSENT(ts->ts_cpu), ("sched_pickcpu: Start scheduler on "
1230efe67753SNathan Whitehorn 	    "absent CPU %d for thread %s.", ts->ts_cpu, td->td_name));
12317b8bfa0dSJeff Roberson 	if (smp_started == 0)
12327b8bfa0dSJeff Roberson 		return (self);
123328994a58SJeff Roberson 	/*
123428994a58SJeff Roberson 	 * Don't migrate a running thread from sched_switch().
123528994a58SJeff Roberson 	 */
123662fa74d9SJeff Roberson 	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
123762fa74d9SJeff Roberson 		return (ts->ts_cpu);
12387b8bfa0dSJeff Roberson 	/*
123962fa74d9SJeff Roberson 	 * Prefer to run interrupt threads on the processors that generate
124062fa74d9SJeff Roberson 	 * the interrupt.
12417b8bfa0dSJeff Roberson 	 */
124236acfc65SAlexander Motin 	pri = td->td_priority;
124362fa74d9SJeff Roberson 	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
12448df78c41SJeff Roberson 	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
12458df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_intrbind);
124662fa74d9SJeff Roberson 		ts->ts_cpu = self;
124736acfc65SAlexander Motin 		if (TDQ_CPU(self)->tdq_lowpri > pri) {
12488df78c41SJeff Roberson 			SCHED_STAT_INC(pickcpu_affinity);
12497b8bfa0dSJeff Roberson 			return (ts->ts_cpu);
12507b8bfa0dSJeff Roberson 		}
12518df78c41SJeff Roberson 	}
12527b8bfa0dSJeff Roberson 	/*
125336acfc65SAlexander Motin 	 * If the thread can run on the last cpu and the affinity has not
125436acfc65SAlexander Motin 	 * expired or it is idle run it there.
12557b8bfa0dSJeff Roberson 	 */
125636acfc65SAlexander Motin 	tdq = TDQ_CPU(ts->ts_cpu);
125736acfc65SAlexander Motin 	cg = tdq->tdq_cg;
125836acfc65SAlexander Motin 	if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
125936acfc65SAlexander Motin 	    tdq->tdq_lowpri >= PRI_MIN_IDLE &&
126036acfc65SAlexander Motin 	    SCHED_AFFINITY(ts, CG_SHARE_L2)) {
126136acfc65SAlexander Motin 		if (cg->cg_flags & CG_FLAG_THREAD) {
126236acfc65SAlexander Motin 			CPUSET_FOREACH(cpu, cg->cg_mask) {
126336acfc65SAlexander Motin 				if (TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE)
126462fa74d9SJeff Roberson 					break;
126536acfc65SAlexander Motin 			}
126636acfc65SAlexander Motin 		} else
126736acfc65SAlexander Motin 			cpu = INT_MAX;
126836acfc65SAlexander Motin 		if (cpu > mp_maxid) {
126936acfc65SAlexander Motin 			SCHED_STAT_INC(pickcpu_idle_affinity);
127036acfc65SAlexander Motin 			return (ts->ts_cpu);
127136acfc65SAlexander Motin 		}
127236acfc65SAlexander Motin 	}
127336acfc65SAlexander Motin 	/*
127436acfc65SAlexander Motin 	 * Search for the last level cache CPU group in the tree.
127536acfc65SAlexander Motin 	 * Skip caches with expired affinity time and SMT groups.
127636acfc65SAlexander Motin 	 * Affinity to higher level caches will be handled less aggressively.
127736acfc65SAlexander Motin 	 */
127836acfc65SAlexander Motin 	for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
127936acfc65SAlexander Motin 		if (cg->cg_flags & CG_FLAG_THREAD)
128036acfc65SAlexander Motin 			continue;
128136acfc65SAlexander Motin 		if (!SCHED_AFFINITY(ts, cg->cg_level))
128236acfc65SAlexander Motin 			continue;
128336acfc65SAlexander Motin 		ccg = cg;
128436acfc65SAlexander Motin 	}
128536acfc65SAlexander Motin 	if (ccg != NULL)
128636acfc65SAlexander Motin 		cg = ccg;
128762fa74d9SJeff Roberson 	cpu = -1;
128836acfc65SAlexander Motin 	/* Search the group for the less loaded idle CPU we can run now. */
1289c76ee827SJeff Roberson 	mask = td->td_cpuset->cs_mask;
129036acfc65SAlexander Motin 	if (cg != NULL && cg != cpu_top &&
129136acfc65SAlexander Motin 	    CPU_CMP(&cg->cg_mask, &cpu_top->cg_mask) != 0)
129236acfc65SAlexander Motin 		cpu = sched_lowest(cg, mask, max(pri, PRI_MAX_TIMESHARE),
129336acfc65SAlexander Motin 		    INT_MAX, ts->ts_cpu);
129436acfc65SAlexander Motin 	/* Search globally for the less loaded CPU we can run now. */
129562fa74d9SJeff Roberson 	if (cpu == -1)
129636acfc65SAlexander Motin 		cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu);
129736acfc65SAlexander Motin 	/* Search globally for the less loaded CPU. */
129836acfc65SAlexander Motin 	if (cpu == -1)
129936acfc65SAlexander Motin 		cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu);
13006022f0bcSAlexander Motin 	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1301efe67753SNathan Whitehorn 	KASSERT(!CPU_ABSENT(cpu), ("sched_pickcpu: Picked absent CPU %d.", cpu));
130262fa74d9SJeff Roberson 	/*
130362fa74d9SJeff Roberson 	 * Compare the lowest loaded cpu to current cpu.
130462fa74d9SJeff Roberson 	 */
1305ff256d9cSJeff Roberson 	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
130636acfc65SAlexander Motin 	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE &&
130736acfc65SAlexander Motin 	    TDQ_CPU(self)->tdq_load <= TDQ_CPU(cpu)->tdq_load + 1) {
13088df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_local);
130962fa74d9SJeff Roberson 		cpu = self;
13108df78c41SJeff Roberson 	} else
13118df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_lowest);
13128df78c41SJeff Roberson 	if (cpu != ts->ts_cpu)
13138df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_migration);
1314ae7a6b38SJeff Roberson 	return (cpu);
131580f86c9fSJeff Roberson }
131662fa74d9SJeff Roberson #endif
131722bf7d9aSJeff Roberson 
131822bf7d9aSJeff Roberson /*
131922bf7d9aSJeff Roberson  * Pick the highest priority task we have and return it.
13200c0a98b2SJeff Roberson  */
13219727e637SJeff Roberson static struct thread *
1322ad1e7d28SJulian Elischer tdq_choose(struct tdq *tdq)
13235d7ef00cSJeff Roberson {
13249727e637SJeff Roberson 	struct thread *td;
13255d7ef00cSJeff Roberson 
1326ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
13279727e637SJeff Roberson 	td = runq_choose(&tdq->tdq_realtime);
13289727e637SJeff Roberson 	if (td != NULL)
13299727e637SJeff Roberson 		return (td);
13309727e637SJeff Roberson 	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
13319727e637SJeff Roberson 	if (td != NULL) {
133212d56c0fSJohn Baldwin 		KASSERT(td->td_priority >= PRI_MIN_BATCH,
1333e7d50326SJeff Roberson 		    ("tdq_choose: Invalid priority on timeshare queue %d",
13349727e637SJeff Roberson 		    td->td_priority));
13359727e637SJeff Roberson 		return (td);
133615dc847eSJeff Roberson 	}
13379727e637SJeff Roberson 	td = runq_choose(&tdq->tdq_idle);
13389727e637SJeff Roberson 	if (td != NULL) {
13399727e637SJeff Roberson 		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1340e7d50326SJeff Roberson 		    ("tdq_choose: Invalid priority on idle queue %d",
13419727e637SJeff Roberson 		    td->td_priority));
13429727e637SJeff Roberson 		return (td);
1343e7d50326SJeff Roberson 	}
1344e7d50326SJeff Roberson 
1345e7d50326SJeff Roberson 	return (NULL);
1346245f3abfSJeff Roberson }
13470a016a05SJeff Roberson 
1348ae7a6b38SJeff Roberson /*
1349ae7a6b38SJeff Roberson  * Initialize a thread queue.
1350ae7a6b38SJeff Roberson  */
13510a016a05SJeff Roberson static void
1352ad1e7d28SJulian Elischer tdq_setup(struct tdq *tdq)
13530a016a05SJeff Roberson {
1354ae7a6b38SJeff Roberson 
1355c47f202bSJeff Roberson 	if (bootverbose)
1356c47f202bSJeff Roberson 		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1357e7d50326SJeff Roberson 	runq_init(&tdq->tdq_realtime);
1358e7d50326SJeff Roberson 	runq_init(&tdq->tdq_timeshare);
1359d2ad694cSJeff Roberson 	runq_init(&tdq->tdq_idle);
136062fa74d9SJeff Roberson 	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
136162fa74d9SJeff Roberson 	    "sched lock %d", (int)TDQ_ID(tdq));
136262fa74d9SJeff Roberson 	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
136362fa74d9SJeff Roberson 	    MTX_SPIN | MTX_RECURSE);
13648f51ad55SJeff Roberson #ifdef KTR
13658f51ad55SJeff Roberson 	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
13668f51ad55SJeff Roberson 	    "CPU %d load", (int)TDQ_ID(tdq));
13678f51ad55SJeff Roberson #endif
13680a016a05SJeff Roberson }
13690a016a05SJeff Roberson 
1370c47f202bSJeff Roberson #ifdef SMP
1371c47f202bSJeff Roberson static void
1372c47f202bSJeff Roberson sched_setup_smp(void)
1373c47f202bSJeff Roberson {
1374c47f202bSJeff Roberson 	struct tdq *tdq;
1375c47f202bSJeff Roberson 	int i;
1376c47f202bSJeff Roberson 
137762fa74d9SJeff Roberson 	cpu_top = smp_topo();
13783aa6d94eSJohn Baldwin 	CPU_FOREACH(i) {
137962fa74d9SJeff Roberson 		tdq = TDQ_CPU(i);
1380c47f202bSJeff Roberson 		tdq_setup(tdq);
138162fa74d9SJeff Roberson 		tdq->tdq_cg = smp_topo_find(cpu_top, i);
138262fa74d9SJeff Roberson 		if (tdq->tdq_cg == NULL)
138362fa74d9SJeff Roberson 			panic("Can't find cpu group for %d\n", i);
1384c47f202bSJeff Roberson 	}
138562fa74d9SJeff Roberson 	balance_tdq = TDQ_SELF();
138662fa74d9SJeff Roberson 	sched_balance();
1387c47f202bSJeff Roberson }
1388c47f202bSJeff Roberson #endif
1389c47f202bSJeff Roberson 
1390ae7a6b38SJeff Roberson /*
1391ae7a6b38SJeff Roberson  * Setup the thread queues and initialize the topology based on MD
1392ae7a6b38SJeff Roberson  * information.
1393ae7a6b38SJeff Roberson  */
139435e6168fSJeff Roberson static void
139535e6168fSJeff Roberson sched_setup(void *dummy)
139635e6168fSJeff Roberson {
1397ae7a6b38SJeff Roberson 	struct tdq *tdq;
1398c47f202bSJeff Roberson 
1399c47f202bSJeff Roberson 	tdq = TDQ_SELF();
14000ec896fdSJeff Roberson #ifdef SMP
1401c47f202bSJeff Roberson 	sched_setup_smp();
1402749d01b0SJeff Roberson #else
1403c47f202bSJeff Roberson 	tdq_setup(tdq);
1404356500a3SJeff Roberson #endif
1405ae7a6b38SJeff Roberson 
1406ae7a6b38SJeff Roberson 	/* Add thread0's load since it's running. */
1407ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
1408efe67753SNathan Whitehorn 	td_get_sched(&thread0)->ts_cpu = curcpu; /* Something valid to start */
1409c47f202bSJeff Roberson 	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
14109727e637SJeff Roberson 	tdq_load_add(tdq, &thread0);
141162fa74d9SJeff Roberson 	tdq->tdq_lowpri = thread0.td_priority;
1412ae7a6b38SJeff Roberson 	TDQ_UNLOCK(tdq);
141335e6168fSJeff Roberson }
141435e6168fSJeff Roberson 
1415ae7a6b38SJeff Roberson /*
1416579895dfSAlexander Motin  * This routine determines time constants after stathz and hz are setup.
1417ae7a6b38SJeff Roberson  */
1418a1d4fe69SDavid Xu /* ARGSUSED */
1419a1d4fe69SDavid Xu static void
1420a1d4fe69SDavid Xu sched_initticks(void *dummy)
1421a1d4fe69SDavid Xu {
1422ae7a6b38SJeff Roberson 	int incr;
1423ae7a6b38SJeff Roberson 
1424a1d4fe69SDavid Xu 	realstathz = stathz ? stathz : hz;
14255e5c3873SJeff Roberson 	sched_slice = realstathz / SCHED_SLICE_DEFAULT_DIVISOR;
14265e5c3873SJeff Roberson 	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
142737f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
142837f4e025SAlexander Motin 	    realstathz);
1429a1d4fe69SDavid Xu 
1430a1d4fe69SDavid Xu 	/*
1431e7d50326SJeff Roberson 	 * tickincr is shifted out by 10 to avoid rounding errors due to
14323f872f85SJeff Roberson 	 * hz not being evenly divisible by stathz on all platforms.
1433e7d50326SJeff Roberson 	 */
1434ae7a6b38SJeff Roberson 	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1435e7d50326SJeff Roberson 	/*
1436e7d50326SJeff Roberson 	 * This does not work for values of stathz that are more than
1437e7d50326SJeff Roberson 	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1438a1d4fe69SDavid Xu 	 */
1439ae7a6b38SJeff Roberson 	if (incr == 0)
1440ae7a6b38SJeff Roberson 		incr = 1;
1441ae7a6b38SJeff Roberson 	tickincr = incr;
14427b8bfa0dSJeff Roberson #ifdef SMP
14439862717aSJeff Roberson 	/*
14447fcf154aSJeff Roberson 	 * Set the default balance interval now that we know
14457fcf154aSJeff Roberson 	 * what realstathz is.
14467fcf154aSJeff Roberson 	 */
14477fcf154aSJeff Roberson 	balance_interval = realstathz;
14487b8bfa0dSJeff Roberson 	affinity = SCHED_AFFINITY_DEFAULT;
14497b8bfa0dSJeff Roberson #endif
1450b3f40a41SAlexander Motin 	if (sched_idlespinthresh < 0)
14512c27cb3aSAlexander Motin 		sched_idlespinthresh = 2 * max(10000, 6 * hz) / realstathz;
1452a1d4fe69SDavid Xu }
1453a1d4fe69SDavid Xu 
1454a1d4fe69SDavid Xu 
145535e6168fSJeff Roberson /*
1456ae7a6b38SJeff Roberson  * This is the core of the interactivity algorithm.  Determines a score based
1457ae7a6b38SJeff Roberson  * on past behavior.  It is the ratio of sleep time to run time scaled to
1458ae7a6b38SJeff Roberson  * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1459ae7a6b38SJeff Roberson  * differs from the cpu usage because it does not account for time spent
1460ae7a6b38SJeff Roberson  * waiting on a run-queue.  Would be prettier if we had floating point.
146157031f79SGeorge V. Neville-Neil  *
146257031f79SGeorge V. Neville-Neil  * When a thread's sleep time is greater than its run time the
146357031f79SGeorge V. Neville-Neil  * calculation is:
146457031f79SGeorge V. Neville-Neil  *
146557031f79SGeorge V. Neville-Neil  *                           scaling factor
146657031f79SGeorge V. Neville-Neil  * interactivity score =  ---------------------
146757031f79SGeorge V. Neville-Neil  *                        sleep time / run time
146857031f79SGeorge V. Neville-Neil  *
146957031f79SGeorge V. Neville-Neil  *
147057031f79SGeorge V. Neville-Neil  * When a thread's run time is greater than its sleep time the
147157031f79SGeorge V. Neville-Neil  * calculation is:
147257031f79SGeorge V. Neville-Neil  *
147357031f79SGeorge V. Neville-Neil  *                           scaling factor
147457031f79SGeorge V. Neville-Neil  * interactivity score =  ---------------------    + scaling factor
147557031f79SGeorge V. Neville-Neil  *                        run time / sleep time
1476ae7a6b38SJeff Roberson  */
1477ae7a6b38SJeff Roberson static int
1478ae7a6b38SJeff Roberson sched_interact_score(struct thread *td)
1479ae7a6b38SJeff Roberson {
1480ae7a6b38SJeff Roberson 	struct td_sched *ts;
1481ae7a6b38SJeff Roberson 	int div;
1482ae7a6b38SJeff Roberson 
148393ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1484ae7a6b38SJeff Roberson 	/*
1485ae7a6b38SJeff Roberson 	 * The score is only needed if this is likely to be an interactive
1486ae7a6b38SJeff Roberson 	 * task.  Don't go through the expense of computing it if there's
1487ae7a6b38SJeff Roberson 	 * no chance.
1488ae7a6b38SJeff Roberson 	 */
1489ae7a6b38SJeff Roberson 	if (sched_interact <= SCHED_INTERACT_HALF &&
1490ae7a6b38SJeff Roberson 		ts->ts_runtime >= ts->ts_slptime)
1491ae7a6b38SJeff Roberson 			return (SCHED_INTERACT_HALF);
1492ae7a6b38SJeff Roberson 
1493ae7a6b38SJeff Roberson 	if (ts->ts_runtime > ts->ts_slptime) {
1494ae7a6b38SJeff Roberson 		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1495ae7a6b38SJeff Roberson 		return (SCHED_INTERACT_HALF +
1496ae7a6b38SJeff Roberson 		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1497ae7a6b38SJeff Roberson 	}
1498ae7a6b38SJeff Roberson 	if (ts->ts_slptime > ts->ts_runtime) {
1499ae7a6b38SJeff Roberson 		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1500ae7a6b38SJeff Roberson 		return (ts->ts_runtime / div);
1501ae7a6b38SJeff Roberson 	}
1502ae7a6b38SJeff Roberson 	/* runtime == slptime */
1503ae7a6b38SJeff Roberson 	if (ts->ts_runtime)
1504ae7a6b38SJeff Roberson 		return (SCHED_INTERACT_HALF);
1505ae7a6b38SJeff Roberson 
1506ae7a6b38SJeff Roberson 	/*
1507ae7a6b38SJeff Roberson 	 * This can happen if slptime and runtime are 0.
1508ae7a6b38SJeff Roberson 	 */
1509ae7a6b38SJeff Roberson 	return (0);
1510ae7a6b38SJeff Roberson 
1511ae7a6b38SJeff Roberson }
1512ae7a6b38SJeff Roberson 
1513ae7a6b38SJeff Roberson /*
151435e6168fSJeff Roberson  * Scale the scheduling priority according to the "interactivity" of this
151535e6168fSJeff Roberson  * process.
151635e6168fSJeff Roberson  */
151715dc847eSJeff Roberson static void
15188460a577SJohn Birrell sched_priority(struct thread *td)
151935e6168fSJeff Roberson {
1520e7d50326SJeff Roberson 	int score;
152135e6168fSJeff Roberson 	int pri;
152235e6168fSJeff Roberson 
1523c9a8cba4SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
152415dc847eSJeff Roberson 		return;
1525e7d50326SJeff Roberson 	/*
1526e7d50326SJeff Roberson 	 * If the score is interactive we place the thread in the realtime
1527e7d50326SJeff Roberson 	 * queue with a priority that is less than kernel and interrupt
1528e7d50326SJeff Roberson 	 * priorities.  These threads are not subject to nice restrictions.
1529e7d50326SJeff Roberson 	 *
1530ae7a6b38SJeff Roberson 	 * Scores greater than this are placed on the normal timeshare queue
1531e7d50326SJeff Roberson 	 * where the priority is partially decided by the most recent cpu
1532e7d50326SJeff Roberson 	 * utilization and the rest is decided by nice value.
1533a5423ea3SJeff Roberson 	 *
1534a5423ea3SJeff Roberson 	 * The nice value of the process has a linear effect on the calculated
1535a5423ea3SJeff Roberson 	 * score.  Negative nice values make it easier for a thread to be
1536a5423ea3SJeff Roberson 	 * considered interactive.
1537e7d50326SJeff Roberson 	 */
1538a0f15352SJohn Baldwin 	score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1539e7d50326SJeff Roberson 	if (score < sched_interact) {
154012d56c0fSJohn Baldwin 		pri = PRI_MIN_INTERACT;
154112d56c0fSJohn Baldwin 		pri += ((PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) /
154278920008SJohn Baldwin 		    sched_interact) * score;
154312d56c0fSJohn Baldwin 		KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
15449a93305aSJeff Roberson 		    ("sched_priority: invalid interactive priority %d score %d",
15459a93305aSJeff Roberson 		    pri, score));
1546e7d50326SJeff Roberson 	} else {
1547e7d50326SJeff Roberson 		pri = SCHED_PRI_MIN;
154893ccd6bfSKonstantin Belousov 		if (td_get_sched(td)->ts_ticks)
154993ccd6bfSKonstantin Belousov 			pri += min(SCHED_PRI_TICKS(td_get_sched(td)),
15505457fa23SJohn Baldwin 			    SCHED_PRI_RANGE - 1);
1551e7d50326SJeff Roberson 		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
155212d56c0fSJohn Baldwin 		KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
1553ae7a6b38SJeff Roberson 		    ("sched_priority: invalid priority %d: nice %d, "
1554ae7a6b38SJeff Roberson 		    "ticks %d ftick %d ltick %d tick pri %d",
155593ccd6bfSKonstantin Belousov 		    pri, td->td_proc->p_nice, td_get_sched(td)->ts_ticks,
155693ccd6bfSKonstantin Belousov 		    td_get_sched(td)->ts_ftick, td_get_sched(td)->ts_ltick,
155793ccd6bfSKonstantin Belousov 		    SCHED_PRI_TICKS(td_get_sched(td))));
1558e7d50326SJeff Roberson 	}
15598460a577SJohn Birrell 	sched_user_prio(td, pri);
156035e6168fSJeff Roberson 
156115dc847eSJeff Roberson 	return;
156235e6168fSJeff Roberson }
156335e6168fSJeff Roberson 
156435e6168fSJeff Roberson /*
1565d322132cSJeff Roberson  * This routine enforces a maximum limit on the amount of scheduling history
1566ae7a6b38SJeff Roberson  * kept.  It is called after either the slptime or runtime is adjusted.  This
1567ae7a6b38SJeff Roberson  * function is ugly due to integer math.
1568d322132cSJeff Roberson  */
15694b60e324SJeff Roberson static void
15708460a577SJohn Birrell sched_interact_update(struct thread *td)
15714b60e324SJeff Roberson {
1572155b6ca1SJeff Roberson 	struct td_sched *ts;
15739a93305aSJeff Roberson 	u_int sum;
15743f741ca1SJeff Roberson 
157593ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1576ae7a6b38SJeff Roberson 	sum = ts->ts_runtime + ts->ts_slptime;
1577d322132cSJeff Roberson 	if (sum < SCHED_SLP_RUN_MAX)
1578d322132cSJeff Roberson 		return;
1579d322132cSJeff Roberson 	/*
1580155b6ca1SJeff Roberson 	 * This only happens from two places:
1581155b6ca1SJeff Roberson 	 * 1) We have added an unusual amount of run time from fork_exit.
1582155b6ca1SJeff Roberson 	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1583155b6ca1SJeff Roberson 	 */
1584155b6ca1SJeff Roberson 	if (sum > SCHED_SLP_RUN_MAX * 2) {
1585ae7a6b38SJeff Roberson 		if (ts->ts_runtime > ts->ts_slptime) {
1586ae7a6b38SJeff Roberson 			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1587ae7a6b38SJeff Roberson 			ts->ts_slptime = 1;
1588155b6ca1SJeff Roberson 		} else {
1589ae7a6b38SJeff Roberson 			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1590ae7a6b38SJeff Roberson 			ts->ts_runtime = 1;
1591155b6ca1SJeff Roberson 		}
1592155b6ca1SJeff Roberson 		return;
1593155b6ca1SJeff Roberson 	}
1594155b6ca1SJeff Roberson 	/*
1595d322132cSJeff Roberson 	 * If we have exceeded by more than 1/5th then the algorithm below
1596d322132cSJeff Roberson 	 * will not bring us back into range.  Dividing by two here forces
15972454aaf5SJeff Roberson 	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1598d322132cSJeff Roberson 	 */
159937a35e4aSJeff Roberson 	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1600ae7a6b38SJeff Roberson 		ts->ts_runtime /= 2;
1601ae7a6b38SJeff Roberson 		ts->ts_slptime /= 2;
1602d322132cSJeff Roberson 		return;
1603d322132cSJeff Roberson 	}
1604ae7a6b38SJeff Roberson 	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1605ae7a6b38SJeff Roberson 	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1606d322132cSJeff Roberson }
1607d322132cSJeff Roberson 
1608ae7a6b38SJeff Roberson /*
1609ae7a6b38SJeff Roberson  * Scale back the interactivity history when a child thread is created.  The
1610ae7a6b38SJeff Roberson  * history is inherited from the parent but the thread may behave totally
1611ae7a6b38SJeff Roberson  * differently.  For example, a shell spawning a compiler process.  We want
1612ae7a6b38SJeff Roberson  * to learn that the compiler is behaving badly very quickly.
1613ae7a6b38SJeff Roberson  */
1614d322132cSJeff Roberson static void
16158460a577SJohn Birrell sched_interact_fork(struct thread *td)
1616d322132cSJeff Roberson {
161793ccd6bfSKonstantin Belousov 	struct td_sched *ts;
1618d322132cSJeff Roberson 	int ratio;
1619d322132cSJeff Roberson 	int sum;
1620d322132cSJeff Roberson 
162193ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
162293ccd6bfSKonstantin Belousov 	sum = ts->ts_runtime + ts->ts_slptime;
1623d322132cSJeff Roberson 	if (sum > SCHED_SLP_RUN_FORK) {
1624d322132cSJeff Roberson 		ratio = sum / SCHED_SLP_RUN_FORK;
162593ccd6bfSKonstantin Belousov 		ts->ts_runtime /= ratio;
162693ccd6bfSKonstantin Belousov 		ts->ts_slptime /= ratio;
16274b60e324SJeff Roberson 	}
16284b60e324SJeff Roberson }
16294b60e324SJeff Roberson 
163015dc847eSJeff Roberson /*
1631ae7a6b38SJeff Roberson  * Called from proc0_init() to setup the scheduler fields.
1632ed062c8dSJulian Elischer  */
1633ed062c8dSJulian Elischer void
1634ed062c8dSJulian Elischer schedinit(void)
1635ed062c8dSJulian Elischer {
163693ccd6bfSKonstantin Belousov 	struct td_sched *ts0;
1637e7d50326SJeff Roberson 
1638ed062c8dSJulian Elischer 	/*
163993ccd6bfSKonstantin Belousov 	 * Set up the scheduler specific parts of thread0.
1640ed062c8dSJulian Elischer 	 */
164193ccd6bfSKonstantin Belousov 	ts0 = td_get_sched(&thread0);
164293ccd6bfSKonstantin Belousov 	ts0->ts_ltick = ticks;
164393ccd6bfSKonstantin Belousov 	ts0->ts_ftick = ticks;
164493ccd6bfSKonstantin Belousov 	ts0->ts_slice = 0;
1645ed062c8dSJulian Elischer }
1646ed062c8dSJulian Elischer 
1647ed062c8dSJulian Elischer /*
164815dc847eSJeff Roberson  * This is only somewhat accurate since given many processes of the same
164915dc847eSJeff Roberson  * priority they will switch when their slices run out, which will be
1650e7d50326SJeff Roberson  * at most sched_slice stathz ticks.
165115dc847eSJeff Roberson  */
165235e6168fSJeff Roberson int
165335e6168fSJeff Roberson sched_rr_interval(void)
165435e6168fSJeff Roberson {
1655e7d50326SJeff Roberson 
1656579895dfSAlexander Motin 	/* Convert sched_slice from stathz to hz. */
165737f4e025SAlexander Motin 	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
165835e6168fSJeff Roberson }
165935e6168fSJeff Roberson 
1660ae7a6b38SJeff Roberson /*
1661ae7a6b38SJeff Roberson  * Update the percent cpu tracking information when it is requested or
1662ae7a6b38SJeff Roberson  * the total history exceeds the maximum.  We keep a sliding history of
1663ae7a6b38SJeff Roberson  * tick counts that slowly decays.  This is less precise than the 4BSD
1664ae7a6b38SJeff Roberson  * mechanism since it happens with less regular and frequent events.
1665ae7a6b38SJeff Roberson  */
166622bf7d9aSJeff Roberson static void
16677295465eSAlexander Motin sched_pctcpu_update(struct td_sched *ts, int run)
166835e6168fSJeff Roberson {
16697295465eSAlexander Motin 	int t = ticks;
1670e7d50326SJeff Roberson 
167178133024SMark Johnston 	/*
167278133024SMark Johnston 	 * The signed difference may be negative if the thread hasn't run for
167378133024SMark Johnston 	 * over half of the ticks rollover period.
167478133024SMark Johnston 	 */
167578133024SMark Johnston 	if ((u_int)(t - ts->ts_ltick) >= SCHED_TICK_TARG) {
1676ad1e7d28SJulian Elischer 		ts->ts_ticks = 0;
16777295465eSAlexander Motin 		ts->ts_ftick = t - SCHED_TICK_TARG;
16787295465eSAlexander Motin 	} else if (t - ts->ts_ftick >= SCHED_TICK_MAX) {
16797295465eSAlexander Motin 		ts->ts_ticks = (ts->ts_ticks / (ts->ts_ltick - ts->ts_ftick)) *
16807295465eSAlexander Motin 		    (ts->ts_ltick - (t - SCHED_TICK_TARG));
16817295465eSAlexander Motin 		ts->ts_ftick = t - SCHED_TICK_TARG;
16827295465eSAlexander Motin 	}
16837295465eSAlexander Motin 	if (run)
16847295465eSAlexander Motin 		ts->ts_ticks += (t - ts->ts_ltick) << SCHED_TICK_SHIFT;
16857295465eSAlexander Motin 	ts->ts_ltick = t;
168635e6168fSJeff Roberson }
168735e6168fSJeff Roberson 
1688ae7a6b38SJeff Roberson /*
1689ae7a6b38SJeff Roberson  * Adjust the priority of a thread.  Move it to the appropriate run-queue
1690ae7a6b38SJeff Roberson  * if necessary.  This is the back-end for several priority related
1691ae7a6b38SJeff Roberson  * functions.
1692ae7a6b38SJeff Roberson  */
1693e7d50326SJeff Roberson static void
1694f5c157d9SJohn Baldwin sched_thread_priority(struct thread *td, u_char prio)
169535e6168fSJeff Roberson {
1696ad1e7d28SJulian Elischer 	struct td_sched *ts;
169773daf66fSJeff Roberson 	struct tdq *tdq;
169873daf66fSJeff Roberson 	int oldpri;
169935e6168fSJeff Roberson 
17008f51ad55SJeff Roberson 	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
17018f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, "new prio:%d", prio,
17028f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(curthread));
1703d9fae5abSAndriy Gapon 	SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
1704e87fc7cfSAndriy Gapon 	if (td != curthread && prio < td->td_priority) {
17058f51ad55SJeff Roberson 		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
17068f51ad55SJeff Roberson 		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
17078f51ad55SJeff Roberson 		    prio, KTR_ATTR_LINKED, sched_tdname(td));
1708d9fae5abSAndriy Gapon 		SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
1709b3e9e682SRyan Stone 		    curthread);
17108f51ad55SJeff Roberson 	}
171193ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
17127b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1713f5c157d9SJohn Baldwin 	if (td->td_priority == prio)
1714f5c157d9SJohn Baldwin 		return;
17153f741ca1SJeff Roberson 	/*
17163f741ca1SJeff Roberson 	 * If the priority has been elevated due to priority
17173f741ca1SJeff Roberson 	 * propagation, we may have to move ourselves to a new
1718e7d50326SJeff Roberson 	 * queue.  This could be optimized to not re-add in some
1719e7d50326SJeff Roberson 	 * cases.
1720f2b74cbfSJeff Roberson 	 */
17216d55b3ecSJeff Roberson 	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1722e7d50326SJeff Roberson 		sched_rem(td);
1723e7d50326SJeff Roberson 		td->td_priority = prio;
1724ae7a6b38SJeff Roberson 		sched_add(td, SRQ_BORROWING);
172573daf66fSJeff Roberson 		return;
172673daf66fSJeff Roberson 	}
17276d55b3ecSJeff Roberson 	/*
17286d55b3ecSJeff Roberson 	 * If the thread is currently running we may have to adjust the lowpri
17296d55b3ecSJeff Roberson 	 * information so other cpus are aware of our current priority.
17306d55b3ecSJeff Roberson 	 */
17316d55b3ecSJeff Roberson 	if (TD_IS_RUNNING(td)) {
1732ae7a6b38SJeff Roberson 		tdq = TDQ_CPU(ts->ts_cpu);
173362fa74d9SJeff Roberson 		oldpri = td->td_priority;
17343f741ca1SJeff Roberson 		td->td_priority = prio;
173562fa74d9SJeff Roberson 		if (prio < tdq->tdq_lowpri)
173662fa74d9SJeff Roberson 			tdq->tdq_lowpri = prio;
173762fa74d9SJeff Roberson 		else if (tdq->tdq_lowpri == oldpri)
173862fa74d9SJeff Roberson 			tdq_setlowpri(tdq, td);
17396d55b3ecSJeff Roberson 		return;
174073daf66fSJeff Roberson 	}
17416d55b3ecSJeff Roberson 	td->td_priority = prio;
1742ae7a6b38SJeff Roberson }
174335e6168fSJeff Roberson 
1744f5c157d9SJohn Baldwin /*
1745f5c157d9SJohn Baldwin  * Update a thread's priority when it is lent another thread's
1746f5c157d9SJohn Baldwin  * priority.
1747f5c157d9SJohn Baldwin  */
1748f5c157d9SJohn Baldwin void
1749f5c157d9SJohn Baldwin sched_lend_prio(struct thread *td, u_char prio)
1750f5c157d9SJohn Baldwin {
1751f5c157d9SJohn Baldwin 
1752f5c157d9SJohn Baldwin 	td->td_flags |= TDF_BORROWING;
1753f5c157d9SJohn Baldwin 	sched_thread_priority(td, prio);
1754f5c157d9SJohn Baldwin }
1755f5c157d9SJohn Baldwin 
1756f5c157d9SJohn Baldwin /*
1757f5c157d9SJohn Baldwin  * Restore a thread's priority when priority propagation is
1758f5c157d9SJohn Baldwin  * over.  The prio argument is the minimum priority the thread
1759f5c157d9SJohn Baldwin  * needs to have to satisfy other possible priority lending
1760f5c157d9SJohn Baldwin  * requests.  If the thread's regular priority is less
1761f5c157d9SJohn Baldwin  * important than prio, the thread will keep a priority boost
1762f5c157d9SJohn Baldwin  * of prio.
1763f5c157d9SJohn Baldwin  */
1764f5c157d9SJohn Baldwin void
1765f5c157d9SJohn Baldwin sched_unlend_prio(struct thread *td, u_char prio)
1766f5c157d9SJohn Baldwin {
1767f5c157d9SJohn Baldwin 	u_char base_pri;
1768f5c157d9SJohn Baldwin 
1769f5c157d9SJohn Baldwin 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1770f5c157d9SJohn Baldwin 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
17718460a577SJohn Birrell 		base_pri = td->td_user_pri;
1772f5c157d9SJohn Baldwin 	else
1773f5c157d9SJohn Baldwin 		base_pri = td->td_base_pri;
1774f5c157d9SJohn Baldwin 	if (prio >= base_pri) {
1775f5c157d9SJohn Baldwin 		td->td_flags &= ~TDF_BORROWING;
1776f5c157d9SJohn Baldwin 		sched_thread_priority(td, base_pri);
1777f5c157d9SJohn Baldwin 	} else
1778f5c157d9SJohn Baldwin 		sched_lend_prio(td, prio);
1779f5c157d9SJohn Baldwin }
1780f5c157d9SJohn Baldwin 
1781ae7a6b38SJeff Roberson /*
1782ae7a6b38SJeff Roberson  * Standard entry for setting the priority to an absolute value.
1783ae7a6b38SJeff Roberson  */
1784f5c157d9SJohn Baldwin void
1785f5c157d9SJohn Baldwin sched_prio(struct thread *td, u_char prio)
1786f5c157d9SJohn Baldwin {
1787f5c157d9SJohn Baldwin 	u_char oldprio;
1788f5c157d9SJohn Baldwin 
1789f5c157d9SJohn Baldwin 	/* First, update the base priority. */
1790f5c157d9SJohn Baldwin 	td->td_base_pri = prio;
1791f5c157d9SJohn Baldwin 
1792f5c157d9SJohn Baldwin 	/*
179350aaa791SJohn Baldwin 	 * If the thread is borrowing another thread's priority, don't
1794f5c157d9SJohn Baldwin 	 * ever lower the priority.
1795f5c157d9SJohn Baldwin 	 */
1796f5c157d9SJohn Baldwin 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1797f5c157d9SJohn Baldwin 		return;
1798f5c157d9SJohn Baldwin 
1799f5c157d9SJohn Baldwin 	/* Change the real priority. */
1800f5c157d9SJohn Baldwin 	oldprio = td->td_priority;
1801f5c157d9SJohn Baldwin 	sched_thread_priority(td, prio);
1802f5c157d9SJohn Baldwin 
1803f5c157d9SJohn Baldwin 	/*
1804f5c157d9SJohn Baldwin 	 * If the thread is on a turnstile, then let the turnstile update
1805f5c157d9SJohn Baldwin 	 * its state.
1806f5c157d9SJohn Baldwin 	 */
1807f5c157d9SJohn Baldwin 	if (TD_ON_LOCK(td) && oldprio != prio)
1808f5c157d9SJohn Baldwin 		turnstile_adjust(td, oldprio);
1809f5c157d9SJohn Baldwin }
1810f5c157d9SJohn Baldwin 
1811ae7a6b38SJeff Roberson /*
1812ae7a6b38SJeff Roberson  * Set the base user priority, does not effect current running priority.
1813ae7a6b38SJeff Roberson  */
181435e6168fSJeff Roberson void
18158460a577SJohn Birrell sched_user_prio(struct thread *td, u_char prio)
18163db720fdSDavid Xu {
18173db720fdSDavid Xu 
18188460a577SJohn Birrell 	td->td_base_user_pri = prio;
1819acbe332aSDavid Xu 	if (td->td_lend_user_pri <= prio)
1820fc6c30f6SJulian Elischer 		return;
18218460a577SJohn Birrell 	td->td_user_pri = prio;
18223db720fdSDavid Xu }
18233db720fdSDavid Xu 
18243db720fdSDavid Xu void
18253db720fdSDavid Xu sched_lend_user_prio(struct thread *td, u_char prio)
18263db720fdSDavid Xu {
18273db720fdSDavid Xu 
1828435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1829acbe332aSDavid Xu 	td->td_lend_user_pri = prio;
1830c8e368a9SDavid Xu 	td->td_user_pri = min(prio, td->td_base_user_pri);
1831c8e368a9SDavid Xu 	if (td->td_priority > td->td_user_pri)
1832c8e368a9SDavid Xu 		sched_prio(td, td->td_user_pri);
1833c8e368a9SDavid Xu 	else if (td->td_priority != td->td_user_pri)
1834c8e368a9SDavid Xu 		td->td_flags |= TDF_NEEDRESCHED;
1835435806d3SDavid Xu }
18363db720fdSDavid Xu 
1837ae7a6b38SJeff Roberson /*
1838c47f202bSJeff Roberson  * Handle migration from sched_switch().  This happens only for
1839c47f202bSJeff Roberson  * cpu binding.
1840c47f202bSJeff Roberson  */
1841c47f202bSJeff Roberson static struct mtx *
1842c47f202bSJeff Roberson sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1843c47f202bSJeff Roberson {
1844c47f202bSJeff Roberson 	struct tdq *tdn;
1845c47f202bSJeff Roberson 
1846efe67753SNathan Whitehorn 	KASSERT(!CPU_ABSENT(td_get_sched(td)->ts_cpu), ("sched_switch_migrate: "
1847efe67753SNathan Whitehorn 	    "thread %s queued on absent CPU %d.", td->td_name,
1848efe67753SNathan Whitehorn 	    td_get_sched(td)->ts_cpu));
184993ccd6bfSKonstantin Belousov 	tdn = TDQ_CPU(td_get_sched(td)->ts_cpu);
1850c47f202bSJeff Roberson #ifdef SMP
18519727e637SJeff Roberson 	tdq_load_rem(tdq, td);
1852c47f202bSJeff Roberson 	/*
1853c47f202bSJeff Roberson 	 * Do the lock dance required to avoid LOR.  We grab an extra
1854c47f202bSJeff Roberson 	 * spinlock nesting to prevent preemption while we're
1855c47f202bSJeff Roberson 	 * not holding either run-queue lock.
1856c47f202bSJeff Roberson 	 */
1857c47f202bSJeff Roberson 	spinlock_enter();
1858b0b9dee5SAttilio Rao 	thread_lock_block(td);	/* This releases the lock on tdq. */
1859435068aaSAttilio Rao 
1860435068aaSAttilio Rao 	/*
1861435068aaSAttilio Rao 	 * Acquire both run-queue locks before placing the thread on the new
1862435068aaSAttilio Rao 	 * run-queue to avoid deadlocks created by placing a thread with a
1863435068aaSAttilio Rao 	 * blocked lock on the run-queue of a remote processor.  The deadlock
1864435068aaSAttilio Rao 	 * occurs when a third processor attempts to lock the two queues in
1865435068aaSAttilio Rao 	 * question while the target processor is spinning with its own
1866435068aaSAttilio Rao 	 * run-queue lock held while waiting for the blocked lock to clear.
1867435068aaSAttilio Rao 	 */
1868435068aaSAttilio Rao 	tdq_lock_pair(tdn, tdq);
1869c47f202bSJeff Roberson 	tdq_add(tdn, td, flags);
187027ee18adSRyan Stone 	tdq_notify(tdn, td);
1871c47f202bSJeff Roberson 	TDQ_UNLOCK(tdn);
1872c47f202bSJeff Roberson 	spinlock_exit();
1873c47f202bSJeff Roberson #endif
1874c47f202bSJeff Roberson 	return (TDQ_LOCKPTR(tdn));
1875c47f202bSJeff Roberson }
1876c47f202bSJeff Roberson 
1877c47f202bSJeff Roberson /*
1878b0b9dee5SAttilio Rao  * Variadic version of thread_lock_unblock() that does not assume td_lock
1879b0b9dee5SAttilio Rao  * is blocked.
1880ae7a6b38SJeff Roberson  */
1881ae7a6b38SJeff Roberson static inline void
1882ae7a6b38SJeff Roberson thread_unblock_switch(struct thread *td, struct mtx *mtx)
1883ae7a6b38SJeff Roberson {
1884ae7a6b38SJeff Roberson 	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1885ae7a6b38SJeff Roberson 	    (uintptr_t)mtx);
1886ae7a6b38SJeff Roberson }
1887ae7a6b38SJeff Roberson 
1888ae7a6b38SJeff Roberson /*
1889ae7a6b38SJeff Roberson  * Switch threads.  This function has to handle threads coming in while
1890ae7a6b38SJeff Roberson  * blocked for some reason, running, or idle.  It also must deal with
1891ae7a6b38SJeff Roberson  * migrating a thread from one queue to another as running threads may
1892ae7a6b38SJeff Roberson  * be assigned elsewhere via binding.
1893ae7a6b38SJeff Roberson  */
18943db720fdSDavid Xu void
18953389af30SJulian Elischer sched_switch(struct thread *td, struct thread *newtd, int flags)
189635e6168fSJeff Roberson {
1897c02bbb43SJeff Roberson 	struct tdq *tdq;
1898ad1e7d28SJulian Elischer 	struct td_sched *ts;
1899ae7a6b38SJeff Roberson 	struct mtx *mtx;
1900c47f202bSJeff Roberson 	int srqflag;
19013d7f4117SAlexander Motin 	int cpuid, preempted;
190235e6168fSJeff Roberson 
19037b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
19046d55b3ecSJeff Roberson 	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
190535e6168fSJeff Roberson 
1906ae7a6b38SJeff Roberson 	cpuid = PCPU_GET(cpuid);
1907ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpuid);
190893ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
1909c47f202bSJeff Roberson 	mtx = td->td_lock;
19107295465eSAlexander Motin 	sched_pctcpu_update(ts, 1);
1911ae7a6b38SJeff Roberson 	ts->ts_rltick = ticks;
1912060563ecSJulian Elischer 	td->td_lastcpu = td->td_oncpu;
1913060563ecSJulian Elischer 	td->td_oncpu = NOCPU;
1914ad9dadc4SAndriy Gapon 	preempted = (td->td_flags & TDF_SLICEEND) == 0 &&
1915ad9dadc4SAndriy Gapon 	    (flags & SW_PREEMPT) != 0;
19163d7f4117SAlexander Motin 	td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
191777918643SStephan Uphoff 	td->td_owepreempt = 0;
19182c27cb3aSAlexander Motin 	if (!TD_IS_IDLETHREAD(td))
19191690c6c1SJeff Roberson 		tdq->tdq_switchcnt++;
1920b11fdad0SJeff Roberson 	/*
1921ae7a6b38SJeff Roberson 	 * The lock pointer in an idle thread should never change.  Reset it
1922ae7a6b38SJeff Roberson 	 * to CAN_RUN as well.
1923b11fdad0SJeff Roberson 	 */
1924486a9414SJulian Elischer 	if (TD_IS_IDLETHREAD(td)) {
1925ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1926bf0acc27SJohn Baldwin 		TD_SET_CAN_RUN(td);
19277b20fb19SJeff Roberson 	} else if (TD_IS_RUNNING(td)) {
1928ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
19293d7f4117SAlexander Motin 		srqflag = preempted ?
1930598b368dSJeff Roberson 		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1931c47f202bSJeff Roberson 		    SRQ_OURSELF|SRQ_YIELDING;
1932ba4932b5SMatthew D Fleming #ifdef SMP
19330f7a0ebdSMatthew D Fleming 		if (THREAD_CAN_MIGRATE(td) && !THREAD_CAN_SCHED(td, ts->ts_cpu))
19340f7a0ebdSMatthew D Fleming 			ts->ts_cpu = sched_pickcpu(td, 0);
1935ba4932b5SMatthew D Fleming #endif
1936c47f202bSJeff Roberson 		if (ts->ts_cpu == cpuid)
19379727e637SJeff Roberson 			tdq_runq_add(tdq, td, srqflag);
19380f7a0ebdSMatthew D Fleming 		else {
19390f7a0ebdSMatthew D Fleming 			KASSERT(THREAD_CAN_MIGRATE(td) ||
19400f7a0ebdSMatthew D Fleming 			    (ts->ts_flags & TSF_BOUND) != 0,
19410f7a0ebdSMatthew D Fleming 			    ("Thread %p shouldn't migrate", td));
1942c47f202bSJeff Roberson 			mtx = sched_switch_migrate(tdq, td, srqflag);
19430f7a0ebdSMatthew D Fleming 		}
1944ae7a6b38SJeff Roberson 	} else {
1945ae7a6b38SJeff Roberson 		/* This thread must be going to sleep. */
1946ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
1947b0b9dee5SAttilio Rao 		mtx = thread_lock_block(td);
19489727e637SJeff Roberson 		tdq_load_rem(tdq, td);
1949ae7a6b38SJeff Roberson 	}
1950afa0a46cSAndriy Gapon 
1951afa0a46cSAndriy Gapon #if (KTR_COMPILE & KTR_SCHED) != 0
1952afa0a46cSAndriy Gapon 	if (TD_IS_IDLETHREAD(td))
1953afa0a46cSAndriy Gapon 		KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle",
1954afa0a46cSAndriy Gapon 		    "prio:%d", td->td_priority);
1955afa0a46cSAndriy Gapon 	else
1956afa0a46cSAndriy Gapon 		KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td),
1957afa0a46cSAndriy Gapon 		    "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg,
1958afa0a46cSAndriy Gapon 		    "lockname:\"%s\"", td->td_lockname);
1959afa0a46cSAndriy Gapon #endif
1960afa0a46cSAndriy Gapon 
1961ae7a6b38SJeff Roberson 	/*
1962ae7a6b38SJeff Roberson 	 * We enter here with the thread blocked and assigned to the
1963ae7a6b38SJeff Roberson 	 * appropriate cpu run-queue or sleep-queue and with the current
1964ae7a6b38SJeff Roberson 	 * thread-queue locked.
1965ae7a6b38SJeff Roberson 	 */
1966ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
19672454aaf5SJeff Roberson 	newtd = choosethread();
1968ae7a6b38SJeff Roberson 	/*
1969ae7a6b38SJeff Roberson 	 * Call the MD code to switch contexts if necessary.
1970ae7a6b38SJeff Roberson 	 */
1971ebccf1e3SJoseph Koshy 	if (td != newtd) {
1972ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1973ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1974ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1975ebccf1e3SJoseph Koshy #endif
1976d9fae5abSAndriy Gapon 		SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
1977eea4f254SJeff Roberson 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
197859c68134SJeff Roberson 		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
197993ccd6bfSKonstantin Belousov 		sched_pctcpu_update(td_get_sched(newtd), 0);
19806f5f25e5SJohn Birrell 
19816f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
19826f5f25e5SJohn Birrell 		/*
19836f5f25e5SJohn Birrell 		 * If DTrace has set the active vtime enum to anything
19846f5f25e5SJohn Birrell 		 * other than INACTIVE (0), then it should have set the
19856f5f25e5SJohn Birrell 		 * function to call.
19866f5f25e5SJohn Birrell 		 */
19876f5f25e5SJohn Birrell 		if (dtrace_vtime_active)
19886f5f25e5SJohn Birrell 			(*dtrace_vtime_switch_func)(newtd);
19896f5f25e5SJohn Birrell #endif
19906f5f25e5SJohn Birrell 
1991ae7a6b38SJeff Roberson 		cpu_switch(td, newtd, mtx);
1992ae7a6b38SJeff Roberson 		/*
1993ae7a6b38SJeff Roberson 		 * We may return from cpu_switch on a different cpu.  However,
1994ae7a6b38SJeff Roberson 		 * we always return with td_lock pointing to the current cpu's
1995ae7a6b38SJeff Roberson 		 * run queue lock.
1996ae7a6b38SJeff Roberson 		 */
1997ae7a6b38SJeff Roberson 		cpuid = PCPU_GET(cpuid);
1998ae7a6b38SJeff Roberson 		tdq = TDQ_CPU(cpuid);
1999eea4f254SJeff Roberson 		lock_profile_obtain_lock_success(
2000eea4f254SJeff Roberson 		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2001b3e9e682SRyan Stone 
2002d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , on__cpu);
2003ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
2004ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
2005ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
2006ebccf1e3SJoseph Koshy #endif
2007b3e9e682SRyan Stone 	} else {
2008ae7a6b38SJeff Roberson 		thread_unblock_switch(td, mtx);
2009d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , remain__cpu);
2010b3e9e682SRyan Stone 	}
2011afa0a46cSAndriy Gapon 
2012afa0a46cSAndriy Gapon 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
2013afa0a46cSAndriy Gapon 	    "prio:%d", td->td_priority);
2014afa0a46cSAndriy Gapon 
2015ae7a6b38SJeff Roberson 	/*
2016ae7a6b38SJeff Roberson 	 * Assert that all went well and return.
2017ae7a6b38SJeff Roberson 	 */
2018ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
2019ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2020ae7a6b38SJeff Roberson 	td->td_oncpu = cpuid;
202135e6168fSJeff Roberson }
202235e6168fSJeff Roberson 
2023ae7a6b38SJeff Roberson /*
2024ae7a6b38SJeff Roberson  * Adjust thread priorities as a result of a nice request.
2025ae7a6b38SJeff Roberson  */
202635e6168fSJeff Roberson void
2027fa885116SJulian Elischer sched_nice(struct proc *p, int nice)
202835e6168fSJeff Roberson {
202935e6168fSJeff Roberson 	struct thread *td;
203035e6168fSJeff Roberson 
2031fa885116SJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
2032e7d50326SJeff Roberson 
2033fa885116SJulian Elischer 	p->p_nice = nice;
20348460a577SJohn Birrell 	FOREACH_THREAD_IN_PROC(p, td) {
20357b20fb19SJeff Roberson 		thread_lock(td);
20368460a577SJohn Birrell 		sched_priority(td);
2037e7d50326SJeff Roberson 		sched_prio(td, td->td_base_user_pri);
20387b20fb19SJeff Roberson 		thread_unlock(td);
203935e6168fSJeff Roberson 	}
2040fa885116SJulian Elischer }
204135e6168fSJeff Roberson 
2042ae7a6b38SJeff Roberson /*
2043ae7a6b38SJeff Roberson  * Record the sleep time for the interactivity scorer.
2044ae7a6b38SJeff Roberson  */
204535e6168fSJeff Roberson void
2046c5aa6b58SJeff Roberson sched_sleep(struct thread *td, int prio)
204735e6168fSJeff Roberson {
2048e7d50326SJeff Roberson 
20497b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
205035e6168fSJeff Roberson 
205154b0e65fSJeff Roberson 	td->td_slptick = ticks;
205217c4c356SKonstantin Belousov 	if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
2053c5aa6b58SJeff Roberson 		td->td_flags |= TDF_CANSWAP;
20542dc29adbSJohn Baldwin 	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
20552dc29adbSJohn Baldwin 		return;
20560502fe2eSJeff Roberson 	if (static_boost == 1 && prio)
2057c5aa6b58SJeff Roberson 		sched_prio(td, prio);
20580502fe2eSJeff Roberson 	else if (static_boost && td->td_priority > static_boost)
20590502fe2eSJeff Roberson 		sched_prio(td, static_boost);
206035e6168fSJeff Roberson }
206135e6168fSJeff Roberson 
2062ae7a6b38SJeff Roberson /*
2063ae7a6b38SJeff Roberson  * Schedule a thread to resume execution and record how long it voluntarily
2064ae7a6b38SJeff Roberson  * slept.  We also update the pctcpu, interactivity, and priority.
2065ae7a6b38SJeff Roberson  */
206635e6168fSJeff Roberson void
206735e6168fSJeff Roberson sched_wakeup(struct thread *td)
206835e6168fSJeff Roberson {
206914618990SJeff Roberson 	struct td_sched *ts;
2070ae7a6b38SJeff Roberson 	int slptick;
2071e7d50326SJeff Roberson 
20727b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
207393ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
2074c5aa6b58SJeff Roberson 	td->td_flags &= ~TDF_CANSWAP;
207535e6168fSJeff Roberson 	/*
2076e7d50326SJeff Roberson 	 * If we slept for more than a tick update our interactivity and
2077e7d50326SJeff Roberson 	 * priority.
207835e6168fSJeff Roberson 	 */
207954b0e65fSJeff Roberson 	slptick = td->td_slptick;
208054b0e65fSJeff Roberson 	td->td_slptick = 0;
2081ae7a6b38SJeff Roberson 	if (slptick && slptick != ticks) {
20827295465eSAlexander Motin 		ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
20838460a577SJohn Birrell 		sched_interact_update(td);
20847295465eSAlexander Motin 		sched_pctcpu_update(ts, 0);
2085f1e8dc4aSJeff Roberson 	}
20865e5c3873SJeff Roberson 	/*
20875e5c3873SJeff Roberson 	 * Reset the slice value since we slept and advanced the round-robin.
20885e5c3873SJeff Roberson 	 */
20895e5c3873SJeff Roberson 	ts->ts_slice = 0;
20907a5e5e2aSJeff Roberson 	sched_add(td, SRQ_BORING);
209135e6168fSJeff Roberson }
209235e6168fSJeff Roberson 
209335e6168fSJeff Roberson /*
209435e6168fSJeff Roberson  * Penalize the parent for creating a new child and initialize the child's
209535e6168fSJeff Roberson  * priority.
209635e6168fSJeff Roberson  */
209735e6168fSJeff Roberson void
20988460a577SJohn Birrell sched_fork(struct thread *td, struct thread *child)
209915dc847eSJeff Roberson {
21007b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
210193ccd6bfSKonstantin Belousov 	sched_pctcpu_update(td_get_sched(td), 1);
2102ad1e7d28SJulian Elischer 	sched_fork_thread(td, child);
2103e7d50326SJeff Roberson 	/*
2104e7d50326SJeff Roberson 	 * Penalize the parent and child for forking.
2105e7d50326SJeff Roberson 	 */
2106e7d50326SJeff Roberson 	sched_interact_fork(child);
2107e7d50326SJeff Roberson 	sched_priority(child);
210893ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_runtime += tickincr;
2109e7d50326SJeff Roberson 	sched_interact_update(td);
2110e7d50326SJeff Roberson 	sched_priority(td);
2111ad1e7d28SJulian Elischer }
2112ad1e7d28SJulian Elischer 
2113ae7a6b38SJeff Roberson /*
2114ae7a6b38SJeff Roberson  * Fork a new thread, may be within the same process.
2115ae7a6b38SJeff Roberson  */
2116ad1e7d28SJulian Elischer void
2117ad1e7d28SJulian Elischer sched_fork_thread(struct thread *td, struct thread *child)
2118ad1e7d28SJulian Elischer {
2119ad1e7d28SJulian Elischer 	struct td_sched *ts;
2120ad1e7d28SJulian Elischer 	struct td_sched *ts2;
21215e5c3873SJeff Roberson 	struct tdq *tdq;
21228460a577SJohn Birrell 
21235e5c3873SJeff Roberson 	tdq = TDQ_SELF();
21248b16c208SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2125e7d50326SJeff Roberson 	/*
2126e7d50326SJeff Roberson 	 * Initialize child.
2127e7d50326SJeff Roberson 	 */
212893ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
212993ccd6bfSKonstantin Belousov 	ts2 = td_get_sched(child);
213092de34dfSJohn Baldwin 	child->td_oncpu = NOCPU;
213192de34dfSJohn Baldwin 	child->td_lastcpu = NOCPU;
21325e5c3873SJeff Roberson 	child->td_lock = TDQ_LOCKPTR(tdq);
21338b16c208SJeff Roberson 	child->td_cpuset = cpuset_ref(td->td_cpuset);
2134ad1e7d28SJulian Elischer 	ts2->ts_cpu = ts->ts_cpu;
21358b16c208SJeff Roberson 	ts2->ts_flags = 0;
2136e7d50326SJeff Roberson 	/*
213722d19207SJohn Baldwin 	 * Grab our parents cpu estimation information.
2138e7d50326SJeff Roberson 	 */
2139ad1e7d28SJulian Elischer 	ts2->ts_ticks = ts->ts_ticks;
2140ad1e7d28SJulian Elischer 	ts2->ts_ltick = ts->ts_ltick;
2141ad1e7d28SJulian Elischer 	ts2->ts_ftick = ts->ts_ftick;
214222d19207SJohn Baldwin 	/*
214322d19207SJohn Baldwin 	 * Do not inherit any borrowed priority from the parent.
214422d19207SJohn Baldwin 	 */
214522d19207SJohn Baldwin 	child->td_priority = child->td_base_pri;
2146e7d50326SJeff Roberson 	/*
2147e7d50326SJeff Roberson 	 * And update interactivity score.
2148e7d50326SJeff Roberson 	 */
2149ae7a6b38SJeff Roberson 	ts2->ts_slptime = ts->ts_slptime;
2150ae7a6b38SJeff Roberson 	ts2->ts_runtime = ts->ts_runtime;
21515e5c3873SJeff Roberson 	/* Attempt to quickly learn interactivity. */
21525e5c3873SJeff Roberson 	ts2->ts_slice = tdq_slice(tdq) - sched_slice_min;
21538f51ad55SJeff Roberson #ifdef KTR
21548f51ad55SJeff Roberson 	bzero(ts2->ts_name, sizeof(ts2->ts_name));
21558f51ad55SJeff Roberson #endif
215615dc847eSJeff Roberson }
215715dc847eSJeff Roberson 
2158ae7a6b38SJeff Roberson /*
2159ae7a6b38SJeff Roberson  * Adjust the priority class of a thread.
2160ae7a6b38SJeff Roberson  */
216115dc847eSJeff Roberson void
21628460a577SJohn Birrell sched_class(struct thread *td, int class)
216315dc847eSJeff Roberson {
216415dc847eSJeff Roberson 
21657b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
21668460a577SJohn Birrell 	if (td->td_pri_class == class)
216715dc847eSJeff Roberson 		return;
21688460a577SJohn Birrell 	td->td_pri_class = class;
216935e6168fSJeff Roberson }
217035e6168fSJeff Roberson 
217135e6168fSJeff Roberson /*
217235e6168fSJeff Roberson  * Return some of the child's priority and interactivity to the parent.
217335e6168fSJeff Roberson  */
217435e6168fSJeff Roberson void
2175fc6c30f6SJulian Elischer sched_exit(struct proc *p, struct thread *child)
217635e6168fSJeff Roberson {
2177e7d50326SJeff Roberson 	struct thread *td;
2178141ad61cSJeff Roberson 
21798f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2180cd39bb09SXin LI 	    "prio:%d", child->td_priority);
2181374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
2182e7d50326SJeff Roberson 	td = FIRST_THREAD_IN_PROC(p);
2183e7d50326SJeff Roberson 	sched_exit_thread(td, child);
2184ad1e7d28SJulian Elischer }
2185ad1e7d28SJulian Elischer 
2186ae7a6b38SJeff Roberson /*
2187ae7a6b38SJeff Roberson  * Penalize another thread for the time spent on this one.  This helps to
2188ae7a6b38SJeff Roberson  * worsen the priority and interactivity of processes which schedule batch
2189ae7a6b38SJeff Roberson  * jobs such as make.  This has little effect on the make process itself but
2190ae7a6b38SJeff Roberson  * causes new processes spawned by it to receive worse scores immediately.
2191ae7a6b38SJeff Roberson  */
2192ad1e7d28SJulian Elischer void
2193fc6c30f6SJulian Elischer sched_exit_thread(struct thread *td, struct thread *child)
2194ad1e7d28SJulian Elischer {
2195fc6c30f6SJulian Elischer 
21968f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2197cd39bb09SXin LI 	    "prio:%d", child->td_priority);
2198e7d50326SJeff Roberson 	/*
2199e7d50326SJeff Roberson 	 * Give the child's runtime to the parent without returning the
2200e7d50326SJeff Roberson 	 * sleep time as a penalty to the parent.  This causes shells that
2201e7d50326SJeff Roberson 	 * launch expensive things to mark their children as expensive.
2202e7d50326SJeff Roberson 	 */
22037b20fb19SJeff Roberson 	thread_lock(td);
220493ccd6bfSKonstantin Belousov 	td_get_sched(td)->ts_runtime += td_get_sched(child)->ts_runtime;
2205fc6c30f6SJulian Elischer 	sched_interact_update(td);
2206e7d50326SJeff Roberson 	sched_priority(td);
22077b20fb19SJeff Roberson 	thread_unlock(td);
2208ad1e7d28SJulian Elischer }
2209ad1e7d28SJulian Elischer 
2210ff256d9cSJeff Roberson void
2211ff256d9cSJeff Roberson sched_preempt(struct thread *td)
2212ff256d9cSJeff Roberson {
2213ff256d9cSJeff Roberson 	struct tdq *tdq;
2214ff256d9cSJeff Roberson 
2215b3e9e682SRyan Stone 	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
2216b3e9e682SRyan Stone 
2217ff256d9cSJeff Roberson 	thread_lock(td);
2218ff256d9cSJeff Roberson 	tdq = TDQ_SELF();
2219ff256d9cSJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2220ff256d9cSJeff Roberson 	tdq->tdq_ipipending = 0;
2221ff256d9cSJeff Roberson 	if (td->td_priority > tdq->tdq_lowpri) {
22228df78c41SJeff Roberson 		int flags;
22238df78c41SJeff Roberson 
22248df78c41SJeff Roberson 		flags = SW_INVOL | SW_PREEMPT;
2225ff256d9cSJeff Roberson 		if (td->td_critnest > 1)
2226ff256d9cSJeff Roberson 			td->td_owepreempt = 1;
22278df78c41SJeff Roberson 		else if (TD_IS_IDLETHREAD(td))
22288df78c41SJeff Roberson 			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2229ff256d9cSJeff Roberson 		else
22308df78c41SJeff Roberson 			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2231ff256d9cSJeff Roberson 	}
2232ff256d9cSJeff Roberson 	thread_unlock(td);
2233ff256d9cSJeff Roberson }
2234ff256d9cSJeff Roberson 
2235ae7a6b38SJeff Roberson /*
2236ae7a6b38SJeff Roberson  * Fix priorities on return to user-space.  Priorities may be elevated due
2237ae7a6b38SJeff Roberson  * to static priorities in msleep() or similar.
2238ae7a6b38SJeff Roberson  */
2239ad1e7d28SJulian Elischer void
2240ad1e7d28SJulian Elischer sched_userret(struct thread *td)
2241ad1e7d28SJulian Elischer {
2242ad1e7d28SJulian Elischer 	/*
2243ad1e7d28SJulian Elischer 	 * XXX we cheat slightly on the locking here to avoid locking in
2244ad1e7d28SJulian Elischer 	 * the usual case.  Setting td_priority here is essentially an
2245ad1e7d28SJulian Elischer 	 * incomplete workaround for not setting it properly elsewhere.
2246ad1e7d28SJulian Elischer 	 * Now that some interrupt handlers are threads, not setting it
2247ad1e7d28SJulian Elischer 	 * properly elsewhere can clobber it in the window between setting
2248ad1e7d28SJulian Elischer 	 * it here and returning to user mode, so don't waste time setting
2249ad1e7d28SJulian Elischer 	 * it perfectly here.
2250ad1e7d28SJulian Elischer 	 */
2251ad1e7d28SJulian Elischer 	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2252ad1e7d28SJulian Elischer 	    ("thread with borrowed priority returning to userland"));
2253ad1e7d28SJulian Elischer 	if (td->td_priority != td->td_user_pri) {
22547b20fb19SJeff Roberson 		thread_lock(td);
2255ad1e7d28SJulian Elischer 		td->td_priority = td->td_user_pri;
2256ad1e7d28SJulian Elischer 		td->td_base_pri = td->td_user_pri;
225762fa74d9SJeff Roberson 		tdq_setlowpri(TDQ_SELF(), td);
22587b20fb19SJeff Roberson 		thread_unlock(td);
2259ad1e7d28SJulian Elischer         }
226035e6168fSJeff Roberson }
226135e6168fSJeff Roberson 
2262ae7a6b38SJeff Roberson /*
2263ae7a6b38SJeff Roberson  * Handle a stathz tick.  This is really only relevant for timeshare
2264ae7a6b38SJeff Roberson  * threads.
2265ae7a6b38SJeff Roberson  */
226635e6168fSJeff Roberson void
22677cf90fb3SJeff Roberson sched_clock(struct thread *td)
226835e6168fSJeff Roberson {
2269ad1e7d28SJulian Elischer 	struct tdq *tdq;
2270ad1e7d28SJulian Elischer 	struct td_sched *ts;
227135e6168fSJeff Roberson 
2272ae7a6b38SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
22733f872f85SJeff Roberson 	tdq = TDQ_SELF();
22747fcf154aSJeff Roberson #ifdef SMP
22757fcf154aSJeff Roberson 	/*
22767fcf154aSJeff Roberson 	 * We run the long term load balancer infrequently on the first cpu.
22777fcf154aSJeff Roberson 	 */
22787fcf154aSJeff Roberson 	if (balance_tdq == tdq) {
22797fcf154aSJeff Roberson 		if (balance_ticks && --balance_ticks == 0)
22807fcf154aSJeff Roberson 			sched_balance();
22817fcf154aSJeff Roberson 	}
22827fcf154aSJeff Roberson #endif
22833f872f85SJeff Roberson 	/*
22841690c6c1SJeff Roberson 	 * Save the old switch count so we have a record of the last ticks
22851690c6c1SJeff Roberson 	 * activity.   Initialize the new switch count based on our load.
22861690c6c1SJeff Roberson 	 * If there is some activity seed it to reflect that.
22871690c6c1SJeff Roberson 	 */
22881690c6c1SJeff Roberson 	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
22896c47aaaeSJeff Roberson 	tdq->tdq_switchcnt = tdq->tdq_load;
22901690c6c1SJeff Roberson 	/*
22913f872f85SJeff Roberson 	 * Advance the insert index once for each tick to ensure that all
22923f872f85SJeff Roberson 	 * threads get a chance to run.
22933f872f85SJeff Roberson 	 */
22943f872f85SJeff Roberson 	if (tdq->tdq_idx == tdq->tdq_ridx) {
22953f872f85SJeff Roberson 		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
22963f872f85SJeff Roberson 		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
22973f872f85SJeff Roberson 			tdq->tdq_ridx = tdq->tdq_idx;
22983f872f85SJeff Roberson 	}
229993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
23007295465eSAlexander Motin 	sched_pctcpu_update(ts, 1);
2301fd0b8c78SJeff Roberson 	if (td->td_pri_class & PRI_FIFO_BIT)
2302a8949de2SJeff Roberson 		return;
2303c9a8cba4SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2304a8949de2SJeff Roberson 		/*
2305fd0b8c78SJeff Roberson 		 * We used a tick; charge it to the thread so
2306fd0b8c78SJeff Roberson 		 * that we can compute our interactivity.
230715dc847eSJeff Roberson 		 */
230893ccd6bfSKonstantin Belousov 		td_get_sched(td)->ts_runtime += tickincr;
23098460a577SJohn Birrell 		sched_interact_update(td);
231073daf66fSJeff Roberson 		sched_priority(td);
2311fd0b8c78SJeff Roberson 	}
2312579895dfSAlexander Motin 
231335e6168fSJeff Roberson 	/*
2314579895dfSAlexander Motin 	 * Force a context switch if the current thread has used up a full
2315579895dfSAlexander Motin 	 * time slice (default is 100ms).
231635e6168fSJeff Roberson 	 */
23175e5c3873SJeff Roberson 	if (!TD_IS_IDLETHREAD(td) && ++ts->ts_slice >= tdq_slice(tdq)) {
23185e5c3873SJeff Roberson 		ts->ts_slice = 0;
23193d7f4117SAlexander Motin 		td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
232035e6168fSJeff Roberson 	}
2321579895dfSAlexander Motin }
232235e6168fSJeff Roberson 
2323ccd0ec40SKonstantin Belousov u_int
2324ccd0ec40SKonstantin Belousov sched_estcpu(struct thread *td __unused)
2325ae7a6b38SJeff Roberson {
2326ae7a6b38SJeff Roberson 
2327ccd0ec40SKonstantin Belousov 	return (0);
2328ae7a6b38SJeff Roberson }
2329ae7a6b38SJeff Roberson 
2330ae7a6b38SJeff Roberson /*
2331ae7a6b38SJeff Roberson  * Return whether the current CPU has runnable tasks.  Used for in-kernel
2332ae7a6b38SJeff Roberson  * cooperative idle threads.
2333ae7a6b38SJeff Roberson  */
233435e6168fSJeff Roberson int
233535e6168fSJeff Roberson sched_runnable(void)
233635e6168fSJeff Roberson {
2337ad1e7d28SJulian Elischer 	struct tdq *tdq;
2338b90816f1SJeff Roberson 	int load;
233935e6168fSJeff Roberson 
2340b90816f1SJeff Roberson 	load = 1;
2341b90816f1SJeff Roberson 
2342ad1e7d28SJulian Elischer 	tdq = TDQ_SELF();
23433f741ca1SJeff Roberson 	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2344d2ad694cSJeff Roberson 		if (tdq->tdq_load > 0)
23453f741ca1SJeff Roberson 			goto out;
23463f741ca1SJeff Roberson 	} else
2347d2ad694cSJeff Roberson 		if (tdq->tdq_load - 1 > 0)
2348b90816f1SJeff Roberson 			goto out;
2349b90816f1SJeff Roberson 	load = 0;
2350b90816f1SJeff Roberson out:
2351b90816f1SJeff Roberson 	return (load);
235235e6168fSJeff Roberson }
235335e6168fSJeff Roberson 
2354ae7a6b38SJeff Roberson /*
2355ae7a6b38SJeff Roberson  * Choose the highest priority thread to run.  The thread is removed from
2356ae7a6b38SJeff Roberson  * the run-queue while running however the load remains.  For SMP we set
2357ae7a6b38SJeff Roberson  * the tdq in the global idle bitmask if it idles here.
2358ae7a6b38SJeff Roberson  */
23597a5e5e2aSJeff Roberson struct thread *
2360c9f25d8fSJeff Roberson sched_choose(void)
2361c9f25d8fSJeff Roberson {
23629727e637SJeff Roberson 	struct thread *td;
2363ae7a6b38SJeff Roberson 	struct tdq *tdq;
2364ae7a6b38SJeff Roberson 
2365ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2366ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
23679727e637SJeff Roberson 	td = tdq_choose(tdq);
23689727e637SJeff Roberson 	if (td) {
23699727e637SJeff Roberson 		tdq_runq_rem(tdq, td);
23700502fe2eSJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
23719727e637SJeff Roberson 		return (td);
237235e6168fSJeff Roberson 	}
23730502fe2eSJeff Roberson 	tdq->tdq_lowpri = PRI_MAX_IDLE;
237462fa74d9SJeff Roberson 	return (PCPU_GET(idlethread));
23757a5e5e2aSJeff Roberson }
23767a5e5e2aSJeff Roberson 
2377ae7a6b38SJeff Roberson /*
2378ae7a6b38SJeff Roberson  * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2379ae7a6b38SJeff Roberson  * we always request it once we exit a critical section.
2380ae7a6b38SJeff Roberson  */
2381ae7a6b38SJeff Roberson static inline void
2382ae7a6b38SJeff Roberson sched_setpreempt(struct thread *td)
23837a5e5e2aSJeff Roberson {
23847a5e5e2aSJeff Roberson 	struct thread *ctd;
23857a5e5e2aSJeff Roberson 	int cpri;
23867a5e5e2aSJeff Roberson 	int pri;
23877a5e5e2aSJeff Roberson 
2388ff256d9cSJeff Roberson 	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2389ff256d9cSJeff Roberson 
23907a5e5e2aSJeff Roberson 	ctd = curthread;
23917a5e5e2aSJeff Roberson 	pri = td->td_priority;
23927a5e5e2aSJeff Roberson 	cpri = ctd->td_priority;
2393ff256d9cSJeff Roberson 	if (pri < cpri)
2394ff256d9cSJeff Roberson 		ctd->td_flags |= TDF_NEEDRESCHED;
23957a5e5e2aSJeff Roberson 	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2396ae7a6b38SJeff Roberson 		return;
2397ff256d9cSJeff Roberson 	if (!sched_shouldpreempt(pri, cpri, 0))
2398ae7a6b38SJeff Roberson 		return;
23997a5e5e2aSJeff Roberson 	ctd->td_owepreempt = 1;
240035e6168fSJeff Roberson }
240135e6168fSJeff Roberson 
2402ae7a6b38SJeff Roberson /*
240373daf66fSJeff Roberson  * Add a thread to a thread queue.  Select the appropriate runq and add the
240473daf66fSJeff Roberson  * thread to it.  This is the internal function called when the tdq is
240573daf66fSJeff Roberson  * predetermined.
2406ae7a6b38SJeff Roberson  */
240735e6168fSJeff Roberson void
2408ae7a6b38SJeff Roberson tdq_add(struct tdq *tdq, struct thread *td, int flags)
240935e6168fSJeff Roberson {
2410c9f25d8fSJeff Roberson 
2411ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
24127a5e5e2aSJeff Roberson 	KASSERT((td->td_inhibitors == 0),
24137a5e5e2aSJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
24147a5e5e2aSJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
24157a5e5e2aSJeff Roberson 	    ("sched_add: bad thread state"));
2416b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
2417b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
2418ae7a6b38SJeff Roberson 
2419ae7a6b38SJeff Roberson 	if (td->td_priority < tdq->tdq_lowpri)
2420ae7a6b38SJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
24219727e637SJeff Roberson 	tdq_runq_add(tdq, td, flags);
24229727e637SJeff Roberson 	tdq_load_add(tdq, td);
2423ae7a6b38SJeff Roberson }
2424ae7a6b38SJeff Roberson 
2425ae7a6b38SJeff Roberson /*
2426ae7a6b38SJeff Roberson  * Select the target thread queue and add a thread to it.  Request
2427ae7a6b38SJeff Roberson  * preemption or IPI a remote processor if required.
2428ae7a6b38SJeff Roberson  */
2429ae7a6b38SJeff Roberson void
2430ae7a6b38SJeff Roberson sched_add(struct thread *td, int flags)
2431ae7a6b38SJeff Roberson {
2432ae7a6b38SJeff Roberson 	struct tdq *tdq;
24337b8bfa0dSJeff Roberson #ifdef SMP
2434ae7a6b38SJeff Roberson 	int cpu;
2435ae7a6b38SJeff Roberson #endif
24368f51ad55SJeff Roberson 
24378f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
24388f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
24398f51ad55SJeff Roberson 	    sched_tdname(curthread));
24408f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
24418f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
2442b3e9e682SRyan Stone 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
2443b3e9e682SRyan Stone 	    flags & SRQ_PREEMPTED);
2444ae7a6b38SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2445ae7a6b38SJeff Roberson 	/*
2446ae7a6b38SJeff Roberson 	 * Recalculate the priority before we select the target cpu or
2447ae7a6b38SJeff Roberson 	 * run-queue.
2448ae7a6b38SJeff Roberson 	 */
2449ae7a6b38SJeff Roberson 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2450ae7a6b38SJeff Roberson 		sched_priority(td);
2451ae7a6b38SJeff Roberson #ifdef SMP
2452ae7a6b38SJeff Roberson 	/*
2453ae7a6b38SJeff Roberson 	 * Pick the destination cpu and if it isn't ours transfer to the
2454ae7a6b38SJeff Roberson 	 * target cpu.
2455ae7a6b38SJeff Roberson 	 */
2456efe67753SNathan Whitehorn 	td_get_sched(td)->ts_cpu = curcpu; /* Pick something valid to start */
24579727e637SJeff Roberson 	cpu = sched_pickcpu(td, flags);
24589727e637SJeff Roberson 	tdq = sched_setcpu(td, cpu, flags);
2459ae7a6b38SJeff Roberson 	tdq_add(tdq, td, flags);
246073daf66fSJeff Roberson 	if (cpu != PCPU_GET(cpuid)) {
246127ee18adSRyan Stone 		tdq_notify(tdq, td);
24627b8bfa0dSJeff Roberson 		return;
24637b8bfa0dSJeff Roberson 	}
2464ae7a6b38SJeff Roberson #else
2465ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2466ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
2467ae7a6b38SJeff Roberson 	/*
2468ae7a6b38SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
2469ae7a6b38SJeff Roberson 	 * to the scheduler's lock.
2470ae7a6b38SJeff Roberson 	 */
2471ae7a6b38SJeff Roberson 	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2472ae7a6b38SJeff Roberson 	tdq_add(tdq, td, flags);
24737b8bfa0dSJeff Roberson #endif
2474ae7a6b38SJeff Roberson 	if (!(flags & SRQ_YIELDING))
2475ae7a6b38SJeff Roberson 		sched_setpreempt(td);
247635e6168fSJeff Roberson }
247735e6168fSJeff Roberson 
2478ae7a6b38SJeff Roberson /*
2479ae7a6b38SJeff Roberson  * Remove a thread from a run-queue without running it.  This is used
2480ae7a6b38SJeff Roberson  * when we're stealing a thread from a remote queue.  Otherwise all threads
2481ae7a6b38SJeff Roberson  * exit by calling sched_exit_thread() and sched_throw() themselves.
2482ae7a6b38SJeff Roberson  */
248335e6168fSJeff Roberson void
24847cf90fb3SJeff Roberson sched_rem(struct thread *td)
248535e6168fSJeff Roberson {
2486ad1e7d28SJulian Elischer 	struct tdq *tdq;
24877cf90fb3SJeff Roberson 
24888f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
24898f51ad55SJeff Roberson 	    "prio:%d", td->td_priority);
2490b3e9e682SRyan Stone 	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
249193ccd6bfSKonstantin Belousov 	tdq = TDQ_CPU(td_get_sched(td)->ts_cpu);
2492ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2493ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
24947a5e5e2aSJeff Roberson 	KASSERT(TD_ON_RUNQ(td),
2495ad1e7d28SJulian Elischer 	    ("sched_rem: thread not on run queue"));
24969727e637SJeff Roberson 	tdq_runq_rem(tdq, td);
24979727e637SJeff Roberson 	tdq_load_rem(tdq, td);
24987a5e5e2aSJeff Roberson 	TD_SET_CAN_RUN(td);
249962fa74d9SJeff Roberson 	if (td->td_priority == tdq->tdq_lowpri)
250062fa74d9SJeff Roberson 		tdq_setlowpri(tdq, NULL);
250135e6168fSJeff Roberson }
250235e6168fSJeff Roberson 
2503ae7a6b38SJeff Roberson /*
2504ae7a6b38SJeff Roberson  * Fetch cpu utilization information.  Updates on demand.
2505ae7a6b38SJeff Roberson  */
250635e6168fSJeff Roberson fixpt_t
25077cf90fb3SJeff Roberson sched_pctcpu(struct thread *td)
250835e6168fSJeff Roberson {
250935e6168fSJeff Roberson 	fixpt_t pctcpu;
2510ad1e7d28SJulian Elischer 	struct td_sched *ts;
251135e6168fSJeff Roberson 
251235e6168fSJeff Roberson 	pctcpu = 0;
251393ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
251435e6168fSJeff Roberson 
25153da35a0aSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
25167295465eSAlexander Motin 	sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2517ad1e7d28SJulian Elischer 	if (ts->ts_ticks) {
251835e6168fSJeff Roberson 		int rtick;
251935e6168fSJeff Roberson 
252035e6168fSJeff Roberson 		/* How many rtick per second ? */
2521e7d50326SJeff Roberson 		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2522e7d50326SJeff Roberson 		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
252335e6168fSJeff Roberson 	}
252435e6168fSJeff Roberson 
252535e6168fSJeff Roberson 	return (pctcpu);
252635e6168fSJeff Roberson }
252735e6168fSJeff Roberson 
252862fa74d9SJeff Roberson /*
252962fa74d9SJeff Roberson  * Enforce affinity settings for a thread.  Called after adjustments to
253062fa74d9SJeff Roberson  * cpumask.
253162fa74d9SJeff Roberson  */
2532885d51a3SJeff Roberson void
2533885d51a3SJeff Roberson sched_affinity(struct thread *td)
2534885d51a3SJeff Roberson {
253562fa74d9SJeff Roberson #ifdef SMP
253662fa74d9SJeff Roberson 	struct td_sched *ts;
253762fa74d9SJeff Roberson 
253862fa74d9SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
253993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
254062fa74d9SJeff Roberson 	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
254162fa74d9SJeff Roberson 		return;
254253a6c8b3SJeff Roberson 	if (TD_ON_RUNQ(td)) {
254353a6c8b3SJeff Roberson 		sched_rem(td);
254453a6c8b3SJeff Roberson 		sched_add(td, SRQ_BORING);
254553a6c8b3SJeff Roberson 		return;
254653a6c8b3SJeff Roberson 	}
254762fa74d9SJeff Roberson 	if (!TD_IS_RUNNING(td))
254862fa74d9SJeff Roberson 		return;
254962fa74d9SJeff Roberson 	/*
25500f7a0ebdSMatthew D Fleming 	 * Force a switch before returning to userspace.  If the
25510f7a0ebdSMatthew D Fleming 	 * target thread is not running locally send an ipi to force
25520f7a0ebdSMatthew D Fleming 	 * the issue.
255362fa74d9SJeff Roberson 	 */
2554a8103ae8SJohn Baldwin 	td->td_flags |= TDF_NEEDRESCHED;
25550f7a0ebdSMatthew D Fleming 	if (td != curthread)
25560f7a0ebdSMatthew D Fleming 		ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
255762fa74d9SJeff Roberson #endif
2558885d51a3SJeff Roberson }
2559885d51a3SJeff Roberson 
2560ae7a6b38SJeff Roberson /*
2561ae7a6b38SJeff Roberson  * Bind a thread to a target cpu.
2562ae7a6b38SJeff Roberson  */
25639bacd788SJeff Roberson void
25649bacd788SJeff Roberson sched_bind(struct thread *td, int cpu)
25659bacd788SJeff Roberson {
2566ad1e7d28SJulian Elischer 	struct td_sched *ts;
25679bacd788SJeff Roberson 
2568c47f202bSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
25691d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
257093ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
25716b2f763fSJeff Roberson 	if (ts->ts_flags & TSF_BOUND)
2572c95d2db2SJeff Roberson 		sched_unbind(td);
25730f7a0ebdSMatthew D Fleming 	KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2574ad1e7d28SJulian Elischer 	ts->ts_flags |= TSF_BOUND;
25756b2f763fSJeff Roberson 	sched_pin();
257680f86c9fSJeff Roberson 	if (PCPU_GET(cpuid) == cpu)
25779bacd788SJeff Roberson 		return;
25786b2f763fSJeff Roberson 	ts->ts_cpu = cpu;
25799bacd788SJeff Roberson 	/* When we return from mi_switch we'll be on the correct cpu. */
2580279f949eSPoul-Henning Kamp 	mi_switch(SW_VOL, NULL);
25819bacd788SJeff Roberson }
25829bacd788SJeff Roberson 
2583ae7a6b38SJeff Roberson /*
2584ae7a6b38SJeff Roberson  * Release a bound thread.
2585ae7a6b38SJeff Roberson  */
25869bacd788SJeff Roberson void
25879bacd788SJeff Roberson sched_unbind(struct thread *td)
25889bacd788SJeff Roberson {
2589e7d50326SJeff Roberson 	struct td_sched *ts;
2590e7d50326SJeff Roberson 
25917b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
25921d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
259393ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
25946b2f763fSJeff Roberson 	if ((ts->ts_flags & TSF_BOUND) == 0)
25956b2f763fSJeff Roberson 		return;
2596e7d50326SJeff Roberson 	ts->ts_flags &= ~TSF_BOUND;
2597e7d50326SJeff Roberson 	sched_unpin();
25989bacd788SJeff Roberson }
25999bacd788SJeff Roberson 
260035e6168fSJeff Roberson int
2601ebccf1e3SJoseph Koshy sched_is_bound(struct thread *td)
2602ebccf1e3SJoseph Koshy {
26037b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
260493ccd6bfSKonstantin Belousov 	return (td_get_sched(td)->ts_flags & TSF_BOUND);
2605ebccf1e3SJoseph Koshy }
2606ebccf1e3SJoseph Koshy 
2607ae7a6b38SJeff Roberson /*
2608ae7a6b38SJeff Roberson  * Basic yield call.
2609ae7a6b38SJeff Roberson  */
261036ec198bSDavid Xu void
261136ec198bSDavid Xu sched_relinquish(struct thread *td)
261236ec198bSDavid Xu {
26137b20fb19SJeff Roberson 	thread_lock(td);
26148df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
26157b20fb19SJeff Roberson 	thread_unlock(td);
261636ec198bSDavid Xu }
261736ec198bSDavid Xu 
2618ae7a6b38SJeff Roberson /*
2619ae7a6b38SJeff Roberson  * Return the total system load.
2620ae7a6b38SJeff Roberson  */
2621ebccf1e3SJoseph Koshy int
262233916c36SJeff Roberson sched_load(void)
262333916c36SJeff Roberson {
262433916c36SJeff Roberson #ifdef SMP
262533916c36SJeff Roberson 	int total;
262633916c36SJeff Roberson 	int i;
262733916c36SJeff Roberson 
262833916c36SJeff Roberson 	total = 0;
26293aa6d94eSJohn Baldwin 	CPU_FOREACH(i)
263062fa74d9SJeff Roberson 		total += TDQ_CPU(i)->tdq_sysload;
263133916c36SJeff Roberson 	return (total);
263233916c36SJeff Roberson #else
2633d2ad694cSJeff Roberson 	return (TDQ_SELF()->tdq_sysload);
263433916c36SJeff Roberson #endif
263533916c36SJeff Roberson }
263633916c36SJeff Roberson 
263733916c36SJeff Roberson int
263835e6168fSJeff Roberson sched_sizeof_proc(void)
263935e6168fSJeff Roberson {
264035e6168fSJeff Roberson 	return (sizeof(struct proc));
264135e6168fSJeff Roberson }
264235e6168fSJeff Roberson 
264335e6168fSJeff Roberson int
264435e6168fSJeff Roberson sched_sizeof_thread(void)
264535e6168fSJeff Roberson {
264635e6168fSJeff Roberson 	return (sizeof(struct thread) + sizeof(struct td_sched));
264735e6168fSJeff Roberson }
2648b41f1452SDavid Xu 
264909c8a4ccSJeff Roberson #ifdef SMP
265009c8a4ccSJeff Roberson #define	TDQ_IDLESPIN(tdq)						\
265109c8a4ccSJeff Roberson     ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
265209c8a4ccSJeff Roberson #else
265309c8a4ccSJeff Roberson #define	TDQ_IDLESPIN(tdq)	1
265409c8a4ccSJeff Roberson #endif
265509c8a4ccSJeff Roberson 
26567a5e5e2aSJeff Roberson /*
26577a5e5e2aSJeff Roberson  * The actual idle process.
26587a5e5e2aSJeff Roberson  */
26597a5e5e2aSJeff Roberson void
26607a5e5e2aSJeff Roberson sched_idletd(void *dummy)
26617a5e5e2aSJeff Roberson {
26627a5e5e2aSJeff Roberson 	struct thread *td;
2663ae7a6b38SJeff Roberson 	struct tdq *tdq;
26642c27cb3aSAlexander Motin 	int oldswitchcnt, switchcnt;
26651690c6c1SJeff Roberson 	int i;
26667a5e5e2aSJeff Roberson 
26677b55ab05SJeff Roberson 	mtx_assert(&Giant, MA_NOTOWNED);
26687a5e5e2aSJeff Roberson 	td = curthread;
2669ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2670ba96d2d8SJohn Baldwin 	THREAD_NO_SLEEPING();
26712c27cb3aSAlexander Motin 	oldswitchcnt = -1;
2672ae7a6b38SJeff Roberson 	for (;;) {
26732c27cb3aSAlexander Motin 		if (tdq->tdq_load) {
26742c27cb3aSAlexander Motin 			thread_lock(td);
26752c27cb3aSAlexander Motin 			mi_switch(SW_VOL | SWT_IDLE, NULL);
26762c27cb3aSAlexander Motin 			thread_unlock(td);
26772c27cb3aSAlexander Motin 		}
26782c27cb3aSAlexander Motin 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2679ae7a6b38SJeff Roberson #ifdef SMP
26802c27cb3aSAlexander Motin 		if (switchcnt != oldswitchcnt) {
26812c27cb3aSAlexander Motin 			oldswitchcnt = switchcnt;
26821690c6c1SJeff Roberson 			if (tdq_idled(tdq) == 0)
26831690c6c1SJeff Roberson 				continue;
26842c27cb3aSAlexander Motin 		}
26851690c6c1SJeff Roberson 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
26862fd4047fSAlexander Motin #else
26872fd4047fSAlexander Motin 		oldswitchcnt = switchcnt;
26882fd4047fSAlexander Motin #endif
26891690c6c1SJeff Roberson 		/*
26901690c6c1SJeff Roberson 		 * If we're switching very frequently, spin while checking
26911690c6c1SJeff Roberson 		 * for load rather than entering a low power state that
26927b55ab05SJeff Roberson 		 * may require an IPI.  However, don't do any busy
26937b55ab05SJeff Roberson 		 * loops while on SMT machines as this simply steals
26947b55ab05SJeff Roberson 		 * cycles from cores doing useful work.
26951690c6c1SJeff Roberson 		 */
269609c8a4ccSJeff Roberson 		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
26971690c6c1SJeff Roberson 			for (i = 0; i < sched_idlespins; i++) {
26981690c6c1SJeff Roberson 				if (tdq->tdq_load)
26991690c6c1SJeff Roberson 					break;
27001690c6c1SJeff Roberson 				cpu_spinwait();
27011690c6c1SJeff Roberson 			}
27021690c6c1SJeff Roberson 		}
27032c27cb3aSAlexander Motin 
27042c27cb3aSAlexander Motin 		/* If there was context switch during spin, restart it. */
27056c47aaaeSJeff Roberson 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
27062c27cb3aSAlexander Motin 		if (tdq->tdq_load != 0 || switchcnt != oldswitchcnt)
27072c27cb3aSAlexander Motin 			continue;
27082c27cb3aSAlexander Motin 
27092c27cb3aSAlexander Motin 		/* Run main MD idle handler. */
27109f9ad565SAlexander Motin 		tdq->tdq_cpu_idle = 1;
271179654969SAlexander Motin 		/*
271279654969SAlexander Motin 		 * Make sure that tdq_cpu_idle update is globally visible
271379654969SAlexander Motin 		 * before cpu_idle() read tdq_load.  The order is important
271479654969SAlexander Motin 		 * to avoid race with tdq_notify.
271579654969SAlexander Motin 		 */
2716e8677f38SKonstantin Belousov 		atomic_thread_fence_seq_cst();
27172c27cb3aSAlexander Motin 		cpu_idle(switchcnt * 4 > sched_idlespinthresh);
27189f9ad565SAlexander Motin 		tdq->tdq_cpu_idle = 0;
27192c27cb3aSAlexander Motin 
27202c27cb3aSAlexander Motin 		/*
27212c27cb3aSAlexander Motin 		 * Account thread-less hardware interrupts and
27222c27cb3aSAlexander Motin 		 * other wakeup reasons equal to context switches.
27232c27cb3aSAlexander Motin 		 */
27242c27cb3aSAlexander Motin 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
27252c27cb3aSAlexander Motin 		if (switchcnt != oldswitchcnt)
27262c27cb3aSAlexander Motin 			continue;
27272c27cb3aSAlexander Motin 		tdq->tdq_switchcnt++;
27282c27cb3aSAlexander Motin 		oldswitchcnt++;
2729ae7a6b38SJeff Roberson 	}
2730b41f1452SDavid Xu }
2731e7d50326SJeff Roberson 
27327b20fb19SJeff Roberson /*
27337b20fb19SJeff Roberson  * A CPU is entering for the first time or a thread is exiting.
27347b20fb19SJeff Roberson  */
27357b20fb19SJeff Roberson void
27367b20fb19SJeff Roberson sched_throw(struct thread *td)
27377b20fb19SJeff Roberson {
273859c68134SJeff Roberson 	struct thread *newtd;
2739ae7a6b38SJeff Roberson 	struct tdq *tdq;
2740ae7a6b38SJeff Roberson 
2741ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
27427b20fb19SJeff Roberson 	if (td == NULL) {
2743ae7a6b38SJeff Roberson 		/* Correct spinlock nesting and acquire the correct lock. */
2744ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
27457b20fb19SJeff Roberson 		spinlock_exit();
27467e3a96eaSJohn Baldwin 		PCPU_SET(switchtime, cpu_ticks());
27477e3a96eaSJohn Baldwin 		PCPU_SET(switchticks, ticks);
27487b20fb19SJeff Roberson 	} else {
2749ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
27509727e637SJeff Roberson 		tdq_load_rem(tdq, td);
2751eea4f254SJeff Roberson 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
275292de34dfSJohn Baldwin 		td->td_lastcpu = td->td_oncpu;
275392de34dfSJohn Baldwin 		td->td_oncpu = NOCPU;
27547b20fb19SJeff Roberson 	}
27557b20fb19SJeff Roberson 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
275659c68134SJeff Roberson 	newtd = choosethread();
275759c68134SJeff Roberson 	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
275859c68134SJeff Roberson 	cpu_throw(td, newtd);		/* doesn't return */
27597b20fb19SJeff Roberson }
27607b20fb19SJeff Roberson 
2761ae7a6b38SJeff Roberson /*
2762ae7a6b38SJeff Roberson  * This is called from fork_exit().  Just acquire the correct locks and
2763ae7a6b38SJeff Roberson  * let fork do the rest of the work.
2764ae7a6b38SJeff Roberson  */
27657b20fb19SJeff Roberson void
2766fe54587fSJeff Roberson sched_fork_exit(struct thread *td)
27677b20fb19SJeff Roberson {
2768ae7a6b38SJeff Roberson 	struct tdq *tdq;
2769ae7a6b38SJeff Roberson 	int cpuid;
27707b20fb19SJeff Roberson 
27717b20fb19SJeff Roberson 	/*
27727b20fb19SJeff Roberson 	 * Finish setting up thread glue so that it begins execution in a
2773ae7a6b38SJeff Roberson 	 * non-nested critical section with the scheduler lock held.
27747b20fb19SJeff Roberson 	 */
2775ae7a6b38SJeff Roberson 	cpuid = PCPU_GET(cpuid);
2776ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpuid);
2777ae7a6b38SJeff Roberson 	if (TD_IS_IDLETHREAD(td))
2778ae7a6b38SJeff Roberson 		td->td_lock = TDQ_LOCKPTR(tdq);
2779ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2780ae7a6b38SJeff Roberson 	td->td_oncpu = cpuid;
278159c68134SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2782eea4f254SJeff Roberson 	lock_profile_obtain_lock_success(
2783eea4f254SJeff Roberson 	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
278428ef18b8SAndriy Gapon 
278528ef18b8SAndriy Gapon 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
278628ef18b8SAndriy Gapon 	    "prio:%d", td->td_priority);
278728ef18b8SAndriy Gapon 	SDT_PROBE0(sched, , , on__cpu);
27887b20fb19SJeff Roberson }
27897b20fb19SJeff Roberson 
27908f51ad55SJeff Roberson /*
27918f51ad55SJeff Roberson  * Create on first use to catch odd startup conditons.
27928f51ad55SJeff Roberson  */
27938f51ad55SJeff Roberson char *
27948f51ad55SJeff Roberson sched_tdname(struct thread *td)
27958f51ad55SJeff Roberson {
27968f51ad55SJeff Roberson #ifdef KTR
27978f51ad55SJeff Roberson 	struct td_sched *ts;
27988f51ad55SJeff Roberson 
279993ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
28008f51ad55SJeff Roberson 	if (ts->ts_name[0] == '\0')
28018f51ad55SJeff Roberson 		snprintf(ts->ts_name, sizeof(ts->ts_name),
28028f51ad55SJeff Roberson 		    "%s tid %d", td->td_name, td->td_tid);
28038f51ad55SJeff Roberson 	return (ts->ts_name);
28048f51ad55SJeff Roberson #else
28058f51ad55SJeff Roberson 	return (td->td_name);
28068f51ad55SJeff Roberson #endif
28078f51ad55SJeff Roberson }
28088f51ad55SJeff Roberson 
280944ad5475SJohn Baldwin #ifdef KTR
281044ad5475SJohn Baldwin void
281144ad5475SJohn Baldwin sched_clear_tdname(struct thread *td)
281244ad5475SJohn Baldwin {
281344ad5475SJohn Baldwin 	struct td_sched *ts;
281444ad5475SJohn Baldwin 
281593ccd6bfSKonstantin Belousov 	ts = td_get_sched(td);
281644ad5475SJohn Baldwin 	ts->ts_name[0] = '\0';
281744ad5475SJohn Baldwin }
281844ad5475SJohn Baldwin #endif
281944ad5475SJohn Baldwin 
282007095abfSIvan Voras #ifdef SMP
282107095abfSIvan Voras 
282207095abfSIvan Voras /*
282307095abfSIvan Voras  * Build the CPU topology dump string. Is recursively called to collect
282407095abfSIvan Voras  * the topology tree.
282507095abfSIvan Voras  */
282607095abfSIvan Voras static int
282707095abfSIvan Voras sysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
282807095abfSIvan Voras     int indent)
282907095abfSIvan Voras {
283071a19bdcSAttilio Rao 	char cpusetbuf[CPUSETBUFSIZ];
283107095abfSIvan Voras 	int i, first;
283207095abfSIvan Voras 
283307095abfSIvan Voras 	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
283419b8a6dbSAndriy Gapon 	    "", 1 + indent / 2, cg->cg_level);
283571a19bdcSAttilio Rao 	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
283671a19bdcSAttilio Rao 	    cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
283707095abfSIvan Voras 	first = TRUE;
283807095abfSIvan Voras 	for (i = 0; i < MAXCPU; i++) {
283971a19bdcSAttilio Rao 		if (CPU_ISSET(i, &cg->cg_mask)) {
284007095abfSIvan Voras 			if (!first)
284107095abfSIvan Voras 				sbuf_printf(sb, ", ");
284207095abfSIvan Voras 			else
284307095abfSIvan Voras 				first = FALSE;
284407095abfSIvan Voras 			sbuf_printf(sb, "%d", i);
284507095abfSIvan Voras 		}
284607095abfSIvan Voras 	}
284707095abfSIvan Voras 	sbuf_printf(sb, "</cpu>\n");
284807095abfSIvan Voras 
284907095abfSIvan Voras 	if (cg->cg_flags != 0) {
2850611daf7eSIvan Voras 		sbuf_printf(sb, "%*s <flags>", indent, "");
285107095abfSIvan Voras 		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
28525368befbSIvan Voras 			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
2853a401f2d0SIvan Voras 		if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
2854a401f2d0SIvan Voras 			sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
28557b55ab05SJeff Roberson 		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
2856a401f2d0SIvan Voras 			sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
285707095abfSIvan Voras 		sbuf_printf(sb, "</flags>\n");
2858611daf7eSIvan Voras 	}
285907095abfSIvan Voras 
286007095abfSIvan Voras 	if (cg->cg_children > 0) {
286107095abfSIvan Voras 		sbuf_printf(sb, "%*s <children>\n", indent, "");
286207095abfSIvan Voras 		for (i = 0; i < cg->cg_children; i++)
286307095abfSIvan Voras 			sysctl_kern_sched_topology_spec_internal(sb,
286407095abfSIvan Voras 			    &cg->cg_child[i], indent+2);
286507095abfSIvan Voras 		sbuf_printf(sb, "%*s </children>\n", indent, "");
286607095abfSIvan Voras 	}
286707095abfSIvan Voras 	sbuf_printf(sb, "%*s</group>\n", indent, "");
286807095abfSIvan Voras 	return (0);
286907095abfSIvan Voras }
287007095abfSIvan Voras 
287107095abfSIvan Voras /*
287207095abfSIvan Voras  * Sysctl handler for retrieving topology dump. It's a wrapper for
287307095abfSIvan Voras  * the recursive sysctl_kern_smp_topology_spec_internal().
287407095abfSIvan Voras  */
287507095abfSIvan Voras static int
287607095abfSIvan Voras sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
287707095abfSIvan Voras {
287807095abfSIvan Voras 	struct sbuf *topo;
287907095abfSIvan Voras 	int err;
288007095abfSIvan Voras 
288107095abfSIvan Voras 	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
288207095abfSIvan Voras 
2883b97fa22cSIan Lepore 	topo = sbuf_new_for_sysctl(NULL, NULL, 512, req);
288407095abfSIvan Voras 	if (topo == NULL)
288507095abfSIvan Voras 		return (ENOMEM);
288607095abfSIvan Voras 
288707095abfSIvan Voras 	sbuf_printf(topo, "<groups>\n");
288807095abfSIvan Voras 	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
288907095abfSIvan Voras 	sbuf_printf(topo, "</groups>\n");
289007095abfSIvan Voras 
289107095abfSIvan Voras 	if (err == 0) {
2892b97fa22cSIan Lepore 		err = sbuf_finish(topo);
289307095abfSIvan Voras 	}
289407095abfSIvan Voras 	sbuf_delete(topo);
289507095abfSIvan Voras 	return (err);
289607095abfSIvan Voras }
2897b67cc292SDavid Xu 
289807095abfSIvan Voras #endif
289907095abfSIvan Voras 
2900579895dfSAlexander Motin static int
2901579895dfSAlexander Motin sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
2902579895dfSAlexander Motin {
2903579895dfSAlexander Motin 	int error, new_val, period;
2904579895dfSAlexander Motin 
2905579895dfSAlexander Motin 	period = 1000000 / realstathz;
2906579895dfSAlexander Motin 	new_val = period * sched_slice;
2907579895dfSAlexander Motin 	error = sysctl_handle_int(oidp, &new_val, 0, req);
2908579895dfSAlexander Motin 	if (error != 0 || req->newptr == NULL)
2909579895dfSAlexander Motin 		return (error);
2910579895dfSAlexander Motin 	if (new_val <= 0)
2911579895dfSAlexander Motin 		return (EINVAL);
291237f4e025SAlexander Motin 	sched_slice = imax(1, (new_val + period / 2) / period);
29135e5c3873SJeff Roberson 	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
291437f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
291537f4e025SAlexander Motin 	    realstathz);
2916579895dfSAlexander Motin 	return (0);
2917579895dfSAlexander Motin }
2918579895dfSAlexander Motin 
29199727e637SJeff Roberson SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2920ae7a6b38SJeff Roberson SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2921e7d50326SJeff Roberson     "Scheduler name");
2922579895dfSAlexander Motin SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
2923579895dfSAlexander Motin     NULL, 0, sysctl_kern_quantum, "I",
292437f4e025SAlexander Motin     "Quantum for timeshare threads in microseconds");
2925ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
292637f4e025SAlexander Motin     "Quantum for timeshare threads in stathz ticks");
2927ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2928ae7a6b38SJeff Roberson     "Interactivity score threshold");
292937f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW,
293037f4e025SAlexander Motin     &preempt_thresh, 0,
293137f4e025SAlexander Motin     "Maximal (lowest) priority for preemption");
293237f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost, 0,
293337f4e025SAlexander Motin     "Assign static kernel priorities to sleeping threads");
293437f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins, 0,
293537f4e025SAlexander Motin     "Number of times idle thread will spin waiting for new work");
293637f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW,
293737f4e025SAlexander Motin     &sched_idlespinthresh, 0,
293837f4e025SAlexander Motin     "Threshold before we will permit idle thread spinning");
29397b8bfa0dSJeff Roberson #ifdef SMP
2940ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2941ae7a6b38SJeff Roberson     "Number of hz ticks to keep thread affinity for");
2942ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2943ae7a6b38SJeff Roberson     "Enables the long-term load balancer");
29447fcf154aSJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
29457fcf154aSJeff Roberson     &balance_interval, 0,
2946579895dfSAlexander Motin     "Average period in stathz ticks to run the long-term balancer");
2947ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2948ae7a6b38SJeff Roberson     "Attempts to steal work from other cores before idling");
294928994a58SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
295037f4e025SAlexander Motin     "Minimum load on remote CPU before we'll steal");
295107095abfSIvan Voras SYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
2952c69a1a50SMateusz Guzik     CTLFLAG_MPSAFE | CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
295307095abfSIvan Voras     "XML dump of detected CPU topology");
29547b8bfa0dSJeff Roberson #endif
2955e7d50326SJeff Roberson 
295654b0e65fSJeff Roberson /* ps compat.  All cpu percentages from ULE are weighted. */
2957a5423ea3SJeff Roberson static int ccpu = 0;
2958e7d50326SJeff Roberson SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2959