sched_ule.c revision 171715
11573Srgrimes/*-
214287Spst * Copyright (c) 2002-2007, Jeffrey Roberson <jeff@freebsd.org>
31573Srgrimes * All rights reserved.
41573Srgrimes *
51573Srgrimes * Redistribution and use in source and binary forms, with or without
61573Srgrimes * modification, are permitted provided that the following conditions
71573Srgrimes * are met:
81573Srgrimes * 1. Redistributions of source code must retain the above copyright
91573Srgrimes *    notice unmodified, this list of conditions, and the following
101573Srgrimes *    disclaimer.
111573Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
121573Srgrimes *    notice, this list of conditions and the following disclaimer in the
131573Srgrimes *    documentation and/or other materials provided with the distribution.
141573Srgrimes *
151573Srgrimes * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
161573Srgrimes * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
171573Srgrimes * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
181573Srgrimes * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
191573Srgrimes * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
201573Srgrimes * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
211573Srgrimes * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
221573Srgrimes * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
231573Srgrimes * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
241573Srgrimes * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
251573Srgrimes */
261573Srgrimes
271573Srgrimes/*
281573Srgrimes * This file implements the ULE scheduler.  ULE supports independent CPU
291573Srgrimes * run queues and fine grain locking.  It has superior interactive
301573Srgrimes * performance under load even on uni-processor systems.
311573Srgrimes *
321573Srgrimes * etymology:
331573Srgrimes *   ULE is the last three letters in schedule.  It owes it's name to a
3414287Spst * generic user created for a scheduling system by Paul Mikesell at
351573Srgrimes * Isilon Systems and a general lack of creativity on the part of the author.
3692889Sobrien */
3792889Sobrien
381573Srgrimes#include <sys/cdefs.h>
391573Srgrimes__FBSDID("$FreeBSD: head/sys/kern/sched_ule.c 171715 2007-08-04 01:21:28Z jeff $");
401573Srgrimes
411573Srgrimes#include "opt_hwpmc_hooks.h"
421573Srgrimes#include "opt_sched.h"
431573Srgrimes
441573Srgrimes#include <sys/param.h>
451573Srgrimes#include <sys/systm.h>
461573Srgrimes#include <sys/kdb.h>
471573Srgrimes#include <sys/kernel.h>
481573Srgrimes#include <sys/ktr.h>
491573Srgrimes#include <sys/lock.h>
501573Srgrimes#include <sys/mutex.h>
511573Srgrimes#include <sys/proc.h>
521573Srgrimes#include <sys/resource.h>
531573Srgrimes#include <sys/resourcevar.h>
541573Srgrimes#include <sys/sched.h>
5571579Sdeischen#include <sys/smp.h>
56190485Sdelphij#include <sys/sx.h>
571573Srgrimes#include <sys/sysctl.h>
581573Srgrimes#include <sys/sysproto.h>
591573Srgrimes#include <sys/turnstile.h>
601573Srgrimes#include <sys/umtx.h>
611573Srgrimes#include <sys/vmmeter.h>
621573Srgrimes#ifdef KTRACE
631573Srgrimes#include <sys/uio.h>
641573Srgrimes#include <sys/ktrace.h>
651573Srgrimes#endif
661573Srgrimes
671573Srgrimes#ifdef HWPMC_HOOKS
6871579Sdeischen#include <sys/pmckern.h>
691573Srgrimes#endif
701573Srgrimes
711573Srgrimes#include <machine/cpu.h>
721573Srgrimes#include <machine/smp.h>
731573Srgrimes
741573Srgrimes#ifndef PREEMPTION
75189291Sdelphij#error	"SCHED_ULE requires options PREEMPTION"
76189291Sdelphij#endif
77189291Sdelphij
78189291Sdelphij#define	KTR_ULE	0
79189291Sdelphij
80189291Sdelphij/*
81189291Sdelphij * Thread scheduler specific section.  All fields are protected
821573Srgrimes * by the thread lock.
831573Srgrimes */
8414287Spststruct td_sched {
8514287Spst	TAILQ_ENTRY(td_sched) ts_procq;	/* Run queue. */
8614287Spst	struct thread	*ts_thread;	/* Active associated thread. */
871573Srgrimes	struct runq	*ts_runq;	/* Run-queue we're queued on. */
881573Srgrimes	short		ts_flags;	/* TSF_* flags. */
891573Srgrimes	u_char		ts_rqindex;	/* Run queue index. */
901573Srgrimes	u_char		ts_cpu;		/* CPU that we have affinity for. */
911573Srgrimes	int		ts_slptick;	/* Tick when we went to sleep. */
921573Srgrimes	int		ts_slice;	/* Ticks of slice remaining. */
931573Srgrimes	u_int		ts_slptime;	/* Number of ticks we vol. slept */
941573Srgrimes	u_int		ts_runtime;	/* Number of ticks we were running */
95189291Sdelphij	/* The following variables are only used for pctcpu calculation */
961573Srgrimes	int		ts_ltick;	/* Last tick that we were running on */
9792889Sobrien	int		ts_ftick;	/* First tick that we were running on */
981573Srgrimes	int		ts_ticks;	/* Tick count */
9914287Spst#ifdef SMP
1001573Srgrimes	int		ts_rltick;	/* Real last tick, for affinity. */
1011573Srgrimes#endif
1021573Srgrimes};
1031573Srgrimes/* flags kept in ts_flags */
1041573Srgrimes#define	TSF_BOUND	0x0001		/* Thread can not migrate. */
1051573Srgrimes#define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
1061573Srgrimes
1071573Srgrimesstatic struct td_sched td_sched0;
1081573Srgrimes
1091573Srgrimes/*
1101573Srgrimes * Cpu percentage computation macros and defines.
1111573Srgrimes *
1121573Srgrimes * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
1131573Srgrimes * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
1141573Srgrimes * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
11514287Spst * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
1161573Srgrimes * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
1171573Srgrimes * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
1181573Srgrimes */
1191573Srgrimes#define	SCHED_TICK_SECS		10
1201573Srgrimes#define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
1211573Srgrimes#define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
1221573Srgrimes#define	SCHED_TICK_SHIFT	10
1231573Srgrimes#define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
124189291Sdelphij#define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
125189291Sdelphij
1261573Srgrimes/*
127190489Sdelphij * These macros determine priorities for non-interactive threads.  They are
12892889Sobrien * assigned a priority based on their recent cpu utilization as expressed
1291573Srgrimes * by the ratio of ticks to the tick total.  NHALF priorities at the start
13014287Spst * and end of the MIN to MAX timeshare range are only reachable with negative
1311573Srgrimes * or positive nice respectively.
1321573Srgrimes *
1331573Srgrimes * PRI_RANGE:	Priority range for utilization dependent priorities.
1341573Srgrimes * PRI_NRESV:	Number of nice values.
1351573Srgrimes * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
1361573Srgrimes * PRI_NICE:	Determines the part of the priority inherited from nice.
1371573Srgrimes */
1381573Srgrimes#define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
1391573Srgrimes#define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
1401573Srgrimes#define	SCHED_PRI_MIN		(PRI_MIN_TIMESHARE + SCHED_PRI_NHALF)
1411573Srgrimes#define	SCHED_PRI_MAX		(PRI_MAX_TIMESHARE - SCHED_PRI_NHALF)
1421573Srgrimes#define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN)
14392889Sobrien#define	SCHED_PRI_TICKS(ts)						\
14492889Sobrien    (SCHED_TICK_HZ((ts)) /						\
14592889Sobrien    (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
1461573Srgrimes#define	SCHED_PRI_NICE(nice)	(nice)
1471573Srgrimes
1481573Srgrimes/*
1491573Srgrimes * These determine the interactivity of a process.  Interactivity differs from
1501573Srgrimes * cpu utilization in that it expresses the voluntary time slept vs time ran
1511573Srgrimes * while cpu utilization includes all time not running.  This more accurately
1521573Srgrimes * models the intent of the thread.
1531573Srgrimes *
1541573Srgrimes * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
1551573Srgrimes *		before throttling back.
1561573Srgrimes * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
1571573Srgrimes * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
158190491Sdelphij * INTERACT_THRESH:	Threshhold for placement on the current runq.
159190491Sdelphij */
160190491Sdelphij#define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
161190491Sdelphij#define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
162190491Sdelphij#define	SCHED_INTERACT_MAX	(100)
163190491Sdelphij#define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
164190491Sdelphij#define	SCHED_INTERACT_THRESH	(30)
165190491Sdelphij
1661573Srgrimes/*
1671573Srgrimes * tickincr:		Converts a stathz tick into a hz domain scaled by
1681573Srgrimes *			the shift factor.  Without the shift the error rate
16914287Spst *			due to rounding would be unacceptably high.
1701573Srgrimes * realstathz:		stathz is sometimes 0 and run off of hz.
1711573Srgrimes * sched_slice:		Runtime of each thread before rescheduling.
1721573Srgrimes * preempt_thresh:	Priority threshold for preemption and remote IPIs.
1731573Srgrimes */
1741573Srgrimesstatic int sched_interact = SCHED_INTERACT_THRESH;
1751573Srgrimesstatic int realstathz;
1761573Srgrimesstatic int tickincr;
1771573Srgrimesstatic int sched_slice;
1781573Srgrimesstatic int preempt_thresh = PRI_MIN_KERN;
1791573Srgrimes
1801573Srgrimes/*
181189291Sdelphij * tdq - per processor runqs and statistics.  All fields are protected by the
182189291Sdelphij * tdq_lock.  The load and lowpri may be accessed without to avoid excess
1831573Srgrimes * locking in sched_pickcpu();
18492889Sobrien */
18592889Sobrienstruct tdq {
18692889Sobrien	struct mtx	*tdq_lock;		/* Pointer to group lock. */
1871573Srgrimes	struct runq	tdq_realtime;		/* real-time run queue. */
1881573Srgrimes	struct runq	tdq_timeshare;		/* timeshare run queue. */
18914287Spst	struct runq	tdq_idle;		/* Queue of IDLE threads. */
1901573Srgrimes	int		tdq_load;		/* Aggregate load. */
1911573Srgrimes	u_char		tdq_idx;		/* Current insert index. */
19214287Spst	u_char		tdq_ridx;		/* Current removal index. */
19314287Spst#ifdef SMP
1941573Srgrimes	u_char		tdq_lowpri;		/* Lowest priority thread. */
1951573Srgrimes	int		tdq_transferable;	/* Transferable thread count. */
1961573Srgrimes	LIST_ENTRY(tdq)	tdq_siblings;		/* Next in tdq group. */
1971573Srgrimes	struct tdq_group *tdq_group;		/* Our processor group. */
1981573Srgrimes#else
1991573Srgrimes	int		tdq_sysload;		/* For loadavg, !ITHD load. */
2001573Srgrimes#endif
2011573Srgrimes} __aligned(64);
2021573Srgrimes
2031573Srgrimes
20414287Spst#ifdef SMP
2051573Srgrimes/*
2061573Srgrimes * tdq groups are groups of processors which can cheaply share threads.  When
2071573Srgrimes * one processor in the group goes idle it will check the runqs of the other
2081573Srgrimes * processors in its group prior to halting and waiting for an interrupt.
2091573Srgrimes * These groups are suitable for SMT (Symetric Multi-Threading) and not NUMA.
2101573Srgrimes * In a numa environment we'd want an idle bitmap per group and a two tiered
2111573Srgrimes * load balancer.
2121573Srgrimes */
2131573Srgrimesstruct tdq_group {
2141573Srgrimes	struct mtx	tdg_lock;	/* Protects all fields below. */
2151573Srgrimes	int		tdg_cpus;	/* Count of CPUs in this tdq group. */
2161573Srgrimes	cpumask_t 	tdg_cpumask;	/* Mask of cpus in this group. */
2171573Srgrimes	cpumask_t 	tdg_idlemask;	/* Idle cpus in this group. */
2181573Srgrimes	cpumask_t 	tdg_mask;	/* Bit mask for first cpu. */
2191573Srgrimes	int		tdg_load;	/* Total load of this group. */
2201573Srgrimes	int	tdg_transferable;	/* Transferable load of this group. */
2211573Srgrimes	LIST_HEAD(, tdq) tdg_members;	/* Linked list of all members. */
2221573Srgrimes	char		tdg_name[16];	/* lock name. */
2231573Srgrimes} __aligned(64);
2241573Srgrimes
2251573Srgrimes#define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 300))
2261573Srgrimes#define	SCHED_AFFINITY(ts)	((ts)->ts_rltick > ticks - affinity)
2271573Srgrimes
2281573Srgrimes/*
2291573Srgrimes * Run-time tunables.
2301573Srgrimes */
2311573Srgrimesstatic int rebalance = 1;
2321573Srgrimesstatic int balance_secs = 1;
2331573Srgrimesstatic int pick_pri = 1;
2341573Srgrimesstatic int affinity;
2351573Srgrimesstatic int tryself = 1;
2361573Srgrimesstatic int steal_htt = 0;
2371573Srgrimesstatic int steal_idle = 1;
2381573Srgrimesstatic int steal_thresh = 2;
2391573Srgrimesstatic int topology = 0;
2401573Srgrimes
2411573Srgrimes/*
2421573Srgrimes * One thread queue per processor.
2431573Srgrimes */
2441573Srgrimesstatic volatile cpumask_t tdq_idle;
2451573Srgrimesstatic int tdg_maxid;
24614287Spststatic struct tdq	tdq_cpu[MAXCPU];
2471573Srgrimesstatic struct tdq_group tdq_groups[MAXCPU];
2481573Srgrimesstatic struct callout balco;
2491573Srgrimesstatic struct callout gbalco;
2501573Srgrimes
25114287Spst#define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
25214287Spst#define	TDQ_CPU(x)	(&tdq_cpu[(x)])
2531573Srgrimes#define	TDQ_ID(x)	((int)((x) - tdq_cpu))
2541573Srgrimes#define	TDQ_GROUP(x)	(&tdq_groups[(x)])
2551573Srgrimes#define	TDG_ID(x)	((int)((x) - tdq_groups))
2561573Srgrimes#else	/* !SMP */
2571573Srgrimesstatic struct tdq	tdq_cpu;
2581573Srgrimesstatic struct mtx	tdq_lock;
2591573Srgrimes
2601573Srgrimes#define	TDQ_ID(x)	(0)
2611573Srgrimes#define	TDQ_SELF()	(&tdq_cpu)
2621573Srgrimes#define	TDQ_CPU(x)	(&tdq_cpu)
2631573Srgrimes#endif
2641573Srgrimes
2651573Srgrimes#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
2661573Srgrimes#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
2671573Srgrimes#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
2681573Srgrimes#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
2691573Srgrimes#define	TDQ_LOCKPTR(t)		((t)->tdq_lock)
2701573Srgrimes
2711573Srgrimesstatic void sched_priority(struct thread *);
2721573Srgrimesstatic void sched_thread_priority(struct thread *, u_char);
2731573Srgrimesstatic int sched_interact_score(struct thread *);
2741573Srgrimesstatic void sched_interact_update(struct thread *);
2751573Srgrimesstatic void sched_interact_fork(struct thread *);
276189291Sdelphijstatic void sched_pctcpu_update(struct td_sched *);
277189291Sdelphij
278189291Sdelphij/* Operations on per processor queues */
279189291Sdelphijstatic struct td_sched * tdq_choose(struct tdq *);
280189291Sdelphijstatic void tdq_setup(struct tdq *);
281189291Sdelphijstatic void tdq_load_add(struct tdq *, struct td_sched *);
2821573Srgrimesstatic void tdq_load_rem(struct tdq *, struct td_sched *);
283189291Sdelphijstatic __inline void tdq_runq_add(struct tdq *, struct td_sched *, int);
284189291Sdelphijstatic __inline void tdq_runq_rem(struct tdq *, struct td_sched *);
285189291Sdelphijvoid tdq_print(int cpu);
286189291Sdelphijstatic void runq_print(struct runq *rq);
2871573Srgrimesstatic void tdq_add(struct tdq *, struct thread *, int);
2881573Srgrimes#ifdef SMP
2891573Srgrimesstatic void tdq_move(struct tdq *, struct tdq *);
2901573Srgrimesstatic int tdq_idled(struct tdq *);
29114287Spststatic void tdq_notify(struct td_sched *);
2921573Srgrimesstatic struct td_sched *tdq_steal(struct tdq *, int);
2931573Srgrimesstatic struct td_sched *runq_steal(struct runq *);
2941573Srgrimesstatic int sched_pickcpu(struct td_sched *, int);
29514287Spststatic void sched_balance(void *);
29614287Spststatic void sched_balance_groups(void *);
29714287Spststatic void sched_balance_group(struct tdq_group *);
2981573Srgrimesstatic void sched_balance_pair(struct tdq *, struct tdq *);
29914287Spststatic inline struct tdq *sched_setcpu(struct td_sched *, int, int);
3001573Srgrimesstatic inline struct mtx *thread_block_switch(struct thread *);
3011573Srgrimesstatic inline void thread_unblock_switch(struct thread *, struct mtx *);
3021573Srgrimesstatic struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
3031573Srgrimes
3041573Srgrimes#define	THREAD_CAN_MIGRATE(td)	 ((td)->td_pinned == 0)
3051573Srgrimes#endif
3061573Srgrimes
3071573Srgrimesstatic void sched_setup(void *dummy);
3081573SrgrimesSYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
3091573Srgrimes
31014287Spststatic void sched_initticks(void *dummy);
3111573SrgrimesSYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks, NULL)
3121573Srgrimes
3131573Srgrimes/*
31414287Spst * Print the threads waiting on a run-queue.
3151573Srgrimes */
3161573Srgrimesstatic void
3171573Srgrimesrunq_print(struct runq *rq)
3181573Srgrimes{
31914287Spst	struct rqhead *rqh;
3201573Srgrimes	struct td_sched *ts;
3211573Srgrimes	int pri;
3221573Srgrimes	int j;
3231573Srgrimes	int i;
3241573Srgrimes
3251573Srgrimes	for (i = 0; i < RQB_LEN; i++) {
3261573Srgrimes		printf("\t\trunq bits %d 0x%zx\n",
3271573Srgrimes		    i, rq->rq_status.rqb_bits[i]);
3281573Srgrimes		for (j = 0; j < RQB_BPW; j++)
32914287Spst			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
3301573Srgrimes				pri = j + (i << RQB_L2BPW);
3311573Srgrimes				rqh = &rq->rq_queues[pri];
3321573Srgrimes				TAILQ_FOREACH(ts, rqh, ts_procq) {
3331573Srgrimes					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
3341573Srgrimes					    ts->ts_thread, ts->ts_thread->td_proc->p_comm, ts->ts_thread->td_priority, ts->ts_rqindex, pri);
3351573Srgrimes				}
33614287Spst			}
3371573Srgrimes	}
3381573Srgrimes}
3391573Srgrimes
3401573Srgrimes/*
3411573Srgrimes * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
3421573Srgrimes */
3431573Srgrimesvoid
3441573Srgrimestdq_print(int cpu)
3451573Srgrimes{
3461573Srgrimes	struct tdq *tdq;
3471573Srgrimes
3481573Srgrimes	tdq = TDQ_CPU(cpu);
3491573Srgrimes
3501573Srgrimes	printf("tdq %d:\n", TDQ_ID(tdq));
3511573Srgrimes	printf("\tlockptr         %p\n", TDQ_LOCKPTR(tdq));
3521573Srgrimes	printf("\tload:           %d\n", tdq->tdq_load);
3531573Srgrimes	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
3541573Srgrimes	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
3551573Srgrimes	printf("\trealtime runq:\n");
3561573Srgrimes	runq_print(&tdq->tdq_realtime);
3571573Srgrimes	printf("\ttimeshare runq:\n");
3581573Srgrimes	runq_print(&tdq->tdq_timeshare);
3591573Srgrimes	printf("\tidle runq:\n");
3601573Srgrimes	runq_print(&tdq->tdq_idle);
3611573Srgrimes#ifdef SMP
3621573Srgrimes	printf("\tload transferable: %d\n", tdq->tdq_transferable);
3631573Srgrimes	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
36414287Spst	printf("\tgroup:             %d\n", TDG_ID(tdq->tdq_group));
3651573Srgrimes	printf("\tLock name:         %s\n", tdq->tdq_group->tdg_name);
3661573Srgrimes#endif
3671573Srgrimes}
3681573Srgrimes
3691573Srgrimes#define	TS_RQ_PPQ	(((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
3701573Srgrimes/*
3711573Srgrimes * Add a thread to the actual run-queue.  Keeps transferable counts up to
3721573Srgrimes * date with what is actually on the run-queue.  Selects the correct
3731573Srgrimes * queue position for timeshare threads.
3741573Srgrimes */
3751573Srgrimesstatic __inline void
3761573Srgrimestdq_runq_add(struct tdq *tdq, struct td_sched *ts, int flags)
37714287Spst{
3781573Srgrimes	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
3791573Srgrimes	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
3801573Srgrimes#ifdef SMP
3811573Srgrimes	if (THREAD_CAN_MIGRATE(ts->ts_thread)) {
3821573Srgrimes		tdq->tdq_transferable++;
3831573Srgrimes		tdq->tdq_group->tdg_transferable++;
3841573Srgrimes		ts->ts_flags |= TSF_XFERABLE;
3851573Srgrimes	}
3861573Srgrimes#endif
3871573Srgrimes	if (ts->ts_runq == &tdq->tdq_timeshare) {
3881573Srgrimes		u_char pri;
3891573Srgrimes
3901573Srgrimes		pri = ts->ts_thread->td_priority;
3911573Srgrimes		KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
3921573Srgrimes			("Invalid priority %d on timeshare runq", pri));
3931573Srgrimes		/*
3941573Srgrimes		 * This queue contains only priorities between MIN and MAX
3951573Srgrimes		 * realtime.  Use the whole queue to represent these values.
396189291Sdelphij		 */
397189291Sdelphij		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
3981573Srgrimes			pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
39992889Sobrien			pri = (pri + tdq->tdq_idx) % RQ_NQS;
4001573Srgrimes			/*
4011573Srgrimes			 * This effectively shortens the queue by one so we
40214287Spst			 * can have a one slot difference between idx and
4031573Srgrimes			 * ridx while we wait for threads to drain.
4041573Srgrimes			 */
4051573Srgrimes			if (tdq->tdq_ridx != tdq->tdq_idx &&
4061573Srgrimes			    pri == tdq->tdq_ridx)
4071573Srgrimes				pri = (unsigned char)(pri - 1) % RQ_NQS;
4081573Srgrimes		} else
4091573Srgrimes			pri = tdq->tdq_ridx;
4101573Srgrimes		runq_add_pri(ts->ts_runq, ts, pri, flags);
4111573Srgrimes	} else
4121573Srgrimes		runq_add(ts->ts_runq, ts, flags);
4131573Srgrimes}
41414287Spst
415190490Sdelphij/*
416190490Sdelphij * Remove a thread from a run-queue.  This typically happens when a thread
417190490Sdelphij * is selected to run.  Running threads are not on the queue and the
418190490Sdelphij * transferable count does not reflect them.
4191573Srgrimes */
420190490Sdelphijstatic __inline void
421190490Sdelphijtdq_runq_rem(struct tdq *tdq, struct td_sched *ts)
4221573Srgrimes{
423190490Sdelphij	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
4241573Srgrimes	KASSERT(ts->ts_runq != NULL,
4251573Srgrimes	    ("tdq_runq_remove: thread %p null ts_runq", ts->ts_thread));
4261573Srgrimes#ifdef SMP
4271573Srgrimes	if (ts->ts_flags & TSF_XFERABLE) {
42814287Spst		tdq->tdq_transferable--;
4291573Srgrimes		tdq->tdq_group->tdg_transferable--;
430190490Sdelphij		ts->ts_flags &= ~TSF_XFERABLE;
4311573Srgrimes	}
4321573Srgrimes#endif
4331573Srgrimes	if (ts->ts_runq == &tdq->tdq_timeshare) {
4341573Srgrimes		if (tdq->tdq_idx != tdq->tdq_ridx)
4351573Srgrimes			runq_remove_idx(ts->ts_runq, ts, &tdq->tdq_ridx);
4361573Srgrimes		else
4371573Srgrimes			runq_remove_idx(ts->ts_runq, ts, NULL);
4381573Srgrimes		/*
43914287Spst		 * For timeshare threads we update the priority here so
4401573Srgrimes		 * the priority reflects the time we've been sleeping.
4411573Srgrimes		 */
4421573Srgrimes		ts->ts_ltick = ticks;
4431573Srgrimes		sched_pctcpu_update(ts);
4441573Srgrimes		sched_priority(ts->ts_thread);
4451573Srgrimes	} else
4461573Srgrimes		runq_remove(ts->ts_runq, ts);
447190490Sdelphij}
4481573Srgrimes
4491573Srgrimes/*
4501573Srgrimes * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
4511573Srgrimes * for this thread to the referenced thread queue.
4521573Srgrimes */
4531573Srgrimesstatic void
4541573Srgrimestdq_load_add(struct tdq *tdq, struct td_sched *ts)
4551573Srgrimes{
4561573Srgrimes	int class;
4571573Srgrimes
4581573Srgrimes	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
4591573Srgrimes	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
4601573Srgrimes	class = PRI_BASE(ts->ts_thread->td_pri_class);
4611573Srgrimes	tdq->tdq_load++;
4621573Srgrimes	CTR2(KTR_SCHED, "cpu %d load: %d", TDQ_ID(tdq), tdq->tdq_load);
4631573Srgrimes	if (class != PRI_ITHD &&
4641573Srgrimes	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
4651573Srgrimes#ifdef SMP
466189291Sdelphij		tdq->tdq_group->tdg_load++;
467189291Sdelphij#else
4681573Srgrimes		tdq->tdq_sysload++;
469190489Sdelphij#endif
4701573Srgrimes}
4711573Srgrimes
4721573Srgrimes/*
47314287Spst * Remove the load from a thread that is transitioning to a sleep state or
4741573Srgrimes * exiting.
4751573Srgrimes */
4761573Srgrimesstatic void
4771573Srgrimestdq_load_rem(struct tdq *tdq, struct td_sched *ts)
4781573Srgrimes{
4791573Srgrimes	int class;
4801573Srgrimes
4811573Srgrimes	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
4821573Srgrimes	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
4831573Srgrimes	class = PRI_BASE(ts->ts_thread->td_pri_class);
4841573Srgrimes	if (class != PRI_ITHD &&
4851573Srgrimes	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
4861573Srgrimes#ifdef SMP
4871573Srgrimes		tdq->tdq_group->tdg_load--;
4881573Srgrimes#else
4891573Srgrimes		tdq->tdq_sysload--;
4901573Srgrimes#endif
4911573Srgrimes	KASSERT(tdq->tdq_load != 0,
4921573Srgrimes	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
4931573Srgrimes	tdq->tdq_load--;
4941573Srgrimes	CTR1(KTR_SCHED, "load: %d", tdq->tdq_load);
4951573Srgrimes	ts->ts_runq = NULL;
4961573Srgrimes}
4971573Srgrimes
4981573Srgrimes#ifdef SMP
4991573Srgrimes/*
5001573Srgrimes * sched_balance is a simple CPU load balancing algorithm.  It operates by
5011573Srgrimes * finding the least loaded and most loaded cpu and equalizing their load
5021573Srgrimes * by migrating some processes.
5031573Srgrimes *
5041573Srgrimes * Dealing only with two CPUs at a time has two advantages.  Firstly, most
5051573Srgrimes * installations will only have 2 cpus.  Secondly, load balancing too much at
5061573Srgrimes * once can have an unpleasant effect on the system.  The scheduler rarely has
5071573Srgrimes * enough information to make perfect decisions.  So this algorithm chooses
5081573Srgrimes * simplicity and more gradual effects on load in larger systems.
5091573Srgrimes *
5101573Srgrimes */
5111573Srgrimesstatic void
5121573Srgrimessched_balance(void *arg)
5131573Srgrimes{
5141573Srgrimes	struct tdq_group *high;
5151573Srgrimes	struct tdq_group *low;
516189291Sdelphij	struct tdq_group *tdg;
517189291Sdelphij	int cnt;
518189291Sdelphij	int i;
5191573Srgrimes
520190489Sdelphij	callout_reset(&balco, max(hz / 2, random() % (hz * balance_secs)),
52114287Spst	    sched_balance, NULL);
5221573Srgrimes	if (smp_started == 0 || rebalance == 0)
5231573Srgrimes		return;
5241573Srgrimes	low = high = NULL;
5251573Srgrimes	i = random() % (tdg_maxid + 1);
5261573Srgrimes	for (cnt = 0; cnt <= tdg_maxid; cnt++) {
5271573Srgrimes		tdg = TDQ_GROUP(i);
5281573Srgrimes		/*
5291573Srgrimes		 * Find the CPU with the highest load that has some
5301573Srgrimes		 * threads to transfer.
5311573Srgrimes		 */
5321573Srgrimes		if ((high == NULL || tdg->tdg_load > high->tdg_load)
5331573Srgrimes		    && tdg->tdg_transferable)
534190486Sdelphij			high = tdg;
5351573Srgrimes		if (low == NULL || tdg->tdg_load < low->tdg_load)
53614287Spst			low = tdg;
5371573Srgrimes		if (++i > tdg_maxid)
5381573Srgrimes			i = 0;
5391573Srgrimes	}
5401573Srgrimes	if (low != NULL && high != NULL && high != low)
5411573Srgrimes		sched_balance_pair(LIST_FIRST(&high->tdg_members),
5421573Srgrimes		    LIST_FIRST(&low->tdg_members));
5431573Srgrimes}
5441573Srgrimes
5451573Srgrimes/*
5461573Srgrimes * Balance load between CPUs in a group.  Will only migrate within the group.
5471573Srgrimes */
54892889Sobrienstatic void
5491573Srgrimessched_balance_groups(void *arg)
5501573Srgrimes{
5511573Srgrimes	int i;
5521573Srgrimes
55314287Spst	callout_reset(&gbalco, max(hz / 2, random() % (hz * balance_secs)),
5541573Srgrimes	    sched_balance_groups, NULL);
5551573Srgrimes	if (smp_started == 0 || rebalance == 0)
5561573Srgrimes		return;
5571573Srgrimes	for (i = 0; i <= tdg_maxid; i++)
5581573Srgrimes		sched_balance_group(TDQ_GROUP(i));
5591573Srgrimes}
5601573Srgrimes
5611573Srgrimes/*
5621573Srgrimes * Finds the greatest imbalance between two tdqs in a group.
5631573Srgrimes */
5641573Srgrimesstatic void
5651573Srgrimessched_balance_group(struct tdq_group *tdg)
5661573Srgrimes{
5671573Srgrimes	struct tdq *tdq;
5681573Srgrimes	struct tdq *high;
5691573Srgrimes	struct tdq *low;
5701573Srgrimes	int load;
571189291Sdelphij
572189291Sdelphij	if (tdg->tdg_transferable == 0)
5731573Srgrimes		return;
574190489Sdelphij	low = NULL;
5751573Srgrimes	high = NULL;
5761573Srgrimes	LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
5771573Srgrimes		load = tdq->tdq_load;
5781573Srgrimes		if (high == NULL || load > high->tdq_load)
5791573Srgrimes			high = tdq;
5801573Srgrimes		if (low == NULL || load < low->tdq_load)
5811573Srgrimes			low = tdq;
582190489Sdelphij	}
5831573Srgrimes	if (high != NULL && low != NULL && high != low)
5841573Srgrimes		sched_balance_pair(high, low);
5851573Srgrimes}
5861573Srgrimes
58714287Spst/*
5881573Srgrimes * Lock two thread queues using their address to maintain lock order.
58914287Spst */
5901573Srgrimesstatic void
59114287Spsttdq_lock_pair(struct tdq *one, struct tdq *two)
5921573Srgrimes{
5931573Srgrimes	if (one < two) {
5941573Srgrimes		TDQ_LOCK(one);
5951573Srgrimes		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
5961573Srgrimes	} else {
5971573Srgrimes		TDQ_LOCK(two);
598190486Sdelphij		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
5991573Srgrimes	}
6001573Srgrimes}
6011573Srgrimes
6021573Srgrimes/*
6031573Srgrimes * Transfer load between two imbalanced thread queues.
6041573Srgrimes */
6051573Srgrimesstatic void
6061573Srgrimessched_balance_pair(struct tdq *high, struct tdq *low)
6071573Srgrimes{
6081573Srgrimes	int transferable;
6091573Srgrimes	int high_load;
6101573Srgrimes	int low_load;
6111573Srgrimes	int move;
6121573Srgrimes	int diff;
613189291Sdelphij	int i;
614189291Sdelphij
6151573Srgrimes	tdq_lock_pair(high, low);
61614287Spst	/*
6171573Srgrimes	 * If we're transfering within a group we have to use this specific
6181573Srgrimes	 * tdq's transferable count, otherwise we can steal from other members
61914287Spst	 * of the group.
6201573Srgrimes	 */
6211573Srgrimes	if (high->tdq_group == low->tdq_group) {
6221573Srgrimes		transferable = high->tdq_transferable;
6231573Srgrimes		high_load = high->tdq_load;
6241573Srgrimes		low_load = low->tdq_load;
6251573Srgrimes	} else {
6261573Srgrimes		transferable = high->tdq_group->tdg_transferable;
6271573Srgrimes		high_load = high->tdq_group->tdg_load;
6281573Srgrimes		low_load = low->tdq_group->tdg_load;
62914287Spst	}
6301573Srgrimes	/*
6311573Srgrimes	 * Determine what the imbalance is and then adjust that to how many
6321573Srgrimes	 * threads we actually have to give up (transferable).
6331573Srgrimes	 */
63414287Spst	if (transferable != 0) {
635189291Sdelphij		diff = high_load - low_load;
6361573Srgrimes		move = diff / 2;
63792889Sobrien		if (diff & 0x1)
6381573Srgrimes			move++;
6391573Srgrimes		move = min(move, transferable);
6401573Srgrimes		for (i = 0; i < move; i++)
6411573Srgrimes			tdq_move(high, low);
6421573Srgrimes	}
6431573Srgrimes	TDQ_UNLOCK(high);
6441573Srgrimes	TDQ_UNLOCK(low);
6451573Srgrimes	return;
6461573Srgrimes}
6471573Srgrimes
64814287Spst/*
649189291Sdelphij * Move a thread from one thread queue to another.
6501573Srgrimes */
65192889Sobrienstatic void
65292889Sobrientdq_move(struct tdq *from, struct tdq *to)
65314287Spst{
6541573Srgrimes	struct td_sched *ts;
6551573Srgrimes	struct thread *td;
6561573Srgrimes	struct tdq *tdq;
6571573Srgrimes	int cpu;
6581573Srgrimes
6591573Srgrimes	tdq = from;
6601573Srgrimes	cpu = TDQ_ID(to);
6611573Srgrimes	ts = tdq_steal(tdq, 1);
6621573Srgrimes	if (ts == NULL) {
6631573Srgrimes		struct tdq_group *tdg;
6641573Srgrimes
6651573Srgrimes		tdg = tdq->tdq_group;
6661573Srgrimes		LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
66714287Spst			if (tdq == from || tdq->tdq_transferable == 0)
6681573Srgrimes				continue;
66914287Spst			ts = tdq_steal(tdq, 1);
6701573Srgrimes			break;
6711573Srgrimes		}
6721573Srgrimes		if (ts == NULL)
6731573Srgrimes			return;
6748870Srgrimes	}
6751573Srgrimes	if (tdq == to)
6761573Srgrimes		return;
6771573Srgrimes	td = ts->ts_thread;
6781573Srgrimes	/*
6791573Srgrimes	 * Although the run queue is locked the thread may be blocked.  Lock
6801573Srgrimes	 * it to clear this.
6811573Srgrimes	 */
6821573Srgrimes	thread_lock(td);
6831573Srgrimes	/* Drop recursive lock on from. */
6841573Srgrimes	TDQ_UNLOCK(from);
6851573Srgrimes	sched_rem(td);
6861573Srgrimes	ts->ts_cpu = cpu;
6871573Srgrimes	td->td_lock = TDQ_LOCKPTR(to);
6881573Srgrimes	tdq_add(to, td, SRQ_YIELDING);
6891573Srgrimes	tdq_notify(ts);
6901573Srgrimes}
6911573Srgrimes
6921573Srgrimes/*
6931573Srgrimes * This tdq has idled.  Try to steal a thread from another cpu and switch
6941573Srgrimes * to it.
6951573Srgrimes */
6961573Srgrimesstatic int
6971573Srgrimestdq_idled(struct tdq *tdq)
69856698Sjasone{
699190487Sdelphij	struct tdq_group *tdg;
70014287Spst	struct tdq *steal;
7011573Srgrimes	struct td_sched *ts;
7021573Srgrimes	struct thread *td;
7031573Srgrimes	int highload;
7041573Srgrimes	int highcpu;
7051573Srgrimes	int load;
7061573Srgrimes	int cpu;
7071573Srgrimes
7081573Srgrimes	/* We don't want to be preempted while we're iterating over tdqs */
7091573Srgrimes	spinlock_enter();
7101573Srgrimes	tdg = tdq->tdq_group;
7111573Srgrimes	/*
71256698Sjasone	 * If we're in a cpu group, try and steal threads from another cpu in
713190487Sdelphij	 * the group before idling.
71414287Spst	 */
7151573Srgrimes	if (steal_htt && tdg->tdg_cpus > 1 && tdg->tdg_transferable) {
7161573Srgrimes		LIST_FOREACH(steal, &tdg->tdg_members, tdq_siblings) {
7171573Srgrimes			if (steal == tdq || steal->tdq_transferable == 0)
7181573Srgrimes				continue;
7191573Srgrimes			TDQ_LOCK(steal);
7201573Srgrimes			ts = tdq_steal(steal, 0);
7211573Srgrimes			if (ts)
7221573Srgrimes				goto steal;
7231573Srgrimes			TDQ_UNLOCK(steal);
7241573Srgrimes		}
7251573Srgrimes	}
7261573Srgrimes	for (;;) {
72714287Spst		if (steal_idle == 0)
72814287Spst			break;
72914287Spst		highcpu = 0;
7301573Srgrimes		highload = 0;
7311573Srgrimes		for (cpu = 0; cpu <= mp_maxid; cpu++) {
7321573Srgrimes			if (CPU_ABSENT(cpu))
7331573Srgrimes				continue;
7341573Srgrimes			steal = TDQ_CPU(cpu);
7351573Srgrimes			load = TDQ_CPU(cpu)->tdq_transferable;
7361573Srgrimes			if (load < highload)
73756698Sjasone				continue;
7381573Srgrimes			highload = load;
739190487Sdelphij			highcpu = cpu;
74014287Spst		}
7411573Srgrimes		if (highload < steal_thresh)
7421573Srgrimes			break;
7431573Srgrimes		steal = TDQ_CPU(highcpu);
7441573Srgrimes		TDQ_LOCK(steal);
7451573Srgrimes		if (steal->tdq_transferable >= steal_thresh &&
7461573Srgrimes		    (ts = tdq_steal(steal, 1)) != NULL)
7471573Srgrimes			goto steal;
7481573Srgrimes		TDQ_UNLOCK(steal);
7491573Srgrimes		break;
7501573Srgrimes	}
7511573Srgrimes	spinlock_exit();
7521573Srgrimes	return (1);
7531573Srgrimessteal:
7541573Srgrimes	td = ts->ts_thread;
7551573Srgrimes	thread_lock(td);
7561573Srgrimes	spinlock_exit();
7571573Srgrimes	MPASS(td->td_lock == TDQ_LOCKPTR(steal));
7581573Srgrimes	TDQ_UNLOCK(steal);
7591573Srgrimes	sched_rem(td);
7601573Srgrimes	sched_setcpu(ts, PCPU_GET(cpuid), SRQ_YIELDING);
7611573Srgrimes	tdq_add(tdq, td, SRQ_YIELDING);
7621573Srgrimes	MPASS(td->td_lock == curthread->td_lock);
7631573Srgrimes	mi_switch(SW_VOL, NULL);
7641573Srgrimes	thread_unlock(curthread);
7651573Srgrimes
7661573Srgrimes	return (0);
7671573Srgrimes}
7681573Srgrimes
7691573Srgrimes/*
7701573Srgrimes * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
7711573Srgrimes */
7721573Srgrimesstatic void
7731573Srgrimestdq_notify(struct td_sched *ts)
7741573Srgrimes{
7751573Srgrimes	struct thread *ctd;
7761573Srgrimes	struct pcpu *pcpu;
7771573Srgrimes	int cpri;
7781573Srgrimes	int pri;
7791573Srgrimes	int cpu;
7801573Srgrimes
7811573Srgrimes	cpu = ts->ts_cpu;
7821573Srgrimes	pri = ts->ts_thread->td_priority;
783190487Sdelphij	pcpu = pcpu_find(cpu);
784190487Sdelphij	ctd = pcpu->pc_curthread;
785190487Sdelphij	cpri = ctd->td_priority;
78614287Spst
787190487Sdelphij	/*
7881573Srgrimes	 * If our priority is not better than the current priority there is
7891573Srgrimes	 * nothing to do.
7901573Srgrimes	 */
7911573Srgrimes	if (pri > cpri)
7921573Srgrimes		return;
7931573Srgrimes	/*
7941573Srgrimes	 * Always IPI idle.
7951573Srgrimes	 */
7961573Srgrimes	if (cpri > PRI_MIN_IDLE)
7971573Srgrimes		goto sendipi;
7981573Srgrimes	/*
7991573Srgrimes	 * If we're realtime or better and there is timeshare or worse running
8001573Srgrimes	 * send an IPI.
801189291Sdelphij	 */
802189291Sdelphij	if (pri < PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
8031573Srgrimes		goto sendipi;
80492889Sobrien	/*
80514287Spst	 * Otherwise only IPI if we exceed the threshold.
8061573Srgrimes	 */
80714287Spst	if (pri > preempt_thresh)
8081573Srgrimes		return;
8091573Srgrimessendipi:
8101573Srgrimes	ctd->td_flags |= TDF_NEEDRESCHED;
8111573Srgrimes	ipi_selected(1 << cpu, IPI_PREEMPT);
8121573Srgrimes}
81314287Spst
8141573Srgrimes/*
8151573Srgrimes * Steals load from a timeshare queue.  Honors the rotating queue head
8161573Srgrimes * index.
8171573Srgrimes */
8181573Srgrimesstatic struct td_sched *
8191573Srgrimesrunq_steal_from(struct runq *rq, u_char start)
8201573Srgrimes{
8211573Srgrimes	struct td_sched *ts;
8221573Srgrimes	struct rqbits *rqb;
8231573Srgrimes	struct rqhead *rqh;
8241573Srgrimes	int first;
8251573Srgrimes	int bit;
8261573Srgrimes	int pri;
8271573Srgrimes	int i;
8281573Srgrimes
8291573Srgrimes	rqb = &rq->rq_status;
8301573Srgrimes	bit = start & (RQB_BPW -1);
8311573Srgrimes	pri = 0;
8321573Srgrimes	first = 0;
8331573Srgrimesagain:
8341573Srgrimes	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
8351573Srgrimes		if (rqb->rqb_bits[i] == 0)
8361573Srgrimes			continue;
8371573Srgrimes		if (bit != 0) {
8381573Srgrimes			for (pri = bit; pri < RQB_BPW; pri++)
8391573Srgrimes				if (rqb->rqb_bits[i] & (1ul << pri))
8401573Srgrimes					break;
8411573Srgrimes			if (pri >= RQB_BPW)
8421573Srgrimes				continue;
8431573Srgrimes		} else
8441573Srgrimes			pri = RQB_FFS(rqb->rqb_bits[i]);
8451573Srgrimes		pri += (i << RQB_L2BPW);
846189291Sdelphij		rqh = &rq->rq_queues[pri];
8471573Srgrimes		TAILQ_FOREACH(ts, rqh, ts_procq) {
8481573Srgrimes			if (first && THREAD_CAN_MIGRATE(ts->ts_thread))
849190485Sdelphij				return (ts);
850190485Sdelphij			first = 1;
851190485Sdelphij		}
8521573Srgrimes	}
853190485Sdelphij	if (start != 0) {
854190485Sdelphij		start = 0;
855190485Sdelphij		goto again;
856190485Sdelphij	}
857190500Sdelphij
858190485Sdelphij	return (NULL);
859190485Sdelphij}
860190485Sdelphij
861190485Sdelphij/*
8621573Srgrimes * Steals load from a standard linear queue.
8631573Srgrimes */
86471579Sdeischenstatic struct td_sched *
865190485Sdelphijrunq_steal(struct runq *rq)
866190485Sdelphij{
86756698Sjasone	struct rqhead *rqh;
8681573Srgrimes	struct rqbits *rqb;
86971579Sdeischen	struct td_sched *ts;
8701573Srgrimes	int word;
8711573Srgrimes	int bit;
8721573Srgrimes
8731573Srgrimes	rqb = &rq->rq_status;
8741573Srgrimes	for (word = 0; word < RQB_LEN; word++) {
8751573Srgrimes		if (rqb->rqb_bits[word] == 0)
8761573Srgrimes			continue;
8771573Srgrimes		for (bit = 0; bit < RQB_BPW; bit++) {
878189291Sdelphij			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
8791573Srgrimes				continue;
88092889Sobrien			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
88114287Spst			TAILQ_FOREACH(ts, rqh, ts_procq)
8821573Srgrimes				if (THREAD_CAN_MIGRATE(ts->ts_thread))
8831573Srgrimes					return (ts);
8841573Srgrimes		}
8851573Srgrimes	}
8861573Srgrimes	return (NULL);
8871573Srgrimes}
8881573Srgrimes
8891573Srgrimes/*
8901573Srgrimes * Attempt to steal a thread in priority order from a thread queue.
8911573Srgrimes */
8921573Srgrimesstatic struct td_sched *
8931573Srgrimestdq_steal(struct tdq *tdq, int stealidle)
8941573Srgrimes{
8951573Srgrimes	struct td_sched *ts;
8961573Srgrimes
8971573Srgrimes	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
8981573Srgrimes	if ((ts = runq_steal(&tdq->tdq_realtime)) != NULL)
8991573Srgrimes		return (ts);
9001573Srgrimes	if ((ts = runq_steal_from(&tdq->tdq_timeshare, tdq->tdq_ridx)) != NULL)
9011573Srgrimes		return (ts);
90214287Spst	if (stealidle)
903189291Sdelphij		return (runq_steal(&tdq->tdq_idle));
9041573Srgrimes	return (NULL);
9051573Srgrimes}
9061573Srgrimes
90714287Spst/*
9081573Srgrimes * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
9091573Srgrimes * current lock and returns with the assigned queue locked.  If this is
9101573Srgrimes * via sched_switch() we leave the thread in a blocked state as an
9111573Srgrimes * optimization.
9121573Srgrimes */
9131573Srgrimesstatic inline struct tdq *
9141573Srgrimessched_setcpu(struct td_sched *ts, int cpu, int flags)
9151573Srgrimes{
9161573Srgrimes	struct thread *td;
9171573Srgrimes	struct tdq *tdq;
9181573Srgrimes
919189291Sdelphij	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
9201573Srgrimes
9211573Srgrimes	tdq = TDQ_CPU(cpu);
9221573Srgrimes	td = ts->ts_thread;
9231573Srgrimes	ts->ts_cpu = cpu;
9241573Srgrimes
9251573Srgrimes	/* If the lock matches just return the queue. */
9261573Srgrimes	if (td->td_lock == TDQ_LOCKPTR(tdq))
9271573Srgrimes		return (tdq);
9281573Srgrimes#ifdef notyet
9291573Srgrimes	/*
9301573Srgrimes	 * If the thread isn't running it's lockptr is a
9311573Srgrimes	 * turnstile or a sleepqueue.  We can just lock_set without
9321573Srgrimes	 * blocking.
9331573Srgrimes	 */
9341573Srgrimes	if (TD_CAN_RUN(td)) {
9351573Srgrimes		TDQ_LOCK(tdq);
9361573Srgrimes		thread_lock_set(td, TDQ_LOCKPTR(tdq));
937		return (tdq);
938	}
939#endif
940	/*
941	 * The hard case, migration, we need to block the thread first to
942	 * prevent order reversals with other cpus locks.
943	 */
944	thread_lock_block(td);
945	TDQ_LOCK(tdq);
946	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
947	return (tdq);
948}
949
950/*
951 * Find the thread queue running the lowest priority thread.
952 */
953static int
954tdq_lowestpri(void)
955{
956	struct tdq *tdq;
957	int lowpri;
958	int lowcpu;
959	int lowload;
960	int load;
961	int cpu;
962	int pri;
963
964	lowload = 0;
965	lowpri = lowcpu = 0;
966	for (cpu = 0; cpu <= mp_maxid; cpu++) {
967		if (CPU_ABSENT(cpu))
968			continue;
969		tdq = TDQ_CPU(cpu);
970		pri = tdq->tdq_lowpri;
971		load = TDQ_CPU(cpu)->tdq_load;
972		CTR4(KTR_ULE,
973		    "cpu %d pri %d lowcpu %d lowpri %d",
974		    cpu, pri, lowcpu, lowpri);
975		if (pri < lowpri)
976			continue;
977		if (lowpri && lowpri == pri && load > lowload)
978			continue;
979		lowpri = pri;
980		lowcpu = cpu;
981		lowload = load;
982	}
983
984	return (lowcpu);
985}
986
987/*
988 * Find the thread queue with the least load.
989 */
990static int
991tdq_lowestload(void)
992{
993	struct tdq *tdq;
994	int lowload;
995	int lowpri;
996	int lowcpu;
997	int load;
998	int cpu;
999	int pri;
1000
1001	lowcpu = 0;
1002	lowload = TDQ_CPU(0)->tdq_load;
1003	lowpri = TDQ_CPU(0)->tdq_lowpri;
1004	for (cpu = 1; cpu <= mp_maxid; cpu++) {
1005		if (CPU_ABSENT(cpu))
1006			continue;
1007		tdq = TDQ_CPU(cpu);
1008		load = tdq->tdq_load;
1009		pri = tdq->tdq_lowpri;
1010		CTR4(KTR_ULE, "cpu %d load %d lowcpu %d lowload %d",
1011		    cpu, load, lowcpu, lowload);
1012		if (load > lowload)
1013			continue;
1014		if (load == lowload && pri < lowpri)
1015			continue;
1016		lowcpu = cpu;
1017		lowload = load;
1018		lowpri = pri;
1019	}
1020
1021	return (lowcpu);
1022}
1023
1024/*
1025 * Pick the destination cpu for sched_add().  Respects affinity and makes
1026 * a determination based on load or priority of available processors.
1027 */
1028static int
1029sched_pickcpu(struct td_sched *ts, int flags)
1030{
1031	struct tdq *tdq;
1032	int self;
1033	int pri;
1034	int cpu;
1035
1036	cpu = self = PCPU_GET(cpuid);
1037	if (smp_started == 0)
1038		return (self);
1039	/*
1040	 * Don't migrate a running thread from sched_switch().
1041	 */
1042	if (flags & SRQ_OURSELF) {
1043		CTR1(KTR_ULE, "YIELDING %d",
1044		    curthread->td_priority);
1045		return (self);
1046	}
1047	pri = ts->ts_thread->td_priority;
1048	cpu = ts->ts_cpu;
1049	/*
1050	 * Regardless of affinity, if the last cpu is idle send it there.
1051	 */
1052	tdq = TDQ_CPU(cpu);
1053	if (tdq->tdq_lowpri > PRI_MIN_IDLE) {
1054		CTR5(KTR_ULE,
1055		    "ts_cpu %d idle, ltick %d ticks %d pri %d curthread %d",
1056		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1057		    tdq->tdq_lowpri);
1058		return (ts->ts_cpu);
1059	}
1060	/*
1061	 * If we have affinity, try to place it on the cpu we last ran on.
1062	 */
1063	if (SCHED_AFFINITY(ts) && tdq->tdq_lowpri > pri) {
1064		CTR5(KTR_ULE,
1065		    "affinity for %d, ltick %d ticks %d pri %d curthread %d",
1066		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1067		    tdq->tdq_lowpri);
1068		return (ts->ts_cpu);
1069	}
1070	/*
1071	 * Look for an idle group.
1072	 */
1073	CTR1(KTR_ULE, "tdq_idle %X", tdq_idle);
1074	cpu = ffs(tdq_idle);
1075	if (cpu)
1076		return (--cpu);
1077	/*
1078	 * If there are no idle cores see if we can run the thread locally.  This may
1079	 * improve locality among sleepers and wakers when there is shared data.
1080	 */
1081	if (tryself && pri < curthread->td_priority) {
1082		CTR1(KTR_ULE, "tryself %d",
1083		    curthread->td_priority);
1084		return (self);
1085	}
1086	/*
1087 	 * Now search for the cpu running the lowest priority thread with
1088	 * the least load.
1089	 */
1090	if (pick_pri)
1091		cpu = tdq_lowestpri();
1092	else
1093		cpu = tdq_lowestload();
1094	return (cpu);
1095}
1096
1097#endif	/* SMP */
1098
1099/*
1100 * Pick the highest priority task we have and return it.
1101 */
1102static struct td_sched *
1103tdq_choose(struct tdq *tdq)
1104{
1105	struct td_sched *ts;
1106
1107	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1108	ts = runq_choose(&tdq->tdq_realtime);
1109	if (ts != NULL)
1110		return (ts);
1111	ts = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1112	if (ts != NULL) {
1113		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_TIMESHARE,
1114		    ("tdq_choose: Invalid priority on timeshare queue %d",
1115		    ts->ts_thread->td_priority));
1116		return (ts);
1117	}
1118
1119	ts = runq_choose(&tdq->tdq_idle);
1120	if (ts != NULL) {
1121		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_IDLE,
1122		    ("tdq_choose: Invalid priority on idle queue %d",
1123		    ts->ts_thread->td_priority));
1124		return (ts);
1125	}
1126
1127	return (NULL);
1128}
1129
1130/*
1131 * Initialize a thread queue.
1132 */
1133static void
1134tdq_setup(struct tdq *tdq)
1135{
1136
1137	if (bootverbose)
1138		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1139	runq_init(&tdq->tdq_realtime);
1140	runq_init(&tdq->tdq_timeshare);
1141	runq_init(&tdq->tdq_idle);
1142	tdq->tdq_load = 0;
1143}
1144
1145#ifdef SMP
1146static void
1147tdg_setup(struct tdq_group *tdg)
1148{
1149	if (bootverbose)
1150		printf("ULE: setup cpu group %d\n", TDG_ID(tdg));
1151	snprintf(tdg->tdg_name, sizeof(tdg->tdg_name),
1152	    "sched lock %d", (int)TDG_ID(tdg));
1153	mtx_init(&tdg->tdg_lock, tdg->tdg_name, "sched lock",
1154	    MTX_SPIN | MTX_RECURSE);
1155	LIST_INIT(&tdg->tdg_members);
1156	tdg->tdg_load = 0;
1157	tdg->tdg_transferable = 0;
1158	tdg->tdg_cpus = 0;
1159	tdg->tdg_mask = 0;
1160	tdg->tdg_cpumask = 0;
1161	tdg->tdg_idlemask = 0;
1162}
1163
1164static void
1165tdg_add(struct tdq_group *tdg, struct tdq *tdq)
1166{
1167	if (tdg->tdg_mask == 0)
1168		tdg->tdg_mask |= 1 << TDQ_ID(tdq);
1169	tdg->tdg_cpumask |= 1 << TDQ_ID(tdq);
1170	tdg->tdg_cpus++;
1171	tdq->tdq_group = tdg;
1172	tdq->tdq_lock = &tdg->tdg_lock;
1173	LIST_INSERT_HEAD(&tdg->tdg_members, tdq, tdq_siblings);
1174	if (bootverbose)
1175		printf("ULE: adding cpu %d to group %d: cpus %d mask 0x%X\n",
1176		    TDQ_ID(tdq), TDG_ID(tdg), tdg->tdg_cpus, tdg->tdg_cpumask);
1177}
1178
1179static void
1180sched_setup_topology(void)
1181{
1182	struct tdq_group *tdg;
1183	struct cpu_group *cg;
1184	int balance_groups;
1185	struct tdq *tdq;
1186	int i;
1187	int j;
1188
1189	topology = 1;
1190	balance_groups = 0;
1191	for (i = 0; i < smp_topology->ct_count; i++) {
1192		cg = &smp_topology->ct_group[i];
1193		tdg = &tdq_groups[i];
1194		/*
1195		 * Initialize the group.
1196		 */
1197		tdg_setup(tdg);
1198		/*
1199		 * Find all of the group members and add them.
1200		 */
1201		for (j = 0; j < MAXCPU; j++) {
1202			if ((cg->cg_mask & (1 << j)) != 0) {
1203				tdq = TDQ_CPU(j);
1204				tdq_setup(tdq);
1205				tdg_add(tdg, tdq);
1206			}
1207		}
1208		if (tdg->tdg_cpus > 1)
1209			balance_groups = 1;
1210	}
1211	tdg_maxid = smp_topology->ct_count - 1;
1212	if (balance_groups)
1213		sched_balance_groups(NULL);
1214}
1215
1216static void
1217sched_setup_smp(void)
1218{
1219	struct tdq_group *tdg;
1220	struct tdq *tdq;
1221	int cpus;
1222	int i;
1223
1224	for (cpus = 0, i = 0; i < MAXCPU; i++) {
1225		if (CPU_ABSENT(i))
1226			continue;
1227		tdq = &tdq_cpu[i];
1228		tdg = &tdq_groups[i];
1229		/*
1230		 * Setup a tdq group with one member.
1231		 */
1232		tdg_setup(tdg);
1233		tdq_setup(tdq);
1234		tdg_add(tdg, tdq);
1235		cpus++;
1236	}
1237	tdg_maxid = cpus - 1;
1238}
1239
1240/*
1241 * Fake a topology with one group containing all CPUs.
1242 */
1243static void
1244sched_fake_topo(void)
1245{
1246#ifdef SCHED_FAKE_TOPOLOGY
1247	static struct cpu_top top;
1248	static struct cpu_group group;
1249
1250	top.ct_count = 1;
1251	top.ct_group = &group;
1252	group.cg_mask = all_cpus;
1253	group.cg_count = mp_ncpus;
1254	group.cg_children = 0;
1255	smp_topology = &top;
1256#endif
1257}
1258#endif
1259
1260/*
1261 * Setup the thread queues and initialize the topology based on MD
1262 * information.
1263 */
1264static void
1265sched_setup(void *dummy)
1266{
1267	struct tdq *tdq;
1268
1269	tdq = TDQ_SELF();
1270#ifdef SMP
1271	/*
1272	 * Initialize long-term cpu balancing algorithm.
1273	 */
1274	callout_init(&balco, CALLOUT_MPSAFE);
1275	callout_init(&gbalco, CALLOUT_MPSAFE);
1276	sched_fake_topo();
1277	/*
1278	 * Setup tdqs based on a topology configuration or vanilla SMP based
1279	 * on mp_maxid.
1280	 */
1281	if (smp_topology == NULL)
1282		sched_setup_smp();
1283	else
1284		sched_setup_topology();
1285	sched_balance(NULL);
1286#else
1287	tdq_setup(tdq);
1288	mtx_init(&tdq_lock, "sched lock", "sched lock", MTX_SPIN | MTX_RECURSE);
1289	tdq->tdq_lock = &tdq_lock;
1290#endif
1291	/*
1292	 * To avoid divide-by-zero, we set realstathz a dummy value
1293	 * in case which sched_clock() called before sched_initticks().
1294	 */
1295	realstathz = hz;
1296	sched_slice = (realstathz/10);	/* ~100ms */
1297	tickincr = 1 << SCHED_TICK_SHIFT;
1298
1299	/* Add thread0's load since it's running. */
1300	TDQ_LOCK(tdq);
1301	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1302	tdq_load_add(tdq, &td_sched0);
1303	TDQ_UNLOCK(tdq);
1304}
1305
1306/*
1307 * This routine determines the tickincr after stathz and hz are setup.
1308 */
1309/* ARGSUSED */
1310static void
1311sched_initticks(void *dummy)
1312{
1313	int incr;
1314
1315	realstathz = stathz ? stathz : hz;
1316	sched_slice = (realstathz/10);	/* ~100ms */
1317
1318	/*
1319	 * tickincr is shifted out by 10 to avoid rounding errors due to
1320	 * hz not being evenly divisible by stathz on all platforms.
1321	 */
1322	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1323	/*
1324	 * This does not work for values of stathz that are more than
1325	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1326	 */
1327	if (incr == 0)
1328		incr = 1;
1329	tickincr = incr;
1330#ifdef SMP
1331	affinity = SCHED_AFFINITY_DEFAULT;
1332#endif
1333}
1334
1335
1336/*
1337 * This is the core of the interactivity algorithm.  Determines a score based
1338 * on past behavior.  It is the ratio of sleep time to run time scaled to
1339 * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1340 * differs from the cpu usage because it does not account for time spent
1341 * waiting on a run-queue.  Would be prettier if we had floating point.
1342 */
1343static int
1344sched_interact_score(struct thread *td)
1345{
1346	struct td_sched *ts;
1347	int div;
1348
1349	ts = td->td_sched;
1350	/*
1351	 * The score is only needed if this is likely to be an interactive
1352	 * task.  Don't go through the expense of computing it if there's
1353	 * no chance.
1354	 */
1355	if (sched_interact <= SCHED_INTERACT_HALF &&
1356		ts->ts_runtime >= ts->ts_slptime)
1357			return (SCHED_INTERACT_HALF);
1358
1359	if (ts->ts_runtime > ts->ts_slptime) {
1360		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1361		return (SCHED_INTERACT_HALF +
1362		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1363	}
1364	if (ts->ts_slptime > ts->ts_runtime) {
1365		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1366		return (ts->ts_runtime / div);
1367	}
1368	/* runtime == slptime */
1369	if (ts->ts_runtime)
1370		return (SCHED_INTERACT_HALF);
1371
1372	/*
1373	 * This can happen if slptime and runtime are 0.
1374	 */
1375	return (0);
1376
1377}
1378
1379/*
1380 * Scale the scheduling priority according to the "interactivity" of this
1381 * process.
1382 */
1383static void
1384sched_priority(struct thread *td)
1385{
1386	int score;
1387	int pri;
1388
1389	if (td->td_pri_class != PRI_TIMESHARE)
1390		return;
1391	/*
1392	 * If the score is interactive we place the thread in the realtime
1393	 * queue with a priority that is less than kernel and interrupt
1394	 * priorities.  These threads are not subject to nice restrictions.
1395	 *
1396	 * Scores greater than this are placed on the normal timeshare queue
1397	 * where the priority is partially decided by the most recent cpu
1398	 * utilization and the rest is decided by nice value.
1399	 */
1400	score = sched_interact_score(td);
1401	if (score < sched_interact) {
1402		pri = PRI_MIN_REALTIME;
1403		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1404		    * score;
1405		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1406		    ("sched_priority: invalid interactive priority %d score %d",
1407		    pri, score));
1408	} else {
1409		pri = SCHED_PRI_MIN;
1410		if (td->td_sched->ts_ticks)
1411			pri += SCHED_PRI_TICKS(td->td_sched);
1412		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1413		KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1414		    ("sched_priority: invalid priority %d: nice %d, "
1415		    "ticks %d ftick %d ltick %d tick pri %d",
1416		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1417		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1418		    SCHED_PRI_TICKS(td->td_sched)));
1419	}
1420	sched_user_prio(td, pri);
1421
1422	return;
1423}
1424
1425/*
1426 * This routine enforces a maximum limit on the amount of scheduling history
1427 * kept.  It is called after either the slptime or runtime is adjusted.  This
1428 * function is ugly due to integer math.
1429 */
1430static void
1431sched_interact_update(struct thread *td)
1432{
1433	struct td_sched *ts;
1434	u_int sum;
1435
1436	ts = td->td_sched;
1437	sum = ts->ts_runtime + ts->ts_slptime;
1438	if (sum < SCHED_SLP_RUN_MAX)
1439		return;
1440	/*
1441	 * This only happens from two places:
1442	 * 1) We have added an unusual amount of run time from fork_exit.
1443	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1444	 */
1445	if (sum > SCHED_SLP_RUN_MAX * 2) {
1446		if (ts->ts_runtime > ts->ts_slptime) {
1447			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1448			ts->ts_slptime = 1;
1449		} else {
1450			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1451			ts->ts_runtime = 1;
1452		}
1453		return;
1454	}
1455	/*
1456	 * If we have exceeded by more than 1/5th then the algorithm below
1457	 * will not bring us back into range.  Dividing by two here forces
1458	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1459	 */
1460	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1461		ts->ts_runtime /= 2;
1462		ts->ts_slptime /= 2;
1463		return;
1464	}
1465	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1466	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1467}
1468
1469/*
1470 * Scale back the interactivity history when a child thread is created.  The
1471 * history is inherited from the parent but the thread may behave totally
1472 * differently.  For example, a shell spawning a compiler process.  We want
1473 * to learn that the compiler is behaving badly very quickly.
1474 */
1475static void
1476sched_interact_fork(struct thread *td)
1477{
1478	int ratio;
1479	int sum;
1480
1481	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1482	if (sum > SCHED_SLP_RUN_FORK) {
1483		ratio = sum / SCHED_SLP_RUN_FORK;
1484		td->td_sched->ts_runtime /= ratio;
1485		td->td_sched->ts_slptime /= ratio;
1486	}
1487}
1488
1489/*
1490 * Called from proc0_init() to setup the scheduler fields.
1491 */
1492void
1493schedinit(void)
1494{
1495
1496	/*
1497	 * Set up the scheduler specific parts of proc0.
1498	 */
1499	proc0.p_sched = NULL; /* XXX */
1500	thread0.td_sched = &td_sched0;
1501	td_sched0.ts_ltick = ticks;
1502	td_sched0.ts_ftick = ticks;
1503	td_sched0.ts_thread = &thread0;
1504}
1505
1506/*
1507 * This is only somewhat accurate since given many processes of the same
1508 * priority they will switch when their slices run out, which will be
1509 * at most sched_slice stathz ticks.
1510 */
1511int
1512sched_rr_interval(void)
1513{
1514
1515	/* Convert sched_slice to hz */
1516	return (hz/(realstathz/sched_slice));
1517}
1518
1519/*
1520 * Update the percent cpu tracking information when it is requested or
1521 * the total history exceeds the maximum.  We keep a sliding history of
1522 * tick counts that slowly decays.  This is less precise than the 4BSD
1523 * mechanism since it happens with less regular and frequent events.
1524 */
1525static void
1526sched_pctcpu_update(struct td_sched *ts)
1527{
1528
1529	if (ts->ts_ticks == 0)
1530		return;
1531	if (ticks - (hz / 10) < ts->ts_ltick &&
1532	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1533		return;
1534	/*
1535	 * Adjust counters and watermark for pctcpu calc.
1536	 */
1537	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1538		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1539			    SCHED_TICK_TARG;
1540	else
1541		ts->ts_ticks = 0;
1542	ts->ts_ltick = ticks;
1543	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1544}
1545
1546/*
1547 * Adjust the priority of a thread.  Move it to the appropriate run-queue
1548 * if necessary.  This is the back-end for several priority related
1549 * functions.
1550 */
1551static void
1552sched_thread_priority(struct thread *td, u_char prio)
1553{
1554	struct td_sched *ts;
1555
1556	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
1557	    td, td->td_proc->p_comm, td->td_priority, prio, curthread,
1558	    curthread->td_proc->p_comm);
1559	ts = td->td_sched;
1560	THREAD_LOCK_ASSERT(td, MA_OWNED);
1561	if (td->td_priority == prio)
1562		return;
1563
1564	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1565		/*
1566		 * If the priority has been elevated due to priority
1567		 * propagation, we may have to move ourselves to a new
1568		 * queue.  This could be optimized to not re-add in some
1569		 * cases.
1570		 */
1571		sched_rem(td);
1572		td->td_priority = prio;
1573		sched_add(td, SRQ_BORROWING);
1574	} else {
1575#ifdef SMP
1576		struct tdq *tdq;
1577
1578		tdq = TDQ_CPU(ts->ts_cpu);
1579		if (prio < tdq->tdq_lowpri)
1580			tdq->tdq_lowpri = prio;
1581#endif
1582		td->td_priority = prio;
1583	}
1584}
1585
1586/*
1587 * Update a thread's priority when it is lent another thread's
1588 * priority.
1589 */
1590void
1591sched_lend_prio(struct thread *td, u_char prio)
1592{
1593
1594	td->td_flags |= TDF_BORROWING;
1595	sched_thread_priority(td, prio);
1596}
1597
1598/*
1599 * Restore a thread's priority when priority propagation is
1600 * over.  The prio argument is the minimum priority the thread
1601 * needs to have to satisfy other possible priority lending
1602 * requests.  If the thread's regular priority is less
1603 * important than prio, the thread will keep a priority boost
1604 * of prio.
1605 */
1606void
1607sched_unlend_prio(struct thread *td, u_char prio)
1608{
1609	u_char base_pri;
1610
1611	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1612	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1613		base_pri = td->td_user_pri;
1614	else
1615		base_pri = td->td_base_pri;
1616	if (prio >= base_pri) {
1617		td->td_flags &= ~TDF_BORROWING;
1618		sched_thread_priority(td, base_pri);
1619	} else
1620		sched_lend_prio(td, prio);
1621}
1622
1623/*
1624 * Standard entry for setting the priority to an absolute value.
1625 */
1626void
1627sched_prio(struct thread *td, u_char prio)
1628{
1629	u_char oldprio;
1630
1631	/* First, update the base priority. */
1632	td->td_base_pri = prio;
1633
1634	/*
1635	 * If the thread is borrowing another thread's priority, don't
1636	 * ever lower the priority.
1637	 */
1638	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1639		return;
1640
1641	/* Change the real priority. */
1642	oldprio = td->td_priority;
1643	sched_thread_priority(td, prio);
1644
1645	/*
1646	 * If the thread is on a turnstile, then let the turnstile update
1647	 * its state.
1648	 */
1649	if (TD_ON_LOCK(td) && oldprio != prio)
1650		turnstile_adjust(td, oldprio);
1651}
1652
1653/*
1654 * Set the base user priority, does not effect current running priority.
1655 */
1656void
1657sched_user_prio(struct thread *td, u_char prio)
1658{
1659	u_char oldprio;
1660
1661	td->td_base_user_pri = prio;
1662	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1663                return;
1664	oldprio = td->td_user_pri;
1665	td->td_user_pri = prio;
1666
1667	if (TD_ON_UPILOCK(td) && oldprio != prio)
1668		umtx_pi_adjust(td, oldprio);
1669}
1670
1671void
1672sched_lend_user_prio(struct thread *td, u_char prio)
1673{
1674	u_char oldprio;
1675
1676	td->td_flags |= TDF_UBORROWING;
1677
1678	oldprio = td->td_user_pri;
1679	td->td_user_pri = prio;
1680
1681	if (TD_ON_UPILOCK(td) && oldprio != prio)
1682		umtx_pi_adjust(td, oldprio);
1683}
1684
1685void
1686sched_unlend_user_prio(struct thread *td, u_char prio)
1687{
1688	u_char base_pri;
1689
1690	base_pri = td->td_base_user_pri;
1691	if (prio >= base_pri) {
1692		td->td_flags &= ~TDF_UBORROWING;
1693		sched_user_prio(td, base_pri);
1694	} else
1695		sched_lend_user_prio(td, prio);
1696}
1697
1698/*
1699 * Add the thread passed as 'newtd' to the run queue before selecting
1700 * the next thread to run.  This is only used for KSE.
1701 */
1702static void
1703sched_switchin(struct tdq *tdq, struct thread *td)
1704{
1705#ifdef SMP
1706	spinlock_enter();
1707	TDQ_UNLOCK(tdq);
1708	thread_lock(td);
1709	spinlock_exit();
1710	sched_setcpu(td->td_sched, TDQ_ID(tdq), SRQ_YIELDING);
1711#else
1712	td->td_lock = TDQ_LOCKPTR(tdq);
1713#endif
1714	tdq_add(tdq, td, SRQ_YIELDING);
1715	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1716}
1717
1718/*
1719 * Handle migration from sched_switch().  This happens only for
1720 * cpu binding.
1721 */
1722static struct mtx *
1723sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1724{
1725	struct tdq *tdn;
1726
1727	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1728#ifdef SMP
1729	/*
1730	 * Do the lock dance required to avoid LOR.  We grab an extra
1731	 * spinlock nesting to prevent preemption while we're
1732	 * not holding either run-queue lock.
1733	 */
1734	spinlock_enter();
1735	thread_block_switch(td);	/* This releases the lock on tdq. */
1736	TDQ_LOCK(tdn);
1737	tdq_add(tdn, td, flags);
1738	tdq_notify(td->td_sched);
1739	/*
1740	 * After we unlock tdn the new cpu still can't switch into this
1741	 * thread until we've unblocked it in cpu_switch().  The lock
1742	 * pointers may match in the case of HTT cores.  Don't unlock here
1743	 * or we can deadlock when the other CPU runs the IPI handler.
1744	 */
1745	if (TDQ_LOCKPTR(tdn) != TDQ_LOCKPTR(tdq)) {
1746		TDQ_UNLOCK(tdn);
1747		TDQ_LOCK(tdq);
1748	}
1749	spinlock_exit();
1750#endif
1751	return (TDQ_LOCKPTR(tdn));
1752}
1753
1754/*
1755 * Block a thread for switching.  Similar to thread_block() but does not
1756 * bump the spin count.
1757 */
1758static inline struct mtx *
1759thread_block_switch(struct thread *td)
1760{
1761	struct mtx *lock;
1762
1763	THREAD_LOCK_ASSERT(td, MA_OWNED);
1764	lock = td->td_lock;
1765	td->td_lock = &blocked_lock;
1766	mtx_unlock_spin(lock);
1767
1768	return (lock);
1769}
1770
1771/*
1772 * Release a thread that was blocked with thread_block_switch().
1773 */
1774static inline void
1775thread_unblock_switch(struct thread *td, struct mtx *mtx)
1776{
1777	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1778	    (uintptr_t)mtx);
1779}
1780
1781/*
1782 * Switch threads.  This function has to handle threads coming in while
1783 * blocked for some reason, running, or idle.  It also must deal with
1784 * migrating a thread from one queue to another as running threads may
1785 * be assigned elsewhere via binding.
1786 */
1787void
1788sched_switch(struct thread *td, struct thread *newtd, int flags)
1789{
1790	struct tdq *tdq;
1791	struct td_sched *ts;
1792	struct mtx *mtx;
1793	int srqflag;
1794	int cpuid;
1795
1796	THREAD_LOCK_ASSERT(td, MA_OWNED);
1797
1798	cpuid = PCPU_GET(cpuid);
1799	tdq = TDQ_CPU(cpuid);
1800	ts = td->td_sched;
1801	mtx = td->td_lock;
1802#ifdef SMP
1803	ts->ts_rltick = ticks;
1804	if (newtd && newtd->td_priority < tdq->tdq_lowpri)
1805		tdq->tdq_lowpri = newtd->td_priority;
1806#endif
1807	td->td_lastcpu = td->td_oncpu;
1808	td->td_oncpu = NOCPU;
1809	td->td_flags &= ~TDF_NEEDRESCHED;
1810	td->td_owepreempt = 0;
1811	/*
1812	 * The lock pointer in an idle thread should never change.  Reset it
1813	 * to CAN_RUN as well.
1814	 */
1815	if (TD_IS_IDLETHREAD(td)) {
1816		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1817		TD_SET_CAN_RUN(td);
1818	} else if (TD_IS_RUNNING(td)) {
1819		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1820		tdq_load_rem(tdq, ts);
1821		srqflag = (flags & SW_PREEMPT) ?
1822		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1823		    SRQ_OURSELF|SRQ_YIELDING;
1824		if (ts->ts_cpu == cpuid)
1825			tdq_add(tdq, td, srqflag);
1826		else
1827			mtx = sched_switch_migrate(tdq, td, srqflag);
1828	} else {
1829		/* This thread must be going to sleep. */
1830		TDQ_LOCK(tdq);
1831		mtx = thread_block_switch(td);
1832		tdq_load_rem(tdq, ts);
1833	}
1834	/*
1835	 * We enter here with the thread blocked and assigned to the
1836	 * appropriate cpu run-queue or sleep-queue and with the current
1837	 * thread-queue locked.
1838	 */
1839	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1840	/*
1841	 * If KSE assigned a new thread just add it here and let choosethread
1842	 * select the best one.
1843	 */
1844	if (newtd != NULL)
1845		sched_switchin(tdq, newtd);
1846	newtd = choosethread();
1847	/*
1848	 * Call the MD code to switch contexts if necessary.
1849	 */
1850	if (td != newtd) {
1851#ifdef	HWPMC_HOOKS
1852		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1853			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1854#endif
1855		cpu_switch(td, newtd, mtx);
1856		/*
1857		 * We may return from cpu_switch on a different cpu.  However,
1858		 * we always return with td_lock pointing to the current cpu's
1859		 * run queue lock.
1860		 */
1861		cpuid = PCPU_GET(cpuid);
1862		tdq = TDQ_CPU(cpuid);
1863		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)td;
1864#ifdef	HWPMC_HOOKS
1865		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1866			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1867#endif
1868	} else
1869		thread_unblock_switch(td, mtx);
1870	/*
1871	 * Assert that all went well and return.
1872	 */
1873#ifdef SMP
1874	/* We should always get here with the lowest priority td possible */
1875	tdq->tdq_lowpri = td->td_priority;
1876#endif
1877	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1878	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1879	td->td_oncpu = cpuid;
1880}
1881
1882/*
1883 * Adjust thread priorities as a result of a nice request.
1884 */
1885void
1886sched_nice(struct proc *p, int nice)
1887{
1888	struct thread *td;
1889
1890	PROC_LOCK_ASSERT(p, MA_OWNED);
1891	PROC_SLOCK_ASSERT(p, MA_OWNED);
1892
1893	p->p_nice = nice;
1894	FOREACH_THREAD_IN_PROC(p, td) {
1895		thread_lock(td);
1896		sched_priority(td);
1897		sched_prio(td, td->td_base_user_pri);
1898		thread_unlock(td);
1899	}
1900}
1901
1902/*
1903 * Record the sleep time for the interactivity scorer.
1904 */
1905void
1906sched_sleep(struct thread *td)
1907{
1908
1909	THREAD_LOCK_ASSERT(td, MA_OWNED);
1910
1911	td->td_sched->ts_slptick = ticks;
1912}
1913
1914/*
1915 * Schedule a thread to resume execution and record how long it voluntarily
1916 * slept.  We also update the pctcpu, interactivity, and priority.
1917 */
1918void
1919sched_wakeup(struct thread *td)
1920{
1921	struct td_sched *ts;
1922	int slptick;
1923
1924	THREAD_LOCK_ASSERT(td, MA_OWNED);
1925	ts = td->td_sched;
1926	/*
1927	 * If we slept for more than a tick update our interactivity and
1928	 * priority.
1929	 */
1930	slptick = ts->ts_slptick;
1931	ts->ts_slptick = 0;
1932	if (slptick && slptick != ticks) {
1933		u_int hzticks;
1934
1935		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1936		ts->ts_slptime += hzticks;
1937		sched_interact_update(td);
1938		sched_pctcpu_update(ts);
1939		sched_priority(td);
1940	}
1941	/* Reset the slice value after we sleep. */
1942	ts->ts_slice = sched_slice;
1943	sched_add(td, SRQ_BORING);
1944}
1945
1946/*
1947 * Penalize the parent for creating a new child and initialize the child's
1948 * priority.
1949 */
1950void
1951sched_fork(struct thread *td, struct thread *child)
1952{
1953	THREAD_LOCK_ASSERT(td, MA_OWNED);
1954	sched_fork_thread(td, child);
1955	/*
1956	 * Penalize the parent and child for forking.
1957	 */
1958	sched_interact_fork(child);
1959	sched_priority(child);
1960	td->td_sched->ts_runtime += tickincr;
1961	sched_interact_update(td);
1962	sched_priority(td);
1963}
1964
1965/*
1966 * Fork a new thread, may be within the same process.
1967 */
1968void
1969sched_fork_thread(struct thread *td, struct thread *child)
1970{
1971	struct td_sched *ts;
1972	struct td_sched *ts2;
1973
1974	/*
1975	 * Initialize child.
1976	 */
1977	THREAD_LOCK_ASSERT(td, MA_OWNED);
1978	sched_newthread(child);
1979	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1980	ts = td->td_sched;
1981	ts2 = child->td_sched;
1982	ts2->ts_cpu = ts->ts_cpu;
1983	ts2->ts_runq = NULL;
1984	/*
1985	 * Grab our parents cpu estimation information and priority.
1986	 */
1987	ts2->ts_ticks = ts->ts_ticks;
1988	ts2->ts_ltick = ts->ts_ltick;
1989	ts2->ts_ftick = ts->ts_ftick;
1990	child->td_user_pri = td->td_user_pri;
1991	child->td_base_user_pri = td->td_base_user_pri;
1992	/*
1993	 * And update interactivity score.
1994	 */
1995	ts2->ts_slptime = ts->ts_slptime;
1996	ts2->ts_runtime = ts->ts_runtime;
1997	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
1998}
1999
2000/*
2001 * Adjust the priority class of a thread.
2002 */
2003void
2004sched_class(struct thread *td, int class)
2005{
2006
2007	THREAD_LOCK_ASSERT(td, MA_OWNED);
2008	if (td->td_pri_class == class)
2009		return;
2010
2011#ifdef SMP
2012	/*
2013	 * On SMP if we're on the RUNQ we must adjust the transferable
2014	 * count because could be changing to or from an interrupt
2015	 * class.
2016	 */
2017	if (TD_ON_RUNQ(td)) {
2018		struct tdq *tdq;
2019
2020		tdq = TDQ_CPU(td->td_sched->ts_cpu);
2021		if (THREAD_CAN_MIGRATE(td)) {
2022			tdq->tdq_transferable--;
2023			tdq->tdq_group->tdg_transferable--;
2024		}
2025		td->td_pri_class = class;
2026		if (THREAD_CAN_MIGRATE(td)) {
2027			tdq->tdq_transferable++;
2028			tdq->tdq_group->tdg_transferable++;
2029		}
2030	}
2031#endif
2032	td->td_pri_class = class;
2033}
2034
2035/*
2036 * Return some of the child's priority and interactivity to the parent.
2037 */
2038void
2039sched_exit(struct proc *p, struct thread *child)
2040{
2041	struct thread *td;
2042
2043	CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
2044	    child, child->td_proc->p_comm, child->td_priority);
2045
2046	PROC_SLOCK_ASSERT(p, MA_OWNED);
2047	td = FIRST_THREAD_IN_PROC(p);
2048	sched_exit_thread(td, child);
2049}
2050
2051/*
2052 * Penalize another thread for the time spent on this one.  This helps to
2053 * worsen the priority and interactivity of processes which schedule batch
2054 * jobs such as make.  This has little effect on the make process itself but
2055 * causes new processes spawned by it to receive worse scores immediately.
2056 */
2057void
2058sched_exit_thread(struct thread *td, struct thread *child)
2059{
2060
2061	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
2062	    child, child->td_proc->p_comm, child->td_priority);
2063
2064#ifdef KSE
2065	/*
2066	 * KSE forks and exits so often that this penalty causes short-lived
2067	 * threads to always be non-interactive.  This causes mozilla to
2068	 * crawl under load.
2069	 */
2070	if ((td->td_pflags & TDP_SA) && td->td_proc == child->td_proc)
2071		return;
2072#endif
2073	/*
2074	 * Give the child's runtime to the parent without returning the
2075	 * sleep time as a penalty to the parent.  This causes shells that
2076	 * launch expensive things to mark their children as expensive.
2077	 */
2078	thread_lock(td);
2079	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
2080	sched_interact_update(td);
2081	sched_priority(td);
2082	thread_unlock(td);
2083}
2084
2085/*
2086 * Fix priorities on return to user-space.  Priorities may be elevated due
2087 * to static priorities in msleep() or similar.
2088 */
2089void
2090sched_userret(struct thread *td)
2091{
2092	/*
2093	 * XXX we cheat slightly on the locking here to avoid locking in
2094	 * the usual case.  Setting td_priority here is essentially an
2095	 * incomplete workaround for not setting it properly elsewhere.
2096	 * Now that some interrupt handlers are threads, not setting it
2097	 * properly elsewhere can clobber it in the window between setting
2098	 * it here and returning to user mode, so don't waste time setting
2099	 * it perfectly here.
2100	 */
2101	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2102	    ("thread with borrowed priority returning to userland"));
2103	if (td->td_priority != td->td_user_pri) {
2104		thread_lock(td);
2105		td->td_priority = td->td_user_pri;
2106		td->td_base_pri = td->td_user_pri;
2107		thread_unlock(td);
2108        }
2109}
2110
2111/*
2112 * Handle a stathz tick.  This is really only relevant for timeshare
2113 * threads.
2114 */
2115void
2116sched_clock(struct thread *td)
2117{
2118	struct tdq *tdq;
2119	struct td_sched *ts;
2120
2121	THREAD_LOCK_ASSERT(td, MA_OWNED);
2122	tdq = TDQ_SELF();
2123	/*
2124	 * Advance the insert index once for each tick to ensure that all
2125	 * threads get a chance to run.
2126	 */
2127	if (tdq->tdq_idx == tdq->tdq_ridx) {
2128		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2129		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2130			tdq->tdq_ridx = tdq->tdq_idx;
2131	}
2132	ts = td->td_sched;
2133	/*
2134	 * We only do slicing code for TIMESHARE threads.
2135	 */
2136	if (td->td_pri_class != PRI_TIMESHARE)
2137		return;
2138	/*
2139	 * We used a tick; charge it to the thread so that we can compute our
2140	 * interactivity.
2141	 */
2142	td->td_sched->ts_runtime += tickincr;
2143	sched_interact_update(td);
2144	/*
2145	 * We used up one time slice.
2146	 */
2147	if (--ts->ts_slice > 0)
2148		return;
2149	/*
2150	 * We're out of time, recompute priorities and requeue.
2151	 */
2152	sched_priority(td);
2153	td->td_flags |= TDF_NEEDRESCHED;
2154}
2155
2156/*
2157 * Called once per hz tick.  Used for cpu utilization information.  This
2158 * is easier than trying to scale based on stathz.
2159 */
2160void
2161sched_tick(void)
2162{
2163	struct td_sched *ts;
2164
2165	ts = curthread->td_sched;
2166	/* Adjust ticks for pctcpu */
2167	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2168	ts->ts_ltick = ticks;
2169	/*
2170	 * Update if we've exceeded our desired tick threshhold by over one
2171	 * second.
2172	 */
2173	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2174		sched_pctcpu_update(ts);
2175}
2176
2177/*
2178 * Return whether the current CPU has runnable tasks.  Used for in-kernel
2179 * cooperative idle threads.
2180 */
2181int
2182sched_runnable(void)
2183{
2184	struct tdq *tdq;
2185	int load;
2186
2187	load = 1;
2188
2189	tdq = TDQ_SELF();
2190	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2191		if (tdq->tdq_load > 0)
2192			goto out;
2193	} else
2194		if (tdq->tdq_load - 1 > 0)
2195			goto out;
2196	load = 0;
2197out:
2198	return (load);
2199}
2200
2201/*
2202 * Choose the highest priority thread to run.  The thread is removed from
2203 * the run-queue while running however the load remains.  For SMP we set
2204 * the tdq in the global idle bitmask if it idles here.
2205 */
2206struct thread *
2207sched_choose(void)
2208{
2209#ifdef SMP
2210	struct tdq_group *tdg;
2211#endif
2212	struct td_sched *ts;
2213	struct tdq *tdq;
2214
2215	tdq = TDQ_SELF();
2216	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2217	ts = tdq_choose(tdq);
2218	if (ts) {
2219		tdq_runq_rem(tdq, ts);
2220		return (ts->ts_thread);
2221	}
2222#ifdef SMP
2223	/*
2224	 * We only set the idled bit when all of the cpus in the group are
2225	 * idle.  Otherwise we could get into a situation where a thread bounces
2226	 * back and forth between two idle cores on seperate physical CPUs.
2227	 */
2228	tdg = tdq->tdq_group;
2229	tdg->tdg_idlemask |= PCPU_GET(cpumask);
2230	if (tdg->tdg_idlemask == tdg->tdg_cpumask)
2231		atomic_set_int(&tdq_idle, tdg->tdg_mask);
2232	tdq->tdq_lowpri = PRI_MAX_IDLE;
2233#endif
2234	return (PCPU_GET(idlethread));
2235}
2236
2237/*
2238 * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2239 * we always request it once we exit a critical section.
2240 */
2241static inline void
2242sched_setpreempt(struct thread *td)
2243{
2244	struct thread *ctd;
2245	int cpri;
2246	int pri;
2247
2248	ctd = curthread;
2249	pri = td->td_priority;
2250	cpri = ctd->td_priority;
2251	if (td->td_priority < ctd->td_priority)
2252		curthread->td_flags |= TDF_NEEDRESCHED;
2253	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2254		return;
2255	/*
2256	 * Always preempt IDLE threads.  Otherwise only if the preempting
2257	 * thread is an ithread.
2258	 */
2259	if (pri > preempt_thresh && cpri < PRI_MIN_IDLE)
2260		return;
2261	ctd->td_owepreempt = 1;
2262	return;
2263}
2264
2265/*
2266 * Add a thread to a thread queue.  Initializes priority, slice, runq, and
2267 * add it to the appropriate queue.  This is the internal function called
2268 * when the tdq is predetermined.
2269 */
2270void
2271tdq_add(struct tdq *tdq, struct thread *td, int flags)
2272{
2273	struct td_sched *ts;
2274	int class;
2275#ifdef SMP
2276	int cpumask;
2277#endif
2278
2279	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2280	KASSERT((td->td_inhibitors == 0),
2281	    ("sched_add: trying to run inhibited thread"));
2282	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2283	    ("sched_add: bad thread state"));
2284	KASSERT(td->td_proc->p_sflag & PS_INMEM,
2285	    ("sched_add: process swapped out"));
2286
2287	ts = td->td_sched;
2288	class = PRI_BASE(td->td_pri_class);
2289        TD_SET_RUNQ(td);
2290	if (ts->ts_slice == 0)
2291		ts->ts_slice = sched_slice;
2292	/*
2293	 * Pick the run queue based on priority.
2294	 */
2295	if (td->td_priority <= PRI_MAX_REALTIME)
2296		ts->ts_runq = &tdq->tdq_realtime;
2297	else if (td->td_priority <= PRI_MAX_TIMESHARE)
2298		ts->ts_runq = &tdq->tdq_timeshare;
2299	else
2300		ts->ts_runq = &tdq->tdq_idle;
2301#ifdef SMP
2302	cpumask = 1 << ts->ts_cpu;
2303	/*
2304	 * If we had been idle, clear our bit in the group and potentially
2305	 * the global bitmap.
2306	 */
2307	if ((class != PRI_IDLE && class != PRI_ITHD) &&
2308	    (tdq->tdq_group->tdg_idlemask & cpumask) != 0) {
2309		/*
2310		 * Check to see if our group is unidling, and if so, remove it
2311		 * from the global idle mask.
2312		 */
2313		if (tdq->tdq_group->tdg_idlemask ==
2314		    tdq->tdq_group->tdg_cpumask)
2315			atomic_clear_int(&tdq_idle, tdq->tdq_group->tdg_mask);
2316		/*
2317		 * Now remove ourselves from the group specific idle mask.
2318		 */
2319		tdq->tdq_group->tdg_idlemask &= ~cpumask;
2320	}
2321	if (td->td_priority < tdq->tdq_lowpri)
2322		tdq->tdq_lowpri = td->td_priority;
2323#endif
2324	tdq_runq_add(tdq, ts, flags);
2325	tdq_load_add(tdq, ts);
2326}
2327
2328/*
2329 * Select the target thread queue and add a thread to it.  Request
2330 * preemption or IPI a remote processor if required.
2331 */
2332void
2333sched_add(struct thread *td, int flags)
2334{
2335	struct td_sched *ts;
2336	struct tdq *tdq;
2337#ifdef SMP
2338	int cpuid;
2339	int cpu;
2340#endif
2341	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
2342	    td, td->td_proc->p_comm, td->td_priority, curthread,
2343	    curthread->td_proc->p_comm);
2344	THREAD_LOCK_ASSERT(td, MA_OWNED);
2345	ts = td->td_sched;
2346	/*
2347	 * Recalculate the priority before we select the target cpu or
2348	 * run-queue.
2349	 */
2350	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2351		sched_priority(td);
2352#ifdef SMP
2353	cpuid = PCPU_GET(cpuid);
2354	/*
2355	 * Pick the destination cpu and if it isn't ours transfer to the
2356	 * target cpu.
2357	 */
2358	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_MIGRATE(td))
2359		cpu = cpuid;
2360	else if (!THREAD_CAN_MIGRATE(td))
2361		cpu = ts->ts_cpu;
2362	else
2363		cpu = sched_pickcpu(ts, flags);
2364	tdq = sched_setcpu(ts, cpu, flags);
2365	tdq_add(tdq, td, flags);
2366	if (cpu != cpuid) {
2367		tdq_notify(ts);
2368		return;
2369	}
2370#else
2371	tdq = TDQ_SELF();
2372	TDQ_LOCK(tdq);
2373	/*
2374	 * Now that the thread is moving to the run-queue, set the lock
2375	 * to the scheduler's lock.
2376	 */
2377	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2378	tdq_add(tdq, td, flags);
2379#endif
2380	if (!(flags & SRQ_YIELDING))
2381		sched_setpreempt(td);
2382}
2383
2384/*
2385 * Remove a thread from a run-queue without running it.  This is used
2386 * when we're stealing a thread from a remote queue.  Otherwise all threads
2387 * exit by calling sched_exit_thread() and sched_throw() themselves.
2388 */
2389void
2390sched_rem(struct thread *td)
2391{
2392	struct tdq *tdq;
2393	struct td_sched *ts;
2394
2395	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
2396	    td, td->td_proc->p_comm, td->td_priority, curthread,
2397	    curthread->td_proc->p_comm);
2398	ts = td->td_sched;
2399	tdq = TDQ_CPU(ts->ts_cpu);
2400	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2401	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2402	KASSERT(TD_ON_RUNQ(td),
2403	    ("sched_rem: thread not on run queue"));
2404	tdq_runq_rem(tdq, ts);
2405	tdq_load_rem(tdq, ts);
2406	TD_SET_CAN_RUN(td);
2407}
2408
2409/*
2410 * Fetch cpu utilization information.  Updates on demand.
2411 */
2412fixpt_t
2413sched_pctcpu(struct thread *td)
2414{
2415	fixpt_t pctcpu;
2416	struct td_sched *ts;
2417
2418	pctcpu = 0;
2419	ts = td->td_sched;
2420	if (ts == NULL)
2421		return (0);
2422
2423	thread_lock(td);
2424	if (ts->ts_ticks) {
2425		int rtick;
2426
2427		sched_pctcpu_update(ts);
2428		/* How many rtick per second ? */
2429		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2430		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2431	}
2432	td->td_proc->p_swtime = ts->ts_ltick - ts->ts_ftick;
2433	thread_unlock(td);
2434
2435	return (pctcpu);
2436}
2437
2438/*
2439 * Bind a thread to a target cpu.
2440 */
2441void
2442sched_bind(struct thread *td, int cpu)
2443{
2444	struct td_sched *ts;
2445
2446	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2447	ts = td->td_sched;
2448	if (ts->ts_flags & TSF_BOUND)
2449		sched_unbind(td);
2450	ts->ts_flags |= TSF_BOUND;
2451#ifdef SMP
2452	sched_pin();
2453	if (PCPU_GET(cpuid) == cpu)
2454		return;
2455	ts->ts_cpu = cpu;
2456	/* When we return from mi_switch we'll be on the correct cpu. */
2457	mi_switch(SW_VOL, NULL);
2458#endif
2459}
2460
2461/*
2462 * Release a bound thread.
2463 */
2464void
2465sched_unbind(struct thread *td)
2466{
2467	struct td_sched *ts;
2468
2469	THREAD_LOCK_ASSERT(td, MA_OWNED);
2470	ts = td->td_sched;
2471	if ((ts->ts_flags & TSF_BOUND) == 0)
2472		return;
2473	ts->ts_flags &= ~TSF_BOUND;
2474#ifdef SMP
2475	sched_unpin();
2476#endif
2477}
2478
2479int
2480sched_is_bound(struct thread *td)
2481{
2482	THREAD_LOCK_ASSERT(td, MA_OWNED);
2483	return (td->td_sched->ts_flags & TSF_BOUND);
2484}
2485
2486/*
2487 * Basic yield call.
2488 */
2489void
2490sched_relinquish(struct thread *td)
2491{
2492	thread_lock(td);
2493	if (td->td_pri_class == PRI_TIMESHARE)
2494		sched_prio(td, PRI_MAX_TIMESHARE);
2495	SCHED_STAT_INC(switch_relinquish);
2496	mi_switch(SW_VOL, NULL);
2497	thread_unlock(td);
2498}
2499
2500/*
2501 * Return the total system load.
2502 */
2503int
2504sched_load(void)
2505{
2506#ifdef SMP
2507	int total;
2508	int i;
2509
2510	total = 0;
2511	for (i = 0; i <= tdg_maxid; i++)
2512		total += TDQ_GROUP(i)->tdg_load;
2513	return (total);
2514#else
2515	return (TDQ_SELF()->tdq_sysload);
2516#endif
2517}
2518
2519int
2520sched_sizeof_proc(void)
2521{
2522	return (sizeof(struct proc));
2523}
2524
2525int
2526sched_sizeof_thread(void)
2527{
2528	return (sizeof(struct thread) + sizeof(struct td_sched));
2529}
2530
2531/*
2532 * The actual idle process.
2533 */
2534void
2535sched_idletd(void *dummy)
2536{
2537	struct thread *td;
2538	struct tdq *tdq;
2539
2540	td = curthread;
2541	tdq = TDQ_SELF();
2542	mtx_assert(&Giant, MA_NOTOWNED);
2543	/* ULE relies on preemption for idle interruption. */
2544	for (;;) {
2545#ifdef SMP
2546		if (tdq_idled(tdq))
2547			cpu_idle();
2548#else
2549		cpu_idle();
2550#endif
2551	}
2552}
2553
2554/*
2555 * A CPU is entering for the first time or a thread is exiting.
2556 */
2557void
2558sched_throw(struct thread *td)
2559{
2560	struct tdq *tdq;
2561
2562	tdq = TDQ_SELF();
2563	if (td == NULL) {
2564		/* Correct spinlock nesting and acquire the correct lock. */
2565		TDQ_LOCK(tdq);
2566		spinlock_exit();
2567	} else {
2568		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2569		tdq_load_rem(tdq, td->td_sched);
2570	}
2571	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2572	PCPU_SET(switchtime, cpu_ticks());
2573	PCPU_SET(switchticks, ticks);
2574	cpu_throw(td, choosethread());	/* doesn't return */
2575}
2576
2577/*
2578 * This is called from fork_exit().  Just acquire the correct locks and
2579 * let fork do the rest of the work.
2580 */
2581void
2582sched_fork_exit(struct thread *td)
2583{
2584	struct td_sched *ts;
2585	struct tdq *tdq;
2586	int cpuid;
2587
2588	/*
2589	 * Finish setting up thread glue so that it begins execution in a
2590	 * non-nested critical section with the scheduler lock held.
2591	 */
2592	cpuid = PCPU_GET(cpuid);
2593	tdq = TDQ_CPU(cpuid);
2594	ts = td->td_sched;
2595	if (TD_IS_IDLETHREAD(td))
2596		td->td_lock = TDQ_LOCKPTR(tdq);
2597	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2598	td->td_oncpu = cpuid;
2599	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)td;
2600	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
2601}
2602
2603static SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0,
2604    "Scheduler");
2605SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2606    "Scheduler name");
2607SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2608    "Slice size for timeshare threads");
2609SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2610     "Interactivity score threshold");
2611SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2612     0,"Min priority for preemption, lower priorities have greater precedence");
2613#ifdef SMP
2614SYSCTL_INT(_kern_sched, OID_AUTO, pick_pri, CTLFLAG_RW, &pick_pri, 0,
2615    "Pick the target cpu based on priority rather than load.");
2616SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2617    "Number of hz ticks to keep thread affinity for");
2618SYSCTL_INT(_kern_sched, OID_AUTO, tryself, CTLFLAG_RW, &tryself, 0, "");
2619SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2620    "Enables the long-term load balancer");
2621SYSCTL_INT(_kern_sched, OID_AUTO, balance_secs, CTLFLAG_RW, &balance_secs, 0,
2622    "Average frequence in seconds to run the long-term balancer");
2623SYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2624    "Steals work from another hyper-threaded core on idle");
2625SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2626    "Attempts to steal work from other cores before idling");
2627SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2628    "Minimum load on remote cpu before we'll steal");
2629SYSCTL_INT(_kern_sched, OID_AUTO, topology, CTLFLAG_RD, &topology, 0,
2630    "True when a topology has been specified by the MD code.");
2631#endif
2632
2633/* ps compat */
2634static fixpt_t  ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
2635SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2636
2637
2638#define KERN_SWITCH_INCLUDE 1
2639#include "kern/kern_switch.c"
2640