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