xref: /freebsd/sys/kern/sched_ule.c (revision 03d17db7d5fece2f198e2d1906bd65e841bf5ca8)
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$");
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  */
85 struct 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 
101 static 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  */
172 static int sched_interact = SCHED_INTERACT_THRESH;
173 static int realstathz;
174 static int tickincr;
175 static int sched_slice = 1;
176 #ifdef PREEMPTION
177 #ifdef FULL_PREEMPTION
178 static int preempt_thresh = PRI_MAX_IDLE;
179 #else
180 static int preempt_thresh = PRI_MIN_KERN;
181 #endif
182 #else
183 static int preempt_thresh = 0;
184 #endif
185 static 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  */
192 struct 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
211 struct 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  */
219 static int rebalance = 1;
220 static int balance_interval = 128;	/* Default set in sched_initticks(). */
221 static int affinity;
222 static int steal_htt = 1;
223 static int steal_idle = 1;
224 static int steal_thresh = 2;
225 
226 /*
227  * One thread queue per processor.
228  */
229 static struct tdq	tdq_cpu[MAXCPU];
230 static struct tdq	*balance_tdq;
231 static 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 */
237 static 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 
250 static void sched_priority(struct thread *);
251 static void sched_thread_priority(struct thread *, u_char);
252 static int sched_interact_score(struct thread *);
253 static void sched_interact_update(struct thread *);
254 static void sched_interact_fork(struct thread *);
255 static void sched_pctcpu_update(struct td_sched *);
256 
257 /* Operations on per processor queues */
258 static struct thread *tdq_choose(struct tdq *);
259 static void tdq_setup(struct tdq *);
260 static void tdq_load_add(struct tdq *, struct thread *);
261 static void tdq_load_rem(struct tdq *, struct thread *);
262 static __inline void tdq_runq_add(struct tdq *, struct thread *, int);
263 static __inline void tdq_runq_rem(struct tdq *, struct thread *);
264 static inline int sched_shouldpreempt(int, int, int);
265 void tdq_print(int cpu);
266 static void runq_print(struct runq *rq);
267 static void tdq_add(struct tdq *, struct thread *, int);
268 #ifdef SMP
269 static int tdq_move(struct tdq *, struct tdq *);
270 static int tdq_idled(struct tdq *);
271 static void tdq_notify(struct tdq *, struct thread *);
272 static struct thread *tdq_steal(struct tdq *, int);
273 static struct thread *runq_steal(struct runq *, int);
274 static int sched_pickcpu(struct thread *, int);
275 static void sched_balance(void);
276 static int sched_balance_pair(struct tdq *, struct tdq *);
277 static inline struct tdq *sched_setcpu(struct thread *, int, int);
278 static inline struct mtx *thread_block_switch(struct thread *);
279 static inline void thread_unblock_switch(struct thread *, struct mtx *);
280 static struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
281 #endif
282 
283 static void sched_setup(void *dummy);
284 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
285 
286 static void sched_initticks(void *dummy);
287 SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
288     NULL);
289 
290 /*
291  * Print the threads waiting on a run-queue.
292  */
293 static void
294 runq_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  */
321 void
322 tdq_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 
344 static inline int
345 sched_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  */
383 static __inline void
384 tdq_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  */
434 static __inline void
435 tdq_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  */
460 static void
461 tdq_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  */
477 static void
478 tdq_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  */
496 static void
497 tdq_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
512 struct 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 
527 static __inline int cpu_search(struct cpu_group *cg, struct cpu_search *low,
528     struct cpu_search *high, const int match);
529 int cpu_search_lowest(struct cpu_group *cg, struct cpu_search *low);
530 int cpu_search_highest(struct cpu_group *cg, struct cpu_search *high);
531 int 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  */
539 static __inline int
540 cpu_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  */
575 static __inline int
576 cpu_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  */
639 int
640 cpu_search_lowest(struct cpu_group *cg, struct cpu_search *low)
641 {
642 	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
643 }
644 
645 int
646 cpu_search_highest(struct cpu_group *cg, struct cpu_search *high)
647 {
648 	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
649 }
650 
651 int
652 cpu_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  */
663 static inline int
664 sched_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  */
679 static inline int
680 sched_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  */
696 static inline void
697 sched_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 
716 static void
717 sched_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 
745 static void
746 sched_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  */
767 static void
768 tdq_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  */
782 static void
783 tdq_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  */
792 static int
793 sched_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  */
833 static int
834 tdq_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  */
868 static int
869 tdq_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  */
924 static void
925 tdq_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  */
946 static struct thread *
947 runq_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;
961 again:
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  */
993 static struct thread *
994 runq_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  */
1022 static struct thread *
1023 tdq_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  */
1040 static inline struct tdq *
1041 sched_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 
1076 static int
1077 sched_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  */
1142 static struct thread *
1143 tdq_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  */
1172 static void
1173 tdq_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
1188 static void
1189 sched_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  */
1213 static void
1214 sched_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 */
1244 static void
1245 sched_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  */
1288 static int
1289 sched_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  */
1328 static void
1329 sched_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  */
1379 static void
1380 sched_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  */
1424 static void
1425 sched_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  */
1441 void
1442 schedinit(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  */
1460 int
1461 sched_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  */
1474 static void
1475 sched_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  */
1500 static void
1501 sched_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  */
1547 void
1548 sched_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  */
1563 void
1564 sched_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  */
1583 void
1584 sched_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  */
1613 void
1614 sched_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 
1625 void
1626 sched_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 
1636 void
1637 sched_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  */
1655 static inline struct mtx *
1656 thread_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  */
1672 static struct mtx *
1673 sched_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  */
1708 static inline void
1709 thread_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  */
1721 void
1722 sched_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  */
1808 void
1809 sched_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  */
1827 void
1828 sched_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 && prio)
1837 		sched_prio(td, prio);
1838 }
1839 
1840 /*
1841  * Schedule a thread to resume execution and record how long it voluntarily
1842  * slept.  We also update the pctcpu, interactivity, and priority.
1843  */
1844 void
1845 sched_wakeup(struct thread *td)
1846 {
1847 	struct td_sched *ts;
1848 	int slptick;
1849 
1850 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1851 	ts = td->td_sched;
1852 	td->td_flags &= ~TDF_CANSWAP;
1853 	/*
1854 	 * If we slept for more than a tick update our interactivity and
1855 	 * priority.
1856 	 */
1857 	slptick = td->td_slptick;
1858 	td->td_slptick = 0;
1859 	if (slptick && slptick != ticks) {
1860 		u_int hzticks;
1861 
1862 		hzticks = (ticks - slptick) << SCHED_TICK_SHIFT;
1863 		ts->ts_slptime += hzticks;
1864 		sched_interact_update(td);
1865 		sched_pctcpu_update(ts);
1866 	}
1867 	/* Reset the slice value after we sleep. */
1868 	ts->ts_slice = sched_slice;
1869 	sched_add(td, SRQ_BORING);
1870 }
1871 
1872 /*
1873  * Penalize the parent for creating a new child and initialize the child's
1874  * priority.
1875  */
1876 void
1877 sched_fork(struct thread *td, struct thread *child)
1878 {
1879 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1880 	sched_fork_thread(td, child);
1881 	/*
1882 	 * Penalize the parent and child for forking.
1883 	 */
1884 	sched_interact_fork(child);
1885 	sched_priority(child);
1886 	td->td_sched->ts_runtime += tickincr;
1887 	sched_interact_update(td);
1888 	sched_priority(td);
1889 }
1890 
1891 /*
1892  * Fork a new thread, may be within the same process.
1893  */
1894 void
1895 sched_fork_thread(struct thread *td, struct thread *child)
1896 {
1897 	struct td_sched *ts;
1898 	struct td_sched *ts2;
1899 
1900 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1901 	/*
1902 	 * Initialize child.
1903 	 */
1904 	ts = td->td_sched;
1905 	ts2 = child->td_sched;
1906 	child->td_lock = TDQ_LOCKPTR(TDQ_SELF());
1907 	child->td_cpuset = cpuset_ref(td->td_cpuset);
1908 	ts2->ts_cpu = ts->ts_cpu;
1909 	ts2->ts_flags = 0;
1910 	/*
1911 	 * Grab our parents cpu estimation information and priority.
1912 	 */
1913 	ts2->ts_ticks = ts->ts_ticks;
1914 	ts2->ts_ltick = ts->ts_ltick;
1915 	ts2->ts_ftick = ts->ts_ftick;
1916 	child->td_user_pri = td->td_user_pri;
1917 	child->td_base_user_pri = td->td_base_user_pri;
1918 	/*
1919 	 * And update interactivity score.
1920 	 */
1921 	ts2->ts_slptime = ts->ts_slptime;
1922 	ts2->ts_runtime = ts->ts_runtime;
1923 	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
1924 }
1925 
1926 /*
1927  * Adjust the priority class of a thread.
1928  */
1929 void
1930 sched_class(struct thread *td, int class)
1931 {
1932 
1933 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1934 	if (td->td_pri_class == class)
1935 		return;
1936 	td->td_pri_class = class;
1937 }
1938 
1939 /*
1940  * Return some of the child's priority and interactivity to the parent.
1941  */
1942 void
1943 sched_exit(struct proc *p, struct thread *child)
1944 {
1945 	struct thread *td;
1946 
1947 	CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
1948 	    child, child->td_name, child->td_priority);
1949 
1950 	PROC_LOCK_ASSERT(p, MA_OWNED);
1951 	td = FIRST_THREAD_IN_PROC(p);
1952 	sched_exit_thread(td, child);
1953 }
1954 
1955 /*
1956  * Penalize another thread for the time spent on this one.  This helps to
1957  * worsen the priority and interactivity of processes which schedule batch
1958  * jobs such as make.  This has little effect on the make process itself but
1959  * causes new processes spawned by it to receive worse scores immediately.
1960  */
1961 void
1962 sched_exit_thread(struct thread *td, struct thread *child)
1963 {
1964 
1965 	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
1966 	    child, child->td_name, child->td_priority);
1967 
1968 	/*
1969 	 * Give the child's runtime to the parent without returning the
1970 	 * sleep time as a penalty to the parent.  This causes shells that
1971 	 * launch expensive things to mark their children as expensive.
1972 	 */
1973 	thread_lock(td);
1974 	td->td_sched->ts_runtime += child->td_sched->ts_runtime;
1975 	sched_interact_update(td);
1976 	sched_priority(td);
1977 	thread_unlock(td);
1978 }
1979 
1980 void
1981 sched_preempt(struct thread *td)
1982 {
1983 	struct tdq *tdq;
1984 
1985 	thread_lock(td);
1986 	tdq = TDQ_SELF();
1987 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1988 	tdq->tdq_ipipending = 0;
1989 	if (td->td_priority > tdq->tdq_lowpri) {
1990 		if (td->td_critnest > 1)
1991 			td->td_owepreempt = 1;
1992 		else
1993 			mi_switch(SW_INVOL | SW_PREEMPT, NULL);
1994 	}
1995 	thread_unlock(td);
1996 }
1997 
1998 /*
1999  * Fix priorities on return to user-space.  Priorities may be elevated due
2000  * to static priorities in msleep() or similar.
2001  */
2002 void
2003 sched_userret(struct thread *td)
2004 {
2005 	/*
2006 	 * XXX we cheat slightly on the locking here to avoid locking in
2007 	 * the usual case.  Setting td_priority here is essentially an
2008 	 * incomplete workaround for not setting it properly elsewhere.
2009 	 * Now that some interrupt handlers are threads, not setting it
2010 	 * properly elsewhere can clobber it in the window between setting
2011 	 * it here and returning to user mode, so don't waste time setting
2012 	 * it perfectly here.
2013 	 */
2014 	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2015 	    ("thread with borrowed priority returning to userland"));
2016 	if (td->td_priority != td->td_user_pri) {
2017 		thread_lock(td);
2018 		td->td_priority = td->td_user_pri;
2019 		td->td_base_pri = td->td_user_pri;
2020 		tdq_setlowpri(TDQ_SELF(), td);
2021 		thread_unlock(td);
2022         }
2023 }
2024 
2025 /*
2026  * Handle a stathz tick.  This is really only relevant for timeshare
2027  * threads.
2028  */
2029 void
2030 sched_clock(struct thread *td)
2031 {
2032 	struct tdq *tdq;
2033 	struct td_sched *ts;
2034 
2035 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2036 	tdq = TDQ_SELF();
2037 #ifdef SMP
2038 	/*
2039 	 * We run the long term load balancer infrequently on the first cpu.
2040 	 */
2041 	if (balance_tdq == tdq) {
2042 		if (balance_ticks && --balance_ticks == 0)
2043 			sched_balance();
2044 	}
2045 #endif
2046 	/*
2047 	 * Advance the insert index once for each tick to ensure that all
2048 	 * threads get a chance to run.
2049 	 */
2050 	if (tdq->tdq_idx == tdq->tdq_ridx) {
2051 		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2052 		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2053 			tdq->tdq_ridx = tdq->tdq_idx;
2054 	}
2055 	ts = td->td_sched;
2056 	if (td->td_pri_class & PRI_FIFO_BIT)
2057 		return;
2058 	if (td->td_pri_class == PRI_TIMESHARE) {
2059 		/*
2060 		 * We used a tick; charge it to the thread so
2061 		 * that we can compute our interactivity.
2062 		 */
2063 		td->td_sched->ts_runtime += tickincr;
2064 		sched_interact_update(td);
2065 		sched_priority(td);
2066 	}
2067 	/*
2068 	 * We used up one time slice.
2069 	 */
2070 	if (--ts->ts_slice > 0)
2071 		return;
2072 	/*
2073 	 * We're out of time, force a requeue at userret().
2074 	 */
2075 	ts->ts_slice = sched_slice;
2076 	td->td_flags |= TDF_NEEDRESCHED;
2077 }
2078 
2079 /*
2080  * Called once per hz tick.  Used for cpu utilization information.  This
2081  * is easier than trying to scale based on stathz.
2082  */
2083 void
2084 sched_tick(void)
2085 {
2086 	struct td_sched *ts;
2087 
2088 	ts = curthread->td_sched;
2089 	/* Adjust ticks for pctcpu */
2090 	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2091 	ts->ts_ltick = ticks;
2092 	/*
2093 	 * Update if we've exceeded our desired tick threshhold by over one
2094 	 * second.
2095 	 */
2096 	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2097 		sched_pctcpu_update(ts);
2098 }
2099 
2100 /*
2101  * Return whether the current CPU has runnable tasks.  Used for in-kernel
2102  * cooperative idle threads.
2103  */
2104 int
2105 sched_runnable(void)
2106 {
2107 	struct tdq *tdq;
2108 	int load;
2109 
2110 	load = 1;
2111 
2112 	tdq = TDQ_SELF();
2113 	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2114 		if (tdq->tdq_load > 0)
2115 			goto out;
2116 	} else
2117 		if (tdq->tdq_load - 1 > 0)
2118 			goto out;
2119 	load = 0;
2120 out:
2121 	return (load);
2122 }
2123 
2124 /*
2125  * Choose the highest priority thread to run.  The thread is removed from
2126  * the run-queue while running however the load remains.  For SMP we set
2127  * the tdq in the global idle bitmask if it idles here.
2128  */
2129 struct thread *
2130 sched_choose(void)
2131 {
2132 	struct thread *td;
2133 	struct tdq *tdq;
2134 
2135 	tdq = TDQ_SELF();
2136 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2137 	td = tdq_choose(tdq);
2138 	if (td) {
2139 		td->td_sched->ts_ltick = ticks;
2140 		tdq_runq_rem(tdq, td);
2141 		return (td);
2142 	}
2143 	return (PCPU_GET(idlethread));
2144 }
2145 
2146 /*
2147  * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2148  * we always request it once we exit a critical section.
2149  */
2150 static inline void
2151 sched_setpreempt(struct thread *td)
2152 {
2153 	struct thread *ctd;
2154 	int cpri;
2155 	int pri;
2156 
2157 	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2158 
2159 	ctd = curthread;
2160 	pri = td->td_priority;
2161 	cpri = ctd->td_priority;
2162 	if (pri < cpri)
2163 		ctd->td_flags |= TDF_NEEDRESCHED;
2164 	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2165 		return;
2166 	if (!sched_shouldpreempt(pri, cpri, 0))
2167 		return;
2168 	ctd->td_owepreempt = 1;
2169 }
2170 
2171 /*
2172  * Add a thread to a thread queue.  Select the appropriate runq and add the
2173  * thread to it.  This is the internal function called when the tdq is
2174  * predetermined.
2175  */
2176 void
2177 tdq_add(struct tdq *tdq, struct thread *td, int flags)
2178 {
2179 
2180 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2181 	KASSERT((td->td_inhibitors == 0),
2182 	    ("sched_add: trying to run inhibited thread"));
2183 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2184 	    ("sched_add: bad thread state"));
2185 	KASSERT(td->td_flags & TDF_INMEM,
2186 	    ("sched_add: thread swapped out"));
2187 
2188 	if (td->td_priority < tdq->tdq_lowpri)
2189 		tdq->tdq_lowpri = td->td_priority;
2190 	tdq_runq_add(tdq, td, flags);
2191 	tdq_load_add(tdq, td);
2192 }
2193 
2194 /*
2195  * Select the target thread queue and add a thread to it.  Request
2196  * preemption or IPI a remote processor if required.
2197  */
2198 void
2199 sched_add(struct thread *td, int flags)
2200 {
2201 	struct tdq *tdq;
2202 #ifdef SMP
2203 	int cpu;
2204 #endif
2205 	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
2206 	    td, td->td_name, td->td_priority, curthread,
2207 	    curthread->td_name);
2208 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2209 	/*
2210 	 * Recalculate the priority before we select the target cpu or
2211 	 * run-queue.
2212 	 */
2213 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2214 		sched_priority(td);
2215 #ifdef SMP
2216 	/*
2217 	 * Pick the destination cpu and if it isn't ours transfer to the
2218 	 * target cpu.
2219 	 */
2220 	cpu = sched_pickcpu(td, flags);
2221 	tdq = sched_setcpu(td, cpu, flags);
2222 	tdq_add(tdq, td, flags);
2223 	if (cpu != PCPU_GET(cpuid)) {
2224 		tdq_notify(tdq, td);
2225 		return;
2226 	}
2227 #else
2228 	tdq = TDQ_SELF();
2229 	TDQ_LOCK(tdq);
2230 	/*
2231 	 * Now that the thread is moving to the run-queue, set the lock
2232 	 * to the scheduler's lock.
2233 	 */
2234 	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2235 	tdq_add(tdq, td, flags);
2236 #endif
2237 	if (!(flags & SRQ_YIELDING))
2238 		sched_setpreempt(td);
2239 }
2240 
2241 /*
2242  * Remove a thread from a run-queue without running it.  This is used
2243  * when we're stealing a thread from a remote queue.  Otherwise all threads
2244  * exit by calling sched_exit_thread() and sched_throw() themselves.
2245  */
2246 void
2247 sched_rem(struct thread *td)
2248 {
2249 	struct tdq *tdq;
2250 
2251 	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
2252 	    td, td->td_name, td->td_priority, curthread,
2253 	    curthread->td_name);
2254 	tdq = TDQ_CPU(td->td_sched->ts_cpu);
2255 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2256 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2257 	KASSERT(TD_ON_RUNQ(td),
2258 	    ("sched_rem: thread not on run queue"));
2259 	tdq_runq_rem(tdq, td);
2260 	tdq_load_rem(tdq, td);
2261 	TD_SET_CAN_RUN(td);
2262 	if (td->td_priority == tdq->tdq_lowpri)
2263 		tdq_setlowpri(tdq, NULL);
2264 }
2265 
2266 /*
2267  * Fetch cpu utilization information.  Updates on demand.
2268  */
2269 fixpt_t
2270 sched_pctcpu(struct thread *td)
2271 {
2272 	fixpt_t pctcpu;
2273 	struct td_sched *ts;
2274 
2275 	pctcpu = 0;
2276 	ts = td->td_sched;
2277 	if (ts == NULL)
2278 		return (0);
2279 
2280 	thread_lock(td);
2281 	if (ts->ts_ticks) {
2282 		int rtick;
2283 
2284 		sched_pctcpu_update(ts);
2285 		/* How many rtick per second ? */
2286 		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2287 		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2288 	}
2289 	thread_unlock(td);
2290 
2291 	return (pctcpu);
2292 }
2293 
2294 /*
2295  * Enforce affinity settings for a thread.  Called after adjustments to
2296  * cpumask.
2297  */
2298 void
2299 sched_affinity(struct thread *td)
2300 {
2301 #ifdef SMP
2302 	struct td_sched *ts;
2303 	int cpu;
2304 
2305 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2306 	ts = td->td_sched;
2307 	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2308 		return;
2309 	if (!TD_IS_RUNNING(td))
2310 		return;
2311 	td->td_flags |= TDF_NEEDRESCHED;
2312 	if (!THREAD_CAN_MIGRATE(td))
2313 		return;
2314 	/*
2315 	 * Assign the new cpu and force a switch before returning to
2316 	 * userspace.  If the target thread is not running locally send
2317 	 * an ipi to force the issue.
2318 	 */
2319 	cpu = ts->ts_cpu;
2320 	ts->ts_cpu = sched_pickcpu(td, 0);
2321 	if (cpu != PCPU_GET(cpuid))
2322 		ipi_selected(1 << cpu, IPI_PREEMPT);
2323 #endif
2324 }
2325 
2326 /*
2327  * Bind a thread to a target cpu.
2328  */
2329 void
2330 sched_bind(struct thread *td, int cpu)
2331 {
2332 	struct td_sched *ts;
2333 
2334 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2335 	ts = td->td_sched;
2336 	if (ts->ts_flags & TSF_BOUND)
2337 		sched_unbind(td);
2338 	ts->ts_flags |= TSF_BOUND;
2339 	sched_pin();
2340 	if (PCPU_GET(cpuid) == cpu)
2341 		return;
2342 	ts->ts_cpu = cpu;
2343 	/* When we return from mi_switch we'll be on the correct cpu. */
2344 	mi_switch(SW_VOL, NULL);
2345 }
2346 
2347 /*
2348  * Release a bound thread.
2349  */
2350 void
2351 sched_unbind(struct thread *td)
2352 {
2353 	struct td_sched *ts;
2354 
2355 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2356 	ts = td->td_sched;
2357 	if ((ts->ts_flags & TSF_BOUND) == 0)
2358 		return;
2359 	ts->ts_flags &= ~TSF_BOUND;
2360 	sched_unpin();
2361 }
2362 
2363 int
2364 sched_is_bound(struct thread *td)
2365 {
2366 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2367 	return (td->td_sched->ts_flags & TSF_BOUND);
2368 }
2369 
2370 /*
2371  * Basic yield call.
2372  */
2373 void
2374 sched_relinquish(struct thread *td)
2375 {
2376 	thread_lock(td);
2377 	SCHED_STAT_INC(switch_relinquish);
2378 	mi_switch(SW_VOL, NULL);
2379 	thread_unlock(td);
2380 }
2381 
2382 /*
2383  * Return the total system load.
2384  */
2385 int
2386 sched_load(void)
2387 {
2388 #ifdef SMP
2389 	int total;
2390 	int i;
2391 
2392 	total = 0;
2393 	for (i = 0; i <= mp_maxid; i++)
2394 		total += TDQ_CPU(i)->tdq_sysload;
2395 	return (total);
2396 #else
2397 	return (TDQ_SELF()->tdq_sysload);
2398 #endif
2399 }
2400 
2401 int
2402 sched_sizeof_proc(void)
2403 {
2404 	return (sizeof(struct proc));
2405 }
2406 
2407 int
2408 sched_sizeof_thread(void)
2409 {
2410 	return (sizeof(struct thread) + sizeof(struct td_sched));
2411 }
2412 
2413 /*
2414  * The actual idle process.
2415  */
2416 void
2417 sched_idletd(void *dummy)
2418 {
2419 	struct thread *td;
2420 	struct tdq *tdq;
2421 
2422 	td = curthread;
2423 	tdq = TDQ_SELF();
2424 	mtx_assert(&Giant, MA_NOTOWNED);
2425 	/* ULE relies on preemption for idle interruption. */
2426 	for (;;) {
2427 #ifdef SMP
2428 		if (tdq_idled(tdq))
2429 			cpu_idle();
2430 #else
2431 		cpu_idle();
2432 #endif
2433 	}
2434 }
2435 
2436 /*
2437  * A CPU is entering for the first time or a thread is exiting.
2438  */
2439 void
2440 sched_throw(struct thread *td)
2441 {
2442 	struct thread *newtd;
2443 	struct tdq *tdq;
2444 
2445 	tdq = TDQ_SELF();
2446 	if (td == NULL) {
2447 		/* Correct spinlock nesting and acquire the correct lock. */
2448 		TDQ_LOCK(tdq);
2449 		spinlock_exit();
2450 	} else {
2451 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2452 		tdq_load_rem(tdq, td);
2453 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2454 	}
2455 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2456 	newtd = choosethread();
2457 	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2458 	PCPU_SET(switchtime, cpu_ticks());
2459 	PCPU_SET(switchticks, ticks);
2460 	cpu_throw(td, newtd);		/* doesn't return */
2461 }
2462 
2463 /*
2464  * This is called from fork_exit().  Just acquire the correct locks and
2465  * let fork do the rest of the work.
2466  */
2467 void
2468 sched_fork_exit(struct thread *td)
2469 {
2470 	struct td_sched *ts;
2471 	struct tdq *tdq;
2472 	int cpuid;
2473 
2474 	/*
2475 	 * Finish setting up thread glue so that it begins execution in a
2476 	 * non-nested critical section with the scheduler lock held.
2477 	 */
2478 	cpuid = PCPU_GET(cpuid);
2479 	tdq = TDQ_CPU(cpuid);
2480 	ts = td->td_sched;
2481 	if (TD_IS_IDLETHREAD(td))
2482 		td->td_lock = TDQ_LOCKPTR(tdq);
2483 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2484 	td->td_oncpu = cpuid;
2485 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2486 	lock_profile_obtain_lock_success(
2487 	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2488 }
2489 
2490 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2491 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2492     "Scheduler name");
2493 SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2494     "Slice size for timeshare threads");
2495 SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2496      "Interactivity score threshold");
2497 SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW, &preempt_thresh,
2498      0,"Min priority for preemption, lower priorities have greater precedence");
2499 SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost,
2500      0,"Controls whether static kernel priorities are assigned to sleeping threads.");
2501 #ifdef SMP
2502 SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2503     "Number of hz ticks to keep thread affinity for");
2504 SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2505     "Enables the long-term load balancer");
2506 SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2507     &balance_interval, 0,
2508     "Average frequency in stathz ticks to run the long-term balancer");
2509 SYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0,
2510     "Steals work from another hyper-threaded core on idle");
2511 SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2512     "Attempts to steal work from other cores before idling");
2513 SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2514     "Minimum load on remote cpu before we'll steal");
2515 #endif
2516 
2517 /* ps compat.  All cpu percentages from ULE are weighted. */
2518 static int ccpu = 0;
2519 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2520