sched_ule.c revision 172207
1109864Sjeff/*-
2165762Sjeff * Copyright (c) 2002-2007, Jeffrey Roberson <jeff@freebsd.org>
3109864Sjeff * All rights reserved.
4109864Sjeff *
5109864Sjeff * Redistribution and use in source and binary forms, with or without
6109864Sjeff * modification, are permitted provided that the following conditions
7109864Sjeff * are met:
8109864Sjeff * 1. Redistributions of source code must retain the above copyright
9109864Sjeff *    notice unmodified, this list of conditions, and the following
10109864Sjeff *    disclaimer.
11109864Sjeff * 2. Redistributions in binary form must reproduce the above copyright
12109864Sjeff *    notice, this list of conditions and the following disclaimer in the
13109864Sjeff *    documentation and/or other materials provided with the distribution.
14109864Sjeff *
15109864Sjeff * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16109864Sjeff * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17109864Sjeff * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18109864Sjeff * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19109864Sjeff * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20109864Sjeff * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21109864Sjeff * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22109864Sjeff * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23109864Sjeff * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24109864Sjeff * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25109864Sjeff */
26109864Sjeff
27171482Sjeff/*
28171482Sjeff * This file implements the ULE scheduler.  ULE supports independent CPU
29171482Sjeff * run queues and fine grain locking.  It has superior interactive
30171482Sjeff * performance under load even on uni-processor systems.
31171482Sjeff *
32171482Sjeff * etymology:
33171482Sjeff *   ULE is the last three letters in schedule.  It owes it's name to a
34171482Sjeff * generic user created for a scheduling system by Paul Mikesell at
35171482Sjeff * Isilon Systems and a general lack of creativity on the part of the author.
36171482Sjeff */
37171482Sjeff
38116182Sobrien#include <sys/cdefs.h>
39116182Sobrien__FBSDID("$FreeBSD: head/sys/kern/sched_ule.c 172207 2007-09-17 05:31:39Z jeff $");
40116182Sobrien
41147565Speter#include "opt_hwpmc_hooks.h"
42147565Speter#include "opt_sched.h"
43134649Sscottl
44109864Sjeff#include <sys/param.h>
45109864Sjeff#include <sys/systm.h>
46131929Smarcel#include <sys/kdb.h>
47109864Sjeff#include <sys/kernel.h>
48109864Sjeff#include <sys/ktr.h>
49109864Sjeff#include <sys/lock.h>
50109864Sjeff#include <sys/mutex.h>
51109864Sjeff#include <sys/proc.h>
52112966Sjeff#include <sys/resource.h>
53122038Sjeff#include <sys/resourcevar.h>
54109864Sjeff#include <sys/sched.h>
55109864Sjeff#include <sys/smp.h>
56109864Sjeff#include <sys/sx.h>
57109864Sjeff#include <sys/sysctl.h>
58109864Sjeff#include <sys/sysproto.h>
59139453Sjhb#include <sys/turnstile.h>
60161599Sdavidxu#include <sys/umtx.h>
61109864Sjeff#include <sys/vmmeter.h>
62109864Sjeff#ifdef KTRACE
63109864Sjeff#include <sys/uio.h>
64109864Sjeff#include <sys/ktrace.h>
65109864Sjeff#endif
66109864Sjeff
67145256Sjkoshy#ifdef HWPMC_HOOKS
68145256Sjkoshy#include <sys/pmckern.h>
69145256Sjkoshy#endif
70145256Sjkoshy
71109864Sjeff#include <machine/cpu.h>
72121790Sjeff#include <machine/smp.h>
73109864Sjeff
74166190Sjeff#ifndef PREEMPTION
75166190Sjeff#error	"SCHED_ULE requires options PREEMPTION"
76166190Sjeff#endif
77166190Sjeff
78171482Sjeff#define	KTR_ULE	0
79166137Sjeff
80166137Sjeff/*
81171482Sjeff * Thread scheduler specific section.  All fields are protected
82171482Sjeff * by the thread lock.
83146954Sjeff */
84164936Sjulianstruct td_sched {
85171482Sjeff	TAILQ_ENTRY(td_sched) ts_procq;	/* Run queue. */
86171482Sjeff	struct thread	*ts_thread;	/* Active associated thread. */
87171482Sjeff	struct runq	*ts_runq;	/* Run-queue we're queued on. */
88171482Sjeff	short		ts_flags;	/* TSF_* flags. */
89171482Sjeff	u_char		ts_rqindex;	/* Run queue index. */
90164936Sjulian	u_char		ts_cpu;		/* CPU that we have affinity for. */
91171482Sjeff	int		ts_slptick;	/* Tick when we went to sleep. */
92171482Sjeff	int		ts_slice;	/* Ticks of slice remaining. */
93171482Sjeff	u_int		ts_slptime;	/* Number of ticks we vol. slept */
94171482Sjeff	u_int		ts_runtime;	/* Number of ticks we were running */
95134791Sjulian	/* The following variables are only used for pctcpu calculation */
96164936Sjulian	int		ts_ltick;	/* Last tick that we were running on */
97164936Sjulian	int		ts_ftick;	/* First tick that we were running on */
98164936Sjulian	int		ts_ticks;	/* Tick count */
99166108Sjeff#ifdef SMP
100166108Sjeff	int		ts_rltick;	/* Real last tick, for affinity. */
101166108Sjeff#endif
102134791Sjulian};
103164936Sjulian/* flags kept in ts_flags */
104166108Sjeff#define	TSF_BOUND	0x0001		/* Thread can not migrate. */
105166108Sjeff#define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
106121790Sjeff
107164936Sjulianstatic struct td_sched td_sched0;
108109864Sjeff
109109864Sjeff/*
110165762Sjeff * Cpu percentage computation macros and defines.
111111857Sjeff *
112165762Sjeff * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
113165762Sjeff * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
114165796Sjeff * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
115165762Sjeff * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
116165762Sjeff * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
117165762Sjeff * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
118165762Sjeff */
119165762Sjeff#define	SCHED_TICK_SECS		10
120165762Sjeff#define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
121165796Sjeff#define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
122165762Sjeff#define	SCHED_TICK_SHIFT	10
123165762Sjeff#define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
124165830Sjeff#define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
125165762Sjeff
126165762Sjeff/*
127165762Sjeff * These macros determine priorities for non-interactive threads.  They are
128165762Sjeff * assigned a priority based on their recent cpu utilization as expressed
129165762Sjeff * by the ratio of ticks to the tick total.  NHALF priorities at the start
130165762Sjeff * and end of the MIN to MAX timeshare range are only reachable with negative
131165762Sjeff * or positive nice respectively.
132165762Sjeff *
133165762Sjeff * PRI_RANGE:	Priority range for utilization dependent priorities.
134116642Sjeff * PRI_NRESV:	Number of nice values.
135165762Sjeff * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
136165762Sjeff * PRI_NICE:	Determines the part of the priority inherited from nice.
137109864Sjeff */
138165762Sjeff#define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
139121869Sjeff#define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
140165762Sjeff#define	SCHED_PRI_MIN		(PRI_MIN_TIMESHARE + SCHED_PRI_NHALF)
141165762Sjeff#define	SCHED_PRI_MAX		(PRI_MAX_TIMESHARE - SCHED_PRI_NHALF)
142170787Sjeff#define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN)
143165762Sjeff#define	SCHED_PRI_TICKS(ts)						\
144165762Sjeff    (SCHED_TICK_HZ((ts)) /						\
145165827Sjeff    (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
146165762Sjeff#define	SCHED_PRI_NICE(nice)	(nice)
147109864Sjeff
148109864Sjeff/*
149165762Sjeff * These determine the interactivity of a process.  Interactivity differs from
150165762Sjeff * cpu utilization in that it expresses the voluntary time slept vs time ran
151165762Sjeff * while cpu utilization includes all time not running.  This more accurately
152165762Sjeff * models the intent of the thread.
153109864Sjeff *
154110645Sjeff * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
155110645Sjeff *		before throttling back.
156121868Sjeff * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
157116365Sjeff * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
158111857Sjeff * INTERACT_THRESH:	Threshhold for placement on the current runq.
159109864Sjeff */
160165762Sjeff#define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
161165762Sjeff#define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
162116365Sjeff#define	SCHED_INTERACT_MAX	(100)
163116365Sjeff#define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
164121126Sjeff#define	SCHED_INTERACT_THRESH	(30)
165111857Sjeff
166109864Sjeff/*
167165762Sjeff * tickincr:		Converts a stathz tick into a hz domain scaled by
168165762Sjeff *			the shift factor.  Without the shift the error rate
169165762Sjeff *			due to rounding would be unacceptably high.
170165762Sjeff * realstathz:		stathz is sometimes 0 and run off of hz.
171165762Sjeff * sched_slice:		Runtime of each thread before rescheduling.
172171482Sjeff * preempt_thresh:	Priority threshold for preemption and remote IPIs.
173109864Sjeff */
174165762Sjeffstatic int sched_interact = SCHED_INTERACT_THRESH;
175165762Sjeffstatic int realstathz;
176165762Sjeffstatic int tickincr;
177165762Sjeffstatic int sched_slice;
178171482Sjeffstatic int preempt_thresh = PRI_MIN_KERN;
179109864Sjeff
180109864Sjeff/*
181171482Sjeff * tdq - per processor runqs and statistics.  All fields are protected by the
182171482Sjeff * tdq_lock.  The load and lowpri may be accessed without to avoid excess
183171482Sjeff * locking in sched_pickcpu();
184109864Sjeff */
185164936Sjulianstruct tdq {
186171713Sjeff	struct mtx	*tdq_lock;		/* Pointer to group lock. */
187171482Sjeff	struct runq	tdq_realtime;		/* real-time run queue. */
188171482Sjeff	struct runq	tdq_timeshare;		/* timeshare run queue. */
189165620Sjeff	struct runq	tdq_idle;		/* Queue of IDLE threads. */
190171482Sjeff	int		tdq_load;		/* Aggregate load. */
191166557Sjeff	u_char		tdq_idx;		/* Current insert index. */
192166557Sjeff	u_char		tdq_ridx;		/* Current removal index. */
193110267Sjeff#ifdef SMP
194171482Sjeff	u_char		tdq_lowpri;		/* Lowest priority thread. */
195171482Sjeff	int		tdq_transferable;	/* Transferable thread count. */
196165620Sjeff	LIST_ENTRY(tdq)	tdq_siblings;		/* Next in tdq group. */
197165620Sjeff	struct tdq_group *tdq_group;		/* Our processor group. */
198125289Sjeff#else
199165620Sjeff	int		tdq_sysload;		/* For loadavg, !ITHD load. */
200110267Sjeff#endif
201171482Sjeff} __aligned(64);
202109864Sjeff
203166108Sjeff
204123433Sjeff#ifdef SMP
205109864Sjeff/*
206164936Sjulian * tdq groups are groups of processors which can cheaply share threads.  When
207123433Sjeff * one processor in the group goes idle it will check the runqs of the other
208123433Sjeff * processors in its group prior to halting and waiting for an interrupt.
209123433Sjeff * These groups are suitable for SMT (Symetric Multi-Threading) and not NUMA.
210123433Sjeff * In a numa environment we'd want an idle bitmap per group and a two tiered
211123433Sjeff * load balancer.
212123433Sjeff */
213164936Sjulianstruct tdq_group {
214171713Sjeff	struct mtx	tdg_lock;	/* Protects all fields below. */
215171713Sjeff	int		tdg_cpus;	/* Count of CPUs in this tdq group. */
216171713Sjeff	cpumask_t 	tdg_cpumask;	/* Mask of cpus in this group. */
217171713Sjeff	cpumask_t 	tdg_idlemask;	/* Idle cpus in this group. */
218171713Sjeff	cpumask_t 	tdg_mask;	/* Bit mask for first cpu. */
219171713Sjeff	int		tdg_load;	/* Total load of this group. */
220165620Sjeff	int	tdg_transferable;	/* Transferable load of this group. */
221165620Sjeff	LIST_HEAD(, tdq) tdg_members;	/* Linked list of all members. */
222171713Sjeff	char		tdg_name[16];	/* lock name. */
223171482Sjeff} __aligned(64);
224123433Sjeff
225171482Sjeff#define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 300))
226166108Sjeff#define	SCHED_AFFINITY(ts)	((ts)->ts_rltick > ticks - affinity)
227166108Sjeff
228123433Sjeff/*
229166108Sjeff * Run-time tunables.
230166108Sjeff */
231171506Sjeffstatic int rebalance = 1;
232171506Sjeffstatic int balance_secs = 1;
233171506Sjeffstatic int pick_pri = 1;
234166108Sjeffstatic int affinity;
235166108Sjeffstatic int tryself = 1;
236171482Sjeffstatic int steal_htt = 0;
237171506Sjeffstatic int steal_idle = 1;
238171506Sjeffstatic int steal_thresh = 2;
239170293Sjeffstatic int topology = 0;
240166108Sjeff
241166108Sjeff/*
242165620Sjeff * One thread queue per processor.
243109864Sjeff */
244166108Sjeffstatic volatile cpumask_t tdq_idle;
245165620Sjeffstatic int tdg_maxid;
246164936Sjulianstatic struct tdq	tdq_cpu[MAXCPU];
247164936Sjulianstatic struct tdq_group tdq_groups[MAXCPU];
248171482Sjeffstatic struct callout balco;
249171482Sjeffstatic struct callout gbalco;
250129982Sjeff
251164936Sjulian#define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
252164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu[(x)])
253171713Sjeff#define	TDQ_ID(x)	((int)((x) - tdq_cpu))
254164936Sjulian#define	TDQ_GROUP(x)	(&tdq_groups[(x)])
255171713Sjeff#define	TDG_ID(x)	((int)((x) - tdq_groups))
256123433Sjeff#else	/* !SMP */
257164936Sjulianstatic struct tdq	tdq_cpu;
258171713Sjeffstatic struct mtx	tdq_lock;
259129982Sjeff
260170315Sjeff#define	TDQ_ID(x)	(0)
261164936Sjulian#define	TDQ_SELF()	(&tdq_cpu)
262164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu)
263110028Sjeff#endif
264109864Sjeff
265171482Sjeff#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
266171482Sjeff#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
267171482Sjeff#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
268171482Sjeff#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
269171713Sjeff#define	TDQ_LOCKPTR(t)		((t)->tdq_lock)
270171482Sjeff
271163709Sjbstatic void sched_priority(struct thread *);
272146954Sjeffstatic void sched_thread_priority(struct thread *, u_char);
273163709Sjbstatic int sched_interact_score(struct thread *);
274163709Sjbstatic void sched_interact_update(struct thread *);
275163709Sjbstatic void sched_interact_fork(struct thread *);
276164936Sjulianstatic void sched_pctcpu_update(struct td_sched *);
277109864Sjeff
278110267Sjeff/* Operations on per processor queues */
279164936Sjulianstatic struct td_sched * tdq_choose(struct tdq *);
280164936Sjulianstatic void tdq_setup(struct tdq *);
281164936Sjulianstatic void tdq_load_add(struct tdq *, struct td_sched *);
282164936Sjulianstatic void tdq_load_rem(struct tdq *, struct td_sched *);
283164936Sjulianstatic __inline void tdq_runq_add(struct tdq *, struct td_sched *, int);
284164936Sjulianstatic __inline void tdq_runq_rem(struct tdq *, struct td_sched *);
285164936Sjulianvoid tdq_print(int cpu);
286165762Sjeffstatic void runq_print(struct runq *rq);
287171482Sjeffstatic void tdq_add(struct tdq *, struct thread *, int);
288110267Sjeff#ifdef SMP
289171482Sjeffstatic void tdq_move(struct tdq *, struct tdq *);
290171482Sjeffstatic int tdq_idled(struct tdq *);
291171482Sjeffstatic void tdq_notify(struct td_sched *);
292171482Sjeffstatic struct td_sched *tdq_steal(struct tdq *, int);
293164936Sjulianstatic struct td_sched *runq_steal(struct runq *);
294171482Sjeffstatic int sched_pickcpu(struct td_sched *, int);
295171482Sjeffstatic void sched_balance(void *);
296171482Sjeffstatic void sched_balance_groups(void *);
297164936Sjulianstatic void sched_balance_group(struct tdq_group *);
298164936Sjulianstatic void sched_balance_pair(struct tdq *, struct tdq *);
299171482Sjeffstatic inline struct tdq *sched_setcpu(struct td_sched *, int, int);
300171482Sjeffstatic inline struct mtx *thread_block_switch(struct thread *);
301171482Sjeffstatic inline void thread_unblock_switch(struct thread *, struct mtx *);
302171713Sjeffstatic struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
303165827Sjeff
304166108Sjeff#define	THREAD_CAN_MIGRATE(td)	 ((td)->td_pinned == 0)
305121790Sjeff#endif
306110028Sjeff
307165762Sjeffstatic void sched_setup(void *dummy);
308165762SjeffSYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
309165762Sjeff
310165762Sjeffstatic void sched_initticks(void *dummy);
311165762SjeffSYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks, NULL)
312165762Sjeff
313171482Sjeff/*
314171482Sjeff * Print the threads waiting on a run-queue.
315171482Sjeff */
316165762Sjeffstatic void
317165762Sjeffrunq_print(struct runq *rq)
318165762Sjeff{
319165762Sjeff	struct rqhead *rqh;
320165762Sjeff	struct td_sched *ts;
321165762Sjeff	int pri;
322165762Sjeff	int j;
323165762Sjeff	int i;
324165762Sjeff
325165762Sjeff	for (i = 0; i < RQB_LEN; i++) {
326165762Sjeff		printf("\t\trunq bits %d 0x%zx\n",
327165762Sjeff		    i, rq->rq_status.rqb_bits[i]);
328165762Sjeff		for (j = 0; j < RQB_BPW; j++)
329165762Sjeff			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
330165762Sjeff				pri = j + (i << RQB_L2BPW);
331165762Sjeff				rqh = &rq->rq_queues[pri];
332165762Sjeff				TAILQ_FOREACH(ts, rqh, ts_procq) {
333165762Sjeff					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
334165762Sjeff					    ts->ts_thread, ts->ts_thread->td_proc->p_comm, ts->ts_thread->td_priority, ts->ts_rqindex, pri);
335165762Sjeff				}
336165762Sjeff			}
337165762Sjeff	}
338165762Sjeff}
339165762Sjeff
340171482Sjeff/*
341171482Sjeff * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
342171482Sjeff */
343113357Sjeffvoid
344164936Sjuliantdq_print(int cpu)
345110267Sjeff{
346164936Sjulian	struct tdq *tdq;
347112994Sjeff
348164936Sjulian	tdq = TDQ_CPU(cpu);
349112994Sjeff
350171713Sjeff	printf("tdq %d:\n", TDQ_ID(tdq));
351171482Sjeff	printf("\tlockptr         %p\n", TDQ_LOCKPTR(tdq));
352165620Sjeff	printf("\tload:           %d\n", tdq->tdq_load);
353171482Sjeff	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
354165766Sjeff	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
355165762Sjeff	printf("\trealtime runq:\n");
356165762Sjeff	runq_print(&tdq->tdq_realtime);
357165762Sjeff	printf("\ttimeshare runq:\n");
358165762Sjeff	runq_print(&tdq->tdq_timeshare);
359165762Sjeff	printf("\tidle runq:\n");
360165762Sjeff	runq_print(&tdq->tdq_idle);
361121896Sjeff#ifdef SMP
362165620Sjeff	printf("\tload transferable: %d\n", tdq->tdq_transferable);
363171713Sjeff	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
364171713Sjeff	printf("\tgroup:             %d\n", TDG_ID(tdq->tdq_group));
365171713Sjeff	printf("\tLock name:         %s\n", tdq->tdq_group->tdg_name);
366121896Sjeff#endif
367113357Sjeff}
368112994Sjeff
369171482Sjeff#define	TS_RQ_PPQ	(((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
370171482Sjeff/*
371171482Sjeff * Add a thread to the actual run-queue.  Keeps transferable counts up to
372171482Sjeff * date with what is actually on the run-queue.  Selects the correct
373171482Sjeff * queue position for timeshare threads.
374171482Sjeff */
375122744Sjeffstatic __inline void
376164936Sjuliantdq_runq_add(struct tdq *tdq, struct td_sched *ts, int flags)
377122744Sjeff{
378171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
379171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
380122744Sjeff#ifdef SMP
381165762Sjeff	if (THREAD_CAN_MIGRATE(ts->ts_thread)) {
382165620Sjeff		tdq->tdq_transferable++;
383165620Sjeff		tdq->tdq_group->tdg_transferable++;
384164936Sjulian		ts->ts_flags |= TSF_XFERABLE;
385123433Sjeff	}
386122744Sjeff#endif
387165762Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
388166557Sjeff		u_char pri;
389165762Sjeff
390165762Sjeff		pri = ts->ts_thread->td_priority;
391165762Sjeff		KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
392165762Sjeff			("Invalid priority %d on timeshare runq", pri));
393165762Sjeff		/*
394165762Sjeff		 * This queue contains only priorities between MIN and MAX
395165762Sjeff		 * realtime.  Use the whole queue to represent these values.
396165762Sjeff		 */
397171713Sjeff		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
398165762Sjeff			pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
399165762Sjeff			pri = (pri + tdq->tdq_idx) % RQ_NQS;
400165766Sjeff			/*
401165766Sjeff			 * This effectively shortens the queue by one so we
402165766Sjeff			 * can have a one slot difference between idx and
403165766Sjeff			 * ridx while we wait for threads to drain.
404165766Sjeff			 */
405165766Sjeff			if (tdq->tdq_ridx != tdq->tdq_idx &&
406165766Sjeff			    pri == tdq->tdq_ridx)
407167664Sjeff				pri = (unsigned char)(pri - 1) % RQ_NQS;
408165762Sjeff		} else
409165766Sjeff			pri = tdq->tdq_ridx;
410165762Sjeff		runq_add_pri(ts->ts_runq, ts, pri, flags);
411165762Sjeff	} else
412165762Sjeff		runq_add(ts->ts_runq, ts, flags);
413122744Sjeff}
414122744Sjeff
415171482Sjeff/*
416171482Sjeff * Remove a thread from a run-queue.  This typically happens when a thread
417171482Sjeff * is selected to run.  Running threads are not on the queue and the
418171482Sjeff * transferable count does not reflect them.
419171482Sjeff */
420122744Sjeffstatic __inline void
421164936Sjuliantdq_runq_rem(struct tdq *tdq, struct td_sched *ts)
422122744Sjeff{
423171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
424171482Sjeff	KASSERT(ts->ts_runq != NULL,
425171482Sjeff	    ("tdq_runq_remove: thread %p null ts_runq", ts->ts_thread));
426122744Sjeff#ifdef SMP
427164936Sjulian	if (ts->ts_flags & TSF_XFERABLE) {
428165620Sjeff		tdq->tdq_transferable--;
429165620Sjeff		tdq->tdq_group->tdg_transferable--;
430164936Sjulian		ts->ts_flags &= ~TSF_XFERABLE;
431123433Sjeff	}
432122744Sjeff#endif
433165766Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
434165766Sjeff		if (tdq->tdq_idx != tdq->tdq_ridx)
435165766Sjeff			runq_remove_idx(ts->ts_runq, ts, &tdq->tdq_ridx);
436165766Sjeff		else
437165766Sjeff			runq_remove_idx(ts->ts_runq, ts, NULL);
438165796Sjeff		/*
439165796Sjeff		 * For timeshare threads we update the priority here so
440165796Sjeff		 * the priority reflects the time we've been sleeping.
441165796Sjeff		 */
442165796Sjeff		ts->ts_ltick = ticks;
443165796Sjeff		sched_pctcpu_update(ts);
444165796Sjeff		sched_priority(ts->ts_thread);
445165766Sjeff	} else
446165762Sjeff		runq_remove(ts->ts_runq, ts);
447122744Sjeff}
448122744Sjeff
449171482Sjeff/*
450171482Sjeff * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
451171482Sjeff * for this thread to the referenced thread queue.
452171482Sjeff */
453113357Sjeffstatic void
454164936Sjuliantdq_load_add(struct tdq *tdq, struct td_sched *ts)
455113357Sjeff{
456121896Sjeff	int class;
457171482Sjeff
458171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
459171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
460164936Sjulian	class = PRI_BASE(ts->ts_thread->td_pri_class);
461165620Sjeff	tdq->tdq_load++;
462171713Sjeff	CTR2(KTR_SCHED, "cpu %d load: %d", TDQ_ID(tdq), tdq->tdq_load);
463166108Sjeff	if (class != PRI_ITHD &&
464166108Sjeff	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
465123487Sjeff#ifdef SMP
466165620Sjeff		tdq->tdq_group->tdg_load++;
467125289Sjeff#else
468165620Sjeff		tdq->tdq_sysload++;
469123487Sjeff#endif
470110267Sjeff}
471113357Sjeff
472171482Sjeff/*
473171482Sjeff * Remove the load from a thread that is transitioning to a sleep state or
474171482Sjeff * exiting.
475171482Sjeff */
476112994Sjeffstatic void
477164936Sjuliantdq_load_rem(struct tdq *tdq, struct td_sched *ts)
478110267Sjeff{
479121896Sjeff	int class;
480171482Sjeff
481171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
482171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
483164936Sjulian	class = PRI_BASE(ts->ts_thread->td_pri_class);
484166108Sjeff	if (class != PRI_ITHD &&
485166108Sjeff	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
486123487Sjeff#ifdef SMP
487165620Sjeff		tdq->tdq_group->tdg_load--;
488125289Sjeff#else
489165620Sjeff		tdq->tdq_sysload--;
490123487Sjeff#endif
491171482Sjeff	KASSERT(tdq->tdq_load != 0,
492171713Sjeff	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
493165620Sjeff	tdq->tdq_load--;
494165620Sjeff	CTR1(KTR_SCHED, "load: %d", tdq->tdq_load);
495164936Sjulian	ts->ts_runq = NULL;
496110267Sjeff}
497110267Sjeff
498113357Sjeff#ifdef SMP
499116069Sjeff/*
500122744Sjeff * sched_balance is a simple CPU load balancing algorithm.  It operates by
501116069Sjeff * finding the least loaded and most loaded cpu and equalizing their load
502116069Sjeff * by migrating some processes.
503116069Sjeff *
504116069Sjeff * Dealing only with two CPUs at a time has two advantages.  Firstly, most
505116069Sjeff * installations will only have 2 cpus.  Secondly, load balancing too much at
506116069Sjeff * once can have an unpleasant effect on the system.  The scheduler rarely has
507116069Sjeff * enough information to make perfect decisions.  So this algorithm chooses
508171482Sjeff * simplicity and more gradual effects on load in larger systems.
509116069Sjeff *
510116069Sjeff */
511121790Sjeffstatic void
512171482Sjeffsched_balance(void *arg)
513116069Sjeff{
514164936Sjulian	struct tdq_group *high;
515164936Sjulian	struct tdq_group *low;
516165620Sjeff	struct tdq_group *tdg;
517123487Sjeff	int cnt;
518123487Sjeff	int i;
519123487Sjeff
520171506Sjeff	callout_reset(&balco, max(hz / 2, random() % (hz * balance_secs)),
521171482Sjeff	    sched_balance, NULL);
522171482Sjeff	if (smp_started == 0 || rebalance == 0)
523139334Sjeff		return;
524123487Sjeff	low = high = NULL;
525165620Sjeff	i = random() % (tdg_maxid + 1);
526165620Sjeff	for (cnt = 0; cnt <= tdg_maxid; cnt++) {
527165620Sjeff		tdg = TDQ_GROUP(i);
528123487Sjeff		/*
529123487Sjeff		 * Find the CPU with the highest load that has some
530123487Sjeff		 * threads to transfer.
531123487Sjeff		 */
532165620Sjeff		if ((high == NULL || tdg->tdg_load > high->tdg_load)
533165620Sjeff		    && tdg->tdg_transferable)
534165620Sjeff			high = tdg;
535165620Sjeff		if (low == NULL || tdg->tdg_load < low->tdg_load)
536165620Sjeff			low = tdg;
537165620Sjeff		if (++i > tdg_maxid)
538123487Sjeff			i = 0;
539123487Sjeff	}
540123487Sjeff	if (low != NULL && high != NULL && high != low)
541165620Sjeff		sched_balance_pair(LIST_FIRST(&high->tdg_members),
542165620Sjeff		    LIST_FIRST(&low->tdg_members));
543123487Sjeff}
544123487Sjeff
545171482Sjeff/*
546171482Sjeff * Balance load between CPUs in a group.  Will only migrate within the group.
547171482Sjeff */
548123487Sjeffstatic void
549171482Sjeffsched_balance_groups(void *arg)
550123487Sjeff{
551123487Sjeff	int i;
552123487Sjeff
553171506Sjeff	callout_reset(&gbalco, max(hz / 2, random() % (hz * balance_secs)),
554171482Sjeff	    sched_balance_groups, NULL);
555171482Sjeff	if (smp_started == 0 || rebalance == 0)
556171482Sjeff		return;
557171482Sjeff	for (i = 0; i <= tdg_maxid; i++)
558171482Sjeff		sched_balance_group(TDQ_GROUP(i));
559123487Sjeff}
560123487Sjeff
561171482Sjeff/*
562171482Sjeff * Finds the greatest imbalance between two tdqs in a group.
563171482Sjeff */
564123487Sjeffstatic void
565165620Sjeffsched_balance_group(struct tdq_group *tdg)
566123487Sjeff{
567164936Sjulian	struct tdq *tdq;
568164936Sjulian	struct tdq *high;
569164936Sjulian	struct tdq *low;
570123487Sjeff	int load;
571123487Sjeff
572165620Sjeff	if (tdg->tdg_transferable == 0)
573123487Sjeff		return;
574123487Sjeff	low = NULL;
575123487Sjeff	high = NULL;
576165620Sjeff	LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
577165620Sjeff		load = tdq->tdq_load;
578165620Sjeff		if (high == NULL || load > high->tdq_load)
579164936Sjulian			high = tdq;
580165620Sjeff		if (low == NULL || load < low->tdq_load)
581164936Sjulian			low = tdq;
582123487Sjeff	}
583123487Sjeff	if (high != NULL && low != NULL && high != low)
584123487Sjeff		sched_balance_pair(high, low);
585123487Sjeff}
586123487Sjeff
587171482Sjeff/*
588171482Sjeff * Lock two thread queues using their address to maintain lock order.
589171482Sjeff */
590123487Sjeffstatic void
591171482Sjefftdq_lock_pair(struct tdq *one, struct tdq *two)
592171482Sjeff{
593171482Sjeff	if (one < two) {
594171482Sjeff		TDQ_LOCK(one);
595171482Sjeff		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
596171482Sjeff	} else {
597171482Sjeff		TDQ_LOCK(two);
598171482Sjeff		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
599171482Sjeff	}
600171482Sjeff}
601171482Sjeff
602171482Sjeff/*
603171482Sjeff * Transfer load between two imbalanced thread queues.
604171482Sjeff */
605171482Sjeffstatic void
606164936Sjuliansched_balance_pair(struct tdq *high, struct tdq *low)
607123487Sjeff{
608123433Sjeff	int transferable;
609116069Sjeff	int high_load;
610116069Sjeff	int low_load;
611116069Sjeff	int move;
612116069Sjeff	int diff;
613116069Sjeff	int i;
614116069Sjeff
615171482Sjeff	tdq_lock_pair(high, low);
616116069Sjeff	/*
617123433Sjeff	 * If we're transfering within a group we have to use this specific
618164936Sjulian	 * tdq's transferable count, otherwise we can steal from other members
619123433Sjeff	 * of the group.
620123433Sjeff	 */
621165620Sjeff	if (high->tdq_group == low->tdq_group) {
622165620Sjeff		transferable = high->tdq_transferable;
623165620Sjeff		high_load = high->tdq_load;
624165620Sjeff		low_load = low->tdq_load;
625123487Sjeff	} else {
626165620Sjeff		transferable = high->tdq_group->tdg_transferable;
627165620Sjeff		high_load = high->tdq_group->tdg_load;
628165620Sjeff		low_load = low->tdq_group->tdg_load;
629123487Sjeff	}
630123433Sjeff	/*
631122744Sjeff	 * Determine what the imbalance is and then adjust that to how many
632165620Sjeff	 * threads we actually have to give up (transferable).
633122744Sjeff	 */
634171482Sjeff	if (transferable != 0) {
635171482Sjeff		diff = high_load - low_load;
636171482Sjeff		move = diff / 2;
637171482Sjeff		if (diff & 0x1)
638171482Sjeff			move++;
639171482Sjeff		move = min(move, transferable);
640171482Sjeff		for (i = 0; i < move; i++)
641171482Sjeff			tdq_move(high, low);
642171482Sjeff	}
643171482Sjeff	TDQ_UNLOCK(high);
644171482Sjeff	TDQ_UNLOCK(low);
645116069Sjeff	return;
646116069Sjeff}
647116069Sjeff
648171482Sjeff/*
649171482Sjeff * Move a thread from one thread queue to another.
650171482Sjeff */
651121790Sjeffstatic void
652171482Sjefftdq_move(struct tdq *from, struct tdq *to)
653116069Sjeff{
654171482Sjeff	struct td_sched *ts;
655171482Sjeff	struct thread *td;
656164936Sjulian	struct tdq *tdq;
657171482Sjeff	int cpu;
658116069Sjeff
659164936Sjulian	tdq = from;
660171482Sjeff	cpu = TDQ_ID(to);
661164936Sjulian	ts = tdq_steal(tdq, 1);
662164936Sjulian	if (ts == NULL) {
663165620Sjeff		struct tdq_group *tdg;
664123433Sjeff
665165620Sjeff		tdg = tdq->tdq_group;
666165620Sjeff		LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
667165620Sjeff			if (tdq == from || tdq->tdq_transferable == 0)
668123433Sjeff				continue;
669164936Sjulian			ts = tdq_steal(tdq, 1);
670123433Sjeff			break;
671123433Sjeff		}
672164936Sjulian		if (ts == NULL)
673171482Sjeff			return;
674123433Sjeff	}
675164936Sjulian	if (tdq == to)
676123433Sjeff		return;
677171482Sjeff	td = ts->ts_thread;
678171482Sjeff	/*
679171482Sjeff	 * Although the run queue is locked the thread may be blocked.  Lock
680171482Sjeff	 * it to clear this.
681171482Sjeff	 */
682171482Sjeff	thread_lock(td);
683171482Sjeff	/* Drop recursive lock on from. */
684171482Sjeff	TDQ_UNLOCK(from);
685171482Sjeff	sched_rem(td);
686166108Sjeff	ts->ts_cpu = cpu;
687171482Sjeff	td->td_lock = TDQ_LOCKPTR(to);
688171482Sjeff	tdq_add(to, td, SRQ_YIELDING);
689171505Sjeff	tdq_notify(ts);
690116069Sjeff}
691110267Sjeff
692171482Sjeff/*
693171482Sjeff * This tdq has idled.  Try to steal a thread from another cpu and switch
694171482Sjeff * to it.
695171482Sjeff */
696123433Sjeffstatic int
697164936Sjuliantdq_idled(struct tdq *tdq)
698121790Sjeff{
699165620Sjeff	struct tdq_group *tdg;
700164936Sjulian	struct tdq *steal;
701164936Sjulian	struct td_sched *ts;
702171482Sjeff	struct thread *td;
703171482Sjeff	int highload;
704171482Sjeff	int highcpu;
705171482Sjeff	int load;
706171482Sjeff	int cpu;
707123433Sjeff
708171482Sjeff	/* We don't want to be preempted while we're iterating over tdqs */
709171482Sjeff	spinlock_enter();
710165620Sjeff	tdg = tdq->tdq_group;
711123433Sjeff	/*
712165620Sjeff	 * If we're in a cpu group, try and steal threads from another cpu in
713123433Sjeff	 * the group before idling.
714123433Sjeff	 */
715166108Sjeff	if (steal_htt && tdg->tdg_cpus > 1 && tdg->tdg_transferable) {
716165620Sjeff		LIST_FOREACH(steal, &tdg->tdg_members, tdq_siblings) {
717165620Sjeff			if (steal == tdq || steal->tdq_transferable == 0)
718123433Sjeff				continue;
719171482Sjeff			TDQ_LOCK(steal);
720164936Sjulian			ts = tdq_steal(steal, 0);
721166108Sjeff			if (ts)
722166108Sjeff				goto steal;
723171482Sjeff			TDQ_UNLOCK(steal);
724166108Sjeff		}
725166108Sjeff	}
726171482Sjeff	for (;;) {
727171482Sjeff		if (steal_idle == 0)
728171482Sjeff			break;
729171482Sjeff		highcpu = 0;
730171482Sjeff		highload = 0;
731171482Sjeff		for (cpu = 0; cpu <= mp_maxid; cpu++) {
732171482Sjeff			if (CPU_ABSENT(cpu))
733171482Sjeff				continue;
734166108Sjeff			steal = TDQ_CPU(cpu);
735171482Sjeff			load = TDQ_CPU(cpu)->tdq_transferable;
736171482Sjeff			if (load < highload)
737166108Sjeff				continue;
738171482Sjeff			highload = load;
739171482Sjeff			highcpu = cpu;
740171482Sjeff		}
741171506Sjeff		if (highload < steal_thresh)
742171482Sjeff			break;
743171482Sjeff		steal = TDQ_CPU(highcpu);
744171482Sjeff		TDQ_LOCK(steal);
745171506Sjeff		if (steal->tdq_transferable >= steal_thresh &&
746171482Sjeff		    (ts = tdq_steal(steal, 1)) != NULL)
747166108Sjeff			goto steal;
748171482Sjeff		TDQ_UNLOCK(steal);
749171482Sjeff		break;
750123433Sjeff	}
751171482Sjeff	spinlock_exit();
752123433Sjeff	return (1);
753166108Sjeffsteal:
754171482Sjeff	td = ts->ts_thread;
755171482Sjeff	thread_lock(td);
756171482Sjeff	spinlock_exit();
757171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(steal));
758171482Sjeff	TDQ_UNLOCK(steal);
759171482Sjeff	sched_rem(td);
760171482Sjeff	sched_setcpu(ts, PCPU_GET(cpuid), SRQ_YIELDING);
761171482Sjeff	tdq_add(tdq, td, SRQ_YIELDING);
762171482Sjeff	MPASS(td->td_lock == curthread->td_lock);
763171482Sjeff	mi_switch(SW_VOL, NULL);
764171482Sjeff	thread_unlock(curthread);
765121790Sjeff
766166108Sjeff	return (0);
767121790Sjeff}
768121790Sjeff
769171482Sjeff/*
770171482Sjeff * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
771171482Sjeff */
772121790Sjeffstatic void
773166108Sjefftdq_notify(struct td_sched *ts)
774121790Sjeff{
775166247Sjeff	struct thread *ctd;
776121790Sjeff	struct pcpu *pcpu;
777166247Sjeff	int cpri;
778166247Sjeff	int pri;
779166108Sjeff	int cpu;
780121790Sjeff
781166108Sjeff	cpu = ts->ts_cpu;
782166247Sjeff	pri = ts->ts_thread->td_priority;
783166108Sjeff	pcpu = pcpu_find(cpu);
784166247Sjeff	ctd = pcpu->pc_curthread;
785166247Sjeff	cpri = ctd->td_priority;
786166137Sjeff
787121790Sjeff	/*
788166137Sjeff	 * If our priority is not better than the current priority there is
789166137Sjeff	 * nothing to do.
790166137Sjeff	 */
791166247Sjeff	if (pri > cpri)
792166137Sjeff		return;
793166137Sjeff	/*
794166247Sjeff	 * Always IPI idle.
795121790Sjeff	 */
796166247Sjeff	if (cpri > PRI_MIN_IDLE)
797166247Sjeff		goto sendipi;
798166247Sjeff	/*
799166247Sjeff	 * If we're realtime or better and there is timeshare or worse running
800166247Sjeff	 * send an IPI.
801166247Sjeff	 */
802166247Sjeff	if (pri < PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
803166247Sjeff		goto sendipi;
804166247Sjeff	/*
805166247Sjeff	 * Otherwise only IPI if we exceed the threshold.
806166247Sjeff	 */
807171482Sjeff	if (pri > preempt_thresh)
808165819Sjeff		return;
809166247Sjeffsendipi:
810166247Sjeff	ctd->td_flags |= TDF_NEEDRESCHED;
811171482Sjeff	ipi_selected(1 << cpu, IPI_PREEMPT);
812121790Sjeff}
813121790Sjeff
814171482Sjeff/*
815171482Sjeff * Steals load from a timeshare queue.  Honors the rotating queue head
816171482Sjeff * index.
817171482Sjeff */
818164936Sjulianstatic struct td_sched *
819171482Sjeffrunq_steal_from(struct runq *rq, u_char start)
820171482Sjeff{
821171482Sjeff	struct td_sched *ts;
822171482Sjeff	struct rqbits *rqb;
823171482Sjeff	struct rqhead *rqh;
824171482Sjeff	int first;
825171482Sjeff	int bit;
826171482Sjeff	int pri;
827171482Sjeff	int i;
828171482Sjeff
829171482Sjeff	rqb = &rq->rq_status;
830171482Sjeff	bit = start & (RQB_BPW -1);
831171482Sjeff	pri = 0;
832171482Sjeff	first = 0;
833171482Sjeffagain:
834171482Sjeff	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
835171482Sjeff		if (rqb->rqb_bits[i] == 0)
836171482Sjeff			continue;
837171482Sjeff		if (bit != 0) {
838171482Sjeff			for (pri = bit; pri < RQB_BPW; pri++)
839171482Sjeff				if (rqb->rqb_bits[i] & (1ul << pri))
840171482Sjeff					break;
841171482Sjeff			if (pri >= RQB_BPW)
842171482Sjeff				continue;
843171482Sjeff		} else
844171482Sjeff			pri = RQB_FFS(rqb->rqb_bits[i]);
845171482Sjeff		pri += (i << RQB_L2BPW);
846171482Sjeff		rqh = &rq->rq_queues[pri];
847171482Sjeff		TAILQ_FOREACH(ts, rqh, ts_procq) {
848171482Sjeff			if (first && THREAD_CAN_MIGRATE(ts->ts_thread))
849171482Sjeff				return (ts);
850171482Sjeff			first = 1;
851171482Sjeff		}
852171482Sjeff	}
853171482Sjeff	if (start != 0) {
854171482Sjeff		start = 0;
855171482Sjeff		goto again;
856171482Sjeff	}
857171482Sjeff
858171482Sjeff	return (NULL);
859171482Sjeff}
860171482Sjeff
861171482Sjeff/*
862171482Sjeff * Steals load from a standard linear queue.
863171482Sjeff */
864171482Sjeffstatic struct td_sched *
865121790Sjeffrunq_steal(struct runq *rq)
866121790Sjeff{
867121790Sjeff	struct rqhead *rqh;
868121790Sjeff	struct rqbits *rqb;
869164936Sjulian	struct td_sched *ts;
870121790Sjeff	int word;
871121790Sjeff	int bit;
872121790Sjeff
873121790Sjeff	rqb = &rq->rq_status;
874121790Sjeff	for (word = 0; word < RQB_LEN; word++) {
875121790Sjeff		if (rqb->rqb_bits[word] == 0)
876121790Sjeff			continue;
877121790Sjeff		for (bit = 0; bit < RQB_BPW; bit++) {
878123231Speter			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
879121790Sjeff				continue;
880121790Sjeff			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
881171506Sjeff			TAILQ_FOREACH(ts, rqh, ts_procq)
882171506Sjeff				if (THREAD_CAN_MIGRATE(ts->ts_thread))
883164936Sjulian					return (ts);
884121790Sjeff		}
885121790Sjeff	}
886121790Sjeff	return (NULL);
887121790Sjeff}
888121790Sjeff
889171482Sjeff/*
890171482Sjeff * Attempt to steal a thread in priority order from a thread queue.
891171482Sjeff */
892164936Sjulianstatic struct td_sched *
893164936Sjuliantdq_steal(struct tdq *tdq, int stealidle)
894121790Sjeff{
895164936Sjulian	struct td_sched *ts;
896121790Sjeff
897171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
898165762Sjeff	if ((ts = runq_steal(&tdq->tdq_realtime)) != NULL)
899164936Sjulian		return (ts);
900171482Sjeff	if ((ts = runq_steal_from(&tdq->tdq_timeshare, tdq->tdq_ridx)) != NULL)
901164936Sjulian		return (ts);
902123433Sjeff	if (stealidle)
903165620Sjeff		return (runq_steal(&tdq->tdq_idle));
904123433Sjeff	return (NULL);
905121790Sjeff}
906123433Sjeff
907171482Sjeff/*
908171482Sjeff * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
909171482Sjeff * current lock and returns with the assigned queue locked.  If this is
910171482Sjeff * via sched_switch() we leave the thread in a blocked state as an
911171482Sjeff * optimization.
912171482Sjeff */
913171482Sjeffstatic inline struct tdq *
914171482Sjeffsched_setcpu(struct td_sched *ts, int cpu, int flags)
915123433Sjeff{
916171482Sjeff	struct thread *td;
917171482Sjeff	struct tdq *tdq;
918123433Sjeff
919171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
920171482Sjeff
921171482Sjeff	tdq = TDQ_CPU(cpu);
922171482Sjeff	td = ts->ts_thread;
923171482Sjeff	ts->ts_cpu = cpu;
924171713Sjeff
925171713Sjeff	/* If the lock matches just return the queue. */
926171482Sjeff	if (td->td_lock == TDQ_LOCKPTR(tdq))
927171482Sjeff		return (tdq);
928171482Sjeff#ifdef notyet
929123433Sjeff	/*
930171482Sjeff	 * If the thread isn't running it's lockptr is a
931171482Sjeff	 * turnstile or a sleepqueue.  We can just lock_set without
932171482Sjeff	 * blocking.
933123685Sjeff	 */
934171482Sjeff	if (TD_CAN_RUN(td)) {
935171482Sjeff		TDQ_LOCK(tdq);
936171482Sjeff		thread_lock_set(td, TDQ_LOCKPTR(tdq));
937171482Sjeff		return (tdq);
938171482Sjeff	}
939171482Sjeff#endif
940166108Sjeff	/*
941171482Sjeff	 * The hard case, migration, we need to block the thread first to
942171482Sjeff	 * prevent order reversals with other cpus locks.
943166108Sjeff	 */
944171482Sjeff	thread_lock_block(td);
945171482Sjeff	TDQ_LOCK(tdq);
946171713Sjeff	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
947171482Sjeff	return (tdq);
948166108Sjeff}
949166108Sjeff
950171482Sjeff/*
951171482Sjeff * Find the thread queue running the lowest priority thread.
952171482Sjeff */
953166108Sjeffstatic int
954171482Sjefftdq_lowestpri(void)
955166108Sjeff{
956171482Sjeff	struct tdq *tdq;
957166108Sjeff	int lowpri;
958166108Sjeff	int lowcpu;
959166108Sjeff	int lowload;
960166108Sjeff	int load;
961171482Sjeff	int cpu;
962171482Sjeff	int pri;
963171482Sjeff
964171482Sjeff	lowload = 0;
965171482Sjeff	lowpri = lowcpu = 0;
966171482Sjeff	for (cpu = 0; cpu <= mp_maxid; cpu++) {
967171482Sjeff		if (CPU_ABSENT(cpu))
968171482Sjeff			continue;
969171482Sjeff		tdq = TDQ_CPU(cpu);
970171482Sjeff		pri = tdq->tdq_lowpri;
971171482Sjeff		load = TDQ_CPU(cpu)->tdq_load;
972171482Sjeff		CTR4(KTR_ULE,
973171482Sjeff		    "cpu %d pri %d lowcpu %d lowpri %d",
974171482Sjeff		    cpu, pri, lowcpu, lowpri);
975171482Sjeff		if (pri < lowpri)
976171482Sjeff			continue;
977171482Sjeff		if (lowpri && lowpri == pri && load > lowload)
978171482Sjeff			continue;
979171482Sjeff		lowpri = pri;
980171482Sjeff		lowcpu = cpu;
981171482Sjeff		lowload = load;
982171482Sjeff	}
983171482Sjeff
984171482Sjeff	return (lowcpu);
985171482Sjeff}
986171482Sjeff
987171482Sjeff/*
988171482Sjeff * Find the thread queue with the least load.
989171482Sjeff */
990171482Sjeffstatic int
991171482Sjefftdq_lowestload(void)
992171482Sjeff{
993171482Sjeff	struct tdq *tdq;
994171482Sjeff	int lowload;
995171482Sjeff	int lowpri;
996171482Sjeff	int lowcpu;
997171482Sjeff	int load;
998171482Sjeff	int cpu;
999171482Sjeff	int pri;
1000171482Sjeff
1001171482Sjeff	lowcpu = 0;
1002171482Sjeff	lowload = TDQ_CPU(0)->tdq_load;
1003171482Sjeff	lowpri = TDQ_CPU(0)->tdq_lowpri;
1004171482Sjeff	for (cpu = 1; cpu <= mp_maxid; cpu++) {
1005171482Sjeff		if (CPU_ABSENT(cpu))
1006171482Sjeff			continue;
1007171482Sjeff		tdq = TDQ_CPU(cpu);
1008171482Sjeff		load = tdq->tdq_load;
1009171482Sjeff		pri = tdq->tdq_lowpri;
1010171482Sjeff		CTR4(KTR_ULE, "cpu %d load %d lowcpu %d lowload %d",
1011171482Sjeff		    cpu, load, lowcpu, lowload);
1012171482Sjeff		if (load > lowload)
1013171482Sjeff			continue;
1014171482Sjeff		if (load == lowload && pri < lowpri)
1015171482Sjeff			continue;
1016171482Sjeff		lowcpu = cpu;
1017171482Sjeff		lowload = load;
1018171482Sjeff		lowpri = pri;
1019171482Sjeff	}
1020171482Sjeff
1021171482Sjeff	return (lowcpu);
1022171482Sjeff}
1023171482Sjeff
1024171482Sjeff/*
1025171482Sjeff * Pick the destination cpu for sched_add().  Respects affinity and makes
1026171482Sjeff * a determination based on load or priority of available processors.
1027171482Sjeff */
1028171482Sjeffstatic int
1029171482Sjeffsched_pickcpu(struct td_sched *ts, int flags)
1030171482Sjeff{
1031171482Sjeff	struct tdq *tdq;
1032166108Sjeff	int self;
1033166108Sjeff	int pri;
1034166108Sjeff	int cpu;
1035166108Sjeff
1036171482Sjeff	cpu = self = PCPU_GET(cpuid);
1037166108Sjeff	if (smp_started == 0)
1038166108Sjeff		return (self);
1039171506Sjeff	/*
1040171506Sjeff	 * Don't migrate a running thread from sched_switch().
1041171506Sjeff	 */
1042171506Sjeff	if (flags & SRQ_OURSELF) {
1043171506Sjeff		CTR1(KTR_ULE, "YIELDING %d",
1044171506Sjeff		    curthread->td_priority);
1045171506Sjeff		return (self);
1046171506Sjeff	}
1047166108Sjeff	pri = ts->ts_thread->td_priority;
1048171482Sjeff	cpu = ts->ts_cpu;
1049166108Sjeff	/*
1050166108Sjeff	 * Regardless of affinity, if the last cpu is idle send it there.
1051166108Sjeff	 */
1052171482Sjeff	tdq = TDQ_CPU(cpu);
1053171482Sjeff	if (tdq->tdq_lowpri > PRI_MIN_IDLE) {
1054166229Sjeff		CTR5(KTR_ULE,
1055166108Sjeff		    "ts_cpu %d idle, ltick %d ticks %d pri %d curthread %d",
1056166108Sjeff		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1057171482Sjeff		    tdq->tdq_lowpri);
1058166108Sjeff		return (ts->ts_cpu);
1059123433Sjeff	}
1060166108Sjeff	/*
1061166108Sjeff	 * If we have affinity, try to place it on the cpu we last ran on.
1062166108Sjeff	 */
1063171482Sjeff	if (SCHED_AFFINITY(ts) && tdq->tdq_lowpri > pri) {
1064166229Sjeff		CTR5(KTR_ULE,
1065166108Sjeff		    "affinity for %d, ltick %d ticks %d pri %d curthread %d",
1066166108Sjeff		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1067171482Sjeff		    tdq->tdq_lowpri);
1068166108Sjeff		return (ts->ts_cpu);
1069139334Sjeff	}
1070123433Sjeff	/*
1071166108Sjeff	 * Look for an idle group.
1072123433Sjeff	 */
1073166229Sjeff	CTR1(KTR_ULE, "tdq_idle %X", tdq_idle);
1074166108Sjeff	cpu = ffs(tdq_idle);
1075166108Sjeff	if (cpu)
1076171482Sjeff		return (--cpu);
1077171506Sjeff	/*
1078171506Sjeff	 * If there are no idle cores see if we can run the thread locally.  This may
1079171506Sjeff	 * improve locality among sleepers and wakers when there is shared data.
1080171506Sjeff	 */
1081171506Sjeff	if (tryself && pri < curthread->td_priority) {
1082171506Sjeff		CTR1(KTR_ULE, "tryself %d",
1083166108Sjeff		    curthread->td_priority);
1084166108Sjeff		return (self);
1085123433Sjeff	}
1086133427Sjeff	/*
1087166108Sjeff 	 * Now search for the cpu running the lowest priority thread with
1088166108Sjeff	 * the least load.
1089123433Sjeff	 */
1090171482Sjeff	if (pick_pri)
1091171482Sjeff		cpu = tdq_lowestpri();
1092171482Sjeff	else
1093171482Sjeff		cpu = tdq_lowestload();
1094171482Sjeff	return (cpu);
1095123433Sjeff}
1096123433Sjeff
1097121790Sjeff#endif	/* SMP */
1098121790Sjeff
1099117326Sjeff/*
1100121790Sjeff * Pick the highest priority task we have and return it.
1101117326Sjeff */
1102164936Sjulianstatic struct td_sched *
1103164936Sjuliantdq_choose(struct tdq *tdq)
1104110267Sjeff{
1105164936Sjulian	struct td_sched *ts;
1106110267Sjeff
1107171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1108165762Sjeff	ts = runq_choose(&tdq->tdq_realtime);
1109170787Sjeff	if (ts != NULL)
1110164936Sjulian		return (ts);
1111165766Sjeff	ts = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1112165762Sjeff	if (ts != NULL) {
1113170787Sjeff		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_TIMESHARE,
1114165762Sjeff		    ("tdq_choose: Invalid priority on timeshare queue %d",
1115165762Sjeff		    ts->ts_thread->td_priority));
1116165762Sjeff		return (ts);
1117165762Sjeff	}
1118110267Sjeff
1119165762Sjeff	ts = runq_choose(&tdq->tdq_idle);
1120165762Sjeff	if (ts != NULL) {
1121165762Sjeff		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_IDLE,
1122165762Sjeff		    ("tdq_choose: Invalid priority on idle queue %d",
1123165762Sjeff		    ts->ts_thread->td_priority));
1124165762Sjeff		return (ts);
1125165762Sjeff	}
1126165762Sjeff
1127165762Sjeff	return (NULL);
1128110267Sjeff}
1129110267Sjeff
1130171482Sjeff/*
1131171482Sjeff * Initialize a thread queue.
1132171482Sjeff */
1133109864Sjeffstatic void
1134164936Sjuliantdq_setup(struct tdq *tdq)
1135110028Sjeff{
1136171482Sjeff
1137171713Sjeff	if (bootverbose)
1138171713Sjeff		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1139165762Sjeff	runq_init(&tdq->tdq_realtime);
1140165762Sjeff	runq_init(&tdq->tdq_timeshare);
1141165620Sjeff	runq_init(&tdq->tdq_idle);
1142165620Sjeff	tdq->tdq_load = 0;
1143110028Sjeff}
1144110028Sjeff
1145171713Sjeff#ifdef SMP
1146110028Sjeffstatic void
1147171713Sjefftdg_setup(struct tdq_group *tdg)
1148109864Sjeff{
1149171713Sjeff	if (bootverbose)
1150171713Sjeff		printf("ULE: setup cpu group %d\n", TDG_ID(tdg));
1151171713Sjeff	snprintf(tdg->tdg_name, sizeof(tdg->tdg_name),
1152171713Sjeff	    "sched lock %d", (int)TDG_ID(tdg));
1153171713Sjeff	mtx_init(&tdg->tdg_lock, tdg->tdg_name, "sched lock",
1154171713Sjeff	    MTX_SPIN | MTX_RECURSE);
1155171713Sjeff	LIST_INIT(&tdg->tdg_members);
1156171713Sjeff	tdg->tdg_load = 0;
1157171713Sjeff	tdg->tdg_transferable = 0;
1158171713Sjeff	tdg->tdg_cpus = 0;
1159171713Sjeff	tdg->tdg_mask = 0;
1160171713Sjeff	tdg->tdg_cpumask = 0;
1161171713Sjeff	tdg->tdg_idlemask = 0;
1162171713Sjeff}
1163171713Sjeff
1164171713Sjeffstatic void
1165171713Sjefftdg_add(struct tdq_group *tdg, struct tdq *tdq)
1166171713Sjeff{
1167171713Sjeff	if (tdg->tdg_mask == 0)
1168171713Sjeff		tdg->tdg_mask |= 1 << TDQ_ID(tdq);
1169171713Sjeff	tdg->tdg_cpumask |= 1 << TDQ_ID(tdq);
1170171713Sjeff	tdg->tdg_cpus++;
1171171713Sjeff	tdq->tdq_group = tdg;
1172171713Sjeff	tdq->tdq_lock = &tdg->tdg_lock;
1173171713Sjeff	LIST_INSERT_HEAD(&tdg->tdg_members, tdq, tdq_siblings);
1174171713Sjeff	if (bootverbose)
1175171713Sjeff		printf("ULE: adding cpu %d to group %d: cpus %d mask 0x%X\n",
1176171713Sjeff		    TDQ_ID(tdq), TDG_ID(tdg), tdg->tdg_cpus, tdg->tdg_cpumask);
1177171713Sjeff}
1178171713Sjeff
1179171713Sjeffstatic void
1180171713Sjeffsched_setup_topology(void)
1181171713Sjeff{
1182171713Sjeff	struct tdq_group *tdg;
1183171713Sjeff	struct cpu_group *cg;
1184171713Sjeff	int balance_groups;
1185171482Sjeff	struct tdq *tdq;
1186109864Sjeff	int i;
1187171713Sjeff	int j;
1188109864Sjeff
1189171713Sjeff	topology = 1;
1190123487Sjeff	balance_groups = 0;
1191171713Sjeff	for (i = 0; i < smp_topology->ct_count; i++) {
1192171713Sjeff		cg = &smp_topology->ct_group[i];
1193171713Sjeff		tdg = &tdq_groups[i];
1194171713Sjeff		/*
1195171713Sjeff		 * Initialize the group.
1196171713Sjeff		 */
1197171713Sjeff		tdg_setup(tdg);
1198171713Sjeff		/*
1199171713Sjeff		 * Find all of the group members and add them.
1200171713Sjeff		 */
1201171713Sjeff		for (j = 0; j < MAXCPU; j++) {
1202171713Sjeff			if ((cg->cg_mask & (1 << j)) != 0) {
1203171713Sjeff				tdq = TDQ_CPU(j);
1204171713Sjeff				tdq_setup(tdq);
1205171713Sjeff				tdg_add(tdg, tdq);
1206171713Sjeff			}
1207171713Sjeff		}
1208171713Sjeff		if (tdg->tdg_cpus > 1)
1209171713Sjeff			balance_groups = 1;
1210171713Sjeff	}
1211171713Sjeff	tdg_maxid = smp_topology->ct_count - 1;
1212171713Sjeff	if (balance_groups)
1213171713Sjeff		sched_balance_groups(NULL);
1214171713Sjeff}
1215171713Sjeff
1216171713Sjeffstatic void
1217171713Sjeffsched_setup_smp(void)
1218171713Sjeff{
1219171713Sjeff	struct tdq_group *tdg;
1220171713Sjeff	struct tdq *tdq;
1221171713Sjeff	int cpus;
1222171713Sjeff	int i;
1223171713Sjeff
1224171713Sjeff	for (cpus = 0, i = 0; i < MAXCPU; i++) {
1225171713Sjeff		if (CPU_ABSENT(i))
1226171713Sjeff			continue;
1227165627Sjeff		tdq = &tdq_cpu[i];
1228171713Sjeff		tdg = &tdq_groups[i];
1229171713Sjeff		/*
1230171713Sjeff		 * Setup a tdq group with one member.
1231171713Sjeff		 */
1232171713Sjeff		tdg_setup(tdg);
1233171713Sjeff		tdq_setup(tdq);
1234171713Sjeff		tdg_add(tdg, tdq);
1235171713Sjeff		cpus++;
1236123433Sjeff	}
1237171713Sjeff	tdg_maxid = cpus - 1;
1238171713Sjeff}
1239123433Sjeff
1240171713Sjeff/*
1241171713Sjeff * Fake a topology with one group containing all CPUs.
1242171713Sjeff */
1243171713Sjeffstatic void
1244171713Sjeffsched_fake_topo(void)
1245171713Sjeff{
1246171713Sjeff#ifdef SCHED_FAKE_TOPOLOGY
1247171713Sjeff	static struct cpu_top top;
1248171713Sjeff	static struct cpu_group group;
1249113357Sjeff
1250171713Sjeff	top.ct_count = 1;
1251171713Sjeff	top.ct_group = &group;
1252171713Sjeff	group.cg_mask = all_cpus;
1253171713Sjeff	group.cg_count = mp_ncpus;
1254171713Sjeff	group.cg_children = 0;
1255171713Sjeff	smp_topology = &top;
1256171713Sjeff#endif
1257171713Sjeff}
1258171713Sjeff#endif
1259171713Sjeff
1260171713Sjeff/*
1261171713Sjeff * Setup the thread queues and initialize the topology based on MD
1262171713Sjeff * information.
1263171713Sjeff */
1264171713Sjeffstatic void
1265171713Sjeffsched_setup(void *dummy)
1266171713Sjeff{
1267171713Sjeff	struct tdq *tdq;
1268171713Sjeff
1269171713Sjeff	tdq = TDQ_SELF();
1270171713Sjeff#ifdef SMP
1271123487Sjeff	/*
1272171482Sjeff	 * Initialize long-term cpu balancing algorithm.
1273123487Sjeff	 */
1274171482Sjeff	callout_init(&balco, CALLOUT_MPSAFE);
1275171482Sjeff	callout_init(&gbalco, CALLOUT_MPSAFE);
1276171713Sjeff	sched_fake_topo();
1277171713Sjeff	/*
1278171713Sjeff	 * Setup tdqs based on a topology configuration or vanilla SMP based
1279171713Sjeff	 * on mp_maxid.
1280171713Sjeff	 */
1281171713Sjeff	if (smp_topology == NULL)
1282171713Sjeff		sched_setup_smp();
1283171713Sjeff	else
1284171713Sjeff		sched_setup_topology();
1285171482Sjeff	sched_balance(NULL);
1286117237Sjeff#else
1287171713Sjeff	tdq_setup(tdq);
1288171713Sjeff	mtx_init(&tdq_lock, "sched lock", "sched lock", MTX_SPIN | MTX_RECURSE);
1289171713Sjeff	tdq->tdq_lock = &tdq_lock;
1290116069Sjeff#endif
1291171482Sjeff	/*
1292171482Sjeff	 * To avoid divide-by-zero, we set realstathz a dummy value
1293171482Sjeff	 * in case which sched_clock() called before sched_initticks().
1294171482Sjeff	 */
1295171482Sjeff	realstathz = hz;
1296171482Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1297171482Sjeff	tickincr = 1 << SCHED_TICK_SHIFT;
1298171482Sjeff
1299171482Sjeff	/* Add thread0's load since it's running. */
1300171482Sjeff	TDQ_LOCK(tdq);
1301171713Sjeff	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1302171482Sjeff	tdq_load_add(tdq, &td_sched0);
1303171482Sjeff	TDQ_UNLOCK(tdq);
1304109864Sjeff}
1305109864Sjeff
1306171482Sjeff/*
1307171482Sjeff * This routine determines the tickincr after stathz and hz are setup.
1308171482Sjeff */
1309153533Sdavidxu/* ARGSUSED */
1310153533Sdavidxustatic void
1311153533Sdavidxusched_initticks(void *dummy)
1312153533Sdavidxu{
1313171482Sjeff	int incr;
1314171482Sjeff
1315153533Sdavidxu	realstathz = stathz ? stathz : hz;
1316166229Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1317153533Sdavidxu
1318153533Sdavidxu	/*
1319165762Sjeff	 * tickincr is shifted out by 10 to avoid rounding errors due to
1320165766Sjeff	 * hz not being evenly divisible by stathz on all platforms.
1321153533Sdavidxu	 */
1322171482Sjeff	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1323165762Sjeff	/*
1324165762Sjeff	 * This does not work for values of stathz that are more than
1325165762Sjeff	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1326165762Sjeff	 */
1327171482Sjeff	if (incr == 0)
1328171482Sjeff		incr = 1;
1329171482Sjeff	tickincr = incr;
1330166108Sjeff#ifdef SMP
1331171899Sjeff	/*
1332171899Sjeff	 * Set steal thresh to log2(mp_ncpu) but no greater than 4.  This
1333171899Sjeff	 * prevents excess thrashing on large machines and excess idle on
1334171899Sjeff	 * smaller machines.
1335171899Sjeff	 */
1336171899Sjeff	steal_thresh = min(ffs(mp_ncpus) - 1, 4);
1337166108Sjeff	affinity = SCHED_AFFINITY_DEFAULT;
1338166108Sjeff#endif
1339153533Sdavidxu}
1340153533Sdavidxu
1341153533Sdavidxu
1342109864Sjeff/*
1343171482Sjeff * This is the core of the interactivity algorithm.  Determines a score based
1344171482Sjeff * on past behavior.  It is the ratio of sleep time to run time scaled to
1345171482Sjeff * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1346171482Sjeff * differs from the cpu usage because it does not account for time spent
1347171482Sjeff * waiting on a run-queue.  Would be prettier if we had floating point.
1348171482Sjeff */
1349171482Sjeffstatic int
1350171482Sjeffsched_interact_score(struct thread *td)
1351171482Sjeff{
1352171482Sjeff	struct td_sched *ts;
1353171482Sjeff	int div;
1354171482Sjeff
1355171482Sjeff	ts = td->td_sched;
1356171482Sjeff	/*
1357171482Sjeff	 * The score is only needed if this is likely to be an interactive
1358171482Sjeff	 * task.  Don't go through the expense of computing it if there's
1359171482Sjeff	 * no chance.
1360171482Sjeff	 */
1361171482Sjeff	if (sched_interact <= SCHED_INTERACT_HALF &&
1362171482Sjeff		ts->ts_runtime >= ts->ts_slptime)
1363171482Sjeff			return (SCHED_INTERACT_HALF);
1364171482Sjeff
1365171482Sjeff	if (ts->ts_runtime > ts->ts_slptime) {
1366171482Sjeff		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1367171482Sjeff		return (SCHED_INTERACT_HALF +
1368171482Sjeff		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1369171482Sjeff	}
1370171482Sjeff	if (ts->ts_slptime > ts->ts_runtime) {
1371171482Sjeff		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1372171482Sjeff		return (ts->ts_runtime / div);
1373171482Sjeff	}
1374171482Sjeff	/* runtime == slptime */
1375171482Sjeff	if (ts->ts_runtime)
1376171482Sjeff		return (SCHED_INTERACT_HALF);
1377171482Sjeff
1378171482Sjeff	/*
1379171482Sjeff	 * This can happen if slptime and runtime are 0.
1380171482Sjeff	 */
1381171482Sjeff	return (0);
1382171482Sjeff
1383171482Sjeff}
1384171482Sjeff
1385171482Sjeff/*
1386109864Sjeff * Scale the scheduling priority according to the "interactivity" of this
1387109864Sjeff * process.
1388109864Sjeff */
1389113357Sjeffstatic void
1390163709Sjbsched_priority(struct thread *td)
1391109864Sjeff{
1392165762Sjeff	int score;
1393109864Sjeff	int pri;
1394109864Sjeff
1395163709Sjb	if (td->td_pri_class != PRI_TIMESHARE)
1396113357Sjeff		return;
1397112966Sjeff	/*
1398165762Sjeff	 * If the score is interactive we place the thread in the realtime
1399165762Sjeff	 * queue with a priority that is less than kernel and interrupt
1400165762Sjeff	 * priorities.  These threads are not subject to nice restrictions.
1401112966Sjeff	 *
1402171482Sjeff	 * Scores greater than this are placed on the normal timeshare queue
1403165762Sjeff	 * where the priority is partially decided by the most recent cpu
1404165762Sjeff	 * utilization and the rest is decided by nice value.
1405112966Sjeff	 */
1406165762Sjeff	score = sched_interact_score(td);
1407165762Sjeff	if (score < sched_interact) {
1408165762Sjeff		pri = PRI_MIN_REALTIME;
1409165762Sjeff		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1410165762Sjeff		    * score;
1411165762Sjeff		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1412166208Sjeff		    ("sched_priority: invalid interactive priority %d score %d",
1413166208Sjeff		    pri, score));
1414165762Sjeff	} else {
1415165762Sjeff		pri = SCHED_PRI_MIN;
1416165762Sjeff		if (td->td_sched->ts_ticks)
1417165762Sjeff			pri += SCHED_PRI_TICKS(td->td_sched);
1418165762Sjeff		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1419171482Sjeff		KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1420171482Sjeff		    ("sched_priority: invalid priority %d: nice %d, "
1421171482Sjeff		    "ticks %d ftick %d ltick %d tick pri %d",
1422171482Sjeff		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1423171482Sjeff		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1424171482Sjeff		    SCHED_PRI_TICKS(td->td_sched)));
1425165762Sjeff	}
1426165762Sjeff	sched_user_prio(td, pri);
1427112966Sjeff
1428112966Sjeff	return;
1429109864Sjeff}
1430109864Sjeff
1431121868Sjeff/*
1432121868Sjeff * This routine enforces a maximum limit on the amount of scheduling history
1433171482Sjeff * kept.  It is called after either the slptime or runtime is adjusted.  This
1434171482Sjeff * function is ugly due to integer math.
1435121868Sjeff */
1436116463Sjeffstatic void
1437163709Sjbsched_interact_update(struct thread *td)
1438116463Sjeff{
1439165819Sjeff	struct td_sched *ts;
1440166208Sjeff	u_int sum;
1441121605Sjeff
1442165819Sjeff	ts = td->td_sched;
1443171482Sjeff	sum = ts->ts_runtime + ts->ts_slptime;
1444121868Sjeff	if (sum < SCHED_SLP_RUN_MAX)
1445121868Sjeff		return;
1446121868Sjeff	/*
1447165819Sjeff	 * This only happens from two places:
1448165819Sjeff	 * 1) We have added an unusual amount of run time from fork_exit.
1449165819Sjeff	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1450165819Sjeff	 */
1451165819Sjeff	if (sum > SCHED_SLP_RUN_MAX * 2) {
1452171482Sjeff		if (ts->ts_runtime > ts->ts_slptime) {
1453171482Sjeff			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1454171482Sjeff			ts->ts_slptime = 1;
1455165819Sjeff		} else {
1456171482Sjeff			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1457171482Sjeff			ts->ts_runtime = 1;
1458165819Sjeff		}
1459165819Sjeff		return;
1460165819Sjeff	}
1461165819Sjeff	/*
1462121868Sjeff	 * If we have exceeded by more than 1/5th then the algorithm below
1463121868Sjeff	 * will not bring us back into range.  Dividing by two here forces
1464133427Sjeff	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1465121868Sjeff	 */
1466127850Sjeff	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1467171482Sjeff		ts->ts_runtime /= 2;
1468171482Sjeff		ts->ts_slptime /= 2;
1469121868Sjeff		return;
1470116463Sjeff	}
1471171482Sjeff	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1472171482Sjeff	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1473116463Sjeff}
1474116463Sjeff
1475171482Sjeff/*
1476171482Sjeff * Scale back the interactivity history when a child thread is created.  The
1477171482Sjeff * history is inherited from the parent but the thread may behave totally
1478171482Sjeff * differently.  For example, a shell spawning a compiler process.  We want
1479171482Sjeff * to learn that the compiler is behaving badly very quickly.
1480171482Sjeff */
1481121868Sjeffstatic void
1482163709Sjbsched_interact_fork(struct thread *td)
1483121868Sjeff{
1484121868Sjeff	int ratio;
1485121868Sjeff	int sum;
1486121868Sjeff
1487171482Sjeff	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1488121868Sjeff	if (sum > SCHED_SLP_RUN_FORK) {
1489121868Sjeff		ratio = sum / SCHED_SLP_RUN_FORK;
1490171482Sjeff		td->td_sched->ts_runtime /= ratio;
1491171482Sjeff		td->td_sched->ts_slptime /= ratio;
1492121868Sjeff	}
1493121868Sjeff}
1494121868Sjeff
1495113357Sjeff/*
1496171482Sjeff * Called from proc0_init() to setup the scheduler fields.
1497134791Sjulian */
1498134791Sjulianvoid
1499134791Sjulianschedinit(void)
1500134791Sjulian{
1501165762Sjeff
1502134791Sjulian	/*
1503134791Sjulian	 * Set up the scheduler specific parts of proc0.
1504134791Sjulian	 */
1505136167Sjulian	proc0.p_sched = NULL; /* XXX */
1506164936Sjulian	thread0.td_sched = &td_sched0;
1507165762Sjeff	td_sched0.ts_ltick = ticks;
1508165796Sjeff	td_sched0.ts_ftick = ticks;
1509164936Sjulian	td_sched0.ts_thread = &thread0;
1510134791Sjulian}
1511134791Sjulian
1512134791Sjulian/*
1513113357Sjeff * This is only somewhat accurate since given many processes of the same
1514113357Sjeff * priority they will switch when their slices run out, which will be
1515165762Sjeff * at most sched_slice stathz ticks.
1516113357Sjeff */
1517109864Sjeffint
1518109864Sjeffsched_rr_interval(void)
1519109864Sjeff{
1520165762Sjeff
1521165762Sjeff	/* Convert sched_slice to hz */
1522165762Sjeff	return (hz/(realstathz/sched_slice));
1523109864Sjeff}
1524109864Sjeff
1525171482Sjeff/*
1526171482Sjeff * Update the percent cpu tracking information when it is requested or
1527171482Sjeff * the total history exceeds the maximum.  We keep a sliding history of
1528171482Sjeff * tick counts that slowly decays.  This is less precise than the 4BSD
1529171482Sjeff * mechanism since it happens with less regular and frequent events.
1530171482Sjeff */
1531121790Sjeffstatic void
1532164936Sjuliansched_pctcpu_update(struct td_sched *ts)
1533109864Sjeff{
1534165762Sjeff
1535165762Sjeff	if (ts->ts_ticks == 0)
1536165762Sjeff		return;
1537165796Sjeff	if (ticks - (hz / 10) < ts->ts_ltick &&
1538165796Sjeff	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1539165796Sjeff		return;
1540109864Sjeff	/*
1541109864Sjeff	 * Adjust counters and watermark for pctcpu calc.
1542116365Sjeff	 */
1543165762Sjeff	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1544164936Sjulian		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1545165762Sjeff			    SCHED_TICK_TARG;
1546165762Sjeff	else
1547164936Sjulian		ts->ts_ticks = 0;
1548164936Sjulian	ts->ts_ltick = ticks;
1549165762Sjeff	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1550109864Sjeff}
1551109864Sjeff
1552171482Sjeff/*
1553171482Sjeff * Adjust the priority of a thread.  Move it to the appropriate run-queue
1554171482Sjeff * if necessary.  This is the back-end for several priority related
1555171482Sjeff * functions.
1556171482Sjeff */
1557165762Sjeffstatic void
1558139453Sjhbsched_thread_priority(struct thread *td, u_char prio)
1559109864Sjeff{
1560164936Sjulian	struct td_sched *ts;
1561109864Sjeff
1562139316Sjeff	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
1563139316Sjeff	    td, td->td_proc->p_comm, td->td_priority, prio, curthread,
1564139316Sjeff	    curthread->td_proc->p_comm);
1565164936Sjulian	ts = td->td_sched;
1566170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1567139453Sjhb	if (td->td_priority == prio)
1568139453Sjhb		return;
1569165762Sjeff
1570165766Sjeff	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1571121605Sjeff		/*
1572121605Sjeff		 * If the priority has been elevated due to priority
1573121605Sjeff		 * propagation, we may have to move ourselves to a new
1574165762Sjeff		 * queue.  This could be optimized to not re-add in some
1575165762Sjeff		 * cases.
1576133555Sjeff		 */
1577165762Sjeff		sched_rem(td);
1578165762Sjeff		td->td_priority = prio;
1579171482Sjeff		sched_add(td, SRQ_BORROWING);
1580171482Sjeff	} else {
1581171482Sjeff#ifdef SMP
1582171482Sjeff		struct tdq *tdq;
1583171482Sjeff
1584171482Sjeff		tdq = TDQ_CPU(ts->ts_cpu);
1585171482Sjeff		if (prio < tdq->tdq_lowpri)
1586171482Sjeff			tdq->tdq_lowpri = prio;
1587171482Sjeff#endif
1588119488Sdavidxu		td->td_priority = prio;
1589171482Sjeff	}
1590109864Sjeff}
1591109864Sjeff
1592139453Sjhb/*
1593139453Sjhb * Update a thread's priority when it is lent another thread's
1594139453Sjhb * priority.
1595139453Sjhb */
1596109864Sjeffvoid
1597139453Sjhbsched_lend_prio(struct thread *td, u_char prio)
1598139453Sjhb{
1599139453Sjhb
1600139453Sjhb	td->td_flags |= TDF_BORROWING;
1601139453Sjhb	sched_thread_priority(td, prio);
1602139453Sjhb}
1603139453Sjhb
1604139453Sjhb/*
1605139453Sjhb * Restore a thread's priority when priority propagation is
1606139453Sjhb * over.  The prio argument is the minimum priority the thread
1607139453Sjhb * needs to have to satisfy other possible priority lending
1608139453Sjhb * requests.  If the thread's regular priority is less
1609139453Sjhb * important than prio, the thread will keep a priority boost
1610139453Sjhb * of prio.
1611139453Sjhb */
1612139453Sjhbvoid
1613139453Sjhbsched_unlend_prio(struct thread *td, u_char prio)
1614139453Sjhb{
1615139453Sjhb	u_char base_pri;
1616139453Sjhb
1617139453Sjhb	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1618139453Sjhb	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1619163709Sjb		base_pri = td->td_user_pri;
1620139453Sjhb	else
1621139453Sjhb		base_pri = td->td_base_pri;
1622139453Sjhb	if (prio >= base_pri) {
1623139455Sjhb		td->td_flags &= ~TDF_BORROWING;
1624139453Sjhb		sched_thread_priority(td, base_pri);
1625139453Sjhb	} else
1626139453Sjhb		sched_lend_prio(td, prio);
1627139453Sjhb}
1628139453Sjhb
1629171482Sjeff/*
1630171482Sjeff * Standard entry for setting the priority to an absolute value.
1631171482Sjeff */
1632139453Sjhbvoid
1633139453Sjhbsched_prio(struct thread *td, u_char prio)
1634139453Sjhb{
1635139453Sjhb	u_char oldprio;
1636139453Sjhb
1637139453Sjhb	/* First, update the base priority. */
1638139453Sjhb	td->td_base_pri = prio;
1639139453Sjhb
1640139453Sjhb	/*
1641139455Sjhb	 * If the thread is borrowing another thread's priority, don't
1642139453Sjhb	 * ever lower the priority.
1643139453Sjhb	 */
1644139453Sjhb	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1645139453Sjhb		return;
1646139453Sjhb
1647139453Sjhb	/* Change the real priority. */
1648139453Sjhb	oldprio = td->td_priority;
1649139453Sjhb	sched_thread_priority(td, prio);
1650139453Sjhb
1651139453Sjhb	/*
1652139453Sjhb	 * If the thread is on a turnstile, then let the turnstile update
1653139453Sjhb	 * its state.
1654139453Sjhb	 */
1655139453Sjhb	if (TD_ON_LOCK(td) && oldprio != prio)
1656139453Sjhb		turnstile_adjust(td, oldprio);
1657139453Sjhb}
1658139455Sjhb
1659171482Sjeff/*
1660171482Sjeff * Set the base user priority, does not effect current running priority.
1661171482Sjeff */
1662139453Sjhbvoid
1663163709Sjbsched_user_prio(struct thread *td, u_char prio)
1664161599Sdavidxu{
1665161599Sdavidxu	u_char oldprio;
1666161599Sdavidxu
1667163709Sjb	td->td_base_user_pri = prio;
1668164939Sjulian	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1669164939Sjulian                return;
1670163709Sjb	oldprio = td->td_user_pri;
1671163709Sjb	td->td_user_pri = prio;
1672163709Sjb
1673161599Sdavidxu	if (TD_ON_UPILOCK(td) && oldprio != prio)
1674161599Sdavidxu		umtx_pi_adjust(td, oldprio);
1675161599Sdavidxu}
1676161599Sdavidxu
1677161599Sdavidxuvoid
1678161599Sdavidxusched_lend_user_prio(struct thread *td, u_char prio)
1679161599Sdavidxu{
1680161599Sdavidxu	u_char oldprio;
1681161599Sdavidxu
1682161599Sdavidxu	td->td_flags |= TDF_UBORROWING;
1683161599Sdavidxu
1684164091Smaxim	oldprio = td->td_user_pri;
1685163709Sjb	td->td_user_pri = prio;
1686161599Sdavidxu
1687161599Sdavidxu	if (TD_ON_UPILOCK(td) && oldprio != prio)
1688161599Sdavidxu		umtx_pi_adjust(td, oldprio);
1689161599Sdavidxu}
1690161599Sdavidxu
1691161599Sdavidxuvoid
1692161599Sdavidxusched_unlend_user_prio(struct thread *td, u_char prio)
1693161599Sdavidxu{
1694161599Sdavidxu	u_char base_pri;
1695161599Sdavidxu
1696163709Sjb	base_pri = td->td_base_user_pri;
1697161599Sdavidxu	if (prio >= base_pri) {
1698161599Sdavidxu		td->td_flags &= ~TDF_UBORROWING;
1699163709Sjb		sched_user_prio(td, base_pri);
1700161599Sdavidxu	} else
1701161599Sdavidxu		sched_lend_user_prio(td, prio);
1702161599Sdavidxu}
1703161599Sdavidxu
1704171482Sjeff/*
1705171505Sjeff * Add the thread passed as 'newtd' to the run queue before selecting
1706171505Sjeff * the next thread to run.  This is only used for KSE.
1707171505Sjeff */
1708171505Sjeffstatic void
1709171505Sjeffsched_switchin(struct tdq *tdq, struct thread *td)
1710171505Sjeff{
1711171505Sjeff#ifdef SMP
1712171505Sjeff	spinlock_enter();
1713171505Sjeff	TDQ_UNLOCK(tdq);
1714171505Sjeff	thread_lock(td);
1715171505Sjeff	spinlock_exit();
1716171505Sjeff	sched_setcpu(td->td_sched, TDQ_ID(tdq), SRQ_YIELDING);
1717171505Sjeff#else
1718171505Sjeff	td->td_lock = TDQ_LOCKPTR(tdq);
1719171505Sjeff#endif
1720171505Sjeff	tdq_add(tdq, td, SRQ_YIELDING);
1721171505Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1722171505Sjeff}
1723171505Sjeff
1724171505Sjeff/*
1725171713Sjeff * Handle migration from sched_switch().  This happens only for
1726171713Sjeff * cpu binding.
1727171713Sjeff */
1728171713Sjeffstatic struct mtx *
1729171713Sjeffsched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1730171713Sjeff{
1731171713Sjeff	struct tdq *tdn;
1732171713Sjeff
1733171713Sjeff	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1734171713Sjeff#ifdef SMP
1735171713Sjeff	/*
1736171713Sjeff	 * Do the lock dance required to avoid LOR.  We grab an extra
1737171713Sjeff	 * spinlock nesting to prevent preemption while we're
1738171713Sjeff	 * not holding either run-queue lock.
1739171713Sjeff	 */
1740171713Sjeff	spinlock_enter();
1741171713Sjeff	thread_block_switch(td);	/* This releases the lock on tdq. */
1742171713Sjeff	TDQ_LOCK(tdn);
1743171713Sjeff	tdq_add(tdn, td, flags);
1744171713Sjeff	tdq_notify(td->td_sched);
1745171713Sjeff	/*
1746171713Sjeff	 * After we unlock tdn the new cpu still can't switch into this
1747171713Sjeff	 * thread until we've unblocked it in cpu_switch().  The lock
1748171713Sjeff	 * pointers may match in the case of HTT cores.  Don't unlock here
1749171713Sjeff	 * or we can deadlock when the other CPU runs the IPI handler.
1750171713Sjeff	 */
1751171713Sjeff	if (TDQ_LOCKPTR(tdn) != TDQ_LOCKPTR(tdq)) {
1752171713Sjeff		TDQ_UNLOCK(tdn);
1753171713Sjeff		TDQ_LOCK(tdq);
1754171713Sjeff	}
1755171713Sjeff	spinlock_exit();
1756171713Sjeff#endif
1757171713Sjeff	return (TDQ_LOCKPTR(tdn));
1758171713Sjeff}
1759171713Sjeff
1760171713Sjeff/*
1761171482Sjeff * Block a thread for switching.  Similar to thread_block() but does not
1762171482Sjeff * bump the spin count.
1763171482Sjeff */
1764171482Sjeffstatic inline struct mtx *
1765171482Sjeffthread_block_switch(struct thread *td)
1766171482Sjeff{
1767171482Sjeff	struct mtx *lock;
1768171482Sjeff
1769171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1770171482Sjeff	lock = td->td_lock;
1771171482Sjeff	td->td_lock = &blocked_lock;
1772171482Sjeff	mtx_unlock_spin(lock);
1773171482Sjeff
1774171482Sjeff	return (lock);
1775171482Sjeff}
1776171482Sjeff
1777171482Sjeff/*
1778171482Sjeff * Release a thread that was blocked with thread_block_switch().
1779171482Sjeff */
1780171482Sjeffstatic inline void
1781171482Sjeffthread_unblock_switch(struct thread *td, struct mtx *mtx)
1782171482Sjeff{
1783171482Sjeff	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1784171482Sjeff	    (uintptr_t)mtx);
1785171482Sjeff}
1786171482Sjeff
1787171482Sjeff/*
1788171482Sjeff * Switch threads.  This function has to handle threads coming in while
1789171482Sjeff * blocked for some reason, running, or idle.  It also must deal with
1790171482Sjeff * migrating a thread from one queue to another as running threads may
1791171482Sjeff * be assigned elsewhere via binding.
1792171482Sjeff */
1793161599Sdavidxuvoid
1794135051Sjuliansched_switch(struct thread *td, struct thread *newtd, int flags)
1795109864Sjeff{
1796165627Sjeff	struct tdq *tdq;
1797164936Sjulian	struct td_sched *ts;
1798171482Sjeff	struct mtx *mtx;
1799171713Sjeff	int srqflag;
1800171482Sjeff	int cpuid;
1801109864Sjeff
1802170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1803109864Sjeff
1804171482Sjeff	cpuid = PCPU_GET(cpuid);
1805171482Sjeff	tdq = TDQ_CPU(cpuid);
1806164936Sjulian	ts = td->td_sched;
1807171713Sjeff	mtx = td->td_lock;
1808171482Sjeff#ifdef SMP
1809171482Sjeff	ts->ts_rltick = ticks;
1810171482Sjeff	if (newtd && newtd->td_priority < tdq->tdq_lowpri)
1811171482Sjeff		tdq->tdq_lowpri = newtd->td_priority;
1812171482Sjeff#endif
1813133555Sjeff	td->td_lastcpu = td->td_oncpu;
1814113339Sjulian	td->td_oncpu = NOCPU;
1815132266Sjhb	td->td_flags &= ~TDF_NEEDRESCHED;
1816144777Sups	td->td_owepreempt = 0;
1817123434Sjeff	/*
1818171482Sjeff	 * The lock pointer in an idle thread should never change.  Reset it
1819171482Sjeff	 * to CAN_RUN as well.
1820123434Sjeff	 */
1821167327Sjulian	if (TD_IS_IDLETHREAD(td)) {
1822171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1823139334Sjeff		TD_SET_CAN_RUN(td);
1824170293Sjeff	} else if (TD_IS_RUNNING(td)) {
1825171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1826165627Sjeff		tdq_load_rem(tdq, ts);
1827171713Sjeff		srqflag = (flags & SW_PREEMPT) ?
1828170293Sjeff		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1829171713Sjeff		    SRQ_OURSELF|SRQ_YIELDING;
1830171713Sjeff		if (ts->ts_cpu == cpuid)
1831171713Sjeff			tdq_add(tdq, td, srqflag);
1832171713Sjeff		else
1833171713Sjeff			mtx = sched_switch_migrate(tdq, td, srqflag);
1834171482Sjeff	} else {
1835171482Sjeff		/* This thread must be going to sleep. */
1836171482Sjeff		TDQ_LOCK(tdq);
1837171482Sjeff		mtx = thread_block_switch(td);
1838170293Sjeff		tdq_load_rem(tdq, ts);
1839171482Sjeff	}
1840171482Sjeff	/*
1841171482Sjeff	 * We enter here with the thread blocked and assigned to the
1842171482Sjeff	 * appropriate cpu run-queue or sleep-queue and with the current
1843171482Sjeff	 * thread-queue locked.
1844171482Sjeff	 */
1845171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1846171482Sjeff	/*
1847171505Sjeff	 * If KSE assigned a new thread just add it here and let choosethread
1848171505Sjeff	 * select the best one.
1849171482Sjeff	 */
1850171505Sjeff	if (newtd != NULL)
1851171505Sjeff		sched_switchin(tdq, newtd);
1852171482Sjeff	newtd = choosethread();
1853171482Sjeff	/*
1854171482Sjeff	 * Call the MD code to switch contexts if necessary.
1855171482Sjeff	 */
1856145256Sjkoshy	if (td != newtd) {
1857145256Sjkoshy#ifdef	HWPMC_HOOKS
1858145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1859145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1860145256Sjkoshy#endif
1861171482Sjeff		cpu_switch(td, newtd, mtx);
1862171482Sjeff		/*
1863171482Sjeff		 * We may return from cpu_switch on a different cpu.  However,
1864171482Sjeff		 * we always return with td_lock pointing to the current cpu's
1865171482Sjeff		 * run queue lock.
1866171482Sjeff		 */
1867171482Sjeff		cpuid = PCPU_GET(cpuid);
1868171482Sjeff		tdq = TDQ_CPU(cpuid);
1869171482Sjeff		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)td;
1870145256Sjkoshy#ifdef	HWPMC_HOOKS
1871145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1872145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1873145256Sjkoshy#endif
1874171482Sjeff	} else
1875171482Sjeff		thread_unblock_switch(td, mtx);
1876171482Sjeff	/*
1877171482Sjeff	 * Assert that all went well and return.
1878171482Sjeff	 */
1879171482Sjeff#ifdef SMP
1880171482Sjeff	/* We should always get here with the lowest priority td possible */
1881171482Sjeff	tdq->tdq_lowpri = td->td_priority;
1882171482Sjeff#endif
1883171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1884171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1885171482Sjeff	td->td_oncpu = cpuid;
1886109864Sjeff}
1887109864Sjeff
1888171482Sjeff/*
1889171482Sjeff * Adjust thread priorities as a result of a nice request.
1890171482Sjeff */
1891109864Sjeffvoid
1892130551Sjuliansched_nice(struct proc *p, int nice)
1893109864Sjeff{
1894109864Sjeff	struct thread *td;
1895109864Sjeff
1896130551Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
1897170293Sjeff	PROC_SLOCK_ASSERT(p, MA_OWNED);
1898165762Sjeff
1899130551Sjulian	p->p_nice = nice;
1900163709Sjb	FOREACH_THREAD_IN_PROC(p, td) {
1901170293Sjeff		thread_lock(td);
1902163709Sjb		sched_priority(td);
1903165762Sjeff		sched_prio(td, td->td_base_user_pri);
1904170293Sjeff		thread_unlock(td);
1905130551Sjulian	}
1906109864Sjeff}
1907109864Sjeff
1908171482Sjeff/*
1909171482Sjeff * Record the sleep time for the interactivity scorer.
1910171482Sjeff */
1911109864Sjeffvoid
1912126326Sjhbsched_sleep(struct thread *td)
1913109864Sjeff{
1914165762Sjeff
1915170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1916109864Sjeff
1917171482Sjeff	td->td_sched->ts_slptick = ticks;
1918109864Sjeff}
1919109864Sjeff
1920171482Sjeff/*
1921171482Sjeff * Schedule a thread to resume execution and record how long it voluntarily
1922171482Sjeff * slept.  We also update the pctcpu, interactivity, and priority.
1923171482Sjeff */
1924109864Sjeffvoid
1925109864Sjeffsched_wakeup(struct thread *td)
1926109864Sjeff{
1927166229Sjeff	struct td_sched *ts;
1928171482Sjeff	int slptick;
1929165762Sjeff
1930170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1931166229Sjeff	ts = td->td_sched;
1932109864Sjeff	/*
1933165762Sjeff	 * If we slept for more than a tick update our interactivity and
1934165762Sjeff	 * priority.
1935109864Sjeff	 */
1936171482Sjeff	slptick = ts->ts_slptick;
1937171482Sjeff	ts->ts_slptick = 0;
1938171482Sjeff	if (slptick && slptick != ticks) {
1939166208Sjeff		u_int hzticks;
1940109864Sjeff
1941171482Sjeff		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1942171482Sjeff		ts->ts_slptime += hzticks;
1943165819Sjeff		sched_interact_update(td);
1944166229Sjeff		sched_pctcpu_update(ts);
1945163709Sjb		sched_priority(td);
1946109864Sjeff	}
1947166229Sjeff	/* Reset the slice value after we sleep. */
1948166229Sjeff	ts->ts_slice = sched_slice;
1949166190Sjeff	sched_add(td, SRQ_BORING);
1950109864Sjeff}
1951109864Sjeff
1952109864Sjeff/*
1953109864Sjeff * Penalize the parent for creating a new child and initialize the child's
1954109864Sjeff * priority.
1955109864Sjeff */
1956109864Sjeffvoid
1957163709Sjbsched_fork(struct thread *td, struct thread *child)
1958109864Sjeff{
1959170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1960164936Sjulian	sched_fork_thread(td, child);
1961165762Sjeff	/*
1962165762Sjeff	 * Penalize the parent and child for forking.
1963165762Sjeff	 */
1964165762Sjeff	sched_interact_fork(child);
1965165762Sjeff	sched_priority(child);
1966171482Sjeff	td->td_sched->ts_runtime += tickincr;
1967165762Sjeff	sched_interact_update(td);
1968165762Sjeff	sched_priority(td);
1969164936Sjulian}
1970109864Sjeff
1971171482Sjeff/*
1972171482Sjeff * Fork a new thread, may be within the same process.
1973171482Sjeff */
1974164936Sjulianvoid
1975164936Sjuliansched_fork_thread(struct thread *td, struct thread *child)
1976164936Sjulian{
1977164936Sjulian	struct td_sched *ts;
1978164936Sjulian	struct td_sched *ts2;
1979164936Sjulian
1980165762Sjeff	/*
1981165762Sjeff	 * Initialize child.
1982165762Sjeff	 */
1983170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1984163709Sjb	sched_newthread(child);
1985171482Sjeff	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1986164936Sjulian	ts = td->td_sched;
1987164936Sjulian	ts2 = child->td_sched;
1988164936Sjulian	ts2->ts_cpu = ts->ts_cpu;
1989164936Sjulian	ts2->ts_runq = NULL;
1990165762Sjeff	/*
1991165762Sjeff	 * Grab our parents cpu estimation information and priority.
1992165762Sjeff	 */
1993164936Sjulian	ts2->ts_ticks = ts->ts_ticks;
1994164936Sjulian	ts2->ts_ltick = ts->ts_ltick;
1995164936Sjulian	ts2->ts_ftick = ts->ts_ftick;
1996165762Sjeff	child->td_user_pri = td->td_user_pri;
1997165762Sjeff	child->td_base_user_pri = td->td_base_user_pri;
1998165762Sjeff	/*
1999165762Sjeff	 * And update interactivity score.
2000165762Sjeff	 */
2001171482Sjeff	ts2->ts_slptime = ts->ts_slptime;
2002171482Sjeff	ts2->ts_runtime = ts->ts_runtime;
2003165762Sjeff	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
2004113357Sjeff}
2005113357Sjeff
2006171482Sjeff/*
2007171482Sjeff * Adjust the priority class of a thread.
2008171482Sjeff */
2009113357Sjeffvoid
2010163709Sjbsched_class(struct thread *td, int class)
2011113357Sjeff{
2012113357Sjeff
2013170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2014163709Sjb	if (td->td_pri_class == class)
2015113357Sjeff		return;
2016113357Sjeff
2017121896Sjeff#ifdef SMP
2018165827Sjeff	/*
2019165827Sjeff	 * On SMP if we're on the RUNQ we must adjust the transferable
2020165827Sjeff	 * count because could be changing to or from an interrupt
2021165827Sjeff	 * class.
2022165827Sjeff	 */
2023166190Sjeff	if (TD_ON_RUNQ(td)) {
2024165827Sjeff		struct tdq *tdq;
2025165827Sjeff
2026165827Sjeff		tdq = TDQ_CPU(td->td_sched->ts_cpu);
2027165827Sjeff		if (THREAD_CAN_MIGRATE(td)) {
2028165827Sjeff			tdq->tdq_transferable--;
2029165827Sjeff			tdq->tdq_group->tdg_transferable--;
2030122744Sjeff		}
2031165827Sjeff		td->td_pri_class = class;
2032165827Sjeff		if (THREAD_CAN_MIGRATE(td)) {
2033165827Sjeff			tdq->tdq_transferable++;
2034165827Sjeff			tdq->tdq_group->tdg_transferable++;
2035165827Sjeff		}
2036165827Sjeff	}
2037164936Sjulian#endif
2038163709Sjb	td->td_pri_class = class;
2039109864Sjeff}
2040109864Sjeff
2041109864Sjeff/*
2042109864Sjeff * Return some of the child's priority and interactivity to the parent.
2043109864Sjeff */
2044109864Sjeffvoid
2045164939Sjuliansched_exit(struct proc *p, struct thread *child)
2046109864Sjeff{
2047165762Sjeff	struct thread *td;
2048164939Sjulian
2049163709Sjb	CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
2050164939Sjulian	    child, child->td_proc->p_comm, child->td_priority);
2051113372Sjeff
2052170293Sjeff	PROC_SLOCK_ASSERT(p, MA_OWNED);
2053165762Sjeff	td = FIRST_THREAD_IN_PROC(p);
2054165762Sjeff	sched_exit_thread(td, child);
2055113372Sjeff}
2056113372Sjeff
2057171482Sjeff/*
2058171482Sjeff * Penalize another thread for the time spent on this one.  This helps to
2059171482Sjeff * worsen the priority and interactivity of processes which schedule batch
2060171482Sjeff * jobs such as make.  This has little effect on the make process itself but
2061171482Sjeff * causes new processes spawned by it to receive worse scores immediately.
2062171482Sjeff */
2063113372Sjeffvoid
2064164939Sjuliansched_exit_thread(struct thread *td, struct thread *child)
2065164936Sjulian{
2066165762Sjeff
2067164939Sjulian	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
2068165762Sjeff	    child, child->td_proc->p_comm, child->td_priority);
2069164939Sjulian
2070165762Sjeff#ifdef KSE
2071165762Sjeff	/*
2072165762Sjeff	 * KSE forks and exits so often that this penalty causes short-lived
2073165762Sjeff	 * threads to always be non-interactive.  This causes mozilla to
2074165762Sjeff	 * crawl under load.
2075165762Sjeff	 */
2076165762Sjeff	if ((td->td_pflags & TDP_SA) && td->td_proc == child->td_proc)
2077165762Sjeff		return;
2078165762Sjeff#endif
2079165762Sjeff	/*
2080165762Sjeff	 * Give the child's runtime to the parent without returning the
2081165762Sjeff	 * sleep time as a penalty to the parent.  This causes shells that
2082165762Sjeff	 * launch expensive things to mark their children as expensive.
2083165762Sjeff	 */
2084170293Sjeff	thread_lock(td);
2085171482Sjeff	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2086164939Sjulian	sched_interact_update(td);
2087165762Sjeff	sched_priority(td);
2088170293Sjeff	thread_unlock(td);
2089164936Sjulian}
2090164936Sjulian
2091171482Sjeff/*
2092171482Sjeff * Fix priorities on return to user-space.  Priorities may be elevated due
2093171482Sjeff * to static priorities in msleep() or similar.
2094171482Sjeff */
2095164936Sjulianvoid
2096164936Sjuliansched_userret(struct thread *td)
2097164936Sjulian{
2098164936Sjulian	/*
2099164936Sjulian	 * XXX we cheat slightly on the locking here to avoid locking in
2100164936Sjulian	 * the usual case.  Setting td_priority here is essentially an
2101164936Sjulian	 * incomplete workaround for not setting it properly elsewhere.
2102164936Sjulian	 * Now that some interrupt handlers are threads, not setting it
2103164936Sjulian	 * properly elsewhere can clobber it in the window between setting
2104164936Sjulian	 * it here and returning to user mode, so don't waste time setting
2105164936Sjulian	 * it perfectly here.
2106164936Sjulian	 */
2107164936Sjulian	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2108164936Sjulian	    ("thread with borrowed priority returning to userland"));
2109164936Sjulian	if (td->td_priority != td->td_user_pri) {
2110170293Sjeff		thread_lock(td);
2111164936Sjulian		td->td_priority = td->td_user_pri;
2112164936Sjulian		td->td_base_pri = td->td_user_pri;
2113170293Sjeff		thread_unlock(td);
2114164936Sjulian        }
2115164936Sjulian}
2116164936Sjulian
2117171482Sjeff/*
2118171482Sjeff * Handle a stathz tick.  This is really only relevant for timeshare
2119171482Sjeff * threads.
2120171482Sjeff */
2121164936Sjulianvoid
2122121127Sjeffsched_clock(struct thread *td)
2123109864Sjeff{
2124164936Sjulian	struct tdq *tdq;
2125164936Sjulian	struct td_sched *ts;
2126109864Sjeff
2127171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2128164936Sjulian	tdq = TDQ_SELF();
2129133427Sjeff	/*
2130165766Sjeff	 * Advance the insert index once for each tick to ensure that all
2131165766Sjeff	 * threads get a chance to run.
2132133427Sjeff	 */
2133165766Sjeff	if (tdq->tdq_idx == tdq->tdq_ridx) {
2134165766Sjeff		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2135165766Sjeff		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2136165766Sjeff			tdq->tdq_ridx = tdq->tdq_idx;
2137165766Sjeff	}
2138165766Sjeff	ts = td->td_sched;
2139165762Sjeff	/*
2140163709Sjb	 * We only do slicing code for TIMESHARE threads.
2141113357Sjeff	 */
2142163709Sjb	if (td->td_pri_class != PRI_TIMESHARE)
2143113357Sjeff		return;
2144113357Sjeff	/*
2145165766Sjeff	 * We used a tick; charge it to the thread so that we can compute our
2146113357Sjeff	 * interactivity.
2147109864Sjeff	 */
2148171482Sjeff	td->td_sched->ts_runtime += tickincr;
2149163709Sjb	sched_interact_update(td);
2150109864Sjeff	/*
2151109864Sjeff	 * We used up one time slice.
2152109864Sjeff	 */
2153164936Sjulian	if (--ts->ts_slice > 0)
2154113357Sjeff		return;
2155109864Sjeff	/*
2156113357Sjeff	 * We're out of time, recompute priorities and requeue.
2157109864Sjeff	 */
2158165796Sjeff	sched_priority(td);
2159113357Sjeff	td->td_flags |= TDF_NEEDRESCHED;
2160109864Sjeff}
2161109864Sjeff
2162171482Sjeff/*
2163171482Sjeff * Called once per hz tick.  Used for cpu utilization information.  This
2164171482Sjeff * is easier than trying to scale based on stathz.
2165171482Sjeff */
2166171482Sjeffvoid
2167171482Sjeffsched_tick(void)
2168171482Sjeff{
2169171482Sjeff	struct td_sched *ts;
2170171482Sjeff
2171171482Sjeff	ts = curthread->td_sched;
2172171482Sjeff	/* Adjust ticks for pctcpu */
2173171482Sjeff	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2174171482Sjeff	ts->ts_ltick = ticks;
2175171482Sjeff	/*
2176171482Sjeff	 * Update if we've exceeded our desired tick threshhold by over one
2177171482Sjeff	 * second.
2178171482Sjeff	 */
2179171482Sjeff	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2180171482Sjeff		sched_pctcpu_update(ts);
2181171482Sjeff}
2182171482Sjeff
2183171482Sjeff/*
2184171482Sjeff * Return whether the current CPU has runnable tasks.  Used for in-kernel
2185171482Sjeff * cooperative idle threads.
2186171482Sjeff */
2187109864Sjeffint
2188109864Sjeffsched_runnable(void)
2189109864Sjeff{
2190164936Sjulian	struct tdq *tdq;
2191115998Sjeff	int load;
2192109864Sjeff
2193115998Sjeff	load = 1;
2194115998Sjeff
2195164936Sjulian	tdq = TDQ_SELF();
2196121605Sjeff	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2197165620Sjeff		if (tdq->tdq_load > 0)
2198121605Sjeff			goto out;
2199121605Sjeff	} else
2200165620Sjeff		if (tdq->tdq_load - 1 > 0)
2201121605Sjeff			goto out;
2202115998Sjeff	load = 0;
2203115998Sjeffout:
2204115998Sjeff	return (load);
2205109864Sjeff}
2206109864Sjeff
2207171482Sjeff/*
2208171482Sjeff * Choose the highest priority thread to run.  The thread is removed from
2209171482Sjeff * the run-queue while running however the load remains.  For SMP we set
2210171482Sjeff * the tdq in the global idle bitmask if it idles here.
2211171482Sjeff */
2212166190Sjeffstruct thread *
2213109970Sjeffsched_choose(void)
2214109970Sjeff{
2215171482Sjeff#ifdef SMP
2216171482Sjeff	struct tdq_group *tdg;
2217171482Sjeff#endif
2218171482Sjeff	struct td_sched *ts;
2219164936Sjulian	struct tdq *tdq;
2220109970Sjeff
2221164936Sjulian	tdq = TDQ_SELF();
2222171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2223164936Sjulian	ts = tdq_choose(tdq);
2224164936Sjulian	if (ts) {
2225164936Sjulian		tdq_runq_rem(tdq, ts);
2226166190Sjeff		return (ts->ts_thread);
2227109864Sjeff	}
2228109970Sjeff#ifdef SMP
2229171482Sjeff	/*
2230171482Sjeff	 * We only set the idled bit when all of the cpus in the group are
2231171482Sjeff	 * idle.  Otherwise we could get into a situation where a thread bounces
2232171482Sjeff	 * back and forth between two idle cores on seperate physical CPUs.
2233171482Sjeff	 */
2234171482Sjeff	tdg = tdq->tdq_group;
2235171482Sjeff	tdg->tdg_idlemask |= PCPU_GET(cpumask);
2236171482Sjeff	if (tdg->tdg_idlemask == tdg->tdg_cpumask)
2237171482Sjeff		atomic_set_int(&tdq_idle, tdg->tdg_mask);
2238171482Sjeff	tdq->tdq_lowpri = PRI_MAX_IDLE;
2239109970Sjeff#endif
2240166190Sjeff	return (PCPU_GET(idlethread));
2241109864Sjeff}
2242109864Sjeff
2243171482Sjeff/*
2244171482Sjeff * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2245171482Sjeff * we always request it once we exit a critical section.
2246171482Sjeff */
2247171482Sjeffstatic inline void
2248171482Sjeffsched_setpreempt(struct thread *td)
2249166190Sjeff{
2250166190Sjeff	struct thread *ctd;
2251166190Sjeff	int cpri;
2252166190Sjeff	int pri;
2253166190Sjeff
2254166190Sjeff	ctd = curthread;
2255166190Sjeff	pri = td->td_priority;
2256166190Sjeff	cpri = ctd->td_priority;
2257171482Sjeff	if (td->td_priority < ctd->td_priority)
2258171482Sjeff		curthread->td_flags |= TDF_NEEDRESCHED;
2259166190Sjeff	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2260171482Sjeff		return;
2261166190Sjeff	/*
2262166190Sjeff	 * Always preempt IDLE threads.  Otherwise only if the preempting
2263166190Sjeff	 * thread is an ithread.
2264166190Sjeff	 */
2265171482Sjeff	if (pri > preempt_thresh && cpri < PRI_MIN_IDLE)
2266171482Sjeff		return;
2267171482Sjeff	ctd->td_owepreempt = 1;
2268171482Sjeff	return;
2269166190Sjeff}
2270166190Sjeff
2271171482Sjeff/*
2272171482Sjeff * Add a thread to a thread queue.  Initializes priority, slice, runq, and
2273171482Sjeff * add it to the appropriate queue.  This is the internal function called
2274171482Sjeff * when the tdq is predetermined.
2275171482Sjeff */
2276109864Sjeffvoid
2277171482Sjefftdq_add(struct tdq *tdq, struct thread *td, int flags)
2278109864Sjeff{
2279164936Sjulian	struct td_sched *ts;
2280121790Sjeff	int class;
2281166108Sjeff#ifdef SMP
2282166108Sjeff	int cpumask;
2283166108Sjeff#endif
2284109864Sjeff
2285171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2286166190Sjeff	KASSERT((td->td_inhibitors == 0),
2287166190Sjeff	    ("sched_add: trying to run inhibited thread"));
2288166190Sjeff	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2289166190Sjeff	    ("sched_add: bad thread state"));
2290172207Sjeff	KASSERT(td->td_flags & TDF_INMEM,
2291172207Sjeff	    ("sched_add: thread swapped out"));
2292171482Sjeff
2293171482Sjeff	ts = td->td_sched;
2294171482Sjeff	class = PRI_BASE(td->td_pri_class);
2295166190Sjeff        TD_SET_RUNQ(td);
2296166190Sjeff	if (ts->ts_slice == 0)
2297166190Sjeff		ts->ts_slice = sched_slice;
2298133427Sjeff	/*
2299171482Sjeff	 * Pick the run queue based on priority.
2300133427Sjeff	 */
2301171482Sjeff	if (td->td_priority <= PRI_MAX_REALTIME)
2302171482Sjeff		ts->ts_runq = &tdq->tdq_realtime;
2303171482Sjeff	else if (td->td_priority <= PRI_MAX_TIMESHARE)
2304171482Sjeff		ts->ts_runq = &tdq->tdq_timeshare;
2305171482Sjeff	else
2306171482Sjeff		ts->ts_runq = &tdq->tdq_idle;
2307171482Sjeff#ifdef SMP
2308166108Sjeff	cpumask = 1 << ts->ts_cpu;
2309121790Sjeff	/*
2310123685Sjeff	 * If we had been idle, clear our bit in the group and potentially
2311166108Sjeff	 * the global bitmap.
2312121790Sjeff	 */
2313165762Sjeff	if ((class != PRI_IDLE && class != PRI_ITHD) &&
2314166108Sjeff	    (tdq->tdq_group->tdg_idlemask & cpumask) != 0) {
2315121790Sjeff		/*
2316123433Sjeff		 * Check to see if our group is unidling, and if so, remove it
2317123433Sjeff		 * from the global idle mask.
2318121790Sjeff		 */
2319165620Sjeff		if (tdq->tdq_group->tdg_idlemask ==
2320165620Sjeff		    tdq->tdq_group->tdg_cpumask)
2321165620Sjeff			atomic_clear_int(&tdq_idle, tdq->tdq_group->tdg_mask);
2322123433Sjeff		/*
2323123433Sjeff		 * Now remove ourselves from the group specific idle mask.
2324123433Sjeff		 */
2325166108Sjeff		tdq->tdq_group->tdg_idlemask &= ~cpumask;
2326166108Sjeff	}
2327171482Sjeff	if (td->td_priority < tdq->tdq_lowpri)
2328171482Sjeff		tdq->tdq_lowpri = td->td_priority;
2329121790Sjeff#endif
2330171482Sjeff	tdq_runq_add(tdq, ts, flags);
2331171482Sjeff	tdq_load_add(tdq, ts);
2332171482Sjeff}
2333171482Sjeff
2334171482Sjeff/*
2335171482Sjeff * Select the target thread queue and add a thread to it.  Request
2336171482Sjeff * preemption or IPI a remote processor if required.
2337171482Sjeff */
2338171482Sjeffvoid
2339171482Sjeffsched_add(struct thread *td, int flags)
2340171482Sjeff{
2341171482Sjeff	struct td_sched *ts;
2342171482Sjeff	struct tdq *tdq;
2343171482Sjeff#ifdef SMP
2344171482Sjeff	int cpuid;
2345171482Sjeff	int cpu;
2346171482Sjeff#endif
2347171482Sjeff	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
2348171482Sjeff	    td, td->td_proc->p_comm, td->td_priority, curthread,
2349171482Sjeff	    curthread->td_proc->p_comm);
2350171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2351171482Sjeff	ts = td->td_sched;
2352166108Sjeff	/*
2353171482Sjeff	 * Recalculate the priority before we select the target cpu or
2354171482Sjeff	 * run-queue.
2355166108Sjeff	 */
2356171482Sjeff	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2357171482Sjeff		sched_priority(td);
2358171482Sjeff#ifdef SMP
2359171482Sjeff	cpuid = PCPU_GET(cpuid);
2360171482Sjeff	/*
2361171482Sjeff	 * Pick the destination cpu and if it isn't ours transfer to the
2362171482Sjeff	 * target cpu.
2363171482Sjeff	 */
2364171482Sjeff	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_MIGRATE(td))
2365171482Sjeff		cpu = cpuid;
2366171482Sjeff	else if (!THREAD_CAN_MIGRATE(td))
2367171482Sjeff		cpu = ts->ts_cpu;
2368166108Sjeff	else
2369171482Sjeff		cpu = sched_pickcpu(ts, flags);
2370171482Sjeff	tdq = sched_setcpu(ts, cpu, flags);
2371171482Sjeff	tdq_add(tdq, td, flags);
2372171482Sjeff	if (cpu != cpuid) {
2373166108Sjeff		tdq_notify(ts);
2374166108Sjeff		return;
2375166108Sjeff	}
2376171482Sjeff#else
2377171482Sjeff	tdq = TDQ_SELF();
2378171482Sjeff	TDQ_LOCK(tdq);
2379171482Sjeff	/*
2380171482Sjeff	 * Now that the thread is moving to the run-queue, set the lock
2381171482Sjeff	 * to the scheduler's lock.
2382171482Sjeff	 */
2383171482Sjeff	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2384171482Sjeff	tdq_add(tdq, td, flags);
2385166108Sjeff#endif
2386171482Sjeff	if (!(flags & SRQ_YIELDING))
2387171482Sjeff		sched_setpreempt(td);
2388109864Sjeff}
2389109864Sjeff
2390171482Sjeff/*
2391171482Sjeff * Remove a thread from a run-queue without running it.  This is used
2392171482Sjeff * when we're stealing a thread from a remote queue.  Otherwise all threads
2393171482Sjeff * exit by calling sched_exit_thread() and sched_throw() themselves.
2394171482Sjeff */
2395109864Sjeffvoid
2396121127Sjeffsched_rem(struct thread *td)
2397109864Sjeff{
2398164936Sjulian	struct tdq *tdq;
2399164936Sjulian	struct td_sched *ts;
2400113357Sjeff
2401139316Sjeff	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
2402139316Sjeff	    td, td->td_proc->p_comm, td->td_priority, curthread,
2403139316Sjeff	    curthread->td_proc->p_comm);
2404164936Sjulian	ts = td->td_sched;
2405171482Sjeff	tdq = TDQ_CPU(ts->ts_cpu);
2406171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2407171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2408166190Sjeff	KASSERT(TD_ON_RUNQ(td),
2409164936Sjulian	    ("sched_rem: thread not on run queue"));
2410164936Sjulian	tdq_runq_rem(tdq, ts);
2411164936Sjulian	tdq_load_rem(tdq, ts);
2412166190Sjeff	TD_SET_CAN_RUN(td);
2413109864Sjeff}
2414109864Sjeff
2415171482Sjeff/*
2416171482Sjeff * Fetch cpu utilization information.  Updates on demand.
2417171482Sjeff */
2418109864Sjefffixpt_t
2419121127Sjeffsched_pctcpu(struct thread *td)
2420109864Sjeff{
2421109864Sjeff	fixpt_t pctcpu;
2422164936Sjulian	struct td_sched *ts;
2423109864Sjeff
2424109864Sjeff	pctcpu = 0;
2425164936Sjulian	ts = td->td_sched;
2426164936Sjulian	if (ts == NULL)
2427121290Sjeff		return (0);
2428109864Sjeff
2429170293Sjeff	thread_lock(td);
2430164936Sjulian	if (ts->ts_ticks) {
2431109864Sjeff		int rtick;
2432109864Sjeff
2433165796Sjeff		sched_pctcpu_update(ts);
2434109864Sjeff		/* How many rtick per second ? */
2435165762Sjeff		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2436165762Sjeff		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2437109864Sjeff	}
2438164936Sjulian	td->td_proc->p_swtime = ts->ts_ltick - ts->ts_ftick;
2439170293Sjeff	thread_unlock(td);
2440109864Sjeff
2441109864Sjeff	return (pctcpu);
2442109864Sjeff}
2443109864Sjeff
2444171482Sjeff/*
2445171482Sjeff * Bind a thread to a target cpu.
2446171482Sjeff */
2447122038Sjeffvoid
2448122038Sjeffsched_bind(struct thread *td, int cpu)
2449122038Sjeff{
2450164936Sjulian	struct td_sched *ts;
2451122038Sjeff
2452171713Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2453164936Sjulian	ts = td->td_sched;
2454166137Sjeff	if (ts->ts_flags & TSF_BOUND)
2455166152Sjeff		sched_unbind(td);
2456164936Sjulian	ts->ts_flags |= TSF_BOUND;
2457123433Sjeff#ifdef SMP
2458166137Sjeff	sched_pin();
2459123433Sjeff	if (PCPU_GET(cpuid) == cpu)
2460122038Sjeff		return;
2461166137Sjeff	ts->ts_cpu = cpu;
2462122038Sjeff	/* When we return from mi_switch we'll be on the correct cpu. */
2463131527Sphk	mi_switch(SW_VOL, NULL);
2464122038Sjeff#endif
2465122038Sjeff}
2466122038Sjeff
2467171482Sjeff/*
2468171482Sjeff * Release a bound thread.
2469171482Sjeff */
2470122038Sjeffvoid
2471122038Sjeffsched_unbind(struct thread *td)
2472122038Sjeff{
2473165762Sjeff	struct td_sched *ts;
2474165762Sjeff
2475170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2476165762Sjeff	ts = td->td_sched;
2477166137Sjeff	if ((ts->ts_flags & TSF_BOUND) == 0)
2478166137Sjeff		return;
2479165762Sjeff	ts->ts_flags &= ~TSF_BOUND;
2480165762Sjeff#ifdef SMP
2481165762Sjeff	sched_unpin();
2482165762Sjeff#endif
2483122038Sjeff}
2484122038Sjeff
2485109864Sjeffint
2486145256Sjkoshysched_is_bound(struct thread *td)
2487145256Sjkoshy{
2488170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2489164936Sjulian	return (td->td_sched->ts_flags & TSF_BOUND);
2490145256Sjkoshy}
2491145256Sjkoshy
2492171482Sjeff/*
2493171482Sjeff * Basic yield call.
2494171482Sjeff */
2495159630Sdavidxuvoid
2496159630Sdavidxusched_relinquish(struct thread *td)
2497159630Sdavidxu{
2498170293Sjeff	thread_lock(td);
2499163709Sjb	if (td->td_pri_class == PRI_TIMESHARE)
2500159630Sdavidxu		sched_prio(td, PRI_MAX_TIMESHARE);
2501170293Sjeff	SCHED_STAT_INC(switch_relinquish);
2502159630Sdavidxu	mi_switch(SW_VOL, NULL);
2503170293Sjeff	thread_unlock(td);
2504159630Sdavidxu}
2505159630Sdavidxu
2506171482Sjeff/*
2507171482Sjeff * Return the total system load.
2508171482Sjeff */
2509145256Sjkoshyint
2510125289Sjeffsched_load(void)
2511125289Sjeff{
2512125289Sjeff#ifdef SMP
2513125289Sjeff	int total;
2514125289Sjeff	int i;
2515125289Sjeff
2516125289Sjeff	total = 0;
2517165620Sjeff	for (i = 0; i <= tdg_maxid; i++)
2518165620Sjeff		total += TDQ_GROUP(i)->tdg_load;
2519125289Sjeff	return (total);
2520125289Sjeff#else
2521165620Sjeff	return (TDQ_SELF()->tdq_sysload);
2522125289Sjeff#endif
2523125289Sjeff}
2524125289Sjeff
2525125289Sjeffint
2526109864Sjeffsched_sizeof_proc(void)
2527109864Sjeff{
2528109864Sjeff	return (sizeof(struct proc));
2529109864Sjeff}
2530109864Sjeff
2531109864Sjeffint
2532109864Sjeffsched_sizeof_thread(void)
2533109864Sjeff{
2534109864Sjeff	return (sizeof(struct thread) + sizeof(struct td_sched));
2535109864Sjeff}
2536159570Sdavidxu
2537166190Sjeff/*
2538166190Sjeff * The actual idle process.
2539166190Sjeff */
2540166190Sjeffvoid
2541166190Sjeffsched_idletd(void *dummy)
2542166190Sjeff{
2543166190Sjeff	struct thread *td;
2544171482Sjeff	struct tdq *tdq;
2545166190Sjeff
2546166190Sjeff	td = curthread;
2547171482Sjeff	tdq = TDQ_SELF();
2548166190Sjeff	mtx_assert(&Giant, MA_NOTOWNED);
2549171482Sjeff	/* ULE relies on preemption for idle interruption. */
2550171482Sjeff	for (;;) {
2551171482Sjeff#ifdef SMP
2552171482Sjeff		if (tdq_idled(tdq))
2553171482Sjeff			cpu_idle();
2554171482Sjeff#else
2555166190Sjeff		cpu_idle();
2556171482Sjeff#endif
2557171482Sjeff	}
2558166190Sjeff}
2559166190Sjeff
2560170293Sjeff/*
2561170293Sjeff * A CPU is entering for the first time or a thread is exiting.
2562170293Sjeff */
2563170293Sjeffvoid
2564170293Sjeffsched_throw(struct thread *td)
2565170293Sjeff{
2566171482Sjeff	struct tdq *tdq;
2567171482Sjeff
2568171482Sjeff	tdq = TDQ_SELF();
2569170293Sjeff	if (td == NULL) {
2570171482Sjeff		/* Correct spinlock nesting and acquire the correct lock. */
2571171482Sjeff		TDQ_LOCK(tdq);
2572170293Sjeff		spinlock_exit();
2573170293Sjeff	} else {
2574171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2575171482Sjeff		tdq_load_rem(tdq, td->td_sched);
2576170293Sjeff	}
2577170293Sjeff	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2578170293Sjeff	PCPU_SET(switchtime, cpu_ticks());
2579170293Sjeff	PCPU_SET(switchticks, ticks);
2580170293Sjeff	cpu_throw(td, choosethread());	/* doesn't return */
2581170293Sjeff}
2582170293Sjeff
2583171482Sjeff/*
2584171482Sjeff * This is called from fork_exit().  Just acquire the correct locks and
2585171482Sjeff * let fork do the rest of the work.
2586171482Sjeff */
2587170293Sjeffvoid
2588170600Sjeffsched_fork_exit(struct thread *td)
2589170293Sjeff{
2590171482Sjeff	struct td_sched *ts;
2591171482Sjeff	struct tdq *tdq;
2592171482Sjeff	int cpuid;
2593170293Sjeff
2594170293Sjeff	/*
2595170293Sjeff	 * Finish setting up thread glue so that it begins execution in a
2596171482Sjeff	 * non-nested critical section with the scheduler lock held.
2597170293Sjeff	 */
2598171482Sjeff	cpuid = PCPU_GET(cpuid);
2599171482Sjeff	tdq = TDQ_CPU(cpuid);
2600171482Sjeff	ts = td->td_sched;
2601171482Sjeff	if (TD_IS_IDLETHREAD(td))
2602171482Sjeff		td->td_lock = TDQ_LOCKPTR(tdq);
2603171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2604171482Sjeff	td->td_oncpu = cpuid;
2605171482Sjeff	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)td;
2606170600Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
2607170293Sjeff}
2608170293Sjeff
2609171482Sjeffstatic SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0,
2610171482Sjeff    "Scheduler");
2611171482SjeffSYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2612165762Sjeff    "Scheduler name");
2613171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2614171482Sjeff    "Slice size for timeshare threads");
2615171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2616171482Sjeff     "Interactivity score threshold");
2617171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2618171482Sjeff     0,"Min priority for preemption, lower priorities have greater precedence");
2619166108Sjeff#ifdef SMP
2620171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, pick_pri, CTLFLAG_RW, &pick_pri, 0,
2621171482Sjeff    "Pick the target cpu based on priority rather than load.");
2622171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2623171482Sjeff    "Number of hz ticks to keep thread affinity for");
2624171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, tryself, CTLFLAG_RW, &tryself, 0, "");
2625171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2626171482Sjeff    "Enables the long-term load balancer");
2627171506SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance_secs, CTLFLAG_RW, &balance_secs, 0,
2628171506Sjeff    "Average frequence in seconds to run the long-term balancer");
2629171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2630171482Sjeff    "Steals work from another hyper-threaded core on idle");
2631171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2632171482Sjeff    "Attempts to steal work from other cores before idling");
2633171506SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2634171506Sjeff    "Minimum load on remote cpu before we'll steal");
2635171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, topology, CTLFLAG_RD, &topology, 0,
2636171482Sjeff    "True when a topology has been specified by the MD code.");
2637166108Sjeff#endif
2638165762Sjeff
2639165762Sjeff/* ps compat */
2640165762Sjeffstatic fixpt_t  ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
2641165762SjeffSYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2642165762Sjeff
2643165762Sjeff
2644134791Sjulian#define KERN_SWITCH_INCLUDE 1
2645134791Sjulian#include "kern/kern_switch.c"
2646