sched_ule.c revision 172308
1/*-
2 * Copyright (c) 2002-2007, Jeffrey Roberson <jeff@freebsd.org>
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice unmodified, this list of conditions, and the following
10 *    disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27/*
28 * This file implements the ULE scheduler.  ULE supports independent CPU
29 * run queues and fine grain locking.  It has superior interactive
30 * performance under load even on uni-processor systems.
31 *
32 * etymology:
33 *   ULE is the last three letters in schedule.  It owes its name to a
34 * generic user created for a scheduling system by Paul Mikesell at
35 * Isilon Systems and a general lack of creativity on the part of the author.
36 */
37
38#include <sys/cdefs.h>
39__FBSDID("$FreeBSD: head/sys/kern/sched_ule.c 172308 2007-09-24 00:28:54Z jeff $");
40
41#include "opt_hwpmc_hooks.h"
42#include "opt_sched.h"
43
44#include <sys/param.h>
45#include <sys/systm.h>
46#include <sys/kdb.h>
47#include <sys/kernel.h>
48#include <sys/ktr.h>
49#include <sys/lock.h>
50#include <sys/mutex.h>
51#include <sys/proc.h>
52#include <sys/resource.h>
53#include <sys/resourcevar.h>
54#include <sys/sched.h>
55#include <sys/smp.h>
56#include <sys/sx.h>
57#include <sys/sysctl.h>
58#include <sys/sysproto.h>
59#include <sys/turnstile.h>
60#include <sys/umtx.h>
61#include <sys/vmmeter.h>
62#ifdef KTRACE
63#include <sys/uio.h>
64#include <sys/ktrace.h>
65#endif
66
67#ifdef HWPMC_HOOKS
68#include <sys/pmckern.h>
69#endif
70
71#include <machine/cpu.h>
72#include <machine/smp.h>
73
74#ifndef PREEMPTION
75#error	"SCHED_ULE requires options PREEMPTION"
76#endif
77
78#define	KTR_ULE	0
79
80/*
81 * Thread scheduler specific section.  All fields are protected
82 * by the thread lock.
83 */
84struct td_sched {
85	TAILQ_ENTRY(td_sched) ts_procq;	/* Run queue. */
86	struct thread	*ts_thread;	/* Active associated thread. */
87	struct runq	*ts_runq;	/* Run-queue we're queued on. */
88	short		ts_flags;	/* TSF_* flags. */
89	u_char		ts_rqindex;	/* Run queue index. */
90	u_char		ts_cpu;		/* CPU that we have affinity for. */
91	int		ts_slice;	/* Ticks of slice remaining. */
92	u_int		ts_slptime;	/* Number of ticks we vol. slept */
93	u_int		ts_runtime;	/* Number of ticks we were running */
94	/* The following variables are only used for pctcpu calculation */
95	int		ts_ltick;	/* Last tick that we were running on */
96	int		ts_ftick;	/* First tick that we were running on */
97	int		ts_ticks;	/* Tick count */
98#ifdef SMP
99	int		ts_rltick;	/* Real last tick, for affinity. */
100#endif
101};
102/* flags kept in ts_flags */
103#define	TSF_BOUND	0x0001		/* Thread can not migrate. */
104#define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
105
106static struct td_sched td_sched0;
107
108/*
109 * Cpu percentage computation macros and defines.
110 *
111 * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
112 * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
113 * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
114 * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
115 * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
116 * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
117 */
118#define	SCHED_TICK_SECS		10
119#define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
120#define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
121#define	SCHED_TICK_SHIFT	10
122#define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
123#define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
124
125/*
126 * These macros determine priorities for non-interactive threads.  They are
127 * assigned a priority based on their recent cpu utilization as expressed
128 * by the ratio of ticks to the tick total.  NHALF priorities at the start
129 * and end of the MIN to MAX timeshare range are only reachable with negative
130 * or positive nice respectively.
131 *
132 * PRI_RANGE:	Priority range for utilization dependent priorities.
133 * PRI_NRESV:	Number of nice values.
134 * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
135 * PRI_NICE:	Determines the part of the priority inherited from nice.
136 */
137#define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
138#define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
139#define	SCHED_PRI_MIN		(PRI_MIN_TIMESHARE + SCHED_PRI_NHALF)
140#define	SCHED_PRI_MAX		(PRI_MAX_TIMESHARE - SCHED_PRI_NHALF)
141#define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN)
142#define	SCHED_PRI_TICKS(ts)						\
143    (SCHED_TICK_HZ((ts)) /						\
144    (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
145#define	SCHED_PRI_NICE(nice)	(nice)
146
147/*
148 * These determine the interactivity of a process.  Interactivity differs from
149 * cpu utilization in that it expresses the voluntary time slept vs time ran
150 * while cpu utilization includes all time not running.  This more accurately
151 * models the intent of the thread.
152 *
153 * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
154 *		before throttling back.
155 * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
156 * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
157 * INTERACT_THRESH:	Threshhold for placement on the current runq.
158 */
159#define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
160#define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
161#define	SCHED_INTERACT_MAX	(100)
162#define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
163#define	SCHED_INTERACT_THRESH	(30)
164
165/*
166 * tickincr:		Converts a stathz tick into a hz domain scaled by
167 *			the shift factor.  Without the shift the error rate
168 *			due to rounding would be unacceptably high.
169 * realstathz:		stathz is sometimes 0 and run off of hz.
170 * sched_slice:		Runtime of each thread before rescheduling.
171 * preempt_thresh:	Priority threshold for preemption and remote IPIs.
172 */
173static int sched_interact = SCHED_INTERACT_THRESH;
174static int realstathz;
175static int tickincr;
176static int sched_slice;
177static int preempt_thresh = PRI_MIN_KERN;
178
179/*
180 * tdq - per processor runqs and statistics.  All fields are protected by the
181 * tdq_lock.  The load and lowpri may be accessed without to avoid excess
182 * locking in sched_pickcpu();
183 */
184struct tdq {
185	struct mtx	*tdq_lock;		/* Pointer to group lock. */
186	struct runq	tdq_realtime;		/* real-time run queue. */
187	struct runq	tdq_timeshare;		/* timeshare run queue. */
188	struct runq	tdq_idle;		/* Queue of IDLE threads. */
189	int		tdq_load;		/* Aggregate load. */
190	u_char		tdq_idx;		/* Current insert index. */
191	u_char		tdq_ridx;		/* Current removal index. */
192#ifdef SMP
193	u_char		tdq_lowpri;		/* Lowest priority thread. */
194	int		tdq_transferable;	/* Transferable thread count. */
195	LIST_ENTRY(tdq)	tdq_siblings;		/* Next in tdq group. */
196	struct tdq_group *tdq_group;		/* Our processor group. */
197#else
198	int		tdq_sysload;		/* For loadavg, !ITHD load. */
199#endif
200} __aligned(64);
201
202
203#ifdef SMP
204/*
205 * tdq groups are groups of processors which can cheaply share threads.  When
206 * one processor in the group goes idle it will check the runqs of the other
207 * processors in its group prior to halting and waiting for an interrupt.
208 * These groups are suitable for SMT (Symetric Multi-Threading) and not NUMA.
209 * In a numa environment we'd want an idle bitmap per group and a two tiered
210 * load balancer.
211 */
212struct tdq_group {
213	struct mtx	tdg_lock;	/* Protects all fields below. */
214	int		tdg_cpus;	/* Count of CPUs in this tdq group. */
215	cpumask_t 	tdg_cpumask;	/* Mask of cpus in this group. */
216	cpumask_t 	tdg_idlemask;	/* Idle cpus in this group. */
217	cpumask_t 	tdg_mask;	/* Bit mask for first cpu. */
218	int		tdg_load;	/* Total load of this group. */
219	int	tdg_transferable;	/* Transferable load of this group. */
220	LIST_HEAD(, tdq) tdg_members;	/* Linked list of all members. */
221	char		tdg_name[16];	/* lock name. */
222} __aligned(64);
223
224#define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 300))
225#define	SCHED_AFFINITY(ts)	((ts)->ts_rltick > ticks - affinity)
226
227/*
228 * Run-time tunables.
229 */
230static int rebalance = 1;
231static int balance_secs = 1;
232static int pick_pri = 1;
233static int affinity;
234static int tryself = 1;
235static int steal_htt = 0;
236static int steal_idle = 1;
237static int steal_thresh = 2;
238static int topology = 0;
239
240/*
241 * One thread queue per processor.
242 */
243static volatile cpumask_t tdq_idle;
244static int tdg_maxid;
245static struct tdq	tdq_cpu[MAXCPU];
246static struct tdq_group tdq_groups[MAXCPU];
247static struct callout balco;
248static struct callout gbalco;
249
250#define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
251#define	TDQ_CPU(x)	(&tdq_cpu[(x)])
252#define	TDQ_ID(x)	((int)((x) - tdq_cpu))
253#define	TDQ_GROUP(x)	(&tdq_groups[(x)])
254#define	TDG_ID(x)	((int)((x) - tdq_groups))
255#else	/* !SMP */
256static struct tdq	tdq_cpu;
257static struct mtx	tdq_lock;
258
259#define	TDQ_ID(x)	(0)
260#define	TDQ_SELF()	(&tdq_cpu)
261#define	TDQ_CPU(x)	(&tdq_cpu)
262#endif
263
264#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
265#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
266#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
267#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
268#define	TDQ_LOCKPTR(t)		((t)->tdq_lock)
269
270static void sched_priority(struct thread *);
271static void sched_thread_priority(struct thread *, u_char);
272static int sched_interact_score(struct thread *);
273static void sched_interact_update(struct thread *);
274static void sched_interact_fork(struct thread *);
275static void sched_pctcpu_update(struct td_sched *);
276
277/* Operations on per processor queues */
278static struct td_sched * tdq_choose(struct tdq *);
279static void tdq_setup(struct tdq *);
280static void tdq_load_add(struct tdq *, struct td_sched *);
281static void tdq_load_rem(struct tdq *, struct td_sched *);
282static __inline void tdq_runq_add(struct tdq *, struct td_sched *, int);
283static __inline void tdq_runq_rem(struct tdq *, struct td_sched *);
284void tdq_print(int cpu);
285static void runq_print(struct runq *rq);
286static void tdq_add(struct tdq *, struct thread *, int);
287#ifdef SMP
288static void tdq_move(struct tdq *, struct tdq *);
289static int tdq_idled(struct tdq *);
290static void tdq_notify(struct td_sched *);
291static struct td_sched *tdq_steal(struct tdq *, int);
292static struct td_sched *runq_steal(struct runq *);
293static int sched_pickcpu(struct td_sched *, int);
294static void sched_balance(void *);
295static void sched_balance_groups(void *);
296static void sched_balance_group(struct tdq_group *);
297static void sched_balance_pair(struct tdq *, struct tdq *);
298static inline struct tdq *sched_setcpu(struct td_sched *, int, int);
299static inline struct mtx *thread_block_switch(struct thread *);
300static inline void thread_unblock_switch(struct thread *, struct mtx *);
301static struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
302
303#define	THREAD_CAN_MIGRATE(td)	 ((td)->td_pinned == 0)
304#endif
305
306static void sched_setup(void *dummy);
307SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
308
309static void sched_initticks(void *dummy);
310SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks, NULL)
311
312/*
313 * Print the threads waiting on a run-queue.
314 */
315static void
316runq_print(struct runq *rq)
317{
318	struct rqhead *rqh;
319	struct td_sched *ts;
320	int pri;
321	int j;
322	int i;
323
324	for (i = 0; i < RQB_LEN; i++) {
325		printf("\t\trunq bits %d 0x%zx\n",
326		    i, rq->rq_status.rqb_bits[i]);
327		for (j = 0; j < RQB_BPW; j++)
328			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
329				pri = j + (i << RQB_L2BPW);
330				rqh = &rq->rq_queues[pri];
331				TAILQ_FOREACH(ts, rqh, ts_procq) {
332					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
333					    ts->ts_thread, ts->ts_thread->td_proc->p_comm, ts->ts_thread->td_priority, ts->ts_rqindex, pri);
334				}
335			}
336	}
337}
338
339/*
340 * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
341 */
342void
343tdq_print(int cpu)
344{
345	struct tdq *tdq;
346
347	tdq = TDQ_CPU(cpu);
348
349	printf("tdq %d:\n", TDQ_ID(tdq));
350	printf("\tlockptr         %p\n", TDQ_LOCKPTR(tdq));
351	printf("\tload:           %d\n", tdq->tdq_load);
352	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
353	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
354	printf("\trealtime runq:\n");
355	runq_print(&tdq->tdq_realtime);
356	printf("\ttimeshare runq:\n");
357	runq_print(&tdq->tdq_timeshare);
358	printf("\tidle runq:\n");
359	runq_print(&tdq->tdq_idle);
360#ifdef SMP
361	printf("\tload transferable: %d\n", tdq->tdq_transferable);
362	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
363	printf("\tgroup:             %d\n", TDG_ID(tdq->tdq_group));
364	printf("\tLock name:         %s\n", tdq->tdq_group->tdg_name);
365#endif
366}
367
368#define	TS_RQ_PPQ	(((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
369/*
370 * Add a thread to the actual run-queue.  Keeps transferable counts up to
371 * date with what is actually on the run-queue.  Selects the correct
372 * queue position for timeshare threads.
373 */
374static __inline void
375tdq_runq_add(struct tdq *tdq, struct td_sched *ts, int flags)
376{
377	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
378	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
379#ifdef SMP
380	if (THREAD_CAN_MIGRATE(ts->ts_thread)) {
381		tdq->tdq_transferable++;
382		tdq->tdq_group->tdg_transferable++;
383		ts->ts_flags |= TSF_XFERABLE;
384	}
385#endif
386	if (ts->ts_runq == &tdq->tdq_timeshare) {
387		u_char pri;
388
389		pri = ts->ts_thread->td_priority;
390		KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
391			("Invalid priority %d on timeshare runq", pri));
392		/*
393		 * This queue contains only priorities between MIN and MAX
394		 * realtime.  Use the whole queue to represent these values.
395		 */
396		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
397			pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
398			pri = (pri + tdq->tdq_idx) % RQ_NQS;
399			/*
400			 * This effectively shortens the queue by one so we
401			 * can have a one slot difference between idx and
402			 * ridx while we wait for threads to drain.
403			 */
404			if (tdq->tdq_ridx != tdq->tdq_idx &&
405			    pri == tdq->tdq_ridx)
406				pri = (unsigned char)(pri - 1) % RQ_NQS;
407		} else
408			pri = tdq->tdq_ridx;
409		runq_add_pri(ts->ts_runq, ts, pri, flags);
410	} else
411		runq_add(ts->ts_runq, ts, flags);
412}
413
414/*
415 * Remove a thread from a run-queue.  This typically happens when a thread
416 * is selected to run.  Running threads are not on the queue and the
417 * transferable count does not reflect them.
418 */
419static __inline void
420tdq_runq_rem(struct tdq *tdq, struct td_sched *ts)
421{
422	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
423	KASSERT(ts->ts_runq != NULL,
424	    ("tdq_runq_remove: thread %p null ts_runq", ts->ts_thread));
425#ifdef SMP
426	if (ts->ts_flags & TSF_XFERABLE) {
427		tdq->tdq_transferable--;
428		tdq->tdq_group->tdg_transferable--;
429		ts->ts_flags &= ~TSF_XFERABLE;
430	}
431#endif
432	if (ts->ts_runq == &tdq->tdq_timeshare) {
433		if (tdq->tdq_idx != tdq->tdq_ridx)
434			runq_remove_idx(ts->ts_runq, ts, &tdq->tdq_ridx);
435		else
436			runq_remove_idx(ts->ts_runq, ts, NULL);
437		/*
438		 * For timeshare threads we update the priority here so
439		 * the priority reflects the time we've been sleeping.
440		 */
441		ts->ts_ltick = ticks;
442		sched_pctcpu_update(ts);
443		sched_priority(ts->ts_thread);
444	} else
445		runq_remove(ts->ts_runq, ts);
446}
447
448/*
449 * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
450 * for this thread to the referenced thread queue.
451 */
452static void
453tdq_load_add(struct tdq *tdq, struct td_sched *ts)
454{
455	int class;
456
457	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
458	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
459	class = PRI_BASE(ts->ts_thread->td_pri_class);
460	tdq->tdq_load++;
461	CTR2(KTR_SCHED, "cpu %d load: %d", TDQ_ID(tdq), tdq->tdq_load);
462	if (class != PRI_ITHD &&
463	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
464#ifdef SMP
465		tdq->tdq_group->tdg_load++;
466#else
467		tdq->tdq_sysload++;
468#endif
469}
470
471/*
472 * Remove the load from a thread that is transitioning to a sleep state or
473 * exiting.
474 */
475static void
476tdq_load_rem(struct tdq *tdq, struct td_sched *ts)
477{
478	int class;
479
480	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
481	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
482	class = PRI_BASE(ts->ts_thread->td_pri_class);
483	if (class != PRI_ITHD &&
484	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
485#ifdef SMP
486		tdq->tdq_group->tdg_load--;
487#else
488		tdq->tdq_sysload--;
489#endif
490	KASSERT(tdq->tdq_load != 0,
491	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
492	tdq->tdq_load--;
493	CTR1(KTR_SCHED, "load: %d", tdq->tdq_load);
494	ts->ts_runq = NULL;
495}
496
497#ifdef SMP
498/*
499 * sched_balance is a simple CPU load balancing algorithm.  It operates by
500 * finding the least loaded and most loaded cpu and equalizing their load
501 * by migrating some processes.
502 *
503 * Dealing only with two CPUs at a time has two advantages.  Firstly, most
504 * installations will only have 2 cpus.  Secondly, load balancing too much at
505 * once can have an unpleasant effect on the system.  The scheduler rarely has
506 * enough information to make perfect decisions.  So this algorithm chooses
507 * simplicity and more gradual effects on load in larger systems.
508 *
509 */
510static void
511sched_balance(void *arg)
512{
513	struct tdq_group *high;
514	struct tdq_group *low;
515	struct tdq_group *tdg;
516	int cnt;
517	int i;
518
519	callout_reset(&balco, max(hz / 2, random() % (hz * balance_secs)),
520	    sched_balance, NULL);
521	if (smp_started == 0 || rebalance == 0)
522		return;
523	low = high = NULL;
524	i = random() % (tdg_maxid + 1);
525	for (cnt = 0; cnt <= tdg_maxid; cnt++) {
526		tdg = TDQ_GROUP(i);
527		/*
528		 * Find the CPU with the highest load that has some
529		 * threads to transfer.
530		 */
531		if ((high == NULL || tdg->tdg_load > high->tdg_load)
532		    && tdg->tdg_transferable)
533			high = tdg;
534		if (low == NULL || tdg->tdg_load < low->tdg_load)
535			low = tdg;
536		if (++i > tdg_maxid)
537			i = 0;
538	}
539	if (low != NULL && high != NULL && high != low)
540		sched_balance_pair(LIST_FIRST(&high->tdg_members),
541		    LIST_FIRST(&low->tdg_members));
542}
543
544/*
545 * Balance load between CPUs in a group.  Will only migrate within the group.
546 */
547static void
548sched_balance_groups(void *arg)
549{
550	int i;
551
552	callout_reset(&gbalco, max(hz / 2, random() % (hz * balance_secs)),
553	    sched_balance_groups, NULL);
554	if (smp_started == 0 || rebalance == 0)
555		return;
556	for (i = 0; i <= tdg_maxid; i++)
557		sched_balance_group(TDQ_GROUP(i));
558}
559
560/*
561 * Finds the greatest imbalance between two tdqs in a group.
562 */
563static void
564sched_balance_group(struct tdq_group *tdg)
565{
566	struct tdq *tdq;
567	struct tdq *high;
568	struct tdq *low;
569	int load;
570
571	if (tdg->tdg_transferable == 0)
572		return;
573	low = NULL;
574	high = NULL;
575	LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
576		load = tdq->tdq_load;
577		if (high == NULL || load > high->tdq_load)
578			high = tdq;
579		if (low == NULL || load < low->tdq_load)
580			low = tdq;
581	}
582	if (high != NULL && low != NULL && high != low)
583		sched_balance_pair(high, low);
584}
585
586/*
587 * Lock two thread queues using their address to maintain lock order.
588 */
589static void
590tdq_lock_pair(struct tdq *one, struct tdq *two)
591{
592	if (one < two) {
593		TDQ_LOCK(one);
594		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
595	} else {
596		TDQ_LOCK(two);
597		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
598	}
599}
600
601/*
602 * Transfer load between two imbalanced thread queues.
603 */
604static void
605sched_balance_pair(struct tdq *high, struct tdq *low)
606{
607	int transferable;
608	int high_load;
609	int low_load;
610	int move;
611	int diff;
612	int i;
613
614	tdq_lock_pair(high, low);
615	/*
616	 * If we're transfering within a group we have to use this specific
617	 * tdq's transferable count, otherwise we can steal from other members
618	 * of the group.
619	 */
620	if (high->tdq_group == low->tdq_group) {
621		transferable = high->tdq_transferable;
622		high_load = high->tdq_load;
623		low_load = low->tdq_load;
624	} else {
625		transferable = high->tdq_group->tdg_transferable;
626		high_load = high->tdq_group->tdg_load;
627		low_load = low->tdq_group->tdg_load;
628	}
629	/*
630	 * Determine what the imbalance is and then adjust that to how many
631	 * threads we actually have to give up (transferable).
632	 */
633	if (transferable != 0) {
634		diff = high_load - low_load;
635		move = diff / 2;
636		if (diff & 0x1)
637			move++;
638		move = min(move, transferable);
639		for (i = 0; i < move; i++)
640			tdq_move(high, low);
641		/*
642		 * IPI the target cpu to force it to reschedule with the new
643		 * workload.
644		 */
645		ipi_selected(1 << TDQ_ID(low), IPI_PREEMPT);
646	}
647	TDQ_UNLOCK(high);
648	TDQ_UNLOCK(low);
649	return;
650}
651
652/*
653 * Move a thread from one thread queue to another.
654 */
655static void
656tdq_move(struct tdq *from, struct tdq *to)
657{
658	struct td_sched *ts;
659	struct thread *td;
660	struct tdq *tdq;
661	int cpu;
662
663	tdq = from;
664	cpu = TDQ_ID(to);
665	ts = tdq_steal(tdq, 1);
666	if (ts == NULL) {
667		struct tdq_group *tdg;
668
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