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