sched_ule.c revision 171506
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 it's 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 171506 2007-07-19 20:03:15Z 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_slptick;	/* Tick when we went to sleep. */
92	int		ts_slice;	/* Ticks of slice remaining. */
93	u_int		ts_slptime;	/* Number of ticks we vol. slept */
94	u_int		ts_runtime;	/* Number of ticks we were running */
95	/* The following variables are only used for pctcpu calculation */
96	int		ts_ltick;	/* Last tick that we were running on */
97	int		ts_ftick;	/* First tick that we were running on */
98	int		ts_ticks;	/* Tick count */
99#ifdef SMP
100	int		ts_rltick;	/* Real last tick, for affinity. */
101#endif
102};
103/* flags kept in ts_flags */
104#define	TSF_BOUND	0x0001		/* Thread can not migrate. */
105#define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
106
107static struct td_sched td_sched0;
108
109/*
110 * Cpu percentage computation macros and defines.
111 *
112 * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
113 * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
114 * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
115 * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
116 * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
117 * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
118 */
119#define	SCHED_TICK_SECS		10
120#define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
121#define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
122#define	SCHED_TICK_SHIFT	10
123#define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
124#define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
125
126/*
127 * These macros determine priorities for non-interactive threads.  They are
128 * assigned a priority based on their recent cpu utilization as expressed
129 * by the ratio of ticks to the tick total.  NHALF priorities at the start
130 * and end of the MIN to MAX timeshare range are only reachable with negative
131 * or positive nice respectively.
132 *
133 * PRI_RANGE:	Priority range for utilization dependent priorities.
134 * PRI_NRESV:	Number of nice values.
135 * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
136 * PRI_NICE:	Determines the part of the priority inherited from nice.
137 */
138#define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
139#define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
140#define	SCHED_PRI_MIN		(PRI_MIN_TIMESHARE + SCHED_PRI_NHALF)
141#define	SCHED_PRI_MAX		(PRI_MAX_TIMESHARE - SCHED_PRI_NHALF)
142#define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN)
143#define	SCHED_PRI_TICKS(ts)						\
144    (SCHED_TICK_HZ((ts)) /						\
145    (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
146#define	SCHED_PRI_NICE(nice)	(nice)
147
148/*
149 * These determine the interactivity of a process.  Interactivity differs from
150 * cpu utilization in that it expresses the voluntary time slept vs time ran
151 * while cpu utilization includes all time not running.  This more accurately
152 * models the intent of the thread.
153 *
154 * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
155 *		before throttling back.
156 * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
157 * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
158 * INTERACT_THRESH:	Threshhold for placement on the current runq.
159 */
160#define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
161#define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
162#define	SCHED_INTERACT_MAX	(100)
163#define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
164#define	SCHED_INTERACT_THRESH	(30)
165
166/*
167 * tickincr:		Converts a stathz tick into a hz domain scaled by
168 *			the shift factor.  Without the shift the error rate
169 *			due to rounding would be unacceptably high.
170 * realstathz:		stathz is sometimes 0 and run off of hz.
171 * sched_slice:		Runtime of each thread before rescheduling.
172 * preempt_thresh:	Priority threshold for preemption and remote IPIs.
173 */
174static int sched_interact = SCHED_INTERACT_THRESH;
175static int realstathz;
176static int tickincr;
177static int sched_slice;
178static int preempt_thresh = PRI_MIN_KERN;
179
180/*
181 * tdq - per processor runqs and statistics.  All fields are protected by the
182 * tdq_lock.  The load and lowpri may be accessed without to avoid excess
183 * locking in sched_pickcpu();
184 */
185struct tdq {
186	struct mtx	tdq_lock;		/* Protects all fields below. */
187	struct runq	tdq_realtime;		/* real-time run queue. */
188	struct runq	tdq_timeshare;		/* timeshare run queue. */
189	struct runq	tdq_idle;		/* Queue of IDLE threads. */
190	int		tdq_load;		/* Aggregate load. */
191	u_char		tdq_idx;		/* Current insert index. */
192	u_char		tdq_ridx;		/* Current removal index. */
193#ifdef SMP
194	u_char		tdq_lowpri;		/* Lowest priority thread. */
195	int		tdq_transferable;	/* Transferable thread count. */
196	LIST_ENTRY(tdq)	tdq_siblings;		/* Next in tdq group. */
197	struct tdq_group *tdq_group;		/* Our processor group. */
198#else
199	int		tdq_sysload;		/* For loadavg, !ITHD load. */
200#endif
201	char		tdq_name[16];		/* lock name. */
202} __aligned(64);
203
204
205#ifdef SMP
206/*
207 * tdq groups are groups of processors which can cheaply share threads.  When
208 * one processor in the group goes idle it will check the runqs of the other
209 * processors in its group prior to halting and waiting for an interrupt.
210 * These groups are suitable for SMT (Symetric Multi-Threading) and not NUMA.
211 * In a numa environment we'd want an idle bitmap per group and a two tiered
212 * load balancer.
213 */
214struct tdq_group {
215	int	tdg_cpus;		/* Count of CPUs in this tdq group. */
216	cpumask_t tdg_cpumask;		/* Mask of cpus in this group. */
217	cpumask_t tdg_idlemask;		/* Idle cpus in this group. */
218	cpumask_t tdg_mask;		/* Bit mask for first cpu. */
219	int	tdg_load;		/* Total load of this group. */
220	int	tdg_transferable;	/* Transferable load of this group. */
221	LIST_HEAD(, tdq) tdg_members;	/* Linked list of all members. */
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)	((x) - tdq_cpu)
253#define	TDQ_GROUP(x)	(&tdq_groups[(x)])
254#else	/* !SMP */
255static struct tdq	tdq_cpu;
256
257#define	TDQ_ID(x)	(0)
258#define	TDQ_SELF()	(&tdq_cpu)
259#define	TDQ_CPU(x)	(&tdq_cpu)
260#endif
261
262#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
263#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
264#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
265#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
266#define	TDQ_LOCKPTR(t)		(&(t)->tdq_lock)
267
268static void sched_priority(struct thread *);
269static void sched_thread_priority(struct thread *, u_char);
270static int sched_interact_score(struct thread *);
271static void sched_interact_update(struct thread *);
272static void sched_interact_fork(struct thread *);
273static void sched_pctcpu_update(struct td_sched *);
274
275/* Operations on per processor queues */
276static struct td_sched * tdq_choose(struct tdq *);
277static void tdq_setup(struct tdq *);
278static void tdq_load_add(struct tdq *, struct td_sched *);
279static void tdq_load_rem(struct tdq *, struct td_sched *);
280static __inline void tdq_runq_add(struct tdq *, struct td_sched *, int);
281static __inline void tdq_runq_rem(struct tdq *, struct td_sched *);
282void tdq_print(int cpu);
283static void runq_print(struct runq *rq);
284static void tdq_add(struct tdq *, struct thread *, int);
285#ifdef SMP
286static void tdq_move(struct tdq *, struct tdq *);
287static int tdq_idled(struct tdq *);
288static void tdq_notify(struct td_sched *);
289static struct td_sched *tdq_steal(struct tdq *, int);
290static struct td_sched *runq_steal(struct runq *);
291static int sched_pickcpu(struct td_sched *, int);
292static void sched_balance(void *);
293static void sched_balance_groups(void *);
294static void sched_balance_group(struct tdq_group *);
295static void sched_balance_pair(struct tdq *, struct tdq *);
296static inline struct tdq *sched_setcpu(struct td_sched *, int, int);
297static inline struct mtx *thread_block_switch(struct thread *);
298static inline void thread_unblock_switch(struct thread *, struct mtx *);
299
300#define	THREAD_CAN_MIGRATE(td)	 ((td)->td_pinned == 0)
301#endif
302
303static void sched_setup(void *dummy);
304SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
305
306static void sched_initticks(void *dummy);
307SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks, NULL)
308
309/*
310 * Print the threads waiting on a run-queue.
311 */
312static void
313runq_print(struct runq *rq)
314{
315	struct rqhead *rqh;
316	struct td_sched *ts;
317	int pri;
318	int j;
319	int i;
320
321	for (i = 0; i < RQB_LEN; i++) {
322		printf("\t\trunq bits %d 0x%zx\n",
323		    i, rq->rq_status.rqb_bits[i]);
324		for (j = 0; j < RQB_BPW; j++)
325			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
326				pri = j + (i << RQB_L2BPW);
327				rqh = &rq->rq_queues[pri];
328				TAILQ_FOREACH(ts, rqh, ts_procq) {
329					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
330					    ts->ts_thread, ts->ts_thread->td_proc->p_comm, ts->ts_thread->td_priority, ts->ts_rqindex, pri);
331				}
332			}
333	}
334}
335
336/*
337 * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
338 */
339void
340tdq_print(int cpu)
341{
342	struct tdq *tdq;
343
344	tdq = TDQ_CPU(cpu);
345
346	printf("tdq:\n");
347	printf("\tlockptr         %p\n", TDQ_LOCKPTR(tdq));
348	printf("\tlock name       %s\n", tdq->tdq_name);
349	printf("\tload:           %d\n", tdq->tdq_load);
350	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
351	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
352	printf("\trealtime runq:\n");
353	runq_print(&tdq->tdq_realtime);
354	printf("\ttimeshare runq:\n");
355	runq_print(&tdq->tdq_timeshare);
356	printf("\tidle runq:\n");
357	runq_print(&tdq->tdq_idle);
358#ifdef SMP
359	printf("\tload transferable: %d\n", tdq->tdq_transferable);
360	printf("\tlowest priority: %d\n", tdq->tdq_lowpri);
361#endif
362}
363
364#define	TS_RQ_PPQ	(((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
365/*
366 * Add a thread to the actual run-queue.  Keeps transferable counts up to
367 * date with what is actually on the run-queue.  Selects the correct
368 * queue position for timeshare threads.
369 */
370static __inline void
371tdq_runq_add(struct tdq *tdq, struct td_sched *ts, int flags)
372{
373	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
374	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
375#ifdef SMP
376	if (THREAD_CAN_MIGRATE(ts->ts_thread)) {
377		tdq->tdq_transferable++;
378		tdq->tdq_group->tdg_transferable++;
379		ts->ts_flags |= TSF_XFERABLE;
380	}
381#endif
382	if (ts->ts_runq == &tdq->tdq_timeshare) {
383		u_char pri;
384
385		pri = ts->ts_thread->td_priority;
386		KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
387			("Invalid priority %d on timeshare runq", pri));
388		/*
389		 * This queue contains only priorities between MIN and MAX
390		 * realtime.  Use the whole queue to represent these values.
391		 */
392		if ((flags & SRQ_BORROWING) == 0) {
393			pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
394			pri = (pri + tdq->tdq_idx) % RQ_NQS;
395			/*
396			 * This effectively shortens the queue by one so we
397			 * can have a one slot difference between idx and
398			 * ridx while we wait for threads to drain.
399			 */
400			if (tdq->tdq_ridx != tdq->tdq_idx &&
401			    pri == tdq->tdq_ridx)
402				pri = (unsigned char)(pri - 1) % RQ_NQS;
403		} else
404			pri = tdq->tdq_ridx;
405		runq_add_pri(ts->ts_runq, ts, pri, flags);
406	} else
407		runq_add(ts->ts_runq, ts, flags);
408}
409
410/*
411 * Remove a thread from a run-queue.  This typically happens when a thread
412 * is selected to run.  Running threads are not on the queue and the
413 * transferable count does not reflect them.
414 */
415static __inline void
416tdq_runq_rem(struct tdq *tdq, struct td_sched *ts)
417{
418	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
419	KASSERT(ts->ts_runq != NULL,
420	    ("tdq_runq_remove: thread %p null ts_runq", ts->ts_thread));
421#ifdef SMP
422	if (ts->ts_flags & TSF_XFERABLE) {
423		tdq->tdq_transferable--;
424		tdq->tdq_group->tdg_transferable--;
425		ts->ts_flags &= ~TSF_XFERABLE;
426	}
427#endif
428	if (ts->ts_runq == &tdq->tdq_timeshare) {
429		if (tdq->tdq_idx != tdq->tdq_ridx)
430			runq_remove_idx(ts->ts_runq, ts, &tdq->tdq_ridx);
431		else
432			runq_remove_idx(ts->ts_runq, ts, NULL);
433		/*
434		 * For timeshare threads we update the priority here so
435		 * the priority reflects the time we've been sleeping.
436		 */
437		ts->ts_ltick = ticks;
438		sched_pctcpu_update(ts);
439		sched_priority(ts->ts_thread);
440	} else
441		runq_remove(ts->ts_runq, ts);
442}
443
444/*
445 * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
446 * for this thread to the referenced thread queue.
447 */
448static void
449tdq_load_add(struct tdq *tdq, struct td_sched *ts)
450{
451	int class;
452
453	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
454	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
455	class = PRI_BASE(ts->ts_thread->td_pri_class);
456	tdq->tdq_load++;
457	CTR2(KTR_SCHED, "cpu %jd load: %d", TDQ_ID(tdq), tdq->tdq_load);
458	if (class != PRI_ITHD &&
459	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
460#ifdef SMP
461		tdq->tdq_group->tdg_load++;
462#else
463		tdq->tdq_sysload++;
464#endif
465}
466
467/*
468 * Remove the load from a thread that is transitioning to a sleep state or
469 * exiting.
470 */
471static void
472tdq_load_rem(struct tdq *tdq, struct td_sched *ts)
473{
474	int class;
475
476	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
477	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
478	class = PRI_BASE(ts->ts_thread->td_pri_class);
479	if (class != PRI_ITHD &&
480	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
481#ifdef SMP
482		tdq->tdq_group->tdg_load--;
483#else
484		tdq->tdq_sysload--;
485#endif
486	KASSERT(tdq->tdq_load != 0,
487	    ("tdq_load_rem: Removing with 0 load on queue %d", (int)TDQ_ID(tdq)));
488	tdq->tdq_load--;
489	CTR1(KTR_SCHED, "load: %d", tdq->tdq_load);
490	ts->ts_runq = NULL;
491}
492
493#ifdef SMP
494/*
495 * sched_balance is a simple CPU load balancing algorithm.  It operates by
496 * finding the least loaded and most loaded cpu and equalizing their load
497 * by migrating some processes.
498 *
499 * Dealing only with two CPUs at a time has two advantages.  Firstly, most
500 * installations will only have 2 cpus.  Secondly, load balancing too much at
501 * once can have an unpleasant effect on the system.  The scheduler rarely has
502 * enough information to make perfect decisions.  So this algorithm chooses
503 * simplicity and more gradual effects on load in larger systems.
504 *
505 */
506static void
507sched_balance(void *arg)
508{
509	struct tdq_group *high;
510	struct tdq_group *low;
511	struct tdq_group *tdg;
512	int cnt;
513	int i;
514
515	callout_reset(&balco, max(hz / 2, random() % (hz * balance_secs)),
516	    sched_balance, NULL);
517	if (smp_started == 0 || rebalance == 0)
518		return;
519	low = high = NULL;
520	i = random() % (tdg_maxid + 1);
521	for (cnt = 0; cnt <= tdg_maxid; cnt++) {
522		tdg = TDQ_GROUP(i);
523		/*
524		 * Find the CPU with the highest load that has some
525		 * threads to transfer.
526		 */
527		if ((high == NULL || tdg->tdg_load > high->tdg_load)
528		    && tdg->tdg_transferable)
529			high = tdg;
530		if (low == NULL || tdg->tdg_load < low->tdg_load)
531			low = tdg;
532		if (++i > tdg_maxid)
533			i = 0;
534	}
535	if (low != NULL && high != NULL && high != low)
536		sched_balance_pair(LIST_FIRST(&high->tdg_members),
537		    LIST_FIRST(&low->tdg_members));
538}
539
540/*
541 * Balance load between CPUs in a group.  Will only migrate within the group.
542 */
543static void
544sched_balance_groups(void *arg)
545{
546	int i;
547
548	callout_reset(&gbalco, max(hz / 2, random() % (hz * balance_secs)),
549	    sched_balance_groups, NULL);
550	if (smp_started == 0 || rebalance == 0)
551		return;
552	for (i = 0; i <= tdg_maxid; i++)
553		sched_balance_group(TDQ_GROUP(i));
554}
555
556/*
557 * Finds the greatest imbalance between two tdqs in a group.
558 */
559static void
560sched_balance_group(struct tdq_group *tdg)
561{
562	struct tdq *tdq;
563	struct tdq *high;
564	struct tdq *low;
565	int load;
566
567	if (tdg->tdg_transferable == 0)
568		return;
569	low = NULL;
570	high = NULL;
571	LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
572		load = tdq->tdq_load;
573		if (high == NULL || load > high->tdq_load)
574			high = tdq;
575		if (low == NULL || load < low->tdq_load)
576			low = tdq;
577	}
578	if (high != NULL && low != NULL && high != low)
579		sched_balance_pair(high, low);
580}
581
582/*
583 * Lock two thread queues using their address to maintain lock order.
584 */
585static void
586tdq_lock_pair(struct tdq *one, struct tdq *two)
587{
588	if (one < two) {
589		TDQ_LOCK(one);
590		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
591	} else {
592		TDQ_LOCK(two);
593		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
594	}
595}
596
597/*
598 * Transfer load between two imbalanced thread queues.
599 */
600static void
601sched_balance_pair(struct tdq *high, struct tdq *low)
602{
603	int transferable;
604	int high_load;
605	int low_load;
606	int move;
607	int diff;
608	int i;
609
610	tdq_lock_pair(high, low);
611	/*
612	 * If we're transfering within a group we have to use this specific
613	 * tdq's transferable count, otherwise we can steal from other members
614	 * of the group.
615	 */
616	if (high->tdq_group == low->tdq_group) {
617		transferable = high->tdq_transferable;
618		high_load = high->tdq_load;
619		low_load = low->tdq_load;
620	} else {
621		transferable = high->tdq_group->tdg_transferable;
622		high_load = high->tdq_group->tdg_load;
623		low_load = low->tdq_group->tdg_load;
624	}
625	/*
626	 * Determine what the imbalance is and then adjust that to how many
627	 * threads we actually have to give up (transferable).
628	 */
629	if (transferable != 0) {
630		diff = high_load - low_load;
631		move = diff / 2;
632		if (diff & 0x1)
633			move++;
634		move = min(move, transferable);
635		for (i = 0; i < move; i++)
636			tdq_move(high, low);
637	}
638	TDQ_UNLOCK(high);
639	TDQ_UNLOCK(low);
640	return;
641}
642
643/*
644 * Move a thread from one thread queue to another.
645 */
646static void
647tdq_move(struct tdq *from, struct tdq *to)
648{
649	struct td_sched *ts;
650	struct thread *td;
651	struct tdq *tdq;
652	int cpu;
653
654	tdq = from;
655	cpu = TDQ_ID(to);
656	ts = tdq_steal(tdq, 1);
657	if (ts == NULL) {
658		struct tdq_group *tdg;
659
660		tdg = tdq->tdq_group;
661		LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
662			if (tdq == from || tdq->tdq_transferable == 0)
663				continue;
664			ts = tdq_steal(tdq, 1);
665			break;
666		}
667		if (ts == NULL)
668			return;
669	}
670	if (tdq == to)
671		return;
672	td = ts->ts_thread;
673	/*
674	 * Although the run queue is locked the thread may be blocked.  Lock
675	 * it to clear this.
676	 */
677	thread_lock(td);
678	/* Drop recursive lock on from. */
679	TDQ_UNLOCK(from);
680	sched_rem(td);
681	ts->ts_cpu = cpu;
682	td->td_lock = TDQ_LOCKPTR(to);
683	tdq_add(to, td, SRQ_YIELDING);
684	tdq_notify(ts);
685}
686
687/*
688 * This tdq has idled.  Try to steal a thread from another cpu and switch
689 * to it.
690 */
691static int
692tdq_idled(struct tdq *tdq)
693{
694	struct tdq_group *tdg;
695	struct tdq *steal;
696	struct td_sched *ts;
697	struct thread *td;
698	int highload;
699	int highcpu;
700	int load;
701	int cpu;
702
703	/* We don't want to be preempted while we're iterating over tdqs */
704	spinlock_enter();
705	tdg = tdq->tdq_group;
706	/*
707	 * If we're in a cpu group, try and steal threads from another cpu in
708	 * the group before idling.
709	 */
710	if (steal_htt && tdg->tdg_cpus > 1 && tdg->tdg_transferable) {
711		LIST_FOREACH(steal, &tdg->tdg_members, tdq_siblings) {
712			if (steal == tdq || steal->tdq_transferable == 0)
713				continue;
714			TDQ_LOCK(steal);
715			ts = tdq_steal(steal, 0);
716			if (ts)
717				goto steal;
718			TDQ_UNLOCK(steal);
719		}
720	}
721	for (;;) {
722		if (steal_idle == 0)
723			break;
724		highcpu = 0;
725		highload = 0;
726		for (cpu = 0; cpu <= mp_maxid; cpu++) {
727			if (CPU_ABSENT(cpu))
728				continue;
729			steal = TDQ_CPU(cpu);
730			load = TDQ_CPU(cpu)->tdq_transferable;
731			if (load < highload)
732				continue;
733			highload = load;
734			highcpu = cpu;
735		}
736		if (highload < steal_thresh)
737			break;
738		steal = TDQ_CPU(highcpu);
739		TDQ_LOCK(steal);
740		if (steal->tdq_transferable >= steal_thresh &&
741		    (ts = tdq_steal(steal, 1)) != NULL)
742			goto steal;
743		TDQ_UNLOCK(steal);
744		break;
745	}
746	spinlock_exit();
747	return (1);
748steal:
749	td = ts->ts_thread;
750	thread_lock(td);
751	spinlock_exit();
752	MPASS(td->td_lock == TDQ_LOCKPTR(steal));
753	TDQ_UNLOCK(steal);
754	sched_rem(td);
755	sched_setcpu(ts, PCPU_GET(cpuid), SRQ_YIELDING);
756	tdq_add(tdq, td, SRQ_YIELDING);
757	MPASS(td->td_lock == curthread->td_lock);
758	mi_switch(SW_VOL, NULL);
759	thread_unlock(curthread);
760
761	return (0);
762}
763
764/*
765 * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
766 */
767static void
768tdq_notify(struct td_sched *ts)
769{
770	struct thread *ctd;
771	struct pcpu *pcpu;
772	int cpri;
773	int pri;
774	int cpu;
775
776	cpu = ts->ts_cpu;
777	pri = ts->ts_thread->td_priority;
778	pcpu = pcpu_find(cpu);
779	ctd = pcpu->pc_curthread;
780	cpri = ctd->td_priority;
781
782	/*
783	 * If our priority is not better than the current priority there is
784	 * nothing to do.
785	 */
786	if (pri > cpri)
787		return;
788	/*
789	 * Always IPI idle.
790	 */
791	if (cpri > PRI_MIN_IDLE)
792		goto sendipi;
793	/*
794	 * If we're realtime or better and there is timeshare or worse running
795	 * send an IPI.
796	 */
797	if (pri < PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
798		goto sendipi;
799	/*
800	 * Otherwise only IPI if we exceed the threshold.
801	 */
802	if (pri > preempt_thresh)
803		return;
804sendipi:
805	ctd->td_flags |= TDF_NEEDRESCHED;
806	ipi_selected(1 << cpu, IPI_PREEMPT);
807}
808
809/*
810 * Steals load from a timeshare queue.  Honors the rotating queue head
811 * index.
812 */
813static struct td_sched *
814runq_steal_from(struct runq *rq, u_char start)
815{
816	struct td_sched *ts;
817	struct rqbits *rqb;
818	struct rqhead *rqh;
819	int first;
820	int bit;
821	int pri;
822	int i;
823
824	rqb = &rq->rq_status;
825	bit = start & (RQB_BPW -1);
826	pri = 0;
827	first = 0;
828again:
829	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
830		if (rqb->rqb_bits[i] == 0)
831			continue;
832		if (bit != 0) {
833			for (pri = bit; pri < RQB_BPW; pri++)
834				if (rqb->rqb_bits[i] & (1ul << pri))
835					break;
836			if (pri >= RQB_BPW)
837				continue;
838		} else
839			pri = RQB_FFS(rqb->rqb_bits[i]);
840		pri += (i << RQB_L2BPW);
841		rqh = &rq->rq_queues[pri];
842		TAILQ_FOREACH(ts, rqh, ts_procq) {
843			if (first && THREAD_CAN_MIGRATE(ts->ts_thread))
844				return (ts);
845			first = 1;
846		}
847	}
848	if (start != 0) {
849		start = 0;
850		goto again;
851	}
852
853	return (NULL);
854}
855
856/*
857 * Steals load from a standard linear queue.
858 */
859static struct td_sched *
860runq_steal(struct runq *rq)
861{
862	struct rqhead *rqh;
863	struct rqbits *rqb;
864	struct td_sched *ts;
865	int word;
866	int bit;
867
868	rqb = &rq->rq_status;
869	for (word = 0; word < RQB_LEN; word++) {
870		if (rqb->rqb_bits[word] == 0)
871			continue;
872		for (bit = 0; bit < RQB_BPW; bit++) {
873			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
874				continue;
875			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
876			TAILQ_FOREACH(ts, rqh, ts_procq)
877				if (THREAD_CAN_MIGRATE(ts->ts_thread))
878					return (ts);
879		}
880	}
881	return (NULL);
882}
883
884/*
885 * Attempt to steal a thread in priority order from a thread queue.
886 */
887static struct td_sched *
888tdq_steal(struct tdq *tdq, int stealidle)
889{
890	struct td_sched *ts;
891
892	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
893	if ((ts = runq_steal(&tdq->tdq_realtime)) != NULL)
894		return (ts);
895	if ((ts = runq_steal_from(&tdq->tdq_timeshare, tdq->tdq_ridx)) != NULL)
896		return (ts);
897	if (stealidle)
898		return (runq_steal(&tdq->tdq_idle));
899	return (NULL);
900}
901
902/*
903 * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
904 * current lock and returns with the assigned queue locked.  If this is
905 * via sched_switch() we leave the thread in a blocked state as an
906 * optimization.
907 */
908static inline struct tdq *
909sched_setcpu(struct td_sched *ts, int cpu, int flags)
910{
911	struct thread *td;
912	struct tdq *tdq;
913
914	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
915
916	tdq = TDQ_CPU(cpu);
917	td = ts->ts_thread;
918	ts->ts_cpu = cpu;
919	if (td->td_lock == TDQ_LOCKPTR(tdq))
920		return (tdq);
921#ifdef notyet
922	/*
923	 * If the thread isn't running it's lockptr is a
924	 * turnstile or a sleepqueue.  We can just lock_set without
925	 * blocking.
926	 */
927	if (TD_CAN_RUN(td)) {
928		TDQ_LOCK(tdq);
929		thread_lock_set(td, TDQ_LOCKPTR(tdq));
930		return (tdq);
931	}
932#endif
933	/*
934	 * The hard case, migration, we need to block the thread first to
935	 * prevent order reversals with other cpus locks.
936	 */
937	thread_lock_block(td);
938	TDQ_LOCK(tdq);
939	/* Return to sched_switch() with the lock still blocked */
940	if ((flags & SRQ_OURSELF) == 0)
941		thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
942	return (tdq);
943}
944
945/*
946 * Find the thread queue running the lowest priority thread.
947 */
948static int
949tdq_lowestpri(void)
950{
951	struct tdq *tdq;
952	int lowpri;
953	int lowcpu;
954	int lowload;
955	int load;
956	int cpu;
957	int pri;
958
959	lowload = 0;
960	lowpri = lowcpu = 0;
961	for (cpu = 0; cpu <= mp_maxid; cpu++) {
962		if (CPU_ABSENT(cpu))
963			continue;
964		tdq = TDQ_CPU(cpu);
965		pri = tdq->tdq_lowpri;
966		load = TDQ_CPU(cpu)->tdq_load;
967		CTR4(KTR_ULE,
968		    "cpu %d pri %d lowcpu %d lowpri %d",
969		    cpu, pri, lowcpu, lowpri);
970		if (pri < lowpri)
971			continue;
972		if (lowpri && lowpri == pri && load > lowload)
973			continue;
974		lowpri = pri;
975		lowcpu = cpu;
976		lowload = load;
977	}
978
979	return (lowcpu);
980}
981
982/*
983 * Find the thread queue with the least load.
984 */
985static int
986tdq_lowestload(void)
987{
988	struct tdq *tdq;
989	int lowload;
990	int lowpri;
991	int lowcpu;
992	int load;
993	int cpu;
994	int pri;
995
996	lowcpu = 0;
997	lowload = TDQ_CPU(0)->tdq_load;
998	lowpri = TDQ_CPU(0)->tdq_lowpri;
999	for (cpu = 1; cpu <= mp_maxid; cpu++) {
1000		if (CPU_ABSENT(cpu))
1001			continue;
1002		tdq = TDQ_CPU(cpu);
1003		load = tdq->tdq_load;
1004		pri = tdq->tdq_lowpri;
1005		CTR4(KTR_ULE, "cpu %d load %d lowcpu %d lowload %d",
1006		    cpu, load, lowcpu, lowload);
1007		if (load > lowload)
1008			continue;
1009		if (load == lowload && pri < lowpri)
1010			continue;
1011		lowcpu = cpu;
1012		lowload = load;
1013		lowpri = pri;
1014	}
1015
1016	return (lowcpu);
1017}
1018
1019/*
1020 * Pick the destination cpu for sched_add().  Respects affinity and makes
1021 * a determination based on load or priority of available processors.
1022 */
1023static int
1024sched_pickcpu(struct td_sched *ts, int flags)
1025{
1026	struct tdq *tdq;
1027	int self;
1028	int pri;
1029	int cpu;
1030
1031	cpu = self = PCPU_GET(cpuid);
1032	if (smp_started == 0)
1033		return (self);
1034	/*
1035	 * Don't migrate a running thread from sched_switch().
1036	 */
1037	if (flags & SRQ_OURSELF) {
1038		CTR1(KTR_ULE, "YIELDING %d",
1039		    curthread->td_priority);
1040		return (self);
1041	}
1042	pri = ts->ts_thread->td_priority;
1043	cpu = ts->ts_cpu;
1044	/*
1045	 * Regardless of affinity, if the last cpu is idle send it there.
1046	 */
1047	tdq = TDQ_CPU(cpu);
1048	if (tdq->tdq_lowpri > PRI_MIN_IDLE) {
1049		CTR5(KTR_ULE,
1050		    "ts_cpu %d idle, ltick %d ticks %d pri %d curthread %d",
1051		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1052		    tdq->tdq_lowpri);
1053		return (ts->ts_cpu);
1054	}
1055	/*
1056	 * If we have affinity, try to place it on the cpu we last ran on.
1057	 */
1058	if (SCHED_AFFINITY(ts) && tdq->tdq_lowpri > pri) {
1059		CTR5(KTR_ULE,
1060		    "affinity for %d, ltick %d ticks %d pri %d curthread %d",
1061		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1062		    tdq->tdq_lowpri);
1063		return (ts->ts_cpu);
1064	}
1065	/*
1066	 * Look for an idle group.
1067	 */
1068	CTR1(KTR_ULE, "tdq_idle %X", tdq_idle);
1069	cpu = ffs(tdq_idle);
1070	if (cpu)
1071		return (--cpu);
1072	/*
1073	 * If there are no idle cores see if we can run the thread locally.  This may
1074	 * improve locality among sleepers and wakers when there is shared data.
1075	 */
1076	if (tryself && pri < curthread->td_priority) {
1077		CTR1(KTR_ULE, "tryself %d",
1078		    curthread->td_priority);
1079		return (self);
1080	}
1081	/*
1082 	 * Now search for the cpu running the lowest priority thread with
1083	 * the least load.
1084	 */
1085	if (pick_pri)
1086		cpu = tdq_lowestpri();
1087	else
1088		cpu = tdq_lowestload();
1089	return (cpu);
1090}
1091
1092#endif	/* SMP */
1093
1094/*
1095 * Pick the highest priority task we have and return it.
1096 */
1097static struct td_sched *
1098tdq_choose(struct tdq *tdq)
1099{
1100	struct td_sched *ts;
1101
1102	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1103	ts = runq_choose(&tdq->tdq_realtime);
1104	if (ts != NULL)
1105		return (ts);
1106	ts = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1107	if (ts != NULL) {
1108		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_TIMESHARE,
1109		    ("tdq_choose: Invalid priority on timeshare queue %d",
1110		    ts->ts_thread->td_priority));
1111		return (ts);
1112	}
1113
1114	ts = runq_choose(&tdq->tdq_idle);
1115	if (ts != NULL) {
1116		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_IDLE,
1117		    ("tdq_choose: Invalid priority on idle queue %d",
1118		    ts->ts_thread->td_priority));
1119		return (ts);
1120	}
1121
1122	return (NULL);
1123}
1124
1125/*
1126 * Initialize a thread queue.
1127 */
1128static void
1129tdq_setup(struct tdq *tdq)
1130{
1131
1132	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1133	    "sched lock %d", (int)TDQ_ID(tdq));
1134	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1135	    MTX_SPIN | MTX_RECURSE);
1136	runq_init(&tdq->tdq_realtime);
1137	runq_init(&tdq->tdq_timeshare);
1138	runq_init(&tdq->tdq_idle);
1139	tdq->tdq_load = 0;
1140}
1141
1142/*
1143 * Setup the thread queues and initialize the topology based on MD
1144 * information.
1145 */
1146static void
1147sched_setup(void *dummy)
1148{
1149	struct tdq *tdq;
1150#ifdef SMP
1151	int balance_groups;
1152	int i;
1153
1154	balance_groups = 0;
1155	/*
1156	 * Initialize the tdqs.
1157	 */
1158	for (i = 0; i < MAXCPU; i++) {
1159		tdq = &tdq_cpu[i];
1160		tdq_setup(&tdq_cpu[i]);
1161	}
1162	if (smp_topology == NULL) {
1163		struct tdq_group *tdg;
1164		int cpus;
1165
1166		for (cpus = 0, i = 0; i < MAXCPU; i++) {
1167			if (CPU_ABSENT(i))
1168				continue;
1169			tdq = &tdq_cpu[i];
1170			tdg = &tdq_groups[cpus];
1171			/*
1172			 * Setup a tdq group with one member.
1173			 */
1174			tdq->tdq_transferable = 0;
1175			tdq->tdq_group = tdg;
1176			tdg->tdg_cpus = 1;
1177			tdg->tdg_idlemask = 0;
1178			tdg->tdg_cpumask = tdg->tdg_mask = 1 << i;
1179			tdg->tdg_load = 0;
1180			tdg->tdg_transferable = 0;
1181			LIST_INIT(&tdg->tdg_members);
1182			LIST_INSERT_HEAD(&tdg->tdg_members, tdq, tdq_siblings);
1183			cpus++;
1184		}
1185		tdg_maxid = cpus - 1;
1186	} else {
1187		struct tdq_group *tdg;
1188		struct cpu_group *cg;
1189		int j;
1190
1191		topology = 1;
1192		for (i = 0; i < smp_topology->ct_count; i++) {
1193			cg = &smp_topology->ct_group[i];
1194			tdg = &tdq_groups[i];
1195			/*
1196			 * Initialize the group.
1197			 */
1198			tdg->tdg_idlemask = 0;
1199			tdg->tdg_load = 0;
1200			tdg->tdg_transferable = 0;
1201			tdg->tdg_cpus = cg->cg_count;
1202			tdg->tdg_cpumask = cg->cg_mask;
1203			LIST_INIT(&tdg->tdg_members);
1204			/*
1205			 * Find all of the group members and add them.
1206			 */
1207			for (j = 0; j < MAXCPU; j++) {
1208				if ((cg->cg_mask & (1 << j)) != 0) {
1209					if (tdg->tdg_mask == 0)
1210						tdg->tdg_mask = 1 << j;
1211					tdq_cpu[j].tdq_transferable = 0;
1212					tdq_cpu[j].tdq_group = tdg;
1213					LIST_INSERT_HEAD(&tdg->tdg_members,
1214					    &tdq_cpu[j], tdq_siblings);
1215				}
1216			}
1217			if (tdg->tdg_cpus > 1)
1218				balance_groups = 1;
1219		}
1220		tdg_maxid = smp_topology->ct_count - 1;
1221	}
1222	/*
1223	 * Initialize long-term cpu balancing algorithm.
1224	 */
1225	callout_init(&balco, CALLOUT_MPSAFE);
1226	callout_init(&gbalco, CALLOUT_MPSAFE);
1227	sched_balance(NULL);
1228	if (balance_groups)
1229		sched_balance_groups(NULL);
1230
1231#else
1232	tdq_setup(TDQ_SELF());
1233#endif
1234	/*
1235	 * To avoid divide-by-zero, we set realstathz a dummy value
1236	 * in case which sched_clock() called before sched_initticks().
1237	 */
1238	realstathz = hz;
1239	sched_slice = (realstathz/10);	/* ~100ms */
1240	tickincr = 1 << SCHED_TICK_SHIFT;
1241
1242	/* Add thread0's load since it's running. */
1243	tdq = TDQ_SELF();
1244	TDQ_LOCK(tdq);
1245	tdq_load_add(tdq, &td_sched0);
1246	TDQ_UNLOCK(tdq);
1247}
1248
1249/*
1250 * This routine determines the tickincr after stathz and hz are setup.
1251 */
1252/* ARGSUSED */
1253static void
1254sched_initticks(void *dummy)
1255{
1256	int incr;
1257
1258	realstathz = stathz ? stathz : hz;
1259	sched_slice = (realstathz/10);	/* ~100ms */
1260
1261	/*
1262	 * tickincr is shifted out by 10 to avoid rounding errors due to
1263	 * hz not being evenly divisible by stathz on all platforms.
1264	 */
1265	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1266	/*
1267	 * This does not work for values of stathz that are more than
1268	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1269	 */
1270	if (incr == 0)
1271		incr = 1;
1272	tickincr = incr;
1273#ifdef SMP
1274	affinity = SCHED_AFFINITY_DEFAULT;
1275#endif
1276}
1277
1278
1279/*
1280 * This is the core of the interactivity algorithm.  Determines a score based
1281 * on past behavior.  It is the ratio of sleep time to run time scaled to
1282 * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1283 * differs from the cpu usage because it does not account for time spent
1284 * waiting on a run-queue.  Would be prettier if we had floating point.
1285 */
1286static int
1287sched_interact_score(struct thread *td)
1288{
1289	struct td_sched *ts;
1290	int div;
1291
1292	ts = td->td_sched;
1293	/*
1294	 * The score is only needed if this is likely to be an interactive
1295	 * task.  Don't go through the expense of computing it if there's
1296	 * no chance.
1297	 */
1298	if (sched_interact <= SCHED_INTERACT_HALF &&
1299		ts->ts_runtime >= ts->ts_slptime)
1300			return (SCHED_INTERACT_HALF);
1301
1302	if (ts->ts_runtime > ts->ts_slptime) {
1303		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1304		return (SCHED_INTERACT_HALF +
1305		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1306	}
1307	if (ts->ts_slptime > ts->ts_runtime) {
1308		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1309		return (ts->ts_runtime / div);
1310	}
1311	/* runtime == slptime */
1312	if (ts->ts_runtime)
1313		return (SCHED_INTERACT_HALF);
1314
1315	/*
1316	 * This can happen if slptime and runtime are 0.
1317	 */
1318	return (0);
1319
1320}
1321
1322/*
1323 * Scale the scheduling priority according to the "interactivity" of this
1324 * process.
1325 */
1326static void
1327sched_priority(struct thread *td)
1328{
1329	int score;
1330	int pri;
1331
1332	if (td->td_pri_class != PRI_TIMESHARE)
1333		return;
1334	/*
1335	 * If the score is interactive we place the thread in the realtime
1336	 * queue with a priority that is less than kernel and interrupt
1337	 * priorities.  These threads are not subject to nice restrictions.
1338	 *
1339	 * Scores greater than this are placed on the normal timeshare queue
1340	 * where the priority is partially decided by the most recent cpu
1341	 * utilization and the rest is decided by nice value.
1342	 */
1343	score = sched_interact_score(td);
1344	if (score < sched_interact) {
1345		pri = PRI_MIN_REALTIME;
1346		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1347		    * score;
1348		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1349		    ("sched_priority: invalid interactive priority %d score %d",
1350		    pri, score));
1351	} else {
1352		pri = SCHED_PRI_MIN;
1353		if (td->td_sched->ts_ticks)
1354			pri += SCHED_PRI_TICKS(td->td_sched);
1355		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1356		KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1357		    ("sched_priority: invalid priority %d: nice %d, "
1358		    "ticks %d ftick %d ltick %d tick pri %d",
1359		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1360		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1361		    SCHED_PRI_TICKS(td->td_sched)));
1362	}
1363	sched_user_prio(td, pri);
1364
1365	return;
1366}
1367
1368/*
1369 * This routine enforces a maximum limit on the amount of scheduling history
1370 * kept.  It is called after either the slptime or runtime is adjusted.  This
1371 * function is ugly due to integer math.
1372 */
1373static void
1374sched_interact_update(struct thread *td)
1375{
1376	struct td_sched *ts;
1377	u_int sum;
1378
1379	ts = td->td_sched;
1380	sum = ts->ts_runtime + ts->ts_slptime;
1381	if (sum < SCHED_SLP_RUN_MAX)
1382		return;
1383	/*
1384	 * This only happens from two places:
1385	 * 1) We have added an unusual amount of run time from fork_exit.
1386	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1387	 */
1388	if (sum > SCHED_SLP_RUN_MAX * 2) {
1389		if (ts->ts_runtime > ts->ts_slptime) {
1390			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1391			ts->ts_slptime = 1;
1392		} else {
1393			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1394			ts->ts_runtime = 1;
1395		}
1396		return;
1397	}
1398	/*
1399	 * If we have exceeded by more than 1/5th then the algorithm below
1400	 * will not bring us back into range.  Dividing by two here forces
1401	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1402	 */
1403	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1404		ts->ts_runtime /= 2;
1405		ts->ts_slptime /= 2;
1406		return;
1407	}
1408	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1409	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1410}
1411
1412/*
1413 * Scale back the interactivity history when a child thread is created.  The
1414 * history is inherited from the parent but the thread may behave totally
1415 * differently.  For example, a shell spawning a compiler process.  We want
1416 * to learn that the compiler is behaving badly very quickly.
1417 */
1418static void
1419sched_interact_fork(struct thread *td)
1420{
1421	int ratio;
1422	int sum;
1423
1424	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1425	if (sum > SCHED_SLP_RUN_FORK) {
1426		ratio = sum / SCHED_SLP_RUN_FORK;
1427		td->td_sched->ts_runtime /= ratio;
1428		td->td_sched->ts_slptime /= ratio;
1429	}
1430}
1431
1432/*
1433 * Called from proc0_init() to setup the scheduler fields.
1434 */
1435void
1436schedinit(void)
1437{
1438
1439	/*
1440	 * Set up the scheduler specific parts of proc0.
1441	 */
1442	proc0.p_sched = NULL; /* XXX */
1443	thread0.td_sched = &td_sched0;
1444	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1445	td_sched0.ts_ltick = ticks;
1446	td_sched0.ts_ftick = ticks;
1447	td_sched0.ts_thread = &thread0;
1448}
1449
1450/*
1451 * This is only somewhat accurate since given many processes of the same
1452 * priority they will switch when their slices run out, which will be
1453 * at most sched_slice stathz ticks.
1454 */
1455int
1456sched_rr_interval(void)
1457{
1458
1459	/* Convert sched_slice to hz */
1460	return (hz/(realstathz/sched_slice));
1461}
1462
1463/*
1464 * Update the percent cpu tracking information when it is requested or
1465 * the total history exceeds the maximum.  We keep a sliding history of
1466 * tick counts that slowly decays.  This is less precise than the 4BSD
1467 * mechanism since it happens with less regular and frequent events.
1468 */
1469static void
1470sched_pctcpu_update(struct td_sched *ts)
1471{
1472
1473	if (ts->ts_ticks == 0)
1474		return;
1475	if (ticks - (hz / 10) < ts->ts_ltick &&
1476	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1477		return;
1478	/*
1479	 * Adjust counters and watermark for pctcpu calc.
1480	 */
1481	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1482		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1483			    SCHED_TICK_TARG;
1484	else
1485		ts->ts_ticks = 0;
1486	ts->ts_ltick = ticks;
1487	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1488}
1489
1490/*
1491 * Adjust the priority of a thread.  Move it to the appropriate run-queue
1492 * if necessary.  This is the back-end for several priority related
1493 * functions.
1494 */
1495static void
1496sched_thread_priority(struct thread *td, u_char prio)
1497{
1498	struct td_sched *ts;
1499
1500	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
1501	    td, td->td_proc->p_comm, td->td_priority, prio, curthread,
1502	    curthread->td_proc->p_comm);
1503	ts = td->td_sched;
1504	THREAD_LOCK_ASSERT(td, MA_OWNED);
1505	if (td->td_priority == prio)
1506		return;
1507
1508	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1509		/*
1510		 * If the priority has been elevated due to priority
1511		 * propagation, we may have to move ourselves to a new
1512		 * queue.  This could be optimized to not re-add in some
1513		 * cases.
1514		 */
1515		sched_rem(td);
1516		td->td_priority = prio;
1517		sched_add(td, SRQ_BORROWING);
1518	} else {
1519#ifdef SMP
1520		struct tdq *tdq;
1521
1522		tdq = TDQ_CPU(ts->ts_cpu);
1523		if (prio < tdq->tdq_lowpri)
1524			tdq->tdq_lowpri = prio;
1525#endif
1526		td->td_priority = prio;
1527	}
1528}
1529
1530/*
1531 * Update a thread's priority when it is lent another thread's
1532 * priority.
1533 */
1534void
1535sched_lend_prio(struct thread *td, u_char prio)
1536{
1537
1538	td->td_flags |= TDF_BORROWING;
1539	sched_thread_priority(td, prio);
1540}
1541
1542/*
1543 * Restore a thread's priority when priority propagation is
1544 * over.  The prio argument is the minimum priority the thread
1545 * needs to have to satisfy other possible priority lending
1546 * requests.  If the thread's regular priority is less
1547 * important than prio, the thread will keep a priority boost
1548 * of prio.
1549 */
1550void
1551sched_unlend_prio(struct thread *td, u_char prio)
1552{
1553	u_char base_pri;
1554
1555	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1556	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1557		base_pri = td->td_user_pri;
1558	else
1559		base_pri = td->td_base_pri;
1560	if (prio >= base_pri) {
1561		td->td_flags &= ~TDF_BORROWING;
1562		sched_thread_priority(td, base_pri);
1563	} else
1564		sched_lend_prio(td, prio);
1565}
1566
1567/*
1568 * Standard entry for setting the priority to an absolute value.
1569 */
1570void
1571sched_prio(struct thread *td, u_char prio)
1572{
1573	u_char oldprio;
1574
1575	/* First, update the base priority. */
1576	td->td_base_pri = prio;
1577
1578	/*
1579	 * If the thread is borrowing another thread's priority, don't
1580	 * ever lower the priority.
1581	 */
1582	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1583		return;
1584
1585	/* Change the real priority. */
1586	oldprio = td->td_priority;
1587	sched_thread_priority(td, prio);
1588
1589	/*
1590	 * If the thread is on a turnstile, then let the turnstile update
1591	 * its state.
1592	 */
1593	if (TD_ON_LOCK(td) && oldprio != prio)
1594		turnstile_adjust(td, oldprio);
1595}
1596
1597/*
1598 * Set the base user priority, does not effect current running priority.
1599 */
1600void
1601sched_user_prio(struct thread *td, u_char prio)
1602{
1603	u_char oldprio;
1604
1605	td->td_base_user_pri = prio;
1606	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1607                return;
1608	oldprio = td->td_user_pri;
1609	td->td_user_pri = prio;
1610
1611	if (TD_ON_UPILOCK(td) && oldprio != prio)
1612		umtx_pi_adjust(td, oldprio);
1613}
1614
1615void
1616sched_lend_user_prio(struct thread *td, u_char prio)
1617{
1618	u_char oldprio;
1619
1620	td->td_flags |= TDF_UBORROWING;
1621
1622	oldprio = td->td_user_pri;
1623	td->td_user_pri = prio;
1624
1625	if (TD_ON_UPILOCK(td) && oldprio != prio)
1626		umtx_pi_adjust(td, oldprio);
1627}
1628
1629void
1630sched_unlend_user_prio(struct thread *td, u_char prio)
1631{
1632	u_char base_pri;
1633
1634	base_pri = td->td_base_user_pri;
1635	if (prio >= base_pri) {
1636		td->td_flags &= ~TDF_UBORROWING;
1637		sched_user_prio(td, base_pri);
1638	} else
1639		sched_lend_user_prio(td, prio);
1640}
1641
1642/*
1643 * Add the thread passed as 'newtd' to the run queue before selecting
1644 * the next thread to run.  This is only used for KSE.
1645 */
1646static void
1647sched_switchin(struct tdq *tdq, struct thread *td)
1648{
1649#ifdef SMP
1650	spinlock_enter();
1651	TDQ_UNLOCK(tdq);
1652	thread_lock(td);
1653	spinlock_exit();
1654	sched_setcpu(td->td_sched, TDQ_ID(tdq), SRQ_YIELDING);
1655#else
1656	td->td_lock = TDQ_LOCKPTR(tdq);
1657#endif
1658	tdq_add(tdq, td, SRQ_YIELDING);
1659	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1660}
1661
1662/*
1663 * Block a thread for switching.  Similar to thread_block() but does not
1664 * bump the spin count.
1665 */
1666static inline struct mtx *
1667thread_block_switch(struct thread *td)
1668{
1669	struct mtx *lock;
1670
1671	THREAD_LOCK_ASSERT(td, MA_OWNED);
1672	lock = td->td_lock;
1673	td->td_lock = &blocked_lock;
1674	mtx_unlock_spin(lock);
1675
1676	return (lock);
1677}
1678
1679/*
1680 * Release a thread that was blocked with thread_block_switch().
1681 */
1682static inline void
1683thread_unblock_switch(struct thread *td, struct mtx *mtx)
1684{
1685	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1686	    (uintptr_t)mtx);
1687}
1688
1689/*
1690 * Switch threads.  This function has to handle threads coming in while
1691 * blocked for some reason, running, or idle.  It also must deal with
1692 * migrating a thread from one queue to another as running threads may
1693 * be assigned elsewhere via binding.
1694 */
1695void
1696sched_switch(struct thread *td, struct thread *newtd, int flags)
1697{
1698	struct tdq *tdq;
1699	struct td_sched *ts;
1700	struct mtx *mtx;
1701	int cpuid;
1702
1703	THREAD_LOCK_ASSERT(td, MA_OWNED);
1704
1705	cpuid = PCPU_GET(cpuid);
1706	tdq = TDQ_CPU(cpuid);
1707	ts = td->td_sched;
1708	mtx = TDQ_LOCKPTR(tdq);
1709#ifdef SMP
1710	ts->ts_rltick = ticks;
1711	if (newtd && newtd->td_priority < tdq->tdq_lowpri)
1712		tdq->tdq_lowpri = newtd->td_priority;
1713#endif
1714	td->td_lastcpu = td->td_oncpu;
1715	td->td_oncpu = NOCPU;
1716	td->td_flags &= ~TDF_NEEDRESCHED;
1717	td->td_owepreempt = 0;
1718	/*
1719	 * The lock pointer in an idle thread should never change.  Reset it
1720	 * to CAN_RUN as well.
1721	 */
1722	if (TD_IS_IDLETHREAD(td)) {
1723		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1724		TD_SET_CAN_RUN(td);
1725	} else if (TD_IS_RUNNING(td)) {
1726		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1727		/* Remove our load so the selection algorithm is not biased. */
1728		tdq_load_rem(tdq, ts);
1729		sched_add(td, (flags & SW_PREEMPT) ?
1730		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1731		    SRQ_OURSELF|SRQ_YIELDING);
1732		/*
1733		 * When migrating we return from sched_add with an extra
1734		 * spinlock nesting, the tdq locked, and a blocked thread.
1735		 * This is to optimize out an extra block/unblock cycle here.
1736		 */
1737		if (ts->ts_cpu != cpuid) {
1738			mtx = TDQ_LOCKPTR(TDQ_CPU(ts->ts_cpu));
1739			mtx_unlock_spin(mtx);
1740			TDQ_LOCK(tdq);
1741			spinlock_exit();
1742		}
1743	} else {
1744		/* This thread must be going to sleep. */
1745		TDQ_LOCK(tdq);
1746		mtx = thread_block_switch(td);
1747		tdq_load_rem(tdq, ts);
1748	}
1749	/*
1750	 * We enter here with the thread blocked and assigned to the
1751	 * appropriate cpu run-queue or sleep-queue and with the current
1752	 * thread-queue locked.
1753	 */
1754	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1755	/*
1756	 * If KSE assigned a new thread just add it here and let choosethread
1757	 * select the best one.
1758	 */
1759	if (newtd != NULL)
1760		sched_switchin(tdq, newtd);
1761	newtd = choosethread();
1762	/*
1763	 * Call the MD code to switch contexts if necessary.
1764	 */
1765	if (td != newtd) {
1766#ifdef	HWPMC_HOOKS
1767		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1768			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1769#endif
1770		cpu_switch(td, newtd, mtx);
1771		/*
1772		 * We may return from cpu_switch on a different cpu.  However,
1773		 * we always return with td_lock pointing to the current cpu's
1774		 * run queue lock.
1775		 */
1776		cpuid = PCPU_GET(cpuid);
1777		tdq = TDQ_CPU(cpuid);
1778		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)td;
1779#ifdef	HWPMC_HOOKS
1780		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1781			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1782#endif
1783	} else
1784		thread_unblock_switch(td, mtx);
1785	/*
1786	 * Assert that all went well and return.
1787	 */
1788#ifdef SMP
1789	/* We should always get here with the lowest priority td possible */
1790	tdq->tdq_lowpri = td->td_priority;
1791#endif
1792	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1793	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1794	td->td_oncpu = cpuid;
1795}
1796
1797/*
1798 * Adjust thread priorities as a result of a nice request.
1799 */
1800void
1801sched_nice(struct proc *p, int nice)
1802{
1803	struct thread *td;
1804
1805	PROC_LOCK_ASSERT(p, MA_OWNED);
1806	PROC_SLOCK_ASSERT(p, MA_OWNED);
1807
1808	p->p_nice = nice;
1809	FOREACH_THREAD_IN_PROC(p, td) {
1810		thread_lock(td);
1811		sched_priority(td);
1812		sched_prio(td, td->td_base_user_pri);
1813		thread_unlock(td);
1814	}
1815}
1816
1817/*
1818 * Record the sleep time for the interactivity scorer.
1819 */
1820void
1821sched_sleep(struct thread *td)
1822{
1823
1824	THREAD_LOCK_ASSERT(td, MA_OWNED);
1825
1826	td->td_sched->ts_slptick = ticks;
1827}
1828
1829/*
1830 * Schedule a thread to resume execution and record how long it voluntarily
1831 * slept.  We also update the pctcpu, interactivity, and priority.
1832 */
1833void
1834sched_wakeup(struct thread *td)
1835{
1836	struct td_sched *ts;
1837	int slptick;
1838
1839	THREAD_LOCK_ASSERT(td, MA_OWNED);
1840	ts = td->td_sched;
1841	/*
1842	 * If we slept for more than a tick update our interactivity and
1843	 * priority.
1844	 */
1845	slptick = ts->ts_slptick;
1846	ts->ts_slptick = 0;
1847	if (slptick && slptick != ticks) {
1848		u_int hzticks;
1849
1850		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1851		ts->ts_slptime += hzticks;
1852		sched_interact_update(td);
1853		sched_pctcpu_update(ts);
1854		sched_priority(td);
1855	}
1856	/* Reset the slice value after we sleep. */
1857	ts->ts_slice = sched_slice;
1858	sched_add(td, SRQ_BORING);
1859}
1860
1861/*
1862 * Penalize the parent for creating a new child and initialize the child's
1863 * priority.
1864 */
1865void
1866sched_fork(struct thread *td, struct thread *child)
1867{
1868	THREAD_LOCK_ASSERT(td, MA_OWNED);
1869	sched_fork_thread(td, child);
1870	/*
1871	 * Penalize the parent and child for forking.
1872	 */
1873	sched_interact_fork(child);
1874	sched_priority(child);
1875	td->td_sched->ts_runtime += tickincr;
1876	sched_interact_update(td);
1877	sched_priority(td);
1878}
1879
1880/*
1881 * Fork a new thread, may be within the same process.
1882 */
1883void
1884sched_fork_thread(struct thread *td, struct thread *child)
1885{
1886	struct td_sched *ts;
1887	struct td_sched *ts2;
1888
1889	/*
1890	 * Initialize child.
1891	 */
1892	THREAD_LOCK_ASSERT(td, MA_OWNED);
1893	sched_newthread(child);
1894	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1895	ts = td->td_sched;
1896	ts2 = child->td_sched;
1897	ts2->ts_cpu = ts->ts_cpu;
1898	ts2->ts_runq = NULL;
1899	/*
1900	 * Grab our parents cpu estimation information and priority.
1901	 */
1902	ts2->ts_ticks = ts->ts_ticks;
1903	ts2->ts_ltick = ts->ts_ltick;
1904	ts2->ts_ftick = ts->ts_ftick;
1905	child->td_user_pri = td->td_user_pri;
1906	child->td_base_user_pri = td->td_base_user_pri;
1907	/*
1908	 * And update interactivity score.
1909	 */
1910	ts2->ts_slptime = ts->ts_slptime;
1911	ts2->ts_runtime = ts->ts_runtime;
1912	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
1913}
1914
1915/*
1916 * Adjust the priority class of a thread.
1917 */
1918void
1919sched_class(struct thread *td, int class)
1920{
1921
1922	THREAD_LOCK_ASSERT(td, MA_OWNED);
1923	if (td->td_pri_class == class)
1924		return;
1925
1926#ifdef SMP
1927	/*
1928	 * On SMP if we're on the RUNQ we must adjust the transferable
1929	 * count because could be changing to or from an interrupt
1930	 * class.
1931	 */
1932	if (TD_ON_RUNQ(td)) {
1933		struct tdq *tdq;
1934
1935		tdq = TDQ_CPU(td->td_sched->ts_cpu);
1936		if (THREAD_CAN_MIGRATE(td)) {
1937			tdq->tdq_transferable--;
1938			tdq->tdq_group->tdg_transferable--;
1939		}
1940		td->td_pri_class = class;
1941		if (THREAD_CAN_MIGRATE(td)) {
1942			tdq->tdq_transferable++;
1943			tdq->tdq_group->tdg_transferable++;
1944		}
1945	}
1946#endif
1947	td->td_pri_class = class;
1948}
1949
1950/*
1951 * Return some of the child's priority and interactivity to the parent.
1952 */
1953void
1954sched_exit(struct proc *p, struct thread *child)
1955{
1956	struct thread *td;
1957
1958	CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
1959	    child, child->td_proc->p_comm, child->td_priority);
1960
1961	PROC_SLOCK_ASSERT(p, MA_OWNED);
1962	td = FIRST_THREAD_IN_PROC(p);
1963	sched_exit_thread(td, child);
1964}
1965
1966/*
1967 * Penalize another thread for the time spent on this one.  This helps to
1968 * worsen the priority and interactivity of processes which schedule batch
1969 * jobs such as make.  This has little effect on the make process itself but
1970 * causes new processes spawned by it to receive worse scores immediately.
1971 */
1972void
1973sched_exit_thread(struct thread *td, struct thread *child)
1974{
1975
1976	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
1977	    child, child->td_proc->p_comm, child->td_priority);
1978
1979#ifdef KSE
1980	/*
1981	 * KSE forks and exits so often that this penalty causes short-lived
1982	 * threads to always be non-interactive.  This causes mozilla to
1983	 * crawl under load.
1984	 */
1985	if ((td->td_pflags & TDP_SA) && td->td_proc == child->td_proc)
1986		return;
1987#endif
1988	/*
1989	 * Give the child's runtime to the parent without returning the
1990	 * sleep time as a penalty to the parent.  This causes shells that
1991	 * launch expensive things to mark their children as expensive.
1992	 */
1993	thread_lock(td);
1994	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
1995	sched_interact_update(td);
1996	sched_priority(td);
1997	thread_unlock(td);
1998}
1999
2000/*
2001 * Fix priorities on return to user-space.  Priorities may be elevated due
2002 * to static priorities in msleep() or similar.
2003 */
2004void
2005sched_userret(struct thread *td)
2006{
2007	/*
2008	 * XXX we cheat slightly on the locking here to avoid locking in
2009	 * the usual case.  Setting td_priority here is essentially an
2010	 * incomplete workaround for not setting it properly elsewhere.
2011	 * Now that some interrupt handlers are threads, not setting it
2012	 * properly elsewhere can clobber it in the window between setting
2013	 * it here and returning to user mode, so don't waste time setting
2014	 * it perfectly here.
2015	 */
2016	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2017	    ("thread with borrowed priority returning to userland"));
2018	if (td->td_priority != td->td_user_pri) {
2019		thread_lock(td);
2020		td->td_priority = td->td_user_pri;
2021		td->td_base_pri = td->td_user_pri;
2022		thread_unlock(td);
2023        }
2024}
2025
2026/*
2027 * Handle a stathz tick.  This is really only relevant for timeshare
2028 * threads.
2029 */
2030void
2031sched_clock(struct thread *td)
2032{
2033	struct tdq *tdq;
2034	struct td_sched *ts;
2035
2036	THREAD_LOCK_ASSERT(td, MA_OWNED);
2037	tdq = TDQ_SELF();
2038	/*
2039	 * Advance the insert index once for each tick to ensure that all
2040	 * threads get a chance to run.
2041	 */
2042	if (tdq->tdq_idx == tdq->tdq_ridx) {
2043		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2044		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2045			tdq->tdq_ridx = tdq->tdq_idx;
2046	}
2047	ts = td->td_sched;
2048	/*
2049	 * We only do slicing code for TIMESHARE threads.
2050	 */
2051	if (td->td_pri_class != PRI_TIMESHARE)
2052		return;
2053	/*
2054	 * We used a tick; charge it to the thread so that we can compute our
2055	 * interactivity.
2056	 */
2057	td->td_sched->ts_runtime += tickincr;
2058	sched_interact_update(td);
2059	/*
2060	 * We used up one time slice.
2061	 */
2062	if (--ts->ts_slice > 0)
2063		return;
2064	/*
2065	 * We're out of time, recompute priorities and requeue.
2066	 */
2067	sched_priority(td);
2068	td->td_flags |= TDF_NEEDRESCHED;
2069}
2070
2071/*
2072 * Called once per hz tick.  Used for cpu utilization information.  This
2073 * is easier than trying to scale based on stathz.
2074 */
2075void
2076sched_tick(void)
2077{
2078	struct td_sched *ts;
2079
2080	ts = curthread->td_sched;
2081	/* Adjust ticks for pctcpu */
2082	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2083	ts->ts_ltick = ticks;
2084	/*
2085	 * Update if we've exceeded our desired tick threshhold by over one
2086	 * second.
2087	 */
2088	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2089		sched_pctcpu_update(ts);
2090}
2091
2092/*
2093 * Return whether the current CPU has runnable tasks.  Used for in-kernel
2094 * cooperative idle threads.
2095 */
2096int
2097sched_runnable(void)
2098{
2099	struct tdq *tdq;
2100	int load;
2101
2102	load = 1;
2103
2104	tdq = TDQ_SELF();
2105	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2106		if (tdq->tdq_load > 0)
2107			goto out;
2108	} else
2109		if (tdq->tdq_load - 1 > 0)
2110			goto out;
2111	load = 0;
2112out:
2113	return (load);
2114}
2115
2116/*
2117 * Choose the highest priority thread to run.  The thread is removed from
2118 * the run-queue while running however the load remains.  For SMP we set
2119 * the tdq in the global idle bitmask if it idles here.
2120 */
2121struct thread *
2122sched_choose(void)
2123{
2124#ifdef SMP
2125	struct tdq_group *tdg;
2126#endif
2127	struct td_sched *ts;
2128	struct tdq *tdq;
2129
2130	tdq = TDQ_SELF();
2131	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2132	ts = tdq_choose(tdq);
2133	if (ts) {
2134		tdq_runq_rem(tdq, ts);
2135		return (ts->ts_thread);
2136	}
2137#ifdef SMP
2138	/*
2139	 * We only set the idled bit when all of the cpus in the group are
2140	 * idle.  Otherwise we could get into a situation where a thread bounces
2141	 * back and forth between two idle cores on seperate physical CPUs.
2142	 */
2143	tdg = tdq->tdq_group;
2144	tdg->tdg_idlemask |= PCPU_GET(cpumask);
2145	if (tdg->tdg_idlemask == tdg->tdg_cpumask)
2146		atomic_set_int(&tdq_idle, tdg->tdg_mask);
2147	tdq->tdq_lowpri = PRI_MAX_IDLE;
2148#endif
2149	return (PCPU_GET(idlethread));
2150}
2151
2152/*
2153 * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2154 * we always request it once we exit a critical section.
2155 */
2156static inline void
2157sched_setpreempt(struct thread *td)
2158{
2159	struct thread *ctd;
2160	int cpri;
2161	int pri;
2162
2163	ctd = curthread;
2164	pri = td->td_priority;
2165	cpri = ctd->td_priority;
2166	if (td->td_priority < ctd->td_priority)
2167		curthread->td_flags |= TDF_NEEDRESCHED;
2168	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2169		return;
2170	/*
2171	 * Always preempt IDLE threads.  Otherwise only if the preempting
2172	 * thread is an ithread.
2173	 */
2174	if (pri > preempt_thresh && cpri < PRI_MIN_IDLE)
2175		return;
2176	ctd->td_owepreempt = 1;
2177	return;
2178}
2179
2180/*
2181 * Add a thread to a thread queue.  Initializes priority, slice, runq, and
2182 * add it to the appropriate queue.  This is the internal function called
2183 * when the tdq is predetermined.
2184 */
2185void
2186tdq_add(struct tdq *tdq, struct thread *td, int flags)
2187{
2188	struct td_sched *ts;
2189	int class;
2190#ifdef SMP
2191	int cpumask;
2192#endif
2193
2194	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2195	KASSERT((td->td_inhibitors == 0),
2196	    ("sched_add: trying to run inhibited thread"));
2197	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2198	    ("sched_add: bad thread state"));
2199	KASSERT(td->td_proc->p_sflag & PS_INMEM,
2200	    ("sched_add: process swapped out"));
2201
2202	ts = td->td_sched;
2203	class = PRI_BASE(td->td_pri_class);
2204        TD_SET_RUNQ(td);
2205	if (ts->ts_slice == 0)
2206		ts->ts_slice = sched_slice;
2207	/*
2208	 * Pick the run queue based on priority.
2209	 */
2210	if (td->td_priority <= PRI_MAX_REALTIME)
2211		ts->ts_runq = &tdq->tdq_realtime;
2212	else if (td->td_priority <= PRI_MAX_TIMESHARE)
2213		ts->ts_runq = &tdq->tdq_timeshare;
2214	else
2215		ts->ts_runq = &tdq->tdq_idle;
2216#ifdef SMP
2217	cpumask = 1 << ts->ts_cpu;
2218	/*
2219	 * If we had been idle, clear our bit in the group and potentially
2220	 * the global bitmap.
2221	 */
2222	if ((class != PRI_IDLE && class != PRI_ITHD) &&
2223	    (tdq->tdq_group->tdg_idlemask & cpumask) != 0) {
2224		/*
2225		 * Check to see if our group is unidling, and if so, remove it
2226		 * from the global idle mask.
2227		 */
2228		if (tdq->tdq_group->tdg_idlemask ==
2229		    tdq->tdq_group->tdg_cpumask)
2230			atomic_clear_int(&tdq_idle, tdq->tdq_group->tdg_mask);
2231		/*
2232		 * Now remove ourselves from the group specific idle mask.
2233		 */
2234		tdq->tdq_group->tdg_idlemask &= ~cpumask;
2235	}
2236	if (td->td_priority < tdq->tdq_lowpri)
2237		tdq->tdq_lowpri = td->td_priority;
2238#endif
2239	tdq_runq_add(tdq, ts, flags);
2240	tdq_load_add(tdq, ts);
2241}
2242
2243/*
2244 * Select the target thread queue and add a thread to it.  Request
2245 * preemption or IPI a remote processor if required.
2246 */
2247void
2248sched_add(struct thread *td, int flags)
2249{
2250	struct td_sched *ts;
2251	struct tdq *tdq;
2252#ifdef SMP
2253	int cpuid;
2254	int cpu;
2255#endif
2256	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
2257	    td, td->td_proc->p_comm, td->td_priority, curthread,
2258	    curthread->td_proc->p_comm);
2259	THREAD_LOCK_ASSERT(td, MA_OWNED);
2260	ts = td->td_sched;
2261	/*
2262	 * Recalculate the priority before we select the target cpu or
2263	 * run-queue.
2264	 */
2265	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2266		sched_priority(td);
2267#ifdef SMP
2268	cpuid = PCPU_GET(cpuid);
2269	/*
2270	 * Pick the destination cpu and if it isn't ours transfer to the
2271	 * target cpu.
2272	 */
2273	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_MIGRATE(td))
2274		cpu = cpuid;
2275	else if (!THREAD_CAN_MIGRATE(td))
2276		cpu = ts->ts_cpu;
2277	else
2278		cpu = sched_pickcpu(ts, flags);
2279	tdq = sched_setcpu(ts, cpu, flags);
2280	tdq_add(tdq, td, flags);
2281	if (cpu != cpuid) {
2282		tdq_notify(ts);
2283		return;
2284	}
2285#else
2286	tdq = TDQ_SELF();
2287	TDQ_LOCK(tdq);
2288	/*
2289	 * Now that the thread is moving to the run-queue, set the lock
2290	 * to the scheduler's lock.
2291	 */
2292	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2293	tdq_add(tdq, td, flags);
2294#endif
2295	if (!(flags & SRQ_YIELDING))
2296		sched_setpreempt(td);
2297}
2298
2299/*
2300 * Remove a thread from a run-queue without running it.  This is used
2301 * when we're stealing a thread from a remote queue.  Otherwise all threads
2302 * exit by calling sched_exit_thread() and sched_throw() themselves.
2303 */
2304void
2305sched_rem(struct thread *td)
2306{
2307	struct tdq *tdq;
2308	struct td_sched *ts;
2309
2310	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
2311	    td, td->td_proc->p_comm, td->td_priority, curthread,
2312	    curthread->td_proc->p_comm);
2313	ts = td->td_sched;
2314	tdq = TDQ_CPU(ts->ts_cpu);
2315	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2316	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2317	KASSERT(TD_ON_RUNQ(td),
2318	    ("sched_rem: thread not on run queue"));
2319	tdq_runq_rem(tdq, ts);
2320	tdq_load_rem(tdq, ts);
2321	TD_SET_CAN_RUN(td);
2322}
2323
2324/*
2325 * Fetch cpu utilization information.  Updates on demand.
2326 */
2327fixpt_t
2328sched_pctcpu(struct thread *td)
2329{
2330	fixpt_t pctcpu;
2331	struct td_sched *ts;
2332
2333	pctcpu = 0;
2334	ts = td->td_sched;
2335	if (ts == NULL)
2336		return (0);
2337
2338	thread_lock(td);
2339	if (ts->ts_ticks) {
2340		int rtick;
2341
2342		sched_pctcpu_update(ts);
2343		/* How many rtick per second ? */
2344		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2345		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2346	}
2347	td->td_proc->p_swtime = ts->ts_ltick - ts->ts_ftick;
2348	thread_unlock(td);
2349
2350	return (pctcpu);
2351}
2352
2353/*
2354 * Bind a thread to a target cpu.
2355 */
2356void
2357sched_bind(struct thread *td, int cpu)
2358{
2359	struct td_sched *ts;
2360
2361	THREAD_LOCK_ASSERT(td, MA_OWNED);
2362	ts = td->td_sched;
2363	if (ts->ts_flags & TSF_BOUND)
2364		sched_unbind(td);
2365	ts->ts_flags |= TSF_BOUND;
2366#ifdef SMP
2367	sched_pin();
2368	if (PCPU_GET(cpuid) == cpu)
2369		return;
2370	ts->ts_cpu = cpu;
2371	/* When we return from mi_switch we'll be on the correct cpu. */
2372	mi_switch(SW_VOL, NULL);
2373#endif
2374}
2375
2376/*
2377 * Release a bound thread.
2378 */
2379void
2380sched_unbind(struct thread *td)
2381{
2382	struct td_sched *ts;
2383
2384	THREAD_LOCK_ASSERT(td, MA_OWNED);
2385	ts = td->td_sched;
2386	if ((ts->ts_flags & TSF_BOUND) == 0)
2387		return;
2388	ts->ts_flags &= ~TSF_BOUND;
2389#ifdef SMP
2390	sched_unpin();
2391#endif
2392}
2393
2394int
2395sched_is_bound(struct thread *td)
2396{
2397	THREAD_LOCK_ASSERT(td, MA_OWNED);
2398	return (td->td_sched->ts_flags & TSF_BOUND);
2399}
2400
2401/*
2402 * Basic yield call.
2403 */
2404void
2405sched_relinquish(struct thread *td)
2406{
2407	thread_lock(td);
2408	if (td->td_pri_class == PRI_TIMESHARE)
2409		sched_prio(td, PRI_MAX_TIMESHARE);
2410	SCHED_STAT_INC(switch_relinquish);
2411	mi_switch(SW_VOL, NULL);
2412	thread_unlock(td);
2413}
2414
2415/*
2416 * Return the total system load.
2417 */
2418int
2419sched_load(void)
2420{
2421#ifdef SMP
2422	int total;
2423	int i;
2424
2425	total = 0;
2426	for (i = 0; i <= tdg_maxid; i++)
2427		total += TDQ_GROUP(i)->tdg_load;
2428	return (total);
2429#else
2430	return (TDQ_SELF()->tdq_sysload);
2431#endif
2432}
2433
2434int
2435sched_sizeof_proc(void)
2436{
2437	return (sizeof(struct proc));
2438}
2439
2440int
2441sched_sizeof_thread(void)
2442{
2443	return (sizeof(struct thread) + sizeof(struct td_sched));
2444}
2445
2446/*
2447 * The actual idle process.
2448 */
2449void
2450sched_idletd(void *dummy)
2451{
2452	struct thread *td;
2453	struct tdq *tdq;
2454
2455	td = curthread;
2456	tdq = TDQ_SELF();
2457	mtx_assert(&Giant, MA_NOTOWNED);
2458	/* ULE relies on preemption for idle interruption. */
2459	for (;;) {
2460#ifdef SMP
2461		if (tdq_idled(tdq))
2462			cpu_idle();
2463#else
2464		cpu_idle();
2465#endif
2466	}
2467}
2468
2469/*
2470 * A CPU is entering for the first time or a thread is exiting.
2471 */
2472void
2473sched_throw(struct thread *td)
2474{
2475	struct tdq *tdq;
2476
2477	tdq = TDQ_SELF();
2478	if (td == NULL) {
2479		/* Correct spinlock nesting and acquire the correct lock. */
2480		TDQ_LOCK(tdq);
2481		spinlock_exit();
2482	} else {
2483		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2484		tdq_load_rem(tdq, td->td_sched);
2485	}
2486	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2487	PCPU_SET(switchtime, cpu_ticks());
2488	PCPU_SET(switchticks, ticks);
2489	cpu_throw(td, choosethread());	/* doesn't return */
2490}
2491
2492/*
2493 * This is called from fork_exit().  Just acquire the correct locks and
2494 * let fork do the rest of the work.
2495 */
2496void
2497sched_fork_exit(struct thread *td)
2498{
2499	struct td_sched *ts;
2500	struct tdq *tdq;
2501	int cpuid;
2502
2503	/*
2504	 * Finish setting up thread glue so that it begins execution in a
2505	 * non-nested critical section with the scheduler lock held.
2506	 */
2507	cpuid = PCPU_GET(cpuid);
2508	tdq = TDQ_CPU(cpuid);
2509	ts = td->td_sched;
2510	if (TD_IS_IDLETHREAD(td))
2511		td->td_lock = TDQ_LOCKPTR(tdq);
2512	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2513	td->td_oncpu = cpuid;
2514	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)td;
2515	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
2516}
2517
2518static SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0,
2519    "Scheduler");
2520SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2521    "Scheduler name");
2522SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2523    "Slice size for timeshare threads");
2524SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2525     "Interactivity score threshold");
2526SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2527     0,"Min priority for preemption, lower priorities have greater precedence");
2528#ifdef SMP
2529SYSCTL_INT(_kern_sched, OID_AUTO, pick_pri, CTLFLAG_RW, &pick_pri, 0,
2530    "Pick the target cpu based on priority rather than load.");
2531SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2532    "Number of hz ticks to keep thread affinity for");
2533SYSCTL_INT(_kern_sched, OID_AUTO, tryself, CTLFLAG_RW, &tryself, 0, "");
2534SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2535    "Enables the long-term load balancer");
2536SYSCTL_INT(_kern_sched, OID_AUTO, balance_secs, CTLFLAG_RW, &balance_secs, 0,
2537    "Average frequence in seconds to run the long-term balancer");
2538SYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2539    "Steals work from another hyper-threaded core on idle");
2540SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2541    "Attempts to steal work from other cores before idling");
2542SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2543    "Minimum load on remote cpu before we'll steal");
2544SYSCTL_INT(_kern_sched, OID_AUTO, topology, CTLFLAG_RD, &topology, 0,
2545    "True when a topology has been specified by the MD code.");
2546#endif
2547
2548/* ps compat */
2549static fixpt_t  ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
2550SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2551
2552
2553#define KERN_SWITCH_INCLUDE 1
2554#include "kern/kern_switch.c"
2555