sched_ule.c revision 178215
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 178215 2008-04-15 05:02:42Z marcel $");
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, 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
1076static int
1077sched_pickcpu(struct thread *td, int flags)
1078{
1079	struct cpu_group *cg;
1080	struct td_sched *ts;
1081	struct tdq *tdq;
1082	cpumask_t mask;
1083	int self;
1084	int pri;
1085	int cpu;
1086
1087	self = PCPU_GET(cpuid);
1088	ts = td->td_sched;
1089	if (smp_started == 0)
1090		return (self);
1091	/*
1092	 * Don't migrate a running thread from sched_switch().
1093	 */
1094	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1095		return (ts->ts_cpu);
1096	/*
1097	 * Prefer to run interrupt threads on the processors that generate
1098	 * the interrupt.
1099	 */
1100	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1101	    curthread->td_intr_nesting_level)
1102		ts->ts_cpu = self;
1103	/*
1104	 * If the thread can run on the last cpu and the affinity has not
1105	 * expired or it is idle run it there.
1106	 */
1107	pri = td->td_priority;
1108	tdq = TDQ_CPU(ts->ts_cpu);
1109	if (THREAD_CAN_SCHED(td, ts->ts_cpu)) {
1110		if (tdq->tdq_lowpri > PRI_MIN_IDLE)
1111			return (ts->ts_cpu);
1112		if (SCHED_AFFINITY(ts, CG_SHARE_L2) && tdq->tdq_lowpri > pri)
1113			return (ts->ts_cpu);
1114	}
1115	/*
1116	 * Search for the highest level in the tree that still has affinity.
1117	 */
1118	cg = NULL;
1119	for (cg = tdq->tdq_cg; cg != NULL; cg = cg->cg_parent)
1120		if (SCHED_AFFINITY(ts, cg->cg_level))
1121			break;
1122	cpu = -1;
1123	mask = td->td_cpuset->cs_mask.__bits[0];
1124	if (cg)
1125		cpu = sched_lowest(cg, mask, pri);
1126	if (cpu == -1)
1127		cpu = sched_lowest(cpu_top, mask, -1);
1128	/*
1129	 * Compare the lowest loaded cpu to current cpu.
1130	 */
1131	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
1132	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE)
1133		cpu = self;
1134	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1135	return (cpu);
1136}
1137#endif
1138
1139/*
1140 * Pick the highest priority task we have and return it.
1141 */
1142static struct thread *
1143tdq_choose(struct tdq *tdq)
1144{
1145	struct thread *td;
1146
1147	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1148	td = runq_choose(&tdq->tdq_realtime);
1149	if (td != NULL)
1150		return (td);
1151	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1152	if (td != NULL) {
1153		KASSERT(td->td_priority >= PRI_MIN_TIMESHARE,
1154		    ("tdq_choose: Invalid priority on timeshare queue %d",
1155		    td->td_priority));
1156		return (td);
1157	}
1158	td = runq_choose(&tdq->tdq_idle);
1159	if (td != NULL) {
1160		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1161		    ("tdq_choose: Invalid priority on idle queue %d",
1162		    td->td_priority));
1163		return (td);
1164	}
1165
1166	return (NULL);
1167}
1168
1169/*
1170 * Initialize a thread queue.
1171 */
1172static void
1173tdq_setup(struct tdq *tdq)
1174{
1175
1176	if (bootverbose)
1177		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1178	runq_init(&tdq->tdq_realtime);
1179	runq_init(&tdq->tdq_timeshare);
1180	runq_init(&tdq->tdq_idle);
1181	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1182	    "sched lock %d", (int)TDQ_ID(tdq));
1183	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1184	    MTX_SPIN | MTX_RECURSE);
1185}
1186
1187#ifdef SMP
1188static void
1189sched_setup_smp(void)
1190{
1191	struct tdq *tdq;
1192	int i;
1193
1194	cpu_top = smp_topo();
1195	for (i = 0; i < MAXCPU; i++) {
1196		if (CPU_ABSENT(i))
1197			continue;
1198		tdq = TDQ_CPU(i);
1199		tdq_setup(tdq);
1200		tdq->tdq_cg = smp_topo_find(cpu_top, i);
1201		if (tdq->tdq_cg == NULL)
1202			panic("Can't find cpu group for %d\n", i);
1203	}
1204	balance_tdq = TDQ_SELF();
1205	sched_balance();
1206}
1207#endif
1208
1209/*
1210 * Setup the thread queues and initialize the topology based on MD
1211 * information.
1212 */
1213static void
1214sched_setup(void *dummy)
1215{
1216	struct tdq *tdq;
1217
1218	tdq = TDQ_SELF();
1219#ifdef SMP
1220	sched_setup_smp();
1221#else
1222	tdq_setup(tdq);
1223#endif
1224	/*
1225	 * To avoid divide-by-zero, we set realstathz a dummy value
1226	 * in case which sched_clock() called before sched_initticks().
1227	 */
1228	realstathz = hz;
1229	sched_slice = (realstathz/10);	/* ~100ms */
1230	tickincr = 1 << SCHED_TICK_SHIFT;
1231
1232	/* Add thread0's load since it's running. */
1233	TDQ_LOCK(tdq);
1234	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1235	tdq_load_add(tdq, &thread0);
1236	tdq->tdq_lowpri = thread0.td_priority;
1237	TDQ_UNLOCK(tdq);
1238}
1239
1240/*
1241 * This routine determines the tickincr after stathz and hz are setup.
1242 */
1243/* ARGSUSED */
1244static void
1245sched_initticks(void *dummy)
1246{
1247	int incr;
1248
1249	realstathz = stathz ? stathz : hz;
1250	sched_slice = (realstathz/10);	/* ~100ms */
1251
1252	/*
1253	 * tickincr is shifted out by 10 to avoid rounding errors due to
1254	 * hz not being evenly divisible by stathz on all platforms.
1255	 */
1256	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1257	/*
1258	 * This does not work for values of stathz that are more than
1259	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1260	 */
1261	if (incr == 0)
1262		incr = 1;
1263	tickincr = incr;
1264#ifdef SMP
1265	/*
1266	 * Set the default balance interval now that we know
1267	 * what realstathz is.
1268	 */
1269	balance_interval = realstathz;
1270	/*
1271	 * Set steal thresh to log2(mp_ncpu) but no greater than 4.  This
1272	 * prevents excess thrashing on large machines and excess idle on
1273	 * smaller machines.
1274	 */
1275	steal_thresh = min(ffs(mp_ncpus) - 1, 3);
1276	affinity = SCHED_AFFINITY_DEFAULT;
1277#endif
1278}
1279
1280
1281/*
1282 * This is the core of the interactivity algorithm.  Determines a score based
1283 * on past behavior.  It is the ratio of sleep time to run time scaled to
1284 * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1285 * differs from the cpu usage because it does not account for time spent
1286 * waiting on a run-queue.  Would be prettier if we had floating point.
1287 */
1288static int
1289sched_interact_score(struct thread *td)
1290{
1291	struct td_sched *ts;
1292	int div;
1293
1294	ts = td->td_sched;
1295	/*
1296	 * The score is only needed if this is likely to be an interactive
1297	 * task.  Don't go through the expense of computing it if there's
1298	 * no chance.
1299	 */
1300	if (sched_interact <= SCHED_INTERACT_HALF &&
1301		ts->ts_runtime >= ts->ts_slptime)
1302			return (SCHED_INTERACT_HALF);
1303
1304	if (ts->ts_runtime > ts->ts_slptime) {
1305		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1306		return (SCHED_INTERACT_HALF +
1307		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1308	}
1309	if (ts->ts_slptime > ts->ts_runtime) {
1310		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1311		return (ts->ts_runtime / div);
1312	}
1313	/* runtime == slptime */
1314	if (ts->ts_runtime)
1315		return (SCHED_INTERACT_HALF);
1316
1317	/*
1318	 * This can happen if slptime and runtime are 0.
1319	 */
1320	return (0);
1321
1322}
1323
1324/*
1325 * Scale the scheduling priority according to the "interactivity" of this
1326 * process.
1327 */
1328static void
1329sched_priority(struct thread *td)
1330{
1331	int score;
1332	int pri;
1333
1334	if (td->td_pri_class != PRI_TIMESHARE)
1335		return;
1336	/*
1337	 * If the score is interactive we place the thread in the realtime
1338	 * queue with a priority that is less than kernel and interrupt
1339	 * priorities.  These threads are not subject to nice restrictions.
1340	 *
1341	 * Scores greater than this are placed on the normal timeshare queue
1342	 * where the priority is partially decided by the most recent cpu
1343	 * utilization and the rest is decided by nice value.
1344	 *
1345	 * The nice value of the process has a linear effect on the calculated
1346	 * score.  Negative nice values make it easier for a thread to be
1347	 * considered interactive.
1348	 */
1349	score = imax(0, sched_interact_score(td) - td->td_proc->p_nice);
1350	if (score < sched_interact) {
1351		pri = PRI_MIN_REALTIME;
1352		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1353		    * score;
1354		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1355		    ("sched_priority: invalid interactive priority %d score %d",
1356		    pri, score));
1357	} else {
1358		pri = SCHED_PRI_MIN;
1359		if (td->td_sched->ts_ticks)
1360			pri += SCHED_PRI_TICKS(td->td_sched);
1361		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1362		KASSERT(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE,
1363		    ("sched_priority: invalid priority %d: nice %d, "
1364		    "ticks %d ftick %d ltick %d tick pri %d",
1365		    pri, td->td_proc->p_nice, td->td_sched->ts_ticks,
1366		    td->td_sched->ts_ftick, td->td_sched->ts_ltick,
1367		    SCHED_PRI_TICKS(td->td_sched)));
1368	}
1369	sched_user_prio(td, pri);
1370
1371	return;
1372}
1373
1374/*
1375 * This routine enforces a maximum limit on the amount of scheduling history
1376 * kept.  It is called after either the slptime or runtime is adjusted.  This
1377 * function is ugly due to integer math.
1378 */
1379static void
1380sched_interact_update(struct thread *td)
1381{
1382	struct td_sched *ts;
1383	u_int sum;
1384
1385	ts = td->td_sched;
1386	sum = ts->ts_runtime + ts->ts_slptime;
1387	if (sum < SCHED_SLP_RUN_MAX)
1388		return;
1389	/*
1390	 * This only happens from two places:
1391	 * 1) We have added an unusual amount of run time from fork_exit.
1392	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1393	 */
1394	if (sum > SCHED_SLP_RUN_MAX * 2) {
1395		if (ts->ts_runtime > ts->ts_slptime) {
1396			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1397			ts->ts_slptime = 1;
1398		} else {
1399			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1400			ts->ts_runtime = 1;
1401		}
1402		return;
1403	}
1404	/*
1405	 * If we have exceeded by more than 1/5th then the algorithm below
1406	 * will not bring us back into range.  Dividing by two here forces
1407	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1408	 */
1409	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1410		ts->ts_runtime /= 2;
1411		ts->ts_slptime /= 2;
1412		return;
1413	}
1414	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1415	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1416}
1417
1418/*
1419 * Scale back the interactivity history when a child thread is created.  The
1420 * history is inherited from the parent but the thread may behave totally
1421 * differently.  For example, a shell spawning a compiler process.  We want
1422 * to learn that the compiler is behaving badly very quickly.
1423 */
1424static void
1425sched_interact_fork(struct thread *td)
1426{
1427	int ratio;
1428	int sum;
1429
1430	sum = td->td_sched->ts_runtime + td->td_sched->ts_slptime;
1431	if (sum > SCHED_SLP_RUN_FORK) {
1432		ratio = sum / SCHED_SLP_RUN_FORK;
1433		td->td_sched->ts_runtime /= ratio;
1434		td->td_sched->ts_slptime /= ratio;
1435	}
1436}
1437
1438/*
1439 * Called from proc0_init() to setup the scheduler fields.
1440 */
1441void
1442schedinit(void)
1443{
1444
1445	/*
1446	 * Set up the scheduler specific parts of proc0.
1447	 */
1448	proc0.p_sched = NULL; /* XXX */
1449	thread0.td_sched = &td_sched0;
1450	td_sched0.ts_ltick = ticks;
1451	td_sched0.ts_ftick = ticks;
1452	td_sched0.ts_slice = sched_slice;
1453}
1454
1455/*
1456 * This is only somewhat accurate since given many processes of the same
1457 * priority they will switch when their slices run out, which will be
1458 * at most sched_slice stathz ticks.
1459 */
1460int
1461sched_rr_interval(void)
1462{
1463
1464	/* Convert sched_slice to hz */
1465	return (hz/(realstathz/sched_slice));
1466}
1467
1468/*
1469 * Update the percent cpu tracking information when it is requested or
1470 * the total history exceeds the maximum.  We keep a sliding history of
1471 * tick counts that slowly decays.  This is less precise than the 4BSD
1472 * mechanism since it happens with less regular and frequent events.
1473 */
1474static void
1475sched_pctcpu_update(struct td_sched *ts)
1476{
1477
1478	if (ts->ts_ticks == 0)
1479		return;
1480	if (ticks - (hz / 10) < ts->ts_ltick &&
1481	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1482		return;
1483	/*
1484	 * Adjust counters and watermark for pctcpu calc.
1485	 */
1486	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1487		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1488			    SCHED_TICK_TARG;
1489	else
1490		ts->ts_ticks = 0;
1491	ts->ts_ltick = ticks;
1492	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1493}
1494
1495/*
1496 * Adjust the priority of a thread.  Move it to the appropriate run-queue
1497 * if necessary.  This is the back-end for several priority related
1498 * functions.
1499 */
1500static void
1501sched_thread_priority(struct thread *td, u_char prio)
1502{
1503	struct td_sched *ts;
1504	struct tdq *tdq;
1505	int oldpri;
1506
1507	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
1508	    td, td->td_name, td->td_priority, prio, curthread,
1509	    curthread->td_name);
1510	ts = td->td_sched;
1511	THREAD_LOCK_ASSERT(td, MA_OWNED);
1512	if (td->td_priority == prio)
1513		return;
1514	/*
1515	 * If the priority has been elevated due to priority
1516	 * propagation, we may have to move ourselves to a new
1517	 * queue.  This could be optimized to not re-add in some
1518	 * cases.
1519	 */
1520	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1521		sched_rem(td);
1522		td->td_priority = prio;
1523		sched_add(td, SRQ_BORROWING);
1524		return;
1525	}
1526	/*
1527	 * If the thread is currently running we may have to adjust the lowpri
1528	 * information so other cpus are aware of our current priority.
1529	 */
1530	if (TD_IS_RUNNING(td)) {
1531		tdq = TDQ_CPU(ts->ts_cpu);
1532		oldpri = td->td_priority;
1533		td->td_priority = prio;
1534		if (prio < tdq->tdq_lowpri)
1535			tdq->tdq_lowpri = prio;
1536		else if (tdq->tdq_lowpri == oldpri)
1537			tdq_setlowpri(tdq, td);
1538		return;
1539	}
1540	td->td_priority = prio;
1541}
1542
1543/*
1544 * Update a thread's priority when it is lent another thread's
1545 * priority.
1546 */
1547void
1548sched_lend_prio(struct thread *td, u_char prio)
1549{
1550
1551	td->td_flags |= TDF_BORROWING;
1552	sched_thread_priority(td, prio);
1553}
1554
1555/*
1556 * Restore a thread's priority when priority propagation is
1557 * over.  The prio argument is the minimum priority the thread
1558 * needs to have to satisfy other possible priority lending
1559 * requests.  If the thread's regular priority is less
1560 * important than prio, the thread will keep a priority boost
1561 * of prio.
1562 */
1563void
1564sched_unlend_prio(struct thread *td, u_char prio)
1565{
1566	u_char base_pri;
1567
1568	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1569	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1570		base_pri = td->td_user_pri;
1571	else
1572		base_pri = td->td_base_pri;
1573	if (prio >= base_pri) {
1574		td->td_flags &= ~TDF_BORROWING;
1575		sched_thread_priority(td, base_pri);
1576	} else
1577		sched_lend_prio(td, prio);
1578}
1579
1580/*
1581 * Standard entry for setting the priority to an absolute value.
1582 */
1583void
1584sched_prio(struct thread *td, u_char prio)
1585{
1586	u_char oldprio;
1587
1588	/* First, update the base priority. */
1589	td->td_base_pri = prio;
1590
1591	/*
1592	 * If the thread is borrowing another thread's priority, don't
1593	 * ever lower the priority.
1594	 */
1595	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1596		return;
1597
1598	/* Change the real priority. */
1599	oldprio = td->td_priority;
1600	sched_thread_priority(td, prio);
1601
1602	/*
1603	 * If the thread is on a turnstile, then let the turnstile update
1604	 * its state.
1605	 */
1606	if (TD_ON_LOCK(td) && oldprio != prio)
1607		turnstile_adjust(td, oldprio);
1608}
1609
1610/*
1611 * Set the base user priority, does not effect current running priority.
1612 */
1613void
1614sched_user_prio(struct thread *td, u_char prio)
1615{
1616	u_char oldprio;
1617
1618	td->td_base_user_pri = prio;
1619	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1620                return;
1621	oldprio = td->td_user_pri;
1622	td->td_user_pri = prio;
1623}
1624
1625void
1626sched_lend_user_prio(struct thread *td, u_char prio)
1627{
1628	u_char oldprio;
1629
1630	THREAD_LOCK_ASSERT(td, MA_OWNED);
1631	td->td_flags |= TDF_UBORROWING;
1632	oldprio = td->td_user_pri;
1633	td->td_user_pri = prio;
1634}
1635
1636void
1637sched_unlend_user_prio(struct thread *td, u_char prio)
1638{
1639	u_char base_pri;
1640
1641	THREAD_LOCK_ASSERT(td, MA_OWNED);
1642	base_pri = td->td_base_user_pri;
1643	if (prio >= base_pri) {
1644		td->td_flags &= ~TDF_UBORROWING;
1645		sched_user_prio(td, base_pri);
1646	} else {
1647		sched_lend_user_prio(td, prio);
1648	}
1649}
1650
1651/*
1652 * Block a thread for switching.  Similar to thread_block() but does not
1653 * bump the spin count.
1654 */
1655static inline struct mtx *
1656thread_block_switch(struct thread *td)
1657{
1658	struct mtx *lock;
1659
1660	THREAD_LOCK_ASSERT(td, MA_OWNED);
1661	lock = td->td_lock;
1662	td->td_lock = &blocked_lock;
1663	mtx_unlock_spin(lock);
1664
1665	return (lock);
1666}
1667
1668/*
1669 * Handle migration from sched_switch().  This happens only for
1670 * cpu binding.
1671 */
1672static struct mtx *
1673sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1674{
1675	struct tdq *tdn;
1676
1677	tdn = TDQ_CPU(td->td_sched->ts_cpu);
1678#ifdef SMP
1679	tdq_load_rem(tdq, td);
1680	/*
1681	 * Do the lock dance required to avoid LOR.  We grab an extra
1682	 * spinlock nesting to prevent preemption while we're
1683	 * not holding either run-queue lock.
1684	 */
1685	spinlock_enter();
1686	thread_block_switch(td);	/* This releases the lock on tdq. */
1687	TDQ_LOCK(tdn);
1688	tdq_add(tdn, td, flags);
1689	tdq_notify(tdn, td);
1690	/*
1691	 * After we unlock tdn the new cpu still can't switch into this
1692	 * thread until we've unblocked it in cpu_switch().  The lock
1693	 * pointers may match in the case of HTT cores.  Don't unlock here
1694	 * or we can deadlock when the other CPU runs the IPI handler.
1695	 */
1696	if (TDQ_LOCKPTR(tdn) != TDQ_LOCKPTR(tdq)) {
1697		TDQ_UNLOCK(tdn);
1698		TDQ_LOCK(tdq);
1699	}
1700	spinlock_exit();
1701#endif
1702	return (TDQ_LOCKPTR(tdn));
1703}
1704
1705/*
1706 * Release a thread that was blocked with thread_block_switch().
1707 */
1708static inline void
1709thread_unblock_switch(struct thread *td, struct mtx *mtx)
1710{
1711	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1712	    (uintptr_t)mtx);
1713}
1714
1715/*
1716 * Switch threads.  This function has to handle threads coming in while
1717 * blocked for some reason, running, or idle.  It also must deal with
1718 * migrating a thread from one queue to another as running threads may
1719 * be assigned elsewhere via binding.
1720 */
1721void
1722sched_switch(struct thread *td, struct thread *newtd, int flags)
1723{
1724	struct tdq *tdq;
1725	struct td_sched *ts;
1726	struct mtx *mtx;
1727	int srqflag;
1728	int cpuid;
1729
1730	THREAD_LOCK_ASSERT(td, MA_OWNED);
1731	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
1732
1733	cpuid = PCPU_GET(cpuid);
1734	tdq = TDQ_CPU(cpuid);
1735	ts = td->td_sched;
1736	mtx = td->td_lock;
1737	ts->ts_rltick = ticks;
1738	td->td_lastcpu = td->td_oncpu;
1739	td->td_oncpu = NOCPU;
1740	td->td_flags &= ~TDF_NEEDRESCHED;
1741	td->td_owepreempt = 0;
1742	/*
1743	 * The lock pointer in an idle thread should never change.  Reset it
1744	 * to CAN_RUN as well.
1745	 */
1746	if (TD_IS_IDLETHREAD(td)) {
1747		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1748		TD_SET_CAN_RUN(td);
1749	} else if (TD_IS_RUNNING(td)) {
1750		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1751		srqflag = (flags & SW_PREEMPT) ?
1752		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1753		    SRQ_OURSELF|SRQ_YIELDING;
1754		if (ts->ts_cpu == cpuid)
1755			tdq_runq_add(tdq, td, srqflag);
1756		else
1757			mtx = sched_switch_migrate(tdq, td, srqflag);
1758	} else {
1759		/* This thread must be going to sleep. */
1760		TDQ_LOCK(tdq);
1761		mtx = thread_block_switch(td);
1762		tdq_load_rem(tdq, td);
1763	}
1764	/*
1765	 * We enter here with the thread blocked and assigned to the
1766	 * appropriate cpu run-queue or sleep-queue and with the current
1767	 * thread-queue locked.
1768	 */
1769	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1770	newtd = choosethread();
1771	/*
1772	 * Call the MD code to switch contexts if necessary.
1773	 */
1774	if (td != newtd) {
1775#ifdef	HWPMC_HOOKS
1776		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1777			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1778#endif
1779		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1780		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1781		cpu_switch(td, newtd, mtx);
1782		/*
1783		 * We may return from cpu_switch on a different cpu.  However,
1784		 * we always return with td_lock pointing to the current cpu's
1785		 * run queue lock.
1786		 */
1787		cpuid = PCPU_GET(cpuid);
1788		tdq = TDQ_CPU(cpuid);
1789		lock_profile_obtain_lock_success(
1790		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1791#ifdef	HWPMC_HOOKS
1792		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1793			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1794#endif
1795	} else
1796		thread_unblock_switch(td, mtx);
1797	/*
1798	 * Assert that all went well and return.
1799	 */
1800	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
1801	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1802	td->td_oncpu = cpuid;
1803}
1804
1805/*
1806 * Adjust thread priorities as a result of a nice request.
1807 */
1808void
1809sched_nice(struct proc *p, int nice)
1810{
1811	struct thread *td;
1812
1813	PROC_LOCK_ASSERT(p, MA_OWNED);
1814
1815	p->p_nice = nice;
1816	FOREACH_THREAD_IN_PROC(p, td) {
1817		thread_lock(td);
1818		sched_priority(td);
1819		sched_prio(td, td->td_base_user_pri);
1820		thread_unlock(td);
1821	}
1822}
1823
1824/*
1825 * Record the sleep time for the interactivity scorer.
1826 */
1827void
1828sched_sleep(struct thread *td, int prio)
1829{
1830
1831	THREAD_LOCK_ASSERT(td, MA_OWNED);
1832
1833	td->td_slptick = ticks;
1834	if (TD_IS_SUSPENDED(td) || prio <= PSOCK)
1835		td->td_flags |= TDF_CANSWAP;
1836	if (static_boost == 1 && prio)
1837		sched_prio(td, prio);
1838	else if (static_boost && td->td_priority > static_boost)
1839		sched_prio(td, static_boost);
1840}
1841
1842/*
1843 * Schedule a thread to resume execution and record how long it voluntarily
1844 * slept.  We also update the pctcpu, interactivity, and priority.
1845 */
1846void
1847sched_wakeup(struct thread *td)
1848{
1849	struct td_sched *ts;
1850	int slptick;
1851
1852	THREAD_LOCK_ASSERT(td, MA_OWNED);
1853	ts = td->td_sched;
1854	td->td_flags &= ~TDF_CANSWAP;
1855	/*
1856	 * If we slept for more than a tick update our interactivity and
1857	 * priority.
1858	 */
1859	slptick = td->td_slptick;
1860	td->td_slptick = 0;
1861	if (slptick && slptick != ticks) {
1862		u_int hzticks;
1863
1864		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1865		ts->ts_slptime += hzticks;
1866		sched_interact_update(td);
1867		sched_pctcpu_update(ts);
1868	}
1869	/* Reset the slice value after we sleep. */
1870	ts->ts_slice = sched_slice;
1871	sched_add(td, SRQ_BORING);
1872}
1873
1874/*
1875 * Penalize the parent for creating a new child and initialize the child's
1876 * priority.
1877 */
1878void
1879sched_fork(struct thread *td, struct thread *child)
1880{
1881	THREAD_LOCK_ASSERT(td, MA_OWNED);
1882	sched_fork_thread(td, child);
1883	/*
1884	 * Penalize the parent and child for forking.
1885	 */
1886	sched_interact_fork(child);
1887	sched_priority(child);
1888	td->td_sched->ts_runtime += tickincr;
1889	sched_interact_update(td);
1890	sched_priority(td);
1891}
1892
1893/*
1894 * Fork a new thread, may be within the same process.
1895 */
1896void
1897sched_fork_thread(struct thread *td, struct thread *child)
1898{
1899	struct td_sched *ts;
1900	struct td_sched *ts2;
1901
1902	THREAD_LOCK_ASSERT(td, MA_OWNED);
1903	/*
1904	 * Initialize child.
1905	 */
1906	ts = td->td_sched;
1907	ts2 = child->td_sched;
1908	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1909	child->td_cpuset = cpuset_ref(td->td_cpuset);
1910	ts2->ts_cpu = ts->ts_cpu;
1911	ts2->ts_flags = 0;
1912	/*
1913	 * Grab our parents cpu estimation information and priority.
1914	 */
1915	ts2->ts_ticks = ts->ts_ticks;
1916	ts2->ts_ltick = ts->ts_ltick;
1917	ts2->ts_ftick = ts->ts_ftick;
1918	child->td_user_pri = td->td_user_pri;
1919	child->td_base_user_pri = td->td_base_user_pri;
1920	/*
1921	 * And update interactivity score.
1922	 */
1923	ts2->ts_slptime = ts->ts_slptime;
1924	ts2->ts_runtime = ts->ts_runtime;
1925	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
1926}
1927
1928/*
1929 * Adjust the priority class of a thread.
1930 */
1931void
1932sched_class(struct thread *td, int class)
1933{
1934
1935	THREAD_LOCK_ASSERT(td, MA_OWNED);
1936	if (td->td_pri_class == class)
1937		return;
1938	td->td_pri_class = class;
1939}
1940
1941/*
1942 * Return some of the child's priority and interactivity to the parent.
1943 */
1944void
1945sched_exit(struct proc *p, struct thread *child)
1946{
1947	struct thread *td;
1948
1949	CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
1950	    child, child->td_name, child->td_priority);
1951
1952	PROC_LOCK_ASSERT(p, MA_OWNED);
1953	td = FIRST_THREAD_IN_PROC(p);
1954	sched_exit_thread(td, child);
1955}
1956
1957/*
1958 * Penalize another thread for the time spent on this one.  This helps to
1959 * worsen the priority and interactivity of processes which schedule batch
1960 * jobs such as make.  This has little effect on the make process itself but
1961 * causes new processes spawned by it to receive worse scores immediately.
1962 */
1963void
1964sched_exit_thread(struct thread *td, struct thread *child)
1965{
1966
1967	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
1968	    child, child->td_name, child->td_priority);
1969
1970	/*
1971	 * Give the child's runtime to the parent without returning the
1972	 * sleep time as a penalty to the parent.  This causes shells that
1973	 * launch expensive things to mark their children as expensive.
1974	 */
1975	thread_lock(td);
1976	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
1977	sched_interact_update(td);
1978	sched_priority(td);
1979	thread_unlock(td);
1980}
1981
1982void
1983sched_preempt(struct thread *td)
1984{
1985	struct tdq *tdq;
1986
1987	thread_lock(td);
1988	tdq = TDQ_SELF();
1989	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1990	tdq->tdq_ipipending = 0;
1991	if (td->td_priority > tdq->tdq_lowpri) {
1992		if (td->td_critnest > 1)
1993			td->td_owepreempt = 1;
1994		else
1995			mi_switch(SW_INVOL | SW_PREEMPT, NULL);
1996	}
1997	thread_unlock(td);
1998}
1999
2000/*
2001 * Fix priorities on return to user-space.  Priorities may be elevated due
2002 * to static priorities in msleep() or similar.
2003 */
2004void
2005sched_userret(struct thread *td)
2006{
2007	/*
2008	 * XXX we cheat slightly on the locking here to avoid locking in
2009	 * the usual case.  Setting td_priority here is essentially an
2010	 * incomplete workaround for not setting it properly elsewhere.
2011	 * Now that some interrupt handlers are threads, not setting it
2012	 * properly elsewhere can clobber it in the window between setting
2013	 * it here and returning to user mode, so don't waste time setting
2014	 * it perfectly here.
2015	 */
2016	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2017	    ("thread with borrowed priority returning to userland"));
2018	if (td->td_priority != td->td_user_pri) {
2019		thread_lock(td);
2020		td->td_priority = td->td_user_pri;
2021		td->td_base_pri = td->td_user_pri;
2022		tdq_setlowpri(TDQ_SELF(), td);
2023		thread_unlock(td);
2024        }
2025}
2026
2027/*
2028 * Handle a stathz tick.  This is really only relevant for timeshare
2029 * threads.
2030 */
2031void
2032sched_clock(struct thread *td)
2033{
2034	struct tdq *tdq;
2035	struct td_sched *ts;
2036
2037	THREAD_LOCK_ASSERT(td, MA_OWNED);
2038	tdq = TDQ_SELF();
2039#ifdef SMP
2040	/*
2041	 * We run the long term load balancer infrequently on the first cpu.
2042	 */
2043	if (balance_tdq == tdq) {
2044		if (balance_ticks && --balance_ticks == 0)
2045			sched_balance();
2046	}
2047#endif
2048	/*
2049	 * Advance the insert index once for each tick to ensure that all
2050	 * threads get a chance to run.
2051	 */
2052	if (tdq->tdq_idx == tdq->tdq_ridx) {
2053		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2054		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2055			tdq->tdq_ridx = tdq->tdq_idx;
2056	}
2057	ts = td->td_sched;
2058	if (td->td_pri_class & PRI_FIFO_BIT)
2059		return;
2060	if (td->td_pri_class == PRI_TIMESHARE) {
2061		/*
2062		 * We used a tick; charge it to the thread so
2063		 * that we can compute our interactivity.
2064		 */
2065		td->td_sched->ts_runtime += tickincr;
2066		sched_interact_update(td);
2067		sched_priority(td);
2068	}
2069	/*
2070	 * We used up one time slice.
2071	 */
2072	if (--ts->ts_slice > 0)
2073		return;
2074	/*
2075	 * We're out of time, force a requeue at userret().
2076	 */
2077	ts->ts_slice = sched_slice;
2078	td->td_flags |= TDF_NEEDRESCHED;
2079}
2080
2081/*
2082 * Called once per hz tick.  Used for cpu utilization information.  This
2083 * is easier than trying to scale based on stathz.
2084 */
2085void
2086sched_tick(void)
2087{
2088	struct td_sched *ts;
2089
2090	ts = curthread->td_sched;
2091	/* Adjust ticks for pctcpu */
2092	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2093	ts->ts_ltick = ticks;
2094	/*
2095	 * Update if we've exceeded our desired tick threshhold by over one
2096	 * second.
2097	 */
2098	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2099		sched_pctcpu_update(ts);
2100}
2101
2102/*
2103 * Return whether the current CPU has runnable tasks.  Used for in-kernel
2104 * cooperative idle threads.
2105 */
2106int
2107sched_runnable(void)
2108{
2109	struct tdq *tdq;
2110	int load;
2111
2112	load = 1;
2113
2114	tdq = TDQ_SELF();
2115	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2116		if (tdq->tdq_load > 0)
2117			goto out;
2118	} else
2119		if (tdq->tdq_load - 1 > 0)
2120			goto out;
2121	load = 0;
2122out:
2123	return (load);
2124}
2125
2126/*
2127 * Choose the highest priority thread to run.  The thread is removed from
2128 * the run-queue while running however the load remains.  For SMP we set
2129 * the tdq in the global idle bitmask if it idles here.
2130 */
2131struct thread *
2132sched_choose(void)
2133{
2134	struct thread *td;
2135	struct tdq *tdq;
2136
2137	tdq = TDQ_SELF();
2138	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2139	td = tdq_choose(tdq);
2140	if (td) {
2141		td->td_sched->ts_ltick = ticks;
2142		tdq_runq_rem(tdq, td);
2143		tdq->tdq_lowpri = td->td_priority;
2144		return (td);
2145	}
2146	tdq->tdq_lowpri = PRI_MAX_IDLE;
2147	return (PCPU_GET(idlethread));
2148}
2149
2150/*
2151 * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2152 * we always request it once we exit a critical section.
2153 */
2154static inline void
2155sched_setpreempt(struct thread *td)
2156{
2157	struct thread *ctd;
2158	int cpri;
2159	int pri;
2160
2161	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2162
2163	ctd = curthread;
2164	pri = td->td_priority;
2165	cpri = ctd->td_priority;
2166	if (pri < cpri)
2167		ctd->td_flags |= TDF_NEEDRESCHED;
2168	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2169		return;
2170	if (!sched_shouldpreempt(pri, cpri, 0))
2171		return;
2172	ctd->td_owepreempt = 1;
2173}
2174
2175/*
2176 * Add a thread to a thread queue.  Select the appropriate runq and add the
2177 * thread to it.  This is the internal function called when the tdq is
2178 * predetermined.
2179 */
2180void
2181tdq_add(struct tdq *tdq, struct thread *td, int flags)
2182{
2183
2184	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2185	KASSERT((td->td_inhibitors == 0),
2186	    ("sched_add: trying to run inhibited thread"));
2187	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2188	    ("sched_add: bad thread state"));
2189	KASSERT(td->td_flags & TDF_INMEM,
2190	    ("sched_add: thread swapped out"));
2191
2192	if (td->td_priority < tdq->tdq_lowpri)
2193		tdq->tdq_lowpri = td->td_priority;
2194	tdq_runq_add(tdq, td, flags);
2195	tdq_load_add(tdq, td);
2196}
2197
2198/*
2199 * Select the target thread queue and add a thread to it.  Request
2200 * preemption or IPI a remote processor if required.
2201 */
2202void
2203sched_add(struct thread *td, int flags)
2204{
2205	struct tdq *tdq;
2206#ifdef SMP
2207	int cpu;
2208#endif
2209	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
2210	    td, td->td_name, td->td_priority, curthread,
2211	    curthread->td_name);
2212	THREAD_LOCK_ASSERT(td, MA_OWNED);
2213	/*
2214	 * Recalculate the priority before we select the target cpu or
2215	 * run-queue.
2216	 */
2217	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2218		sched_priority(td);
2219#ifdef SMP
2220	/*
2221	 * Pick the destination cpu and if it isn't ours transfer to the
2222	 * target cpu.
2223	 */
2224	cpu = sched_pickcpu(td, flags);
2225	tdq = sched_setcpu(td, cpu, flags);
2226	tdq_add(tdq, td, flags);
2227	if (cpu != PCPU_GET(cpuid)) {
2228		tdq_notify(tdq, td);
2229		return;
2230	}
2231#else
2232	tdq = TDQ_SELF();
2233	TDQ_LOCK(tdq);
2234	/*
2235	 * Now that the thread is moving to the run-queue, set the lock
2236	 * to the scheduler's lock.
2237	 */
2238	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2239	tdq_add(tdq, td, flags);
2240#endif
2241	if (!(flags & SRQ_YIELDING))
2242		sched_setpreempt(td);
2243}
2244
2245/*
2246 * Remove a thread from a run-queue without running it.  This is used
2247 * when we're stealing a thread from a remote queue.  Otherwise all threads
2248 * exit by calling sched_exit_thread() and sched_throw() themselves.
2249 */
2250void
2251sched_rem(struct thread *td)
2252{
2253	struct tdq *tdq;
2254
2255	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
2256	    td, td->td_name, td->td_priority, curthread,
2257	    curthread->td_name);
2258	tdq = TDQ_CPU(td->td_sched->ts_cpu);
2259	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2260	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2261	KASSERT(TD_ON_RUNQ(td),
2262	    ("sched_rem: thread not on run queue"));
2263	tdq_runq_rem(tdq, td);
2264	tdq_load_rem(tdq, td);
2265	TD_SET_CAN_RUN(td);
2266	if (td->td_priority == tdq->tdq_lowpri)
2267		tdq_setlowpri(tdq, NULL);
2268}
2269
2270/*
2271 * Fetch cpu utilization information.  Updates on demand.
2272 */
2273fixpt_t
2274sched_pctcpu(struct thread *td)
2275{
2276	fixpt_t pctcpu;
2277	struct td_sched *ts;
2278
2279	pctcpu = 0;
2280	ts = td->td_sched;
2281	if (ts == NULL)
2282		return (0);
2283
2284	thread_lock(td);
2285	if (ts->ts_ticks) {
2286		int rtick;
2287
2288		sched_pctcpu_update(ts);
2289		/* How many rtick per second ? */
2290		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2291		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2292	}
2293	thread_unlock(td);
2294
2295	return (pctcpu);
2296}
2297
2298/*
2299 * Enforce affinity settings for a thread.  Called after adjustments to
2300 * cpumask.
2301 */
2302void
2303sched_affinity(struct thread *td)
2304{
2305#ifdef SMP
2306	struct td_sched *ts;
2307	int cpu;
2308
2309	THREAD_LOCK_ASSERT(td, MA_OWNED);
2310	ts = td->td_sched;
2311	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2312		return;
2313	if (!TD_IS_RUNNING(td))
2314		return;
2315	td->td_flags |= TDF_NEEDRESCHED;
2316	if (!THREAD_CAN_MIGRATE(td))
2317		return;
2318	/*
2319	 * Assign the new cpu and force a switch before returning to
2320	 * userspace.  If the target thread is not running locally send
2321	 * an ipi to force the issue.
2322	 */
2323	cpu = ts->ts_cpu;
2324	ts->ts_cpu = sched_pickcpu(td, 0);
2325	if (cpu != PCPU_GET(cpuid))
2326		ipi_selected(1 << cpu, IPI_PREEMPT);
2327#endif
2328}
2329
2330/*
2331 * Bind a thread to a target cpu.
2332 */
2333void
2334sched_bind(struct thread *td, int cpu)
2335{
2336	struct td_sched *ts;
2337
2338	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2339	ts = td->td_sched;
2340	if (ts->ts_flags & TSF_BOUND)
2341		sched_unbind(td);
2342	ts->ts_flags |= TSF_BOUND;
2343	sched_pin();
2344	if (PCPU_GET(cpuid) == cpu)
2345		return;
2346	ts->ts_cpu = cpu;
2347	/* When we return from mi_switch we'll be on the correct cpu. */
2348	mi_switch(SW_VOL, NULL);
2349}
2350
2351/*
2352 * Release a bound thread.
2353 */
2354void
2355sched_unbind(struct thread *td)
2356{
2357	struct td_sched *ts;
2358
2359	THREAD_LOCK_ASSERT(td, MA_OWNED);
2360	ts = td->td_sched;
2361	if ((ts->ts_flags & TSF_BOUND) == 0)
2362		return;
2363	ts->ts_flags &= ~TSF_BOUND;
2364	sched_unpin();
2365}
2366
2367int
2368sched_is_bound(struct thread *td)
2369{
2370	THREAD_LOCK_ASSERT(td, MA_OWNED);
2371	return (td->td_sched->ts_flags & TSF_BOUND);
2372}
2373
2374/*
2375 * Basic yield call.
2376 */
2377void
2378sched_relinquish(struct thread *td)
2379{
2380	thread_lock(td);
2381	SCHED_STAT_INC(switch_relinquish);
2382	mi_switch(SW_VOL, NULL);
2383	thread_unlock(td);
2384}
2385
2386/*
2387 * Return the total system load.
2388 */
2389int
2390sched_load(void)
2391{
2392#ifdef SMP
2393	int total;
2394	int i;
2395
2396	total = 0;
2397	for (i = 0; i <= mp_maxid; i++)
2398		total += TDQ_CPU(i)->tdq_sysload;
2399	return (total);
2400#else
2401	return (TDQ_SELF()->tdq_sysload);
2402#endif
2403}
2404
2405int
2406sched_sizeof_proc(void)
2407{
2408	return (sizeof(struct proc));
2409}
2410
2411int
2412sched_sizeof_thread(void)
2413{
2414	return (sizeof(struct thread) + sizeof(struct td_sched));
2415}
2416
2417/*
2418 * The actual idle process.
2419 */
2420void
2421sched_idletd(void *dummy)
2422{
2423	struct thread *td;
2424	struct tdq *tdq;
2425
2426	td = curthread;
2427	tdq = TDQ_SELF();
2428	mtx_assert(&Giant, MA_NOTOWNED);
2429	/* ULE relies on preemption for idle interruption. */
2430	for (;;) {
2431#ifdef SMP
2432		if (tdq_idled(tdq))
2433			cpu_idle();
2434#else
2435		cpu_idle();
2436#endif
2437	}
2438}
2439
2440/*
2441 * A CPU is entering for the first time or a thread is exiting.
2442 */
2443void
2444sched_throw(struct thread *td)
2445{
2446	struct thread *newtd;
2447	struct tdq *tdq;
2448
2449	tdq = TDQ_SELF();
2450	if (td == NULL) {
2451		/* Correct spinlock nesting and acquire the correct lock. */
2452		TDQ_LOCK(tdq);
2453		spinlock_exit();
2454	} else {
2455		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2456		tdq_load_rem(tdq, td);
2457		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2458	}
2459	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2460	newtd = choosethread();
2461	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2462	PCPU_SET(switchtime, cpu_ticks());
2463	PCPU_SET(switchticks, ticks);
2464	cpu_throw(td, newtd);		/* doesn't return */
2465}
2466
2467/*
2468 * This is called from fork_exit().  Just acquire the correct locks and
2469 * let fork do the rest of the work.
2470 */
2471void
2472sched_fork_exit(struct thread *td)
2473{
2474	struct td_sched *ts;
2475	struct tdq *tdq;
2476	int cpuid;
2477
2478	/*
2479	 * Finish setting up thread glue so that it begins execution in a
2480	 * non-nested critical section with the scheduler lock held.
2481	 */
2482	cpuid = PCPU_GET(cpuid);
2483	tdq = TDQ_CPU(cpuid);
2484	ts = td->td_sched;
2485	if (TD_IS_IDLETHREAD(td))
2486		td->td_lock = TDQ_LOCKPTR(tdq);
2487	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2488	td->td_oncpu = cpuid;
2489	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2490	lock_profile_obtain_lock_success(
2491	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2492}
2493
2494SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2495SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2496    "Scheduler name");
2497SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2498    "Slice size for timeshare threads");
2499SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2500     "Interactivity score threshold");
2501SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2502     0,"Min priority for preemption, lower priorities have greater precedence");
2503SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost,
2504     0,"Controls whether static kernel priorities are assigned to sleeping threads.");
2505#ifdef SMP
2506SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2507    "Number of hz ticks to keep thread affinity for");
2508SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2509    "Enables the long-term load balancer");
2510SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2511    &balance_interval, 0,
2512    "Average frequency in stathz ticks to run the long-term balancer");
2513SYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2514    "Steals work from another hyper-threaded core on idle");
2515SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2516    "Attempts to steal work from other cores before idling");
2517SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2518    "Minimum load on remote cpu before we'll steal");
2519#endif
2520
2521/* ps compat.  All cpu percentages from ULE are weighted. */
2522static int ccpu = 0;
2523SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2524