xref: /freebsd/sys/kern/sched_ule.c (revision 6f5f25e5218f31a7928d694c7e3afa20a38c40b5)
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>
39677b542eSDavid E. O'Brien __FBSDID("$FreeBSD$");
40677b542eSDavid E. O'Brien 
414da0d332SPeter Wemm #include "opt_hwpmc_hooks.h"
426f5f25e5SJohn Birrell #include "opt_kdtrace.h"
434da0d332SPeter Wemm #include "opt_sched.h"
449923b511SScott Long 
4535e6168fSJeff Roberson #include <sys/param.h>
4635e6168fSJeff Roberson #include <sys/systm.h>
472c3490b1SMarcel Moolenaar #include <sys/kdb.h>
4835e6168fSJeff Roberson #include <sys/kernel.h>
4935e6168fSJeff Roberson #include <sys/ktr.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>
5635e6168fSJeff Roberson #include <sys/smp.h>
5735e6168fSJeff Roberson #include <sys/sx.h>
5835e6168fSJeff Roberson #include <sys/sysctl.h>
5935e6168fSJeff Roberson #include <sys/sysproto.h>
60f5c157d9SJohn Baldwin #include <sys/turnstile.h>
613db720fdSDavid Xu #include <sys/umtx.h>
6235e6168fSJeff Roberson #include <sys/vmmeter.h>
6362fa74d9SJeff Roberson #include <sys/cpuset.h>
6435e6168fSJeff Roberson #ifdef KTRACE
6535e6168fSJeff Roberson #include <sys/uio.h>
6635e6168fSJeff Roberson #include <sys/ktrace.h>
6735e6168fSJeff Roberson #endif
6835e6168fSJeff Roberson 
69ebccf1e3SJoseph Koshy #ifdef HWPMC_HOOKS
70ebccf1e3SJoseph Koshy #include <sys/pmckern.h>
71ebccf1e3SJoseph Koshy #endif
72ebccf1e3SJoseph Koshy 
736f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
746f5f25e5SJohn Birrell #include <sys/dtrace_bsd.h>
756f5f25e5SJohn Birrell int				dtrace_vtime_active;
766f5f25e5SJohn Birrell dtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
776f5f25e5SJohn Birrell #endif
786f5f25e5SJohn Birrell 
7935e6168fSJeff Roberson #include <machine/cpu.h>
8022bf7d9aSJeff Roberson #include <machine/smp.h>
8135e6168fSJeff Roberson 
82495168baSMarcel Moolenaar #if defined(__sparc64__) || defined(__mips__)
8302e2d6b4SJeff Roberson #error "This architecture is not currently compatible with ULE"
847a5e5e2aSJeff Roberson #endif
857a5e5e2aSJeff Roberson 
86ae7a6b38SJeff Roberson #define	KTR_ULE	0
8714618990SJeff Roberson 
886b2f763fSJeff Roberson /*
89ae7a6b38SJeff Roberson  * Thread scheduler specific section.  All fields are protected
90ae7a6b38SJeff Roberson  * by the thread lock.
91ed062c8dSJulian Elischer  */
92ad1e7d28SJulian Elischer struct td_sched {
93ae7a6b38SJeff Roberson 	struct runq	*ts_runq;	/* Run-queue we're queued on. */
94ae7a6b38SJeff Roberson 	short		ts_flags;	/* TSF_* flags. */
95ad1e7d28SJulian Elischer 	u_char		ts_cpu;		/* CPU that we have affinity for. */
9673daf66fSJeff Roberson 	int		ts_rltick;	/* Real last tick, for affinity. */
97ae7a6b38SJeff Roberson 	int		ts_slice;	/* Ticks of slice remaining. */
98ae7a6b38SJeff Roberson 	u_int		ts_slptime;	/* Number of ticks we vol. slept */
99ae7a6b38SJeff Roberson 	u_int		ts_runtime;	/* Number of ticks we were running */
100ad1e7d28SJulian Elischer 	int		ts_ltick;	/* Last tick that we were running on */
101ad1e7d28SJulian Elischer 	int		ts_ftick;	/* First tick that we were running on */
102ad1e7d28SJulian Elischer 	int		ts_ticks;	/* Tick count */
103ed062c8dSJulian Elischer };
104ad1e7d28SJulian Elischer /* flags kept in ts_flags */
1057b8bfa0dSJeff Roberson #define	TSF_BOUND	0x0001		/* Thread can not migrate. */
1067b8bfa0dSJeff Roberson #define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
10735e6168fSJeff Roberson 
108ad1e7d28SJulian Elischer static struct td_sched td_sched0;
10935e6168fSJeff Roberson 
11062fa74d9SJeff Roberson #define	THREAD_CAN_MIGRATE(td)	((td)->td_pinned == 0)
11162fa74d9SJeff Roberson #define	THREAD_CAN_SCHED(td, cpu)	\
11262fa74d9SJeff Roberson     CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
11362fa74d9SJeff Roberson 
11435e6168fSJeff Roberson /*
115e7d50326SJeff Roberson  * Cpu percentage computation macros and defines.
116e1f89c22SJeff Roberson  *
117e7d50326SJeff Roberson  * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
118e7d50326SJeff Roberson  * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
1198ab80cf0SJeff Roberson  * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
120e7d50326SJeff Roberson  * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
121e7d50326SJeff Roberson  * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
122e7d50326SJeff Roberson  * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
12335e6168fSJeff Roberson  */
124e7d50326SJeff Roberson #define	SCHED_TICK_SECS		10
125e7d50326SJeff Roberson #define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
1268ab80cf0SJeff Roberson #define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
127e7d50326SJeff Roberson #define	SCHED_TICK_SHIFT	10
128e7d50326SJeff Roberson #define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
129eddb4efaSJeff Roberson #define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
13035e6168fSJeff Roberson 
13135e6168fSJeff Roberson /*
132e7d50326SJeff Roberson  * These macros determine priorities for non-interactive threads.  They are
133e7d50326SJeff Roberson  * assigned a priority based on their recent cpu utilization as expressed
134e7d50326SJeff Roberson  * by the ratio of ticks to the tick total.  NHALF priorities at the start
135e7d50326SJeff Roberson  * and end of the MIN to MAX timeshare range are only reachable with negative
136e7d50326SJeff Roberson  * or positive nice respectively.
137e7d50326SJeff Roberson  *
138e7d50326SJeff Roberson  * PRI_RANGE:	Priority range for utilization dependent priorities.
139e7d50326SJeff Roberson  * PRI_NRESV:	Number of nice values.
140e7d50326SJeff Roberson  * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
141e7d50326SJeff Roberson  * PRI_NICE:	Determines the part of the priority inherited from nice.
142e7d50326SJeff Roberson  */
143e7d50326SJeff Roberson #define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
144e7d50326SJeff Roberson #define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
145e7d50326SJeff Roberson #define	SCHED_PRI_MIN		(PRI_MIN_TIMESHARE + SCHED_PRI_NHALF)
146e7d50326SJeff Roberson #define	SCHED_PRI_MAX		(PRI_MAX_TIMESHARE - SCHED_PRI_NHALF)
147dda713dfSJeff Roberson #define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN)
148e7d50326SJeff Roberson #define	SCHED_PRI_TICKS(ts)						\
149e7d50326SJeff Roberson     (SCHED_TICK_HZ((ts)) /						\
1501e516cf5SJeff Roberson     (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
151e7d50326SJeff Roberson #define	SCHED_PRI_NICE(nice)	(nice)
152e7d50326SJeff Roberson 
153e7d50326SJeff Roberson /*
154e7d50326SJeff Roberson  * These determine the interactivity of a process.  Interactivity differs from
155e7d50326SJeff Roberson  * cpu utilization in that it expresses the voluntary time slept vs time ran
156e7d50326SJeff Roberson  * while cpu utilization includes all time not running.  This more accurately
157e7d50326SJeff Roberson  * models the intent of the thread.
15835e6168fSJeff Roberson  *
159407b0157SJeff Roberson  * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
160407b0157SJeff Roberson  *		before throttling back.
161d322132cSJeff Roberson  * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
162210491d3SJeff Roberson  * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
163e1f89c22SJeff Roberson  * INTERACT_THRESH:	Threshhold for placement on the current runq.
16435e6168fSJeff Roberson  */
165e7d50326SJeff Roberson #define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
166e7d50326SJeff Roberson #define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
167210491d3SJeff Roberson #define	SCHED_INTERACT_MAX	(100)
168210491d3SJeff Roberson #define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
1694c9612c6SJeff Roberson #define	SCHED_INTERACT_THRESH	(30)
170e1f89c22SJeff Roberson 
17135e6168fSJeff Roberson /*
172e7d50326SJeff Roberson  * tickincr:		Converts a stathz tick into a hz domain scaled by
173e7d50326SJeff Roberson  *			the shift factor.  Without the shift the error rate
174e7d50326SJeff Roberson  *			due to rounding would be unacceptably high.
175e7d50326SJeff Roberson  * realstathz:		stathz is sometimes 0 and run off of hz.
176e7d50326SJeff Roberson  * sched_slice:		Runtime of each thread before rescheduling.
177ae7a6b38SJeff Roberson  * preempt_thresh:	Priority threshold for preemption and remote IPIs.
17835e6168fSJeff Roberson  */
179e7d50326SJeff Roberson static int sched_interact = SCHED_INTERACT_THRESH;
180e7d50326SJeff Roberson static int realstathz;
181e7d50326SJeff Roberson static int tickincr;
18273daf66fSJeff Roberson static int sched_slice = 1;
18302e2d6b4SJeff Roberson #ifdef PREEMPTION
18402e2d6b4SJeff Roberson #ifdef FULL_PREEMPTION
18502e2d6b4SJeff Roberson static int preempt_thresh = PRI_MAX_IDLE;
18602e2d6b4SJeff Roberson #else
187ae7a6b38SJeff Roberson static int preempt_thresh = PRI_MIN_KERN;
18802e2d6b4SJeff Roberson #endif
18902e2d6b4SJeff Roberson #else
19002e2d6b4SJeff Roberson static int preempt_thresh = 0;
19102e2d6b4SJeff Roberson #endif
1920502fe2eSJeff Roberson static int static_boost = PRI_MIN_TIMESHARE;
1931690c6c1SJeff Roberson static int sched_idlespins = 10000;
1941690c6c1SJeff Roberson static int sched_idlespinthresh = 4;
195ae7a6b38SJeff Roberson 
19635e6168fSJeff Roberson /*
197ae7a6b38SJeff Roberson  * tdq - per processor runqs and statistics.  All fields are protected by the
198ae7a6b38SJeff Roberson  * tdq_lock.  The load and lowpri may be accessed without to avoid excess
199ae7a6b38SJeff Roberson  * locking in sched_pickcpu();
20035e6168fSJeff Roberson  */
201ad1e7d28SJulian Elischer struct tdq {
20273daf66fSJeff Roberson 	/* Ordered to improve efficiency of cpu_search() and switch(). */
20362fa74d9SJeff Roberson 	struct mtx	tdq_lock;		/* run queue lock. */
20473daf66fSJeff Roberson 	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
2051690c6c1SJeff Roberson 	volatile int	tdq_load;		/* Aggregate load. */
20673daf66fSJeff Roberson 	int		tdq_sysload;		/* For loadavg, !ITHD load. */
20773daf66fSJeff Roberson 	int		tdq_transferable;	/* Transferable thread count. */
2081690c6c1SJeff Roberson 	volatile int	tdq_idlestate;		/* State of the idle thread. */
2091690c6c1SJeff Roberson 	short		tdq_switchcnt;		/* Switches this tick. */
2101690c6c1SJeff Roberson 	short		tdq_oldswitchcnt;	/* Switches last tick. */
21173daf66fSJeff Roberson 	u_char		tdq_lowpri;		/* Lowest priority thread. */
21273daf66fSJeff Roberson 	u_char		tdq_ipipending;		/* IPI pending. */
21373daf66fSJeff Roberson 	u_char		tdq_idx;		/* Current insert index. */
21473daf66fSJeff Roberson 	u_char		tdq_ridx;		/* Current removal index. */
215e7d50326SJeff Roberson 	struct runq	tdq_realtime;		/* real-time run queue. */
216ae7a6b38SJeff Roberson 	struct runq	tdq_timeshare;		/* timeshare run queue. */
217ae7a6b38SJeff Roberson 	struct runq	tdq_idle;		/* Queue of IDLE threads. */
21862fa74d9SJeff Roberson 	char		tdq_name[sizeof("sched lock") + 6];
219ae7a6b38SJeff Roberson } __aligned(64);
22035e6168fSJeff Roberson 
2211690c6c1SJeff Roberson /* Idle thread states and config. */
2221690c6c1SJeff Roberson #define	TDQ_RUNNING	1
2231690c6c1SJeff Roberson #define	TDQ_IDLE	2
2247b8bfa0dSJeff Roberson 
22580f86c9fSJeff Roberson #ifdef SMP
22662fa74d9SJeff Roberson struct cpu_group *cpu_top;
2277b8bfa0dSJeff Roberson 
22862fa74d9SJeff Roberson #define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
22962fa74d9SJeff Roberson #define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
2307b8bfa0dSJeff Roberson 
2317b8bfa0dSJeff Roberson /*
2327b8bfa0dSJeff Roberson  * Run-time tunables.
2337b8bfa0dSJeff Roberson  */
23428994a58SJeff Roberson static int rebalance = 1;
2357fcf154aSJeff Roberson static int balance_interval = 128;	/* Default set in sched_initticks(). */
2367b8bfa0dSJeff Roberson static int affinity;
2377fcf154aSJeff Roberson static int steal_htt = 1;
23828994a58SJeff Roberson static int steal_idle = 1;
23928994a58SJeff Roberson static int steal_thresh = 2;
24080f86c9fSJeff Roberson 
24135e6168fSJeff Roberson /*
242d2ad694cSJeff Roberson  * One thread queue per processor.
24335e6168fSJeff Roberson  */
244ad1e7d28SJulian Elischer static struct tdq	tdq_cpu[MAXCPU];
2457fcf154aSJeff Roberson static struct tdq	*balance_tdq;
2467fcf154aSJeff Roberson static int balance_ticks;
247dc03363dSJeff Roberson 
248ad1e7d28SJulian Elischer #define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
249ad1e7d28SJulian Elischer #define	TDQ_CPU(x)	(&tdq_cpu[(x)])
250c47f202bSJeff Roberson #define	TDQ_ID(x)	((int)((x) - tdq_cpu))
25180f86c9fSJeff Roberson #else	/* !SMP */
252ad1e7d28SJulian Elischer static struct tdq	tdq_cpu;
253dc03363dSJeff Roberson 
25436b36916SJeff Roberson #define	TDQ_ID(x)	(0)
255ad1e7d28SJulian Elischer #define	TDQ_SELF()	(&tdq_cpu)
256ad1e7d28SJulian Elischer #define	TDQ_CPU(x)	(&tdq_cpu)
2570a016a05SJeff Roberson #endif
25835e6168fSJeff Roberson 
259ae7a6b38SJeff Roberson #define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
260ae7a6b38SJeff Roberson #define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
261ae7a6b38SJeff Roberson #define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
262ae7a6b38SJeff Roberson #define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
26362fa74d9SJeff Roberson #define	TDQ_LOCKPTR(t)		(&(t)->tdq_lock)
264ae7a6b38SJeff Roberson 
2658460a577SJohn Birrell static void sched_priority(struct thread *);
26621381d1bSJeff Roberson static void sched_thread_priority(struct thread *, u_char);
2678460a577SJohn Birrell static int sched_interact_score(struct thread *);
2688460a577SJohn Birrell static void sched_interact_update(struct thread *);
2698460a577SJohn Birrell static void sched_interact_fork(struct thread *);
270ad1e7d28SJulian Elischer static void sched_pctcpu_update(struct td_sched *);
27135e6168fSJeff Roberson 
2725d7ef00cSJeff Roberson /* Operations on per processor queues */
2739727e637SJeff Roberson static struct thread *tdq_choose(struct tdq *);
274ad1e7d28SJulian Elischer static void tdq_setup(struct tdq *);
2759727e637SJeff Roberson static void tdq_load_add(struct tdq *, struct thread *);
2769727e637SJeff Roberson static void tdq_load_rem(struct tdq *, struct thread *);
2779727e637SJeff Roberson static __inline void tdq_runq_add(struct tdq *, struct thread *, int);
2789727e637SJeff Roberson static __inline void tdq_runq_rem(struct tdq *, struct thread *);
279ff256d9cSJeff Roberson static inline int sched_shouldpreempt(int, int, int);
280ad1e7d28SJulian Elischer void tdq_print(int cpu);
281e7d50326SJeff Roberson static void runq_print(struct runq *rq);
282ae7a6b38SJeff Roberson static void tdq_add(struct tdq *, struct thread *, int);
2835d7ef00cSJeff Roberson #ifdef SMP
28462fa74d9SJeff Roberson static int tdq_move(struct tdq *, struct tdq *);
285ad1e7d28SJulian Elischer static int tdq_idled(struct tdq *);
2869727e637SJeff Roberson static void tdq_notify(struct tdq *, struct thread *);
2879727e637SJeff Roberson static struct thread *tdq_steal(struct tdq *, int);
2889727e637SJeff Roberson static struct thread *runq_steal(struct runq *, int);
2899727e637SJeff Roberson static int sched_pickcpu(struct thread *, int);
2907fcf154aSJeff Roberson static void sched_balance(void);
29162fa74d9SJeff Roberson static int sched_balance_pair(struct tdq *, struct tdq *);
2929727e637SJeff Roberson static inline struct tdq *sched_setcpu(struct thread *, int, int);
293ae7a6b38SJeff Roberson static inline struct mtx *thread_block_switch(struct thread *);
294ae7a6b38SJeff Roberson static inline void thread_unblock_switch(struct thread *, struct mtx *);
295c47f202bSJeff Roberson static struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
2965d7ef00cSJeff Roberson #endif
2975d7ef00cSJeff Roberson 
298e7d50326SJeff Roberson static void sched_setup(void *dummy);
299237fdd78SRobert Watson SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
300e7d50326SJeff Roberson 
301e7d50326SJeff Roberson static void sched_initticks(void *dummy);
302237fdd78SRobert Watson SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
303237fdd78SRobert Watson     NULL);
304e7d50326SJeff Roberson 
305ae7a6b38SJeff Roberson /*
306ae7a6b38SJeff Roberson  * Print the threads waiting on a run-queue.
307ae7a6b38SJeff Roberson  */
308e7d50326SJeff Roberson static void
309e7d50326SJeff Roberson runq_print(struct runq *rq)
310e7d50326SJeff Roberson {
311e7d50326SJeff Roberson 	struct rqhead *rqh;
3129727e637SJeff Roberson 	struct thread *td;
313e7d50326SJeff Roberson 	int pri;
314e7d50326SJeff Roberson 	int j;
315e7d50326SJeff Roberson 	int i;
316e7d50326SJeff Roberson 
317e7d50326SJeff Roberson 	for (i = 0; i < RQB_LEN; i++) {
318e7d50326SJeff Roberson 		printf("\t\trunq bits %d 0x%zx\n",
319e7d50326SJeff Roberson 		    i, rq->rq_status.rqb_bits[i]);
320e7d50326SJeff Roberson 		for (j = 0; j < RQB_BPW; j++)
321e7d50326SJeff Roberson 			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
322e7d50326SJeff Roberson 				pri = j + (i << RQB_L2BPW);
323e7d50326SJeff Roberson 				rqh = &rq->rq_queues[pri];
3249727e637SJeff Roberson 				TAILQ_FOREACH(td, rqh, td_runq) {
325e7d50326SJeff Roberson 					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
3269727e637SJeff Roberson 					    td, td->td_name, td->td_priority,
3279727e637SJeff Roberson 					    td->td_rqindex, pri);
328e7d50326SJeff Roberson 				}
329e7d50326SJeff Roberson 			}
330e7d50326SJeff Roberson 	}
331e7d50326SJeff Roberson }
332e7d50326SJeff Roberson 
333ae7a6b38SJeff Roberson /*
334ae7a6b38SJeff Roberson  * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
335ae7a6b38SJeff Roberson  */
33615dc847eSJeff Roberson void
337ad1e7d28SJulian Elischer tdq_print(int cpu)
33815dc847eSJeff Roberson {
339ad1e7d28SJulian Elischer 	struct tdq *tdq;
34015dc847eSJeff Roberson 
341ad1e7d28SJulian Elischer 	tdq = TDQ_CPU(cpu);
34215dc847eSJeff Roberson 
343c47f202bSJeff Roberson 	printf("tdq %d:\n", TDQ_ID(tdq));
34462fa74d9SJeff Roberson 	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
34562fa74d9SJeff Roberson 	printf("\tLock name:      %s\n", tdq->tdq_name);
346d2ad694cSJeff Roberson 	printf("\tload:           %d\n", tdq->tdq_load);
3471690c6c1SJeff Roberson 	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
3481690c6c1SJeff Roberson 	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
3491690c6c1SJeff Roberson 	printf("\tidle state:     %d\n", tdq->tdq_idlestate);
350e7d50326SJeff Roberson 	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
3513f872f85SJeff Roberson 	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
3521690c6c1SJeff Roberson 	printf("\tload transferable: %d\n", tdq->tdq_transferable);
3531690c6c1SJeff Roberson 	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
354e7d50326SJeff Roberson 	printf("\trealtime runq:\n");
355e7d50326SJeff Roberson 	runq_print(&tdq->tdq_realtime);
356e7d50326SJeff Roberson 	printf("\ttimeshare runq:\n");
357e7d50326SJeff Roberson 	runq_print(&tdq->tdq_timeshare);
358e7d50326SJeff Roberson 	printf("\tidle runq:\n");
359e7d50326SJeff Roberson 	runq_print(&tdq->tdq_idle);
36015dc847eSJeff Roberson }
36115dc847eSJeff Roberson 
362ff256d9cSJeff Roberson static inline int
363ff256d9cSJeff Roberson sched_shouldpreempt(int pri, int cpri, int remote)
364ff256d9cSJeff Roberson {
365ff256d9cSJeff Roberson 	/*
366ff256d9cSJeff Roberson 	 * If the new priority is not better than the current priority there is
367ff256d9cSJeff Roberson 	 * nothing to do.
368ff256d9cSJeff Roberson 	 */
369ff256d9cSJeff Roberson 	if (pri >= cpri)
370ff256d9cSJeff Roberson 		return (0);
371ff256d9cSJeff Roberson 	/*
372ff256d9cSJeff Roberson 	 * Always preempt idle.
373ff256d9cSJeff Roberson 	 */
374ff256d9cSJeff Roberson 	if (cpri >= PRI_MIN_IDLE)
375ff256d9cSJeff Roberson 		return (1);
376ff256d9cSJeff Roberson 	/*
377ff256d9cSJeff Roberson 	 * If preemption is disabled don't preempt others.
378ff256d9cSJeff Roberson 	 */
379ff256d9cSJeff Roberson 	if (preempt_thresh == 0)
380ff256d9cSJeff Roberson 		return (0);
381ff256d9cSJeff Roberson 	/*
382ff256d9cSJeff Roberson 	 * Preempt if we exceed the threshold.
383ff256d9cSJeff Roberson 	 */
384ff256d9cSJeff Roberson 	if (pri <= preempt_thresh)
385ff256d9cSJeff Roberson 		return (1);
386ff256d9cSJeff Roberson 	/*
387ff256d9cSJeff Roberson 	 * If we're realtime or better and there is timeshare or worse running
388ff256d9cSJeff Roberson 	 * preempt only remote processors.
389ff256d9cSJeff Roberson 	 */
390ff256d9cSJeff Roberson 	if (remote && pri <= PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
391ff256d9cSJeff Roberson 		return (1);
392ff256d9cSJeff Roberson 	return (0);
393ff256d9cSJeff Roberson }
394ff256d9cSJeff Roberson 
395ae7a6b38SJeff Roberson #define	TS_RQ_PPQ	(((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
396ae7a6b38SJeff Roberson /*
397ae7a6b38SJeff Roberson  * Add a thread to the actual run-queue.  Keeps transferable counts up to
398ae7a6b38SJeff Roberson  * date with what is actually on the run-queue.  Selects the correct
399ae7a6b38SJeff Roberson  * queue position for timeshare threads.
400ae7a6b38SJeff Roberson  */
401155b9987SJeff Roberson static __inline void
4029727e637SJeff Roberson tdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
403155b9987SJeff Roberson {
4049727e637SJeff Roberson 	struct td_sched *ts;
405c143ac21SJeff Roberson 	u_char pri;
406c143ac21SJeff Roberson 
407ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
4089727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
40973daf66fSJeff Roberson 
4109727e637SJeff Roberson 	pri = td->td_priority;
4119727e637SJeff Roberson 	ts = td->td_sched;
4129727e637SJeff Roberson 	TD_SET_RUNQ(td);
4139727e637SJeff Roberson 	if (THREAD_CAN_MIGRATE(td)) {
414d2ad694cSJeff Roberson 		tdq->tdq_transferable++;
415ad1e7d28SJulian Elischer 		ts->ts_flags |= TSF_XFERABLE;
41680f86c9fSJeff Roberson 	}
417c143ac21SJeff Roberson 	if (pri <= PRI_MAX_REALTIME) {
418c143ac21SJeff Roberson 		ts->ts_runq = &tdq->tdq_realtime;
419c143ac21SJeff Roberson 	} else if (pri <= PRI_MAX_TIMESHARE) {
420c143ac21SJeff Roberson 		ts->ts_runq = &tdq->tdq_timeshare;
421e7d50326SJeff Roberson 		KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
422e7d50326SJeff Roberson 			("Invalid priority %d on timeshare runq", pri));
423e7d50326SJeff Roberson 		/*
424e7d50326SJeff Roberson 		 * This queue contains only priorities between MIN and MAX
425e7d50326SJeff Roberson 		 * realtime.  Use the whole queue to represent these values.
426e7d50326SJeff Roberson 		 */
427c47f202bSJeff Roberson 		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
428e7d50326SJeff Roberson 			pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
429e7d50326SJeff Roberson 			pri = (pri + tdq->tdq_idx) % RQ_NQS;
4303f872f85SJeff Roberson 			/*
4313f872f85SJeff Roberson 			 * This effectively shortens the queue by one so we
4323f872f85SJeff Roberson 			 * can have a one slot difference between idx and
4333f872f85SJeff Roberson 			 * ridx while we wait for threads to drain.
4343f872f85SJeff Roberson 			 */
4353f872f85SJeff Roberson 			if (tdq->tdq_ridx != tdq->tdq_idx &&
4363f872f85SJeff Roberson 			    pri == tdq->tdq_ridx)
4374499aff6SJeff Roberson 				pri = (unsigned char)(pri - 1) % RQ_NQS;
438e7d50326SJeff Roberson 		} else
4393f872f85SJeff Roberson 			pri = tdq->tdq_ridx;
4409727e637SJeff Roberson 		runq_add_pri(ts->ts_runq, td, pri, flags);
441c143ac21SJeff Roberson 		return;
442e7d50326SJeff Roberson 	} else
44373daf66fSJeff Roberson 		ts->ts_runq = &tdq->tdq_idle;
4449727e637SJeff Roberson 	runq_add(ts->ts_runq, td, flags);
44573daf66fSJeff Roberson }
44673daf66fSJeff Roberson 
44773daf66fSJeff Roberson /*
448ae7a6b38SJeff Roberson  * Remove a thread from a run-queue.  This typically happens when a thread
449ae7a6b38SJeff Roberson  * is selected to run.  Running threads are not on the queue and the
450ae7a6b38SJeff Roberson  * transferable count does not reflect them.
451ae7a6b38SJeff Roberson  */
452155b9987SJeff Roberson static __inline void
4539727e637SJeff Roberson tdq_runq_rem(struct tdq *tdq, struct thread *td)
454155b9987SJeff Roberson {
4559727e637SJeff Roberson 	struct td_sched *ts;
4569727e637SJeff Roberson 
4579727e637SJeff Roberson 	ts = td->td_sched;
458ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
459ae7a6b38SJeff Roberson 	KASSERT(ts->ts_runq != NULL,
4609727e637SJeff Roberson 	    ("tdq_runq_remove: thread %p null ts_runq", td));
461ad1e7d28SJulian Elischer 	if (ts->ts_flags & TSF_XFERABLE) {
462d2ad694cSJeff Roberson 		tdq->tdq_transferable--;
463ad1e7d28SJulian Elischer 		ts->ts_flags &= ~TSF_XFERABLE;
46480f86c9fSJeff Roberson 	}
4653f872f85SJeff Roberson 	if (ts->ts_runq == &tdq->tdq_timeshare) {
4663f872f85SJeff Roberson 		if (tdq->tdq_idx != tdq->tdq_ridx)
4679727e637SJeff Roberson 			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
468e7d50326SJeff Roberson 		else
4699727e637SJeff Roberson 			runq_remove_idx(ts->ts_runq, td, NULL);
4703f872f85SJeff Roberson 	} else
4719727e637SJeff Roberson 		runq_remove(ts->ts_runq, td);
472155b9987SJeff Roberson }
473155b9987SJeff Roberson 
474ae7a6b38SJeff Roberson /*
475ae7a6b38SJeff Roberson  * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
476ae7a6b38SJeff Roberson  * for this thread to the referenced thread queue.
477ae7a6b38SJeff Roberson  */
478a8949de2SJeff Roberson static void
4799727e637SJeff Roberson tdq_load_add(struct tdq *tdq, struct thread *td)
4805d7ef00cSJeff Roberson {
481ae7a6b38SJeff Roberson 
482ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
4839727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
48403d17db7SJeff Roberson 
485d2ad694cSJeff Roberson 	tdq->tdq_load++;
48603d17db7SJeff Roberson 	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
487d2ad694cSJeff Roberson 		tdq->tdq_sysload++;
48803d17db7SJeff Roberson 	CTR2(KTR_SCHED, "cpu %d load: %d", TDQ_ID(tdq), tdq->tdq_load);
4895d7ef00cSJeff Roberson }
49015dc847eSJeff Roberson 
491ae7a6b38SJeff Roberson /*
492ae7a6b38SJeff Roberson  * Remove the load from a thread that is transitioning to a sleep state or
493ae7a6b38SJeff Roberson  * exiting.
494ae7a6b38SJeff Roberson  */
495a8949de2SJeff Roberson static void
4969727e637SJeff Roberson tdq_load_rem(struct tdq *tdq, struct thread *td)
4975d7ef00cSJeff Roberson {
498ae7a6b38SJeff Roberson 
4999727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
500ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
501ae7a6b38SJeff Roberson 	KASSERT(tdq->tdq_load != 0,
502c47f202bSJeff Roberson 	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
50303d17db7SJeff Roberson 
504d2ad694cSJeff Roberson 	tdq->tdq_load--;
50503d17db7SJeff Roberson 	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
50603d17db7SJeff Roberson 		tdq->tdq_sysload--;
507d2ad694cSJeff Roberson 	CTR1(KTR_SCHED, "load: %d", tdq->tdq_load);
50815dc847eSJeff Roberson }
50915dc847eSJeff Roberson 
510356500a3SJeff Roberson /*
51162fa74d9SJeff Roberson  * Set lowpri to its exact value by searching the run-queue and
51262fa74d9SJeff Roberson  * evaluating curthread.  curthread may be passed as an optimization.
513356500a3SJeff Roberson  */
51422bf7d9aSJeff Roberson static void
51562fa74d9SJeff Roberson tdq_setlowpri(struct tdq *tdq, struct thread *ctd)
51662fa74d9SJeff Roberson {
51762fa74d9SJeff Roberson 	struct thread *td;
51862fa74d9SJeff Roberson 
51962fa74d9SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
52062fa74d9SJeff Roberson 	if (ctd == NULL)
52162fa74d9SJeff Roberson 		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
5229727e637SJeff Roberson 	td = tdq_choose(tdq);
5239727e637SJeff Roberson 	if (td == NULL || td->td_priority > ctd->td_priority)
52462fa74d9SJeff Roberson 		tdq->tdq_lowpri = ctd->td_priority;
52562fa74d9SJeff Roberson 	else
52662fa74d9SJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
52762fa74d9SJeff Roberson }
52862fa74d9SJeff Roberson 
52962fa74d9SJeff Roberson #ifdef SMP
53062fa74d9SJeff Roberson struct cpu_search {
53162fa74d9SJeff Roberson 	cpumask_t cs_mask;	/* Mask of valid cpus. */
53262fa74d9SJeff Roberson 	u_int	cs_load;
53362fa74d9SJeff Roberson 	u_int	cs_cpu;
53462fa74d9SJeff Roberson 	int	cs_limit;	/* Min priority for low min load for high. */
53562fa74d9SJeff Roberson };
53662fa74d9SJeff Roberson 
53762fa74d9SJeff Roberson #define	CPU_SEARCH_LOWEST	0x1
53862fa74d9SJeff Roberson #define	CPU_SEARCH_HIGHEST	0x2
53962fa74d9SJeff Roberson #define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
54062fa74d9SJeff Roberson 
54162fa74d9SJeff Roberson #define	CPUMASK_FOREACH(cpu, mask)				\
54262fa74d9SJeff Roberson 	for ((cpu) = 0; (cpu) < sizeof((mask)) * 8; (cpu)++)	\
54362fa74d9SJeff Roberson 		if ((mask) & 1 << (cpu))
54462fa74d9SJeff Roberson 
545d628fbfaSJohn Baldwin static __inline int cpu_search(struct cpu_group *cg, struct cpu_search *low,
54662fa74d9SJeff Roberson     struct cpu_search *high, const int match);
54762fa74d9SJeff Roberson int cpu_search_lowest(struct cpu_group *cg, struct cpu_search *low);
54862fa74d9SJeff Roberson int cpu_search_highest(struct cpu_group *cg, struct cpu_search *high);
54962fa74d9SJeff Roberson int cpu_search_both(struct cpu_group *cg, struct cpu_search *low,
55062fa74d9SJeff Roberson     struct cpu_search *high);
55162fa74d9SJeff Roberson 
55262fa74d9SJeff Roberson /*
55362fa74d9SJeff Roberson  * This routine compares according to the match argument and should be
55462fa74d9SJeff Roberson  * reduced in actual instantiations via constant propagation and dead code
55562fa74d9SJeff Roberson  * elimination.
55662fa74d9SJeff Roberson  */
55762fa74d9SJeff Roberson static __inline int
55862fa74d9SJeff Roberson cpu_compare(int cpu, struct cpu_search *low, struct cpu_search *high,
55962fa74d9SJeff Roberson     const int match)
56062fa74d9SJeff Roberson {
56162fa74d9SJeff Roberson 	struct tdq *tdq;
56262fa74d9SJeff Roberson 
56362fa74d9SJeff Roberson 	tdq = TDQ_CPU(cpu);
56462fa74d9SJeff Roberson 	if (match & CPU_SEARCH_LOWEST)
56562fa74d9SJeff Roberson 		if (low->cs_mask & (1 << cpu) &&
56662fa74d9SJeff Roberson 		    tdq->tdq_load < low->cs_load &&
56762fa74d9SJeff Roberson 		    tdq->tdq_lowpri > low->cs_limit) {
56862fa74d9SJeff Roberson 			low->cs_cpu = cpu;
56962fa74d9SJeff Roberson 			low->cs_load = tdq->tdq_load;
57062fa74d9SJeff Roberson 		}
57162fa74d9SJeff Roberson 	if (match & CPU_SEARCH_HIGHEST)
57262fa74d9SJeff Roberson 		if (high->cs_mask & (1 << cpu) &&
57362fa74d9SJeff Roberson 		    tdq->tdq_load >= high->cs_limit &&
57462fa74d9SJeff Roberson 		    tdq->tdq_load > high->cs_load &&
57562fa74d9SJeff Roberson 		    tdq->tdq_transferable) {
57662fa74d9SJeff Roberson 			high->cs_cpu = cpu;
57762fa74d9SJeff Roberson 			high->cs_load = tdq->tdq_load;
57862fa74d9SJeff Roberson 		}
57962fa74d9SJeff Roberson 	return (tdq->tdq_load);
58062fa74d9SJeff Roberson }
58162fa74d9SJeff Roberson 
58262fa74d9SJeff Roberson /*
58362fa74d9SJeff Roberson  * Search the tree of cpu_groups for the lowest or highest loaded cpu
58462fa74d9SJeff Roberson  * according to the match argument.  This routine actually compares the
58562fa74d9SJeff Roberson  * load on all paths through the tree and finds the least loaded cpu on
58662fa74d9SJeff Roberson  * the least loaded path, which may differ from the least loaded cpu in
58762fa74d9SJeff Roberson  * the system.  This balances work among caches and busses.
58862fa74d9SJeff Roberson  *
58962fa74d9SJeff Roberson  * This inline is instantiated in three forms below using constants for the
59062fa74d9SJeff Roberson  * match argument.  It is reduced to the minimum set for each case.  It is
59162fa74d9SJeff Roberson  * also recursive to the depth of the tree.
59262fa74d9SJeff Roberson  */
593d628fbfaSJohn Baldwin static __inline int
59462fa74d9SJeff Roberson cpu_search(struct cpu_group *cg, struct cpu_search *low,
59562fa74d9SJeff Roberson     struct cpu_search *high, const int match)
59662fa74d9SJeff Roberson {
59762fa74d9SJeff Roberson 	int total;
59862fa74d9SJeff Roberson 
59962fa74d9SJeff Roberson 	total = 0;
60062fa74d9SJeff Roberson 	if (cg->cg_children) {
60162fa74d9SJeff Roberson 		struct cpu_search lgroup;
60262fa74d9SJeff Roberson 		struct cpu_search hgroup;
60362fa74d9SJeff Roberson 		struct cpu_group *child;
60462fa74d9SJeff Roberson 		u_int lload;
60562fa74d9SJeff Roberson 		int hload;
60662fa74d9SJeff Roberson 		int load;
60762fa74d9SJeff Roberson 		int i;
60862fa74d9SJeff Roberson 
60962fa74d9SJeff Roberson 		lload = -1;
61062fa74d9SJeff Roberson 		hload = -1;
61162fa74d9SJeff Roberson 		for (i = 0; i < cg->cg_children; i++) {
61262fa74d9SJeff Roberson 			child = &cg->cg_child[i];
61362fa74d9SJeff Roberson 			if (match & CPU_SEARCH_LOWEST) {
61462fa74d9SJeff Roberson 				lgroup = *low;
61562fa74d9SJeff Roberson 				lgroup.cs_load = -1;
61662fa74d9SJeff Roberson 			}
61762fa74d9SJeff Roberson 			if (match & CPU_SEARCH_HIGHEST) {
61862fa74d9SJeff Roberson 				hgroup = *high;
61962fa74d9SJeff Roberson 				lgroup.cs_load = 0;
62062fa74d9SJeff Roberson 			}
62162fa74d9SJeff Roberson 			switch (match) {
62262fa74d9SJeff Roberson 			case CPU_SEARCH_LOWEST:
62362fa74d9SJeff Roberson 				load = cpu_search_lowest(child, &lgroup);
62462fa74d9SJeff Roberson 				break;
62562fa74d9SJeff Roberson 			case CPU_SEARCH_HIGHEST:
62662fa74d9SJeff Roberson 				load = cpu_search_highest(child, &hgroup);
62762fa74d9SJeff Roberson 				break;
62862fa74d9SJeff Roberson 			case CPU_SEARCH_BOTH:
62962fa74d9SJeff Roberson 				load = cpu_search_both(child, &lgroup, &hgroup);
63062fa74d9SJeff Roberson 				break;
63162fa74d9SJeff Roberson 			}
63262fa74d9SJeff Roberson 			total += load;
63362fa74d9SJeff Roberson 			if (match & CPU_SEARCH_LOWEST)
63462fa74d9SJeff Roberson 				if (load < lload || low->cs_cpu == -1) {
63562fa74d9SJeff Roberson 					*low = lgroup;
63662fa74d9SJeff Roberson 					lload = load;
63762fa74d9SJeff Roberson 				}
63862fa74d9SJeff Roberson 			if (match & CPU_SEARCH_HIGHEST)
63962fa74d9SJeff Roberson 				if (load > hload || high->cs_cpu == -1) {
64062fa74d9SJeff Roberson 					hload = load;
64162fa74d9SJeff Roberson 					*high = hgroup;
64262fa74d9SJeff Roberson 				}
64362fa74d9SJeff Roberson 		}
64462fa74d9SJeff Roberson 	} else {
64562fa74d9SJeff Roberson 		int cpu;
64662fa74d9SJeff Roberson 
64762fa74d9SJeff Roberson 		CPUMASK_FOREACH(cpu, cg->cg_mask)
64862fa74d9SJeff Roberson 			total += cpu_compare(cpu, low, high, match);
64962fa74d9SJeff Roberson 	}
65062fa74d9SJeff Roberson 	return (total);
65162fa74d9SJeff Roberson }
65262fa74d9SJeff Roberson 
65362fa74d9SJeff Roberson /*
65462fa74d9SJeff Roberson  * cpu_search instantiations must pass constants to maintain the inline
65562fa74d9SJeff Roberson  * optimization.
65662fa74d9SJeff Roberson  */
65762fa74d9SJeff Roberson int
65862fa74d9SJeff Roberson cpu_search_lowest(struct cpu_group *cg, struct cpu_search *low)
65962fa74d9SJeff Roberson {
66062fa74d9SJeff Roberson 	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
66162fa74d9SJeff Roberson }
66262fa74d9SJeff Roberson 
66362fa74d9SJeff Roberson int
66462fa74d9SJeff Roberson cpu_search_highest(struct cpu_group *cg, struct cpu_search *high)
66562fa74d9SJeff Roberson {
66662fa74d9SJeff Roberson 	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
66762fa74d9SJeff Roberson }
66862fa74d9SJeff Roberson 
66962fa74d9SJeff Roberson int
67062fa74d9SJeff Roberson cpu_search_both(struct cpu_group *cg, struct cpu_search *low,
67162fa74d9SJeff Roberson     struct cpu_search *high)
67262fa74d9SJeff Roberson {
67362fa74d9SJeff Roberson 	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
67462fa74d9SJeff Roberson }
67562fa74d9SJeff Roberson 
67662fa74d9SJeff Roberson /*
67762fa74d9SJeff Roberson  * Find the cpu with the least load via the least loaded path that has a
67862fa74d9SJeff Roberson  * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
67962fa74d9SJeff Roberson  * acceptable.
68062fa74d9SJeff Roberson  */
68162fa74d9SJeff Roberson static inline int
68262fa74d9SJeff Roberson sched_lowest(struct cpu_group *cg, cpumask_t mask, int pri)
68362fa74d9SJeff Roberson {
68462fa74d9SJeff Roberson 	struct cpu_search low;
68562fa74d9SJeff Roberson 
68662fa74d9SJeff Roberson 	low.cs_cpu = -1;
68762fa74d9SJeff Roberson 	low.cs_load = -1;
68862fa74d9SJeff Roberson 	low.cs_mask = mask;
68962fa74d9SJeff Roberson 	low.cs_limit = pri;
69062fa74d9SJeff Roberson 	cpu_search_lowest(cg, &low);
69162fa74d9SJeff Roberson 	return low.cs_cpu;
69262fa74d9SJeff Roberson }
69362fa74d9SJeff Roberson 
69462fa74d9SJeff Roberson /*
69562fa74d9SJeff Roberson  * Find the cpu with the highest load via the highest loaded path.
69662fa74d9SJeff Roberson  */
69762fa74d9SJeff Roberson static inline int
69862fa74d9SJeff Roberson sched_highest(struct cpu_group *cg, cpumask_t mask, int minload)
69962fa74d9SJeff Roberson {
70062fa74d9SJeff Roberson 	struct cpu_search high;
70162fa74d9SJeff Roberson 
70262fa74d9SJeff Roberson 	high.cs_cpu = -1;
70362fa74d9SJeff Roberson 	high.cs_load = 0;
70462fa74d9SJeff Roberson 	high.cs_mask = mask;
70562fa74d9SJeff Roberson 	high.cs_limit = minload;
70662fa74d9SJeff Roberson 	cpu_search_highest(cg, &high);
70762fa74d9SJeff Roberson 	return high.cs_cpu;
70862fa74d9SJeff Roberson }
70962fa74d9SJeff Roberson 
71062fa74d9SJeff Roberson /*
71162fa74d9SJeff Roberson  * Simultaneously find the highest and lowest loaded cpu reachable via
71262fa74d9SJeff Roberson  * cg.
71362fa74d9SJeff Roberson  */
71462fa74d9SJeff Roberson static inline void
71562fa74d9SJeff Roberson sched_both(struct cpu_group *cg, cpumask_t mask, int *lowcpu, int *highcpu)
71662fa74d9SJeff Roberson {
71762fa74d9SJeff Roberson 	struct cpu_search high;
71862fa74d9SJeff Roberson 	struct cpu_search low;
71962fa74d9SJeff Roberson 
72062fa74d9SJeff Roberson 	low.cs_cpu = -1;
72162fa74d9SJeff Roberson 	low.cs_limit = -1;
72262fa74d9SJeff Roberson 	low.cs_load = -1;
72362fa74d9SJeff Roberson 	low.cs_mask = mask;
72462fa74d9SJeff Roberson 	high.cs_load = 0;
72562fa74d9SJeff Roberson 	high.cs_cpu = -1;
72662fa74d9SJeff Roberson 	high.cs_limit = -1;
72762fa74d9SJeff Roberson 	high.cs_mask = mask;
72862fa74d9SJeff Roberson 	cpu_search_both(cg, &low, &high);
72962fa74d9SJeff Roberson 	*lowcpu = low.cs_cpu;
73062fa74d9SJeff Roberson 	*highcpu = high.cs_cpu;
73162fa74d9SJeff Roberson 	return;
73262fa74d9SJeff Roberson }
73362fa74d9SJeff Roberson 
73462fa74d9SJeff Roberson static void
73562fa74d9SJeff Roberson sched_balance_group(struct cpu_group *cg)
73662fa74d9SJeff Roberson {
73762fa74d9SJeff Roberson 	cpumask_t mask;
73862fa74d9SJeff Roberson 	int high;
73962fa74d9SJeff Roberson 	int low;
74062fa74d9SJeff Roberson 	int i;
74162fa74d9SJeff Roberson 
74262fa74d9SJeff Roberson 	mask = -1;
74362fa74d9SJeff Roberson 	for (;;) {
74462fa74d9SJeff Roberson 		sched_both(cg, mask, &low, &high);
74562fa74d9SJeff Roberson 		if (low == high || low == -1 || high == -1)
74662fa74d9SJeff Roberson 			break;
74762fa74d9SJeff Roberson 		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low)))
74862fa74d9SJeff Roberson 			break;
74962fa74d9SJeff Roberson 		/*
75062fa74d9SJeff Roberson 		 * If we failed to move any threads determine which cpu
75162fa74d9SJeff Roberson 		 * to kick out of the set and try again.
75262fa74d9SJeff Roberson 	 	 */
75362fa74d9SJeff Roberson 		if (TDQ_CPU(high)->tdq_transferable == 0)
75462fa74d9SJeff Roberson 			mask &= ~(1 << high);
75562fa74d9SJeff Roberson 		else
75662fa74d9SJeff Roberson 			mask &= ~(1 << low);
75762fa74d9SJeff Roberson 	}
75862fa74d9SJeff Roberson 
75962fa74d9SJeff Roberson 	for (i = 0; i < cg->cg_children; i++)
76062fa74d9SJeff Roberson 		sched_balance_group(&cg->cg_child[i]);
76162fa74d9SJeff Roberson }
76262fa74d9SJeff Roberson 
76362fa74d9SJeff Roberson static void
7647fcf154aSJeff Roberson sched_balance()
765356500a3SJeff Roberson {
7667fcf154aSJeff Roberson 	struct tdq *tdq;
767356500a3SJeff Roberson 
7687fcf154aSJeff Roberson 	/*
7697fcf154aSJeff Roberson 	 * Select a random time between .5 * balance_interval and
7707fcf154aSJeff Roberson 	 * 1.5 * balance_interval.
7717fcf154aSJeff Roberson 	 */
7727fcf154aSJeff Roberson 	balance_ticks = max(balance_interval / 2, 1);
7737fcf154aSJeff Roberson 	balance_ticks += random() % balance_interval;
774ae7a6b38SJeff Roberson 	if (smp_started == 0 || rebalance == 0)
775598b368dSJeff Roberson 		return;
7767fcf154aSJeff Roberson 	tdq = TDQ_SELF();
7777fcf154aSJeff Roberson 	TDQ_UNLOCK(tdq);
77862fa74d9SJeff Roberson 	sched_balance_group(cpu_top);
7797fcf154aSJeff Roberson 	TDQ_LOCK(tdq);
780cac77d04SJeff Roberson }
78186f8ae96SJeff Roberson 
782ae7a6b38SJeff Roberson /*
783ae7a6b38SJeff Roberson  * Lock two thread queues using their address to maintain lock order.
784ae7a6b38SJeff Roberson  */
785ae7a6b38SJeff Roberson static void
786ae7a6b38SJeff Roberson tdq_lock_pair(struct tdq *one, struct tdq *two)
787ae7a6b38SJeff Roberson {
788ae7a6b38SJeff Roberson 	if (one < two) {
789ae7a6b38SJeff Roberson 		TDQ_LOCK(one);
790ae7a6b38SJeff Roberson 		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
791ae7a6b38SJeff Roberson 	} else {
792ae7a6b38SJeff Roberson 		TDQ_LOCK(two);
793ae7a6b38SJeff Roberson 		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
794ae7a6b38SJeff Roberson 	}
795ae7a6b38SJeff Roberson }
796ae7a6b38SJeff Roberson 
797ae7a6b38SJeff Roberson /*
7987fcf154aSJeff Roberson  * Unlock two thread queues.  Order is not important here.
7997fcf154aSJeff Roberson  */
8007fcf154aSJeff Roberson static void
8017fcf154aSJeff Roberson tdq_unlock_pair(struct tdq *one, struct tdq *two)
8027fcf154aSJeff Roberson {
8037fcf154aSJeff Roberson 	TDQ_UNLOCK(one);
8047fcf154aSJeff Roberson 	TDQ_UNLOCK(two);
8057fcf154aSJeff Roberson }
8067fcf154aSJeff Roberson 
8077fcf154aSJeff Roberson /*
808ae7a6b38SJeff Roberson  * Transfer load between two imbalanced thread queues.
809ae7a6b38SJeff Roberson  */
81062fa74d9SJeff Roberson static int
811ad1e7d28SJulian Elischer sched_balance_pair(struct tdq *high, struct tdq *low)
812cac77d04SJeff Roberson {
813cac77d04SJeff Roberson 	int transferable;
814cac77d04SJeff Roberson 	int high_load;
815cac77d04SJeff Roberson 	int low_load;
81662fa74d9SJeff Roberson 	int moved;
817cac77d04SJeff Roberson 	int move;
818cac77d04SJeff Roberson 	int diff;
819cac77d04SJeff Roberson 	int i;
820cac77d04SJeff Roberson 
821ae7a6b38SJeff Roberson 	tdq_lock_pair(high, low);
822d2ad694cSJeff Roberson 	transferable = high->tdq_transferable;
823d2ad694cSJeff Roberson 	high_load = high->tdq_load;
824d2ad694cSJeff Roberson 	low_load = low->tdq_load;
82562fa74d9SJeff Roberson 	moved = 0;
826155b9987SJeff Roberson 	/*
827155b9987SJeff Roberson 	 * Determine what the imbalance is and then adjust that to how many
828d2ad694cSJeff Roberson 	 * threads we actually have to give up (transferable).
829155b9987SJeff Roberson 	 */
830ae7a6b38SJeff Roberson 	if (transferable != 0) {
831cac77d04SJeff Roberson 		diff = high_load - low_load;
832356500a3SJeff Roberson 		move = diff / 2;
833356500a3SJeff Roberson 		if (diff & 0x1)
834356500a3SJeff Roberson 			move++;
83580f86c9fSJeff Roberson 		move = min(move, transferable);
836356500a3SJeff Roberson 		for (i = 0; i < move; i++)
83762fa74d9SJeff Roberson 			moved += tdq_move(high, low);
838a5423ea3SJeff Roberson 		/*
839a5423ea3SJeff Roberson 		 * IPI the target cpu to force it to reschedule with the new
840a5423ea3SJeff Roberson 		 * workload.
841a5423ea3SJeff Roberson 		 */
842a5423ea3SJeff Roberson 		ipi_selected(1 << TDQ_ID(low), IPI_PREEMPT);
843ae7a6b38SJeff Roberson 	}
8447fcf154aSJeff Roberson 	tdq_unlock_pair(high, low);
84562fa74d9SJeff Roberson 	return (moved);
846356500a3SJeff Roberson }
847356500a3SJeff Roberson 
848ae7a6b38SJeff Roberson /*
849ae7a6b38SJeff Roberson  * Move a thread from one thread queue to another.
850ae7a6b38SJeff Roberson  */
85162fa74d9SJeff Roberson static int
852ae7a6b38SJeff Roberson tdq_move(struct tdq *from, struct tdq *to)
853356500a3SJeff Roberson {
854ad1e7d28SJulian Elischer 	struct td_sched *ts;
855ae7a6b38SJeff Roberson 	struct thread *td;
856ae7a6b38SJeff Roberson 	struct tdq *tdq;
857ae7a6b38SJeff Roberson 	int cpu;
858356500a3SJeff Roberson 
8597fcf154aSJeff Roberson 	TDQ_LOCK_ASSERT(from, MA_OWNED);
8607fcf154aSJeff Roberson 	TDQ_LOCK_ASSERT(to, MA_OWNED);
8617fcf154aSJeff Roberson 
862ad1e7d28SJulian Elischer 	tdq = from;
863ae7a6b38SJeff Roberson 	cpu = TDQ_ID(to);
8649727e637SJeff Roberson 	td = tdq_steal(tdq, cpu);
8659727e637SJeff Roberson 	if (td == NULL)
86662fa74d9SJeff Roberson 		return (0);
8679727e637SJeff Roberson 	ts = td->td_sched;
868ae7a6b38SJeff Roberson 	/*
869ae7a6b38SJeff Roberson 	 * Although the run queue is locked the thread may be blocked.  Lock
8707fcf154aSJeff Roberson 	 * it to clear this and acquire the run-queue lock.
871ae7a6b38SJeff Roberson 	 */
872ae7a6b38SJeff Roberson 	thread_lock(td);
8737fcf154aSJeff Roberson 	/* Drop recursive lock on from acquired via thread_lock(). */
874ae7a6b38SJeff Roberson 	TDQ_UNLOCK(from);
875ae7a6b38SJeff Roberson 	sched_rem(td);
8767b8bfa0dSJeff Roberson 	ts->ts_cpu = cpu;
877ae7a6b38SJeff Roberson 	td->td_lock = TDQ_LOCKPTR(to);
878ae7a6b38SJeff Roberson 	tdq_add(to, td, SRQ_YIELDING);
87962fa74d9SJeff Roberson 	return (1);
880356500a3SJeff Roberson }
88122bf7d9aSJeff Roberson 
882ae7a6b38SJeff Roberson /*
883ae7a6b38SJeff Roberson  * This tdq has idled.  Try to steal a thread from another cpu and switch
884ae7a6b38SJeff Roberson  * to it.
885ae7a6b38SJeff Roberson  */
88680f86c9fSJeff Roberson static int
887ad1e7d28SJulian Elischer tdq_idled(struct tdq *tdq)
88822bf7d9aSJeff Roberson {
88962fa74d9SJeff Roberson 	struct cpu_group *cg;
890ad1e7d28SJulian Elischer 	struct tdq *steal;
89162fa74d9SJeff Roberson 	cpumask_t mask;
89262fa74d9SJeff Roberson 	int thresh;
893ae7a6b38SJeff Roberson 	int cpu;
89480f86c9fSJeff Roberson 
89588f530ccSJeff Roberson 	if (smp_started == 0 || steal_idle == 0)
89688f530ccSJeff Roberson 		return (1);
89762fa74d9SJeff Roberson 	mask = -1;
89862fa74d9SJeff Roberson 	mask &= ~PCPU_GET(cpumask);
89962fa74d9SJeff Roberson 	/* We don't want to be preempted while we're iterating. */
900ae7a6b38SJeff Roberson 	spinlock_enter();
90162fa74d9SJeff Roberson 	for (cg = tdq->tdq_cg; cg != NULL; ) {
90262fa74d9SJeff Roberson 		if ((cg->cg_flags & (CG_FLAG_HTT | CG_FLAG_THREAD)) == 0)
90362fa74d9SJeff Roberson 			thresh = steal_thresh;
90462fa74d9SJeff Roberson 		else
90562fa74d9SJeff Roberson 			thresh = 1;
90662fa74d9SJeff Roberson 		cpu = sched_highest(cg, mask, thresh);
90762fa74d9SJeff Roberson 		if (cpu == -1) {
90862fa74d9SJeff Roberson 			cg = cg->cg_parent;
90980f86c9fSJeff Roberson 			continue;
9107b8bfa0dSJeff Roberson 		}
9117b8bfa0dSJeff Roberson 		steal = TDQ_CPU(cpu);
91262fa74d9SJeff Roberson 		mask &= ~(1 << cpu);
9137fcf154aSJeff Roberson 		tdq_lock_pair(tdq, steal);
91462fa74d9SJeff Roberson 		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
9157fcf154aSJeff Roberson 			tdq_unlock_pair(tdq, steal);
91662fa74d9SJeff Roberson 			continue;
91762fa74d9SJeff Roberson 		}
91862fa74d9SJeff Roberson 		/*
91962fa74d9SJeff Roberson 		 * If a thread was added while interrupts were disabled don't
92062fa74d9SJeff Roberson 		 * steal one here.  If we fail to acquire one due to affinity
92162fa74d9SJeff Roberson 		 * restrictions loop again with this cpu removed from the
92262fa74d9SJeff Roberson 		 * set.
92362fa74d9SJeff Roberson 		 */
92462fa74d9SJeff Roberson 		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
92562fa74d9SJeff Roberson 			tdq_unlock_pair(tdq, steal);
92662fa74d9SJeff Roberson 			continue;
92780f86c9fSJeff Roberson 		}
928ae7a6b38SJeff Roberson 		spinlock_exit();
929ae7a6b38SJeff Roberson 		TDQ_UNLOCK(steal);
9308df78c41SJeff Roberson 		mi_switch(SW_VOL | SWT_IDLE, NULL);
931ae7a6b38SJeff Roberson 		thread_unlock(curthread);
9327b8bfa0dSJeff Roberson 
9337b8bfa0dSJeff Roberson 		return (0);
93422bf7d9aSJeff Roberson 	}
93562fa74d9SJeff Roberson 	spinlock_exit();
93662fa74d9SJeff Roberson 	return (1);
93762fa74d9SJeff Roberson }
93822bf7d9aSJeff Roberson 
939ae7a6b38SJeff Roberson /*
940ae7a6b38SJeff Roberson  * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
941ae7a6b38SJeff Roberson  */
94222bf7d9aSJeff Roberson static void
9439727e637SJeff Roberson tdq_notify(struct tdq *tdq, struct thread *td)
94422bf7d9aSJeff Roberson {
945fc3a97dcSJeff Roberson 	int cpri;
946fc3a97dcSJeff Roberson 	int pri;
9477b8bfa0dSJeff Roberson 	int cpu;
94822bf7d9aSJeff Roberson 
949ff256d9cSJeff Roberson 	if (tdq->tdq_ipipending)
950ff256d9cSJeff Roberson 		return;
9519727e637SJeff Roberson 	cpu = td->td_sched->ts_cpu;
9529727e637SJeff Roberson 	pri = td->td_priority;
953ff256d9cSJeff Roberson 	cpri = pcpu_find(cpu)->pc_curthread->td_priority;
954ff256d9cSJeff Roberson 	if (!sched_shouldpreempt(pri, cpri, 1))
9556b2f763fSJeff Roberson 		return;
9561690c6c1SJeff Roberson 	if (TD_IS_IDLETHREAD(td)) {
9571690c6c1SJeff Roberson 		/*
9581690c6c1SJeff Roberson 		 * If the idle thread is still 'running' it's probably
9591690c6c1SJeff Roberson 		 * waiting on us to release the tdq spinlock already.  No
9601690c6c1SJeff Roberson 		 * need to ipi.
9611690c6c1SJeff Roberson 		 */
9621690c6c1SJeff Roberson 		if (tdq->tdq_idlestate == TDQ_RUNNING)
9631690c6c1SJeff Roberson 			return;
9646c47aaaeSJeff Roberson 		/*
9656c47aaaeSJeff Roberson 		 * If the MD code has an idle wakeup routine try that before
9666c47aaaeSJeff Roberson 		 * falling back to IPI.
9676c47aaaeSJeff Roberson 		 */
9686c47aaaeSJeff Roberson 		if (cpu_idle_wakeup(cpu))
9696c47aaaeSJeff Roberson 			return;
9701690c6c1SJeff Roberson 	}
971ff256d9cSJeff Roberson 	tdq->tdq_ipipending = 1;
97214618990SJeff Roberson 	ipi_selected(1 << cpu, IPI_PREEMPT);
97322bf7d9aSJeff Roberson }
97422bf7d9aSJeff Roberson 
975ae7a6b38SJeff Roberson /*
976ae7a6b38SJeff Roberson  * Steals load from a timeshare queue.  Honors the rotating queue head
977ae7a6b38SJeff Roberson  * index.
978ae7a6b38SJeff Roberson  */
9799727e637SJeff Roberson static struct thread *
98062fa74d9SJeff Roberson runq_steal_from(struct runq *rq, int cpu, u_char start)
981ae7a6b38SJeff Roberson {
982ae7a6b38SJeff Roberson 	struct rqbits *rqb;
983ae7a6b38SJeff Roberson 	struct rqhead *rqh;
9849727e637SJeff Roberson 	struct thread *td;
985ae7a6b38SJeff Roberson 	int first;
986ae7a6b38SJeff Roberson 	int bit;
987ae7a6b38SJeff Roberson 	int pri;
988ae7a6b38SJeff Roberson 	int i;
989ae7a6b38SJeff Roberson 
990ae7a6b38SJeff Roberson 	rqb = &rq->rq_status;
991ae7a6b38SJeff Roberson 	bit = start & (RQB_BPW -1);
992ae7a6b38SJeff Roberson 	pri = 0;
993ae7a6b38SJeff Roberson 	first = 0;
994ae7a6b38SJeff Roberson again:
995ae7a6b38SJeff Roberson 	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
996ae7a6b38SJeff Roberson 		if (rqb->rqb_bits[i] == 0)
997ae7a6b38SJeff Roberson 			continue;
998ae7a6b38SJeff Roberson 		if (bit != 0) {
999ae7a6b38SJeff Roberson 			for (pri = bit; pri < RQB_BPW; pri++)
1000ae7a6b38SJeff Roberson 				if (rqb->rqb_bits[i] & (1ul << pri))
1001ae7a6b38SJeff Roberson 					break;
1002ae7a6b38SJeff Roberson 			if (pri >= RQB_BPW)
1003ae7a6b38SJeff Roberson 				continue;
1004ae7a6b38SJeff Roberson 		} else
1005ae7a6b38SJeff Roberson 			pri = RQB_FFS(rqb->rqb_bits[i]);
1006ae7a6b38SJeff Roberson 		pri += (i << RQB_L2BPW);
1007ae7a6b38SJeff Roberson 		rqh = &rq->rq_queues[pri];
10089727e637SJeff Roberson 		TAILQ_FOREACH(td, rqh, td_runq) {
10099727e637SJeff Roberson 			if (first && THREAD_CAN_MIGRATE(td) &&
10109727e637SJeff Roberson 			    THREAD_CAN_SCHED(td, cpu))
10119727e637SJeff Roberson 				return (td);
1012ae7a6b38SJeff Roberson 			first = 1;
1013ae7a6b38SJeff Roberson 		}
1014ae7a6b38SJeff Roberson 	}
1015ae7a6b38SJeff Roberson 	if (start != 0) {
1016ae7a6b38SJeff Roberson 		start = 0;
1017ae7a6b38SJeff Roberson 		goto again;
1018ae7a6b38SJeff Roberson 	}
1019ae7a6b38SJeff Roberson 
1020ae7a6b38SJeff Roberson 	return (NULL);
1021ae7a6b38SJeff Roberson }
1022ae7a6b38SJeff Roberson 
1023ae7a6b38SJeff Roberson /*
1024ae7a6b38SJeff Roberson  * Steals load from a standard linear queue.
1025ae7a6b38SJeff Roberson  */
10269727e637SJeff Roberson static struct thread *
102762fa74d9SJeff Roberson runq_steal(struct runq *rq, int cpu)
102822bf7d9aSJeff Roberson {
102922bf7d9aSJeff Roberson 	struct rqhead *rqh;
103022bf7d9aSJeff Roberson 	struct rqbits *rqb;
10319727e637SJeff Roberson 	struct thread *td;
103222bf7d9aSJeff Roberson 	int word;
103322bf7d9aSJeff Roberson 	int bit;
103422bf7d9aSJeff Roberson 
103522bf7d9aSJeff Roberson 	rqb = &rq->rq_status;
103622bf7d9aSJeff Roberson 	for (word = 0; word < RQB_LEN; word++) {
103722bf7d9aSJeff Roberson 		if (rqb->rqb_bits[word] == 0)
103822bf7d9aSJeff Roberson 			continue;
103922bf7d9aSJeff Roberson 		for (bit = 0; bit < RQB_BPW; bit++) {
1040a2640c9bSPeter Wemm 			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
104122bf7d9aSJeff Roberson 				continue;
104222bf7d9aSJeff Roberson 			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
10439727e637SJeff Roberson 			TAILQ_FOREACH(td, rqh, td_runq)
10449727e637SJeff Roberson 				if (THREAD_CAN_MIGRATE(td) &&
10459727e637SJeff Roberson 				    THREAD_CAN_SCHED(td, cpu))
10469727e637SJeff Roberson 					return (td);
104722bf7d9aSJeff Roberson 		}
104822bf7d9aSJeff Roberson 	}
104922bf7d9aSJeff Roberson 	return (NULL);
105022bf7d9aSJeff Roberson }
105122bf7d9aSJeff Roberson 
1052ae7a6b38SJeff Roberson /*
1053ae7a6b38SJeff Roberson  * Attempt to steal a thread in priority order from a thread queue.
1054ae7a6b38SJeff Roberson  */
10559727e637SJeff Roberson static struct thread *
105662fa74d9SJeff Roberson tdq_steal(struct tdq *tdq, int cpu)
105722bf7d9aSJeff Roberson {
10589727e637SJeff Roberson 	struct thread *td;
105922bf7d9aSJeff Roberson 
1060ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
10619727e637SJeff Roberson 	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
10629727e637SJeff Roberson 		return (td);
10639727e637SJeff Roberson 	if ((td = runq_steal_from(&tdq->tdq_timeshare,
10649727e637SJeff Roberson 	    cpu, tdq->tdq_ridx)) != NULL)
10659727e637SJeff Roberson 		return (td);
106662fa74d9SJeff Roberson 	return (runq_steal(&tdq->tdq_idle, cpu));
106722bf7d9aSJeff Roberson }
106880f86c9fSJeff Roberson 
1069ae7a6b38SJeff Roberson /*
1070ae7a6b38SJeff Roberson  * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
10717fcf154aSJeff Roberson  * current lock and returns with the assigned queue locked.
1072ae7a6b38SJeff Roberson  */
1073ae7a6b38SJeff Roberson static inline struct tdq *
10749727e637SJeff Roberson sched_setcpu(struct thread *td, int cpu, int flags)
107580f86c9fSJeff Roberson {
10769727e637SJeff Roberson 
1077ae7a6b38SJeff Roberson 	struct tdq *tdq;
107880f86c9fSJeff Roberson 
10799727e637SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1080ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpu);
10819727e637SJeff Roberson 	td->td_sched->ts_cpu = cpu;
10829727e637SJeff Roberson 	/*
10839727e637SJeff Roberson 	 * If the lock matches just return the queue.
10849727e637SJeff Roberson 	 */
1085ae7a6b38SJeff Roberson 	if (td->td_lock == TDQ_LOCKPTR(tdq))
1086ae7a6b38SJeff Roberson 		return (tdq);
1087ae7a6b38SJeff Roberson #ifdef notyet
108880f86c9fSJeff Roberson 	/*
1089a5423ea3SJeff Roberson 	 * If the thread isn't running its lockptr is a
1090ae7a6b38SJeff Roberson 	 * turnstile or a sleepqueue.  We can just lock_set without
1091ae7a6b38SJeff Roberson 	 * blocking.
1092670c524fSJeff Roberson 	 */
1093ae7a6b38SJeff Roberson 	if (TD_CAN_RUN(td)) {
1094ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
1095ae7a6b38SJeff Roberson 		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1096ae7a6b38SJeff Roberson 		return (tdq);
1097ae7a6b38SJeff Roberson 	}
1098ae7a6b38SJeff Roberson #endif
109980f86c9fSJeff Roberson 	/*
1100ae7a6b38SJeff Roberson 	 * The hard case, migration, we need to block the thread first to
1101ae7a6b38SJeff Roberson 	 * prevent order reversals with other cpus locks.
11027b8bfa0dSJeff Roberson 	 */
1103ae7a6b38SJeff Roberson 	thread_lock_block(td);
1104ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
1105ae7a6b38SJeff Roberson 	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1106ae7a6b38SJeff Roberson 	return (tdq);
110780f86c9fSJeff Roberson }
11082454aaf5SJeff Roberson 
11098df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
11108df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
11118df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
11128df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
11138df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
11148df78c41SJeff Roberson SCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
11158df78c41SJeff Roberson 
1116ae7a6b38SJeff Roberson static int
11179727e637SJeff Roberson sched_pickcpu(struct thread *td, int flags)
1118ae7a6b38SJeff Roberson {
111962fa74d9SJeff Roberson 	struct cpu_group *cg;
11209727e637SJeff Roberson 	struct td_sched *ts;
1121ae7a6b38SJeff Roberson 	struct tdq *tdq;
112262fa74d9SJeff Roberson 	cpumask_t mask;
11237b8bfa0dSJeff Roberson 	int self;
11247b8bfa0dSJeff Roberson 	int pri;
11257b8bfa0dSJeff Roberson 	int cpu;
11267b8bfa0dSJeff Roberson 
112762fa74d9SJeff Roberson 	self = PCPU_GET(cpuid);
11289727e637SJeff Roberson 	ts = td->td_sched;
11297b8bfa0dSJeff Roberson 	if (smp_started == 0)
11307b8bfa0dSJeff Roberson 		return (self);
113128994a58SJeff Roberson 	/*
113228994a58SJeff Roberson 	 * Don't migrate a running thread from sched_switch().
113328994a58SJeff Roberson 	 */
113462fa74d9SJeff Roberson 	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
113562fa74d9SJeff Roberson 		return (ts->ts_cpu);
11367b8bfa0dSJeff Roberson 	/*
113762fa74d9SJeff Roberson 	 * Prefer to run interrupt threads on the processors that generate
113862fa74d9SJeff Roberson 	 * the interrupt.
11397b8bfa0dSJeff Roberson 	 */
114062fa74d9SJeff Roberson 	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
11418df78c41SJeff Roberson 	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
11428df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_intrbind);
114362fa74d9SJeff Roberson 		ts->ts_cpu = self;
11448df78c41SJeff Roberson 	}
114562fa74d9SJeff Roberson 	/*
114662fa74d9SJeff Roberson 	 * If the thread can run on the last cpu and the affinity has not
114762fa74d9SJeff Roberson 	 * expired or it is idle run it there.
114862fa74d9SJeff Roberson 	 */
114962fa74d9SJeff Roberson 	pri = td->td_priority;
115062fa74d9SJeff Roberson 	tdq = TDQ_CPU(ts->ts_cpu);
115162fa74d9SJeff Roberson 	if (THREAD_CAN_SCHED(td, ts->ts_cpu)) {
11528df78c41SJeff Roberson 		if (tdq->tdq_lowpri > PRI_MIN_IDLE) {
11538df78c41SJeff Roberson 			SCHED_STAT_INC(pickcpu_idle_affinity);
115462fa74d9SJeff Roberson 			return (ts->ts_cpu);
11558df78c41SJeff Roberson 		}
11568df78c41SJeff Roberson 		if (SCHED_AFFINITY(ts, CG_SHARE_L2) && tdq->tdq_lowpri > pri) {
11578df78c41SJeff Roberson 			SCHED_STAT_INC(pickcpu_affinity);
11587b8bfa0dSJeff Roberson 			return (ts->ts_cpu);
11597b8bfa0dSJeff Roberson 		}
11608df78c41SJeff Roberson 	}
11617b8bfa0dSJeff Roberson 	/*
116262fa74d9SJeff Roberson 	 * Search for the highest level in the tree that still has affinity.
11637b8bfa0dSJeff Roberson 	 */
116462fa74d9SJeff Roberson 	cg = NULL;
116562fa74d9SJeff Roberson 	for (cg = tdq->tdq_cg; cg != NULL; cg = cg->cg_parent)
116662fa74d9SJeff Roberson 		if (SCHED_AFFINITY(ts, cg->cg_level))
116762fa74d9SJeff Roberson 			break;
116862fa74d9SJeff Roberson 	cpu = -1;
116962fa74d9SJeff Roberson 	mask = td->td_cpuset->cs_mask.__bits[0];
117062fa74d9SJeff Roberson 	if (cg)
117162fa74d9SJeff Roberson 		cpu = sched_lowest(cg, mask, pri);
117262fa74d9SJeff Roberson 	if (cpu == -1)
117362fa74d9SJeff Roberson 		cpu = sched_lowest(cpu_top, mask, -1);
117462fa74d9SJeff Roberson 	/*
117562fa74d9SJeff Roberson 	 * Compare the lowest loaded cpu to current cpu.
117662fa74d9SJeff Roberson 	 */
1177ff256d9cSJeff Roberson 	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
11788df78c41SJeff Roberson 	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE) {
11798df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_local);
118062fa74d9SJeff Roberson 		cpu = self;
11818df78c41SJeff Roberson 	} else
11828df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_lowest);
11838df78c41SJeff Roberson 	if (cpu != ts->ts_cpu)
11848df78c41SJeff Roberson 		SCHED_STAT_INC(pickcpu_migration);
1185ff256d9cSJeff Roberson 	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1186ae7a6b38SJeff Roberson 	return (cpu);
118780f86c9fSJeff Roberson }
118862fa74d9SJeff Roberson #endif
118922bf7d9aSJeff Roberson 
119022bf7d9aSJeff Roberson /*
119122bf7d9aSJeff Roberson  * Pick the highest priority task we have and return it.
11920c0a98b2SJeff Roberson  */
11939727e637SJeff Roberson static struct thread *
1194ad1e7d28SJulian Elischer tdq_choose(struct tdq *tdq)
11955d7ef00cSJeff Roberson {
11969727e637SJeff Roberson 	struct thread *td;
11975d7ef00cSJeff Roberson 
1198ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
11999727e637SJeff Roberson 	td = runq_choose(&tdq->tdq_realtime);
12009727e637SJeff Roberson 	if (td != NULL)
12019727e637SJeff Roberson 		return (td);
12029727e637SJeff Roberson 	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
12039727e637SJeff Roberson 	if (td != NULL) {
12049727e637SJeff Roberson 		KASSERT(td->td_priority >= PRI_MIN_TIMESHARE,
1205e7d50326SJeff Roberson 		    ("tdq_choose: Invalid priority on timeshare queue %d",
12069727e637SJeff Roberson 		    td->td_priority));
12079727e637SJeff Roberson 		return (td);
120815dc847eSJeff Roberson 	}
12099727e637SJeff Roberson 	td = runq_choose(&tdq->tdq_idle);
12109727e637SJeff Roberson 	if (td != NULL) {
12119727e637SJeff Roberson 		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1212e7d50326SJeff Roberson 		    ("tdq_choose: Invalid priority on idle queue %d",
12139727e637SJeff Roberson 		    td->td_priority));
12149727e637SJeff Roberson 		return (td);
1215e7d50326SJeff Roberson 	}
1216e7d50326SJeff Roberson 
1217e7d50326SJeff Roberson 	return (NULL);
1218245f3abfSJeff Roberson }
12190a016a05SJeff Roberson 
1220ae7a6b38SJeff Roberson /*
1221ae7a6b38SJeff Roberson  * Initialize a thread queue.
1222ae7a6b38SJeff Roberson  */
12230a016a05SJeff Roberson static void
1224ad1e7d28SJulian Elischer tdq_setup(struct tdq *tdq)
12250a016a05SJeff Roberson {
1226ae7a6b38SJeff Roberson 
1227c47f202bSJeff Roberson 	if (bootverbose)
1228c47f202bSJeff Roberson 		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1229e7d50326SJeff Roberson 	runq_init(&tdq->tdq_realtime);
1230e7d50326SJeff Roberson 	runq_init(&tdq->tdq_timeshare);
1231d2ad694cSJeff Roberson 	runq_init(&tdq->tdq_idle);
123262fa74d9SJeff Roberson 	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
123362fa74d9SJeff Roberson 	    "sched lock %d", (int)TDQ_ID(tdq));
123462fa74d9SJeff Roberson 	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
123562fa74d9SJeff Roberson 	    MTX_SPIN | MTX_RECURSE);
12360a016a05SJeff Roberson }
12370a016a05SJeff Roberson 
1238c47f202bSJeff Roberson #ifdef SMP
1239c47f202bSJeff Roberson static void
1240c47f202bSJeff Roberson sched_setup_smp(void)
1241c47f202bSJeff Roberson {
1242c47f202bSJeff Roberson 	struct tdq *tdq;
1243c47f202bSJeff Roberson 	int i;
1244c47f202bSJeff Roberson 
124562fa74d9SJeff Roberson 	cpu_top = smp_topo();
124662fa74d9SJeff Roberson 	for (i = 0; i < MAXCPU; i++) {
1247c47f202bSJeff Roberson 		if (CPU_ABSENT(i))
1248c47f202bSJeff Roberson 			continue;
124962fa74d9SJeff Roberson 		tdq = TDQ_CPU(i);
1250c47f202bSJeff Roberson 		tdq_setup(tdq);
125162fa74d9SJeff Roberson 		tdq->tdq_cg = smp_topo_find(cpu_top, i);
125262fa74d9SJeff Roberson 		if (tdq->tdq_cg == NULL)
125362fa74d9SJeff Roberson 			panic("Can't find cpu group for %d\n", i);
1254c47f202bSJeff Roberson 	}
125562fa74d9SJeff Roberson 	balance_tdq = TDQ_SELF();
125662fa74d9SJeff Roberson 	sched_balance();
1257c47f202bSJeff Roberson }
1258c47f202bSJeff Roberson #endif
1259c47f202bSJeff Roberson 
1260ae7a6b38SJeff Roberson /*
1261ae7a6b38SJeff Roberson  * Setup the thread queues and initialize the topology based on MD
1262ae7a6b38SJeff Roberson  * information.
1263ae7a6b38SJeff Roberson  */
126435e6168fSJeff Roberson static void
126535e6168fSJeff Roberson sched_setup(void *dummy)
126635e6168fSJeff Roberson {
1267ae7a6b38SJeff Roberson 	struct tdq *tdq;
1268c47f202bSJeff Roberson 
1269c47f202bSJeff Roberson 	tdq = TDQ_SELF();
12700ec896fdSJeff Roberson #ifdef SMP
1271c47f202bSJeff Roberson 	sched_setup_smp();
1272749d01b0SJeff Roberson #else
1273c47f202bSJeff Roberson 	tdq_setup(tdq);
1274356500a3SJeff Roberson #endif
1275ae7a6b38SJeff Roberson 	/*
1276ae7a6b38SJeff Roberson 	 * To avoid divide-by-zero, we set realstathz a dummy value
1277ae7a6b38SJeff Roberson 	 * in case which sched_clock() called before sched_initticks().
1278ae7a6b38SJeff Roberson 	 */
1279ae7a6b38SJeff Roberson 	realstathz = hz;
1280ae7a6b38SJeff Roberson 	sched_slice = (realstathz/10);	/* ~100ms */
1281ae7a6b38SJeff Roberson 	tickincr = 1 << SCHED_TICK_SHIFT;
1282ae7a6b38SJeff Roberson 
1283ae7a6b38SJeff Roberson 	/* Add thread0's load since it's running. */
1284ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
1285c47f202bSJeff Roberson 	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
12869727e637SJeff Roberson 	tdq_load_add(tdq, &thread0);
128762fa74d9SJeff Roberson 	tdq->tdq_lowpri = thread0.td_priority;
1288ae7a6b38SJeff Roberson 	TDQ_UNLOCK(tdq);
128935e6168fSJeff Roberson }
129035e6168fSJeff Roberson 
1291ae7a6b38SJeff Roberson /*
1292ae7a6b38SJeff Roberson  * This routine determines the tickincr after stathz and hz are setup.
1293ae7a6b38SJeff Roberson  */
1294a1d4fe69SDavid Xu /* ARGSUSED */
1295a1d4fe69SDavid Xu static void
1296a1d4fe69SDavid Xu sched_initticks(void *dummy)
1297a1d4fe69SDavid Xu {
1298ae7a6b38SJeff Roberson 	int incr;
1299ae7a6b38SJeff Roberson 
1300a1d4fe69SDavid Xu 	realstathz = stathz ? stathz : hz;
130114618990SJeff Roberson 	sched_slice = (realstathz/10);	/* ~100ms */
1302a1d4fe69SDavid Xu 
1303a1d4fe69SDavid Xu 	/*
1304e7d50326SJeff Roberson 	 * tickincr is shifted out by 10 to avoid rounding errors due to
13053f872f85SJeff Roberson 	 * hz not being evenly divisible by stathz on all platforms.
1306e7d50326SJeff Roberson 	 */
1307ae7a6b38SJeff Roberson 	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1308e7d50326SJeff Roberson 	/*
1309e7d50326SJeff Roberson 	 * This does not work for values of stathz that are more than
1310e7d50326SJeff Roberson 	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1311a1d4fe69SDavid Xu 	 */
1312ae7a6b38SJeff Roberson 	if (incr == 0)
1313ae7a6b38SJeff Roberson 		incr = 1;
1314ae7a6b38SJeff Roberson 	tickincr = incr;
13157b8bfa0dSJeff Roberson #ifdef SMP
13169862717aSJeff Roberson 	/*
13177fcf154aSJeff Roberson 	 * Set the default balance interval now that we know
13187fcf154aSJeff Roberson 	 * what realstathz is.
13197fcf154aSJeff Roberson 	 */
13207fcf154aSJeff Roberson 	balance_interval = realstathz;
13217fcf154aSJeff Roberson 	/*
13229862717aSJeff Roberson 	 * Set steal thresh to log2(mp_ncpu) but no greater than 4.  This
13239862717aSJeff Roberson 	 * prevents excess thrashing on large machines and excess idle on
13249862717aSJeff Roberson 	 * smaller machines.
13259862717aSJeff Roberson 	 */
132662fa74d9SJeff Roberson 	steal_thresh = min(ffs(mp_ncpus) - 1, 3);
13277b8bfa0dSJeff Roberson 	affinity = SCHED_AFFINITY_DEFAULT;
13287b8bfa0dSJeff Roberson #endif
1329a1d4fe69SDavid Xu }
1330a1d4fe69SDavid Xu 
1331a1d4fe69SDavid Xu 
133235e6168fSJeff Roberson /*
1333ae7a6b38SJeff Roberson  * This is the core of the interactivity algorithm.  Determines a score based
1334ae7a6b38SJeff Roberson  * on past behavior.  It is the ratio of sleep time to run time scaled to
1335ae7a6b38SJeff Roberson  * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1336ae7a6b38SJeff Roberson  * differs from the cpu usage because it does not account for time spent
1337ae7a6b38SJeff Roberson  * waiting on a run-queue.  Would be prettier if we had floating point.
1338ae7a6b38SJeff Roberson  */
1339ae7a6b38SJeff Roberson static int
1340ae7a6b38SJeff Roberson sched_interact_score(struct thread *td)
1341ae7a6b38SJeff Roberson {
1342ae7a6b38SJeff Roberson 	struct td_sched *ts;
1343ae7a6b38SJeff Roberson 	int div;
1344ae7a6b38SJeff Roberson 
1345ae7a6b38SJeff Roberson 	ts = td->td_sched;
1346ae7a6b38SJeff Roberson 	/*
1347ae7a6b38SJeff Roberson 	 * The score is only needed if this is likely to be an interactive
1348ae7a6b38SJeff Roberson 	 * task.  Don't go through the expense of computing it if there's
1349ae7a6b38SJeff Roberson 	 * no chance.
1350ae7a6b38SJeff Roberson 	 */
1351ae7a6b38SJeff Roberson 	if (sched_interact <= SCHED_INTERACT_HALF &&
1352ae7a6b38SJeff Roberson 		ts->ts_runtime >= ts->ts_slptime)
1353ae7a6b38SJeff Roberson 			return (SCHED_INTERACT_HALF);
1354ae7a6b38SJeff Roberson 
1355ae7a6b38SJeff Roberson 	if (ts->ts_runtime > ts->ts_slptime) {
1356ae7a6b38SJeff Roberson 		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1357ae7a6b38SJeff Roberson 		return (SCHED_INTERACT_HALF +
1358ae7a6b38SJeff Roberson 		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1359ae7a6b38SJeff Roberson 	}
1360ae7a6b38SJeff Roberson 	if (ts->ts_slptime > ts->ts_runtime) {
1361ae7a6b38SJeff Roberson 		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1362ae7a6b38SJeff Roberson 		return (ts->ts_runtime / div);
1363ae7a6b38SJeff Roberson 	}
1364ae7a6b38SJeff Roberson 	/* runtime == slptime */
1365ae7a6b38SJeff Roberson 	if (ts->ts_runtime)
1366ae7a6b38SJeff Roberson 		return (SCHED_INTERACT_HALF);
1367ae7a6b38SJeff Roberson 
1368ae7a6b38SJeff Roberson 	/*
1369ae7a6b38SJeff Roberson 	 * This can happen if slptime and runtime are 0.
1370ae7a6b38SJeff Roberson 	 */
1371ae7a6b38SJeff Roberson 	return (0);
1372ae7a6b38SJeff Roberson 
1373ae7a6b38SJeff Roberson }
1374ae7a6b38SJeff Roberson 
1375ae7a6b38SJeff Roberson /*
137635e6168fSJeff Roberson  * Scale the scheduling priority according to the "interactivity" of this
137735e6168fSJeff Roberson  * process.
137835e6168fSJeff Roberson  */
137915dc847eSJeff Roberson static void
13808460a577SJohn Birrell sched_priority(struct thread *td)
138135e6168fSJeff Roberson {
1382e7d50326SJeff Roberson 	int score;
138335e6168fSJeff Roberson 	int pri;
138435e6168fSJeff Roberson 
13858460a577SJohn Birrell 	if (td->td_pri_class != PRI_TIMESHARE)
138615dc847eSJeff Roberson 		return;
1387e7d50326SJeff Roberson 	/*
1388e7d50326SJeff Roberson 	 * If the score is interactive we place the thread in the realtime
1389e7d50326SJeff Roberson 	 * queue with a priority that is less than kernel and interrupt
1390e7d50326SJeff Roberson 	 * priorities.  These threads are not subject to nice restrictions.
1391e7d50326SJeff Roberson 	 *
1392ae7a6b38SJeff Roberson 	 * Scores greater than this are placed on the normal timeshare queue
1393e7d50326SJeff Roberson 	 * where the priority is partially decided by the most recent cpu
1394e7d50326SJeff Roberson 	 * utilization and the rest is decided by nice value.
1395a5423ea3SJeff Roberson 	 *
1396a5423ea3SJeff Roberson 	 * The nice value of the process has a linear effect on the calculated
1397a5423ea3SJeff Roberson 	 * score.  Negative nice values make it easier for a thread to be
1398a5423ea3SJeff Roberson 	 * considered interactive.
1399e7d50326SJeff Roberson 	 */
1400e270652bSJeff Roberson 	score = imax(0, sched_interact_score(td) - td->td_proc->p_nice);
1401e7d50326SJeff Roberson 	if (score < sched_interact) {
1402e7d50326SJeff Roberson 		pri = PRI_MIN_REALTIME;
1403e7d50326SJeff Roberson 		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1404e7d50326SJeff Roberson 		    * score;
1405e7d50326SJeff Roberson 		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
14069a93305aSJeff Roberson 		    ("sched_priority: invalid interactive priority %d score %d",
14079a93305aSJeff Roberson 		    pri, score));
1408e7d50326SJeff Roberson 	} else {
1409e7d50326SJeff Roberson 		pri = SCHED_PRI_MIN;
1410e7d50326SJeff Roberson 		if (td->td_sched->ts_ticks)
1411e7d50326SJeff Roberson 			pri += SCHED_PRI_TICKS(td->td_sched);
1412e7d50326SJeff Roberson 		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1413ae7a6b38SJeff Roberson 		KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1414ae7a6b38SJeff Roberson 		    ("sched_priority: invalid priority %d: nice %d, "
1415ae7a6b38SJeff Roberson 		    "ticks %d ftick %d ltick %d tick pri %d",
1416ae7a6b38SJeff Roberson 		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1417ae7a6b38SJeff Roberson 		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1418ae7a6b38SJeff Roberson 		    SCHED_PRI_TICKS(td->td_sched)));
1419e7d50326SJeff Roberson 	}
14208460a577SJohn Birrell 	sched_user_prio(td, pri);
142135e6168fSJeff Roberson 
142215dc847eSJeff Roberson 	return;
142335e6168fSJeff Roberson }
142435e6168fSJeff Roberson 
142535e6168fSJeff Roberson /*
1426d322132cSJeff Roberson  * This routine enforces a maximum limit on the amount of scheduling history
1427ae7a6b38SJeff Roberson  * kept.  It is called after either the slptime or runtime is adjusted.  This
1428ae7a6b38SJeff Roberson  * function is ugly due to integer math.
1429d322132cSJeff Roberson  */
14304b60e324SJeff Roberson static void
14318460a577SJohn Birrell sched_interact_update(struct thread *td)
14324b60e324SJeff Roberson {
1433155b6ca1SJeff Roberson 	struct td_sched *ts;
14349a93305aSJeff Roberson 	u_int sum;
14353f741ca1SJeff Roberson 
1436155b6ca1SJeff Roberson 	ts = td->td_sched;
1437ae7a6b38SJeff Roberson 	sum = ts->ts_runtime + ts->ts_slptime;
1438d322132cSJeff Roberson 	if (sum < SCHED_SLP_RUN_MAX)
1439d322132cSJeff Roberson 		return;
1440d322132cSJeff Roberson 	/*
1441155b6ca1SJeff Roberson 	 * This only happens from two places:
1442155b6ca1SJeff Roberson 	 * 1) We have added an unusual amount of run time from fork_exit.
1443155b6ca1SJeff Roberson 	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1444155b6ca1SJeff Roberson 	 */
1445155b6ca1SJeff Roberson 	if (sum > SCHED_SLP_RUN_MAX * 2) {
1446ae7a6b38SJeff Roberson 		if (ts->ts_runtime > ts->ts_slptime) {
1447ae7a6b38SJeff Roberson 			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1448ae7a6b38SJeff Roberson 			ts->ts_slptime = 1;
1449155b6ca1SJeff Roberson 		} else {
1450ae7a6b38SJeff Roberson 			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1451ae7a6b38SJeff Roberson 			ts->ts_runtime = 1;
1452155b6ca1SJeff Roberson 		}
1453155b6ca1SJeff Roberson 		return;
1454155b6ca1SJeff Roberson 	}
1455155b6ca1SJeff Roberson 	/*
1456d322132cSJeff Roberson 	 * If we have exceeded by more than 1/5th then the algorithm below
1457d322132cSJeff Roberson 	 * will not bring us back into range.  Dividing by two here forces
14582454aaf5SJeff Roberson 	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1459d322132cSJeff Roberson 	 */
146037a35e4aSJeff Roberson 	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1461ae7a6b38SJeff Roberson 		ts->ts_runtime /= 2;
1462ae7a6b38SJeff Roberson 		ts->ts_slptime /= 2;
1463d322132cSJeff Roberson 		return;
1464d322132cSJeff Roberson 	}
1465ae7a6b38SJeff Roberson 	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1466ae7a6b38SJeff Roberson 	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1467d322132cSJeff Roberson }
1468d322132cSJeff Roberson 
1469ae7a6b38SJeff Roberson /*
1470ae7a6b38SJeff Roberson  * Scale back the interactivity history when a child thread is created.  The
1471ae7a6b38SJeff Roberson  * history is inherited from the parent but the thread may behave totally
1472ae7a6b38SJeff Roberson  * differently.  For example, a shell spawning a compiler process.  We want
1473ae7a6b38SJeff Roberson  * to learn that the compiler is behaving badly very quickly.
1474ae7a6b38SJeff Roberson  */
1475d322132cSJeff Roberson static void
14768460a577SJohn Birrell sched_interact_fork(struct thread *td)
1477d322132cSJeff Roberson {
1478d322132cSJeff Roberson 	int ratio;
1479d322132cSJeff Roberson 	int sum;
1480d322132cSJeff Roberson 
1481ae7a6b38SJeff Roberson 	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1482d322132cSJeff Roberson 	if (sum > SCHED_SLP_RUN_FORK) {
1483d322132cSJeff Roberson 		ratio = sum / SCHED_SLP_RUN_FORK;
1484ae7a6b38SJeff Roberson 		td->td_sched->ts_runtime /= ratio;
1485ae7a6b38SJeff Roberson 		td->td_sched->ts_slptime /= ratio;
14864b60e324SJeff Roberson 	}
14874b60e324SJeff Roberson }
14884b60e324SJeff Roberson 
148915dc847eSJeff Roberson /*
1490ae7a6b38SJeff Roberson  * Called from proc0_init() to setup the scheduler fields.
1491ed062c8dSJulian Elischer  */
1492ed062c8dSJulian Elischer void
1493ed062c8dSJulian Elischer schedinit(void)
1494ed062c8dSJulian Elischer {
1495e7d50326SJeff Roberson 
1496ed062c8dSJulian Elischer 	/*
1497ed062c8dSJulian Elischer 	 * Set up the scheduler specific parts of proc0.
1498ed062c8dSJulian Elischer 	 */
1499ed062c8dSJulian Elischer 	proc0.p_sched = NULL; /* XXX */
1500ad1e7d28SJulian Elischer 	thread0.td_sched = &td_sched0;
1501e7d50326SJeff Roberson 	td_sched0.ts_ltick = ticks;
15028ab80cf0SJeff Roberson 	td_sched0.ts_ftick = ticks;
150373daf66fSJeff Roberson 	td_sched0.ts_slice = sched_slice;
1504ed062c8dSJulian Elischer }
1505ed062c8dSJulian Elischer 
1506ed062c8dSJulian Elischer /*
150715dc847eSJeff Roberson  * This is only somewhat accurate since given many processes of the same
150815dc847eSJeff Roberson  * priority they will switch when their slices run out, which will be
1509e7d50326SJeff Roberson  * at most sched_slice stathz ticks.
151015dc847eSJeff Roberson  */
151135e6168fSJeff Roberson int
151235e6168fSJeff Roberson sched_rr_interval(void)
151335e6168fSJeff Roberson {
1514e7d50326SJeff Roberson 
1515e7d50326SJeff Roberson 	/* Convert sched_slice to hz */
1516e7d50326SJeff Roberson 	return (hz/(realstathz/sched_slice));
151735e6168fSJeff Roberson }
151835e6168fSJeff Roberson 
1519ae7a6b38SJeff Roberson /*
1520ae7a6b38SJeff Roberson  * Update the percent cpu tracking information when it is requested or
1521ae7a6b38SJeff Roberson  * the total history exceeds the maximum.  We keep a sliding history of
1522ae7a6b38SJeff Roberson  * tick counts that slowly decays.  This is less precise than the 4BSD
1523ae7a6b38SJeff Roberson  * mechanism since it happens with less regular and frequent events.
1524ae7a6b38SJeff Roberson  */
152522bf7d9aSJeff Roberson static void
1526ad1e7d28SJulian Elischer sched_pctcpu_update(struct td_sched *ts)
152735e6168fSJeff Roberson {
1528e7d50326SJeff Roberson 
1529e7d50326SJeff Roberson 	if (ts->ts_ticks == 0)
1530e7d50326SJeff Roberson 		return;
15318ab80cf0SJeff Roberson 	if (ticks - (hz / 10) < ts->ts_ltick &&
15328ab80cf0SJeff Roberson 	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
15338ab80cf0SJeff Roberson 		return;
153435e6168fSJeff Roberson 	/*
153535e6168fSJeff Roberson 	 * Adjust counters and watermark for pctcpu calc.
1536210491d3SJeff Roberson 	 */
1537e7d50326SJeff Roberson 	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1538ad1e7d28SJulian Elischer 		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1539e7d50326SJeff Roberson 			    SCHED_TICK_TARG;
1540e7d50326SJeff Roberson 	else
1541ad1e7d28SJulian Elischer 		ts->ts_ticks = 0;
1542ad1e7d28SJulian Elischer 	ts->ts_ltick = ticks;
1543e7d50326SJeff Roberson 	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
154435e6168fSJeff Roberson }
154535e6168fSJeff Roberson 
1546ae7a6b38SJeff Roberson /*
1547ae7a6b38SJeff Roberson  * Adjust the priority of a thread.  Move it to the appropriate run-queue
1548ae7a6b38SJeff Roberson  * if necessary.  This is the back-end for several priority related
1549ae7a6b38SJeff Roberson  * functions.
1550ae7a6b38SJeff Roberson  */
1551e7d50326SJeff Roberson static void
1552f5c157d9SJohn Baldwin sched_thread_priority(struct thread *td, u_char prio)
155335e6168fSJeff Roberson {
1554ad1e7d28SJulian Elischer 	struct td_sched *ts;
155573daf66fSJeff Roberson 	struct tdq *tdq;
155673daf66fSJeff Roberson 	int oldpri;
155735e6168fSJeff Roberson 
155881d47d3fSJeff Roberson 	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
1559431f8906SJulian Elischer 	    td, td->td_name, td->td_priority, prio, curthread,
1560431f8906SJulian Elischer 	    curthread->td_name);
1561ad1e7d28SJulian Elischer 	ts = td->td_sched;
15627b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1563f5c157d9SJohn Baldwin 	if (td->td_priority == prio)
1564f5c157d9SJohn Baldwin 		return;
15653f741ca1SJeff Roberson 	/*
15663f741ca1SJeff Roberson 	 * If the priority has been elevated due to priority
15673f741ca1SJeff Roberson 	 * propagation, we may have to move ourselves to a new
1568e7d50326SJeff Roberson 	 * queue.  This could be optimized to not re-add in some
1569e7d50326SJeff Roberson 	 * cases.
1570f2b74cbfSJeff Roberson 	 */
15716d55b3ecSJeff Roberson 	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1572e7d50326SJeff Roberson 		sched_rem(td);
1573e7d50326SJeff Roberson 		td->td_priority = prio;
1574ae7a6b38SJeff Roberson 		sched_add(td, SRQ_BORROWING);
157573daf66fSJeff Roberson 		return;
157673daf66fSJeff Roberson 	}
15776d55b3ecSJeff Roberson 	/*
15786d55b3ecSJeff Roberson 	 * If the thread is currently running we may have to adjust the lowpri
15796d55b3ecSJeff Roberson 	 * information so other cpus are aware of our current priority.
15806d55b3ecSJeff Roberson 	 */
15816d55b3ecSJeff Roberson 	if (TD_IS_RUNNING(td)) {
1582ae7a6b38SJeff Roberson 		tdq = TDQ_CPU(ts->ts_cpu);
158362fa74d9SJeff Roberson 		oldpri = td->td_priority;
15843f741ca1SJeff Roberson 		td->td_priority = prio;
158562fa74d9SJeff Roberson 		if (prio < tdq->tdq_lowpri)
158662fa74d9SJeff Roberson 			tdq->tdq_lowpri = prio;
158762fa74d9SJeff Roberson 		else if (tdq->tdq_lowpri == oldpri)
158862fa74d9SJeff Roberson 			tdq_setlowpri(tdq, td);
15896d55b3ecSJeff Roberson 		return;
159073daf66fSJeff Roberson 	}
15916d55b3ecSJeff Roberson 	td->td_priority = prio;
1592ae7a6b38SJeff Roberson }
159335e6168fSJeff Roberson 
1594f5c157d9SJohn Baldwin /*
1595f5c157d9SJohn Baldwin  * Update a thread's priority when it is lent another thread's
1596f5c157d9SJohn Baldwin  * priority.
1597f5c157d9SJohn Baldwin  */
1598f5c157d9SJohn Baldwin void
1599f5c157d9SJohn Baldwin sched_lend_prio(struct thread *td, u_char prio)
1600f5c157d9SJohn Baldwin {
1601f5c157d9SJohn Baldwin 
1602f5c157d9SJohn Baldwin 	td->td_flags |= TDF_BORROWING;
1603f5c157d9SJohn Baldwin 	sched_thread_priority(td, prio);
1604f5c157d9SJohn Baldwin }
1605f5c157d9SJohn Baldwin 
1606f5c157d9SJohn Baldwin /*
1607f5c157d9SJohn Baldwin  * Restore a thread's priority when priority propagation is
1608f5c157d9SJohn Baldwin  * over.  The prio argument is the minimum priority the thread
1609f5c157d9SJohn Baldwin  * needs to have to satisfy other possible priority lending
1610f5c157d9SJohn Baldwin  * requests.  If the thread's regular priority is less
1611f5c157d9SJohn Baldwin  * important than prio, the thread will keep a priority boost
1612f5c157d9SJohn Baldwin  * of prio.
1613f5c157d9SJohn Baldwin  */
1614f5c157d9SJohn Baldwin void
1615f5c157d9SJohn Baldwin sched_unlend_prio(struct thread *td, u_char prio)
1616f5c157d9SJohn Baldwin {
1617f5c157d9SJohn Baldwin 	u_char base_pri;
1618f5c157d9SJohn Baldwin 
1619f5c157d9SJohn Baldwin 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1620f5c157d9SJohn Baldwin 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
16218460a577SJohn Birrell 		base_pri = td->td_user_pri;
1622f5c157d9SJohn Baldwin 	else
1623f5c157d9SJohn Baldwin 		base_pri = td->td_base_pri;
1624f5c157d9SJohn Baldwin 	if (prio >= base_pri) {
1625f5c157d9SJohn Baldwin 		td->td_flags &= ~TDF_BORROWING;
1626f5c157d9SJohn Baldwin 		sched_thread_priority(td, base_pri);
1627f5c157d9SJohn Baldwin 	} else
1628f5c157d9SJohn Baldwin 		sched_lend_prio(td, prio);
1629f5c157d9SJohn Baldwin }
1630f5c157d9SJohn Baldwin 
1631ae7a6b38SJeff Roberson /*
1632ae7a6b38SJeff Roberson  * Standard entry for setting the priority to an absolute value.
1633ae7a6b38SJeff Roberson  */
1634f5c157d9SJohn Baldwin void
1635f5c157d9SJohn Baldwin sched_prio(struct thread *td, u_char prio)
1636f5c157d9SJohn Baldwin {
1637f5c157d9SJohn Baldwin 	u_char oldprio;
1638f5c157d9SJohn Baldwin 
1639f5c157d9SJohn Baldwin 	/* First, update the base priority. */
1640f5c157d9SJohn Baldwin 	td->td_base_pri = prio;
1641f5c157d9SJohn Baldwin 
1642f5c157d9SJohn Baldwin 	/*
164350aaa791SJohn Baldwin 	 * If the thread is borrowing another thread's priority, don't
1644f5c157d9SJohn Baldwin 	 * ever lower the priority.
1645f5c157d9SJohn Baldwin 	 */
1646f5c157d9SJohn Baldwin 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1647f5c157d9SJohn Baldwin 		return;
1648f5c157d9SJohn Baldwin 
1649f5c157d9SJohn Baldwin 	/* Change the real priority. */
1650f5c157d9SJohn Baldwin 	oldprio = td->td_priority;
1651f5c157d9SJohn Baldwin 	sched_thread_priority(td, prio);
1652f5c157d9SJohn Baldwin 
1653f5c157d9SJohn Baldwin 	/*
1654f5c157d9SJohn Baldwin 	 * If the thread is on a turnstile, then let the turnstile update
1655f5c157d9SJohn Baldwin 	 * its state.
1656f5c157d9SJohn Baldwin 	 */
1657f5c157d9SJohn Baldwin 	if (TD_ON_LOCK(td) && oldprio != prio)
1658f5c157d9SJohn Baldwin 		turnstile_adjust(td, oldprio);
1659f5c157d9SJohn Baldwin }
1660f5c157d9SJohn Baldwin 
1661ae7a6b38SJeff Roberson /*
1662ae7a6b38SJeff Roberson  * Set the base user priority, does not effect current running priority.
1663ae7a6b38SJeff Roberson  */
166435e6168fSJeff Roberson void
16658460a577SJohn Birrell sched_user_prio(struct thread *td, u_char prio)
16663db720fdSDavid Xu {
16673db720fdSDavid Xu 	u_char oldprio;
16683db720fdSDavid Xu 
16698460a577SJohn Birrell 	td->td_base_user_pri = prio;
1670fc6c30f6SJulian Elischer 	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1671fc6c30f6SJulian Elischer                 return;
16728460a577SJohn Birrell 	oldprio = td->td_user_pri;
16738460a577SJohn Birrell 	td->td_user_pri = prio;
16743db720fdSDavid Xu }
16753db720fdSDavid Xu 
16763db720fdSDavid Xu void
16773db720fdSDavid Xu sched_lend_user_prio(struct thread *td, u_char prio)
16783db720fdSDavid Xu {
16793db720fdSDavid Xu 	u_char oldprio;
16803db720fdSDavid Xu 
1681435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
16823db720fdSDavid Xu 	td->td_flags |= TDF_UBORROWING;
1683f645b5daSMaxim Konovalov 	oldprio = td->td_user_pri;
16848460a577SJohn Birrell 	td->td_user_pri = prio;
16853db720fdSDavid Xu }
16863db720fdSDavid Xu 
16873db720fdSDavid Xu void
16883db720fdSDavid Xu sched_unlend_user_prio(struct thread *td, u_char prio)
16893db720fdSDavid Xu {
16903db720fdSDavid Xu 	u_char base_pri;
16913db720fdSDavid Xu 
1692435806d3SDavid Xu 	THREAD_LOCK_ASSERT(td, MA_OWNED);
16938460a577SJohn Birrell 	base_pri = td->td_base_user_pri;
16943db720fdSDavid Xu 	if (prio >= base_pri) {
16953db720fdSDavid Xu 		td->td_flags &= ~TDF_UBORROWING;
16968460a577SJohn Birrell 		sched_user_prio(td, base_pri);
1697435806d3SDavid Xu 	} else {
16983db720fdSDavid Xu 		sched_lend_user_prio(td, prio);
16993db720fdSDavid Xu 	}
1700435806d3SDavid Xu }
17013db720fdSDavid Xu 
1702ae7a6b38SJeff Roberson /*
1703731016feSWojciech A. Koszek  * Block a thread for switching.  Similar to thread_block() but does not
1704731016feSWojciech A. Koszek  * bump the spin count.
1705731016feSWojciech A. Koszek  */
1706731016feSWojciech A. Koszek static inline struct mtx *
1707731016feSWojciech A. Koszek thread_block_switch(struct thread *td)
1708731016feSWojciech A. Koszek {
1709731016feSWojciech A. Koszek 	struct mtx *lock;
1710731016feSWojciech A. Koszek 
1711731016feSWojciech A. Koszek 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1712731016feSWojciech A. Koszek 	lock = td->td_lock;
1713731016feSWojciech A. Koszek 	td->td_lock = &blocked_lock;
1714731016feSWojciech A. Koszek 	mtx_unlock_spin(lock);
1715731016feSWojciech A. Koszek 
1716731016feSWojciech A. Koszek 	return (lock);
1717731016feSWojciech A. Koszek }
1718731016feSWojciech A. Koszek 
1719731016feSWojciech A. Koszek /*
1720c47f202bSJeff Roberson  * Handle migration from sched_switch().  This happens only for
1721c47f202bSJeff Roberson  * cpu binding.
1722c47f202bSJeff Roberson  */
1723c47f202bSJeff Roberson static struct mtx *
1724c47f202bSJeff Roberson sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1725c47f202bSJeff Roberson {
1726c47f202bSJeff Roberson 	struct tdq *tdn;
1727c47f202bSJeff Roberson 
1728c47f202bSJeff Roberson 	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1729c47f202bSJeff Roberson #ifdef SMP
17309727e637SJeff Roberson 	tdq_load_rem(tdq, td);
1731c47f202bSJeff Roberson 	/*
1732c47f202bSJeff Roberson 	 * Do the lock dance required to avoid LOR.  We grab an extra
1733c47f202bSJeff Roberson 	 * spinlock nesting to prevent preemption while we're
1734c47f202bSJeff Roberson 	 * not holding either run-queue lock.
1735c47f202bSJeff Roberson 	 */
1736c47f202bSJeff Roberson 	spinlock_enter();
1737c47f202bSJeff Roberson 	thread_block_switch(td);	/* This releases the lock on tdq. */
1738c47f202bSJeff Roberson 	TDQ_LOCK(tdn);
1739c47f202bSJeff Roberson 	tdq_add(tdn, td, flags);
17409727e637SJeff Roberson 	tdq_notify(tdn, td);
1741c47f202bSJeff Roberson 	/*
1742c47f202bSJeff Roberson 	 * After we unlock tdn the new cpu still can't switch into this
1743c47f202bSJeff Roberson 	 * thread until we've unblocked it in cpu_switch().  The lock
1744c47f202bSJeff Roberson 	 * pointers may match in the case of HTT cores.  Don't unlock here
1745c47f202bSJeff Roberson 	 * or we can deadlock when the other CPU runs the IPI handler.
1746c47f202bSJeff Roberson 	 */
1747c47f202bSJeff Roberson 	if (TDQ_LOCKPTR(tdn) != TDQ_LOCKPTR(tdq)) {
1748c47f202bSJeff Roberson 		TDQ_UNLOCK(tdn);
1749c47f202bSJeff Roberson 		TDQ_LOCK(tdq);
1750c47f202bSJeff Roberson 	}
1751c47f202bSJeff Roberson 	spinlock_exit();
1752c47f202bSJeff Roberson #endif
1753c47f202bSJeff Roberson 	return (TDQ_LOCKPTR(tdn));
1754c47f202bSJeff Roberson }
1755c47f202bSJeff Roberson 
1756c47f202bSJeff Roberson /*
1757ae7a6b38SJeff Roberson  * Release a thread that was blocked with thread_block_switch().
1758ae7a6b38SJeff Roberson  */
1759ae7a6b38SJeff Roberson static inline void
1760ae7a6b38SJeff Roberson thread_unblock_switch(struct thread *td, struct mtx *mtx)
1761ae7a6b38SJeff Roberson {
1762ae7a6b38SJeff Roberson 	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1763ae7a6b38SJeff Roberson 	    (uintptr_t)mtx);
1764ae7a6b38SJeff Roberson }
1765ae7a6b38SJeff Roberson 
1766ae7a6b38SJeff Roberson /*
1767ae7a6b38SJeff Roberson  * Switch threads.  This function has to handle threads coming in while
1768ae7a6b38SJeff Roberson  * blocked for some reason, running, or idle.  It also must deal with
1769ae7a6b38SJeff Roberson  * migrating a thread from one queue to another as running threads may
1770ae7a6b38SJeff Roberson  * be assigned elsewhere via binding.
1771ae7a6b38SJeff Roberson  */
17723db720fdSDavid Xu void
17733389af30SJulian Elischer sched_switch(struct thread *td, struct thread *newtd, int flags)
177435e6168fSJeff Roberson {
1775c02bbb43SJeff Roberson 	struct tdq *tdq;
1776ad1e7d28SJulian Elischer 	struct td_sched *ts;
1777ae7a6b38SJeff Roberson 	struct mtx *mtx;
1778c47f202bSJeff Roberson 	int srqflag;
1779ae7a6b38SJeff Roberson 	int cpuid;
178035e6168fSJeff Roberson 
17817b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
17826d55b3ecSJeff Roberson 	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
178335e6168fSJeff Roberson 
1784ae7a6b38SJeff Roberson 	cpuid = PCPU_GET(cpuid);
1785ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpuid);
1786e7d50326SJeff Roberson 	ts = td->td_sched;
1787c47f202bSJeff Roberson 	mtx = td->td_lock;
1788ae7a6b38SJeff Roberson 	ts->ts_rltick = ticks;
1789060563ecSJulian Elischer 	td->td_lastcpu = td->td_oncpu;
1790060563ecSJulian Elischer 	td->td_oncpu = NOCPU;
179152eb8464SJohn Baldwin 	td->td_flags &= ~TDF_NEEDRESCHED;
179277918643SStephan Uphoff 	td->td_owepreempt = 0;
17931690c6c1SJeff Roberson 	tdq->tdq_switchcnt++;
1794b11fdad0SJeff Roberson 	/*
1795ae7a6b38SJeff Roberson 	 * The lock pointer in an idle thread should never change.  Reset it
1796ae7a6b38SJeff Roberson 	 * to CAN_RUN as well.
1797b11fdad0SJeff Roberson 	 */
1798486a9414SJulian Elischer 	if (TD_IS_IDLETHREAD(td)) {
1799ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1800bf0acc27SJohn Baldwin 		TD_SET_CAN_RUN(td);
18017b20fb19SJeff Roberson 	} else if (TD_IS_RUNNING(td)) {
1802ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1803c47f202bSJeff Roberson 		srqflag = (flags & SW_PREEMPT) ?
1804598b368dSJeff Roberson 		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1805c47f202bSJeff Roberson 		    SRQ_OURSELF|SRQ_YIELDING;
1806c47f202bSJeff Roberson 		if (ts->ts_cpu == cpuid)
18079727e637SJeff Roberson 			tdq_runq_add(tdq, td, srqflag);
1808c47f202bSJeff Roberson 		else
1809c47f202bSJeff Roberson 			mtx = sched_switch_migrate(tdq, td, srqflag);
1810ae7a6b38SJeff Roberson 	} else {
1811ae7a6b38SJeff Roberson 		/* This thread must be going to sleep. */
1812ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
1813ae7a6b38SJeff Roberson 		mtx = thread_block_switch(td);
18149727e637SJeff Roberson 		tdq_load_rem(tdq, td);
1815ae7a6b38SJeff Roberson 	}
1816ae7a6b38SJeff Roberson 	/*
1817ae7a6b38SJeff Roberson 	 * We enter here with the thread blocked and assigned to the
1818ae7a6b38SJeff Roberson 	 * appropriate cpu run-queue or sleep-queue and with the current
1819ae7a6b38SJeff Roberson 	 * thread-queue locked.
1820ae7a6b38SJeff Roberson 	 */
1821ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
18222454aaf5SJeff Roberson 	newtd = choosethread();
1823ae7a6b38SJeff Roberson 	/*
1824ae7a6b38SJeff Roberson 	 * Call the MD code to switch contexts if necessary.
1825ae7a6b38SJeff Roberson 	 */
1826ebccf1e3SJoseph Koshy 	if (td != newtd) {
1827ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1828ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1829ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1830ebccf1e3SJoseph Koshy #endif
1831eea4f254SJeff Roberson 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
183259c68134SJeff Roberson 		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
18336f5f25e5SJohn Birrell 
18346f5f25e5SJohn Birrell #ifdef KDTRACE_HOOKS
18356f5f25e5SJohn Birrell 		/*
18366f5f25e5SJohn Birrell 		 * If DTrace has set the active vtime enum to anything
18376f5f25e5SJohn Birrell 		 * other than INACTIVE (0), then it should have set the
18386f5f25e5SJohn Birrell 		 * function to call.
18396f5f25e5SJohn Birrell 		 */
18406f5f25e5SJohn Birrell 		if (dtrace_vtime_active)
18416f5f25e5SJohn Birrell 			(*dtrace_vtime_switch_func)(newtd);
18426f5f25e5SJohn Birrell #endif
18436f5f25e5SJohn Birrell 
1844ae7a6b38SJeff Roberson 		cpu_switch(td, newtd, mtx);
1845ae7a6b38SJeff Roberson 		/*
1846ae7a6b38SJeff Roberson 		 * We may return from cpu_switch on a different cpu.  However,
1847ae7a6b38SJeff Roberson 		 * we always return with td_lock pointing to the current cpu's
1848ae7a6b38SJeff Roberson 		 * run queue lock.
1849ae7a6b38SJeff Roberson 		 */
1850ae7a6b38SJeff Roberson 		cpuid = PCPU_GET(cpuid);
1851ae7a6b38SJeff Roberson 		tdq = TDQ_CPU(cpuid);
1852eea4f254SJeff Roberson 		lock_profile_obtain_lock_success(
1853eea4f254SJeff Roberson 		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1854ebccf1e3SJoseph Koshy #ifdef	HWPMC_HOOKS
1855ebccf1e3SJoseph Koshy 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1856ebccf1e3SJoseph Koshy 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1857ebccf1e3SJoseph Koshy #endif
1858ae7a6b38SJeff Roberson 	} else
1859ae7a6b38SJeff Roberson 		thread_unblock_switch(td, mtx);
1860ae7a6b38SJeff Roberson 	/*
1861ae7a6b38SJeff Roberson 	 * Assert that all went well and return.
1862ae7a6b38SJeff Roberson 	 */
1863ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1864ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1865ae7a6b38SJeff Roberson 	td->td_oncpu = cpuid;
186635e6168fSJeff Roberson }
186735e6168fSJeff Roberson 
1868ae7a6b38SJeff Roberson /*
1869ae7a6b38SJeff Roberson  * Adjust thread priorities as a result of a nice request.
1870ae7a6b38SJeff Roberson  */
187135e6168fSJeff Roberson void
1872fa885116SJulian Elischer sched_nice(struct proc *p, int nice)
187335e6168fSJeff Roberson {
187435e6168fSJeff Roberson 	struct thread *td;
187535e6168fSJeff Roberson 
1876fa885116SJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
1877e7d50326SJeff Roberson 
1878fa885116SJulian Elischer 	p->p_nice = nice;
18798460a577SJohn Birrell 	FOREACH_THREAD_IN_PROC(p, td) {
18807b20fb19SJeff Roberson 		thread_lock(td);
18818460a577SJohn Birrell 		sched_priority(td);
1882e7d50326SJeff Roberson 		sched_prio(td, td->td_base_user_pri);
18837b20fb19SJeff Roberson 		thread_unlock(td);
188435e6168fSJeff Roberson 	}
1885fa885116SJulian Elischer }
188635e6168fSJeff Roberson 
1887ae7a6b38SJeff Roberson /*
1888ae7a6b38SJeff Roberson  * Record the sleep time for the interactivity scorer.
1889ae7a6b38SJeff Roberson  */
189035e6168fSJeff Roberson void
1891c5aa6b58SJeff Roberson sched_sleep(struct thread *td, int prio)
189235e6168fSJeff Roberson {
1893e7d50326SJeff Roberson 
18947b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
189535e6168fSJeff Roberson 
189654b0e65fSJeff Roberson 	td->td_slptick = ticks;
1897c5aa6b58SJeff Roberson 	if (TD_IS_SUSPENDED(td) || prio <= PSOCK)
1898c5aa6b58SJeff Roberson 		td->td_flags |= TDF_CANSWAP;
18990502fe2eSJeff Roberson 	if (static_boost == 1 && prio)
1900c5aa6b58SJeff Roberson 		sched_prio(td, prio);
19010502fe2eSJeff Roberson 	else if (static_boost && td->td_priority > static_boost)
19020502fe2eSJeff Roberson 		sched_prio(td, static_boost);
190335e6168fSJeff Roberson }
190435e6168fSJeff Roberson 
1905ae7a6b38SJeff Roberson /*
1906ae7a6b38SJeff Roberson  * Schedule a thread to resume execution and record how long it voluntarily
1907ae7a6b38SJeff Roberson  * slept.  We also update the pctcpu, interactivity, and priority.
1908ae7a6b38SJeff Roberson  */
190935e6168fSJeff Roberson void
191035e6168fSJeff Roberson sched_wakeup(struct thread *td)
191135e6168fSJeff Roberson {
191214618990SJeff Roberson 	struct td_sched *ts;
1913ae7a6b38SJeff Roberson 	int slptick;
1914e7d50326SJeff Roberson 
19157b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
191614618990SJeff Roberson 	ts = td->td_sched;
1917c5aa6b58SJeff Roberson 	td->td_flags &= ~TDF_CANSWAP;
191835e6168fSJeff Roberson 	/*
1919e7d50326SJeff Roberson 	 * If we slept for more than a tick update our interactivity and
1920e7d50326SJeff Roberson 	 * priority.
192135e6168fSJeff Roberson 	 */
192254b0e65fSJeff Roberson 	slptick = td->td_slptick;
192354b0e65fSJeff Roberson 	td->td_slptick = 0;
1924ae7a6b38SJeff Roberson 	if (slptick && slptick != ticks) {
19259a93305aSJeff Roberson 		u_int hzticks;
1926f1e8dc4aSJeff Roberson 
1927ae7a6b38SJeff Roberson 		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1928ae7a6b38SJeff Roberson 		ts->ts_slptime += hzticks;
19298460a577SJohn Birrell 		sched_interact_update(td);
193014618990SJeff Roberson 		sched_pctcpu_update(ts);
1931f1e8dc4aSJeff Roberson 	}
193214618990SJeff Roberson 	/* Reset the slice value after we sleep. */
193314618990SJeff Roberson 	ts->ts_slice = sched_slice;
19347a5e5e2aSJeff Roberson 	sched_add(td, SRQ_BORING);
193535e6168fSJeff Roberson }
193635e6168fSJeff Roberson 
193735e6168fSJeff Roberson /*
193835e6168fSJeff Roberson  * Penalize the parent for creating a new child and initialize the child's
193935e6168fSJeff Roberson  * priority.
194035e6168fSJeff Roberson  */
194135e6168fSJeff Roberson void
19428460a577SJohn Birrell sched_fork(struct thread *td, struct thread *child)
194315dc847eSJeff Roberson {
19447b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1945ad1e7d28SJulian Elischer 	sched_fork_thread(td, child);
1946e7d50326SJeff Roberson 	/*
1947e7d50326SJeff Roberson 	 * Penalize the parent and child for forking.
1948e7d50326SJeff Roberson 	 */
1949e7d50326SJeff Roberson 	sched_interact_fork(child);
1950e7d50326SJeff Roberson 	sched_priority(child);
1951ae7a6b38SJeff Roberson 	td->td_sched->ts_runtime += tickincr;
1952e7d50326SJeff Roberson 	sched_interact_update(td);
1953e7d50326SJeff Roberson 	sched_priority(td);
1954ad1e7d28SJulian Elischer }
1955ad1e7d28SJulian Elischer 
1956ae7a6b38SJeff Roberson /*
1957ae7a6b38SJeff Roberson  * Fork a new thread, may be within the same process.
1958ae7a6b38SJeff Roberson  */
1959ad1e7d28SJulian Elischer void
1960ad1e7d28SJulian Elischer sched_fork_thread(struct thread *td, struct thread *child)
1961ad1e7d28SJulian Elischer {
1962ad1e7d28SJulian Elischer 	struct td_sched *ts;
1963ad1e7d28SJulian Elischer 	struct td_sched *ts2;
19648460a577SJohn Birrell 
19658b16c208SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1966e7d50326SJeff Roberson 	/*
1967e7d50326SJeff Roberson 	 * Initialize child.
1968e7d50326SJeff Roberson 	 */
1969ad1e7d28SJulian Elischer 	ts = td->td_sched;
1970ad1e7d28SJulian Elischer 	ts2 = child->td_sched;
19718b16c208SJeff Roberson 	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
19728b16c208SJeff Roberson 	child->td_cpuset = cpuset_ref(td->td_cpuset);
1973ad1e7d28SJulian Elischer 	ts2->ts_cpu = ts->ts_cpu;
19748b16c208SJeff Roberson 	ts2->ts_flags = 0;
1975e7d50326SJeff Roberson 	/*
1976e7d50326SJeff Roberson 	 * Grab our parents cpu estimation information and priority.
1977e7d50326SJeff Roberson 	 */
1978ad1e7d28SJulian Elischer 	ts2->ts_ticks = ts->ts_ticks;
1979ad1e7d28SJulian Elischer 	ts2->ts_ltick = ts->ts_ltick;
1980ad1e7d28SJulian Elischer 	ts2->ts_ftick = ts->ts_ftick;
1981e7d50326SJeff Roberson 	child->td_user_pri = td->td_user_pri;
1982e7d50326SJeff Roberson 	child->td_base_user_pri = td->td_base_user_pri;
1983e7d50326SJeff Roberson 	/*
1984e7d50326SJeff Roberson 	 * And update interactivity score.
1985e7d50326SJeff Roberson 	 */
1986ae7a6b38SJeff Roberson 	ts2->ts_slptime = ts->ts_slptime;
1987ae7a6b38SJeff Roberson 	ts2->ts_runtime = ts->ts_runtime;
1988e7d50326SJeff Roberson 	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
198915dc847eSJeff Roberson }
199015dc847eSJeff Roberson 
1991ae7a6b38SJeff Roberson /*
1992ae7a6b38SJeff Roberson  * Adjust the priority class of a thread.
1993ae7a6b38SJeff Roberson  */
199415dc847eSJeff Roberson void
19958460a577SJohn Birrell sched_class(struct thread *td, int class)
199615dc847eSJeff Roberson {
199715dc847eSJeff Roberson 
19987b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
19998460a577SJohn Birrell 	if (td->td_pri_class == class)
200015dc847eSJeff Roberson 		return;
20018460a577SJohn Birrell 	td->td_pri_class = class;
200235e6168fSJeff Roberson }
200335e6168fSJeff Roberson 
200435e6168fSJeff Roberson /*
200535e6168fSJeff Roberson  * Return some of the child's priority and interactivity to the parent.
200635e6168fSJeff Roberson  */
200735e6168fSJeff Roberson void
2008fc6c30f6SJulian Elischer sched_exit(struct proc *p, struct thread *child)
200935e6168fSJeff Roberson {
2010e7d50326SJeff Roberson 	struct thread *td;
2011141ad61cSJeff Roberson 
20128460a577SJohn Birrell 	CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
2013431f8906SJulian Elischer 	    child, child->td_name, child->td_priority);
20148460a577SJohn Birrell 
2015374ae2a3SJeff Roberson 	PROC_LOCK_ASSERT(p, MA_OWNED);
2016e7d50326SJeff Roberson 	td = FIRST_THREAD_IN_PROC(p);
2017e7d50326SJeff Roberson 	sched_exit_thread(td, child);
2018ad1e7d28SJulian Elischer }
2019ad1e7d28SJulian Elischer 
2020ae7a6b38SJeff Roberson /*
2021ae7a6b38SJeff Roberson  * Penalize another thread for the time spent on this one.  This helps to
2022ae7a6b38SJeff Roberson  * worsen the priority and interactivity of processes which schedule batch
2023ae7a6b38SJeff Roberson  * jobs such as make.  This has little effect on the make process itself but
2024ae7a6b38SJeff Roberson  * causes new processes spawned by it to receive worse scores immediately.
2025ae7a6b38SJeff Roberson  */
2026ad1e7d28SJulian Elischer void
2027fc6c30f6SJulian Elischer sched_exit_thread(struct thread *td, struct thread *child)
2028ad1e7d28SJulian Elischer {
2029fc6c30f6SJulian Elischer 
2030e7d50326SJeff Roberson 	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
2031431f8906SJulian Elischer 	    child, child->td_name, child->td_priority);
2032e7d50326SJeff Roberson 
2033e7d50326SJeff Roberson 	/*
2034e7d50326SJeff Roberson 	 * Give the child's runtime to the parent without returning the
2035e7d50326SJeff Roberson 	 * sleep time as a penalty to the parent.  This causes shells that
2036e7d50326SJeff Roberson 	 * launch expensive things to mark their children as expensive.
2037e7d50326SJeff Roberson 	 */
20387b20fb19SJeff Roberson 	thread_lock(td);
2039ae7a6b38SJeff Roberson 	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2040fc6c30f6SJulian Elischer 	sched_interact_update(td);
2041e7d50326SJeff Roberson 	sched_priority(td);
20427b20fb19SJeff Roberson 	thread_unlock(td);
2043ad1e7d28SJulian Elischer }
2044ad1e7d28SJulian Elischer 
2045ff256d9cSJeff Roberson void
2046ff256d9cSJeff Roberson sched_preempt(struct thread *td)
2047ff256d9cSJeff Roberson {
2048ff256d9cSJeff Roberson 	struct tdq *tdq;
2049ff256d9cSJeff Roberson 
2050ff256d9cSJeff Roberson 	thread_lock(td);
2051ff256d9cSJeff Roberson 	tdq = TDQ_SELF();
2052ff256d9cSJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2053ff256d9cSJeff Roberson 	tdq->tdq_ipipending = 0;
2054ff256d9cSJeff Roberson 	if (td->td_priority > tdq->tdq_lowpri) {
20558df78c41SJeff Roberson 		int flags;
20568df78c41SJeff Roberson 
20578df78c41SJeff Roberson 		flags = SW_INVOL | SW_PREEMPT;
2058ff256d9cSJeff Roberson 		if (td->td_critnest > 1)
2059ff256d9cSJeff Roberson 			td->td_owepreempt = 1;
20608df78c41SJeff Roberson 		else if (TD_IS_IDLETHREAD(td))
20618df78c41SJeff Roberson 			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2062ff256d9cSJeff Roberson 		else
20638df78c41SJeff Roberson 			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2064ff256d9cSJeff Roberson 	}
2065ff256d9cSJeff Roberson 	thread_unlock(td);
2066ff256d9cSJeff Roberson }
2067ff256d9cSJeff Roberson 
2068ae7a6b38SJeff Roberson /*
2069ae7a6b38SJeff Roberson  * Fix priorities on return to user-space.  Priorities may be elevated due
2070ae7a6b38SJeff Roberson  * to static priorities in msleep() or similar.
2071ae7a6b38SJeff Roberson  */
2072ad1e7d28SJulian Elischer void
2073ad1e7d28SJulian Elischer sched_userret(struct thread *td)
2074ad1e7d28SJulian Elischer {
2075ad1e7d28SJulian Elischer 	/*
2076ad1e7d28SJulian Elischer 	 * XXX we cheat slightly on the locking here to avoid locking in
2077ad1e7d28SJulian Elischer 	 * the usual case.  Setting td_priority here is essentially an
2078ad1e7d28SJulian Elischer 	 * incomplete workaround for not setting it properly elsewhere.
2079ad1e7d28SJulian Elischer 	 * Now that some interrupt handlers are threads, not setting it
2080ad1e7d28SJulian Elischer 	 * properly elsewhere can clobber it in the window between setting
2081ad1e7d28SJulian Elischer 	 * it here and returning to user mode, so don't waste time setting
2082ad1e7d28SJulian Elischer 	 * it perfectly here.
2083ad1e7d28SJulian Elischer 	 */
2084ad1e7d28SJulian Elischer 	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2085ad1e7d28SJulian Elischer 	    ("thread with borrowed priority returning to userland"));
2086ad1e7d28SJulian Elischer 	if (td->td_priority != td->td_user_pri) {
20877b20fb19SJeff Roberson 		thread_lock(td);
2088ad1e7d28SJulian Elischer 		td->td_priority = td->td_user_pri;
2089ad1e7d28SJulian Elischer 		td->td_base_pri = td->td_user_pri;
209062fa74d9SJeff Roberson 		tdq_setlowpri(TDQ_SELF(), td);
20917b20fb19SJeff Roberson 		thread_unlock(td);
2092ad1e7d28SJulian Elischer         }
209335e6168fSJeff Roberson }
209435e6168fSJeff Roberson 
2095ae7a6b38SJeff Roberson /*
2096ae7a6b38SJeff Roberson  * Handle a stathz tick.  This is really only relevant for timeshare
2097ae7a6b38SJeff Roberson  * threads.
2098ae7a6b38SJeff Roberson  */
209935e6168fSJeff Roberson void
21007cf90fb3SJeff Roberson sched_clock(struct thread *td)
210135e6168fSJeff Roberson {
2102ad1e7d28SJulian Elischer 	struct tdq *tdq;
2103ad1e7d28SJulian Elischer 	struct td_sched *ts;
210435e6168fSJeff Roberson 
2105ae7a6b38SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
21063f872f85SJeff Roberson 	tdq = TDQ_SELF();
21077fcf154aSJeff Roberson #ifdef SMP
21087fcf154aSJeff Roberson 	/*
21097fcf154aSJeff Roberson 	 * We run the long term load balancer infrequently on the first cpu.
21107fcf154aSJeff Roberson 	 */
21117fcf154aSJeff Roberson 	if (balance_tdq == tdq) {
21127fcf154aSJeff Roberson 		if (balance_ticks && --balance_ticks == 0)
21137fcf154aSJeff Roberson 			sched_balance();
21147fcf154aSJeff Roberson 	}
21157fcf154aSJeff Roberson #endif
21163f872f85SJeff Roberson 	/*
21171690c6c1SJeff Roberson 	 * Save the old switch count so we have a record of the last ticks
21181690c6c1SJeff Roberson 	 * activity.   Initialize the new switch count based on our load.
21191690c6c1SJeff Roberson 	 * If there is some activity seed it to reflect that.
21201690c6c1SJeff Roberson 	 */
21211690c6c1SJeff Roberson 	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
21226c47aaaeSJeff Roberson 	tdq->tdq_switchcnt = tdq->tdq_load;
21231690c6c1SJeff Roberson 	/*
21243f872f85SJeff Roberson 	 * Advance the insert index once for each tick to ensure that all
21253f872f85SJeff Roberson 	 * threads get a chance to run.
21263f872f85SJeff Roberson 	 */
21273f872f85SJeff Roberson 	if (tdq->tdq_idx == tdq->tdq_ridx) {
21283f872f85SJeff Roberson 		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
21293f872f85SJeff Roberson 		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
21303f872f85SJeff Roberson 			tdq->tdq_ridx = tdq->tdq_idx;
21313f872f85SJeff Roberson 	}
21323f872f85SJeff Roberson 	ts = td->td_sched;
2133fd0b8c78SJeff Roberson 	if (td->td_pri_class & PRI_FIFO_BIT)
2134a8949de2SJeff Roberson 		return;
2135fd0b8c78SJeff Roberson 	if (td->td_pri_class == PRI_TIMESHARE) {
2136a8949de2SJeff Roberson 		/*
2137fd0b8c78SJeff Roberson 		 * We used a tick; charge it to the thread so
2138fd0b8c78SJeff Roberson 		 * that we can compute our interactivity.
213915dc847eSJeff Roberson 		 */
2140ae7a6b38SJeff Roberson 		td->td_sched->ts_runtime += tickincr;
21418460a577SJohn Birrell 		sched_interact_update(td);
214273daf66fSJeff Roberson 		sched_priority(td);
2143fd0b8c78SJeff Roberson 	}
214435e6168fSJeff Roberson 	/*
214535e6168fSJeff Roberson 	 * We used up one time slice.
214635e6168fSJeff Roberson 	 */
2147ad1e7d28SJulian Elischer 	if (--ts->ts_slice > 0)
214815dc847eSJeff Roberson 		return;
214935e6168fSJeff Roberson 	/*
215073daf66fSJeff Roberson 	 * We're out of time, force a requeue at userret().
215135e6168fSJeff Roberson 	 */
215273daf66fSJeff Roberson 	ts->ts_slice = sched_slice;
21534a338afdSJulian Elischer 	td->td_flags |= TDF_NEEDRESCHED;
215435e6168fSJeff Roberson }
215535e6168fSJeff Roberson 
2156ae7a6b38SJeff Roberson /*
2157ae7a6b38SJeff Roberson  * Called once per hz tick.  Used for cpu utilization information.  This
2158ae7a6b38SJeff Roberson  * is easier than trying to scale based on stathz.
2159ae7a6b38SJeff Roberson  */
2160ae7a6b38SJeff Roberson void
2161ae7a6b38SJeff Roberson sched_tick(void)
2162ae7a6b38SJeff Roberson {
2163ae7a6b38SJeff Roberson 	struct td_sched *ts;
2164ae7a6b38SJeff Roberson 
2165ae7a6b38SJeff Roberson 	ts = curthread->td_sched;
2166ae7a6b38SJeff Roberson 	/* Adjust ticks for pctcpu */
2167ae7a6b38SJeff Roberson 	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2168ae7a6b38SJeff Roberson 	ts->ts_ltick = ticks;
2169ae7a6b38SJeff Roberson 	/*
2170ae7a6b38SJeff Roberson 	 * Update if we've exceeded our desired tick threshhold by over one
2171ae7a6b38SJeff Roberson 	 * second.
2172ae7a6b38SJeff Roberson 	 */
2173ae7a6b38SJeff Roberson 	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2174ae7a6b38SJeff Roberson 		sched_pctcpu_update(ts);
2175ae7a6b38SJeff Roberson }
2176ae7a6b38SJeff Roberson 
2177ae7a6b38SJeff Roberson /*
2178ae7a6b38SJeff Roberson  * Return whether the current CPU has runnable tasks.  Used for in-kernel
2179ae7a6b38SJeff Roberson  * cooperative idle threads.
2180ae7a6b38SJeff Roberson  */
218135e6168fSJeff Roberson int
218235e6168fSJeff Roberson sched_runnable(void)
218335e6168fSJeff Roberson {
2184ad1e7d28SJulian Elischer 	struct tdq *tdq;
2185b90816f1SJeff Roberson 	int load;
218635e6168fSJeff Roberson 
2187b90816f1SJeff Roberson 	load = 1;
2188b90816f1SJeff Roberson 
2189ad1e7d28SJulian Elischer 	tdq = TDQ_SELF();
21903f741ca1SJeff Roberson 	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2191d2ad694cSJeff Roberson 		if (tdq->tdq_load > 0)
21923f741ca1SJeff Roberson 			goto out;
21933f741ca1SJeff Roberson 	} else
2194d2ad694cSJeff Roberson 		if (tdq->tdq_load - 1 > 0)
2195b90816f1SJeff Roberson 			goto out;
2196b90816f1SJeff Roberson 	load = 0;
2197b90816f1SJeff Roberson out:
2198b90816f1SJeff Roberson 	return (load);
219935e6168fSJeff Roberson }
220035e6168fSJeff Roberson 
2201ae7a6b38SJeff Roberson /*
2202ae7a6b38SJeff Roberson  * Choose the highest priority thread to run.  The thread is removed from
2203ae7a6b38SJeff Roberson  * the run-queue while running however the load remains.  For SMP we set
2204ae7a6b38SJeff Roberson  * the tdq in the global idle bitmask if it idles here.
2205ae7a6b38SJeff Roberson  */
22067a5e5e2aSJeff Roberson struct thread *
2207c9f25d8fSJeff Roberson sched_choose(void)
2208c9f25d8fSJeff Roberson {
22099727e637SJeff Roberson 	struct thread *td;
2210ae7a6b38SJeff Roberson 	struct tdq *tdq;
2211ae7a6b38SJeff Roberson 
2212ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2213ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
22149727e637SJeff Roberson 	td = tdq_choose(tdq);
22159727e637SJeff Roberson 	if (td) {
22169727e637SJeff Roberson 		td->td_sched->ts_ltick = ticks;
22179727e637SJeff Roberson 		tdq_runq_rem(tdq, td);
22180502fe2eSJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
22199727e637SJeff Roberson 		return (td);
222035e6168fSJeff Roberson 	}
22210502fe2eSJeff Roberson 	tdq->tdq_lowpri = PRI_MAX_IDLE;
222262fa74d9SJeff Roberson 	return (PCPU_GET(idlethread));
22237a5e5e2aSJeff Roberson }
22247a5e5e2aSJeff Roberson 
2225ae7a6b38SJeff Roberson /*
2226ae7a6b38SJeff Roberson  * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2227ae7a6b38SJeff Roberson  * we always request it once we exit a critical section.
2228ae7a6b38SJeff Roberson  */
2229ae7a6b38SJeff Roberson static inline void
2230ae7a6b38SJeff Roberson sched_setpreempt(struct thread *td)
22317a5e5e2aSJeff Roberson {
22327a5e5e2aSJeff Roberson 	struct thread *ctd;
22337a5e5e2aSJeff Roberson 	int cpri;
22347a5e5e2aSJeff Roberson 	int pri;
22357a5e5e2aSJeff Roberson 
2236ff256d9cSJeff Roberson 	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2237ff256d9cSJeff Roberson 
22387a5e5e2aSJeff Roberson 	ctd = curthread;
22397a5e5e2aSJeff Roberson 	pri = td->td_priority;
22407a5e5e2aSJeff Roberson 	cpri = ctd->td_priority;
2241ff256d9cSJeff Roberson 	if (pri < cpri)
2242ff256d9cSJeff Roberson 		ctd->td_flags |= TDF_NEEDRESCHED;
22437a5e5e2aSJeff Roberson 	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2244ae7a6b38SJeff Roberson 		return;
2245ff256d9cSJeff Roberson 	if (!sched_shouldpreempt(pri, cpri, 0))
2246ae7a6b38SJeff Roberson 		return;
22477a5e5e2aSJeff Roberson 	ctd->td_owepreempt = 1;
224835e6168fSJeff Roberson }
224935e6168fSJeff Roberson 
2250ae7a6b38SJeff Roberson /*
225173daf66fSJeff Roberson  * Add a thread to a thread queue.  Select the appropriate runq and add the
225273daf66fSJeff Roberson  * thread to it.  This is the internal function called when the tdq is
225373daf66fSJeff Roberson  * predetermined.
2254ae7a6b38SJeff Roberson  */
225535e6168fSJeff Roberson void
2256ae7a6b38SJeff Roberson tdq_add(struct tdq *tdq, struct thread *td, int flags)
225735e6168fSJeff Roberson {
2258c9f25d8fSJeff Roberson 
2259ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
22607a5e5e2aSJeff Roberson 	KASSERT((td->td_inhibitors == 0),
22617a5e5e2aSJeff Roberson 	    ("sched_add: trying to run inhibited thread"));
22627a5e5e2aSJeff Roberson 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
22637a5e5e2aSJeff Roberson 	    ("sched_add: bad thread state"));
2264b61ce5b0SJeff Roberson 	KASSERT(td->td_flags & TDF_INMEM,
2265b61ce5b0SJeff Roberson 	    ("sched_add: thread swapped out"));
2266ae7a6b38SJeff Roberson 
2267ae7a6b38SJeff Roberson 	if (td->td_priority < tdq->tdq_lowpri)
2268ae7a6b38SJeff Roberson 		tdq->tdq_lowpri = td->td_priority;
22699727e637SJeff Roberson 	tdq_runq_add(tdq, td, flags);
22709727e637SJeff Roberson 	tdq_load_add(tdq, td);
2271ae7a6b38SJeff Roberson }
2272ae7a6b38SJeff Roberson 
2273ae7a6b38SJeff Roberson /*
2274ae7a6b38SJeff Roberson  * Select the target thread queue and add a thread to it.  Request
2275ae7a6b38SJeff Roberson  * preemption or IPI a remote processor if required.
2276ae7a6b38SJeff Roberson  */
2277ae7a6b38SJeff Roberson void
2278ae7a6b38SJeff Roberson sched_add(struct thread *td, int flags)
2279ae7a6b38SJeff Roberson {
2280ae7a6b38SJeff Roberson 	struct tdq *tdq;
22817b8bfa0dSJeff Roberson #ifdef SMP
2282ae7a6b38SJeff Roberson 	int cpu;
2283ae7a6b38SJeff Roberson #endif
2284ae7a6b38SJeff Roberson 	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
2285431f8906SJulian Elischer 	    td, td->td_name, td->td_priority, curthread,
2286431f8906SJulian Elischer 	    curthread->td_name);
2287ae7a6b38SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2288ae7a6b38SJeff Roberson 	/*
2289ae7a6b38SJeff Roberson 	 * Recalculate the priority before we select the target cpu or
2290ae7a6b38SJeff Roberson 	 * run-queue.
2291ae7a6b38SJeff Roberson 	 */
2292ae7a6b38SJeff Roberson 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2293ae7a6b38SJeff Roberson 		sched_priority(td);
2294ae7a6b38SJeff Roberson #ifdef SMP
2295ae7a6b38SJeff Roberson 	/*
2296ae7a6b38SJeff Roberson 	 * Pick the destination cpu and if it isn't ours transfer to the
2297ae7a6b38SJeff Roberson 	 * target cpu.
2298ae7a6b38SJeff Roberson 	 */
22999727e637SJeff Roberson 	cpu = sched_pickcpu(td, flags);
23009727e637SJeff Roberson 	tdq = sched_setcpu(td, cpu, flags);
2301ae7a6b38SJeff Roberson 	tdq_add(tdq, td, flags);
230273daf66fSJeff Roberson 	if (cpu != PCPU_GET(cpuid)) {
23039727e637SJeff Roberson 		tdq_notify(tdq, td);
23047b8bfa0dSJeff Roberson 		return;
23057b8bfa0dSJeff Roberson 	}
2306ae7a6b38SJeff Roberson #else
2307ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
2308ae7a6b38SJeff Roberson 	TDQ_LOCK(tdq);
2309ae7a6b38SJeff Roberson 	/*
2310ae7a6b38SJeff Roberson 	 * Now that the thread is moving to the run-queue, set the lock
2311ae7a6b38SJeff Roberson 	 * to the scheduler's lock.
2312ae7a6b38SJeff Roberson 	 */
2313ae7a6b38SJeff Roberson 	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2314ae7a6b38SJeff Roberson 	tdq_add(tdq, td, flags);
23157b8bfa0dSJeff Roberson #endif
2316ae7a6b38SJeff Roberson 	if (!(flags & SRQ_YIELDING))
2317ae7a6b38SJeff Roberson 		sched_setpreempt(td);
231835e6168fSJeff Roberson }
231935e6168fSJeff Roberson 
2320ae7a6b38SJeff Roberson /*
2321ae7a6b38SJeff Roberson  * Remove a thread from a run-queue without running it.  This is used
2322ae7a6b38SJeff Roberson  * when we're stealing a thread from a remote queue.  Otherwise all threads
2323ae7a6b38SJeff Roberson  * exit by calling sched_exit_thread() and sched_throw() themselves.
2324ae7a6b38SJeff Roberson  */
232535e6168fSJeff Roberson void
23267cf90fb3SJeff Roberson sched_rem(struct thread *td)
232735e6168fSJeff Roberson {
2328ad1e7d28SJulian Elischer 	struct tdq *tdq;
23297cf90fb3SJeff Roberson 
233081d47d3fSJeff Roberson 	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
2331431f8906SJulian Elischer 	    td, td->td_name, td->td_priority, curthread,
2332431f8906SJulian Elischer 	    curthread->td_name);
23339727e637SJeff Roberson 	tdq = TDQ_CPU(td->td_sched->ts_cpu);
2334ae7a6b38SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2335ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
23367a5e5e2aSJeff Roberson 	KASSERT(TD_ON_RUNQ(td),
2337ad1e7d28SJulian Elischer 	    ("sched_rem: thread not on run queue"));
23389727e637SJeff Roberson 	tdq_runq_rem(tdq, td);
23399727e637SJeff Roberson 	tdq_load_rem(tdq, td);
23407a5e5e2aSJeff Roberson 	TD_SET_CAN_RUN(td);
234162fa74d9SJeff Roberson 	if (td->td_priority == tdq->tdq_lowpri)
234262fa74d9SJeff Roberson 		tdq_setlowpri(tdq, NULL);
234335e6168fSJeff Roberson }
234435e6168fSJeff Roberson 
2345ae7a6b38SJeff Roberson /*
2346ae7a6b38SJeff Roberson  * Fetch cpu utilization information.  Updates on demand.
2347ae7a6b38SJeff Roberson  */
234835e6168fSJeff Roberson fixpt_t
23497cf90fb3SJeff Roberson sched_pctcpu(struct thread *td)
235035e6168fSJeff Roberson {
235135e6168fSJeff Roberson 	fixpt_t pctcpu;
2352ad1e7d28SJulian Elischer 	struct td_sched *ts;
235335e6168fSJeff Roberson 
235435e6168fSJeff Roberson 	pctcpu = 0;
2355ad1e7d28SJulian Elischer 	ts = td->td_sched;
2356ad1e7d28SJulian Elischer 	if (ts == NULL)
2357484288deSJeff Roberson 		return (0);
235835e6168fSJeff Roberson 
23597b20fb19SJeff Roberson 	thread_lock(td);
2360ad1e7d28SJulian Elischer 	if (ts->ts_ticks) {
236135e6168fSJeff Roberson 		int rtick;
236235e6168fSJeff Roberson 
2363ad1e7d28SJulian Elischer 		sched_pctcpu_update(ts);
236435e6168fSJeff Roberson 		/* How many rtick per second ? */
2365e7d50326SJeff Roberson 		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2366e7d50326SJeff Roberson 		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
236735e6168fSJeff Roberson 	}
23687b20fb19SJeff Roberson 	thread_unlock(td);
236935e6168fSJeff Roberson 
237035e6168fSJeff Roberson 	return (pctcpu);
237135e6168fSJeff Roberson }
237235e6168fSJeff Roberson 
237362fa74d9SJeff Roberson /*
237462fa74d9SJeff Roberson  * Enforce affinity settings for a thread.  Called after adjustments to
237562fa74d9SJeff Roberson  * cpumask.
237662fa74d9SJeff Roberson  */
2377885d51a3SJeff Roberson void
2378885d51a3SJeff Roberson sched_affinity(struct thread *td)
2379885d51a3SJeff Roberson {
238062fa74d9SJeff Roberson #ifdef SMP
238162fa74d9SJeff Roberson 	struct td_sched *ts;
238262fa74d9SJeff Roberson 	int cpu;
238362fa74d9SJeff Roberson 
238462fa74d9SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
238562fa74d9SJeff Roberson 	ts = td->td_sched;
238662fa74d9SJeff Roberson 	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
238762fa74d9SJeff Roberson 		return;
238862fa74d9SJeff Roberson 	if (!TD_IS_RUNNING(td))
238962fa74d9SJeff Roberson 		return;
239062fa74d9SJeff Roberson 	td->td_flags |= TDF_NEEDRESCHED;
239162fa74d9SJeff Roberson 	if (!THREAD_CAN_MIGRATE(td))
239262fa74d9SJeff Roberson 		return;
239362fa74d9SJeff Roberson 	/*
239462fa74d9SJeff Roberson 	 * Assign the new cpu and force a switch before returning to
239562fa74d9SJeff Roberson 	 * userspace.  If the target thread is not running locally send
239662fa74d9SJeff Roberson 	 * an ipi to force the issue.
239762fa74d9SJeff Roberson 	 */
239862fa74d9SJeff Roberson 	cpu = ts->ts_cpu;
23999727e637SJeff Roberson 	ts->ts_cpu = sched_pickcpu(td, 0);
240062fa74d9SJeff Roberson 	if (cpu != PCPU_GET(cpuid))
240162fa74d9SJeff Roberson 		ipi_selected(1 << cpu, IPI_PREEMPT);
240262fa74d9SJeff Roberson #endif
2403885d51a3SJeff Roberson }
2404885d51a3SJeff Roberson 
2405ae7a6b38SJeff Roberson /*
2406ae7a6b38SJeff Roberson  * Bind a thread to a target cpu.
2407ae7a6b38SJeff Roberson  */
24089bacd788SJeff Roberson void
24099bacd788SJeff Roberson sched_bind(struct thread *td, int cpu)
24109bacd788SJeff Roberson {
2411ad1e7d28SJulian Elischer 	struct td_sched *ts;
24129bacd788SJeff Roberson 
2413c47f202bSJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2414ad1e7d28SJulian Elischer 	ts = td->td_sched;
24156b2f763fSJeff Roberson 	if (ts->ts_flags & TSF_BOUND)
2416c95d2db2SJeff Roberson 		sched_unbind(td);
2417ad1e7d28SJulian Elischer 	ts->ts_flags |= TSF_BOUND;
24186b2f763fSJeff Roberson 	sched_pin();
241980f86c9fSJeff Roberson 	if (PCPU_GET(cpuid) == cpu)
24209bacd788SJeff Roberson 		return;
24216b2f763fSJeff Roberson 	ts->ts_cpu = cpu;
24229bacd788SJeff Roberson 	/* When we return from mi_switch we'll be on the correct cpu. */
2423279f949eSPoul-Henning Kamp 	mi_switch(SW_VOL, NULL);
24249bacd788SJeff Roberson }
24259bacd788SJeff Roberson 
2426ae7a6b38SJeff Roberson /*
2427ae7a6b38SJeff Roberson  * Release a bound thread.
2428ae7a6b38SJeff Roberson  */
24299bacd788SJeff Roberson void
24309bacd788SJeff Roberson sched_unbind(struct thread *td)
24319bacd788SJeff Roberson {
2432e7d50326SJeff Roberson 	struct td_sched *ts;
2433e7d50326SJeff Roberson 
24347b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2435e7d50326SJeff Roberson 	ts = td->td_sched;
24366b2f763fSJeff Roberson 	if ((ts->ts_flags & TSF_BOUND) == 0)
24376b2f763fSJeff Roberson 		return;
2438e7d50326SJeff Roberson 	ts->ts_flags &= ~TSF_BOUND;
2439e7d50326SJeff Roberson 	sched_unpin();
24409bacd788SJeff Roberson }
24419bacd788SJeff Roberson 
244235e6168fSJeff Roberson int
2443ebccf1e3SJoseph Koshy sched_is_bound(struct thread *td)
2444ebccf1e3SJoseph Koshy {
24457b20fb19SJeff Roberson 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2446ad1e7d28SJulian Elischer 	return (td->td_sched->ts_flags & TSF_BOUND);
2447ebccf1e3SJoseph Koshy }
2448ebccf1e3SJoseph Koshy 
2449ae7a6b38SJeff Roberson /*
2450ae7a6b38SJeff Roberson  * Basic yield call.
2451ae7a6b38SJeff Roberson  */
245236ec198bSDavid Xu void
245336ec198bSDavid Xu sched_relinquish(struct thread *td)
245436ec198bSDavid Xu {
24557b20fb19SJeff Roberson 	thread_lock(td);
24568df78c41SJeff Roberson 	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
24577b20fb19SJeff Roberson 	thread_unlock(td);
245836ec198bSDavid Xu }
245936ec198bSDavid Xu 
2460ae7a6b38SJeff Roberson /*
2461ae7a6b38SJeff Roberson  * Return the total system load.
2462ae7a6b38SJeff Roberson  */
2463ebccf1e3SJoseph Koshy int
246433916c36SJeff Roberson sched_load(void)
246533916c36SJeff Roberson {
246633916c36SJeff Roberson #ifdef SMP
246733916c36SJeff Roberson 	int total;
246833916c36SJeff Roberson 	int i;
246933916c36SJeff Roberson 
247033916c36SJeff Roberson 	total = 0;
247162fa74d9SJeff Roberson 	for (i = 0; i <= mp_maxid; i++)
247262fa74d9SJeff Roberson 		total += TDQ_CPU(i)->tdq_sysload;
247333916c36SJeff Roberson 	return (total);
247433916c36SJeff Roberson #else
2475d2ad694cSJeff Roberson 	return (TDQ_SELF()->tdq_sysload);
247633916c36SJeff Roberson #endif
247733916c36SJeff Roberson }
247833916c36SJeff Roberson 
247933916c36SJeff Roberson int
248035e6168fSJeff Roberson sched_sizeof_proc(void)
248135e6168fSJeff Roberson {
248235e6168fSJeff Roberson 	return (sizeof(struct proc));
248335e6168fSJeff Roberson }
248435e6168fSJeff Roberson 
248535e6168fSJeff Roberson int
248635e6168fSJeff Roberson sched_sizeof_thread(void)
248735e6168fSJeff Roberson {
248835e6168fSJeff Roberson 	return (sizeof(struct thread) + sizeof(struct td_sched));
248935e6168fSJeff Roberson }
2490b41f1452SDavid Xu 
24917a5e5e2aSJeff Roberson /*
24927a5e5e2aSJeff Roberson  * The actual idle process.
24937a5e5e2aSJeff Roberson  */
24947a5e5e2aSJeff Roberson void
24957a5e5e2aSJeff Roberson sched_idletd(void *dummy)
24967a5e5e2aSJeff Roberson {
24977a5e5e2aSJeff Roberson 	struct thread *td;
2498ae7a6b38SJeff Roberson 	struct tdq *tdq;
24991690c6c1SJeff Roberson 	int switchcnt;
25001690c6c1SJeff Roberson 	int i;
25017a5e5e2aSJeff Roberson 
25027a5e5e2aSJeff Roberson 	td = curthread;
2503ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
25047a5e5e2aSJeff Roberson 	mtx_assert(&Giant, MA_NOTOWNED);
2505ae7a6b38SJeff Roberson 	/* ULE relies on preemption for idle interruption. */
2506ae7a6b38SJeff Roberson 	for (;;) {
25071690c6c1SJeff Roberson 		tdq->tdq_idlestate = TDQ_RUNNING;
2508ae7a6b38SJeff Roberson #ifdef SMP
25091690c6c1SJeff Roberson 		if (tdq_idled(tdq) == 0)
25101690c6c1SJeff Roberson 			continue;
2511ae7a6b38SJeff Roberson #endif
25121690c6c1SJeff Roberson 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
25131690c6c1SJeff Roberson 		/*
25141690c6c1SJeff Roberson 		 * If we're switching very frequently, spin while checking
25151690c6c1SJeff Roberson 		 * for load rather than entering a low power state that
25161690c6c1SJeff Roberson 		 * requires an IPI.
25171690c6c1SJeff Roberson 		 */
25181690c6c1SJeff Roberson 		if (switchcnt > sched_idlespinthresh) {
25191690c6c1SJeff Roberson 			for (i = 0; i < sched_idlespins; i++) {
25201690c6c1SJeff Roberson 				if (tdq->tdq_load)
25211690c6c1SJeff Roberson 					break;
25221690c6c1SJeff Roberson 				cpu_spinwait();
25231690c6c1SJeff Roberson 			}
25241690c6c1SJeff Roberson 		}
25251690c6c1SJeff Roberson 		/*
25261690c6c1SJeff Roberson 		 * We must set our state to IDLE before checking
25271690c6c1SJeff Roberson 		 * tdq_load for the last time to avoid a race with
25281690c6c1SJeff Roberson 		 * tdq_notify().
25291690c6c1SJeff Roberson 		 */
25301690c6c1SJeff Roberson 		if (tdq->tdq_load == 0) {
25316c47aaaeSJeff Roberson 			switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
25321690c6c1SJeff Roberson 			tdq->tdq_idlestate = TDQ_IDLE;
25331690c6c1SJeff Roberson 			if (tdq->tdq_load == 0)
25346c47aaaeSJeff Roberson 				cpu_idle(switchcnt > 1);
25351690c6c1SJeff Roberson 		}
25361690c6c1SJeff Roberson 		if (tdq->tdq_load) {
25371690c6c1SJeff Roberson 			thread_lock(td);
25381690c6c1SJeff Roberson 			mi_switch(SW_VOL | SWT_IDLE, NULL);
25391690c6c1SJeff Roberson 			thread_unlock(td);
25401690c6c1SJeff Roberson 		}
2541ae7a6b38SJeff Roberson 	}
2542b41f1452SDavid Xu }
2543e7d50326SJeff Roberson 
25447b20fb19SJeff Roberson /*
25457b20fb19SJeff Roberson  * A CPU is entering for the first time or a thread is exiting.
25467b20fb19SJeff Roberson  */
25477b20fb19SJeff Roberson void
25487b20fb19SJeff Roberson sched_throw(struct thread *td)
25497b20fb19SJeff Roberson {
255059c68134SJeff Roberson 	struct thread *newtd;
2551ae7a6b38SJeff Roberson 	struct tdq *tdq;
2552ae7a6b38SJeff Roberson 
2553ae7a6b38SJeff Roberson 	tdq = TDQ_SELF();
25547b20fb19SJeff Roberson 	if (td == NULL) {
2555ae7a6b38SJeff Roberson 		/* Correct spinlock nesting and acquire the correct lock. */
2556ae7a6b38SJeff Roberson 		TDQ_LOCK(tdq);
25577b20fb19SJeff Roberson 		spinlock_exit();
25587b20fb19SJeff Roberson 	} else {
2559ae7a6b38SJeff Roberson 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
25609727e637SJeff Roberson 		tdq_load_rem(tdq, td);
2561eea4f254SJeff Roberson 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
25627b20fb19SJeff Roberson 	}
25637b20fb19SJeff Roberson 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
256459c68134SJeff Roberson 	newtd = choosethread();
256559c68134SJeff Roberson 	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
25667b20fb19SJeff Roberson 	PCPU_SET(switchtime, cpu_ticks());
25677b20fb19SJeff Roberson 	PCPU_SET(switchticks, ticks);
256859c68134SJeff Roberson 	cpu_throw(td, newtd);		/* doesn't return */
25697b20fb19SJeff Roberson }
25707b20fb19SJeff Roberson 
2571ae7a6b38SJeff Roberson /*
2572ae7a6b38SJeff Roberson  * This is called from fork_exit().  Just acquire the correct locks and
2573ae7a6b38SJeff Roberson  * let fork do the rest of the work.
2574ae7a6b38SJeff Roberson  */
25757b20fb19SJeff Roberson void
2576fe54587fSJeff Roberson sched_fork_exit(struct thread *td)
25777b20fb19SJeff Roberson {
2578ae7a6b38SJeff Roberson 	struct td_sched *ts;
2579ae7a6b38SJeff Roberson 	struct tdq *tdq;
2580ae7a6b38SJeff Roberson 	int cpuid;
25817b20fb19SJeff Roberson 
25827b20fb19SJeff Roberson 	/*
25837b20fb19SJeff Roberson 	 * Finish setting up thread glue so that it begins execution in a
2584ae7a6b38SJeff Roberson 	 * non-nested critical section with the scheduler lock held.
25857b20fb19SJeff Roberson 	 */
2586ae7a6b38SJeff Roberson 	cpuid = PCPU_GET(cpuid);
2587ae7a6b38SJeff Roberson 	tdq = TDQ_CPU(cpuid);
2588ae7a6b38SJeff Roberson 	ts = td->td_sched;
2589ae7a6b38SJeff Roberson 	if (TD_IS_IDLETHREAD(td))
2590ae7a6b38SJeff Roberson 		td->td_lock = TDQ_LOCKPTR(tdq);
2591ae7a6b38SJeff Roberson 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2592ae7a6b38SJeff Roberson 	td->td_oncpu = cpuid;
259359c68134SJeff Roberson 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2594eea4f254SJeff Roberson 	lock_profile_obtain_lock_success(
2595eea4f254SJeff Roberson 	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
25967b20fb19SJeff Roberson }
25977b20fb19SJeff Roberson 
25989727e637SJeff Roberson SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2599ae7a6b38SJeff Roberson SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2600e7d50326SJeff Roberson     "Scheduler name");
2601ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2602ae7a6b38SJeff Roberson     "Slice size for timeshare threads");
2603ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2604ae7a6b38SJeff Roberson      "Interactivity score threshold");
2605ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2606ae7a6b38SJeff Roberson      0,"Min priority for preemption, lower priorities have greater precedence");
2607c5aa6b58SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost,
2608c5aa6b58SJeff Roberson      0,"Controls whether static kernel priorities are assigned to sleeping threads.");
26091690c6c1SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins,
26101690c6c1SJeff Roberson      0,"Number of times idle will spin waiting for new work.");
26111690c6c1SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW, &sched_idlespinthresh,
26121690c6c1SJeff Roberson      0,"Threshold before we will permit idle spinning.");
26137b8bfa0dSJeff Roberson #ifdef SMP
2614ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2615ae7a6b38SJeff Roberson     "Number of hz ticks to keep thread affinity for");
2616ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2617ae7a6b38SJeff Roberson     "Enables the long-term load balancer");
26187fcf154aSJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
26197fcf154aSJeff Roberson     &balance_interval, 0,
26207fcf154aSJeff Roberson     "Average frequency in stathz ticks to run the long-term balancer");
2621ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2622ae7a6b38SJeff Roberson     "Steals work from another hyper-threaded core on idle");
2623ae7a6b38SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2624ae7a6b38SJeff Roberson     "Attempts to steal work from other cores before idling");
262528994a58SJeff Roberson SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
262628994a58SJeff Roberson     "Minimum load on remote cpu before we'll steal");
26277b8bfa0dSJeff Roberson #endif
2628e7d50326SJeff Roberson 
262954b0e65fSJeff Roberson /* ps compat.  All cpu percentages from ULE are weighted. */
2630a5423ea3SJeff Roberson static int ccpu = 0;
2631e7d50326SJeff Roberson SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2632