sched_ule.c revision 177435
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 177435 2008-03-20 05:51:16Z 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(__i386__) && !defined(__amd64__) && !defined(__powerpc__) && !defined(__arm__)
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 = 1;
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	struct td_sched *ts;
464	int class;
465
466	ts = td->td_sched;
467	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
468	THREAD_LOCK_ASSERT(td, MA_OWNED);
469	class = PRI_BASE(td->td_pri_class);
470	tdq->tdq_load++;
471	CTR2(KTR_SCHED, "cpu %d load: %d", TDQ_ID(tdq), tdq->tdq_load);
472	if (class != PRI_ITHD && (td->td_proc->p_flag & P_NOLOAD) == 0)
473		tdq->tdq_sysload++;
474}
475
476/*
477 * Remove the load from a thread that is transitioning to a sleep state or
478 * exiting.
479 */
480static void
481tdq_load_rem(struct tdq *tdq, struct thread *td)
482{
483	struct td_sched *ts;
484	int class;
485
486	ts = td->td_sched;
487	THREAD_LOCK_ASSERT(td, MA_OWNED);
488	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
489	class = PRI_BASE(td->td_pri_class);
490	if (class != PRI_ITHD && (td->td_proc->p_flag & P_NOLOAD) == 0)
491		tdq->tdq_sysload--;
492	KASSERT(tdq->tdq_load != 0,
493	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
494	tdq->tdq_load--;
495	CTR1(KTR_SCHED, "load: %d", tdq->tdq_load);
496}
497
498/*
499 * Set lowpri to its exact value by searching the run-queue and
500 * evaluating curthread.  curthread may be passed as an optimization.
501 */
502static void
503tdq_setlowpri(struct tdq *tdq, struct thread *ctd)
504{
505	struct thread *td;
506
507	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
508	if (ctd == NULL)
509		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
510	td = tdq_choose(tdq);
511	if (td == NULL || td->td_priority > ctd->td_priority)
512		tdq->tdq_lowpri = ctd->td_priority;
513	else
514		tdq->tdq_lowpri = td->td_priority;
515}
516
517#ifdef SMP
518struct cpu_search {
519	cpumask_t cs_mask;	/* Mask of valid cpus. */
520	u_int	cs_load;
521	u_int	cs_cpu;
522	int	cs_limit;	/* Min priority for low min load for high. */
523};
524
525#define	CPU_SEARCH_LOWEST	0x1
526#define	CPU_SEARCH_HIGHEST	0x2
527#define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
528
529#define	CPUMASK_FOREACH(cpu, mask)				\
530	for ((cpu) = 0; (cpu) < sizeof((mask)) * 8; (cpu)++)	\
531		if ((mask) & 1 << (cpu))
532
533static __inline int cpu_search(struct cpu_group *cg, struct cpu_search *low,
534    struct cpu_search *high, const int match);
535int cpu_search_lowest(struct cpu_group *cg, struct cpu_search *low);
536int cpu_search_highest(struct cpu_group *cg, struct cpu_search *high);
537int cpu_search_both(struct cpu_group *cg, struct cpu_search *low,
538    struct cpu_search *high);
539
540/*
541 * This routine compares according to the match argument and should be
542 * reduced in actual instantiations via constant propagation and dead code
543 * elimination.
544 */
545static __inline int
546cpu_compare(int cpu, struct cpu_search *low, struct cpu_search *high,
547    const int match)
548{
549	struct tdq *tdq;
550
551	tdq = TDQ_CPU(cpu);
552	if (match & CPU_SEARCH_LOWEST)
553		if (low->cs_mask & (1 << cpu) &&
554		    tdq->tdq_load < low->cs_load &&
555		    tdq->tdq_lowpri > low->cs_limit) {
556			low->cs_cpu = cpu;
557			low->cs_load = tdq->tdq_load;
558		}
559	if (match & CPU_SEARCH_HIGHEST)
560		if (high->cs_mask & (1 << cpu) &&
561		    tdq->tdq_load >= high->cs_limit &&
562		    tdq->tdq_load > high->cs_load &&
563		    tdq->tdq_transferable) {
564			high->cs_cpu = cpu;
565			high->cs_load = tdq->tdq_load;
566		}
567	return (tdq->tdq_load);
568}
569
570/*
571 * Search the tree of cpu_groups for the lowest or highest loaded cpu
572 * according to the match argument.  This routine actually compares the
573 * load on all paths through the tree and finds the least loaded cpu on
574 * the least loaded path, which may differ from the least loaded cpu in
575 * the system.  This balances work among caches and busses.
576 *
577 * This inline is instantiated in three forms below using constants for the
578 * match argument.  It is reduced to the minimum set for each case.  It is
579 * also recursive to the depth of the tree.
580 */
581static __inline int
582cpu_search(struct cpu_group *cg, struct cpu_search *low,
583    struct cpu_search *high, const int match)
584{
585	int total;
586
587	total = 0;
588	if (cg->cg_children) {
589		struct cpu_search lgroup;
590		struct cpu_search hgroup;
591		struct cpu_group *child;
592		u_int lload;
593		int hload;
594		int load;
595		int i;
596
597		lload = -1;
598		hload = -1;
599		for (i = 0; i < cg->cg_children; i++) {
600			child = &cg->cg_child[i];
601			if (match & CPU_SEARCH_LOWEST) {
602				lgroup = *low;
603				lgroup.cs_load = -1;
604			}
605			if (match & CPU_SEARCH_HIGHEST) {
606				hgroup = *high;
607				lgroup.cs_load = 0;
608			}
609			switch (match) {
610			case CPU_SEARCH_LOWEST:
611				load = cpu_search_lowest(child, &lgroup);
612				break;
613			case CPU_SEARCH_HIGHEST:
614				load = cpu_search_highest(child, &hgroup);
615				break;
616			case CPU_SEARCH_BOTH:
617				load = cpu_search_both(child, &lgroup, &hgroup);
618				break;
619			}
620			total += load;
621			if (match & CPU_SEARCH_LOWEST)
622				if (load < lload || low->cs_cpu == -1) {
623					*low = lgroup;
624					lload = load;
625				}
626			if (match & CPU_SEARCH_HIGHEST)
627				if (load > hload || high->cs_cpu == -1) {
628					hload = load;
629					*high = hgroup;
630				}
631		}
632	} else {
633		int cpu;
634
635		CPUMASK_FOREACH(cpu, cg->cg_mask)
636			total += cpu_compare(cpu, low, high, match);
637	}
638	return (total);
639}
640
641/*
642 * cpu_search instantiations must pass constants to maintain the inline
643 * optimization.
644 */
645int
646cpu_search_lowest(struct cpu_group *cg, struct cpu_search *low)
647{
648	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
649}
650
651int
652cpu_search_highest(struct cpu_group *cg, struct cpu_search *high)
653{
654	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
655}
656
657int
658cpu_search_both(struct cpu_group *cg, struct cpu_search *low,
659    struct cpu_search *high)
660{
661	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
662}
663
664/*
665 * Find the cpu with the least load via the least loaded path that has a
666 * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
667 * acceptable.
668 */
669static inline int
670sched_lowest(struct cpu_group *cg, cpumask_t mask, int pri)
671{
672	struct cpu_search low;
673
674	low.cs_cpu = -1;
675	low.cs_load = -1;
676	low.cs_mask = mask;
677	low.cs_limit = pri;
678	cpu_search_lowest(cg, &low);
679	return low.cs_cpu;
680}
681
682/*
683 * Find the cpu with the highest load via the highest loaded path.
684 */
685static inline int
686sched_highest(struct cpu_group *cg, cpumask_t mask, int minload)
687{
688	struct cpu_search high;
689
690	high.cs_cpu = -1;
691	high.cs_load = 0;
692	high.cs_mask = mask;
693	high.cs_limit = minload;
694	cpu_search_highest(cg, &high);
695	return high.cs_cpu;
696}
697
698/*
699 * Simultaneously find the highest and lowest loaded cpu reachable via
700 * cg.
701 */
702static inline void
703sched_both(struct cpu_group *cg, cpumask_t mask, int *lowcpu, int *highcpu)
704{
705	struct cpu_search high;
706	struct cpu_search low;
707
708	low.cs_cpu = -1;
709	low.cs_limit = -1;
710	low.cs_load = -1;
711	low.cs_mask = mask;
712	high.cs_load = 0;
713	high.cs_cpu = -1;
714	high.cs_limit = -1;
715	high.cs_mask = mask;
716	cpu_search_both(cg, &low, &high);
717	*lowcpu = low.cs_cpu;
718	*highcpu = high.cs_cpu;
719	return;
720}
721
722static void
723sched_balance_group(struct cpu_group *cg)
724{
725	cpumask_t mask;
726	int high;
727	int low;
728	int i;
729
730	mask = -1;
731	for (;;) {
732		sched_both(cg, mask, &low, &high);
733		if (low == high || low == -1 || high == -1)
734			break;
735		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low)))
736			break;
737		/*
738		 * If we failed to move any threads determine which cpu
739		 * to kick out of the set and try again.
740	 	 */
741		if (TDQ_CPU(high)->tdq_transferable == 0)
742			mask &= ~(1 << high);
743		else
744			mask &= ~(1 << low);
745	}
746
747	for (i = 0; i < cg->cg_children; i++)
748		sched_balance_group(&cg->cg_child[i]);
749}
750
751static void
752sched_balance()
753{
754	struct tdq *tdq;
755
756	/*
757	 * Select a random time between .5 * balance_interval and
758	 * 1.5 * balance_interval.
759	 */
760	balance_ticks = max(balance_interval / 2, 1);
761	balance_ticks += random() % balance_interval;
762	if (smp_started == 0 || rebalance == 0)
763		return;
764	tdq = TDQ_SELF();
765	TDQ_UNLOCK(tdq);
766	sched_balance_group(cpu_top);
767	TDQ_LOCK(tdq);
768}
769
770/*
771 * Lock two thread queues using their address to maintain lock order.
772 */
773static void
774tdq_lock_pair(struct tdq *one, struct tdq *two)
775{
776	if (one < two) {
777		TDQ_LOCK(one);
778		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
779	} else {
780		TDQ_LOCK(two);
781		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
782	}
783}
784
785/*
786 * Unlock two thread queues.  Order is not important here.
787 */
788static void
789tdq_unlock_pair(struct tdq *one, struct tdq *two)
790{
791	TDQ_UNLOCK(one);
792	TDQ_UNLOCK(two);
793}
794
795/*
796 * Transfer load between two imbalanced thread queues.
797 */
798static int
799sched_balance_pair(struct tdq *high, struct tdq *low)
800{
801	int transferable;
802	int high_load;
803	int low_load;
804	int moved;
805	int move;
806	int diff;
807	int i;
808
809	tdq_lock_pair(high, low);
810	transferable = high->tdq_transferable;
811	high_load = high->tdq_load;
812	low_load = low->tdq_load;
813	moved = 0;
814	/*
815	 * Determine what the imbalance is and then adjust that to how many
816	 * threads we actually have to give up (transferable).
817	 */
818	if (transferable != 0) {
819		diff = high_load - low_load;
820		move = diff / 2;
821		if (diff & 0x1)
822			move++;
823		move = min(move, transferable);
824		for (i = 0; i < move; i++)
825			moved += tdq_move(high, low);
826		/*
827		 * IPI the target cpu to force it to reschedule with the new
828		 * workload.
829		 */
830		ipi_selected(1 << TDQ_ID(low), IPI_PREEMPT);
831	}
832	tdq_unlock_pair(high, low);
833	return (moved);
834}
835
836/*
837 * Move a thread from one thread queue to another.
838 */
839static int
840tdq_move(struct tdq *from, struct tdq *to)
841{
842	struct td_sched *ts;
843	struct thread *td;
844	struct tdq *tdq;
845	int cpu;
846
847	TDQ_LOCK_ASSERT(from, MA_OWNED);
848	TDQ_LOCK_ASSERT(to, MA_OWNED);
849
850	tdq = from;
851	cpu = TDQ_ID(to);
852	td = tdq_steal(tdq, cpu);
853	if (td == NULL)
854		return (0);
855	ts = td->td_sched;
856	/*
857	 * Although the run queue is locked the thread may be blocked.  Lock
858	 * it to clear this and acquire the run-queue lock.
859	 */
860	thread_lock(td);
861	/* Drop recursive lock on from acquired via thread_lock(). */
862	TDQ_UNLOCK(from);
863	sched_rem(td);
864	ts->ts_cpu = cpu;
865	td->td_lock = TDQ_LOCKPTR(to);
866	tdq_add(to, td, SRQ_YIELDING);
867	return (1);
868}
869
870/*
871 * This tdq has idled.  Try to steal a thread from another cpu and switch
872 * to it.
873 */
874static int
875tdq_idled(struct tdq *tdq)
876{
877	struct cpu_group *cg;
878	struct tdq *steal;
879	cpumask_t mask;
880	int thresh;
881	int cpu;
882
883	if (smp_started == 0 || steal_idle == 0)
884		return (1);
885	mask = -1;
886	mask &= ~PCPU_GET(cpumask);
887	/* We don't want to be preempted while we're iterating. */
888	spinlock_enter();
889	for (cg = tdq->tdq_cg; cg != NULL; ) {
890		if ((cg->cg_flags & (CG_FLAG_HTT | CG_FLAG_THREAD)) == 0)
891			thresh = steal_thresh;
892		else
893			thresh = 1;
894		cpu = sched_highest(cg, mask, thresh);
895		if (cpu == -1) {
896			cg = cg->cg_parent;
897			continue;
898		}
899		steal = TDQ_CPU(cpu);
900		mask &= ~(1 << cpu);
901		tdq_lock_pair(tdq, steal);
902		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
903			tdq_unlock_pair(tdq, steal);
904			continue;
905		}
906		/*
907		 * If a thread was added while interrupts were disabled don't
908		 * steal one here.  If we fail to acquire one due to affinity
909		 * restrictions loop again with this cpu removed from the
910		 * set.
911		 */
912		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
913			tdq_unlock_pair(tdq, steal);
914			continue;
915		}
916		spinlock_exit();
917		TDQ_UNLOCK(steal);
918		mi_switch(SW_VOL, NULL);
919		thread_unlock(curthread);
920
921		return (0);
922	}
923	spinlock_exit();
924	return (1);
925}
926
927/*
928 * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
929 */
930static void
931tdq_notify(struct tdq *tdq, struct thread *td)
932{
933	int cpri;
934	int pri;
935	int cpu;
936
937	if (tdq->tdq_ipipending)
938		return;
939	cpu = td->td_sched->ts_cpu;
940	pri = td->td_priority;
941	cpri = pcpu_find(cpu)->pc_curthread->td_priority;
942	if (!sched_shouldpreempt(pri, cpri, 1))
943		return;
944	tdq->tdq_ipipending = 1;
945	ipi_selected(1 << cpu, IPI_PREEMPT);
946}
947
948/*
949 * Steals load from a timeshare queue.  Honors the rotating queue head
950 * index.
951 */
952static struct thread *
953runq_steal_from(struct runq *rq, int cpu, u_char start)
954{
955	struct rqbits *rqb;
956	struct rqhead *rqh;
957	struct thread *td;
958	int first;
959	int bit;
960	int pri;
961	int i;
962
963	rqb = &rq->rq_status;
964	bit = start & (RQB_BPW -1);
965	pri = 0;
966	first = 0;
967again:
968	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
969		if (rqb->rqb_bits[i] == 0)
970			continue;
971		if (bit != 0) {
972			for (pri = bit; pri < RQB_BPW; pri++)
973				if (rqb->rqb_bits[i] & (1ul << pri))
974					break;
975			if (pri >= RQB_BPW)
976				continue;
977		} else
978			pri = RQB_FFS(rqb->rqb_bits[i]);
979		pri += (i << RQB_L2BPW);
980		rqh = &rq->rq_queues[pri];
981		TAILQ_FOREACH(td, rqh, td_runq) {
982			if (first && THREAD_CAN_MIGRATE(td) &&
983			    THREAD_CAN_SCHED(td, cpu))
984				return (td);
985			first = 1;
986		}
987	}
988	if (start != 0) {
989		start = 0;
990		goto again;
991	}
992
993	return (NULL);
994}
995
996/*
997 * Steals load from a standard linear queue.
998 */
999static struct thread *
1000runq_steal(struct runq *rq, int cpu)
1001{
1002	struct rqhead *rqh;
1003	struct rqbits *rqb;
1004	struct thread *td;
1005	int word;
1006	int bit;
1007
1008	rqb = &rq->rq_status;
1009	for (word = 0; word < RQB_LEN; word++) {
1010		if (rqb->rqb_bits[word] == 0)
1011			continue;
1012		for (bit = 0; bit < RQB_BPW; bit++) {
1013			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
1014				continue;
1015			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
1016			TAILQ_FOREACH(td, rqh, td_runq)
1017				if (THREAD_CAN_MIGRATE(td) &&
1018				    THREAD_CAN_SCHED(td, cpu))
1019					return (td);
1020		}
1021	}
1022	return (NULL);
1023}
1024
1025/*
1026 * Attempt to steal a thread in priority order from a thread queue.
1027 */
1028static struct thread *
1029tdq_steal(struct tdq *tdq, int cpu)
1030{
1031	struct thread *td;
1032
1033	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1034	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
1035		return (td);
1036	if ((td = runq_steal_from(&tdq->tdq_timeshare,
1037	    cpu, tdq->tdq_ridx)) != NULL)
1038		return (td);
1039	return (runq_steal(&tdq->tdq_idle, cpu));
1040}
1041
1042/*
1043 * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
1044 * current lock and returns with the assigned queue locked.
1045 */
1046static inline struct tdq *
1047sched_setcpu(struct thread *td, int cpu, int flags)
1048{
1049
1050	struct tdq *tdq;
1051
1052	THREAD_LOCK_ASSERT(td, MA_OWNED);
1053	tdq = TDQ_CPU(cpu);
1054	td->td_sched->ts_cpu = cpu;
1055	/*
1056	 * If the lock matches just return the queue.
1057	 */
1058	if (td->td_lock == TDQ_LOCKPTR(tdq))
1059		return (tdq);
1060#ifdef notyet
1061	/*
1062	 * If the thread isn't running its lockptr is a
1063	 * turnstile or a sleepqueue.  We can just lock_set without
1064	 * blocking.
1065	 */
1066	if (TD_CAN_RUN(td)) {
1067		TDQ_LOCK(tdq);
1068		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1069		return (tdq);
1070	}
1071#endif
1072	/*
1073	 * The hard case, migration, we need to block the thread first to
1074	 * prevent order reversals with other cpus locks.
1075	 */
1076	thread_lock_block(td);
1077	TDQ_LOCK(tdq);
1078	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1079	return (tdq);
1080}
1081
1082static int
1083sched_pickcpu(struct thread *td, int flags)
1084{
1085	struct cpu_group *cg;
1086	struct td_sched *ts;
1087	struct tdq *tdq;
1088	cpumask_t mask;
1089	int self;
1090	int pri;
1091	int cpu;
1092
1093	self = PCPU_GET(cpuid);
1094	ts = td->td_sched;
1095	if (smp_started == 0)
1096		return (self);
1097	/*
1098	 * Don't migrate a running thread from sched_switch().
1099	 */
1100	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1101		return (ts->ts_cpu);
1102	/*
1103	 * Prefer to run interrupt threads on the processors that generate
1104	 * the interrupt.
1105	 */
1106	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1107	    curthread->td_intr_nesting_level)
1108		ts->ts_cpu = self;
1109	/*
1110	 * If the thread can run on the last cpu and the affinity has not
1111	 * expired or it is idle run it there.
1112	 */
1113	pri = td->td_priority;
1114	tdq = TDQ_CPU(ts->ts_cpu);
1115	if (THREAD_CAN_SCHED(td, ts->ts_cpu)) {
1116		if (tdq->tdq_lowpri > PRI_MIN_IDLE)
1117			return (ts->ts_cpu);
1118		if (SCHED_AFFINITY(ts, CG_SHARE_L2) && tdq->tdq_lowpri > pri)
1119			return (ts->ts_cpu);
1120	}
1121	/*
1122	 * Search for the highest level in the tree that still has affinity.
1123	 */
1124	cg = NULL;
1125	for (cg = tdq->tdq_cg; cg != NULL; cg = cg->cg_parent)
1126		if (SCHED_AFFINITY(ts, cg->cg_level))
1127			break;
1128	cpu = -1;
1129	mask = td->td_cpuset->cs_mask.__bits[0];
1130	if (cg)
1131		cpu = sched_lowest(cg, mask, pri);
1132	if (cpu == -1)
1133		cpu = sched_lowest(cpu_top, mask, -1);
1134	/*
1135	 * Compare the lowest loaded cpu to current cpu.
1136	 */
1137	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
1138	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE)
1139		cpu = self;
1140	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1141	return (cpu);
1142}
1143#endif
1144
1145/*
1146 * Pick the highest priority task we have and return it.
1147 */
1148static struct thread *
1149tdq_choose(struct tdq *tdq)
1150{
1151	struct thread *td;
1152
1153	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1154	td = runq_choose(&tdq->tdq_realtime);
1155	if (td != NULL)
1156		return (td);
1157	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1158	if (td != NULL) {
1159		KASSERT(td->td_priority >= PRI_MIN_TIMESHARE,
1160		    ("tdq_choose: Invalid priority on timeshare queue %d",
1161		    td->td_priority));
1162		return (td);
1163	}
1164	td = runq_choose(&tdq->tdq_idle);
1165	if (td != NULL) {
1166		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1167		    ("tdq_choose: Invalid priority on idle queue %d",
1168		    td->td_priority));
1169		return (td);
1170	}
1171
1172	return (NULL);
1173}
1174
1175/*
1176 * Initialize a thread queue.
1177 */
1178static void
1179tdq_setup(struct tdq *tdq)
1180{
1181
1182	if (bootverbose)
1183		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1184	runq_init(&tdq->tdq_realtime);
1185	runq_init(&tdq->tdq_timeshare);
1186	runq_init(&tdq->tdq_idle);
1187	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1188	    "sched lock %d", (int)TDQ_ID(tdq));
1189	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1190	    MTX_SPIN | MTX_RECURSE);
1191}
1192
1193#ifdef SMP
1194static void
1195sched_setup_smp(void)
1196{
1197	struct tdq *tdq;
1198	int i;
1199
1200	cpu_top = smp_topo();
1201	for (i = 0; i < MAXCPU; i++) {
1202		if (CPU_ABSENT(i))
1203			continue;
1204		tdq = TDQ_CPU(i);
1205		tdq_setup(tdq);
1206		tdq->tdq_cg = smp_topo_find(cpu_top, i);
1207		if (tdq->tdq_cg == NULL)
1208			panic("Can't find cpu group for %d\n", i);
1209	}
1210	balance_tdq = TDQ_SELF();
1211	sched_balance();
1212}
1213#endif
1214
1215/*
1216 * Setup the thread queues and initialize the topology based on MD
1217 * information.
1218 */
1219static void
1220sched_setup(void *dummy)
1221{
1222	struct tdq *tdq;
1223
1224	tdq = TDQ_SELF();
1225#ifdef SMP
1226	sched_setup_smp();
1227#else
1228	tdq_setup(tdq);
1229#endif
1230	/*
1231	 * To avoid divide-by-zero, we set realstathz a dummy value
1232	 * in case which sched_clock() called before sched_initticks().
1233	 */
1234	realstathz = hz;
1235	sched_slice = (realstathz/10);	/* ~100ms */
1236	tickincr = 1 << SCHED_TICK_SHIFT;
1237
1238	/* Add thread0's load since it's running. */
1239	TDQ_LOCK(tdq);
1240	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1241	tdq_load_add(tdq, &thread0);
1242	tdq->tdq_lowpri = thread0.td_priority;
1243	TDQ_UNLOCK(tdq);
1244}
1245
1246/*
1247 * This routine determines the tickincr after stathz and hz are setup.
1248 */
1249/* ARGSUSED */
1250static void
1251sched_initticks(void *dummy)
1252{
1253	int incr;
1254
1255	realstathz = stathz ? stathz : hz;
1256	sched_slice = (realstathz/10);	/* ~100ms */
1257
1258	/*
1259	 * tickincr is shifted out by 10 to avoid rounding errors due to
1260	 * hz not being evenly divisible by stathz on all platforms.
1261	 */
1262	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1263	/*
1264	 * This does not work for values of stathz that are more than
1265	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1266	 */
1267	if (incr == 0)
1268		incr = 1;
1269	tickincr = incr;
1270#ifdef SMP
1271	/*
1272	 * Set the default balance interval now that we know
1273	 * what realstathz is.
1274	 */
1275	balance_interval = realstathz;
1276	/*
1277	 * Set steal thresh to log2(mp_ncpu) but no greater than 4.  This
1278	 * prevents excess thrashing on large machines and excess idle on
1279	 * smaller machines.
1280	 */
1281	steal_thresh = min(ffs(mp_ncpus) - 1, 3);
1282	affinity = SCHED_AFFINITY_DEFAULT;
1283#endif
1284}
1285
1286
1287/*
1288 * This is the core of the interactivity algorithm.  Determines a score based
1289 * on past behavior.  It is the ratio of sleep time to run time scaled to
1290 * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1291 * differs from the cpu usage because it does not account for time spent
1292 * waiting on a run-queue.  Would be prettier if we had floating point.
1293 */
1294static int
1295sched_interact_score(struct thread *td)
1296{
1297	struct td_sched *ts;
1298	int div;
1299
1300	ts = td->td_sched;
1301	/*
1302	 * The score is only needed if this is likely to be an interactive
1303	 * task.  Don't go through the expense of computing it if there's
1304	 * no chance.
1305	 */
1306	if (sched_interact <= SCHED_INTERACT_HALF &&
1307		ts->ts_runtime >= ts->ts_slptime)
1308			return (SCHED_INTERACT_HALF);
1309
1310	if (ts->ts_runtime > ts->ts_slptime) {
1311		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1312		return (SCHED_INTERACT_HALF +
1313		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1314	}
1315	if (ts->ts_slptime > ts->ts_runtime) {
1316		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1317		return (ts->ts_runtime / div);
1318	}
1319	/* runtime == slptime */
1320	if (ts->ts_runtime)
1321		return (SCHED_INTERACT_HALF);
1322
1323	/*
1324	 * This can happen if slptime and runtime are 0.
1325	 */
1326	return (0);
1327
1328}
1329
1330/*
1331 * Scale the scheduling priority according to the "interactivity" of this
1332 * process.
1333 */
1334static void
1335sched_priority(struct thread *td)
1336{
1337	int score;
1338	int pri;
1339
1340	if (td->td_pri_class != PRI_TIMESHARE)
1341		return;
1342	/*
1343	 * If the score is interactive we place the thread in the realtime
1344	 * queue with a priority that is less than kernel and interrupt
1345	 * priorities.  These threads are not subject to nice restrictions.
1346	 *
1347	 * Scores greater than this are placed on the normal timeshare queue
1348	 * where the priority is partially decided by the most recent cpu
1349	 * utilization and the rest is decided by nice value.
1350	 *
1351	 * The nice value of the process has a linear effect on the calculated
1352	 * score.  Negative nice values make it easier for a thread to be
1353	 * considered interactive.
1354	 */
1355	score = imax(0, sched_interact_score(td) - td->td_proc->p_nice);
1356	if (score < sched_interact) {
1357		pri = PRI_MIN_REALTIME;
1358		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1359		    * score;
1360		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1361		    ("sched_priority: invalid interactive priority %d score %d",
1362		    pri, score));
1363	} else {
1364		pri = SCHED_PRI_MIN;
1365		if (td->td_sched->ts_ticks)
1366			pri += SCHED_PRI_TICKS(td->td_sched);
1367		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1368		KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1369		    ("sched_priority: invalid priority %d: nice %d, "
1370		    "ticks %d ftick %d ltick %d tick pri %d",
1371		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1372		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1373		    SCHED_PRI_TICKS(td->td_sched)));
1374	}
1375	sched_user_prio(td, pri);
1376
1377	return;
1378}
1379
1380/*
1381 * This routine enforces a maximum limit on the amount of scheduling history
1382 * kept.  It is called after either the slptime or runtime is adjusted.  This
1383 * function is ugly due to integer math.
1384 */
1385static void
1386sched_interact_update(struct thread *td)
1387{
1388	struct td_sched *ts;
1389	u_int sum;
1390
1391	ts = td->td_sched;
1392	sum = ts->ts_runtime + ts->ts_slptime;
1393	if (sum < SCHED_SLP_RUN_MAX)
1394		return;
1395	/*
1396	 * This only happens from two places:
1397	 * 1) We have added an unusual amount of run time from fork_exit.
1398	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1399	 */
1400	if (sum > SCHED_SLP_RUN_MAX * 2) {
1401		if (ts->ts_runtime > ts->ts_slptime) {
1402			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1403			ts->ts_slptime = 1;
1404		} else {
1405			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1406			ts->ts_runtime = 1;
1407		}
1408		return;
1409	}
1410	/*
1411	 * If we have exceeded by more than 1/5th then the algorithm below
1412	 * will not bring us back into range.  Dividing by two here forces
1413	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1414	 */
1415	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1416		ts->ts_runtime /= 2;
1417		ts->ts_slptime /= 2;
1418		return;
1419	}
1420	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1421	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1422}
1423
1424/*
1425 * Scale back the interactivity history when a child thread is created.  The
1426 * history is inherited from the parent but the thread may behave totally
1427 * differently.  For example, a shell spawning a compiler process.  We want
1428 * to learn that the compiler is behaving badly very quickly.
1429 */
1430static void
1431sched_interact_fork(struct thread *td)
1432{
1433	int ratio;
1434	int sum;
1435
1436	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1437	if (sum > SCHED_SLP_RUN_FORK) {
1438		ratio = sum / SCHED_SLP_RUN_FORK;
1439		td->td_sched->ts_runtime /= ratio;
1440		td->td_sched->ts_slptime /= ratio;
1441	}
1442}
1443
1444/*
1445 * Called from proc0_init() to setup the scheduler fields.
1446 */
1447void
1448schedinit(void)
1449{
1450
1451	/*
1452	 * Set up the scheduler specific parts of proc0.
1453	 */
1454	proc0.p_sched = NULL; /* XXX */
1455	thread0.td_sched = &td_sched0;
1456	td_sched0.ts_ltick = ticks;
1457	td_sched0.ts_ftick = ticks;
1458	td_sched0.ts_slice = sched_slice;
1459}
1460
1461/*
1462 * This is only somewhat accurate since given many processes of the same
1463 * priority they will switch when their slices run out, which will be
1464 * at most sched_slice stathz ticks.
1465 */
1466int
1467sched_rr_interval(void)
1468{
1469
1470	/* Convert sched_slice to hz */
1471	return (hz/(realstathz/sched_slice));
1472}
1473
1474/*
1475 * Update the percent cpu tracking information when it is requested or
1476 * the total history exceeds the maximum.  We keep a sliding history of
1477 * tick counts that slowly decays.  This is less precise than the 4BSD
1478 * mechanism since it happens with less regular and frequent events.
1479 */
1480static void
1481sched_pctcpu_update(struct td_sched *ts)
1482{
1483
1484	if (ts->ts_ticks == 0)
1485		return;
1486	if (ticks - (hz / 10) < ts->ts_ltick &&
1487	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1488		return;
1489	/*
1490	 * Adjust counters and watermark for pctcpu calc.
1491	 */
1492	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1493		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1494			    SCHED_TICK_TARG;
1495	else
1496		ts->ts_ticks = 0;
1497	ts->ts_ltick = ticks;
1498	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1499}
1500
1501/*
1502 * Adjust the priority of a thread.  Move it to the appropriate run-queue
1503 * if necessary.  This is the back-end for several priority related
1504 * functions.
1505 */
1506static void
1507sched_thread_priority(struct thread *td, u_char prio)
1508{
1509	struct td_sched *ts;
1510	struct tdq *tdq;
1511	int oldpri;
1512
1513	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
1514	    td, td->td_name, td->td_priority, prio, curthread,
1515	    curthread->td_name);
1516	ts = td->td_sched;
1517	THREAD_LOCK_ASSERT(td, MA_OWNED);
1518	if (td->td_priority == prio)
1519		return;
1520	/*
1521	 * If the priority has been elevated due to priority
1522	 * propagation, we may have to move ourselves to a new
1523	 * queue.  This could be optimized to not re-add in some
1524	 * cases.
1525	 */
1526	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1527		sched_rem(td);
1528		td->td_priority = prio;
1529		sched_add(td, SRQ_BORROWING);
1530		return;
1531	}
1532	/*
1533	 * If the thread is currently running we may have to adjust the lowpri
1534	 * information so other cpus are aware of our current priority.
1535	 */
1536	if (TD_IS_RUNNING(td)) {
1537		tdq = TDQ_CPU(ts->ts_cpu);
1538		oldpri = td->td_priority;
1539		td->td_priority = prio;
1540		if (prio < tdq->tdq_lowpri)
1541			tdq->tdq_lowpri = prio;
1542		else if (tdq->tdq_lowpri == oldpri)
1543			tdq_setlowpri(tdq, td);
1544		return;
1545	}
1546	td->td_priority = prio;
1547}
1548
1549/*
1550 * Update a thread's priority when it is lent another thread's
1551 * priority.
1552 */
1553void
1554sched_lend_prio(struct thread *td, u_char prio)
1555{
1556
1557	td->td_flags |= TDF_BORROWING;
1558	sched_thread_priority(td, prio);
1559}
1560
1561/*
1562 * Restore a thread's priority when priority propagation is
1563 * over.  The prio argument is the minimum priority the thread
1564 * needs to have to satisfy other possible priority lending
1565 * requests.  If the thread's regular priority is less
1566 * important than prio, the thread will keep a priority boost
1567 * of prio.
1568 */
1569void
1570sched_unlend_prio(struct thread *td, u_char prio)
1571{
1572	u_char base_pri;
1573
1574	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1575	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1576		base_pri = td->td_user_pri;
1577	else
1578		base_pri = td->td_base_pri;
1579	if (prio >= base_pri) {
1580		td->td_flags &= ~TDF_BORROWING;
1581		sched_thread_priority(td, base_pri);
1582	} else
1583		sched_lend_prio(td, prio);
1584}
1585
1586/*
1587 * Standard entry for setting the priority to an absolute value.
1588 */
1589void
1590sched_prio(struct thread *td, u_char prio)
1591{
1592	u_char oldprio;
1593
1594	/* First, update the base priority. */
1595	td->td_base_pri = prio;
1596
1597	/*
1598	 * If the thread is borrowing another thread's priority, don't
1599	 * ever lower the priority.
1600	 */
1601	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1602		return;
1603
1604	/* Change the real priority. */
1605	oldprio = td->td_priority;
1606	sched_thread_priority(td, prio);
1607
1608	/*
1609	 * If the thread is on a turnstile, then let the turnstile update
1610	 * its state.
1611	 */
1612	if (TD_ON_LOCK(td) && oldprio != prio)
1613		turnstile_adjust(td, oldprio);
1614}
1615
1616/*
1617 * Set the base user priority, does not effect current running priority.
1618 */
1619void
1620sched_user_prio(struct thread *td, u_char prio)
1621{
1622	u_char oldprio;
1623
1624	td->td_base_user_pri = prio;
1625	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1626                return;
1627	oldprio = td->td_user_pri;
1628	td->td_user_pri = prio;
1629}
1630
1631void
1632sched_lend_user_prio(struct thread *td, u_char prio)
1633{
1634	u_char oldprio;
1635
1636	THREAD_LOCK_ASSERT(td, MA_OWNED);
1637	td->td_flags |= TDF_UBORROWING;
1638	oldprio = td->td_user_pri;
1639	td->td_user_pri = prio;
1640}
1641
1642void
1643sched_unlend_user_prio(struct thread *td, u_char prio)
1644{
1645	u_char base_pri;
1646
1647	THREAD_LOCK_ASSERT(td, MA_OWNED);
1648	base_pri = td->td_base_user_pri;
1649	if (prio >= base_pri) {
1650		td->td_flags &= ~TDF_UBORROWING;
1651		sched_user_prio(td, base_pri);
1652	} else {
1653		sched_lend_user_prio(td, prio);
1654	}
1655}
1656
1657/*
1658 * Block a thread for switching.  Similar to thread_block() but does not
1659 * bump the spin count.
1660 */
1661static inline struct mtx *
1662thread_block_switch(struct thread *td)
1663{
1664	struct mtx *lock;
1665
1666	THREAD_LOCK_ASSERT(td, MA_OWNED);
1667	lock = td->td_lock;
1668	td->td_lock = &blocked_lock;
1669	mtx_unlock_spin(lock);
1670
1671	return (lock);
1672}
1673
1674/*
1675 * Handle migration from sched_switch().  This happens only for
1676 * cpu binding.
1677 */
1678static struct mtx *
1679sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1680{
1681	struct tdq *tdn;
1682
1683	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1684#ifdef SMP
1685	tdq_load_rem(tdq, td);
1686	/*
1687	 * Do the lock dance required to avoid LOR.  We grab an extra
1688	 * spinlock nesting to prevent preemption while we're
1689	 * not holding either run-queue lock.
1690	 */
1691	spinlock_enter();
1692	thread_block_switch(td);	/* This releases the lock on tdq. */
1693	TDQ_LOCK(tdn);
1694	tdq_add(tdn, td, flags);
1695	tdq_notify(tdn, td);
1696	/*
1697	 * After we unlock tdn the new cpu still can't switch into this
1698	 * thread until we've unblocked it in cpu_switch().  The lock
1699	 * pointers may match in the case of HTT cores.  Don't unlock here
1700	 * or we can deadlock when the other CPU runs the IPI handler.
1701	 */
1702	if (TDQ_LOCKPTR(tdn) != TDQ_LOCKPTR(tdq)) {
1703		TDQ_UNLOCK(tdn);
1704		TDQ_LOCK(tdq);
1705	}
1706	spinlock_exit();
1707#endif
1708	return (TDQ_LOCKPTR(tdn));
1709}
1710
1711/*
1712 * Release a thread that was blocked with thread_block_switch().
1713 */
1714static inline void
1715thread_unblock_switch(struct thread *td, struct mtx *mtx)
1716{
1717	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1718	    (uintptr_t)mtx);
1719}
1720
1721/*
1722 * Switch threads.  This function has to handle threads coming in while
1723 * blocked for some reason, running, or idle.  It also must deal with
1724 * migrating a thread from one queue to another as running threads may
1725 * be assigned elsewhere via binding.
1726 */
1727void
1728sched_switch(struct thread *td, struct thread *newtd, int flags)
1729{
1730	struct tdq *tdq;
1731	struct td_sched *ts;
1732	struct mtx *mtx;
1733	int srqflag;
1734	int cpuid;
1735
1736	THREAD_LOCK_ASSERT(td, MA_OWNED);
1737	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
1738
1739	cpuid = PCPU_GET(cpuid);
1740	tdq = TDQ_CPU(cpuid);
1741	ts = td->td_sched;
1742	mtx = td->td_lock;
1743	ts->ts_rltick = ticks;
1744	td->td_lastcpu = td->td_oncpu;
1745	td->td_oncpu = NOCPU;
1746	td->td_flags &= ~TDF_NEEDRESCHED;
1747	td->td_owepreempt = 0;
1748	/*
1749	 * The lock pointer in an idle thread should never change.  Reset it
1750	 * to CAN_RUN as well.
1751	 */
1752	if (TD_IS_IDLETHREAD(td)) {
1753		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1754		TD_SET_CAN_RUN(td);
1755	} else if (TD_IS_RUNNING(td)) {
1756		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1757		srqflag = (flags & SW_PREEMPT) ?
1758		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1759		    SRQ_OURSELF|SRQ_YIELDING;
1760		if (ts->ts_cpu == cpuid)
1761			tdq_runq_add(tdq, td, srqflag);
1762		else
1763			mtx = sched_switch_migrate(tdq, td, srqflag);
1764	} else {
1765		/* This thread must be going to sleep. */
1766		TDQ_LOCK(tdq);
1767		mtx = thread_block_switch(td);
1768		tdq_load_rem(tdq, td);
1769	}
1770	/*
1771	 * We enter here with the thread blocked and assigned to the
1772	 * appropriate cpu run-queue or sleep-queue and with the current
1773	 * thread-queue locked.
1774	 */
1775	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1776	newtd = choosethread();
1777	/*
1778	 * Call the MD code to switch contexts if necessary.
1779	 */
1780	if (td != newtd) {
1781#ifdef	HWPMC_HOOKS
1782		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1783			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1784#endif
1785		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1786		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1787		cpu_switch(td, newtd, mtx);
1788		/*
1789		 * We may return from cpu_switch on a different cpu.  However,
1790		 * we always return with td_lock pointing to the current cpu's
1791		 * run queue lock.
1792		 */
1793		cpuid = PCPU_GET(cpuid);
1794		tdq = TDQ_CPU(cpuid);
1795		lock_profile_obtain_lock_success(
1796		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1797#ifdef	HWPMC_HOOKS
1798		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1799			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1800#endif
1801	} else
1802		thread_unblock_switch(td, mtx);
1803	/*
1804	 * Assert that all went well and return.
1805	 */
1806	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1807	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1808	td->td_oncpu = cpuid;
1809}
1810
1811/*
1812 * Adjust thread priorities as a result of a nice request.
1813 */
1814void
1815sched_nice(struct proc *p, int nice)
1816{
1817	struct thread *td;
1818
1819	PROC_LOCK_ASSERT(p, MA_OWNED);
1820
1821	p->p_nice = nice;
1822	FOREACH_THREAD_IN_PROC(p, td) {
1823		thread_lock(td);
1824		sched_priority(td);
1825		sched_prio(td, td->td_base_user_pri);
1826		thread_unlock(td);
1827	}
1828}
1829
1830/*
1831 * Record the sleep time for the interactivity scorer.
1832 */
1833void
1834sched_sleep(struct thread *td, int prio)
1835{
1836
1837	THREAD_LOCK_ASSERT(td, MA_OWNED);
1838
1839	td->td_slptick = ticks;
1840	if (TD_IS_SUSPENDED(td) || prio <= PSOCK)
1841		td->td_flags |= TDF_CANSWAP;
1842	if (static_boost && prio)
1843		sched_prio(td, prio);
1844}
1845
1846/*
1847 * Schedule a thread to resume execution and record how long it voluntarily
1848 * slept.  We also update the pctcpu, interactivity, and priority.
1849 */
1850void
1851sched_wakeup(struct thread *td)
1852{
1853	struct td_sched *ts;
1854	int slptick;
1855
1856	THREAD_LOCK_ASSERT(td, MA_OWNED);
1857	ts = td->td_sched;
1858	td->td_flags &= ~TDF_CANSWAP;
1859	/*
1860	 * If we slept for more than a tick update our interactivity and
1861	 * priority.
1862	 */
1863	slptick = td->td_slptick;
1864	td->td_slptick = 0;
1865	if (slptick && slptick != ticks) {
1866		u_int hzticks;
1867
1868		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1869		ts->ts_slptime += hzticks;
1870		sched_interact_update(td);
1871		sched_pctcpu_update(ts);
1872	}
1873	/* Reset the slice value after we sleep. */
1874	ts->ts_slice = sched_slice;
1875	sched_add(td, SRQ_BORING);
1876}
1877
1878/*
1879 * Penalize the parent for creating a new child and initialize the child's
1880 * priority.
1881 */
1882void
1883sched_fork(struct thread *td, struct thread *child)
1884{
1885	THREAD_LOCK_ASSERT(td, MA_OWNED);
1886	sched_fork_thread(td, child);
1887	/*
1888	 * Penalize the parent and child for forking.
1889	 */
1890	sched_interact_fork(child);
1891	sched_priority(child);
1892	td->td_sched->ts_runtime += tickincr;
1893	sched_interact_update(td);
1894	sched_priority(td);
1895}
1896
1897/*
1898 * Fork a new thread, may be within the same process.
1899 */
1900void
1901sched_fork_thread(struct thread *td, struct thread *child)
1902{
1903	struct td_sched *ts;
1904	struct td_sched *ts2;
1905
1906	THREAD_LOCK_ASSERT(td, MA_OWNED);
1907	/*
1908	 * Initialize child.
1909	 */
1910	ts = td->td_sched;
1911	ts2 = child->td_sched;
1912	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1913	child->td_cpuset = cpuset_ref(td->td_cpuset);
1914	ts2->ts_cpu = ts->ts_cpu;
1915	ts2->ts_flags = 0;
1916	/*
1917	 * Grab our parents cpu estimation information and priority.
1918	 */
1919	ts2->ts_ticks = ts->ts_ticks;
1920	ts2->ts_ltick = ts->ts_ltick;
1921	ts2->ts_ftick = ts->ts_ftick;
1922	child->td_user_pri = td->td_user_pri;
1923	child->td_base_user_pri = td->td_base_user_pri;
1924	/*
1925	 * And update interactivity score.
1926	 */
1927	ts2->ts_slptime = ts->ts_slptime;
1928	ts2->ts_runtime = ts->ts_runtime;
1929	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
1930}
1931
1932/*
1933 * Adjust the priority class of a thread.
1934 */
1935void
1936sched_class(struct thread *td, int class)
1937{
1938
1939	THREAD_LOCK_ASSERT(td, MA_OWNED);
1940	if (td->td_pri_class == class)
1941		return;
1942	td->td_pri_class = class;
1943}
1944
1945/*
1946 * Return some of the child's priority and interactivity to the parent.
1947 */
1948void
1949sched_exit(struct proc *p, struct thread *child)
1950{
1951	struct thread *td;
1952
1953	CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
1954	    child, child->td_name, child->td_priority);
1955
1956	PROC_LOCK_ASSERT(p, MA_OWNED);
1957	td = FIRST_THREAD_IN_PROC(p);
1958	sched_exit_thread(td, child);
1959}
1960
1961/*
1962 * Penalize another thread for the time spent on this one.  This helps to
1963 * worsen the priority and interactivity of processes which schedule batch
1964 * jobs such as make.  This has little effect on the make process itself but
1965 * causes new processes spawned by it to receive worse scores immediately.
1966 */
1967void
1968sched_exit_thread(struct thread *td, struct thread *child)
1969{
1970
1971	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
1972	    child, child->td_name, child->td_priority);
1973
1974	/*
1975	 * Give the child's runtime to the parent without returning the
1976	 * sleep time as a penalty to the parent.  This causes shells that
1977	 * launch expensive things to mark their children as expensive.
1978	 */
1979	thread_lock(td);
1980	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
1981	sched_interact_update(td);
1982	sched_priority(td);
1983	thread_unlock(td);
1984}
1985
1986void
1987sched_preempt(struct thread *td)
1988{
1989	struct tdq *tdq;
1990
1991	thread_lock(td);
1992	tdq = TDQ_SELF();
1993	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1994	tdq->tdq_ipipending = 0;
1995	if (td->td_priority > tdq->tdq_lowpri) {
1996		if (td->td_critnest > 1)
1997			td->td_owepreempt = 1;
1998		else
1999			mi_switch(SW_INVOL | SW_PREEMPT, NULL);
2000	}
2001	thread_unlock(td);
2002}
2003
2004/*
2005 * Fix priorities on return to user-space.  Priorities may be elevated due
2006 * to static priorities in msleep() or similar.
2007 */
2008void
2009sched_userret(struct thread *td)
2010{
2011	/*
2012	 * XXX we cheat slightly on the locking here to avoid locking in
2013	 * the usual case.  Setting td_priority here is essentially an
2014	 * incomplete workaround for not setting it properly elsewhere.
2015	 * Now that some interrupt handlers are threads, not setting it
2016	 * properly elsewhere can clobber it in the window between setting
2017	 * it here and returning to user mode, so don't waste time setting
2018	 * it perfectly here.
2019	 */
2020	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2021	    ("thread with borrowed priority returning to userland"));
2022	if (td->td_priority != td->td_user_pri) {
2023		thread_lock(td);
2024		td->td_priority = td->td_user_pri;
2025		td->td_base_pri = td->td_user_pri;
2026		tdq_setlowpri(TDQ_SELF(), td);
2027		thread_unlock(td);
2028        }
2029}
2030
2031/*
2032 * Handle a stathz tick.  This is really only relevant for timeshare
2033 * threads.
2034 */
2035void
2036sched_clock(struct thread *td)
2037{
2038	struct tdq *tdq;
2039	struct td_sched *ts;
2040
2041	THREAD_LOCK_ASSERT(td, MA_OWNED);
2042	tdq = TDQ_SELF();
2043#ifdef SMP
2044	/*
2045	 * We run the long term load balancer infrequently on the first cpu.
2046	 */
2047	if (balance_tdq == tdq) {
2048		if (balance_ticks && --balance_ticks == 0)
2049			sched_balance();
2050	}
2051#endif
2052	/*
2053	 * Advance the insert index once for each tick to ensure that all
2054	 * threads get a chance to run.
2055	 */
2056	if (tdq->tdq_idx == tdq->tdq_ridx) {
2057		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2058		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2059			tdq->tdq_ridx = tdq->tdq_idx;
2060	}
2061	ts = td->td_sched;
2062	if (td->td_pri_class & PRI_FIFO_BIT)
2063		return;
2064	if (td->td_pri_class == PRI_TIMESHARE) {
2065		/*
2066		 * We used a tick; charge it to the thread so
2067		 * that we can compute our interactivity.
2068		 */
2069		td->td_sched->ts_runtime += tickincr;
2070		sched_interact_update(td);
2071		sched_priority(td);
2072	}
2073	/*
2074	 * We used up one time slice.
2075	 */
2076	if (--ts->ts_slice > 0)
2077		return;
2078	/*
2079	 * We're out of time, force a requeue at userret().
2080	 */
2081	ts->ts_slice = sched_slice;
2082	td->td_flags |= TDF_NEEDRESCHED;
2083}
2084
2085/*
2086 * Called once per hz tick.  Used for cpu utilization information.  This
2087 * is easier than trying to scale based on stathz.
2088 */
2089void
2090sched_tick(void)
2091{
2092	struct td_sched *ts;
2093
2094	ts = curthread->td_sched;
2095	/* Adjust ticks for pctcpu */
2096	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2097	ts->ts_ltick = ticks;
2098	/*
2099	 * Update if we've exceeded our desired tick threshhold by over one
2100	 * second.
2101	 */
2102	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2103		sched_pctcpu_update(ts);
2104}
2105
2106/*
2107 * Return whether the current CPU has runnable tasks.  Used for in-kernel
2108 * cooperative idle threads.
2109 */
2110int
2111sched_runnable(void)
2112{
2113	struct tdq *tdq;
2114	int load;
2115
2116	load = 1;
2117
2118	tdq = TDQ_SELF();
2119	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2120		if (tdq->tdq_load > 0)
2121			goto out;
2122	} else
2123		if (tdq->tdq_load - 1 > 0)
2124			goto out;
2125	load = 0;
2126out:
2127	return (load);
2128}
2129
2130/*
2131 * Choose the highest priority thread to run.  The thread is removed from
2132 * the run-queue while running however the load remains.  For SMP we set
2133 * the tdq in the global idle bitmask if it idles here.
2134 */
2135struct thread *
2136sched_choose(void)
2137{
2138	struct thread *td;
2139	struct tdq *tdq;
2140
2141	tdq = TDQ_SELF();
2142	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2143	td = tdq_choose(tdq);
2144	if (td) {
2145		td->td_sched->ts_ltick = ticks;
2146		tdq_runq_rem(tdq, td);
2147		return (td);
2148	}
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	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2164
2165	ctd = curthread;
2166	pri = td->td_priority;
2167	cpri = ctd->td_priority;
2168	if (pri < cpri)
2169		ctd->td_flags |= TDF_NEEDRESCHED;
2170	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2171		return;
2172	if (!sched_shouldpreempt(pri, cpri, 0))
2173		return;
2174	ctd->td_owepreempt = 1;
2175}
2176
2177/*
2178 * Add a thread to a thread queue.  Select the appropriate runq and add the
2179 * thread to it.  This is the internal function called when the tdq is
2180 * predetermined.
2181 */
2182void
2183tdq_add(struct tdq *tdq, struct thread *td, int flags)
2184{
2185
2186	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2187	KASSERT((td->td_inhibitors == 0),
2188	    ("sched_add: trying to run inhibited thread"));
2189	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2190	    ("sched_add: bad thread state"));
2191	KASSERT(td->td_flags & TDF_INMEM,
2192	    ("sched_add: thread swapped out"));
2193
2194	if (td->td_priority < tdq->tdq_lowpri)
2195		tdq->tdq_lowpri = td->td_priority;
2196	tdq_runq_add(tdq, td, flags);
2197	tdq_load_add(tdq, td);
2198}
2199
2200/*
2201 * Select the target thread queue and add a thread to it.  Request
2202 * preemption or IPI a remote processor if required.
2203 */
2204void
2205sched_add(struct thread *td, int flags)
2206{
2207	struct tdq *tdq;
2208#ifdef SMP
2209	int cpu;
2210#endif
2211	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
2212	    td, td->td_name, td->td_priority, curthread,
2213	    curthread->td_name);
2214	THREAD_LOCK_ASSERT(td, MA_OWNED);
2215	/*
2216	 * Recalculate the priority before we select the target cpu or
2217	 * run-queue.
2218	 */
2219	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2220		sched_priority(td);
2221#ifdef SMP
2222	/*
2223	 * Pick the destination cpu and if it isn't ours transfer to the
2224	 * target cpu.
2225	 */
2226	cpu = sched_pickcpu(td, flags);
2227	tdq = sched_setcpu(td, cpu, flags);
2228	tdq_add(tdq, td, flags);
2229	if (cpu != PCPU_GET(cpuid)) {
2230		tdq_notify(tdq, td);
2231		return;
2232	}
2233#else
2234	tdq = TDQ_SELF();
2235	TDQ_LOCK(tdq);
2236	/*
2237	 * Now that the thread is moving to the run-queue, set the lock
2238	 * to the scheduler's lock.
2239	 */
2240	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2241	tdq_add(tdq, td, flags);
2242#endif
2243	if (!(flags & SRQ_YIELDING))
2244		sched_setpreempt(td);
2245}
2246
2247/*
2248 * Remove a thread from a run-queue without running it.  This is used
2249 * when we're stealing a thread from a remote queue.  Otherwise all threads
2250 * exit by calling sched_exit_thread() and sched_throw() themselves.
2251 */
2252void
2253sched_rem(struct thread *td)
2254{
2255	struct tdq *tdq;
2256
2257	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
2258	    td, td->td_name, td->td_priority, curthread,
2259	    curthread->td_name);
2260	tdq = TDQ_CPU(td->td_sched->ts_cpu);
2261	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2262	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2263	KASSERT(TD_ON_RUNQ(td),
2264	    ("sched_rem: thread not on run queue"));
2265	tdq_runq_rem(tdq, td);
2266	tdq_load_rem(tdq, td);
2267	TD_SET_CAN_RUN(td);
2268	if (td->td_priority == tdq->tdq_lowpri)
2269		tdq_setlowpri(tdq, NULL);
2270}
2271
2272/*
2273 * Fetch cpu utilization information.  Updates on demand.
2274 */
2275fixpt_t
2276sched_pctcpu(struct thread *td)
2277{
2278	fixpt_t pctcpu;
2279	struct td_sched *ts;
2280
2281	pctcpu = 0;
2282	ts = td->td_sched;
2283	if (ts == NULL)
2284		return (0);
2285
2286	thread_lock(td);
2287	if (ts->ts_ticks) {
2288		int rtick;
2289
2290		sched_pctcpu_update(ts);
2291		/* How many rtick per second ? */
2292		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2293		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2294	}
2295	thread_unlock(td);
2296
2297	return (pctcpu);
2298}
2299
2300/*
2301 * Enforce affinity settings for a thread.  Called after adjustments to
2302 * cpumask.
2303 */
2304void
2305sched_affinity(struct thread *td)
2306{
2307#ifdef SMP
2308	struct td_sched *ts;
2309	int cpu;
2310
2311	THREAD_LOCK_ASSERT(td, MA_OWNED);
2312	ts = td->td_sched;
2313	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2314		return;
2315	if (!TD_IS_RUNNING(td))
2316		return;
2317	td->td_flags |= TDF_NEEDRESCHED;
2318	if (!THREAD_CAN_MIGRATE(td))
2319		return;
2320	/*
2321	 * Assign the new cpu and force a switch before returning to
2322	 * userspace.  If the target thread is not running locally send
2323	 * an ipi to force the issue.
2324	 */
2325	cpu = ts->ts_cpu;
2326	ts->ts_cpu = sched_pickcpu(td, 0);
2327	if (cpu != PCPU_GET(cpuid))
2328		ipi_selected(1 << cpu, IPI_PREEMPT);
2329#endif
2330}
2331
2332/*
2333 * Bind a thread to a target cpu.
2334 */
2335void
2336sched_bind(struct thread *td, int cpu)
2337{
2338	struct td_sched *ts;
2339
2340	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2341	ts = td->td_sched;
2342	if (ts->ts_flags & TSF_BOUND)
2343		sched_unbind(td);
2344	ts->ts_flags |= TSF_BOUND;
2345	sched_pin();
2346	if (PCPU_GET(cpuid) == cpu)
2347		return;
2348	ts->ts_cpu = cpu;
2349	/* When we return from mi_switch we'll be on the correct cpu. */
2350	mi_switch(SW_VOL, NULL);
2351}
2352
2353/*
2354 * Release a bound thread.
2355 */
2356void
2357sched_unbind(struct thread *td)
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) == 0)
2364		return;
2365	ts->ts_flags &= ~TSF_BOUND;
2366	sched_unpin();
2367}
2368
2369int
2370sched_is_bound(struct thread *td)
2371{
2372	THREAD_LOCK_ASSERT(td, MA_OWNED);
2373	return (td->td_sched->ts_flags & TSF_BOUND);
2374}
2375
2376/*
2377 * Basic yield call.
2378 */
2379void
2380sched_relinquish(struct thread *td)
2381{
2382	thread_lock(td);
2383	SCHED_STAT_INC(switch_relinquish);
2384	mi_switch(SW_VOL, NULL);
2385	thread_unlock(td);
2386}
2387
2388/*
2389 * Return the total system load.
2390 */
2391int
2392sched_load(void)
2393{
2394#ifdef SMP
2395	int total;
2396	int i;
2397
2398	total = 0;
2399	for (i = 0; i <= mp_maxid; i++)
2400		total += TDQ_CPU(i)->tdq_sysload;
2401	return (total);
2402#else
2403	return (TDQ_SELF()->tdq_sysload);
2404#endif
2405}
2406
2407int
2408sched_sizeof_proc(void)
2409{
2410	return (sizeof(struct proc));
2411}
2412
2413int
2414sched_sizeof_thread(void)
2415{
2416	return (sizeof(struct thread) + sizeof(struct td_sched));
2417}
2418
2419/*
2420 * The actual idle process.
2421 */
2422void
2423sched_idletd(void *dummy)
2424{
2425	struct thread *td;
2426	struct tdq *tdq;
2427
2428	td = curthread;
2429	tdq = TDQ_SELF();
2430	mtx_assert(&Giant, MA_NOTOWNED);
2431	/* ULE relies on preemption for idle interruption. */
2432	for (;;) {
2433#ifdef SMP
2434		if (tdq_idled(tdq))
2435			cpu_idle();
2436#else
2437		cpu_idle();
2438#endif
2439	}
2440}
2441
2442/*
2443 * A CPU is entering for the first time or a thread is exiting.
2444 */
2445void
2446sched_throw(struct thread *td)
2447{
2448	struct thread *newtd;
2449	struct tdq *tdq;
2450
2451	tdq = TDQ_SELF();
2452	if (td == NULL) {
2453		/* Correct spinlock nesting and acquire the correct lock. */
2454		TDQ_LOCK(tdq);
2455		spinlock_exit();
2456	} else {
2457		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2458		tdq_load_rem(tdq, td);
2459		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2460	}
2461	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2462	newtd = choosethread();
2463	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2464	PCPU_SET(switchtime, cpu_ticks());
2465	PCPU_SET(switchticks, ticks);
2466	cpu_throw(td, newtd);		/* doesn't return */
2467}
2468
2469/*
2470 * This is called from fork_exit().  Just acquire the correct locks and
2471 * let fork do the rest of the work.
2472 */
2473void
2474sched_fork_exit(struct thread *td)
2475{
2476	struct td_sched *ts;
2477	struct tdq *tdq;
2478	int cpuid;
2479
2480	/*
2481	 * Finish setting up thread glue so that it begins execution in a
2482	 * non-nested critical section with the scheduler lock held.
2483	 */
2484	cpuid = PCPU_GET(cpuid);
2485	tdq = TDQ_CPU(cpuid);
2486	ts = td->td_sched;
2487	if (TD_IS_IDLETHREAD(td))
2488		td->td_lock = TDQ_LOCKPTR(tdq);
2489	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2490	td->td_oncpu = cpuid;
2491	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2492	lock_profile_obtain_lock_success(
2493	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2494}
2495
2496SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2497SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2498    "Scheduler name");
2499SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2500    "Slice size for timeshare threads");
2501SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2502     "Interactivity score threshold");
2503SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2504     0,"Min priority for preemption, lower priorities have greater precedence");
2505SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost,
2506     0,"Controls whether static kernel priorities are assigned to sleeping threads.");
2507#ifdef SMP
2508SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2509    "Number of hz ticks to keep thread affinity for");
2510SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2511    "Enables the long-term load balancer");
2512SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2513    &balance_interval, 0,
2514    "Average frequency in stathz ticks to run the long-term balancer");
2515SYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2516    "Steals work from another hyper-threaded core on idle");
2517SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2518    "Attempts to steal work from other cores before idling");
2519SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2520    "Minimum load on remote cpu before we'll steal");
2521#endif
2522
2523/* ps compat.  All cpu percentages from ULE are weighted. */
2524static int ccpu = 0;
2525SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2526