sched_ule.c revision 172308
1299910Ssgalabov/*-
2299910Ssgalabov * Copyright (c) 2002-2007, Jeffrey Roberson <jeff@freebsd.org>
3299910Ssgalabov * All rights reserved.
4299910Ssgalabov *
5299910Ssgalabov * Redistribution and use in source and binary forms, with or without
6299910Ssgalabov * modification, are permitted provided that the following conditions
7299910Ssgalabov * are met:
8299910Ssgalabov * 1. Redistributions of source code must retain the above copyright
9299910Ssgalabov *    notice unmodified, this list of conditions, and the following
10299910Ssgalabov *    disclaimer.
11299910Ssgalabov * 2. Redistributions in binary form must reproduce the above copyright
12299910Ssgalabov *    notice, this list of conditions and the following disclaimer in the
13299910Ssgalabov *    documentation and/or other materials provided with the distribution.
14299910Ssgalabov *
15299910Ssgalabov * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16299910Ssgalabov * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17299910Ssgalabov * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18299910Ssgalabov * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19299910Ssgalabov * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20299910Ssgalabov * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21299910Ssgalabov * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22299910Ssgalabov * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23299910Ssgalabov * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24299910Ssgalabov * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25299910Ssgalabov */
26299910Ssgalabov
27299910Ssgalabov/*
28299910Ssgalabov * This file implements the ULE scheduler.  ULE supports independent CPU
29299910Ssgalabov * run queues and fine grain locking.  It has superior interactive
30299910Ssgalabov * performance under load even on uni-processor systems.
31299910Ssgalabov *
32299910Ssgalabov * etymology:
33299910Ssgalabov *   ULE is the last three letters in schedule.  It owes its name to a
34299910Ssgalabov * generic user created for a scheduling system by Paul Mikesell at
35299910Ssgalabov * Isilon Systems and a general lack of creativity on the part of the author.
36299910Ssgalabov */
37299910Ssgalabov
38299910Ssgalabov#include <sys/cdefs.h>
39299910Ssgalabov__FBSDID("$FreeBSD: head/sys/kern/sched_ule.c 172308 2007-09-24 00:28:54Z jeff $");
40299910Ssgalabov
41299910Ssgalabov#include "opt_hwpmc_hooks.h"
42299910Ssgalabov#include "opt_sched.h"
43299910Ssgalabov
44299910Ssgalabov#include <sys/param.h>
45299910Ssgalabov#include <sys/systm.h>
46299910Ssgalabov#include <sys/kdb.h>
47299910Ssgalabov#include <sys/kernel.h>
48299910Ssgalabov#include <sys/ktr.h>
49299910Ssgalabov#include <sys/lock.h>
50299910Ssgalabov#include <sys/mutex.h>
51299910Ssgalabov#include <sys/proc.h>
52299910Ssgalabov#include <sys/resource.h>
53299910Ssgalabov#include <sys/resourcevar.h>
54299910Ssgalabov#include <sys/sched.h>
55299910Ssgalabov#include <sys/smp.h>
56299910Ssgalabov#include <sys/sx.h>
57299910Ssgalabov#include <sys/sysctl.h>
58299910Ssgalabov#include <sys/sysproto.h>
59299910Ssgalabov#include <sys/turnstile.h>
60299910Ssgalabov#include <sys/umtx.h>
61299910Ssgalabov#include <sys/vmmeter.h>
62299910Ssgalabov#ifdef KTRACE
63299910Ssgalabov#include <sys/uio.h>
64299910Ssgalabov#include <sys/ktrace.h>
65299910Ssgalabov#endif
66299910Ssgalabov
67299910Ssgalabov#ifdef HWPMC_HOOKS
68299910Ssgalabov#include <sys/pmckern.h>
69299910Ssgalabov#endif
70299910Ssgalabov
71299910Ssgalabov#include <machine/cpu.h>
72299910Ssgalabov#include <machine/smp.h>
73299910Ssgalabov
74299910Ssgalabov#ifndef PREEMPTION
75299910Ssgalabov#error	"SCHED_ULE requires options PREEMPTION"
76299910Ssgalabov#endif
77299910Ssgalabov
78299910Ssgalabov#define	KTR_ULE	0
79299910Ssgalabov
80299910Ssgalabov/*
81299910Ssgalabov * Thread scheduler specific section.  All fields are protected
82299910Ssgalabov * by the thread lock.
83299910Ssgalabov */
84299910Ssgalabovstruct td_sched {
85299910Ssgalabov	TAILQ_ENTRY(td_sched) ts_procq;	/* Run queue. */
86299910Ssgalabov	struct thread	*ts_thread;	/* Active associated thread. */
87299910Ssgalabov	struct runq	*ts_runq;	/* Run-queue we're queued on. */
88299910Ssgalabov	short		ts_flags;	/* TSF_* flags. */
89299910Ssgalabov	u_char		ts_rqindex;	/* Run queue index. */
90299910Ssgalabov	u_char		ts_cpu;		/* CPU that we have affinity for. */
91299910Ssgalabov	int		ts_slice;	/* Ticks of slice remaining. */
92299910Ssgalabov	u_int		ts_slptime;	/* Number of ticks we vol. slept */
93299910Ssgalabov	u_int		ts_runtime;	/* Number of ticks we were running */
94299910Ssgalabov	/* The following variables are only used for pctcpu calculation */
95299910Ssgalabov	int		ts_ltick;	/* Last tick that we were running on */
96299910Ssgalabov	int		ts_ftick;	/* First tick that we were running on */
97299910Ssgalabov	int		ts_ticks;	/* Tick count */
98299910Ssgalabov#ifdef SMP
99299910Ssgalabov	int		ts_rltick;	/* Real last tick, for affinity. */
100299910Ssgalabov#endif
101299910Ssgalabov};
102299910Ssgalabov/* flags kept in ts_flags */
103299910Ssgalabov#define	TSF_BOUND	0x0001		/* Thread can not migrate. */
104299910Ssgalabov#define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
105299910Ssgalabov
106299910Ssgalabovstatic struct td_sched td_sched0;
107299910Ssgalabov
108299910Ssgalabov/*
109299910Ssgalabov * Cpu percentage computation macros and defines.
110299910Ssgalabov *
111299910Ssgalabov * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
112299910Ssgalabov * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
113299910Ssgalabov * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
114299910Ssgalabov * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
115299910Ssgalabov * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
116299910Ssgalabov * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
117299910Ssgalabov */
118299910Ssgalabov#define	SCHED_TICK_SECS		10
119299910Ssgalabov#define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
120299910Ssgalabov#define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
121299910Ssgalabov#define	SCHED_TICK_SHIFT	10
122299910Ssgalabov#define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
123299910Ssgalabov#define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
124299910Ssgalabov
125299910Ssgalabov/*
126299910Ssgalabov * These macros determine priorities for non-interactive threads.  They are
127299910Ssgalabov * assigned a priority based on their recent cpu utilization as expressed
128299910Ssgalabov * by the ratio of ticks to the tick total.  NHALF priorities at the start
129299910Ssgalabov * and end of the MIN to MAX timeshare range are only reachable with negative
130299910Ssgalabov * or positive nice respectively.
131299910Ssgalabov *
132299910Ssgalabov * PRI_RANGE:	Priority range for utilization dependent priorities.
133299910Ssgalabov * PRI_NRESV:	Number of nice values.
134299910Ssgalabov * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
135299910Ssgalabov * PRI_NICE:	Determines the part of the priority inherited from nice.
136299910Ssgalabov */
137299910Ssgalabov#define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
138299910Ssgalabov#define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
139299910Ssgalabov#define	SCHED_PRI_MIN		(PRI_MIN_TIMESHARE + SCHED_PRI_NHALF)
140299910Ssgalabov#define	SCHED_PRI_MAX		(PRI_MAX_TIMESHARE - SCHED_PRI_NHALF)
141299910Ssgalabov#define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN)
142299910Ssgalabov#define	SCHED_PRI_TICKS(ts)						\
143299910Ssgalabov    (SCHED_TICK_HZ((ts)) /						\
144299910Ssgalabov    (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
145299910Ssgalabov#define	SCHED_PRI_NICE(nice)	(nice)
146299910Ssgalabov
147299910Ssgalabov/*
148299910Ssgalabov * These determine the interactivity of a process.  Interactivity differs from
149299910Ssgalabov * cpu utilization in that it expresses the voluntary time slept vs time ran
150299910Ssgalabov * while cpu utilization includes all time not running.  This more accurately
151299910Ssgalabov * models the intent of the thread.
152299910Ssgalabov *
153299910Ssgalabov * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
154299910Ssgalabov *		before throttling back.
155299910Ssgalabov * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
156299910Ssgalabov * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
157299910Ssgalabov * INTERACT_THRESH:	Threshhold for placement on the current runq.
158299910Ssgalabov */
159299910Ssgalabov#define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
160299910Ssgalabov#define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
161299910Ssgalabov#define	SCHED_INTERACT_MAX	(100)
162299910Ssgalabov#define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
163299910Ssgalabov#define	SCHED_INTERACT_THRESH	(30)
164299910Ssgalabov
165299910Ssgalabov/*
166299910Ssgalabov * tickincr:		Converts a stathz tick into a hz domain scaled by
167299910Ssgalabov *			the shift factor.  Without the shift the error rate
168299910Ssgalabov *			due to rounding would be unacceptably high.
169299910Ssgalabov * realstathz:		stathz is sometimes 0 and run off of hz.
170299910Ssgalabov * sched_slice:		Runtime of each thread before rescheduling.
171299910Ssgalabov * preempt_thresh:	Priority threshold for preemption and remote IPIs.
172299910Ssgalabov */
173299910Ssgalabovstatic int sched_interact = SCHED_INTERACT_THRESH;
174299910Ssgalabovstatic int realstathz;
175299910Ssgalabovstatic int tickincr;
176299910Ssgalabovstatic int sched_slice;
177299910Ssgalabovstatic int preempt_thresh = PRI_MIN_KERN;
178299910Ssgalabov
179299910Ssgalabov/*
180299910Ssgalabov * tdq - per processor runqs and statistics.  All fields are protected by the
181299910Ssgalabov * tdq_lock.  The load and lowpri may be accessed without to avoid excess
182299910Ssgalabov * locking in sched_pickcpu();
183299910Ssgalabov */
184299910Ssgalabovstruct tdq {
185299910Ssgalabov	struct mtx	*tdq_lock;		/* Pointer to group lock. */
186299910Ssgalabov	struct runq	tdq_realtime;		/* real-time run queue. */
187299910Ssgalabov	struct runq	tdq_timeshare;		/* timeshare run queue. */
188299910Ssgalabov	struct runq	tdq_idle;		/* Queue of IDLE threads. */
189299910Ssgalabov	int		tdq_load;		/* Aggregate load. */
190299910Ssgalabov	u_char		tdq_idx;		/* Current insert index. */
191299910Ssgalabov	u_char		tdq_ridx;		/* Current removal index. */
192299910Ssgalabov#ifdef SMP
193299910Ssgalabov	u_char		tdq_lowpri;		/* Lowest priority thread. */
194299910Ssgalabov	int		tdq_transferable;	/* Transferable thread count. */
195299910Ssgalabov	LIST_ENTRY(tdq)	tdq_siblings;		/* Next in tdq group. */
196299910Ssgalabov	struct tdq_group *tdq_group;		/* Our processor group. */
197299910Ssgalabov#else
198299910Ssgalabov	int		tdq_sysload;		/* For loadavg, !ITHD load. */
199299910Ssgalabov#endif
200299910Ssgalabov} __aligned(64);
201299910Ssgalabov
202299910Ssgalabov
203299910Ssgalabov#ifdef SMP
204299910Ssgalabov/*
205299910Ssgalabov * tdq groups are groups of processors which can cheaply share threads.  When
206299910Ssgalabov * one processor in the group goes idle it will check the runqs of the other
207299910Ssgalabov * processors in its group prior to halting and waiting for an interrupt.
208299910Ssgalabov * These groups are suitable for SMT (Symetric Multi-Threading) and not NUMA.
209299910Ssgalabov * In a numa environment we'd want an idle bitmap per group and a two tiered
210299910Ssgalabov * load balancer.
211299910Ssgalabov */
212299910Ssgalabovstruct tdq_group {
213299910Ssgalabov	struct mtx	tdg_lock;	/* Protects all fields below. */
214299910Ssgalabov	int		tdg_cpus;	/* Count of CPUs in this tdq group. */
215299910Ssgalabov	cpumask_t 	tdg_cpumask;	/* Mask of cpus in this group. */
216299910Ssgalabov	cpumask_t 	tdg_idlemask;	/* Idle cpus in this group. */
217299910Ssgalabov	cpumask_t 	tdg_mask;	/* Bit mask for first cpu. */
218299910Ssgalabov	int		tdg_load;	/* Total load of this group. */
219299910Ssgalabov	int	tdg_transferable;	/* Transferable load of this group. */
220299910Ssgalabov	LIST_HEAD(, tdq) tdg_members;	/* Linked list of all members. */
221299910Ssgalabov	char		tdg_name[16];	/* lock name. */
222299910Ssgalabov} __aligned(64);
223299910Ssgalabov
224299910Ssgalabov#define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 300))
225299910Ssgalabov#define	SCHED_AFFINITY(ts)	((ts)->ts_rltick > ticks - affinity)
226299910Ssgalabov
227299910Ssgalabov/*
228299910Ssgalabov * Run-time tunables.
229299910Ssgalabov */
230299910Ssgalabovstatic int rebalance = 1;
231299910Ssgalabovstatic int balance_secs = 1;
232299910Ssgalabovstatic int pick_pri = 1;
233299910Ssgalabovstatic int affinity;
234299910Ssgalabovstatic int tryself = 1;
235299910Ssgalabovstatic int steal_htt = 0;
236299910Ssgalabovstatic int steal_idle = 1;
237299910Ssgalabovstatic int steal_thresh = 2;
238299910Ssgalabovstatic int topology = 0;
239299910Ssgalabov
240299910Ssgalabov/*
241299910Ssgalabov * One thread queue per processor.
242299910Ssgalabov */
243299910Ssgalabovstatic volatile cpumask_t tdq_idle;
244299910Ssgalabovstatic int tdg_maxid;
245299910Ssgalabovstatic struct tdq	tdq_cpu[MAXCPU];
246299910Ssgalabovstatic struct tdq_group tdq_groups[MAXCPU];
247299910Ssgalabovstatic struct callout balco;
248299910Ssgalabovstatic struct callout gbalco;
249299910Ssgalabov
250299910Ssgalabov#define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
251299910Ssgalabov#define	TDQ_CPU(x)	(&tdq_cpu[(x)])
252299910Ssgalabov#define	TDQ_ID(x)	((int)((x) - tdq_cpu))
253299910Ssgalabov#define	TDQ_GROUP(x)	(&tdq_groups[(x)])
254299910Ssgalabov#define	TDG_ID(x)	((int)((x) - tdq_groups))
255299910Ssgalabov#else	/* !SMP */
256299910Ssgalabovstatic struct tdq	tdq_cpu;
257299910Ssgalabovstatic struct mtx	tdq_lock;
258299910Ssgalabov
259299910Ssgalabov#define	TDQ_ID(x)	(0)
260299910Ssgalabov#define	TDQ_SELF()	(&tdq_cpu)
261299910Ssgalabov#define	TDQ_CPU(x)	(&tdq_cpu)
262299910Ssgalabov#endif
263299910Ssgalabov
264299910Ssgalabov#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
265299910Ssgalabov#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
266299910Ssgalabov#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
267299910Ssgalabov#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
268299910Ssgalabov#define	TDQ_LOCKPTR(t)		((t)->tdq_lock)
269299910Ssgalabov
270299910Ssgalabovstatic void sched_priority(struct thread *);
271299910Ssgalabovstatic void sched_thread_priority(struct thread *, u_char);
272299910Ssgalabovstatic int sched_interact_score(struct thread *);
273299910Ssgalabovstatic void sched_interact_update(struct thread *);
274299910Ssgalabovstatic void sched_interact_fork(struct thread *);
275299910Ssgalabovstatic void sched_pctcpu_update(struct td_sched *);
276299910Ssgalabov
277299910Ssgalabov/* Operations on per processor queues */
278299910Ssgalabovstatic struct td_sched * tdq_choose(struct tdq *);
279299910Ssgalabovstatic void tdq_setup(struct tdq *);
280299910Ssgalabovstatic void tdq_load_add(struct tdq *, struct td_sched *);
281299910Ssgalabovstatic void tdq_load_rem(struct tdq *, struct td_sched *);
282299910Ssgalabovstatic __inline void tdq_runq_add(struct tdq *, struct td_sched *, int);
283299910Ssgalabovstatic __inline void tdq_runq_rem(struct tdq *, struct td_sched *);
284299910Ssgalabovvoid tdq_print(int cpu);
285299910Ssgalabovstatic void runq_print(struct runq *rq);
286299910Ssgalabovstatic void tdq_add(struct tdq *, struct thread *, int);
287299910Ssgalabov#ifdef SMP
288299910Ssgalabovstatic void tdq_move(struct tdq *, struct tdq *);
289299910Ssgalabovstatic int tdq_idled(struct tdq *);
290299910Ssgalabovstatic void tdq_notify(struct td_sched *);
291299910Ssgalabovstatic struct td_sched *tdq_steal(struct tdq *, int);
292299910Ssgalabovstatic struct td_sched *runq_steal(struct runq *);
293299910Ssgalabovstatic int sched_pickcpu(struct td_sched *, int);
294299910Ssgalabovstatic void sched_balance(void *);
295299910Ssgalabovstatic void sched_balance_groups(void *);
296299910Ssgalabovstatic void sched_balance_group(struct tdq_group *);
297299910Ssgalabovstatic void sched_balance_pair(struct tdq *, struct tdq *);
298299910Ssgalabovstatic inline struct tdq *sched_setcpu(struct td_sched *, int, int);
299299910Ssgalabovstatic inline struct mtx *thread_block_switch(struct thread *);
300299910Ssgalabovstatic inline void thread_unblock_switch(struct thread *, struct mtx *);
301299910Ssgalabovstatic struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
302299910Ssgalabov
303299910Ssgalabov#define	THREAD_CAN_MIGRATE(td)	 ((td)->td_pinned == 0)
304299910Ssgalabov#endif
305299910Ssgalabov
306299910Ssgalabovstatic void sched_setup(void *dummy);
307299910SsgalabovSYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
308299910Ssgalabov
309299910Ssgalabovstatic void sched_initticks(void *dummy);
310299910SsgalabovSYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks, NULL)
311299910Ssgalabov
312299910Ssgalabov/*
313299910Ssgalabov * Print the threads waiting on a run-queue.
314299910Ssgalabov */
315299910Ssgalabovstatic void
316299910Ssgalabovrunq_print(struct runq *rq)
317299910Ssgalabov{
318299910Ssgalabov	struct rqhead *rqh;
319299910Ssgalabov	struct td_sched *ts;
320299910Ssgalabov	int pri;
321299910Ssgalabov	int j;
322299910Ssgalabov	int i;
323299910Ssgalabov
324299910Ssgalabov	for (i = 0; i < RQB_LEN; i++) {
325299910Ssgalabov		printf("\t\trunq bits %d 0x%zx\n",
326299910Ssgalabov		    i, rq->rq_status.rqb_bits[i]);
327299910Ssgalabov		for (j = 0; j < RQB_BPW; j++)
328299910Ssgalabov			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
329299910Ssgalabov				pri = j + (i << RQB_L2BPW);
330299910Ssgalabov				rqh = &rq->rq_queues[pri];
331299910Ssgalabov				TAILQ_FOREACH(ts, rqh, ts_procq) {
332299910Ssgalabov					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
333299910Ssgalabov					    ts->ts_thread, ts->ts_thread->td_proc->p_comm, ts->ts_thread->td_priority, ts->ts_rqindex, pri);
334299910Ssgalabov				}
335299910Ssgalabov			}
336299910Ssgalabov	}
337299910Ssgalabov}
338299910Ssgalabov
339299910Ssgalabov/*
340299910Ssgalabov * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
341299910Ssgalabov */
342299910Ssgalabovvoid
343299910Ssgalabovtdq_print(int cpu)
344299910Ssgalabov{
345299910Ssgalabov	struct tdq *tdq;
346299910Ssgalabov
347299910Ssgalabov	tdq = TDQ_CPU(cpu);
348299910Ssgalabov
349299910Ssgalabov	printf("tdq %d:\n", TDQ_ID(tdq));
350299910Ssgalabov	printf("\tlockptr         %p\n", TDQ_LOCKPTR(tdq));
351299910Ssgalabov	printf("\tload:           %d\n", tdq->tdq_load);
352299910Ssgalabov	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
353299910Ssgalabov	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
354299910Ssgalabov	printf("\trealtime runq:\n");
355299910Ssgalabov	runq_print(&tdq->tdq_realtime);
356299910Ssgalabov	printf("\ttimeshare runq:\n");
357299910Ssgalabov	runq_print(&tdq->tdq_timeshare);
358299910Ssgalabov	printf("\tidle runq:\n");
359299910Ssgalabov	runq_print(&tdq->tdq_idle);
360299910Ssgalabov#ifdef SMP
361299910Ssgalabov	printf("\tload transferable: %d\n", tdq->tdq_transferable);
362299910Ssgalabov	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
363299910Ssgalabov	printf("\tgroup:             %d\n", TDG_ID(tdq->tdq_group));
364299910Ssgalabov	printf("\tLock name:         %s\n", tdq->tdq_group->tdg_name);
365299910Ssgalabov#endif
366299910Ssgalabov}
367299910Ssgalabov
368299910Ssgalabov#define	TS_RQ_PPQ	(((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
369299910Ssgalabov/*
370299910Ssgalabov * Add a thread to the actual run-queue.  Keeps transferable counts up to
371299910Ssgalabov * date with what is actually on the run-queue.  Selects the correct
372299910Ssgalabov * queue position for timeshare threads.
373299910Ssgalabov */
374299910Ssgalabovstatic __inline void
375299910Ssgalabovtdq_runq_add(struct tdq *tdq, struct td_sched *ts, int flags)
376299910Ssgalabov{
377299910Ssgalabov	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
378299910Ssgalabov	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
379299910Ssgalabov#ifdef SMP
380299910Ssgalabov	if (THREAD_CAN_MIGRATE(ts->ts_thread)) {
381299910Ssgalabov		tdq->tdq_transferable++;
382299910Ssgalabov		tdq->tdq_group->tdg_transferable++;
383299910Ssgalabov		ts->ts_flags |= TSF_XFERABLE;
384299910Ssgalabov	}
385299910Ssgalabov#endif
386299910Ssgalabov	if (ts->ts_runq == &tdq->tdq_timeshare) {
387299910Ssgalabov		u_char pri;
388299910Ssgalabov
389299910Ssgalabov		pri = ts->ts_thread->td_priority;
390299910Ssgalabov		KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
391299910Ssgalabov			("Invalid priority %d on timeshare runq", pri));
392299910Ssgalabov		/*
393299910Ssgalabov		 * This queue contains only priorities between MIN and MAX
394299910Ssgalabov		 * realtime.  Use the whole queue to represent these values.
395299910Ssgalabov		 */
396299910Ssgalabov		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
397299910Ssgalabov			pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
398299910Ssgalabov			pri = (pri + tdq->tdq_idx) % RQ_NQS;
399299910Ssgalabov			/*
400299910Ssgalabov			 * This effectively shortens the queue by one so we
401299910Ssgalabov			 * can have a one slot difference between idx and
402299910Ssgalabov			 * ridx while we wait for threads to drain.
403299910Ssgalabov			 */
404299910Ssgalabov			if (tdq->tdq_ridx != tdq->tdq_idx &&
405299910Ssgalabov			    pri == tdq->tdq_ridx)
406299910Ssgalabov				pri = (unsigned char)(pri - 1) % RQ_NQS;
407299910Ssgalabov		} else
408299910Ssgalabov			pri = tdq->tdq_ridx;
409299910Ssgalabov		runq_add_pri(ts->ts_runq, ts, pri, flags);
410299910Ssgalabov	} else
411299910Ssgalabov		runq_add(ts->ts_runq, ts, flags);
412299910Ssgalabov}
413299910Ssgalabov
414299910Ssgalabov/*
415299910Ssgalabov * Remove a thread from a run-queue.  This typically happens when a thread
416299910Ssgalabov * is selected to run.  Running threads are not on the queue and the
417299910Ssgalabov * transferable count does not reflect them.
418299910Ssgalabov */
419299910Ssgalabovstatic __inline void
420299910Ssgalabovtdq_runq_rem(struct tdq *tdq, struct td_sched *ts)
421299910Ssgalabov{
422299910Ssgalabov	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
423299910Ssgalabov	KASSERT(ts->ts_runq != NULL,
424299910Ssgalabov	    ("tdq_runq_remove: thread %p null ts_runq", ts->ts_thread));
425299910Ssgalabov#ifdef SMP
426299910Ssgalabov	if (ts->ts_flags & TSF_XFERABLE) {
427299910Ssgalabov		tdq->tdq_transferable--;
428299910Ssgalabov		tdq->tdq_group->tdg_transferable--;
429299910Ssgalabov		ts->ts_flags &= ~TSF_XFERABLE;
430299910Ssgalabov	}
431299910Ssgalabov#endif
432299910Ssgalabov	if (ts->ts_runq == &tdq->tdq_timeshare) {
433299910Ssgalabov		if (tdq->tdq_idx != tdq->tdq_ridx)
434299910Ssgalabov			runq_remove_idx(ts->ts_runq, ts, &tdq->tdq_ridx);
435299910Ssgalabov		else
436299910Ssgalabov			runq_remove_idx(ts->ts_runq, ts, NULL);
437299910Ssgalabov		/*
438299910Ssgalabov		 * For timeshare threads we update the priority here so
439299910Ssgalabov		 * the priority reflects the time we've been sleeping.
440299910Ssgalabov		 */
441299910Ssgalabov		ts->ts_ltick = ticks;
442299910Ssgalabov		sched_pctcpu_update(ts);
443299910Ssgalabov		sched_priority(ts->ts_thread);
444299910Ssgalabov	} else
445299910Ssgalabov		runq_remove(ts->ts_runq, ts);
446299910Ssgalabov}
447299910Ssgalabov
448299910Ssgalabov/*
449299910Ssgalabov * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
450299910Ssgalabov * for this thread to the referenced thread queue.
451299910Ssgalabov */
452299910Ssgalabovstatic void
453299910Ssgalabovtdq_load_add(struct tdq *tdq, struct td_sched *ts)
454299910Ssgalabov{
455299910Ssgalabov	int class;
456299910Ssgalabov
457299910Ssgalabov	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
458299910Ssgalabov	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
459299910Ssgalabov	class = PRI_BASE(ts->ts_thread->td_pri_class);
460299910Ssgalabov	tdq->tdq_load++;
461299910Ssgalabov	CTR2(KTR_SCHED, "cpu %d load: %d", TDQ_ID(tdq), tdq->tdq_load);
462299910Ssgalabov	if (class != PRI_ITHD &&
463299910Ssgalabov	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
464299910Ssgalabov#ifdef SMP
465299910Ssgalabov		tdq->tdq_group->tdg_load++;
466299910Ssgalabov#else
467299910Ssgalabov		tdq->tdq_sysload++;
468299910Ssgalabov#endif
469299910Ssgalabov}
470299910Ssgalabov
471299910Ssgalabov/*
472299910Ssgalabov * Remove the load from a thread that is transitioning to a sleep state or
473299910Ssgalabov * exiting.
474299910Ssgalabov */
475299910Ssgalabovstatic void
476299910Ssgalabovtdq_load_rem(struct tdq *tdq, struct td_sched *ts)
477299910Ssgalabov{
478299910Ssgalabov	int class;
479299910Ssgalabov
480299910Ssgalabov	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
481299910Ssgalabov	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
482299910Ssgalabov	class = PRI_BASE(ts->ts_thread->td_pri_class);
483299910Ssgalabov	if (class != PRI_ITHD &&
484299910Ssgalabov	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
485299910Ssgalabov#ifdef SMP
486299910Ssgalabov		tdq->tdq_group->tdg_load--;
487299910Ssgalabov#else
488299910Ssgalabov		tdq->tdq_sysload--;
489299910Ssgalabov#endif
490299910Ssgalabov	KASSERT(tdq->tdq_load != 0,
491299910Ssgalabov	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
492299910Ssgalabov	tdq->tdq_load--;
493299910Ssgalabov	CTR1(KTR_SCHED, "load: %d", tdq->tdq_load);
494299910Ssgalabov	ts->ts_runq = NULL;
495299910Ssgalabov}
496299910Ssgalabov
497299910Ssgalabov#ifdef SMP
498299910Ssgalabov/*
499299910Ssgalabov * sched_balance is a simple CPU load balancing algorithm.  It operates by
500299910Ssgalabov * finding the least loaded and most loaded cpu and equalizing their load
501299910Ssgalabov * by migrating some processes.
502299910Ssgalabov *
503299910Ssgalabov * Dealing only with two CPUs at a time has two advantages.  Firstly, most
504299910Ssgalabov * installations will only have 2 cpus.  Secondly, load balancing too much at
505299910Ssgalabov * once can have an unpleasant effect on the system.  The scheduler rarely has
506299910Ssgalabov * enough information to make perfect decisions.  So this algorithm chooses
507299910Ssgalabov * simplicity and more gradual effects on load in larger systems.
508299910Ssgalabov *
509299910Ssgalabov */
510299910Ssgalabovstatic void
511299910Ssgalabovsched_balance(void *arg)
512299910Ssgalabov{
513299910Ssgalabov	struct tdq_group *high;
514299910Ssgalabov	struct tdq_group *low;
515299910Ssgalabov	struct tdq_group *tdg;
516299910Ssgalabov	int cnt;
517299910Ssgalabov	int i;
518299910Ssgalabov
519299910Ssgalabov	callout_reset(&balco, max(hz / 2, random() % (hz * balance_secs)),
520299910Ssgalabov	    sched_balance, NULL);
521299910Ssgalabov	if (smp_started == 0 || rebalance == 0)
522299910Ssgalabov		return;
523299910Ssgalabov	low = high = NULL;
524299910Ssgalabov	i = random() % (tdg_maxid + 1);
525299910Ssgalabov	for (cnt = 0; cnt <= tdg_maxid; cnt++) {
526299910Ssgalabov		tdg = TDQ_GROUP(i);
527299910Ssgalabov		/*
528299910Ssgalabov		 * Find the CPU with the highest load that has some
529299910Ssgalabov		 * threads to transfer.
530299910Ssgalabov		 */
531299910Ssgalabov		if ((high == NULL || tdg->tdg_load > high->tdg_load)
532299910Ssgalabov		    && tdg->tdg_transferable)
533299910Ssgalabov			high = tdg;
534299910Ssgalabov		if (low == NULL || tdg->tdg_load < low->tdg_load)
535299910Ssgalabov			low = tdg;
536299910Ssgalabov		if (++i > tdg_maxid)
537299910Ssgalabov			i = 0;
538299910Ssgalabov	}
539299910Ssgalabov	if (low != NULL && high != NULL && high != low)
540299910Ssgalabov		sched_balance_pair(LIST_FIRST(&high->tdg_members),
541299910Ssgalabov		    LIST_FIRST(&low->tdg_members));
542299910Ssgalabov}
543299910Ssgalabov
544299910Ssgalabov/*
545299910Ssgalabov * Balance load between CPUs in a group.  Will only migrate within the group.
546299910Ssgalabov */
547299910Ssgalabovstatic void
548299910Ssgalabovsched_balance_groups(void *arg)
549299910Ssgalabov{
550299910Ssgalabov	int i;
551299910Ssgalabov
552299910Ssgalabov	callout_reset(&gbalco, max(hz / 2, random() % (hz * balance_secs)),
553299910Ssgalabov	    sched_balance_groups, NULL);
554299910Ssgalabov	if (smp_started == 0 || rebalance == 0)
555299910Ssgalabov		return;
556299910Ssgalabov	for (i = 0; i <= tdg_maxid; i++)
557299910Ssgalabov		sched_balance_group(TDQ_GROUP(i));
558299910Ssgalabov}
559299910Ssgalabov
560299910Ssgalabov/*
561299910Ssgalabov * Finds the greatest imbalance between two tdqs in a group.
562299910Ssgalabov */
563299910Ssgalabovstatic void
564299910Ssgalabovsched_balance_group(struct tdq_group *tdg)
565299910Ssgalabov{
566299910Ssgalabov	struct tdq *tdq;
567299910Ssgalabov	struct tdq *high;
568299910Ssgalabov	struct tdq *low;
569299910Ssgalabov	int load;
570299910Ssgalabov
571299910Ssgalabov	if (tdg->tdg_transferable == 0)
572299910Ssgalabov		return;
573299910Ssgalabov	low = NULL;
574299910Ssgalabov	high = NULL;
575299910Ssgalabov	LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
576299910Ssgalabov		load = tdq->tdq_load;
577299910Ssgalabov		if (high == NULL || load > high->tdq_load)
578299910Ssgalabov			high = tdq;
579299910Ssgalabov		if (low == NULL || load < low->tdq_load)
580299910Ssgalabov			low = tdq;
581299910Ssgalabov	}
582299910Ssgalabov	if (high != NULL && low != NULL && high != low)
583299910Ssgalabov		sched_balance_pair(high, low);
584299910Ssgalabov}
585299910Ssgalabov
586299910Ssgalabov/*
587299910Ssgalabov * Lock two thread queues using their address to maintain lock order.
588299910Ssgalabov */
589299910Ssgalabovstatic void
590299910Ssgalabovtdq_lock_pair(struct tdq *one, struct tdq *two)
591299910Ssgalabov{
592299910Ssgalabov	if (one < two) {
593299910Ssgalabov		TDQ_LOCK(one);
594299910Ssgalabov		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
595299910Ssgalabov	} else {
596299910Ssgalabov		TDQ_LOCK(two);
597299910Ssgalabov		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
598299910Ssgalabov	}
599299910Ssgalabov}
600299910Ssgalabov
601299910Ssgalabov/*
602299910Ssgalabov * Transfer load between two imbalanced thread queues.
603299910Ssgalabov */
604299910Ssgalabovstatic void
605299910Ssgalabovsched_balance_pair(struct tdq *high, struct tdq *low)
606299910Ssgalabov{
607299910Ssgalabov	int transferable;
608299910Ssgalabov	int high_load;
609299910Ssgalabov	int low_load;
610299910Ssgalabov	int move;
611299910Ssgalabov	int diff;
612299910Ssgalabov	int i;
613299910Ssgalabov
614299910Ssgalabov	tdq_lock_pair(high, low);
615299910Ssgalabov	/*
616299910Ssgalabov	 * If we're transfering within a group we have to use this specific
617299910Ssgalabov	 * tdq's transferable count, otherwise we can steal from other members
618299910Ssgalabov	 * of the group.
619299910Ssgalabov	 */
620299910Ssgalabov	if (high->tdq_group == low->tdq_group) {
621299910Ssgalabov		transferable = high->tdq_transferable;
622299910Ssgalabov		high_load = high->tdq_load;
623299910Ssgalabov		low_load = low->tdq_load;
624299910Ssgalabov	} else {
625299910Ssgalabov		transferable = high->tdq_group->tdg_transferable;
626299910Ssgalabov		high_load = high->tdq_group->tdg_load;
627299910Ssgalabov		low_load = low->tdq_group->tdg_load;
628299910Ssgalabov	}
629299910Ssgalabov	/*
630299910Ssgalabov	 * Determine what the imbalance is and then adjust that to how many
631299910Ssgalabov	 * threads we actually have to give up (transferable).
632299910Ssgalabov	 */
633299910Ssgalabov	if (transferable != 0) {
634299910Ssgalabov		diff = high_load - low_load;
635299910Ssgalabov		move = diff / 2;
636299910Ssgalabov		if (diff & 0x1)
637299910Ssgalabov			move++;
638299910Ssgalabov		move = min(move, transferable);
639299910Ssgalabov		for (i = 0; i < move; i++)
640299910Ssgalabov			tdq_move(high, low);
641299910Ssgalabov		/*
642299910Ssgalabov		 * IPI the target cpu to force it to reschedule with the new
643299910Ssgalabov		 * workload.
644299910Ssgalabov		 */
645299910Ssgalabov		ipi_selected(1 << TDQ_ID(low), IPI_PREEMPT);
646299910Ssgalabov	}
647299910Ssgalabov	TDQ_UNLOCK(high);
648299910Ssgalabov	TDQ_UNLOCK(low);
649299910Ssgalabov	return;
650299910Ssgalabov}
651299910Ssgalabov
652299910Ssgalabov/*
653299910Ssgalabov * Move a thread from one thread queue to another.
654299910Ssgalabov */
655299910Ssgalabovstatic void
656299910Ssgalabovtdq_move(struct tdq *from, struct tdq *to)
657299910Ssgalabov{
658299910Ssgalabov	struct td_sched *ts;
659299910Ssgalabov	struct thread *td;
660299910Ssgalabov	struct tdq *tdq;
661299910Ssgalabov	int cpu;
662299910Ssgalabov
663299910Ssgalabov	tdq = from;
664299910Ssgalabov	cpu = TDQ_ID(to);
665299910Ssgalabov	ts = tdq_steal(tdq, 1);
666299910Ssgalabov	if (ts == NULL) {
667299910Ssgalabov		struct tdq_group *tdg;
668299910Ssgalabov
669		tdg = tdq->tdq_group;
670		LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
671			if (tdq == from || tdq->tdq_transferable == 0)
672				continue;
673			ts = tdq_steal(tdq, 1);
674			break;
675		}
676		if (ts == NULL)
677			return;
678	}
679	if (tdq == to)
680		return;
681	td = ts->ts_thread;
682	/*
683	 * Although the run queue is locked the thread may be blocked.  Lock
684	 * it to clear this.
685	 */
686	thread_lock(td);
687	/* Drop recursive lock on from. */
688	TDQ_UNLOCK(from);
689	sched_rem(td);
690	ts->ts_cpu = cpu;
691	td->td_lock = TDQ_LOCKPTR(to);
692	tdq_add(to, td, SRQ_YIELDING);
693}
694
695/*
696 * This tdq has idled.  Try to steal a thread from another cpu and switch
697 * to it.
698 */
699static int
700tdq_idled(struct tdq *tdq)
701{
702	struct tdq_group *tdg;
703	struct tdq *steal;
704	struct td_sched *ts;
705	struct thread *td;
706	int highload;
707	int highcpu;
708	int load;
709	int cpu;
710
711	/* We don't want to be preempted while we're iterating over tdqs */
712	spinlock_enter();
713	tdg = tdq->tdq_group;
714	/*
715	 * If we're in a cpu group, try and steal threads from another cpu in
716	 * the group before idling.
717	 */
718	if (steal_htt && tdg->tdg_cpus > 1 && tdg->tdg_transferable) {
719		LIST_FOREACH(steal, &tdg->tdg_members, tdq_siblings) {
720			if (steal == tdq || steal->tdq_transferable == 0)
721				continue;
722			TDQ_LOCK(steal);
723			ts = tdq_steal(steal, 0);
724			if (ts)
725				goto steal;
726			TDQ_UNLOCK(steal);
727		}
728	}
729	for (;;) {
730		if (steal_idle == 0)
731			break;
732		highcpu = 0;
733		highload = 0;
734		for (cpu = 0; cpu <= mp_maxid; cpu++) {
735			if (CPU_ABSENT(cpu))
736				continue;
737			steal = TDQ_CPU(cpu);
738			load = TDQ_CPU(cpu)->tdq_transferable;
739			if (load < highload)
740				continue;
741			highload = load;
742			highcpu = cpu;
743		}
744		if (highload < steal_thresh)
745			break;
746		steal = TDQ_CPU(highcpu);
747		TDQ_LOCK(steal);
748		if (steal->tdq_transferable >= steal_thresh &&
749		    (ts = tdq_steal(steal, 1)) != NULL)
750			goto steal;
751		TDQ_UNLOCK(steal);
752		break;
753	}
754	spinlock_exit();
755	return (1);
756steal:
757	td = ts->ts_thread;
758	thread_lock(td);
759	spinlock_exit();
760	MPASS(td->td_lock == TDQ_LOCKPTR(steal));
761	TDQ_UNLOCK(steal);
762	sched_rem(td);
763	sched_setcpu(ts, PCPU_GET(cpuid), SRQ_YIELDING);
764	tdq_add(tdq, td, SRQ_YIELDING);
765	MPASS(td->td_lock == curthread->td_lock);
766	mi_switch(SW_VOL, NULL);
767	thread_unlock(curthread);
768
769	return (0);
770}
771
772/*
773 * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
774 */
775static void
776tdq_notify(struct td_sched *ts)
777{
778	struct thread *ctd;
779	struct pcpu *pcpu;
780	int cpri;
781	int pri;
782	int cpu;
783
784	cpu = ts->ts_cpu;
785	pri = ts->ts_thread->td_priority;
786	pcpu = pcpu_find(cpu);
787	ctd = pcpu->pc_curthread;
788	cpri = ctd->td_priority;
789
790	/*
791	 * If our priority is not better than the current priority there is
792	 * nothing to do.
793	 */
794	if (pri > cpri)
795		return;
796	/*
797	 * Always IPI idle.
798	 */
799	if (cpri > PRI_MIN_IDLE)
800		goto sendipi;
801	/*
802	 * If we're realtime or better and there is timeshare or worse running
803	 * send an IPI.
804	 */
805	if (pri < PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
806		goto sendipi;
807	/*
808	 * Otherwise only IPI if we exceed the threshold.
809	 */
810	if (pri > preempt_thresh)
811		return;
812sendipi:
813	ctd->td_flags |= TDF_NEEDRESCHED;
814	ipi_selected(1 << cpu, IPI_PREEMPT);
815}
816
817/*
818 * Steals load from a timeshare queue.  Honors the rotating queue head
819 * index.
820 */
821static struct td_sched *
822runq_steal_from(struct runq *rq, u_char start)
823{
824	struct td_sched *ts;
825	struct rqbits *rqb;
826	struct rqhead *rqh;
827	int first;
828	int bit;
829	int pri;
830	int i;
831
832	rqb = &rq->rq_status;
833	bit = start & (RQB_BPW -1);
834	pri = 0;
835	first = 0;
836again:
837	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
838		if (rqb->rqb_bits[i] == 0)
839			continue;
840		if (bit != 0) {
841			for (pri = bit; pri < RQB_BPW; pri++)
842				if (rqb->rqb_bits[i] & (1ul << pri))
843					break;
844			if (pri >= RQB_BPW)
845				continue;
846		} else
847			pri = RQB_FFS(rqb->rqb_bits[i]);
848		pri += (i << RQB_L2BPW);
849		rqh = &rq->rq_queues[pri];
850		TAILQ_FOREACH(ts, rqh, ts_procq) {
851			if (first && THREAD_CAN_MIGRATE(ts->ts_thread))
852				return (ts);
853			first = 1;
854		}
855	}
856	if (start != 0) {
857		start = 0;
858		goto again;
859	}
860
861	return (NULL);
862}
863
864/*
865 * Steals load from a standard linear queue.
866 */
867static struct td_sched *
868runq_steal(struct runq *rq)
869{
870	struct rqhead *rqh;
871	struct rqbits *rqb;
872	struct td_sched *ts;
873	int word;
874	int bit;
875
876	rqb = &rq->rq_status;
877	for (word = 0; word < RQB_LEN; word++) {
878		if (rqb->rqb_bits[word] == 0)
879			continue;
880		for (bit = 0; bit < RQB_BPW; bit++) {
881			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
882				continue;
883			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
884			TAILQ_FOREACH(ts, rqh, ts_procq)
885				if (THREAD_CAN_MIGRATE(ts->ts_thread))
886					return (ts);
887		}
888	}
889	return (NULL);
890}
891
892/*
893 * Attempt to steal a thread in priority order from a thread queue.
894 */
895static struct td_sched *
896tdq_steal(struct tdq *tdq, int stealidle)
897{
898	struct td_sched *ts;
899
900	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
901	if ((ts = runq_steal(&tdq->tdq_realtime)) != NULL)
902		return (ts);
903	if ((ts = runq_steal_from(&tdq->tdq_timeshare, tdq->tdq_ridx)) != NULL)
904		return (ts);
905	if (stealidle)
906		return (runq_steal(&tdq->tdq_idle));
907	return (NULL);
908}
909
910/*
911 * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
912 * current lock and returns with the assigned queue locked.  If this is
913 * via sched_switch() we leave the thread in a blocked state as an
914 * optimization.
915 */
916static inline struct tdq *
917sched_setcpu(struct td_sched *ts, int cpu, int flags)
918{
919	struct thread *td;
920	struct tdq *tdq;
921
922	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
923
924	tdq = TDQ_CPU(cpu);
925	td = ts->ts_thread;
926	ts->ts_cpu = cpu;
927
928	/* If the lock matches just return the queue. */
929	if (td->td_lock == TDQ_LOCKPTR(tdq))
930		return (tdq);
931#ifdef notyet
932	/*
933	 * If the thread isn't running its lockptr is a
934	 * turnstile or a sleepqueue.  We can just lock_set without
935	 * blocking.
936	 */
937	if (TD_CAN_RUN(td)) {
938		TDQ_LOCK(tdq);
939		thread_lock_set(td, TDQ_LOCKPTR(tdq));
940		return (tdq);
941	}
942#endif
943	/*
944	 * The hard case, migration, we need to block the thread first to
945	 * prevent order reversals with other cpus locks.
946	 */
947	thread_lock_block(td);
948	TDQ_LOCK(tdq);
949	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
950	return (tdq);
951}
952
953/*
954 * Find the thread queue running the lowest priority thread.
955 */
956static int
957tdq_lowestpri(void)
958{
959	struct tdq *tdq;
960	int lowpri;
961	int lowcpu;
962	int lowload;
963	int load;
964	int cpu;
965	int pri;
966
967	lowload = 0;
968	lowpri = lowcpu = 0;
969	for (cpu = 0; cpu <= mp_maxid; cpu++) {
970		if (CPU_ABSENT(cpu))
971			continue;
972		tdq = TDQ_CPU(cpu);
973		pri = tdq->tdq_lowpri;
974		load = TDQ_CPU(cpu)->tdq_load;
975		CTR4(KTR_ULE,
976		    "cpu %d pri %d lowcpu %d lowpri %d",
977		    cpu, pri, lowcpu, lowpri);
978		if (pri < lowpri)
979			continue;
980		if (lowpri && lowpri == pri && load > lowload)
981			continue;
982		lowpri = pri;
983		lowcpu = cpu;
984		lowload = load;
985	}
986
987	return (lowcpu);
988}
989
990/*
991 * Find the thread queue with the least load.
992 */
993static int
994tdq_lowestload(void)
995{
996	struct tdq *tdq;
997	int lowload;
998	int lowpri;
999	int lowcpu;
1000	int load;
1001	int cpu;
1002	int pri;
1003
1004	lowcpu = 0;
1005	lowload = TDQ_CPU(0)->tdq_load;
1006	lowpri = TDQ_CPU(0)->tdq_lowpri;
1007	for (cpu = 1; cpu <= mp_maxid; cpu++) {
1008		if (CPU_ABSENT(cpu))
1009			continue;
1010		tdq = TDQ_CPU(cpu);
1011		load = tdq->tdq_load;
1012		pri = tdq->tdq_lowpri;
1013		CTR4(KTR_ULE, "cpu %d load %d lowcpu %d lowload %d",
1014		    cpu, load, lowcpu, lowload);
1015		if (load > lowload)
1016			continue;
1017		if (load == lowload && pri < lowpri)
1018			continue;
1019		lowcpu = cpu;
1020		lowload = load;
1021		lowpri = pri;
1022	}
1023
1024	return (lowcpu);
1025}
1026
1027/*
1028 * Pick the destination cpu for sched_add().  Respects affinity and makes
1029 * a determination based on load or priority of available processors.
1030 */
1031static int
1032sched_pickcpu(struct td_sched *ts, int flags)
1033{
1034	struct tdq *tdq;
1035	int self;
1036	int pri;
1037	int cpu;
1038
1039	cpu = self = PCPU_GET(cpuid);
1040	if (smp_started == 0)
1041		return (self);
1042	/*
1043	 * Don't migrate a running thread from sched_switch().
1044	 */
1045	if (flags & SRQ_OURSELF) {
1046		CTR1(KTR_ULE, "YIELDING %d",
1047		    curthread->td_priority);
1048		return (self);
1049	}
1050	pri = ts->ts_thread->td_priority;
1051	cpu = ts->ts_cpu;
1052	/*
1053	 * Regardless of affinity, if the last cpu is idle send it there.
1054	 */
1055	tdq = TDQ_CPU(cpu);
1056	if (tdq->tdq_lowpri > PRI_MIN_IDLE) {
1057		CTR5(KTR_ULE,
1058		    "ts_cpu %d idle, ltick %d ticks %d pri %d curthread %d",
1059		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1060		    tdq->tdq_lowpri);
1061		return (ts->ts_cpu);
1062	}
1063	/*
1064	 * If we have affinity, try to place it on the cpu we last ran on.
1065	 */
1066	if (SCHED_AFFINITY(ts) && tdq->tdq_lowpri > pri) {
1067		CTR5(KTR_ULE,
1068		    "affinity for %d, ltick %d ticks %d pri %d curthread %d",
1069		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1070		    tdq->tdq_lowpri);
1071		return (ts->ts_cpu);
1072	}
1073	/*
1074	 * Look for an idle group.
1075	 */
1076	CTR1(KTR_ULE, "tdq_idle %X", tdq_idle);
1077	cpu = ffs(tdq_idle);
1078	if (cpu)
1079		return (--cpu);
1080	/*
1081	 * If there are no idle cores see if we can run the thread locally.  This may
1082	 * improve locality among sleepers and wakers when there is shared data.
1083	 */
1084	if (tryself && pri < curthread->td_priority) {
1085		CTR1(KTR_ULE, "tryself %d",
1086		    curthread->td_priority);
1087		return (self);
1088	}
1089	/*
1090 	 * Now search for the cpu running the lowest priority thread with
1091	 * the least load.
1092	 */
1093	if (pick_pri)
1094		cpu = tdq_lowestpri();
1095	else
1096		cpu = tdq_lowestload();
1097	return (cpu);
1098}
1099
1100#endif	/* SMP */
1101
1102/*
1103 * Pick the highest priority task we have and return it.
1104 */
1105static struct td_sched *
1106tdq_choose(struct tdq *tdq)
1107{
1108	struct td_sched *ts;
1109
1110	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1111	ts = runq_choose(&tdq->tdq_realtime);
1112	if (ts != NULL)
1113		return (ts);
1114	ts = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1115	if (ts != NULL) {
1116		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_TIMESHARE,
1117		    ("tdq_choose: Invalid priority on timeshare queue %d",
1118		    ts->ts_thread->td_priority));
1119		return (ts);
1120	}
1121
1122	ts = runq_choose(&tdq->tdq_idle);
1123	if (ts != NULL) {
1124		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_IDLE,
1125		    ("tdq_choose: Invalid priority on idle queue %d",
1126		    ts->ts_thread->td_priority));
1127		return (ts);
1128	}
1129
1130	return (NULL);
1131}
1132
1133/*
1134 * Initialize a thread queue.
1135 */
1136static void
1137tdq_setup(struct tdq *tdq)
1138{
1139
1140	if (bootverbose)
1141		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1142	runq_init(&tdq->tdq_realtime);
1143	runq_init(&tdq->tdq_timeshare);
1144	runq_init(&tdq->tdq_idle);
1145	tdq->tdq_load = 0;
1146}
1147
1148#ifdef SMP
1149static void
1150tdg_setup(struct tdq_group *tdg)
1151{
1152	if (bootverbose)
1153		printf("ULE: setup cpu group %d\n", TDG_ID(tdg));
1154	snprintf(tdg->tdg_name, sizeof(tdg->tdg_name),
1155	    "sched lock %d", (int)TDG_ID(tdg));
1156	mtx_init(&tdg->tdg_lock, tdg->tdg_name, "sched lock",
1157	    MTX_SPIN | MTX_RECURSE);
1158	LIST_INIT(&tdg->tdg_members);
1159	tdg->tdg_load = 0;
1160	tdg->tdg_transferable = 0;
1161	tdg->tdg_cpus = 0;
1162	tdg->tdg_mask = 0;
1163	tdg->tdg_cpumask = 0;
1164	tdg->tdg_idlemask = 0;
1165}
1166
1167static void
1168tdg_add(struct tdq_group *tdg, struct tdq *tdq)
1169{
1170	if (tdg->tdg_mask == 0)
1171		tdg->tdg_mask |= 1 << TDQ_ID(tdq);
1172	tdg->tdg_cpumask |= 1 << TDQ_ID(tdq);
1173	tdg->tdg_cpus++;
1174	tdq->tdq_group = tdg;
1175	tdq->tdq_lock = &tdg->tdg_lock;
1176	LIST_INSERT_HEAD(&tdg->tdg_members, tdq, tdq_siblings);
1177	if (bootverbose)
1178		printf("ULE: adding cpu %d to group %d: cpus %d mask 0x%X\n",
1179		    TDQ_ID(tdq), TDG_ID(tdg), tdg->tdg_cpus, tdg->tdg_cpumask);
1180}
1181
1182static void
1183sched_setup_topology(void)
1184{
1185	struct tdq_group *tdg;
1186	struct cpu_group *cg;
1187	int balance_groups;
1188	struct tdq *tdq;
1189	int i;
1190	int j;
1191
1192	topology = 1;
1193	balance_groups = 0;
1194	for (i = 0; i < smp_topology->ct_count; i++) {
1195		cg = &smp_topology->ct_group[i];
1196		tdg = &tdq_groups[i];
1197		/*
1198		 * Initialize the group.
1199		 */
1200		tdg_setup(tdg);
1201		/*
1202		 * Find all of the group members and add them.
1203		 */
1204		for (j = 0; j < MAXCPU; j++) {
1205			if ((cg->cg_mask & (1 << j)) != 0) {
1206				tdq = TDQ_CPU(j);
1207				tdq_setup(tdq);
1208				tdg_add(tdg, tdq);
1209			}
1210		}
1211		if (tdg->tdg_cpus > 1)
1212			balance_groups = 1;
1213	}
1214	tdg_maxid = smp_topology->ct_count - 1;
1215	if (balance_groups)
1216		sched_balance_groups(NULL);
1217}
1218
1219static void
1220sched_setup_smp(void)
1221{
1222	struct tdq_group *tdg;
1223	struct tdq *tdq;
1224	int cpus;
1225	int i;
1226
1227	for (cpus = 0, i = 0; i < MAXCPU; i++) {
1228		if (CPU_ABSENT(i))
1229			continue;
1230		tdq = &tdq_cpu[i];
1231		tdg = &tdq_groups[i];
1232		/*
1233		 * Setup a tdq group with one member.
1234		 */
1235		tdg_setup(tdg);
1236		tdq_setup(tdq);
1237		tdg_add(tdg, tdq);
1238		cpus++;
1239	}
1240	tdg_maxid = cpus - 1;
1241}
1242
1243/*
1244 * Fake a topology with one group containing all CPUs.
1245 */
1246static void
1247sched_fake_topo(void)
1248{
1249#ifdef SCHED_FAKE_TOPOLOGY
1250	static struct cpu_top top;
1251	static struct cpu_group group;
1252
1253	top.ct_count = 1;
1254	top.ct_group = &group;
1255	group.cg_mask = all_cpus;
1256	group.cg_count = mp_ncpus;
1257	group.cg_children = 0;
1258	smp_topology = &top;
1259#endif
1260}
1261#endif
1262
1263/*
1264 * Setup the thread queues and initialize the topology based on MD
1265 * information.
1266 */
1267static void
1268sched_setup(void *dummy)
1269{
1270	struct tdq *tdq;
1271
1272	tdq = TDQ_SELF();
1273#ifdef SMP
1274	/*
1275	 * Initialize long-term cpu balancing algorithm.
1276	 */
1277	callout_init(&balco, CALLOUT_MPSAFE);
1278	callout_init(&gbalco, CALLOUT_MPSAFE);
1279	sched_fake_topo();
1280	/*
1281	 * Setup tdqs based on a topology configuration or vanilla SMP based
1282	 * on mp_maxid.
1283	 */
1284	if (smp_topology == NULL)
1285		sched_setup_smp();
1286	else
1287		sched_setup_topology();
1288	sched_balance(NULL);
1289#else
1290	tdq_setup(tdq);
1291	mtx_init(&tdq_lock, "sched lock", "sched lock", MTX_SPIN | MTX_RECURSE);
1292	tdq->tdq_lock = &tdq_lock;
1293#endif
1294	/*
1295	 * To avoid divide-by-zero, we set realstathz a dummy value
1296	 * in case which sched_clock() called before sched_initticks().
1297	 */
1298	realstathz = hz;
1299	sched_slice = (realstathz/10);	/* ~100ms */
1300	tickincr = 1 << SCHED_TICK_SHIFT;
1301
1302	/* Add thread0's load since it's running. */
1303	TDQ_LOCK(tdq);
1304	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1305	tdq_load_add(tdq, &td_sched0);
1306	TDQ_UNLOCK(tdq);
1307}
1308
1309/*
1310 * This routine determines the tickincr after stathz and hz are setup.
1311 */
1312/* ARGSUSED */
1313static void
1314sched_initticks(void *dummy)
1315{
1316	int incr;
1317
1318	realstathz = stathz ? stathz : hz;
1319	sched_slice = (realstathz/10);	/* ~100ms */
1320
1321	/*
1322	 * tickincr is shifted out by 10 to avoid rounding errors due to
1323	 * hz not being evenly divisible by stathz on all platforms.
1324	 */
1325	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1326	/*
1327	 * This does not work for values of stathz that are more than
1328	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1329	 */
1330	if (incr == 0)
1331		incr = 1;
1332	tickincr = incr;
1333#ifdef SMP
1334	/*
1335	 * Set steal thresh to log2(mp_ncpu) but no greater than 4.  This
1336	 * prevents excess thrashing on large machines and excess idle on
1337	 * smaller machines.
1338	 */
1339	steal_thresh = min(ffs(mp_ncpus) - 1, 4);
1340	affinity = SCHED_AFFINITY_DEFAULT;
1341#endif
1342}
1343
1344
1345/*
1346 * This is the core of the interactivity algorithm.  Determines a score based
1347 * on past behavior.  It is the ratio of sleep time to run time scaled to
1348 * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1349 * differs from the cpu usage because it does not account for time spent
1350 * waiting on a run-queue.  Would be prettier if we had floating point.
1351 */
1352static int
1353sched_interact_score(struct thread *td)
1354{
1355	struct td_sched *ts;
1356	int div;
1357
1358	ts = td->td_sched;
1359	/*
1360	 * The score is only needed if this is likely to be an interactive
1361	 * task.  Don't go through the expense of computing it if there's
1362	 * no chance.
1363	 */
1364	if (sched_interact <= SCHED_INTERACT_HALF &&
1365		ts->ts_runtime >= ts->ts_slptime)
1366			return (SCHED_INTERACT_HALF);
1367
1368	if (ts->ts_runtime > ts->ts_slptime) {
1369		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1370		return (SCHED_INTERACT_HALF +
1371		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1372	}
1373	if (ts->ts_slptime > ts->ts_runtime) {
1374		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1375		return (ts->ts_runtime / div);
1376	}
1377	/* runtime == slptime */
1378	if (ts->ts_runtime)
1379		return (SCHED_INTERACT_HALF);
1380
1381	/*
1382	 * This can happen if slptime and runtime are 0.
1383	 */
1384	return (0);
1385
1386}
1387
1388/*
1389 * Scale the scheduling priority according to the "interactivity" of this
1390 * process.
1391 */
1392static void
1393sched_priority(struct thread *td)
1394{
1395	int score;
1396	int pri;
1397
1398	if (td->td_pri_class != PRI_TIMESHARE)
1399		return;
1400	/*
1401	 * If the score is interactive we place the thread in the realtime
1402	 * queue with a priority that is less than kernel and interrupt
1403	 * priorities.  These threads are not subject to nice restrictions.
1404	 *
1405	 * Scores greater than this are placed on the normal timeshare queue
1406	 * where the priority is partially decided by the most recent cpu
1407	 * utilization and the rest is decided by nice value.
1408	 *
1409	 * The nice value of the process has a linear effect on the calculated
1410	 * score.  Negative nice values make it easier for a thread to be
1411	 * considered interactive.
1412	 */
1413	score = imax(0, sched_interact_score(td) - td->td_proc->p_nice);
1414	if (score < sched_interact) {
1415		pri = PRI_MIN_REALTIME;
1416		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1417		    * score;
1418		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1419		    ("sched_priority: invalid interactive priority %d score %d",
1420		    pri, score));
1421	} else {
1422		pri = SCHED_PRI_MIN;
1423		if (td->td_sched->ts_ticks)
1424			pri += SCHED_PRI_TICKS(td->td_sched);
1425		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1426		KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1427		    ("sched_priority: invalid priority %d: nice %d, "
1428		    "ticks %d ftick %d ltick %d tick pri %d",
1429		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1430		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1431		    SCHED_PRI_TICKS(td->td_sched)));
1432	}
1433	sched_user_prio(td, pri);
1434
1435	return;
1436}
1437
1438/*
1439 * This routine enforces a maximum limit on the amount of scheduling history
1440 * kept.  It is called after either the slptime or runtime is adjusted.  This
1441 * function is ugly due to integer math.
1442 */
1443static void
1444sched_interact_update(struct thread *td)
1445{
1446	struct td_sched *ts;
1447	u_int sum;
1448
1449	ts = td->td_sched;
1450	sum = ts->ts_runtime + ts->ts_slptime;
1451	if (sum < SCHED_SLP_RUN_MAX)
1452		return;
1453	/*
1454	 * This only happens from two places:
1455	 * 1) We have added an unusual amount of run time from fork_exit.
1456	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1457	 */
1458	if (sum > SCHED_SLP_RUN_MAX * 2) {
1459		if (ts->ts_runtime > ts->ts_slptime) {
1460			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1461			ts->ts_slptime = 1;
1462		} else {
1463			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1464			ts->ts_runtime = 1;
1465		}
1466		return;
1467	}
1468	/*
1469	 * If we have exceeded by more than 1/5th then the algorithm below
1470	 * will not bring us back into range.  Dividing by two here forces
1471	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1472	 */
1473	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1474		ts->ts_runtime /= 2;
1475		ts->ts_slptime /= 2;
1476		return;
1477	}
1478	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1479	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1480}
1481
1482/*
1483 * Scale back the interactivity history when a child thread is created.  The
1484 * history is inherited from the parent but the thread may behave totally
1485 * differently.  For example, a shell spawning a compiler process.  We want
1486 * to learn that the compiler is behaving badly very quickly.
1487 */
1488static void
1489sched_interact_fork(struct thread *td)
1490{
1491	int ratio;
1492	int sum;
1493
1494	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1495	if (sum > SCHED_SLP_RUN_FORK) {
1496		ratio = sum / SCHED_SLP_RUN_FORK;
1497		td->td_sched->ts_runtime /= ratio;
1498		td->td_sched->ts_slptime /= ratio;
1499	}
1500}
1501
1502/*
1503 * Called from proc0_init() to setup the scheduler fields.
1504 */
1505void
1506schedinit(void)
1507{
1508
1509	/*
1510	 * Set up the scheduler specific parts of proc0.
1511	 */
1512	proc0.p_sched = NULL; /* XXX */
1513	thread0.td_sched = &td_sched0;
1514	td_sched0.ts_ltick = ticks;
1515	td_sched0.ts_ftick = ticks;
1516	td_sched0.ts_thread = &thread0;
1517}
1518
1519/*
1520 * This is only somewhat accurate since given many processes of the same
1521 * priority they will switch when their slices run out, which will be
1522 * at most sched_slice stathz ticks.
1523 */
1524int
1525sched_rr_interval(void)
1526{
1527
1528	/* Convert sched_slice to hz */
1529	return (hz/(realstathz/sched_slice));
1530}
1531
1532/*
1533 * Update the percent cpu tracking information when it is requested or
1534 * the total history exceeds the maximum.  We keep a sliding history of
1535 * tick counts that slowly decays.  This is less precise than the 4BSD
1536 * mechanism since it happens with less regular and frequent events.
1537 */
1538static void
1539sched_pctcpu_update(struct td_sched *ts)
1540{
1541
1542	if (ts->ts_ticks == 0)
1543		return;
1544	if (ticks - (hz / 10) < ts->ts_ltick &&
1545	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1546		return;
1547	/*
1548	 * Adjust counters and watermark for pctcpu calc.
1549	 */
1550	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1551		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1552			    SCHED_TICK_TARG;
1553	else
1554		ts->ts_ticks = 0;
1555	ts->ts_ltick = ticks;
1556	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1557}
1558
1559/*
1560 * Adjust the priority of a thread.  Move it to the appropriate run-queue
1561 * if necessary.  This is the back-end for several priority related
1562 * functions.
1563 */
1564static void
1565sched_thread_priority(struct thread *td, u_char prio)
1566{
1567	struct td_sched *ts;
1568
1569	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
1570	    td, td->td_proc->p_comm, td->td_priority, prio, curthread,
1571	    curthread->td_proc->p_comm);
1572	ts = td->td_sched;
1573	THREAD_LOCK_ASSERT(td, MA_OWNED);
1574	if (td->td_priority == prio)
1575		return;
1576
1577	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1578		/*
1579		 * If the priority has been elevated due to priority
1580		 * propagation, we may have to move ourselves to a new
1581		 * queue.  This could be optimized to not re-add in some
1582		 * cases.
1583		 */
1584		sched_rem(td);
1585		td->td_priority = prio;
1586		sched_add(td, SRQ_BORROWING);
1587	} else {
1588#ifdef SMP
1589		struct tdq *tdq;
1590
1591		tdq = TDQ_CPU(ts->ts_cpu);
1592		if (prio < tdq->tdq_lowpri)
1593			tdq->tdq_lowpri = prio;
1594#endif
1595		td->td_priority = prio;
1596	}
1597}
1598
1599/*
1600 * Update a thread's priority when it is lent another thread's
1601 * priority.
1602 */
1603void
1604sched_lend_prio(struct thread *td, u_char prio)
1605{
1606
1607	td->td_flags |= TDF_BORROWING;
1608	sched_thread_priority(td, prio);
1609}
1610
1611/*
1612 * Restore a thread's priority when priority propagation is
1613 * over.  The prio argument is the minimum priority the thread
1614 * needs to have to satisfy other possible priority lending
1615 * requests.  If the thread's regular priority is less
1616 * important than prio, the thread will keep a priority boost
1617 * of prio.
1618 */
1619void
1620sched_unlend_prio(struct thread *td, u_char prio)
1621{
1622	u_char base_pri;
1623
1624	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1625	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1626		base_pri = td->td_user_pri;
1627	else
1628		base_pri = td->td_base_pri;
1629	if (prio >= base_pri) {
1630		td->td_flags &= ~TDF_BORROWING;
1631		sched_thread_priority(td, base_pri);
1632	} else
1633		sched_lend_prio(td, prio);
1634}
1635
1636/*
1637 * Standard entry for setting the priority to an absolute value.
1638 */
1639void
1640sched_prio(struct thread *td, u_char prio)
1641{
1642	u_char oldprio;
1643
1644	/* First, update the base priority. */
1645	td->td_base_pri = prio;
1646
1647	/*
1648	 * If the thread is borrowing another thread's priority, don't
1649	 * ever lower the priority.
1650	 */
1651	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1652		return;
1653
1654	/* Change the real priority. */
1655	oldprio = td->td_priority;
1656	sched_thread_priority(td, prio);
1657
1658	/*
1659	 * If the thread is on a turnstile, then let the turnstile update
1660	 * its state.
1661	 */
1662	if (TD_ON_LOCK(td) && oldprio != prio)
1663		turnstile_adjust(td, oldprio);
1664}
1665
1666/*
1667 * Set the base user priority, does not effect current running priority.
1668 */
1669void
1670sched_user_prio(struct thread *td, u_char prio)
1671{
1672	u_char oldprio;
1673
1674	td->td_base_user_pri = prio;
1675	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1676                return;
1677	oldprio = td->td_user_pri;
1678	td->td_user_pri = prio;
1679
1680	if (TD_ON_UPILOCK(td) && oldprio != prio)
1681		umtx_pi_adjust(td, oldprio);
1682}
1683
1684void
1685sched_lend_user_prio(struct thread *td, u_char prio)
1686{
1687	u_char oldprio;
1688
1689	td->td_flags |= TDF_UBORROWING;
1690
1691	oldprio = td->td_user_pri;
1692	td->td_user_pri = prio;
1693
1694	if (TD_ON_UPILOCK(td) && oldprio != prio)
1695		umtx_pi_adjust(td, oldprio);
1696}
1697
1698void
1699sched_unlend_user_prio(struct thread *td, u_char prio)
1700{
1701	u_char base_pri;
1702
1703	base_pri = td->td_base_user_pri;
1704	if (prio >= base_pri) {
1705		td->td_flags &= ~TDF_UBORROWING;
1706		sched_user_prio(td, base_pri);
1707	} else
1708		sched_lend_user_prio(td, prio);
1709}
1710
1711/*
1712 * Add the thread passed as 'newtd' to the run queue before selecting
1713 * the next thread to run.  This is only used for KSE.
1714 */
1715static void
1716sched_switchin(struct tdq *tdq, struct thread *td)
1717{
1718#ifdef SMP
1719	spinlock_enter();
1720	TDQ_UNLOCK(tdq);
1721	thread_lock(td);
1722	spinlock_exit();
1723	sched_setcpu(td->td_sched, TDQ_ID(tdq), SRQ_YIELDING);
1724#else
1725	td->td_lock = TDQ_LOCKPTR(tdq);
1726#endif
1727	tdq_add(tdq, td, SRQ_YIELDING);
1728	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1729}
1730
1731/*
1732 * Handle migration from sched_switch().  This happens only for
1733 * cpu binding.
1734 */
1735static struct mtx *
1736sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1737{
1738	struct tdq *tdn;
1739
1740	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1741#ifdef SMP
1742	/*
1743	 * Do the lock dance required to avoid LOR.  We grab an extra
1744	 * spinlock nesting to prevent preemption while we're
1745	 * not holding either run-queue lock.
1746	 */
1747	spinlock_enter();
1748	thread_block_switch(td);	/* This releases the lock on tdq. */
1749	TDQ_LOCK(tdn);
1750	tdq_add(tdn, td, flags);
1751	tdq_notify(td->td_sched);
1752	/*
1753	 * After we unlock tdn the new cpu still can't switch into this
1754	 * thread until we've unblocked it in cpu_switch().  The lock
1755	 * pointers may match in the case of HTT cores.  Don't unlock here
1756	 * or we can deadlock when the other CPU runs the IPI handler.
1757	 */
1758	if (TDQ_LOCKPTR(tdn) != TDQ_LOCKPTR(tdq)) {
1759		TDQ_UNLOCK(tdn);
1760		TDQ_LOCK(tdq);
1761	}
1762	spinlock_exit();
1763#endif
1764	return (TDQ_LOCKPTR(tdn));
1765}
1766
1767/*
1768 * Block a thread for switching.  Similar to thread_block() but does not
1769 * bump the spin count.
1770 */
1771static inline struct mtx *
1772thread_block_switch(struct thread *td)
1773{
1774	struct mtx *lock;
1775
1776	THREAD_LOCK_ASSERT(td, MA_OWNED);
1777	lock = td->td_lock;
1778	td->td_lock = &blocked_lock;
1779	mtx_unlock_spin(lock);
1780
1781	return (lock);
1782}
1783
1784/*
1785 * Release a thread that was blocked with thread_block_switch().
1786 */
1787static inline void
1788thread_unblock_switch(struct thread *td, struct mtx *mtx)
1789{
1790	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1791	    (uintptr_t)mtx);
1792}
1793
1794/*
1795 * Switch threads.  This function has to handle threads coming in while
1796 * blocked for some reason, running, or idle.  It also must deal with
1797 * migrating a thread from one queue to another as running threads may
1798 * be assigned elsewhere via binding.
1799 */
1800void
1801sched_switch(struct thread *td, struct thread *newtd, int flags)
1802{
1803	struct tdq *tdq;
1804	struct td_sched *ts;
1805	struct mtx *mtx;
1806	int srqflag;
1807	int cpuid;
1808
1809	THREAD_LOCK_ASSERT(td, MA_OWNED);
1810
1811	cpuid = PCPU_GET(cpuid);
1812	tdq = TDQ_CPU(cpuid);
1813	ts = td->td_sched;
1814	mtx = td->td_lock;
1815#ifdef SMP
1816	ts->ts_rltick = ticks;
1817	if (newtd && newtd->td_priority < tdq->tdq_lowpri)
1818		tdq->tdq_lowpri = newtd->td_priority;
1819#endif
1820	td->td_lastcpu = td->td_oncpu;
1821	td->td_oncpu = NOCPU;
1822	td->td_flags &= ~TDF_NEEDRESCHED;
1823	td->td_owepreempt = 0;
1824	/*
1825	 * The lock pointer in an idle thread should never change.  Reset it
1826	 * to CAN_RUN as well.
1827	 */
1828	if (TD_IS_IDLETHREAD(td)) {
1829		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1830		TD_SET_CAN_RUN(td);
1831	} else if (TD_IS_RUNNING(td)) {
1832		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1833		tdq_load_rem(tdq, ts);
1834		srqflag = (flags & SW_PREEMPT) ?
1835		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1836		    SRQ_OURSELF|SRQ_YIELDING;
1837		if (ts->ts_cpu == cpuid)
1838			tdq_add(tdq, td, srqflag);
1839		else
1840			mtx = sched_switch_migrate(tdq, td, srqflag);
1841	} else {
1842		/* This thread must be going to sleep. */
1843		TDQ_LOCK(tdq);
1844		mtx = thread_block_switch(td);
1845		tdq_load_rem(tdq, ts);
1846	}
1847	/*
1848	 * We enter here with the thread blocked and assigned to the
1849	 * appropriate cpu run-queue or sleep-queue and with the current
1850	 * thread-queue locked.
1851	 */
1852	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1853	/*
1854	 * If KSE assigned a new thread just add it here and let choosethread
1855	 * select the best one.
1856	 */
1857	if (newtd != NULL)
1858		sched_switchin(tdq, newtd);
1859	newtd = choosethread();
1860	/*
1861	 * Call the MD code to switch contexts if necessary.
1862	 */
1863	if (td != newtd) {
1864#ifdef	HWPMC_HOOKS
1865		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1866			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1867#endif
1868		cpu_switch(td, newtd, mtx);
1869		/*
1870		 * We may return from cpu_switch on a different cpu.  However,
1871		 * we always return with td_lock pointing to the current cpu's
1872		 * run queue lock.
1873		 */
1874		cpuid = PCPU_GET(cpuid);
1875		tdq = TDQ_CPU(cpuid);
1876		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)td;
1877#ifdef	HWPMC_HOOKS
1878		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1879			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1880#endif
1881	} else
1882		thread_unblock_switch(td, mtx);
1883	/*
1884	 * Assert that all went well and return.
1885	 */
1886#ifdef SMP
1887	/* We should always get here with the lowest priority td possible */
1888	tdq->tdq_lowpri = td->td_priority;
1889#endif
1890	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1891	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1892	td->td_oncpu = cpuid;
1893}
1894
1895/*
1896 * Adjust thread priorities as a result of a nice request.
1897 */
1898void
1899sched_nice(struct proc *p, int nice)
1900{
1901	struct thread *td;
1902
1903	PROC_LOCK_ASSERT(p, MA_OWNED);
1904	PROC_SLOCK_ASSERT(p, MA_OWNED);
1905
1906	p->p_nice = nice;
1907	FOREACH_THREAD_IN_PROC(p, td) {
1908		thread_lock(td);
1909		sched_priority(td);
1910		sched_prio(td, td->td_base_user_pri);
1911		thread_unlock(td);
1912	}
1913}
1914
1915/*
1916 * Record the sleep time for the interactivity scorer.
1917 */
1918void
1919sched_sleep(struct thread *td)
1920{
1921
1922	THREAD_LOCK_ASSERT(td, MA_OWNED);
1923
1924	td->td_slptick = ticks;
1925}
1926
1927/*
1928 * Schedule a thread to resume execution and record how long it voluntarily
1929 * slept.  We also update the pctcpu, interactivity, and priority.
1930 */
1931void
1932sched_wakeup(struct thread *td)
1933{
1934	struct td_sched *ts;
1935	int slptick;
1936
1937	THREAD_LOCK_ASSERT(td, MA_OWNED);
1938	ts = td->td_sched;
1939	/*
1940	 * If we slept for more than a tick update our interactivity and
1941	 * priority.
1942	 */
1943	slptick = td->td_slptick;
1944	td->td_slptick = 0;
1945	if (slptick && slptick != ticks) {
1946		u_int hzticks;
1947
1948		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1949		ts->ts_slptime += hzticks;
1950		sched_interact_update(td);
1951		sched_pctcpu_update(ts);
1952		sched_priority(td);
1953	}
1954	/* Reset the slice value after we sleep. */
1955	ts->ts_slice = sched_slice;
1956	sched_add(td, SRQ_BORING);
1957}
1958
1959/*
1960 * Penalize the parent for creating a new child and initialize the child's
1961 * priority.
1962 */
1963void
1964sched_fork(struct thread *td, struct thread *child)
1965{
1966	THREAD_LOCK_ASSERT(td, MA_OWNED);
1967	sched_fork_thread(td, child);
1968	/*
1969	 * Penalize the parent and child for forking.
1970	 */
1971	sched_interact_fork(child);
1972	sched_priority(child);
1973	td->td_sched->ts_runtime += tickincr;
1974	sched_interact_update(td);
1975	sched_priority(td);
1976}
1977
1978/*
1979 * Fork a new thread, may be within the same process.
1980 */
1981void
1982sched_fork_thread(struct thread *td, struct thread *child)
1983{
1984	struct td_sched *ts;
1985	struct td_sched *ts2;
1986
1987	/*
1988	 * Initialize child.
1989	 */
1990	THREAD_LOCK_ASSERT(td, MA_OWNED);
1991	sched_newthread(child);
1992	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1993	ts = td->td_sched;
1994	ts2 = child->td_sched;
1995	ts2->ts_cpu = ts->ts_cpu;
1996	ts2->ts_runq = NULL;
1997	/*
1998	 * Grab our parents cpu estimation information and priority.
1999	 */
2000	ts2->ts_ticks = ts->ts_ticks;
2001	ts2->ts_ltick = ts->ts_ltick;
2002	ts2->ts_ftick = ts->ts_ftick;
2003	child->td_user_pri = td->td_user_pri;
2004	child->td_base_user_pri = td->td_base_user_pri;
2005	/*
2006	 * And update interactivity score.
2007	 */
2008	ts2->ts_slptime = ts->ts_slptime;
2009	ts2->ts_runtime = ts->ts_runtime;
2010	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
2011}
2012
2013/*
2014 * Adjust the priority class of a thread.
2015 */
2016void
2017sched_class(struct thread *td, int class)
2018{
2019
2020	THREAD_LOCK_ASSERT(td, MA_OWNED);
2021	if (td->td_pri_class == class)
2022		return;
2023
2024#ifdef SMP
2025	/*
2026	 * On SMP if we're on the RUNQ we must adjust the transferable
2027	 * count because could be changing to or from an interrupt
2028	 * class.
2029	 */
2030	if (TD_ON_RUNQ(td)) {
2031		struct tdq *tdq;
2032
2033		tdq = TDQ_CPU(td->td_sched->ts_cpu);
2034		if (THREAD_CAN_MIGRATE(td)) {
2035			tdq->tdq_transferable--;
2036			tdq->tdq_group->tdg_transferable--;
2037		}
2038		td->td_pri_class = class;
2039		if (THREAD_CAN_MIGRATE(td)) {
2040			tdq->tdq_transferable++;
2041			tdq->tdq_group->tdg_transferable++;
2042		}
2043	}
2044#endif
2045	td->td_pri_class = class;
2046}
2047
2048/*
2049 * Return some of the child's priority and interactivity to the parent.
2050 */
2051void
2052sched_exit(struct proc *p, struct thread *child)
2053{
2054	struct thread *td;
2055
2056	CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
2057	    child, child->td_proc->p_comm, child->td_priority);
2058
2059	PROC_SLOCK_ASSERT(p, MA_OWNED);
2060	td = FIRST_THREAD_IN_PROC(p);
2061	sched_exit_thread(td, child);
2062}
2063
2064/*
2065 * Penalize another thread for the time spent on this one.  This helps to
2066 * worsen the priority and interactivity of processes which schedule batch
2067 * jobs such as make.  This has little effect on the make process itself but
2068 * causes new processes spawned by it to receive worse scores immediately.
2069 */
2070void
2071sched_exit_thread(struct thread *td, struct thread *child)
2072{
2073
2074	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
2075	    child, child->td_proc->p_comm, child->td_priority);
2076
2077#ifdef KSE
2078	/*
2079	 * KSE forks and exits so often that this penalty causes short-lived
2080	 * threads to always be non-interactive.  This causes mozilla to
2081	 * crawl under load.
2082	 */
2083	if ((td->td_pflags & TDP_SA) && td->td_proc == child->td_proc)
2084		return;
2085#endif
2086	/*
2087	 * Give the child's runtime to the parent without returning the
2088	 * sleep time as a penalty to the parent.  This causes shells that
2089	 * launch expensive things to mark their children as expensive.
2090	 */
2091	thread_lock(td);
2092	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2093	sched_interact_update(td);
2094	sched_priority(td);
2095	thread_unlock(td);
2096}
2097
2098/*
2099 * Fix priorities on return to user-space.  Priorities may be elevated due
2100 * to static priorities in msleep() or similar.
2101 */
2102void
2103sched_userret(struct thread *td)
2104{
2105	/*
2106	 * XXX we cheat slightly on the locking here to avoid locking in
2107	 * the usual case.  Setting td_priority here is essentially an
2108	 * incomplete workaround for not setting it properly elsewhere.
2109	 * Now that some interrupt handlers are threads, not setting it
2110	 * properly elsewhere can clobber it in the window between setting
2111	 * it here and returning to user mode, so don't waste time setting
2112	 * it perfectly here.
2113	 */
2114	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2115	    ("thread with borrowed priority returning to userland"));
2116	if (td->td_priority != td->td_user_pri) {
2117		thread_lock(td);
2118		td->td_priority = td->td_user_pri;
2119		td->td_base_pri = td->td_user_pri;
2120		thread_unlock(td);
2121        }
2122}
2123
2124/*
2125 * Handle a stathz tick.  This is really only relevant for timeshare
2126 * threads.
2127 */
2128void
2129sched_clock(struct thread *td)
2130{
2131	struct tdq *tdq;
2132	struct td_sched *ts;
2133
2134	THREAD_LOCK_ASSERT(td, MA_OWNED);
2135	tdq = TDQ_SELF();
2136	/*
2137	 * Advance the insert index once for each tick to ensure that all
2138	 * threads get a chance to run.
2139	 */
2140	if (tdq->tdq_idx == tdq->tdq_ridx) {
2141		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2142		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2143			tdq->tdq_ridx = tdq->tdq_idx;
2144	}
2145	ts = td->td_sched;
2146	/*
2147	 * We only do slicing code for TIMESHARE threads.
2148	 */
2149	if (td->td_pri_class != PRI_TIMESHARE)
2150		return;
2151	/*
2152	 * We used a tick; charge it to the thread so that we can compute our
2153	 * interactivity.
2154	 */
2155	td->td_sched->ts_runtime += tickincr;
2156	sched_interact_update(td);
2157	/*
2158	 * We used up one time slice.
2159	 */
2160	if (--ts->ts_slice > 0)
2161		return;
2162	/*
2163	 * We're out of time, recompute priorities and requeue.
2164	 */
2165	sched_priority(td);
2166	td->td_flags |= TDF_NEEDRESCHED;
2167}
2168
2169/*
2170 * Called once per hz tick.  Used for cpu utilization information.  This
2171 * is easier than trying to scale based on stathz.
2172 */
2173void
2174sched_tick(void)
2175{
2176	struct td_sched *ts;
2177
2178	ts = curthread->td_sched;
2179	/* Adjust ticks for pctcpu */
2180	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2181	ts->ts_ltick = ticks;
2182	/*
2183	 * Update if we've exceeded our desired tick threshhold by over one
2184	 * second.
2185	 */
2186	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2187		sched_pctcpu_update(ts);
2188}
2189
2190/*
2191 * Return whether the current CPU has runnable tasks.  Used for in-kernel
2192 * cooperative idle threads.
2193 */
2194int
2195sched_runnable(void)
2196{
2197	struct tdq *tdq;
2198	int load;
2199
2200	load = 1;
2201
2202	tdq = TDQ_SELF();
2203	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2204		if (tdq->tdq_load > 0)
2205			goto out;
2206	} else
2207		if (tdq->tdq_load - 1 > 0)
2208			goto out;
2209	load = 0;
2210out:
2211	return (load);
2212}
2213
2214/*
2215 * Choose the highest priority thread to run.  The thread is removed from
2216 * the run-queue while running however the load remains.  For SMP we set
2217 * the tdq in the global idle bitmask if it idles here.
2218 */
2219struct thread *
2220sched_choose(void)
2221{
2222#ifdef SMP
2223	struct tdq_group *tdg;
2224#endif
2225	struct td_sched *ts;
2226	struct tdq *tdq;
2227
2228	tdq = TDQ_SELF();
2229	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2230	ts = tdq_choose(tdq);
2231	if (ts) {
2232		tdq_runq_rem(tdq, ts);
2233		return (ts->ts_thread);
2234	}
2235#ifdef SMP
2236	/*
2237	 * We only set the idled bit when all of the cpus in the group are
2238	 * idle.  Otherwise we could get into a situation where a thread bounces
2239	 * back and forth between two idle cores on seperate physical CPUs.
2240	 */
2241	tdg = tdq->tdq_group;
2242	tdg->tdg_idlemask |= PCPU_GET(cpumask);
2243	if (tdg->tdg_idlemask == tdg->tdg_cpumask)
2244		atomic_set_int(&tdq_idle, tdg->tdg_mask);
2245	tdq->tdq_lowpri = PRI_MAX_IDLE;
2246#endif
2247	return (PCPU_GET(idlethread));
2248}
2249
2250/*
2251 * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2252 * we always request it once we exit a critical section.
2253 */
2254static inline void
2255sched_setpreempt(struct thread *td)
2256{
2257	struct thread *ctd;
2258	int cpri;
2259	int pri;
2260
2261	ctd = curthread;
2262	pri = td->td_priority;
2263	cpri = ctd->td_priority;
2264	if (td->td_priority < ctd->td_priority)
2265		curthread->td_flags |= TDF_NEEDRESCHED;
2266	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2267		return;
2268	/*
2269	 * Always preempt IDLE threads.  Otherwise only if the preempting
2270	 * thread is an ithread.
2271	 */
2272	if (pri > preempt_thresh && cpri < PRI_MIN_IDLE)
2273		return;
2274	ctd->td_owepreempt = 1;
2275	return;
2276}
2277
2278/*
2279 * Add a thread to a thread queue.  Initializes priority, slice, runq, and
2280 * add it to the appropriate queue.  This is the internal function called
2281 * when the tdq is predetermined.
2282 */
2283void
2284tdq_add(struct tdq *tdq, struct thread *td, int flags)
2285{
2286	struct td_sched *ts;
2287	int class;
2288#ifdef SMP
2289	int cpumask;
2290#endif
2291
2292	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2293	KASSERT((td->td_inhibitors == 0),
2294	    ("sched_add: trying to run inhibited thread"));
2295	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2296	    ("sched_add: bad thread state"));
2297	KASSERT(td->td_flags & TDF_INMEM,
2298	    ("sched_add: thread swapped out"));
2299
2300	ts = td->td_sched;
2301	class = PRI_BASE(td->td_pri_class);
2302        TD_SET_RUNQ(td);
2303	if (ts->ts_slice == 0)
2304		ts->ts_slice = sched_slice;
2305	/*
2306	 * Pick the run queue based on priority.
2307	 */
2308	if (td->td_priority <= PRI_MAX_REALTIME)
2309		ts->ts_runq = &tdq->tdq_realtime;
2310	else if (td->td_priority <= PRI_MAX_TIMESHARE)
2311		ts->ts_runq = &tdq->tdq_timeshare;
2312	else
2313		ts->ts_runq = &tdq->tdq_idle;
2314#ifdef SMP
2315	cpumask = 1 << ts->ts_cpu;
2316	/*
2317	 * If we had been idle, clear our bit in the group and potentially
2318	 * the global bitmap.
2319	 */
2320	if ((class != PRI_IDLE && class != PRI_ITHD) &&
2321	    (tdq->tdq_group->tdg_idlemask & cpumask) != 0) {
2322		/*
2323		 * Check to see if our group is unidling, and if so, remove it
2324		 * from the global idle mask.
2325		 */
2326		if (tdq->tdq_group->tdg_idlemask ==
2327		    tdq->tdq_group->tdg_cpumask)
2328			atomic_clear_int(&tdq_idle, tdq->tdq_group->tdg_mask);
2329		/*
2330		 * Now remove ourselves from the group specific idle mask.
2331		 */
2332		tdq->tdq_group->tdg_idlemask &= ~cpumask;
2333	}
2334	if (td->td_priority < tdq->tdq_lowpri)
2335		tdq->tdq_lowpri = td->td_priority;
2336#endif
2337	tdq_runq_add(tdq, ts, flags);
2338	tdq_load_add(tdq, ts);
2339}
2340
2341/*
2342 * Select the target thread queue and add a thread to it.  Request
2343 * preemption or IPI a remote processor if required.
2344 */
2345void
2346sched_add(struct thread *td, int flags)
2347{
2348	struct td_sched *ts;
2349	struct tdq *tdq;
2350#ifdef SMP
2351	int cpuid;
2352	int cpu;
2353#endif
2354	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
2355	    td, td->td_proc->p_comm, td->td_priority, curthread,
2356	    curthread->td_proc->p_comm);
2357	THREAD_LOCK_ASSERT(td, MA_OWNED);
2358	ts = td->td_sched;
2359	/*
2360	 * Recalculate the priority before we select the target cpu or
2361	 * run-queue.
2362	 */
2363	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2364		sched_priority(td);
2365#ifdef SMP
2366	cpuid = PCPU_GET(cpuid);
2367	/*
2368	 * Pick the destination cpu and if it isn't ours transfer to the
2369	 * target cpu.
2370	 */
2371	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_MIGRATE(td))
2372		cpu = cpuid;
2373	else if (!THREAD_CAN_MIGRATE(td))
2374		cpu = ts->ts_cpu;
2375	else
2376		cpu = sched_pickcpu(ts, flags);
2377	tdq = sched_setcpu(ts, cpu, flags);
2378	tdq_add(tdq, td, flags);
2379	if (cpu != cpuid) {
2380		tdq_notify(ts);
2381		return;
2382	}
2383#else
2384	tdq = TDQ_SELF();
2385	TDQ_LOCK(tdq);
2386	/*
2387	 * Now that the thread is moving to the run-queue, set the lock
2388	 * to the scheduler's lock.
2389	 */
2390	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2391	tdq_add(tdq, td, flags);
2392#endif
2393	if (!(flags & SRQ_YIELDING))
2394		sched_setpreempt(td);
2395}
2396
2397/*
2398 * Remove a thread from a run-queue without running it.  This is used
2399 * when we're stealing a thread from a remote queue.  Otherwise all threads
2400 * exit by calling sched_exit_thread() and sched_throw() themselves.
2401 */
2402void
2403sched_rem(struct thread *td)
2404{
2405	struct tdq *tdq;
2406	struct td_sched *ts;
2407
2408	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
2409	    td, td->td_proc->p_comm, td->td_priority, curthread,
2410	    curthread->td_proc->p_comm);
2411	ts = td->td_sched;
2412	tdq = TDQ_CPU(ts->ts_cpu);
2413	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2414	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2415	KASSERT(TD_ON_RUNQ(td),
2416	    ("sched_rem: thread not on run queue"));
2417	tdq_runq_rem(tdq, ts);
2418	tdq_load_rem(tdq, ts);
2419	TD_SET_CAN_RUN(td);
2420}
2421
2422/*
2423 * Fetch cpu utilization information.  Updates on demand.
2424 */
2425fixpt_t
2426sched_pctcpu(struct thread *td)
2427{
2428	fixpt_t pctcpu;
2429	struct td_sched *ts;
2430
2431	pctcpu = 0;
2432	ts = td->td_sched;
2433	if (ts == NULL)
2434		return (0);
2435
2436	thread_lock(td);
2437	if (ts->ts_ticks) {
2438		int rtick;
2439
2440		sched_pctcpu_update(ts);
2441		/* How many rtick per second ? */
2442		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2443		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2444	}
2445	thread_unlock(td);
2446
2447	return (pctcpu);
2448}
2449
2450/*
2451 * Bind a thread to a target cpu.
2452 */
2453void
2454sched_bind(struct thread *td, int cpu)
2455{
2456	struct td_sched *ts;
2457
2458	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2459	ts = td->td_sched;
2460	if (ts->ts_flags & TSF_BOUND)
2461		sched_unbind(td);
2462	ts->ts_flags |= TSF_BOUND;
2463#ifdef SMP
2464	sched_pin();
2465	if (PCPU_GET(cpuid) == cpu)
2466		return;
2467	ts->ts_cpu = cpu;
2468	/* When we return from mi_switch we'll be on the correct cpu. */
2469	mi_switch(SW_VOL, NULL);
2470#endif
2471}
2472
2473/*
2474 * Release a bound thread.
2475 */
2476void
2477sched_unbind(struct thread *td)
2478{
2479	struct td_sched *ts;
2480
2481	THREAD_LOCK_ASSERT(td, MA_OWNED);
2482	ts = td->td_sched;
2483	if ((ts->ts_flags & TSF_BOUND) == 0)
2484		return;
2485	ts->ts_flags &= ~TSF_BOUND;
2486#ifdef SMP
2487	sched_unpin();
2488#endif
2489}
2490
2491int
2492sched_is_bound(struct thread *td)
2493{
2494	THREAD_LOCK_ASSERT(td, MA_OWNED);
2495	return (td->td_sched->ts_flags & TSF_BOUND);
2496}
2497
2498/*
2499 * Basic yield call.
2500 */
2501void
2502sched_relinquish(struct thread *td)
2503{
2504	thread_lock(td);
2505	if (td->td_pri_class == PRI_TIMESHARE)
2506		sched_prio(td, PRI_MAX_TIMESHARE);
2507	SCHED_STAT_INC(switch_relinquish);
2508	mi_switch(SW_VOL, NULL);
2509	thread_unlock(td);
2510}
2511
2512/*
2513 * Return the total system load.
2514 */
2515int
2516sched_load(void)
2517{
2518#ifdef SMP
2519	int total;
2520	int i;
2521
2522	total = 0;
2523	for (i = 0; i <= tdg_maxid; i++)
2524		total += TDQ_GROUP(i)->tdg_load;
2525	return (total);
2526#else
2527	return (TDQ_SELF()->tdq_sysload);
2528#endif
2529}
2530
2531int
2532sched_sizeof_proc(void)
2533{
2534	return (sizeof(struct proc));
2535}
2536
2537int
2538sched_sizeof_thread(void)
2539{
2540	return (sizeof(struct thread) + sizeof(struct td_sched));
2541}
2542
2543/*
2544 * The actual idle process.
2545 */
2546void
2547sched_idletd(void *dummy)
2548{
2549	struct thread *td;
2550	struct tdq *tdq;
2551
2552	td = curthread;
2553	tdq = TDQ_SELF();
2554	mtx_assert(&Giant, MA_NOTOWNED);
2555	/* ULE relies on preemption for idle interruption. */
2556	for (;;) {
2557#ifdef SMP
2558		if (tdq_idled(tdq))
2559			cpu_idle();
2560#else
2561		cpu_idle();
2562#endif
2563	}
2564}
2565
2566/*
2567 * A CPU is entering for the first time or a thread is exiting.
2568 */
2569void
2570sched_throw(struct thread *td)
2571{
2572	struct tdq *tdq;
2573
2574	tdq = TDQ_SELF();
2575	if (td == NULL) {
2576		/* Correct spinlock nesting and acquire the correct lock. */
2577		TDQ_LOCK(tdq);
2578		spinlock_exit();
2579	} else {
2580		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2581		tdq_load_rem(tdq, td->td_sched);
2582	}
2583	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2584	PCPU_SET(switchtime, cpu_ticks());
2585	PCPU_SET(switchticks, ticks);
2586	cpu_throw(td, choosethread());	/* doesn't return */
2587}
2588
2589/*
2590 * This is called from fork_exit().  Just acquire the correct locks and
2591 * let fork do the rest of the work.
2592 */
2593void
2594sched_fork_exit(struct thread *td)
2595{
2596	struct td_sched *ts;
2597	struct tdq *tdq;
2598	int cpuid;
2599
2600	/*
2601	 * Finish setting up thread glue so that it begins execution in a
2602	 * non-nested critical section with the scheduler lock held.
2603	 */
2604	cpuid = PCPU_GET(cpuid);
2605	tdq = TDQ_CPU(cpuid);
2606	ts = td->td_sched;
2607	if (TD_IS_IDLETHREAD(td))
2608		td->td_lock = TDQ_LOCKPTR(tdq);
2609	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2610	td->td_oncpu = cpuid;
2611	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)td;
2612	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
2613}
2614
2615static SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0,
2616    "Scheduler");
2617SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2618    "Scheduler name");
2619SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2620    "Slice size for timeshare threads");
2621SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2622     "Interactivity score threshold");
2623SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2624     0,"Min priority for preemption, lower priorities have greater precedence");
2625#ifdef SMP
2626SYSCTL_INT(_kern_sched, OID_AUTO, pick_pri, CTLFLAG_RW, &pick_pri, 0,
2627    "Pick the target cpu based on priority rather than load.");
2628SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2629    "Number of hz ticks to keep thread affinity for");
2630SYSCTL_INT(_kern_sched, OID_AUTO, tryself, CTLFLAG_RW, &tryself, 0, "");
2631SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2632    "Enables the long-term load balancer");
2633SYSCTL_INT(_kern_sched, OID_AUTO, balance_secs, CTLFLAG_RW, &balance_secs, 0,
2634    "Average frequence in seconds to run the long-term balancer");
2635SYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2636    "Steals work from another hyper-threaded core on idle");
2637SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2638    "Attempts to steal work from other cores before idling");
2639SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2640    "Minimum load on remote cpu before we'll steal");
2641SYSCTL_INT(_kern_sched, OID_AUTO, topology, CTLFLAG_RD, &topology, 0,
2642    "True when a topology has been specified by the MD code.");
2643#endif
2644
2645/* ps compat.  All cpu percentages from ULE are weighted. */
2646static int ccpu = 0;
2647SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2648
2649
2650#define KERN_SWITCH_INCLUDE 1
2651#include "kern/kern_switch.c"
2652