sched_ule.c revision 176734
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:
33172293Sjeff *   ULE is the last three letters in schedule.  It owes its 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 176734 2008-03-02 07:58:42Z 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
74172887Sgrehan#if !defined(__i386__) && !defined(__amd64__) && !defined(__powerpc__) && !defined(__arm__)
75172345Sjeff#error "This architecture is not currently compatible with ULE"
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_slice;	/* Ticks of slice remaining. */
92171482Sjeff	u_int		ts_slptime;	/* Number of ticks we vol. slept */
93171482Sjeff	u_int		ts_runtime;	/* Number of ticks we were running */
94134791Sjulian	/* The following variables are only used for pctcpu calculation */
95164936Sjulian	int		ts_ltick;	/* Last tick that we were running on */
96164936Sjulian	int		ts_ftick;	/* First tick that we were running on */
97164936Sjulian	int		ts_ticks;	/* Tick count */
98166108Sjeff#ifdef SMP
99166108Sjeff	int		ts_rltick;	/* Real last tick, for affinity. */
100166108Sjeff#endif
101134791Sjulian};
102164936Sjulian/* flags kept in ts_flags */
103166108Sjeff#define	TSF_BOUND	0x0001		/* Thread can not migrate. */
104166108Sjeff#define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
105121790Sjeff
106164936Sjulianstatic struct td_sched td_sched0;
107109864Sjeff
108109864Sjeff/*
109165762Sjeff * Cpu percentage computation macros and defines.
110111857Sjeff *
111165762Sjeff * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
112165762Sjeff * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
113165796Sjeff * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
114165762Sjeff * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
115165762Sjeff * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
116165762Sjeff * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
117165762Sjeff */
118165762Sjeff#define	SCHED_TICK_SECS		10
119165762Sjeff#define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
120165796Sjeff#define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
121165762Sjeff#define	SCHED_TICK_SHIFT	10
122165762Sjeff#define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
123165830Sjeff#define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
124165762Sjeff
125165762Sjeff/*
126165762Sjeff * These macros determine priorities for non-interactive threads.  They are
127165762Sjeff * assigned a priority based on their recent cpu utilization as expressed
128165762Sjeff * by the ratio of ticks to the tick total.  NHALF priorities at the start
129165762Sjeff * and end of the MIN to MAX timeshare range are only reachable with negative
130165762Sjeff * or positive nice respectively.
131165762Sjeff *
132165762Sjeff * PRI_RANGE:	Priority range for utilization dependent priorities.
133116642Sjeff * PRI_NRESV:	Number of nice values.
134165762Sjeff * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
135165762Sjeff * PRI_NICE:	Determines the part of the priority inherited from nice.
136109864Sjeff */
137165762Sjeff#define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
138121869Sjeff#define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
139165762Sjeff#define	SCHED_PRI_MIN		(PRI_MIN_TIMESHARE + SCHED_PRI_NHALF)
140165762Sjeff#define	SCHED_PRI_MAX		(PRI_MAX_TIMESHARE - SCHED_PRI_NHALF)
141170787Sjeff#define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN)
142165762Sjeff#define	SCHED_PRI_TICKS(ts)						\
143165762Sjeff    (SCHED_TICK_HZ((ts)) /						\
144165827Sjeff    (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
145165762Sjeff#define	SCHED_PRI_NICE(nice)	(nice)
146109864Sjeff
147109864Sjeff/*
148165762Sjeff * These determine the interactivity of a process.  Interactivity differs from
149165762Sjeff * cpu utilization in that it expresses the voluntary time slept vs time ran
150165762Sjeff * while cpu utilization includes all time not running.  This more accurately
151165762Sjeff * models the intent of the thread.
152109864Sjeff *
153110645Sjeff * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
154110645Sjeff *		before throttling back.
155121868Sjeff * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
156116365Sjeff * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
157111857Sjeff * INTERACT_THRESH:	Threshhold for placement on the current runq.
158109864Sjeff */
159165762Sjeff#define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
160165762Sjeff#define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
161116365Sjeff#define	SCHED_INTERACT_MAX	(100)
162116365Sjeff#define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
163121126Sjeff#define	SCHED_INTERACT_THRESH	(30)
164111857Sjeff
165109864Sjeff/*
166165762Sjeff * tickincr:		Converts a stathz tick into a hz domain scaled by
167165762Sjeff *			the shift factor.  Without the shift the error rate
168165762Sjeff *			due to rounding would be unacceptably high.
169165762Sjeff * realstathz:		stathz is sometimes 0 and run off of hz.
170165762Sjeff * sched_slice:		Runtime of each thread before rescheduling.
171171482Sjeff * preempt_thresh:	Priority threshold for preemption and remote IPIs.
172109864Sjeff */
173165762Sjeffstatic int sched_interact = SCHED_INTERACT_THRESH;
174165762Sjeffstatic int realstathz;
175165762Sjeffstatic int tickincr;
176165762Sjeffstatic int sched_slice;
177172345Sjeff#ifdef PREEMPTION
178172345Sjeff#ifdef FULL_PREEMPTION
179172345Sjeffstatic int preempt_thresh = PRI_MAX_IDLE;
180172345Sjeff#else
181171482Sjeffstatic int preempt_thresh = PRI_MIN_KERN;
182172345Sjeff#endif
183172345Sjeff#else
184172345Sjeffstatic int preempt_thresh = 0;
185172345Sjeff#endif
186109864Sjeff
187109864Sjeff/*
188171482Sjeff * tdq - per processor runqs and statistics.  All fields are protected by the
189171482Sjeff * tdq_lock.  The load and lowpri may be accessed without to avoid excess
190171482Sjeff * locking in sched_pickcpu();
191109864Sjeff */
192164936Sjulianstruct tdq {
193171713Sjeff	struct mtx	*tdq_lock;		/* Pointer to group lock. */
194171482Sjeff	struct runq	tdq_realtime;		/* real-time run queue. */
195171482Sjeff	struct runq	tdq_timeshare;		/* timeshare run queue. */
196165620Sjeff	struct runq	tdq_idle;		/* Queue of IDLE threads. */
197171482Sjeff	int		tdq_load;		/* Aggregate load. */
198166557Sjeff	u_char		tdq_idx;		/* Current insert index. */
199166557Sjeff	u_char		tdq_ridx;		/* Current removal index. */
200110267Sjeff#ifdef SMP
201171482Sjeff	u_char		tdq_lowpri;		/* Lowest priority thread. */
202171482Sjeff	int		tdq_transferable;	/* Transferable thread count. */
203165620Sjeff	LIST_ENTRY(tdq)	tdq_siblings;		/* Next in tdq group. */
204165620Sjeff	struct tdq_group *tdq_group;		/* Our processor group. */
205125289Sjeff#else
206165620Sjeff	int		tdq_sysload;		/* For loadavg, !ITHD load. */
207110267Sjeff#endif
208171482Sjeff} __aligned(64);
209109864Sjeff
210166108Sjeff
211123433Sjeff#ifdef SMP
212109864Sjeff/*
213164936Sjulian * tdq groups are groups of processors which can cheaply share threads.  When
214123433Sjeff * one processor in the group goes idle it will check the runqs of the other
215123433Sjeff * processors in its group prior to halting and waiting for an interrupt.
216123433Sjeff * These groups are suitable for SMT (Symetric Multi-Threading) and not NUMA.
217123433Sjeff * In a numa environment we'd want an idle bitmap per group and a two tiered
218123433Sjeff * load balancer.
219123433Sjeff */
220164936Sjulianstruct tdq_group {
221171713Sjeff	struct mtx	tdg_lock;	/* Protects all fields below. */
222171713Sjeff	int		tdg_cpus;	/* Count of CPUs in this tdq group. */
223171713Sjeff	cpumask_t 	tdg_cpumask;	/* Mask of cpus in this group. */
224171713Sjeff	cpumask_t 	tdg_idlemask;	/* Idle cpus in this group. */
225171713Sjeff	cpumask_t 	tdg_mask;	/* Bit mask for first cpu. */
226171713Sjeff	int		tdg_load;	/* Total load of this group. */
227165620Sjeff	int	tdg_transferable;	/* Transferable load of this group. */
228165620Sjeff	LIST_HEAD(, tdq) tdg_members;	/* Linked list of all members. */
229171713Sjeff	char		tdg_name[16];	/* lock name. */
230171482Sjeff} __aligned(64);
231123433Sjeff
232171482Sjeff#define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 300))
233166108Sjeff#define	SCHED_AFFINITY(ts)	((ts)->ts_rltick > ticks - affinity)
234166108Sjeff
235123433Sjeff/*
236166108Sjeff * Run-time tunables.
237166108Sjeff */
238171506Sjeffstatic int rebalance = 1;
239172409Sjeffstatic int balance_interval = 128;	/* Default set in sched_initticks(). */
240171506Sjeffstatic int pick_pri = 1;
241166108Sjeffstatic int affinity;
242166108Sjeffstatic int tryself = 1;
243172409Sjeffstatic int steal_htt = 1;
244171506Sjeffstatic int steal_idle = 1;
245171506Sjeffstatic int steal_thresh = 2;
246166108Sjeff
247166108Sjeff/*
248165620Sjeff * One thread queue per processor.
249109864Sjeff */
250166108Sjeffstatic volatile cpumask_t tdq_idle;
251165620Sjeffstatic int tdg_maxid;
252164936Sjulianstatic struct tdq	tdq_cpu[MAXCPU];
253164936Sjulianstatic struct tdq_group tdq_groups[MAXCPU];
254172409Sjeffstatic struct tdq	*balance_tdq;
255172409Sjeffstatic int balance_group_ticks;
256172409Sjeffstatic int balance_ticks;
257129982Sjeff
258164936Sjulian#define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
259164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu[(x)])
260171713Sjeff#define	TDQ_ID(x)	((int)((x) - tdq_cpu))
261164936Sjulian#define	TDQ_GROUP(x)	(&tdq_groups[(x)])
262171713Sjeff#define	TDG_ID(x)	((int)((x) - tdq_groups))
263123433Sjeff#else	/* !SMP */
264164936Sjulianstatic struct tdq	tdq_cpu;
265171713Sjeffstatic struct mtx	tdq_lock;
266129982Sjeff
267170315Sjeff#define	TDQ_ID(x)	(0)
268164936Sjulian#define	TDQ_SELF()	(&tdq_cpu)
269164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu)
270110028Sjeff#endif
271109864Sjeff
272171482Sjeff#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
273171482Sjeff#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
274171482Sjeff#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
275171482Sjeff#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
276171713Sjeff#define	TDQ_LOCKPTR(t)		((t)->tdq_lock)
277171482Sjeff
278163709Sjbstatic void sched_priority(struct thread *);
279146954Sjeffstatic void sched_thread_priority(struct thread *, u_char);
280163709Sjbstatic int sched_interact_score(struct thread *);
281163709Sjbstatic void sched_interact_update(struct thread *);
282163709Sjbstatic void sched_interact_fork(struct thread *);
283164936Sjulianstatic void sched_pctcpu_update(struct td_sched *);
284109864Sjeff
285110267Sjeff/* Operations on per processor queues */
286164936Sjulianstatic struct td_sched * tdq_choose(struct tdq *);
287164936Sjulianstatic void tdq_setup(struct tdq *);
288164936Sjulianstatic void tdq_load_add(struct tdq *, struct td_sched *);
289164936Sjulianstatic void tdq_load_rem(struct tdq *, struct td_sched *);
290164936Sjulianstatic __inline void tdq_runq_add(struct tdq *, struct td_sched *, int);
291164936Sjulianstatic __inline void tdq_runq_rem(struct tdq *, struct td_sched *);
292164936Sjulianvoid tdq_print(int cpu);
293165762Sjeffstatic void runq_print(struct runq *rq);
294171482Sjeffstatic void tdq_add(struct tdq *, struct thread *, int);
295110267Sjeff#ifdef SMP
296171482Sjeffstatic void tdq_move(struct tdq *, struct tdq *);
297171482Sjeffstatic int tdq_idled(struct tdq *);
298171482Sjeffstatic void tdq_notify(struct td_sched *);
299172409Sjeffstatic struct td_sched *tdq_steal(struct tdq *);
300164936Sjulianstatic struct td_sched *runq_steal(struct runq *);
301171482Sjeffstatic int sched_pickcpu(struct td_sched *, int);
302172409Sjeffstatic void sched_balance(void);
303172409Sjeffstatic void sched_balance_groups(void);
304164936Sjulianstatic void sched_balance_group(struct tdq_group *);
305164936Sjulianstatic void sched_balance_pair(struct tdq *, struct tdq *);
306171482Sjeffstatic inline struct tdq *sched_setcpu(struct td_sched *, int, int);
307171482Sjeffstatic inline struct mtx *thread_block_switch(struct thread *);
308171482Sjeffstatic inline void thread_unblock_switch(struct thread *, struct mtx *);
309171713Sjeffstatic struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
310165827Sjeff
311166108Sjeff#define	THREAD_CAN_MIGRATE(td)	 ((td)->td_pinned == 0)
312121790Sjeff#endif
313110028Sjeff
314165762Sjeffstatic void sched_setup(void *dummy);
315165762SjeffSYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
316165762Sjeff
317165762Sjeffstatic void sched_initticks(void *dummy);
318165762SjeffSYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks, NULL)
319165762Sjeff
320171482Sjeff/*
321171482Sjeff * Print the threads waiting on a run-queue.
322171482Sjeff */
323165762Sjeffstatic void
324165762Sjeffrunq_print(struct runq *rq)
325165762Sjeff{
326165762Sjeff	struct rqhead *rqh;
327165762Sjeff	struct td_sched *ts;
328165762Sjeff	int pri;
329165762Sjeff	int j;
330165762Sjeff	int i;
331165762Sjeff
332165762Sjeff	for (i = 0; i < RQB_LEN; i++) {
333165762Sjeff		printf("\t\trunq bits %d 0x%zx\n",
334165762Sjeff		    i, rq->rq_status.rqb_bits[i]);
335165762Sjeff		for (j = 0; j < RQB_BPW; j++)
336165762Sjeff			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
337165762Sjeff				pri = j + (i << RQB_L2BPW);
338165762Sjeff				rqh = &rq->rq_queues[pri];
339165762Sjeff				TAILQ_FOREACH(ts, rqh, ts_procq) {
340165762Sjeff					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
341173600Sjulian					    ts->ts_thread, ts->ts_thread->td_name, ts->ts_thread->td_priority, ts->ts_rqindex, pri);
342165762Sjeff				}
343165762Sjeff			}
344165762Sjeff	}
345165762Sjeff}
346165762Sjeff
347171482Sjeff/*
348171482Sjeff * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
349171482Sjeff */
350113357Sjeffvoid
351164936Sjuliantdq_print(int cpu)
352110267Sjeff{
353164936Sjulian	struct tdq *tdq;
354112994Sjeff
355164936Sjulian	tdq = TDQ_CPU(cpu);
356112994Sjeff
357171713Sjeff	printf("tdq %d:\n", TDQ_ID(tdq));
358171482Sjeff	printf("\tlockptr         %p\n", TDQ_LOCKPTR(tdq));
359165620Sjeff	printf("\tload:           %d\n", tdq->tdq_load);
360171482Sjeff	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
361165766Sjeff	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
362165762Sjeff	printf("\trealtime runq:\n");
363165762Sjeff	runq_print(&tdq->tdq_realtime);
364165762Sjeff	printf("\ttimeshare runq:\n");
365165762Sjeff	runq_print(&tdq->tdq_timeshare);
366165762Sjeff	printf("\tidle runq:\n");
367165762Sjeff	runq_print(&tdq->tdq_idle);
368121896Sjeff#ifdef SMP
369165620Sjeff	printf("\tload transferable: %d\n", tdq->tdq_transferable);
370171713Sjeff	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
371171713Sjeff	printf("\tgroup:             %d\n", TDG_ID(tdq->tdq_group));
372171713Sjeff	printf("\tLock name:         %s\n", tdq->tdq_group->tdg_name);
373121896Sjeff#endif
374113357Sjeff}
375112994Sjeff
376171482Sjeff#define	TS_RQ_PPQ	(((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
377171482Sjeff/*
378171482Sjeff * Add a thread to the actual run-queue.  Keeps transferable counts up to
379171482Sjeff * date with what is actually on the run-queue.  Selects the correct
380171482Sjeff * queue position for timeshare threads.
381171482Sjeff */
382122744Sjeffstatic __inline void
383164936Sjuliantdq_runq_add(struct tdq *tdq, struct td_sched *ts, int flags)
384122744Sjeff{
385171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
386171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
387122744Sjeff#ifdef SMP
388165762Sjeff	if (THREAD_CAN_MIGRATE(ts->ts_thread)) {
389165620Sjeff		tdq->tdq_transferable++;
390165620Sjeff		tdq->tdq_group->tdg_transferable++;
391164936Sjulian		ts->ts_flags |= TSF_XFERABLE;
392123433Sjeff	}
393122744Sjeff#endif
394165762Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
395166557Sjeff		u_char pri;
396165762Sjeff
397165762Sjeff		pri = ts->ts_thread->td_priority;
398165762Sjeff		KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
399165762Sjeff			("Invalid priority %d on timeshare runq", pri));
400165762Sjeff		/*
401165762Sjeff		 * This queue contains only priorities between MIN and MAX
402165762Sjeff		 * realtime.  Use the whole queue to represent these values.
403165762Sjeff		 */
404171713Sjeff		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
405165762Sjeff			pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
406165762Sjeff			pri = (pri + tdq->tdq_idx) % RQ_NQS;
407165766Sjeff			/*
408165766Sjeff			 * This effectively shortens the queue by one so we
409165766Sjeff			 * can have a one slot difference between idx and
410165766Sjeff			 * ridx while we wait for threads to drain.
411165766Sjeff			 */
412165766Sjeff			if (tdq->tdq_ridx != tdq->tdq_idx &&
413165766Sjeff			    pri == tdq->tdq_ridx)
414167664Sjeff				pri = (unsigned char)(pri - 1) % RQ_NQS;
415165762Sjeff		} else
416165766Sjeff			pri = tdq->tdq_ridx;
417165762Sjeff		runq_add_pri(ts->ts_runq, ts, pri, flags);
418165762Sjeff	} else
419165762Sjeff		runq_add(ts->ts_runq, ts, flags);
420122744Sjeff}
421122744Sjeff
422171482Sjeff/*
423171482Sjeff * Remove a thread from a run-queue.  This typically happens when a thread
424171482Sjeff * is selected to run.  Running threads are not on the queue and the
425171482Sjeff * transferable count does not reflect them.
426171482Sjeff */
427122744Sjeffstatic __inline void
428164936Sjuliantdq_runq_rem(struct tdq *tdq, struct td_sched *ts)
429122744Sjeff{
430171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
431171482Sjeff	KASSERT(ts->ts_runq != NULL,
432171482Sjeff	    ("tdq_runq_remove: thread %p null ts_runq", ts->ts_thread));
433122744Sjeff#ifdef SMP
434164936Sjulian	if (ts->ts_flags & TSF_XFERABLE) {
435165620Sjeff		tdq->tdq_transferable--;
436165620Sjeff		tdq->tdq_group->tdg_transferable--;
437164936Sjulian		ts->ts_flags &= ~TSF_XFERABLE;
438123433Sjeff	}
439122744Sjeff#endif
440165766Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
441165766Sjeff		if (tdq->tdq_idx != tdq->tdq_ridx)
442165766Sjeff			runq_remove_idx(ts->ts_runq, ts, &tdq->tdq_ridx);
443165766Sjeff		else
444165766Sjeff			runq_remove_idx(ts->ts_runq, ts, NULL);
445165796Sjeff		/*
446165796Sjeff		 * For timeshare threads we update the priority here so
447165796Sjeff		 * the priority reflects the time we've been sleeping.
448165796Sjeff		 */
449165796Sjeff		ts->ts_ltick = ticks;
450165796Sjeff		sched_pctcpu_update(ts);
451165796Sjeff		sched_priority(ts->ts_thread);
452165766Sjeff	} else
453165762Sjeff		runq_remove(ts->ts_runq, ts);
454122744Sjeff}
455122744Sjeff
456171482Sjeff/*
457171482Sjeff * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
458171482Sjeff * for this thread to the referenced thread queue.
459171482Sjeff */
460113357Sjeffstatic void
461164936Sjuliantdq_load_add(struct tdq *tdq, struct td_sched *ts)
462113357Sjeff{
463121896Sjeff	int class;
464171482Sjeff
465171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
466171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
467164936Sjulian	class = PRI_BASE(ts->ts_thread->td_pri_class);
468165620Sjeff	tdq->tdq_load++;
469171713Sjeff	CTR2(KTR_SCHED, "cpu %d load: %d", TDQ_ID(tdq), tdq->tdq_load);
470166108Sjeff	if (class != PRI_ITHD &&
471166108Sjeff	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
472123487Sjeff#ifdef SMP
473165620Sjeff		tdq->tdq_group->tdg_load++;
474125289Sjeff#else
475165620Sjeff		tdq->tdq_sysload++;
476123487Sjeff#endif
477110267Sjeff}
478113357Sjeff
479171482Sjeff/*
480171482Sjeff * Remove the load from a thread that is transitioning to a sleep state or
481171482Sjeff * exiting.
482171482Sjeff */
483112994Sjeffstatic void
484164936Sjuliantdq_load_rem(struct tdq *tdq, struct td_sched *ts)
485110267Sjeff{
486121896Sjeff	int class;
487171482Sjeff
488171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
489171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
490164936Sjulian	class = PRI_BASE(ts->ts_thread->td_pri_class);
491166108Sjeff	if (class != PRI_ITHD &&
492166108Sjeff	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
493123487Sjeff#ifdef SMP
494165620Sjeff		tdq->tdq_group->tdg_load--;
495125289Sjeff#else
496165620Sjeff		tdq->tdq_sysload--;
497123487Sjeff#endif
498171482Sjeff	KASSERT(tdq->tdq_load != 0,
499171713Sjeff	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
500165620Sjeff	tdq->tdq_load--;
501165620Sjeff	CTR1(KTR_SCHED, "load: %d", tdq->tdq_load);
502164936Sjulian	ts->ts_runq = NULL;
503110267Sjeff}
504110267Sjeff
505113357Sjeff#ifdef SMP
506116069Sjeff/*
507122744Sjeff * sched_balance is a simple CPU load balancing algorithm.  It operates by
508116069Sjeff * finding the least loaded and most loaded cpu and equalizing their load
509116069Sjeff * by migrating some processes.
510116069Sjeff *
511116069Sjeff * Dealing only with two CPUs at a time has two advantages.  Firstly, most
512116069Sjeff * installations will only have 2 cpus.  Secondly, load balancing too much at
513116069Sjeff * once can have an unpleasant effect on the system.  The scheduler rarely has
514116069Sjeff * enough information to make perfect decisions.  So this algorithm chooses
515171482Sjeff * simplicity and more gradual effects on load in larger systems.
516116069Sjeff *
517116069Sjeff */
518121790Sjeffstatic void
519172409Sjeffsched_balance()
520116069Sjeff{
521164936Sjulian	struct tdq_group *high;
522164936Sjulian	struct tdq_group *low;
523165620Sjeff	struct tdq_group *tdg;
524172409Sjeff	struct tdq *tdq;
525123487Sjeff	int cnt;
526123487Sjeff	int i;
527123487Sjeff
528172409Sjeff	/*
529172409Sjeff	 * Select a random time between .5 * balance_interval and
530172409Sjeff	 * 1.5 * balance_interval.
531172409Sjeff	 */
532172409Sjeff	balance_ticks = max(balance_interval / 2, 1);
533172409Sjeff	balance_ticks += random() % balance_interval;
534171482Sjeff	if (smp_started == 0 || rebalance == 0)
535139334Sjeff		return;
536172409Sjeff	tdq = TDQ_SELF();
537172409Sjeff	TDQ_UNLOCK(tdq);
538123487Sjeff	low = high = NULL;
539165620Sjeff	i = random() % (tdg_maxid + 1);
540165620Sjeff	for (cnt = 0; cnt <= tdg_maxid; cnt++) {
541165620Sjeff		tdg = TDQ_GROUP(i);
542123487Sjeff		/*
543123487Sjeff		 * Find the CPU with the highest load that has some
544123487Sjeff		 * threads to transfer.
545123487Sjeff		 */
546165620Sjeff		if ((high == NULL || tdg->tdg_load > high->tdg_load)
547165620Sjeff		    && tdg->tdg_transferable)
548165620Sjeff			high = tdg;
549165620Sjeff		if (low == NULL || tdg->tdg_load < low->tdg_load)
550165620Sjeff			low = tdg;
551165620Sjeff		if (++i > tdg_maxid)
552123487Sjeff			i = 0;
553123487Sjeff	}
554123487Sjeff	if (low != NULL && high != NULL && high != low)
555165620Sjeff		sched_balance_pair(LIST_FIRST(&high->tdg_members),
556165620Sjeff		    LIST_FIRST(&low->tdg_members));
557172409Sjeff	TDQ_LOCK(tdq);
558123487Sjeff}
559123487Sjeff
560171482Sjeff/*
561171482Sjeff * Balance load between CPUs in a group.  Will only migrate within the group.
562171482Sjeff */
563123487Sjeffstatic void
564172409Sjeffsched_balance_groups()
565123487Sjeff{
566172409Sjeff	struct tdq *tdq;
567123487Sjeff	int i;
568123487Sjeff
569172409Sjeff	/*
570172409Sjeff	 * Select a random time between .5 * balance_interval and
571172409Sjeff	 * 1.5 * balance_interval.
572172409Sjeff	 */
573172409Sjeff	balance_group_ticks = max(balance_interval / 2, 1);
574172409Sjeff	balance_group_ticks += random() % balance_interval;
575171482Sjeff	if (smp_started == 0 || rebalance == 0)
576171482Sjeff		return;
577172409Sjeff	tdq = TDQ_SELF();
578172409Sjeff	TDQ_UNLOCK(tdq);
579171482Sjeff	for (i = 0; i <= tdg_maxid; i++)
580171482Sjeff		sched_balance_group(TDQ_GROUP(i));
581172409Sjeff	TDQ_LOCK(tdq);
582123487Sjeff}
583123487Sjeff
584171482Sjeff/*
585171482Sjeff * Finds the greatest imbalance between two tdqs in a group.
586171482Sjeff */
587123487Sjeffstatic void
588165620Sjeffsched_balance_group(struct tdq_group *tdg)
589123487Sjeff{
590164936Sjulian	struct tdq *tdq;
591164936Sjulian	struct tdq *high;
592164936Sjulian	struct tdq *low;
593123487Sjeff	int load;
594123487Sjeff
595165620Sjeff	if (tdg->tdg_transferable == 0)
596123487Sjeff		return;
597123487Sjeff	low = NULL;
598123487Sjeff	high = NULL;
599165620Sjeff	LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
600165620Sjeff		load = tdq->tdq_load;
601165620Sjeff		if (high == NULL || load > high->tdq_load)
602164936Sjulian			high = tdq;
603165620Sjeff		if (low == NULL || load < low->tdq_load)
604164936Sjulian			low = tdq;
605123487Sjeff	}
606123487Sjeff	if (high != NULL && low != NULL && high != low)
607123487Sjeff		sched_balance_pair(high, low);
608123487Sjeff}
609123487Sjeff
610171482Sjeff/*
611171482Sjeff * Lock two thread queues using their address to maintain lock order.
612171482Sjeff */
613123487Sjeffstatic void
614171482Sjefftdq_lock_pair(struct tdq *one, struct tdq *two)
615171482Sjeff{
616171482Sjeff	if (one < two) {
617171482Sjeff		TDQ_LOCK(one);
618171482Sjeff		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
619171482Sjeff	} else {
620171482Sjeff		TDQ_LOCK(two);
621171482Sjeff		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
622171482Sjeff	}
623171482Sjeff}
624171482Sjeff
625171482Sjeff/*
626172409Sjeff * Unlock two thread queues.  Order is not important here.
627172409Sjeff */
628172409Sjeffstatic void
629172409Sjefftdq_unlock_pair(struct tdq *one, struct tdq *two)
630172409Sjeff{
631172409Sjeff	TDQ_UNLOCK(one);
632172409Sjeff	TDQ_UNLOCK(two);
633172409Sjeff}
634172409Sjeff
635172409Sjeff/*
636171482Sjeff * Transfer load between two imbalanced thread queues.
637171482Sjeff */
638171482Sjeffstatic void
639164936Sjuliansched_balance_pair(struct tdq *high, struct tdq *low)
640123487Sjeff{
641123433Sjeff	int transferable;
642116069Sjeff	int high_load;
643116069Sjeff	int low_load;
644116069Sjeff	int move;
645116069Sjeff	int diff;
646116069Sjeff	int i;
647116069Sjeff
648171482Sjeff	tdq_lock_pair(high, low);
649116069Sjeff	/*
650123433Sjeff	 * If we're transfering within a group we have to use this specific
651164936Sjulian	 * tdq's transferable count, otherwise we can steal from other members
652123433Sjeff	 * of the group.
653123433Sjeff	 */
654165620Sjeff	if (high->tdq_group == low->tdq_group) {
655165620Sjeff		transferable = high->tdq_transferable;
656165620Sjeff		high_load = high->tdq_load;
657165620Sjeff		low_load = low->tdq_load;
658123487Sjeff	} else {
659165620Sjeff		transferable = high->tdq_group->tdg_transferable;
660165620Sjeff		high_load = high->tdq_group->tdg_load;
661165620Sjeff		low_load = low->tdq_group->tdg_load;
662123487Sjeff	}
663123433Sjeff	/*
664122744Sjeff	 * Determine what the imbalance is and then adjust that to how many
665165620Sjeff	 * threads we actually have to give up (transferable).
666122744Sjeff	 */
667171482Sjeff	if (transferable != 0) {
668171482Sjeff		diff = high_load - low_load;
669171482Sjeff		move = diff / 2;
670171482Sjeff		if (diff & 0x1)
671171482Sjeff			move++;
672171482Sjeff		move = min(move, transferable);
673171482Sjeff		for (i = 0; i < move; i++)
674171482Sjeff			tdq_move(high, low);
675172293Sjeff		/*
676172293Sjeff		 * IPI the target cpu to force it to reschedule with the new
677172293Sjeff		 * workload.
678172293Sjeff		 */
679172293Sjeff		ipi_selected(1 << TDQ_ID(low), IPI_PREEMPT);
680171482Sjeff	}
681172409Sjeff	tdq_unlock_pair(high, low);
682116069Sjeff	return;
683116069Sjeff}
684116069Sjeff
685171482Sjeff/*
686171482Sjeff * Move a thread from one thread queue to another.
687171482Sjeff */
688121790Sjeffstatic void
689171482Sjefftdq_move(struct tdq *from, struct tdq *to)
690116069Sjeff{
691171482Sjeff	struct td_sched *ts;
692171482Sjeff	struct thread *td;
693164936Sjulian	struct tdq *tdq;
694171482Sjeff	int cpu;
695116069Sjeff
696172409Sjeff	TDQ_LOCK_ASSERT(from, MA_OWNED);
697172409Sjeff	TDQ_LOCK_ASSERT(to, MA_OWNED);
698172409Sjeff
699164936Sjulian	tdq = from;
700171482Sjeff	cpu = TDQ_ID(to);
701172409Sjeff	ts = tdq_steal(tdq);
702164936Sjulian	if (ts == NULL) {
703165620Sjeff		struct tdq_group *tdg;
704123433Sjeff
705165620Sjeff		tdg = tdq->tdq_group;
706165620Sjeff		LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
707165620Sjeff			if (tdq == from || tdq->tdq_transferable == 0)
708123433Sjeff				continue;
709172409Sjeff			ts = tdq_steal(tdq);
710123433Sjeff			break;
711123433Sjeff		}
712164936Sjulian		if (ts == NULL)
713171482Sjeff			return;
714123433Sjeff	}
715164936Sjulian	if (tdq == to)
716123433Sjeff		return;
717171482Sjeff	td = ts->ts_thread;
718171482Sjeff	/*
719171482Sjeff	 * Although the run queue is locked the thread may be blocked.  Lock
720172409Sjeff	 * it to clear this and acquire the run-queue lock.
721171482Sjeff	 */
722171482Sjeff	thread_lock(td);
723172409Sjeff	/* Drop recursive lock on from acquired via thread_lock(). */
724171482Sjeff	TDQ_UNLOCK(from);
725171482Sjeff	sched_rem(td);
726166108Sjeff	ts->ts_cpu = cpu;
727171482Sjeff	td->td_lock = TDQ_LOCKPTR(to);
728171482Sjeff	tdq_add(to, td, SRQ_YIELDING);
729116069Sjeff}
730110267Sjeff
731171482Sjeff/*
732171482Sjeff * This tdq has idled.  Try to steal a thread from another cpu and switch
733171482Sjeff * to it.
734171482Sjeff */
735123433Sjeffstatic int
736164936Sjuliantdq_idled(struct tdq *tdq)
737121790Sjeff{
738165620Sjeff	struct tdq_group *tdg;
739164936Sjulian	struct tdq *steal;
740171482Sjeff	int highload;
741171482Sjeff	int highcpu;
742171482Sjeff	int cpu;
743123433Sjeff
744172484Sjeff	if (smp_started == 0 || steal_idle == 0)
745172484Sjeff		return (1);
746171482Sjeff	/* We don't want to be preempted while we're iterating over tdqs */
747171482Sjeff	spinlock_enter();
748165620Sjeff	tdg = tdq->tdq_group;
749123433Sjeff	/*
750165620Sjeff	 * If we're in a cpu group, try and steal threads from another cpu in
751172409Sjeff	 * the group before idling.  In a HTT group all cpus share the same
752172409Sjeff	 * run-queue lock, however, we still need a recursive lock to
753172409Sjeff	 * call tdq_move().
754123433Sjeff	 */
755166108Sjeff	if (steal_htt && tdg->tdg_cpus > 1 && tdg->tdg_transferable) {
756172409Sjeff		TDQ_LOCK(tdq);
757165620Sjeff		LIST_FOREACH(steal, &tdg->tdg_members, tdq_siblings) {
758165620Sjeff			if (steal == tdq || steal->tdq_transferable == 0)
759123433Sjeff				continue;
760171482Sjeff			TDQ_LOCK(steal);
761172409Sjeff			goto steal;
762166108Sjeff		}
763172409Sjeff		TDQ_UNLOCK(tdq);
764166108Sjeff	}
765172484Sjeff	/*
766172484Sjeff	 * Find the least loaded CPU with a transferable thread and attempt
767172484Sjeff	 * to steal it.  We make a lockless pass and then verify that the
768172484Sjeff	 * thread is still available after locking.
769172484Sjeff	 */
770171482Sjeff	for (;;) {
771171482Sjeff		highcpu = 0;
772171482Sjeff		highload = 0;
773171482Sjeff		for (cpu = 0; cpu <= mp_maxid; cpu++) {
774171482Sjeff			if (CPU_ABSENT(cpu))
775171482Sjeff				continue;
776166108Sjeff			steal = TDQ_CPU(cpu);
777172484Sjeff			if (steal->tdq_transferable == 0)
778166108Sjeff				continue;
779172484Sjeff			if (steal->tdq_load < highload)
780172484Sjeff				continue;
781172484Sjeff			highload = steal->tdq_load;
782171482Sjeff			highcpu = cpu;
783171482Sjeff		}
784171506Sjeff		if (highload < steal_thresh)
785171482Sjeff			break;
786171482Sjeff		steal = TDQ_CPU(highcpu);
787172484Sjeff		if (steal == tdq)
788172484Sjeff			break;
789172409Sjeff		tdq_lock_pair(tdq, steal);
790172484Sjeff		if (steal->tdq_load >= steal_thresh && steal->tdq_transferable)
791166108Sjeff			goto steal;
792172409Sjeff		tdq_unlock_pair(tdq, steal);
793123433Sjeff	}
794171482Sjeff	spinlock_exit();
795123433Sjeff	return (1);
796166108Sjeffsteal:
797171482Sjeff	spinlock_exit();
798172409Sjeff	tdq_move(steal, tdq);
799171482Sjeff	TDQ_UNLOCK(steal);
800171482Sjeff	mi_switch(SW_VOL, NULL);
801171482Sjeff	thread_unlock(curthread);
802121790Sjeff
803166108Sjeff	return (0);
804121790Sjeff}
805121790Sjeff
806171482Sjeff/*
807171482Sjeff * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
808171482Sjeff */
809121790Sjeffstatic void
810166108Sjefftdq_notify(struct td_sched *ts)
811121790Sjeff{
812166247Sjeff	struct thread *ctd;
813121790Sjeff	struct pcpu *pcpu;
814166247Sjeff	int cpri;
815166247Sjeff	int pri;
816166108Sjeff	int cpu;
817121790Sjeff
818166108Sjeff	cpu = ts->ts_cpu;
819166247Sjeff	pri = ts->ts_thread->td_priority;
820166108Sjeff	pcpu = pcpu_find(cpu);
821166247Sjeff	ctd = pcpu->pc_curthread;
822166247Sjeff	cpri = ctd->td_priority;
823166137Sjeff
824121790Sjeff	/*
825166137Sjeff	 * If our priority is not better than the current priority there is
826166137Sjeff	 * nothing to do.
827166137Sjeff	 */
828166247Sjeff	if (pri > cpri)
829166137Sjeff		return;
830166137Sjeff	/*
831166247Sjeff	 * Always IPI idle.
832121790Sjeff	 */
833166247Sjeff	if (cpri > PRI_MIN_IDLE)
834166247Sjeff		goto sendipi;
835166247Sjeff	/*
836166247Sjeff	 * If we're realtime or better and there is timeshare or worse running
837166247Sjeff	 * send an IPI.
838166247Sjeff	 */
839166247Sjeff	if (pri < PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
840166247Sjeff		goto sendipi;
841166247Sjeff	/*
842166247Sjeff	 * Otherwise only IPI if we exceed the threshold.
843166247Sjeff	 */
844171482Sjeff	if (pri > preempt_thresh)
845165819Sjeff		return;
846166247Sjeffsendipi:
847166247Sjeff	ctd->td_flags |= TDF_NEEDRESCHED;
848171482Sjeff	ipi_selected(1 << cpu, IPI_PREEMPT);
849121790Sjeff}
850121790Sjeff
851171482Sjeff/*
852171482Sjeff * Steals load from a timeshare queue.  Honors the rotating queue head
853171482Sjeff * index.
854171482Sjeff */
855164936Sjulianstatic struct td_sched *
856171482Sjeffrunq_steal_from(struct runq *rq, u_char start)
857171482Sjeff{
858171482Sjeff	struct td_sched *ts;
859171482Sjeff	struct rqbits *rqb;
860171482Sjeff	struct rqhead *rqh;
861171482Sjeff	int first;
862171482Sjeff	int bit;
863171482Sjeff	int pri;
864171482Sjeff	int i;
865171482Sjeff
866171482Sjeff	rqb = &rq->rq_status;
867171482Sjeff	bit = start & (RQB_BPW -1);
868171482Sjeff	pri = 0;
869171482Sjeff	first = 0;
870171482Sjeffagain:
871171482Sjeff	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
872171482Sjeff		if (rqb->rqb_bits[i] == 0)
873171482Sjeff			continue;
874171482Sjeff		if (bit != 0) {
875171482Sjeff			for (pri = bit; pri < RQB_BPW; pri++)
876171482Sjeff				if (rqb->rqb_bits[i] & (1ul << pri))
877171482Sjeff					break;
878171482Sjeff			if (pri >= RQB_BPW)
879171482Sjeff				continue;
880171482Sjeff		} else
881171482Sjeff			pri = RQB_FFS(rqb->rqb_bits[i]);
882171482Sjeff		pri += (i << RQB_L2BPW);
883171482Sjeff		rqh = &rq->rq_queues[pri];
884171482Sjeff		TAILQ_FOREACH(ts, rqh, ts_procq) {
885171482Sjeff			if (first && THREAD_CAN_MIGRATE(ts->ts_thread))
886171482Sjeff				return (ts);
887171482Sjeff			first = 1;
888171482Sjeff		}
889171482Sjeff	}
890171482Sjeff	if (start != 0) {
891171482Sjeff		start = 0;
892171482Sjeff		goto again;
893171482Sjeff	}
894171482Sjeff
895171482Sjeff	return (NULL);
896171482Sjeff}
897171482Sjeff
898171482Sjeff/*
899171482Sjeff * Steals load from a standard linear queue.
900171482Sjeff */
901171482Sjeffstatic struct td_sched *
902121790Sjeffrunq_steal(struct runq *rq)
903121790Sjeff{
904121790Sjeff	struct rqhead *rqh;
905121790Sjeff	struct rqbits *rqb;
906164936Sjulian	struct td_sched *ts;
907121790Sjeff	int word;
908121790Sjeff	int bit;
909121790Sjeff
910121790Sjeff	rqb = &rq->rq_status;
911121790Sjeff	for (word = 0; word < RQB_LEN; word++) {
912121790Sjeff		if (rqb->rqb_bits[word] == 0)
913121790Sjeff			continue;
914121790Sjeff		for (bit = 0; bit < RQB_BPW; bit++) {
915123231Speter			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
916121790Sjeff				continue;
917121790Sjeff			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
918171506Sjeff			TAILQ_FOREACH(ts, rqh, ts_procq)
919171506Sjeff				if (THREAD_CAN_MIGRATE(ts->ts_thread))
920164936Sjulian					return (ts);
921121790Sjeff		}
922121790Sjeff	}
923121790Sjeff	return (NULL);
924121790Sjeff}
925121790Sjeff
926171482Sjeff/*
927171482Sjeff * Attempt to steal a thread in priority order from a thread queue.
928171482Sjeff */
929164936Sjulianstatic struct td_sched *
930172409Sjefftdq_steal(struct tdq *tdq)
931121790Sjeff{
932164936Sjulian	struct td_sched *ts;
933121790Sjeff
934171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
935165762Sjeff	if ((ts = runq_steal(&tdq->tdq_realtime)) != NULL)
936164936Sjulian		return (ts);
937171482Sjeff	if ((ts = runq_steal_from(&tdq->tdq_timeshare, tdq->tdq_ridx)) != NULL)
938164936Sjulian		return (ts);
939172409Sjeff	return (runq_steal(&tdq->tdq_idle));
940121790Sjeff}
941123433Sjeff
942171482Sjeff/*
943171482Sjeff * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
944172409Sjeff * current lock and returns with the assigned queue locked.
945171482Sjeff */
946171482Sjeffstatic inline struct tdq *
947171482Sjeffsched_setcpu(struct td_sched *ts, int cpu, int flags)
948123433Sjeff{
949171482Sjeff	struct thread *td;
950171482Sjeff	struct tdq *tdq;
951123433Sjeff
952171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
953171482Sjeff
954171482Sjeff	tdq = TDQ_CPU(cpu);
955171482Sjeff	td = ts->ts_thread;
956171482Sjeff	ts->ts_cpu = cpu;
957171713Sjeff
958171713Sjeff	/* If the lock matches just return the queue. */
959171482Sjeff	if (td->td_lock == TDQ_LOCKPTR(tdq))
960171482Sjeff		return (tdq);
961171482Sjeff#ifdef notyet
962123433Sjeff	/*
963172293Sjeff	 * If the thread isn't running its lockptr is a
964171482Sjeff	 * turnstile or a sleepqueue.  We can just lock_set without
965171482Sjeff	 * blocking.
966123685Sjeff	 */
967171482Sjeff	if (TD_CAN_RUN(td)) {
968171482Sjeff		TDQ_LOCK(tdq);
969171482Sjeff		thread_lock_set(td, TDQ_LOCKPTR(tdq));
970171482Sjeff		return (tdq);
971171482Sjeff	}
972171482Sjeff#endif
973166108Sjeff	/*
974171482Sjeff	 * The hard case, migration, we need to block the thread first to
975171482Sjeff	 * prevent order reversals with other cpus locks.
976166108Sjeff	 */
977171482Sjeff	thread_lock_block(td);
978171482Sjeff	TDQ_LOCK(tdq);
979171713Sjeff	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
980171482Sjeff	return (tdq);
981166108Sjeff}
982166108Sjeff
983171482Sjeff/*
984171482Sjeff * Find the thread queue running the lowest priority thread.
985171482Sjeff */
986166108Sjeffstatic int
987171482Sjefftdq_lowestpri(void)
988166108Sjeff{
989171482Sjeff	struct tdq *tdq;
990166108Sjeff	int lowpri;
991166108Sjeff	int lowcpu;
992166108Sjeff	int lowload;
993166108Sjeff	int load;
994171482Sjeff	int cpu;
995171482Sjeff	int pri;
996171482Sjeff
997171482Sjeff	lowload = 0;
998171482Sjeff	lowpri = lowcpu = 0;
999171482Sjeff	for (cpu = 0; cpu <= mp_maxid; cpu++) {
1000171482Sjeff		if (CPU_ABSENT(cpu))
1001171482Sjeff			continue;
1002171482Sjeff		tdq = TDQ_CPU(cpu);
1003171482Sjeff		pri = tdq->tdq_lowpri;
1004171482Sjeff		load = TDQ_CPU(cpu)->tdq_load;
1005171482Sjeff		CTR4(KTR_ULE,
1006171482Sjeff		    "cpu %d pri %d lowcpu %d lowpri %d",
1007171482Sjeff		    cpu, pri, lowcpu, lowpri);
1008171482Sjeff		if (pri < lowpri)
1009171482Sjeff			continue;
1010171482Sjeff		if (lowpri && lowpri == pri && load > lowload)
1011171482Sjeff			continue;
1012171482Sjeff		lowpri = pri;
1013171482Sjeff		lowcpu = cpu;
1014171482Sjeff		lowload = load;
1015171482Sjeff	}
1016171482Sjeff
1017171482Sjeff	return (lowcpu);
1018171482Sjeff}
1019171482Sjeff
1020171482Sjeff/*
1021171482Sjeff * Find the thread queue with the least load.
1022171482Sjeff */
1023171482Sjeffstatic int
1024171482Sjefftdq_lowestload(void)
1025171482Sjeff{
1026171482Sjeff	struct tdq *tdq;
1027171482Sjeff	int lowload;
1028171482Sjeff	int lowpri;
1029171482Sjeff	int lowcpu;
1030171482Sjeff	int load;
1031171482Sjeff	int cpu;
1032171482Sjeff	int pri;
1033171482Sjeff
1034171482Sjeff	lowcpu = 0;
1035171482Sjeff	lowload = TDQ_CPU(0)->tdq_load;
1036171482Sjeff	lowpri = TDQ_CPU(0)->tdq_lowpri;
1037171482Sjeff	for (cpu = 1; cpu <= mp_maxid; cpu++) {
1038171482Sjeff		if (CPU_ABSENT(cpu))
1039171482Sjeff			continue;
1040171482Sjeff		tdq = TDQ_CPU(cpu);
1041171482Sjeff		load = tdq->tdq_load;
1042171482Sjeff		pri = tdq->tdq_lowpri;
1043171482Sjeff		CTR4(KTR_ULE, "cpu %d load %d lowcpu %d lowload %d",
1044171482Sjeff		    cpu, load, lowcpu, lowload);
1045171482Sjeff		if (load > lowload)
1046171482Sjeff			continue;
1047171482Sjeff		if (load == lowload && pri < lowpri)
1048171482Sjeff			continue;
1049171482Sjeff		lowcpu = cpu;
1050171482Sjeff		lowload = load;
1051171482Sjeff		lowpri = pri;
1052171482Sjeff	}
1053171482Sjeff
1054171482Sjeff	return (lowcpu);
1055171482Sjeff}
1056171482Sjeff
1057171482Sjeff/*
1058171482Sjeff * Pick the destination cpu for sched_add().  Respects affinity and makes
1059171482Sjeff * a determination based on load or priority of available processors.
1060171482Sjeff */
1061171482Sjeffstatic int
1062171482Sjeffsched_pickcpu(struct td_sched *ts, int flags)
1063171482Sjeff{
1064171482Sjeff	struct tdq *tdq;
1065166108Sjeff	int self;
1066166108Sjeff	int pri;
1067166108Sjeff	int cpu;
1068166108Sjeff
1069171482Sjeff	cpu = self = PCPU_GET(cpuid);
1070166108Sjeff	if (smp_started == 0)
1071166108Sjeff		return (self);
1072171506Sjeff	/*
1073171506Sjeff	 * Don't migrate a running thread from sched_switch().
1074171506Sjeff	 */
1075171506Sjeff	if (flags & SRQ_OURSELF) {
1076171506Sjeff		CTR1(KTR_ULE, "YIELDING %d",
1077171506Sjeff		    curthread->td_priority);
1078171506Sjeff		return (self);
1079171506Sjeff	}
1080166108Sjeff	pri = ts->ts_thread->td_priority;
1081171482Sjeff	cpu = ts->ts_cpu;
1082166108Sjeff	/*
1083166108Sjeff	 * Regardless of affinity, if the last cpu is idle send it there.
1084166108Sjeff	 */
1085171482Sjeff	tdq = TDQ_CPU(cpu);
1086171482Sjeff	if (tdq->tdq_lowpri > PRI_MIN_IDLE) {
1087166229Sjeff		CTR5(KTR_ULE,
1088166108Sjeff		    "ts_cpu %d idle, ltick %d ticks %d pri %d curthread %d",
1089166108Sjeff		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1090171482Sjeff		    tdq->tdq_lowpri);
1091166108Sjeff		return (ts->ts_cpu);
1092123433Sjeff	}
1093166108Sjeff	/*
1094166108Sjeff	 * If we have affinity, try to place it on the cpu we last ran on.
1095166108Sjeff	 */
1096171482Sjeff	if (SCHED_AFFINITY(ts) && tdq->tdq_lowpri > pri) {
1097166229Sjeff		CTR5(KTR_ULE,
1098166108Sjeff		    "affinity for %d, ltick %d ticks %d pri %d curthread %d",
1099166108Sjeff		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1100171482Sjeff		    tdq->tdq_lowpri);
1101166108Sjeff		return (ts->ts_cpu);
1102139334Sjeff	}
1103123433Sjeff	/*
1104166108Sjeff	 * Look for an idle group.
1105123433Sjeff	 */
1106166229Sjeff	CTR1(KTR_ULE, "tdq_idle %X", tdq_idle);
1107166108Sjeff	cpu = ffs(tdq_idle);
1108166108Sjeff	if (cpu)
1109171482Sjeff		return (--cpu);
1110171506Sjeff	/*
1111172409Sjeff	 * If there are no idle cores see if we can run the thread locally.
1112172409Sjeff	 * This may improve locality among sleepers and wakers when there
1113172409Sjeff	 * is shared data.
1114171506Sjeff	 */
1115175348Sjeff	if (tryself && pri < TDQ_CPU(self)->tdq_lowpri) {
1116171506Sjeff		CTR1(KTR_ULE, "tryself %d",
1117166108Sjeff		    curthread->td_priority);
1118166108Sjeff		return (self);
1119123433Sjeff	}
1120133427Sjeff	/*
1121166108Sjeff 	 * Now search for the cpu running the lowest priority thread with
1122166108Sjeff	 * the least load.
1123123433Sjeff	 */
1124171482Sjeff	if (pick_pri)
1125171482Sjeff		cpu = tdq_lowestpri();
1126171482Sjeff	else
1127171482Sjeff		cpu = tdq_lowestload();
1128171482Sjeff	return (cpu);
1129123433Sjeff}
1130123433Sjeff
1131121790Sjeff#endif	/* SMP */
1132121790Sjeff
1133117326Sjeff/*
1134121790Sjeff * Pick the highest priority task we have and return it.
1135117326Sjeff */
1136164936Sjulianstatic struct td_sched *
1137164936Sjuliantdq_choose(struct tdq *tdq)
1138110267Sjeff{
1139164936Sjulian	struct td_sched *ts;
1140110267Sjeff
1141171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1142165762Sjeff	ts = runq_choose(&tdq->tdq_realtime);
1143170787Sjeff	if (ts != NULL)
1144164936Sjulian		return (ts);
1145165766Sjeff	ts = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1146165762Sjeff	if (ts != NULL) {
1147170787Sjeff		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_TIMESHARE,
1148165762Sjeff		    ("tdq_choose: Invalid priority on timeshare queue %d",
1149165762Sjeff		    ts->ts_thread->td_priority));
1150165762Sjeff		return (ts);
1151165762Sjeff	}
1152110267Sjeff
1153165762Sjeff	ts = runq_choose(&tdq->tdq_idle);
1154165762Sjeff	if (ts != NULL) {
1155165762Sjeff		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_IDLE,
1156165762Sjeff		    ("tdq_choose: Invalid priority on idle queue %d",
1157165762Sjeff		    ts->ts_thread->td_priority));
1158165762Sjeff		return (ts);
1159165762Sjeff	}
1160165762Sjeff
1161165762Sjeff	return (NULL);
1162110267Sjeff}
1163110267Sjeff
1164171482Sjeff/*
1165171482Sjeff * Initialize a thread queue.
1166171482Sjeff */
1167109864Sjeffstatic void
1168164936Sjuliantdq_setup(struct tdq *tdq)
1169110028Sjeff{
1170171482Sjeff
1171171713Sjeff	if (bootverbose)
1172171713Sjeff		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1173165762Sjeff	runq_init(&tdq->tdq_realtime);
1174165762Sjeff	runq_init(&tdq->tdq_timeshare);
1175165620Sjeff	runq_init(&tdq->tdq_idle);
1176165620Sjeff	tdq->tdq_load = 0;
1177110028Sjeff}
1178110028Sjeff
1179171713Sjeff#ifdef SMP
1180110028Sjeffstatic void
1181171713Sjefftdg_setup(struct tdq_group *tdg)
1182109864Sjeff{
1183171713Sjeff	if (bootverbose)
1184171713Sjeff		printf("ULE: setup cpu group %d\n", TDG_ID(tdg));
1185171713Sjeff	snprintf(tdg->tdg_name, sizeof(tdg->tdg_name),
1186171713Sjeff	    "sched lock %d", (int)TDG_ID(tdg));
1187171713Sjeff	mtx_init(&tdg->tdg_lock, tdg->tdg_name, "sched lock",
1188171713Sjeff	    MTX_SPIN | MTX_RECURSE);
1189171713Sjeff	LIST_INIT(&tdg->tdg_members);
1190171713Sjeff	tdg->tdg_load = 0;
1191171713Sjeff	tdg->tdg_transferable = 0;
1192171713Sjeff	tdg->tdg_cpus = 0;
1193171713Sjeff	tdg->tdg_mask = 0;
1194171713Sjeff	tdg->tdg_cpumask = 0;
1195171713Sjeff	tdg->tdg_idlemask = 0;
1196171713Sjeff}
1197171713Sjeff
1198171713Sjeffstatic void
1199171713Sjefftdg_add(struct tdq_group *tdg, struct tdq *tdq)
1200171713Sjeff{
1201171713Sjeff	if (tdg->tdg_mask == 0)
1202171713Sjeff		tdg->tdg_mask |= 1 << TDQ_ID(tdq);
1203171713Sjeff	tdg->tdg_cpumask |= 1 << TDQ_ID(tdq);
1204171713Sjeff	tdg->tdg_cpus++;
1205171713Sjeff	tdq->tdq_group = tdg;
1206171713Sjeff	tdq->tdq_lock = &tdg->tdg_lock;
1207171713Sjeff	LIST_INSERT_HEAD(&tdg->tdg_members, tdq, tdq_siblings);
1208171713Sjeff	if (bootverbose)
1209171713Sjeff		printf("ULE: adding cpu %d to group %d: cpus %d mask 0x%X\n",
1210171713Sjeff		    TDQ_ID(tdq), TDG_ID(tdg), tdg->tdg_cpus, tdg->tdg_cpumask);
1211171713Sjeff}
1212171713Sjeff
1213171713Sjeffstatic void
1214171713Sjeffsched_setup_smp(void)
1215171713Sjeff{
1216171713Sjeff	struct tdq_group *tdg;
1217171713Sjeff	struct tdq *tdq;
1218171713Sjeff	int cpus;
1219171713Sjeff	int i;
1220171713Sjeff
1221171713Sjeff	for (cpus = 0, i = 0; i < MAXCPU; i++) {
1222171713Sjeff		if (CPU_ABSENT(i))
1223171713Sjeff			continue;
1224165627Sjeff		tdq = &tdq_cpu[i];
1225171713Sjeff		tdg = &tdq_groups[i];
1226171713Sjeff		/*
1227171713Sjeff		 * Setup a tdq group with one member.
1228171713Sjeff		 */
1229171713Sjeff		tdg_setup(tdg);
1230171713Sjeff		tdq_setup(tdq);
1231171713Sjeff		tdg_add(tdg, tdq);
1232171713Sjeff		cpus++;
1233123433Sjeff	}
1234171713Sjeff	tdg_maxid = cpus - 1;
1235171713Sjeff}
1236171713Sjeff#endif
1237171713Sjeff
1238171713Sjeff/*
1239171713Sjeff * Setup the thread queues and initialize the topology based on MD
1240171713Sjeff * information.
1241171713Sjeff */
1242171713Sjeffstatic void
1243171713Sjeffsched_setup(void *dummy)
1244171713Sjeff{
1245171713Sjeff	struct tdq *tdq;
1246171713Sjeff
1247171713Sjeff	tdq = TDQ_SELF();
1248171713Sjeff#ifdef SMP
1249171713Sjeff	/*
1250171713Sjeff	 * Setup tdqs based on a topology configuration or vanilla SMP based
1251171713Sjeff	 * on mp_maxid.
1252171713Sjeff	 */
1253176734Sjeff	sched_setup_smp();
1254172409Sjeff	balance_tdq = tdq;
1255172409Sjeff	sched_balance();
1256117237Sjeff#else
1257171713Sjeff	tdq_setup(tdq);
1258171713Sjeff	mtx_init(&tdq_lock, "sched lock", "sched lock", MTX_SPIN | MTX_RECURSE);
1259171713Sjeff	tdq->tdq_lock = &tdq_lock;
1260116069Sjeff#endif
1261171482Sjeff	/*
1262171482Sjeff	 * To avoid divide-by-zero, we set realstathz a dummy value
1263171482Sjeff	 * in case which sched_clock() called before sched_initticks().
1264171482Sjeff	 */
1265171482Sjeff	realstathz = hz;
1266171482Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1267171482Sjeff	tickincr = 1 << SCHED_TICK_SHIFT;
1268171482Sjeff
1269171482Sjeff	/* Add thread0's load since it's running. */
1270171482Sjeff	TDQ_LOCK(tdq);
1271171713Sjeff	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1272171482Sjeff	tdq_load_add(tdq, &td_sched0);
1273171482Sjeff	TDQ_UNLOCK(tdq);
1274109864Sjeff}
1275109864Sjeff
1276171482Sjeff/*
1277171482Sjeff * This routine determines the tickincr after stathz and hz are setup.
1278171482Sjeff */
1279153533Sdavidxu/* ARGSUSED */
1280153533Sdavidxustatic void
1281153533Sdavidxusched_initticks(void *dummy)
1282153533Sdavidxu{
1283171482Sjeff	int incr;
1284171482Sjeff
1285153533Sdavidxu	realstathz = stathz ? stathz : hz;
1286166229Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1287153533Sdavidxu
1288153533Sdavidxu	/*
1289165762Sjeff	 * tickincr is shifted out by 10 to avoid rounding errors due to
1290165766Sjeff	 * hz not being evenly divisible by stathz on all platforms.
1291153533Sdavidxu	 */
1292171482Sjeff	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1293165762Sjeff	/*
1294165762Sjeff	 * This does not work for values of stathz that are more than
1295165762Sjeff	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1296165762Sjeff	 */
1297171482Sjeff	if (incr == 0)
1298171482Sjeff		incr = 1;
1299171482Sjeff	tickincr = incr;
1300166108Sjeff#ifdef SMP
1301171899Sjeff	/*
1302172409Sjeff	 * Set the default balance interval now that we know
1303172409Sjeff	 * what realstathz is.
1304172409Sjeff	 */
1305172409Sjeff	balance_interval = realstathz;
1306172409Sjeff	/*
1307171899Sjeff	 * Set steal thresh to log2(mp_ncpu) but no greater than 4.  This
1308171899Sjeff	 * prevents excess thrashing on large machines and excess idle on
1309171899Sjeff	 * smaller machines.
1310171899Sjeff	 */
1311171899Sjeff	steal_thresh = min(ffs(mp_ncpus) - 1, 4);
1312166108Sjeff	affinity = SCHED_AFFINITY_DEFAULT;
1313166108Sjeff#endif
1314153533Sdavidxu}
1315153533Sdavidxu
1316153533Sdavidxu
1317109864Sjeff/*
1318171482Sjeff * This is the core of the interactivity algorithm.  Determines a score based
1319171482Sjeff * on past behavior.  It is the ratio of sleep time to run time scaled to
1320171482Sjeff * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1321171482Sjeff * differs from the cpu usage because it does not account for time spent
1322171482Sjeff * waiting on a run-queue.  Would be prettier if we had floating point.
1323171482Sjeff */
1324171482Sjeffstatic int
1325171482Sjeffsched_interact_score(struct thread *td)
1326171482Sjeff{
1327171482Sjeff	struct td_sched *ts;
1328171482Sjeff	int div;
1329171482Sjeff
1330171482Sjeff	ts = td->td_sched;
1331171482Sjeff	/*
1332171482Sjeff	 * The score is only needed if this is likely to be an interactive
1333171482Sjeff	 * task.  Don't go through the expense of computing it if there's
1334171482Sjeff	 * no chance.
1335171482Sjeff	 */
1336171482Sjeff	if (sched_interact <= SCHED_INTERACT_HALF &&
1337171482Sjeff		ts->ts_runtime >= ts->ts_slptime)
1338171482Sjeff			return (SCHED_INTERACT_HALF);
1339171482Sjeff
1340171482Sjeff	if (ts->ts_runtime > ts->ts_slptime) {
1341171482Sjeff		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1342171482Sjeff		return (SCHED_INTERACT_HALF +
1343171482Sjeff		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1344171482Sjeff	}
1345171482Sjeff	if (ts->ts_slptime > ts->ts_runtime) {
1346171482Sjeff		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1347171482Sjeff		return (ts->ts_runtime / div);
1348171482Sjeff	}
1349171482Sjeff	/* runtime == slptime */
1350171482Sjeff	if (ts->ts_runtime)
1351171482Sjeff		return (SCHED_INTERACT_HALF);
1352171482Sjeff
1353171482Sjeff	/*
1354171482Sjeff	 * This can happen if slptime and runtime are 0.
1355171482Sjeff	 */
1356171482Sjeff	return (0);
1357171482Sjeff
1358171482Sjeff}
1359171482Sjeff
1360171482Sjeff/*
1361109864Sjeff * Scale the scheduling priority according to the "interactivity" of this
1362109864Sjeff * process.
1363109864Sjeff */
1364113357Sjeffstatic void
1365163709Sjbsched_priority(struct thread *td)
1366109864Sjeff{
1367165762Sjeff	int score;
1368109864Sjeff	int pri;
1369109864Sjeff
1370163709Sjb	if (td->td_pri_class != PRI_TIMESHARE)
1371113357Sjeff		return;
1372112966Sjeff	/*
1373165762Sjeff	 * If the score is interactive we place the thread in the realtime
1374165762Sjeff	 * queue with a priority that is less than kernel and interrupt
1375165762Sjeff	 * priorities.  These threads are not subject to nice restrictions.
1376112966Sjeff	 *
1377171482Sjeff	 * Scores greater than this are placed on the normal timeshare queue
1378165762Sjeff	 * where the priority is partially decided by the most recent cpu
1379165762Sjeff	 * utilization and the rest is decided by nice value.
1380172293Sjeff	 *
1381172293Sjeff	 * The nice value of the process has a linear effect on the calculated
1382172293Sjeff	 * score.  Negative nice values make it easier for a thread to be
1383172293Sjeff	 * considered interactive.
1384112966Sjeff	 */
1385172308Sjeff	score = imax(0, sched_interact_score(td) - td->td_proc->p_nice);
1386165762Sjeff	if (score < sched_interact) {
1387165762Sjeff		pri = PRI_MIN_REALTIME;
1388165762Sjeff		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1389165762Sjeff		    * score;
1390165762Sjeff		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1391166208Sjeff		    ("sched_priority: invalid interactive priority %d score %d",
1392166208Sjeff		    pri, score));
1393165762Sjeff	} else {
1394165762Sjeff		pri = SCHED_PRI_MIN;
1395165762Sjeff		if (td->td_sched->ts_ticks)
1396165762Sjeff			pri += SCHED_PRI_TICKS(td->td_sched);
1397165762Sjeff		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1398171482Sjeff		KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1399171482Sjeff		    ("sched_priority: invalid priority %d: nice %d, "
1400171482Sjeff		    "ticks %d ftick %d ltick %d tick pri %d",
1401171482Sjeff		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1402171482Sjeff		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1403171482Sjeff		    SCHED_PRI_TICKS(td->td_sched)));
1404165762Sjeff	}
1405165762Sjeff	sched_user_prio(td, pri);
1406112966Sjeff
1407112966Sjeff	return;
1408109864Sjeff}
1409109864Sjeff
1410121868Sjeff/*
1411121868Sjeff * This routine enforces a maximum limit on the amount of scheduling history
1412171482Sjeff * kept.  It is called after either the slptime or runtime is adjusted.  This
1413171482Sjeff * function is ugly due to integer math.
1414121868Sjeff */
1415116463Sjeffstatic void
1416163709Sjbsched_interact_update(struct thread *td)
1417116463Sjeff{
1418165819Sjeff	struct td_sched *ts;
1419166208Sjeff	u_int sum;
1420121605Sjeff
1421165819Sjeff	ts = td->td_sched;
1422171482Sjeff	sum = ts->ts_runtime + ts->ts_slptime;
1423121868Sjeff	if (sum < SCHED_SLP_RUN_MAX)
1424121868Sjeff		return;
1425121868Sjeff	/*
1426165819Sjeff	 * This only happens from two places:
1427165819Sjeff	 * 1) We have added an unusual amount of run time from fork_exit.
1428165819Sjeff	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1429165819Sjeff	 */
1430165819Sjeff	if (sum > SCHED_SLP_RUN_MAX * 2) {
1431171482Sjeff		if (ts->ts_runtime > ts->ts_slptime) {
1432171482Sjeff			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1433171482Sjeff			ts->ts_slptime = 1;
1434165819Sjeff		} else {
1435171482Sjeff			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1436171482Sjeff			ts->ts_runtime = 1;
1437165819Sjeff		}
1438165819Sjeff		return;
1439165819Sjeff	}
1440165819Sjeff	/*
1441121868Sjeff	 * If we have exceeded by more than 1/5th then the algorithm below
1442121868Sjeff	 * will not bring us back into range.  Dividing by two here forces
1443133427Sjeff	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1444121868Sjeff	 */
1445127850Sjeff	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1446171482Sjeff		ts->ts_runtime /= 2;
1447171482Sjeff		ts->ts_slptime /= 2;
1448121868Sjeff		return;
1449116463Sjeff	}
1450171482Sjeff	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1451171482Sjeff	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1452116463Sjeff}
1453116463Sjeff
1454171482Sjeff/*
1455171482Sjeff * Scale back the interactivity history when a child thread is created.  The
1456171482Sjeff * history is inherited from the parent but the thread may behave totally
1457171482Sjeff * differently.  For example, a shell spawning a compiler process.  We want
1458171482Sjeff * to learn that the compiler is behaving badly very quickly.
1459171482Sjeff */
1460121868Sjeffstatic void
1461163709Sjbsched_interact_fork(struct thread *td)
1462121868Sjeff{
1463121868Sjeff	int ratio;
1464121868Sjeff	int sum;
1465121868Sjeff
1466171482Sjeff	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1467121868Sjeff	if (sum > SCHED_SLP_RUN_FORK) {
1468121868Sjeff		ratio = sum / SCHED_SLP_RUN_FORK;
1469171482Sjeff		td->td_sched->ts_runtime /= ratio;
1470171482Sjeff		td->td_sched->ts_slptime /= ratio;
1471121868Sjeff	}
1472121868Sjeff}
1473121868Sjeff
1474113357Sjeff/*
1475171482Sjeff * Called from proc0_init() to setup the scheduler fields.
1476134791Sjulian */
1477134791Sjulianvoid
1478134791Sjulianschedinit(void)
1479134791Sjulian{
1480165762Sjeff
1481134791Sjulian	/*
1482134791Sjulian	 * Set up the scheduler specific parts of proc0.
1483134791Sjulian	 */
1484136167Sjulian	proc0.p_sched = NULL; /* XXX */
1485164936Sjulian	thread0.td_sched = &td_sched0;
1486165762Sjeff	td_sched0.ts_ltick = ticks;
1487165796Sjeff	td_sched0.ts_ftick = ticks;
1488164936Sjulian	td_sched0.ts_thread = &thread0;
1489134791Sjulian}
1490134791Sjulian
1491134791Sjulian/*
1492113357Sjeff * This is only somewhat accurate since given many processes of the same
1493113357Sjeff * priority they will switch when their slices run out, which will be
1494165762Sjeff * at most sched_slice stathz ticks.
1495113357Sjeff */
1496109864Sjeffint
1497109864Sjeffsched_rr_interval(void)
1498109864Sjeff{
1499165762Sjeff
1500165762Sjeff	/* Convert sched_slice to hz */
1501165762Sjeff	return (hz/(realstathz/sched_slice));
1502109864Sjeff}
1503109864Sjeff
1504171482Sjeff/*
1505171482Sjeff * Update the percent cpu tracking information when it is requested or
1506171482Sjeff * the total history exceeds the maximum.  We keep a sliding history of
1507171482Sjeff * tick counts that slowly decays.  This is less precise than the 4BSD
1508171482Sjeff * mechanism since it happens with less regular and frequent events.
1509171482Sjeff */
1510121790Sjeffstatic void
1511164936Sjuliansched_pctcpu_update(struct td_sched *ts)
1512109864Sjeff{
1513165762Sjeff
1514165762Sjeff	if (ts->ts_ticks == 0)
1515165762Sjeff		return;
1516165796Sjeff	if (ticks - (hz / 10) < ts->ts_ltick &&
1517165796Sjeff	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1518165796Sjeff		return;
1519109864Sjeff	/*
1520109864Sjeff	 * Adjust counters and watermark for pctcpu calc.
1521116365Sjeff	 */
1522165762Sjeff	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1523164936Sjulian		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1524165762Sjeff			    SCHED_TICK_TARG;
1525165762Sjeff	else
1526164936Sjulian		ts->ts_ticks = 0;
1527164936Sjulian	ts->ts_ltick = ticks;
1528165762Sjeff	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1529109864Sjeff}
1530109864Sjeff
1531171482Sjeff/*
1532171482Sjeff * Adjust the priority of a thread.  Move it to the appropriate run-queue
1533171482Sjeff * if necessary.  This is the back-end for several priority related
1534171482Sjeff * functions.
1535171482Sjeff */
1536165762Sjeffstatic void
1537139453Sjhbsched_thread_priority(struct thread *td, u_char prio)
1538109864Sjeff{
1539164936Sjulian	struct td_sched *ts;
1540109864Sjeff
1541139316Sjeff	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
1542173600Sjulian	    td, td->td_name, td->td_priority, prio, curthread,
1543173600Sjulian	    curthread->td_name);
1544164936Sjulian	ts = td->td_sched;
1545170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1546139453Sjhb	if (td->td_priority == prio)
1547139453Sjhb		return;
1548165762Sjeff
1549165766Sjeff	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1550121605Sjeff		/*
1551121605Sjeff		 * If the priority has been elevated due to priority
1552121605Sjeff		 * propagation, we may have to move ourselves to a new
1553165762Sjeff		 * queue.  This could be optimized to not re-add in some
1554165762Sjeff		 * cases.
1555133555Sjeff		 */
1556165762Sjeff		sched_rem(td);
1557165762Sjeff		td->td_priority = prio;
1558171482Sjeff		sched_add(td, SRQ_BORROWING);
1559171482Sjeff#ifdef SMP
1560175587Sjeff	} else if (TD_IS_RUNNING(td)) {
1561171482Sjeff		struct tdq *tdq;
1562171482Sjeff
1563171482Sjeff		tdq = TDQ_CPU(ts->ts_cpu);
1564175587Sjeff		if (prio < tdq->tdq_lowpri ||
1565175587Sjeff		   (td->td_priority == tdq->tdq_lowpri && tdq->tdq_load <= 1))
1566171482Sjeff			tdq->tdq_lowpri = prio;
1567175587Sjeff		td->td_priority = prio;
1568171482Sjeff#endif
1569175587Sjeff	} else
1570119488Sdavidxu		td->td_priority = prio;
1571109864Sjeff}
1572109864Sjeff
1573139453Sjhb/*
1574139453Sjhb * Update a thread's priority when it is lent another thread's
1575139453Sjhb * priority.
1576139453Sjhb */
1577109864Sjeffvoid
1578139453Sjhbsched_lend_prio(struct thread *td, u_char prio)
1579139453Sjhb{
1580139453Sjhb
1581139453Sjhb	td->td_flags |= TDF_BORROWING;
1582139453Sjhb	sched_thread_priority(td, prio);
1583139453Sjhb}
1584139453Sjhb
1585139453Sjhb/*
1586139453Sjhb * Restore a thread's priority when priority propagation is
1587139453Sjhb * over.  The prio argument is the minimum priority the thread
1588139453Sjhb * needs to have to satisfy other possible priority lending
1589139453Sjhb * requests.  If the thread's regular priority is less
1590139453Sjhb * important than prio, the thread will keep a priority boost
1591139453Sjhb * of prio.
1592139453Sjhb */
1593139453Sjhbvoid
1594139453Sjhbsched_unlend_prio(struct thread *td, u_char prio)
1595139453Sjhb{
1596139453Sjhb	u_char base_pri;
1597139453Sjhb
1598139453Sjhb	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1599139453Sjhb	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1600163709Sjb		base_pri = td->td_user_pri;
1601139453Sjhb	else
1602139453Sjhb		base_pri = td->td_base_pri;
1603139453Sjhb	if (prio >= base_pri) {
1604139455Sjhb		td->td_flags &= ~TDF_BORROWING;
1605139453Sjhb		sched_thread_priority(td, base_pri);
1606139453Sjhb	} else
1607139453Sjhb		sched_lend_prio(td, prio);
1608139453Sjhb}
1609139453Sjhb
1610171482Sjeff/*
1611171482Sjeff * Standard entry for setting the priority to an absolute value.
1612171482Sjeff */
1613139453Sjhbvoid
1614139453Sjhbsched_prio(struct thread *td, u_char prio)
1615139453Sjhb{
1616139453Sjhb	u_char oldprio;
1617139453Sjhb
1618139453Sjhb	/* First, update the base priority. */
1619139453Sjhb	td->td_base_pri = prio;
1620139453Sjhb
1621139453Sjhb	/*
1622139455Sjhb	 * If the thread is borrowing another thread's priority, don't
1623139453Sjhb	 * ever lower the priority.
1624139453Sjhb	 */
1625139453Sjhb	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1626139453Sjhb		return;
1627139453Sjhb
1628139453Sjhb	/* Change the real priority. */
1629139453Sjhb	oldprio = td->td_priority;
1630139453Sjhb	sched_thread_priority(td, prio);
1631139453Sjhb
1632139453Sjhb	/*
1633139453Sjhb	 * If the thread is on a turnstile, then let the turnstile update
1634139453Sjhb	 * its state.
1635139453Sjhb	 */
1636139453Sjhb	if (TD_ON_LOCK(td) && oldprio != prio)
1637139453Sjhb		turnstile_adjust(td, oldprio);
1638139453Sjhb}
1639139455Sjhb
1640171482Sjeff/*
1641171482Sjeff * Set the base user priority, does not effect current running priority.
1642171482Sjeff */
1643139453Sjhbvoid
1644163709Sjbsched_user_prio(struct thread *td, u_char prio)
1645161599Sdavidxu{
1646161599Sdavidxu	u_char oldprio;
1647161599Sdavidxu
1648163709Sjb	td->td_base_user_pri = prio;
1649164939Sjulian	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1650164939Sjulian                return;
1651163709Sjb	oldprio = td->td_user_pri;
1652163709Sjb	td->td_user_pri = prio;
1653161599Sdavidxu}
1654161599Sdavidxu
1655161599Sdavidxuvoid
1656161599Sdavidxusched_lend_user_prio(struct thread *td, u_char prio)
1657161599Sdavidxu{
1658161599Sdavidxu	u_char oldprio;
1659161599Sdavidxu
1660174536Sdavidxu	THREAD_LOCK_ASSERT(td, MA_OWNED);
1661161599Sdavidxu	td->td_flags |= TDF_UBORROWING;
1662164091Smaxim	oldprio = td->td_user_pri;
1663163709Sjb	td->td_user_pri = prio;
1664161599Sdavidxu}
1665161599Sdavidxu
1666161599Sdavidxuvoid
1667161599Sdavidxusched_unlend_user_prio(struct thread *td, u_char prio)
1668161599Sdavidxu{
1669161599Sdavidxu	u_char base_pri;
1670161599Sdavidxu
1671174536Sdavidxu	THREAD_LOCK_ASSERT(td, MA_OWNED);
1672163709Sjb	base_pri = td->td_base_user_pri;
1673161599Sdavidxu	if (prio >= base_pri) {
1674161599Sdavidxu		td->td_flags &= ~TDF_UBORROWING;
1675163709Sjb		sched_user_prio(td, base_pri);
1676174536Sdavidxu	} else {
1677161599Sdavidxu		sched_lend_user_prio(td, prio);
1678174536Sdavidxu	}
1679161599Sdavidxu}
1680161599Sdavidxu
1681171482Sjeff/*
1682171505Sjeff * Add the thread passed as 'newtd' to the run queue before selecting
1683171505Sjeff * the next thread to run.  This is only used for KSE.
1684171505Sjeff */
1685171505Sjeffstatic void
1686171505Sjeffsched_switchin(struct tdq *tdq, struct thread *td)
1687171505Sjeff{
1688171505Sjeff#ifdef SMP
1689171505Sjeff	spinlock_enter();
1690171505Sjeff	TDQ_UNLOCK(tdq);
1691171505Sjeff	thread_lock(td);
1692171505Sjeff	spinlock_exit();
1693171505Sjeff	sched_setcpu(td->td_sched, TDQ_ID(tdq), SRQ_YIELDING);
1694171505Sjeff#else
1695171505Sjeff	td->td_lock = TDQ_LOCKPTR(tdq);
1696171505Sjeff#endif
1697171505Sjeff	tdq_add(tdq, td, SRQ_YIELDING);
1698171505Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1699171505Sjeff}
1700171505Sjeff
1701171505Sjeff/*
1702174847Swkoszek * Block a thread for switching.  Similar to thread_block() but does not
1703174847Swkoszek * bump the spin count.
1704174847Swkoszek */
1705174847Swkoszekstatic inline struct mtx *
1706174847Swkoszekthread_block_switch(struct thread *td)
1707174847Swkoszek{
1708174847Swkoszek	struct mtx *lock;
1709174847Swkoszek
1710174847Swkoszek	THREAD_LOCK_ASSERT(td, MA_OWNED);
1711174847Swkoszek	lock = td->td_lock;
1712174847Swkoszek	td->td_lock = &blocked_lock;
1713174847Swkoszek	mtx_unlock_spin(lock);
1714174847Swkoszek
1715174847Swkoszek	return (lock);
1716174847Swkoszek}
1717174847Swkoszek
1718174847Swkoszek/*
1719171713Sjeff * Handle migration from sched_switch().  This happens only for
1720171713Sjeff * cpu binding.
1721171713Sjeff */
1722171713Sjeffstatic struct mtx *
1723171713Sjeffsched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1724171713Sjeff{
1725171713Sjeff	struct tdq *tdn;
1726171713Sjeff
1727171713Sjeff	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1728171713Sjeff#ifdef SMP
1729171713Sjeff	/*
1730171713Sjeff	 * Do the lock dance required to avoid LOR.  We grab an extra
1731171713Sjeff	 * spinlock nesting to prevent preemption while we're
1732171713Sjeff	 * not holding either run-queue lock.
1733171713Sjeff	 */
1734171713Sjeff	spinlock_enter();
1735171713Sjeff	thread_block_switch(td);	/* This releases the lock on tdq. */
1736171713Sjeff	TDQ_LOCK(tdn);
1737171713Sjeff	tdq_add(tdn, td, flags);
1738171713Sjeff	tdq_notify(td->td_sched);
1739171713Sjeff	/*
1740171713Sjeff	 * After we unlock tdn the new cpu still can't switch into this
1741171713Sjeff	 * thread until we've unblocked it in cpu_switch().  The lock
1742171713Sjeff	 * pointers may match in the case of HTT cores.  Don't unlock here
1743171713Sjeff	 * or we can deadlock when the other CPU runs the IPI handler.
1744171713Sjeff	 */
1745171713Sjeff	if (TDQ_LOCKPTR(tdn) != TDQ_LOCKPTR(tdq)) {
1746171713Sjeff		TDQ_UNLOCK(tdn);
1747171713Sjeff		TDQ_LOCK(tdq);
1748171713Sjeff	}
1749171713Sjeff	spinlock_exit();
1750171713Sjeff#endif
1751171713Sjeff	return (TDQ_LOCKPTR(tdn));
1752171713Sjeff}
1753171713Sjeff
1754171713Sjeff/*
1755171482Sjeff * Release a thread that was blocked with thread_block_switch().
1756171482Sjeff */
1757171482Sjeffstatic inline void
1758171482Sjeffthread_unblock_switch(struct thread *td, struct mtx *mtx)
1759171482Sjeff{
1760171482Sjeff	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1761171482Sjeff	    (uintptr_t)mtx);
1762171482Sjeff}
1763171482Sjeff
1764171482Sjeff/*
1765171482Sjeff * Switch threads.  This function has to handle threads coming in while
1766171482Sjeff * blocked for some reason, running, or idle.  It also must deal with
1767171482Sjeff * migrating a thread from one queue to another as running threads may
1768171482Sjeff * be assigned elsewhere via binding.
1769171482Sjeff */
1770161599Sdavidxuvoid
1771135051Sjuliansched_switch(struct thread *td, struct thread *newtd, int flags)
1772109864Sjeff{
1773165627Sjeff	struct tdq *tdq;
1774164936Sjulian	struct td_sched *ts;
1775171482Sjeff	struct mtx *mtx;
1776171713Sjeff	int srqflag;
1777171482Sjeff	int cpuid;
1778109864Sjeff
1779170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1780109864Sjeff
1781171482Sjeff	cpuid = PCPU_GET(cpuid);
1782171482Sjeff	tdq = TDQ_CPU(cpuid);
1783164936Sjulian	ts = td->td_sched;
1784171713Sjeff	mtx = td->td_lock;
1785171482Sjeff#ifdef SMP
1786171482Sjeff	ts->ts_rltick = ticks;
1787171482Sjeff#endif
1788133555Sjeff	td->td_lastcpu = td->td_oncpu;
1789113339Sjulian	td->td_oncpu = NOCPU;
1790132266Sjhb	td->td_flags &= ~TDF_NEEDRESCHED;
1791144777Sups	td->td_owepreempt = 0;
1792123434Sjeff	/*
1793171482Sjeff	 * The lock pointer in an idle thread should never change.  Reset it
1794171482Sjeff	 * to CAN_RUN as well.
1795123434Sjeff	 */
1796167327Sjulian	if (TD_IS_IDLETHREAD(td)) {
1797171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1798139334Sjeff		TD_SET_CAN_RUN(td);
1799170293Sjeff	} else if (TD_IS_RUNNING(td)) {
1800171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1801165627Sjeff		tdq_load_rem(tdq, ts);
1802171713Sjeff		srqflag = (flags & SW_PREEMPT) ?
1803170293Sjeff		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1804171713Sjeff		    SRQ_OURSELF|SRQ_YIELDING;
1805171713Sjeff		if (ts->ts_cpu == cpuid)
1806171713Sjeff			tdq_add(tdq, td, srqflag);
1807171713Sjeff		else
1808171713Sjeff			mtx = sched_switch_migrate(tdq, td, srqflag);
1809171482Sjeff	} else {
1810171482Sjeff		/* This thread must be going to sleep. */
1811171482Sjeff		TDQ_LOCK(tdq);
1812171482Sjeff		mtx = thread_block_switch(td);
1813170293Sjeff		tdq_load_rem(tdq, ts);
1814171482Sjeff	}
1815171482Sjeff	/*
1816171482Sjeff	 * We enter here with the thread blocked and assigned to the
1817171482Sjeff	 * appropriate cpu run-queue or sleep-queue and with the current
1818171482Sjeff	 * thread-queue locked.
1819171482Sjeff	 */
1820171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1821171482Sjeff	/*
1822171505Sjeff	 * If KSE assigned a new thread just add it here and let choosethread
1823171505Sjeff	 * select the best one.
1824171482Sjeff	 */
1825171505Sjeff	if (newtd != NULL)
1826171505Sjeff		sched_switchin(tdq, newtd);
1827171482Sjeff	newtd = choosethread();
1828171482Sjeff	/*
1829171482Sjeff	 * Call the MD code to switch contexts if necessary.
1830171482Sjeff	 */
1831145256Sjkoshy	if (td != newtd) {
1832145256Sjkoshy#ifdef	HWPMC_HOOKS
1833145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1834145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1835145256Sjkoshy#endif
1836174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1837172411Sjeff		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1838171482Sjeff		cpu_switch(td, newtd, mtx);
1839171482Sjeff		/*
1840171482Sjeff		 * We may return from cpu_switch on a different cpu.  However,
1841171482Sjeff		 * we always return with td_lock pointing to the current cpu's
1842171482Sjeff		 * run queue lock.
1843171482Sjeff		 */
1844171482Sjeff		cpuid = PCPU_GET(cpuid);
1845171482Sjeff		tdq = TDQ_CPU(cpuid);
1846174629Sjeff		lock_profile_obtain_lock_success(
1847174629Sjeff		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1848145256Sjkoshy#ifdef	HWPMC_HOOKS
1849145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1850145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1851145256Sjkoshy#endif
1852171482Sjeff	} else
1853171482Sjeff		thread_unblock_switch(td, mtx);
1854171482Sjeff	/*
1855171482Sjeff	 * Assert that all went well and return.
1856171482Sjeff	 */
1857171482Sjeff#ifdef SMP
1858171482Sjeff	/* We should always get here with the lowest priority td possible */
1859171482Sjeff	tdq->tdq_lowpri = td->td_priority;
1860171482Sjeff#endif
1861171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1862171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1863171482Sjeff	td->td_oncpu = cpuid;
1864109864Sjeff}
1865109864Sjeff
1866171482Sjeff/*
1867171482Sjeff * Adjust thread priorities as a result of a nice request.
1868171482Sjeff */
1869109864Sjeffvoid
1870130551Sjuliansched_nice(struct proc *p, int nice)
1871109864Sjeff{
1872109864Sjeff	struct thread *td;
1873109864Sjeff
1874130551Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
1875170293Sjeff	PROC_SLOCK_ASSERT(p, MA_OWNED);
1876165762Sjeff
1877130551Sjulian	p->p_nice = nice;
1878163709Sjb	FOREACH_THREAD_IN_PROC(p, td) {
1879170293Sjeff		thread_lock(td);
1880163709Sjb		sched_priority(td);
1881165762Sjeff		sched_prio(td, td->td_base_user_pri);
1882170293Sjeff		thread_unlock(td);
1883130551Sjulian	}
1884109864Sjeff}
1885109864Sjeff
1886171482Sjeff/*
1887171482Sjeff * Record the sleep time for the interactivity scorer.
1888171482Sjeff */
1889109864Sjeffvoid
1890126326Sjhbsched_sleep(struct thread *td)
1891109864Sjeff{
1892165762Sjeff
1893170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1894109864Sjeff
1895172264Sjeff	td->td_slptick = ticks;
1896109864Sjeff}
1897109864Sjeff
1898171482Sjeff/*
1899171482Sjeff * Schedule a thread to resume execution and record how long it voluntarily
1900171482Sjeff * slept.  We also update the pctcpu, interactivity, and priority.
1901171482Sjeff */
1902109864Sjeffvoid
1903109864Sjeffsched_wakeup(struct thread *td)
1904109864Sjeff{
1905166229Sjeff	struct td_sched *ts;
1906171482Sjeff	int slptick;
1907165762Sjeff
1908170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1909166229Sjeff	ts = td->td_sched;
1910109864Sjeff	/*
1911165762Sjeff	 * If we slept for more than a tick update our interactivity and
1912165762Sjeff	 * priority.
1913109864Sjeff	 */
1914172264Sjeff	slptick = td->td_slptick;
1915172264Sjeff	td->td_slptick = 0;
1916171482Sjeff	if (slptick && slptick != ticks) {
1917166208Sjeff		u_int hzticks;
1918109864Sjeff
1919171482Sjeff		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1920171482Sjeff		ts->ts_slptime += hzticks;
1921165819Sjeff		sched_interact_update(td);
1922166229Sjeff		sched_pctcpu_update(ts);
1923163709Sjb		sched_priority(td);
1924109864Sjeff	}
1925166229Sjeff	/* Reset the slice value after we sleep. */
1926166229Sjeff	ts->ts_slice = sched_slice;
1927166190Sjeff	sched_add(td, SRQ_BORING);
1928109864Sjeff}
1929109864Sjeff
1930109864Sjeff/*
1931109864Sjeff * Penalize the parent for creating a new child and initialize the child's
1932109864Sjeff * priority.
1933109864Sjeff */
1934109864Sjeffvoid
1935163709Sjbsched_fork(struct thread *td, struct thread *child)
1936109864Sjeff{
1937170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1938164936Sjulian	sched_fork_thread(td, child);
1939165762Sjeff	/*
1940165762Sjeff	 * Penalize the parent and child for forking.
1941165762Sjeff	 */
1942165762Sjeff	sched_interact_fork(child);
1943165762Sjeff	sched_priority(child);
1944171482Sjeff	td->td_sched->ts_runtime += tickincr;
1945165762Sjeff	sched_interact_update(td);
1946165762Sjeff	sched_priority(td);
1947164936Sjulian}
1948109864Sjeff
1949171482Sjeff/*
1950171482Sjeff * Fork a new thread, may be within the same process.
1951171482Sjeff */
1952164936Sjulianvoid
1953164936Sjuliansched_fork_thread(struct thread *td, struct thread *child)
1954164936Sjulian{
1955164936Sjulian	struct td_sched *ts;
1956164936Sjulian	struct td_sched *ts2;
1957164936Sjulian
1958165762Sjeff	/*
1959165762Sjeff	 * Initialize child.
1960165762Sjeff	 */
1961170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1962163709Sjb	sched_newthread(child);
1963171482Sjeff	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1964164936Sjulian	ts = td->td_sched;
1965164936Sjulian	ts2 = child->td_sched;
1966164936Sjulian	ts2->ts_cpu = ts->ts_cpu;
1967164936Sjulian	ts2->ts_runq = NULL;
1968165762Sjeff	/*
1969165762Sjeff	 * Grab our parents cpu estimation information and priority.
1970165762Sjeff	 */
1971164936Sjulian	ts2->ts_ticks = ts->ts_ticks;
1972164936Sjulian	ts2->ts_ltick = ts->ts_ltick;
1973164936Sjulian	ts2->ts_ftick = ts->ts_ftick;
1974165762Sjeff	child->td_user_pri = td->td_user_pri;
1975165762Sjeff	child->td_base_user_pri = td->td_base_user_pri;
1976165762Sjeff	/*
1977165762Sjeff	 * And update interactivity score.
1978165762Sjeff	 */
1979171482Sjeff	ts2->ts_slptime = ts->ts_slptime;
1980171482Sjeff	ts2->ts_runtime = ts->ts_runtime;
1981165762Sjeff	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
1982113357Sjeff}
1983113357Sjeff
1984171482Sjeff/*
1985171482Sjeff * Adjust the priority class of a thread.
1986171482Sjeff */
1987113357Sjeffvoid
1988163709Sjbsched_class(struct thread *td, int class)
1989113357Sjeff{
1990113357Sjeff
1991170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1992163709Sjb	if (td->td_pri_class == class)
1993113357Sjeff		return;
1994113357Sjeff
1995121896Sjeff#ifdef SMP
1996165827Sjeff	/*
1997165827Sjeff	 * On SMP if we're on the RUNQ we must adjust the transferable
1998165827Sjeff	 * count because could be changing to or from an interrupt
1999165827Sjeff	 * class.
2000165827Sjeff	 */
2001166190Sjeff	if (TD_ON_RUNQ(td)) {
2002165827Sjeff		struct tdq *tdq;
2003165827Sjeff
2004165827Sjeff		tdq = TDQ_CPU(td->td_sched->ts_cpu);
2005165827Sjeff		if (THREAD_CAN_MIGRATE(td)) {
2006165827Sjeff			tdq->tdq_transferable--;
2007165827Sjeff			tdq->tdq_group->tdg_transferable--;
2008122744Sjeff		}
2009165827Sjeff		td->td_pri_class = class;
2010165827Sjeff		if (THREAD_CAN_MIGRATE(td)) {
2011165827Sjeff			tdq->tdq_transferable++;
2012165827Sjeff			tdq->tdq_group->tdg_transferable++;
2013165827Sjeff		}
2014165827Sjeff	}
2015164936Sjulian#endif
2016163709Sjb	td->td_pri_class = class;
2017109864Sjeff}
2018109864Sjeff
2019109864Sjeff/*
2020109864Sjeff * Return some of the child's priority and interactivity to the parent.
2021109864Sjeff */
2022109864Sjeffvoid
2023164939Sjuliansched_exit(struct proc *p, struct thread *child)
2024109864Sjeff{
2025165762Sjeff	struct thread *td;
2026164939Sjulian
2027163709Sjb	CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
2028173600Sjulian	    child, child->td_name, child->td_priority);
2029113372Sjeff
2030170293Sjeff	PROC_SLOCK_ASSERT(p, MA_OWNED);
2031165762Sjeff	td = FIRST_THREAD_IN_PROC(p);
2032165762Sjeff	sched_exit_thread(td, child);
2033113372Sjeff}
2034113372Sjeff
2035171482Sjeff/*
2036171482Sjeff * Penalize another thread for the time spent on this one.  This helps to
2037171482Sjeff * worsen the priority and interactivity of processes which schedule batch
2038171482Sjeff * jobs such as make.  This has little effect on the make process itself but
2039171482Sjeff * causes new processes spawned by it to receive worse scores immediately.
2040171482Sjeff */
2041113372Sjeffvoid
2042164939Sjuliansched_exit_thread(struct thread *td, struct thread *child)
2043164936Sjulian{
2044165762Sjeff
2045164939Sjulian	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
2046173600Sjulian	    child, child->td_name, child->td_priority);
2047164939Sjulian
2048165762Sjeff#ifdef KSE
2049165762Sjeff	/*
2050165762Sjeff	 * KSE forks and exits so often that this penalty causes short-lived
2051165762Sjeff	 * threads to always be non-interactive.  This causes mozilla to
2052165762Sjeff	 * crawl under load.
2053165762Sjeff	 */
2054165762Sjeff	if ((td->td_pflags & TDP_SA) && td->td_proc == child->td_proc)
2055165762Sjeff		return;
2056165762Sjeff#endif
2057165762Sjeff	/*
2058165762Sjeff	 * Give the child's runtime to the parent without returning the
2059165762Sjeff	 * sleep time as a penalty to the parent.  This causes shells that
2060165762Sjeff	 * launch expensive things to mark their children as expensive.
2061165762Sjeff	 */
2062170293Sjeff	thread_lock(td);
2063171482Sjeff	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2064164939Sjulian	sched_interact_update(td);
2065165762Sjeff	sched_priority(td);
2066170293Sjeff	thread_unlock(td);
2067164936Sjulian}
2068164936Sjulian
2069171482Sjeff/*
2070171482Sjeff * Fix priorities on return to user-space.  Priorities may be elevated due
2071171482Sjeff * to static priorities in msleep() or similar.
2072171482Sjeff */
2073164936Sjulianvoid
2074164936Sjuliansched_userret(struct thread *td)
2075164936Sjulian{
2076164936Sjulian	/*
2077164936Sjulian	 * XXX we cheat slightly on the locking here to avoid locking in
2078164936Sjulian	 * the usual case.  Setting td_priority here is essentially an
2079164936Sjulian	 * incomplete workaround for not setting it properly elsewhere.
2080164936Sjulian	 * Now that some interrupt handlers are threads, not setting it
2081164936Sjulian	 * properly elsewhere can clobber it in the window between setting
2082164936Sjulian	 * it here and returning to user mode, so don't waste time setting
2083164936Sjulian	 * it perfectly here.
2084164936Sjulian	 */
2085164936Sjulian	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2086164936Sjulian	    ("thread with borrowed priority returning to userland"));
2087164936Sjulian	if (td->td_priority != td->td_user_pri) {
2088170293Sjeff		thread_lock(td);
2089164936Sjulian		td->td_priority = td->td_user_pri;
2090164936Sjulian		td->td_base_pri = td->td_user_pri;
2091170293Sjeff		thread_unlock(td);
2092164936Sjulian        }
2093164936Sjulian}
2094164936Sjulian
2095171482Sjeff/*
2096171482Sjeff * Handle a stathz tick.  This is really only relevant for timeshare
2097171482Sjeff * threads.
2098171482Sjeff */
2099164936Sjulianvoid
2100121127Sjeffsched_clock(struct thread *td)
2101109864Sjeff{
2102164936Sjulian	struct tdq *tdq;
2103164936Sjulian	struct td_sched *ts;
2104109864Sjeff
2105171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2106164936Sjulian	tdq = TDQ_SELF();
2107172409Sjeff#ifdef SMP
2108133427Sjeff	/*
2109172409Sjeff	 * We run the long term load balancer infrequently on the first cpu.
2110172409Sjeff	 */
2111172409Sjeff	if (balance_tdq == tdq) {
2112172409Sjeff		if (balance_ticks && --balance_ticks == 0)
2113172409Sjeff			sched_balance();
2114172409Sjeff		if (balance_group_ticks && --balance_group_ticks == 0)
2115172409Sjeff			sched_balance_groups();
2116172409Sjeff	}
2117172409Sjeff#endif
2118172409Sjeff	/*
2119165766Sjeff	 * Advance the insert index once for each tick to ensure that all
2120165766Sjeff	 * threads get a chance to run.
2121133427Sjeff	 */
2122165766Sjeff	if (tdq->tdq_idx == tdq->tdq_ridx) {
2123165766Sjeff		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2124165766Sjeff		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2125165766Sjeff			tdq->tdq_ridx = tdq->tdq_idx;
2126165766Sjeff	}
2127165766Sjeff	ts = td->td_sched;
2128175104Sjeff	if (td->td_pri_class & PRI_FIFO_BIT)
2129113357Sjeff		return;
2130175104Sjeff	if (td->td_pri_class == PRI_TIMESHARE) {
2131175104Sjeff		/*
2132175104Sjeff		 * We used a tick; charge it to the thread so
2133175104Sjeff		 * that we can compute our interactivity.
2134175104Sjeff		 */
2135175104Sjeff		td->td_sched->ts_runtime += tickincr;
2136175104Sjeff		sched_interact_update(td);
2137175104Sjeff	}
2138113357Sjeff	/*
2139109864Sjeff	 * We used up one time slice.
2140109864Sjeff	 */
2141164936Sjulian	if (--ts->ts_slice > 0)
2142113357Sjeff		return;
2143109864Sjeff	/*
2144113357Sjeff	 * We're out of time, recompute priorities and requeue.
2145109864Sjeff	 */
2146165796Sjeff	sched_priority(td);
2147113357Sjeff	td->td_flags |= TDF_NEEDRESCHED;
2148109864Sjeff}
2149109864Sjeff
2150171482Sjeff/*
2151171482Sjeff * Called once per hz tick.  Used for cpu utilization information.  This
2152171482Sjeff * is easier than trying to scale based on stathz.
2153171482Sjeff */
2154171482Sjeffvoid
2155171482Sjeffsched_tick(void)
2156171482Sjeff{
2157171482Sjeff	struct td_sched *ts;
2158171482Sjeff
2159171482Sjeff	ts = curthread->td_sched;
2160171482Sjeff	/* Adjust ticks for pctcpu */
2161171482Sjeff	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2162171482Sjeff	ts->ts_ltick = ticks;
2163171482Sjeff	/*
2164171482Sjeff	 * Update if we've exceeded our desired tick threshhold by over one
2165171482Sjeff	 * second.
2166171482Sjeff	 */
2167171482Sjeff	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2168171482Sjeff		sched_pctcpu_update(ts);
2169171482Sjeff}
2170171482Sjeff
2171171482Sjeff/*
2172171482Sjeff * Return whether the current CPU has runnable tasks.  Used for in-kernel
2173171482Sjeff * cooperative idle threads.
2174171482Sjeff */
2175109864Sjeffint
2176109864Sjeffsched_runnable(void)
2177109864Sjeff{
2178164936Sjulian	struct tdq *tdq;
2179115998Sjeff	int load;
2180109864Sjeff
2181115998Sjeff	load = 1;
2182115998Sjeff
2183164936Sjulian	tdq = TDQ_SELF();
2184121605Sjeff	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2185165620Sjeff		if (tdq->tdq_load > 0)
2186121605Sjeff			goto out;
2187121605Sjeff	} else
2188165620Sjeff		if (tdq->tdq_load - 1 > 0)
2189121605Sjeff			goto out;
2190115998Sjeff	load = 0;
2191115998Sjeffout:
2192115998Sjeff	return (load);
2193109864Sjeff}
2194109864Sjeff
2195171482Sjeff/*
2196171482Sjeff * Choose the highest priority thread to run.  The thread is removed from
2197171482Sjeff * the run-queue while running however the load remains.  For SMP we set
2198171482Sjeff * the tdq in the global idle bitmask if it idles here.
2199171482Sjeff */
2200166190Sjeffstruct thread *
2201109970Sjeffsched_choose(void)
2202109970Sjeff{
2203171482Sjeff#ifdef SMP
2204171482Sjeff	struct tdq_group *tdg;
2205171482Sjeff#endif
2206171482Sjeff	struct td_sched *ts;
2207175587Sjeff	struct thread *td;
2208164936Sjulian	struct tdq *tdq;
2209109970Sjeff
2210164936Sjulian	tdq = TDQ_SELF();
2211171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2212164936Sjulian	ts = tdq_choose(tdq);
2213164936Sjulian	if (ts) {
2214164936Sjulian		tdq_runq_rem(tdq, ts);
2215166190Sjeff		return (ts->ts_thread);
2216109864Sjeff	}
2217175587Sjeff	td = PCPU_GET(idlethread);
2218109970Sjeff#ifdef SMP
2219171482Sjeff	/*
2220171482Sjeff	 * We only set the idled bit when all of the cpus in the group are
2221171482Sjeff	 * idle.  Otherwise we could get into a situation where a thread bounces
2222171482Sjeff	 * back and forth between two idle cores on seperate physical CPUs.
2223171482Sjeff	 */
2224171482Sjeff	tdg = tdq->tdq_group;
2225171482Sjeff	tdg->tdg_idlemask |= PCPU_GET(cpumask);
2226171482Sjeff	if (tdg->tdg_idlemask == tdg->tdg_cpumask)
2227171482Sjeff		atomic_set_int(&tdq_idle, tdg->tdg_mask);
2228175587Sjeff	tdq->tdq_lowpri = td->td_priority;
2229109970Sjeff#endif
2230175587Sjeff	return (td);
2231109864Sjeff}
2232109864Sjeff
2233171482Sjeff/*
2234171482Sjeff * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2235171482Sjeff * we always request it once we exit a critical section.
2236171482Sjeff */
2237171482Sjeffstatic inline void
2238171482Sjeffsched_setpreempt(struct thread *td)
2239166190Sjeff{
2240166190Sjeff	struct thread *ctd;
2241166190Sjeff	int cpri;
2242166190Sjeff	int pri;
2243166190Sjeff
2244166190Sjeff	ctd = curthread;
2245166190Sjeff	pri = td->td_priority;
2246166190Sjeff	cpri = ctd->td_priority;
2247171482Sjeff	if (td->td_priority < ctd->td_priority)
2248171482Sjeff		curthread->td_flags |= TDF_NEEDRESCHED;
2249166190Sjeff	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2250171482Sjeff		return;
2251166190Sjeff	/*
2252166190Sjeff	 * Always preempt IDLE threads.  Otherwise only if the preempting
2253166190Sjeff	 * thread is an ithread.
2254166190Sjeff	 */
2255171482Sjeff	if (pri > preempt_thresh && cpri < PRI_MIN_IDLE)
2256171482Sjeff		return;
2257171482Sjeff	ctd->td_owepreempt = 1;
2258171482Sjeff	return;
2259166190Sjeff}
2260166190Sjeff
2261171482Sjeff/*
2262171482Sjeff * Add a thread to a thread queue.  Initializes priority, slice, runq, and
2263171482Sjeff * add it to the appropriate queue.  This is the internal function called
2264171482Sjeff * when the tdq is predetermined.
2265171482Sjeff */
2266109864Sjeffvoid
2267171482Sjefftdq_add(struct tdq *tdq, struct thread *td, int flags)
2268109864Sjeff{
2269164936Sjulian	struct td_sched *ts;
2270121790Sjeff	int class;
2271166108Sjeff#ifdef SMP
2272166108Sjeff	int cpumask;
2273166108Sjeff#endif
2274109864Sjeff
2275171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2276166190Sjeff	KASSERT((td->td_inhibitors == 0),
2277166190Sjeff	    ("sched_add: trying to run inhibited thread"));
2278166190Sjeff	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2279166190Sjeff	    ("sched_add: bad thread state"));
2280172207Sjeff	KASSERT(td->td_flags & TDF_INMEM,
2281172207Sjeff	    ("sched_add: thread swapped out"));
2282171482Sjeff
2283171482Sjeff	ts = td->td_sched;
2284171482Sjeff	class = PRI_BASE(td->td_pri_class);
2285166190Sjeff        TD_SET_RUNQ(td);
2286166190Sjeff	if (ts->ts_slice == 0)
2287166190Sjeff		ts->ts_slice = sched_slice;
2288133427Sjeff	/*
2289171482Sjeff	 * Pick the run queue based on priority.
2290133427Sjeff	 */
2291171482Sjeff	if (td->td_priority <= PRI_MAX_REALTIME)
2292171482Sjeff		ts->ts_runq = &tdq->tdq_realtime;
2293171482Sjeff	else if (td->td_priority <= PRI_MAX_TIMESHARE)
2294171482Sjeff		ts->ts_runq = &tdq->tdq_timeshare;
2295171482Sjeff	else
2296171482Sjeff		ts->ts_runq = &tdq->tdq_idle;
2297171482Sjeff#ifdef SMP
2298166108Sjeff	cpumask = 1 << ts->ts_cpu;
2299121790Sjeff	/*
2300123685Sjeff	 * If we had been idle, clear our bit in the group and potentially
2301166108Sjeff	 * the global bitmap.
2302121790Sjeff	 */
2303165762Sjeff	if ((class != PRI_IDLE && class != PRI_ITHD) &&
2304166108Sjeff	    (tdq->tdq_group->tdg_idlemask & cpumask) != 0) {
2305121790Sjeff		/*
2306123433Sjeff		 * Check to see if our group is unidling, and if so, remove it
2307123433Sjeff		 * from the global idle mask.
2308121790Sjeff		 */
2309165620Sjeff		if (tdq->tdq_group->tdg_idlemask ==
2310165620Sjeff		    tdq->tdq_group->tdg_cpumask)
2311165620Sjeff			atomic_clear_int(&tdq_idle, tdq->tdq_group->tdg_mask);
2312123433Sjeff		/*
2313123433Sjeff		 * Now remove ourselves from the group specific idle mask.
2314123433Sjeff		 */
2315166108Sjeff		tdq->tdq_group->tdg_idlemask &= ~cpumask;
2316166108Sjeff	}
2317171482Sjeff	if (td->td_priority < tdq->tdq_lowpri)
2318171482Sjeff		tdq->tdq_lowpri = td->td_priority;
2319121790Sjeff#endif
2320171482Sjeff	tdq_runq_add(tdq, ts, flags);
2321171482Sjeff	tdq_load_add(tdq, ts);
2322171482Sjeff}
2323171482Sjeff
2324171482Sjeff/*
2325171482Sjeff * Select the target thread queue and add a thread to it.  Request
2326171482Sjeff * preemption or IPI a remote processor if required.
2327171482Sjeff */
2328171482Sjeffvoid
2329171482Sjeffsched_add(struct thread *td, int flags)
2330171482Sjeff{
2331171482Sjeff	struct td_sched *ts;
2332171482Sjeff	struct tdq *tdq;
2333171482Sjeff#ifdef SMP
2334171482Sjeff	int cpuid;
2335171482Sjeff	int cpu;
2336171482Sjeff#endif
2337171482Sjeff	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
2338173600Sjulian	    td, td->td_name, td->td_priority, curthread,
2339173600Sjulian	    curthread->td_name);
2340171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2341171482Sjeff	ts = td->td_sched;
2342166108Sjeff	/*
2343171482Sjeff	 * Recalculate the priority before we select the target cpu or
2344171482Sjeff	 * run-queue.
2345166108Sjeff	 */
2346171482Sjeff	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2347171482Sjeff		sched_priority(td);
2348171482Sjeff#ifdef SMP
2349171482Sjeff	cpuid = PCPU_GET(cpuid);
2350171482Sjeff	/*
2351171482Sjeff	 * Pick the destination cpu and if it isn't ours transfer to the
2352171482Sjeff	 * target cpu.
2353171482Sjeff	 */
2354175348Sjeff	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_MIGRATE(td) &&
2355175348Sjeff	    curthread->td_intr_nesting_level)
2356175348Sjeff		ts->ts_cpu = cpuid;
2357175348Sjeff	if (!THREAD_CAN_MIGRATE(td))
2358171482Sjeff		cpu = ts->ts_cpu;
2359166108Sjeff	else
2360171482Sjeff		cpu = sched_pickcpu(ts, flags);
2361171482Sjeff	tdq = sched_setcpu(ts, cpu, flags);
2362171482Sjeff	tdq_add(tdq, td, flags);
2363171482Sjeff	if (cpu != cpuid) {
2364166108Sjeff		tdq_notify(ts);
2365166108Sjeff		return;
2366166108Sjeff	}
2367171482Sjeff#else
2368171482Sjeff	tdq = TDQ_SELF();
2369171482Sjeff	TDQ_LOCK(tdq);
2370171482Sjeff	/*
2371171482Sjeff	 * Now that the thread is moving to the run-queue, set the lock
2372171482Sjeff	 * to the scheduler's lock.
2373171482Sjeff	 */
2374171482Sjeff	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2375171482Sjeff	tdq_add(tdq, td, flags);
2376166108Sjeff#endif
2377171482Sjeff	if (!(flags & SRQ_YIELDING))
2378171482Sjeff		sched_setpreempt(td);
2379109864Sjeff}
2380109864Sjeff
2381171482Sjeff/*
2382171482Sjeff * Remove a thread from a run-queue without running it.  This is used
2383171482Sjeff * when we're stealing a thread from a remote queue.  Otherwise all threads
2384171482Sjeff * exit by calling sched_exit_thread() and sched_throw() themselves.
2385171482Sjeff */
2386109864Sjeffvoid
2387121127Sjeffsched_rem(struct thread *td)
2388109864Sjeff{
2389164936Sjulian	struct tdq *tdq;
2390164936Sjulian	struct td_sched *ts;
2391113357Sjeff
2392139316Sjeff	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
2393173600Sjulian	    td, td->td_name, td->td_priority, curthread,
2394173600Sjulian	    curthread->td_name);
2395164936Sjulian	ts = td->td_sched;
2396171482Sjeff	tdq = TDQ_CPU(ts->ts_cpu);
2397171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2398171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2399166190Sjeff	KASSERT(TD_ON_RUNQ(td),
2400164936Sjulian	    ("sched_rem: thread not on run queue"));
2401164936Sjulian	tdq_runq_rem(tdq, ts);
2402164936Sjulian	tdq_load_rem(tdq, ts);
2403166190Sjeff	TD_SET_CAN_RUN(td);
2404109864Sjeff}
2405109864Sjeff
2406171482Sjeff/*
2407171482Sjeff * Fetch cpu utilization information.  Updates on demand.
2408171482Sjeff */
2409109864Sjefffixpt_t
2410121127Sjeffsched_pctcpu(struct thread *td)
2411109864Sjeff{
2412109864Sjeff	fixpt_t pctcpu;
2413164936Sjulian	struct td_sched *ts;
2414109864Sjeff
2415109864Sjeff	pctcpu = 0;
2416164936Sjulian	ts = td->td_sched;
2417164936Sjulian	if (ts == NULL)
2418121290Sjeff		return (0);
2419109864Sjeff
2420170293Sjeff	thread_lock(td);
2421164936Sjulian	if (ts->ts_ticks) {
2422109864Sjeff		int rtick;
2423109864Sjeff
2424165796Sjeff		sched_pctcpu_update(ts);
2425109864Sjeff		/* How many rtick per second ? */
2426165762Sjeff		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2427165762Sjeff		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2428109864Sjeff	}
2429170293Sjeff	thread_unlock(td);
2430109864Sjeff
2431109864Sjeff	return (pctcpu);
2432109864Sjeff}
2433109864Sjeff
2434176729Sjeffvoid
2435176729Sjeffsched_affinity(struct thread *td)
2436176729Sjeff{
2437176729Sjeff}
2438176729Sjeff
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);
2494170293Sjeff	SCHED_STAT_INC(switch_relinquish);
2495159630Sdavidxu	mi_switch(SW_VOL, NULL);
2496170293Sjeff	thread_unlock(td);
2497159630Sdavidxu}
2498159630Sdavidxu
2499171482Sjeff/*
2500171482Sjeff * Return the total system load.
2501171482Sjeff */
2502145256Sjkoshyint
2503125289Sjeffsched_load(void)
2504125289Sjeff{
2505125289Sjeff#ifdef SMP
2506125289Sjeff	int total;
2507125289Sjeff	int i;
2508125289Sjeff
2509125289Sjeff	total = 0;
2510165620Sjeff	for (i = 0; i <= tdg_maxid; i++)
2511165620Sjeff		total += TDQ_GROUP(i)->tdg_load;
2512125289Sjeff	return (total);
2513125289Sjeff#else
2514165620Sjeff	return (TDQ_SELF()->tdq_sysload);
2515125289Sjeff#endif
2516125289Sjeff}
2517125289Sjeff
2518125289Sjeffint
2519109864Sjeffsched_sizeof_proc(void)
2520109864Sjeff{
2521109864Sjeff	return (sizeof(struct proc));
2522109864Sjeff}
2523109864Sjeff
2524109864Sjeffint
2525109864Sjeffsched_sizeof_thread(void)
2526109864Sjeff{
2527109864Sjeff	return (sizeof(struct thread) + sizeof(struct td_sched));
2528109864Sjeff}
2529159570Sdavidxu
2530166190Sjeff/*
2531166190Sjeff * The actual idle process.
2532166190Sjeff */
2533166190Sjeffvoid
2534166190Sjeffsched_idletd(void *dummy)
2535166190Sjeff{
2536166190Sjeff	struct thread *td;
2537171482Sjeff	struct tdq *tdq;
2538166190Sjeff
2539166190Sjeff	td = curthread;
2540171482Sjeff	tdq = TDQ_SELF();
2541166190Sjeff	mtx_assert(&Giant, MA_NOTOWNED);
2542171482Sjeff	/* ULE relies on preemption for idle interruption. */
2543171482Sjeff	for (;;) {
2544171482Sjeff#ifdef SMP
2545171482Sjeff		if (tdq_idled(tdq))
2546171482Sjeff			cpu_idle();
2547171482Sjeff#else
2548166190Sjeff		cpu_idle();
2549171482Sjeff#endif
2550171482Sjeff	}
2551166190Sjeff}
2552166190Sjeff
2553170293Sjeff/*
2554170293Sjeff * A CPU is entering for the first time or a thread is exiting.
2555170293Sjeff */
2556170293Sjeffvoid
2557170293Sjeffsched_throw(struct thread *td)
2558170293Sjeff{
2559172411Sjeff	struct thread *newtd;
2560171482Sjeff	struct tdq *tdq;
2561171482Sjeff
2562171482Sjeff	tdq = TDQ_SELF();
2563170293Sjeff	if (td == NULL) {
2564171482Sjeff		/* Correct spinlock nesting and acquire the correct lock. */
2565171482Sjeff		TDQ_LOCK(tdq);
2566170293Sjeff		spinlock_exit();
2567170293Sjeff	} else {
2568171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2569171482Sjeff		tdq_load_rem(tdq, td->td_sched);
2570174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2571170293Sjeff	}
2572170293Sjeff	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2573172411Sjeff	newtd = choosethread();
2574172411Sjeff	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2575170293Sjeff	PCPU_SET(switchtime, cpu_ticks());
2576170293Sjeff	PCPU_SET(switchticks, ticks);
2577172411Sjeff	cpu_throw(td, newtd);		/* doesn't return */
2578170293Sjeff}
2579170293Sjeff
2580171482Sjeff/*
2581171482Sjeff * This is called from fork_exit().  Just acquire the correct locks and
2582171482Sjeff * let fork do the rest of the work.
2583171482Sjeff */
2584170293Sjeffvoid
2585170600Sjeffsched_fork_exit(struct thread *td)
2586170293Sjeff{
2587171482Sjeff	struct td_sched *ts;
2588171482Sjeff	struct tdq *tdq;
2589171482Sjeff	int cpuid;
2590170293Sjeff
2591170293Sjeff	/*
2592170293Sjeff	 * Finish setting up thread glue so that it begins execution in a
2593171482Sjeff	 * non-nested critical section with the scheduler lock held.
2594170293Sjeff	 */
2595171482Sjeff	cpuid = PCPU_GET(cpuid);
2596171482Sjeff	tdq = TDQ_CPU(cpuid);
2597171482Sjeff	ts = td->td_sched;
2598171482Sjeff	if (TD_IS_IDLETHREAD(td))
2599171482Sjeff		td->td_lock = TDQ_LOCKPTR(tdq);
2600171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2601171482Sjeff	td->td_oncpu = cpuid;
2602172411Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2603174629Sjeff	lock_profile_obtain_lock_success(
2604174629Sjeff	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2605170293Sjeff}
2606170293Sjeff
2607171482Sjeffstatic SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0,
2608171482Sjeff    "Scheduler");
2609171482SjeffSYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2610165762Sjeff    "Scheduler name");
2611171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2612171482Sjeff    "Slice size for timeshare threads");
2613171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2614171482Sjeff     "Interactivity score threshold");
2615171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2616171482Sjeff     0,"Min priority for preemption, lower priorities have greater precedence");
2617166108Sjeff#ifdef SMP
2618171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, pick_pri, CTLFLAG_RW, &pick_pri, 0,
2619171482Sjeff    "Pick the target cpu based on priority rather than load.");
2620171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2621171482Sjeff    "Number of hz ticks to keep thread affinity for");
2622171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, tryself, CTLFLAG_RW, &tryself, 0, "");
2623171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2624171482Sjeff    "Enables the long-term load balancer");
2625172409SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2626172409Sjeff    &balance_interval, 0,
2627172409Sjeff    "Average frequency in stathz ticks to run the long-term balancer");
2628171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2629171482Sjeff    "Steals work from another hyper-threaded core on idle");
2630171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2631171482Sjeff    "Attempts to steal work from other cores before idling");
2632171506SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2633171506Sjeff    "Minimum load on remote cpu before we'll steal");
2634166108Sjeff#endif
2635165762Sjeff
2636172264Sjeff/* ps compat.  All cpu percentages from ULE are weighted. */
2637172293Sjeffstatic int ccpu = 0;
2638165762SjeffSYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2639165762Sjeff
2640165762Sjeff
2641134791Sjulian#define KERN_SWITCH_INCLUDE 1
2642134791Sjulian#include "kern/kern_switch.c"
2643