sched_ule.c revision 172409
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 172409 2007-10-02 00:36:06Z 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
74172345Sjeff#if !defined(__i386__) && !defined(__amd64__)
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;
246170293Sjeffstatic int topology = 0;
247166108Sjeff
248166108Sjeff/*
249165620Sjeff * One thread queue per processor.
250109864Sjeff */
251166108Sjeffstatic volatile cpumask_t tdq_idle;
252165620Sjeffstatic int tdg_maxid;
253164936Sjulianstatic struct tdq	tdq_cpu[MAXCPU];
254164936Sjulianstatic struct tdq_group tdq_groups[MAXCPU];
255172409Sjeffstatic struct tdq	*balance_tdq;
256172409Sjeffstatic int balance_group_ticks;
257172409Sjeffstatic int balance_ticks;
258129982Sjeff
259164936Sjulian#define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
260164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu[(x)])
261171713Sjeff#define	TDQ_ID(x)	((int)((x) - tdq_cpu))
262164936Sjulian#define	TDQ_GROUP(x)	(&tdq_groups[(x)])
263171713Sjeff#define	TDG_ID(x)	((int)((x) - tdq_groups))
264123433Sjeff#else	/* !SMP */
265164936Sjulianstatic struct tdq	tdq_cpu;
266171713Sjeffstatic struct mtx	tdq_lock;
267129982Sjeff
268170315Sjeff#define	TDQ_ID(x)	(0)
269164936Sjulian#define	TDQ_SELF()	(&tdq_cpu)
270164936Sjulian#define	TDQ_CPU(x)	(&tdq_cpu)
271110028Sjeff#endif
272109864Sjeff
273171482Sjeff#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
274171482Sjeff#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
275171482Sjeff#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
276171482Sjeff#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
277171713Sjeff#define	TDQ_LOCKPTR(t)		((t)->tdq_lock)
278171482Sjeff
279163709Sjbstatic void sched_priority(struct thread *);
280146954Sjeffstatic void sched_thread_priority(struct thread *, u_char);
281163709Sjbstatic int sched_interact_score(struct thread *);
282163709Sjbstatic void sched_interact_update(struct thread *);
283163709Sjbstatic void sched_interact_fork(struct thread *);
284164936Sjulianstatic void sched_pctcpu_update(struct td_sched *);
285109864Sjeff
286110267Sjeff/* Operations on per processor queues */
287164936Sjulianstatic struct td_sched * tdq_choose(struct tdq *);
288164936Sjulianstatic void tdq_setup(struct tdq *);
289164936Sjulianstatic void tdq_load_add(struct tdq *, struct td_sched *);
290164936Sjulianstatic void tdq_load_rem(struct tdq *, struct td_sched *);
291164936Sjulianstatic __inline void tdq_runq_add(struct tdq *, struct td_sched *, int);
292164936Sjulianstatic __inline void tdq_runq_rem(struct tdq *, struct td_sched *);
293164936Sjulianvoid tdq_print(int cpu);
294165762Sjeffstatic void runq_print(struct runq *rq);
295171482Sjeffstatic void tdq_add(struct tdq *, struct thread *, int);
296110267Sjeff#ifdef SMP
297171482Sjeffstatic void tdq_move(struct tdq *, struct tdq *);
298171482Sjeffstatic int tdq_idled(struct tdq *);
299171482Sjeffstatic void tdq_notify(struct td_sched *);
300172409Sjeffstatic struct td_sched *tdq_steal(struct tdq *);
301164936Sjulianstatic struct td_sched *runq_steal(struct runq *);
302171482Sjeffstatic int sched_pickcpu(struct td_sched *, int);
303172409Sjeffstatic void sched_balance(void);
304172409Sjeffstatic void sched_balance_groups(void);
305164936Sjulianstatic void sched_balance_group(struct tdq_group *);
306164936Sjulianstatic void sched_balance_pair(struct tdq *, struct tdq *);
307171482Sjeffstatic inline struct tdq *sched_setcpu(struct td_sched *, int, int);
308171482Sjeffstatic inline struct mtx *thread_block_switch(struct thread *);
309171482Sjeffstatic inline void thread_unblock_switch(struct thread *, struct mtx *);
310171713Sjeffstatic struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
311165827Sjeff
312166108Sjeff#define	THREAD_CAN_MIGRATE(td)	 ((td)->td_pinned == 0)
313121790Sjeff#endif
314110028Sjeff
315165762Sjeffstatic void sched_setup(void *dummy);
316165762SjeffSYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
317165762Sjeff
318165762Sjeffstatic void sched_initticks(void *dummy);
319165762SjeffSYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks, NULL)
320165762Sjeff
321171482Sjeff/*
322171482Sjeff * Print the threads waiting on a run-queue.
323171482Sjeff */
324165762Sjeffstatic void
325165762Sjeffrunq_print(struct runq *rq)
326165762Sjeff{
327165762Sjeff	struct rqhead *rqh;
328165762Sjeff	struct td_sched *ts;
329165762Sjeff	int pri;
330165762Sjeff	int j;
331165762Sjeff	int i;
332165762Sjeff
333165762Sjeff	for (i = 0; i < RQB_LEN; i++) {
334165762Sjeff		printf("\t\trunq bits %d 0x%zx\n",
335165762Sjeff		    i, rq->rq_status.rqb_bits[i]);
336165762Sjeff		for (j = 0; j < RQB_BPW; j++)
337165762Sjeff			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
338165762Sjeff				pri = j + (i << RQB_L2BPW);
339165762Sjeff				rqh = &rq->rq_queues[pri];
340165762Sjeff				TAILQ_FOREACH(ts, rqh, ts_procq) {
341165762Sjeff					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
342165762Sjeff					    ts->ts_thread, ts->ts_thread->td_proc->p_comm, ts->ts_thread->td_priority, ts->ts_rqindex, pri);
343165762Sjeff				}
344165762Sjeff			}
345165762Sjeff	}
346165762Sjeff}
347165762Sjeff
348171482Sjeff/*
349171482Sjeff * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
350171482Sjeff */
351113357Sjeffvoid
352164936Sjuliantdq_print(int cpu)
353110267Sjeff{
354164936Sjulian	struct tdq *tdq;
355112994Sjeff
356164936Sjulian	tdq = TDQ_CPU(cpu);
357112994Sjeff
358171713Sjeff	printf("tdq %d:\n", TDQ_ID(tdq));
359171482Sjeff	printf("\tlockptr         %p\n", TDQ_LOCKPTR(tdq));
360165620Sjeff	printf("\tload:           %d\n", tdq->tdq_load);
361171482Sjeff	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
362165766Sjeff	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
363165762Sjeff	printf("\trealtime runq:\n");
364165762Sjeff	runq_print(&tdq->tdq_realtime);
365165762Sjeff	printf("\ttimeshare runq:\n");
366165762Sjeff	runq_print(&tdq->tdq_timeshare);
367165762Sjeff	printf("\tidle runq:\n");
368165762Sjeff	runq_print(&tdq->tdq_idle);
369121896Sjeff#ifdef SMP
370165620Sjeff	printf("\tload transferable: %d\n", tdq->tdq_transferable);
371171713Sjeff	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
372171713Sjeff	printf("\tgroup:             %d\n", TDG_ID(tdq->tdq_group));
373171713Sjeff	printf("\tLock name:         %s\n", tdq->tdq_group->tdg_name);
374121896Sjeff#endif
375113357Sjeff}
376112994Sjeff
377171482Sjeff#define	TS_RQ_PPQ	(((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
378171482Sjeff/*
379171482Sjeff * Add a thread to the actual run-queue.  Keeps transferable counts up to
380171482Sjeff * date with what is actually on the run-queue.  Selects the correct
381171482Sjeff * queue position for timeshare threads.
382171482Sjeff */
383122744Sjeffstatic __inline void
384164936Sjuliantdq_runq_add(struct tdq *tdq, struct td_sched *ts, int flags)
385122744Sjeff{
386171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
387171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
388122744Sjeff#ifdef SMP
389165762Sjeff	if (THREAD_CAN_MIGRATE(ts->ts_thread)) {
390165620Sjeff		tdq->tdq_transferable++;
391165620Sjeff		tdq->tdq_group->tdg_transferable++;
392164936Sjulian		ts->ts_flags |= TSF_XFERABLE;
393123433Sjeff	}
394122744Sjeff#endif
395165762Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
396166557Sjeff		u_char pri;
397165762Sjeff
398165762Sjeff		pri = ts->ts_thread->td_priority;
399165762Sjeff		KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
400165762Sjeff			("Invalid priority %d on timeshare runq", pri));
401165762Sjeff		/*
402165762Sjeff		 * This queue contains only priorities between MIN and MAX
403165762Sjeff		 * realtime.  Use the whole queue to represent these values.
404165762Sjeff		 */
405171713Sjeff		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
406165762Sjeff			pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
407165762Sjeff			pri = (pri + tdq->tdq_idx) % RQ_NQS;
408165766Sjeff			/*
409165766Sjeff			 * This effectively shortens the queue by one so we
410165766Sjeff			 * can have a one slot difference between idx and
411165766Sjeff			 * ridx while we wait for threads to drain.
412165766Sjeff			 */
413165766Sjeff			if (tdq->tdq_ridx != tdq->tdq_idx &&
414165766Sjeff			    pri == tdq->tdq_ridx)
415167664Sjeff				pri = (unsigned char)(pri - 1) % RQ_NQS;
416165762Sjeff		} else
417165766Sjeff			pri = tdq->tdq_ridx;
418165762Sjeff		runq_add_pri(ts->ts_runq, ts, pri, flags);
419165762Sjeff	} else
420165762Sjeff		runq_add(ts->ts_runq, ts, flags);
421122744Sjeff}
422122744Sjeff
423171482Sjeff/*
424171482Sjeff * Remove a thread from a run-queue.  This typically happens when a thread
425171482Sjeff * is selected to run.  Running threads are not on the queue and the
426171482Sjeff * transferable count does not reflect them.
427171482Sjeff */
428122744Sjeffstatic __inline void
429164936Sjuliantdq_runq_rem(struct tdq *tdq, struct td_sched *ts)
430122744Sjeff{
431171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
432171482Sjeff	KASSERT(ts->ts_runq != NULL,
433171482Sjeff	    ("tdq_runq_remove: thread %p null ts_runq", ts->ts_thread));
434122744Sjeff#ifdef SMP
435164936Sjulian	if (ts->ts_flags & TSF_XFERABLE) {
436165620Sjeff		tdq->tdq_transferable--;
437165620Sjeff		tdq->tdq_group->tdg_transferable--;
438164936Sjulian		ts->ts_flags &= ~TSF_XFERABLE;
439123433Sjeff	}
440122744Sjeff#endif
441165766Sjeff	if (ts->ts_runq == &tdq->tdq_timeshare) {
442165766Sjeff		if (tdq->tdq_idx != tdq->tdq_ridx)
443165766Sjeff			runq_remove_idx(ts->ts_runq, ts, &tdq->tdq_ridx);
444165766Sjeff		else
445165766Sjeff			runq_remove_idx(ts->ts_runq, ts, NULL);
446165796Sjeff		/*
447165796Sjeff		 * For timeshare threads we update the priority here so
448165796Sjeff		 * the priority reflects the time we've been sleeping.
449165796Sjeff		 */
450165796Sjeff		ts->ts_ltick = ticks;
451165796Sjeff		sched_pctcpu_update(ts);
452165796Sjeff		sched_priority(ts->ts_thread);
453165766Sjeff	} else
454165762Sjeff		runq_remove(ts->ts_runq, ts);
455122744Sjeff}
456122744Sjeff
457171482Sjeff/*
458171482Sjeff * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
459171482Sjeff * for this thread to the referenced thread queue.
460171482Sjeff */
461113357Sjeffstatic void
462164936Sjuliantdq_load_add(struct tdq *tdq, struct td_sched *ts)
463113357Sjeff{
464121896Sjeff	int class;
465171482Sjeff
466171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
467171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
468164936Sjulian	class = PRI_BASE(ts->ts_thread->td_pri_class);
469165620Sjeff	tdq->tdq_load++;
470171713Sjeff	CTR2(KTR_SCHED, "cpu %d load: %d", TDQ_ID(tdq), tdq->tdq_load);
471166108Sjeff	if (class != PRI_ITHD &&
472166108Sjeff	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
473123487Sjeff#ifdef SMP
474165620Sjeff		tdq->tdq_group->tdg_load++;
475125289Sjeff#else
476165620Sjeff		tdq->tdq_sysload++;
477123487Sjeff#endif
478110267Sjeff}
479113357Sjeff
480171482Sjeff/*
481171482Sjeff * Remove the load from a thread that is transitioning to a sleep state or
482171482Sjeff * exiting.
483171482Sjeff */
484112994Sjeffstatic void
485164936Sjuliantdq_load_rem(struct tdq *tdq, struct td_sched *ts)
486110267Sjeff{
487121896Sjeff	int class;
488171482Sjeff
489171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
490171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
491164936Sjulian	class = PRI_BASE(ts->ts_thread->td_pri_class);
492166108Sjeff	if (class != PRI_ITHD &&
493166108Sjeff	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
494123487Sjeff#ifdef SMP
495165620Sjeff		tdq->tdq_group->tdg_load--;
496125289Sjeff#else
497165620Sjeff		tdq->tdq_sysload--;
498123487Sjeff#endif
499171482Sjeff	KASSERT(tdq->tdq_load != 0,
500171713Sjeff	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
501165620Sjeff	tdq->tdq_load--;
502165620Sjeff	CTR1(KTR_SCHED, "load: %d", tdq->tdq_load);
503164936Sjulian	ts->ts_runq = NULL;
504110267Sjeff}
505110267Sjeff
506113357Sjeff#ifdef SMP
507116069Sjeff/*
508122744Sjeff * sched_balance is a simple CPU load balancing algorithm.  It operates by
509116069Sjeff * finding the least loaded and most loaded cpu and equalizing their load
510116069Sjeff * by migrating some processes.
511116069Sjeff *
512116069Sjeff * Dealing only with two CPUs at a time has two advantages.  Firstly, most
513116069Sjeff * installations will only have 2 cpus.  Secondly, load balancing too much at
514116069Sjeff * once can have an unpleasant effect on the system.  The scheduler rarely has
515116069Sjeff * enough information to make perfect decisions.  So this algorithm chooses
516171482Sjeff * simplicity and more gradual effects on load in larger systems.
517116069Sjeff *
518116069Sjeff */
519121790Sjeffstatic void
520172409Sjeffsched_balance()
521116069Sjeff{
522164936Sjulian	struct tdq_group *high;
523164936Sjulian	struct tdq_group *low;
524165620Sjeff	struct tdq_group *tdg;
525172409Sjeff	struct tdq *tdq;
526123487Sjeff	int cnt;
527123487Sjeff	int i;
528123487Sjeff
529172409Sjeff	/*
530172409Sjeff	 * Select a random time between .5 * balance_interval and
531172409Sjeff	 * 1.5 * balance_interval.
532172409Sjeff	 */
533172409Sjeff	balance_ticks = max(balance_interval / 2, 1);
534172409Sjeff	balance_ticks += random() % balance_interval;
535171482Sjeff	if (smp_started == 0 || rebalance == 0)
536139334Sjeff		return;
537172409Sjeff	tdq = TDQ_SELF();
538172409Sjeff	TDQ_UNLOCK(tdq);
539123487Sjeff	low = high = NULL;
540165620Sjeff	i = random() % (tdg_maxid + 1);
541165620Sjeff	for (cnt = 0; cnt <= tdg_maxid; cnt++) {
542165620Sjeff		tdg = TDQ_GROUP(i);
543123487Sjeff		/*
544123487Sjeff		 * Find the CPU with the highest load that has some
545123487Sjeff		 * threads to transfer.
546123487Sjeff		 */
547165620Sjeff		if ((high == NULL || tdg->tdg_load > high->tdg_load)
548165620Sjeff		    && tdg->tdg_transferable)
549165620Sjeff			high = tdg;
550165620Sjeff		if (low == NULL || tdg->tdg_load < low->tdg_load)
551165620Sjeff			low = tdg;
552165620Sjeff		if (++i > tdg_maxid)
553123487Sjeff			i = 0;
554123487Sjeff	}
555123487Sjeff	if (low != NULL && high != NULL && high != low)
556165620Sjeff		sched_balance_pair(LIST_FIRST(&high->tdg_members),
557165620Sjeff		    LIST_FIRST(&low->tdg_members));
558172409Sjeff	TDQ_LOCK(tdq);
559123487Sjeff}
560123487Sjeff
561171482Sjeff/*
562171482Sjeff * Balance load between CPUs in a group.  Will only migrate within the group.
563171482Sjeff */
564123487Sjeffstatic void
565172409Sjeffsched_balance_groups()
566123487Sjeff{
567172409Sjeff	struct tdq *tdq;
568123487Sjeff	int i;
569123487Sjeff
570172409Sjeff	/*
571172409Sjeff	 * Select a random time between .5 * balance_interval and
572172409Sjeff	 * 1.5 * balance_interval.
573172409Sjeff	 */
574172409Sjeff	balance_group_ticks = max(balance_interval / 2, 1);
575172409Sjeff	balance_group_ticks += random() % balance_interval;
576171482Sjeff	if (smp_started == 0 || rebalance == 0)
577171482Sjeff		return;
578172409Sjeff	tdq = TDQ_SELF();
579172409Sjeff	TDQ_UNLOCK(tdq);
580171482Sjeff	for (i = 0; i <= tdg_maxid; i++)
581171482Sjeff		sched_balance_group(TDQ_GROUP(i));
582172409Sjeff	TDQ_LOCK(tdq);
583123487Sjeff}
584123487Sjeff
585171482Sjeff/*
586171482Sjeff * Finds the greatest imbalance between two tdqs in a group.
587171482Sjeff */
588123487Sjeffstatic void
589165620Sjeffsched_balance_group(struct tdq_group *tdg)
590123487Sjeff{
591164936Sjulian	struct tdq *tdq;
592164936Sjulian	struct tdq *high;
593164936Sjulian	struct tdq *low;
594123487Sjeff	int load;
595123487Sjeff
596165620Sjeff	if (tdg->tdg_transferable == 0)
597123487Sjeff		return;
598123487Sjeff	low = NULL;
599123487Sjeff	high = NULL;
600165620Sjeff	LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
601165620Sjeff		load = tdq->tdq_load;
602165620Sjeff		if (high == NULL || load > high->tdq_load)
603164936Sjulian			high = tdq;
604165620Sjeff		if (low == NULL || load < low->tdq_load)
605164936Sjulian			low = tdq;
606123487Sjeff	}
607123487Sjeff	if (high != NULL && low != NULL && high != low)
608123487Sjeff		sched_balance_pair(high, low);
609123487Sjeff}
610123487Sjeff
611171482Sjeff/*
612171482Sjeff * Lock two thread queues using their address to maintain lock order.
613171482Sjeff */
614123487Sjeffstatic void
615171482Sjefftdq_lock_pair(struct tdq *one, struct tdq *two)
616171482Sjeff{
617171482Sjeff	if (one < two) {
618171482Sjeff		TDQ_LOCK(one);
619171482Sjeff		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
620171482Sjeff	} else {
621171482Sjeff		TDQ_LOCK(two);
622171482Sjeff		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
623171482Sjeff	}
624171482Sjeff}
625171482Sjeff
626171482Sjeff/*
627172409Sjeff * Unlock two thread queues.  Order is not important here.
628172409Sjeff */
629172409Sjeffstatic void
630172409Sjefftdq_unlock_pair(struct tdq *one, struct tdq *two)
631172409Sjeff{
632172409Sjeff	TDQ_UNLOCK(one);
633172409Sjeff	TDQ_UNLOCK(two);
634172409Sjeff}
635172409Sjeff
636172409Sjeff/*
637171482Sjeff * Transfer load between two imbalanced thread queues.
638171482Sjeff */
639171482Sjeffstatic void
640164936Sjuliansched_balance_pair(struct tdq *high, struct tdq *low)
641123487Sjeff{
642123433Sjeff	int transferable;
643116069Sjeff	int high_load;
644116069Sjeff	int low_load;
645116069Sjeff	int move;
646116069Sjeff	int diff;
647116069Sjeff	int i;
648116069Sjeff
649171482Sjeff	tdq_lock_pair(high, low);
650116069Sjeff	/*
651123433Sjeff	 * If we're transfering within a group we have to use this specific
652164936Sjulian	 * tdq's transferable count, otherwise we can steal from other members
653123433Sjeff	 * of the group.
654123433Sjeff	 */
655165620Sjeff	if (high->tdq_group == low->tdq_group) {
656165620Sjeff		transferable = high->tdq_transferable;
657165620Sjeff		high_load = high->tdq_load;
658165620Sjeff		low_load = low->tdq_load;
659123487Sjeff	} else {
660165620Sjeff		transferable = high->tdq_group->tdg_transferable;
661165620Sjeff		high_load = high->tdq_group->tdg_load;
662165620Sjeff		low_load = low->tdq_group->tdg_load;
663123487Sjeff	}
664123433Sjeff	/*
665122744Sjeff	 * Determine what the imbalance is and then adjust that to how many
666165620Sjeff	 * threads we actually have to give up (transferable).
667122744Sjeff	 */
668171482Sjeff	if (transferable != 0) {
669171482Sjeff		diff = high_load - low_load;
670171482Sjeff		move = diff / 2;
671171482Sjeff		if (diff & 0x1)
672171482Sjeff			move++;
673171482Sjeff		move = min(move, transferable);
674171482Sjeff		for (i = 0; i < move; i++)
675171482Sjeff			tdq_move(high, low);
676172293Sjeff		/*
677172293Sjeff		 * IPI the target cpu to force it to reschedule with the new
678172293Sjeff		 * workload.
679172293Sjeff		 */
680172293Sjeff		ipi_selected(1 << TDQ_ID(low), IPI_PREEMPT);
681171482Sjeff	}
682172409Sjeff	tdq_unlock_pair(high, low);
683116069Sjeff	return;
684116069Sjeff}
685116069Sjeff
686171482Sjeff/*
687171482Sjeff * Move a thread from one thread queue to another.
688171482Sjeff */
689121790Sjeffstatic void
690171482Sjefftdq_move(struct tdq *from, struct tdq *to)
691116069Sjeff{
692171482Sjeff	struct td_sched *ts;
693171482Sjeff	struct thread *td;
694164936Sjulian	struct tdq *tdq;
695171482Sjeff	int cpu;
696116069Sjeff
697172409Sjeff	TDQ_LOCK_ASSERT(from, MA_OWNED);
698172409Sjeff	TDQ_LOCK_ASSERT(to, MA_OWNED);
699172409Sjeff
700164936Sjulian	tdq = from;
701171482Sjeff	cpu = TDQ_ID(to);
702172409Sjeff	ts = tdq_steal(tdq);
703164936Sjulian	if (ts == NULL) {
704165620Sjeff		struct tdq_group *tdg;
705123433Sjeff
706165620Sjeff		tdg = tdq->tdq_group;
707165620Sjeff		LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
708165620Sjeff			if (tdq == from || tdq->tdq_transferable == 0)
709123433Sjeff				continue;
710172409Sjeff			ts = tdq_steal(tdq);
711123433Sjeff			break;
712123433Sjeff		}
713164936Sjulian		if (ts == NULL)
714171482Sjeff			return;
715123433Sjeff	}
716164936Sjulian	if (tdq == to)
717123433Sjeff		return;
718171482Sjeff	td = ts->ts_thread;
719171482Sjeff	/*
720171482Sjeff	 * Although the run queue is locked the thread may be blocked.  Lock
721172409Sjeff	 * it to clear this and acquire the run-queue lock.
722171482Sjeff	 */
723171482Sjeff	thread_lock(td);
724172409Sjeff	/* Drop recursive lock on from acquired via thread_lock(). */
725171482Sjeff	TDQ_UNLOCK(from);
726171482Sjeff	sched_rem(td);
727166108Sjeff	ts->ts_cpu = cpu;
728171482Sjeff	td->td_lock = TDQ_LOCKPTR(to);
729171482Sjeff	tdq_add(to, td, SRQ_YIELDING);
730116069Sjeff}
731110267Sjeff
732171482Sjeff/*
733171482Sjeff * This tdq has idled.  Try to steal a thread from another cpu and switch
734171482Sjeff * to it.
735171482Sjeff */
736123433Sjeffstatic int
737164936Sjuliantdq_idled(struct tdq *tdq)
738121790Sjeff{
739165620Sjeff	struct tdq_group *tdg;
740164936Sjulian	struct tdq *steal;
741171482Sjeff	int highload;
742171482Sjeff	int highcpu;
743171482Sjeff	int load;
744171482Sjeff	int cpu;
745123433Sjeff
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	}
765171482Sjeff	for (;;) {
766171482Sjeff		if (steal_idle == 0)
767171482Sjeff			break;
768171482Sjeff		highcpu = 0;
769171482Sjeff		highload = 0;
770171482Sjeff		for (cpu = 0; cpu <= mp_maxid; cpu++) {
771171482Sjeff			if (CPU_ABSENT(cpu))
772171482Sjeff				continue;
773166108Sjeff			steal = TDQ_CPU(cpu);
774171482Sjeff			load = TDQ_CPU(cpu)->tdq_transferable;
775171482Sjeff			if (load < highload)
776166108Sjeff				continue;
777171482Sjeff			highload = load;
778171482Sjeff			highcpu = cpu;
779171482Sjeff		}
780171506Sjeff		if (highload < steal_thresh)
781171482Sjeff			break;
782171482Sjeff		steal = TDQ_CPU(highcpu);
783172409Sjeff		tdq_lock_pair(tdq, steal);
784172409Sjeff		if (steal->tdq_transferable >= steal_thresh)
785166108Sjeff			goto steal;
786172409Sjeff		tdq_unlock_pair(tdq, steal);
787171482Sjeff		break;
788123433Sjeff	}
789171482Sjeff	spinlock_exit();
790123433Sjeff	return (1);
791166108Sjeffsteal:
792171482Sjeff	spinlock_exit();
793172409Sjeff	tdq_move(steal, tdq);
794171482Sjeff	TDQ_UNLOCK(steal);
795171482Sjeff	mi_switch(SW_VOL, NULL);
796171482Sjeff	thread_unlock(curthread);
797121790Sjeff
798166108Sjeff	return (0);
799121790Sjeff}
800121790Sjeff
801171482Sjeff/*
802171482Sjeff * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
803171482Sjeff */
804121790Sjeffstatic void
805166108Sjefftdq_notify(struct td_sched *ts)
806121790Sjeff{
807166247Sjeff	struct thread *ctd;
808121790Sjeff	struct pcpu *pcpu;
809166247Sjeff	int cpri;
810166247Sjeff	int pri;
811166108Sjeff	int cpu;
812121790Sjeff
813166108Sjeff	cpu = ts->ts_cpu;
814166247Sjeff	pri = ts->ts_thread->td_priority;
815166108Sjeff	pcpu = pcpu_find(cpu);
816166247Sjeff	ctd = pcpu->pc_curthread;
817166247Sjeff	cpri = ctd->td_priority;
818166137Sjeff
819121790Sjeff	/*
820166137Sjeff	 * If our priority is not better than the current priority there is
821166137Sjeff	 * nothing to do.
822166137Sjeff	 */
823166247Sjeff	if (pri > cpri)
824166137Sjeff		return;
825166137Sjeff	/*
826166247Sjeff	 * Always IPI idle.
827121790Sjeff	 */
828166247Sjeff	if (cpri > PRI_MIN_IDLE)
829166247Sjeff		goto sendipi;
830166247Sjeff	/*
831166247Sjeff	 * If we're realtime or better and there is timeshare or worse running
832166247Sjeff	 * send an IPI.
833166247Sjeff	 */
834166247Sjeff	if (pri < PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
835166247Sjeff		goto sendipi;
836166247Sjeff	/*
837166247Sjeff	 * Otherwise only IPI if we exceed the threshold.
838166247Sjeff	 */
839171482Sjeff	if (pri > preempt_thresh)
840165819Sjeff		return;
841166247Sjeffsendipi:
842166247Sjeff	ctd->td_flags |= TDF_NEEDRESCHED;
843171482Sjeff	ipi_selected(1 << cpu, IPI_PREEMPT);
844121790Sjeff}
845121790Sjeff
846171482Sjeff/*
847171482Sjeff * Steals load from a timeshare queue.  Honors the rotating queue head
848171482Sjeff * index.
849171482Sjeff */
850164936Sjulianstatic struct td_sched *
851171482Sjeffrunq_steal_from(struct runq *rq, u_char start)
852171482Sjeff{
853171482Sjeff	struct td_sched *ts;
854171482Sjeff	struct rqbits *rqb;
855171482Sjeff	struct rqhead *rqh;
856171482Sjeff	int first;
857171482Sjeff	int bit;
858171482Sjeff	int pri;
859171482Sjeff	int i;
860171482Sjeff
861171482Sjeff	rqb = &rq->rq_status;
862171482Sjeff	bit = start & (RQB_BPW -1);
863171482Sjeff	pri = 0;
864171482Sjeff	first = 0;
865171482Sjeffagain:
866171482Sjeff	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
867171482Sjeff		if (rqb->rqb_bits[i] == 0)
868171482Sjeff			continue;
869171482Sjeff		if (bit != 0) {
870171482Sjeff			for (pri = bit; pri < RQB_BPW; pri++)
871171482Sjeff				if (rqb->rqb_bits[i] & (1ul << pri))
872171482Sjeff					break;
873171482Sjeff			if (pri >= RQB_BPW)
874171482Sjeff				continue;
875171482Sjeff		} else
876171482Sjeff			pri = RQB_FFS(rqb->rqb_bits[i]);
877171482Sjeff		pri += (i << RQB_L2BPW);
878171482Sjeff		rqh = &rq->rq_queues[pri];
879171482Sjeff		TAILQ_FOREACH(ts, rqh, ts_procq) {
880171482Sjeff			if (first && THREAD_CAN_MIGRATE(ts->ts_thread))
881171482Sjeff				return (ts);
882171482Sjeff			first = 1;
883171482Sjeff		}
884171482Sjeff	}
885171482Sjeff	if (start != 0) {
886171482Sjeff		start = 0;
887171482Sjeff		goto again;
888171482Sjeff	}
889171482Sjeff
890171482Sjeff	return (NULL);
891171482Sjeff}
892171482Sjeff
893171482Sjeff/*
894171482Sjeff * Steals load from a standard linear queue.
895171482Sjeff */
896171482Sjeffstatic struct td_sched *
897121790Sjeffrunq_steal(struct runq *rq)
898121790Sjeff{
899121790Sjeff	struct rqhead *rqh;
900121790Sjeff	struct rqbits *rqb;
901164936Sjulian	struct td_sched *ts;
902121790Sjeff	int word;
903121790Sjeff	int bit;
904121790Sjeff
905121790Sjeff	rqb = &rq->rq_status;
906121790Sjeff	for (word = 0; word < RQB_LEN; word++) {
907121790Sjeff		if (rqb->rqb_bits[word] == 0)
908121790Sjeff			continue;
909121790Sjeff		for (bit = 0; bit < RQB_BPW; bit++) {
910123231Speter			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
911121790Sjeff				continue;
912121790Sjeff			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
913171506Sjeff			TAILQ_FOREACH(ts, rqh, ts_procq)
914171506Sjeff				if (THREAD_CAN_MIGRATE(ts->ts_thread))
915164936Sjulian					return (ts);
916121790Sjeff		}
917121790Sjeff	}
918121790Sjeff	return (NULL);
919121790Sjeff}
920121790Sjeff
921171482Sjeff/*
922171482Sjeff * Attempt to steal a thread in priority order from a thread queue.
923171482Sjeff */
924164936Sjulianstatic struct td_sched *
925172409Sjefftdq_steal(struct tdq *tdq)
926121790Sjeff{
927164936Sjulian	struct td_sched *ts;
928121790Sjeff
929171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
930165762Sjeff	if ((ts = runq_steal(&tdq->tdq_realtime)) != NULL)
931164936Sjulian		return (ts);
932171482Sjeff	if ((ts = runq_steal_from(&tdq->tdq_timeshare, tdq->tdq_ridx)) != NULL)
933164936Sjulian		return (ts);
934172409Sjeff	return (runq_steal(&tdq->tdq_idle));
935121790Sjeff}
936123433Sjeff
937171482Sjeff/*
938171482Sjeff * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
939172409Sjeff * current lock and returns with the assigned queue locked.
940171482Sjeff */
941171482Sjeffstatic inline struct tdq *
942171482Sjeffsched_setcpu(struct td_sched *ts, int cpu, int flags)
943123433Sjeff{
944171482Sjeff	struct thread *td;
945171482Sjeff	struct tdq *tdq;
946123433Sjeff
947171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
948171482Sjeff
949171482Sjeff	tdq = TDQ_CPU(cpu);
950171482Sjeff	td = ts->ts_thread;
951171482Sjeff	ts->ts_cpu = cpu;
952171713Sjeff
953171713Sjeff	/* If the lock matches just return the queue. */
954171482Sjeff	if (td->td_lock == TDQ_LOCKPTR(tdq))
955171482Sjeff		return (tdq);
956171482Sjeff#ifdef notyet
957123433Sjeff	/*
958172293Sjeff	 * If the thread isn't running its lockptr is a
959171482Sjeff	 * turnstile or a sleepqueue.  We can just lock_set without
960171482Sjeff	 * blocking.
961123685Sjeff	 */
962171482Sjeff	if (TD_CAN_RUN(td)) {
963171482Sjeff		TDQ_LOCK(tdq);
964171482Sjeff		thread_lock_set(td, TDQ_LOCKPTR(tdq));
965171482Sjeff		return (tdq);
966171482Sjeff	}
967171482Sjeff#endif
968166108Sjeff	/*
969171482Sjeff	 * The hard case, migration, we need to block the thread first to
970171482Sjeff	 * prevent order reversals with other cpus locks.
971166108Sjeff	 */
972171482Sjeff	thread_lock_block(td);
973171482Sjeff	TDQ_LOCK(tdq);
974171713Sjeff	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
975171482Sjeff	return (tdq);
976166108Sjeff}
977166108Sjeff
978171482Sjeff/*
979171482Sjeff * Find the thread queue running the lowest priority thread.
980171482Sjeff */
981166108Sjeffstatic int
982171482Sjefftdq_lowestpri(void)
983166108Sjeff{
984171482Sjeff	struct tdq *tdq;
985166108Sjeff	int lowpri;
986166108Sjeff	int lowcpu;
987166108Sjeff	int lowload;
988166108Sjeff	int load;
989171482Sjeff	int cpu;
990171482Sjeff	int pri;
991171482Sjeff
992171482Sjeff	lowload = 0;
993171482Sjeff	lowpri = lowcpu = 0;
994171482Sjeff	for (cpu = 0; cpu <= mp_maxid; cpu++) {
995171482Sjeff		if (CPU_ABSENT(cpu))
996171482Sjeff			continue;
997171482Sjeff		tdq = TDQ_CPU(cpu);
998171482Sjeff		pri = tdq->tdq_lowpri;
999171482Sjeff		load = TDQ_CPU(cpu)->tdq_load;
1000171482Sjeff		CTR4(KTR_ULE,
1001171482Sjeff		    "cpu %d pri %d lowcpu %d lowpri %d",
1002171482Sjeff		    cpu, pri, lowcpu, lowpri);
1003171482Sjeff		if (pri < lowpri)
1004171482Sjeff			continue;
1005171482Sjeff		if (lowpri && lowpri == pri && load > lowload)
1006171482Sjeff			continue;
1007171482Sjeff		lowpri = pri;
1008171482Sjeff		lowcpu = cpu;
1009171482Sjeff		lowload = load;
1010171482Sjeff	}
1011171482Sjeff
1012171482Sjeff	return (lowcpu);
1013171482Sjeff}
1014171482Sjeff
1015171482Sjeff/*
1016171482Sjeff * Find the thread queue with the least load.
1017171482Sjeff */
1018171482Sjeffstatic int
1019171482Sjefftdq_lowestload(void)
1020171482Sjeff{
1021171482Sjeff	struct tdq *tdq;
1022171482Sjeff	int lowload;
1023171482Sjeff	int lowpri;
1024171482Sjeff	int lowcpu;
1025171482Sjeff	int load;
1026171482Sjeff	int cpu;
1027171482Sjeff	int pri;
1028171482Sjeff
1029171482Sjeff	lowcpu = 0;
1030171482Sjeff	lowload = TDQ_CPU(0)->tdq_load;
1031171482Sjeff	lowpri = TDQ_CPU(0)->tdq_lowpri;
1032171482Sjeff	for (cpu = 1; cpu <= mp_maxid; cpu++) {
1033171482Sjeff		if (CPU_ABSENT(cpu))
1034171482Sjeff			continue;
1035171482Sjeff		tdq = TDQ_CPU(cpu);
1036171482Sjeff		load = tdq->tdq_load;
1037171482Sjeff		pri = tdq->tdq_lowpri;
1038171482Sjeff		CTR4(KTR_ULE, "cpu %d load %d lowcpu %d lowload %d",
1039171482Sjeff		    cpu, load, lowcpu, lowload);
1040171482Sjeff		if (load > lowload)
1041171482Sjeff			continue;
1042171482Sjeff		if (load == lowload && pri < lowpri)
1043171482Sjeff			continue;
1044171482Sjeff		lowcpu = cpu;
1045171482Sjeff		lowload = load;
1046171482Sjeff		lowpri = pri;
1047171482Sjeff	}
1048171482Sjeff
1049171482Sjeff	return (lowcpu);
1050171482Sjeff}
1051171482Sjeff
1052171482Sjeff/*
1053171482Sjeff * Pick the destination cpu for sched_add().  Respects affinity and makes
1054171482Sjeff * a determination based on load or priority of available processors.
1055171482Sjeff */
1056171482Sjeffstatic int
1057171482Sjeffsched_pickcpu(struct td_sched *ts, int flags)
1058171482Sjeff{
1059171482Sjeff	struct tdq *tdq;
1060166108Sjeff	int self;
1061166108Sjeff	int pri;
1062166108Sjeff	int cpu;
1063166108Sjeff
1064171482Sjeff	cpu = self = PCPU_GET(cpuid);
1065166108Sjeff	if (smp_started == 0)
1066166108Sjeff		return (self);
1067171506Sjeff	/*
1068171506Sjeff	 * Don't migrate a running thread from sched_switch().
1069171506Sjeff	 */
1070171506Sjeff	if (flags & SRQ_OURSELF) {
1071171506Sjeff		CTR1(KTR_ULE, "YIELDING %d",
1072171506Sjeff		    curthread->td_priority);
1073171506Sjeff		return (self);
1074171506Sjeff	}
1075166108Sjeff	pri = ts->ts_thread->td_priority;
1076171482Sjeff	cpu = ts->ts_cpu;
1077166108Sjeff	/*
1078166108Sjeff	 * Regardless of affinity, if the last cpu is idle send it there.
1079166108Sjeff	 */
1080171482Sjeff	tdq = TDQ_CPU(cpu);
1081171482Sjeff	if (tdq->tdq_lowpri > PRI_MIN_IDLE) {
1082166229Sjeff		CTR5(KTR_ULE,
1083166108Sjeff		    "ts_cpu %d idle, ltick %d ticks %d pri %d curthread %d",
1084166108Sjeff		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1085171482Sjeff		    tdq->tdq_lowpri);
1086166108Sjeff		return (ts->ts_cpu);
1087123433Sjeff	}
1088166108Sjeff	/*
1089166108Sjeff	 * If we have affinity, try to place it on the cpu we last ran on.
1090166108Sjeff	 */
1091171482Sjeff	if (SCHED_AFFINITY(ts) && tdq->tdq_lowpri > pri) {
1092166229Sjeff		CTR5(KTR_ULE,
1093166108Sjeff		    "affinity for %d, ltick %d ticks %d pri %d curthread %d",
1094166108Sjeff		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1095171482Sjeff		    tdq->tdq_lowpri);
1096166108Sjeff		return (ts->ts_cpu);
1097139334Sjeff	}
1098123433Sjeff	/*
1099166108Sjeff	 * Look for an idle group.
1100123433Sjeff	 */
1101166229Sjeff	CTR1(KTR_ULE, "tdq_idle %X", tdq_idle);
1102166108Sjeff	cpu = ffs(tdq_idle);
1103166108Sjeff	if (cpu)
1104171482Sjeff		return (--cpu);
1105171506Sjeff	/*
1106172409Sjeff	 * If there are no idle cores see if we can run the thread locally.
1107172409Sjeff	 * This may improve locality among sleepers and wakers when there
1108172409Sjeff	 * is shared data.
1109171506Sjeff	 */
1110171506Sjeff	if (tryself && pri < curthread->td_priority) {
1111171506Sjeff		CTR1(KTR_ULE, "tryself %d",
1112166108Sjeff		    curthread->td_priority);
1113166108Sjeff		return (self);
1114123433Sjeff	}
1115133427Sjeff	/*
1116166108Sjeff 	 * Now search for the cpu running the lowest priority thread with
1117166108Sjeff	 * the least load.
1118123433Sjeff	 */
1119171482Sjeff	if (pick_pri)
1120171482Sjeff		cpu = tdq_lowestpri();
1121171482Sjeff	else
1122171482Sjeff		cpu = tdq_lowestload();
1123171482Sjeff	return (cpu);
1124123433Sjeff}
1125123433Sjeff
1126121790Sjeff#endif	/* SMP */
1127121790Sjeff
1128117326Sjeff/*
1129121790Sjeff * Pick the highest priority task we have and return it.
1130117326Sjeff */
1131164936Sjulianstatic struct td_sched *
1132164936Sjuliantdq_choose(struct tdq *tdq)
1133110267Sjeff{
1134164936Sjulian	struct td_sched *ts;
1135110267Sjeff
1136171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1137165762Sjeff	ts = runq_choose(&tdq->tdq_realtime);
1138170787Sjeff	if (ts != NULL)
1139164936Sjulian		return (ts);
1140165766Sjeff	ts = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1141165762Sjeff	if (ts != NULL) {
1142170787Sjeff		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_TIMESHARE,
1143165762Sjeff		    ("tdq_choose: Invalid priority on timeshare queue %d",
1144165762Sjeff		    ts->ts_thread->td_priority));
1145165762Sjeff		return (ts);
1146165762Sjeff	}
1147110267Sjeff
1148165762Sjeff	ts = runq_choose(&tdq->tdq_idle);
1149165762Sjeff	if (ts != NULL) {
1150165762Sjeff		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_IDLE,
1151165762Sjeff		    ("tdq_choose: Invalid priority on idle queue %d",
1152165762Sjeff		    ts->ts_thread->td_priority));
1153165762Sjeff		return (ts);
1154165762Sjeff	}
1155165762Sjeff
1156165762Sjeff	return (NULL);
1157110267Sjeff}
1158110267Sjeff
1159171482Sjeff/*
1160171482Sjeff * Initialize a thread queue.
1161171482Sjeff */
1162109864Sjeffstatic void
1163164936Sjuliantdq_setup(struct tdq *tdq)
1164110028Sjeff{
1165171482Sjeff
1166171713Sjeff	if (bootverbose)
1167171713Sjeff		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1168165762Sjeff	runq_init(&tdq->tdq_realtime);
1169165762Sjeff	runq_init(&tdq->tdq_timeshare);
1170165620Sjeff	runq_init(&tdq->tdq_idle);
1171165620Sjeff	tdq->tdq_load = 0;
1172110028Sjeff}
1173110028Sjeff
1174171713Sjeff#ifdef SMP
1175110028Sjeffstatic void
1176171713Sjefftdg_setup(struct tdq_group *tdg)
1177109864Sjeff{
1178171713Sjeff	if (bootverbose)
1179171713Sjeff		printf("ULE: setup cpu group %d\n", TDG_ID(tdg));
1180171713Sjeff	snprintf(tdg->tdg_name, sizeof(tdg->tdg_name),
1181171713Sjeff	    "sched lock %d", (int)TDG_ID(tdg));
1182171713Sjeff	mtx_init(&tdg->tdg_lock, tdg->tdg_name, "sched lock",
1183171713Sjeff	    MTX_SPIN | MTX_RECURSE);
1184171713Sjeff	LIST_INIT(&tdg->tdg_members);
1185171713Sjeff	tdg->tdg_load = 0;
1186171713Sjeff	tdg->tdg_transferable = 0;
1187171713Sjeff	tdg->tdg_cpus = 0;
1188171713Sjeff	tdg->tdg_mask = 0;
1189171713Sjeff	tdg->tdg_cpumask = 0;
1190171713Sjeff	tdg->tdg_idlemask = 0;
1191171713Sjeff}
1192171713Sjeff
1193171713Sjeffstatic void
1194171713Sjefftdg_add(struct tdq_group *tdg, struct tdq *tdq)
1195171713Sjeff{
1196171713Sjeff	if (tdg->tdg_mask == 0)
1197171713Sjeff		tdg->tdg_mask |= 1 << TDQ_ID(tdq);
1198171713Sjeff	tdg->tdg_cpumask |= 1 << TDQ_ID(tdq);
1199171713Sjeff	tdg->tdg_cpus++;
1200171713Sjeff	tdq->tdq_group = tdg;
1201171713Sjeff	tdq->tdq_lock = &tdg->tdg_lock;
1202171713Sjeff	LIST_INSERT_HEAD(&tdg->tdg_members, tdq, tdq_siblings);
1203171713Sjeff	if (bootverbose)
1204171713Sjeff		printf("ULE: adding cpu %d to group %d: cpus %d mask 0x%X\n",
1205171713Sjeff		    TDQ_ID(tdq), TDG_ID(tdg), tdg->tdg_cpus, tdg->tdg_cpumask);
1206171713Sjeff}
1207171713Sjeff
1208171713Sjeffstatic void
1209171713Sjeffsched_setup_topology(void)
1210171713Sjeff{
1211171713Sjeff	struct tdq_group *tdg;
1212171713Sjeff	struct cpu_group *cg;
1213171713Sjeff	int balance_groups;
1214171482Sjeff	struct tdq *tdq;
1215109864Sjeff	int i;
1216171713Sjeff	int j;
1217109864Sjeff
1218171713Sjeff	topology = 1;
1219123487Sjeff	balance_groups = 0;
1220171713Sjeff	for (i = 0; i < smp_topology->ct_count; i++) {
1221171713Sjeff		cg = &smp_topology->ct_group[i];
1222171713Sjeff		tdg = &tdq_groups[i];
1223171713Sjeff		/*
1224171713Sjeff		 * Initialize the group.
1225171713Sjeff		 */
1226171713Sjeff		tdg_setup(tdg);
1227171713Sjeff		/*
1228171713Sjeff		 * Find all of the group members and add them.
1229171713Sjeff		 */
1230171713Sjeff		for (j = 0; j < MAXCPU; j++) {
1231171713Sjeff			if ((cg->cg_mask & (1 << j)) != 0) {
1232171713Sjeff				tdq = TDQ_CPU(j);
1233171713Sjeff				tdq_setup(tdq);
1234171713Sjeff				tdg_add(tdg, tdq);
1235171713Sjeff			}
1236171713Sjeff		}
1237171713Sjeff		if (tdg->tdg_cpus > 1)
1238171713Sjeff			balance_groups = 1;
1239171713Sjeff	}
1240171713Sjeff	tdg_maxid = smp_topology->ct_count - 1;
1241171713Sjeff	if (balance_groups)
1242172409Sjeff		sched_balance_groups();
1243171713Sjeff}
1244171713Sjeff
1245171713Sjeffstatic void
1246171713Sjeffsched_setup_smp(void)
1247171713Sjeff{
1248171713Sjeff	struct tdq_group *tdg;
1249171713Sjeff	struct tdq *tdq;
1250171713Sjeff	int cpus;
1251171713Sjeff	int i;
1252171713Sjeff
1253171713Sjeff	for (cpus = 0, i = 0; i < MAXCPU; i++) {
1254171713Sjeff		if (CPU_ABSENT(i))
1255171713Sjeff			continue;
1256165627Sjeff		tdq = &tdq_cpu[i];
1257171713Sjeff		tdg = &tdq_groups[i];
1258171713Sjeff		/*
1259171713Sjeff		 * Setup a tdq group with one member.
1260171713Sjeff		 */
1261171713Sjeff		tdg_setup(tdg);
1262171713Sjeff		tdq_setup(tdq);
1263171713Sjeff		tdg_add(tdg, tdq);
1264171713Sjeff		cpus++;
1265123433Sjeff	}
1266171713Sjeff	tdg_maxid = cpus - 1;
1267171713Sjeff}
1268123433Sjeff
1269171713Sjeff/*
1270171713Sjeff * Fake a topology with one group containing all CPUs.
1271171713Sjeff */
1272171713Sjeffstatic void
1273171713Sjeffsched_fake_topo(void)
1274171713Sjeff{
1275171713Sjeff#ifdef SCHED_FAKE_TOPOLOGY
1276171713Sjeff	static struct cpu_top top;
1277171713Sjeff	static struct cpu_group group;
1278113357Sjeff
1279171713Sjeff	top.ct_count = 1;
1280171713Sjeff	top.ct_group = &group;
1281171713Sjeff	group.cg_mask = all_cpus;
1282171713Sjeff	group.cg_count = mp_ncpus;
1283171713Sjeff	group.cg_children = 0;
1284171713Sjeff	smp_topology = &top;
1285171713Sjeff#endif
1286171713Sjeff}
1287171713Sjeff#endif
1288171713Sjeff
1289171713Sjeff/*
1290171713Sjeff * Setup the thread queues and initialize the topology based on MD
1291171713Sjeff * information.
1292171713Sjeff */
1293171713Sjeffstatic void
1294171713Sjeffsched_setup(void *dummy)
1295171713Sjeff{
1296171713Sjeff	struct tdq *tdq;
1297171713Sjeff
1298171713Sjeff	tdq = TDQ_SELF();
1299171713Sjeff#ifdef SMP
1300171713Sjeff	sched_fake_topo();
1301171713Sjeff	/*
1302171713Sjeff	 * Setup tdqs based on a topology configuration or vanilla SMP based
1303171713Sjeff	 * on mp_maxid.
1304171713Sjeff	 */
1305171713Sjeff	if (smp_topology == NULL)
1306171713Sjeff		sched_setup_smp();
1307171713Sjeff	else
1308171713Sjeff		sched_setup_topology();
1309172409Sjeff	balance_tdq = tdq;
1310172409Sjeff	sched_balance();
1311117237Sjeff#else
1312171713Sjeff	tdq_setup(tdq);
1313171713Sjeff	mtx_init(&tdq_lock, "sched lock", "sched lock", MTX_SPIN | MTX_RECURSE);
1314171713Sjeff	tdq->tdq_lock = &tdq_lock;
1315116069Sjeff#endif
1316171482Sjeff	/*
1317171482Sjeff	 * To avoid divide-by-zero, we set realstathz a dummy value
1318171482Sjeff	 * in case which sched_clock() called before sched_initticks().
1319171482Sjeff	 */
1320171482Sjeff	realstathz = hz;
1321171482Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1322171482Sjeff	tickincr = 1 << SCHED_TICK_SHIFT;
1323171482Sjeff
1324171482Sjeff	/* Add thread0's load since it's running. */
1325171482Sjeff	TDQ_LOCK(tdq);
1326171713Sjeff	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1327171482Sjeff	tdq_load_add(tdq, &td_sched0);
1328171482Sjeff	TDQ_UNLOCK(tdq);
1329109864Sjeff}
1330109864Sjeff
1331171482Sjeff/*
1332171482Sjeff * This routine determines the tickincr after stathz and hz are setup.
1333171482Sjeff */
1334153533Sdavidxu/* ARGSUSED */
1335153533Sdavidxustatic void
1336153533Sdavidxusched_initticks(void *dummy)
1337153533Sdavidxu{
1338171482Sjeff	int incr;
1339171482Sjeff
1340153533Sdavidxu	realstathz = stathz ? stathz : hz;
1341166229Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1342153533Sdavidxu
1343153533Sdavidxu	/*
1344165762Sjeff	 * tickincr is shifted out by 10 to avoid rounding errors due to
1345165766Sjeff	 * hz not being evenly divisible by stathz on all platforms.
1346153533Sdavidxu	 */
1347171482Sjeff	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1348165762Sjeff	/*
1349165762Sjeff	 * This does not work for values of stathz that are more than
1350165762Sjeff	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1351165762Sjeff	 */
1352171482Sjeff	if (incr == 0)
1353171482Sjeff		incr = 1;
1354171482Sjeff	tickincr = incr;
1355166108Sjeff#ifdef SMP
1356171899Sjeff	/*
1357172409Sjeff	 * Set the default balance interval now that we know
1358172409Sjeff	 * what realstathz is.
1359172409Sjeff	 */
1360172409Sjeff	balance_interval = realstathz;
1361172409Sjeff	/*
1362171899Sjeff	 * Set steal thresh to log2(mp_ncpu) but no greater than 4.  This
1363171899Sjeff	 * prevents excess thrashing on large machines and excess idle on
1364171899Sjeff	 * smaller machines.
1365171899Sjeff	 */
1366171899Sjeff	steal_thresh = min(ffs(mp_ncpus) - 1, 4);
1367166108Sjeff	affinity = SCHED_AFFINITY_DEFAULT;
1368166108Sjeff#endif
1369153533Sdavidxu}
1370153533Sdavidxu
1371153533Sdavidxu
1372109864Sjeff/*
1373171482Sjeff * This is the core of the interactivity algorithm.  Determines a score based
1374171482Sjeff * on past behavior.  It is the ratio of sleep time to run time scaled to
1375171482Sjeff * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1376171482Sjeff * differs from the cpu usage because it does not account for time spent
1377171482Sjeff * waiting on a run-queue.  Would be prettier if we had floating point.
1378171482Sjeff */
1379171482Sjeffstatic int
1380171482Sjeffsched_interact_score(struct thread *td)
1381171482Sjeff{
1382171482Sjeff	struct td_sched *ts;
1383171482Sjeff	int div;
1384171482Sjeff
1385171482Sjeff	ts = td->td_sched;
1386171482Sjeff	/*
1387171482Sjeff	 * The score is only needed if this is likely to be an interactive
1388171482Sjeff	 * task.  Don't go through the expense of computing it if there's
1389171482Sjeff	 * no chance.
1390171482Sjeff	 */
1391171482Sjeff	if (sched_interact <= SCHED_INTERACT_HALF &&
1392171482Sjeff		ts->ts_runtime >= ts->ts_slptime)
1393171482Sjeff			return (SCHED_INTERACT_HALF);
1394171482Sjeff
1395171482Sjeff	if (ts->ts_runtime > ts->ts_slptime) {
1396171482Sjeff		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1397171482Sjeff		return (SCHED_INTERACT_HALF +
1398171482Sjeff		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1399171482Sjeff	}
1400171482Sjeff	if (ts->ts_slptime > ts->ts_runtime) {
1401171482Sjeff		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1402171482Sjeff		return (ts->ts_runtime / div);
1403171482Sjeff	}
1404171482Sjeff	/* runtime == slptime */
1405171482Sjeff	if (ts->ts_runtime)
1406171482Sjeff		return (SCHED_INTERACT_HALF);
1407171482Sjeff
1408171482Sjeff	/*
1409171482Sjeff	 * This can happen if slptime and runtime are 0.
1410171482Sjeff	 */
1411171482Sjeff	return (0);
1412171482Sjeff
1413171482Sjeff}
1414171482Sjeff
1415171482Sjeff/*
1416109864Sjeff * Scale the scheduling priority according to the "interactivity" of this
1417109864Sjeff * process.
1418109864Sjeff */
1419113357Sjeffstatic void
1420163709Sjbsched_priority(struct thread *td)
1421109864Sjeff{
1422165762Sjeff	int score;
1423109864Sjeff	int pri;
1424109864Sjeff
1425163709Sjb	if (td->td_pri_class != PRI_TIMESHARE)
1426113357Sjeff		return;
1427112966Sjeff	/*
1428165762Sjeff	 * If the score is interactive we place the thread in the realtime
1429165762Sjeff	 * queue with a priority that is less than kernel and interrupt
1430165762Sjeff	 * priorities.  These threads are not subject to nice restrictions.
1431112966Sjeff	 *
1432171482Sjeff	 * Scores greater than this are placed on the normal timeshare queue
1433165762Sjeff	 * where the priority is partially decided by the most recent cpu
1434165762Sjeff	 * utilization and the rest is decided by nice value.
1435172293Sjeff	 *
1436172293Sjeff	 * The nice value of the process has a linear effect on the calculated
1437172293Sjeff	 * score.  Negative nice values make it easier for a thread to be
1438172293Sjeff	 * considered interactive.
1439112966Sjeff	 */
1440172308Sjeff	score = imax(0, sched_interact_score(td) - td->td_proc->p_nice);
1441165762Sjeff	if (score < sched_interact) {
1442165762Sjeff		pri = PRI_MIN_REALTIME;
1443165762Sjeff		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1444165762Sjeff		    * score;
1445165762Sjeff		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1446166208Sjeff		    ("sched_priority: invalid interactive priority %d score %d",
1447166208Sjeff		    pri, score));
1448165762Sjeff	} else {
1449165762Sjeff		pri = SCHED_PRI_MIN;
1450165762Sjeff		if (td->td_sched->ts_ticks)
1451165762Sjeff			pri += SCHED_PRI_TICKS(td->td_sched);
1452165762Sjeff		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1453171482Sjeff		KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1454171482Sjeff		    ("sched_priority: invalid priority %d: nice %d, "
1455171482Sjeff		    "ticks %d ftick %d ltick %d tick pri %d",
1456171482Sjeff		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1457171482Sjeff		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1458171482Sjeff		    SCHED_PRI_TICKS(td->td_sched)));
1459165762Sjeff	}
1460165762Sjeff	sched_user_prio(td, pri);
1461112966Sjeff
1462112966Sjeff	return;
1463109864Sjeff}
1464109864Sjeff
1465121868Sjeff/*
1466121868Sjeff * This routine enforces a maximum limit on the amount of scheduling history
1467171482Sjeff * kept.  It is called after either the slptime or runtime is adjusted.  This
1468171482Sjeff * function is ugly due to integer math.
1469121868Sjeff */
1470116463Sjeffstatic void
1471163709Sjbsched_interact_update(struct thread *td)
1472116463Sjeff{
1473165819Sjeff	struct td_sched *ts;
1474166208Sjeff	u_int sum;
1475121605Sjeff
1476165819Sjeff	ts = td->td_sched;
1477171482Sjeff	sum = ts->ts_runtime + ts->ts_slptime;
1478121868Sjeff	if (sum < SCHED_SLP_RUN_MAX)
1479121868Sjeff		return;
1480121868Sjeff	/*
1481165819Sjeff	 * This only happens from two places:
1482165819Sjeff	 * 1) We have added an unusual amount of run time from fork_exit.
1483165819Sjeff	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1484165819Sjeff	 */
1485165819Sjeff	if (sum > SCHED_SLP_RUN_MAX * 2) {
1486171482Sjeff		if (ts->ts_runtime > ts->ts_slptime) {
1487171482Sjeff			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1488171482Sjeff			ts->ts_slptime = 1;
1489165819Sjeff		} else {
1490171482Sjeff			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1491171482Sjeff			ts->ts_runtime = 1;
1492165819Sjeff		}
1493165819Sjeff		return;
1494165819Sjeff	}
1495165819Sjeff	/*
1496121868Sjeff	 * If we have exceeded by more than 1/5th then the algorithm below
1497121868Sjeff	 * will not bring us back into range.  Dividing by two here forces
1498133427Sjeff	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1499121868Sjeff	 */
1500127850Sjeff	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1501171482Sjeff		ts->ts_runtime /= 2;
1502171482Sjeff		ts->ts_slptime /= 2;
1503121868Sjeff		return;
1504116463Sjeff	}
1505171482Sjeff	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1506171482Sjeff	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1507116463Sjeff}
1508116463Sjeff
1509171482Sjeff/*
1510171482Sjeff * Scale back the interactivity history when a child thread is created.  The
1511171482Sjeff * history is inherited from the parent but the thread may behave totally
1512171482Sjeff * differently.  For example, a shell spawning a compiler process.  We want
1513171482Sjeff * to learn that the compiler is behaving badly very quickly.
1514171482Sjeff */
1515121868Sjeffstatic void
1516163709Sjbsched_interact_fork(struct thread *td)
1517121868Sjeff{
1518121868Sjeff	int ratio;
1519121868Sjeff	int sum;
1520121868Sjeff
1521171482Sjeff	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1522121868Sjeff	if (sum > SCHED_SLP_RUN_FORK) {
1523121868Sjeff		ratio = sum / SCHED_SLP_RUN_FORK;
1524171482Sjeff		td->td_sched->ts_runtime /= ratio;
1525171482Sjeff		td->td_sched->ts_slptime /= ratio;
1526121868Sjeff	}
1527121868Sjeff}
1528121868Sjeff
1529113357Sjeff/*
1530171482Sjeff * Called from proc0_init() to setup the scheduler fields.
1531134791Sjulian */
1532134791Sjulianvoid
1533134791Sjulianschedinit(void)
1534134791Sjulian{
1535165762Sjeff
1536134791Sjulian	/*
1537134791Sjulian	 * Set up the scheduler specific parts of proc0.
1538134791Sjulian	 */
1539136167Sjulian	proc0.p_sched = NULL; /* XXX */
1540164936Sjulian	thread0.td_sched = &td_sched0;
1541165762Sjeff	td_sched0.ts_ltick = ticks;
1542165796Sjeff	td_sched0.ts_ftick = ticks;
1543164936Sjulian	td_sched0.ts_thread = &thread0;
1544134791Sjulian}
1545134791Sjulian
1546134791Sjulian/*
1547113357Sjeff * This is only somewhat accurate since given many processes of the same
1548113357Sjeff * priority they will switch when their slices run out, which will be
1549165762Sjeff * at most sched_slice stathz ticks.
1550113357Sjeff */
1551109864Sjeffint
1552109864Sjeffsched_rr_interval(void)
1553109864Sjeff{
1554165762Sjeff
1555165762Sjeff	/* Convert sched_slice to hz */
1556165762Sjeff	return (hz/(realstathz/sched_slice));
1557109864Sjeff}
1558109864Sjeff
1559171482Sjeff/*
1560171482Sjeff * Update the percent cpu tracking information when it is requested or
1561171482Sjeff * the total history exceeds the maximum.  We keep a sliding history of
1562171482Sjeff * tick counts that slowly decays.  This is less precise than the 4BSD
1563171482Sjeff * mechanism since it happens with less regular and frequent events.
1564171482Sjeff */
1565121790Sjeffstatic void
1566164936Sjuliansched_pctcpu_update(struct td_sched *ts)
1567109864Sjeff{
1568165762Sjeff
1569165762Sjeff	if (ts->ts_ticks == 0)
1570165762Sjeff		return;
1571165796Sjeff	if (ticks - (hz / 10) < ts->ts_ltick &&
1572165796Sjeff	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1573165796Sjeff		return;
1574109864Sjeff	/*
1575109864Sjeff	 * Adjust counters and watermark for pctcpu calc.
1576116365Sjeff	 */
1577165762Sjeff	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1578164936Sjulian		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1579165762Sjeff			    SCHED_TICK_TARG;
1580165762Sjeff	else
1581164936Sjulian		ts->ts_ticks = 0;
1582164936Sjulian	ts->ts_ltick = ticks;
1583165762Sjeff	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1584109864Sjeff}
1585109864Sjeff
1586171482Sjeff/*
1587171482Sjeff * Adjust the priority of a thread.  Move it to the appropriate run-queue
1588171482Sjeff * if necessary.  This is the back-end for several priority related
1589171482Sjeff * functions.
1590171482Sjeff */
1591165762Sjeffstatic void
1592139453Sjhbsched_thread_priority(struct thread *td, u_char prio)
1593109864Sjeff{
1594164936Sjulian	struct td_sched *ts;
1595109864Sjeff
1596139316Sjeff	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
1597139316Sjeff	    td, td->td_proc->p_comm, td->td_priority, prio, curthread,
1598139316Sjeff	    curthread->td_proc->p_comm);
1599164936Sjulian	ts = td->td_sched;
1600170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1601139453Sjhb	if (td->td_priority == prio)
1602139453Sjhb		return;
1603165762Sjeff
1604165766Sjeff	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1605121605Sjeff		/*
1606121605Sjeff		 * If the priority has been elevated due to priority
1607121605Sjeff		 * propagation, we may have to move ourselves to a new
1608165762Sjeff		 * queue.  This could be optimized to not re-add in some
1609165762Sjeff		 * cases.
1610133555Sjeff		 */
1611165762Sjeff		sched_rem(td);
1612165762Sjeff		td->td_priority = prio;
1613171482Sjeff		sched_add(td, SRQ_BORROWING);
1614171482Sjeff	} else {
1615171482Sjeff#ifdef SMP
1616171482Sjeff		struct tdq *tdq;
1617171482Sjeff
1618171482Sjeff		tdq = TDQ_CPU(ts->ts_cpu);
1619171482Sjeff		if (prio < tdq->tdq_lowpri)
1620171482Sjeff			tdq->tdq_lowpri = prio;
1621171482Sjeff#endif
1622119488Sdavidxu		td->td_priority = prio;
1623171482Sjeff	}
1624109864Sjeff}
1625109864Sjeff
1626139453Sjhb/*
1627139453Sjhb * Update a thread's priority when it is lent another thread's
1628139453Sjhb * priority.
1629139453Sjhb */
1630109864Sjeffvoid
1631139453Sjhbsched_lend_prio(struct thread *td, u_char prio)
1632139453Sjhb{
1633139453Sjhb
1634139453Sjhb	td->td_flags |= TDF_BORROWING;
1635139453Sjhb	sched_thread_priority(td, prio);
1636139453Sjhb}
1637139453Sjhb
1638139453Sjhb/*
1639139453Sjhb * Restore a thread's priority when priority propagation is
1640139453Sjhb * over.  The prio argument is the minimum priority the thread
1641139453Sjhb * needs to have to satisfy other possible priority lending
1642139453Sjhb * requests.  If the thread's regular priority is less
1643139453Sjhb * important than prio, the thread will keep a priority boost
1644139453Sjhb * of prio.
1645139453Sjhb */
1646139453Sjhbvoid
1647139453Sjhbsched_unlend_prio(struct thread *td, u_char prio)
1648139453Sjhb{
1649139453Sjhb	u_char base_pri;
1650139453Sjhb
1651139453Sjhb	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1652139453Sjhb	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1653163709Sjb		base_pri = td->td_user_pri;
1654139453Sjhb	else
1655139453Sjhb		base_pri = td->td_base_pri;
1656139453Sjhb	if (prio >= base_pri) {
1657139455Sjhb		td->td_flags &= ~TDF_BORROWING;
1658139453Sjhb		sched_thread_priority(td, base_pri);
1659139453Sjhb	} else
1660139453Sjhb		sched_lend_prio(td, prio);
1661139453Sjhb}
1662139453Sjhb
1663171482Sjeff/*
1664171482Sjeff * Standard entry for setting the priority to an absolute value.
1665171482Sjeff */
1666139453Sjhbvoid
1667139453Sjhbsched_prio(struct thread *td, u_char prio)
1668139453Sjhb{
1669139453Sjhb	u_char oldprio;
1670139453Sjhb
1671139453Sjhb	/* First, update the base priority. */
1672139453Sjhb	td->td_base_pri = prio;
1673139453Sjhb
1674139453Sjhb	/*
1675139455Sjhb	 * If the thread is borrowing another thread's priority, don't
1676139453Sjhb	 * ever lower the priority.
1677139453Sjhb	 */
1678139453Sjhb	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1679139453Sjhb		return;
1680139453Sjhb
1681139453Sjhb	/* Change the real priority. */
1682139453Sjhb	oldprio = td->td_priority;
1683139453Sjhb	sched_thread_priority(td, prio);
1684139453Sjhb
1685139453Sjhb	/*
1686139453Sjhb	 * If the thread is on a turnstile, then let the turnstile update
1687139453Sjhb	 * its state.
1688139453Sjhb	 */
1689139453Sjhb	if (TD_ON_LOCK(td) && oldprio != prio)
1690139453Sjhb		turnstile_adjust(td, oldprio);
1691139453Sjhb}
1692139455Sjhb
1693171482Sjeff/*
1694171482Sjeff * Set the base user priority, does not effect current running priority.
1695171482Sjeff */
1696139453Sjhbvoid
1697163709Sjbsched_user_prio(struct thread *td, u_char prio)
1698161599Sdavidxu{
1699161599Sdavidxu	u_char oldprio;
1700161599Sdavidxu
1701163709Sjb	td->td_base_user_pri = prio;
1702164939Sjulian	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1703164939Sjulian                return;
1704163709Sjb	oldprio = td->td_user_pri;
1705163709Sjb	td->td_user_pri = prio;
1706163709Sjb
1707161599Sdavidxu	if (TD_ON_UPILOCK(td) && oldprio != prio)
1708161599Sdavidxu		umtx_pi_adjust(td, oldprio);
1709161599Sdavidxu}
1710161599Sdavidxu
1711161599Sdavidxuvoid
1712161599Sdavidxusched_lend_user_prio(struct thread *td, u_char prio)
1713161599Sdavidxu{
1714161599Sdavidxu	u_char oldprio;
1715161599Sdavidxu
1716161599Sdavidxu	td->td_flags |= TDF_UBORROWING;
1717161599Sdavidxu
1718164091Smaxim	oldprio = td->td_user_pri;
1719163709Sjb	td->td_user_pri = prio;
1720161599Sdavidxu
1721161599Sdavidxu	if (TD_ON_UPILOCK(td) && oldprio != prio)
1722161599Sdavidxu		umtx_pi_adjust(td, oldprio);
1723161599Sdavidxu}
1724161599Sdavidxu
1725161599Sdavidxuvoid
1726161599Sdavidxusched_unlend_user_prio(struct thread *td, u_char prio)
1727161599Sdavidxu{
1728161599Sdavidxu	u_char base_pri;
1729161599Sdavidxu
1730163709Sjb	base_pri = td->td_base_user_pri;
1731161599Sdavidxu	if (prio >= base_pri) {
1732161599Sdavidxu		td->td_flags &= ~TDF_UBORROWING;
1733163709Sjb		sched_user_prio(td, base_pri);
1734161599Sdavidxu	} else
1735161599Sdavidxu		sched_lend_user_prio(td, prio);
1736161599Sdavidxu}
1737161599Sdavidxu
1738171482Sjeff/*
1739171505Sjeff * Add the thread passed as 'newtd' to the run queue before selecting
1740171505Sjeff * the next thread to run.  This is only used for KSE.
1741171505Sjeff */
1742171505Sjeffstatic void
1743171505Sjeffsched_switchin(struct tdq *tdq, struct thread *td)
1744171505Sjeff{
1745171505Sjeff#ifdef SMP
1746171505Sjeff	spinlock_enter();
1747171505Sjeff	TDQ_UNLOCK(tdq);
1748171505Sjeff	thread_lock(td);
1749171505Sjeff	spinlock_exit();
1750171505Sjeff	sched_setcpu(td->td_sched, TDQ_ID(tdq), SRQ_YIELDING);
1751171505Sjeff#else
1752171505Sjeff	td->td_lock = TDQ_LOCKPTR(tdq);
1753171505Sjeff#endif
1754171505Sjeff	tdq_add(tdq, td, SRQ_YIELDING);
1755171505Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1756171505Sjeff}
1757171505Sjeff
1758171505Sjeff/*
1759171713Sjeff * Handle migration from sched_switch().  This happens only for
1760171713Sjeff * cpu binding.
1761171713Sjeff */
1762171713Sjeffstatic struct mtx *
1763171713Sjeffsched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1764171713Sjeff{
1765171713Sjeff	struct tdq *tdn;
1766171713Sjeff
1767171713Sjeff	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1768171713Sjeff#ifdef SMP
1769171713Sjeff	/*
1770171713Sjeff	 * Do the lock dance required to avoid LOR.  We grab an extra
1771171713Sjeff	 * spinlock nesting to prevent preemption while we're
1772171713Sjeff	 * not holding either run-queue lock.
1773171713Sjeff	 */
1774171713Sjeff	spinlock_enter();
1775171713Sjeff	thread_block_switch(td);	/* This releases the lock on tdq. */
1776171713Sjeff	TDQ_LOCK(tdn);
1777171713Sjeff	tdq_add(tdn, td, flags);
1778171713Sjeff	tdq_notify(td->td_sched);
1779171713Sjeff	/*
1780171713Sjeff	 * After we unlock tdn the new cpu still can't switch into this
1781171713Sjeff	 * thread until we've unblocked it in cpu_switch().  The lock
1782171713Sjeff	 * pointers may match in the case of HTT cores.  Don't unlock here
1783171713Sjeff	 * or we can deadlock when the other CPU runs the IPI handler.
1784171713Sjeff	 */
1785171713Sjeff	if (TDQ_LOCKPTR(tdn) != TDQ_LOCKPTR(tdq)) {
1786171713Sjeff		TDQ_UNLOCK(tdn);
1787171713Sjeff		TDQ_LOCK(tdq);
1788171713Sjeff	}
1789171713Sjeff	spinlock_exit();
1790171713Sjeff#endif
1791171713Sjeff	return (TDQ_LOCKPTR(tdn));
1792171713Sjeff}
1793171713Sjeff
1794171713Sjeff/*
1795171482Sjeff * Block a thread for switching.  Similar to thread_block() but does not
1796171482Sjeff * bump the spin count.
1797171482Sjeff */
1798171482Sjeffstatic inline struct mtx *
1799171482Sjeffthread_block_switch(struct thread *td)
1800171482Sjeff{
1801171482Sjeff	struct mtx *lock;
1802171482Sjeff
1803171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1804171482Sjeff	lock = td->td_lock;
1805171482Sjeff	td->td_lock = &blocked_lock;
1806171482Sjeff	mtx_unlock_spin(lock);
1807171482Sjeff
1808171482Sjeff	return (lock);
1809171482Sjeff}
1810171482Sjeff
1811171482Sjeff/*
1812171482Sjeff * Release a thread that was blocked with thread_block_switch().
1813171482Sjeff */
1814171482Sjeffstatic inline void
1815171482Sjeffthread_unblock_switch(struct thread *td, struct mtx *mtx)
1816171482Sjeff{
1817171482Sjeff	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1818171482Sjeff	    (uintptr_t)mtx);
1819171482Sjeff}
1820171482Sjeff
1821171482Sjeff/*
1822171482Sjeff * Switch threads.  This function has to handle threads coming in while
1823171482Sjeff * blocked for some reason, running, or idle.  It also must deal with
1824171482Sjeff * migrating a thread from one queue to another as running threads may
1825171482Sjeff * be assigned elsewhere via binding.
1826171482Sjeff */
1827161599Sdavidxuvoid
1828135051Sjuliansched_switch(struct thread *td, struct thread *newtd, int flags)
1829109864Sjeff{
1830165627Sjeff	struct tdq *tdq;
1831164936Sjulian	struct td_sched *ts;
1832171482Sjeff	struct mtx *mtx;
1833171713Sjeff	int srqflag;
1834171482Sjeff	int cpuid;
1835109864Sjeff
1836170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1837109864Sjeff
1838171482Sjeff	cpuid = PCPU_GET(cpuid);
1839171482Sjeff	tdq = TDQ_CPU(cpuid);
1840164936Sjulian	ts = td->td_sched;
1841171713Sjeff	mtx = td->td_lock;
1842171482Sjeff#ifdef SMP
1843171482Sjeff	ts->ts_rltick = ticks;
1844171482Sjeff	if (newtd && newtd->td_priority < tdq->tdq_lowpri)
1845171482Sjeff		tdq->tdq_lowpri = newtd->td_priority;
1846171482Sjeff#endif
1847133555Sjeff	td->td_lastcpu = td->td_oncpu;
1848113339Sjulian	td->td_oncpu = NOCPU;
1849132266Sjhb	td->td_flags &= ~TDF_NEEDRESCHED;
1850144777Sups	td->td_owepreempt = 0;
1851123434Sjeff	/*
1852171482Sjeff	 * The lock pointer in an idle thread should never change.  Reset it
1853171482Sjeff	 * to CAN_RUN as well.
1854123434Sjeff	 */
1855167327Sjulian	if (TD_IS_IDLETHREAD(td)) {
1856171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1857139334Sjeff		TD_SET_CAN_RUN(td);
1858170293Sjeff	} else if (TD_IS_RUNNING(td)) {
1859171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1860165627Sjeff		tdq_load_rem(tdq, ts);
1861171713Sjeff		srqflag = (flags & SW_PREEMPT) ?
1862170293Sjeff		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1863171713Sjeff		    SRQ_OURSELF|SRQ_YIELDING;
1864171713Sjeff		if (ts->ts_cpu == cpuid)
1865171713Sjeff			tdq_add(tdq, td, srqflag);
1866171713Sjeff		else
1867171713Sjeff			mtx = sched_switch_migrate(tdq, td, srqflag);
1868171482Sjeff	} else {
1869171482Sjeff		/* This thread must be going to sleep. */
1870171482Sjeff		TDQ_LOCK(tdq);
1871171482Sjeff		mtx = thread_block_switch(td);
1872170293Sjeff		tdq_load_rem(tdq, ts);
1873171482Sjeff	}
1874171482Sjeff	/*
1875171482Sjeff	 * We enter here with the thread blocked and assigned to the
1876171482Sjeff	 * appropriate cpu run-queue or sleep-queue and with the current
1877171482Sjeff	 * thread-queue locked.
1878171482Sjeff	 */
1879171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1880171482Sjeff	/*
1881171505Sjeff	 * If KSE assigned a new thread just add it here and let choosethread
1882171505Sjeff	 * select the best one.
1883171482Sjeff	 */
1884171505Sjeff	if (newtd != NULL)
1885171505Sjeff		sched_switchin(tdq, newtd);
1886171482Sjeff	newtd = choosethread();
1887171482Sjeff	/*
1888171482Sjeff	 * Call the MD code to switch contexts if necessary.
1889171482Sjeff	 */
1890145256Sjkoshy	if (td != newtd) {
1891145256Sjkoshy#ifdef	HWPMC_HOOKS
1892145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1893145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1894145256Sjkoshy#endif
1895171482Sjeff		cpu_switch(td, newtd, mtx);
1896171482Sjeff		/*
1897171482Sjeff		 * We may return from cpu_switch on a different cpu.  However,
1898171482Sjeff		 * we always return with td_lock pointing to the current cpu's
1899171482Sjeff		 * run queue lock.
1900171482Sjeff		 */
1901171482Sjeff		cpuid = PCPU_GET(cpuid);
1902171482Sjeff		tdq = TDQ_CPU(cpuid);
1903171482Sjeff		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)td;
1904145256Sjkoshy#ifdef	HWPMC_HOOKS
1905145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1906145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1907145256Sjkoshy#endif
1908171482Sjeff	} else
1909171482Sjeff		thread_unblock_switch(td, mtx);
1910171482Sjeff	/*
1911171482Sjeff	 * Assert that all went well and return.
1912171482Sjeff	 */
1913171482Sjeff#ifdef SMP
1914171482Sjeff	/* We should always get here with the lowest priority td possible */
1915171482Sjeff	tdq->tdq_lowpri = td->td_priority;
1916171482Sjeff#endif
1917171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1918171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1919171482Sjeff	td->td_oncpu = cpuid;
1920109864Sjeff}
1921109864Sjeff
1922171482Sjeff/*
1923171482Sjeff * Adjust thread priorities as a result of a nice request.
1924171482Sjeff */
1925109864Sjeffvoid
1926130551Sjuliansched_nice(struct proc *p, int nice)
1927109864Sjeff{
1928109864Sjeff	struct thread *td;
1929109864Sjeff
1930130551Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
1931170293Sjeff	PROC_SLOCK_ASSERT(p, MA_OWNED);
1932165762Sjeff
1933130551Sjulian	p->p_nice = nice;
1934163709Sjb	FOREACH_THREAD_IN_PROC(p, td) {
1935170293Sjeff		thread_lock(td);
1936163709Sjb		sched_priority(td);
1937165762Sjeff		sched_prio(td, td->td_base_user_pri);
1938170293Sjeff		thread_unlock(td);
1939130551Sjulian	}
1940109864Sjeff}
1941109864Sjeff
1942171482Sjeff/*
1943171482Sjeff * Record the sleep time for the interactivity scorer.
1944171482Sjeff */
1945109864Sjeffvoid
1946126326Sjhbsched_sleep(struct thread *td)
1947109864Sjeff{
1948165762Sjeff
1949170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1950109864Sjeff
1951172264Sjeff	td->td_slptick = ticks;
1952109864Sjeff}
1953109864Sjeff
1954171482Sjeff/*
1955171482Sjeff * Schedule a thread to resume execution and record how long it voluntarily
1956171482Sjeff * slept.  We also update the pctcpu, interactivity, and priority.
1957171482Sjeff */
1958109864Sjeffvoid
1959109864Sjeffsched_wakeup(struct thread *td)
1960109864Sjeff{
1961166229Sjeff	struct td_sched *ts;
1962171482Sjeff	int slptick;
1963165762Sjeff
1964170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1965166229Sjeff	ts = td->td_sched;
1966109864Sjeff	/*
1967165762Sjeff	 * If we slept for more than a tick update our interactivity and
1968165762Sjeff	 * priority.
1969109864Sjeff	 */
1970172264Sjeff	slptick = td->td_slptick;
1971172264Sjeff	td->td_slptick = 0;
1972171482Sjeff	if (slptick && slptick != ticks) {
1973166208Sjeff		u_int hzticks;
1974109864Sjeff
1975171482Sjeff		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1976171482Sjeff		ts->ts_slptime += hzticks;
1977165819Sjeff		sched_interact_update(td);
1978166229Sjeff		sched_pctcpu_update(ts);
1979163709Sjb		sched_priority(td);
1980109864Sjeff	}
1981166229Sjeff	/* Reset the slice value after we sleep. */
1982166229Sjeff	ts->ts_slice = sched_slice;
1983166190Sjeff	sched_add(td, SRQ_BORING);
1984109864Sjeff}
1985109864Sjeff
1986109864Sjeff/*
1987109864Sjeff * Penalize the parent for creating a new child and initialize the child's
1988109864Sjeff * priority.
1989109864Sjeff */
1990109864Sjeffvoid
1991163709Sjbsched_fork(struct thread *td, struct thread *child)
1992109864Sjeff{
1993170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1994164936Sjulian	sched_fork_thread(td, child);
1995165762Sjeff	/*
1996165762Sjeff	 * Penalize the parent and child for forking.
1997165762Sjeff	 */
1998165762Sjeff	sched_interact_fork(child);
1999165762Sjeff	sched_priority(child);
2000171482Sjeff	td->td_sched->ts_runtime += tickincr;
2001165762Sjeff	sched_interact_update(td);
2002165762Sjeff	sched_priority(td);
2003164936Sjulian}
2004109864Sjeff
2005171482Sjeff/*
2006171482Sjeff * Fork a new thread, may be within the same process.
2007171482Sjeff */
2008164936Sjulianvoid
2009164936Sjuliansched_fork_thread(struct thread *td, struct thread *child)
2010164936Sjulian{
2011164936Sjulian	struct td_sched *ts;
2012164936Sjulian	struct td_sched *ts2;
2013164936Sjulian
2014165762Sjeff	/*
2015165762Sjeff	 * Initialize child.
2016165762Sjeff	 */
2017170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2018163709Sjb	sched_newthread(child);
2019171482Sjeff	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
2020164936Sjulian	ts = td->td_sched;
2021164936Sjulian	ts2 = child->td_sched;
2022164936Sjulian	ts2->ts_cpu = ts->ts_cpu;
2023164936Sjulian	ts2->ts_runq = NULL;
2024165762Sjeff	/*
2025165762Sjeff	 * Grab our parents cpu estimation information and priority.
2026165762Sjeff	 */
2027164936Sjulian	ts2->ts_ticks = ts->ts_ticks;
2028164936Sjulian	ts2->ts_ltick = ts->ts_ltick;
2029164936Sjulian	ts2->ts_ftick = ts->ts_ftick;
2030165762Sjeff	child->td_user_pri = td->td_user_pri;
2031165762Sjeff	child->td_base_user_pri = td->td_base_user_pri;
2032165762Sjeff	/*
2033165762Sjeff	 * And update interactivity score.
2034165762Sjeff	 */
2035171482Sjeff	ts2->ts_slptime = ts->ts_slptime;
2036171482Sjeff	ts2->ts_runtime = ts->ts_runtime;
2037165762Sjeff	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
2038113357Sjeff}
2039113357Sjeff
2040171482Sjeff/*
2041171482Sjeff * Adjust the priority class of a thread.
2042171482Sjeff */
2043113357Sjeffvoid
2044163709Sjbsched_class(struct thread *td, int class)
2045113357Sjeff{
2046113357Sjeff
2047170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2048163709Sjb	if (td->td_pri_class == class)
2049113357Sjeff		return;
2050113357Sjeff
2051121896Sjeff#ifdef SMP
2052165827Sjeff	/*
2053165827Sjeff	 * On SMP if we're on the RUNQ we must adjust the transferable
2054165827Sjeff	 * count because could be changing to or from an interrupt
2055165827Sjeff	 * class.
2056165827Sjeff	 */
2057166190Sjeff	if (TD_ON_RUNQ(td)) {
2058165827Sjeff		struct tdq *tdq;
2059165827Sjeff
2060165827Sjeff		tdq = TDQ_CPU(td->td_sched->ts_cpu);
2061165827Sjeff		if (THREAD_CAN_MIGRATE(td)) {
2062165827Sjeff			tdq->tdq_transferable--;
2063165827Sjeff			tdq->tdq_group->tdg_transferable--;
2064122744Sjeff		}
2065165827Sjeff		td->td_pri_class = class;
2066165827Sjeff		if (THREAD_CAN_MIGRATE(td)) {
2067165827Sjeff			tdq->tdq_transferable++;
2068165827Sjeff			tdq->tdq_group->tdg_transferable++;
2069165827Sjeff		}
2070165827Sjeff	}
2071164936Sjulian#endif
2072163709Sjb	td->td_pri_class = class;
2073109864Sjeff}
2074109864Sjeff
2075109864Sjeff/*
2076109864Sjeff * Return some of the child's priority and interactivity to the parent.
2077109864Sjeff */
2078109864Sjeffvoid
2079164939Sjuliansched_exit(struct proc *p, struct thread *child)
2080109864Sjeff{
2081165762Sjeff	struct thread *td;
2082164939Sjulian
2083163709Sjb	CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
2084164939Sjulian	    child, child->td_proc->p_comm, child->td_priority);
2085113372Sjeff
2086170293Sjeff	PROC_SLOCK_ASSERT(p, MA_OWNED);
2087165762Sjeff	td = FIRST_THREAD_IN_PROC(p);
2088165762Sjeff	sched_exit_thread(td, child);
2089113372Sjeff}
2090113372Sjeff
2091171482Sjeff/*
2092171482Sjeff * Penalize another thread for the time spent on this one.  This helps to
2093171482Sjeff * worsen the priority and interactivity of processes which schedule batch
2094171482Sjeff * jobs such as make.  This has little effect on the make process itself but
2095171482Sjeff * causes new processes spawned by it to receive worse scores immediately.
2096171482Sjeff */
2097113372Sjeffvoid
2098164939Sjuliansched_exit_thread(struct thread *td, struct thread *child)
2099164936Sjulian{
2100165762Sjeff
2101164939Sjulian	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
2102165762Sjeff	    child, child->td_proc->p_comm, child->td_priority);
2103164939Sjulian
2104165762Sjeff#ifdef KSE
2105165762Sjeff	/*
2106165762Sjeff	 * KSE forks and exits so often that this penalty causes short-lived
2107165762Sjeff	 * threads to always be non-interactive.  This causes mozilla to
2108165762Sjeff	 * crawl under load.
2109165762Sjeff	 */
2110165762Sjeff	if ((td->td_pflags & TDP_SA) && td->td_proc == child->td_proc)
2111165762Sjeff		return;
2112165762Sjeff#endif
2113165762Sjeff	/*
2114165762Sjeff	 * Give the child's runtime to the parent without returning the
2115165762Sjeff	 * sleep time as a penalty to the parent.  This causes shells that
2116165762Sjeff	 * launch expensive things to mark their children as expensive.
2117165762Sjeff	 */
2118170293Sjeff	thread_lock(td);
2119171482Sjeff	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2120164939Sjulian	sched_interact_update(td);
2121165762Sjeff	sched_priority(td);
2122170293Sjeff	thread_unlock(td);
2123164936Sjulian}
2124164936Sjulian
2125171482Sjeff/*
2126171482Sjeff * Fix priorities on return to user-space.  Priorities may be elevated due
2127171482Sjeff * to static priorities in msleep() or similar.
2128171482Sjeff */
2129164936Sjulianvoid
2130164936Sjuliansched_userret(struct thread *td)
2131164936Sjulian{
2132164936Sjulian	/*
2133164936Sjulian	 * XXX we cheat slightly on the locking here to avoid locking in
2134164936Sjulian	 * the usual case.  Setting td_priority here is essentially an
2135164936Sjulian	 * incomplete workaround for not setting it properly elsewhere.
2136164936Sjulian	 * Now that some interrupt handlers are threads, not setting it
2137164936Sjulian	 * properly elsewhere can clobber it in the window between setting
2138164936Sjulian	 * it here and returning to user mode, so don't waste time setting
2139164936Sjulian	 * it perfectly here.
2140164936Sjulian	 */
2141164936Sjulian	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2142164936Sjulian	    ("thread with borrowed priority returning to userland"));
2143164936Sjulian	if (td->td_priority != td->td_user_pri) {
2144170293Sjeff		thread_lock(td);
2145164936Sjulian		td->td_priority = td->td_user_pri;
2146164936Sjulian		td->td_base_pri = td->td_user_pri;
2147170293Sjeff		thread_unlock(td);
2148164936Sjulian        }
2149164936Sjulian}
2150164936Sjulian
2151171482Sjeff/*
2152171482Sjeff * Handle a stathz tick.  This is really only relevant for timeshare
2153171482Sjeff * threads.
2154171482Sjeff */
2155164936Sjulianvoid
2156121127Sjeffsched_clock(struct thread *td)
2157109864Sjeff{
2158164936Sjulian	struct tdq *tdq;
2159164936Sjulian	struct td_sched *ts;
2160109864Sjeff
2161171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2162164936Sjulian	tdq = TDQ_SELF();
2163172409Sjeff#ifdef SMP
2164133427Sjeff	/*
2165172409Sjeff	 * We run the long term load balancer infrequently on the first cpu.
2166172409Sjeff	 */
2167172409Sjeff	if (balance_tdq == tdq) {
2168172409Sjeff		if (balance_ticks && --balance_ticks == 0)
2169172409Sjeff			sched_balance();
2170172409Sjeff		if (balance_group_ticks && --balance_group_ticks == 0)
2171172409Sjeff			sched_balance_groups();
2172172409Sjeff	}
2173172409Sjeff#endif
2174172409Sjeff	/*
2175165766Sjeff	 * Advance the insert index once for each tick to ensure that all
2176165766Sjeff	 * threads get a chance to run.
2177133427Sjeff	 */
2178165766Sjeff	if (tdq->tdq_idx == tdq->tdq_ridx) {
2179165766Sjeff		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2180165766Sjeff		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2181165766Sjeff			tdq->tdq_ridx = tdq->tdq_idx;
2182165766Sjeff	}
2183165766Sjeff	ts = td->td_sched;
2184165762Sjeff	/*
2185163709Sjb	 * We only do slicing code for TIMESHARE threads.
2186113357Sjeff	 */
2187163709Sjb	if (td->td_pri_class != PRI_TIMESHARE)
2188113357Sjeff		return;
2189113357Sjeff	/*
2190165766Sjeff	 * We used a tick; charge it to the thread so that we can compute our
2191113357Sjeff	 * interactivity.
2192109864Sjeff	 */
2193171482Sjeff	td->td_sched->ts_runtime += tickincr;
2194163709Sjb	sched_interact_update(td);
2195109864Sjeff	/*
2196109864Sjeff	 * We used up one time slice.
2197109864Sjeff	 */
2198164936Sjulian	if (--ts->ts_slice > 0)
2199113357Sjeff		return;
2200109864Sjeff	/*
2201113357Sjeff	 * We're out of time, recompute priorities and requeue.
2202109864Sjeff	 */
2203165796Sjeff	sched_priority(td);
2204113357Sjeff	td->td_flags |= TDF_NEEDRESCHED;
2205109864Sjeff}
2206109864Sjeff
2207171482Sjeff/*
2208171482Sjeff * Called once per hz tick.  Used for cpu utilization information.  This
2209171482Sjeff * is easier than trying to scale based on stathz.
2210171482Sjeff */
2211171482Sjeffvoid
2212171482Sjeffsched_tick(void)
2213171482Sjeff{
2214171482Sjeff	struct td_sched *ts;
2215171482Sjeff
2216171482Sjeff	ts = curthread->td_sched;
2217171482Sjeff	/* Adjust ticks for pctcpu */
2218171482Sjeff	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2219171482Sjeff	ts->ts_ltick = ticks;
2220171482Sjeff	/*
2221171482Sjeff	 * Update if we've exceeded our desired tick threshhold by over one
2222171482Sjeff	 * second.
2223171482Sjeff	 */
2224171482Sjeff	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2225171482Sjeff		sched_pctcpu_update(ts);
2226171482Sjeff}
2227171482Sjeff
2228171482Sjeff/*
2229171482Sjeff * Return whether the current CPU has runnable tasks.  Used for in-kernel
2230171482Sjeff * cooperative idle threads.
2231171482Sjeff */
2232109864Sjeffint
2233109864Sjeffsched_runnable(void)
2234109864Sjeff{
2235164936Sjulian	struct tdq *tdq;
2236115998Sjeff	int load;
2237109864Sjeff
2238115998Sjeff	load = 1;
2239115998Sjeff
2240164936Sjulian	tdq = TDQ_SELF();
2241121605Sjeff	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2242165620Sjeff		if (tdq->tdq_load > 0)
2243121605Sjeff			goto out;
2244121605Sjeff	} else
2245165620Sjeff		if (tdq->tdq_load - 1 > 0)
2246121605Sjeff			goto out;
2247115998Sjeff	load = 0;
2248115998Sjeffout:
2249115998Sjeff	return (load);
2250109864Sjeff}
2251109864Sjeff
2252171482Sjeff/*
2253171482Sjeff * Choose the highest priority thread to run.  The thread is removed from
2254171482Sjeff * the run-queue while running however the load remains.  For SMP we set
2255171482Sjeff * the tdq in the global idle bitmask if it idles here.
2256171482Sjeff */
2257166190Sjeffstruct thread *
2258109970Sjeffsched_choose(void)
2259109970Sjeff{
2260171482Sjeff#ifdef SMP
2261171482Sjeff	struct tdq_group *tdg;
2262171482Sjeff#endif
2263171482Sjeff	struct td_sched *ts;
2264164936Sjulian	struct tdq *tdq;
2265109970Sjeff
2266164936Sjulian	tdq = TDQ_SELF();
2267171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2268164936Sjulian	ts = tdq_choose(tdq);
2269164936Sjulian	if (ts) {
2270164936Sjulian		tdq_runq_rem(tdq, ts);
2271166190Sjeff		return (ts->ts_thread);
2272109864Sjeff	}
2273109970Sjeff#ifdef SMP
2274171482Sjeff	/*
2275171482Sjeff	 * We only set the idled bit when all of the cpus in the group are
2276171482Sjeff	 * idle.  Otherwise we could get into a situation where a thread bounces
2277171482Sjeff	 * back and forth between two idle cores on seperate physical CPUs.
2278171482Sjeff	 */
2279171482Sjeff	tdg = tdq->tdq_group;
2280171482Sjeff	tdg->tdg_idlemask |= PCPU_GET(cpumask);
2281171482Sjeff	if (tdg->tdg_idlemask == tdg->tdg_cpumask)
2282171482Sjeff		atomic_set_int(&tdq_idle, tdg->tdg_mask);
2283171482Sjeff	tdq->tdq_lowpri = PRI_MAX_IDLE;
2284109970Sjeff#endif
2285166190Sjeff	return (PCPU_GET(idlethread));
2286109864Sjeff}
2287109864Sjeff
2288171482Sjeff/*
2289171482Sjeff * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2290171482Sjeff * we always request it once we exit a critical section.
2291171482Sjeff */
2292171482Sjeffstatic inline void
2293171482Sjeffsched_setpreempt(struct thread *td)
2294166190Sjeff{
2295166190Sjeff	struct thread *ctd;
2296166190Sjeff	int cpri;
2297166190Sjeff	int pri;
2298166190Sjeff
2299166190Sjeff	ctd = curthread;
2300166190Sjeff	pri = td->td_priority;
2301166190Sjeff	cpri = ctd->td_priority;
2302171482Sjeff	if (td->td_priority < ctd->td_priority)
2303171482Sjeff		curthread->td_flags |= TDF_NEEDRESCHED;
2304166190Sjeff	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2305171482Sjeff		return;
2306166190Sjeff	/*
2307166190Sjeff	 * Always preempt IDLE threads.  Otherwise only if the preempting
2308166190Sjeff	 * thread is an ithread.
2309166190Sjeff	 */
2310171482Sjeff	if (pri > preempt_thresh && cpri < PRI_MIN_IDLE)
2311171482Sjeff		return;
2312171482Sjeff	ctd->td_owepreempt = 1;
2313171482Sjeff	return;
2314166190Sjeff}
2315166190Sjeff
2316171482Sjeff/*
2317171482Sjeff * Add a thread to a thread queue.  Initializes priority, slice, runq, and
2318171482Sjeff * add it to the appropriate queue.  This is the internal function called
2319171482Sjeff * when the tdq is predetermined.
2320171482Sjeff */
2321109864Sjeffvoid
2322171482Sjefftdq_add(struct tdq *tdq, struct thread *td, int flags)
2323109864Sjeff{
2324164936Sjulian	struct td_sched *ts;
2325121790Sjeff	int class;
2326166108Sjeff#ifdef SMP
2327166108Sjeff	int cpumask;
2328166108Sjeff#endif
2329109864Sjeff
2330171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2331166190Sjeff	KASSERT((td->td_inhibitors == 0),
2332166190Sjeff	    ("sched_add: trying to run inhibited thread"));
2333166190Sjeff	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2334166190Sjeff	    ("sched_add: bad thread state"));
2335172207Sjeff	KASSERT(td->td_flags & TDF_INMEM,
2336172207Sjeff	    ("sched_add: thread swapped out"));
2337171482Sjeff
2338171482Sjeff	ts = td->td_sched;
2339171482Sjeff	class = PRI_BASE(td->td_pri_class);
2340166190Sjeff        TD_SET_RUNQ(td);
2341166190Sjeff	if (ts->ts_slice == 0)
2342166190Sjeff		ts->ts_slice = sched_slice;
2343133427Sjeff	/*
2344171482Sjeff	 * Pick the run queue based on priority.
2345133427Sjeff	 */
2346171482Sjeff	if (td->td_priority <= PRI_MAX_REALTIME)
2347171482Sjeff		ts->ts_runq = &tdq->tdq_realtime;
2348171482Sjeff	else if (td->td_priority <= PRI_MAX_TIMESHARE)
2349171482Sjeff		ts->ts_runq = &tdq->tdq_timeshare;
2350171482Sjeff	else
2351171482Sjeff		ts->ts_runq = &tdq->tdq_idle;
2352171482Sjeff#ifdef SMP
2353166108Sjeff	cpumask = 1 << ts->ts_cpu;
2354121790Sjeff	/*
2355123685Sjeff	 * If we had been idle, clear our bit in the group and potentially
2356166108Sjeff	 * the global bitmap.
2357121790Sjeff	 */
2358165762Sjeff	if ((class != PRI_IDLE && class != PRI_ITHD) &&
2359166108Sjeff	    (tdq->tdq_group->tdg_idlemask & cpumask) != 0) {
2360121790Sjeff		/*
2361123433Sjeff		 * Check to see if our group is unidling, and if so, remove it
2362123433Sjeff		 * from the global idle mask.
2363121790Sjeff		 */
2364165620Sjeff		if (tdq->tdq_group->tdg_idlemask ==
2365165620Sjeff		    tdq->tdq_group->tdg_cpumask)
2366165620Sjeff			atomic_clear_int(&tdq_idle, tdq->tdq_group->tdg_mask);
2367123433Sjeff		/*
2368123433Sjeff		 * Now remove ourselves from the group specific idle mask.
2369123433Sjeff		 */
2370166108Sjeff		tdq->tdq_group->tdg_idlemask &= ~cpumask;
2371166108Sjeff	}
2372171482Sjeff	if (td->td_priority < tdq->tdq_lowpri)
2373171482Sjeff		tdq->tdq_lowpri = td->td_priority;
2374121790Sjeff#endif
2375171482Sjeff	tdq_runq_add(tdq, ts, flags);
2376171482Sjeff	tdq_load_add(tdq, ts);
2377171482Sjeff}
2378171482Sjeff
2379171482Sjeff/*
2380171482Sjeff * Select the target thread queue and add a thread to it.  Request
2381171482Sjeff * preemption or IPI a remote processor if required.
2382171482Sjeff */
2383171482Sjeffvoid
2384171482Sjeffsched_add(struct thread *td, int flags)
2385171482Sjeff{
2386171482Sjeff	struct td_sched *ts;
2387171482Sjeff	struct tdq *tdq;
2388171482Sjeff#ifdef SMP
2389171482Sjeff	int cpuid;
2390171482Sjeff	int cpu;
2391171482Sjeff#endif
2392171482Sjeff	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
2393171482Sjeff	    td, td->td_proc->p_comm, td->td_priority, curthread,
2394171482Sjeff	    curthread->td_proc->p_comm);
2395171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2396171482Sjeff	ts = td->td_sched;
2397166108Sjeff	/*
2398171482Sjeff	 * Recalculate the priority before we select the target cpu or
2399171482Sjeff	 * run-queue.
2400166108Sjeff	 */
2401171482Sjeff	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2402171482Sjeff		sched_priority(td);
2403171482Sjeff#ifdef SMP
2404171482Sjeff	cpuid = PCPU_GET(cpuid);
2405171482Sjeff	/*
2406171482Sjeff	 * Pick the destination cpu and if it isn't ours transfer to the
2407171482Sjeff	 * target cpu.
2408171482Sjeff	 */
2409171482Sjeff	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_MIGRATE(td))
2410171482Sjeff		cpu = cpuid;
2411171482Sjeff	else if (!THREAD_CAN_MIGRATE(td))
2412171482Sjeff		cpu = ts->ts_cpu;
2413166108Sjeff	else
2414171482Sjeff		cpu = sched_pickcpu(ts, flags);
2415171482Sjeff	tdq = sched_setcpu(ts, cpu, flags);
2416171482Sjeff	tdq_add(tdq, td, flags);
2417171482Sjeff	if (cpu != cpuid) {
2418166108Sjeff		tdq_notify(ts);
2419166108Sjeff		return;
2420166108Sjeff	}
2421171482Sjeff#else
2422171482Sjeff	tdq = TDQ_SELF();
2423171482Sjeff	TDQ_LOCK(tdq);
2424171482Sjeff	/*
2425171482Sjeff	 * Now that the thread is moving to the run-queue, set the lock
2426171482Sjeff	 * to the scheduler's lock.
2427171482Sjeff	 */
2428171482Sjeff	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2429171482Sjeff	tdq_add(tdq, td, flags);
2430166108Sjeff#endif
2431171482Sjeff	if (!(flags & SRQ_YIELDING))
2432171482Sjeff		sched_setpreempt(td);
2433109864Sjeff}
2434109864Sjeff
2435171482Sjeff/*
2436171482Sjeff * Remove a thread from a run-queue without running it.  This is used
2437171482Sjeff * when we're stealing a thread from a remote queue.  Otherwise all threads
2438171482Sjeff * exit by calling sched_exit_thread() and sched_throw() themselves.
2439171482Sjeff */
2440109864Sjeffvoid
2441121127Sjeffsched_rem(struct thread *td)
2442109864Sjeff{
2443164936Sjulian	struct tdq *tdq;
2444164936Sjulian	struct td_sched *ts;
2445113357Sjeff
2446139316Sjeff	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
2447139316Sjeff	    td, td->td_proc->p_comm, td->td_priority, curthread,
2448139316Sjeff	    curthread->td_proc->p_comm);
2449164936Sjulian	ts = td->td_sched;
2450171482Sjeff	tdq = TDQ_CPU(ts->ts_cpu);
2451171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2452171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2453166190Sjeff	KASSERT(TD_ON_RUNQ(td),
2454164936Sjulian	    ("sched_rem: thread not on run queue"));
2455164936Sjulian	tdq_runq_rem(tdq, ts);
2456164936Sjulian	tdq_load_rem(tdq, ts);
2457166190Sjeff	TD_SET_CAN_RUN(td);
2458109864Sjeff}
2459109864Sjeff
2460171482Sjeff/*
2461171482Sjeff * Fetch cpu utilization information.  Updates on demand.
2462171482Sjeff */
2463109864Sjefffixpt_t
2464121127Sjeffsched_pctcpu(struct thread *td)
2465109864Sjeff{
2466109864Sjeff	fixpt_t pctcpu;
2467164936Sjulian	struct td_sched *ts;
2468109864Sjeff
2469109864Sjeff	pctcpu = 0;
2470164936Sjulian	ts = td->td_sched;
2471164936Sjulian	if (ts == NULL)
2472121290Sjeff		return (0);
2473109864Sjeff
2474170293Sjeff	thread_lock(td);
2475164936Sjulian	if (ts->ts_ticks) {
2476109864Sjeff		int rtick;
2477109864Sjeff
2478165796Sjeff		sched_pctcpu_update(ts);
2479109864Sjeff		/* How many rtick per second ? */
2480165762Sjeff		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2481165762Sjeff		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2482109864Sjeff	}
2483170293Sjeff	thread_unlock(td);
2484109864Sjeff
2485109864Sjeff	return (pctcpu);
2486109864Sjeff}
2487109864Sjeff
2488171482Sjeff/*
2489171482Sjeff * Bind a thread to a target cpu.
2490171482Sjeff */
2491122038Sjeffvoid
2492122038Sjeffsched_bind(struct thread *td, int cpu)
2493122038Sjeff{
2494164936Sjulian	struct td_sched *ts;
2495122038Sjeff
2496171713Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2497164936Sjulian	ts = td->td_sched;
2498166137Sjeff	if (ts->ts_flags & TSF_BOUND)
2499166152Sjeff		sched_unbind(td);
2500164936Sjulian	ts->ts_flags |= TSF_BOUND;
2501123433Sjeff#ifdef SMP
2502166137Sjeff	sched_pin();
2503123433Sjeff	if (PCPU_GET(cpuid) == cpu)
2504122038Sjeff		return;
2505166137Sjeff	ts->ts_cpu = cpu;
2506122038Sjeff	/* When we return from mi_switch we'll be on the correct cpu. */
2507131527Sphk	mi_switch(SW_VOL, NULL);
2508122038Sjeff#endif
2509122038Sjeff}
2510122038Sjeff
2511171482Sjeff/*
2512171482Sjeff * Release a bound thread.
2513171482Sjeff */
2514122038Sjeffvoid
2515122038Sjeffsched_unbind(struct thread *td)
2516122038Sjeff{
2517165762Sjeff	struct td_sched *ts;
2518165762Sjeff
2519170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2520165762Sjeff	ts = td->td_sched;
2521166137Sjeff	if ((ts->ts_flags & TSF_BOUND) == 0)
2522166137Sjeff		return;
2523165762Sjeff	ts->ts_flags &= ~TSF_BOUND;
2524165762Sjeff#ifdef SMP
2525165762Sjeff	sched_unpin();
2526165762Sjeff#endif
2527122038Sjeff}
2528122038Sjeff
2529109864Sjeffint
2530145256Sjkoshysched_is_bound(struct thread *td)
2531145256Sjkoshy{
2532170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2533164936Sjulian	return (td->td_sched->ts_flags & TSF_BOUND);
2534145256Sjkoshy}
2535145256Sjkoshy
2536171482Sjeff/*
2537171482Sjeff * Basic yield call.
2538171482Sjeff */
2539159630Sdavidxuvoid
2540159630Sdavidxusched_relinquish(struct thread *td)
2541159630Sdavidxu{
2542170293Sjeff	thread_lock(td);
2543163709Sjb	if (td->td_pri_class == PRI_TIMESHARE)
2544159630Sdavidxu		sched_prio(td, PRI_MAX_TIMESHARE);
2545170293Sjeff	SCHED_STAT_INC(switch_relinquish);
2546159630Sdavidxu	mi_switch(SW_VOL, NULL);
2547170293Sjeff	thread_unlock(td);
2548159630Sdavidxu}
2549159630Sdavidxu
2550171482Sjeff/*
2551171482Sjeff * Return the total system load.
2552171482Sjeff */
2553145256Sjkoshyint
2554125289Sjeffsched_load(void)
2555125289Sjeff{
2556125289Sjeff#ifdef SMP
2557125289Sjeff	int total;
2558125289Sjeff	int i;
2559125289Sjeff
2560125289Sjeff	total = 0;
2561165620Sjeff	for (i = 0; i <= tdg_maxid; i++)
2562165620Sjeff		total += TDQ_GROUP(i)->tdg_load;
2563125289Sjeff	return (total);
2564125289Sjeff#else
2565165620Sjeff	return (TDQ_SELF()->tdq_sysload);
2566125289Sjeff#endif
2567125289Sjeff}
2568125289Sjeff
2569125289Sjeffint
2570109864Sjeffsched_sizeof_proc(void)
2571109864Sjeff{
2572109864Sjeff	return (sizeof(struct proc));
2573109864Sjeff}
2574109864Sjeff
2575109864Sjeffint
2576109864Sjeffsched_sizeof_thread(void)
2577109864Sjeff{
2578109864Sjeff	return (sizeof(struct thread) + sizeof(struct td_sched));
2579109864Sjeff}
2580159570Sdavidxu
2581166190Sjeff/*
2582166190Sjeff * The actual idle process.
2583166190Sjeff */
2584166190Sjeffvoid
2585166190Sjeffsched_idletd(void *dummy)
2586166190Sjeff{
2587166190Sjeff	struct thread *td;
2588171482Sjeff	struct tdq *tdq;
2589166190Sjeff
2590166190Sjeff	td = curthread;
2591171482Sjeff	tdq = TDQ_SELF();
2592166190Sjeff	mtx_assert(&Giant, MA_NOTOWNED);
2593171482Sjeff	/* ULE relies on preemption for idle interruption. */
2594171482Sjeff	for (;;) {
2595171482Sjeff#ifdef SMP
2596171482Sjeff		if (tdq_idled(tdq))
2597171482Sjeff			cpu_idle();
2598171482Sjeff#else
2599166190Sjeff		cpu_idle();
2600171482Sjeff#endif
2601171482Sjeff	}
2602166190Sjeff}
2603166190Sjeff
2604170293Sjeff/*
2605170293Sjeff * A CPU is entering for the first time or a thread is exiting.
2606170293Sjeff */
2607170293Sjeffvoid
2608170293Sjeffsched_throw(struct thread *td)
2609170293Sjeff{
2610171482Sjeff	struct tdq *tdq;
2611171482Sjeff
2612171482Sjeff	tdq = TDQ_SELF();
2613170293Sjeff	if (td == NULL) {
2614171482Sjeff		/* Correct spinlock nesting and acquire the correct lock. */
2615171482Sjeff		TDQ_LOCK(tdq);
2616170293Sjeff		spinlock_exit();
2617170293Sjeff	} else {
2618171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2619171482Sjeff		tdq_load_rem(tdq, td->td_sched);
2620170293Sjeff	}
2621170293Sjeff	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2622170293Sjeff	PCPU_SET(switchtime, cpu_ticks());
2623170293Sjeff	PCPU_SET(switchticks, ticks);
2624170293Sjeff	cpu_throw(td, choosethread());	/* doesn't return */
2625170293Sjeff}
2626170293Sjeff
2627171482Sjeff/*
2628171482Sjeff * This is called from fork_exit().  Just acquire the correct locks and
2629171482Sjeff * let fork do the rest of the work.
2630171482Sjeff */
2631170293Sjeffvoid
2632170600Sjeffsched_fork_exit(struct thread *td)
2633170293Sjeff{
2634171482Sjeff	struct td_sched *ts;
2635171482Sjeff	struct tdq *tdq;
2636171482Sjeff	int cpuid;
2637170293Sjeff
2638170293Sjeff	/*
2639170293Sjeff	 * Finish setting up thread glue so that it begins execution in a
2640171482Sjeff	 * non-nested critical section with the scheduler lock held.
2641170293Sjeff	 */
2642171482Sjeff	cpuid = PCPU_GET(cpuid);
2643171482Sjeff	tdq = TDQ_CPU(cpuid);
2644171482Sjeff	ts = td->td_sched;
2645171482Sjeff	if (TD_IS_IDLETHREAD(td))
2646171482Sjeff		td->td_lock = TDQ_LOCKPTR(tdq);
2647171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2648171482Sjeff	td->td_oncpu = cpuid;
2649171482Sjeff	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)td;
2650170600Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
2651170293Sjeff}
2652170293Sjeff
2653171482Sjeffstatic SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0,
2654171482Sjeff    "Scheduler");
2655171482SjeffSYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2656165762Sjeff    "Scheduler name");
2657171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2658171482Sjeff    "Slice size for timeshare threads");
2659171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2660171482Sjeff     "Interactivity score threshold");
2661171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2662171482Sjeff     0,"Min priority for preemption, lower priorities have greater precedence");
2663166108Sjeff#ifdef SMP
2664171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, pick_pri, CTLFLAG_RW, &pick_pri, 0,
2665171482Sjeff    "Pick the target cpu based on priority rather than load.");
2666171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2667171482Sjeff    "Number of hz ticks to keep thread affinity for");
2668171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, tryself, CTLFLAG_RW, &tryself, 0, "");
2669171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2670171482Sjeff    "Enables the long-term load balancer");
2671172409SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2672172409Sjeff    &balance_interval, 0,
2673172409Sjeff    "Average frequency in stathz ticks to run the long-term balancer");
2674171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2675171482Sjeff    "Steals work from another hyper-threaded core on idle");
2676171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2677171482Sjeff    "Attempts to steal work from other cores before idling");
2678171506SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2679171506Sjeff    "Minimum load on remote cpu before we'll steal");
2680171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, topology, CTLFLAG_RD, &topology, 0,
2681171482Sjeff    "True when a topology has been specified by the MD code.");
2682166108Sjeff#endif
2683165762Sjeff
2684172264Sjeff/* ps compat.  All cpu percentages from ULE are weighted. */
2685172293Sjeffstatic int ccpu = 0;
2686165762SjeffSYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2687165762Sjeff
2688165762Sjeff
2689134791Sjulian#define KERN_SWITCH_INCLUDE 1
2690134791Sjulian#include "kern/kern_switch.c"
2691