sched_ule.c revision 171713
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 171713 2007-08-03 23:38:46Z 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);
300171713Sjeffstatic inline struct tdq *sched_switchcpu(struct td_sched *, int, int);
301171482Sjeffstatic inline struct mtx *thread_block_switch(struct thread *);
302171482Sjeffstatic inline void thread_unblock_switch(struct thread *, struct mtx *);
303171713Sjeffstatic struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
304165827Sjeff
305166108Sjeff#define	THREAD_CAN_MIGRATE(td)	 ((td)->td_pinned == 0)
306121790Sjeff#endif
307110028Sjeff
308165762Sjeffstatic void sched_setup(void *dummy);
309165762SjeffSYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
310165762Sjeff
311165762Sjeffstatic void sched_initticks(void *dummy);
312165762SjeffSYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks, NULL)
313165762Sjeff
314171482Sjeff/*
315171482Sjeff * Print the threads waiting on a run-queue.
316171482Sjeff */
317165762Sjeffstatic void
318165762Sjeffrunq_print(struct runq *rq)
319165762Sjeff{
320165762Sjeff	struct rqhead *rqh;
321165762Sjeff	struct td_sched *ts;
322165762Sjeff	int pri;
323165762Sjeff	int j;
324165762Sjeff	int i;
325165762Sjeff
326165762Sjeff	for (i = 0; i < RQB_LEN; i++) {
327165762Sjeff		printf("\t\trunq bits %d 0x%zx\n",
328165762Sjeff		    i, rq->rq_status.rqb_bits[i]);
329165762Sjeff		for (j = 0; j < RQB_BPW; j++)
330165762Sjeff			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
331165762Sjeff				pri = j + (i << RQB_L2BPW);
332165762Sjeff				rqh = &rq->rq_queues[pri];
333165762Sjeff				TAILQ_FOREACH(ts, rqh, ts_procq) {
334165762Sjeff					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
335165762Sjeff					    ts->ts_thread, ts->ts_thread->td_proc->p_comm, ts->ts_thread->td_priority, ts->ts_rqindex, pri);
336165762Sjeff				}
337165762Sjeff			}
338165762Sjeff	}
339165762Sjeff}
340165762Sjeff
341171482Sjeff/*
342171482Sjeff * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
343171482Sjeff */
344113357Sjeffvoid
345164936Sjuliantdq_print(int cpu)
346110267Sjeff{
347164936Sjulian	struct tdq *tdq;
348112994Sjeff
349164936Sjulian	tdq = TDQ_CPU(cpu);
350112994Sjeff
351171713Sjeff	printf("tdq %d:\n", TDQ_ID(tdq));
352171482Sjeff	printf("\tlockptr         %p\n", TDQ_LOCKPTR(tdq));
353165620Sjeff	printf("\tload:           %d\n", tdq->tdq_load);
354171482Sjeff	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
355165766Sjeff	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
356165762Sjeff	printf("\trealtime runq:\n");
357165762Sjeff	runq_print(&tdq->tdq_realtime);
358165762Sjeff	printf("\ttimeshare runq:\n");
359165762Sjeff	runq_print(&tdq->tdq_timeshare);
360165762Sjeff	printf("\tidle runq:\n");
361165762Sjeff	runq_print(&tdq->tdq_idle);
362121896Sjeff#ifdef SMP
363165620Sjeff	printf("\tload transferable: %d\n", tdq->tdq_transferable);
364171713Sjeff	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
365171713Sjeff	printf("\tgroup:             %d\n", TDG_ID(tdq->tdq_group));
366171713Sjeff	printf("\tLock name:         %s\n", tdq->tdq_group->tdg_name);
367121896Sjeff#endif
368113357Sjeff}
369112994Sjeff
370171482Sjeff#define	TS_RQ_PPQ	(((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
371171482Sjeff/*
372171482Sjeff * Add a thread to the actual run-queue.  Keeps transferable counts up to
373171482Sjeff * date with what is actually on the run-queue.  Selects the correct
374171482Sjeff * queue position for timeshare threads.
375171482Sjeff */
376122744Sjeffstatic __inline void
377164936Sjuliantdq_runq_add(struct tdq *tdq, struct td_sched *ts, int flags)
378122744Sjeff{
379171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
380171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
381122744Sjeff#ifdef SMP
382165762Sjeff	if (THREAD_CAN_MIGRATE(ts->ts_thread)) {
383165620Sjeff		tdq->tdq_transferable++;
384165620Sjeff		tdq->tdq_group->tdg_transferable++;
385164936Sjulian		ts->ts_flags |= TSF_XFERABLE;
386123433Sjeff	}
387122744Sjeff#endif
388165762Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
389166557Sjeff		u_char pri;
390165762Sjeff
391165762Sjeff		pri = ts->ts_thread->td_priority;
392165762Sjeff		KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
393165762Sjeff			("Invalid priority %d on timeshare runq", pri));
394165762Sjeff		/*
395165762Sjeff		 * This queue contains only priorities between MIN and MAX
396165762Sjeff		 * realtime.  Use the whole queue to represent these values.
397165762Sjeff		 */
398171713Sjeff		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
399165762Sjeff			pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
400165762Sjeff			pri = (pri + tdq->tdq_idx) % RQ_NQS;
401165766Sjeff			/*
402165766Sjeff			 * This effectively shortens the queue by one so we
403165766Sjeff			 * can have a one slot difference between idx and
404165766Sjeff			 * ridx while we wait for threads to drain.
405165766Sjeff			 */
406165766Sjeff			if (tdq->tdq_ridx != tdq->tdq_idx &&
407165766Sjeff			    pri == tdq->tdq_ridx)
408167664Sjeff				pri = (unsigned char)(pri - 1) % RQ_NQS;
409165762Sjeff		} else
410165766Sjeff			pri = tdq->tdq_ridx;
411165762Sjeff		runq_add_pri(ts->ts_runq, ts, pri, flags);
412165762Sjeff	} else
413165762Sjeff		runq_add(ts->ts_runq, ts, flags);
414122744Sjeff}
415122744Sjeff
416171482Sjeff/*
417171482Sjeff * Remove a thread from a run-queue.  This typically happens when a thread
418171482Sjeff * is selected to run.  Running threads are not on the queue and the
419171482Sjeff * transferable count does not reflect them.
420171482Sjeff */
421122744Sjeffstatic __inline void
422164936Sjuliantdq_runq_rem(struct tdq *tdq, struct td_sched *ts)
423122744Sjeff{
424171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
425171482Sjeff	KASSERT(ts->ts_runq != NULL,
426171482Sjeff	    ("tdq_runq_remove: thread %p null ts_runq", ts->ts_thread));
427122744Sjeff#ifdef SMP
428164936Sjulian	if (ts->ts_flags & TSF_XFERABLE) {
429165620Sjeff		tdq->tdq_transferable--;
430165620Sjeff		tdq->tdq_group->tdg_transferable--;
431164936Sjulian		ts->ts_flags &= ~TSF_XFERABLE;
432123433Sjeff	}
433122744Sjeff#endif
434165766Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
435165766Sjeff		if (tdq->tdq_idx != tdq->tdq_ridx)
436165766Sjeff			runq_remove_idx(ts->ts_runq, ts, &tdq->tdq_ridx);
437165766Sjeff		else
438165766Sjeff			runq_remove_idx(ts->ts_runq, ts, NULL);
439165796Sjeff		/*
440165796Sjeff		 * For timeshare threads we update the priority here so
441165796Sjeff		 * the priority reflects the time we've been sleeping.
442165796Sjeff		 */
443165796Sjeff		ts->ts_ltick = ticks;
444165796Sjeff		sched_pctcpu_update(ts);
445165796Sjeff		sched_priority(ts->ts_thread);
446165766Sjeff	} else
447165762Sjeff		runq_remove(ts->ts_runq, ts);
448122744Sjeff}
449122744Sjeff
450171482Sjeff/*
451171482Sjeff * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
452171482Sjeff * for this thread to the referenced thread queue.
453171482Sjeff */
454113357Sjeffstatic void
455164936Sjuliantdq_load_add(struct tdq *tdq, struct td_sched *ts)
456113357Sjeff{
457121896Sjeff	int class;
458171482Sjeff
459171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
460171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
461164936Sjulian	class = PRI_BASE(ts->ts_thread->td_pri_class);
462165620Sjeff	tdq->tdq_load++;
463171713Sjeff	CTR2(KTR_SCHED, "cpu %d load: %d", TDQ_ID(tdq), tdq->tdq_load);
464166108Sjeff	if (class != PRI_ITHD &&
465166108Sjeff	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
466123487Sjeff#ifdef SMP
467165620Sjeff		tdq->tdq_group->tdg_load++;
468125289Sjeff#else
469165620Sjeff		tdq->tdq_sysload++;
470123487Sjeff#endif
471110267Sjeff}
472113357Sjeff
473171482Sjeff/*
474171482Sjeff * Remove the load from a thread that is transitioning to a sleep state or
475171482Sjeff * exiting.
476171482Sjeff */
477112994Sjeffstatic void
478164936Sjuliantdq_load_rem(struct tdq *tdq, struct td_sched *ts)
479110267Sjeff{
480121896Sjeff	int class;
481171482Sjeff
482171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
483171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
484164936Sjulian	class = PRI_BASE(ts->ts_thread->td_pri_class);
485166108Sjeff	if (class != PRI_ITHD &&
486166108Sjeff	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
487123487Sjeff#ifdef SMP
488165620Sjeff		tdq->tdq_group->tdg_load--;
489125289Sjeff#else
490165620Sjeff		tdq->tdq_sysload--;
491123487Sjeff#endif
492171482Sjeff	KASSERT(tdq->tdq_load != 0,
493171713Sjeff	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
494165620Sjeff	tdq->tdq_load--;
495165620Sjeff	CTR1(KTR_SCHED, "load: %d", tdq->tdq_load);
496164936Sjulian	ts->ts_runq = NULL;
497110267Sjeff}
498110267Sjeff
499113357Sjeff#ifdef SMP
500116069Sjeff/*
501122744Sjeff * sched_balance is a simple CPU load balancing algorithm.  It operates by
502116069Sjeff * finding the least loaded and most loaded cpu and equalizing their load
503116069Sjeff * by migrating some processes.
504116069Sjeff *
505116069Sjeff * Dealing only with two CPUs at a time has two advantages.  Firstly, most
506116069Sjeff * installations will only have 2 cpus.  Secondly, load balancing too much at
507116069Sjeff * once can have an unpleasant effect on the system.  The scheduler rarely has
508116069Sjeff * enough information to make perfect decisions.  So this algorithm chooses
509171482Sjeff * simplicity and more gradual effects on load in larger systems.
510116069Sjeff *
511116069Sjeff */
512121790Sjeffstatic void
513171482Sjeffsched_balance(void *arg)
514116069Sjeff{
515164936Sjulian	struct tdq_group *high;
516164936Sjulian	struct tdq_group *low;
517165620Sjeff	struct tdq_group *tdg;
518123487Sjeff	int cnt;
519123487Sjeff	int i;
520123487Sjeff
521171506Sjeff	callout_reset(&balco, max(hz / 2, random() % (hz * balance_secs)),
522171482Sjeff	    sched_balance, NULL);
523171482Sjeff	if (smp_started == 0 || rebalance == 0)
524139334Sjeff		return;
525123487Sjeff	low = high = NULL;
526165620Sjeff	i = random() % (tdg_maxid + 1);
527165620Sjeff	for (cnt = 0; cnt <= tdg_maxid; cnt++) {
528165620Sjeff		tdg = TDQ_GROUP(i);
529123487Sjeff		/*
530123487Sjeff		 * Find the CPU with the highest load that has some
531123487Sjeff		 * threads to transfer.
532123487Sjeff		 */
533165620Sjeff		if ((high == NULL || tdg->tdg_load > high->tdg_load)
534165620Sjeff		    && tdg->tdg_transferable)
535165620Sjeff			high = tdg;
536165620Sjeff		if (low == NULL || tdg->tdg_load < low->tdg_load)
537165620Sjeff			low = tdg;
538165620Sjeff		if (++i > tdg_maxid)
539123487Sjeff			i = 0;
540123487Sjeff	}
541123487Sjeff	if (low != NULL && high != NULL && high != low)
542165620Sjeff		sched_balance_pair(LIST_FIRST(&high->tdg_members),
543165620Sjeff		    LIST_FIRST(&low->tdg_members));
544123487Sjeff}
545123487Sjeff
546171482Sjeff/*
547171482Sjeff * Balance load between CPUs in a group.  Will only migrate within the group.
548171482Sjeff */
549123487Sjeffstatic void
550171482Sjeffsched_balance_groups(void *arg)
551123487Sjeff{
552123487Sjeff	int i;
553123487Sjeff
554171506Sjeff	callout_reset(&gbalco, max(hz / 2, random() % (hz * balance_secs)),
555171482Sjeff	    sched_balance_groups, NULL);
556171482Sjeff	if (smp_started == 0 || rebalance == 0)
557171482Sjeff		return;
558171482Sjeff	for (i = 0; i <= tdg_maxid; i++)
559171482Sjeff		sched_balance_group(TDQ_GROUP(i));
560123487Sjeff}
561123487Sjeff
562171482Sjeff/*
563171482Sjeff * Finds the greatest imbalance between two tdqs in a group.
564171482Sjeff */
565123487Sjeffstatic void
566165620Sjeffsched_balance_group(struct tdq_group *tdg)
567123487Sjeff{
568164936Sjulian	struct tdq *tdq;
569164936Sjulian	struct tdq *high;
570164936Sjulian	struct tdq *low;
571123487Sjeff	int load;
572123487Sjeff
573165620Sjeff	if (tdg->tdg_transferable == 0)
574123487Sjeff		return;
575123487Sjeff	low = NULL;
576123487Sjeff	high = NULL;
577165620Sjeff	LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
578165620Sjeff		load = tdq->tdq_load;
579165620Sjeff		if (high == NULL || load > high->tdq_load)
580164936Sjulian			high = tdq;
581165620Sjeff		if (low == NULL || load < low->tdq_load)
582164936Sjulian			low = tdq;
583123487Sjeff	}
584123487Sjeff	if (high != NULL && low != NULL && high != low)
585123487Sjeff		sched_balance_pair(high, low);
586123487Sjeff}
587123487Sjeff
588171482Sjeff/*
589171482Sjeff * Lock two thread queues using their address to maintain lock order.
590171482Sjeff */
591123487Sjeffstatic void
592171482Sjefftdq_lock_pair(struct tdq *one, struct tdq *two)
593171482Sjeff{
594171482Sjeff	if (one < two) {
595171482Sjeff		TDQ_LOCK(one);
596171482Sjeff		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
597171482Sjeff	} else {
598171482Sjeff		TDQ_LOCK(two);
599171482Sjeff		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
600171482Sjeff	}
601171482Sjeff}
602171482Sjeff
603171482Sjeff/*
604171482Sjeff * Transfer load between two imbalanced thread queues.
605171482Sjeff */
606171482Sjeffstatic void
607164936Sjuliansched_balance_pair(struct tdq *high, struct tdq *low)
608123487Sjeff{
609123433Sjeff	int transferable;
610116069Sjeff	int high_load;
611116069Sjeff	int low_load;
612116069Sjeff	int move;
613116069Sjeff	int diff;
614116069Sjeff	int i;
615116069Sjeff
616171482Sjeff	tdq_lock_pair(high, low);
617116069Sjeff	/*
618123433Sjeff	 * If we're transfering within a group we have to use this specific
619164936Sjulian	 * tdq's transferable count, otherwise we can steal from other members
620123433Sjeff	 * of the group.
621123433Sjeff	 */
622165620Sjeff	if (high->tdq_group == low->tdq_group) {
623165620Sjeff		transferable = high->tdq_transferable;
624165620Sjeff		high_load = high->tdq_load;
625165620Sjeff		low_load = low->tdq_load;
626123487Sjeff	} else {
627165620Sjeff		transferable = high->tdq_group->tdg_transferable;
628165620Sjeff		high_load = high->tdq_group->tdg_load;
629165620Sjeff		low_load = low->tdq_group->tdg_load;
630123487Sjeff	}
631123433Sjeff	/*
632122744Sjeff	 * Determine what the imbalance is and then adjust that to how many
633165620Sjeff	 * threads we actually have to give up (transferable).
634122744Sjeff	 */
635171482Sjeff	if (transferable != 0) {
636171482Sjeff		diff = high_load - low_load;
637171482Sjeff		move = diff / 2;
638171482Sjeff		if (diff & 0x1)
639171482Sjeff			move++;
640171482Sjeff		move = min(move, transferable);
641171482Sjeff		for (i = 0; i < move; i++)
642171482Sjeff			tdq_move(high, low);
643171482Sjeff	}
644171482Sjeff	TDQ_UNLOCK(high);
645171482Sjeff	TDQ_UNLOCK(low);
646116069Sjeff	return;
647116069Sjeff}
648116069Sjeff
649171482Sjeff/*
650171482Sjeff * Move a thread from one thread queue to another.
651171482Sjeff */
652121790Sjeffstatic void
653171482Sjefftdq_move(struct tdq *from, struct tdq *to)
654116069Sjeff{
655171482Sjeff	struct td_sched *ts;
656171482Sjeff	struct thread *td;
657164936Sjulian	struct tdq *tdq;
658171482Sjeff	int cpu;
659116069Sjeff
660164936Sjulian	tdq = from;
661171482Sjeff	cpu = TDQ_ID(to);
662164936Sjulian	ts = tdq_steal(tdq, 1);
663164936Sjulian	if (ts == NULL) {
664165620Sjeff		struct tdq_group *tdg;
665123433Sjeff
666165620Sjeff		tdg = tdq->tdq_group;
667165620Sjeff		LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
668165620Sjeff			if (tdq == from || tdq->tdq_transferable == 0)
669123433Sjeff				continue;
670164936Sjulian			ts = tdq_steal(tdq, 1);
671123433Sjeff			break;
672123433Sjeff		}
673164936Sjulian		if (ts == NULL)
674171482Sjeff			return;
675123433Sjeff	}
676164936Sjulian	if (tdq == to)
677123433Sjeff		return;
678171482Sjeff	td = ts->ts_thread;
679171482Sjeff	/*
680171482Sjeff	 * Although the run queue is locked the thread may be blocked.  Lock
681171482Sjeff	 * it to clear this.
682171482Sjeff	 */
683171482Sjeff	thread_lock(td);
684171482Sjeff	/* Drop recursive lock on from. */
685171482Sjeff	TDQ_UNLOCK(from);
686171482Sjeff	sched_rem(td);
687166108Sjeff	ts->ts_cpu = cpu;
688171482Sjeff	td->td_lock = TDQ_LOCKPTR(to);
689171482Sjeff	tdq_add(to, td, SRQ_YIELDING);
690171505Sjeff	tdq_notify(ts);
691116069Sjeff}
692110267Sjeff
693171482Sjeff/*
694171482Sjeff * This tdq has idled.  Try to steal a thread from another cpu and switch
695171482Sjeff * to it.
696171482Sjeff */
697123433Sjeffstatic int
698164936Sjuliantdq_idled(struct tdq *tdq)
699121790Sjeff{
700165620Sjeff	struct tdq_group *tdg;
701164936Sjulian	struct tdq *steal;
702164936Sjulian	struct td_sched *ts;
703171482Sjeff	struct thread *td;
704171482Sjeff	int highload;
705171482Sjeff	int highcpu;
706171482Sjeff	int load;
707171482Sjeff	int cpu;
708123433Sjeff
709171482Sjeff	/* We don't want to be preempted while we're iterating over tdqs */
710171482Sjeff	spinlock_enter();
711165620Sjeff	tdg = tdq->tdq_group;
712123433Sjeff	/*
713165620Sjeff	 * If we're in a cpu group, try and steal threads from another cpu in
714123433Sjeff	 * the group before idling.
715123433Sjeff	 */
716166108Sjeff	if (steal_htt && tdg->tdg_cpus > 1 && tdg->tdg_transferable) {
717165620Sjeff		LIST_FOREACH(steal, &tdg->tdg_members, tdq_siblings) {
718165620Sjeff			if (steal == tdq || steal->tdq_transferable == 0)
719123433Sjeff				continue;
720171482Sjeff			TDQ_LOCK(steal);
721164936Sjulian			ts = tdq_steal(steal, 0);
722166108Sjeff			if (ts)
723166108Sjeff				goto steal;
724171482Sjeff			TDQ_UNLOCK(steal);
725166108Sjeff		}
726166108Sjeff	}
727171482Sjeff	for (;;) {
728171482Sjeff		if (steal_idle == 0)
729171482Sjeff			break;
730171482Sjeff		highcpu = 0;
731171482Sjeff		highload = 0;
732171482Sjeff		for (cpu = 0; cpu <= mp_maxid; cpu++) {
733171482Sjeff			if (CPU_ABSENT(cpu))
734171482Sjeff				continue;
735166108Sjeff			steal = TDQ_CPU(cpu);
736171482Sjeff			load = TDQ_CPU(cpu)->tdq_transferable;
737171482Sjeff			if (load < highload)
738166108Sjeff				continue;
739171482Sjeff			highload = load;
740171482Sjeff			highcpu = cpu;
741171482Sjeff		}
742171506Sjeff		if (highload < steal_thresh)
743171482Sjeff			break;
744171482Sjeff		steal = TDQ_CPU(highcpu);
745171482Sjeff		TDQ_LOCK(steal);
746171506Sjeff		if (steal->tdq_transferable >= steal_thresh &&
747171482Sjeff		    (ts = tdq_steal(steal, 1)) != NULL)
748166108Sjeff			goto steal;
749171482Sjeff		TDQ_UNLOCK(steal);
750171482Sjeff		break;
751123433Sjeff	}
752171482Sjeff	spinlock_exit();
753123433Sjeff	return (1);
754166108Sjeffsteal:
755171482Sjeff	td = ts->ts_thread;
756171482Sjeff	thread_lock(td);
757171482Sjeff	spinlock_exit();
758171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(steal));
759171482Sjeff	TDQ_UNLOCK(steal);
760171482Sjeff	sched_rem(td);
761171482Sjeff	sched_setcpu(ts, PCPU_GET(cpuid), SRQ_YIELDING);
762171482Sjeff	tdq_add(tdq, td, SRQ_YIELDING);
763171482Sjeff	MPASS(td->td_lock == curthread->td_lock);
764171482Sjeff	mi_switch(SW_VOL, NULL);
765171482Sjeff	thread_unlock(curthread);
766121790Sjeff
767166108Sjeff	return (0);
768121790Sjeff}
769121790Sjeff
770171482Sjeff/*
771171482Sjeff * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
772171482Sjeff */
773121790Sjeffstatic void
774166108Sjefftdq_notify(struct td_sched *ts)
775121790Sjeff{
776166247Sjeff	struct thread *ctd;
777121790Sjeff	struct pcpu *pcpu;
778166247Sjeff	int cpri;
779166247Sjeff	int pri;
780166108Sjeff	int cpu;
781121790Sjeff
782166108Sjeff	cpu = ts->ts_cpu;
783166247Sjeff	pri = ts->ts_thread->td_priority;
784166108Sjeff	pcpu = pcpu_find(cpu);
785166247Sjeff	ctd = pcpu->pc_curthread;
786166247Sjeff	cpri = ctd->td_priority;
787166137Sjeff
788121790Sjeff	/*
789166137Sjeff	 * If our priority is not better than the current priority there is
790166137Sjeff	 * nothing to do.
791166137Sjeff	 */
792166247Sjeff	if (pri > cpri)
793166137Sjeff		return;
794166137Sjeff	/*
795166247Sjeff	 * Always IPI idle.
796121790Sjeff	 */
797166247Sjeff	if (cpri > PRI_MIN_IDLE)
798166247Sjeff		goto sendipi;
799166247Sjeff	/*
800166247Sjeff	 * If we're realtime or better and there is timeshare or worse running
801166247Sjeff	 * send an IPI.
802166247Sjeff	 */
803166247Sjeff	if (pri < PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
804166247Sjeff		goto sendipi;
805166247Sjeff	/*
806166247Sjeff	 * Otherwise only IPI if we exceed the threshold.
807166247Sjeff	 */
808171482Sjeff	if (pri > preempt_thresh)
809165819Sjeff		return;
810166247Sjeffsendipi:
811166247Sjeff	ctd->td_flags |= TDF_NEEDRESCHED;
812171482Sjeff	ipi_selected(1 << cpu, IPI_PREEMPT);
813121790Sjeff}
814121790Sjeff
815171482Sjeff/*
816171482Sjeff * Steals load from a timeshare queue.  Honors the rotating queue head
817171482Sjeff * index.
818171482Sjeff */
819164936Sjulianstatic struct td_sched *
820171482Sjeffrunq_steal_from(struct runq *rq, u_char start)
821171482Sjeff{
822171482Sjeff	struct td_sched *ts;
823171482Sjeff	struct rqbits *rqb;
824171482Sjeff	struct rqhead *rqh;
825171482Sjeff	int first;
826171482Sjeff	int bit;
827171482Sjeff	int pri;
828171482Sjeff	int i;
829171482Sjeff
830171482Sjeff	rqb = &rq->rq_status;
831171482Sjeff	bit = start & (RQB_BPW -1);
832171482Sjeff	pri = 0;
833171482Sjeff	first = 0;
834171482Sjeffagain:
835171482Sjeff	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
836171482Sjeff		if (rqb->rqb_bits[i] == 0)
837171482Sjeff			continue;
838171482Sjeff		if (bit != 0) {
839171482Sjeff			for (pri = bit; pri < RQB_BPW; pri++)
840171482Sjeff				if (rqb->rqb_bits[i] & (1ul << pri))
841171482Sjeff					break;
842171482Sjeff			if (pri >= RQB_BPW)
843171482Sjeff				continue;
844171482Sjeff		} else
845171482Sjeff			pri = RQB_FFS(rqb->rqb_bits[i]);
846171482Sjeff		pri += (i << RQB_L2BPW);
847171482Sjeff		rqh = &rq->rq_queues[pri];
848171482Sjeff		TAILQ_FOREACH(ts, rqh, ts_procq) {
849171482Sjeff			if (first && THREAD_CAN_MIGRATE(ts->ts_thread))
850171482Sjeff				return (ts);
851171482Sjeff			first = 1;
852171482Sjeff		}
853171482Sjeff	}
854171482Sjeff	if (start != 0) {
855171482Sjeff		start = 0;
856171482Sjeff		goto again;
857171482Sjeff	}
858171482Sjeff
859171482Sjeff	return (NULL);
860171482Sjeff}
861171482Sjeff
862171482Sjeff/*
863171482Sjeff * Steals load from a standard linear queue.
864171482Sjeff */
865171482Sjeffstatic struct td_sched *
866121790Sjeffrunq_steal(struct runq *rq)
867121790Sjeff{
868121790Sjeff	struct rqhead *rqh;
869121790Sjeff	struct rqbits *rqb;
870164936Sjulian	struct td_sched *ts;
871121790Sjeff	int word;
872121790Sjeff	int bit;
873121790Sjeff
874121790Sjeff	rqb = &rq->rq_status;
875121790Sjeff	for (word = 0; word < RQB_LEN; word++) {
876121790Sjeff		if (rqb->rqb_bits[word] == 0)
877121790Sjeff			continue;
878121790Sjeff		for (bit = 0; bit < RQB_BPW; bit++) {
879123231Speter			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
880121790Sjeff				continue;
881121790Sjeff			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
882171506Sjeff			TAILQ_FOREACH(ts, rqh, ts_procq)
883171506Sjeff				if (THREAD_CAN_MIGRATE(ts->ts_thread))
884164936Sjulian					return (ts);
885121790Sjeff		}
886121790Sjeff	}
887121790Sjeff	return (NULL);
888121790Sjeff}
889121790Sjeff
890171482Sjeff/*
891171482Sjeff * Attempt to steal a thread in priority order from a thread queue.
892171482Sjeff */
893164936Sjulianstatic struct td_sched *
894164936Sjuliantdq_steal(struct tdq *tdq, int stealidle)
895121790Sjeff{
896164936Sjulian	struct td_sched *ts;
897121790Sjeff
898171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
899165762Sjeff	if ((ts = runq_steal(&tdq->tdq_realtime)) != NULL)
900164936Sjulian		return (ts);
901171482Sjeff	if ((ts = runq_steal_from(&tdq->tdq_timeshare, tdq->tdq_ridx)) != NULL)
902164936Sjulian		return (ts);
903123433Sjeff	if (stealidle)
904165620Sjeff		return (runq_steal(&tdq->tdq_idle));
905123433Sjeff	return (NULL);
906121790Sjeff}
907123433Sjeff
908171482Sjeff/*
909171482Sjeff * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
910171482Sjeff * current lock and returns with the assigned queue locked.  If this is
911171482Sjeff * via sched_switch() we leave the thread in a blocked state as an
912171482Sjeff * optimization.
913171482Sjeff */
914171482Sjeffstatic inline struct tdq *
915171482Sjeffsched_setcpu(struct td_sched *ts, int cpu, int flags)
916123433Sjeff{
917171482Sjeff	struct thread *td;
918171482Sjeff	struct tdq *tdq;
919123433Sjeff
920171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
921171482Sjeff
922171482Sjeff	tdq = TDQ_CPU(cpu);
923171482Sjeff	td = ts->ts_thread;
924171482Sjeff	ts->ts_cpu = cpu;
925171713Sjeff
926171713Sjeff	/* If the lock matches just return the queue. */
927171482Sjeff	if (td->td_lock == TDQ_LOCKPTR(tdq))
928171482Sjeff		return (tdq);
929171482Sjeff#ifdef notyet
930123433Sjeff	/*
931171482Sjeff	 * If the thread isn't running it's lockptr is a
932171482Sjeff	 * turnstile or a sleepqueue.  We can just lock_set without
933171482Sjeff	 * blocking.
934123685Sjeff	 */
935171482Sjeff	if (TD_CAN_RUN(td)) {
936171482Sjeff		TDQ_LOCK(tdq);
937171482Sjeff		thread_lock_set(td, TDQ_LOCKPTR(tdq));
938171482Sjeff		return (tdq);
939171482Sjeff	}
940171482Sjeff#endif
941166108Sjeff	/*
942171482Sjeff	 * The hard case, migration, we need to block the thread first to
943171482Sjeff	 * prevent order reversals with other cpus locks.
944166108Sjeff	 */
945171482Sjeff	thread_lock_block(td);
946171482Sjeff	TDQ_LOCK(tdq);
947171713Sjeff	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
948171482Sjeff	return (tdq);
949166108Sjeff}
950166108Sjeff
951171482Sjeff/*
952171482Sjeff * Find the thread queue running the lowest priority thread.
953171482Sjeff */
954166108Sjeffstatic int
955171482Sjefftdq_lowestpri(void)
956166108Sjeff{
957171482Sjeff	struct tdq *tdq;
958166108Sjeff	int lowpri;
959166108Sjeff	int lowcpu;
960166108Sjeff	int lowload;
961166108Sjeff	int load;
962171482Sjeff	int cpu;
963171482Sjeff	int pri;
964171482Sjeff
965171482Sjeff	lowload = 0;
966171482Sjeff	lowpri = lowcpu = 0;
967171482Sjeff	for (cpu = 0; cpu <= mp_maxid; cpu++) {
968171482Sjeff		if (CPU_ABSENT(cpu))
969171482Sjeff			continue;
970171482Sjeff		tdq = TDQ_CPU(cpu);
971171482Sjeff		pri = tdq->tdq_lowpri;
972171482Sjeff		load = TDQ_CPU(cpu)->tdq_load;
973171482Sjeff		CTR4(KTR_ULE,
974171482Sjeff		    "cpu %d pri %d lowcpu %d lowpri %d",
975171482Sjeff		    cpu, pri, lowcpu, lowpri);
976171482Sjeff		if (pri < lowpri)
977171482Sjeff			continue;
978171482Sjeff		if (lowpri && lowpri == pri && load > lowload)
979171482Sjeff			continue;
980171482Sjeff		lowpri = pri;
981171482Sjeff		lowcpu = cpu;
982171482Sjeff		lowload = load;
983171482Sjeff	}
984171482Sjeff
985171482Sjeff	return (lowcpu);
986171482Sjeff}
987171482Sjeff
988171482Sjeff/*
989171482Sjeff * Find the thread queue with the least load.
990171482Sjeff */
991171482Sjeffstatic int
992171482Sjefftdq_lowestload(void)
993171482Sjeff{
994171482Sjeff	struct tdq *tdq;
995171482Sjeff	int lowload;
996171482Sjeff	int lowpri;
997171482Sjeff	int lowcpu;
998171482Sjeff	int load;
999171482Sjeff	int cpu;
1000171482Sjeff	int pri;
1001171482Sjeff
1002171482Sjeff	lowcpu = 0;
1003171482Sjeff	lowload = TDQ_CPU(0)->tdq_load;
1004171482Sjeff	lowpri = TDQ_CPU(0)->tdq_lowpri;
1005171482Sjeff	for (cpu = 1; cpu <= mp_maxid; cpu++) {
1006171482Sjeff		if (CPU_ABSENT(cpu))
1007171482Sjeff			continue;
1008171482Sjeff		tdq = TDQ_CPU(cpu);
1009171482Sjeff		load = tdq->tdq_load;
1010171482Sjeff		pri = tdq->tdq_lowpri;
1011171482Sjeff		CTR4(KTR_ULE, "cpu %d load %d lowcpu %d lowload %d",
1012171482Sjeff		    cpu, load, lowcpu, lowload);
1013171482Sjeff		if (load > lowload)
1014171482Sjeff			continue;
1015171482Sjeff		if (load == lowload && pri < lowpri)
1016171482Sjeff			continue;
1017171482Sjeff		lowcpu = cpu;
1018171482Sjeff		lowload = load;
1019171482Sjeff		lowpri = pri;
1020171482Sjeff	}
1021171482Sjeff
1022171482Sjeff	return (lowcpu);
1023171482Sjeff}
1024171482Sjeff
1025171482Sjeff/*
1026171482Sjeff * Pick the destination cpu for sched_add().  Respects affinity and makes
1027171482Sjeff * a determination based on load or priority of available processors.
1028171482Sjeff */
1029171482Sjeffstatic int
1030171482Sjeffsched_pickcpu(struct td_sched *ts, int flags)
1031171482Sjeff{
1032171482Sjeff	struct tdq *tdq;
1033166108Sjeff	int self;
1034166108Sjeff	int pri;
1035166108Sjeff	int cpu;
1036166108Sjeff
1037171482Sjeff	cpu = self = PCPU_GET(cpuid);
1038166108Sjeff	if (smp_started == 0)
1039166108Sjeff		return (self);
1040171506Sjeff	/*
1041171506Sjeff	 * Don't migrate a running thread from sched_switch().
1042171506Sjeff	 */
1043171506Sjeff	if (flags & SRQ_OURSELF) {
1044171506Sjeff		CTR1(KTR_ULE, "YIELDING %d",
1045171506Sjeff		    curthread->td_priority);
1046171506Sjeff		return (self);
1047171506Sjeff	}
1048166108Sjeff	pri = ts->ts_thread->td_priority;
1049171482Sjeff	cpu = ts->ts_cpu;
1050166108Sjeff	/*
1051166108Sjeff	 * Regardless of affinity, if the last cpu is idle send it there.
1052166108Sjeff	 */
1053171482Sjeff	tdq = TDQ_CPU(cpu);
1054171482Sjeff	if (tdq->tdq_lowpri > PRI_MIN_IDLE) {
1055166229Sjeff		CTR5(KTR_ULE,
1056166108Sjeff		    "ts_cpu %d idle, ltick %d ticks %d pri %d curthread %d",
1057166108Sjeff		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1058171482Sjeff		    tdq->tdq_lowpri);
1059166108Sjeff		return (ts->ts_cpu);
1060123433Sjeff	}
1061166108Sjeff	/*
1062166108Sjeff	 * If we have affinity, try to place it on the cpu we last ran on.
1063166108Sjeff	 */
1064171482Sjeff	if (SCHED_AFFINITY(ts) && tdq->tdq_lowpri > pri) {
1065166229Sjeff		CTR5(KTR_ULE,
1066166108Sjeff		    "affinity for %d, ltick %d ticks %d pri %d curthread %d",
1067166108Sjeff		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1068171482Sjeff		    tdq->tdq_lowpri);
1069166108Sjeff		return (ts->ts_cpu);
1070139334Sjeff	}
1071123433Sjeff	/*
1072166108Sjeff	 * Look for an idle group.
1073123433Sjeff	 */
1074166229Sjeff	CTR1(KTR_ULE, "tdq_idle %X", tdq_idle);
1075166108Sjeff	cpu = ffs(tdq_idle);
1076166108Sjeff	if (cpu)
1077171482Sjeff		return (--cpu);
1078171506Sjeff	/*
1079171506Sjeff	 * If there are no idle cores see if we can run the thread locally.  This may
1080171506Sjeff	 * improve locality among sleepers and wakers when there is shared data.
1081171506Sjeff	 */
1082171506Sjeff	if (tryself && pri < curthread->td_priority) {
1083171506Sjeff		CTR1(KTR_ULE, "tryself %d",
1084166108Sjeff		    curthread->td_priority);
1085166108Sjeff		return (self);
1086123433Sjeff	}
1087133427Sjeff	/*
1088166108Sjeff 	 * Now search for the cpu running the lowest priority thread with
1089166108Sjeff	 * the least load.
1090123433Sjeff	 */
1091171482Sjeff	if (pick_pri)
1092171482Sjeff		cpu = tdq_lowestpri();
1093171482Sjeff	else
1094171482Sjeff		cpu = tdq_lowestload();
1095171482Sjeff	return (cpu);
1096123433Sjeff}
1097123433Sjeff
1098121790Sjeff#endif	/* SMP */
1099121790Sjeff
1100117326Sjeff/*
1101121790Sjeff * Pick the highest priority task we have and return it.
1102117326Sjeff */
1103164936Sjulianstatic struct td_sched *
1104164936Sjuliantdq_choose(struct tdq *tdq)
1105110267Sjeff{
1106164936Sjulian	struct td_sched *ts;
1107110267Sjeff
1108171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1109165762Sjeff	ts = runq_choose(&tdq->tdq_realtime);
1110170787Sjeff	if (ts != NULL)
1111164936Sjulian		return (ts);
1112165766Sjeff	ts = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1113165762Sjeff	if (ts != NULL) {
1114170787Sjeff		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_TIMESHARE,
1115165762Sjeff		    ("tdq_choose: Invalid priority on timeshare queue %d",
1116165762Sjeff		    ts->ts_thread->td_priority));
1117165762Sjeff		return (ts);
1118165762Sjeff	}
1119110267Sjeff
1120165762Sjeff	ts = runq_choose(&tdq->tdq_idle);
1121165762Sjeff	if (ts != NULL) {
1122165762Sjeff		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_IDLE,
1123165762Sjeff		    ("tdq_choose: Invalid priority on idle queue %d",
1124165762Sjeff		    ts->ts_thread->td_priority));
1125165762Sjeff		return (ts);
1126165762Sjeff	}
1127165762Sjeff
1128165762Sjeff	return (NULL);
1129110267Sjeff}
1130110267Sjeff
1131171482Sjeff/*
1132171482Sjeff * Initialize a thread queue.
1133171482Sjeff */
1134109864Sjeffstatic void
1135164936Sjuliantdq_setup(struct tdq *tdq)
1136110028Sjeff{
1137171482Sjeff
1138171713Sjeff	if (bootverbose)
1139171713Sjeff		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1140165762Sjeff	runq_init(&tdq->tdq_realtime);
1141165762Sjeff	runq_init(&tdq->tdq_timeshare);
1142165620Sjeff	runq_init(&tdq->tdq_idle);
1143165620Sjeff	tdq->tdq_load = 0;
1144110028Sjeff}
1145110028Sjeff
1146171713Sjeff#ifdef SMP
1147110028Sjeffstatic void
1148171713Sjefftdg_setup(struct tdq_group *tdg)
1149109864Sjeff{
1150171713Sjeff	if (bootverbose)
1151171713Sjeff		printf("ULE: setup cpu group %d\n", TDG_ID(tdg));
1152171713Sjeff	snprintf(tdg->tdg_name, sizeof(tdg->tdg_name),
1153171713Sjeff	    "sched lock %d", (int)TDG_ID(tdg));
1154171713Sjeff	mtx_init(&tdg->tdg_lock, tdg->tdg_name, "sched lock",
1155171713Sjeff	    MTX_SPIN | MTX_RECURSE);
1156171713Sjeff	LIST_INIT(&tdg->tdg_members);
1157171713Sjeff	tdg->tdg_load = 0;
1158171713Sjeff	tdg->tdg_transferable = 0;
1159171713Sjeff	tdg->tdg_cpus = 0;
1160171713Sjeff	tdg->tdg_mask = 0;
1161171713Sjeff	tdg->tdg_cpumask = 0;
1162171713Sjeff	tdg->tdg_idlemask = 0;
1163171713Sjeff}
1164171713Sjeff
1165171713Sjeffstatic void
1166171713Sjefftdg_add(struct tdq_group *tdg, struct tdq *tdq)
1167171713Sjeff{
1168171713Sjeff	if (tdg->tdg_mask == 0)
1169171713Sjeff		tdg->tdg_mask |= 1 << TDQ_ID(tdq);
1170171713Sjeff	tdg->tdg_cpumask |= 1 << TDQ_ID(tdq);
1171171713Sjeff	tdg->tdg_cpus++;
1172171713Sjeff	tdq->tdq_group = tdg;
1173171713Sjeff	tdq->tdq_lock = &tdg->tdg_lock;
1174171713Sjeff	LIST_INSERT_HEAD(&tdg->tdg_members, tdq, tdq_siblings);
1175171713Sjeff	if (bootverbose)
1176171713Sjeff		printf("ULE: adding cpu %d to group %d: cpus %d mask 0x%X\n",
1177171713Sjeff		    TDQ_ID(tdq), TDG_ID(tdg), tdg->tdg_cpus, tdg->tdg_cpumask);
1178171713Sjeff}
1179171713Sjeff
1180171713Sjeffstatic void
1181171713Sjeffsched_setup_topology(void)
1182171713Sjeff{
1183171713Sjeff	struct tdq_group *tdg;
1184171713Sjeff	struct cpu_group *cg;
1185171713Sjeff	int balance_groups;
1186171482Sjeff	struct tdq *tdq;
1187109864Sjeff	int i;
1188171713Sjeff	int j;
1189109864Sjeff
1190171713Sjeff	topology = 1;
1191123487Sjeff	balance_groups = 0;
1192171713Sjeff	for (i = 0; i < smp_topology->ct_count; i++) {
1193171713Sjeff		cg = &smp_topology->ct_group[i];
1194171713Sjeff		tdg = &tdq_groups[i];
1195171713Sjeff		/*
1196171713Sjeff		 * Initialize the group.
1197171713Sjeff		 */
1198171713Sjeff		tdg_setup(tdg);
1199171713Sjeff		/*
1200171713Sjeff		 * Find all of the group members and add them.
1201171713Sjeff		 */
1202171713Sjeff		for (j = 0; j < MAXCPU; j++) {
1203171713Sjeff			if ((cg->cg_mask & (1 << j)) != 0) {
1204171713Sjeff				tdq = TDQ_CPU(j);
1205171713Sjeff				tdq_setup(tdq);
1206171713Sjeff				tdg_add(tdg, tdq);
1207171713Sjeff			}
1208171713Sjeff		}
1209171713Sjeff		if (tdg->tdg_cpus > 1)
1210171713Sjeff			balance_groups = 1;
1211171713Sjeff	}
1212171713Sjeff	tdg_maxid = smp_topology->ct_count - 1;
1213171713Sjeff	if (balance_groups)
1214171713Sjeff		sched_balance_groups(NULL);
1215171713Sjeff}
1216171713Sjeff
1217171713Sjeffstatic void
1218171713Sjeffsched_setup_smp(void)
1219171713Sjeff{
1220171713Sjeff	struct tdq_group *tdg;
1221171713Sjeff	struct tdq *tdq;
1222171713Sjeff	int cpus;
1223171713Sjeff	int i;
1224171713Sjeff
1225171713Sjeff	for (cpus = 0, i = 0; i < MAXCPU; i++) {
1226171713Sjeff		if (CPU_ABSENT(i))
1227171713Sjeff			continue;
1228165627Sjeff		tdq = &tdq_cpu[i];
1229171713Sjeff		tdg = &tdq_groups[i];
1230171713Sjeff		/*
1231171713Sjeff		 * Setup a tdq group with one member.
1232171713Sjeff		 */
1233171713Sjeff		tdg_setup(tdg);
1234171713Sjeff		tdq_setup(tdq);
1235171713Sjeff		tdg_add(tdg, tdq);
1236171713Sjeff		cpus++;
1237123433Sjeff	}
1238171713Sjeff	tdg_maxid = cpus - 1;
1239171713Sjeff}
1240123433Sjeff
1241171713Sjeff/*
1242171713Sjeff * Fake a topology with one group containing all CPUs.
1243171713Sjeff */
1244171713Sjeffstatic void
1245171713Sjeffsched_fake_topo(void)
1246171713Sjeff{
1247171713Sjeff#ifdef SCHED_FAKE_TOPOLOGY
1248171713Sjeff	static struct cpu_top top;
1249171713Sjeff	static struct cpu_group group;
1250113357Sjeff
1251171713Sjeff	top.ct_count = 1;
1252171713Sjeff	top.ct_group = &group;
1253171713Sjeff	group.cg_mask = all_cpus;
1254171713Sjeff	group.cg_count = mp_ncpus;
1255171713Sjeff	group.cg_children = 0;
1256171713Sjeff	smp_topology = &top;
1257171713Sjeff#endif
1258171713Sjeff}
1259171713Sjeff#endif
1260171713Sjeff
1261171713Sjeff/*
1262171713Sjeff * Setup the thread queues and initialize the topology based on MD
1263171713Sjeff * information.
1264171713Sjeff */
1265171713Sjeffstatic void
1266171713Sjeffsched_setup(void *dummy)
1267171713Sjeff{
1268171713Sjeff	struct tdq *tdq;
1269171713Sjeff
1270171713Sjeff	tdq = TDQ_SELF();
1271171713Sjeff#ifdef SMP
1272123487Sjeff	/*
1273171482Sjeff	 * Initialize long-term cpu balancing algorithm.
1274123487Sjeff	 */
1275171482Sjeff	callout_init(&balco, CALLOUT_MPSAFE);
1276171482Sjeff	callout_init(&gbalco, CALLOUT_MPSAFE);
1277171713Sjeff	sched_fake_topo();
1278171713Sjeff	/*
1279171713Sjeff	 * Setup tdqs based on a topology configuration or vanilla SMP based
1280171713Sjeff	 * on mp_maxid.
1281171713Sjeff	 */
1282171713Sjeff	if (smp_topology == NULL)
1283171713Sjeff		sched_setup_smp();
1284171713Sjeff	else
1285171713Sjeff		sched_setup_topology();
1286171482Sjeff	sched_balance(NULL);
1287117237Sjeff#else
1288171713Sjeff	tdq_setup(tdq);
1289171713Sjeff	mtx_init(&tdq_lock, "sched lock", "sched lock", MTX_SPIN | MTX_RECURSE);
1290171713Sjeff	tdq->tdq_lock = &tdq_lock;
1291116069Sjeff#endif
1292171482Sjeff	/*
1293171482Sjeff	 * To avoid divide-by-zero, we set realstathz a dummy value
1294171482Sjeff	 * in case which sched_clock() called before sched_initticks().
1295171482Sjeff	 */
1296171482Sjeff	realstathz = hz;
1297171482Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1298171482Sjeff	tickincr = 1 << SCHED_TICK_SHIFT;
1299171482Sjeff
1300171482Sjeff	/* Add thread0's load since it's running. */
1301171482Sjeff	TDQ_LOCK(tdq);
1302171713Sjeff	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1303171482Sjeff	tdq_load_add(tdq, &td_sched0);
1304171482Sjeff	TDQ_UNLOCK(tdq);
1305109864Sjeff}
1306109864Sjeff
1307171482Sjeff/*
1308171482Sjeff * This routine determines the tickincr after stathz and hz are setup.
1309171482Sjeff */
1310153533Sdavidxu/* ARGSUSED */
1311153533Sdavidxustatic void
1312153533Sdavidxusched_initticks(void *dummy)
1313153533Sdavidxu{
1314171482Sjeff	int incr;
1315171482Sjeff
1316153533Sdavidxu	realstathz = stathz ? stathz : hz;
1317166229Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1318153533Sdavidxu
1319153533Sdavidxu	/*
1320165762Sjeff	 * tickincr is shifted out by 10 to avoid rounding errors due to
1321165766Sjeff	 * hz not being evenly divisible by stathz on all platforms.
1322153533Sdavidxu	 */
1323171482Sjeff	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1324165762Sjeff	/*
1325165762Sjeff	 * This does not work for values of stathz that are more than
1326165762Sjeff	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1327165762Sjeff	 */
1328171482Sjeff	if (incr == 0)
1329171482Sjeff		incr = 1;
1330171482Sjeff	tickincr = incr;
1331166108Sjeff#ifdef SMP
1332166108Sjeff	affinity = SCHED_AFFINITY_DEFAULT;
1333166108Sjeff#endif
1334153533Sdavidxu}
1335153533Sdavidxu
1336153533Sdavidxu
1337109864Sjeff/*
1338171482Sjeff * This is the core of the interactivity algorithm.  Determines a score based
1339171482Sjeff * on past behavior.  It is the ratio of sleep time to run time scaled to
1340171482Sjeff * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1341171482Sjeff * differs from the cpu usage because it does not account for time spent
1342171482Sjeff * waiting on a run-queue.  Would be prettier if we had floating point.
1343171482Sjeff */
1344171482Sjeffstatic int
1345171482Sjeffsched_interact_score(struct thread *td)
1346171482Sjeff{
1347171482Sjeff	struct td_sched *ts;
1348171482Sjeff	int div;
1349171482Sjeff
1350171482Sjeff	ts = td->td_sched;
1351171482Sjeff	/*
1352171482Sjeff	 * The score is only needed if this is likely to be an interactive
1353171482Sjeff	 * task.  Don't go through the expense of computing it if there's
1354171482Sjeff	 * no chance.
1355171482Sjeff	 */
1356171482Sjeff	if (sched_interact <= SCHED_INTERACT_HALF &&
1357171482Sjeff		ts->ts_runtime >= ts->ts_slptime)
1358171482Sjeff			return (SCHED_INTERACT_HALF);
1359171482Sjeff
1360171482Sjeff	if (ts->ts_runtime > ts->ts_slptime) {
1361171482Sjeff		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1362171482Sjeff		return (SCHED_INTERACT_HALF +
1363171482Sjeff		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1364171482Sjeff	}
1365171482Sjeff	if (ts->ts_slptime > ts->ts_runtime) {
1366171482Sjeff		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1367171482Sjeff		return (ts->ts_runtime / div);
1368171482Sjeff	}
1369171482Sjeff	/* runtime == slptime */
1370171482Sjeff	if (ts->ts_runtime)
1371171482Sjeff		return (SCHED_INTERACT_HALF);
1372171482Sjeff
1373171482Sjeff	/*
1374171482Sjeff	 * This can happen if slptime and runtime are 0.
1375171482Sjeff	 */
1376171482Sjeff	return (0);
1377171482Sjeff
1378171482Sjeff}
1379171482Sjeff
1380171482Sjeff/*
1381109864Sjeff * Scale the scheduling priority according to the "interactivity" of this
1382109864Sjeff * process.
1383109864Sjeff */
1384113357Sjeffstatic void
1385163709Sjbsched_priority(struct thread *td)
1386109864Sjeff{
1387165762Sjeff	int score;
1388109864Sjeff	int pri;
1389109864Sjeff
1390163709Sjb	if (td->td_pri_class != PRI_TIMESHARE)
1391113357Sjeff		return;
1392112966Sjeff	/*
1393165762Sjeff	 * If the score is interactive we place the thread in the realtime
1394165762Sjeff	 * queue with a priority that is less than kernel and interrupt
1395165762Sjeff	 * priorities.  These threads are not subject to nice restrictions.
1396112966Sjeff	 *
1397171482Sjeff	 * Scores greater than this are placed on the normal timeshare queue
1398165762Sjeff	 * where the priority is partially decided by the most recent cpu
1399165762Sjeff	 * utilization and the rest is decided by nice value.
1400112966Sjeff	 */
1401165762Sjeff	score = sched_interact_score(td);
1402165762Sjeff	if (score < sched_interact) {
1403165762Sjeff		pri = PRI_MIN_REALTIME;
1404165762Sjeff		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1405165762Sjeff		    * score;
1406165762Sjeff		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1407166208Sjeff		    ("sched_priority: invalid interactive priority %d score %d",
1408166208Sjeff		    pri, score));
1409165762Sjeff	} else {
1410165762Sjeff		pri = SCHED_PRI_MIN;
1411165762Sjeff		if (td->td_sched->ts_ticks)
1412165762Sjeff			pri += SCHED_PRI_TICKS(td->td_sched);
1413165762Sjeff		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1414171482Sjeff		KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1415171482Sjeff		    ("sched_priority: invalid priority %d: nice %d, "
1416171482Sjeff		    "ticks %d ftick %d ltick %d tick pri %d",
1417171482Sjeff		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1418171482Sjeff		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1419171482Sjeff		    SCHED_PRI_TICKS(td->td_sched)));
1420165762Sjeff	}
1421165762Sjeff	sched_user_prio(td, pri);
1422112966Sjeff
1423112966Sjeff	return;
1424109864Sjeff}
1425109864Sjeff
1426121868Sjeff/*
1427121868Sjeff * This routine enforces a maximum limit on the amount of scheduling history
1428171482Sjeff * kept.  It is called after either the slptime or runtime is adjusted.  This
1429171482Sjeff * function is ugly due to integer math.
1430121868Sjeff */
1431116463Sjeffstatic void
1432163709Sjbsched_interact_update(struct thread *td)
1433116463Sjeff{
1434165819Sjeff	struct td_sched *ts;
1435166208Sjeff	u_int sum;
1436121605Sjeff
1437165819Sjeff	ts = td->td_sched;
1438171482Sjeff	sum = ts->ts_runtime + ts->ts_slptime;
1439121868Sjeff	if (sum < SCHED_SLP_RUN_MAX)
1440121868Sjeff		return;
1441121868Sjeff	/*
1442165819Sjeff	 * This only happens from two places:
1443165819Sjeff	 * 1) We have added an unusual amount of run time from fork_exit.
1444165819Sjeff	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1445165819Sjeff	 */
1446165819Sjeff	if (sum > SCHED_SLP_RUN_MAX * 2) {
1447171482Sjeff		if (ts->ts_runtime > ts->ts_slptime) {
1448171482Sjeff			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1449171482Sjeff			ts->ts_slptime = 1;
1450165819Sjeff		} else {
1451171482Sjeff			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1452171482Sjeff			ts->ts_runtime = 1;
1453165819Sjeff		}
1454165819Sjeff		return;
1455165819Sjeff	}
1456165819Sjeff	/*
1457121868Sjeff	 * If we have exceeded by more than 1/5th then the algorithm below
1458121868Sjeff	 * will not bring us back into range.  Dividing by two here forces
1459133427Sjeff	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1460121868Sjeff	 */
1461127850Sjeff	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1462171482Sjeff		ts->ts_runtime /= 2;
1463171482Sjeff		ts->ts_slptime /= 2;
1464121868Sjeff		return;
1465116463Sjeff	}
1466171482Sjeff	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1467171482Sjeff	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1468116463Sjeff}
1469116463Sjeff
1470171482Sjeff/*
1471171482Sjeff * Scale back the interactivity history when a child thread is created.  The
1472171482Sjeff * history is inherited from the parent but the thread may behave totally
1473171482Sjeff * differently.  For example, a shell spawning a compiler process.  We want
1474171482Sjeff * to learn that the compiler is behaving badly very quickly.
1475171482Sjeff */
1476121868Sjeffstatic void
1477163709Sjbsched_interact_fork(struct thread *td)
1478121868Sjeff{
1479121868Sjeff	int ratio;
1480121868Sjeff	int sum;
1481121868Sjeff
1482171482Sjeff	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1483121868Sjeff	if (sum > SCHED_SLP_RUN_FORK) {
1484121868Sjeff		ratio = sum / SCHED_SLP_RUN_FORK;
1485171482Sjeff		td->td_sched->ts_runtime /= ratio;
1486171482Sjeff		td->td_sched->ts_slptime /= ratio;
1487121868Sjeff	}
1488121868Sjeff}
1489121868Sjeff
1490113357Sjeff/*
1491171482Sjeff * Called from proc0_init() to setup the scheduler fields.
1492134791Sjulian */
1493134791Sjulianvoid
1494134791Sjulianschedinit(void)
1495134791Sjulian{
1496165762Sjeff
1497134791Sjulian	/*
1498134791Sjulian	 * Set up the scheduler specific parts of proc0.
1499134791Sjulian	 */
1500136167Sjulian	proc0.p_sched = NULL; /* XXX */
1501164936Sjulian	thread0.td_sched = &td_sched0;
1502165762Sjeff	td_sched0.ts_ltick = ticks;
1503165796Sjeff	td_sched0.ts_ftick = ticks;
1504164936Sjulian	td_sched0.ts_thread = &thread0;
1505134791Sjulian}
1506134791Sjulian
1507134791Sjulian/*
1508113357Sjeff * This is only somewhat accurate since given many processes of the same
1509113357Sjeff * priority they will switch when their slices run out, which will be
1510165762Sjeff * at most sched_slice stathz ticks.
1511113357Sjeff */
1512109864Sjeffint
1513109864Sjeffsched_rr_interval(void)
1514109864Sjeff{
1515165762Sjeff
1516165762Sjeff	/* Convert sched_slice to hz */
1517165762Sjeff	return (hz/(realstathz/sched_slice));
1518109864Sjeff}
1519109864Sjeff
1520171482Sjeff/*
1521171482Sjeff * Update the percent cpu tracking information when it is requested or
1522171482Sjeff * the total history exceeds the maximum.  We keep a sliding history of
1523171482Sjeff * tick counts that slowly decays.  This is less precise than the 4BSD
1524171482Sjeff * mechanism since it happens with less regular and frequent events.
1525171482Sjeff */
1526121790Sjeffstatic void
1527164936Sjuliansched_pctcpu_update(struct td_sched *ts)
1528109864Sjeff{
1529165762Sjeff
1530165762Sjeff	if (ts->ts_ticks == 0)
1531165762Sjeff		return;
1532165796Sjeff	if (ticks - (hz / 10) < ts->ts_ltick &&
1533165796Sjeff	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1534165796Sjeff		return;
1535109864Sjeff	/*
1536109864Sjeff	 * Adjust counters and watermark for pctcpu calc.
1537116365Sjeff	 */
1538165762Sjeff	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1539164936Sjulian		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1540165762Sjeff			    SCHED_TICK_TARG;
1541165762Sjeff	else
1542164936Sjulian		ts->ts_ticks = 0;
1543164936Sjulian	ts->ts_ltick = ticks;
1544165762Sjeff	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1545109864Sjeff}
1546109864Sjeff
1547171482Sjeff/*
1548171482Sjeff * Adjust the priority of a thread.  Move it to the appropriate run-queue
1549171482Sjeff * if necessary.  This is the back-end for several priority related
1550171482Sjeff * functions.
1551171482Sjeff */
1552165762Sjeffstatic void
1553139453Sjhbsched_thread_priority(struct thread *td, u_char prio)
1554109864Sjeff{
1555164936Sjulian	struct td_sched *ts;
1556109864Sjeff
1557139316Sjeff	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
1558139316Sjeff	    td, td->td_proc->p_comm, td->td_priority, prio, curthread,
1559139316Sjeff	    curthread->td_proc->p_comm);
1560164936Sjulian	ts = td->td_sched;
1561170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1562139453Sjhb	if (td->td_priority == prio)
1563139453Sjhb		return;
1564165762Sjeff
1565165766Sjeff	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1566121605Sjeff		/*
1567121605Sjeff		 * If the priority has been elevated due to priority
1568121605Sjeff		 * propagation, we may have to move ourselves to a new
1569165762Sjeff		 * queue.  This could be optimized to not re-add in some
1570165762Sjeff		 * cases.
1571133555Sjeff		 */
1572165762Sjeff		sched_rem(td);
1573165762Sjeff		td->td_priority = prio;
1574171482Sjeff		sched_add(td, SRQ_BORROWING);
1575171482Sjeff	} else {
1576171482Sjeff#ifdef SMP
1577171482Sjeff		struct tdq *tdq;
1578171482Sjeff
1579171482Sjeff		tdq = TDQ_CPU(ts->ts_cpu);
1580171482Sjeff		if (prio < tdq->tdq_lowpri)
1581171482Sjeff			tdq->tdq_lowpri = prio;
1582171482Sjeff#endif
1583119488Sdavidxu		td->td_priority = prio;
1584171482Sjeff	}
1585109864Sjeff}
1586109864Sjeff
1587139453Sjhb/*
1588139453Sjhb * Update a thread's priority when it is lent another thread's
1589139453Sjhb * priority.
1590139453Sjhb */
1591109864Sjeffvoid
1592139453Sjhbsched_lend_prio(struct thread *td, u_char prio)
1593139453Sjhb{
1594139453Sjhb
1595139453Sjhb	td->td_flags |= TDF_BORROWING;
1596139453Sjhb	sched_thread_priority(td, prio);
1597139453Sjhb}
1598139453Sjhb
1599139453Sjhb/*
1600139453Sjhb * Restore a thread's priority when priority propagation is
1601139453Sjhb * over.  The prio argument is the minimum priority the thread
1602139453Sjhb * needs to have to satisfy other possible priority lending
1603139453Sjhb * requests.  If the thread's regular priority is less
1604139453Sjhb * important than prio, the thread will keep a priority boost
1605139453Sjhb * of prio.
1606139453Sjhb */
1607139453Sjhbvoid
1608139453Sjhbsched_unlend_prio(struct thread *td, u_char prio)
1609139453Sjhb{
1610139453Sjhb	u_char base_pri;
1611139453Sjhb
1612139453Sjhb	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1613139453Sjhb	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1614163709Sjb		base_pri = td->td_user_pri;
1615139453Sjhb	else
1616139453Sjhb		base_pri = td->td_base_pri;
1617139453Sjhb	if (prio >= base_pri) {
1618139455Sjhb		td->td_flags &= ~TDF_BORROWING;
1619139453Sjhb		sched_thread_priority(td, base_pri);
1620139453Sjhb	} else
1621139453Sjhb		sched_lend_prio(td, prio);
1622139453Sjhb}
1623139453Sjhb
1624171482Sjeff/*
1625171482Sjeff * Standard entry for setting the priority to an absolute value.
1626171482Sjeff */
1627139453Sjhbvoid
1628139453Sjhbsched_prio(struct thread *td, u_char prio)
1629139453Sjhb{
1630139453Sjhb	u_char oldprio;
1631139453Sjhb
1632139453Sjhb	/* First, update the base priority. */
1633139453Sjhb	td->td_base_pri = prio;
1634139453Sjhb
1635139453Sjhb	/*
1636139455Sjhb	 * If the thread is borrowing another thread's priority, don't
1637139453Sjhb	 * ever lower the priority.
1638139453Sjhb	 */
1639139453Sjhb	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1640139453Sjhb		return;
1641139453Sjhb
1642139453Sjhb	/* Change the real priority. */
1643139453Sjhb	oldprio = td->td_priority;
1644139453Sjhb	sched_thread_priority(td, prio);
1645139453Sjhb
1646139453Sjhb	/*
1647139453Sjhb	 * If the thread is on a turnstile, then let the turnstile update
1648139453Sjhb	 * its state.
1649139453Sjhb	 */
1650139453Sjhb	if (TD_ON_LOCK(td) && oldprio != prio)
1651139453Sjhb		turnstile_adjust(td, oldprio);
1652139453Sjhb}
1653139455Sjhb
1654171482Sjeff/*
1655171482Sjeff * Set the base user priority, does not effect current running priority.
1656171482Sjeff */
1657139453Sjhbvoid
1658163709Sjbsched_user_prio(struct thread *td, u_char prio)
1659161599Sdavidxu{
1660161599Sdavidxu	u_char oldprio;
1661161599Sdavidxu
1662163709Sjb	td->td_base_user_pri = prio;
1663164939Sjulian	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1664164939Sjulian                return;
1665163709Sjb	oldprio = td->td_user_pri;
1666163709Sjb	td->td_user_pri = prio;
1667163709Sjb
1668161599Sdavidxu	if (TD_ON_UPILOCK(td) && oldprio != prio)
1669161599Sdavidxu		umtx_pi_adjust(td, oldprio);
1670161599Sdavidxu}
1671161599Sdavidxu
1672161599Sdavidxuvoid
1673161599Sdavidxusched_lend_user_prio(struct thread *td, u_char prio)
1674161599Sdavidxu{
1675161599Sdavidxu	u_char oldprio;
1676161599Sdavidxu
1677161599Sdavidxu	td->td_flags |= TDF_UBORROWING;
1678161599Sdavidxu
1679164091Smaxim	oldprio = td->td_user_pri;
1680163709Sjb	td->td_user_pri = prio;
1681161599Sdavidxu
1682161599Sdavidxu	if (TD_ON_UPILOCK(td) && oldprio != prio)
1683161599Sdavidxu		umtx_pi_adjust(td, oldprio);
1684161599Sdavidxu}
1685161599Sdavidxu
1686161599Sdavidxuvoid
1687161599Sdavidxusched_unlend_user_prio(struct thread *td, u_char prio)
1688161599Sdavidxu{
1689161599Sdavidxu	u_char base_pri;
1690161599Sdavidxu
1691163709Sjb	base_pri = td->td_base_user_pri;
1692161599Sdavidxu	if (prio >= base_pri) {
1693161599Sdavidxu		td->td_flags &= ~TDF_UBORROWING;
1694163709Sjb		sched_user_prio(td, base_pri);
1695161599Sdavidxu	} else
1696161599Sdavidxu		sched_lend_user_prio(td, prio);
1697161599Sdavidxu}
1698161599Sdavidxu
1699171482Sjeff/*
1700171505Sjeff * Add the thread passed as 'newtd' to the run queue before selecting
1701171505Sjeff * the next thread to run.  This is only used for KSE.
1702171505Sjeff */
1703171505Sjeffstatic void
1704171505Sjeffsched_switchin(struct tdq *tdq, struct thread *td)
1705171505Sjeff{
1706171505Sjeff#ifdef SMP
1707171505Sjeff	spinlock_enter();
1708171505Sjeff	TDQ_UNLOCK(tdq);
1709171505Sjeff	thread_lock(td);
1710171505Sjeff	spinlock_exit();
1711171505Sjeff	sched_setcpu(td->td_sched, TDQ_ID(tdq), SRQ_YIELDING);
1712171505Sjeff#else
1713171505Sjeff	td->td_lock = TDQ_LOCKPTR(tdq);
1714171505Sjeff#endif
1715171505Sjeff	tdq_add(tdq, td, SRQ_YIELDING);
1716171505Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1717171505Sjeff}
1718171505Sjeff
1719171505Sjeff/*
1720171713Sjeff * Handle migration from sched_switch().  This happens only for
1721171713Sjeff * cpu binding.
1722171713Sjeff */
1723171713Sjeffstatic struct mtx *
1724171713Sjeffsched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1725171713Sjeff{
1726171713Sjeff	struct tdq *tdn;
1727171713Sjeff
1728171713Sjeff	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1729171713Sjeff#ifdef SMP
1730171713Sjeff	/*
1731171713Sjeff	 * Do the lock dance required to avoid LOR.  We grab an extra
1732171713Sjeff	 * spinlock nesting to prevent preemption while we're
1733171713Sjeff	 * not holding either run-queue lock.
1734171713Sjeff	 */
1735171713Sjeff	spinlock_enter();
1736171713Sjeff	thread_block_switch(td);	/* This releases the lock on tdq. */
1737171713Sjeff	TDQ_LOCK(tdn);
1738171713Sjeff	tdq_add(tdn, td, flags);
1739171713Sjeff	tdq_notify(td->td_sched);
1740171713Sjeff	/*
1741171713Sjeff	 * After we unlock tdn the new cpu still can't switch into this
1742171713Sjeff	 * thread until we've unblocked it in cpu_switch().  The lock
1743171713Sjeff	 * pointers may match in the case of HTT cores.  Don't unlock here
1744171713Sjeff	 * or we can deadlock when the other CPU runs the IPI handler.
1745171713Sjeff	 */
1746171713Sjeff	if (TDQ_LOCKPTR(tdn) != TDQ_LOCKPTR(tdq)) {
1747171713Sjeff		TDQ_UNLOCK(tdn);
1748171713Sjeff		TDQ_LOCK(tdq);
1749171713Sjeff	}
1750171713Sjeff	spinlock_exit();
1751171713Sjeff#endif
1752171713Sjeff	return (TDQ_LOCKPTR(tdn));
1753171713Sjeff}
1754171713Sjeff
1755171713Sjeff/*
1756171482Sjeff * Block a thread for switching.  Similar to thread_block() but does not
1757171482Sjeff * bump the spin count.
1758171482Sjeff */
1759171482Sjeffstatic inline struct mtx *
1760171482Sjeffthread_block_switch(struct thread *td)
1761171482Sjeff{
1762171482Sjeff	struct mtx *lock;
1763171482Sjeff
1764171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1765171482Sjeff	lock = td->td_lock;
1766171482Sjeff	td->td_lock = &blocked_lock;
1767171482Sjeff	mtx_unlock_spin(lock);
1768171482Sjeff
1769171482Sjeff	return (lock);
1770171482Sjeff}
1771171482Sjeff
1772171482Sjeff/*
1773171482Sjeff * Release a thread that was blocked with thread_block_switch().
1774171482Sjeff */
1775171482Sjeffstatic inline void
1776171482Sjeffthread_unblock_switch(struct thread *td, struct mtx *mtx)
1777171482Sjeff{
1778171482Sjeff	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1779171482Sjeff	    (uintptr_t)mtx);
1780171482Sjeff}
1781171482Sjeff
1782171482Sjeff/*
1783171482Sjeff * Switch threads.  This function has to handle threads coming in while
1784171482Sjeff * blocked for some reason, running, or idle.  It also must deal with
1785171482Sjeff * migrating a thread from one queue to another as running threads may
1786171482Sjeff * be assigned elsewhere via binding.
1787171482Sjeff */
1788161599Sdavidxuvoid
1789135051Sjuliansched_switch(struct thread *td, struct thread *newtd, int flags)
1790109864Sjeff{
1791165627Sjeff	struct tdq *tdq;
1792164936Sjulian	struct td_sched *ts;
1793171482Sjeff	struct mtx *mtx;
1794171713Sjeff	int srqflag;
1795171482Sjeff	int cpuid;
1796109864Sjeff
1797170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1798109864Sjeff
1799171482Sjeff	cpuid = PCPU_GET(cpuid);
1800171482Sjeff	tdq = TDQ_CPU(cpuid);
1801164936Sjulian	ts = td->td_sched;
1802171713Sjeff	mtx = td->td_lock;
1803171482Sjeff#ifdef SMP
1804171482Sjeff	ts->ts_rltick = ticks;
1805171482Sjeff	if (newtd && newtd->td_priority < tdq->tdq_lowpri)
1806171482Sjeff		tdq->tdq_lowpri = newtd->td_priority;
1807171482Sjeff#endif
1808133555Sjeff	td->td_lastcpu = td->td_oncpu;
1809113339Sjulian	td->td_oncpu = NOCPU;
1810132266Sjhb	td->td_flags &= ~TDF_NEEDRESCHED;
1811144777Sups	td->td_owepreempt = 0;
1812123434Sjeff	/*
1813171482Sjeff	 * The lock pointer in an idle thread should never change.  Reset it
1814171482Sjeff	 * to CAN_RUN as well.
1815123434Sjeff	 */
1816167327Sjulian	if (TD_IS_IDLETHREAD(td)) {
1817171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1818139334Sjeff		TD_SET_CAN_RUN(td);
1819170293Sjeff	} else if (TD_IS_RUNNING(td)) {
1820171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1821165627Sjeff		tdq_load_rem(tdq, ts);
1822171713Sjeff		srqflag = (flags & SW_PREEMPT) ?
1823170293Sjeff		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1824171713Sjeff		    SRQ_OURSELF|SRQ_YIELDING;
1825171713Sjeff		if (ts->ts_cpu == cpuid)
1826171713Sjeff			tdq_add(tdq, td, srqflag);
1827171713Sjeff		else
1828171713Sjeff			mtx = sched_switch_migrate(tdq, td, srqflag);
1829171482Sjeff	} else {
1830171482Sjeff		/* This thread must be going to sleep. */
1831171482Sjeff		TDQ_LOCK(tdq);
1832171482Sjeff		mtx = thread_block_switch(td);
1833170293Sjeff		tdq_load_rem(tdq, ts);
1834171482Sjeff	}
1835171482Sjeff	/*
1836171482Sjeff	 * We enter here with the thread blocked and assigned to the
1837171482Sjeff	 * appropriate cpu run-queue or sleep-queue and with the current
1838171482Sjeff	 * thread-queue locked.
1839171482Sjeff	 */
1840171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1841171482Sjeff	/*
1842171505Sjeff	 * If KSE assigned a new thread just add it here and let choosethread
1843171505Sjeff	 * select the best one.
1844171482Sjeff	 */
1845171505Sjeff	if (newtd != NULL)
1846171505Sjeff		sched_switchin(tdq, newtd);
1847171482Sjeff	newtd = choosethread();
1848171482Sjeff	/*
1849171482Sjeff	 * Call the MD code to switch contexts if necessary.
1850171482Sjeff	 */
1851145256Sjkoshy	if (td != newtd) {
1852145256Sjkoshy#ifdef	HWPMC_HOOKS
1853145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1854145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1855145256Sjkoshy#endif
1856171482Sjeff		cpu_switch(td, newtd, mtx);
1857171482Sjeff		/*
1858171482Sjeff		 * We may return from cpu_switch on a different cpu.  However,
1859171482Sjeff		 * we always return with td_lock pointing to the current cpu's
1860171482Sjeff		 * run queue lock.
1861171482Sjeff		 */
1862171482Sjeff		cpuid = PCPU_GET(cpuid);
1863171482Sjeff		tdq = TDQ_CPU(cpuid);
1864171482Sjeff		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)td;
1865145256Sjkoshy#ifdef	HWPMC_HOOKS
1866145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1867145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1868145256Sjkoshy#endif
1869171482Sjeff	} else
1870171482Sjeff		thread_unblock_switch(td, mtx);
1871171482Sjeff	/*
1872171482Sjeff	 * Assert that all went well and return.
1873171482Sjeff	 */
1874171482Sjeff#ifdef SMP
1875171482Sjeff	/* We should always get here with the lowest priority td possible */
1876171482Sjeff	tdq->tdq_lowpri = td->td_priority;
1877171482Sjeff#endif
1878171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1879171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1880171482Sjeff	td->td_oncpu = cpuid;
1881109864Sjeff}
1882109864Sjeff
1883171482Sjeff/*
1884171482Sjeff * Adjust thread priorities as a result of a nice request.
1885171482Sjeff */
1886109864Sjeffvoid
1887130551Sjuliansched_nice(struct proc *p, int nice)
1888109864Sjeff{
1889109864Sjeff	struct thread *td;
1890109864Sjeff
1891130551Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
1892170293Sjeff	PROC_SLOCK_ASSERT(p, MA_OWNED);
1893165762Sjeff
1894130551Sjulian	p->p_nice = nice;
1895163709Sjb	FOREACH_THREAD_IN_PROC(p, td) {
1896170293Sjeff		thread_lock(td);
1897163709Sjb		sched_priority(td);
1898165762Sjeff		sched_prio(td, td->td_base_user_pri);
1899170293Sjeff		thread_unlock(td);
1900130551Sjulian	}
1901109864Sjeff}
1902109864Sjeff
1903171482Sjeff/*
1904171482Sjeff * Record the sleep time for the interactivity scorer.
1905171482Sjeff */
1906109864Sjeffvoid
1907126326Sjhbsched_sleep(struct thread *td)
1908109864Sjeff{
1909165762Sjeff
1910170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1911109864Sjeff
1912171482Sjeff	td->td_sched->ts_slptick = ticks;
1913109864Sjeff}
1914109864Sjeff
1915171482Sjeff/*
1916171482Sjeff * Schedule a thread to resume execution and record how long it voluntarily
1917171482Sjeff * slept.  We also update the pctcpu, interactivity, and priority.
1918171482Sjeff */
1919109864Sjeffvoid
1920109864Sjeffsched_wakeup(struct thread *td)
1921109864Sjeff{
1922166229Sjeff	struct td_sched *ts;
1923171482Sjeff	int slptick;
1924165762Sjeff
1925170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1926166229Sjeff	ts = td->td_sched;
1927109864Sjeff	/*
1928165762Sjeff	 * If we slept for more than a tick update our interactivity and
1929165762Sjeff	 * priority.
1930109864Sjeff	 */
1931171482Sjeff	slptick = ts->ts_slptick;
1932171482Sjeff	ts->ts_slptick = 0;
1933171482Sjeff	if (slptick && slptick != ticks) {
1934166208Sjeff		u_int hzticks;
1935109864Sjeff
1936171482Sjeff		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1937171482Sjeff		ts->ts_slptime += hzticks;
1938165819Sjeff		sched_interact_update(td);
1939166229Sjeff		sched_pctcpu_update(ts);
1940163709Sjb		sched_priority(td);
1941109864Sjeff	}
1942166229Sjeff	/* Reset the slice value after we sleep. */
1943166229Sjeff	ts->ts_slice = sched_slice;
1944166190Sjeff	sched_add(td, SRQ_BORING);
1945109864Sjeff}
1946109864Sjeff
1947109864Sjeff/*
1948109864Sjeff * Penalize the parent for creating a new child and initialize the child's
1949109864Sjeff * priority.
1950109864Sjeff */
1951109864Sjeffvoid
1952163709Sjbsched_fork(struct thread *td, struct thread *child)
1953109864Sjeff{
1954170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1955164936Sjulian	sched_fork_thread(td, child);
1956165762Sjeff	/*
1957165762Sjeff	 * Penalize the parent and child for forking.
1958165762Sjeff	 */
1959165762Sjeff	sched_interact_fork(child);
1960165762Sjeff	sched_priority(child);
1961171482Sjeff	td->td_sched->ts_runtime += tickincr;
1962165762Sjeff	sched_interact_update(td);
1963165762Sjeff	sched_priority(td);
1964164936Sjulian}
1965109864Sjeff
1966171482Sjeff/*
1967171482Sjeff * Fork a new thread, may be within the same process.
1968171482Sjeff */
1969164936Sjulianvoid
1970164936Sjuliansched_fork_thread(struct thread *td, struct thread *child)
1971164936Sjulian{
1972164936Sjulian	struct td_sched *ts;
1973164936Sjulian	struct td_sched *ts2;
1974164936Sjulian
1975165762Sjeff	/*
1976165762Sjeff	 * Initialize child.
1977165762Sjeff	 */
1978170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1979163709Sjb	sched_newthread(child);
1980171482Sjeff	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1981164936Sjulian	ts = td->td_sched;
1982164936Sjulian	ts2 = child->td_sched;
1983164936Sjulian	ts2->ts_cpu = ts->ts_cpu;
1984164936Sjulian	ts2->ts_runq = NULL;
1985165762Sjeff	/*
1986165762Sjeff	 * Grab our parents cpu estimation information and priority.
1987165762Sjeff	 */
1988164936Sjulian	ts2->ts_ticks = ts->ts_ticks;
1989164936Sjulian	ts2->ts_ltick = ts->ts_ltick;
1990164936Sjulian	ts2->ts_ftick = ts->ts_ftick;
1991165762Sjeff	child->td_user_pri = td->td_user_pri;
1992165762Sjeff	child->td_base_user_pri = td->td_base_user_pri;
1993165762Sjeff	/*
1994165762Sjeff	 * And update interactivity score.
1995165762Sjeff	 */
1996171482Sjeff	ts2->ts_slptime = ts->ts_slptime;
1997171482Sjeff	ts2->ts_runtime = ts->ts_runtime;
1998165762Sjeff	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
1999113357Sjeff}
2000113357Sjeff
2001171482Sjeff/*
2002171482Sjeff * Adjust the priority class of a thread.
2003171482Sjeff */
2004113357Sjeffvoid
2005163709Sjbsched_class(struct thread *td, int class)
2006113357Sjeff{
2007113357Sjeff
2008170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2009163709Sjb	if (td->td_pri_class == class)
2010113357Sjeff		return;
2011113357Sjeff
2012121896Sjeff#ifdef SMP
2013165827Sjeff	/*
2014165827Sjeff	 * On SMP if we're on the RUNQ we must adjust the transferable
2015165827Sjeff	 * count because could be changing to or from an interrupt
2016165827Sjeff	 * class.
2017165827Sjeff	 */
2018166190Sjeff	if (TD_ON_RUNQ(td)) {
2019165827Sjeff		struct tdq *tdq;
2020165827Sjeff
2021165827Sjeff		tdq = TDQ_CPU(td->td_sched->ts_cpu);
2022165827Sjeff		if (THREAD_CAN_MIGRATE(td)) {
2023165827Sjeff			tdq->tdq_transferable--;
2024165827Sjeff			tdq->tdq_group->tdg_transferable--;
2025122744Sjeff		}
2026165827Sjeff		td->td_pri_class = class;
2027165827Sjeff		if (THREAD_CAN_MIGRATE(td)) {
2028165827Sjeff			tdq->tdq_transferable++;
2029165827Sjeff			tdq->tdq_group->tdg_transferable++;
2030165827Sjeff		}
2031165827Sjeff	}
2032164936Sjulian#endif
2033163709Sjb	td->td_pri_class = class;
2034109864Sjeff}
2035109864Sjeff
2036109864Sjeff/*
2037109864Sjeff * Return some of the child's priority and interactivity to the parent.
2038109864Sjeff */
2039109864Sjeffvoid
2040164939Sjuliansched_exit(struct proc *p, struct thread *child)
2041109864Sjeff{
2042165762Sjeff	struct thread *td;
2043164939Sjulian
2044163709Sjb	CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
2045164939Sjulian	    child, child->td_proc->p_comm, child->td_priority);
2046113372Sjeff
2047170293Sjeff	PROC_SLOCK_ASSERT(p, MA_OWNED);
2048165762Sjeff	td = FIRST_THREAD_IN_PROC(p);
2049165762Sjeff	sched_exit_thread(td, child);
2050113372Sjeff}
2051113372Sjeff
2052171482Sjeff/*
2053171482Sjeff * Penalize another thread for the time spent on this one.  This helps to
2054171482Sjeff * worsen the priority and interactivity of processes which schedule batch
2055171482Sjeff * jobs such as make.  This has little effect on the make process itself but
2056171482Sjeff * causes new processes spawned by it to receive worse scores immediately.
2057171482Sjeff */
2058113372Sjeffvoid
2059164939Sjuliansched_exit_thread(struct thread *td, struct thread *child)
2060164936Sjulian{
2061165762Sjeff
2062164939Sjulian	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
2063165762Sjeff	    child, child->td_proc->p_comm, child->td_priority);
2064164939Sjulian
2065165762Sjeff#ifdef KSE
2066165762Sjeff	/*
2067165762Sjeff	 * KSE forks and exits so often that this penalty causes short-lived
2068165762Sjeff	 * threads to always be non-interactive.  This causes mozilla to
2069165762Sjeff	 * crawl under load.
2070165762Sjeff	 */
2071165762Sjeff	if ((td->td_pflags & TDP_SA) && td->td_proc == child->td_proc)
2072165762Sjeff		return;
2073165762Sjeff#endif
2074165762Sjeff	/*
2075165762Sjeff	 * Give the child's runtime to the parent without returning the
2076165762Sjeff	 * sleep time as a penalty to the parent.  This causes shells that
2077165762Sjeff	 * launch expensive things to mark their children as expensive.
2078165762Sjeff	 */
2079170293Sjeff	thread_lock(td);
2080171482Sjeff	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2081164939Sjulian	sched_interact_update(td);
2082165762Sjeff	sched_priority(td);
2083170293Sjeff	thread_unlock(td);
2084164936Sjulian}
2085164936Sjulian
2086171482Sjeff/*
2087171482Sjeff * Fix priorities on return to user-space.  Priorities may be elevated due
2088171482Sjeff * to static priorities in msleep() or similar.
2089171482Sjeff */
2090164936Sjulianvoid
2091164936Sjuliansched_userret(struct thread *td)
2092164936Sjulian{
2093164936Sjulian	/*
2094164936Sjulian	 * XXX we cheat slightly on the locking here to avoid locking in
2095164936Sjulian	 * the usual case.  Setting td_priority here is essentially an
2096164936Sjulian	 * incomplete workaround for not setting it properly elsewhere.
2097164936Sjulian	 * Now that some interrupt handlers are threads, not setting it
2098164936Sjulian	 * properly elsewhere can clobber it in the window between setting
2099164936Sjulian	 * it here and returning to user mode, so don't waste time setting
2100164936Sjulian	 * it perfectly here.
2101164936Sjulian	 */
2102164936Sjulian	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2103164936Sjulian	    ("thread with borrowed priority returning to userland"));
2104164936Sjulian	if (td->td_priority != td->td_user_pri) {
2105170293Sjeff		thread_lock(td);
2106164936Sjulian		td->td_priority = td->td_user_pri;
2107164936Sjulian		td->td_base_pri = td->td_user_pri;
2108170293Sjeff		thread_unlock(td);
2109164936Sjulian        }
2110164936Sjulian}
2111164936Sjulian
2112171482Sjeff/*
2113171482Sjeff * Handle a stathz tick.  This is really only relevant for timeshare
2114171482Sjeff * threads.
2115171482Sjeff */
2116164936Sjulianvoid
2117121127Sjeffsched_clock(struct thread *td)
2118109864Sjeff{
2119164936Sjulian	struct tdq *tdq;
2120164936Sjulian	struct td_sched *ts;
2121109864Sjeff
2122171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2123164936Sjulian	tdq = TDQ_SELF();
2124133427Sjeff	/*
2125165766Sjeff	 * Advance the insert index once for each tick to ensure that all
2126165766Sjeff	 * threads get a chance to run.
2127133427Sjeff	 */
2128165766Sjeff	if (tdq->tdq_idx == tdq->tdq_ridx) {
2129165766Sjeff		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2130165766Sjeff		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2131165766Sjeff			tdq->tdq_ridx = tdq->tdq_idx;
2132165766Sjeff	}
2133165766Sjeff	ts = td->td_sched;
2134165762Sjeff	/*
2135163709Sjb	 * We only do slicing code for TIMESHARE threads.
2136113357Sjeff	 */
2137163709Sjb	if (td->td_pri_class != PRI_TIMESHARE)
2138113357Sjeff		return;
2139113357Sjeff	/*
2140165766Sjeff	 * We used a tick; charge it to the thread so that we can compute our
2141113357Sjeff	 * interactivity.
2142109864Sjeff	 */
2143171482Sjeff	td->td_sched->ts_runtime += tickincr;
2144163709Sjb	sched_interact_update(td);
2145109864Sjeff	/*
2146109864Sjeff	 * We used up one time slice.
2147109864Sjeff	 */
2148164936Sjulian	if (--ts->ts_slice > 0)
2149113357Sjeff		return;
2150109864Sjeff	/*
2151113357Sjeff	 * We're out of time, recompute priorities and requeue.
2152109864Sjeff	 */
2153165796Sjeff	sched_priority(td);
2154113357Sjeff	td->td_flags |= TDF_NEEDRESCHED;
2155109864Sjeff}
2156109864Sjeff
2157171482Sjeff/*
2158171482Sjeff * Called once per hz tick.  Used for cpu utilization information.  This
2159171482Sjeff * is easier than trying to scale based on stathz.
2160171482Sjeff */
2161171482Sjeffvoid
2162171482Sjeffsched_tick(void)
2163171482Sjeff{
2164171482Sjeff	struct td_sched *ts;
2165171482Sjeff
2166171482Sjeff	ts = curthread->td_sched;
2167171482Sjeff	/* Adjust ticks for pctcpu */
2168171482Sjeff	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2169171482Sjeff	ts->ts_ltick = ticks;
2170171482Sjeff	/*
2171171482Sjeff	 * Update if we've exceeded our desired tick threshhold by over one
2172171482Sjeff	 * second.
2173171482Sjeff	 */
2174171482Sjeff	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2175171482Sjeff		sched_pctcpu_update(ts);
2176171482Sjeff}
2177171482Sjeff
2178171482Sjeff/*
2179171482Sjeff * Return whether the current CPU has runnable tasks.  Used for in-kernel
2180171482Sjeff * cooperative idle threads.
2181171482Sjeff */
2182109864Sjeffint
2183109864Sjeffsched_runnable(void)
2184109864Sjeff{
2185164936Sjulian	struct tdq *tdq;
2186115998Sjeff	int load;
2187109864Sjeff
2188115998Sjeff	load = 1;
2189115998Sjeff
2190164936Sjulian	tdq = TDQ_SELF();
2191121605Sjeff	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2192165620Sjeff		if (tdq->tdq_load > 0)
2193121605Sjeff			goto out;
2194121605Sjeff	} else
2195165620Sjeff		if (tdq->tdq_load - 1 > 0)
2196121605Sjeff			goto out;
2197115998Sjeff	load = 0;
2198115998Sjeffout:
2199115998Sjeff	return (load);
2200109864Sjeff}
2201109864Sjeff
2202171482Sjeff/*
2203171482Sjeff * Choose the highest priority thread to run.  The thread is removed from
2204171482Sjeff * the run-queue while running however the load remains.  For SMP we set
2205171482Sjeff * the tdq in the global idle bitmask if it idles here.
2206171482Sjeff */
2207166190Sjeffstruct thread *
2208109970Sjeffsched_choose(void)
2209109970Sjeff{
2210171482Sjeff#ifdef SMP
2211171482Sjeff	struct tdq_group *tdg;
2212171482Sjeff#endif
2213171482Sjeff	struct td_sched *ts;
2214164936Sjulian	struct tdq *tdq;
2215109970Sjeff
2216164936Sjulian	tdq = TDQ_SELF();
2217171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2218164936Sjulian	ts = tdq_choose(tdq);
2219164936Sjulian	if (ts) {
2220164936Sjulian		tdq_runq_rem(tdq, ts);
2221166190Sjeff		return (ts->ts_thread);
2222109864Sjeff	}
2223109970Sjeff#ifdef SMP
2224171482Sjeff	/*
2225171482Sjeff	 * We only set the idled bit when all of the cpus in the group are
2226171482Sjeff	 * idle.  Otherwise we could get into a situation where a thread bounces
2227171482Sjeff	 * back and forth between two idle cores on seperate physical CPUs.
2228171482Sjeff	 */
2229171482Sjeff	tdg = tdq->tdq_group;
2230171482Sjeff	tdg->tdg_idlemask |= PCPU_GET(cpumask);
2231171482Sjeff	if (tdg->tdg_idlemask == tdg->tdg_cpumask)
2232171482Sjeff		atomic_set_int(&tdq_idle, tdg->tdg_mask);
2233171482Sjeff	tdq->tdq_lowpri = PRI_MAX_IDLE;
2234109970Sjeff#endif
2235166190Sjeff	return (PCPU_GET(idlethread));
2236109864Sjeff}
2237109864Sjeff
2238171482Sjeff/*
2239171482Sjeff * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2240171482Sjeff * we always request it once we exit a critical section.
2241171482Sjeff */
2242171482Sjeffstatic inline void
2243171482Sjeffsched_setpreempt(struct thread *td)
2244166190Sjeff{
2245166190Sjeff	struct thread *ctd;
2246166190Sjeff	int cpri;
2247166190Sjeff	int pri;
2248166190Sjeff
2249166190Sjeff	ctd = curthread;
2250166190Sjeff	pri = td->td_priority;
2251166190Sjeff	cpri = ctd->td_priority;
2252171482Sjeff	if (td->td_priority < ctd->td_priority)
2253171482Sjeff		curthread->td_flags |= TDF_NEEDRESCHED;
2254166190Sjeff	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2255171482Sjeff		return;
2256166190Sjeff	/*
2257166190Sjeff	 * Always preempt IDLE threads.  Otherwise only if the preempting
2258166190Sjeff	 * thread is an ithread.
2259166190Sjeff	 */
2260171482Sjeff	if (pri > preempt_thresh && cpri < PRI_MIN_IDLE)
2261171482Sjeff		return;
2262171482Sjeff	ctd->td_owepreempt = 1;
2263171482Sjeff	return;
2264166190Sjeff}
2265166190Sjeff
2266171482Sjeff/*
2267171482Sjeff * Add a thread to a thread queue.  Initializes priority, slice, runq, and
2268171482Sjeff * add it to the appropriate queue.  This is the internal function called
2269171482Sjeff * when the tdq is predetermined.
2270171482Sjeff */
2271109864Sjeffvoid
2272171482Sjefftdq_add(struct tdq *tdq, struct thread *td, int flags)
2273109864Sjeff{
2274164936Sjulian	struct td_sched *ts;
2275121790Sjeff	int class;
2276166108Sjeff#ifdef SMP
2277166108Sjeff	int cpumask;
2278166108Sjeff#endif
2279109864Sjeff
2280171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2281166190Sjeff	KASSERT((td->td_inhibitors == 0),
2282166190Sjeff	    ("sched_add: trying to run inhibited thread"));
2283166190Sjeff	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2284166190Sjeff	    ("sched_add: bad thread state"));
2285163709Sjb	KASSERT(td->td_proc->p_sflag & PS_INMEM,
2286110267Sjeff	    ("sched_add: process swapped out"));
2287171482Sjeff
2288171482Sjeff	ts = td->td_sched;
2289171482Sjeff	class = PRI_BASE(td->td_pri_class);
2290166190Sjeff        TD_SET_RUNQ(td);
2291166190Sjeff	if (ts->ts_slice == 0)
2292166190Sjeff		ts->ts_slice = sched_slice;
2293133427Sjeff	/*
2294171482Sjeff	 * Pick the run queue based on priority.
2295133427Sjeff	 */
2296171482Sjeff	if (td->td_priority <= PRI_MAX_REALTIME)
2297171482Sjeff		ts->ts_runq = &tdq->tdq_realtime;
2298171482Sjeff	else if (td->td_priority <= PRI_MAX_TIMESHARE)
2299171482Sjeff		ts->ts_runq = &tdq->tdq_timeshare;
2300171482Sjeff	else
2301171482Sjeff		ts->ts_runq = &tdq->tdq_idle;
2302171482Sjeff#ifdef SMP
2303166108Sjeff	cpumask = 1 << ts->ts_cpu;
2304121790Sjeff	/*
2305123685Sjeff	 * If we had been idle, clear our bit in the group and potentially
2306166108Sjeff	 * the global bitmap.
2307121790Sjeff	 */
2308165762Sjeff	if ((class != PRI_IDLE && class != PRI_ITHD) &&
2309166108Sjeff	    (tdq->tdq_group->tdg_idlemask & cpumask) != 0) {
2310121790Sjeff		/*
2311123433Sjeff		 * Check to see if our group is unidling, and if so, remove it
2312123433Sjeff		 * from the global idle mask.
2313121790Sjeff		 */
2314165620Sjeff		if (tdq->tdq_group->tdg_idlemask ==
2315165620Sjeff		    tdq->tdq_group->tdg_cpumask)
2316165620Sjeff			atomic_clear_int(&tdq_idle, tdq->tdq_group->tdg_mask);
2317123433Sjeff		/*
2318123433Sjeff		 * Now remove ourselves from the group specific idle mask.
2319123433Sjeff		 */
2320166108Sjeff		tdq->tdq_group->tdg_idlemask &= ~cpumask;
2321166108Sjeff	}
2322171482Sjeff	if (td->td_priority < tdq->tdq_lowpri)
2323171482Sjeff		tdq->tdq_lowpri = td->td_priority;
2324121790Sjeff#endif
2325171482Sjeff	tdq_runq_add(tdq, ts, flags);
2326171482Sjeff	tdq_load_add(tdq, ts);
2327171482Sjeff}
2328171482Sjeff
2329171482Sjeff/*
2330171482Sjeff * Select the target thread queue and add a thread to it.  Request
2331171482Sjeff * preemption or IPI a remote processor if required.
2332171482Sjeff */
2333171482Sjeffvoid
2334171482Sjeffsched_add(struct thread *td, int flags)
2335171482Sjeff{
2336171482Sjeff	struct td_sched *ts;
2337171482Sjeff	struct tdq *tdq;
2338171482Sjeff#ifdef SMP
2339171482Sjeff	int cpuid;
2340171482Sjeff	int cpu;
2341171482Sjeff#endif
2342171482Sjeff	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
2343171482Sjeff	    td, td->td_proc->p_comm, td->td_priority, curthread,
2344171482Sjeff	    curthread->td_proc->p_comm);
2345171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2346171482Sjeff	ts = td->td_sched;
2347166108Sjeff	/*
2348171482Sjeff	 * Recalculate the priority before we select the target cpu or
2349171482Sjeff	 * run-queue.
2350166108Sjeff	 */
2351171482Sjeff	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2352171482Sjeff		sched_priority(td);
2353171482Sjeff#ifdef SMP
2354171482Sjeff	cpuid = PCPU_GET(cpuid);
2355171482Sjeff	/*
2356171482Sjeff	 * Pick the destination cpu and if it isn't ours transfer to the
2357171482Sjeff	 * target cpu.
2358171482Sjeff	 */
2359171482Sjeff	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_MIGRATE(td))
2360171482Sjeff		cpu = cpuid;
2361171482Sjeff	else if (!THREAD_CAN_MIGRATE(td))
2362171482Sjeff		cpu = ts->ts_cpu;
2363166108Sjeff	else
2364171482Sjeff		cpu = sched_pickcpu(ts, flags);
2365171482Sjeff	tdq = sched_setcpu(ts, cpu, flags);
2366171482Sjeff	tdq_add(tdq, td, flags);
2367171482Sjeff	if (cpu != cpuid) {
2368166108Sjeff		tdq_notify(ts);
2369166108Sjeff		return;
2370166108Sjeff	}
2371171482Sjeff#else
2372171482Sjeff	tdq = TDQ_SELF();
2373171482Sjeff	TDQ_LOCK(tdq);
2374171482Sjeff	/*
2375171482Sjeff	 * Now that the thread is moving to the run-queue, set the lock
2376171482Sjeff	 * to the scheduler's lock.
2377171482Sjeff	 */
2378171482Sjeff	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2379171482Sjeff	tdq_add(tdq, td, flags);
2380166108Sjeff#endif
2381171482Sjeff	if (!(flags & SRQ_YIELDING))
2382171482Sjeff		sched_setpreempt(td);
2383109864Sjeff}
2384109864Sjeff
2385171482Sjeff/*
2386171482Sjeff * Remove a thread from a run-queue without running it.  This is used
2387171482Sjeff * when we're stealing a thread from a remote queue.  Otherwise all threads
2388171482Sjeff * exit by calling sched_exit_thread() and sched_throw() themselves.
2389171482Sjeff */
2390109864Sjeffvoid
2391121127Sjeffsched_rem(struct thread *td)
2392109864Sjeff{
2393164936Sjulian	struct tdq *tdq;
2394164936Sjulian	struct td_sched *ts;
2395113357Sjeff
2396139316Sjeff	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
2397139316Sjeff	    td, td->td_proc->p_comm, td->td_priority, curthread,
2398139316Sjeff	    curthread->td_proc->p_comm);
2399164936Sjulian	ts = td->td_sched;
2400171482Sjeff	tdq = TDQ_CPU(ts->ts_cpu);
2401171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2402171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2403166190Sjeff	KASSERT(TD_ON_RUNQ(td),
2404164936Sjulian	    ("sched_rem: thread not on run queue"));
2405164936Sjulian	tdq_runq_rem(tdq, ts);
2406164936Sjulian	tdq_load_rem(tdq, ts);
2407166190Sjeff	TD_SET_CAN_RUN(td);
2408109864Sjeff}
2409109864Sjeff
2410171482Sjeff/*
2411171482Sjeff * Fetch cpu utilization information.  Updates on demand.
2412171482Sjeff */
2413109864Sjefffixpt_t
2414121127Sjeffsched_pctcpu(struct thread *td)
2415109864Sjeff{
2416109864Sjeff	fixpt_t pctcpu;
2417164936Sjulian	struct td_sched *ts;
2418109864Sjeff
2419109864Sjeff	pctcpu = 0;
2420164936Sjulian	ts = td->td_sched;
2421164936Sjulian	if (ts == NULL)
2422121290Sjeff		return (0);
2423109864Sjeff
2424170293Sjeff	thread_lock(td);
2425164936Sjulian	if (ts->ts_ticks) {
2426109864Sjeff		int rtick;
2427109864Sjeff
2428165796Sjeff		sched_pctcpu_update(ts);
2429109864Sjeff		/* How many rtick per second ? */
2430165762Sjeff		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2431165762Sjeff		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2432109864Sjeff	}
2433164936Sjulian	td->td_proc->p_swtime = ts->ts_ltick - ts->ts_ftick;
2434170293Sjeff	thread_unlock(td);
2435109864Sjeff
2436109864Sjeff	return (pctcpu);
2437109864Sjeff}
2438109864Sjeff
2439171482Sjeff/*
2440171482Sjeff * Bind a thread to a target cpu.
2441171482Sjeff */
2442122038Sjeffvoid
2443122038Sjeffsched_bind(struct thread *td, int cpu)
2444122038Sjeff{
2445164936Sjulian	struct td_sched *ts;
2446122038Sjeff
2447171713Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2448164936Sjulian	ts = td->td_sched;
2449166137Sjeff	if (ts->ts_flags & TSF_BOUND)
2450166152Sjeff		sched_unbind(td);
2451164936Sjulian	ts->ts_flags |= TSF_BOUND;
2452123433Sjeff#ifdef SMP
2453166137Sjeff	sched_pin();
2454123433Sjeff	if (PCPU_GET(cpuid) == cpu)
2455122038Sjeff		return;
2456166137Sjeff	ts->ts_cpu = cpu;
2457122038Sjeff	/* When we return from mi_switch we'll be on the correct cpu. */
2458131527Sphk	mi_switch(SW_VOL, NULL);
2459122038Sjeff#endif
2460122038Sjeff}
2461122038Sjeff
2462171482Sjeff/*
2463171482Sjeff * Release a bound thread.
2464171482Sjeff */
2465122038Sjeffvoid
2466122038Sjeffsched_unbind(struct thread *td)
2467122038Sjeff{
2468165762Sjeff	struct td_sched *ts;
2469165762Sjeff
2470170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2471165762Sjeff	ts = td->td_sched;
2472166137Sjeff	if ((ts->ts_flags & TSF_BOUND) == 0)
2473166137Sjeff		return;
2474165762Sjeff	ts->ts_flags &= ~TSF_BOUND;
2475165762Sjeff#ifdef SMP
2476165762Sjeff	sched_unpin();
2477165762Sjeff#endif
2478122038Sjeff}
2479122038Sjeff
2480109864Sjeffint
2481145256Sjkoshysched_is_bound(struct thread *td)
2482145256Sjkoshy{
2483170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2484164936Sjulian	return (td->td_sched->ts_flags & TSF_BOUND);
2485145256Sjkoshy}
2486145256Sjkoshy
2487171482Sjeff/*
2488171482Sjeff * Basic yield call.
2489171482Sjeff */
2490159630Sdavidxuvoid
2491159630Sdavidxusched_relinquish(struct thread *td)
2492159630Sdavidxu{
2493170293Sjeff	thread_lock(td);
2494163709Sjb	if (td->td_pri_class == PRI_TIMESHARE)
2495159630Sdavidxu		sched_prio(td, PRI_MAX_TIMESHARE);
2496170293Sjeff	SCHED_STAT_INC(switch_relinquish);
2497159630Sdavidxu	mi_switch(SW_VOL, NULL);
2498170293Sjeff	thread_unlock(td);
2499159630Sdavidxu}
2500159630Sdavidxu
2501171482Sjeff/*
2502171482Sjeff * Return the total system load.
2503171482Sjeff */
2504145256Sjkoshyint
2505125289Sjeffsched_load(void)
2506125289Sjeff{
2507125289Sjeff#ifdef SMP
2508125289Sjeff	int total;
2509125289Sjeff	int i;
2510125289Sjeff
2511125289Sjeff	total = 0;
2512165620Sjeff	for (i = 0; i <= tdg_maxid; i++)
2513165620Sjeff		total += TDQ_GROUP(i)->tdg_load;
2514125289Sjeff	return (total);
2515125289Sjeff#else
2516165620Sjeff	return (TDQ_SELF()->tdq_sysload);
2517125289Sjeff#endif
2518125289Sjeff}
2519125289Sjeff
2520125289Sjeffint
2521109864Sjeffsched_sizeof_proc(void)
2522109864Sjeff{
2523109864Sjeff	return (sizeof(struct proc));
2524109864Sjeff}
2525109864Sjeff
2526109864Sjeffint
2527109864Sjeffsched_sizeof_thread(void)
2528109864Sjeff{
2529109864Sjeff	return (sizeof(struct thread) + sizeof(struct td_sched));
2530109864Sjeff}
2531159570Sdavidxu
2532166190Sjeff/*
2533166190Sjeff * The actual idle process.
2534166190Sjeff */
2535166190Sjeffvoid
2536166190Sjeffsched_idletd(void *dummy)
2537166190Sjeff{
2538166190Sjeff	struct thread *td;
2539171482Sjeff	struct tdq *tdq;
2540166190Sjeff
2541166190Sjeff	td = curthread;
2542171482Sjeff	tdq = TDQ_SELF();
2543166190Sjeff	mtx_assert(&Giant, MA_NOTOWNED);
2544171482Sjeff	/* ULE relies on preemption for idle interruption. */
2545171482Sjeff	for (;;) {
2546171482Sjeff#ifdef SMP
2547171482Sjeff		if (tdq_idled(tdq))
2548171482Sjeff			cpu_idle();
2549171482Sjeff#else
2550166190Sjeff		cpu_idle();
2551171482Sjeff#endif
2552171482Sjeff	}
2553166190Sjeff}
2554166190Sjeff
2555170293Sjeff/*
2556170293Sjeff * A CPU is entering for the first time or a thread is exiting.
2557170293Sjeff */
2558170293Sjeffvoid
2559170293Sjeffsched_throw(struct thread *td)
2560170293Sjeff{
2561171482Sjeff	struct tdq *tdq;
2562171482Sjeff
2563171482Sjeff	tdq = TDQ_SELF();
2564170293Sjeff	if (td == NULL) {
2565171482Sjeff		/* Correct spinlock nesting and acquire the correct lock. */
2566171482Sjeff		TDQ_LOCK(tdq);
2567170293Sjeff		spinlock_exit();
2568170293Sjeff	} else {
2569171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2570171482Sjeff		tdq_load_rem(tdq, td->td_sched);
2571170293Sjeff	}
2572170293Sjeff	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2573170293Sjeff	PCPU_SET(switchtime, cpu_ticks());
2574170293Sjeff	PCPU_SET(switchticks, ticks);
2575170293Sjeff	cpu_throw(td, choosethread());	/* doesn't return */
2576170293Sjeff}
2577170293Sjeff
2578171482Sjeff/*
2579171482Sjeff * This is called from fork_exit().  Just acquire the correct locks and
2580171482Sjeff * let fork do the rest of the work.
2581171482Sjeff */
2582170293Sjeffvoid
2583170600Sjeffsched_fork_exit(struct thread *td)
2584170293Sjeff{
2585171482Sjeff	struct td_sched *ts;
2586171482Sjeff	struct tdq *tdq;
2587171482Sjeff	int cpuid;
2588170293Sjeff
2589170293Sjeff	/*
2590170293Sjeff	 * Finish setting up thread glue so that it begins execution in a
2591171482Sjeff	 * non-nested critical section with the scheduler lock held.
2592170293Sjeff	 */
2593171482Sjeff	cpuid = PCPU_GET(cpuid);
2594171482Sjeff	tdq = TDQ_CPU(cpuid);
2595171482Sjeff	ts = td->td_sched;
2596171482Sjeff	if (TD_IS_IDLETHREAD(td))
2597171482Sjeff		td->td_lock = TDQ_LOCKPTR(tdq);
2598171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2599171482Sjeff	td->td_oncpu = cpuid;
2600171482Sjeff	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)td;
2601170600Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
2602170293Sjeff}
2603170293Sjeff
2604171482Sjeffstatic SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0,
2605171482Sjeff    "Scheduler");
2606171482SjeffSYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2607165762Sjeff    "Scheduler name");
2608171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2609171482Sjeff    "Slice size for timeshare threads");
2610171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2611171482Sjeff     "Interactivity score threshold");
2612171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2613171482Sjeff     0,"Min priority for preemption, lower priorities have greater precedence");
2614166108Sjeff#ifdef SMP
2615171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, pick_pri, CTLFLAG_RW, &pick_pri, 0,
2616171482Sjeff    "Pick the target cpu based on priority rather than load.");
2617171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2618171482Sjeff    "Number of hz ticks to keep thread affinity for");
2619171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, tryself, CTLFLAG_RW, &tryself, 0, "");
2620171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2621171482Sjeff    "Enables the long-term load balancer");
2622171506SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance_secs, CTLFLAG_RW, &balance_secs, 0,
2623171506Sjeff    "Average frequence in seconds to run the long-term balancer");
2624171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2625171482Sjeff    "Steals work from another hyper-threaded core on idle");
2626171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2627171482Sjeff    "Attempts to steal work from other cores before idling");
2628171506SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2629171506Sjeff    "Minimum load on remote cpu before we'll steal");
2630171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, topology, CTLFLAG_RD, &topology, 0,
2631171482Sjeff    "True when a topology has been specified by the MD code.");
2632166108Sjeff#endif
2633165762Sjeff
2634165762Sjeff/* ps compat */
2635165762Sjeffstatic fixpt_t  ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
2636165762SjeffSYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2637165762Sjeff
2638165762Sjeff
2639134791Sjulian#define KERN_SWITCH_INCLUDE 1
2640134791Sjulian#include "kern/kern_switch.c"
2641