sched_ule.c revision 174629
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 174629 2007-12-15 23:13:31Z jeff $");
40116182Sobrien
41147565Speter#include "opt_hwpmc_hooks.h"
42147565Speter#include "opt_sched.h"
43134649Sscottl
44109864Sjeff#include <sys/param.h>
45109864Sjeff#include <sys/systm.h>
46131929Smarcel#include <sys/kdb.h>
47109864Sjeff#include <sys/kernel.h>
48109864Sjeff#include <sys/ktr.h>
49109864Sjeff#include <sys/lock.h>
50109864Sjeff#include <sys/mutex.h>
51109864Sjeff#include <sys/proc.h>
52112966Sjeff#include <sys/resource.h>
53122038Sjeff#include <sys/resourcevar.h>
54109864Sjeff#include <sys/sched.h>
55109864Sjeff#include <sys/smp.h>
56109864Sjeff#include <sys/sx.h>
57109864Sjeff#include <sys/sysctl.h>
58109864Sjeff#include <sys/sysproto.h>
59139453Sjhb#include <sys/turnstile.h>
60161599Sdavidxu#include <sys/umtx.h>
61109864Sjeff#include <sys/vmmeter.h>
62109864Sjeff#ifdef KTRACE
63109864Sjeff#include <sys/uio.h>
64109864Sjeff#include <sys/ktrace.h>
65109864Sjeff#endif
66109864Sjeff
67145256Sjkoshy#ifdef HWPMC_HOOKS
68145256Sjkoshy#include <sys/pmckern.h>
69145256Sjkoshy#endif
70145256Sjkoshy
71109864Sjeff#include <machine/cpu.h>
72121790Sjeff#include <machine/smp.h>
73109864Sjeff
74172887Sgrehan#if !defined(__i386__) && !defined(__amd64__) && !defined(__powerpc__) && !defined(__arm__)
75172345Sjeff#error "This architecture is not currently compatible with ULE"
76166190Sjeff#endif
77166190Sjeff
78171482Sjeff#define	KTR_ULE	0
79166137Sjeff
80166137Sjeff/*
81171482Sjeff * Thread scheduler specific section.  All fields are protected
82171482Sjeff * by the thread lock.
83146954Sjeff */
84164936Sjulianstruct td_sched {
85171482Sjeff	TAILQ_ENTRY(td_sched) ts_procq;	/* Run queue. */
86171482Sjeff	struct thread	*ts_thread;	/* Active associated thread. */
87171482Sjeff	struct runq	*ts_runq;	/* Run-queue we're queued on. */
88171482Sjeff	short		ts_flags;	/* TSF_* flags. */
89171482Sjeff	u_char		ts_rqindex;	/* Run queue index. */
90164936Sjulian	u_char		ts_cpu;		/* CPU that we have affinity for. */
91171482Sjeff	int		ts_slice;	/* Ticks of slice remaining. */
92171482Sjeff	u_int		ts_slptime;	/* Number of ticks we vol. slept */
93171482Sjeff	u_int		ts_runtime;	/* Number of ticks we were running */
94134791Sjulian	/* The following variables are only used for pctcpu calculation */
95164936Sjulian	int		ts_ltick;	/* Last tick that we were running on */
96164936Sjulian	int		ts_ftick;	/* First tick that we were running on */
97164936Sjulian	int		ts_ticks;	/* Tick count */
98166108Sjeff#ifdef SMP
99166108Sjeff	int		ts_rltick;	/* Real last tick, for affinity. */
100166108Sjeff#endif
101134791Sjulian};
102164936Sjulian/* flags kept in ts_flags */
103166108Sjeff#define	TSF_BOUND	0x0001		/* Thread can not migrate. */
104166108Sjeff#define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
105121790Sjeff
106164936Sjulianstatic struct td_sched td_sched0;
107109864Sjeff
108109864Sjeff/*
109165762Sjeff * Cpu percentage computation macros and defines.
110111857Sjeff *
111165762Sjeff * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
112165762Sjeff * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
113165796Sjeff * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
114165762Sjeff * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
115165762Sjeff * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
116165762Sjeff * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
117165762Sjeff */
118165762Sjeff#define	SCHED_TICK_SECS		10
119165762Sjeff#define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
120165796Sjeff#define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
121165762Sjeff#define	SCHED_TICK_SHIFT	10
122165762Sjeff#define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
123165830Sjeff#define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
124165762Sjeff
125165762Sjeff/*
126165762Sjeff * These macros determine priorities for non-interactive threads.  They are
127165762Sjeff * assigned a priority based on their recent cpu utilization as expressed
128165762Sjeff * by the ratio of ticks to the tick total.  NHALF priorities at the start
129165762Sjeff * and end of the MIN to MAX timeshare range are only reachable with negative
130165762Sjeff * or positive nice respectively.
131165762Sjeff *
132165762Sjeff * PRI_RANGE:	Priority range for utilization dependent priorities.
133116642Sjeff * PRI_NRESV:	Number of nice values.
134165762Sjeff * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
135165762Sjeff * PRI_NICE:	Determines the part of the priority inherited from nice.
136109864Sjeff */
137165762Sjeff#define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
138121869Sjeff#define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
139165762Sjeff#define	SCHED_PRI_MIN		(PRI_MIN_TIMESHARE + SCHED_PRI_NHALF)
140165762Sjeff#define	SCHED_PRI_MAX		(PRI_MAX_TIMESHARE - SCHED_PRI_NHALF)
141170787Sjeff#define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN)
142165762Sjeff#define	SCHED_PRI_TICKS(ts)						\
143165762Sjeff    (SCHED_TICK_HZ((ts)) /						\
144165827Sjeff    (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
145165762Sjeff#define	SCHED_PRI_NICE(nice)	(nice)
146109864Sjeff
147109864Sjeff/*
148165762Sjeff * These determine the interactivity of a process.  Interactivity differs from
149165762Sjeff * cpu utilization in that it expresses the voluntary time slept vs time ran
150165762Sjeff * while cpu utilization includes all time not running.  This more accurately
151165762Sjeff * models the intent of the thread.
152109864Sjeff *
153110645Sjeff * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
154110645Sjeff *		before throttling back.
155121868Sjeff * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
156116365Sjeff * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
157111857Sjeff * INTERACT_THRESH:	Threshhold for placement on the current runq.
158109864Sjeff */
159165762Sjeff#define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
160165762Sjeff#define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
161116365Sjeff#define	SCHED_INTERACT_MAX	(100)
162116365Sjeff#define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
163121126Sjeff#define	SCHED_INTERACT_THRESH	(30)
164111857Sjeff
165109864Sjeff/*
166165762Sjeff * tickincr:		Converts a stathz tick into a hz domain scaled by
167165762Sjeff *			the shift factor.  Without the shift the error rate
168165762Sjeff *			due to rounding would be unacceptably high.
169165762Sjeff * realstathz:		stathz is sometimes 0 and run off of hz.
170165762Sjeff * sched_slice:		Runtime of each thread before rescheduling.
171171482Sjeff * preempt_thresh:	Priority threshold for preemption and remote IPIs.
172109864Sjeff */
173165762Sjeffstatic int sched_interact = SCHED_INTERACT_THRESH;
174165762Sjeffstatic int realstathz;
175165762Sjeffstatic int tickincr;
176165762Sjeffstatic int sched_slice;
177172345Sjeff#ifdef PREEMPTION
178172345Sjeff#ifdef FULL_PREEMPTION
179172345Sjeffstatic int preempt_thresh = PRI_MAX_IDLE;
180172345Sjeff#else
181171482Sjeffstatic int preempt_thresh = PRI_MIN_KERN;
182172345Sjeff#endif
183172345Sjeff#else
184172345Sjeffstatic int preempt_thresh = 0;
185172345Sjeff#endif
186109864Sjeff
187109864Sjeff/*
188171482Sjeff * tdq - per processor runqs and statistics.  All fields are protected by the
189171482Sjeff * tdq_lock.  The load and lowpri may be accessed without to avoid excess
190171482Sjeff * locking in sched_pickcpu();
191109864Sjeff */
192164936Sjulianstruct tdq {
193171713Sjeff	struct mtx	*tdq_lock;		/* Pointer to group lock. */
194171482Sjeff	struct runq	tdq_realtime;		/* real-time run queue. */
195171482Sjeff	struct runq	tdq_timeshare;		/* timeshare run queue. */
196165620Sjeff	struct runq	tdq_idle;		/* Queue of IDLE threads. */
197171482Sjeff	int		tdq_load;		/* Aggregate load. */
198166557Sjeff	u_char		tdq_idx;		/* Current insert index. */
199166557Sjeff	u_char		tdq_ridx;		/* Current removal index. */
200110267Sjeff#ifdef SMP
201171482Sjeff	u_char		tdq_lowpri;		/* Lowest priority thread. */
202171482Sjeff	int		tdq_transferable;	/* Transferable thread count. */
203165620Sjeff	LIST_ENTRY(tdq)	tdq_siblings;		/* Next in tdq group. */
204165620Sjeff	struct tdq_group *tdq_group;		/* Our processor group. */
205125289Sjeff#else
206165620Sjeff	int		tdq_sysload;		/* For loadavg, !ITHD load. */
207110267Sjeff#endif
208171482Sjeff} __aligned(64);
209109864Sjeff
210166108Sjeff
211123433Sjeff#ifdef SMP
212109864Sjeff/*
213164936Sjulian * tdq groups are groups of processors which can cheaply share threads.  When
214123433Sjeff * one processor in the group goes idle it will check the runqs of the other
215123433Sjeff * processors in its group prior to halting and waiting for an interrupt.
216123433Sjeff * These groups are suitable for SMT (Symetric Multi-Threading) and not NUMA.
217123433Sjeff * In a numa environment we'd want an idle bitmap per group and a two tiered
218123433Sjeff * load balancer.
219123433Sjeff */
220164936Sjulianstruct tdq_group {
221171713Sjeff	struct mtx	tdg_lock;	/* Protects all fields below. */
222171713Sjeff	int		tdg_cpus;	/* Count of CPUs in this tdq group. */
223171713Sjeff	cpumask_t 	tdg_cpumask;	/* Mask of cpus in this group. */
224171713Sjeff	cpumask_t 	tdg_idlemask;	/* Idle cpus in this group. */
225171713Sjeff	cpumask_t 	tdg_mask;	/* Bit mask for first cpu. */
226171713Sjeff	int		tdg_load;	/* Total load of this group. */
227165620Sjeff	int	tdg_transferable;	/* Transferable load of this group. */
228165620Sjeff	LIST_HEAD(, tdq) tdg_members;	/* Linked list of all members. */
229171713Sjeff	char		tdg_name[16];	/* lock name. */
230171482Sjeff} __aligned(64);
231123433Sjeff
232171482Sjeff#define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 300))
233166108Sjeff#define	SCHED_AFFINITY(ts)	((ts)->ts_rltick > ticks - affinity)
234166108Sjeff
235123433Sjeff/*
236166108Sjeff * Run-time tunables.
237166108Sjeff */
238171506Sjeffstatic int rebalance = 1;
239172409Sjeffstatic int balance_interval = 128;	/* Default set in sched_initticks(). */
240171506Sjeffstatic int pick_pri = 1;
241166108Sjeffstatic int affinity;
242166108Sjeffstatic int tryself = 1;
243172409Sjeffstatic int steal_htt = 1;
244171506Sjeffstatic int steal_idle = 1;
245171506Sjeffstatic int steal_thresh = 2;
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",
342173600Sjulian					    ts->ts_thread, ts->ts_thread->td_name, 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 cpu;
744123433Sjeff
745172484Sjeff	if (smp_started == 0 || steal_idle == 0)
746172484Sjeff		return (1);
747171482Sjeff	/* We don't want to be preempted while we're iterating over tdqs */
748171482Sjeff	spinlock_enter();
749165620Sjeff	tdg = tdq->tdq_group;
750123433Sjeff	/*
751165620Sjeff	 * If we're in a cpu group, try and steal threads from another cpu in
752172409Sjeff	 * the group before idling.  In a HTT group all cpus share the same
753172409Sjeff	 * run-queue lock, however, we still need a recursive lock to
754172409Sjeff	 * call tdq_move().
755123433Sjeff	 */
756166108Sjeff	if (steal_htt && tdg->tdg_cpus > 1 && tdg->tdg_transferable) {
757172409Sjeff		TDQ_LOCK(tdq);
758165620Sjeff		LIST_FOREACH(steal, &tdg->tdg_members, tdq_siblings) {
759165620Sjeff			if (steal == tdq || steal->tdq_transferable == 0)
760123433Sjeff				continue;
761171482Sjeff			TDQ_LOCK(steal);
762172409Sjeff			goto steal;
763166108Sjeff		}
764172409Sjeff		TDQ_UNLOCK(tdq);
765166108Sjeff	}
766172484Sjeff	/*
767172484Sjeff	 * Find the least loaded CPU with a transferable thread and attempt
768172484Sjeff	 * to steal it.  We make a lockless pass and then verify that the
769172484Sjeff	 * thread is still available after locking.
770172484Sjeff	 */
771171482Sjeff	for (;;) {
772171482Sjeff		highcpu = 0;
773171482Sjeff		highload = 0;
774171482Sjeff		for (cpu = 0; cpu <= mp_maxid; cpu++) {
775171482Sjeff			if (CPU_ABSENT(cpu))
776171482Sjeff				continue;
777166108Sjeff			steal = TDQ_CPU(cpu);
778172484Sjeff			if (steal->tdq_transferable == 0)
779166108Sjeff				continue;
780172484Sjeff			if (steal->tdq_load < highload)
781172484Sjeff				continue;
782172484Sjeff			highload = steal->tdq_load;
783171482Sjeff			highcpu = cpu;
784171482Sjeff		}
785171506Sjeff		if (highload < steal_thresh)
786171482Sjeff			break;
787171482Sjeff		steal = TDQ_CPU(highcpu);
788172484Sjeff		if (steal == tdq)
789172484Sjeff			break;
790172409Sjeff		tdq_lock_pair(tdq, steal);
791172484Sjeff		if (steal->tdq_load >= steal_thresh && steal->tdq_transferable)
792166108Sjeff			goto steal;
793172409Sjeff		tdq_unlock_pair(tdq, steal);
794123433Sjeff	}
795171482Sjeff	spinlock_exit();
796123433Sjeff	return (1);
797166108Sjeffsteal:
798171482Sjeff	spinlock_exit();
799172409Sjeff	tdq_move(steal, tdq);
800171482Sjeff	TDQ_UNLOCK(steal);
801171482Sjeff	mi_switch(SW_VOL, NULL);
802171482Sjeff	thread_unlock(curthread);
803121790Sjeff
804166108Sjeff	return (0);
805121790Sjeff}
806121790Sjeff
807171482Sjeff/*
808171482Sjeff * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
809171482Sjeff */
810121790Sjeffstatic void
811166108Sjefftdq_notify(struct td_sched *ts)
812121790Sjeff{
813166247Sjeff	struct thread *ctd;
814121790Sjeff	struct pcpu *pcpu;
815166247Sjeff	int cpri;
816166247Sjeff	int pri;
817166108Sjeff	int cpu;
818121790Sjeff
819166108Sjeff	cpu = ts->ts_cpu;
820166247Sjeff	pri = ts->ts_thread->td_priority;
821166108Sjeff	pcpu = pcpu_find(cpu);
822166247Sjeff	ctd = pcpu->pc_curthread;
823166247Sjeff	cpri = ctd->td_priority;
824166137Sjeff
825121790Sjeff	/*
826166137Sjeff	 * If our priority is not better than the current priority there is
827166137Sjeff	 * nothing to do.
828166137Sjeff	 */
829166247Sjeff	if (pri > cpri)
830166137Sjeff		return;
831166137Sjeff	/*
832166247Sjeff	 * Always IPI idle.
833121790Sjeff	 */
834166247Sjeff	if (cpri > PRI_MIN_IDLE)
835166247Sjeff		goto sendipi;
836166247Sjeff	/*
837166247Sjeff	 * If we're realtime or better and there is timeshare or worse running
838166247Sjeff	 * send an IPI.
839166247Sjeff	 */
840166247Sjeff	if (pri < PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
841166247Sjeff		goto sendipi;
842166247Sjeff	/*
843166247Sjeff	 * Otherwise only IPI if we exceed the threshold.
844166247Sjeff	 */
845171482Sjeff	if (pri > preempt_thresh)
846165819Sjeff		return;
847166247Sjeffsendipi:
848166247Sjeff	ctd->td_flags |= TDF_NEEDRESCHED;
849171482Sjeff	ipi_selected(1 << cpu, IPI_PREEMPT);
850121790Sjeff}
851121790Sjeff
852171482Sjeff/*
853171482Sjeff * Steals load from a timeshare queue.  Honors the rotating queue head
854171482Sjeff * index.
855171482Sjeff */
856164936Sjulianstatic struct td_sched *
857171482Sjeffrunq_steal_from(struct runq *rq, u_char start)
858171482Sjeff{
859171482Sjeff	struct td_sched *ts;
860171482Sjeff	struct rqbits *rqb;
861171482Sjeff	struct rqhead *rqh;
862171482Sjeff	int first;
863171482Sjeff	int bit;
864171482Sjeff	int pri;
865171482Sjeff	int i;
866171482Sjeff
867171482Sjeff	rqb = &rq->rq_status;
868171482Sjeff	bit = start & (RQB_BPW -1);
869171482Sjeff	pri = 0;
870171482Sjeff	first = 0;
871171482Sjeffagain:
872171482Sjeff	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
873171482Sjeff		if (rqb->rqb_bits[i] == 0)
874171482Sjeff			continue;
875171482Sjeff		if (bit != 0) {
876171482Sjeff			for (pri = bit; pri < RQB_BPW; pri++)
877171482Sjeff				if (rqb->rqb_bits[i] & (1ul << pri))
878171482Sjeff					break;
879171482Sjeff			if (pri >= RQB_BPW)
880171482Sjeff				continue;
881171482Sjeff		} else
882171482Sjeff			pri = RQB_FFS(rqb->rqb_bits[i]);
883171482Sjeff		pri += (i << RQB_L2BPW);
884171482Sjeff		rqh = &rq->rq_queues[pri];
885171482Sjeff		TAILQ_FOREACH(ts, rqh, ts_procq) {
886171482Sjeff			if (first && THREAD_CAN_MIGRATE(ts->ts_thread))
887171482Sjeff				return (ts);
888171482Sjeff			first = 1;
889171482Sjeff		}
890171482Sjeff	}
891171482Sjeff	if (start != 0) {
892171482Sjeff		start = 0;
893171482Sjeff		goto again;
894171482Sjeff	}
895171482Sjeff
896171482Sjeff	return (NULL);
897171482Sjeff}
898171482Sjeff
899171482Sjeff/*
900171482Sjeff * Steals load from a standard linear queue.
901171482Sjeff */
902171482Sjeffstatic struct td_sched *
903121790Sjeffrunq_steal(struct runq *rq)
904121790Sjeff{
905121790Sjeff	struct rqhead *rqh;
906121790Sjeff	struct rqbits *rqb;
907164936Sjulian	struct td_sched *ts;
908121790Sjeff	int word;
909121790Sjeff	int bit;
910121790Sjeff
911121790Sjeff	rqb = &rq->rq_status;
912121790Sjeff	for (word = 0; word < RQB_LEN; word++) {
913121790Sjeff		if (rqb->rqb_bits[word] == 0)
914121790Sjeff			continue;
915121790Sjeff		for (bit = 0; bit < RQB_BPW; bit++) {
916123231Speter			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
917121790Sjeff				continue;
918121790Sjeff			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
919171506Sjeff			TAILQ_FOREACH(ts, rqh, ts_procq)
920171506Sjeff				if (THREAD_CAN_MIGRATE(ts->ts_thread))
921164936Sjulian					return (ts);
922121790Sjeff		}
923121790Sjeff	}
924121790Sjeff	return (NULL);
925121790Sjeff}
926121790Sjeff
927171482Sjeff/*
928171482Sjeff * Attempt to steal a thread in priority order from a thread queue.
929171482Sjeff */
930164936Sjulianstatic struct td_sched *
931172409Sjefftdq_steal(struct tdq *tdq)
932121790Sjeff{
933164936Sjulian	struct td_sched *ts;
934121790Sjeff
935171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
936165762Sjeff	if ((ts = runq_steal(&tdq->tdq_realtime)) != NULL)
937164936Sjulian		return (ts);
938171482Sjeff	if ((ts = runq_steal_from(&tdq->tdq_timeshare, tdq->tdq_ridx)) != NULL)
939164936Sjulian		return (ts);
940172409Sjeff	return (runq_steal(&tdq->tdq_idle));
941121790Sjeff}
942123433Sjeff
943171482Sjeff/*
944171482Sjeff * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
945172409Sjeff * current lock and returns with the assigned queue locked.
946171482Sjeff */
947171482Sjeffstatic inline struct tdq *
948171482Sjeffsched_setcpu(struct td_sched *ts, int cpu, int flags)
949123433Sjeff{
950171482Sjeff	struct thread *td;
951171482Sjeff	struct tdq *tdq;
952123433Sjeff
953171482Sjeff	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
954171482Sjeff
955171482Sjeff	tdq = TDQ_CPU(cpu);
956171482Sjeff	td = ts->ts_thread;
957171482Sjeff	ts->ts_cpu = cpu;
958171713Sjeff
959171713Sjeff	/* If the lock matches just return the queue. */
960171482Sjeff	if (td->td_lock == TDQ_LOCKPTR(tdq))
961171482Sjeff		return (tdq);
962171482Sjeff#ifdef notyet
963123433Sjeff	/*
964172293Sjeff	 * If the thread isn't running its lockptr is a
965171482Sjeff	 * turnstile or a sleepqueue.  We can just lock_set without
966171482Sjeff	 * blocking.
967123685Sjeff	 */
968171482Sjeff	if (TD_CAN_RUN(td)) {
969171482Sjeff		TDQ_LOCK(tdq);
970171482Sjeff		thread_lock_set(td, TDQ_LOCKPTR(tdq));
971171482Sjeff		return (tdq);
972171482Sjeff	}
973171482Sjeff#endif
974166108Sjeff	/*
975171482Sjeff	 * The hard case, migration, we need to block the thread first to
976171482Sjeff	 * prevent order reversals with other cpus locks.
977166108Sjeff	 */
978171482Sjeff	thread_lock_block(td);
979171482Sjeff	TDQ_LOCK(tdq);
980171713Sjeff	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
981171482Sjeff	return (tdq);
982166108Sjeff}
983166108Sjeff
984171482Sjeff/*
985171482Sjeff * Find the thread queue running the lowest priority thread.
986171482Sjeff */
987166108Sjeffstatic int
988171482Sjefftdq_lowestpri(void)
989166108Sjeff{
990171482Sjeff	struct tdq *tdq;
991166108Sjeff	int lowpri;
992166108Sjeff	int lowcpu;
993166108Sjeff	int lowload;
994166108Sjeff	int load;
995171482Sjeff	int cpu;
996171482Sjeff	int pri;
997171482Sjeff
998171482Sjeff	lowload = 0;
999171482Sjeff	lowpri = lowcpu = 0;
1000171482Sjeff	for (cpu = 0; cpu <= mp_maxid; cpu++) {
1001171482Sjeff		if (CPU_ABSENT(cpu))
1002171482Sjeff			continue;
1003171482Sjeff		tdq = TDQ_CPU(cpu);
1004171482Sjeff		pri = tdq->tdq_lowpri;
1005171482Sjeff		load = TDQ_CPU(cpu)->tdq_load;
1006171482Sjeff		CTR4(KTR_ULE,
1007171482Sjeff		    "cpu %d pri %d lowcpu %d lowpri %d",
1008171482Sjeff		    cpu, pri, lowcpu, lowpri);
1009171482Sjeff		if (pri < lowpri)
1010171482Sjeff			continue;
1011171482Sjeff		if (lowpri && lowpri == pri && load > lowload)
1012171482Sjeff			continue;
1013171482Sjeff		lowpri = pri;
1014171482Sjeff		lowcpu = cpu;
1015171482Sjeff		lowload = load;
1016171482Sjeff	}
1017171482Sjeff
1018171482Sjeff	return (lowcpu);
1019171482Sjeff}
1020171482Sjeff
1021171482Sjeff/*
1022171482Sjeff * Find the thread queue with the least load.
1023171482Sjeff */
1024171482Sjeffstatic int
1025171482Sjefftdq_lowestload(void)
1026171482Sjeff{
1027171482Sjeff	struct tdq *tdq;
1028171482Sjeff	int lowload;
1029171482Sjeff	int lowpri;
1030171482Sjeff	int lowcpu;
1031171482Sjeff	int load;
1032171482Sjeff	int cpu;
1033171482Sjeff	int pri;
1034171482Sjeff
1035171482Sjeff	lowcpu = 0;
1036171482Sjeff	lowload = TDQ_CPU(0)->tdq_load;
1037171482Sjeff	lowpri = TDQ_CPU(0)->tdq_lowpri;
1038171482Sjeff	for (cpu = 1; cpu <= mp_maxid; cpu++) {
1039171482Sjeff		if (CPU_ABSENT(cpu))
1040171482Sjeff			continue;
1041171482Sjeff		tdq = TDQ_CPU(cpu);
1042171482Sjeff		load = tdq->tdq_load;
1043171482Sjeff		pri = tdq->tdq_lowpri;
1044171482Sjeff		CTR4(KTR_ULE, "cpu %d load %d lowcpu %d lowload %d",
1045171482Sjeff		    cpu, load, lowcpu, lowload);
1046171482Sjeff		if (load > lowload)
1047171482Sjeff			continue;
1048171482Sjeff		if (load == lowload && pri < lowpri)
1049171482Sjeff			continue;
1050171482Sjeff		lowcpu = cpu;
1051171482Sjeff		lowload = load;
1052171482Sjeff		lowpri = pri;
1053171482Sjeff	}
1054171482Sjeff
1055171482Sjeff	return (lowcpu);
1056171482Sjeff}
1057171482Sjeff
1058171482Sjeff/*
1059171482Sjeff * Pick the destination cpu for sched_add().  Respects affinity and makes
1060171482Sjeff * a determination based on load or priority of available processors.
1061171482Sjeff */
1062171482Sjeffstatic int
1063171482Sjeffsched_pickcpu(struct td_sched *ts, int flags)
1064171482Sjeff{
1065171482Sjeff	struct tdq *tdq;
1066166108Sjeff	int self;
1067166108Sjeff	int pri;
1068166108Sjeff	int cpu;
1069166108Sjeff
1070171482Sjeff	cpu = self = PCPU_GET(cpuid);
1071166108Sjeff	if (smp_started == 0)
1072166108Sjeff		return (self);
1073171506Sjeff	/*
1074171506Sjeff	 * Don't migrate a running thread from sched_switch().
1075171506Sjeff	 */
1076171506Sjeff	if (flags & SRQ_OURSELF) {
1077171506Sjeff		CTR1(KTR_ULE, "YIELDING %d",
1078171506Sjeff		    curthread->td_priority);
1079171506Sjeff		return (self);
1080171506Sjeff	}
1081166108Sjeff	pri = ts->ts_thread->td_priority;
1082171482Sjeff	cpu = ts->ts_cpu;
1083166108Sjeff	/*
1084166108Sjeff	 * Regardless of affinity, if the last cpu is idle send it there.
1085166108Sjeff	 */
1086171482Sjeff	tdq = TDQ_CPU(cpu);
1087171482Sjeff	if (tdq->tdq_lowpri > PRI_MIN_IDLE) {
1088166229Sjeff		CTR5(KTR_ULE,
1089166108Sjeff		    "ts_cpu %d idle, ltick %d ticks %d pri %d curthread %d",
1090166108Sjeff		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1091171482Sjeff		    tdq->tdq_lowpri);
1092166108Sjeff		return (ts->ts_cpu);
1093123433Sjeff	}
1094166108Sjeff	/*
1095166108Sjeff	 * If we have affinity, try to place it on the cpu we last ran on.
1096166108Sjeff	 */
1097171482Sjeff	if (SCHED_AFFINITY(ts) && tdq->tdq_lowpri > pri) {
1098166229Sjeff		CTR5(KTR_ULE,
1099166108Sjeff		    "affinity for %d, ltick %d ticks %d pri %d curthread %d",
1100166108Sjeff		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1101171482Sjeff		    tdq->tdq_lowpri);
1102166108Sjeff		return (ts->ts_cpu);
1103139334Sjeff	}
1104123433Sjeff	/*
1105166108Sjeff	 * Look for an idle group.
1106123433Sjeff	 */
1107166229Sjeff	CTR1(KTR_ULE, "tdq_idle %X", tdq_idle);
1108166108Sjeff	cpu = ffs(tdq_idle);
1109166108Sjeff	if (cpu)
1110171482Sjeff		return (--cpu);
1111171506Sjeff	/*
1112172409Sjeff	 * If there are no idle cores see if we can run the thread locally.
1113172409Sjeff	 * This may improve locality among sleepers and wakers when there
1114172409Sjeff	 * is shared data.
1115171506Sjeff	 */
1116171506Sjeff	if (tryself && pri < curthread->td_priority) {
1117171506Sjeff		CTR1(KTR_ULE, "tryself %d",
1118166108Sjeff		    curthread->td_priority);
1119166108Sjeff		return (self);
1120123433Sjeff	}
1121133427Sjeff	/*
1122166108Sjeff 	 * Now search for the cpu running the lowest priority thread with
1123166108Sjeff	 * the least load.
1124123433Sjeff	 */
1125171482Sjeff	if (pick_pri)
1126171482Sjeff		cpu = tdq_lowestpri();
1127171482Sjeff	else
1128171482Sjeff		cpu = tdq_lowestload();
1129171482Sjeff	return (cpu);
1130123433Sjeff}
1131123433Sjeff
1132121790Sjeff#endif	/* SMP */
1133121790Sjeff
1134117326Sjeff/*
1135121790Sjeff * Pick the highest priority task we have and return it.
1136117326Sjeff */
1137164936Sjulianstatic struct td_sched *
1138164936Sjuliantdq_choose(struct tdq *tdq)
1139110267Sjeff{
1140164936Sjulian	struct td_sched *ts;
1141110267Sjeff
1142171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1143165762Sjeff	ts = runq_choose(&tdq->tdq_realtime);
1144170787Sjeff	if (ts != NULL)
1145164936Sjulian		return (ts);
1146165766Sjeff	ts = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1147165762Sjeff	if (ts != NULL) {
1148170787Sjeff		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_TIMESHARE,
1149165762Sjeff		    ("tdq_choose: Invalid priority on timeshare queue %d",
1150165762Sjeff		    ts->ts_thread->td_priority));
1151165762Sjeff		return (ts);
1152165762Sjeff	}
1153110267Sjeff
1154165762Sjeff	ts = runq_choose(&tdq->tdq_idle);
1155165762Sjeff	if (ts != NULL) {
1156165762Sjeff		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_IDLE,
1157165762Sjeff		    ("tdq_choose: Invalid priority on idle queue %d",
1158165762Sjeff		    ts->ts_thread->td_priority));
1159165762Sjeff		return (ts);
1160165762Sjeff	}
1161165762Sjeff
1162165762Sjeff	return (NULL);
1163110267Sjeff}
1164110267Sjeff
1165171482Sjeff/*
1166171482Sjeff * Initialize a thread queue.
1167171482Sjeff */
1168109864Sjeffstatic void
1169164936Sjuliantdq_setup(struct tdq *tdq)
1170110028Sjeff{
1171171482Sjeff
1172171713Sjeff	if (bootverbose)
1173171713Sjeff		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1174165762Sjeff	runq_init(&tdq->tdq_realtime);
1175165762Sjeff	runq_init(&tdq->tdq_timeshare);
1176165620Sjeff	runq_init(&tdq->tdq_idle);
1177165620Sjeff	tdq->tdq_load = 0;
1178110028Sjeff}
1179110028Sjeff
1180171713Sjeff#ifdef SMP
1181110028Sjeffstatic void
1182171713Sjefftdg_setup(struct tdq_group *tdg)
1183109864Sjeff{
1184171713Sjeff	if (bootverbose)
1185171713Sjeff		printf("ULE: setup cpu group %d\n", TDG_ID(tdg));
1186171713Sjeff	snprintf(tdg->tdg_name, sizeof(tdg->tdg_name),
1187171713Sjeff	    "sched lock %d", (int)TDG_ID(tdg));
1188171713Sjeff	mtx_init(&tdg->tdg_lock, tdg->tdg_name, "sched lock",
1189171713Sjeff	    MTX_SPIN | MTX_RECURSE);
1190171713Sjeff	LIST_INIT(&tdg->tdg_members);
1191171713Sjeff	tdg->tdg_load = 0;
1192171713Sjeff	tdg->tdg_transferable = 0;
1193171713Sjeff	tdg->tdg_cpus = 0;
1194171713Sjeff	tdg->tdg_mask = 0;
1195171713Sjeff	tdg->tdg_cpumask = 0;
1196171713Sjeff	tdg->tdg_idlemask = 0;
1197171713Sjeff}
1198171713Sjeff
1199171713Sjeffstatic void
1200171713Sjefftdg_add(struct tdq_group *tdg, struct tdq *tdq)
1201171713Sjeff{
1202171713Sjeff	if (tdg->tdg_mask == 0)
1203171713Sjeff		tdg->tdg_mask |= 1 << TDQ_ID(tdq);
1204171713Sjeff	tdg->tdg_cpumask |= 1 << TDQ_ID(tdq);
1205171713Sjeff	tdg->tdg_cpus++;
1206171713Sjeff	tdq->tdq_group = tdg;
1207171713Sjeff	tdq->tdq_lock = &tdg->tdg_lock;
1208171713Sjeff	LIST_INSERT_HEAD(&tdg->tdg_members, tdq, tdq_siblings);
1209171713Sjeff	if (bootverbose)
1210171713Sjeff		printf("ULE: adding cpu %d to group %d: cpus %d mask 0x%X\n",
1211171713Sjeff		    TDQ_ID(tdq), TDG_ID(tdg), tdg->tdg_cpus, tdg->tdg_cpumask);
1212171713Sjeff}
1213171713Sjeff
1214171713Sjeffstatic void
1215171713Sjeffsched_setup_topology(void)
1216171713Sjeff{
1217171713Sjeff	struct tdq_group *tdg;
1218171713Sjeff	struct cpu_group *cg;
1219171713Sjeff	int balance_groups;
1220171482Sjeff	struct tdq *tdq;
1221109864Sjeff	int i;
1222171713Sjeff	int j;
1223109864Sjeff
1224171713Sjeff	topology = 1;
1225123487Sjeff	balance_groups = 0;
1226171713Sjeff	for (i = 0; i < smp_topology->ct_count; i++) {
1227171713Sjeff		cg = &smp_topology->ct_group[i];
1228171713Sjeff		tdg = &tdq_groups[i];
1229171713Sjeff		/*
1230171713Sjeff		 * Initialize the group.
1231171713Sjeff		 */
1232171713Sjeff		tdg_setup(tdg);
1233171713Sjeff		/*
1234171713Sjeff		 * Find all of the group members and add them.
1235171713Sjeff		 */
1236171713Sjeff		for (j = 0; j < MAXCPU; j++) {
1237171713Sjeff			if ((cg->cg_mask & (1 << j)) != 0) {
1238171713Sjeff				tdq = TDQ_CPU(j);
1239171713Sjeff				tdq_setup(tdq);
1240171713Sjeff				tdg_add(tdg, tdq);
1241171713Sjeff			}
1242171713Sjeff		}
1243171713Sjeff		if (tdg->tdg_cpus > 1)
1244171713Sjeff			balance_groups = 1;
1245171713Sjeff	}
1246171713Sjeff	tdg_maxid = smp_topology->ct_count - 1;
1247171713Sjeff	if (balance_groups)
1248172409Sjeff		sched_balance_groups();
1249171713Sjeff}
1250171713Sjeff
1251171713Sjeffstatic void
1252171713Sjeffsched_setup_smp(void)
1253171713Sjeff{
1254171713Sjeff	struct tdq_group *tdg;
1255171713Sjeff	struct tdq *tdq;
1256171713Sjeff	int cpus;
1257171713Sjeff	int i;
1258171713Sjeff
1259171713Sjeff	for (cpus = 0, i = 0; i < MAXCPU; i++) {
1260171713Sjeff		if (CPU_ABSENT(i))
1261171713Sjeff			continue;
1262165627Sjeff		tdq = &tdq_cpu[i];
1263171713Sjeff		tdg = &tdq_groups[i];
1264171713Sjeff		/*
1265171713Sjeff		 * Setup a tdq group with one member.
1266171713Sjeff		 */
1267171713Sjeff		tdg_setup(tdg);
1268171713Sjeff		tdq_setup(tdq);
1269171713Sjeff		tdg_add(tdg, tdq);
1270171713Sjeff		cpus++;
1271123433Sjeff	}
1272171713Sjeff	tdg_maxid = cpus - 1;
1273171713Sjeff}
1274123433Sjeff
1275171713Sjeff/*
1276171713Sjeff * Fake a topology with one group containing all CPUs.
1277171713Sjeff */
1278171713Sjeffstatic void
1279171713Sjeffsched_fake_topo(void)
1280171713Sjeff{
1281171713Sjeff#ifdef SCHED_FAKE_TOPOLOGY
1282171713Sjeff	static struct cpu_top top;
1283171713Sjeff	static struct cpu_group group;
1284113357Sjeff
1285171713Sjeff	top.ct_count = 1;
1286171713Sjeff	top.ct_group = &group;
1287171713Sjeff	group.cg_mask = all_cpus;
1288171713Sjeff	group.cg_count = mp_ncpus;
1289171713Sjeff	group.cg_children = 0;
1290171713Sjeff	smp_topology = &top;
1291171713Sjeff#endif
1292171713Sjeff}
1293171713Sjeff#endif
1294171713Sjeff
1295171713Sjeff/*
1296171713Sjeff * Setup the thread queues and initialize the topology based on MD
1297171713Sjeff * information.
1298171713Sjeff */
1299171713Sjeffstatic void
1300171713Sjeffsched_setup(void *dummy)
1301171713Sjeff{
1302171713Sjeff	struct tdq *tdq;
1303171713Sjeff
1304171713Sjeff	tdq = TDQ_SELF();
1305171713Sjeff#ifdef SMP
1306171713Sjeff	sched_fake_topo();
1307171713Sjeff	/*
1308171713Sjeff	 * Setup tdqs based on a topology configuration or vanilla SMP based
1309171713Sjeff	 * on mp_maxid.
1310171713Sjeff	 */
1311171713Sjeff	if (smp_topology == NULL)
1312171713Sjeff		sched_setup_smp();
1313171713Sjeff	else
1314171713Sjeff		sched_setup_topology();
1315172409Sjeff	balance_tdq = tdq;
1316172409Sjeff	sched_balance();
1317117237Sjeff#else
1318171713Sjeff	tdq_setup(tdq);
1319171713Sjeff	mtx_init(&tdq_lock, "sched lock", "sched lock", MTX_SPIN | MTX_RECURSE);
1320171713Sjeff	tdq->tdq_lock = &tdq_lock;
1321116069Sjeff#endif
1322171482Sjeff	/*
1323171482Sjeff	 * To avoid divide-by-zero, we set realstathz a dummy value
1324171482Sjeff	 * in case which sched_clock() called before sched_initticks().
1325171482Sjeff	 */
1326171482Sjeff	realstathz = hz;
1327171482Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1328171482Sjeff	tickincr = 1 << SCHED_TICK_SHIFT;
1329171482Sjeff
1330171482Sjeff	/* Add thread0's load since it's running. */
1331171482Sjeff	TDQ_LOCK(tdq);
1332171713Sjeff	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1333171482Sjeff	tdq_load_add(tdq, &td_sched0);
1334171482Sjeff	TDQ_UNLOCK(tdq);
1335109864Sjeff}
1336109864Sjeff
1337171482Sjeff/*
1338171482Sjeff * This routine determines the tickincr after stathz and hz are setup.
1339171482Sjeff */
1340153533Sdavidxu/* ARGSUSED */
1341153533Sdavidxustatic void
1342153533Sdavidxusched_initticks(void *dummy)
1343153533Sdavidxu{
1344171482Sjeff	int incr;
1345171482Sjeff
1346153533Sdavidxu	realstathz = stathz ? stathz : hz;
1347166229Sjeff	sched_slice = (realstathz/10);	/* ~100ms */
1348153533Sdavidxu
1349153533Sdavidxu	/*
1350165762Sjeff	 * tickincr is shifted out by 10 to avoid rounding errors due to
1351165766Sjeff	 * hz not being evenly divisible by stathz on all platforms.
1352153533Sdavidxu	 */
1353171482Sjeff	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1354165762Sjeff	/*
1355165762Sjeff	 * This does not work for values of stathz that are more than
1356165762Sjeff	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1357165762Sjeff	 */
1358171482Sjeff	if (incr == 0)
1359171482Sjeff		incr = 1;
1360171482Sjeff	tickincr = incr;
1361166108Sjeff#ifdef SMP
1362171899Sjeff	/*
1363172409Sjeff	 * Set the default balance interval now that we know
1364172409Sjeff	 * what realstathz is.
1365172409Sjeff	 */
1366172409Sjeff	balance_interval = realstathz;
1367172409Sjeff	/*
1368171899Sjeff	 * Set steal thresh to log2(mp_ncpu) but no greater than 4.  This
1369171899Sjeff	 * prevents excess thrashing on large machines and excess idle on
1370171899Sjeff	 * smaller machines.
1371171899Sjeff	 */
1372171899Sjeff	steal_thresh = min(ffs(mp_ncpus) - 1, 4);
1373166108Sjeff	affinity = SCHED_AFFINITY_DEFAULT;
1374166108Sjeff#endif
1375153533Sdavidxu}
1376153533Sdavidxu
1377153533Sdavidxu
1378109864Sjeff/*
1379171482Sjeff * This is the core of the interactivity algorithm.  Determines a score based
1380171482Sjeff * on past behavior.  It is the ratio of sleep time to run time scaled to
1381171482Sjeff * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1382171482Sjeff * differs from the cpu usage because it does not account for time spent
1383171482Sjeff * waiting on a run-queue.  Would be prettier if we had floating point.
1384171482Sjeff */
1385171482Sjeffstatic int
1386171482Sjeffsched_interact_score(struct thread *td)
1387171482Sjeff{
1388171482Sjeff	struct td_sched *ts;
1389171482Sjeff	int div;
1390171482Sjeff
1391171482Sjeff	ts = td->td_sched;
1392171482Sjeff	/*
1393171482Sjeff	 * The score is only needed if this is likely to be an interactive
1394171482Sjeff	 * task.  Don't go through the expense of computing it if there's
1395171482Sjeff	 * no chance.
1396171482Sjeff	 */
1397171482Sjeff	if (sched_interact <= SCHED_INTERACT_HALF &&
1398171482Sjeff		ts->ts_runtime >= ts->ts_slptime)
1399171482Sjeff			return (SCHED_INTERACT_HALF);
1400171482Sjeff
1401171482Sjeff	if (ts->ts_runtime > ts->ts_slptime) {
1402171482Sjeff		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1403171482Sjeff		return (SCHED_INTERACT_HALF +
1404171482Sjeff		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1405171482Sjeff	}
1406171482Sjeff	if (ts->ts_slptime > ts->ts_runtime) {
1407171482Sjeff		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1408171482Sjeff		return (ts->ts_runtime / div);
1409171482Sjeff	}
1410171482Sjeff	/* runtime == slptime */
1411171482Sjeff	if (ts->ts_runtime)
1412171482Sjeff		return (SCHED_INTERACT_HALF);
1413171482Sjeff
1414171482Sjeff	/*
1415171482Sjeff	 * This can happen if slptime and runtime are 0.
1416171482Sjeff	 */
1417171482Sjeff	return (0);
1418171482Sjeff
1419171482Sjeff}
1420171482Sjeff
1421171482Sjeff/*
1422109864Sjeff * Scale the scheduling priority according to the "interactivity" of this
1423109864Sjeff * process.
1424109864Sjeff */
1425113357Sjeffstatic void
1426163709Sjbsched_priority(struct thread *td)
1427109864Sjeff{
1428165762Sjeff	int score;
1429109864Sjeff	int pri;
1430109864Sjeff
1431163709Sjb	if (td->td_pri_class != PRI_TIMESHARE)
1432113357Sjeff		return;
1433112966Sjeff	/*
1434165762Sjeff	 * If the score is interactive we place the thread in the realtime
1435165762Sjeff	 * queue with a priority that is less than kernel and interrupt
1436165762Sjeff	 * priorities.  These threads are not subject to nice restrictions.
1437112966Sjeff	 *
1438171482Sjeff	 * Scores greater than this are placed on the normal timeshare queue
1439165762Sjeff	 * where the priority is partially decided by the most recent cpu
1440165762Sjeff	 * utilization and the rest is decided by nice value.
1441172293Sjeff	 *
1442172293Sjeff	 * The nice value of the process has a linear effect on the calculated
1443172293Sjeff	 * score.  Negative nice values make it easier for a thread to be
1444172293Sjeff	 * considered interactive.
1445112966Sjeff	 */
1446172308Sjeff	score = imax(0, sched_interact_score(td) - td->td_proc->p_nice);
1447165762Sjeff	if (score < sched_interact) {
1448165762Sjeff		pri = PRI_MIN_REALTIME;
1449165762Sjeff		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1450165762Sjeff		    * score;
1451165762Sjeff		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1452166208Sjeff		    ("sched_priority: invalid interactive priority %d score %d",
1453166208Sjeff		    pri, score));
1454165762Sjeff	} else {
1455165762Sjeff		pri = SCHED_PRI_MIN;
1456165762Sjeff		if (td->td_sched->ts_ticks)
1457165762Sjeff			pri += SCHED_PRI_TICKS(td->td_sched);
1458165762Sjeff		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1459171482Sjeff		KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1460171482Sjeff		    ("sched_priority: invalid priority %d: nice %d, "
1461171482Sjeff		    "ticks %d ftick %d ltick %d tick pri %d",
1462171482Sjeff		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1463171482Sjeff		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1464171482Sjeff		    SCHED_PRI_TICKS(td->td_sched)));
1465165762Sjeff	}
1466165762Sjeff	sched_user_prio(td, pri);
1467112966Sjeff
1468112966Sjeff	return;
1469109864Sjeff}
1470109864Sjeff
1471121868Sjeff/*
1472121868Sjeff * This routine enforces a maximum limit on the amount of scheduling history
1473171482Sjeff * kept.  It is called after either the slptime or runtime is adjusted.  This
1474171482Sjeff * function is ugly due to integer math.
1475121868Sjeff */
1476116463Sjeffstatic void
1477163709Sjbsched_interact_update(struct thread *td)
1478116463Sjeff{
1479165819Sjeff	struct td_sched *ts;
1480166208Sjeff	u_int sum;
1481121605Sjeff
1482165819Sjeff	ts = td->td_sched;
1483171482Sjeff	sum = ts->ts_runtime + ts->ts_slptime;
1484121868Sjeff	if (sum < SCHED_SLP_RUN_MAX)
1485121868Sjeff		return;
1486121868Sjeff	/*
1487165819Sjeff	 * This only happens from two places:
1488165819Sjeff	 * 1) We have added an unusual amount of run time from fork_exit.
1489165819Sjeff	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1490165819Sjeff	 */
1491165819Sjeff	if (sum > SCHED_SLP_RUN_MAX * 2) {
1492171482Sjeff		if (ts->ts_runtime > ts->ts_slptime) {
1493171482Sjeff			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1494171482Sjeff			ts->ts_slptime = 1;
1495165819Sjeff		} else {
1496171482Sjeff			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1497171482Sjeff			ts->ts_runtime = 1;
1498165819Sjeff		}
1499165819Sjeff		return;
1500165819Sjeff	}
1501165819Sjeff	/*
1502121868Sjeff	 * If we have exceeded by more than 1/5th then the algorithm below
1503121868Sjeff	 * will not bring us back into range.  Dividing by two here forces
1504133427Sjeff	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1505121868Sjeff	 */
1506127850Sjeff	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1507171482Sjeff		ts->ts_runtime /= 2;
1508171482Sjeff		ts->ts_slptime /= 2;
1509121868Sjeff		return;
1510116463Sjeff	}
1511171482Sjeff	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1512171482Sjeff	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1513116463Sjeff}
1514116463Sjeff
1515171482Sjeff/*
1516171482Sjeff * Scale back the interactivity history when a child thread is created.  The
1517171482Sjeff * history is inherited from the parent but the thread may behave totally
1518171482Sjeff * differently.  For example, a shell spawning a compiler process.  We want
1519171482Sjeff * to learn that the compiler is behaving badly very quickly.
1520171482Sjeff */
1521121868Sjeffstatic void
1522163709Sjbsched_interact_fork(struct thread *td)
1523121868Sjeff{
1524121868Sjeff	int ratio;
1525121868Sjeff	int sum;
1526121868Sjeff
1527171482Sjeff	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1528121868Sjeff	if (sum > SCHED_SLP_RUN_FORK) {
1529121868Sjeff		ratio = sum / SCHED_SLP_RUN_FORK;
1530171482Sjeff		td->td_sched->ts_runtime /= ratio;
1531171482Sjeff		td->td_sched->ts_slptime /= ratio;
1532121868Sjeff	}
1533121868Sjeff}
1534121868Sjeff
1535113357Sjeff/*
1536171482Sjeff * Called from proc0_init() to setup the scheduler fields.
1537134791Sjulian */
1538134791Sjulianvoid
1539134791Sjulianschedinit(void)
1540134791Sjulian{
1541165762Sjeff
1542134791Sjulian	/*
1543134791Sjulian	 * Set up the scheduler specific parts of proc0.
1544134791Sjulian	 */
1545136167Sjulian	proc0.p_sched = NULL; /* XXX */
1546164936Sjulian	thread0.td_sched = &td_sched0;
1547165762Sjeff	td_sched0.ts_ltick = ticks;
1548165796Sjeff	td_sched0.ts_ftick = ticks;
1549164936Sjulian	td_sched0.ts_thread = &thread0;
1550134791Sjulian}
1551134791Sjulian
1552134791Sjulian/*
1553113357Sjeff * This is only somewhat accurate since given many processes of the same
1554113357Sjeff * priority they will switch when their slices run out, which will be
1555165762Sjeff * at most sched_slice stathz ticks.
1556113357Sjeff */
1557109864Sjeffint
1558109864Sjeffsched_rr_interval(void)
1559109864Sjeff{
1560165762Sjeff
1561165762Sjeff	/* Convert sched_slice to hz */
1562165762Sjeff	return (hz/(realstathz/sched_slice));
1563109864Sjeff}
1564109864Sjeff
1565171482Sjeff/*
1566171482Sjeff * Update the percent cpu tracking information when it is requested or
1567171482Sjeff * the total history exceeds the maximum.  We keep a sliding history of
1568171482Sjeff * tick counts that slowly decays.  This is less precise than the 4BSD
1569171482Sjeff * mechanism since it happens with less regular and frequent events.
1570171482Sjeff */
1571121790Sjeffstatic void
1572164936Sjuliansched_pctcpu_update(struct td_sched *ts)
1573109864Sjeff{
1574165762Sjeff
1575165762Sjeff	if (ts->ts_ticks == 0)
1576165762Sjeff		return;
1577165796Sjeff	if (ticks - (hz / 10) < ts->ts_ltick &&
1578165796Sjeff	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1579165796Sjeff		return;
1580109864Sjeff	/*
1581109864Sjeff	 * Adjust counters and watermark for pctcpu calc.
1582116365Sjeff	 */
1583165762Sjeff	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1584164936Sjulian		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1585165762Sjeff			    SCHED_TICK_TARG;
1586165762Sjeff	else
1587164936Sjulian		ts->ts_ticks = 0;
1588164936Sjulian	ts->ts_ltick = ticks;
1589165762Sjeff	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1590109864Sjeff}
1591109864Sjeff
1592171482Sjeff/*
1593171482Sjeff * Adjust the priority of a thread.  Move it to the appropriate run-queue
1594171482Sjeff * if necessary.  This is the back-end for several priority related
1595171482Sjeff * functions.
1596171482Sjeff */
1597165762Sjeffstatic void
1598139453Sjhbsched_thread_priority(struct thread *td, u_char prio)
1599109864Sjeff{
1600164936Sjulian	struct td_sched *ts;
1601109864Sjeff
1602139316Sjeff	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
1603173600Sjulian	    td, td->td_name, td->td_priority, prio, curthread,
1604173600Sjulian	    curthread->td_name);
1605164936Sjulian	ts = td->td_sched;
1606170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1607139453Sjhb	if (td->td_priority == prio)
1608139453Sjhb		return;
1609165762Sjeff
1610165766Sjeff	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1611121605Sjeff		/*
1612121605Sjeff		 * If the priority has been elevated due to priority
1613121605Sjeff		 * propagation, we may have to move ourselves to a new
1614165762Sjeff		 * queue.  This could be optimized to not re-add in some
1615165762Sjeff		 * cases.
1616133555Sjeff		 */
1617165762Sjeff		sched_rem(td);
1618165762Sjeff		td->td_priority = prio;
1619171482Sjeff		sched_add(td, SRQ_BORROWING);
1620171482Sjeff	} else {
1621171482Sjeff#ifdef SMP
1622171482Sjeff		struct tdq *tdq;
1623171482Sjeff
1624171482Sjeff		tdq = TDQ_CPU(ts->ts_cpu);
1625171482Sjeff		if (prio < tdq->tdq_lowpri)
1626171482Sjeff			tdq->tdq_lowpri = prio;
1627171482Sjeff#endif
1628119488Sdavidxu		td->td_priority = prio;
1629171482Sjeff	}
1630109864Sjeff}
1631109864Sjeff
1632139453Sjhb/*
1633139453Sjhb * Update a thread's priority when it is lent another thread's
1634139453Sjhb * priority.
1635139453Sjhb */
1636109864Sjeffvoid
1637139453Sjhbsched_lend_prio(struct thread *td, u_char prio)
1638139453Sjhb{
1639139453Sjhb
1640139453Sjhb	td->td_flags |= TDF_BORROWING;
1641139453Sjhb	sched_thread_priority(td, prio);
1642139453Sjhb}
1643139453Sjhb
1644139453Sjhb/*
1645139453Sjhb * Restore a thread's priority when priority propagation is
1646139453Sjhb * over.  The prio argument is the minimum priority the thread
1647139453Sjhb * needs to have to satisfy other possible priority lending
1648139453Sjhb * requests.  If the thread's regular priority is less
1649139453Sjhb * important than prio, the thread will keep a priority boost
1650139453Sjhb * of prio.
1651139453Sjhb */
1652139453Sjhbvoid
1653139453Sjhbsched_unlend_prio(struct thread *td, u_char prio)
1654139453Sjhb{
1655139453Sjhb	u_char base_pri;
1656139453Sjhb
1657139453Sjhb	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1658139453Sjhb	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1659163709Sjb		base_pri = td->td_user_pri;
1660139453Sjhb	else
1661139453Sjhb		base_pri = td->td_base_pri;
1662139453Sjhb	if (prio >= base_pri) {
1663139455Sjhb		td->td_flags &= ~TDF_BORROWING;
1664139453Sjhb		sched_thread_priority(td, base_pri);
1665139453Sjhb	} else
1666139453Sjhb		sched_lend_prio(td, prio);
1667139453Sjhb}
1668139453Sjhb
1669171482Sjeff/*
1670171482Sjeff * Standard entry for setting the priority to an absolute value.
1671171482Sjeff */
1672139453Sjhbvoid
1673139453Sjhbsched_prio(struct thread *td, u_char prio)
1674139453Sjhb{
1675139453Sjhb	u_char oldprio;
1676139453Sjhb
1677139453Sjhb	/* First, update the base priority. */
1678139453Sjhb	td->td_base_pri = prio;
1679139453Sjhb
1680139453Sjhb	/*
1681139455Sjhb	 * If the thread is borrowing another thread's priority, don't
1682139453Sjhb	 * ever lower the priority.
1683139453Sjhb	 */
1684139453Sjhb	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1685139453Sjhb		return;
1686139453Sjhb
1687139453Sjhb	/* Change the real priority. */
1688139453Sjhb	oldprio = td->td_priority;
1689139453Sjhb	sched_thread_priority(td, prio);
1690139453Sjhb
1691139453Sjhb	/*
1692139453Sjhb	 * If the thread is on a turnstile, then let the turnstile update
1693139453Sjhb	 * its state.
1694139453Sjhb	 */
1695139453Sjhb	if (TD_ON_LOCK(td) && oldprio != prio)
1696139453Sjhb		turnstile_adjust(td, oldprio);
1697139453Sjhb}
1698139455Sjhb
1699171482Sjeff/*
1700171482Sjeff * Set the base user priority, does not effect current running priority.
1701171482Sjeff */
1702139453Sjhbvoid
1703163709Sjbsched_user_prio(struct thread *td, u_char prio)
1704161599Sdavidxu{
1705161599Sdavidxu	u_char oldprio;
1706161599Sdavidxu
1707163709Sjb	td->td_base_user_pri = prio;
1708164939Sjulian	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1709164939Sjulian                return;
1710163709Sjb	oldprio = td->td_user_pri;
1711163709Sjb	td->td_user_pri = prio;
1712161599Sdavidxu}
1713161599Sdavidxu
1714161599Sdavidxuvoid
1715161599Sdavidxusched_lend_user_prio(struct thread *td, u_char prio)
1716161599Sdavidxu{
1717161599Sdavidxu	u_char oldprio;
1718161599Sdavidxu
1719174536Sdavidxu	THREAD_LOCK_ASSERT(td, MA_OWNED);
1720161599Sdavidxu	td->td_flags |= TDF_UBORROWING;
1721164091Smaxim	oldprio = td->td_user_pri;
1722163709Sjb	td->td_user_pri = prio;
1723161599Sdavidxu}
1724161599Sdavidxu
1725161599Sdavidxuvoid
1726161599Sdavidxusched_unlend_user_prio(struct thread *td, u_char prio)
1727161599Sdavidxu{
1728161599Sdavidxu	u_char base_pri;
1729161599Sdavidxu
1730174536Sdavidxu	THREAD_LOCK_ASSERT(td, MA_OWNED);
1731163709Sjb	base_pri = td->td_base_user_pri;
1732161599Sdavidxu	if (prio >= base_pri) {
1733161599Sdavidxu		td->td_flags &= ~TDF_UBORROWING;
1734163709Sjb		sched_user_prio(td, base_pri);
1735174536Sdavidxu	} else {
1736161599Sdavidxu		sched_lend_user_prio(td, prio);
1737174536Sdavidxu	}
1738161599Sdavidxu}
1739161599Sdavidxu
1740171482Sjeff/*
1741171505Sjeff * Add the thread passed as 'newtd' to the run queue before selecting
1742171505Sjeff * the next thread to run.  This is only used for KSE.
1743171505Sjeff */
1744171505Sjeffstatic void
1745171505Sjeffsched_switchin(struct tdq *tdq, struct thread *td)
1746171505Sjeff{
1747171505Sjeff#ifdef SMP
1748171505Sjeff	spinlock_enter();
1749171505Sjeff	TDQ_UNLOCK(tdq);
1750171505Sjeff	thread_lock(td);
1751171505Sjeff	spinlock_exit();
1752171505Sjeff	sched_setcpu(td->td_sched, TDQ_ID(tdq), SRQ_YIELDING);
1753171505Sjeff#else
1754171505Sjeff	td->td_lock = TDQ_LOCKPTR(tdq);
1755171505Sjeff#endif
1756171505Sjeff	tdq_add(tdq, td, SRQ_YIELDING);
1757171505Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1758171505Sjeff}
1759171505Sjeff
1760171505Sjeff/*
1761171713Sjeff * Handle migration from sched_switch().  This happens only for
1762171713Sjeff * cpu binding.
1763171713Sjeff */
1764171713Sjeffstatic struct mtx *
1765171713Sjeffsched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1766171713Sjeff{
1767171713Sjeff	struct tdq *tdn;
1768171713Sjeff
1769171713Sjeff	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1770171713Sjeff#ifdef SMP
1771171713Sjeff	/*
1772171713Sjeff	 * Do the lock dance required to avoid LOR.  We grab an extra
1773171713Sjeff	 * spinlock nesting to prevent preemption while we're
1774171713Sjeff	 * not holding either run-queue lock.
1775171713Sjeff	 */
1776171713Sjeff	spinlock_enter();
1777171713Sjeff	thread_block_switch(td);	/* This releases the lock on tdq. */
1778171713Sjeff	TDQ_LOCK(tdn);
1779171713Sjeff	tdq_add(tdn, td, flags);
1780171713Sjeff	tdq_notify(td->td_sched);
1781171713Sjeff	/*
1782171713Sjeff	 * After we unlock tdn the new cpu still can't switch into this
1783171713Sjeff	 * thread until we've unblocked it in cpu_switch().  The lock
1784171713Sjeff	 * pointers may match in the case of HTT cores.  Don't unlock here
1785171713Sjeff	 * or we can deadlock when the other CPU runs the IPI handler.
1786171713Sjeff	 */
1787171713Sjeff	if (TDQ_LOCKPTR(tdn) != TDQ_LOCKPTR(tdq)) {
1788171713Sjeff		TDQ_UNLOCK(tdn);
1789171713Sjeff		TDQ_LOCK(tdq);
1790171713Sjeff	}
1791171713Sjeff	spinlock_exit();
1792171713Sjeff#endif
1793171713Sjeff	return (TDQ_LOCKPTR(tdn));
1794171713Sjeff}
1795171713Sjeff
1796171713Sjeff/*
1797171482Sjeff * Block a thread for switching.  Similar to thread_block() but does not
1798171482Sjeff * bump the spin count.
1799171482Sjeff */
1800171482Sjeffstatic inline struct mtx *
1801171482Sjeffthread_block_switch(struct thread *td)
1802171482Sjeff{
1803171482Sjeff	struct mtx *lock;
1804171482Sjeff
1805171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1806171482Sjeff	lock = td->td_lock;
1807171482Sjeff	td->td_lock = &blocked_lock;
1808171482Sjeff	mtx_unlock_spin(lock);
1809171482Sjeff
1810171482Sjeff	return (lock);
1811171482Sjeff}
1812171482Sjeff
1813171482Sjeff/*
1814171482Sjeff * Release a thread that was blocked with thread_block_switch().
1815171482Sjeff */
1816171482Sjeffstatic inline void
1817171482Sjeffthread_unblock_switch(struct thread *td, struct mtx *mtx)
1818171482Sjeff{
1819171482Sjeff	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1820171482Sjeff	    (uintptr_t)mtx);
1821171482Sjeff}
1822171482Sjeff
1823171482Sjeff/*
1824171482Sjeff * Switch threads.  This function has to handle threads coming in while
1825171482Sjeff * blocked for some reason, running, or idle.  It also must deal with
1826171482Sjeff * migrating a thread from one queue to another as running threads may
1827171482Sjeff * be assigned elsewhere via binding.
1828171482Sjeff */
1829161599Sdavidxuvoid
1830135051Sjuliansched_switch(struct thread *td, struct thread *newtd, int flags)
1831109864Sjeff{
1832165627Sjeff	struct tdq *tdq;
1833164936Sjulian	struct td_sched *ts;
1834171482Sjeff	struct mtx *mtx;
1835171713Sjeff	int srqflag;
1836171482Sjeff	int cpuid;
1837109864Sjeff
1838170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1839109864Sjeff
1840171482Sjeff	cpuid = PCPU_GET(cpuid);
1841171482Sjeff	tdq = TDQ_CPU(cpuid);
1842164936Sjulian	ts = td->td_sched;
1843171713Sjeff	mtx = td->td_lock;
1844171482Sjeff#ifdef SMP
1845171482Sjeff	ts->ts_rltick = ticks;
1846171482Sjeff	if (newtd && newtd->td_priority < tdq->tdq_lowpri)
1847171482Sjeff		tdq->tdq_lowpri = newtd->td_priority;
1848171482Sjeff#endif
1849133555Sjeff	td->td_lastcpu = td->td_oncpu;
1850113339Sjulian	td->td_oncpu = NOCPU;
1851132266Sjhb	td->td_flags &= ~TDF_NEEDRESCHED;
1852144777Sups	td->td_owepreempt = 0;
1853123434Sjeff	/*
1854171482Sjeff	 * The lock pointer in an idle thread should never change.  Reset it
1855171482Sjeff	 * to CAN_RUN as well.
1856123434Sjeff	 */
1857167327Sjulian	if (TD_IS_IDLETHREAD(td)) {
1858171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1859139334Sjeff		TD_SET_CAN_RUN(td);
1860170293Sjeff	} else if (TD_IS_RUNNING(td)) {
1861171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1862165627Sjeff		tdq_load_rem(tdq, ts);
1863171713Sjeff		srqflag = (flags & SW_PREEMPT) ?
1864170293Sjeff		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1865171713Sjeff		    SRQ_OURSELF|SRQ_YIELDING;
1866171713Sjeff		if (ts->ts_cpu == cpuid)
1867171713Sjeff			tdq_add(tdq, td, srqflag);
1868171713Sjeff		else
1869171713Sjeff			mtx = sched_switch_migrate(tdq, td, srqflag);
1870171482Sjeff	} else {
1871171482Sjeff		/* This thread must be going to sleep. */
1872171482Sjeff		TDQ_LOCK(tdq);
1873171482Sjeff		mtx = thread_block_switch(td);
1874170293Sjeff		tdq_load_rem(tdq, ts);
1875171482Sjeff	}
1876171482Sjeff	/*
1877171482Sjeff	 * We enter here with the thread blocked and assigned to the
1878171482Sjeff	 * appropriate cpu run-queue or sleep-queue and with the current
1879171482Sjeff	 * thread-queue locked.
1880171482Sjeff	 */
1881171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1882171482Sjeff	/*
1883171505Sjeff	 * If KSE assigned a new thread just add it here and let choosethread
1884171505Sjeff	 * select the best one.
1885171482Sjeff	 */
1886171505Sjeff	if (newtd != NULL)
1887171505Sjeff		sched_switchin(tdq, newtd);
1888171482Sjeff	newtd = choosethread();
1889171482Sjeff	/*
1890171482Sjeff	 * Call the MD code to switch contexts if necessary.
1891171482Sjeff	 */
1892145256Sjkoshy	if (td != newtd) {
1893145256Sjkoshy#ifdef	HWPMC_HOOKS
1894145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1895145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1896145256Sjkoshy#endif
1897174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1898172411Sjeff		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1899171482Sjeff		cpu_switch(td, newtd, mtx);
1900171482Sjeff		/*
1901171482Sjeff		 * We may return from cpu_switch on a different cpu.  However,
1902171482Sjeff		 * we always return with td_lock pointing to the current cpu's
1903171482Sjeff		 * run queue lock.
1904171482Sjeff		 */
1905171482Sjeff		cpuid = PCPU_GET(cpuid);
1906171482Sjeff		tdq = TDQ_CPU(cpuid);
1907174629Sjeff		lock_profile_obtain_lock_success(
1908174629Sjeff		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1909145256Sjkoshy#ifdef	HWPMC_HOOKS
1910145256Sjkoshy		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1911145256Sjkoshy			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1912145256Sjkoshy#endif
1913171482Sjeff	} else
1914171482Sjeff		thread_unblock_switch(td, mtx);
1915171482Sjeff	/*
1916171482Sjeff	 * Assert that all went well and return.
1917171482Sjeff	 */
1918171482Sjeff#ifdef SMP
1919171482Sjeff	/* We should always get here with the lowest priority td possible */
1920171482Sjeff	tdq->tdq_lowpri = td->td_priority;
1921171482Sjeff#endif
1922171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1923171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1924171482Sjeff	td->td_oncpu = cpuid;
1925109864Sjeff}
1926109864Sjeff
1927171482Sjeff/*
1928171482Sjeff * Adjust thread priorities as a result of a nice request.
1929171482Sjeff */
1930109864Sjeffvoid
1931130551Sjuliansched_nice(struct proc *p, int nice)
1932109864Sjeff{
1933109864Sjeff	struct thread *td;
1934109864Sjeff
1935130551Sjulian	PROC_LOCK_ASSERT(p, MA_OWNED);
1936170293Sjeff	PROC_SLOCK_ASSERT(p, MA_OWNED);
1937165762Sjeff
1938130551Sjulian	p->p_nice = nice;
1939163709Sjb	FOREACH_THREAD_IN_PROC(p, td) {
1940170293Sjeff		thread_lock(td);
1941163709Sjb		sched_priority(td);
1942165762Sjeff		sched_prio(td, td->td_base_user_pri);
1943170293Sjeff		thread_unlock(td);
1944130551Sjulian	}
1945109864Sjeff}
1946109864Sjeff
1947171482Sjeff/*
1948171482Sjeff * Record the sleep time for the interactivity scorer.
1949171482Sjeff */
1950109864Sjeffvoid
1951126326Sjhbsched_sleep(struct thread *td)
1952109864Sjeff{
1953165762Sjeff
1954170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1955109864Sjeff
1956172264Sjeff	td->td_slptick = ticks;
1957109864Sjeff}
1958109864Sjeff
1959171482Sjeff/*
1960171482Sjeff * Schedule a thread to resume execution and record how long it voluntarily
1961171482Sjeff * slept.  We also update the pctcpu, interactivity, and priority.
1962171482Sjeff */
1963109864Sjeffvoid
1964109864Sjeffsched_wakeup(struct thread *td)
1965109864Sjeff{
1966166229Sjeff	struct td_sched *ts;
1967171482Sjeff	int slptick;
1968165762Sjeff
1969170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1970166229Sjeff	ts = td->td_sched;
1971109864Sjeff	/*
1972165762Sjeff	 * If we slept for more than a tick update our interactivity and
1973165762Sjeff	 * priority.
1974109864Sjeff	 */
1975172264Sjeff	slptick = td->td_slptick;
1976172264Sjeff	td->td_slptick = 0;
1977171482Sjeff	if (slptick && slptick != ticks) {
1978166208Sjeff		u_int hzticks;
1979109864Sjeff
1980171482Sjeff		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1981171482Sjeff		ts->ts_slptime += hzticks;
1982165819Sjeff		sched_interact_update(td);
1983166229Sjeff		sched_pctcpu_update(ts);
1984163709Sjb		sched_priority(td);
1985109864Sjeff	}
1986166229Sjeff	/* Reset the slice value after we sleep. */
1987166229Sjeff	ts->ts_slice = sched_slice;
1988166190Sjeff	sched_add(td, SRQ_BORING);
1989109864Sjeff}
1990109864Sjeff
1991109864Sjeff/*
1992109864Sjeff * Penalize the parent for creating a new child and initialize the child's
1993109864Sjeff * priority.
1994109864Sjeff */
1995109864Sjeffvoid
1996163709Sjbsched_fork(struct thread *td, struct thread *child)
1997109864Sjeff{
1998170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
1999164936Sjulian	sched_fork_thread(td, child);
2000165762Sjeff	/*
2001165762Sjeff	 * Penalize the parent and child for forking.
2002165762Sjeff	 */
2003165762Sjeff	sched_interact_fork(child);
2004165762Sjeff	sched_priority(child);
2005171482Sjeff	td->td_sched->ts_runtime += tickincr;
2006165762Sjeff	sched_interact_update(td);
2007165762Sjeff	sched_priority(td);
2008164936Sjulian}
2009109864Sjeff
2010171482Sjeff/*
2011171482Sjeff * Fork a new thread, may be within the same process.
2012171482Sjeff */
2013164936Sjulianvoid
2014164936Sjuliansched_fork_thread(struct thread *td, struct thread *child)
2015164936Sjulian{
2016164936Sjulian	struct td_sched *ts;
2017164936Sjulian	struct td_sched *ts2;
2018164936Sjulian
2019165762Sjeff	/*
2020165762Sjeff	 * Initialize child.
2021165762Sjeff	 */
2022170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2023163709Sjb	sched_newthread(child);
2024171482Sjeff	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
2025164936Sjulian	ts = td->td_sched;
2026164936Sjulian	ts2 = child->td_sched;
2027164936Sjulian	ts2->ts_cpu = ts->ts_cpu;
2028164936Sjulian	ts2->ts_runq = NULL;
2029165762Sjeff	/*
2030165762Sjeff	 * Grab our parents cpu estimation information and priority.
2031165762Sjeff	 */
2032164936Sjulian	ts2->ts_ticks = ts->ts_ticks;
2033164936Sjulian	ts2->ts_ltick = ts->ts_ltick;
2034164936Sjulian	ts2->ts_ftick = ts->ts_ftick;
2035165762Sjeff	child->td_user_pri = td->td_user_pri;
2036165762Sjeff	child->td_base_user_pri = td->td_base_user_pri;
2037165762Sjeff	/*
2038165762Sjeff	 * And update interactivity score.
2039165762Sjeff	 */
2040171482Sjeff	ts2->ts_slptime = ts->ts_slptime;
2041171482Sjeff	ts2->ts_runtime = ts->ts_runtime;
2042165762Sjeff	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
2043113357Sjeff}
2044113357Sjeff
2045171482Sjeff/*
2046171482Sjeff * Adjust the priority class of a thread.
2047171482Sjeff */
2048113357Sjeffvoid
2049163709Sjbsched_class(struct thread *td, int class)
2050113357Sjeff{
2051113357Sjeff
2052170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2053163709Sjb	if (td->td_pri_class == class)
2054113357Sjeff		return;
2055113357Sjeff
2056121896Sjeff#ifdef SMP
2057165827Sjeff	/*
2058165827Sjeff	 * On SMP if we're on the RUNQ we must adjust the transferable
2059165827Sjeff	 * count because could be changing to or from an interrupt
2060165827Sjeff	 * class.
2061165827Sjeff	 */
2062166190Sjeff	if (TD_ON_RUNQ(td)) {
2063165827Sjeff		struct tdq *tdq;
2064165827Sjeff
2065165827Sjeff		tdq = TDQ_CPU(td->td_sched->ts_cpu);
2066165827Sjeff		if (THREAD_CAN_MIGRATE(td)) {
2067165827Sjeff			tdq->tdq_transferable--;
2068165827Sjeff			tdq->tdq_group->tdg_transferable--;
2069122744Sjeff		}
2070165827Sjeff		td->td_pri_class = class;
2071165827Sjeff		if (THREAD_CAN_MIGRATE(td)) {
2072165827Sjeff			tdq->tdq_transferable++;
2073165827Sjeff			tdq->tdq_group->tdg_transferable++;
2074165827Sjeff		}
2075165827Sjeff	}
2076164936Sjulian#endif
2077163709Sjb	td->td_pri_class = class;
2078109864Sjeff}
2079109864Sjeff
2080109864Sjeff/*
2081109864Sjeff * Return some of the child's priority and interactivity to the parent.
2082109864Sjeff */
2083109864Sjeffvoid
2084164939Sjuliansched_exit(struct proc *p, struct thread *child)
2085109864Sjeff{
2086165762Sjeff	struct thread *td;
2087164939Sjulian
2088163709Sjb	CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
2089173600Sjulian	    child, child->td_name, child->td_priority);
2090113372Sjeff
2091170293Sjeff	PROC_SLOCK_ASSERT(p, MA_OWNED);
2092165762Sjeff	td = FIRST_THREAD_IN_PROC(p);
2093165762Sjeff	sched_exit_thread(td, child);
2094113372Sjeff}
2095113372Sjeff
2096171482Sjeff/*
2097171482Sjeff * Penalize another thread for the time spent on this one.  This helps to
2098171482Sjeff * worsen the priority and interactivity of processes which schedule batch
2099171482Sjeff * jobs such as make.  This has little effect on the make process itself but
2100171482Sjeff * causes new processes spawned by it to receive worse scores immediately.
2101171482Sjeff */
2102113372Sjeffvoid
2103164939Sjuliansched_exit_thread(struct thread *td, struct thread *child)
2104164936Sjulian{
2105165762Sjeff
2106164939Sjulian	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
2107173600Sjulian	    child, child->td_name, child->td_priority);
2108164939Sjulian
2109165762Sjeff#ifdef KSE
2110165762Sjeff	/*
2111165762Sjeff	 * KSE forks and exits so often that this penalty causes short-lived
2112165762Sjeff	 * threads to always be non-interactive.  This causes mozilla to
2113165762Sjeff	 * crawl under load.
2114165762Sjeff	 */
2115165762Sjeff	if ((td->td_pflags & TDP_SA) && td->td_proc == child->td_proc)
2116165762Sjeff		return;
2117165762Sjeff#endif
2118165762Sjeff	/*
2119165762Sjeff	 * Give the child's runtime to the parent without returning the
2120165762Sjeff	 * sleep time as a penalty to the parent.  This causes shells that
2121165762Sjeff	 * launch expensive things to mark their children as expensive.
2122165762Sjeff	 */
2123170293Sjeff	thread_lock(td);
2124171482Sjeff	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2125164939Sjulian	sched_interact_update(td);
2126165762Sjeff	sched_priority(td);
2127170293Sjeff	thread_unlock(td);
2128164936Sjulian}
2129164936Sjulian
2130171482Sjeff/*
2131171482Sjeff * Fix priorities on return to user-space.  Priorities may be elevated due
2132171482Sjeff * to static priorities in msleep() or similar.
2133171482Sjeff */
2134164936Sjulianvoid
2135164936Sjuliansched_userret(struct thread *td)
2136164936Sjulian{
2137164936Sjulian	/*
2138164936Sjulian	 * XXX we cheat slightly on the locking here to avoid locking in
2139164936Sjulian	 * the usual case.  Setting td_priority here is essentially an
2140164936Sjulian	 * incomplete workaround for not setting it properly elsewhere.
2141164936Sjulian	 * Now that some interrupt handlers are threads, not setting it
2142164936Sjulian	 * properly elsewhere can clobber it in the window between setting
2143164936Sjulian	 * it here and returning to user mode, so don't waste time setting
2144164936Sjulian	 * it perfectly here.
2145164936Sjulian	 */
2146164936Sjulian	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2147164936Sjulian	    ("thread with borrowed priority returning to userland"));
2148164936Sjulian	if (td->td_priority != td->td_user_pri) {
2149170293Sjeff		thread_lock(td);
2150164936Sjulian		td->td_priority = td->td_user_pri;
2151164936Sjulian		td->td_base_pri = td->td_user_pri;
2152170293Sjeff		thread_unlock(td);
2153164936Sjulian        }
2154164936Sjulian}
2155164936Sjulian
2156171482Sjeff/*
2157171482Sjeff * Handle a stathz tick.  This is really only relevant for timeshare
2158171482Sjeff * threads.
2159171482Sjeff */
2160164936Sjulianvoid
2161121127Sjeffsched_clock(struct thread *td)
2162109864Sjeff{
2163164936Sjulian	struct tdq *tdq;
2164164936Sjulian	struct td_sched *ts;
2165109864Sjeff
2166171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2167164936Sjulian	tdq = TDQ_SELF();
2168172409Sjeff#ifdef SMP
2169133427Sjeff	/*
2170172409Sjeff	 * We run the long term load balancer infrequently on the first cpu.
2171172409Sjeff	 */
2172172409Sjeff	if (balance_tdq == tdq) {
2173172409Sjeff		if (balance_ticks && --balance_ticks == 0)
2174172409Sjeff			sched_balance();
2175172409Sjeff		if (balance_group_ticks && --balance_group_ticks == 0)
2176172409Sjeff			sched_balance_groups();
2177172409Sjeff	}
2178172409Sjeff#endif
2179172409Sjeff	/*
2180165766Sjeff	 * Advance the insert index once for each tick to ensure that all
2181165766Sjeff	 * threads get a chance to run.
2182133427Sjeff	 */
2183165766Sjeff	if (tdq->tdq_idx == tdq->tdq_ridx) {
2184165766Sjeff		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2185165766Sjeff		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2186165766Sjeff			tdq->tdq_ridx = tdq->tdq_idx;
2187165766Sjeff	}
2188165766Sjeff	ts = td->td_sched;
2189165762Sjeff	/*
2190163709Sjb	 * We only do slicing code for TIMESHARE threads.
2191113357Sjeff	 */
2192163709Sjb	if (td->td_pri_class != PRI_TIMESHARE)
2193113357Sjeff		return;
2194113357Sjeff	/*
2195165766Sjeff	 * We used a tick; charge it to the thread so that we can compute our
2196113357Sjeff	 * interactivity.
2197109864Sjeff	 */
2198171482Sjeff	td->td_sched->ts_runtime += tickincr;
2199163709Sjb	sched_interact_update(td);
2200109864Sjeff	/*
2201109864Sjeff	 * We used up one time slice.
2202109864Sjeff	 */
2203164936Sjulian	if (--ts->ts_slice > 0)
2204113357Sjeff		return;
2205109864Sjeff	/*
2206113357Sjeff	 * We're out of time, recompute priorities and requeue.
2207109864Sjeff	 */
2208165796Sjeff	sched_priority(td);
2209113357Sjeff	td->td_flags |= TDF_NEEDRESCHED;
2210109864Sjeff}
2211109864Sjeff
2212171482Sjeff/*
2213171482Sjeff * Called once per hz tick.  Used for cpu utilization information.  This
2214171482Sjeff * is easier than trying to scale based on stathz.
2215171482Sjeff */
2216171482Sjeffvoid
2217171482Sjeffsched_tick(void)
2218171482Sjeff{
2219171482Sjeff	struct td_sched *ts;
2220171482Sjeff
2221171482Sjeff	ts = curthread->td_sched;
2222171482Sjeff	/* Adjust ticks for pctcpu */
2223171482Sjeff	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2224171482Sjeff	ts->ts_ltick = ticks;
2225171482Sjeff	/*
2226171482Sjeff	 * Update if we've exceeded our desired tick threshhold by over one
2227171482Sjeff	 * second.
2228171482Sjeff	 */
2229171482Sjeff	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2230171482Sjeff		sched_pctcpu_update(ts);
2231171482Sjeff}
2232171482Sjeff
2233171482Sjeff/*
2234171482Sjeff * Return whether the current CPU has runnable tasks.  Used for in-kernel
2235171482Sjeff * cooperative idle threads.
2236171482Sjeff */
2237109864Sjeffint
2238109864Sjeffsched_runnable(void)
2239109864Sjeff{
2240164936Sjulian	struct tdq *tdq;
2241115998Sjeff	int load;
2242109864Sjeff
2243115998Sjeff	load = 1;
2244115998Sjeff
2245164936Sjulian	tdq = TDQ_SELF();
2246121605Sjeff	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2247165620Sjeff		if (tdq->tdq_load > 0)
2248121605Sjeff			goto out;
2249121605Sjeff	} else
2250165620Sjeff		if (tdq->tdq_load - 1 > 0)
2251121605Sjeff			goto out;
2252115998Sjeff	load = 0;
2253115998Sjeffout:
2254115998Sjeff	return (load);
2255109864Sjeff}
2256109864Sjeff
2257171482Sjeff/*
2258171482Sjeff * Choose the highest priority thread to run.  The thread is removed from
2259171482Sjeff * the run-queue while running however the load remains.  For SMP we set
2260171482Sjeff * the tdq in the global idle bitmask if it idles here.
2261171482Sjeff */
2262166190Sjeffstruct thread *
2263109970Sjeffsched_choose(void)
2264109970Sjeff{
2265171482Sjeff#ifdef SMP
2266171482Sjeff	struct tdq_group *tdg;
2267171482Sjeff#endif
2268171482Sjeff	struct td_sched *ts;
2269164936Sjulian	struct tdq *tdq;
2270109970Sjeff
2271164936Sjulian	tdq = TDQ_SELF();
2272171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2273164936Sjulian	ts = tdq_choose(tdq);
2274164936Sjulian	if (ts) {
2275164936Sjulian		tdq_runq_rem(tdq, ts);
2276166190Sjeff		return (ts->ts_thread);
2277109864Sjeff	}
2278109970Sjeff#ifdef SMP
2279171482Sjeff	/*
2280171482Sjeff	 * We only set the idled bit when all of the cpus in the group are
2281171482Sjeff	 * idle.  Otherwise we could get into a situation where a thread bounces
2282171482Sjeff	 * back and forth between two idle cores on seperate physical CPUs.
2283171482Sjeff	 */
2284171482Sjeff	tdg = tdq->tdq_group;
2285171482Sjeff	tdg->tdg_idlemask |= PCPU_GET(cpumask);
2286171482Sjeff	if (tdg->tdg_idlemask == tdg->tdg_cpumask)
2287171482Sjeff		atomic_set_int(&tdq_idle, tdg->tdg_mask);
2288171482Sjeff	tdq->tdq_lowpri = PRI_MAX_IDLE;
2289109970Sjeff#endif
2290166190Sjeff	return (PCPU_GET(idlethread));
2291109864Sjeff}
2292109864Sjeff
2293171482Sjeff/*
2294171482Sjeff * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2295171482Sjeff * we always request it once we exit a critical section.
2296171482Sjeff */
2297171482Sjeffstatic inline void
2298171482Sjeffsched_setpreempt(struct thread *td)
2299166190Sjeff{
2300166190Sjeff	struct thread *ctd;
2301166190Sjeff	int cpri;
2302166190Sjeff	int pri;
2303166190Sjeff
2304166190Sjeff	ctd = curthread;
2305166190Sjeff	pri = td->td_priority;
2306166190Sjeff	cpri = ctd->td_priority;
2307171482Sjeff	if (td->td_priority < ctd->td_priority)
2308171482Sjeff		curthread->td_flags |= TDF_NEEDRESCHED;
2309166190Sjeff	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2310171482Sjeff		return;
2311166190Sjeff	/*
2312166190Sjeff	 * Always preempt IDLE threads.  Otherwise only if the preempting
2313166190Sjeff	 * thread is an ithread.
2314166190Sjeff	 */
2315171482Sjeff	if (pri > preempt_thresh && cpri < PRI_MIN_IDLE)
2316171482Sjeff		return;
2317171482Sjeff	ctd->td_owepreempt = 1;
2318171482Sjeff	return;
2319166190Sjeff}
2320166190Sjeff
2321171482Sjeff/*
2322171482Sjeff * Add a thread to a thread queue.  Initializes priority, slice, runq, and
2323171482Sjeff * add it to the appropriate queue.  This is the internal function called
2324171482Sjeff * when the tdq is predetermined.
2325171482Sjeff */
2326109864Sjeffvoid
2327171482Sjefftdq_add(struct tdq *tdq, struct thread *td, int flags)
2328109864Sjeff{
2329164936Sjulian	struct td_sched *ts;
2330121790Sjeff	int class;
2331166108Sjeff#ifdef SMP
2332166108Sjeff	int cpumask;
2333166108Sjeff#endif
2334109864Sjeff
2335171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2336166190Sjeff	KASSERT((td->td_inhibitors == 0),
2337166190Sjeff	    ("sched_add: trying to run inhibited thread"));
2338166190Sjeff	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2339166190Sjeff	    ("sched_add: bad thread state"));
2340172207Sjeff	KASSERT(td->td_flags & TDF_INMEM,
2341172207Sjeff	    ("sched_add: thread swapped out"));
2342171482Sjeff
2343171482Sjeff	ts = td->td_sched;
2344171482Sjeff	class = PRI_BASE(td->td_pri_class);
2345166190Sjeff        TD_SET_RUNQ(td);
2346166190Sjeff	if (ts->ts_slice == 0)
2347166190Sjeff		ts->ts_slice = sched_slice;
2348133427Sjeff	/*
2349171482Sjeff	 * Pick the run queue based on priority.
2350133427Sjeff	 */
2351171482Sjeff	if (td->td_priority <= PRI_MAX_REALTIME)
2352171482Sjeff		ts->ts_runq = &tdq->tdq_realtime;
2353171482Sjeff	else if (td->td_priority <= PRI_MAX_TIMESHARE)
2354171482Sjeff		ts->ts_runq = &tdq->tdq_timeshare;
2355171482Sjeff	else
2356171482Sjeff		ts->ts_runq = &tdq->tdq_idle;
2357171482Sjeff#ifdef SMP
2358166108Sjeff	cpumask = 1 << ts->ts_cpu;
2359121790Sjeff	/*
2360123685Sjeff	 * If we had been idle, clear our bit in the group and potentially
2361166108Sjeff	 * the global bitmap.
2362121790Sjeff	 */
2363165762Sjeff	if ((class != PRI_IDLE && class != PRI_ITHD) &&
2364166108Sjeff	    (tdq->tdq_group->tdg_idlemask & cpumask) != 0) {
2365121790Sjeff		/*
2366123433Sjeff		 * Check to see if our group is unidling, and if so, remove it
2367123433Sjeff		 * from the global idle mask.
2368121790Sjeff		 */
2369165620Sjeff		if (tdq->tdq_group->tdg_idlemask ==
2370165620Sjeff		    tdq->tdq_group->tdg_cpumask)
2371165620Sjeff			atomic_clear_int(&tdq_idle, tdq->tdq_group->tdg_mask);
2372123433Sjeff		/*
2373123433Sjeff		 * Now remove ourselves from the group specific idle mask.
2374123433Sjeff		 */
2375166108Sjeff		tdq->tdq_group->tdg_idlemask &= ~cpumask;
2376166108Sjeff	}
2377171482Sjeff	if (td->td_priority < tdq->tdq_lowpri)
2378171482Sjeff		tdq->tdq_lowpri = td->td_priority;
2379121790Sjeff#endif
2380171482Sjeff	tdq_runq_add(tdq, ts, flags);
2381171482Sjeff	tdq_load_add(tdq, ts);
2382171482Sjeff}
2383171482Sjeff
2384171482Sjeff/*
2385171482Sjeff * Select the target thread queue and add a thread to it.  Request
2386171482Sjeff * preemption or IPI a remote processor if required.
2387171482Sjeff */
2388171482Sjeffvoid
2389171482Sjeffsched_add(struct thread *td, int flags)
2390171482Sjeff{
2391171482Sjeff	struct td_sched *ts;
2392171482Sjeff	struct tdq *tdq;
2393171482Sjeff#ifdef SMP
2394171482Sjeff	int cpuid;
2395171482Sjeff	int cpu;
2396171482Sjeff#endif
2397171482Sjeff	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
2398173600Sjulian	    td, td->td_name, td->td_priority, curthread,
2399173600Sjulian	    curthread->td_name);
2400171482Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2401171482Sjeff	ts = td->td_sched;
2402166108Sjeff	/*
2403171482Sjeff	 * Recalculate the priority before we select the target cpu or
2404171482Sjeff	 * run-queue.
2405166108Sjeff	 */
2406171482Sjeff	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2407171482Sjeff		sched_priority(td);
2408171482Sjeff#ifdef SMP
2409171482Sjeff	cpuid = PCPU_GET(cpuid);
2410171482Sjeff	/*
2411171482Sjeff	 * Pick the destination cpu and if it isn't ours transfer to the
2412171482Sjeff	 * target cpu.
2413171482Sjeff	 */
2414171482Sjeff	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_MIGRATE(td))
2415171482Sjeff		cpu = cpuid;
2416171482Sjeff	else if (!THREAD_CAN_MIGRATE(td))
2417171482Sjeff		cpu = ts->ts_cpu;
2418166108Sjeff	else
2419171482Sjeff		cpu = sched_pickcpu(ts, flags);
2420171482Sjeff	tdq = sched_setcpu(ts, cpu, flags);
2421171482Sjeff	tdq_add(tdq, td, flags);
2422171482Sjeff	if (cpu != cpuid) {
2423166108Sjeff		tdq_notify(ts);
2424166108Sjeff		return;
2425166108Sjeff	}
2426171482Sjeff#else
2427171482Sjeff	tdq = TDQ_SELF();
2428171482Sjeff	TDQ_LOCK(tdq);
2429171482Sjeff	/*
2430171482Sjeff	 * Now that the thread is moving to the run-queue, set the lock
2431171482Sjeff	 * to the scheduler's lock.
2432171482Sjeff	 */
2433171482Sjeff	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2434171482Sjeff	tdq_add(tdq, td, flags);
2435166108Sjeff#endif
2436171482Sjeff	if (!(flags & SRQ_YIELDING))
2437171482Sjeff		sched_setpreempt(td);
2438109864Sjeff}
2439109864Sjeff
2440171482Sjeff/*
2441171482Sjeff * Remove a thread from a run-queue without running it.  This is used
2442171482Sjeff * when we're stealing a thread from a remote queue.  Otherwise all threads
2443171482Sjeff * exit by calling sched_exit_thread() and sched_throw() themselves.
2444171482Sjeff */
2445109864Sjeffvoid
2446121127Sjeffsched_rem(struct thread *td)
2447109864Sjeff{
2448164936Sjulian	struct tdq *tdq;
2449164936Sjulian	struct td_sched *ts;
2450113357Sjeff
2451139316Sjeff	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
2452173600Sjulian	    td, td->td_name, td->td_priority, curthread,
2453173600Sjulian	    curthread->td_name);
2454164936Sjulian	ts = td->td_sched;
2455171482Sjeff	tdq = TDQ_CPU(ts->ts_cpu);
2456171482Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2457171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2458166190Sjeff	KASSERT(TD_ON_RUNQ(td),
2459164936Sjulian	    ("sched_rem: thread not on run queue"));
2460164936Sjulian	tdq_runq_rem(tdq, ts);
2461164936Sjulian	tdq_load_rem(tdq, ts);
2462166190Sjeff	TD_SET_CAN_RUN(td);
2463109864Sjeff}
2464109864Sjeff
2465171482Sjeff/*
2466171482Sjeff * Fetch cpu utilization information.  Updates on demand.
2467171482Sjeff */
2468109864Sjefffixpt_t
2469121127Sjeffsched_pctcpu(struct thread *td)
2470109864Sjeff{
2471109864Sjeff	fixpt_t pctcpu;
2472164936Sjulian	struct td_sched *ts;
2473109864Sjeff
2474109864Sjeff	pctcpu = 0;
2475164936Sjulian	ts = td->td_sched;
2476164936Sjulian	if (ts == NULL)
2477121290Sjeff		return (0);
2478109864Sjeff
2479170293Sjeff	thread_lock(td);
2480164936Sjulian	if (ts->ts_ticks) {
2481109864Sjeff		int rtick;
2482109864Sjeff
2483165796Sjeff		sched_pctcpu_update(ts);
2484109864Sjeff		/* How many rtick per second ? */
2485165762Sjeff		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2486165762Sjeff		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2487109864Sjeff	}
2488170293Sjeff	thread_unlock(td);
2489109864Sjeff
2490109864Sjeff	return (pctcpu);
2491109864Sjeff}
2492109864Sjeff
2493171482Sjeff/*
2494171482Sjeff * Bind a thread to a target cpu.
2495171482Sjeff */
2496122038Sjeffvoid
2497122038Sjeffsched_bind(struct thread *td, int cpu)
2498122038Sjeff{
2499164936Sjulian	struct td_sched *ts;
2500122038Sjeff
2501171713Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2502164936Sjulian	ts = td->td_sched;
2503166137Sjeff	if (ts->ts_flags & TSF_BOUND)
2504166152Sjeff		sched_unbind(td);
2505164936Sjulian	ts->ts_flags |= TSF_BOUND;
2506123433Sjeff#ifdef SMP
2507166137Sjeff	sched_pin();
2508123433Sjeff	if (PCPU_GET(cpuid) == cpu)
2509122038Sjeff		return;
2510166137Sjeff	ts->ts_cpu = cpu;
2511122038Sjeff	/* When we return from mi_switch we'll be on the correct cpu. */
2512131527Sphk	mi_switch(SW_VOL, NULL);
2513122038Sjeff#endif
2514122038Sjeff}
2515122038Sjeff
2516171482Sjeff/*
2517171482Sjeff * Release a bound thread.
2518171482Sjeff */
2519122038Sjeffvoid
2520122038Sjeffsched_unbind(struct thread *td)
2521122038Sjeff{
2522165762Sjeff	struct td_sched *ts;
2523165762Sjeff
2524170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2525165762Sjeff	ts = td->td_sched;
2526166137Sjeff	if ((ts->ts_flags & TSF_BOUND) == 0)
2527166137Sjeff		return;
2528165762Sjeff	ts->ts_flags &= ~TSF_BOUND;
2529165762Sjeff#ifdef SMP
2530165762Sjeff	sched_unpin();
2531165762Sjeff#endif
2532122038Sjeff}
2533122038Sjeff
2534109864Sjeffint
2535145256Sjkoshysched_is_bound(struct thread *td)
2536145256Sjkoshy{
2537170293Sjeff	THREAD_LOCK_ASSERT(td, MA_OWNED);
2538164936Sjulian	return (td->td_sched->ts_flags & TSF_BOUND);
2539145256Sjkoshy}
2540145256Sjkoshy
2541171482Sjeff/*
2542171482Sjeff * Basic yield call.
2543171482Sjeff */
2544159630Sdavidxuvoid
2545159630Sdavidxusched_relinquish(struct thread *td)
2546159630Sdavidxu{
2547170293Sjeff	thread_lock(td);
2548170293Sjeff	SCHED_STAT_INC(switch_relinquish);
2549159630Sdavidxu	mi_switch(SW_VOL, NULL);
2550170293Sjeff	thread_unlock(td);
2551159630Sdavidxu}
2552159630Sdavidxu
2553171482Sjeff/*
2554171482Sjeff * Return the total system load.
2555171482Sjeff */
2556145256Sjkoshyint
2557125289Sjeffsched_load(void)
2558125289Sjeff{
2559125289Sjeff#ifdef SMP
2560125289Sjeff	int total;
2561125289Sjeff	int i;
2562125289Sjeff
2563125289Sjeff	total = 0;
2564165620Sjeff	for (i = 0; i <= tdg_maxid; i++)
2565165620Sjeff		total += TDQ_GROUP(i)->tdg_load;
2566125289Sjeff	return (total);
2567125289Sjeff#else
2568165620Sjeff	return (TDQ_SELF()->tdq_sysload);
2569125289Sjeff#endif
2570125289Sjeff}
2571125289Sjeff
2572125289Sjeffint
2573109864Sjeffsched_sizeof_proc(void)
2574109864Sjeff{
2575109864Sjeff	return (sizeof(struct proc));
2576109864Sjeff}
2577109864Sjeff
2578109864Sjeffint
2579109864Sjeffsched_sizeof_thread(void)
2580109864Sjeff{
2581109864Sjeff	return (sizeof(struct thread) + sizeof(struct td_sched));
2582109864Sjeff}
2583159570Sdavidxu
2584166190Sjeff/*
2585166190Sjeff * The actual idle process.
2586166190Sjeff */
2587166190Sjeffvoid
2588166190Sjeffsched_idletd(void *dummy)
2589166190Sjeff{
2590166190Sjeff	struct thread *td;
2591171482Sjeff	struct tdq *tdq;
2592166190Sjeff
2593166190Sjeff	td = curthread;
2594171482Sjeff	tdq = TDQ_SELF();
2595166190Sjeff	mtx_assert(&Giant, MA_NOTOWNED);
2596171482Sjeff	/* ULE relies on preemption for idle interruption. */
2597171482Sjeff	for (;;) {
2598171482Sjeff#ifdef SMP
2599171482Sjeff		if (tdq_idled(tdq))
2600171482Sjeff			cpu_idle();
2601171482Sjeff#else
2602166190Sjeff		cpu_idle();
2603171482Sjeff#endif
2604171482Sjeff	}
2605166190Sjeff}
2606166190Sjeff
2607170293Sjeff/*
2608170293Sjeff * A CPU is entering for the first time or a thread is exiting.
2609170293Sjeff */
2610170293Sjeffvoid
2611170293Sjeffsched_throw(struct thread *td)
2612170293Sjeff{
2613172411Sjeff	struct thread *newtd;
2614171482Sjeff	struct tdq *tdq;
2615171482Sjeff
2616171482Sjeff	tdq = TDQ_SELF();
2617170293Sjeff	if (td == NULL) {
2618171482Sjeff		/* Correct spinlock nesting and acquire the correct lock. */
2619171482Sjeff		TDQ_LOCK(tdq);
2620170293Sjeff		spinlock_exit();
2621170293Sjeff	} else {
2622171482Sjeff		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2623171482Sjeff		tdq_load_rem(tdq, td->td_sched);
2624174629Sjeff		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2625170293Sjeff	}
2626170293Sjeff	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2627172411Sjeff	newtd = choosethread();
2628172411Sjeff	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2629170293Sjeff	PCPU_SET(switchtime, cpu_ticks());
2630170293Sjeff	PCPU_SET(switchticks, ticks);
2631172411Sjeff	cpu_throw(td, newtd);		/* doesn't return */
2632170293Sjeff}
2633170293Sjeff
2634171482Sjeff/*
2635171482Sjeff * This is called from fork_exit().  Just acquire the correct locks and
2636171482Sjeff * let fork do the rest of the work.
2637171482Sjeff */
2638170293Sjeffvoid
2639170600Sjeffsched_fork_exit(struct thread *td)
2640170293Sjeff{
2641171482Sjeff	struct td_sched *ts;
2642171482Sjeff	struct tdq *tdq;
2643171482Sjeff	int cpuid;
2644170293Sjeff
2645170293Sjeff	/*
2646170293Sjeff	 * Finish setting up thread glue so that it begins execution in a
2647171482Sjeff	 * non-nested critical section with the scheduler lock held.
2648170293Sjeff	 */
2649171482Sjeff	cpuid = PCPU_GET(cpuid);
2650171482Sjeff	tdq = TDQ_CPU(cpuid);
2651171482Sjeff	ts = td->td_sched;
2652171482Sjeff	if (TD_IS_IDLETHREAD(td))
2653171482Sjeff		td->td_lock = TDQ_LOCKPTR(tdq);
2654171482Sjeff	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2655171482Sjeff	td->td_oncpu = cpuid;
2656172411Sjeff	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2657174629Sjeff	lock_profile_obtain_lock_success(
2658174629Sjeff	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2659170293Sjeff}
2660170293Sjeff
2661171482Sjeffstatic SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0,
2662171482Sjeff    "Scheduler");
2663171482SjeffSYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2664165762Sjeff    "Scheduler name");
2665171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2666171482Sjeff    "Slice size for timeshare threads");
2667171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2668171482Sjeff     "Interactivity score threshold");
2669171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2670171482Sjeff     0,"Min priority for preemption, lower priorities have greater precedence");
2671166108Sjeff#ifdef SMP
2672171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, pick_pri, CTLFLAG_RW, &pick_pri, 0,
2673171482Sjeff    "Pick the target cpu based on priority rather than load.");
2674171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2675171482Sjeff    "Number of hz ticks to keep thread affinity for");
2676171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, tryself, CTLFLAG_RW, &tryself, 0, "");
2677171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2678171482Sjeff    "Enables the long-term load balancer");
2679172409SjeffSYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2680172409Sjeff    &balance_interval, 0,
2681172409Sjeff    "Average frequency in stathz ticks to run the long-term balancer");
2682171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2683171482Sjeff    "Steals work from another hyper-threaded core on idle");
2684171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2685171482Sjeff    "Attempts to steal work from other cores before idling");
2686171506SjeffSYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2687171506Sjeff    "Minimum load on remote cpu before we'll steal");
2688171482SjeffSYSCTL_INT(_kern_sched, OID_AUTO, topology, CTLFLAG_RD, &topology, 0,
2689171482Sjeff    "True when a topology has been specified by the MD code.");
2690166108Sjeff#endif
2691165762Sjeff
2692172264Sjeff/* ps compat.  All cpu percentages from ULE are weighted. */
2693172293Sjeffstatic int ccpu = 0;
2694165762SjeffSYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2695165762Sjeff
2696165762Sjeff
2697134791Sjulian#define KERN_SWITCH_INCLUDE 1
2698134791Sjulian#include "kern/kern_switch.c"
2699