xref: /freebsd/sys/kern/sched_ule.c (revision 0567b6cc16673727a15578ef6e69e163e55a11eb)
135e6168fSJeff Roberson /*-
2e7d50326SJeff Roberson  * Copyright (c) 2002-2007, Jeffrey Roberson <jeff@freebsd.org>
335e6168fSJeff Roberson  * All rights reserved.
435e6168fSJeff Roberson  *
535e6168fSJeff Roberson  * Redistribution and use in source and binary forms, with or without
635e6168fSJeff Roberson  * modification, are permitted provided that the following conditions
735e6168fSJeff Roberson  * are met:
835e6168fSJeff Roberson  * 1. Redistributions of source code must retain the above copyright
935e6168fSJeff Roberson  *    notice unmodified, this list of conditions, and the following
1035e6168fSJeff Roberson  *    disclaimer.
1135e6168fSJeff Roberson  * 2. Redistributions in binary form must reproduce the above copyright
1235e6168fSJeff Roberson  *    notice, this list of conditions and the following disclaimer in the
1335e6168fSJeff Roberson  *    documentation and/or other materials provided with the distribution.
1435e6168fSJeff Roberson  *
1535e6168fSJeff Roberson  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
1635e6168fSJeff Roberson  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
1735e6168fSJeff Roberson  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
1835e6168fSJeff Roberson  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
1935e6168fSJeff Roberson  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
2035e6168fSJeff Roberson  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2135e6168fSJeff Roberson  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2235e6168fSJeff Roberson  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2335e6168fSJeff Roberson  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
2435e6168fSJeff Roberson  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2535e6168fSJeff Roberson  */
2635e6168fSJeff Roberson 
27ae7a6b38SJeff Roberson /*
28ae7a6b38SJeff Roberson  * This file implements the ULE scheduler.  ULE supports independent CPU
29ae7a6b38SJeff Roberson  * run queues and fine grain locking.  It has superior interactive
30ae7a6b38SJeff Roberson  * performance under load even on uni-processor systems.
31ae7a6b38SJeff Roberson  *
32ae7a6b38SJeff Roberson  * etymology:
33a5423ea3SJeff Roberson  *   ULE is the last three letters in schedule.  It owes its name to a
34ae7a6b38SJeff Roberson  * generic user created for a scheduling system by Paul Mikesell at
35ae7a6b38SJeff Roberson  * Isilon Systems and a general lack of creativity on the part of the author.
36ae7a6b38SJeff Roberson  */
37ae7a6b38SJeff Roberson 
38677b542eSDavid E. O'Brien #include <sys/cdefs.h>
39113dda8aSJeff Roberson __FBSDID("$FreeBSD$");
40677b542eSDavid E. O'Brien 
414da0d332SPeter Wemm #include "opt_hwpmc_hooks.h"
424da0d332SPeter Wemm #include "opt_sched.h"
439923b511SScott Long 
4435e6168fSJeff Roberson #include <sys/param.h>
4535e6168fSJeff Roberson #include <sys/systm.h>
462c3490b1SMarcel Moolenaar #include <sys/kdb.h>
4735e6168fSJeff Roberson #include <sys/kernel.h>
4835e6168fSJeff Roberson #include <sys/ktr.h>
49c149e542SAttilio Rao #include <sys/limits.h>
5035e6168fSJeff Roberson #include <sys/lock.h>
5135e6168fSJeff Roberson #include <sys/mutex.h>
5235e6168fSJeff Roberson #include <sys/proc.h>
53245f3abfSJeff Roberson #include <sys/resource.h>
549bacd788SJeff Roberson #include <sys/resourcevar.h>
5535e6168fSJeff Roberson #include <sys/sched.h>
56b3e9e682SRyan Stone #include <sys/sdt.h>
5735e6168fSJeff Roberson #include <sys/smp.h>
5835e6168fSJeff Roberson #include <sys/sx.h>
5935e6168fSJeff Roberson #include <sys/sysctl.h>
6035e6168fSJeff Roberson #include <sys/sysproto.h>
61f5c157d9SJohn Baldwin #include <sys/turnstile.h>
623db720fdSDavid Xu #include <sys/umtx.h>
6335e6168fSJeff Roberson #include <sys/vmmeter.h>
6462fa74d9SJeff Roberson #include <sys/cpuset.h>
6507095abfSIvan Voras #include <sys/sbuf.h>
6635e6168fSJeff Roberson 
67ebccf1e3SJoseph Koshy #ifdef HWPMC_HOOKS
68ebccf1e3SJoseph Koshy #include <sys/pmckern.h>
69ebccf1e3SJoseph Koshy #endif
70ebccf1e3SJoseph Koshy 
716f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
726f5f25e5SJohn Birrell #include <sys/dtrace_bsd.h>
736f5f25e5SJohn Birrell int				dtrace_vtime_active;
746f5f25e5SJohn Birrell dtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
756f5f25e5SJohn Birrell #endif
766f5f25e5SJohn Birrell 
7735e6168fSJeff Roberson #include <machine/cpu.h>
7822bf7d9aSJeff Roberson #include <machine/smp.h>
7935e6168fSJeff Roberson 
80ae7a6b38SJeff Roberson #define	KTR_ULE	0
8114618990SJeff Roberson 
820d2cf837SJeff Roberson #define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
830d2cf837SJeff Roberson #define	TDQ_NAME_LEN	(sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
846338c579SAttilio Rao #define	TDQ_LOADNAME_LEN	(sizeof("CPU ") + sizeof(__XSTRING(MAXCPU)) - 1 + sizeof(" load"))
858f51ad55SJeff Roberson 
866b2f763fSJeff Roberson /*
87ae7a6b38SJeff Roberson  * Thread scheduler specific section.  All fields are protected
88ae7a6b38SJeff Roberson  * by the thread lock.
89ed062c8dSJulian Elischer  */
90ad1e7d28SJulian Elischer struct td_sched {
91ae7a6b38SJeff Roberson 	struct runq	*ts_runq;	/* Run-queue we're queued on. */
92ae7a6b38SJeff Roberson 	short		ts_flags;	/* TSF_* flags. */
93e77f9fedSAdrian Chadd 	int		ts_cpu;		/* CPU that we have affinity for. */
9473daf66fSJeff Roberson 	int		ts_rltick;	/* Real last tick, for affinity. */
95ae7a6b38SJeff Roberson 	int		ts_slice;	/* Ticks of slice remaining. */
96ae7a6b38SJeff Roberson 	u_int		ts_slptime;	/* Number of ticks we vol. slept */
97ae7a6b38SJeff Roberson 	u_int		ts_runtime;	/* Number of ticks we were running */
98ad1e7d28SJulian Elischer 	int		ts_ltick;	/* Last tick that we were running on */
99ad1e7d28SJulian Elischer 	int		ts_ftick;	/* First tick that we were running on */
100ad1e7d28SJulian Elischer 	int		ts_ticks;	/* Tick count */
1018f51ad55SJeff Roberson #ifdef KTR
1028f51ad55SJeff Roberson 	char		ts_name[TS_NAME_LEN];
1038f51ad55SJeff Roberson #endif
104ed062c8dSJulian Elischer };
105ad1e7d28SJulian Elischer /* flags kept in ts_flags */
1067b8bfa0dSJeff Roberson #define	TSF_BOUND	0x0001		/* Thread can not migrate. */
1077b8bfa0dSJeff Roberson #define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
10835e6168fSJeff Roberson 
109ad1e7d28SJulian Elischer static struct td_sched td_sched0;
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 
11535e6168fSJeff Roberson /*
11612d56c0fSJohn Baldwin  * Priority ranges used for interactive and non-interactive timeshare
1172dc29adbSJohn Baldwin  * threads.  The timeshare priorities are split up into four ranges.
1182dc29adbSJohn Baldwin  * The first range handles interactive threads.  The last three ranges
1192dc29adbSJohn Baldwin  * (NHALF, x, and NHALF) handle non-interactive threads with the outer
1202dc29adbSJohn Baldwin  * ranges supporting nice values.
12112d56c0fSJohn Baldwin  */
1222dc29adbSJohn Baldwin #define	PRI_TIMESHARE_RANGE	(PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
1232dc29adbSJohn Baldwin #define	PRI_INTERACT_RANGE	((PRI_TIMESHARE_RANGE - SCHED_PRI_NRESV) / 2)
12416705791SAndriy Gapon #define	PRI_BATCH_RANGE		(PRI_TIMESHARE_RANGE - PRI_INTERACT_RANGE)
1252dc29adbSJohn Baldwin 
1262dc29adbSJohn Baldwin #define	PRI_MIN_INTERACT	PRI_MIN_TIMESHARE
1272dc29adbSJohn Baldwin #define	PRI_MAX_INTERACT	(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE - 1)
1282dc29adbSJohn Baldwin #define	PRI_MIN_BATCH		(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE)
12912d56c0fSJohn Baldwin #define	PRI_MAX_BATCH		PRI_MAX_TIMESHARE
13012d56c0fSJohn Baldwin 
13112d56c0fSJohn Baldwin /*
132e7d50326SJeff Roberson  * Cpu percentage computation macros and defines.
133e1f89c22SJeff Roberson  *
134e7d50326SJeff Roberson  * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
135e7d50326SJeff Roberson  * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
1368ab80cf0SJeff Roberson  * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
137e7d50326SJeff Roberson  * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
138e7d50326SJeff Roberson  * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
139e7d50326SJeff Roberson  * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
14035e6168fSJeff Roberson  */
141e7d50326SJeff Roberson #define	SCHED_TICK_SECS		10
142e7d50326SJeff Roberson #define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
1438ab80cf0SJeff Roberson #define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
144e7d50326SJeff Roberson #define	SCHED_TICK_SHIFT	10
145e7d50326SJeff Roberson #define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
146eddb4efaSJeff Roberson #define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
14735e6168fSJeff Roberson 
14835e6168fSJeff Roberson /*
149e7d50326SJeff Roberson  * These macros determine priorities for non-interactive threads.  They are
150e7d50326SJeff Roberson  * assigned a priority based on their recent cpu utilization as expressed
151e7d50326SJeff Roberson  * by the ratio of ticks to the tick total.  NHALF priorities at the start
152e7d50326SJeff Roberson  * and end of the MIN to MAX timeshare range are only reachable with negative
153e7d50326SJeff Roberson  * or positive nice respectively.
154e7d50326SJeff Roberson  *
155e7d50326SJeff Roberson  * PRI_RANGE:	Priority range for utilization dependent priorities.
156e7d50326SJeff Roberson  * PRI_NRESV:	Number of nice values.
157e7d50326SJeff Roberson  * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
158e7d50326SJeff Roberson  * PRI_NICE:	Determines the part of the priority inherited from nice.
159e7d50326SJeff Roberson  */
160e7d50326SJeff Roberson #define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
161e7d50326SJeff Roberson #define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
16212d56c0fSJohn Baldwin #define	SCHED_PRI_MIN		(PRI_MIN_BATCH + SCHED_PRI_NHALF)
16312d56c0fSJohn Baldwin #define	SCHED_PRI_MAX		(PRI_MAX_BATCH - SCHED_PRI_NHALF)
16478920008SJohn Baldwin #define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN + 1)
165e7d50326SJeff Roberson #define	SCHED_PRI_TICKS(ts)						\
166e7d50326SJeff Roberson     (SCHED_TICK_HZ((ts)) /						\
1671e516cf5SJeff Roberson     (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
168e7d50326SJeff Roberson #define	SCHED_PRI_NICE(nice)	(nice)
169e7d50326SJeff Roberson 
170e7d50326SJeff Roberson /*
171e7d50326SJeff Roberson  * These determine the interactivity of a process.  Interactivity differs from
172e7d50326SJeff Roberson  * cpu utilization in that it expresses the voluntary time slept vs time ran
173e7d50326SJeff Roberson  * while cpu utilization includes all time not running.  This more accurately
174e7d50326SJeff Roberson  * models the intent of the thread.
17535e6168fSJeff Roberson  *
176407b0157SJeff Roberson  * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
177407b0157SJeff Roberson  *		before throttling back.
178d322132cSJeff Roberson  * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
179210491d3SJeff Roberson  * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
1809f518f20SAttilio Rao  * INTERACT_THRESH:	Threshold for placement on the current runq.
18135e6168fSJeff Roberson  */
182e7d50326SJeff Roberson #define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
183e7d50326SJeff Roberson #define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
184210491d3SJeff Roberson #define	SCHED_INTERACT_MAX	(100)
185210491d3SJeff Roberson #define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
1864c9612c6SJeff Roberson #define	SCHED_INTERACT_THRESH	(30)
187e1f89c22SJeff Roberson 
1885e5c3873SJeff Roberson /*
1895e5c3873SJeff Roberson  * These parameters determine the slice behavior for batch work.
1905e5c3873SJeff Roberson  */
1915e5c3873SJeff Roberson #define	SCHED_SLICE_DEFAULT_DIVISOR	10	/* ~94 ms, 12 stathz ticks. */
1925e5c3873SJeff Roberson #define	SCHED_SLICE_MIN_DIVISOR		6	/* DEFAULT/MIN = ~16 ms. */
1935e5c3873SJeff Roberson 
1943d7f4117SAlexander Motin /* Flags kept in td_flags. */
1953d7f4117SAlexander Motin #define	TDF_SLICEEND	TDF_SCHED2	/* Thread time slice is over. */
1963d7f4117SAlexander Motin 
19735e6168fSJeff Roberson /*
198e7d50326SJeff Roberson  * tickincr:		Converts a stathz tick into a hz domain scaled by
199e7d50326SJeff Roberson  *			the shift factor.  Without the shift the error rate
200e7d50326SJeff Roberson  *			due to rounding would be unacceptably high.
201e7d50326SJeff Roberson  * realstathz:		stathz is sometimes 0 and run off of hz.
202e7d50326SJeff Roberson  * sched_slice:		Runtime of each thread before rescheduling.
203ae7a6b38SJeff Roberson  * preempt_thresh:	Priority threshold for preemption and remote IPIs.
20435e6168fSJeff Roberson  */
205e7d50326SJeff Roberson static int sched_interact = SCHED_INTERACT_THRESH;
206db702c59SEitan Adler static int tickincr = 8 << SCHED_TICK_SHIFT;
2075e5c3873SJeff Roberson static int realstathz = 127;	/* reset during boot. */
2085e5c3873SJeff Roberson static int sched_slice = 10;	/* reset during boot. */
2095e5c3873SJeff Roberson static int sched_slice_min = 1;	/* reset during boot. */
21002e2d6b4SJeff Roberson #ifdef PREEMPTION
21102e2d6b4SJeff Roberson #ifdef FULL_PREEMPTION
21202e2d6b4SJeff Roberson static int preempt_thresh = PRI_MAX_IDLE;
21302e2d6b4SJeff Roberson #else
214ae7a6b38SJeff Roberson static int preempt_thresh = PRI_MIN_KERN;
21502e2d6b4SJeff Roberson #endif
21602e2d6b4SJeff Roberson #else
21702e2d6b4SJeff Roberson static int preempt_thresh = 0;
21802e2d6b4SJeff Roberson #endif
21912d56c0fSJohn Baldwin static int static_boost = PRI_MIN_BATCH;
2201690c6c1SJeff Roberson static int sched_idlespins = 10000;
221b3f40a41SAlexander Motin static int sched_idlespinthresh = -1;
222ae7a6b38SJeff Roberson 
22335e6168fSJeff Roberson /*
224ae7a6b38SJeff Roberson  * tdq - per processor runqs and statistics.  All fields are protected by the
225ae7a6b38SJeff Roberson  * tdq_lock.  The load and lowpri may be accessed without to avoid excess
226ae7a6b38SJeff Roberson  * locking in sched_pickcpu();
22735e6168fSJeff Roberson  */
228ad1e7d28SJulian Elischer struct tdq {
22939f819e2SJim Harris 	/*
23039f819e2SJim Harris 	 * Ordered to improve efficiency of cpu_search() and switch().
23139f819e2SJim Harris 	 * tdq_lock is padded to avoid false sharing with tdq_load and
23239f819e2SJim Harris 	 * tdq_cpu_idle.
23339f819e2SJim Harris 	 */
2344ceaf45dSAttilio Rao 	struct mtx_padalign tdq_lock;		/* run queue lock. */
23573daf66fSJeff Roberson 	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
2361690c6c1SJeff Roberson 	volatile int	tdq_load;		/* Aggregate load. */
2379f9ad565SAlexander Motin 	volatile int	tdq_cpu_idle;		/* cpu_idle() is active. */
23873daf66fSJeff Roberson 	int		tdq_sysload;		/* For loadavg, !ITHD load. */
23973daf66fSJeff Roberson 	int		tdq_transferable;	/* Transferable thread count. */
2401690c6c1SJeff Roberson 	short		tdq_switchcnt;		/* Switches this tick. */
2411690c6c1SJeff Roberson 	short		tdq_oldswitchcnt;	/* Switches last tick. */
24273daf66fSJeff Roberson 	u_char		tdq_lowpri;		/* Lowest priority thread. */
24373daf66fSJeff Roberson 	u_char		tdq_ipipending;		/* IPI pending. */
24473daf66fSJeff Roberson 	u_char		tdq_idx;		/* Current insert index. */
24573daf66fSJeff Roberson 	u_char		tdq_ridx;		/* Current removal index. */
246e7d50326SJeff Roberson 	struct runq	tdq_realtime;		/* real-time run queue. */
247ae7a6b38SJeff Roberson 	struct runq	tdq_timeshare;		/* timeshare run queue. */
248ae7a6b38SJeff Roberson 	struct runq	tdq_idle;		/* Queue of IDLE threads. */
2498f51ad55SJeff Roberson 	char		tdq_name[TDQ_NAME_LEN];
2508f51ad55SJeff Roberson #ifdef KTR
2518f51ad55SJeff Roberson 	char		tdq_loadname[TDQ_LOADNAME_LEN];
2528f51ad55SJeff Roberson #endif
253ae7a6b38SJeff Roberson } __aligned(64);
25435e6168fSJeff Roberson 
2551690c6c1SJeff Roberson /* Idle thread states and config. */
2561690c6c1SJeff Roberson #define	TDQ_RUNNING	1
2571690c6c1SJeff Roberson #define	TDQ_IDLE	2
2587b8bfa0dSJeff Roberson 
25980f86c9fSJeff Roberson #ifdef SMP
26007095abfSIvan Voras struct cpu_group *cpu_top;		/* CPU topology */
2617b8bfa0dSJeff Roberson 
26262fa74d9SJeff Roberson #define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
26362fa74d9SJeff Roberson #define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
2647b8bfa0dSJeff Roberson 
2657b8bfa0dSJeff Roberson /*
2667b8bfa0dSJeff Roberson  * Run-time tunables.
2677b8bfa0dSJeff Roberson  */
26828994a58SJeff Roberson static int rebalance = 1;
2697fcf154aSJeff Roberson static int balance_interval = 128;	/* Default set in sched_initticks(). */
2707b8bfa0dSJeff Roberson static int affinity;
27128994a58SJeff Roberson static int steal_idle = 1;
27228994a58SJeff Roberson static int steal_thresh = 2;
27380f86c9fSJeff Roberson 
27435e6168fSJeff Roberson /*
275d2ad694cSJeff Roberson  * One thread queue per processor.
27635e6168fSJeff Roberson  */
277ad1e7d28SJulian Elischer static struct tdq	tdq_cpu[MAXCPU];
2787fcf154aSJeff Roberson static struct tdq	*balance_tdq;
2797fcf154aSJeff Roberson static int balance_ticks;
28036acfc65SAlexander Motin static DPCPU_DEFINE(uint32_t, randomval);
281dc03363dSJeff Roberson 
282ad1e7d28SJulian Elischer #define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
283ad1e7d28SJulian Elischer #define	TDQ_CPU(x)	(&tdq_cpu[(x)])
284c47f202bSJeff Roberson #define	TDQ_ID(x)	((int)((x) - tdq_cpu))
28580f86c9fSJeff Roberson #else	/* !SMP */
286ad1e7d28SJulian Elischer static struct tdq	tdq_cpu;
287dc03363dSJeff Roberson 
28836b36916SJeff Roberson #define	TDQ_ID(x)	(0)
289ad1e7d28SJulian Elischer #define	TDQ_SELF()	(&tdq_cpu)
290ad1e7d28SJulian Elischer #define	TDQ_CPU(x)	(&tdq_cpu)
2910a016a05SJeff Roberson #endif
29235e6168fSJeff Roberson 
293ae7a6b38SJeff Roberson #define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
294ae7a6b38SJeff Roberson #define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
295ae7a6b38SJeff Roberson #define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
296ae7a6b38SJeff Roberson #define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
2974ceaf45dSAttilio Rao #define	TDQ_LOCKPTR(t)		((struct mtx *)(&(t)->tdq_lock))
298ae7a6b38SJeff Roberson 
2998460a577SJohn Birrell static void sched_priority(struct thread *);
30021381d1bSJeff Roberson static void sched_thread_priority(struct thread *, u_char);
3018460a577SJohn Birrell static int sched_interact_score(struct thread *);
3028460a577SJohn Birrell static void sched_interact_update(struct thread *);
3038460a577SJohn Birrell static void sched_interact_fork(struct thread *);
3047295465eSAlexander Motin static void sched_pctcpu_update(struct td_sched *, int);
305*0567b6ccSWarner Losh static int sched_random(void);
30635e6168fSJeff Roberson 
3075d7ef00cSJeff Roberson /* Operations on per processor queues */
3089727e637SJeff Roberson static struct thread *tdq_choose(struct tdq *);
309ad1e7d28SJulian Elischer static void tdq_setup(struct tdq *);
3109727e637SJeff Roberson static void tdq_load_add(struct tdq *, struct thread *);
3119727e637SJeff Roberson static void tdq_load_rem(struct tdq *, struct thread *);
3129727e637SJeff Roberson static __inline void tdq_runq_add(struct tdq *, struct thread *, int);
3139727e637SJeff Roberson static __inline void tdq_runq_rem(struct tdq *, struct thread *);
314ff256d9cSJeff Roberson static inline int sched_shouldpreempt(int, int, int);
315ad1e7d28SJulian Elischer void tdq_print(int cpu);
316e7d50326SJeff Roberson static void runq_print(struct runq *rq);
317ae7a6b38SJeff Roberson static void tdq_add(struct tdq *, struct thread *, int);
3185d7ef00cSJeff Roberson #ifdef SMP
31962fa74d9SJeff Roberson static int tdq_move(struct tdq *, struct tdq *);
320ad1e7d28SJulian Elischer static int tdq_idled(struct tdq *);
3219727e637SJeff Roberson static void tdq_notify(struct tdq *, struct thread *);
3229727e637SJeff Roberson static struct thread *tdq_steal(struct tdq *, int);
3239727e637SJeff Roberson static struct thread *runq_steal(struct runq *, int);
3249727e637SJeff Roberson static int sched_pickcpu(struct thread *, int);
3257fcf154aSJeff Roberson static void sched_balance(void);
32662fa74d9SJeff Roberson static int sched_balance_pair(struct tdq *, struct tdq *);
3279727e637SJeff Roberson static inline struct tdq *sched_setcpu(struct thread *, int, int);
328ae7a6b38SJeff Roberson static inline void thread_unblock_switch(struct thread *, struct mtx *);
329c47f202bSJeff Roberson static struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
33007095abfSIvan Voras static int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
33107095abfSIvan Voras static int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
33207095abfSIvan Voras     struct cpu_group *cg, int indent);
3335d7ef00cSJeff Roberson #endif
3345d7ef00cSJeff Roberson 
335e7d50326SJeff Roberson static void sched_setup(void *dummy);
336237fdd78SRobert Watson SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
337e7d50326SJeff Roberson 
338e7d50326SJeff Roberson static void sched_initticks(void *dummy);
339237fdd78SRobert Watson SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
340237fdd78SRobert Watson     NULL);
341e7d50326SJeff Roberson 
342b3e9e682SRyan Stone SDT_PROVIDER_DEFINE(sched);
343b3e9e682SRyan Stone 
344d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
345b3e9e682SRyan Stone     "struct proc *", "uint8_t");
346d9fae5abSAndriy Gapon SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
347b3e9e682SRyan Stone     "struct proc *", "void *");
348d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
349b3e9e682SRyan Stone     "struct proc *", "void *", "int");
350d9fae5abSAndriy Gapon SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
351b3e9e682SRyan Stone     "struct proc *", "uint8_t", "struct thread *");
352d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
353d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
354b3e9e682SRyan Stone     "struct proc *");
355d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , on__cpu);
356d9fae5abSAndriy Gapon SDT_PROBE_DEFINE(sched, , , remain__cpu);
357d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
358b3e9e682SRyan Stone     "struct proc *");
359b3e9e682SRyan Stone 
360ae7a6b38SJeff Roberson /*
361*0567b6ccSWarner Losh  * We need some randomness. Implement the classic Linear Congruential
362*0567b6ccSWarner Losh  * generator X_{n+1}=(aX_n+c) mod m. These values are optimized for
363*0567b6ccSWarner Losh  * m = 2^32, a = 69069 and c = 5. This is signed so that we can get
364*0567b6ccSWarner Losh  * both positive and negative values from it by shifting the value
365*0567b6ccSWarner Losh  * right.
366*0567b6ccSWarner Losh  */
367*0567b6ccSWarner Losh static int sched_random()
368*0567b6ccSWarner Losh {
369*0567b6ccSWarner Losh         int rnd, *rndptr;
370*0567b6ccSWarner Losh         rndptr = DPCPU_PTR(randomval);
371*0567b6ccSWarner Losh         rnd = *rndptr * 69069 + 5;
372*0567b6ccSWarner Losh         *rndptr = rnd;
373*0567b6ccSWarner Losh         return(rnd);
374*0567b6ccSWarner Losh }
375*0567b6ccSWarner Losh 
376*0567b6ccSWarner Losh /*
377ae7a6b38SJeff Roberson  * Print the threads waiting on a run-queue.
378ae7a6b38SJeff Roberson  */
379e7d50326SJeff Roberson static void
380e7d50326SJeff Roberson runq_print(struct runq *rq)
381e7d50326SJeff Roberson {
382e7d50326SJeff Roberson 	struct rqhead *rqh;
3839727e637SJeff Roberson 	struct thread *td;
384e7d50326SJeff Roberson 	int pri;
385e7d50326SJeff Roberson 	int j;
386e7d50326SJeff Roberson 	int i;
387e7d50326SJeff Roberson 
388e7d50326SJeff Roberson 	for (i = 0; i < RQB_LEN; i++) {
389e7d50326SJeff Roberson 		printf("\t\trunq bits %d 0x%zx\n",
390e7d50326SJeff Roberson 		    i, rq->rq_status.rqb_bits[i]);
391e7d50326SJeff Roberson 		for (j = 0; j < RQB_BPW; j++)
392e7d50326SJeff Roberson 			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
393e7d50326SJeff Roberson 				pri = j + (i << RQB_L2BPW);
394e7d50326SJeff Roberson 				rqh = &rq->rq_queues[pri];
3959727e637SJeff Roberson 				TAILQ_FOREACH(td, rqh, td_runq) {
396e7d50326SJeff Roberson 					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
3979727e637SJeff Roberson 					    td, td->td_name, td->td_priority,
3989727e637SJeff Roberson 					    td->td_rqindex, pri);
399e7d50326SJeff Roberson 				}
400e7d50326SJeff Roberson 			}
401e7d50326SJeff Roberson 	}
402e7d50326SJeff Roberson }
403e7d50326SJeff Roberson 
404ae7a6b38SJeff Roberson /*
405ae7a6b38SJeff Roberson  * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
406ae7a6b38SJeff Roberson  */
40715dc847eSJeff Roberson void
408ad1e7d28SJulian Elischer tdq_print(int cpu)
40915dc847eSJeff Roberson {
410ad1e7d28SJulian Elischer 	struct tdq *tdq;
41115dc847eSJeff Roberson 
412ad1e7d28SJulian Elischer 	tdq = TDQ_CPU(cpu);
41315dc847eSJeff Roberson 
414c47f202bSJeff Roberson 	printf("tdq %d:\n", TDQ_ID(tdq));
41562fa74d9SJeff Roberson 	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
41662fa74d9SJeff Roberson 	printf("\tLock name:      %s\n", tdq->tdq_name);
417d2ad694cSJeff Roberson 	printf("\tload:           %d\n", tdq->tdq_load);
4181690c6c1SJeff Roberson 	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
4191690c6c1SJeff Roberson 	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
420e7d50326SJeff Roberson 	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
4213f872f85SJeff Roberson 	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
4221690c6c1SJeff Roberson 	printf("\tload transferable: %d\n", tdq->tdq_transferable);
4231690c6c1SJeff Roberson 	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
424e7d50326SJeff Roberson 	printf("\trealtime runq:\n");
425e7d50326SJeff Roberson 	runq_print(&tdq->tdq_realtime);
426e7d50326SJeff Roberson 	printf("\ttimeshare runq:\n");
427e7d50326SJeff Roberson 	runq_print(&tdq->tdq_timeshare);
428e7d50326SJeff Roberson 	printf("\tidle runq:\n");
429e7d50326SJeff Roberson 	runq_print(&tdq->tdq_idle);
43015dc847eSJeff Roberson }
43115dc847eSJeff Roberson 
432ff256d9cSJeff Roberson static inline int
433ff256d9cSJeff Roberson sched_shouldpreempt(int pri, int cpri, int remote)
434ff256d9cSJeff Roberson {
435ff256d9cSJeff Roberson 	/*
436ff256d9cSJeff Roberson 	 * If the new priority is not better than the current priority there is
437ff256d9cSJeff Roberson 	 * nothing to do.
438ff256d9cSJeff Roberson 	 */
439ff256d9cSJeff Roberson 	if (pri >= cpri)
440ff256d9cSJeff Roberson 		return (0);
441ff256d9cSJeff Roberson 	/*
442ff256d9cSJeff Roberson 	 * Always preempt idle.
443ff256d9cSJeff Roberson 	 */
444ff256d9cSJeff Roberson 	if (cpri >= PRI_MIN_IDLE)
445ff256d9cSJeff Roberson 		return (1);
446ff256d9cSJeff Roberson 	/*
447ff256d9cSJeff Roberson 	 * If preemption is disabled don't preempt others.
448ff256d9cSJeff Roberson 	 */
449ff256d9cSJeff Roberson 	if (preempt_thresh == 0)
450ff256d9cSJeff Roberson 		return (0);
451ff256d9cSJeff Roberson 	/*
452ff256d9cSJeff Roberson 	 * Preempt if we exceed the threshold.
453ff256d9cSJeff Roberson 	 */
454ff256d9cSJeff Roberson 	if (pri <= preempt_thresh)
455ff256d9cSJeff Roberson 		return (1);
456ff256d9cSJeff Roberson 	/*
45712d56c0fSJohn Baldwin 	 * If we're interactive or better and there is non-interactive
45812d56c0fSJohn Baldwin 	 * or worse running preempt only remote processors.
459ff256d9cSJeff Roberson 	 */
46012d56c0fSJohn Baldwin 	if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
461ff256d9cSJeff Roberson 		return (1);
462ff256d9cSJeff Roberson 	return (0);
463ff256d9cSJeff Roberson }
464ff256d9cSJeff Roberson 
465ae7a6b38SJeff Roberson /*
466ae7a6b38SJeff Roberson  * Add a thread to the actual run-queue.  Keeps transferable counts up to
467ae7a6b38SJeff Roberson  * date with what is actually on the run-queue.  Selects the correct
468ae7a6b38SJeff Roberson  * queue position for timeshare threads.
469ae7a6b38SJeff Roberson  */
470155b9987SJeff Roberson static __inline void
4719727e637SJeff Roberson tdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
472155b9987SJeff Roberson {
4739727e637SJeff Roberson 	struct td_sched *ts;
474c143ac21SJeff Roberson 	u_char pri;
475c143ac21SJeff Roberson 
476ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
4779727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
47873daf66fSJeff Roberson 
4799727e637SJeff Roberson 	pri = td->td_priority;
4809727e637SJeff Roberson 	ts = td->td_sched;
4819727e637SJeff Roberson 	TD_SET_RUNQ(td);
4829727e637SJeff Roberson 	if (THREAD_CAN_MIGRATE(td)) {
483d2ad694cSJeff Roberson 		tdq->tdq_transferable++;
484ad1e7d28SJulian Elischer 		ts->ts_flags |= TSF_XFERABLE;
48580f86c9fSJeff Roberson 	}
48612d56c0fSJohn Baldwin 	if (pri < PRI_MIN_BATCH) {
487c143ac21SJeff Roberson 		ts->ts_runq = &tdq->tdq_realtime;
48812d56c0fSJohn Baldwin 	} else if (pri <= PRI_MAX_BATCH) {
489c143ac21SJeff Roberson 		ts->ts_runq = &tdq->tdq_timeshare;
49012d56c0fSJohn Baldwin 		KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
491e7d50326SJeff Roberson 			("Invalid priority %d on timeshare runq", pri));
492e7d50326SJeff Roberson 		/*
493e7d50326SJeff Roberson 		 * This queue contains only priorities between MIN and MAX
494e7d50326SJeff Roberson 		 * realtime.  Use the whole queue to represent these values.
495e7d50326SJeff Roberson 		 */
496c47f202bSJeff Roberson 		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
49716705791SAndriy Gapon 			pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
498e7d50326SJeff Roberson 			pri = (pri + tdq->tdq_idx) % RQ_NQS;
4993f872f85SJeff Roberson 			/*
5003f872f85SJeff Roberson 			 * This effectively shortens the queue by one so we
5013f872f85SJeff Roberson 			 * can have a one slot difference between idx and
5023f872f85SJeff Roberson 			 * ridx while we wait for threads to drain.
5033f872f85SJeff Roberson 			 */
5043f872f85SJeff Roberson 			if (tdq->tdq_ridx != tdq->tdq_idx &&
5053f872f85SJeff Roberson 			    pri == tdq->tdq_ridx)
5064499aff6SJeff Roberson 				pri = (unsigned char)(pri - 1) % RQ_NQS;
507e7d50326SJeff Roberson 		} else
5083f872f85SJeff Roberson 			pri = tdq->tdq_ridx;
5099727e637SJeff Roberson 		runq_add_pri(ts->ts_runq, td, pri, flags);
510c143ac21SJeff Roberson 		return;
511e7d50326SJeff Roberson 	} else
51273daf66fSJeff Roberson 		ts->ts_runq = &tdq->tdq_idle;
5139727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
51473daf66fSJeff Roberson }
51573daf66fSJeff Roberson 
51673daf66fSJeff Roberson /*
517ae7a6b38SJeff Roberson  * Remove a thread from a run-queue.  This typically happens when a thread
518ae7a6b38SJeff Roberson  * is selected to run.  Running threads are not on the queue and the
519ae7a6b38SJeff Roberson  * transferable count does not reflect them.
520ae7a6b38SJeff Roberson  */
521155b9987SJeff Roberson static __inline void
5229727e637SJeff Roberson tdq_runq_rem(struct tdq *tdq, struct thread *td)
523155b9987SJeff Roberson {
5249727e637SJeff Roberson 	struct td_sched *ts;
5259727e637SJeff Roberson 
5269727e637SJeff Roberson 	ts = td->td_sched;
527ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
528ae7a6b38SJeff Roberson 	KASSERT(ts->ts_runq != NULL,
5299727e637SJeff Roberson 	    ("tdq_runq_remove: thread %p null ts_runq", td));
530ad1e7d28SJulian Elischer 	if (ts->ts_flags & TSF_XFERABLE) {
531d2ad694cSJeff Roberson 		tdq->tdq_transferable--;
532ad1e7d28SJulian Elischer 		ts->ts_flags &= ~TSF_XFERABLE;
53380f86c9fSJeff Roberson 	}
5343f872f85SJeff Roberson 	if (ts->ts_runq == &tdq->tdq_timeshare) {
5353f872f85SJeff Roberson 		if (tdq->tdq_idx != tdq->tdq_ridx)
5369727e637SJeff Roberson 			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
537e7d50326SJeff Roberson 		else
5389727e637SJeff Roberson 			runq_remove_idx(ts->ts_runq, td, NULL);
5393f872f85SJeff Roberson 	} else
5409727e637SJeff Roberson 		runq_remove(ts->ts_runq, td);
541155b9987SJeff Roberson }
542155b9987SJeff Roberson 
543ae7a6b38SJeff Roberson /*
544ae7a6b38SJeff Roberson  * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
545ae7a6b38SJeff Roberson  * for this thread to the referenced thread queue.
546ae7a6b38SJeff Roberson  */
547a8949de2SJeff Roberson static void
5489727e637SJeff Roberson tdq_load_add(struct tdq *tdq, struct thread *td)
5495d7ef00cSJeff Roberson {
550ae7a6b38SJeff Roberson 
551ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
5529727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
55303d17db7SJeff Roberson 
554d2ad694cSJeff Roberson 	tdq->tdq_load++;
5551b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
556d2ad694cSJeff Roberson 		tdq->tdq_sysload++;
5578f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
558d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
5595d7ef00cSJeff Roberson }
56015dc847eSJeff Roberson 
561ae7a6b38SJeff Roberson /*
562ae7a6b38SJeff Roberson  * Remove the load from a thread that is transitioning to a sleep state or
563ae7a6b38SJeff Roberson  * exiting.
564ae7a6b38SJeff Roberson  */
565a8949de2SJeff Roberson static void
5669727e637SJeff Roberson tdq_load_rem(struct tdq *tdq, struct thread *td)
5675d7ef00cSJeff Roberson {
568ae7a6b38SJeff Roberson 
5699727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
570ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
571ae7a6b38SJeff Roberson 	KASSERT(tdq->tdq_load != 0,
572c47f202bSJeff Roberson 	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
57303d17db7SJeff Roberson 
574d2ad694cSJeff Roberson 	tdq->tdq_load--;
5751b9d701fSAttilio Rao 	if ((td->td_flags & TDF_NOLOAD) == 0)
57603d17db7SJeff Roberson 		tdq->tdq_sysload--;
5778f51ad55SJeff Roberson 	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
578d9fae5abSAndriy Gapon 	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
57915dc847eSJeff Roberson }
58015dc847eSJeff Roberson 
581356500a3SJeff Roberson /*
5825e5c3873SJeff Roberson  * Bound timeshare latency by decreasing slice size as load increases.  We
5835e5c3873SJeff Roberson  * consider the maximum latency as the sum of the threads waiting to run
5845e5c3873SJeff Roberson  * aside from curthread and target no more than sched_slice latency but
5855e5c3873SJeff Roberson  * no less than sched_slice_min runtime.
5865e5c3873SJeff Roberson  */
5875e5c3873SJeff Roberson static inline int
5885e5c3873SJeff Roberson tdq_slice(struct tdq *tdq)
5895e5c3873SJeff Roberson {
5905e5c3873SJeff Roberson 	int load;
5915e5c3873SJeff Roberson 
5925e5c3873SJeff Roberson 	/*
5935e5c3873SJeff Roberson 	 * It is safe to use sys_load here because this is called from
5945e5c3873SJeff Roberson 	 * contexts where timeshare threads are running and so there
5955e5c3873SJeff Roberson 	 * cannot be higher priority load in the system.
5965e5c3873SJeff Roberson 	 */
5975e5c3873SJeff Roberson 	load = tdq->tdq_sysload - 1;
5985e5c3873SJeff Roberson 	if (load >= SCHED_SLICE_MIN_DIVISOR)
5995e5c3873SJeff Roberson 		return (sched_slice_min);
6005e5c3873SJeff Roberson 	if (load <= 1)
6015e5c3873SJeff Roberson 		return (sched_slice);
6025e5c3873SJeff Roberson 	return (sched_slice / load);
6035e5c3873SJeff Roberson }
6045e5c3873SJeff Roberson 
6055e5c3873SJeff Roberson /*
60662fa74d9SJeff Roberson  * Set lowpri to its exact value by searching the run-queue and
60762fa74d9SJeff Roberson  * evaluating curthread.  curthread may be passed as an optimization.
608356500a3SJeff Roberson  */
60922bf7d9aSJeff Roberson static void
61062fa74d9SJeff Roberson tdq_setlowpri(struct tdq *tdq, struct thread *ctd)
61162fa74d9SJeff Roberson {
61262fa74d9SJeff Roberson 	struct thread *td;
61362fa74d9SJeff Roberson 
61462fa74d9SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
61562fa74d9SJeff Roberson 	if (ctd == NULL)
61662fa74d9SJeff Roberson 		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
6179727e637SJeff Roberson 	td = tdq_choose(tdq);
6189727e637SJeff Roberson 	if (td == NULL || td->td_priority > ctd->td_priority)
61962fa74d9SJeff Roberson 		tdq->tdq_lowpri = ctd->td_priority;
62062fa74d9SJeff Roberson 	else
62162fa74d9SJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
62262fa74d9SJeff Roberson }
62362fa74d9SJeff Roberson 
62462fa74d9SJeff Roberson #ifdef SMP
62562fa74d9SJeff Roberson struct cpu_search {
626c76ee827SJeff Roberson 	cpuset_t cs_mask;
62736acfc65SAlexander Motin 	u_int	cs_prefer;
62836acfc65SAlexander Motin 	int	cs_pri;		/* Min priority for low. */
62936acfc65SAlexander Motin 	int	cs_limit;	/* Max load for low, min load for high. */
63036acfc65SAlexander Motin 	int	cs_cpu;
63136acfc65SAlexander Motin 	int	cs_load;
63262fa74d9SJeff Roberson };
63362fa74d9SJeff Roberson 
63462fa74d9SJeff Roberson #define	CPU_SEARCH_LOWEST	0x1
63562fa74d9SJeff Roberson #define	CPU_SEARCH_HIGHEST	0x2
63662fa74d9SJeff Roberson #define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
63762fa74d9SJeff Roberson 
638c76ee827SJeff Roberson #define	CPUSET_FOREACH(cpu, mask)				\
639c76ee827SJeff Roberson 	for ((cpu) = 0; (cpu) <= mp_maxid; (cpu)++)		\
64071a19bdcSAttilio Rao 		if (CPU_ISSET(cpu, &mask))
64162fa74d9SJeff Roberson 
6422499a5ccSKonstantin Belousov static __always_inline int cpu_search(const struct cpu_group *cg,
6432499a5ccSKonstantin Belousov     struct cpu_search *low, struct cpu_search *high, const int match);
6442499a5ccSKonstantin Belousov int __noinline cpu_search_lowest(const struct cpu_group *cg,
6452499a5ccSKonstantin Belousov     struct cpu_search *low);
6462499a5ccSKonstantin Belousov int __noinline cpu_search_highest(const struct cpu_group *cg,
64762fa74d9SJeff Roberson     struct cpu_search *high);
6482499a5ccSKonstantin Belousov int __noinline cpu_search_both(const struct cpu_group *cg,
6492499a5ccSKonstantin Belousov     struct cpu_search *low, struct cpu_search *high);
65062fa74d9SJeff Roberson 
65162fa74d9SJeff Roberson /*
65262fa74d9SJeff Roberson  * Search the tree of cpu_groups for the lowest or highest loaded cpu
65362fa74d9SJeff Roberson  * according to the match argument.  This routine actually compares the
65462fa74d9SJeff Roberson  * load on all paths through the tree and finds the least loaded cpu on
65562fa74d9SJeff Roberson  * the least loaded path, which may differ from the least loaded cpu in
65662fa74d9SJeff Roberson  * the system.  This balances work among caches and busses.
65762fa74d9SJeff Roberson  *
65862fa74d9SJeff Roberson  * This inline is instantiated in three forms below using constants for the
65962fa74d9SJeff Roberson  * match argument.  It is reduced to the minimum set for each case.  It is
66062fa74d9SJeff Roberson  * also recursive to the depth of the tree.
66162fa74d9SJeff Roberson  */
6622499a5ccSKonstantin Belousov static __always_inline int
66336acfc65SAlexander Motin cpu_search(const struct cpu_group *cg, struct cpu_search *low,
66462fa74d9SJeff Roberson     struct cpu_search *high, const int match)
66562fa74d9SJeff Roberson {
66662fa74d9SJeff Roberson 	struct cpu_search lgroup;
66762fa74d9SJeff Roberson 	struct cpu_search hgroup;
66836acfc65SAlexander Motin 	cpuset_t cpumask;
66962fa74d9SJeff Roberson 	struct cpu_group *child;
67036acfc65SAlexander Motin 	struct tdq *tdq;
671*0567b6ccSWarner Losh 	int cpu, i, hload, lload, load, total, rnd;
67262fa74d9SJeff Roberson 
67336acfc65SAlexander Motin 	total = 0;
67436acfc65SAlexander Motin 	cpumask = cg->cg_mask;
67562fa74d9SJeff Roberson 	if (match & CPU_SEARCH_LOWEST) {
67636acfc65SAlexander Motin 		lload = INT_MAX;
67762fa74d9SJeff Roberson 		lgroup = *low;
67862fa74d9SJeff Roberson 	}
67962fa74d9SJeff Roberson 	if (match & CPU_SEARCH_HIGHEST) {
68070801abeSAlexander Motin 		hload = INT_MIN;
68162fa74d9SJeff Roberson 		hgroup = *high;
68262fa74d9SJeff Roberson 	}
68336acfc65SAlexander Motin 
68436acfc65SAlexander Motin 	/* Iterate through the child CPU groups and then remaining CPUs. */
68558909b74SAlexander Motin 	for (i = cg->cg_children, cpu = mp_maxid; ; ) {
68670801abeSAlexander Motin 		if (i == 0) {
68758909b74SAlexander Motin #ifdef HAVE_INLINE_FFSL
68858909b74SAlexander Motin 			cpu = CPU_FFS(&cpumask) - 1;
68958909b74SAlexander Motin #else
69070801abeSAlexander Motin 			while (cpu >= 0 && !CPU_ISSET(cpu, &cpumask))
69170801abeSAlexander Motin 				cpu--;
69258909b74SAlexander Motin #endif
69370801abeSAlexander Motin 			if (cpu < 0)
69436acfc65SAlexander Motin 				break;
69536acfc65SAlexander Motin 			child = NULL;
69636acfc65SAlexander Motin 		} else
69770801abeSAlexander Motin 			child = &cg->cg_child[i - 1];
69836acfc65SAlexander Motin 
69970801abeSAlexander Motin 		if (match & CPU_SEARCH_LOWEST)
70070801abeSAlexander Motin 			lgroup.cs_cpu = -1;
70170801abeSAlexander Motin 		if (match & CPU_SEARCH_HIGHEST)
70270801abeSAlexander Motin 			hgroup.cs_cpu = -1;
70336acfc65SAlexander Motin 		if (child) {			/* Handle child CPU group. */
70436acfc65SAlexander Motin 			CPU_NAND(&cpumask, &child->cg_mask);
70562fa74d9SJeff Roberson 			switch (match) {
70662fa74d9SJeff Roberson 			case CPU_SEARCH_LOWEST:
70762fa74d9SJeff Roberson 				load = cpu_search_lowest(child, &lgroup);
70862fa74d9SJeff Roberson 				break;
70962fa74d9SJeff Roberson 			case CPU_SEARCH_HIGHEST:
71062fa74d9SJeff Roberson 				load = cpu_search_highest(child, &hgroup);
71162fa74d9SJeff Roberson 				break;
71262fa74d9SJeff Roberson 			case CPU_SEARCH_BOTH:
71362fa74d9SJeff Roberson 				load = cpu_search_both(child, &lgroup, &hgroup);
71462fa74d9SJeff Roberson 				break;
71562fa74d9SJeff Roberson 			}
71636acfc65SAlexander Motin 		} else {			/* Handle child CPU. */
71758909b74SAlexander Motin 			CPU_CLR(cpu, &cpumask);
71836acfc65SAlexander Motin 			tdq = TDQ_CPU(cpu);
71936acfc65SAlexander Motin 			load = tdq->tdq_load * 256;
720*0567b6ccSWarner Losh 			rnd = sched_random() >> 26;	/* -32 to +31 */
72136acfc65SAlexander Motin 			if (match & CPU_SEARCH_LOWEST) {
72236acfc65SAlexander Motin 				if (cpu == low->cs_prefer)
72336acfc65SAlexander Motin 					load -= 64;
72436acfc65SAlexander Motin 				/* If that CPU is allowed and get data. */
72570801abeSAlexander Motin 				if (tdq->tdq_lowpri > lgroup.cs_pri &&
72670801abeSAlexander Motin 				    tdq->tdq_load <= lgroup.cs_limit &&
72770801abeSAlexander Motin 				    CPU_ISSET(cpu, &lgroup.cs_mask)) {
72836acfc65SAlexander Motin 					lgroup.cs_cpu = cpu;
72936acfc65SAlexander Motin 					lgroup.cs_load = load - rnd;
73036acfc65SAlexander Motin 				}
73162fa74d9SJeff Roberson 			}
73262fa74d9SJeff Roberson 			if (match & CPU_SEARCH_HIGHEST)
73370801abeSAlexander Motin 				if (tdq->tdq_load >= hgroup.cs_limit &&
73470801abeSAlexander Motin 				    tdq->tdq_transferable &&
73570801abeSAlexander Motin 				    CPU_ISSET(cpu, &hgroup.cs_mask)) {
73636acfc65SAlexander Motin 					hgroup.cs_cpu = cpu;
73736acfc65SAlexander Motin 					hgroup.cs_load = load - rnd;
73862fa74d9SJeff Roberson 				}
73962fa74d9SJeff Roberson 		}
74036acfc65SAlexander Motin 		total += load;
74162fa74d9SJeff Roberson 
74236acfc65SAlexander Motin 		/* We have info about child item. Compare it. */
74336acfc65SAlexander Motin 		if (match & CPU_SEARCH_LOWEST) {
74470801abeSAlexander Motin 			if (lgroup.cs_cpu >= 0 &&
7456022f0bcSAlexander Motin 			    (load < lload ||
7466022f0bcSAlexander Motin 			     (load == lload && lgroup.cs_load < low->cs_load))) {
74736acfc65SAlexander Motin 				lload = load;
74836acfc65SAlexander Motin 				low->cs_cpu = lgroup.cs_cpu;
74936acfc65SAlexander Motin 				low->cs_load = lgroup.cs_load;
75036acfc65SAlexander Motin 			}
75136acfc65SAlexander Motin 		}
75236acfc65SAlexander Motin 		if (match & CPU_SEARCH_HIGHEST)
75370801abeSAlexander Motin 			if (hgroup.cs_cpu >= 0 &&
7546022f0bcSAlexander Motin 			    (load > hload ||
7556022f0bcSAlexander Motin 			     (load == hload && hgroup.cs_load > high->cs_load))) {
75636acfc65SAlexander Motin 				hload = load;
75736acfc65SAlexander Motin 				high->cs_cpu = hgroup.cs_cpu;
75836acfc65SAlexander Motin 				high->cs_load = hgroup.cs_load;
75936acfc65SAlexander Motin 			}
76070801abeSAlexander Motin 		if (child) {
76170801abeSAlexander Motin 			i--;
76270801abeSAlexander Motin 			if (i == 0 && CPU_EMPTY(&cpumask))
76370801abeSAlexander Motin 				break;
76458909b74SAlexander Motin 		}
76558909b74SAlexander Motin #ifndef HAVE_INLINE_FFSL
76658909b74SAlexander Motin 		else
76770801abeSAlexander Motin 			cpu--;
76858909b74SAlexander Motin #endif
76962fa74d9SJeff Roberson 	}
77062fa74d9SJeff Roberson 	return (total);
77162fa74d9SJeff Roberson }
77262fa74d9SJeff Roberson 
77362fa74d9SJeff Roberson /*
77462fa74d9SJeff Roberson  * cpu_search instantiations must pass constants to maintain the inline
77562fa74d9SJeff Roberson  * optimization.
77662fa74d9SJeff Roberson  */
77762fa74d9SJeff Roberson int
77836acfc65SAlexander Motin cpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low)
77962fa74d9SJeff Roberson {
78062fa74d9SJeff Roberson 	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
78162fa74d9SJeff Roberson }
78262fa74d9SJeff Roberson 
78362fa74d9SJeff Roberson int
78436acfc65SAlexander Motin cpu_search_highest(const struct cpu_group *cg, struct cpu_search *high)
78562fa74d9SJeff Roberson {
78662fa74d9SJeff Roberson 	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
78762fa74d9SJeff Roberson }
78862fa74d9SJeff Roberson 
78962fa74d9SJeff Roberson int
79036acfc65SAlexander Motin cpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
79162fa74d9SJeff Roberson     struct cpu_search *high)
79262fa74d9SJeff Roberson {
79362fa74d9SJeff Roberson 	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
79462fa74d9SJeff Roberson }
79562fa74d9SJeff Roberson 
79662fa74d9SJeff Roberson /*
79762fa74d9SJeff Roberson  * Find the cpu with the least load via the least loaded path that has a
79862fa74d9SJeff Roberson  * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
79962fa74d9SJeff Roberson  * acceptable.
80062fa74d9SJeff Roberson  */
80162fa74d9SJeff Roberson static inline int
80236acfc65SAlexander Motin sched_lowest(const struct cpu_group *cg, cpuset_t mask, int pri, int maxload,
80336acfc65SAlexander Motin     int prefer)
80462fa74d9SJeff Roberson {
80562fa74d9SJeff Roberson 	struct cpu_search low;
80662fa74d9SJeff Roberson 
80762fa74d9SJeff Roberson 	low.cs_cpu = -1;
80836acfc65SAlexander Motin 	low.cs_prefer = prefer;
80962fa74d9SJeff Roberson 	low.cs_mask = mask;
81036acfc65SAlexander Motin 	low.cs_pri = pri;
81136acfc65SAlexander Motin 	low.cs_limit = maxload;
81262fa74d9SJeff Roberson 	cpu_search_lowest(cg, &low);
81362fa74d9SJeff Roberson 	return low.cs_cpu;
81462fa74d9SJeff Roberson }
81562fa74d9SJeff Roberson 
81662fa74d9SJeff Roberson /*
81762fa74d9SJeff Roberson  * Find the cpu with the highest load via the highest loaded path.
81862fa74d9SJeff Roberson  */
81962fa74d9SJeff Roberson static inline int
82036acfc65SAlexander Motin sched_highest(const struct cpu_group *cg, cpuset_t mask, int minload)
82162fa74d9SJeff Roberson {
82262fa74d9SJeff Roberson 	struct cpu_search high;
82362fa74d9SJeff Roberson 
82462fa74d9SJeff Roberson 	high.cs_cpu = -1;
82562fa74d9SJeff Roberson 	high.cs_mask = mask;
82662fa74d9SJeff Roberson 	high.cs_limit = minload;
82762fa74d9SJeff Roberson 	cpu_search_highest(cg, &high);
82862fa74d9SJeff Roberson 	return high.cs_cpu;
82962fa74d9SJeff Roberson }
83062fa74d9SJeff Roberson 
83162fa74d9SJeff Roberson static void
83262fa74d9SJeff Roberson sched_balance_group(struct cpu_group *cg)
83362fa74d9SJeff Roberson {
83436acfc65SAlexander Motin 	cpuset_t hmask, lmask;
83536acfc65SAlexander Motin 	int high, low, anylow;
83662fa74d9SJeff Roberson 
83736acfc65SAlexander Motin 	CPU_FILL(&hmask);
83862fa74d9SJeff Roberson 	for (;;) {
83936acfc65SAlexander Motin 		high = sched_highest(cg, hmask, 1);
84036acfc65SAlexander Motin 		/* Stop if there is no more CPU with transferrable threads. */
84136acfc65SAlexander Motin 		if (high == -1)
84262fa74d9SJeff Roberson 			break;
84336acfc65SAlexander Motin 		CPU_CLR(high, &hmask);
84436acfc65SAlexander Motin 		CPU_COPY(&hmask, &lmask);
84536acfc65SAlexander Motin 		/* Stop if there is no more CPU left for low. */
84636acfc65SAlexander Motin 		if (CPU_EMPTY(&lmask))
84762fa74d9SJeff Roberson 			break;
84836acfc65SAlexander Motin 		anylow = 1;
84936acfc65SAlexander Motin nextlow:
85036acfc65SAlexander Motin 		low = sched_lowest(cg, lmask, -1,
85136acfc65SAlexander Motin 		    TDQ_CPU(high)->tdq_load - 1, high);
85236acfc65SAlexander Motin 		/* Stop if we looked well and found no less loaded CPU. */
85336acfc65SAlexander Motin 		if (anylow && low == -1)
85436acfc65SAlexander Motin 			break;
85536acfc65SAlexander Motin 		/* Go to next high if we found no less loaded CPU. */
85636acfc65SAlexander Motin 		if (low == -1)
85736acfc65SAlexander Motin 			continue;
85836acfc65SAlexander Motin 		/* Transfer thread from high to low. */
85936acfc65SAlexander Motin 		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low))) {
86036acfc65SAlexander Motin 			/* CPU that got thread can no longer be a donor. */
86136acfc65SAlexander Motin 			CPU_CLR(low, &hmask);
86236acfc65SAlexander Motin 		} else {
86362fa74d9SJeff Roberson 			/*
86436acfc65SAlexander Motin 			 * If failed, then there is no threads on high
86536acfc65SAlexander Motin 			 * that can run on this low. Drop low from low
86636acfc65SAlexander Motin 			 * mask and look for different one.
86762fa74d9SJeff Roberson 			 */
86836acfc65SAlexander Motin 			CPU_CLR(low, &lmask);
86936acfc65SAlexander Motin 			anylow = 0;
87036acfc65SAlexander Motin 			goto nextlow;
87162fa74d9SJeff Roberson 		}
87236acfc65SAlexander Motin 	}
87362fa74d9SJeff Roberson }
87462fa74d9SJeff Roberson 
87562fa74d9SJeff Roberson static void
87662375ca8SEd Schouten sched_balance(void)
877356500a3SJeff Roberson {
8787fcf154aSJeff Roberson 	struct tdq *tdq;
879356500a3SJeff Roberson 
880ae7a6b38SJeff Roberson 	if (smp_started == 0 || rebalance == 0)
881598b368dSJeff Roberson 		return;
882*0567b6ccSWarner Losh 
883*0567b6ccSWarner Losh 	balance_ticks = max(balance_interval / 2, 1) +
884*0567b6ccSWarner Losh             ((sched_random() >> 16) % balance_interval);
8857fcf154aSJeff Roberson 	tdq = TDQ_SELF();
8867fcf154aSJeff Roberson 	TDQ_UNLOCK(tdq);
88762fa74d9SJeff Roberson 	sched_balance_group(cpu_top);
8887fcf154aSJeff Roberson 	TDQ_LOCK(tdq);
889cac77d04SJeff Roberson }
89086f8ae96SJeff Roberson 
891ae7a6b38SJeff Roberson /*
892ae7a6b38SJeff Roberson  * Lock two thread queues using their address to maintain lock order.
893ae7a6b38SJeff Roberson  */
894ae7a6b38SJeff Roberson static void
895ae7a6b38SJeff Roberson tdq_lock_pair(struct tdq *one, struct tdq *two)
896ae7a6b38SJeff Roberson {
897ae7a6b38SJeff Roberson 	if (one < two) {
898ae7a6b38SJeff Roberson 		TDQ_LOCK(one);
899ae7a6b38SJeff Roberson 		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
900ae7a6b38SJeff Roberson 	} else {
901ae7a6b38SJeff Roberson 		TDQ_LOCK(two);
902ae7a6b38SJeff Roberson 		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
903ae7a6b38SJeff Roberson 	}
904ae7a6b38SJeff Roberson }
905ae7a6b38SJeff Roberson 
906ae7a6b38SJeff Roberson /*
9077fcf154aSJeff Roberson  * Unlock two thread queues.  Order is not important here.
9087fcf154aSJeff Roberson  */
9097fcf154aSJeff Roberson static void
9107fcf154aSJeff Roberson tdq_unlock_pair(struct tdq *one, struct tdq *two)
9117fcf154aSJeff Roberson {
9127fcf154aSJeff Roberson 	TDQ_UNLOCK(one);
9137fcf154aSJeff Roberson 	TDQ_UNLOCK(two);
9147fcf154aSJeff Roberson }
9157fcf154aSJeff Roberson 
9167fcf154aSJeff Roberson /*
917ae7a6b38SJeff Roberson  * Transfer load between two imbalanced thread queues.
918ae7a6b38SJeff Roberson  */
91962fa74d9SJeff Roberson static int
920ad1e7d28SJulian Elischer sched_balance_pair(struct tdq *high, struct tdq *low)
921cac77d04SJeff Roberson {
92262fa74d9SJeff Roberson 	int moved;
923880bf8b9SMarius Strobl 	int cpu;
924cac77d04SJeff Roberson 
925ae7a6b38SJeff Roberson 	tdq_lock_pair(high, low);
92662fa74d9SJeff Roberson 	moved = 0;
927155b9987SJeff Roberson 	/*
928155b9987SJeff Roberson 	 * Determine what the imbalance is and then adjust that to how many
929d2ad694cSJeff Roberson 	 * threads we actually have to give up (transferable).
930155b9987SJeff Roberson 	 */
93136acfc65SAlexander Motin 	if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load &&
93236acfc65SAlexander Motin 	    (moved = tdq_move(high, low)) > 0) {
933a5423ea3SJeff Roberson 		/*
934880bf8b9SMarius Strobl 		 * In case the target isn't the current cpu IPI it to force a
935880bf8b9SMarius Strobl 		 * reschedule with the new workload.
936a5423ea3SJeff Roberson 		 */
937880bf8b9SMarius Strobl 		cpu = TDQ_ID(low);
938880bf8b9SMarius Strobl 		if (cpu != PCPU_GET(cpuid))
939880bf8b9SMarius Strobl 			ipi_cpu(cpu, IPI_PREEMPT);
940ae7a6b38SJeff Roberson 	}
9417fcf154aSJeff Roberson 	tdq_unlock_pair(high, low);
94262fa74d9SJeff Roberson 	return (moved);
943356500a3SJeff Roberson }
944356500a3SJeff Roberson 
945ae7a6b38SJeff Roberson /*
946ae7a6b38SJeff Roberson  * Move a thread from one thread queue to another.
947ae7a6b38SJeff Roberson  */
94862fa74d9SJeff Roberson static int
949ae7a6b38SJeff Roberson tdq_move(struct tdq *from, struct tdq *to)
950356500a3SJeff Roberson {
951ad1e7d28SJulian Elischer 	struct td_sched *ts;
952ae7a6b38SJeff Roberson 	struct thread *td;
953ae7a6b38SJeff Roberson 	struct tdq *tdq;
954ae7a6b38SJeff Roberson 	int cpu;
955356500a3SJeff Roberson 
9567fcf154aSJeff Roberson 	TDQ_LOCK_ASSERT(from, MA_OWNED);
9577fcf154aSJeff Roberson 	TDQ_LOCK_ASSERT(to, MA_OWNED);
9587fcf154aSJeff Roberson 
959ad1e7d28SJulian Elischer 	tdq = from;
960ae7a6b38SJeff Roberson 	cpu = TDQ_ID(to);
9619727e637SJeff Roberson 	td = tdq_steal(tdq, cpu);
9629727e637SJeff Roberson 	if (td == NULL)
96362fa74d9SJeff Roberson 		return (0);
9649727e637SJeff Roberson 	ts = td->td_sched;
965ae7a6b38SJeff Roberson 	/*
966ae7a6b38SJeff Roberson 	 * Although the run queue is locked the thread may be blocked.  Lock
9677fcf154aSJeff Roberson 	 * it to clear this and acquire the run-queue lock.
968ae7a6b38SJeff Roberson 	 */
969ae7a6b38SJeff Roberson 	thread_lock(td);
9707fcf154aSJeff Roberson 	/* Drop recursive lock on from acquired via thread_lock(). */
971ae7a6b38SJeff Roberson 	TDQ_UNLOCK(from);
972ae7a6b38SJeff Roberson 	sched_rem(td);
9737b8bfa0dSJeff Roberson 	ts->ts_cpu = cpu;
974ae7a6b38SJeff Roberson 	td->td_lock = TDQ_LOCKPTR(to);
975ae7a6b38SJeff Roberson 	tdq_add(to, td, SRQ_YIELDING);
97662fa74d9SJeff Roberson 	return (1);
977356500a3SJeff Roberson }
97822bf7d9aSJeff Roberson 
979ae7a6b38SJeff Roberson /*
980ae7a6b38SJeff Roberson  * This tdq has idled.  Try to steal a thread from another cpu and switch
981ae7a6b38SJeff Roberson  * to it.
982ae7a6b38SJeff Roberson  */
98380f86c9fSJeff Roberson static int
984ad1e7d28SJulian Elischer tdq_idled(struct tdq *tdq)
98522bf7d9aSJeff Roberson {
98662fa74d9SJeff Roberson 	struct cpu_group *cg;
987ad1e7d28SJulian Elischer 	struct tdq *steal;
988c76ee827SJeff Roberson 	cpuset_t mask;
98962fa74d9SJeff Roberson 	int thresh;
990ae7a6b38SJeff Roberson 	int cpu;
99180f86c9fSJeff Roberson 
99288f530ccSJeff Roberson 	if (smp_started == 0 || steal_idle == 0)
99388f530ccSJeff Roberson 		return (1);
994c76ee827SJeff Roberson 	CPU_FILL(&mask);
995c76ee827SJeff Roberson 	CPU_CLR(PCPU_GET(cpuid), &mask);
99662fa74d9SJeff Roberson 	/* We don't want to be preempted while we're iterating. */
997ae7a6b38SJeff Roberson 	spinlock_enter();
99862fa74d9SJeff Roberson 	for (cg = tdq->tdq_cg; cg != NULL; ) {
9997b55ab05SJeff Roberson 		if ((cg->cg_flags & CG_FLAG_THREAD) == 0)
100062fa74d9SJeff Roberson 			thresh = steal_thresh;
100162fa74d9SJeff Roberson 		else
100262fa74d9SJeff Roberson 			thresh = 1;
100362fa74d9SJeff Roberson 		cpu = sched_highest(cg, mask, thresh);
100462fa74d9SJeff Roberson 		if (cpu == -1) {
100562fa74d9SJeff Roberson 			cg = cg->cg_parent;
100680f86c9fSJeff Roberson 			continue;
10077b8bfa0dSJeff Roberson 		}
10087b8bfa0dSJeff Roberson 		steal = TDQ_CPU(cpu);
1009c76ee827SJeff Roberson 		CPU_CLR(cpu, &mask);
10107fcf154aSJeff Roberson 		tdq_lock_pair(tdq, steal);
101162fa74d9SJeff Roberson 		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
10127fcf154aSJeff Roberson 			tdq_unlock_pair(tdq, steal);
101362fa74d9SJeff Roberson 			continue;
101462fa74d9SJeff Roberson 		}
101562fa74d9SJeff Roberson 		/*
101662fa74d9SJeff Roberson 		 * If a thread was added while interrupts were disabled don't
101762fa74d9SJeff Roberson 		 * steal one here.  If we fail to acquire one due to affinity
101862fa74d9SJeff Roberson 		 * restrictions loop again with this cpu removed from the
101962fa74d9SJeff Roberson 		 * set.
102062fa74d9SJeff Roberson 		 */
102162fa74d9SJeff Roberson 		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
102262fa74d9SJeff Roberson 			tdq_unlock_pair(tdq, steal);
102362fa74d9SJeff Roberson 			continue;
102480f86c9fSJeff Roberson 		}
1025ae7a6b38SJeff Roberson 		spinlock_exit();
1026ae7a6b38SJeff Roberson 		TDQ_UNLOCK(steal);
10278df78c41SJeff Roberson 		mi_switch(SW_VOL | SWT_IDLE, NULL);
1028ae7a6b38SJeff Roberson 		thread_unlock(curthread);
10297b8bfa0dSJeff Roberson 
10307b8bfa0dSJeff Roberson 		return (0);
103122bf7d9aSJeff Roberson 	}
103262fa74d9SJeff Roberson 	spinlock_exit();
103362fa74d9SJeff Roberson 	return (1);
103462fa74d9SJeff Roberson }
103522bf7d9aSJeff Roberson 
1036ae7a6b38SJeff Roberson /*
1037ae7a6b38SJeff Roberson  * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
1038ae7a6b38SJeff Roberson  */
103922bf7d9aSJeff Roberson static void
10409727e637SJeff Roberson tdq_notify(struct tdq *tdq, struct thread *td)
104122bf7d9aSJeff Roberson {
104202f0ff6dSJohn Baldwin 	struct thread *ctd;
1043fc3a97dcSJeff Roberson 	int pri;
10447b8bfa0dSJeff Roberson 	int cpu;
104522bf7d9aSJeff Roberson 
1046ff256d9cSJeff Roberson 	if (tdq->tdq_ipipending)
1047ff256d9cSJeff Roberson 		return;
10489727e637SJeff Roberson 	cpu = td->td_sched->ts_cpu;
10499727e637SJeff Roberson 	pri = td->td_priority;
105002f0ff6dSJohn Baldwin 	ctd = pcpu_find(cpu)->pc_curthread;
105102f0ff6dSJohn Baldwin 	if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
10526b2f763fSJeff Roberson 		return;
105379654969SAlexander Motin 
105479654969SAlexander Motin 	/*
1055ae9e9b4fSAlexander Motin 	 * Make sure that our caller's earlier update to tdq_load is
1056ae9e9b4fSAlexander Motin 	 * globally visible before we read tdq_cpu_idle.  Idle thread
105779654969SAlexander Motin 	 * accesses both of them without locks, and the order is important.
105879654969SAlexander Motin 	 */
10597e9b58eaSAlexander Motin 	mb();
106079654969SAlexander Motin 
106102f0ff6dSJohn Baldwin 	if (TD_IS_IDLETHREAD(ctd)) {
10621690c6c1SJeff Roberson 		/*
10636c47aaaeSJeff Roberson 		 * If the MD code has an idle wakeup routine try that before
10646c47aaaeSJeff Roberson 		 * falling back to IPI.
10656c47aaaeSJeff Roberson 		 */
10669f9ad565SAlexander Motin 		if (!tdq->tdq_cpu_idle || cpu_idle_wakeup(cpu))
10676c47aaaeSJeff Roberson 			return;
10681690c6c1SJeff Roberson 	}
1069ff256d9cSJeff Roberson 	tdq->tdq_ipipending = 1;
1070d9d8d144SJohn Baldwin 	ipi_cpu(cpu, IPI_PREEMPT);
107122bf7d9aSJeff Roberson }
107222bf7d9aSJeff Roberson 
1073ae7a6b38SJeff Roberson /*
1074ae7a6b38SJeff Roberson  * Steals load from a timeshare queue.  Honors the rotating queue head
1075ae7a6b38SJeff Roberson  * index.
1076ae7a6b38SJeff Roberson  */
10779727e637SJeff Roberson static struct thread *
107862fa74d9SJeff Roberson runq_steal_from(struct runq *rq, int cpu, u_char start)
1079ae7a6b38SJeff Roberson {
1080ae7a6b38SJeff Roberson 	struct rqbits *rqb;
1081ae7a6b38SJeff Roberson 	struct rqhead *rqh;
108236acfc65SAlexander Motin 	struct thread *td, *first;
1083ae7a6b38SJeff Roberson 	int bit;
1084ae7a6b38SJeff Roberson 	int i;
1085ae7a6b38SJeff Roberson 
1086ae7a6b38SJeff Roberson 	rqb = &rq->rq_status;
1087ae7a6b38SJeff Roberson 	bit = start & (RQB_BPW -1);
108836acfc65SAlexander Motin 	first = NULL;
1089ae7a6b38SJeff Roberson again:
1090ae7a6b38SJeff Roberson 	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1091ae7a6b38SJeff Roberson 		if (rqb->rqb_bits[i] == 0)
1092ae7a6b38SJeff Roberson 			continue;
10938bc713f6SJeff Roberson 		if (bit == 0)
10948bc713f6SJeff Roberson 			bit = RQB_FFS(rqb->rqb_bits[i]);
10958bc713f6SJeff Roberson 		for (; bit < RQB_BPW; bit++) {
10968bc713f6SJeff Roberson 			if ((rqb->rqb_bits[i] & (1ul << bit)) == 0)
1097ae7a6b38SJeff Roberson 				continue;
10988bc713f6SJeff Roberson 			rqh = &rq->rq_queues[bit + (i << RQB_L2BPW)];
10999727e637SJeff Roberson 			TAILQ_FOREACH(td, rqh, td_runq) {
11009727e637SJeff Roberson 				if (first && THREAD_CAN_MIGRATE(td) &&
11019727e637SJeff Roberson 				    THREAD_CAN_SCHED(td, cpu))
11029727e637SJeff Roberson 					return (td);
110336acfc65SAlexander Motin 				first = td;
1104ae7a6b38SJeff Roberson 			}
1105ae7a6b38SJeff Roberson 		}
11068bc713f6SJeff Roberson 	}
1107ae7a6b38SJeff Roberson 	if (start != 0) {
1108ae7a6b38SJeff Roberson 		start = 0;
1109ae7a6b38SJeff Roberson 		goto again;
1110ae7a6b38SJeff Roberson 	}
1111ae7a6b38SJeff Roberson 
111236acfc65SAlexander Motin 	if (first && THREAD_CAN_MIGRATE(first) &&
111336acfc65SAlexander Motin 	    THREAD_CAN_SCHED(first, cpu))
111436acfc65SAlexander Motin 		return (first);
1115ae7a6b38SJeff Roberson 	return (NULL);
1116ae7a6b38SJeff Roberson }
1117ae7a6b38SJeff Roberson 
1118ae7a6b38SJeff Roberson /*
1119ae7a6b38SJeff Roberson  * Steals load from a standard linear queue.
1120ae7a6b38SJeff Roberson  */
11219727e637SJeff Roberson static struct thread *
112262fa74d9SJeff Roberson runq_steal(struct runq *rq, int cpu)
112322bf7d9aSJeff Roberson {
112422bf7d9aSJeff Roberson 	struct rqhead *rqh;
112522bf7d9aSJeff Roberson 	struct rqbits *rqb;
11269727e637SJeff Roberson 	struct thread *td;
112722bf7d9aSJeff Roberson 	int word;
112822bf7d9aSJeff Roberson 	int bit;
112922bf7d9aSJeff Roberson 
113022bf7d9aSJeff Roberson 	rqb = &rq->rq_status;
113122bf7d9aSJeff Roberson 	for (word = 0; word < RQB_LEN; word++) {
113222bf7d9aSJeff Roberson 		if (rqb->rqb_bits[word] == 0)
113322bf7d9aSJeff Roberson 			continue;
113422bf7d9aSJeff Roberson 		for (bit = 0; bit < RQB_BPW; bit++) {
1135a2640c9bSPeter Wemm 			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
113622bf7d9aSJeff Roberson 				continue;
113722bf7d9aSJeff Roberson 			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
11389727e637SJeff Roberson 			TAILQ_FOREACH(td, rqh, td_runq)
11399727e637SJeff Roberson 				if (THREAD_CAN_MIGRATE(td) &&
11409727e637SJeff Roberson 				    THREAD_CAN_SCHED(td, cpu))
11419727e637SJeff Roberson 					return (td);
114222bf7d9aSJeff Roberson 		}
114322bf7d9aSJeff Roberson 	}
114422bf7d9aSJeff Roberson 	return (NULL);
114522bf7d9aSJeff Roberson }
114622bf7d9aSJeff Roberson 
1147ae7a6b38SJeff Roberson /*
1148ae7a6b38SJeff Roberson  * Attempt to steal a thread in priority order from a thread queue.
1149ae7a6b38SJeff Roberson  */
11509727e637SJeff Roberson static struct thread *
115162fa74d9SJeff Roberson tdq_steal(struct tdq *tdq, int cpu)
115222bf7d9aSJeff Roberson {
11539727e637SJeff Roberson 	struct thread *td;
115422bf7d9aSJeff Roberson 
1155ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
11569727e637SJeff Roberson 	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
11579727e637SJeff Roberson 		return (td);
11589727e637SJeff Roberson 	if ((td = runq_steal_from(&tdq->tdq_timeshare,
11599727e637SJeff Roberson 	    cpu, tdq->tdq_ridx)) != NULL)
11609727e637SJeff Roberson 		return (td);
116162fa74d9SJeff Roberson 	return (runq_steal(&tdq->tdq_idle, cpu));
116222bf7d9aSJeff Roberson }
116380f86c9fSJeff Roberson 
1164ae7a6b38SJeff Roberson /*
1165ae7a6b38SJeff Roberson  * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
11667fcf154aSJeff Roberson  * current lock and returns with the assigned queue locked.
1167ae7a6b38SJeff Roberson  */
1168ae7a6b38SJeff Roberson static inline struct tdq *
11699727e637SJeff Roberson sched_setcpu(struct thread *td, int cpu, int flags)
117080f86c9fSJeff Roberson {
11719727e637SJeff Roberson 
1172ae7a6b38SJeff Roberson 	struct tdq *tdq;
117380f86c9fSJeff Roberson 
11749727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1175ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpu);
11769727e637SJeff Roberson 	td->td_sched->ts_cpu = cpu;
11779727e637SJeff Roberson 	/*
11789727e637SJeff Roberson 	 * If the lock matches just return the queue.
11799727e637SJeff Roberson 	 */
1180ae7a6b38SJeff Roberson 	if (td->td_lock == TDQ_LOCKPTR(tdq))
1181ae7a6b38SJeff Roberson 		return (tdq);
1182ae7a6b38SJeff Roberson #ifdef notyet
118380f86c9fSJeff Roberson 	/*
1184a5423ea3SJeff Roberson 	 * If the thread isn't running its lockptr is a
1185ae7a6b38SJeff Roberson 	 * turnstile or a sleepqueue.  We can just lock_set without
1186ae7a6b38SJeff Roberson 	 * blocking.
1187670c524fSJeff Roberson 	 */
1188ae7a6b38SJeff Roberson 	if (TD_CAN_RUN(td)) {
1189ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
1190ae7a6b38SJeff Roberson 		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1191ae7a6b38SJeff Roberson 		return (tdq);
1192ae7a6b38SJeff Roberson 	}
1193ae7a6b38SJeff Roberson #endif
119480f86c9fSJeff Roberson 	/*
1195ae7a6b38SJeff Roberson 	 * The hard case, migration, we need to block the thread first to
1196ae7a6b38SJeff Roberson 	 * prevent order reversals with other cpus locks.
11977b8bfa0dSJeff Roberson 	 */
1198b0b9dee5SAttilio Rao 	spinlock_enter();
1199ae7a6b38SJeff Roberson 	thread_lock_block(td);
1200ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
1201ae7a6b38SJeff Roberson 	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1202b0b9dee5SAttilio Rao 	spinlock_exit();
1203ae7a6b38SJeff Roberson 	return (tdq);
120480f86c9fSJeff Roberson }
12052454aaf5SJeff Roberson 
12068df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
12078df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
12088df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
12098df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
12108df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
12118df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
12128df78c41SJeff Roberson 
1213ae7a6b38SJeff Roberson static int
12149727e637SJeff Roberson sched_pickcpu(struct thread *td, int flags)
1215ae7a6b38SJeff Roberson {
121636acfc65SAlexander Motin 	struct cpu_group *cg, *ccg;
12179727e637SJeff Roberson 	struct td_sched *ts;
1218ae7a6b38SJeff Roberson 	struct tdq *tdq;
1219c76ee827SJeff Roberson 	cpuset_t mask;
122036acfc65SAlexander Motin 	int cpu, pri, self;
12217b8bfa0dSJeff Roberson 
122262fa74d9SJeff Roberson 	self = PCPU_GET(cpuid);
12239727e637SJeff Roberson 	ts = td->td_sched;
12247b8bfa0dSJeff Roberson 	if (smp_started == 0)
12257b8bfa0dSJeff Roberson 		return (self);
122628994a58SJeff Roberson 	/*
122728994a58SJeff Roberson 	 * Don't migrate a running thread from sched_switch().
122828994a58SJeff Roberson 	 */
122962fa74d9SJeff Roberson 	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
123062fa74d9SJeff Roberson 		return (ts->ts_cpu);
12317b8bfa0dSJeff Roberson 	/*
123262fa74d9SJeff Roberson 	 * Prefer to run interrupt threads on the processors that generate
123362fa74d9SJeff Roberson 	 * the interrupt.
12347b8bfa0dSJeff Roberson 	 */
123536acfc65SAlexander Motin 	pri = td->td_priority;
123662fa74d9SJeff Roberson 	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
12378df78c41SJeff Roberson 	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
12388df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_intrbind);
123962fa74d9SJeff Roberson 		ts->ts_cpu = self;
124036acfc65SAlexander Motin 		if (TDQ_CPU(self)->tdq_lowpri > pri) {
12418df78c41SJeff Roberson 			SCHED_STAT_INC(pickcpu_affinity);
12427b8bfa0dSJeff Roberson 			return (ts->ts_cpu);
12437b8bfa0dSJeff Roberson 		}
12448df78c41SJeff Roberson 	}
12457b8bfa0dSJeff Roberson 	/*
124636acfc65SAlexander Motin 	 * If the thread can run on the last cpu and the affinity has not
124736acfc65SAlexander Motin 	 * expired or it is idle run it there.
12487b8bfa0dSJeff Roberson 	 */
124936acfc65SAlexander Motin 	tdq = TDQ_CPU(ts->ts_cpu);
125036acfc65SAlexander Motin 	cg = tdq->tdq_cg;
125136acfc65SAlexander Motin 	if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
125236acfc65SAlexander Motin 	    tdq->tdq_lowpri >= PRI_MIN_IDLE &&
125336acfc65SAlexander Motin 	    SCHED_AFFINITY(ts, CG_SHARE_L2)) {
125436acfc65SAlexander Motin 		if (cg->cg_flags & CG_FLAG_THREAD) {
125536acfc65SAlexander Motin 			CPUSET_FOREACH(cpu, cg->cg_mask) {
125636acfc65SAlexander Motin 				if (TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE)
125762fa74d9SJeff Roberson 					break;
125836acfc65SAlexander Motin 			}
125936acfc65SAlexander Motin 		} else
126036acfc65SAlexander Motin 			cpu = INT_MAX;
126136acfc65SAlexander Motin 		if (cpu > mp_maxid) {
126236acfc65SAlexander Motin 			SCHED_STAT_INC(pickcpu_idle_affinity);
126336acfc65SAlexander Motin 			return (ts->ts_cpu);
126436acfc65SAlexander Motin 		}
126536acfc65SAlexander Motin 	}
126636acfc65SAlexander Motin 	/*
126736acfc65SAlexander Motin 	 * Search for the last level cache CPU group in the tree.
126836acfc65SAlexander Motin 	 * Skip caches with expired affinity time and SMT groups.
126936acfc65SAlexander Motin 	 * Affinity to higher level caches will be handled less aggressively.
127036acfc65SAlexander Motin 	 */
127136acfc65SAlexander Motin 	for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
127236acfc65SAlexander Motin 		if (cg->cg_flags & CG_FLAG_THREAD)
127336acfc65SAlexander Motin 			continue;
127436acfc65SAlexander Motin 		if (!SCHED_AFFINITY(ts, cg->cg_level))
127536acfc65SAlexander Motin 			continue;
127636acfc65SAlexander Motin 		ccg = cg;
127736acfc65SAlexander Motin 	}
127836acfc65SAlexander Motin 	if (ccg != NULL)
127936acfc65SAlexander Motin 		cg = ccg;
128062fa74d9SJeff Roberson 	cpu = -1;
128136acfc65SAlexander Motin 	/* Search the group for the less loaded idle CPU we can run now. */
1282c76ee827SJeff Roberson 	mask = td->td_cpuset->cs_mask;
128336acfc65SAlexander Motin 	if (cg != NULL && cg != cpu_top &&
128436acfc65SAlexander Motin 	    CPU_CMP(&cg->cg_mask, &cpu_top->cg_mask) != 0)
128536acfc65SAlexander Motin 		cpu = sched_lowest(cg, mask, max(pri, PRI_MAX_TIMESHARE),
128636acfc65SAlexander Motin 		    INT_MAX, ts->ts_cpu);
128736acfc65SAlexander Motin 	/* Search globally for the less loaded CPU we can run now. */
128862fa74d9SJeff Roberson 	if (cpu == -1)
128936acfc65SAlexander Motin 		cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu);
129036acfc65SAlexander Motin 	/* Search globally for the less loaded CPU. */
129136acfc65SAlexander Motin 	if (cpu == -1)
129236acfc65SAlexander Motin 		cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu);
12936022f0bcSAlexander Motin 	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
129462fa74d9SJeff Roberson 	/*
129562fa74d9SJeff Roberson 	 * Compare the lowest loaded cpu to current cpu.
129662fa74d9SJeff Roberson 	 */
1297ff256d9cSJeff Roberson 	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
129836acfc65SAlexander Motin 	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE &&
129936acfc65SAlexander Motin 	    TDQ_CPU(self)->tdq_load <= TDQ_CPU(cpu)->tdq_load + 1) {
13008df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_local);
130162fa74d9SJeff Roberson 		cpu = self;
13028df78c41SJeff Roberson 	} else
13038df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_lowest);
13048df78c41SJeff Roberson 	if (cpu != ts->ts_cpu)
13058df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_migration);
1306ae7a6b38SJeff Roberson 	return (cpu);
130780f86c9fSJeff Roberson }
130862fa74d9SJeff Roberson #endif
130922bf7d9aSJeff Roberson 
131022bf7d9aSJeff Roberson /*
131122bf7d9aSJeff Roberson  * Pick the highest priority task we have and return it.
13120c0a98b2SJeff Roberson  */
13139727e637SJeff Roberson static struct thread *
1314ad1e7d28SJulian Elischer tdq_choose(struct tdq *tdq)
13155d7ef00cSJeff Roberson {
13169727e637SJeff Roberson 	struct thread *td;
13175d7ef00cSJeff Roberson 
1318ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
13199727e637SJeff Roberson 	td = runq_choose(&tdq->tdq_realtime);
13209727e637SJeff Roberson 	if (td != NULL)
13219727e637SJeff Roberson 		return (td);
13229727e637SJeff Roberson 	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
13239727e637SJeff Roberson 	if (td != NULL) {
132412d56c0fSJohn Baldwin 		KASSERT(td->td_priority >= PRI_MIN_BATCH,
1325e7d50326SJeff Roberson 		    ("tdq_choose: Invalid priority on timeshare queue %d",
13269727e637SJeff Roberson 		    td->td_priority));
13279727e637SJeff Roberson 		return (td);
132815dc847eSJeff Roberson 	}
13299727e637SJeff Roberson 	td = runq_choose(&tdq->tdq_idle);
13309727e637SJeff Roberson 	if (td != NULL) {
13319727e637SJeff Roberson 		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1332e7d50326SJeff Roberson 		    ("tdq_choose: Invalid priority on idle queue %d",
13339727e637SJeff Roberson 		    td->td_priority));
13349727e637SJeff Roberson 		return (td);
1335e7d50326SJeff Roberson 	}
1336e7d50326SJeff Roberson 
1337e7d50326SJeff Roberson 	return (NULL);
1338245f3abfSJeff Roberson }
13390a016a05SJeff Roberson 
1340ae7a6b38SJeff Roberson /*
1341ae7a6b38SJeff Roberson  * Initialize a thread queue.
1342ae7a6b38SJeff Roberson  */
13430a016a05SJeff Roberson static void
1344ad1e7d28SJulian Elischer tdq_setup(struct tdq *tdq)
13450a016a05SJeff Roberson {
1346ae7a6b38SJeff Roberson 
1347c47f202bSJeff Roberson 	if (bootverbose)
1348c47f202bSJeff Roberson 		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1349e7d50326SJeff Roberson 	runq_init(&tdq->tdq_realtime);
1350e7d50326SJeff Roberson 	runq_init(&tdq->tdq_timeshare);
1351d2ad694cSJeff Roberson 	runq_init(&tdq->tdq_idle);
135262fa74d9SJeff Roberson 	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
135362fa74d9SJeff Roberson 	    "sched lock %d", (int)TDQ_ID(tdq));
135462fa74d9SJeff Roberson 	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
135562fa74d9SJeff Roberson 	    MTX_SPIN | MTX_RECURSE);
13568f51ad55SJeff Roberson #ifdef KTR
13578f51ad55SJeff Roberson 	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
13588f51ad55SJeff Roberson 	    "CPU %d load", (int)TDQ_ID(tdq));
13598f51ad55SJeff Roberson #endif
13600a016a05SJeff Roberson }
13610a016a05SJeff Roberson 
1362c47f202bSJeff Roberson #ifdef SMP
1363c47f202bSJeff Roberson static void
1364c47f202bSJeff Roberson sched_setup_smp(void)
1365c47f202bSJeff Roberson {
1366c47f202bSJeff Roberson 	struct tdq *tdq;
1367c47f202bSJeff Roberson 	int i;
1368c47f202bSJeff Roberson 
136962fa74d9SJeff Roberson 	cpu_top = smp_topo();
13703aa6d94eSJohn Baldwin 	CPU_FOREACH(i) {
137162fa74d9SJeff Roberson 		tdq = TDQ_CPU(i);
1372c47f202bSJeff Roberson 		tdq_setup(tdq);
137362fa74d9SJeff Roberson 		tdq->tdq_cg = smp_topo_find(cpu_top, i);
137462fa74d9SJeff Roberson 		if (tdq->tdq_cg == NULL)
137562fa74d9SJeff Roberson 			panic("Can't find cpu group for %d\n", i);
1376c47f202bSJeff Roberson 	}
137762fa74d9SJeff Roberson 	balance_tdq = TDQ_SELF();
137862fa74d9SJeff Roberson 	sched_balance();
1379c47f202bSJeff Roberson }
1380c47f202bSJeff Roberson #endif
1381c47f202bSJeff Roberson 
1382ae7a6b38SJeff Roberson /*
1383ae7a6b38SJeff Roberson  * Setup the thread queues and initialize the topology based on MD
1384ae7a6b38SJeff Roberson  * information.
1385ae7a6b38SJeff Roberson  */
138635e6168fSJeff Roberson static void
138735e6168fSJeff Roberson sched_setup(void *dummy)
138835e6168fSJeff Roberson {
1389ae7a6b38SJeff Roberson 	struct tdq *tdq;
1390c47f202bSJeff Roberson 
1391c47f202bSJeff Roberson 	tdq = TDQ_SELF();
13920ec896fdSJeff Roberson #ifdef SMP
1393c47f202bSJeff Roberson 	sched_setup_smp();
1394749d01b0SJeff Roberson #else
1395c47f202bSJeff Roberson 	tdq_setup(tdq);
1396356500a3SJeff Roberson #endif
1397ae7a6b38SJeff Roberson 
1398ae7a6b38SJeff Roberson 	/* Add thread0's load since it's running. */
1399ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
1400c47f202bSJeff Roberson 	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
14019727e637SJeff Roberson 	tdq_load_add(tdq, &thread0);
140262fa74d9SJeff Roberson 	tdq->tdq_lowpri = thread0.td_priority;
1403ae7a6b38SJeff Roberson 	TDQ_UNLOCK(tdq);
140435e6168fSJeff Roberson }
140535e6168fSJeff Roberson 
1406ae7a6b38SJeff Roberson /*
1407579895dfSAlexander Motin  * This routine determines time constants after stathz and hz are setup.
1408ae7a6b38SJeff Roberson  */
1409a1d4fe69SDavid Xu /* ARGSUSED */
1410a1d4fe69SDavid Xu static void
1411a1d4fe69SDavid Xu sched_initticks(void *dummy)
1412a1d4fe69SDavid Xu {
1413ae7a6b38SJeff Roberson 	int incr;
1414ae7a6b38SJeff Roberson 
1415a1d4fe69SDavid Xu 	realstathz = stathz ? stathz : hz;
14165e5c3873SJeff Roberson 	sched_slice = realstathz / SCHED_SLICE_DEFAULT_DIVISOR;
14175e5c3873SJeff Roberson 	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
141837f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
141937f4e025SAlexander Motin 	    realstathz);
1420a1d4fe69SDavid Xu 
1421a1d4fe69SDavid Xu 	/*
1422e7d50326SJeff Roberson 	 * tickincr is shifted out by 10 to avoid rounding errors due to
14233f872f85SJeff Roberson 	 * hz not being evenly divisible by stathz on all platforms.
1424e7d50326SJeff Roberson 	 */
1425ae7a6b38SJeff Roberson 	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1426e7d50326SJeff Roberson 	/*
1427e7d50326SJeff Roberson 	 * This does not work for values of stathz that are more than
1428e7d50326SJeff Roberson 	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1429a1d4fe69SDavid Xu 	 */
1430ae7a6b38SJeff Roberson 	if (incr == 0)
1431ae7a6b38SJeff Roberson 		incr = 1;
1432ae7a6b38SJeff Roberson 	tickincr = incr;
14337b8bfa0dSJeff Roberson #ifdef SMP
14349862717aSJeff Roberson 	/*
14357fcf154aSJeff Roberson 	 * Set the default balance interval now that we know
14367fcf154aSJeff Roberson 	 * what realstathz is.
14377fcf154aSJeff Roberson 	 */
14387fcf154aSJeff Roberson 	balance_interval = realstathz;
14397b8bfa0dSJeff Roberson 	affinity = SCHED_AFFINITY_DEFAULT;
14407b8bfa0dSJeff Roberson #endif
1441b3f40a41SAlexander Motin 	if (sched_idlespinthresh < 0)
14422c27cb3aSAlexander Motin 		sched_idlespinthresh = 2 * max(10000, 6 * hz) / realstathz;
1443a1d4fe69SDavid Xu }
1444a1d4fe69SDavid Xu 
1445a1d4fe69SDavid Xu 
144635e6168fSJeff Roberson /*
1447ae7a6b38SJeff Roberson  * This is the core of the interactivity algorithm.  Determines a score based
1448ae7a6b38SJeff Roberson  * on past behavior.  It is the ratio of sleep time to run time scaled to
1449ae7a6b38SJeff Roberson  * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1450ae7a6b38SJeff Roberson  * differs from the cpu usage because it does not account for time spent
1451ae7a6b38SJeff Roberson  * waiting on a run-queue.  Would be prettier if we had floating point.
1452ae7a6b38SJeff Roberson  */
1453ae7a6b38SJeff Roberson static int
1454ae7a6b38SJeff Roberson sched_interact_score(struct thread *td)
1455ae7a6b38SJeff Roberson {
1456ae7a6b38SJeff Roberson 	struct td_sched *ts;
1457ae7a6b38SJeff Roberson 	int div;
1458ae7a6b38SJeff Roberson 
1459ae7a6b38SJeff Roberson 	ts = td->td_sched;
1460ae7a6b38SJeff Roberson 	/*
1461ae7a6b38SJeff Roberson 	 * The score is only needed if this is likely to be an interactive
1462ae7a6b38SJeff Roberson 	 * task.  Don't go through the expense of computing it if there's
1463ae7a6b38SJeff Roberson 	 * no chance.
1464ae7a6b38SJeff Roberson 	 */
1465ae7a6b38SJeff Roberson 	if (sched_interact <= SCHED_INTERACT_HALF &&
1466ae7a6b38SJeff Roberson 		ts->ts_runtime >= ts->ts_slptime)
1467ae7a6b38SJeff Roberson 			return (SCHED_INTERACT_HALF);
1468ae7a6b38SJeff Roberson 
1469ae7a6b38SJeff Roberson 	if (ts->ts_runtime > ts->ts_slptime) {
1470ae7a6b38SJeff Roberson 		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1471ae7a6b38SJeff Roberson 		return (SCHED_INTERACT_HALF +
1472ae7a6b38SJeff Roberson 		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1473ae7a6b38SJeff Roberson 	}
1474ae7a6b38SJeff Roberson 	if (ts->ts_slptime > ts->ts_runtime) {
1475ae7a6b38SJeff Roberson 		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1476ae7a6b38SJeff Roberson 		return (ts->ts_runtime / div);
1477ae7a6b38SJeff Roberson 	}
1478ae7a6b38SJeff Roberson 	/* runtime == slptime */
1479ae7a6b38SJeff Roberson 	if (ts->ts_runtime)
1480ae7a6b38SJeff Roberson 		return (SCHED_INTERACT_HALF);
1481ae7a6b38SJeff Roberson 
1482ae7a6b38SJeff Roberson 	/*
1483ae7a6b38SJeff Roberson 	 * This can happen if slptime and runtime are 0.
1484ae7a6b38SJeff Roberson 	 */
1485ae7a6b38SJeff Roberson 	return (0);
1486ae7a6b38SJeff Roberson 
1487ae7a6b38SJeff Roberson }
1488ae7a6b38SJeff Roberson 
1489ae7a6b38SJeff Roberson /*
149035e6168fSJeff Roberson  * Scale the scheduling priority according to the "interactivity" of this
149135e6168fSJeff Roberson  * process.
149235e6168fSJeff Roberson  */
149315dc847eSJeff Roberson static void
14948460a577SJohn Birrell sched_priority(struct thread *td)
149535e6168fSJeff Roberson {
1496e7d50326SJeff Roberson 	int score;
149735e6168fSJeff Roberson 	int pri;
149835e6168fSJeff Roberson 
1499c9a8cba4SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
150015dc847eSJeff Roberson 		return;
1501e7d50326SJeff Roberson 	/*
1502e7d50326SJeff Roberson 	 * If the score is interactive we place the thread in the realtime
1503e7d50326SJeff Roberson 	 * queue with a priority that is less than kernel and interrupt
1504e7d50326SJeff Roberson 	 * priorities.  These threads are not subject to nice restrictions.
1505e7d50326SJeff Roberson 	 *
1506ae7a6b38SJeff Roberson 	 * Scores greater than this are placed on the normal timeshare queue
1507e7d50326SJeff Roberson 	 * where the priority is partially decided by the most recent cpu
1508e7d50326SJeff Roberson 	 * utilization and the rest is decided by nice value.
1509a5423ea3SJeff Roberson 	 *
1510a5423ea3SJeff Roberson 	 * The nice value of the process has a linear effect on the calculated
1511a5423ea3SJeff Roberson 	 * score.  Negative nice values make it easier for a thread to be
1512a5423ea3SJeff Roberson 	 * considered interactive.
1513e7d50326SJeff Roberson 	 */
1514a0f15352SJohn Baldwin 	score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1515e7d50326SJeff Roberson 	if (score < sched_interact) {
151612d56c0fSJohn Baldwin 		pri = PRI_MIN_INTERACT;
151712d56c0fSJohn Baldwin 		pri += ((PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) /
151878920008SJohn Baldwin 		    sched_interact) * score;
151912d56c0fSJohn Baldwin 		KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
15209a93305aSJeff Roberson 		    ("sched_priority: invalid interactive priority %d score %d",
15219a93305aSJeff Roberson 		    pri, score));
1522e7d50326SJeff Roberson 	} else {
1523e7d50326SJeff Roberson 		pri = SCHED_PRI_MIN;
1524e7d50326SJeff Roberson 		if (td->td_sched->ts_ticks)
15250c0d27d5SJohn Baldwin 			pri += min(SCHED_PRI_TICKS(td->td_sched),
15265457fa23SJohn Baldwin 			    SCHED_PRI_RANGE - 1);
1527e7d50326SJeff Roberson 		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
152812d56c0fSJohn Baldwin 		KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
1529ae7a6b38SJeff Roberson 		    ("sched_priority: invalid priority %d: nice %d, "
1530ae7a6b38SJeff Roberson 		    "ticks %d ftick %d ltick %d tick pri %d",
1531ae7a6b38SJeff Roberson 		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1532ae7a6b38SJeff Roberson 		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1533ae7a6b38SJeff Roberson 		    SCHED_PRI_TICKS(td->td_sched)));
1534e7d50326SJeff Roberson 	}
15358460a577SJohn Birrell 	sched_user_prio(td, pri);
153635e6168fSJeff Roberson 
153715dc847eSJeff Roberson 	return;
153835e6168fSJeff Roberson }
153935e6168fSJeff Roberson 
154035e6168fSJeff Roberson /*
1541d322132cSJeff Roberson  * This routine enforces a maximum limit on the amount of scheduling history
1542ae7a6b38SJeff Roberson  * kept.  It is called after either the slptime or runtime is adjusted.  This
1543ae7a6b38SJeff Roberson  * function is ugly due to integer math.
1544d322132cSJeff Roberson  */
15454b60e324SJeff Roberson static void
15468460a577SJohn Birrell sched_interact_update(struct thread *td)
15474b60e324SJeff Roberson {
1548155b6ca1SJeff Roberson 	struct td_sched *ts;
15499a93305aSJeff Roberson 	u_int sum;
15503f741ca1SJeff Roberson 
1551155b6ca1SJeff Roberson 	ts = td->td_sched;
1552ae7a6b38SJeff Roberson 	sum = ts->ts_runtime + ts->ts_slptime;
1553d322132cSJeff Roberson 	if (sum < SCHED_SLP_RUN_MAX)
1554d322132cSJeff Roberson 		return;
1555d322132cSJeff Roberson 	/*
1556155b6ca1SJeff Roberson 	 * This only happens from two places:
1557155b6ca1SJeff Roberson 	 * 1) We have added an unusual amount of run time from fork_exit.
1558155b6ca1SJeff Roberson 	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1559155b6ca1SJeff Roberson 	 */
1560155b6ca1SJeff Roberson 	if (sum > SCHED_SLP_RUN_MAX * 2) {
1561ae7a6b38SJeff Roberson 		if (ts->ts_runtime > ts->ts_slptime) {
1562ae7a6b38SJeff Roberson 			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1563ae7a6b38SJeff Roberson 			ts->ts_slptime = 1;
1564155b6ca1SJeff Roberson 		} else {
1565ae7a6b38SJeff Roberson 			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1566ae7a6b38SJeff Roberson 			ts->ts_runtime = 1;
1567155b6ca1SJeff Roberson 		}
1568155b6ca1SJeff Roberson 		return;
1569155b6ca1SJeff Roberson 	}
1570155b6ca1SJeff Roberson 	/*
1571d322132cSJeff Roberson 	 * If we have exceeded by more than 1/5th then the algorithm below
1572d322132cSJeff Roberson 	 * will not bring us back into range.  Dividing by two here forces
15732454aaf5SJeff Roberson 	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1574d322132cSJeff Roberson 	 */
157537a35e4aSJeff Roberson 	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1576ae7a6b38SJeff Roberson 		ts->ts_runtime /= 2;
1577ae7a6b38SJeff Roberson 		ts->ts_slptime /= 2;
1578d322132cSJeff Roberson 		return;
1579d322132cSJeff Roberson 	}
1580ae7a6b38SJeff Roberson 	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1581ae7a6b38SJeff Roberson 	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1582d322132cSJeff Roberson }
1583d322132cSJeff Roberson 
1584ae7a6b38SJeff Roberson /*
1585ae7a6b38SJeff Roberson  * Scale back the interactivity history when a child thread is created.  The
1586ae7a6b38SJeff Roberson  * history is inherited from the parent but the thread may behave totally
1587ae7a6b38SJeff Roberson  * differently.  For example, a shell spawning a compiler process.  We want
1588ae7a6b38SJeff Roberson  * to learn that the compiler is behaving badly very quickly.
1589ae7a6b38SJeff Roberson  */
1590d322132cSJeff Roberson static void
15918460a577SJohn Birrell sched_interact_fork(struct thread *td)
1592d322132cSJeff Roberson {
1593d322132cSJeff Roberson 	int ratio;
1594d322132cSJeff Roberson 	int sum;
1595d322132cSJeff Roberson 
1596ae7a6b38SJeff Roberson 	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1597d322132cSJeff Roberson 	if (sum > SCHED_SLP_RUN_FORK) {
1598d322132cSJeff Roberson 		ratio = sum / SCHED_SLP_RUN_FORK;
1599ae7a6b38SJeff Roberson 		td->td_sched->ts_runtime /= ratio;
1600ae7a6b38SJeff Roberson 		td->td_sched->ts_slptime /= ratio;
16014b60e324SJeff Roberson 	}
16024b60e324SJeff Roberson }
16034b60e324SJeff Roberson 
160415dc847eSJeff Roberson /*
1605ae7a6b38SJeff Roberson  * Called from proc0_init() to setup the scheduler fields.
1606ed062c8dSJulian Elischer  */
1607ed062c8dSJulian Elischer void
1608ed062c8dSJulian Elischer schedinit(void)
1609ed062c8dSJulian Elischer {
1610e7d50326SJeff Roberson 
1611ed062c8dSJulian Elischer 	/*
1612ed062c8dSJulian Elischer 	 * Set up the scheduler specific parts of proc0.
1613ed062c8dSJulian Elischer 	 */
1614ed062c8dSJulian Elischer 	proc0.p_sched = NULL; /* XXX */
1615ad1e7d28SJulian Elischer 	thread0.td_sched = &td_sched0;
1616e7d50326SJeff Roberson 	td_sched0.ts_ltick = ticks;
16178ab80cf0SJeff Roberson 	td_sched0.ts_ftick = ticks;
16185e5c3873SJeff Roberson 	td_sched0.ts_slice = 0;
1619ed062c8dSJulian Elischer }
1620ed062c8dSJulian Elischer 
1621ed062c8dSJulian Elischer /*
162215dc847eSJeff Roberson  * This is only somewhat accurate since given many processes of the same
162315dc847eSJeff Roberson  * priority they will switch when their slices run out, which will be
1624e7d50326SJeff Roberson  * at most sched_slice stathz ticks.
162515dc847eSJeff Roberson  */
162635e6168fSJeff Roberson int
162735e6168fSJeff Roberson sched_rr_interval(void)
162835e6168fSJeff Roberson {
1629e7d50326SJeff Roberson 
1630579895dfSAlexander Motin 	/* Convert sched_slice from stathz to hz. */
163137f4e025SAlexander Motin 	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
163235e6168fSJeff Roberson }
163335e6168fSJeff Roberson 
1634ae7a6b38SJeff Roberson /*
1635ae7a6b38SJeff Roberson  * Update the percent cpu tracking information when it is requested or
1636ae7a6b38SJeff Roberson  * the total history exceeds the maximum.  We keep a sliding history of
1637ae7a6b38SJeff Roberson  * tick counts that slowly decays.  This is less precise than the 4BSD
1638ae7a6b38SJeff Roberson  * mechanism since it happens with less regular and frequent events.
1639ae7a6b38SJeff Roberson  */
164022bf7d9aSJeff Roberson static void
16417295465eSAlexander Motin sched_pctcpu_update(struct td_sched *ts, int run)
164235e6168fSJeff Roberson {
16437295465eSAlexander Motin 	int t = ticks;
1644e7d50326SJeff Roberson 
16457295465eSAlexander Motin 	if (t - ts->ts_ltick >= SCHED_TICK_TARG) {
1646ad1e7d28SJulian Elischer 		ts->ts_ticks = 0;
16477295465eSAlexander Motin 		ts->ts_ftick = t - SCHED_TICK_TARG;
16487295465eSAlexander Motin 	} else if (t - ts->ts_ftick >= SCHED_TICK_MAX) {
16497295465eSAlexander Motin 		ts->ts_ticks = (ts->ts_ticks / (ts->ts_ltick - ts->ts_ftick)) *
16507295465eSAlexander Motin 		    (ts->ts_ltick - (t - SCHED_TICK_TARG));
16517295465eSAlexander Motin 		ts->ts_ftick = t - SCHED_TICK_TARG;
16527295465eSAlexander Motin 	}
16537295465eSAlexander Motin 	if (run)
16547295465eSAlexander Motin 		ts->ts_ticks += (t - ts->ts_ltick) << SCHED_TICK_SHIFT;
16557295465eSAlexander Motin 	ts->ts_ltick = t;
165635e6168fSJeff Roberson }
165735e6168fSJeff Roberson 
1658ae7a6b38SJeff Roberson /*
1659ae7a6b38SJeff Roberson  * Adjust the priority of a thread.  Move it to the appropriate run-queue
1660ae7a6b38SJeff Roberson  * if necessary.  This is the back-end for several priority related
1661ae7a6b38SJeff Roberson  * functions.
1662ae7a6b38SJeff Roberson  */
1663e7d50326SJeff Roberson static void
1664f5c157d9SJohn Baldwin sched_thread_priority(struct thread *td, u_char prio)
166535e6168fSJeff Roberson {
1666ad1e7d28SJulian Elischer 	struct td_sched *ts;
166773daf66fSJeff Roberson 	struct tdq *tdq;
166873daf66fSJeff Roberson 	int oldpri;
166935e6168fSJeff Roberson 
16708f51ad55SJeff Roberson 	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
16718f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, "new prio:%d", prio,
16728f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(curthread));
1673d9fae5abSAndriy Gapon 	SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
1674e87fc7cfSAndriy Gapon 	if (td != curthread && prio < td->td_priority) {
16758f51ad55SJeff Roberson 		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
16768f51ad55SJeff Roberson 		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
16778f51ad55SJeff Roberson 		    prio, KTR_ATTR_LINKED, sched_tdname(td));
1678d9fae5abSAndriy Gapon 		SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
1679b3e9e682SRyan Stone 		    curthread);
16808f51ad55SJeff Roberson 	}
1681ad1e7d28SJulian Elischer 	ts = td->td_sched;
16827b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1683f5c157d9SJohn Baldwin 	if (td->td_priority == prio)
1684f5c157d9SJohn Baldwin 		return;
16853f741ca1SJeff Roberson 	/*
16863f741ca1SJeff Roberson 	 * If the priority has been elevated due to priority
16873f741ca1SJeff Roberson 	 * propagation, we may have to move ourselves to a new
1688e7d50326SJeff Roberson 	 * queue.  This could be optimized to not re-add in some
1689e7d50326SJeff Roberson 	 * cases.
1690f2b74cbfSJeff Roberson 	 */
16916d55b3ecSJeff Roberson 	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1692e7d50326SJeff Roberson 		sched_rem(td);
1693e7d50326SJeff Roberson 		td->td_priority = prio;
1694ae7a6b38SJeff Roberson 		sched_add(td, SRQ_BORROWING);
169573daf66fSJeff Roberson 		return;
169673daf66fSJeff Roberson 	}
16976d55b3ecSJeff Roberson 	/*
16986d55b3ecSJeff Roberson 	 * If the thread is currently running we may have to adjust the lowpri
16996d55b3ecSJeff Roberson 	 * information so other cpus are aware of our current priority.
17006d55b3ecSJeff Roberson 	 */
17016d55b3ecSJeff Roberson 	if (TD_IS_RUNNING(td)) {
1702ae7a6b38SJeff Roberson 		tdq = TDQ_CPU(ts->ts_cpu);
170362fa74d9SJeff Roberson 		oldpri = td->td_priority;
17043f741ca1SJeff Roberson 		td->td_priority = prio;
170562fa74d9SJeff Roberson 		if (prio < tdq->tdq_lowpri)
170662fa74d9SJeff Roberson 			tdq->tdq_lowpri = prio;
170762fa74d9SJeff Roberson 		else if (tdq->tdq_lowpri == oldpri)
170862fa74d9SJeff Roberson 			tdq_setlowpri(tdq, td);
17096d55b3ecSJeff Roberson 		return;
171073daf66fSJeff Roberson 	}
17116d55b3ecSJeff Roberson 	td->td_priority = prio;
1712ae7a6b38SJeff Roberson }
171335e6168fSJeff Roberson 
1714f5c157d9SJohn Baldwin /*
1715f5c157d9SJohn Baldwin  * Update a thread's priority when it is lent another thread's
1716f5c157d9SJohn Baldwin  * priority.
1717f5c157d9SJohn Baldwin  */
1718f5c157d9SJohn Baldwin void
1719f5c157d9SJohn Baldwin sched_lend_prio(struct thread *td, u_char prio)
1720f5c157d9SJohn Baldwin {
1721f5c157d9SJohn Baldwin 
1722f5c157d9SJohn Baldwin 	td->td_flags |= TDF_BORROWING;
1723f5c157d9SJohn Baldwin 	sched_thread_priority(td, prio);
1724f5c157d9SJohn Baldwin }
1725f5c157d9SJohn Baldwin 
1726f5c157d9SJohn Baldwin /*
1727f5c157d9SJohn Baldwin  * Restore a thread's priority when priority propagation is
1728f5c157d9SJohn Baldwin  * over.  The prio argument is the minimum priority the thread
1729f5c157d9SJohn Baldwin  * needs to have to satisfy other possible priority lending
1730f5c157d9SJohn Baldwin  * requests.  If the thread's regular priority is less
1731f5c157d9SJohn Baldwin  * important than prio, the thread will keep a priority boost
1732f5c157d9SJohn Baldwin  * of prio.
1733f5c157d9SJohn Baldwin  */
1734f5c157d9SJohn Baldwin void
1735f5c157d9SJohn Baldwin sched_unlend_prio(struct thread *td, u_char prio)
1736f5c157d9SJohn Baldwin {
1737f5c157d9SJohn Baldwin 	u_char base_pri;
1738f5c157d9SJohn Baldwin 
1739f5c157d9SJohn Baldwin 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1740f5c157d9SJohn Baldwin 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
17418460a577SJohn Birrell 		base_pri = td->td_user_pri;
1742f5c157d9SJohn Baldwin 	else
1743f5c157d9SJohn Baldwin 		base_pri = td->td_base_pri;
1744f5c157d9SJohn Baldwin 	if (prio >= base_pri) {
1745f5c157d9SJohn Baldwin 		td->td_flags &= ~TDF_BORROWING;
1746f5c157d9SJohn Baldwin 		sched_thread_priority(td, base_pri);
1747f5c157d9SJohn Baldwin 	} else
1748f5c157d9SJohn Baldwin 		sched_lend_prio(td, prio);
1749f5c157d9SJohn Baldwin }
1750f5c157d9SJohn Baldwin 
1751ae7a6b38SJeff Roberson /*
1752ae7a6b38SJeff Roberson  * Standard entry for setting the priority to an absolute value.
1753ae7a6b38SJeff Roberson  */
1754f5c157d9SJohn Baldwin void
1755f5c157d9SJohn Baldwin sched_prio(struct thread *td, u_char prio)
1756f5c157d9SJohn Baldwin {
1757f5c157d9SJohn Baldwin 	u_char oldprio;
1758f5c157d9SJohn Baldwin 
1759f5c157d9SJohn Baldwin 	/* First, update the base priority. */
1760f5c157d9SJohn Baldwin 	td->td_base_pri = prio;
1761f5c157d9SJohn Baldwin 
1762f5c157d9SJohn Baldwin 	/*
176350aaa791SJohn Baldwin 	 * If the thread is borrowing another thread's priority, don't
1764f5c157d9SJohn Baldwin 	 * ever lower the priority.
1765f5c157d9SJohn Baldwin 	 */
1766f5c157d9SJohn Baldwin 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1767f5c157d9SJohn Baldwin 		return;
1768f5c157d9SJohn Baldwin 
1769f5c157d9SJohn Baldwin 	/* Change the real priority. */
1770f5c157d9SJohn Baldwin 	oldprio = td->td_priority;
1771f5c157d9SJohn Baldwin 	sched_thread_priority(td, prio);
1772f5c157d9SJohn Baldwin 
1773f5c157d9SJohn Baldwin 	/*
1774f5c157d9SJohn Baldwin 	 * If the thread is on a turnstile, then let the turnstile update
1775f5c157d9SJohn Baldwin 	 * its state.
1776f5c157d9SJohn Baldwin 	 */
1777f5c157d9SJohn Baldwin 	if (TD_ON_LOCK(td) && oldprio != prio)
1778f5c157d9SJohn Baldwin 		turnstile_adjust(td, oldprio);
1779f5c157d9SJohn Baldwin }
1780f5c157d9SJohn Baldwin 
1781ae7a6b38SJeff Roberson /*
1782ae7a6b38SJeff Roberson  * Set the base user priority, does not effect current running priority.
1783ae7a6b38SJeff Roberson  */
178435e6168fSJeff Roberson void
17858460a577SJohn Birrell sched_user_prio(struct thread *td, u_char prio)
17863db720fdSDavid Xu {
17873db720fdSDavid Xu 
17888460a577SJohn Birrell 	td->td_base_user_pri = prio;
1789acbe332aSDavid Xu 	if (td->td_lend_user_pri <= prio)
1790fc6c30f6SJulian Elischer 		return;
17918460a577SJohn Birrell 	td->td_user_pri = prio;
17923db720fdSDavid Xu }
17933db720fdSDavid Xu 
17943db720fdSDavid Xu void
17953db720fdSDavid Xu sched_lend_user_prio(struct thread *td, u_char prio)
17963db720fdSDavid Xu {
17973db720fdSDavid Xu 
1798435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1799acbe332aSDavid Xu 	td->td_lend_user_pri = prio;
1800c8e368a9SDavid Xu 	td->td_user_pri = min(prio, td->td_base_user_pri);
1801c8e368a9SDavid Xu 	if (td->td_priority > td->td_user_pri)
1802c8e368a9SDavid Xu 		sched_prio(td, td->td_user_pri);
1803c8e368a9SDavid Xu 	else if (td->td_priority != td->td_user_pri)
1804c8e368a9SDavid Xu 		td->td_flags |= TDF_NEEDRESCHED;
1805435806d3SDavid Xu }
18063db720fdSDavid Xu 
1807ae7a6b38SJeff Roberson /*
1808c47f202bSJeff Roberson  * Handle migration from sched_switch().  This happens only for
1809c47f202bSJeff Roberson  * cpu binding.
1810c47f202bSJeff Roberson  */
1811c47f202bSJeff Roberson static struct mtx *
1812c47f202bSJeff Roberson sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1813c47f202bSJeff Roberson {
1814c47f202bSJeff Roberson 	struct tdq *tdn;
1815c47f202bSJeff Roberson 
1816c47f202bSJeff Roberson 	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1817c47f202bSJeff Roberson #ifdef SMP
18189727e637SJeff Roberson 	tdq_load_rem(tdq, td);
1819c47f202bSJeff Roberson 	/*
1820c47f202bSJeff Roberson 	 * Do the lock dance required to avoid LOR.  We grab an extra
1821c47f202bSJeff Roberson 	 * spinlock nesting to prevent preemption while we're
1822c47f202bSJeff Roberson 	 * not holding either run-queue lock.
1823c47f202bSJeff Roberson 	 */
1824c47f202bSJeff Roberson 	spinlock_enter();
1825b0b9dee5SAttilio Rao 	thread_lock_block(td);	/* This releases the lock on tdq. */
1826435068aaSAttilio Rao 
1827435068aaSAttilio Rao 	/*
1828435068aaSAttilio Rao 	 * Acquire both run-queue locks before placing the thread on the new
1829435068aaSAttilio Rao 	 * run-queue to avoid deadlocks created by placing a thread with a
1830435068aaSAttilio Rao 	 * blocked lock on the run-queue of a remote processor.  The deadlock
1831435068aaSAttilio Rao 	 * occurs when a third processor attempts to lock the two queues in
1832435068aaSAttilio Rao 	 * question while the target processor is spinning with its own
1833435068aaSAttilio Rao 	 * run-queue lock held while waiting for the blocked lock to clear.
1834435068aaSAttilio Rao 	 */
1835435068aaSAttilio Rao 	tdq_lock_pair(tdn, tdq);
1836c47f202bSJeff Roberson 	tdq_add(tdn, td, flags);
18379727e637SJeff Roberson 	tdq_notify(tdn, td);
1838c47f202bSJeff Roberson 	TDQ_UNLOCK(tdn);
1839c47f202bSJeff Roberson 	spinlock_exit();
1840c47f202bSJeff Roberson #endif
1841c47f202bSJeff Roberson 	return (TDQ_LOCKPTR(tdn));
1842c47f202bSJeff Roberson }
1843c47f202bSJeff Roberson 
1844c47f202bSJeff Roberson /*
1845b0b9dee5SAttilio Rao  * Variadic version of thread_lock_unblock() that does not assume td_lock
1846b0b9dee5SAttilio Rao  * is blocked.
1847ae7a6b38SJeff Roberson  */
1848ae7a6b38SJeff Roberson static inline void
1849ae7a6b38SJeff Roberson thread_unblock_switch(struct thread *td, struct mtx *mtx)
1850ae7a6b38SJeff Roberson {
1851ae7a6b38SJeff Roberson 	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1852ae7a6b38SJeff Roberson 	    (uintptr_t)mtx);
1853ae7a6b38SJeff Roberson }
1854ae7a6b38SJeff Roberson 
1855ae7a6b38SJeff Roberson /*
1856ae7a6b38SJeff Roberson  * Switch threads.  This function has to handle threads coming in while
1857ae7a6b38SJeff Roberson  * blocked for some reason, running, or idle.  It also must deal with
1858ae7a6b38SJeff Roberson  * migrating a thread from one queue to another as running threads may
1859ae7a6b38SJeff Roberson  * be assigned elsewhere via binding.
1860ae7a6b38SJeff Roberson  */
18613db720fdSDavid Xu void
18623389af30SJulian Elischer sched_switch(struct thread *td, struct thread *newtd, int flags)
186335e6168fSJeff Roberson {
1864c02bbb43SJeff Roberson 	struct tdq *tdq;
1865ad1e7d28SJulian Elischer 	struct td_sched *ts;
1866ae7a6b38SJeff Roberson 	struct mtx *mtx;
1867c47f202bSJeff Roberson 	int srqflag;
18683d7f4117SAlexander Motin 	int cpuid, preempted;
186935e6168fSJeff Roberson 
18707b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
18716d55b3ecSJeff Roberson 	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
187235e6168fSJeff Roberson 
1873ae7a6b38SJeff Roberson 	cpuid = PCPU_GET(cpuid);
1874ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpuid);
1875e7d50326SJeff Roberson 	ts = td->td_sched;
1876c47f202bSJeff Roberson 	mtx = td->td_lock;
18777295465eSAlexander Motin 	sched_pctcpu_update(ts, 1);
1878ae7a6b38SJeff Roberson 	ts->ts_rltick = ticks;
1879060563ecSJulian Elischer 	td->td_lastcpu = td->td_oncpu;
1880060563ecSJulian Elischer 	td->td_oncpu = NOCPU;
18812e7d7bb2SAlexander Motin 	preempted = !((td->td_flags & TDF_SLICEEND) ||
18822e7d7bb2SAlexander Motin 	    (flags & SWT_RELINQUISH));
18833d7f4117SAlexander Motin 	td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
188477918643SStephan Uphoff 	td->td_owepreempt = 0;
18852c27cb3aSAlexander Motin 	if (!TD_IS_IDLETHREAD(td))
18861690c6c1SJeff Roberson 		tdq->tdq_switchcnt++;
1887b11fdad0SJeff Roberson 	/*
1888ae7a6b38SJeff Roberson 	 * The lock pointer in an idle thread should never change.  Reset it
1889ae7a6b38SJeff Roberson 	 * to CAN_RUN as well.
1890b11fdad0SJeff Roberson 	 */
1891486a9414SJulian Elischer 	if (TD_IS_IDLETHREAD(td)) {
1892ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1893bf0acc27SJohn Baldwin 		TD_SET_CAN_RUN(td);
18947b20fb19SJeff Roberson 	} else if (TD_IS_RUNNING(td)) {
1895ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
18963d7f4117SAlexander Motin 		srqflag = preempted ?
1897598b368dSJeff Roberson 		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1898c47f202bSJeff Roberson 		    SRQ_OURSELF|SRQ_YIELDING;
1899ba4932b5SMatthew D Fleming #ifdef SMP
19000f7a0ebdSMatthew D Fleming 		if (THREAD_CAN_MIGRATE(td) && !THREAD_CAN_SCHED(td, ts->ts_cpu))
19010f7a0ebdSMatthew D Fleming 			ts->ts_cpu = sched_pickcpu(td, 0);
1902ba4932b5SMatthew D Fleming #endif
1903c47f202bSJeff Roberson 		if (ts->ts_cpu == cpuid)
19049727e637SJeff Roberson 			tdq_runq_add(tdq, td, srqflag);
19050f7a0ebdSMatthew D Fleming 		else {
19060f7a0ebdSMatthew D Fleming 			KASSERT(THREAD_CAN_MIGRATE(td) ||
19070f7a0ebdSMatthew D Fleming 			    (ts->ts_flags & TSF_BOUND) != 0,
19080f7a0ebdSMatthew D Fleming 			    ("Thread %p shouldn't migrate", td));
1909c47f202bSJeff Roberson 			mtx = sched_switch_migrate(tdq, td, srqflag);
19100f7a0ebdSMatthew D Fleming 		}
1911ae7a6b38SJeff Roberson 	} else {
1912ae7a6b38SJeff Roberson 		/* This thread must be going to sleep. */
1913ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
1914b0b9dee5SAttilio Rao 		mtx = thread_lock_block(td);
19159727e637SJeff Roberson 		tdq_load_rem(tdq, td);
1916ae7a6b38SJeff Roberson 	}
1917ae7a6b38SJeff Roberson 	/*
1918ae7a6b38SJeff Roberson 	 * We enter here with the thread blocked and assigned to the
1919ae7a6b38SJeff Roberson 	 * appropriate cpu run-queue or sleep-queue and with the current
1920ae7a6b38SJeff Roberson 	 * thread-queue locked.
1921ae7a6b38SJeff Roberson 	 */
1922ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
19232454aaf5SJeff Roberson 	newtd = choosethread();
1924ae7a6b38SJeff Roberson 	/*
1925ae7a6b38SJeff Roberson 	 * Call the MD code to switch contexts if necessary.
1926ae7a6b38SJeff Roberson 	 */
1927ebccf1e3SJoseph Koshy 	if (td != newtd) {
1928ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1929ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1930ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1931ebccf1e3SJoseph Koshy #endif
1932d9fae5abSAndriy Gapon 		SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
1933eea4f254SJeff Roberson 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
193459c68134SJeff Roberson 		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
19357295465eSAlexander Motin 		sched_pctcpu_update(newtd->td_sched, 0);
19366f5f25e5SJohn Birrell 
19376f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
19386f5f25e5SJohn Birrell 		/*
19396f5f25e5SJohn Birrell 		 * If DTrace has set the active vtime enum to anything
19406f5f25e5SJohn Birrell 		 * other than INACTIVE (0), then it should have set the
19416f5f25e5SJohn Birrell 		 * function to call.
19426f5f25e5SJohn Birrell 		 */
19436f5f25e5SJohn Birrell 		if (dtrace_vtime_active)
19446f5f25e5SJohn Birrell 			(*dtrace_vtime_switch_func)(newtd);
19456f5f25e5SJohn Birrell #endif
19466f5f25e5SJohn Birrell 
1947ae7a6b38SJeff Roberson 		cpu_switch(td, newtd, mtx);
1948ae7a6b38SJeff Roberson 		/*
1949ae7a6b38SJeff Roberson 		 * We may return from cpu_switch on a different cpu.  However,
1950ae7a6b38SJeff Roberson 		 * we always return with td_lock pointing to the current cpu's
1951ae7a6b38SJeff Roberson 		 * run queue lock.
1952ae7a6b38SJeff Roberson 		 */
1953ae7a6b38SJeff Roberson 		cpuid = PCPU_GET(cpuid);
1954ae7a6b38SJeff Roberson 		tdq = TDQ_CPU(cpuid);
1955eea4f254SJeff Roberson 		lock_profile_obtain_lock_success(
1956eea4f254SJeff Roberson 		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1957b3e9e682SRyan Stone 
1958d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , on__cpu);
1959ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1960ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1961ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1962ebccf1e3SJoseph Koshy #endif
1963b3e9e682SRyan Stone 	} else {
1964ae7a6b38SJeff Roberson 		thread_unblock_switch(td, mtx);
1965d9fae5abSAndriy Gapon 		SDT_PROBE0(sched, , , remain__cpu);
1966b3e9e682SRyan Stone 	}
1967ae7a6b38SJeff Roberson 	/*
1968ae7a6b38SJeff Roberson 	 * Assert that all went well and return.
1969ae7a6b38SJeff Roberson 	 */
1970ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1971ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1972ae7a6b38SJeff Roberson 	td->td_oncpu = cpuid;
197335e6168fSJeff Roberson }
197435e6168fSJeff Roberson 
1975ae7a6b38SJeff Roberson /*
1976ae7a6b38SJeff Roberson  * Adjust thread priorities as a result of a nice request.
1977ae7a6b38SJeff Roberson  */
197835e6168fSJeff Roberson void
1979fa885116SJulian Elischer sched_nice(struct proc *p, int nice)
198035e6168fSJeff Roberson {
198135e6168fSJeff Roberson 	struct thread *td;
198235e6168fSJeff Roberson 
1983fa885116SJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
1984e7d50326SJeff Roberson 
1985fa885116SJulian Elischer 	p->p_nice = nice;
19868460a577SJohn Birrell 	FOREACH_THREAD_IN_PROC(p, td) {
19877b20fb19SJeff Roberson 		thread_lock(td);
19888460a577SJohn Birrell 		sched_priority(td);
1989e7d50326SJeff Roberson 		sched_prio(td, td->td_base_user_pri);
19907b20fb19SJeff Roberson 		thread_unlock(td);
199135e6168fSJeff Roberson 	}
1992fa885116SJulian Elischer }
199335e6168fSJeff Roberson 
1994ae7a6b38SJeff Roberson /*
1995ae7a6b38SJeff Roberson  * Record the sleep time for the interactivity scorer.
1996ae7a6b38SJeff Roberson  */
199735e6168fSJeff Roberson void
1998c5aa6b58SJeff Roberson sched_sleep(struct thread *td, int prio)
199935e6168fSJeff Roberson {
2000e7d50326SJeff Roberson 
20017b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
200235e6168fSJeff Roberson 
200354b0e65fSJeff Roberson 	td->td_slptick = ticks;
200417c4c356SKonstantin Belousov 	if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
2005c5aa6b58SJeff Roberson 		td->td_flags |= TDF_CANSWAP;
20062dc29adbSJohn Baldwin 	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
20072dc29adbSJohn Baldwin 		return;
20080502fe2eSJeff Roberson 	if (static_boost == 1 && prio)
2009c5aa6b58SJeff Roberson 		sched_prio(td, prio);
20100502fe2eSJeff Roberson 	else if (static_boost && td->td_priority > static_boost)
20110502fe2eSJeff Roberson 		sched_prio(td, static_boost);
201235e6168fSJeff Roberson }
201335e6168fSJeff Roberson 
2014ae7a6b38SJeff Roberson /*
2015ae7a6b38SJeff Roberson  * Schedule a thread to resume execution and record how long it voluntarily
2016ae7a6b38SJeff Roberson  * slept.  We also update the pctcpu, interactivity, and priority.
2017ae7a6b38SJeff Roberson  */
201835e6168fSJeff Roberson void
201935e6168fSJeff Roberson sched_wakeup(struct thread *td)
202035e6168fSJeff Roberson {
202114618990SJeff Roberson 	struct td_sched *ts;
2022ae7a6b38SJeff Roberson 	int slptick;
2023e7d50326SJeff Roberson 
20247b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
202514618990SJeff Roberson 	ts = td->td_sched;
2026c5aa6b58SJeff Roberson 	td->td_flags &= ~TDF_CANSWAP;
202735e6168fSJeff Roberson 	/*
2028e7d50326SJeff Roberson 	 * If we slept for more than a tick update our interactivity and
2029e7d50326SJeff Roberson 	 * priority.
203035e6168fSJeff Roberson 	 */
203154b0e65fSJeff Roberson 	slptick = td->td_slptick;
203254b0e65fSJeff Roberson 	td->td_slptick = 0;
2033ae7a6b38SJeff Roberson 	if (slptick && slptick != ticks) {
20347295465eSAlexander Motin 		ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
20358460a577SJohn Birrell 		sched_interact_update(td);
20367295465eSAlexander Motin 		sched_pctcpu_update(ts, 0);
2037f1e8dc4aSJeff Roberson 	}
20385e5c3873SJeff Roberson 	/*
20395e5c3873SJeff Roberson 	 * Reset the slice value since we slept and advanced the round-robin.
20405e5c3873SJeff Roberson 	 */
20415e5c3873SJeff Roberson 	ts->ts_slice = 0;
20427a5e5e2aSJeff Roberson 	sched_add(td, SRQ_BORING);
204335e6168fSJeff Roberson }
204435e6168fSJeff Roberson 
204535e6168fSJeff Roberson /*
204635e6168fSJeff Roberson  * Penalize the parent for creating a new child and initialize the child's
204735e6168fSJeff Roberson  * priority.
204835e6168fSJeff Roberson  */
204935e6168fSJeff Roberson void
20508460a577SJohn Birrell sched_fork(struct thread *td, struct thread *child)
205115dc847eSJeff Roberson {
20527b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
20537295465eSAlexander Motin 	sched_pctcpu_update(td->td_sched, 1);
2054ad1e7d28SJulian Elischer 	sched_fork_thread(td, child);
2055e7d50326SJeff Roberson 	/*
2056e7d50326SJeff Roberson 	 * Penalize the parent and child for forking.
2057e7d50326SJeff Roberson 	 */
2058e7d50326SJeff Roberson 	sched_interact_fork(child);
2059e7d50326SJeff Roberson 	sched_priority(child);
2060ae7a6b38SJeff Roberson 	td->td_sched->ts_runtime += tickincr;
2061e7d50326SJeff Roberson 	sched_interact_update(td);
2062e7d50326SJeff Roberson 	sched_priority(td);
2063ad1e7d28SJulian Elischer }
2064ad1e7d28SJulian Elischer 
2065ae7a6b38SJeff Roberson /*
2066ae7a6b38SJeff Roberson  * Fork a new thread, may be within the same process.
2067ae7a6b38SJeff Roberson  */
2068ad1e7d28SJulian Elischer void
2069ad1e7d28SJulian Elischer sched_fork_thread(struct thread *td, struct thread *child)
2070ad1e7d28SJulian Elischer {
2071ad1e7d28SJulian Elischer 	struct td_sched *ts;
2072ad1e7d28SJulian Elischer 	struct td_sched *ts2;
20735e5c3873SJeff Roberson 	struct tdq *tdq;
20748460a577SJohn Birrell 
20755e5c3873SJeff Roberson 	tdq = TDQ_SELF();
20768b16c208SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2077e7d50326SJeff Roberson 	/*
2078e7d50326SJeff Roberson 	 * Initialize child.
2079e7d50326SJeff Roberson 	 */
2080ad1e7d28SJulian Elischer 	ts = td->td_sched;
2081ad1e7d28SJulian Elischer 	ts2 = child->td_sched;
20825e5c3873SJeff Roberson 	child->td_lock = TDQ_LOCKPTR(tdq);
20838b16c208SJeff Roberson 	child->td_cpuset = cpuset_ref(td->td_cpuset);
2084ad1e7d28SJulian Elischer 	ts2->ts_cpu = ts->ts_cpu;
20858b16c208SJeff Roberson 	ts2->ts_flags = 0;
2086e7d50326SJeff Roberson 	/*
208722d19207SJohn Baldwin 	 * Grab our parents cpu estimation information.
2088e7d50326SJeff Roberson 	 */
2089ad1e7d28SJulian Elischer 	ts2->ts_ticks = ts->ts_ticks;
2090ad1e7d28SJulian Elischer 	ts2->ts_ltick = ts->ts_ltick;
2091ad1e7d28SJulian Elischer 	ts2->ts_ftick = ts->ts_ftick;
209222d19207SJohn Baldwin 	/*
209322d19207SJohn Baldwin 	 * Do not inherit any borrowed priority from the parent.
209422d19207SJohn Baldwin 	 */
209522d19207SJohn Baldwin 	child->td_priority = child->td_base_pri;
2096e7d50326SJeff Roberson 	/*
2097e7d50326SJeff Roberson 	 * And update interactivity score.
2098e7d50326SJeff Roberson 	 */
2099ae7a6b38SJeff Roberson 	ts2->ts_slptime = ts->ts_slptime;
2100ae7a6b38SJeff Roberson 	ts2->ts_runtime = ts->ts_runtime;
21015e5c3873SJeff Roberson 	/* Attempt to quickly learn interactivity. */
21025e5c3873SJeff Roberson 	ts2->ts_slice = tdq_slice(tdq) - sched_slice_min;
21038f51ad55SJeff Roberson #ifdef KTR
21048f51ad55SJeff Roberson 	bzero(ts2->ts_name, sizeof(ts2->ts_name));
21058f51ad55SJeff Roberson #endif
210615dc847eSJeff Roberson }
210715dc847eSJeff Roberson 
2108ae7a6b38SJeff Roberson /*
2109ae7a6b38SJeff Roberson  * Adjust the priority class of a thread.
2110ae7a6b38SJeff Roberson  */
211115dc847eSJeff Roberson void
21128460a577SJohn Birrell sched_class(struct thread *td, int class)
211315dc847eSJeff Roberson {
211415dc847eSJeff Roberson 
21157b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
21168460a577SJohn Birrell 	if (td->td_pri_class == class)
211715dc847eSJeff Roberson 		return;
21188460a577SJohn Birrell 	td->td_pri_class = class;
211935e6168fSJeff Roberson }
212035e6168fSJeff Roberson 
212135e6168fSJeff Roberson /*
212235e6168fSJeff Roberson  * Return some of the child's priority and interactivity to the parent.
212335e6168fSJeff Roberson  */
212435e6168fSJeff Roberson void
2125fc6c30f6SJulian Elischer sched_exit(struct proc *p, struct thread *child)
212635e6168fSJeff Roberson {
2127e7d50326SJeff Roberson 	struct thread *td;
2128141ad61cSJeff Roberson 
21298f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2130cd39bb09SXin LI 	    "prio:%d", child->td_priority);
2131374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
2132e7d50326SJeff Roberson 	td = FIRST_THREAD_IN_PROC(p);
2133e7d50326SJeff Roberson 	sched_exit_thread(td, child);
2134ad1e7d28SJulian Elischer }
2135ad1e7d28SJulian Elischer 
2136ae7a6b38SJeff Roberson /*
2137ae7a6b38SJeff Roberson  * Penalize another thread for the time spent on this one.  This helps to
2138ae7a6b38SJeff Roberson  * worsen the priority and interactivity of processes which schedule batch
2139ae7a6b38SJeff Roberson  * jobs such as make.  This has little effect on the make process itself but
2140ae7a6b38SJeff Roberson  * causes new processes spawned by it to receive worse scores immediately.
2141ae7a6b38SJeff Roberson  */
2142ad1e7d28SJulian Elischer void
2143fc6c30f6SJulian Elischer sched_exit_thread(struct thread *td, struct thread *child)
2144ad1e7d28SJulian Elischer {
2145fc6c30f6SJulian Elischer 
21468f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2147cd39bb09SXin LI 	    "prio:%d", child->td_priority);
2148e7d50326SJeff Roberson 	/*
2149e7d50326SJeff Roberson 	 * Give the child's runtime to the parent without returning the
2150e7d50326SJeff Roberson 	 * sleep time as a penalty to the parent.  This causes shells that
2151e7d50326SJeff Roberson 	 * launch expensive things to mark their children as expensive.
2152e7d50326SJeff Roberson 	 */
21537b20fb19SJeff Roberson 	thread_lock(td);
2154ae7a6b38SJeff Roberson 	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2155fc6c30f6SJulian Elischer 	sched_interact_update(td);
2156e7d50326SJeff Roberson 	sched_priority(td);
21577b20fb19SJeff Roberson 	thread_unlock(td);
2158ad1e7d28SJulian Elischer }
2159ad1e7d28SJulian Elischer 
2160ff256d9cSJeff Roberson void
2161ff256d9cSJeff Roberson sched_preempt(struct thread *td)
2162ff256d9cSJeff Roberson {
2163ff256d9cSJeff Roberson 	struct tdq *tdq;
2164ff256d9cSJeff Roberson 
2165b3e9e682SRyan Stone 	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
2166b3e9e682SRyan Stone 
2167ff256d9cSJeff Roberson 	thread_lock(td);
2168ff256d9cSJeff Roberson 	tdq = TDQ_SELF();
2169ff256d9cSJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2170ff256d9cSJeff Roberson 	tdq->tdq_ipipending = 0;
2171ff256d9cSJeff Roberson 	if (td->td_priority > tdq->tdq_lowpri) {
21728df78c41SJeff Roberson 		int flags;
21738df78c41SJeff Roberson 
21748df78c41SJeff Roberson 		flags = SW_INVOL | SW_PREEMPT;
2175ff256d9cSJeff Roberson 		if (td->td_critnest > 1)
2176ff256d9cSJeff Roberson 			td->td_owepreempt = 1;
21778df78c41SJeff Roberson 		else if (TD_IS_IDLETHREAD(td))
21788df78c41SJeff Roberson 			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2179ff256d9cSJeff Roberson 		else
21808df78c41SJeff Roberson 			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2181ff256d9cSJeff Roberson 	}
2182ff256d9cSJeff Roberson 	thread_unlock(td);
2183ff256d9cSJeff Roberson }
2184ff256d9cSJeff Roberson 
2185ae7a6b38SJeff Roberson /*
2186ae7a6b38SJeff Roberson  * Fix priorities on return to user-space.  Priorities may be elevated due
2187ae7a6b38SJeff Roberson  * to static priorities in msleep() or similar.
2188ae7a6b38SJeff Roberson  */
2189ad1e7d28SJulian Elischer void
2190ad1e7d28SJulian Elischer sched_userret(struct thread *td)
2191ad1e7d28SJulian Elischer {
2192ad1e7d28SJulian Elischer 	/*
2193ad1e7d28SJulian Elischer 	 * XXX we cheat slightly on the locking here to avoid locking in
2194ad1e7d28SJulian Elischer 	 * the usual case.  Setting td_priority here is essentially an
2195ad1e7d28SJulian Elischer 	 * incomplete workaround for not setting it properly elsewhere.
2196ad1e7d28SJulian Elischer 	 * Now that some interrupt handlers are threads, not setting it
2197ad1e7d28SJulian Elischer 	 * properly elsewhere can clobber it in the window between setting
2198ad1e7d28SJulian Elischer 	 * it here and returning to user mode, so don't waste time setting
2199ad1e7d28SJulian Elischer 	 * it perfectly here.
2200ad1e7d28SJulian Elischer 	 */
2201ad1e7d28SJulian Elischer 	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2202ad1e7d28SJulian Elischer 	    ("thread with borrowed priority returning to userland"));
2203ad1e7d28SJulian Elischer 	if (td->td_priority != td->td_user_pri) {
22047b20fb19SJeff Roberson 		thread_lock(td);
2205ad1e7d28SJulian Elischer 		td->td_priority = td->td_user_pri;
2206ad1e7d28SJulian Elischer 		td->td_base_pri = td->td_user_pri;
220762fa74d9SJeff Roberson 		tdq_setlowpri(TDQ_SELF(), td);
22087b20fb19SJeff Roberson 		thread_unlock(td);
2209ad1e7d28SJulian Elischer         }
221035e6168fSJeff Roberson }
221135e6168fSJeff Roberson 
2212ae7a6b38SJeff Roberson /*
2213ae7a6b38SJeff Roberson  * Handle a stathz tick.  This is really only relevant for timeshare
2214ae7a6b38SJeff Roberson  * threads.
2215ae7a6b38SJeff Roberson  */
221635e6168fSJeff Roberson void
22177cf90fb3SJeff Roberson sched_clock(struct thread *td)
221835e6168fSJeff Roberson {
2219ad1e7d28SJulian Elischer 	struct tdq *tdq;
2220ad1e7d28SJulian Elischer 	struct td_sched *ts;
222135e6168fSJeff Roberson 
2222ae7a6b38SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
22233f872f85SJeff Roberson 	tdq = TDQ_SELF();
22247fcf154aSJeff Roberson #ifdef SMP
22257fcf154aSJeff Roberson 	/*
22267fcf154aSJeff Roberson 	 * We run the long term load balancer infrequently on the first cpu.
22277fcf154aSJeff Roberson 	 */
22287fcf154aSJeff Roberson 	if (balance_tdq == tdq) {
22297fcf154aSJeff Roberson 		if (balance_ticks && --balance_ticks == 0)
22307fcf154aSJeff Roberson 			sched_balance();
22317fcf154aSJeff Roberson 	}
22327fcf154aSJeff Roberson #endif
22333f872f85SJeff Roberson 	/*
22341690c6c1SJeff Roberson 	 * Save the old switch count so we have a record of the last ticks
22351690c6c1SJeff Roberson 	 * activity.   Initialize the new switch count based on our load.
22361690c6c1SJeff Roberson 	 * If there is some activity seed it to reflect that.
22371690c6c1SJeff Roberson 	 */
22381690c6c1SJeff Roberson 	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
22396c47aaaeSJeff Roberson 	tdq->tdq_switchcnt = tdq->tdq_load;
22401690c6c1SJeff Roberson 	/*
22413f872f85SJeff Roberson 	 * Advance the insert index once for each tick to ensure that all
22423f872f85SJeff Roberson 	 * threads get a chance to run.
22433f872f85SJeff Roberson 	 */
22443f872f85SJeff Roberson 	if (tdq->tdq_idx == tdq->tdq_ridx) {
22453f872f85SJeff Roberson 		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
22463f872f85SJeff Roberson 		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
22473f872f85SJeff Roberson 			tdq->tdq_ridx = tdq->tdq_idx;
22483f872f85SJeff Roberson 	}
22493f872f85SJeff Roberson 	ts = td->td_sched;
22507295465eSAlexander Motin 	sched_pctcpu_update(ts, 1);
2251fd0b8c78SJeff Roberson 	if (td->td_pri_class & PRI_FIFO_BIT)
2252a8949de2SJeff Roberson 		return;
2253c9a8cba4SJohn Baldwin 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2254a8949de2SJeff Roberson 		/*
2255fd0b8c78SJeff Roberson 		 * We used a tick; charge it to the thread so
2256fd0b8c78SJeff Roberson 		 * that we can compute our interactivity.
225715dc847eSJeff Roberson 		 */
2258ae7a6b38SJeff Roberson 		td->td_sched->ts_runtime += tickincr;
22598460a577SJohn Birrell 		sched_interact_update(td);
226073daf66fSJeff Roberson 		sched_priority(td);
2261fd0b8c78SJeff Roberson 	}
2262579895dfSAlexander Motin 
226335e6168fSJeff Roberson 	/*
2264579895dfSAlexander Motin 	 * Force a context switch if the current thread has used up a full
2265579895dfSAlexander Motin 	 * time slice (default is 100ms).
226635e6168fSJeff Roberson 	 */
22675e5c3873SJeff Roberson 	if (!TD_IS_IDLETHREAD(td) && ++ts->ts_slice >= tdq_slice(tdq)) {
22685e5c3873SJeff Roberson 		ts->ts_slice = 0;
22693d7f4117SAlexander Motin 		td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
227035e6168fSJeff Roberson 	}
2271579895dfSAlexander Motin }
227235e6168fSJeff Roberson 
2273ae7a6b38SJeff Roberson /*
22747295465eSAlexander Motin  * Called once per hz tick.
2275ae7a6b38SJeff Roberson  */
2276ae7a6b38SJeff Roberson void
2277a157e425SAlexander Motin sched_tick(int cnt)
2278ae7a6b38SJeff Roberson {
2279ae7a6b38SJeff Roberson 
2280ae7a6b38SJeff Roberson }
2281ae7a6b38SJeff Roberson 
2282ae7a6b38SJeff Roberson /*
2283ae7a6b38SJeff Roberson  * Return whether the current CPU has runnable tasks.  Used for in-kernel
2284ae7a6b38SJeff Roberson  * cooperative idle threads.
2285ae7a6b38SJeff Roberson  */
228635e6168fSJeff Roberson int
228735e6168fSJeff Roberson sched_runnable(void)
228835e6168fSJeff Roberson {
2289ad1e7d28SJulian Elischer 	struct tdq *tdq;
2290b90816f1SJeff Roberson 	int load;
229135e6168fSJeff Roberson 
2292b90816f1SJeff Roberson 	load = 1;
2293b90816f1SJeff Roberson 
2294ad1e7d28SJulian Elischer 	tdq = TDQ_SELF();
22953f741ca1SJeff Roberson 	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2296d2ad694cSJeff Roberson 		if (tdq->tdq_load > 0)
22973f741ca1SJeff Roberson 			goto out;
22983f741ca1SJeff Roberson 	} else
2299d2ad694cSJeff Roberson 		if (tdq->tdq_load - 1 > 0)
2300b90816f1SJeff Roberson 			goto out;
2301b90816f1SJeff Roberson 	load = 0;
2302b90816f1SJeff Roberson out:
2303b90816f1SJeff Roberson 	return (load);
230435e6168fSJeff Roberson }
230535e6168fSJeff Roberson 
2306ae7a6b38SJeff Roberson /*
2307ae7a6b38SJeff Roberson  * Choose the highest priority thread to run.  The thread is removed from
2308ae7a6b38SJeff Roberson  * the run-queue while running however the load remains.  For SMP we set
2309ae7a6b38SJeff Roberson  * the tdq in the global idle bitmask if it idles here.
2310ae7a6b38SJeff Roberson  */
23117a5e5e2aSJeff Roberson struct thread *
2312c9f25d8fSJeff Roberson sched_choose(void)
2313c9f25d8fSJeff Roberson {
23149727e637SJeff Roberson 	struct thread *td;
2315ae7a6b38SJeff Roberson 	struct tdq *tdq;
2316ae7a6b38SJeff Roberson 
2317ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2318ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
23199727e637SJeff Roberson 	td = tdq_choose(tdq);
23209727e637SJeff Roberson 	if (td) {
23219727e637SJeff Roberson 		tdq_runq_rem(tdq, td);
23220502fe2eSJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
23239727e637SJeff Roberson 		return (td);
232435e6168fSJeff Roberson 	}
23250502fe2eSJeff Roberson 	tdq->tdq_lowpri = PRI_MAX_IDLE;
232662fa74d9SJeff Roberson 	return (PCPU_GET(idlethread));
23277a5e5e2aSJeff Roberson }
23287a5e5e2aSJeff Roberson 
2329ae7a6b38SJeff Roberson /*
2330ae7a6b38SJeff Roberson  * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2331ae7a6b38SJeff Roberson  * we always request it once we exit a critical section.
2332ae7a6b38SJeff Roberson  */
2333ae7a6b38SJeff Roberson static inline void
2334ae7a6b38SJeff Roberson sched_setpreempt(struct thread *td)
23357a5e5e2aSJeff Roberson {
23367a5e5e2aSJeff Roberson 	struct thread *ctd;
23377a5e5e2aSJeff Roberson 	int cpri;
23387a5e5e2aSJeff Roberson 	int pri;
23397a5e5e2aSJeff Roberson 
2340ff256d9cSJeff Roberson 	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2341ff256d9cSJeff Roberson 
23427a5e5e2aSJeff Roberson 	ctd = curthread;
23437a5e5e2aSJeff Roberson 	pri = td->td_priority;
23447a5e5e2aSJeff Roberson 	cpri = ctd->td_priority;
2345ff256d9cSJeff Roberson 	if (pri < cpri)
2346ff256d9cSJeff Roberson 		ctd->td_flags |= TDF_NEEDRESCHED;
23477a5e5e2aSJeff Roberson 	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2348ae7a6b38SJeff Roberson 		return;
2349ff256d9cSJeff Roberson 	if (!sched_shouldpreempt(pri, cpri, 0))
2350ae7a6b38SJeff Roberson 		return;
23517a5e5e2aSJeff Roberson 	ctd->td_owepreempt = 1;
235235e6168fSJeff Roberson }
235335e6168fSJeff Roberson 
2354ae7a6b38SJeff Roberson /*
235573daf66fSJeff Roberson  * Add a thread to a thread queue.  Select the appropriate runq and add the
235673daf66fSJeff Roberson  * thread to it.  This is the internal function called when the tdq is
235773daf66fSJeff Roberson  * predetermined.
2358ae7a6b38SJeff Roberson  */
235935e6168fSJeff Roberson void
2360ae7a6b38SJeff Roberson tdq_add(struct tdq *tdq, struct thread *td, int flags)
236135e6168fSJeff Roberson {
2362c9f25d8fSJeff Roberson 
2363ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
23647a5e5e2aSJeff Roberson 	KASSERT((td->td_inhibitors == 0),
23657a5e5e2aSJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
23667a5e5e2aSJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
23677a5e5e2aSJeff Roberson 	    ("sched_add: bad thread state"));
2368b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
2369b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
2370ae7a6b38SJeff Roberson 
2371ae7a6b38SJeff Roberson 	if (td->td_priority < tdq->tdq_lowpri)
2372ae7a6b38SJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
23739727e637SJeff Roberson 	tdq_runq_add(tdq, td, flags);
23749727e637SJeff Roberson 	tdq_load_add(tdq, td);
2375ae7a6b38SJeff Roberson }
2376ae7a6b38SJeff Roberson 
2377ae7a6b38SJeff Roberson /*
2378ae7a6b38SJeff Roberson  * Select the target thread queue and add a thread to it.  Request
2379ae7a6b38SJeff Roberson  * preemption or IPI a remote processor if required.
2380ae7a6b38SJeff Roberson  */
2381ae7a6b38SJeff Roberson void
2382ae7a6b38SJeff Roberson sched_add(struct thread *td, int flags)
2383ae7a6b38SJeff Roberson {
2384ae7a6b38SJeff Roberson 	struct tdq *tdq;
23857b8bfa0dSJeff Roberson #ifdef SMP
2386ae7a6b38SJeff Roberson 	int cpu;
2387ae7a6b38SJeff Roberson #endif
23888f51ad55SJeff Roberson 
23898f51ad55SJeff Roberson 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
23908f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
23918f51ad55SJeff Roberson 	    sched_tdname(curthread));
23928f51ad55SJeff Roberson 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
23938f51ad55SJeff Roberson 	    KTR_ATTR_LINKED, sched_tdname(td));
2394b3e9e682SRyan Stone 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
2395b3e9e682SRyan Stone 	    flags & SRQ_PREEMPTED);
2396ae7a6b38SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2397ae7a6b38SJeff Roberson 	/*
2398ae7a6b38SJeff Roberson 	 * Recalculate the priority before we select the target cpu or
2399ae7a6b38SJeff Roberson 	 * run-queue.
2400ae7a6b38SJeff Roberson 	 */
2401ae7a6b38SJeff Roberson 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2402ae7a6b38SJeff Roberson 		sched_priority(td);
2403ae7a6b38SJeff Roberson #ifdef SMP
2404ae7a6b38SJeff Roberson 	/*
2405ae7a6b38SJeff Roberson 	 * Pick the destination cpu and if it isn't ours transfer to the
2406ae7a6b38SJeff Roberson 	 * target cpu.
2407ae7a6b38SJeff Roberson 	 */
24089727e637SJeff Roberson 	cpu = sched_pickcpu(td, flags);
24099727e637SJeff Roberson 	tdq = sched_setcpu(td, cpu, flags);
2410ae7a6b38SJeff Roberson 	tdq_add(tdq, td, flags);
241173daf66fSJeff Roberson 	if (cpu != PCPU_GET(cpuid)) {
24129727e637SJeff Roberson 		tdq_notify(tdq, td);
24137b8bfa0dSJeff Roberson 		return;
24147b8bfa0dSJeff Roberson 	}
2415ae7a6b38SJeff Roberson #else
2416ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2417ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
2418ae7a6b38SJeff Roberson 	/*
2419ae7a6b38SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
2420ae7a6b38SJeff Roberson 	 * to the scheduler's lock.
2421ae7a6b38SJeff Roberson 	 */
2422ae7a6b38SJeff Roberson 	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2423ae7a6b38SJeff Roberson 	tdq_add(tdq, td, flags);
24247b8bfa0dSJeff Roberson #endif
2425ae7a6b38SJeff Roberson 	if (!(flags & SRQ_YIELDING))
2426ae7a6b38SJeff Roberson 		sched_setpreempt(td);
242735e6168fSJeff Roberson }
242835e6168fSJeff Roberson 
2429ae7a6b38SJeff Roberson /*
2430ae7a6b38SJeff Roberson  * Remove a thread from a run-queue without running it.  This is used
2431ae7a6b38SJeff Roberson  * when we're stealing a thread from a remote queue.  Otherwise all threads
2432ae7a6b38SJeff Roberson  * exit by calling sched_exit_thread() and sched_throw() themselves.
2433ae7a6b38SJeff Roberson  */
243435e6168fSJeff Roberson void
24357cf90fb3SJeff Roberson sched_rem(struct thread *td)
243635e6168fSJeff Roberson {
2437ad1e7d28SJulian Elischer 	struct tdq *tdq;
24387cf90fb3SJeff Roberson 
24398f51ad55SJeff Roberson 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
24408f51ad55SJeff Roberson 	    "prio:%d", td->td_priority);
2441b3e9e682SRyan Stone 	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
24429727e637SJeff Roberson 	tdq = TDQ_CPU(td->td_sched->ts_cpu);
2443ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2444ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
24457a5e5e2aSJeff Roberson 	KASSERT(TD_ON_RUNQ(td),
2446ad1e7d28SJulian Elischer 	    ("sched_rem: thread not on run queue"));
24479727e637SJeff Roberson 	tdq_runq_rem(tdq, td);
24489727e637SJeff Roberson 	tdq_load_rem(tdq, td);
24497a5e5e2aSJeff Roberson 	TD_SET_CAN_RUN(td);
245062fa74d9SJeff Roberson 	if (td->td_priority == tdq->tdq_lowpri)
245162fa74d9SJeff Roberson 		tdq_setlowpri(tdq, NULL);
245235e6168fSJeff Roberson }
245335e6168fSJeff Roberson 
2454ae7a6b38SJeff Roberson /*
2455ae7a6b38SJeff Roberson  * Fetch cpu utilization information.  Updates on demand.
2456ae7a6b38SJeff Roberson  */
245735e6168fSJeff Roberson fixpt_t
24587cf90fb3SJeff Roberson sched_pctcpu(struct thread *td)
245935e6168fSJeff Roberson {
246035e6168fSJeff Roberson 	fixpt_t pctcpu;
2461ad1e7d28SJulian Elischer 	struct td_sched *ts;
246235e6168fSJeff Roberson 
246335e6168fSJeff Roberson 	pctcpu = 0;
2464ad1e7d28SJulian Elischer 	ts = td->td_sched;
2465ad1e7d28SJulian Elischer 	if (ts == NULL)
2466484288deSJeff Roberson 		return (0);
246735e6168fSJeff Roberson 
24683da35a0aSJohn Baldwin 	THREAD_LOCK_ASSERT(td, MA_OWNED);
24697295465eSAlexander Motin 	sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2470ad1e7d28SJulian Elischer 	if (ts->ts_ticks) {
247135e6168fSJeff Roberson 		int rtick;
247235e6168fSJeff Roberson 
247335e6168fSJeff Roberson 		/* How many rtick per second ? */
2474e7d50326SJeff Roberson 		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2475e7d50326SJeff Roberson 		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
247635e6168fSJeff Roberson 	}
247735e6168fSJeff Roberson 
247835e6168fSJeff Roberson 	return (pctcpu);
247935e6168fSJeff Roberson }
248035e6168fSJeff Roberson 
248162fa74d9SJeff Roberson /*
248262fa74d9SJeff Roberson  * Enforce affinity settings for a thread.  Called after adjustments to
248362fa74d9SJeff Roberson  * cpumask.
248462fa74d9SJeff Roberson  */
2485885d51a3SJeff Roberson void
2486885d51a3SJeff Roberson sched_affinity(struct thread *td)
2487885d51a3SJeff Roberson {
248862fa74d9SJeff Roberson #ifdef SMP
248962fa74d9SJeff Roberson 	struct td_sched *ts;
249062fa74d9SJeff Roberson 
249162fa74d9SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
249262fa74d9SJeff Roberson 	ts = td->td_sched;
249362fa74d9SJeff Roberson 	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
249462fa74d9SJeff Roberson 		return;
249553a6c8b3SJeff Roberson 	if (TD_ON_RUNQ(td)) {
249653a6c8b3SJeff Roberson 		sched_rem(td);
249753a6c8b3SJeff Roberson 		sched_add(td, SRQ_BORING);
249853a6c8b3SJeff Roberson 		return;
249953a6c8b3SJeff Roberson 	}
250062fa74d9SJeff Roberson 	if (!TD_IS_RUNNING(td))
250162fa74d9SJeff Roberson 		return;
250262fa74d9SJeff Roberson 	/*
25030f7a0ebdSMatthew D Fleming 	 * Force a switch before returning to userspace.  If the
25040f7a0ebdSMatthew D Fleming 	 * target thread is not running locally send an ipi to force
25050f7a0ebdSMatthew D Fleming 	 * the issue.
250662fa74d9SJeff Roberson 	 */
2507a8103ae8SJohn Baldwin 	td->td_flags |= TDF_NEEDRESCHED;
25080f7a0ebdSMatthew D Fleming 	if (td != curthread)
25090f7a0ebdSMatthew D Fleming 		ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
251062fa74d9SJeff Roberson #endif
2511885d51a3SJeff Roberson }
2512885d51a3SJeff Roberson 
2513ae7a6b38SJeff Roberson /*
2514ae7a6b38SJeff Roberson  * Bind a thread to a target cpu.
2515ae7a6b38SJeff Roberson  */
25169bacd788SJeff Roberson void
25179bacd788SJeff Roberson sched_bind(struct thread *td, int cpu)
25189bacd788SJeff Roberson {
2519ad1e7d28SJulian Elischer 	struct td_sched *ts;
25209bacd788SJeff Roberson 
2521c47f202bSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
25221d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
2523ad1e7d28SJulian Elischer 	ts = td->td_sched;
25246b2f763fSJeff Roberson 	if (ts->ts_flags & TSF_BOUND)
2525c95d2db2SJeff Roberson 		sched_unbind(td);
25260f7a0ebdSMatthew D Fleming 	KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2527ad1e7d28SJulian Elischer 	ts->ts_flags |= TSF_BOUND;
25286b2f763fSJeff Roberson 	sched_pin();
252980f86c9fSJeff Roberson 	if (PCPU_GET(cpuid) == cpu)
25309bacd788SJeff Roberson 		return;
25316b2f763fSJeff Roberson 	ts->ts_cpu = cpu;
25329bacd788SJeff Roberson 	/* When we return from mi_switch we'll be on the correct cpu. */
2533279f949eSPoul-Henning Kamp 	mi_switch(SW_VOL, NULL);
25349bacd788SJeff Roberson }
25359bacd788SJeff Roberson 
2536ae7a6b38SJeff Roberson /*
2537ae7a6b38SJeff Roberson  * Release a bound thread.
2538ae7a6b38SJeff Roberson  */
25399bacd788SJeff Roberson void
25409bacd788SJeff Roberson sched_unbind(struct thread *td)
25419bacd788SJeff Roberson {
2542e7d50326SJeff Roberson 	struct td_sched *ts;
2543e7d50326SJeff Roberson 
25447b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
25451d7830edSJohn Baldwin 	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
2546e7d50326SJeff Roberson 	ts = td->td_sched;
25476b2f763fSJeff Roberson 	if ((ts->ts_flags & TSF_BOUND) == 0)
25486b2f763fSJeff Roberson 		return;
2549e7d50326SJeff Roberson 	ts->ts_flags &= ~TSF_BOUND;
2550e7d50326SJeff Roberson 	sched_unpin();
25519bacd788SJeff Roberson }
25529bacd788SJeff Roberson 
255335e6168fSJeff Roberson int
2554ebccf1e3SJoseph Koshy sched_is_bound(struct thread *td)
2555ebccf1e3SJoseph Koshy {
25567b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2557ad1e7d28SJulian Elischer 	return (td->td_sched->ts_flags & TSF_BOUND);
2558ebccf1e3SJoseph Koshy }
2559ebccf1e3SJoseph Koshy 
2560ae7a6b38SJeff Roberson /*
2561ae7a6b38SJeff Roberson  * Basic yield call.
2562ae7a6b38SJeff Roberson  */
256336ec198bSDavid Xu void
256436ec198bSDavid Xu sched_relinquish(struct thread *td)
256536ec198bSDavid Xu {
25667b20fb19SJeff Roberson 	thread_lock(td);
25678df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
25687b20fb19SJeff Roberson 	thread_unlock(td);
256936ec198bSDavid Xu }
257036ec198bSDavid Xu 
2571ae7a6b38SJeff Roberson /*
2572ae7a6b38SJeff Roberson  * Return the total system load.
2573ae7a6b38SJeff Roberson  */
2574ebccf1e3SJoseph Koshy int
257533916c36SJeff Roberson sched_load(void)
257633916c36SJeff Roberson {
257733916c36SJeff Roberson #ifdef SMP
257833916c36SJeff Roberson 	int total;
257933916c36SJeff Roberson 	int i;
258033916c36SJeff Roberson 
258133916c36SJeff Roberson 	total = 0;
25823aa6d94eSJohn Baldwin 	CPU_FOREACH(i)
258362fa74d9SJeff Roberson 		total += TDQ_CPU(i)->tdq_sysload;
258433916c36SJeff Roberson 	return (total);
258533916c36SJeff Roberson #else
2586d2ad694cSJeff Roberson 	return (TDQ_SELF()->tdq_sysload);
258733916c36SJeff Roberson #endif
258833916c36SJeff Roberson }
258933916c36SJeff Roberson 
259033916c36SJeff Roberson int
259135e6168fSJeff Roberson sched_sizeof_proc(void)
259235e6168fSJeff Roberson {
259335e6168fSJeff Roberson 	return (sizeof(struct proc));
259435e6168fSJeff Roberson }
259535e6168fSJeff Roberson 
259635e6168fSJeff Roberson int
259735e6168fSJeff Roberson sched_sizeof_thread(void)
259835e6168fSJeff Roberson {
259935e6168fSJeff Roberson 	return (sizeof(struct thread) + sizeof(struct td_sched));
260035e6168fSJeff Roberson }
2601b41f1452SDavid Xu 
260209c8a4ccSJeff Roberson #ifdef SMP
260309c8a4ccSJeff Roberson #define	TDQ_IDLESPIN(tdq)						\
260409c8a4ccSJeff Roberson     ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
260509c8a4ccSJeff Roberson #else
260609c8a4ccSJeff Roberson #define	TDQ_IDLESPIN(tdq)	1
260709c8a4ccSJeff Roberson #endif
260809c8a4ccSJeff Roberson 
26097a5e5e2aSJeff Roberson /*
26107a5e5e2aSJeff Roberson  * The actual idle process.
26117a5e5e2aSJeff Roberson  */
26127a5e5e2aSJeff Roberson void
26137a5e5e2aSJeff Roberson sched_idletd(void *dummy)
26147a5e5e2aSJeff Roberson {
26157a5e5e2aSJeff Roberson 	struct thread *td;
2616ae7a6b38SJeff Roberson 	struct tdq *tdq;
26172c27cb3aSAlexander Motin 	int oldswitchcnt, switchcnt;
26181690c6c1SJeff Roberson 	int i;
26197a5e5e2aSJeff Roberson 
26207b55ab05SJeff Roberson 	mtx_assert(&Giant, MA_NOTOWNED);
26217a5e5e2aSJeff Roberson 	td = curthread;
2622ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2623ba96d2d8SJohn Baldwin 	THREAD_NO_SLEEPING();
26242c27cb3aSAlexander Motin 	oldswitchcnt = -1;
2625ae7a6b38SJeff Roberson 	for (;;) {
26262c27cb3aSAlexander Motin 		if (tdq->tdq_load) {
26272c27cb3aSAlexander Motin 			thread_lock(td);
26282c27cb3aSAlexander Motin 			mi_switch(SW_VOL | SWT_IDLE, NULL);
26292c27cb3aSAlexander Motin 			thread_unlock(td);
26302c27cb3aSAlexander Motin 		}
26312c27cb3aSAlexander Motin 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2632ae7a6b38SJeff Roberson #ifdef SMP
26332c27cb3aSAlexander Motin 		if (switchcnt != oldswitchcnt) {
26342c27cb3aSAlexander Motin 			oldswitchcnt = switchcnt;
26351690c6c1SJeff Roberson 			if (tdq_idled(tdq) == 0)
26361690c6c1SJeff Roberson 				continue;
26372c27cb3aSAlexander Motin 		}
26381690c6c1SJeff Roberson 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
26392fd4047fSAlexander Motin #else
26402fd4047fSAlexander Motin 		oldswitchcnt = switchcnt;
26412fd4047fSAlexander Motin #endif
26421690c6c1SJeff Roberson 		/*
26431690c6c1SJeff Roberson 		 * If we're switching very frequently, spin while checking
26441690c6c1SJeff Roberson 		 * for load rather than entering a low power state that
26457b55ab05SJeff Roberson 		 * may require an IPI.  However, don't do any busy
26467b55ab05SJeff Roberson 		 * loops while on SMT machines as this simply steals
26477b55ab05SJeff Roberson 		 * cycles from cores doing useful work.
26481690c6c1SJeff Roberson 		 */
264909c8a4ccSJeff Roberson 		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
26501690c6c1SJeff Roberson 			for (i = 0; i < sched_idlespins; i++) {
26511690c6c1SJeff Roberson 				if (tdq->tdq_load)
26521690c6c1SJeff Roberson 					break;
26531690c6c1SJeff Roberson 				cpu_spinwait();
26541690c6c1SJeff Roberson 			}
26551690c6c1SJeff Roberson 		}
26562c27cb3aSAlexander Motin 
26572c27cb3aSAlexander Motin 		/* If there was context switch during spin, restart it. */
26586c47aaaeSJeff Roberson 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
26592c27cb3aSAlexander Motin 		if (tdq->tdq_load != 0 || switchcnt != oldswitchcnt)
26602c27cb3aSAlexander Motin 			continue;
26612c27cb3aSAlexander Motin 
26622c27cb3aSAlexander Motin 		/* Run main MD idle handler. */
26639f9ad565SAlexander Motin 		tdq->tdq_cpu_idle = 1;
266479654969SAlexander Motin 		/*
266579654969SAlexander Motin 		 * Make sure that tdq_cpu_idle update is globally visible
266679654969SAlexander Motin 		 * before cpu_idle() read tdq_load.  The order is important
266779654969SAlexander Motin 		 * to avoid race with tdq_notify.
266879654969SAlexander Motin 		 */
26697e9b58eaSAlexander Motin 		mb();
26702c27cb3aSAlexander Motin 		cpu_idle(switchcnt * 4 > sched_idlespinthresh);
26719f9ad565SAlexander Motin 		tdq->tdq_cpu_idle = 0;
26722c27cb3aSAlexander Motin 
26732c27cb3aSAlexander Motin 		/*
26742c27cb3aSAlexander Motin 		 * Account thread-less hardware interrupts and
26752c27cb3aSAlexander Motin 		 * other wakeup reasons equal to context switches.
26762c27cb3aSAlexander Motin 		 */
26772c27cb3aSAlexander Motin 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
26782c27cb3aSAlexander Motin 		if (switchcnt != oldswitchcnt)
26792c27cb3aSAlexander Motin 			continue;
26802c27cb3aSAlexander Motin 		tdq->tdq_switchcnt++;
26812c27cb3aSAlexander Motin 		oldswitchcnt++;
2682ae7a6b38SJeff Roberson 	}
2683b41f1452SDavid Xu }
2684e7d50326SJeff Roberson 
26857b20fb19SJeff Roberson /*
26867b20fb19SJeff Roberson  * A CPU is entering for the first time or a thread is exiting.
26877b20fb19SJeff Roberson  */
26887b20fb19SJeff Roberson void
26897b20fb19SJeff Roberson sched_throw(struct thread *td)
26907b20fb19SJeff Roberson {
269159c68134SJeff Roberson 	struct thread *newtd;
2692ae7a6b38SJeff Roberson 	struct tdq *tdq;
2693ae7a6b38SJeff Roberson 
2694ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
26957b20fb19SJeff Roberson 	if (td == NULL) {
2696ae7a6b38SJeff Roberson 		/* Correct spinlock nesting and acquire the correct lock. */
2697ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
26987b20fb19SJeff Roberson 		spinlock_exit();
26997e3a96eaSJohn Baldwin 		PCPU_SET(switchtime, cpu_ticks());
27007e3a96eaSJohn Baldwin 		PCPU_SET(switchticks, ticks);
27017b20fb19SJeff Roberson 	} else {
2702ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
27039727e637SJeff Roberson 		tdq_load_rem(tdq, td);
2704eea4f254SJeff Roberson 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
27057b20fb19SJeff Roberson 	}
27067b20fb19SJeff Roberson 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
270759c68134SJeff Roberson 	newtd = choosethread();
270859c68134SJeff Roberson 	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
270959c68134SJeff Roberson 	cpu_throw(td, newtd);		/* doesn't return */
27107b20fb19SJeff Roberson }
27117b20fb19SJeff Roberson 
2712ae7a6b38SJeff Roberson /*
2713ae7a6b38SJeff Roberson  * This is called from fork_exit().  Just acquire the correct locks and
2714ae7a6b38SJeff Roberson  * let fork do the rest of the work.
2715ae7a6b38SJeff Roberson  */
27167b20fb19SJeff Roberson void
2717fe54587fSJeff Roberson sched_fork_exit(struct thread *td)
27187b20fb19SJeff Roberson {
2719ae7a6b38SJeff Roberson 	struct tdq *tdq;
2720ae7a6b38SJeff Roberson 	int cpuid;
27217b20fb19SJeff Roberson 
27227b20fb19SJeff Roberson 	/*
27237b20fb19SJeff Roberson 	 * Finish setting up thread glue so that it begins execution in a
2724ae7a6b38SJeff Roberson 	 * non-nested critical section with the scheduler lock held.
27257b20fb19SJeff Roberson 	 */
2726ae7a6b38SJeff Roberson 	cpuid = PCPU_GET(cpuid);
2727ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpuid);
2728ae7a6b38SJeff Roberson 	if (TD_IS_IDLETHREAD(td))
2729ae7a6b38SJeff Roberson 		td->td_lock = TDQ_LOCKPTR(tdq);
2730ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2731ae7a6b38SJeff Roberson 	td->td_oncpu = cpuid;
273259c68134SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2733eea4f254SJeff Roberson 	lock_profile_obtain_lock_success(
2734eea4f254SJeff Roberson 	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
27357b20fb19SJeff Roberson }
27367b20fb19SJeff Roberson 
27378f51ad55SJeff Roberson /*
27388f51ad55SJeff Roberson  * Create on first use to catch odd startup conditons.
27398f51ad55SJeff Roberson  */
27408f51ad55SJeff Roberson char *
27418f51ad55SJeff Roberson sched_tdname(struct thread *td)
27428f51ad55SJeff Roberson {
27438f51ad55SJeff Roberson #ifdef KTR
27448f51ad55SJeff Roberson 	struct td_sched *ts;
27458f51ad55SJeff Roberson 
27468f51ad55SJeff Roberson 	ts = td->td_sched;
27478f51ad55SJeff Roberson 	if (ts->ts_name[0] == '\0')
27488f51ad55SJeff Roberson 		snprintf(ts->ts_name, sizeof(ts->ts_name),
27498f51ad55SJeff Roberson 		    "%s tid %d", td->td_name, td->td_tid);
27508f51ad55SJeff Roberson 	return (ts->ts_name);
27518f51ad55SJeff Roberson #else
27528f51ad55SJeff Roberson 	return (td->td_name);
27538f51ad55SJeff Roberson #endif
27548f51ad55SJeff Roberson }
27558f51ad55SJeff Roberson 
275644ad5475SJohn Baldwin #ifdef KTR
275744ad5475SJohn Baldwin void
275844ad5475SJohn Baldwin sched_clear_tdname(struct thread *td)
275944ad5475SJohn Baldwin {
276044ad5475SJohn Baldwin 	struct td_sched *ts;
276144ad5475SJohn Baldwin 
276244ad5475SJohn Baldwin 	ts = td->td_sched;
276344ad5475SJohn Baldwin 	ts->ts_name[0] = '\0';
276444ad5475SJohn Baldwin }
276544ad5475SJohn Baldwin #endif
276644ad5475SJohn Baldwin 
276707095abfSIvan Voras #ifdef SMP
276807095abfSIvan Voras 
276907095abfSIvan Voras /*
277007095abfSIvan Voras  * Build the CPU topology dump string. Is recursively called to collect
277107095abfSIvan Voras  * the topology tree.
277207095abfSIvan Voras  */
277307095abfSIvan Voras static int
277407095abfSIvan Voras sysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
277507095abfSIvan Voras     int indent)
277607095abfSIvan Voras {
277771a19bdcSAttilio Rao 	char cpusetbuf[CPUSETBUFSIZ];
277807095abfSIvan Voras 	int i, first;
277907095abfSIvan Voras 
278007095abfSIvan Voras 	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
278119b8a6dbSAndriy Gapon 	    "", 1 + indent / 2, cg->cg_level);
278271a19bdcSAttilio Rao 	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
278371a19bdcSAttilio Rao 	    cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
278407095abfSIvan Voras 	first = TRUE;
278507095abfSIvan Voras 	for (i = 0; i < MAXCPU; i++) {
278671a19bdcSAttilio Rao 		if (CPU_ISSET(i, &cg->cg_mask)) {
278707095abfSIvan Voras 			if (!first)
278807095abfSIvan Voras 				sbuf_printf(sb, ", ");
278907095abfSIvan Voras 			else
279007095abfSIvan Voras 				first = FALSE;
279107095abfSIvan Voras 			sbuf_printf(sb, "%d", i);
279207095abfSIvan Voras 		}
279307095abfSIvan Voras 	}
279407095abfSIvan Voras 	sbuf_printf(sb, "</cpu>\n");
279507095abfSIvan Voras 
279607095abfSIvan Voras 	if (cg->cg_flags != 0) {
2797611daf7eSIvan Voras 		sbuf_printf(sb, "%*s <flags>", indent, "");
279807095abfSIvan Voras 		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
27995368befbSIvan Voras 			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
2800a401f2d0SIvan Voras 		if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
2801a401f2d0SIvan Voras 			sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
28027b55ab05SJeff Roberson 		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
2803a401f2d0SIvan Voras 			sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
280407095abfSIvan Voras 		sbuf_printf(sb, "</flags>\n");
2805611daf7eSIvan Voras 	}
280607095abfSIvan Voras 
280707095abfSIvan Voras 	if (cg->cg_children > 0) {
280807095abfSIvan Voras 		sbuf_printf(sb, "%*s <children>\n", indent, "");
280907095abfSIvan Voras 		for (i = 0; i < cg->cg_children; i++)
281007095abfSIvan Voras 			sysctl_kern_sched_topology_spec_internal(sb,
281107095abfSIvan Voras 			    &cg->cg_child[i], indent+2);
281207095abfSIvan Voras 		sbuf_printf(sb, "%*s </children>\n", indent, "");
281307095abfSIvan Voras 	}
281407095abfSIvan Voras 	sbuf_printf(sb, "%*s</group>\n", indent, "");
281507095abfSIvan Voras 	return (0);
281607095abfSIvan Voras }
281707095abfSIvan Voras 
281807095abfSIvan Voras /*
281907095abfSIvan Voras  * Sysctl handler for retrieving topology dump. It's a wrapper for
282007095abfSIvan Voras  * the recursive sysctl_kern_smp_topology_spec_internal().
282107095abfSIvan Voras  */
282207095abfSIvan Voras static int
282307095abfSIvan Voras sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
282407095abfSIvan Voras {
282507095abfSIvan Voras 	struct sbuf *topo;
282607095abfSIvan Voras 	int err;
282707095abfSIvan Voras 
282807095abfSIvan Voras 	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
282907095abfSIvan Voras 
2830aa880b90SIvan Voras 	topo = sbuf_new(NULL, NULL, 500, SBUF_AUTOEXTEND);
283107095abfSIvan Voras 	if (topo == NULL)
283207095abfSIvan Voras 		return (ENOMEM);
283307095abfSIvan Voras 
283407095abfSIvan Voras 	sbuf_printf(topo, "<groups>\n");
283507095abfSIvan Voras 	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
283607095abfSIvan Voras 	sbuf_printf(topo, "</groups>\n");
283707095abfSIvan Voras 
283807095abfSIvan Voras 	if (err == 0) {
283907095abfSIvan Voras 		sbuf_finish(topo);
284007095abfSIvan Voras 		err = SYSCTL_OUT(req, sbuf_data(topo), sbuf_len(topo));
284107095abfSIvan Voras 	}
284207095abfSIvan Voras 	sbuf_delete(topo);
284307095abfSIvan Voras 	return (err);
284407095abfSIvan Voras }
2845b67cc292SDavid Xu 
284607095abfSIvan Voras #endif
284707095abfSIvan Voras 
2848579895dfSAlexander Motin static int
2849579895dfSAlexander Motin sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
2850579895dfSAlexander Motin {
2851579895dfSAlexander Motin 	int error, new_val, period;
2852579895dfSAlexander Motin 
2853579895dfSAlexander Motin 	period = 1000000 / realstathz;
2854579895dfSAlexander Motin 	new_val = period * sched_slice;
2855579895dfSAlexander Motin 	error = sysctl_handle_int(oidp, &new_val, 0, req);
2856579895dfSAlexander Motin 	if (error != 0 || req->newptr == NULL)
2857579895dfSAlexander Motin 		return (error);
2858579895dfSAlexander Motin 	if (new_val <= 0)
2859579895dfSAlexander Motin 		return (EINVAL);
286037f4e025SAlexander Motin 	sched_slice = imax(1, (new_val + period / 2) / period);
28615e5c3873SJeff Roberson 	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
286237f4e025SAlexander Motin 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
286337f4e025SAlexander Motin 	    realstathz);
2864579895dfSAlexander Motin 	return (0);
2865579895dfSAlexander Motin }
2866579895dfSAlexander Motin 
28679727e637SJeff Roberson SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2868ae7a6b38SJeff Roberson SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2869e7d50326SJeff Roberson     "Scheduler name");
2870579895dfSAlexander Motin SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
2871579895dfSAlexander Motin     NULL, 0, sysctl_kern_quantum, "I",
287237f4e025SAlexander Motin     "Quantum for timeshare threads in microseconds");
2873ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
287437f4e025SAlexander Motin     "Quantum for timeshare threads in stathz ticks");
2875ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2876ae7a6b38SJeff Roberson     "Interactivity score threshold");
287737f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW,
287837f4e025SAlexander Motin     &preempt_thresh, 0,
287937f4e025SAlexander Motin     "Maximal (lowest) priority for preemption");
288037f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost, 0,
288137f4e025SAlexander Motin     "Assign static kernel priorities to sleeping threads");
288237f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins, 0,
288337f4e025SAlexander Motin     "Number of times idle thread will spin waiting for new work");
288437f4e025SAlexander Motin SYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW,
288537f4e025SAlexander Motin     &sched_idlespinthresh, 0,
288637f4e025SAlexander Motin     "Threshold before we will permit idle thread spinning");
28877b8bfa0dSJeff Roberson #ifdef SMP
2888ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2889ae7a6b38SJeff Roberson     "Number of hz ticks to keep thread affinity for");
2890ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2891ae7a6b38SJeff Roberson     "Enables the long-term load balancer");
28927fcf154aSJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
28937fcf154aSJeff Roberson     &balance_interval, 0,
2894579895dfSAlexander Motin     "Average period in stathz ticks to run the long-term balancer");
2895ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2896ae7a6b38SJeff Roberson     "Attempts to steal work from other cores before idling");
289728994a58SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
289837f4e025SAlexander Motin     "Minimum load on remote CPU before we'll steal");
289907095abfSIvan Voras SYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
290007095abfSIvan Voras     CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
290107095abfSIvan Voras     "XML dump of detected CPU topology");
29027b8bfa0dSJeff Roberson #endif
2903e7d50326SJeff Roberson 
290454b0e65fSJeff Roberson /* ps compat.  All cpu percentages from ULE are weighted. */
2905a5423ea3SJeff Roberson static int ccpu = 0;
2906e7d50326SJeff Roberson SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2907