sched_ule.c revision 171482
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 171482 2007-07-17 22:53:23Z 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#define	SCHED_BAL_SECS	2	/* How often we run the rebalance algorithm. */
181
182/*
183 * tdq - per processor runqs and statistics.  All fields are protected by the
184 * tdq_lock.  The load and lowpri may be accessed without to avoid excess
185 * locking in sched_pickcpu();
186 */
187struct tdq {
188	struct mtx	tdq_lock;		/* Protects all fields below. */
189	struct runq	tdq_realtime;		/* real-time run queue. */
190	struct runq	tdq_timeshare;		/* timeshare run queue. */
191	struct runq	tdq_idle;		/* Queue of IDLE threads. */
192	int		tdq_load;		/* Aggregate load. */
193	u_char		tdq_idx;		/* Current insert index. */
194	u_char		tdq_ridx;		/* Current removal index. */
195#ifdef SMP
196	u_char		tdq_lowpri;		/* Lowest priority thread. */
197	int		tdq_transferable;	/* Transferable thread count. */
198	LIST_ENTRY(tdq)	tdq_siblings;		/* Next in tdq group. */
199	struct tdq_group *tdq_group;		/* Our processor group. */
200#else
201	int		tdq_sysload;		/* For loadavg, !ITHD load. */
202#endif
203	char		tdq_name[16];		/* lock name. */
204} __aligned(64);
205
206
207#ifdef SMP
208/*
209 * tdq groups are groups of processors which can cheaply share threads.  When
210 * one processor in the group goes idle it will check the runqs of the other
211 * processors in its group prior to halting and waiting for an interrupt.
212 * These groups are suitable for SMT (Symetric Multi-Threading) and not NUMA.
213 * In a numa environment we'd want an idle bitmap per group and a two tiered
214 * load balancer.
215 */
216struct tdq_group {
217	int	tdg_cpus;		/* Count of CPUs in this tdq group. */
218	cpumask_t tdg_cpumask;		/* Mask of cpus in this group. */
219	cpumask_t tdg_idlemask;		/* Idle cpus in this group. */
220	cpumask_t tdg_mask;		/* Bit mask for first cpu. */
221	int	tdg_load;		/* Total load of this group. */
222	int	tdg_transferable;	/* Transferable load of this group. */
223	LIST_HEAD(, tdq) tdg_members;	/* Linked list of all members. */
224} __aligned(64);
225
226#define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 300))
227#define	SCHED_AFFINITY(ts)	((ts)->ts_rltick > ticks - affinity)
228
229/*
230 * Run-time tunables.
231 */
232static int rebalance = 0;
233static int pick_pri = 0;
234static int pick_zero = 0;
235static int affinity;
236static int tryself = 1;
237static int tryselfidle = 1;
238static int steal_htt = 0;
239static int steal_idle = 0;
240static int topology = 0;
241
242/*
243 * One thread queue per processor.
244 */
245static volatile cpumask_t tdq_idle;
246static int tdg_maxid;
247static struct tdq	tdq_cpu[MAXCPU];
248static struct tdq_group tdq_groups[MAXCPU];
249static struct callout balco;
250static struct callout gbalco;
251
252#define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
253#define	TDQ_CPU(x)	(&tdq_cpu[(x)])
254#define	TDQ_ID(x)	((x) - tdq_cpu)
255#define	TDQ_GROUP(x)	(&tdq_groups[(x)])
256#else	/* !SMP */
257static struct tdq	tdq_cpu;
258
259#define	TDQ_ID(x)	(0)
260#define	TDQ_SELF()	(&tdq_cpu)
261#define	TDQ_CPU(x)	(&tdq_cpu)
262#endif
263
264#define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
265#define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
266#define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
267#define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
268#define	TDQ_LOCKPTR(t)		(&(t)->tdq_lock)
269
270static void sched_priority(struct thread *);
271static void sched_thread_priority(struct thread *, u_char);
272static int sched_interact_score(struct thread *);
273static void sched_interact_update(struct thread *);
274static void sched_interact_fork(struct thread *);
275static void sched_pctcpu_update(struct td_sched *);
276
277/* Operations on per processor queues */
278static struct td_sched * tdq_choose(struct tdq *);
279static void tdq_setup(struct tdq *);
280static void tdq_load_add(struct tdq *, struct td_sched *);
281static void tdq_load_rem(struct tdq *, struct td_sched *);
282static __inline void tdq_runq_add(struct tdq *, struct td_sched *, int);
283static __inline void tdq_runq_rem(struct tdq *, struct td_sched *);
284void tdq_print(int cpu);
285static void runq_print(struct runq *rq);
286static void tdq_add(struct tdq *, struct thread *, int);
287#ifdef SMP
288static void tdq_move(struct tdq *, struct tdq *);
289static int tdq_idled(struct tdq *);
290static void tdq_notify(struct td_sched *);
291static struct td_sched *tdq_steal(struct tdq *, int);
292static struct td_sched *runq_steal(struct runq *);
293static int sched_pickcpu(struct td_sched *, int);
294static void sched_balance(void *);
295static void sched_balance_groups(void *);
296static void sched_balance_group(struct tdq_group *);
297static void sched_balance_pair(struct tdq *, struct tdq *);
298static inline struct tdq *sched_setcpu(struct td_sched *, int, int);
299static inline struct mtx *thread_block_switch(struct thread *);
300static inline void thread_unblock_switch(struct thread *, struct mtx *);
301
302#define	THREAD_CAN_MIGRATE(td)	 ((td)->td_pinned == 0)
303#endif
304
305static void sched_setup(void *dummy);
306SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
307
308static void sched_initticks(void *dummy);
309SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks, NULL)
310
311/*
312 * Print the threads waiting on a run-queue.
313 */
314static void
315runq_print(struct runq *rq)
316{
317	struct rqhead *rqh;
318	struct td_sched *ts;
319	int pri;
320	int j;
321	int i;
322
323	for (i = 0; i < RQB_LEN; i++) {
324		printf("\t\trunq bits %d 0x%zx\n",
325		    i, rq->rq_status.rqb_bits[i]);
326		for (j = 0; j < RQB_BPW; j++)
327			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
328				pri = j + (i << RQB_L2BPW);
329				rqh = &rq->rq_queues[pri];
330				TAILQ_FOREACH(ts, rqh, ts_procq) {
331					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
332					    ts->ts_thread, ts->ts_thread->td_proc->p_comm, ts->ts_thread->td_priority, ts->ts_rqindex, pri);
333				}
334			}
335	}
336}
337
338/*
339 * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
340 */
341void
342tdq_print(int cpu)
343{
344	struct tdq *tdq;
345
346	tdq = TDQ_CPU(cpu);
347
348	printf("tdq:\n");
349	printf("\tlockptr         %p\n", TDQ_LOCKPTR(tdq));
350	printf("\tlock name       %s\n", tdq->tdq_name);
351	printf("\tload:           %d\n", tdq->tdq_load);
352	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
353	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
354	printf("\trealtime runq:\n");
355	runq_print(&tdq->tdq_realtime);
356	printf("\ttimeshare runq:\n");
357	runq_print(&tdq->tdq_timeshare);
358	printf("\tidle runq:\n");
359	runq_print(&tdq->tdq_idle);
360#ifdef SMP
361	printf("\tload transferable: %d\n", tdq->tdq_transferable);
362	printf("\tlowest priority: %d\n", tdq->tdq_lowpri);
363#endif
364}
365
366#define	TS_RQ_PPQ	(((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
367/*
368 * Add a thread to the actual run-queue.  Keeps transferable counts up to
369 * date with what is actually on the run-queue.  Selects the correct
370 * queue position for timeshare threads.
371 */
372static __inline void
373tdq_runq_add(struct tdq *tdq, struct td_sched *ts, int flags)
374{
375	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
376	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
377#ifdef SMP
378	if (THREAD_CAN_MIGRATE(ts->ts_thread)) {
379		tdq->tdq_transferable++;
380		tdq->tdq_group->tdg_transferable++;
381		ts->ts_flags |= TSF_XFERABLE;
382	}
383#endif
384	if (ts->ts_runq == &tdq->tdq_timeshare) {
385		u_char pri;
386
387		pri = ts->ts_thread->td_priority;
388		KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
389			("Invalid priority %d on timeshare runq", pri));
390		/*
391		 * This queue contains only priorities between MIN and MAX
392		 * realtime.  Use the whole queue to represent these values.
393		 */
394		if ((flags & SRQ_BORROWING) == 0) {
395			pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
396			pri = (pri + tdq->tdq_idx) % RQ_NQS;
397			/*
398			 * This effectively shortens the queue by one so we
399			 * can have a one slot difference between idx and
400			 * ridx while we wait for threads to drain.
401			 */
402			if (tdq->tdq_ridx != tdq->tdq_idx &&
403			    pri == tdq->tdq_ridx)
404				pri = (unsigned char)(pri - 1) % RQ_NQS;
405		} else
406			pri = tdq->tdq_ridx;
407		runq_add_pri(ts->ts_runq, ts, pri, flags);
408	} else
409		runq_add(ts->ts_runq, ts, flags);
410}
411
412/*
413 * Remove a thread from a run-queue.  This typically happens when a thread
414 * is selected to run.  Running threads are not on the queue and the
415 * transferable count does not reflect them.
416 */
417static __inline void
418tdq_runq_rem(struct tdq *tdq, struct td_sched *ts)
419{
420	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
421	KASSERT(ts->ts_runq != NULL,
422	    ("tdq_runq_remove: thread %p null ts_runq", ts->ts_thread));
423#ifdef SMP
424	if (ts->ts_flags & TSF_XFERABLE) {
425		tdq->tdq_transferable--;
426		tdq->tdq_group->tdg_transferable--;
427		ts->ts_flags &= ~TSF_XFERABLE;
428	}
429#endif
430	if (ts->ts_runq == &tdq->tdq_timeshare) {
431		if (tdq->tdq_idx != tdq->tdq_ridx)
432			runq_remove_idx(ts->ts_runq, ts, &tdq->tdq_ridx);
433		else
434			runq_remove_idx(ts->ts_runq, ts, NULL);
435		/*
436		 * For timeshare threads we update the priority here so
437		 * the priority reflects the time we've been sleeping.
438		 */
439		ts->ts_ltick = ticks;
440		sched_pctcpu_update(ts);
441		sched_priority(ts->ts_thread);
442	} else
443		runq_remove(ts->ts_runq, ts);
444}
445
446/*
447 * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
448 * for this thread to the referenced thread queue.
449 */
450static void
451tdq_load_add(struct tdq *tdq, struct td_sched *ts)
452{
453	int class;
454
455	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
456	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
457	class = PRI_BASE(ts->ts_thread->td_pri_class);
458	tdq->tdq_load++;
459	CTR2(KTR_SCHED, "cpu %jd load: %d", TDQ_ID(tdq), tdq->tdq_load);
460	if (class != PRI_ITHD &&
461	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
462#ifdef SMP
463		tdq->tdq_group->tdg_load++;
464#else
465		tdq->tdq_sysload++;
466#endif
467}
468
469/*
470 * Remove the load from a thread that is transitioning to a sleep state or
471 * exiting.
472 */
473static void
474tdq_load_rem(struct tdq *tdq, struct td_sched *ts)
475{
476	int class;
477
478	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
479	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
480	class = PRI_BASE(ts->ts_thread->td_pri_class);
481	if (class != PRI_ITHD &&
482	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
483#ifdef SMP
484		tdq->tdq_group->tdg_load--;
485#else
486		tdq->tdq_sysload--;
487#endif
488	KASSERT(tdq->tdq_load != 0,
489	    ("tdq_load_rem: Removing with 0 load on queue %d", (int)TDQ_ID(tdq)));
490	tdq->tdq_load--;
491	CTR1(KTR_SCHED, "load: %d", tdq->tdq_load);
492	ts->ts_runq = NULL;
493}
494
495#ifdef SMP
496/*
497 * sched_balance is a simple CPU load balancing algorithm.  It operates by
498 * finding the least loaded and most loaded cpu and equalizing their load
499 * by migrating some processes.
500 *
501 * Dealing only with two CPUs at a time has two advantages.  Firstly, most
502 * installations will only have 2 cpus.  Secondly, load balancing too much at
503 * once can have an unpleasant effect on the system.  The scheduler rarely has
504 * enough information to make perfect decisions.  So this algorithm chooses
505 * simplicity and more gradual effects on load in larger systems.
506 *
507 */
508static void
509sched_balance(void *arg)
510{
511	struct tdq_group *high;
512	struct tdq_group *low;
513	struct tdq_group *tdg;
514	int cnt;
515	int i;
516
517	callout_reset(&balco, max(hz / 2, random() % (hz * SCHED_BAL_SECS)),
518	    sched_balance, NULL);
519	if (smp_started == 0 || rebalance == 0)
520		return;
521	low = high = NULL;
522	i = random() % (tdg_maxid + 1);
523	for (cnt = 0; cnt <= tdg_maxid; cnt++) {
524		tdg = TDQ_GROUP(i);
525		/*
526		 * Find the CPU with the highest load that has some
527		 * threads to transfer.
528		 */
529		if ((high == NULL || tdg->tdg_load > high->tdg_load)
530		    && tdg->tdg_transferable)
531			high = tdg;
532		if (low == NULL || tdg->tdg_load < low->tdg_load)
533			low = tdg;
534		if (++i > tdg_maxid)
535			i = 0;
536	}
537	if (low != NULL && high != NULL && high != low)
538		sched_balance_pair(LIST_FIRST(&high->tdg_members),
539		    LIST_FIRST(&low->tdg_members));
540}
541
542/*
543 * Balance load between CPUs in a group.  Will only migrate within the group.
544 */
545static void
546sched_balance_groups(void *arg)
547{
548	int i;
549
550	callout_reset(&gbalco, max(hz / 2, random() % (hz * SCHED_BAL_SECS)),
551	    sched_balance_groups, NULL);
552	if (smp_started == 0 || rebalance == 0)
553		return;
554	for (i = 0; i <= tdg_maxid; i++)
555		sched_balance_group(TDQ_GROUP(i));
556}
557
558/*
559 * Finds the greatest imbalance between two tdqs in a group.
560 */
561static void
562sched_balance_group(struct tdq_group *tdg)
563{
564	struct tdq *tdq;
565	struct tdq *high;
566	struct tdq *low;
567	int load;
568
569	if (tdg->tdg_transferable == 0)
570		return;
571	low = NULL;
572	high = NULL;
573	LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
574		load = tdq->tdq_load;
575		if (high == NULL || load > high->tdq_load)
576			high = tdq;
577		if (low == NULL || load < low->tdq_load)
578			low = tdq;
579	}
580	if (high != NULL && low != NULL && high != low)
581		sched_balance_pair(high, low);
582}
583
584/*
585 * Lock two thread queues using their address to maintain lock order.
586 */
587static void
588tdq_lock_pair(struct tdq *one, struct tdq *two)
589{
590	if (one < two) {
591		TDQ_LOCK(one);
592		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
593	} else {
594		TDQ_LOCK(two);
595		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
596	}
597}
598
599/*
600 * Transfer load between two imbalanced thread queues.
601 */
602static void
603sched_balance_pair(struct tdq *high, struct tdq *low)
604{
605	int transferable;
606	int high_load;
607	int low_load;
608	int move;
609	int diff;
610	int i;
611
612	tdq_lock_pair(high, low);
613	/*
614	 * If we're transfering within a group we have to use this specific
615	 * tdq's transferable count, otherwise we can steal from other members
616	 * of the group.
617	 */
618	if (high->tdq_group == low->tdq_group) {
619		transferable = high->tdq_transferable;
620		high_load = high->tdq_load;
621		low_load = low->tdq_load;
622	} else {
623		transferable = high->tdq_group->tdg_transferable;
624		high_load = high->tdq_group->tdg_load;
625		low_load = low->tdq_group->tdg_load;
626	}
627	/*
628	 * Determine what the imbalance is and then adjust that to how many
629	 * threads we actually have to give up (transferable).
630	 */
631	if (transferable != 0) {
632		diff = high_load - low_load;
633		move = diff / 2;
634		if (diff & 0x1)
635			move++;
636		move = min(move, transferable);
637		for (i = 0; i < move; i++)
638			tdq_move(high, low);
639	}
640	TDQ_UNLOCK(high);
641	TDQ_UNLOCK(low);
642	return;
643}
644
645/*
646 * Move a thread from one thread queue to another.
647 */
648static void
649tdq_move(struct tdq *from, struct tdq *to)
650{
651	struct td_sched *ts;
652	struct thread *td;
653	struct tdq *tdq;
654	int cpu;
655
656	tdq = from;
657	cpu = TDQ_ID(to);
658	ts = tdq_steal(tdq, 1);
659	if (ts == NULL) {
660		struct tdq_group *tdg;
661
662		tdg = tdq->tdq_group;
663		LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
664			if (tdq == from || tdq->tdq_transferable == 0)
665				continue;
666			ts = tdq_steal(tdq, 1);
667			break;
668		}
669		if (ts == NULL)
670			return;
671	}
672	if (tdq == to)
673		return;
674	td = ts->ts_thread;
675	/*
676	 * Although the run queue is locked the thread may be blocked.  Lock
677	 * it to clear this.
678	 */
679	thread_lock(td);
680	/* Drop recursive lock on from. */
681	TDQ_UNLOCK(from);
682	sched_rem(td);
683	ts->ts_cpu = cpu;
684	td->td_lock = TDQ_LOCKPTR(to);
685	tdq_add(to, td, SRQ_YIELDING);
686}
687
688/*
689 * This tdq has idled.  Try to steal a thread from another cpu and switch
690 * to it.
691 */
692static int
693tdq_idled(struct tdq *tdq)
694{
695	struct tdq_group *tdg;
696	struct tdq *steal;
697	struct td_sched *ts;
698	struct thread *td;
699	int highload;
700	int highcpu;
701	int load;
702	int cpu;
703
704	/* We don't want to be preempted while we're iterating over tdqs */
705	spinlock_enter();
706	tdg = tdq->tdq_group;
707	/*
708	 * If we're in a cpu group, try and steal threads from another cpu in
709	 * the group before idling.
710	 */
711	if (steal_htt && tdg->tdg_cpus > 1 && tdg->tdg_transferable) {
712		LIST_FOREACH(steal, &tdg->tdg_members, tdq_siblings) {
713			if (steal == tdq || steal->tdq_transferable == 0)
714				continue;
715			TDQ_LOCK(steal);
716			ts = tdq_steal(steal, 0);
717			if (ts)
718				goto steal;
719			TDQ_UNLOCK(steal);
720		}
721	}
722	for (;;) {
723		if (steal_idle == 0)
724			break;
725		highcpu = 0;
726		highload = 0;
727		for (cpu = 0; cpu <= mp_maxid; cpu++) {
728			if (CPU_ABSENT(cpu))
729				continue;
730			steal = TDQ_CPU(cpu);
731			load = TDQ_CPU(cpu)->tdq_transferable;
732			if (load < highload)
733				continue;
734			highload = load;
735			highcpu = cpu;
736		}
737		if (highload < 2)
738			break;
739		steal = TDQ_CPU(highcpu);
740		TDQ_LOCK(steal);
741		if (steal->tdq_transferable > 1 &&
742		    (ts = tdq_steal(steal, 1)) != NULL)
743			goto steal;
744		TDQ_UNLOCK(steal);
745		break;
746	}
747	spinlock_exit();
748	return (1);
749steal:
750	td = ts->ts_thread;
751	thread_lock(td);
752	spinlock_exit();
753	MPASS(td->td_lock == TDQ_LOCKPTR(steal));
754	TDQ_UNLOCK(steal);
755	sched_rem(td);
756	sched_setcpu(ts, PCPU_GET(cpuid), SRQ_YIELDING);
757	tdq_add(tdq, td, SRQ_YIELDING);
758	MPASS(td->td_lock == curthread->td_lock);
759	mi_switch(SW_VOL, NULL);
760	thread_unlock(curthread);
761
762	return (0);
763}
764
765/*
766 * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
767 */
768static void
769tdq_notify(struct td_sched *ts)
770{
771	struct thread *ctd;
772	struct pcpu *pcpu;
773	int cpri;
774	int pri;
775	int cpu;
776
777	cpu = ts->ts_cpu;
778	pri = ts->ts_thread->td_priority;
779	pcpu = pcpu_find(cpu);
780	ctd = pcpu->pc_curthread;
781	cpri = ctd->td_priority;
782
783	/*
784	 * If our priority is not better than the current priority there is
785	 * nothing to do.
786	 */
787	if (pri > cpri)
788		return;
789	/*
790	 * Always IPI idle.
791	 */
792	if (cpri > PRI_MIN_IDLE)
793		goto sendipi;
794	/*
795	 * If we're realtime or better and there is timeshare or worse running
796	 * send an IPI.
797	 */
798	if (pri < PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
799		goto sendipi;
800	/*
801	 * Otherwise only IPI if we exceed the threshold.
802	 */
803	if (pri > preempt_thresh)
804		return;
805sendipi:
806	ctd->td_flags |= TDF_NEEDRESCHED;
807	ipi_selected(1 << cpu, IPI_PREEMPT);
808}
809
810/*
811 * Steals load from a timeshare queue.  Honors the rotating queue head
812 * index.
813 */
814static struct td_sched *
815runq_steal_from(struct runq *rq, u_char start)
816{
817	struct td_sched *ts;
818	struct rqbits *rqb;
819	struct rqhead *rqh;
820	int first;
821	int bit;
822	int pri;
823	int i;
824
825	rqb = &rq->rq_status;
826	bit = start & (RQB_BPW -1);
827	pri = 0;
828	first = 0;
829again:
830	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
831		if (rqb->rqb_bits[i] == 0)
832			continue;
833		if (bit != 0) {
834			for (pri = bit; pri < RQB_BPW; pri++)
835				if (rqb->rqb_bits[i] & (1ul << pri))
836					break;
837			if (pri >= RQB_BPW)
838				continue;
839		} else
840			pri = RQB_FFS(rqb->rqb_bits[i]);
841		pri += (i << RQB_L2BPW);
842		rqh = &rq->rq_queues[pri];
843		TAILQ_FOREACH(ts, rqh, ts_procq) {
844			if (first && THREAD_CAN_MIGRATE(ts->ts_thread))
845				return (ts);
846			first = 1;
847		}
848	}
849	if (start != 0) {
850		start = 0;
851		goto again;
852	}
853
854	return (NULL);
855}
856
857/*
858 * Steals load from a standard linear queue.
859 */
860static struct td_sched *
861runq_steal(struct runq *rq)
862{
863	struct rqhead *rqh;
864	struct rqbits *rqb;
865	struct td_sched *ts;
866	int first;
867	int word;
868	int bit;
869
870	first = 0;
871	rqb = &rq->rq_status;
872	for (word = 0; word < RQB_LEN; word++) {
873		if (rqb->rqb_bits[word] == 0)
874			continue;
875		for (bit = 0; bit < RQB_BPW; bit++) {
876			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
877				continue;
878			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
879			TAILQ_FOREACH(ts, rqh, ts_procq) {
880				if (first && THREAD_CAN_MIGRATE(ts->ts_thread))
881					return (ts);
882				first = 1;
883			}
884		}
885	}
886	return (NULL);
887}
888
889/*
890 * Attempt to steal a thread in priority order from a thread queue.
891 */
892static struct td_sched *
893tdq_steal(struct tdq *tdq, int stealidle)
894{
895	struct td_sched *ts;
896
897	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
898	if ((ts = runq_steal(&tdq->tdq_realtime)) != NULL)
899		return (ts);
900	if ((ts = runq_steal_from(&tdq->tdq_timeshare, tdq->tdq_ridx)) != NULL)
901		return (ts);
902	if (stealidle)
903		return (runq_steal(&tdq->tdq_idle));
904	return (NULL);
905}
906
907/*
908 * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
909 * current lock and returns with the assigned queue locked.  If this is
910 * via sched_switch() we leave the thread in a blocked state as an
911 * optimization.
912 */
913static inline struct tdq *
914sched_setcpu(struct td_sched *ts, int cpu, int flags)
915{
916	struct thread *td;
917	struct tdq *tdq;
918
919	THREAD_LOCK_ASSERT(ts->ts_thread, MA_OWNED);
920
921	tdq = TDQ_CPU(cpu);
922	td = ts->ts_thread;
923	ts->ts_cpu = cpu;
924	if (td->td_lock == TDQ_LOCKPTR(tdq))
925		return (tdq);
926#ifdef notyet
927	/*
928	 * If the thread isn't running it's lockptr is a
929	 * turnstile or a sleepqueue.  We can just lock_set without
930	 * blocking.
931	 */
932	if (TD_CAN_RUN(td)) {
933		TDQ_LOCK(tdq);
934		thread_lock_set(td, TDQ_LOCKPTR(tdq));
935		return (tdq);
936	}
937#endif
938	/*
939	 * The hard case, migration, we need to block the thread first to
940	 * prevent order reversals with other cpus locks.
941	 */
942	thread_lock_block(td);
943	TDQ_LOCK(tdq);
944	/* Return to sched_switch() with the lock still blocked */
945	if ((flags & SRQ_OURSELF) == 0)
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	pri = ts->ts_thread->td_priority;
1040	cpu = ts->ts_cpu;
1041	/*
1042	 * Regardless of affinity, if the last cpu is idle send it there.
1043	 */
1044	tdq = TDQ_CPU(cpu);
1045	if (tdq->tdq_lowpri > PRI_MIN_IDLE) {
1046		CTR5(KTR_ULE,
1047		    "ts_cpu %d idle, ltick %d ticks %d pri %d curthread %d",
1048		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1049		    tdq->tdq_lowpri);
1050		return (ts->ts_cpu);
1051	}
1052	/*
1053	 * If we have affinity, try to place it on the cpu we last ran on.
1054	 */
1055	if (SCHED_AFFINITY(ts) && tdq->tdq_lowpri > pri) {
1056		CTR5(KTR_ULE,
1057		    "affinity for %d, ltick %d ticks %d pri %d curthread %d",
1058		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
1059		    tdq->tdq_lowpri);
1060		return (ts->ts_cpu);
1061	}
1062	/*
1063	 * Try ourself first; If we're running something lower priority this
1064	 * may have some locality with the waking thread and execute faster
1065	 * here.
1066	 */
1067	if (tryself) {
1068		/*
1069		 * If we're being awoken by an interrupt thread or the waker
1070		 * is going right to sleep run here as well.
1071		 */
1072		if ((TDQ_SELF()->tdq_load <= 1) && (flags & (SRQ_YIELDING) ||
1073		    curthread->td_pri_class == PRI_ITHD)) {
1074			CTR2(KTR_ULE, "tryself load %d flags %d",
1075			    TDQ_SELF()->tdq_load, flags);
1076			return (self);
1077		}
1078	}
1079	/*
1080	 * Look for an idle group.
1081	 */
1082	CTR1(KTR_ULE, "tdq_idle %X", tdq_idle);
1083	cpu = ffs(tdq_idle);
1084	if (cpu)
1085		return (--cpu);
1086	if (tryselfidle && pri < curthread->td_priority) {
1087		CTR1(KTR_ULE, "tryselfidle %d",
1088		    curthread->td_priority);
1089		return (self);
1090	}
1091	/*
1092	 * XXX Under heavy load mysql performs way better if you
1093	 * serialize the non-running threads on one cpu.  This is
1094	 * a horrible hack.
1095	 */
1096	if (pick_zero)
1097		return (0);
1098	/*
1099 	 * Now search for the cpu running the lowest priority thread with
1100	 * the least load.
1101	 */
1102	if (pick_pri)
1103		cpu = tdq_lowestpri();
1104	else
1105		cpu = tdq_lowestload();
1106	return (cpu);
1107}
1108
1109#endif	/* SMP */
1110
1111/*
1112 * Pick the highest priority task we have and return it.
1113 */
1114static struct td_sched *
1115tdq_choose(struct tdq *tdq)
1116{
1117	struct td_sched *ts;
1118
1119	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1120	ts = runq_choose(&tdq->tdq_realtime);
1121	if (ts != NULL)
1122		return (ts);
1123	ts = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1124	if (ts != NULL) {
1125		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_TIMESHARE,
1126		    ("tdq_choose: Invalid priority on timeshare queue %d",
1127		    ts->ts_thread->td_priority));
1128		return (ts);
1129	}
1130
1131	ts = runq_choose(&tdq->tdq_idle);
1132	if (ts != NULL) {
1133		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_IDLE,
1134		    ("tdq_choose: Invalid priority on idle queue %d",
1135		    ts->ts_thread->td_priority));
1136		return (ts);
1137	}
1138
1139	return (NULL);
1140}
1141
1142/*
1143 * Initialize a thread queue.
1144 */
1145static void
1146tdq_setup(struct tdq *tdq)
1147{
1148
1149	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1150	    "sched lock %d", (int)TDQ_ID(tdq));
1151	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1152	    MTX_SPIN | MTX_RECURSE);
1153	runq_init(&tdq->tdq_realtime);
1154	runq_init(&tdq->tdq_timeshare);
1155	runq_init(&tdq->tdq_idle);
1156	tdq->tdq_load = 0;
1157}
1158
1159/*
1160 * Setup the thread queues and initialize the topology based on MD
1161 * information.
1162 */
1163static void
1164sched_setup(void *dummy)
1165{
1166	struct tdq *tdq;
1167#ifdef SMP
1168	int balance_groups;
1169	int i;
1170
1171	balance_groups = 0;
1172	/*
1173	 * Initialize the tdqs.
1174	 */
1175	for (i = 0; i < MAXCPU; i++) {
1176		tdq = &tdq_cpu[i];
1177		tdq_setup(&tdq_cpu[i]);
1178	}
1179	if (smp_topology == NULL) {
1180		struct tdq_group *tdg;
1181		int cpus;
1182
1183		for (cpus = 0, i = 0; i < MAXCPU; i++) {
1184			if (CPU_ABSENT(i))
1185				continue;
1186			tdq = &tdq_cpu[i];
1187			tdg = &tdq_groups[cpus];
1188			/*
1189			 * Setup a tdq group with one member.
1190			 */
1191			tdq->tdq_transferable = 0;
1192			tdq->tdq_group = tdg;
1193			tdg->tdg_cpus = 1;
1194			tdg->tdg_idlemask = 0;
1195			tdg->tdg_cpumask = tdg->tdg_mask = 1 << i;
1196			tdg->tdg_load = 0;
1197			tdg->tdg_transferable = 0;
1198			LIST_INIT(&tdg->tdg_members);
1199			LIST_INSERT_HEAD(&tdg->tdg_members, tdq, tdq_siblings);
1200			cpus++;
1201		}
1202		tdg_maxid = cpus - 1;
1203	} else {
1204		struct tdq_group *tdg;
1205		struct cpu_group *cg;
1206		int j;
1207
1208		topology = 1;
1209		for (i = 0; i < smp_topology->ct_count; i++) {
1210			cg = &smp_topology->ct_group[i];
1211			tdg = &tdq_groups[i];
1212			/*
1213			 * Initialize the group.
1214			 */
1215			tdg->tdg_idlemask = 0;
1216			tdg->tdg_load = 0;
1217			tdg->tdg_transferable = 0;
1218			tdg->tdg_cpus = cg->cg_count;
1219			tdg->tdg_cpumask = cg->cg_mask;
1220			LIST_INIT(&tdg->tdg_members);
1221			/*
1222			 * Find all of the group members and add them.
1223			 */
1224			for (j = 0; j < MAXCPU; j++) {
1225				if ((cg->cg_mask & (1 << j)) != 0) {
1226					if (tdg->tdg_mask == 0)
1227						tdg->tdg_mask = 1 << j;
1228					tdq_cpu[j].tdq_transferable = 0;
1229					tdq_cpu[j].tdq_group = tdg;
1230					LIST_INSERT_HEAD(&tdg->tdg_members,
1231					    &tdq_cpu[j], tdq_siblings);
1232				}
1233			}
1234			if (tdg->tdg_cpus > 1)
1235				balance_groups = 1;
1236		}
1237		tdg_maxid = smp_topology->ct_count - 1;
1238	}
1239	/*
1240	 * Initialize long-term cpu balancing algorithm.
1241	 */
1242	callout_init(&balco, CALLOUT_MPSAFE);
1243	callout_init(&gbalco, CALLOUT_MPSAFE);
1244	sched_balance(NULL);
1245	if (balance_groups)
1246		sched_balance_groups(NULL);
1247
1248#else
1249	tdq_setup(TDQ_SELF());
1250#endif
1251	/*
1252	 * To avoid divide-by-zero, we set realstathz a dummy value
1253	 * in case which sched_clock() called before sched_initticks().
1254	 */
1255	realstathz = hz;
1256	sched_slice = (realstathz/10);	/* ~100ms */
1257	tickincr = 1 << SCHED_TICK_SHIFT;
1258
1259	/* Add thread0's load since it's running. */
1260	tdq = TDQ_SELF();
1261	TDQ_LOCK(tdq);
1262	tdq_load_add(tdq, &td_sched0);
1263	TDQ_UNLOCK(tdq);
1264}
1265
1266/*
1267 * This routine determines the tickincr after stathz and hz are setup.
1268 */
1269/* ARGSUSED */
1270static void
1271sched_initticks(void *dummy)
1272{
1273	int incr;
1274
1275	realstathz = stathz ? stathz : hz;
1276	sched_slice = (realstathz/10);	/* ~100ms */
1277
1278	/*
1279	 * tickincr is shifted out by 10 to avoid rounding errors due to
1280	 * hz not being evenly divisible by stathz on all platforms.
1281	 */
1282	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1283	/*
1284	 * This does not work for values of stathz that are more than
1285	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1286	 */
1287	if (incr == 0)
1288		incr = 1;
1289	tickincr = incr;
1290#ifdef SMP
1291	affinity = SCHED_AFFINITY_DEFAULT;
1292#endif
1293}
1294
1295
1296/*
1297 * This is the core of the interactivity algorithm.  Determines a score based
1298 * on past behavior.  It is the ratio of sleep time to run time scaled to
1299 * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1300 * differs from the cpu usage because it does not account for time spent
1301 * waiting on a run-queue.  Would be prettier if we had floating point.
1302 */
1303static int
1304sched_interact_score(struct thread *td)
1305{
1306	struct td_sched *ts;
1307	int div;
1308
1309	ts = td->td_sched;
1310	/*
1311	 * The score is only needed if this is likely to be an interactive
1312	 * task.  Don't go through the expense of computing it if there's
1313	 * no chance.
1314	 */
1315	if (sched_interact <= SCHED_INTERACT_HALF &&
1316		ts->ts_runtime >= ts->ts_slptime)
1317			return (SCHED_INTERACT_HALF);
1318
1319	if (ts->ts_runtime > ts->ts_slptime) {
1320		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1321		return (SCHED_INTERACT_HALF +
1322		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1323	}
1324	if (ts->ts_slptime > ts->ts_runtime) {
1325		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1326		return (ts->ts_runtime / div);
1327	}
1328	/* runtime == slptime */
1329	if (ts->ts_runtime)
1330		return (SCHED_INTERACT_HALF);
1331
1332	/*
1333	 * This can happen if slptime and runtime are 0.
1334	 */
1335	return (0);
1336
1337}
1338
1339/*
1340 * Scale the scheduling priority according to the "interactivity" of this
1341 * process.
1342 */
1343static void
1344sched_priority(struct thread *td)
1345{
1346	int score;
1347	int pri;
1348
1349	if (td->td_pri_class != PRI_TIMESHARE)
1350		return;
1351	/*
1352	 * If the score is interactive we place the thread in the realtime
1353	 * queue with a priority that is less than kernel and interrupt
1354	 * priorities.  These threads are not subject to nice restrictions.
1355	 *
1356	 * Scores greater than this are placed on the normal timeshare queue
1357	 * where the priority is partially decided by the most recent cpu
1358	 * utilization and the rest is decided by nice value.
1359	 */
1360	score = sched_interact_score(td);
1361	if (score < sched_interact) {
1362		pri = PRI_MIN_REALTIME;
1363		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1364		    * score;
1365		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1366		    ("sched_priority: invalid interactive priority %d score %d",
1367		    pri, score));
1368	} else {
1369		pri = SCHED_PRI_MIN;
1370		if (td->td_sched->ts_ticks)
1371			pri += SCHED_PRI_TICKS(td->td_sched);
1372		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1373		KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1374		    ("sched_priority: invalid priority %d: nice %d, "
1375		    "ticks %d ftick %d ltick %d tick pri %d",
1376		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1377		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1378		    SCHED_PRI_TICKS(td->td_sched)));
1379	}
1380	sched_user_prio(td, pri);
1381
1382	return;
1383}
1384
1385/*
1386 * This routine enforces a maximum limit on the amount of scheduling history
1387 * kept.  It is called after either the slptime or runtime is adjusted.  This
1388 * function is ugly due to integer math.
1389 */
1390static void
1391sched_interact_update(struct thread *td)
1392{
1393	struct td_sched *ts;
1394	u_int sum;
1395
1396	ts = td->td_sched;
1397	sum = ts->ts_runtime + ts->ts_slptime;
1398	if (sum < SCHED_SLP_RUN_MAX)
1399		return;
1400	/*
1401	 * This only happens from two places:
1402	 * 1) We have added an unusual amount of run time from fork_exit.
1403	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1404	 */
1405	if (sum > SCHED_SLP_RUN_MAX * 2) {
1406		if (ts->ts_runtime > ts->ts_slptime) {
1407			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1408			ts->ts_slptime = 1;
1409		} else {
1410			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1411			ts->ts_runtime = 1;
1412		}
1413		return;
1414	}
1415	/*
1416	 * If we have exceeded by more than 1/5th then the algorithm below
1417	 * will not bring us back into range.  Dividing by two here forces
1418	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1419	 */
1420	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1421		ts->ts_runtime /= 2;
1422		ts->ts_slptime /= 2;
1423		return;
1424	}
1425	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1426	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1427}
1428
1429/*
1430 * Scale back the interactivity history when a child thread is created.  The
1431 * history is inherited from the parent but the thread may behave totally
1432 * differently.  For example, a shell spawning a compiler process.  We want
1433 * to learn that the compiler is behaving badly very quickly.
1434 */
1435static void
1436sched_interact_fork(struct thread *td)
1437{
1438	int ratio;
1439	int sum;
1440
1441	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1442	if (sum > SCHED_SLP_RUN_FORK) {
1443		ratio = sum / SCHED_SLP_RUN_FORK;
1444		td->td_sched->ts_runtime /= ratio;
1445		td->td_sched->ts_slptime /= ratio;
1446	}
1447}
1448
1449/*
1450 * Called from proc0_init() to setup the scheduler fields.
1451 */
1452void
1453schedinit(void)
1454{
1455
1456	/*
1457	 * Set up the scheduler specific parts of proc0.
1458	 */
1459	proc0.p_sched = NULL; /* XXX */
1460	thread0.td_sched = &td_sched0;
1461	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1462	td_sched0.ts_ltick = ticks;
1463	td_sched0.ts_ftick = ticks;
1464	td_sched0.ts_thread = &thread0;
1465}
1466
1467/*
1468 * This is only somewhat accurate since given many processes of the same
1469 * priority they will switch when their slices run out, which will be
1470 * at most sched_slice stathz ticks.
1471 */
1472int
1473sched_rr_interval(void)
1474{
1475
1476	/* Convert sched_slice to hz */
1477	return (hz/(realstathz/sched_slice));
1478}
1479
1480/*
1481 * Update the percent cpu tracking information when it is requested or
1482 * the total history exceeds the maximum.  We keep a sliding history of
1483 * tick counts that slowly decays.  This is less precise than the 4BSD
1484 * mechanism since it happens with less regular and frequent events.
1485 */
1486static void
1487sched_pctcpu_update(struct td_sched *ts)
1488{
1489
1490	if (ts->ts_ticks == 0)
1491		return;
1492	if (ticks - (hz / 10) < ts->ts_ltick &&
1493	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1494		return;
1495	/*
1496	 * Adjust counters and watermark for pctcpu calc.
1497	 */
1498	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1499		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1500			    SCHED_TICK_TARG;
1501	else
1502		ts->ts_ticks = 0;
1503	ts->ts_ltick = ticks;
1504	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1505}
1506
1507/*
1508 * Adjust the priority of a thread.  Move it to the appropriate run-queue
1509 * if necessary.  This is the back-end for several priority related
1510 * functions.
1511 */
1512static void
1513sched_thread_priority(struct thread *td, u_char prio)
1514{
1515	struct td_sched *ts;
1516
1517	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
1518	    td, td->td_proc->p_comm, td->td_priority, prio, curthread,
1519	    curthread->td_proc->p_comm);
1520	ts = td->td_sched;
1521	THREAD_LOCK_ASSERT(td, MA_OWNED);
1522	if (td->td_priority == prio)
1523		return;
1524
1525	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1526		/*
1527		 * If the priority has been elevated due to priority
1528		 * propagation, we may have to move ourselves to a new
1529		 * queue.  This could be optimized to not re-add in some
1530		 * cases.
1531		 */
1532		sched_rem(td);
1533		td->td_priority = prio;
1534		sched_add(td, SRQ_BORROWING);
1535	} else {
1536#ifdef SMP
1537		struct tdq *tdq;
1538
1539		tdq = TDQ_CPU(ts->ts_cpu);
1540		if (prio < tdq->tdq_lowpri)
1541			tdq->tdq_lowpri = prio;
1542#endif
1543		td->td_priority = prio;
1544	}
1545}
1546
1547/*
1548 * Update a thread's priority when it is lent another thread's
1549 * priority.
1550 */
1551void
1552sched_lend_prio(struct thread *td, u_char prio)
1553{
1554
1555	td->td_flags |= TDF_BORROWING;
1556	sched_thread_priority(td, prio);
1557}
1558
1559/*
1560 * Restore a thread's priority when priority propagation is
1561 * over.  The prio argument is the minimum priority the thread
1562 * needs to have to satisfy other possible priority lending
1563 * requests.  If the thread's regular priority is less
1564 * important than prio, the thread will keep a priority boost
1565 * of prio.
1566 */
1567void
1568sched_unlend_prio(struct thread *td, u_char prio)
1569{
1570	u_char base_pri;
1571
1572	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1573	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1574		base_pri = td->td_user_pri;
1575	else
1576		base_pri = td->td_base_pri;
1577	if (prio >= base_pri) {
1578		td->td_flags &= ~TDF_BORROWING;
1579		sched_thread_priority(td, base_pri);
1580	} else
1581		sched_lend_prio(td, prio);
1582}
1583
1584/*
1585 * Standard entry for setting the priority to an absolute value.
1586 */
1587void
1588sched_prio(struct thread *td, u_char prio)
1589{
1590	u_char oldprio;
1591
1592	/* First, update the base priority. */
1593	td->td_base_pri = prio;
1594
1595	/*
1596	 * If the thread is borrowing another thread's priority, don't
1597	 * ever lower the priority.
1598	 */
1599	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1600		return;
1601
1602	/* Change the real priority. */
1603	oldprio = td->td_priority;
1604	sched_thread_priority(td, prio);
1605
1606	/*
1607	 * If the thread is on a turnstile, then let the turnstile update
1608	 * its state.
1609	 */
1610	if (TD_ON_LOCK(td) && oldprio != prio)
1611		turnstile_adjust(td, oldprio);
1612}
1613
1614/*
1615 * Set the base user priority, does not effect current running priority.
1616 */
1617void
1618sched_user_prio(struct thread *td, u_char prio)
1619{
1620	u_char oldprio;
1621
1622	td->td_base_user_pri = prio;
1623	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1624                return;
1625	oldprio = td->td_user_pri;
1626	td->td_user_pri = prio;
1627
1628	if (TD_ON_UPILOCK(td) && oldprio != prio)
1629		umtx_pi_adjust(td, oldprio);
1630}
1631
1632void
1633sched_lend_user_prio(struct thread *td, u_char prio)
1634{
1635	u_char oldprio;
1636
1637	td->td_flags |= TDF_UBORROWING;
1638
1639	oldprio = td->td_user_pri;
1640	td->td_user_pri = prio;
1641
1642	if (TD_ON_UPILOCK(td) && oldprio != prio)
1643		umtx_pi_adjust(td, oldprio);
1644}
1645
1646void
1647sched_unlend_user_prio(struct thread *td, u_char prio)
1648{
1649	u_char base_pri;
1650
1651	base_pri = td->td_base_user_pri;
1652	if (prio >= base_pri) {
1653		td->td_flags &= ~TDF_UBORROWING;
1654		sched_user_prio(td, base_pri);
1655	} else
1656		sched_lend_user_prio(td, prio);
1657}
1658
1659/*
1660 * Block a thread for switching.  Similar to thread_block() but does not
1661 * bump the spin count.
1662 */
1663static inline struct mtx *
1664thread_block_switch(struct thread *td)
1665{
1666	struct mtx *lock;
1667
1668	THREAD_LOCK_ASSERT(td, MA_OWNED);
1669	lock = td->td_lock;
1670	td->td_lock = &blocked_lock;
1671	mtx_unlock_spin(lock);
1672
1673	return (lock);
1674}
1675
1676/*
1677 * Release a thread that was blocked with thread_block_switch().
1678 */
1679static inline void
1680thread_unblock_switch(struct thread *td, struct mtx *mtx)
1681{
1682	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1683	    (uintptr_t)mtx);
1684}
1685
1686/*
1687 * Switch threads.  This function has to handle threads coming in while
1688 * blocked for some reason, running, or idle.  It also must deal with
1689 * migrating a thread from one queue to another as running threads may
1690 * be assigned elsewhere via binding.
1691 */
1692void
1693sched_switch(struct thread *td, struct thread *newtd, int flags)
1694{
1695	struct tdq *tdq;
1696	struct td_sched *ts;
1697	struct mtx *mtx;
1698	int cpuid;
1699
1700	THREAD_LOCK_ASSERT(td, MA_OWNED);
1701
1702	cpuid = PCPU_GET(cpuid);
1703	tdq = TDQ_CPU(cpuid);
1704	ts = td->td_sched;
1705	mtx = TDQ_LOCKPTR(tdq);
1706#ifdef SMP
1707	ts->ts_rltick = ticks;
1708	if (newtd && newtd->td_priority < tdq->tdq_lowpri)
1709		tdq->tdq_lowpri = newtd->td_priority;
1710#endif
1711	td->td_lastcpu = td->td_oncpu;
1712	td->td_oncpu = NOCPU;
1713	td->td_flags &= ~TDF_NEEDRESCHED;
1714	td->td_owepreempt = 0;
1715	/*
1716	 * The lock pointer in an idle thread should never change.  Reset it
1717	 * to CAN_RUN as well.
1718	 */
1719	if (TD_IS_IDLETHREAD(td)) {
1720		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1721		TD_SET_CAN_RUN(td);
1722	} else if (TD_IS_RUNNING(td)) {
1723		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1724		/* Remove our load so the selection algorithm is not biased. */
1725		tdq_load_rem(tdq, ts);
1726		sched_add(td, (flags & SW_PREEMPT) ?
1727		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1728		    SRQ_OURSELF|SRQ_YIELDING);
1729		/*
1730		 * When migrating we return from sched_add with an extra
1731		 * spinlock nesting, the tdq locked, and a blocked thread.
1732		 * This is to optimize out an extra block/unblock cycle here.
1733		 */
1734		if (ts->ts_cpu != cpuid) {
1735			mtx = TDQ_LOCKPTR(TDQ_CPU(ts->ts_cpu));
1736			mtx_unlock_spin(mtx);
1737			TDQ_LOCK(tdq);
1738			spinlock_exit();
1739		}
1740	} else {
1741		/* This thread must be going to sleep. */
1742		TDQ_LOCK(tdq);
1743		mtx = thread_block_switch(td);
1744		tdq_load_rem(tdq, ts);
1745	}
1746	/*
1747	 * We enter here with the thread blocked and assigned to the
1748	 * appropriate cpu run-queue or sleep-queue and with the current
1749	 * thread-queue locked.
1750	 */
1751	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1752	/*
1753	 * If KSE assigned a new thread just add it here and pick the best one.
1754	 */
1755	if (newtd != NULL) {
1756		/* XXX This is bogus.  What if the thread is locked elsewhere? */
1757		td->td_lock = TDQ_LOCKPTR(tdq);
1758		td->td_sched->ts_cpu = cpuid;
1759		tdq_add(tdq, td, SRQ_YIELDING);
1760	}
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, pick_zero, CTLFLAG_RW, &pick_zero, 0,
2532    "If there are no idle cpus pick cpu0");
2533SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2534    "Number of hz ticks to keep thread affinity for");
2535SYSCTL_INT(_kern_sched, OID_AUTO, tryself, CTLFLAG_RW, &tryself, 0, "");
2536SYSCTL_INT(_kern_sched, OID_AUTO, tryselfidle, CTLFLAG_RW,
2537    &tryselfidle, 0, "");
2538SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2539    "Enables the long-term load balancer");
2540SYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2541    "Steals work from another hyper-threaded core on idle");
2542SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2543    "Attempts to steal work from other cores before idling");
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