xref: /freebsd/sys/kern/sched_ule.c (revision 718cf2ccb9956613756ab15d7a0e28f2c8e91cab)
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/limits.h>
50 #include <sys/lock.h>
51 #include <sys/mutex.h>
52 #include <sys/proc.h>
53 #include <sys/resource.h>
54 #include <sys/resourcevar.h>
55 #include <sys/sched.h>
56 #include <sys/sdt.h>
57 #include <sys/smp.h>
58 #include <sys/sx.h>
59 #include <sys/sysctl.h>
60 #include <sys/sysproto.h>
61 #include <sys/turnstile.h>
62 #include <sys/umtx.h>
63 #include <sys/vmmeter.h>
64 #include <sys/cpuset.h>
65 #include <sys/sbuf.h>
66 
67 #ifdef HWPMC_HOOKS
68 #include <sys/pmckern.h>
69 #endif
70 
71 #ifdef KDTRACE_HOOKS
72 #include <sys/dtrace_bsd.h>
73 int				dtrace_vtime_active;
74 dtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
75 #endif
76 
77 #include <machine/cpu.h>
78 #include <machine/smp.h>
79 
80 #define	KTR_ULE	0
81 
82 #define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
83 #define	TDQ_NAME_LEN	(sizeof("sched lock ") + sizeof(__XSTRING(MAXCPU)))
84 #define	TDQ_LOADNAME_LEN	(sizeof("CPU ") + sizeof(__XSTRING(MAXCPU)) - 1 + sizeof(" load"))
85 
86 /*
87  * Thread scheduler specific section.  All fields are protected
88  * by the thread lock.
89  */
90 struct td_sched {
91 	struct runq	*ts_runq;	/* Run-queue we're queued on. */
92 	short		ts_flags;	/* TSF_* flags. */
93 	int		ts_cpu;		/* CPU that we have affinity for. */
94 	int		ts_rltick;	/* Real last tick, for affinity. */
95 	int		ts_slice;	/* Ticks of slice remaining. */
96 	u_int		ts_slptime;	/* Number of ticks we vol. slept */
97 	u_int		ts_runtime;	/* Number of ticks we were running */
98 	int		ts_ltick;	/* Last tick that we were running on */
99 	int		ts_ftick;	/* First tick that we were running on */
100 	int		ts_ticks;	/* Tick count */
101 #ifdef KTR
102 	char		ts_name[TS_NAME_LEN];
103 #endif
104 };
105 /* flags kept in ts_flags */
106 #define	TSF_BOUND	0x0001		/* Thread can not migrate. */
107 #define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
108 
109 #define	THREAD_CAN_MIGRATE(td)	((td)->td_pinned == 0)
110 #define	THREAD_CAN_SCHED(td, cpu)	\
111     CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
112 
113 _Static_assert(sizeof(struct thread) + sizeof(struct td_sched) <=
114     sizeof(struct thread0_storage),
115     "increase struct thread0_storage.t0st_sched size");
116 
117 /*
118  * Priority ranges used for interactive and non-interactive timeshare
119  * threads.  The timeshare priorities are split up into four ranges.
120  * The first range handles interactive threads.  The last three ranges
121  * (NHALF, x, and NHALF) handle non-interactive threads with the outer
122  * ranges supporting nice values.
123  */
124 #define	PRI_TIMESHARE_RANGE	(PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE + 1)
125 #define	PRI_INTERACT_RANGE	((PRI_TIMESHARE_RANGE - SCHED_PRI_NRESV) / 2)
126 #define	PRI_BATCH_RANGE		(PRI_TIMESHARE_RANGE - PRI_INTERACT_RANGE)
127 
128 #define	PRI_MIN_INTERACT	PRI_MIN_TIMESHARE
129 #define	PRI_MAX_INTERACT	(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE - 1)
130 #define	PRI_MIN_BATCH		(PRI_MIN_TIMESHARE + PRI_INTERACT_RANGE)
131 #define	PRI_MAX_BATCH		PRI_MAX_TIMESHARE
132 
133 /*
134  * Cpu percentage computation macros and defines.
135  *
136  * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
137  * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
138  * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
139  * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
140  * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
141  * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
142  */
143 #define	SCHED_TICK_SECS		10
144 #define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
145 #define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
146 #define	SCHED_TICK_SHIFT	10
147 #define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
148 #define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
149 
150 /*
151  * These macros determine priorities for non-interactive threads.  They are
152  * assigned a priority based on their recent cpu utilization as expressed
153  * by the ratio of ticks to the tick total.  NHALF priorities at the start
154  * and end of the MIN to MAX timeshare range are only reachable with negative
155  * or positive nice respectively.
156  *
157  * PRI_RANGE:	Priority range for utilization dependent priorities.
158  * PRI_NRESV:	Number of nice values.
159  * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
160  * PRI_NICE:	Determines the part of the priority inherited from nice.
161  */
162 #define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
163 #define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
164 #define	SCHED_PRI_MIN		(PRI_MIN_BATCH + SCHED_PRI_NHALF)
165 #define	SCHED_PRI_MAX		(PRI_MAX_BATCH - SCHED_PRI_NHALF)
166 #define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN + 1)
167 #define	SCHED_PRI_TICKS(ts)						\
168     (SCHED_TICK_HZ((ts)) /						\
169     (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
170 #define	SCHED_PRI_NICE(nice)	(nice)
171 
172 /*
173  * These determine the interactivity of a process.  Interactivity differs from
174  * cpu utilization in that it expresses the voluntary time slept vs time ran
175  * while cpu utilization includes all time not running.  This more accurately
176  * models the intent of the thread.
177  *
178  * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
179  *		before throttling back.
180  * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
181  * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
182  * INTERACT_THRESH:	Threshold for placement on the current runq.
183  */
184 #define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
185 #define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
186 #define	SCHED_INTERACT_MAX	(100)
187 #define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
188 #define	SCHED_INTERACT_THRESH	(30)
189 
190 /*
191  * These parameters determine the slice behavior for batch work.
192  */
193 #define	SCHED_SLICE_DEFAULT_DIVISOR	10	/* ~94 ms, 12 stathz ticks. */
194 #define	SCHED_SLICE_MIN_DIVISOR		6	/* DEFAULT/MIN = ~16 ms. */
195 
196 /* Flags kept in td_flags. */
197 #define	TDF_SLICEEND	TDF_SCHED2	/* Thread time slice is over. */
198 
199 /*
200  * tickincr:		Converts a stathz tick into a hz domain scaled by
201  *			the shift factor.  Without the shift the error rate
202  *			due to rounding would be unacceptably high.
203  * realstathz:		stathz is sometimes 0 and run off of hz.
204  * sched_slice:		Runtime of each thread before rescheduling.
205  * preempt_thresh:	Priority threshold for preemption and remote IPIs.
206  */
207 static int sched_interact = SCHED_INTERACT_THRESH;
208 static int tickincr = 8 << SCHED_TICK_SHIFT;
209 static int realstathz = 127;	/* reset during boot. */
210 static int sched_slice = 10;	/* reset during boot. */
211 static int sched_slice_min = 1;	/* reset during boot. */
212 #ifdef PREEMPTION
213 #ifdef FULL_PREEMPTION
214 static int preempt_thresh = PRI_MAX_IDLE;
215 #else
216 static int preempt_thresh = PRI_MIN_KERN;
217 #endif
218 #else
219 static int preempt_thresh = 0;
220 #endif
221 static int static_boost = PRI_MIN_BATCH;
222 static int sched_idlespins = 10000;
223 static int sched_idlespinthresh = -1;
224 
225 /*
226  * tdq - per processor runqs and statistics.  All fields are protected by the
227  * tdq_lock.  The load and lowpri may be accessed without to avoid excess
228  * locking in sched_pickcpu();
229  */
230 struct tdq {
231 	/*
232 	 * Ordered to improve efficiency of cpu_search() and switch().
233 	 * tdq_lock is padded to avoid false sharing with tdq_load and
234 	 * tdq_cpu_idle.
235 	 */
236 	struct mtx_padalign tdq_lock;		/* run queue lock. */
237 	struct cpu_group *tdq_cg;		/* Pointer to cpu topology. */
238 	volatile int	tdq_load;		/* Aggregate load. */
239 	volatile int	tdq_cpu_idle;		/* cpu_idle() is active. */
240 	int		tdq_sysload;		/* For loadavg, !ITHD load. */
241 	int		tdq_transferable;	/* Transferable thread count. */
242 	short		tdq_switchcnt;		/* Switches this tick. */
243 	short		tdq_oldswitchcnt;	/* Switches last tick. */
244 	u_char		tdq_lowpri;		/* Lowest priority thread. */
245 	u_char		tdq_ipipending;		/* IPI pending. */
246 	u_char		tdq_idx;		/* Current insert index. */
247 	u_char		tdq_ridx;		/* Current removal index. */
248 	struct runq	tdq_realtime;		/* real-time run queue. */
249 	struct runq	tdq_timeshare;		/* timeshare run queue. */
250 	struct runq	tdq_idle;		/* Queue of IDLE threads. */
251 	char		tdq_name[TDQ_NAME_LEN];
252 #ifdef KTR
253 	char		tdq_loadname[TDQ_LOADNAME_LEN];
254 #endif
255 } __aligned(64);
256 
257 /* Idle thread states and config. */
258 #define	TDQ_RUNNING	1
259 #define	TDQ_IDLE	2
260 
261 #ifdef SMP
262 struct cpu_group *cpu_top;		/* CPU topology */
263 
264 #define	SCHED_AFFINITY_DEFAULT	(max(1, hz / 1000))
265 #define	SCHED_AFFINITY(ts, t)	((ts)->ts_rltick > ticks - ((t) * affinity))
266 
267 /*
268  * Run-time tunables.
269  */
270 static int rebalance = 1;
271 static int balance_interval = 128;	/* Default set in sched_initticks(). */
272 static int affinity;
273 static int steal_idle = 1;
274 static int steal_thresh = 2;
275 
276 /*
277  * One thread queue per processor.
278  */
279 static struct tdq	tdq_cpu[MAXCPU];
280 static struct tdq	*balance_tdq;
281 static int balance_ticks;
282 static DPCPU_DEFINE(uint32_t, randomval);
283 
284 #define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
285 #define	TDQ_CPU(x)	(&tdq_cpu[(x)])
286 #define	TDQ_ID(x)	((int)((x) - tdq_cpu))
287 #else	/* !SMP */
288 static struct tdq	tdq_cpu;
289 
290 #define	TDQ_ID(x)	(0)
291 #define	TDQ_SELF()	(&tdq_cpu)
292 #define	TDQ_CPU(x)	(&tdq_cpu)
293 #endif
294 
295 #define	TDQ_LOCK_ASSERT(t, type)	mtx_assert(TDQ_LOCKPTR((t)), (type))
296 #define	TDQ_LOCK(t)		mtx_lock_spin(TDQ_LOCKPTR((t)))
297 #define	TDQ_LOCK_FLAGS(t, f)	mtx_lock_spin_flags(TDQ_LOCKPTR((t)), (f))
298 #define	TDQ_UNLOCK(t)		mtx_unlock_spin(TDQ_LOCKPTR((t)))
299 #define	TDQ_LOCKPTR(t)		((struct mtx *)(&(t)->tdq_lock))
300 
301 static void sched_priority(struct thread *);
302 static void sched_thread_priority(struct thread *, u_char);
303 static int sched_interact_score(struct thread *);
304 static void sched_interact_update(struct thread *);
305 static void sched_interact_fork(struct thread *);
306 static void sched_pctcpu_update(struct td_sched *, int);
307 
308 /* Operations on per processor queues */
309 static struct thread *tdq_choose(struct tdq *);
310 static void tdq_setup(struct tdq *);
311 static void tdq_load_add(struct tdq *, struct thread *);
312 static void tdq_load_rem(struct tdq *, struct thread *);
313 static __inline void tdq_runq_add(struct tdq *, struct thread *, int);
314 static __inline void tdq_runq_rem(struct tdq *, struct thread *);
315 static inline int sched_shouldpreempt(int, int, int);
316 void tdq_print(int cpu);
317 static void runq_print(struct runq *rq);
318 static void tdq_add(struct tdq *, struct thread *, int);
319 #ifdef SMP
320 static int tdq_move(struct tdq *, struct tdq *);
321 static int tdq_idled(struct tdq *);
322 static void tdq_notify(struct tdq *, struct thread *);
323 static struct thread *tdq_steal(struct tdq *, int);
324 static struct thread *runq_steal(struct runq *, int);
325 static int sched_pickcpu(struct thread *, int);
326 static void sched_balance(void);
327 static int sched_balance_pair(struct tdq *, struct tdq *);
328 static inline struct tdq *sched_setcpu(struct thread *, int, int);
329 static inline void thread_unblock_switch(struct thread *, struct mtx *);
330 static struct mtx *sched_switch_migrate(struct tdq *, struct thread *, int);
331 static int sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS);
332 static int sysctl_kern_sched_topology_spec_internal(struct sbuf *sb,
333     struct cpu_group *cg, int indent);
334 #endif
335 
336 static void sched_setup(void *dummy);
337 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
338 
339 static void sched_initticks(void *dummy);
340 SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
341     NULL);
342 
343 SDT_PROVIDER_DEFINE(sched);
344 
345 SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
346     "struct proc *", "uint8_t");
347 SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
348     "struct proc *", "void *");
349 SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
350     "struct proc *", "void *", "int");
351 SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
352     "struct proc *", "uint8_t", "struct thread *");
353 SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
354 SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
355     "struct proc *");
356 SDT_PROBE_DEFINE(sched, , , on__cpu);
357 SDT_PROBE_DEFINE(sched, , , remain__cpu);
358 SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
359     "struct proc *");
360 
361 /*
362  * Print the threads waiting on a run-queue.
363  */
364 static void
365 runq_print(struct runq *rq)
366 {
367 	struct rqhead *rqh;
368 	struct thread *td;
369 	int pri;
370 	int j;
371 	int i;
372 
373 	for (i = 0; i < RQB_LEN; i++) {
374 		printf("\t\trunq bits %d 0x%zx\n",
375 		    i, rq->rq_status.rqb_bits[i]);
376 		for (j = 0; j < RQB_BPW; j++)
377 			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
378 				pri = j + (i << RQB_L2BPW);
379 				rqh = &rq->rq_queues[pri];
380 				TAILQ_FOREACH(td, rqh, td_runq) {
381 					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
382 					    td, td->td_name, td->td_priority,
383 					    td->td_rqindex, pri);
384 				}
385 			}
386 	}
387 }
388 
389 /*
390  * Print the status of a per-cpu thread queue.  Should be a ddb show cmd.
391  */
392 void
393 tdq_print(int cpu)
394 {
395 	struct tdq *tdq;
396 
397 	tdq = TDQ_CPU(cpu);
398 
399 	printf("tdq %d:\n", TDQ_ID(tdq));
400 	printf("\tlock            %p\n", TDQ_LOCKPTR(tdq));
401 	printf("\tLock name:      %s\n", tdq->tdq_name);
402 	printf("\tload:           %d\n", tdq->tdq_load);
403 	printf("\tswitch cnt:     %d\n", tdq->tdq_switchcnt);
404 	printf("\told switch cnt: %d\n", tdq->tdq_oldswitchcnt);
405 	printf("\ttimeshare idx:  %d\n", tdq->tdq_idx);
406 	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
407 	printf("\tload transferable: %d\n", tdq->tdq_transferable);
408 	printf("\tlowest priority:   %d\n", tdq->tdq_lowpri);
409 	printf("\trealtime runq:\n");
410 	runq_print(&tdq->tdq_realtime);
411 	printf("\ttimeshare runq:\n");
412 	runq_print(&tdq->tdq_timeshare);
413 	printf("\tidle runq:\n");
414 	runq_print(&tdq->tdq_idle);
415 }
416 
417 static inline int
418 sched_shouldpreempt(int pri, int cpri, int remote)
419 {
420 	/*
421 	 * If the new priority is not better than the current priority there is
422 	 * nothing to do.
423 	 */
424 	if (pri >= cpri)
425 		return (0);
426 	/*
427 	 * Always preempt idle.
428 	 */
429 	if (cpri >= PRI_MIN_IDLE)
430 		return (1);
431 	/*
432 	 * If preemption is disabled don't preempt others.
433 	 */
434 	if (preempt_thresh == 0)
435 		return (0);
436 	/*
437 	 * Preempt if we exceed the threshold.
438 	 */
439 	if (pri <= preempt_thresh)
440 		return (1);
441 	/*
442 	 * If we're interactive or better and there is non-interactive
443 	 * or worse running preempt only remote processors.
444 	 */
445 	if (remote && pri <= PRI_MAX_INTERACT && cpri > PRI_MAX_INTERACT)
446 		return (1);
447 	return (0);
448 }
449 
450 /*
451  * Add a thread to the actual run-queue.  Keeps transferable counts up to
452  * date with what is actually on the run-queue.  Selects the correct
453  * queue position for timeshare threads.
454  */
455 static __inline void
456 tdq_runq_add(struct tdq *tdq, struct thread *td, int flags)
457 {
458 	struct td_sched *ts;
459 	u_char pri;
460 
461 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
462 	THREAD_LOCK_ASSERT(td, MA_OWNED);
463 
464 	pri = td->td_priority;
465 	ts = td_get_sched(td);
466 	TD_SET_RUNQ(td);
467 	if (THREAD_CAN_MIGRATE(td)) {
468 		tdq->tdq_transferable++;
469 		ts->ts_flags |= TSF_XFERABLE;
470 	}
471 	if (pri < PRI_MIN_BATCH) {
472 		ts->ts_runq = &tdq->tdq_realtime;
473 	} else if (pri <= PRI_MAX_BATCH) {
474 		ts->ts_runq = &tdq->tdq_timeshare;
475 		KASSERT(pri <= PRI_MAX_BATCH && pri >= PRI_MIN_BATCH,
476 			("Invalid priority %d on timeshare runq", pri));
477 		/*
478 		 * This queue contains only priorities between MIN and MAX
479 		 * realtime.  Use the whole queue to represent these values.
480 		 */
481 		if ((flags & (SRQ_BORROWING|SRQ_PREEMPTED)) == 0) {
482 			pri = RQ_NQS * (pri - PRI_MIN_BATCH) / PRI_BATCH_RANGE;
483 			pri = (pri + tdq->tdq_idx) % RQ_NQS;
484 			/*
485 			 * This effectively shortens the queue by one so we
486 			 * can have a one slot difference between idx and
487 			 * ridx while we wait for threads to drain.
488 			 */
489 			if (tdq->tdq_ridx != tdq->tdq_idx &&
490 			    pri == tdq->tdq_ridx)
491 				pri = (unsigned char)(pri - 1) % RQ_NQS;
492 		} else
493 			pri = tdq->tdq_ridx;
494 		runq_add_pri(ts->ts_runq, td, pri, flags);
495 		return;
496 	} else
497 		ts->ts_runq = &tdq->tdq_idle;
498 	runq_add(ts->ts_runq, td, flags);
499 }
500 
501 /*
502  * Remove a thread from a run-queue.  This typically happens when a thread
503  * is selected to run.  Running threads are not on the queue and the
504  * transferable count does not reflect them.
505  */
506 static __inline void
507 tdq_runq_rem(struct tdq *tdq, struct thread *td)
508 {
509 	struct td_sched *ts;
510 
511 	ts = td_get_sched(td);
512 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
513 	KASSERT(ts->ts_runq != NULL,
514 	    ("tdq_runq_remove: thread %p null ts_runq", td));
515 	if (ts->ts_flags & TSF_XFERABLE) {
516 		tdq->tdq_transferable--;
517 		ts->ts_flags &= ~TSF_XFERABLE;
518 	}
519 	if (ts->ts_runq == &tdq->tdq_timeshare) {
520 		if (tdq->tdq_idx != tdq->tdq_ridx)
521 			runq_remove_idx(ts->ts_runq, td, &tdq->tdq_ridx);
522 		else
523 			runq_remove_idx(ts->ts_runq, td, NULL);
524 	} else
525 		runq_remove(ts->ts_runq, td);
526 }
527 
528 /*
529  * Load is maintained for all threads RUNNING and ON_RUNQ.  Add the load
530  * for this thread to the referenced thread queue.
531  */
532 static void
533 tdq_load_add(struct tdq *tdq, struct thread *td)
534 {
535 
536 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
537 	THREAD_LOCK_ASSERT(td, MA_OWNED);
538 
539 	tdq->tdq_load++;
540 	if ((td->td_flags & TDF_NOLOAD) == 0)
541 		tdq->tdq_sysload++;
542 	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
543 	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
544 }
545 
546 /*
547  * Remove the load from a thread that is transitioning to a sleep state or
548  * exiting.
549  */
550 static void
551 tdq_load_rem(struct tdq *tdq, struct thread *td)
552 {
553 
554 	THREAD_LOCK_ASSERT(td, MA_OWNED);
555 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
556 	KASSERT(tdq->tdq_load != 0,
557 	    ("tdq_load_rem: Removing with 0 load on queue %d", TDQ_ID(tdq)));
558 
559 	tdq->tdq_load--;
560 	if ((td->td_flags & TDF_NOLOAD) == 0)
561 		tdq->tdq_sysload--;
562 	KTR_COUNTER0(KTR_SCHED, "load", tdq->tdq_loadname, tdq->tdq_load);
563 	SDT_PROBE2(sched, , , load__change, (int)TDQ_ID(tdq), tdq->tdq_load);
564 }
565 
566 /*
567  * Bound timeshare latency by decreasing slice size as load increases.  We
568  * consider the maximum latency as the sum of the threads waiting to run
569  * aside from curthread and target no more than sched_slice latency but
570  * no less than sched_slice_min runtime.
571  */
572 static inline int
573 tdq_slice(struct tdq *tdq)
574 {
575 	int load;
576 
577 	/*
578 	 * It is safe to use sys_load here because this is called from
579 	 * contexts where timeshare threads are running and so there
580 	 * cannot be higher priority load in the system.
581 	 */
582 	load = tdq->tdq_sysload - 1;
583 	if (load >= SCHED_SLICE_MIN_DIVISOR)
584 		return (sched_slice_min);
585 	if (load <= 1)
586 		return (sched_slice);
587 	return (sched_slice / load);
588 }
589 
590 /*
591  * Set lowpri to its exact value by searching the run-queue and
592  * evaluating curthread.  curthread may be passed as an optimization.
593  */
594 static void
595 tdq_setlowpri(struct tdq *tdq, struct thread *ctd)
596 {
597 	struct thread *td;
598 
599 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
600 	if (ctd == NULL)
601 		ctd = pcpu_find(TDQ_ID(tdq))->pc_curthread;
602 	td = tdq_choose(tdq);
603 	if (td == NULL || td->td_priority > ctd->td_priority)
604 		tdq->tdq_lowpri = ctd->td_priority;
605 	else
606 		tdq->tdq_lowpri = td->td_priority;
607 }
608 
609 #ifdef SMP
610 /*
611  * We need some randomness. Implement a classic Linear Congruential
612  * Generator X_{n+1}=(aX_n+c) mod m. These values are optimized for
613  * m = 2^32, a = 69069 and c = 5. We only return the upper 16 bits
614  * of the random state (in the low bits of our answer) to keep
615  * the maximum randomness.
616  */
617 static uint32_t
618 sched_random(void)
619 {
620 	uint32_t *rndptr;
621 
622 	rndptr = DPCPU_PTR(randomval);
623 	*rndptr = *rndptr * 69069 + 5;
624 
625 	return (*rndptr >> 16);
626 }
627 
628 struct cpu_search {
629 	cpuset_t cs_mask;
630 	u_int	cs_prefer;
631 	int	cs_pri;		/* Min priority for low. */
632 	int	cs_limit;	/* Max load for low, min load for high. */
633 	int	cs_cpu;
634 	int	cs_load;
635 };
636 
637 #define	CPU_SEARCH_LOWEST	0x1
638 #define	CPU_SEARCH_HIGHEST	0x2
639 #define	CPU_SEARCH_BOTH		(CPU_SEARCH_LOWEST|CPU_SEARCH_HIGHEST)
640 
641 #define	CPUSET_FOREACH(cpu, mask)				\
642 	for ((cpu) = 0; (cpu) <= mp_maxid; (cpu)++)		\
643 		if (CPU_ISSET(cpu, &mask))
644 
645 static __always_inline int cpu_search(const struct cpu_group *cg,
646     struct cpu_search *low, struct cpu_search *high, const int match);
647 int __noinline cpu_search_lowest(const struct cpu_group *cg,
648     struct cpu_search *low);
649 int __noinline cpu_search_highest(const struct cpu_group *cg,
650     struct cpu_search *high);
651 int __noinline cpu_search_both(const struct cpu_group *cg,
652     struct cpu_search *low, struct cpu_search *high);
653 
654 /*
655  * Search the tree of cpu_groups for the lowest or highest loaded cpu
656  * according to the match argument.  This routine actually compares the
657  * load on all paths through the tree and finds the least loaded cpu on
658  * the least loaded path, which may differ from the least loaded cpu in
659  * the system.  This balances work among caches and buses.
660  *
661  * This inline is instantiated in three forms below using constants for the
662  * match argument.  It is reduced to the minimum set for each case.  It is
663  * also recursive to the depth of the tree.
664  */
665 static __always_inline int
666 cpu_search(const struct cpu_group *cg, struct cpu_search *low,
667     struct cpu_search *high, const int match)
668 {
669 	struct cpu_search lgroup;
670 	struct cpu_search hgroup;
671 	cpuset_t cpumask;
672 	struct cpu_group *child;
673 	struct tdq *tdq;
674 	int cpu, i, hload, lload, load, total, rnd;
675 
676 	total = 0;
677 	cpumask = cg->cg_mask;
678 	if (match & CPU_SEARCH_LOWEST) {
679 		lload = INT_MAX;
680 		lgroup = *low;
681 	}
682 	if (match & CPU_SEARCH_HIGHEST) {
683 		hload = INT_MIN;
684 		hgroup = *high;
685 	}
686 
687 	/* Iterate through the child CPU groups and then remaining CPUs. */
688 	for (i = cg->cg_children, cpu = mp_maxid; ; ) {
689 		if (i == 0) {
690 #ifdef HAVE_INLINE_FFSL
691 			cpu = CPU_FFS(&cpumask) - 1;
692 #else
693 			while (cpu >= 0 && !CPU_ISSET(cpu, &cpumask))
694 				cpu--;
695 #endif
696 			if (cpu < 0)
697 				break;
698 			child = NULL;
699 		} else
700 			child = &cg->cg_child[i - 1];
701 
702 		if (match & CPU_SEARCH_LOWEST)
703 			lgroup.cs_cpu = -1;
704 		if (match & CPU_SEARCH_HIGHEST)
705 			hgroup.cs_cpu = -1;
706 		if (child) {			/* Handle child CPU group. */
707 			CPU_NAND(&cpumask, &child->cg_mask);
708 			switch (match) {
709 			case CPU_SEARCH_LOWEST:
710 				load = cpu_search_lowest(child, &lgroup);
711 				break;
712 			case CPU_SEARCH_HIGHEST:
713 				load = cpu_search_highest(child, &hgroup);
714 				break;
715 			case CPU_SEARCH_BOTH:
716 				load = cpu_search_both(child, &lgroup, &hgroup);
717 				break;
718 			}
719 		} else {			/* Handle child CPU. */
720 			CPU_CLR(cpu, &cpumask);
721 			tdq = TDQ_CPU(cpu);
722 			load = tdq->tdq_load * 256;
723 			rnd = sched_random() % 32;
724 			if (match & CPU_SEARCH_LOWEST) {
725 				if (cpu == low->cs_prefer)
726 					load -= 64;
727 				/* If that CPU is allowed and get data. */
728 				if (tdq->tdq_lowpri > lgroup.cs_pri &&
729 				    tdq->tdq_load <= lgroup.cs_limit &&
730 				    CPU_ISSET(cpu, &lgroup.cs_mask)) {
731 					lgroup.cs_cpu = cpu;
732 					lgroup.cs_load = load - rnd;
733 				}
734 			}
735 			if (match & CPU_SEARCH_HIGHEST)
736 				if (tdq->tdq_load >= hgroup.cs_limit &&
737 				    tdq->tdq_transferable &&
738 				    CPU_ISSET(cpu, &hgroup.cs_mask)) {
739 					hgroup.cs_cpu = cpu;
740 					hgroup.cs_load = load - rnd;
741 				}
742 		}
743 		total += load;
744 
745 		/* We have info about child item. Compare it. */
746 		if (match & CPU_SEARCH_LOWEST) {
747 			if (lgroup.cs_cpu >= 0 &&
748 			    (load < lload ||
749 			     (load == lload && lgroup.cs_load < low->cs_load))) {
750 				lload = load;
751 				low->cs_cpu = lgroup.cs_cpu;
752 				low->cs_load = lgroup.cs_load;
753 			}
754 		}
755 		if (match & CPU_SEARCH_HIGHEST)
756 			if (hgroup.cs_cpu >= 0 &&
757 			    (load > hload ||
758 			     (load == hload && hgroup.cs_load > high->cs_load))) {
759 				hload = load;
760 				high->cs_cpu = hgroup.cs_cpu;
761 				high->cs_load = hgroup.cs_load;
762 			}
763 		if (child) {
764 			i--;
765 			if (i == 0 && CPU_EMPTY(&cpumask))
766 				break;
767 		}
768 #ifndef HAVE_INLINE_FFSL
769 		else
770 			cpu--;
771 #endif
772 	}
773 	return (total);
774 }
775 
776 /*
777  * cpu_search instantiations must pass constants to maintain the inline
778  * optimization.
779  */
780 int
781 cpu_search_lowest(const struct cpu_group *cg, struct cpu_search *low)
782 {
783 	return cpu_search(cg, low, NULL, CPU_SEARCH_LOWEST);
784 }
785 
786 int
787 cpu_search_highest(const struct cpu_group *cg, struct cpu_search *high)
788 {
789 	return cpu_search(cg, NULL, high, CPU_SEARCH_HIGHEST);
790 }
791 
792 int
793 cpu_search_both(const struct cpu_group *cg, struct cpu_search *low,
794     struct cpu_search *high)
795 {
796 	return cpu_search(cg, low, high, CPU_SEARCH_BOTH);
797 }
798 
799 /*
800  * Find the cpu with the least load via the least loaded path that has a
801  * lowpri greater than pri  pri.  A pri of -1 indicates any priority is
802  * acceptable.
803  */
804 static inline int
805 sched_lowest(const struct cpu_group *cg, cpuset_t mask, int pri, int maxload,
806     int prefer)
807 {
808 	struct cpu_search low;
809 
810 	low.cs_cpu = -1;
811 	low.cs_prefer = prefer;
812 	low.cs_mask = mask;
813 	low.cs_pri = pri;
814 	low.cs_limit = maxload;
815 	cpu_search_lowest(cg, &low);
816 	return low.cs_cpu;
817 }
818 
819 /*
820  * Find the cpu with the highest load via the highest loaded path.
821  */
822 static inline int
823 sched_highest(const struct cpu_group *cg, cpuset_t mask, int minload)
824 {
825 	struct cpu_search high;
826 
827 	high.cs_cpu = -1;
828 	high.cs_mask = mask;
829 	high.cs_limit = minload;
830 	cpu_search_highest(cg, &high);
831 	return high.cs_cpu;
832 }
833 
834 static void
835 sched_balance_group(struct cpu_group *cg)
836 {
837 	cpuset_t hmask, lmask;
838 	int high, low, anylow;
839 
840 	CPU_FILL(&hmask);
841 	for (;;) {
842 		high = sched_highest(cg, hmask, 1);
843 		/* Stop if there is no more CPU with transferrable threads. */
844 		if (high == -1)
845 			break;
846 		CPU_CLR(high, &hmask);
847 		CPU_COPY(&hmask, &lmask);
848 		/* Stop if there is no more CPU left for low. */
849 		if (CPU_EMPTY(&lmask))
850 			break;
851 		anylow = 1;
852 nextlow:
853 		low = sched_lowest(cg, lmask, -1,
854 		    TDQ_CPU(high)->tdq_load - 1, high);
855 		/* Stop if we looked well and found no less loaded CPU. */
856 		if (anylow && low == -1)
857 			break;
858 		/* Go to next high if we found no less loaded CPU. */
859 		if (low == -1)
860 			continue;
861 		/* Transfer thread from high to low. */
862 		if (sched_balance_pair(TDQ_CPU(high), TDQ_CPU(low))) {
863 			/* CPU that got thread can no longer be a donor. */
864 			CPU_CLR(low, &hmask);
865 		} else {
866 			/*
867 			 * If failed, then there is no threads on high
868 			 * that can run on this low. Drop low from low
869 			 * mask and look for different one.
870 			 */
871 			CPU_CLR(low, &lmask);
872 			anylow = 0;
873 			goto nextlow;
874 		}
875 	}
876 }
877 
878 static void
879 sched_balance(void)
880 {
881 	struct tdq *tdq;
882 
883 	if (smp_started == 0 || rebalance == 0)
884 		return;
885 
886 	balance_ticks = max(balance_interval / 2, 1) +
887 	    (sched_random() % balance_interval);
888 	tdq = TDQ_SELF();
889 	TDQ_UNLOCK(tdq);
890 	sched_balance_group(cpu_top);
891 	TDQ_LOCK(tdq);
892 }
893 
894 /*
895  * Lock two thread queues using their address to maintain lock order.
896  */
897 static void
898 tdq_lock_pair(struct tdq *one, struct tdq *two)
899 {
900 	if (one < two) {
901 		TDQ_LOCK(one);
902 		TDQ_LOCK_FLAGS(two, MTX_DUPOK);
903 	} else {
904 		TDQ_LOCK(two);
905 		TDQ_LOCK_FLAGS(one, MTX_DUPOK);
906 	}
907 }
908 
909 /*
910  * Unlock two thread queues.  Order is not important here.
911  */
912 static void
913 tdq_unlock_pair(struct tdq *one, struct tdq *two)
914 {
915 	TDQ_UNLOCK(one);
916 	TDQ_UNLOCK(two);
917 }
918 
919 /*
920  * Transfer load between two imbalanced thread queues.
921  */
922 static int
923 sched_balance_pair(struct tdq *high, struct tdq *low)
924 {
925 	int moved;
926 	int cpu;
927 
928 	tdq_lock_pair(high, low);
929 	moved = 0;
930 	/*
931 	 * Determine what the imbalance is and then adjust that to how many
932 	 * threads we actually have to give up (transferable).
933 	 */
934 	if (high->tdq_transferable != 0 && high->tdq_load > low->tdq_load &&
935 	    (moved = tdq_move(high, low)) > 0) {
936 		/*
937 		 * In case the target isn't the current cpu IPI it to force a
938 		 * reschedule with the new workload.
939 		 */
940 		cpu = TDQ_ID(low);
941 		if (cpu != PCPU_GET(cpuid))
942 			ipi_cpu(cpu, IPI_PREEMPT);
943 	}
944 	tdq_unlock_pair(high, low);
945 	return (moved);
946 }
947 
948 /*
949  * Move a thread from one thread queue to another.
950  */
951 static int
952 tdq_move(struct tdq *from, struct tdq *to)
953 {
954 	struct td_sched *ts;
955 	struct thread *td;
956 	struct tdq *tdq;
957 	int cpu;
958 
959 	TDQ_LOCK_ASSERT(from, MA_OWNED);
960 	TDQ_LOCK_ASSERT(to, MA_OWNED);
961 
962 	tdq = from;
963 	cpu = TDQ_ID(to);
964 	td = tdq_steal(tdq, cpu);
965 	if (td == NULL)
966 		return (0);
967 	ts = td_get_sched(td);
968 	/*
969 	 * Although the run queue is locked the thread may be blocked.  Lock
970 	 * it to clear this and acquire the run-queue lock.
971 	 */
972 	thread_lock(td);
973 	/* Drop recursive lock on from acquired via thread_lock(). */
974 	TDQ_UNLOCK(from);
975 	sched_rem(td);
976 	ts->ts_cpu = cpu;
977 	td->td_lock = TDQ_LOCKPTR(to);
978 	tdq_add(to, td, SRQ_YIELDING);
979 	return (1);
980 }
981 
982 /*
983  * This tdq has idled.  Try to steal a thread from another cpu and switch
984  * to it.
985  */
986 static int
987 tdq_idled(struct tdq *tdq)
988 {
989 	struct cpu_group *cg;
990 	struct tdq *steal;
991 	cpuset_t mask;
992 	int thresh;
993 	int cpu;
994 
995 	if (smp_started == 0 || steal_idle == 0)
996 		return (1);
997 	CPU_FILL(&mask);
998 	CPU_CLR(PCPU_GET(cpuid), &mask);
999 	/* We don't want to be preempted while we're iterating. */
1000 	spinlock_enter();
1001 	for (cg = tdq->tdq_cg; cg != NULL; ) {
1002 		if ((cg->cg_flags & CG_FLAG_THREAD) == 0)
1003 			thresh = steal_thresh;
1004 		else
1005 			thresh = 1;
1006 		cpu = sched_highest(cg, mask, thresh);
1007 		if (cpu == -1) {
1008 			cg = cg->cg_parent;
1009 			continue;
1010 		}
1011 		steal = TDQ_CPU(cpu);
1012 		CPU_CLR(cpu, &mask);
1013 		tdq_lock_pair(tdq, steal);
1014 		if (steal->tdq_load < thresh || steal->tdq_transferable == 0) {
1015 			tdq_unlock_pair(tdq, steal);
1016 			continue;
1017 		}
1018 		/*
1019 		 * If a thread was added while interrupts were disabled don't
1020 		 * steal one here.  If we fail to acquire one due to affinity
1021 		 * restrictions loop again with this cpu removed from the
1022 		 * set.
1023 		 */
1024 		if (tdq->tdq_load == 0 && tdq_move(steal, tdq) == 0) {
1025 			tdq_unlock_pair(tdq, steal);
1026 			continue;
1027 		}
1028 		spinlock_exit();
1029 		TDQ_UNLOCK(steal);
1030 		mi_switch(SW_VOL | SWT_IDLE, NULL);
1031 		thread_unlock(curthread);
1032 
1033 		return (0);
1034 	}
1035 	spinlock_exit();
1036 	return (1);
1037 }
1038 
1039 /*
1040  * Notify a remote cpu of new work.  Sends an IPI if criteria are met.
1041  */
1042 static void
1043 tdq_notify(struct tdq *tdq, struct thread *td)
1044 {
1045 	struct thread *ctd;
1046 	int pri;
1047 	int cpu;
1048 
1049 	if (tdq->tdq_ipipending)
1050 		return;
1051 	cpu = td_get_sched(td)->ts_cpu;
1052 	pri = td->td_priority;
1053 	ctd = pcpu_find(cpu)->pc_curthread;
1054 	if (!sched_shouldpreempt(pri, ctd->td_priority, 1))
1055 		return;
1056 
1057 	/*
1058 	 * Make sure that our caller's earlier update to tdq_load is
1059 	 * globally visible before we read tdq_cpu_idle.  Idle thread
1060 	 * accesses both of them without locks, and the order is important.
1061 	 */
1062 	atomic_thread_fence_seq_cst();
1063 
1064 	if (TD_IS_IDLETHREAD(ctd)) {
1065 		/*
1066 		 * If the MD code has an idle wakeup routine try that before
1067 		 * falling back to IPI.
1068 		 */
1069 		if (!tdq->tdq_cpu_idle || cpu_idle_wakeup(cpu))
1070 			return;
1071 	}
1072 	tdq->tdq_ipipending = 1;
1073 	ipi_cpu(cpu, IPI_PREEMPT);
1074 }
1075 
1076 /*
1077  * Steals load from a timeshare queue.  Honors the rotating queue head
1078  * index.
1079  */
1080 static struct thread *
1081 runq_steal_from(struct runq *rq, int cpu, u_char start)
1082 {
1083 	struct rqbits *rqb;
1084 	struct rqhead *rqh;
1085 	struct thread *td, *first;
1086 	int bit;
1087 	int i;
1088 
1089 	rqb = &rq->rq_status;
1090 	bit = start & (RQB_BPW -1);
1091 	first = NULL;
1092 again:
1093 	for (i = RQB_WORD(start); i < RQB_LEN; bit = 0, i++) {
1094 		if (rqb->rqb_bits[i] == 0)
1095 			continue;
1096 		if (bit == 0)
1097 			bit = RQB_FFS(rqb->rqb_bits[i]);
1098 		for (; bit < RQB_BPW; bit++) {
1099 			if ((rqb->rqb_bits[i] & (1ul << bit)) == 0)
1100 				continue;
1101 			rqh = &rq->rq_queues[bit + (i << RQB_L2BPW)];
1102 			TAILQ_FOREACH(td, rqh, td_runq) {
1103 				if (first && THREAD_CAN_MIGRATE(td) &&
1104 				    THREAD_CAN_SCHED(td, cpu))
1105 					return (td);
1106 				first = td;
1107 			}
1108 		}
1109 	}
1110 	if (start != 0) {
1111 		start = 0;
1112 		goto again;
1113 	}
1114 
1115 	if (first && THREAD_CAN_MIGRATE(first) &&
1116 	    THREAD_CAN_SCHED(first, cpu))
1117 		return (first);
1118 	return (NULL);
1119 }
1120 
1121 /*
1122  * Steals load from a standard linear queue.
1123  */
1124 static struct thread *
1125 runq_steal(struct runq *rq, int cpu)
1126 {
1127 	struct rqhead *rqh;
1128 	struct rqbits *rqb;
1129 	struct thread *td;
1130 	int word;
1131 	int bit;
1132 
1133 	rqb = &rq->rq_status;
1134 	for (word = 0; word < RQB_LEN; word++) {
1135 		if (rqb->rqb_bits[word] == 0)
1136 			continue;
1137 		for (bit = 0; bit < RQB_BPW; bit++) {
1138 			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
1139 				continue;
1140 			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
1141 			TAILQ_FOREACH(td, rqh, td_runq)
1142 				if (THREAD_CAN_MIGRATE(td) &&
1143 				    THREAD_CAN_SCHED(td, cpu))
1144 					return (td);
1145 		}
1146 	}
1147 	return (NULL);
1148 }
1149 
1150 /*
1151  * Attempt to steal a thread in priority order from a thread queue.
1152  */
1153 static struct thread *
1154 tdq_steal(struct tdq *tdq, int cpu)
1155 {
1156 	struct thread *td;
1157 
1158 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1159 	if ((td = runq_steal(&tdq->tdq_realtime, cpu)) != NULL)
1160 		return (td);
1161 	if ((td = runq_steal_from(&tdq->tdq_timeshare,
1162 	    cpu, tdq->tdq_ridx)) != NULL)
1163 		return (td);
1164 	return (runq_steal(&tdq->tdq_idle, cpu));
1165 }
1166 
1167 /*
1168  * Sets the thread lock and ts_cpu to match the requested cpu.  Unlocks the
1169  * current lock and returns with the assigned queue locked.
1170  */
1171 static inline struct tdq *
1172 sched_setcpu(struct thread *td, int cpu, int flags)
1173 {
1174 
1175 	struct tdq *tdq;
1176 
1177 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1178 	tdq = TDQ_CPU(cpu);
1179 	td_get_sched(td)->ts_cpu = cpu;
1180 	/*
1181 	 * If the lock matches just return the queue.
1182 	 */
1183 	if (td->td_lock == TDQ_LOCKPTR(tdq))
1184 		return (tdq);
1185 #ifdef notyet
1186 	/*
1187 	 * If the thread isn't running its lockptr is a
1188 	 * turnstile or a sleepqueue.  We can just lock_set without
1189 	 * blocking.
1190 	 */
1191 	if (TD_CAN_RUN(td)) {
1192 		TDQ_LOCK(tdq);
1193 		thread_lock_set(td, TDQ_LOCKPTR(tdq));
1194 		return (tdq);
1195 	}
1196 #endif
1197 	/*
1198 	 * The hard case, migration, we need to block the thread first to
1199 	 * prevent order reversals with other cpus locks.
1200 	 */
1201 	spinlock_enter();
1202 	thread_lock_block(td);
1203 	TDQ_LOCK(tdq);
1204 	thread_lock_unblock(td, TDQ_LOCKPTR(tdq));
1205 	spinlock_exit();
1206 	return (tdq);
1207 }
1208 
1209 SCHED_STAT_DEFINE(pickcpu_intrbind, "Soft interrupt binding");
1210 SCHED_STAT_DEFINE(pickcpu_idle_affinity, "Picked idle cpu based on affinity");
1211 SCHED_STAT_DEFINE(pickcpu_affinity, "Picked cpu based on affinity");
1212 SCHED_STAT_DEFINE(pickcpu_lowest, "Selected lowest load");
1213 SCHED_STAT_DEFINE(pickcpu_local, "Migrated to current cpu");
1214 SCHED_STAT_DEFINE(pickcpu_migration, "Selection may have caused migration");
1215 
1216 static int
1217 sched_pickcpu(struct thread *td, int flags)
1218 {
1219 	struct cpu_group *cg, *ccg;
1220 	struct td_sched *ts;
1221 	struct tdq *tdq;
1222 	cpuset_t mask;
1223 	int cpu, pri, self;
1224 
1225 	self = PCPU_GET(cpuid);
1226 	ts = td_get_sched(td);
1227 	KASSERT(!CPU_ABSENT(ts->ts_cpu), ("sched_pickcpu: Start scheduler on "
1228 	    "absent CPU %d for thread %s.", ts->ts_cpu, td->td_name));
1229 	if (smp_started == 0)
1230 		return (self);
1231 	/*
1232 	 * Don't migrate a running thread from sched_switch().
1233 	 */
1234 	if ((flags & SRQ_OURSELF) || !THREAD_CAN_MIGRATE(td))
1235 		return (ts->ts_cpu);
1236 	/*
1237 	 * Prefer to run interrupt threads on the processors that generate
1238 	 * the interrupt.
1239 	 */
1240 	pri = td->td_priority;
1241 	if (td->td_priority <= PRI_MAX_ITHD && THREAD_CAN_SCHED(td, self) &&
1242 	    curthread->td_intr_nesting_level && ts->ts_cpu != self) {
1243 		SCHED_STAT_INC(pickcpu_intrbind);
1244 		ts->ts_cpu = self;
1245 		if (TDQ_CPU(self)->tdq_lowpri > pri) {
1246 			SCHED_STAT_INC(pickcpu_affinity);
1247 			return (ts->ts_cpu);
1248 		}
1249 	}
1250 	/*
1251 	 * If the thread can run on the last cpu and the affinity has not
1252 	 * expired or it is idle run it there.
1253 	 */
1254 	tdq = TDQ_CPU(ts->ts_cpu);
1255 	cg = tdq->tdq_cg;
1256 	if (THREAD_CAN_SCHED(td, ts->ts_cpu) &&
1257 	    tdq->tdq_lowpri >= PRI_MIN_IDLE &&
1258 	    SCHED_AFFINITY(ts, CG_SHARE_L2)) {
1259 		if (cg->cg_flags & CG_FLAG_THREAD) {
1260 			CPUSET_FOREACH(cpu, cg->cg_mask) {
1261 				if (TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE)
1262 					break;
1263 			}
1264 		} else
1265 			cpu = INT_MAX;
1266 		if (cpu > mp_maxid) {
1267 			SCHED_STAT_INC(pickcpu_idle_affinity);
1268 			return (ts->ts_cpu);
1269 		}
1270 	}
1271 	/*
1272 	 * Search for the last level cache CPU group in the tree.
1273 	 * Skip caches with expired affinity time and SMT groups.
1274 	 * Affinity to higher level caches will be handled less aggressively.
1275 	 */
1276 	for (ccg = NULL; cg != NULL; cg = cg->cg_parent) {
1277 		if (cg->cg_flags & CG_FLAG_THREAD)
1278 			continue;
1279 		if (!SCHED_AFFINITY(ts, cg->cg_level))
1280 			continue;
1281 		ccg = cg;
1282 	}
1283 	if (ccg != NULL)
1284 		cg = ccg;
1285 	cpu = -1;
1286 	/* Search the group for the less loaded idle CPU we can run now. */
1287 	mask = td->td_cpuset->cs_mask;
1288 	if (cg != NULL && cg != cpu_top &&
1289 	    CPU_CMP(&cg->cg_mask, &cpu_top->cg_mask) != 0)
1290 		cpu = sched_lowest(cg, mask, max(pri, PRI_MAX_TIMESHARE),
1291 		    INT_MAX, ts->ts_cpu);
1292 	/* Search globally for the less loaded CPU we can run now. */
1293 	if (cpu == -1)
1294 		cpu = sched_lowest(cpu_top, mask, pri, INT_MAX, ts->ts_cpu);
1295 	/* Search globally for the less loaded CPU. */
1296 	if (cpu == -1)
1297 		cpu = sched_lowest(cpu_top, mask, -1, INT_MAX, ts->ts_cpu);
1298 	KASSERT(cpu != -1, ("sched_pickcpu: Failed to find a cpu."));
1299 	KASSERT(!CPU_ABSENT(cpu), ("sched_pickcpu: Picked absent CPU %d.", cpu));
1300 	/*
1301 	 * Compare the lowest loaded cpu to current cpu.
1302 	 */
1303 	if (THREAD_CAN_SCHED(td, self) && TDQ_CPU(self)->tdq_lowpri > pri &&
1304 	    TDQ_CPU(cpu)->tdq_lowpri < PRI_MIN_IDLE &&
1305 	    TDQ_CPU(self)->tdq_load <= TDQ_CPU(cpu)->tdq_load + 1) {
1306 		SCHED_STAT_INC(pickcpu_local);
1307 		cpu = self;
1308 	} else
1309 		SCHED_STAT_INC(pickcpu_lowest);
1310 	if (cpu != ts->ts_cpu)
1311 		SCHED_STAT_INC(pickcpu_migration);
1312 	return (cpu);
1313 }
1314 #endif
1315 
1316 /*
1317  * Pick the highest priority task we have and return it.
1318  */
1319 static struct thread *
1320 tdq_choose(struct tdq *tdq)
1321 {
1322 	struct thread *td;
1323 
1324 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
1325 	td = runq_choose(&tdq->tdq_realtime);
1326 	if (td != NULL)
1327 		return (td);
1328 	td = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
1329 	if (td != NULL) {
1330 		KASSERT(td->td_priority >= PRI_MIN_BATCH,
1331 		    ("tdq_choose: Invalid priority on timeshare queue %d",
1332 		    td->td_priority));
1333 		return (td);
1334 	}
1335 	td = runq_choose(&tdq->tdq_idle);
1336 	if (td != NULL) {
1337 		KASSERT(td->td_priority >= PRI_MIN_IDLE,
1338 		    ("tdq_choose: Invalid priority on idle queue %d",
1339 		    td->td_priority));
1340 		return (td);
1341 	}
1342 
1343 	return (NULL);
1344 }
1345 
1346 /*
1347  * Initialize a thread queue.
1348  */
1349 static void
1350 tdq_setup(struct tdq *tdq)
1351 {
1352 
1353 	if (bootverbose)
1354 		printf("ULE: setup cpu %d\n", TDQ_ID(tdq));
1355 	runq_init(&tdq->tdq_realtime);
1356 	runq_init(&tdq->tdq_timeshare);
1357 	runq_init(&tdq->tdq_idle);
1358 	snprintf(tdq->tdq_name, sizeof(tdq->tdq_name),
1359 	    "sched lock %d", (int)TDQ_ID(tdq));
1360 	mtx_init(&tdq->tdq_lock, tdq->tdq_name, "sched lock",
1361 	    MTX_SPIN | MTX_RECURSE);
1362 #ifdef KTR
1363 	snprintf(tdq->tdq_loadname, sizeof(tdq->tdq_loadname),
1364 	    "CPU %d load", (int)TDQ_ID(tdq));
1365 #endif
1366 }
1367 
1368 #ifdef SMP
1369 static void
1370 sched_setup_smp(void)
1371 {
1372 	struct tdq *tdq;
1373 	int i;
1374 
1375 	cpu_top = smp_topo();
1376 	CPU_FOREACH(i) {
1377 		tdq = TDQ_CPU(i);
1378 		tdq_setup(tdq);
1379 		tdq->tdq_cg = smp_topo_find(cpu_top, i);
1380 		if (tdq->tdq_cg == NULL)
1381 			panic("Can't find cpu group for %d\n", i);
1382 	}
1383 	balance_tdq = TDQ_SELF();
1384 	sched_balance();
1385 }
1386 #endif
1387 
1388 /*
1389  * Setup the thread queues and initialize the topology based on MD
1390  * information.
1391  */
1392 static void
1393 sched_setup(void *dummy)
1394 {
1395 	struct tdq *tdq;
1396 
1397 	tdq = TDQ_SELF();
1398 #ifdef SMP
1399 	sched_setup_smp();
1400 #else
1401 	tdq_setup(tdq);
1402 #endif
1403 
1404 	/* Add thread0's load since it's running. */
1405 	TDQ_LOCK(tdq);
1406 	td_get_sched(&thread0)->ts_cpu = curcpu; /* Something valid to start */
1407 	thread0.td_lock = TDQ_LOCKPTR(TDQ_SELF());
1408 	tdq_load_add(tdq, &thread0);
1409 	tdq->tdq_lowpri = thread0.td_priority;
1410 	TDQ_UNLOCK(tdq);
1411 }
1412 
1413 /*
1414  * This routine determines time constants after stathz and hz are setup.
1415  */
1416 /* ARGSUSED */
1417 static void
1418 sched_initticks(void *dummy)
1419 {
1420 	int incr;
1421 
1422 	realstathz = stathz ? stathz : hz;
1423 	sched_slice = realstathz / SCHED_SLICE_DEFAULT_DIVISOR;
1424 	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
1425 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
1426 	    realstathz);
1427 
1428 	/*
1429 	 * tickincr is shifted out by 10 to avoid rounding errors due to
1430 	 * hz not being evenly divisible by stathz on all platforms.
1431 	 */
1432 	incr = (hz << SCHED_TICK_SHIFT) / realstathz;
1433 	/*
1434 	 * This does not work for values of stathz that are more than
1435 	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1436 	 */
1437 	if (incr == 0)
1438 		incr = 1;
1439 	tickincr = incr;
1440 #ifdef SMP
1441 	/*
1442 	 * Set the default balance interval now that we know
1443 	 * what realstathz is.
1444 	 */
1445 	balance_interval = realstathz;
1446 	affinity = SCHED_AFFINITY_DEFAULT;
1447 #endif
1448 	if (sched_idlespinthresh < 0)
1449 		sched_idlespinthresh = 2 * max(10000, 6 * hz) / realstathz;
1450 }
1451 
1452 
1453 /*
1454  * This is the core of the interactivity algorithm.  Determines a score based
1455  * on past behavior.  It is the ratio of sleep time to run time scaled to
1456  * a [0, 100] integer.  This is the voluntary sleep time of a process, which
1457  * differs from the cpu usage because it does not account for time spent
1458  * waiting on a run-queue.  Would be prettier if we had floating point.
1459  *
1460  * When a thread's sleep time is greater than its run time the
1461  * calculation is:
1462  *
1463  *                           scaling factor
1464  * interactivity score =  ---------------------
1465  *                        sleep time / run time
1466  *
1467  *
1468  * When a thread's run time is greater than its sleep time the
1469  * calculation is:
1470  *
1471  *                           scaling factor
1472  * interactivity score =  ---------------------    + scaling factor
1473  *                        run time / sleep time
1474  */
1475 static int
1476 sched_interact_score(struct thread *td)
1477 {
1478 	struct td_sched *ts;
1479 	int div;
1480 
1481 	ts = td_get_sched(td);
1482 	/*
1483 	 * The score is only needed if this is likely to be an interactive
1484 	 * task.  Don't go through the expense of computing it if there's
1485 	 * no chance.
1486 	 */
1487 	if (sched_interact <= SCHED_INTERACT_HALF &&
1488 		ts->ts_runtime >= ts->ts_slptime)
1489 			return (SCHED_INTERACT_HALF);
1490 
1491 	if (ts->ts_runtime > ts->ts_slptime) {
1492 		div = max(1, ts->ts_runtime / SCHED_INTERACT_HALF);
1493 		return (SCHED_INTERACT_HALF +
1494 		    (SCHED_INTERACT_HALF - (ts->ts_slptime / div)));
1495 	}
1496 	if (ts->ts_slptime > ts->ts_runtime) {
1497 		div = max(1, ts->ts_slptime / SCHED_INTERACT_HALF);
1498 		return (ts->ts_runtime / div);
1499 	}
1500 	/* runtime == slptime */
1501 	if (ts->ts_runtime)
1502 		return (SCHED_INTERACT_HALF);
1503 
1504 	/*
1505 	 * This can happen if slptime and runtime are 0.
1506 	 */
1507 	return (0);
1508 
1509 }
1510 
1511 /*
1512  * Scale the scheduling priority according to the "interactivity" of this
1513  * process.
1514  */
1515 static void
1516 sched_priority(struct thread *td)
1517 {
1518 	int score;
1519 	int pri;
1520 
1521 	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
1522 		return;
1523 	/*
1524 	 * If the score is interactive we place the thread in the realtime
1525 	 * queue with a priority that is less than kernel and interrupt
1526 	 * priorities.  These threads are not subject to nice restrictions.
1527 	 *
1528 	 * Scores greater than this are placed on the normal timeshare queue
1529 	 * where the priority is partially decided by the most recent cpu
1530 	 * utilization and the rest is decided by nice value.
1531 	 *
1532 	 * The nice value of the process has a linear effect on the calculated
1533 	 * score.  Negative nice values make it easier for a thread to be
1534 	 * considered interactive.
1535 	 */
1536 	score = imax(0, sched_interact_score(td) + td->td_proc->p_nice);
1537 	if (score < sched_interact) {
1538 		pri = PRI_MIN_INTERACT;
1539 		pri += ((PRI_MAX_INTERACT - PRI_MIN_INTERACT + 1) /
1540 		    sched_interact) * score;
1541 		KASSERT(pri >= PRI_MIN_INTERACT && pri <= PRI_MAX_INTERACT,
1542 		    ("sched_priority: invalid interactive priority %d score %d",
1543 		    pri, score));
1544 	} else {
1545 		pri = SCHED_PRI_MIN;
1546 		if (td_get_sched(td)->ts_ticks)
1547 			pri += min(SCHED_PRI_TICKS(td_get_sched(td)),
1548 			    SCHED_PRI_RANGE - 1);
1549 		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1550 		KASSERT(pri >= PRI_MIN_BATCH && pri <= PRI_MAX_BATCH,
1551 		    ("sched_priority: invalid priority %d: nice %d, "
1552 		    "ticks %d ftick %d ltick %d tick pri %d",
1553 		    pri, td->td_proc->p_nice, td_get_sched(td)->ts_ticks,
1554 		    td_get_sched(td)->ts_ftick, td_get_sched(td)->ts_ltick,
1555 		    SCHED_PRI_TICKS(td_get_sched(td))));
1556 	}
1557 	sched_user_prio(td, pri);
1558 
1559 	return;
1560 }
1561 
1562 /*
1563  * This routine enforces a maximum limit on the amount of scheduling history
1564  * kept.  It is called after either the slptime or runtime is adjusted.  This
1565  * function is ugly due to integer math.
1566  */
1567 static void
1568 sched_interact_update(struct thread *td)
1569 {
1570 	struct td_sched *ts;
1571 	u_int sum;
1572 
1573 	ts = td_get_sched(td);
1574 	sum = ts->ts_runtime + ts->ts_slptime;
1575 	if (sum < SCHED_SLP_RUN_MAX)
1576 		return;
1577 	/*
1578 	 * This only happens from two places:
1579 	 * 1) We have added an unusual amount of run time from fork_exit.
1580 	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1581 	 */
1582 	if (sum > SCHED_SLP_RUN_MAX * 2) {
1583 		if (ts->ts_runtime > ts->ts_slptime) {
1584 			ts->ts_runtime = SCHED_SLP_RUN_MAX;
1585 			ts->ts_slptime = 1;
1586 		} else {
1587 			ts->ts_slptime = SCHED_SLP_RUN_MAX;
1588 			ts->ts_runtime = 1;
1589 		}
1590 		return;
1591 	}
1592 	/*
1593 	 * If we have exceeded by more than 1/5th then the algorithm below
1594 	 * will not bring us back into range.  Dividing by two here forces
1595 	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1596 	 */
1597 	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1598 		ts->ts_runtime /= 2;
1599 		ts->ts_slptime /= 2;
1600 		return;
1601 	}
1602 	ts->ts_runtime = (ts->ts_runtime / 5) * 4;
1603 	ts->ts_slptime = (ts->ts_slptime / 5) * 4;
1604 }
1605 
1606 /*
1607  * Scale back the interactivity history when a child thread is created.  The
1608  * history is inherited from the parent but the thread may behave totally
1609  * differently.  For example, a shell spawning a compiler process.  We want
1610  * to learn that the compiler is behaving badly very quickly.
1611  */
1612 static void
1613 sched_interact_fork(struct thread *td)
1614 {
1615 	struct td_sched *ts;
1616 	int ratio;
1617 	int sum;
1618 
1619 	ts = td_get_sched(td);
1620 	sum = ts->ts_runtime + ts->ts_slptime;
1621 	if (sum > SCHED_SLP_RUN_FORK) {
1622 		ratio = sum / SCHED_SLP_RUN_FORK;
1623 		ts->ts_runtime /= ratio;
1624 		ts->ts_slptime /= ratio;
1625 	}
1626 }
1627 
1628 /*
1629  * Called from proc0_init() to setup the scheduler fields.
1630  */
1631 void
1632 schedinit(void)
1633 {
1634 	struct td_sched *ts0;
1635 
1636 	/*
1637 	 * Set up the scheduler specific parts of thread0.
1638 	 */
1639 	ts0 = td_get_sched(&thread0);
1640 	ts0->ts_ltick = ticks;
1641 	ts0->ts_ftick = ticks;
1642 	ts0->ts_slice = 0;
1643 }
1644 
1645 /*
1646  * This is only somewhat accurate since given many processes of the same
1647  * priority they will switch when their slices run out, which will be
1648  * at most sched_slice stathz ticks.
1649  */
1650 int
1651 sched_rr_interval(void)
1652 {
1653 
1654 	/* Convert sched_slice from stathz to hz. */
1655 	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
1656 }
1657 
1658 /*
1659  * Update the percent cpu tracking information when it is requested or
1660  * the total history exceeds the maximum.  We keep a sliding history of
1661  * tick counts that slowly decays.  This is less precise than the 4BSD
1662  * mechanism since it happens with less regular and frequent events.
1663  */
1664 static void
1665 sched_pctcpu_update(struct td_sched *ts, int run)
1666 {
1667 	int t = ticks;
1668 
1669 	/*
1670 	 * The signed difference may be negative if the thread hasn't run for
1671 	 * over half of the ticks rollover period.
1672 	 */
1673 	if ((u_int)(t - ts->ts_ltick) >= SCHED_TICK_TARG) {
1674 		ts->ts_ticks = 0;
1675 		ts->ts_ftick = t - SCHED_TICK_TARG;
1676 	} else if (t - ts->ts_ftick >= SCHED_TICK_MAX) {
1677 		ts->ts_ticks = (ts->ts_ticks / (ts->ts_ltick - ts->ts_ftick)) *
1678 		    (ts->ts_ltick - (t - SCHED_TICK_TARG));
1679 		ts->ts_ftick = t - SCHED_TICK_TARG;
1680 	}
1681 	if (run)
1682 		ts->ts_ticks += (t - ts->ts_ltick) << SCHED_TICK_SHIFT;
1683 	ts->ts_ltick = t;
1684 }
1685 
1686 /*
1687  * Adjust the priority of a thread.  Move it to the appropriate run-queue
1688  * if necessary.  This is the back-end for several priority related
1689  * functions.
1690  */
1691 static void
1692 sched_thread_priority(struct thread *td, u_char prio)
1693 {
1694 	struct td_sched *ts;
1695 	struct tdq *tdq;
1696 	int oldpri;
1697 
1698 	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "prio",
1699 	    "prio:%d", td->td_priority, "new prio:%d", prio,
1700 	    KTR_ATTR_LINKED, sched_tdname(curthread));
1701 	SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
1702 	if (td != curthread && prio < td->td_priority) {
1703 		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
1704 		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
1705 		    prio, KTR_ATTR_LINKED, sched_tdname(td));
1706 		SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
1707 		    curthread);
1708 	}
1709 	ts = td_get_sched(td);
1710 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1711 	if (td->td_priority == prio)
1712 		return;
1713 	/*
1714 	 * If the priority has been elevated due to priority
1715 	 * propagation, we may have to move ourselves to a new
1716 	 * queue.  This could be optimized to not re-add in some
1717 	 * cases.
1718 	 */
1719 	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1720 		sched_rem(td);
1721 		td->td_priority = prio;
1722 		sched_add(td, SRQ_BORROWING);
1723 		return;
1724 	}
1725 	/*
1726 	 * If the thread is currently running we may have to adjust the lowpri
1727 	 * information so other cpus are aware of our current priority.
1728 	 */
1729 	if (TD_IS_RUNNING(td)) {
1730 		tdq = TDQ_CPU(ts->ts_cpu);
1731 		oldpri = td->td_priority;
1732 		td->td_priority = prio;
1733 		if (prio < tdq->tdq_lowpri)
1734 			tdq->tdq_lowpri = prio;
1735 		else if (tdq->tdq_lowpri == oldpri)
1736 			tdq_setlowpri(tdq, td);
1737 		return;
1738 	}
1739 	td->td_priority = prio;
1740 }
1741 
1742 /*
1743  * Update a thread's priority when it is lent another thread's
1744  * priority.
1745  */
1746 void
1747 sched_lend_prio(struct thread *td, u_char prio)
1748 {
1749 
1750 	td->td_flags |= TDF_BORROWING;
1751 	sched_thread_priority(td, prio);
1752 }
1753 
1754 /*
1755  * Restore a thread's priority when priority propagation is
1756  * over.  The prio argument is the minimum priority the thread
1757  * needs to have to satisfy other possible priority lending
1758  * requests.  If the thread's regular priority is less
1759  * important than prio, the thread will keep a priority boost
1760  * of prio.
1761  */
1762 void
1763 sched_unlend_prio(struct thread *td, u_char prio)
1764 {
1765 	u_char base_pri;
1766 
1767 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1768 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1769 		base_pri = td->td_user_pri;
1770 	else
1771 		base_pri = td->td_base_pri;
1772 	if (prio >= base_pri) {
1773 		td->td_flags &= ~TDF_BORROWING;
1774 		sched_thread_priority(td, base_pri);
1775 	} else
1776 		sched_lend_prio(td, prio);
1777 }
1778 
1779 /*
1780  * Standard entry for setting the priority to an absolute value.
1781  */
1782 void
1783 sched_prio(struct thread *td, u_char prio)
1784 {
1785 	u_char oldprio;
1786 
1787 	/* First, update the base priority. */
1788 	td->td_base_pri = prio;
1789 
1790 	/*
1791 	 * If the thread is borrowing another thread's priority, don't
1792 	 * ever lower the priority.
1793 	 */
1794 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1795 		return;
1796 
1797 	/* Change the real priority. */
1798 	oldprio = td->td_priority;
1799 	sched_thread_priority(td, prio);
1800 
1801 	/*
1802 	 * If the thread is on a turnstile, then let the turnstile update
1803 	 * its state.
1804 	 */
1805 	if (TD_ON_LOCK(td) && oldprio != prio)
1806 		turnstile_adjust(td, oldprio);
1807 }
1808 
1809 /*
1810  * Set the base user priority, does not effect current running priority.
1811  */
1812 void
1813 sched_user_prio(struct thread *td, u_char prio)
1814 {
1815 
1816 	td->td_base_user_pri = prio;
1817 	if (td->td_lend_user_pri <= prio)
1818 		return;
1819 	td->td_user_pri = prio;
1820 }
1821 
1822 void
1823 sched_lend_user_prio(struct thread *td, u_char prio)
1824 {
1825 
1826 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1827 	td->td_lend_user_pri = prio;
1828 	td->td_user_pri = min(prio, td->td_base_user_pri);
1829 	if (td->td_priority > td->td_user_pri)
1830 		sched_prio(td, td->td_user_pri);
1831 	else if (td->td_priority != td->td_user_pri)
1832 		td->td_flags |= TDF_NEEDRESCHED;
1833 }
1834 
1835 /*
1836  * Handle migration from sched_switch().  This happens only for
1837  * cpu binding.
1838  */
1839 static struct mtx *
1840 sched_switch_migrate(struct tdq *tdq, struct thread *td, int flags)
1841 {
1842 	struct tdq *tdn;
1843 
1844 	KASSERT(!CPU_ABSENT(td_get_sched(td)->ts_cpu), ("sched_switch_migrate: "
1845 	    "thread %s queued on absent CPU %d.", td->td_name,
1846 	    td_get_sched(td)->ts_cpu));
1847 	tdn = TDQ_CPU(td_get_sched(td)->ts_cpu);
1848 #ifdef SMP
1849 	tdq_load_rem(tdq, td);
1850 	/*
1851 	 * Do the lock dance required to avoid LOR.  We grab an extra
1852 	 * spinlock nesting to prevent preemption while we're
1853 	 * not holding either run-queue lock.
1854 	 */
1855 	spinlock_enter();
1856 	thread_lock_block(td);	/* This releases the lock on tdq. */
1857 
1858 	/*
1859 	 * Acquire both run-queue locks before placing the thread on the new
1860 	 * run-queue to avoid deadlocks created by placing a thread with a
1861 	 * blocked lock on the run-queue of a remote processor.  The deadlock
1862 	 * occurs when a third processor attempts to lock the two queues in
1863 	 * question while the target processor is spinning with its own
1864 	 * run-queue lock held while waiting for the blocked lock to clear.
1865 	 */
1866 	tdq_lock_pair(tdn, tdq);
1867 	tdq_add(tdn, td, flags);
1868 	tdq_notify(tdn, td);
1869 	TDQ_UNLOCK(tdn);
1870 	spinlock_exit();
1871 #endif
1872 	return (TDQ_LOCKPTR(tdn));
1873 }
1874 
1875 /*
1876  * Variadic version of thread_lock_unblock() that does not assume td_lock
1877  * is blocked.
1878  */
1879 static inline void
1880 thread_unblock_switch(struct thread *td, struct mtx *mtx)
1881 {
1882 	atomic_store_rel_ptr((volatile uintptr_t *)&td->td_lock,
1883 	    (uintptr_t)mtx);
1884 }
1885 
1886 /*
1887  * Switch threads.  This function has to handle threads coming in while
1888  * blocked for some reason, running, or idle.  It also must deal with
1889  * migrating a thread from one queue to another as running threads may
1890  * be assigned elsewhere via binding.
1891  */
1892 void
1893 sched_switch(struct thread *td, struct thread *newtd, int flags)
1894 {
1895 	struct tdq *tdq;
1896 	struct td_sched *ts;
1897 	struct mtx *mtx;
1898 	int srqflag;
1899 	int cpuid, preempted;
1900 
1901 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1902 	KASSERT(newtd == NULL, ("sched_switch: Unsupported newtd argument"));
1903 
1904 	cpuid = PCPU_GET(cpuid);
1905 	tdq = TDQ_CPU(cpuid);
1906 	ts = td_get_sched(td);
1907 	mtx = td->td_lock;
1908 	sched_pctcpu_update(ts, 1);
1909 	ts->ts_rltick = ticks;
1910 	td->td_lastcpu = td->td_oncpu;
1911 	td->td_oncpu = NOCPU;
1912 	preempted = (td->td_flags & TDF_SLICEEND) == 0 &&
1913 	    (flags & SW_PREEMPT) != 0;
1914 	td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
1915 	td->td_owepreempt = 0;
1916 	if (!TD_IS_IDLETHREAD(td))
1917 		tdq->tdq_switchcnt++;
1918 	/*
1919 	 * The lock pointer in an idle thread should never change.  Reset it
1920 	 * to CAN_RUN as well.
1921 	 */
1922 	if (TD_IS_IDLETHREAD(td)) {
1923 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1924 		TD_SET_CAN_RUN(td);
1925 	} else if (TD_IS_RUNNING(td)) {
1926 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
1927 		srqflag = preempted ?
1928 		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1929 		    SRQ_OURSELF|SRQ_YIELDING;
1930 #ifdef SMP
1931 		if (THREAD_CAN_MIGRATE(td) && !THREAD_CAN_SCHED(td, ts->ts_cpu))
1932 			ts->ts_cpu = sched_pickcpu(td, 0);
1933 #endif
1934 		if (ts->ts_cpu == cpuid)
1935 			tdq_runq_add(tdq, td, srqflag);
1936 		else {
1937 			KASSERT(THREAD_CAN_MIGRATE(td) ||
1938 			    (ts->ts_flags & TSF_BOUND) != 0,
1939 			    ("Thread %p shouldn't migrate", td));
1940 			mtx = sched_switch_migrate(tdq, td, srqflag);
1941 		}
1942 	} else {
1943 		/* This thread must be going to sleep. */
1944 		TDQ_LOCK(tdq);
1945 		mtx = thread_lock_block(td);
1946 		tdq_load_rem(tdq, td);
1947 	}
1948 
1949 #if (KTR_COMPILE & KTR_SCHED) != 0
1950 	if (TD_IS_IDLETHREAD(td))
1951 		KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "idle",
1952 		    "prio:%d", td->td_priority);
1953 	else
1954 		KTR_STATE3(KTR_SCHED, "thread", sched_tdname(td), KTDSTATE(td),
1955 		    "prio:%d", td->td_priority, "wmesg:\"%s\"", td->td_wmesg,
1956 		    "lockname:\"%s\"", td->td_lockname);
1957 #endif
1958 
1959 	/*
1960 	 * We enter here with the thread blocked and assigned to the
1961 	 * appropriate cpu run-queue or sleep-queue and with the current
1962 	 * thread-queue locked.
1963 	 */
1964 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
1965 	newtd = choosethread();
1966 	/*
1967 	 * Call the MD code to switch contexts if necessary.
1968 	 */
1969 	if (td != newtd) {
1970 #ifdef	HWPMC_HOOKS
1971 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1972 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1973 #endif
1974 		SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
1975 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
1976 		TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
1977 		sched_pctcpu_update(td_get_sched(newtd), 0);
1978 
1979 #ifdef KDTRACE_HOOKS
1980 		/*
1981 		 * If DTrace has set the active vtime enum to anything
1982 		 * other than INACTIVE (0), then it should have set the
1983 		 * function to call.
1984 		 */
1985 		if (dtrace_vtime_active)
1986 			(*dtrace_vtime_switch_func)(newtd);
1987 #endif
1988 
1989 		cpu_switch(td, newtd, mtx);
1990 		/*
1991 		 * We may return from cpu_switch on a different cpu.  However,
1992 		 * we always return with td_lock pointing to the current cpu's
1993 		 * run queue lock.
1994 		 */
1995 		cpuid = PCPU_GET(cpuid);
1996 		tdq = TDQ_CPU(cpuid);
1997 		lock_profile_obtain_lock_success(
1998 		    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
1999 
2000 		SDT_PROBE0(sched, , , on__cpu);
2001 #ifdef	HWPMC_HOOKS
2002 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
2003 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
2004 #endif
2005 	} else {
2006 		thread_unblock_switch(td, mtx);
2007 		SDT_PROBE0(sched, , , remain__cpu);
2008 	}
2009 
2010 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
2011 	    "prio:%d", td->td_priority);
2012 
2013 	/*
2014 	 * Assert that all went well and return.
2015 	 */
2016 	TDQ_LOCK_ASSERT(tdq, MA_OWNED|MA_NOTRECURSED);
2017 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2018 	td->td_oncpu = cpuid;
2019 }
2020 
2021 /*
2022  * Adjust thread priorities as a result of a nice request.
2023  */
2024 void
2025 sched_nice(struct proc *p, int nice)
2026 {
2027 	struct thread *td;
2028 
2029 	PROC_LOCK_ASSERT(p, MA_OWNED);
2030 
2031 	p->p_nice = nice;
2032 	FOREACH_THREAD_IN_PROC(p, td) {
2033 		thread_lock(td);
2034 		sched_priority(td);
2035 		sched_prio(td, td->td_base_user_pri);
2036 		thread_unlock(td);
2037 	}
2038 }
2039 
2040 /*
2041  * Record the sleep time for the interactivity scorer.
2042  */
2043 void
2044 sched_sleep(struct thread *td, int prio)
2045 {
2046 
2047 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2048 
2049 	td->td_slptick = ticks;
2050 	if (TD_IS_SUSPENDED(td) || prio >= PSOCK)
2051 		td->td_flags |= TDF_CANSWAP;
2052 	if (PRI_BASE(td->td_pri_class) != PRI_TIMESHARE)
2053 		return;
2054 	if (static_boost == 1 && prio)
2055 		sched_prio(td, prio);
2056 	else if (static_boost && td->td_priority > static_boost)
2057 		sched_prio(td, static_boost);
2058 }
2059 
2060 /*
2061  * Schedule a thread to resume execution and record how long it voluntarily
2062  * slept.  We also update the pctcpu, interactivity, and priority.
2063  */
2064 void
2065 sched_wakeup(struct thread *td)
2066 {
2067 	struct td_sched *ts;
2068 	int slptick;
2069 
2070 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2071 	ts = td_get_sched(td);
2072 	td->td_flags &= ~TDF_CANSWAP;
2073 	/*
2074 	 * If we slept for more than a tick update our interactivity and
2075 	 * priority.
2076 	 */
2077 	slptick = td->td_slptick;
2078 	td->td_slptick = 0;
2079 	if (slptick && slptick != ticks) {
2080 		ts->ts_slptime += (ticks - slptick) << SCHED_TICK_SHIFT;
2081 		sched_interact_update(td);
2082 		sched_pctcpu_update(ts, 0);
2083 	}
2084 	/*
2085 	 * Reset the slice value since we slept and advanced the round-robin.
2086 	 */
2087 	ts->ts_slice = 0;
2088 	sched_add(td, SRQ_BORING);
2089 }
2090 
2091 /*
2092  * Penalize the parent for creating a new child and initialize the child's
2093  * priority.
2094  */
2095 void
2096 sched_fork(struct thread *td, struct thread *child)
2097 {
2098 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2099 	sched_pctcpu_update(td_get_sched(td), 1);
2100 	sched_fork_thread(td, child);
2101 	/*
2102 	 * Penalize the parent and child for forking.
2103 	 */
2104 	sched_interact_fork(child);
2105 	sched_priority(child);
2106 	td_get_sched(td)->ts_runtime += tickincr;
2107 	sched_interact_update(td);
2108 	sched_priority(td);
2109 }
2110 
2111 /*
2112  * Fork a new thread, may be within the same process.
2113  */
2114 void
2115 sched_fork_thread(struct thread *td, struct thread *child)
2116 {
2117 	struct td_sched *ts;
2118 	struct td_sched *ts2;
2119 	struct tdq *tdq;
2120 
2121 	tdq = TDQ_SELF();
2122 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2123 	/*
2124 	 * Initialize child.
2125 	 */
2126 	ts = td_get_sched(td);
2127 	ts2 = td_get_sched(child);
2128 	child->td_oncpu = NOCPU;
2129 	child->td_lastcpu = NOCPU;
2130 	child->td_lock = TDQ_LOCKPTR(tdq);
2131 	child->td_cpuset = cpuset_ref(td->td_cpuset);
2132 	ts2->ts_cpu = ts->ts_cpu;
2133 	ts2->ts_flags = 0;
2134 	/*
2135 	 * Grab our parents cpu estimation information.
2136 	 */
2137 	ts2->ts_ticks = ts->ts_ticks;
2138 	ts2->ts_ltick = ts->ts_ltick;
2139 	ts2->ts_ftick = ts->ts_ftick;
2140 	/*
2141 	 * Do not inherit any borrowed priority from the parent.
2142 	 */
2143 	child->td_priority = child->td_base_pri;
2144 	/*
2145 	 * And update interactivity score.
2146 	 */
2147 	ts2->ts_slptime = ts->ts_slptime;
2148 	ts2->ts_runtime = ts->ts_runtime;
2149 	/* Attempt to quickly learn interactivity. */
2150 	ts2->ts_slice = tdq_slice(tdq) - sched_slice_min;
2151 #ifdef KTR
2152 	bzero(ts2->ts_name, sizeof(ts2->ts_name));
2153 #endif
2154 }
2155 
2156 /*
2157  * Adjust the priority class of a thread.
2158  */
2159 void
2160 sched_class(struct thread *td, int class)
2161 {
2162 
2163 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2164 	if (td->td_pri_class == class)
2165 		return;
2166 	td->td_pri_class = class;
2167 }
2168 
2169 /*
2170  * Return some of the child's priority and interactivity to the parent.
2171  */
2172 void
2173 sched_exit(struct proc *p, struct thread *child)
2174 {
2175 	struct thread *td;
2176 
2177 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "proc exit",
2178 	    "prio:%d", child->td_priority);
2179 	PROC_LOCK_ASSERT(p, MA_OWNED);
2180 	td = FIRST_THREAD_IN_PROC(p);
2181 	sched_exit_thread(td, child);
2182 }
2183 
2184 /*
2185  * Penalize another thread for the time spent on this one.  This helps to
2186  * worsen the priority and interactivity of processes which schedule batch
2187  * jobs such as make.  This has little effect on the make process itself but
2188  * causes new processes spawned by it to receive worse scores immediately.
2189  */
2190 void
2191 sched_exit_thread(struct thread *td, struct thread *child)
2192 {
2193 
2194 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "thread exit",
2195 	    "prio:%d", child->td_priority);
2196 	/*
2197 	 * Give the child's runtime to the parent without returning the
2198 	 * sleep time as a penalty to the parent.  This causes shells that
2199 	 * launch expensive things to mark their children as expensive.
2200 	 */
2201 	thread_lock(td);
2202 	td_get_sched(td)->ts_runtime += td_get_sched(child)->ts_runtime;
2203 	sched_interact_update(td);
2204 	sched_priority(td);
2205 	thread_unlock(td);
2206 }
2207 
2208 void
2209 sched_preempt(struct thread *td)
2210 {
2211 	struct tdq *tdq;
2212 
2213 	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
2214 
2215 	thread_lock(td);
2216 	tdq = TDQ_SELF();
2217 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2218 	tdq->tdq_ipipending = 0;
2219 	if (td->td_priority > tdq->tdq_lowpri) {
2220 		int flags;
2221 
2222 		flags = SW_INVOL | SW_PREEMPT;
2223 		if (td->td_critnest > 1)
2224 			td->td_owepreempt = 1;
2225 		else if (TD_IS_IDLETHREAD(td))
2226 			mi_switch(flags | SWT_REMOTEWAKEIDLE, NULL);
2227 		else
2228 			mi_switch(flags | SWT_REMOTEPREEMPT, NULL);
2229 	}
2230 	thread_unlock(td);
2231 }
2232 
2233 /*
2234  * Fix priorities on return to user-space.  Priorities may be elevated due
2235  * to static priorities in msleep() or similar.
2236  */
2237 void
2238 sched_userret(struct thread *td)
2239 {
2240 	/*
2241 	 * XXX we cheat slightly on the locking here to avoid locking in
2242 	 * the usual case.  Setting td_priority here is essentially an
2243 	 * incomplete workaround for not setting it properly elsewhere.
2244 	 * Now that some interrupt handlers are threads, not setting it
2245 	 * properly elsewhere can clobber it in the window between setting
2246 	 * it here and returning to user mode, so don't waste time setting
2247 	 * it perfectly here.
2248 	 */
2249 	KASSERT((td->td_flags & TDF_BORROWING) == 0,
2250 	    ("thread with borrowed priority returning to userland"));
2251 	if (td->td_priority != td->td_user_pri) {
2252 		thread_lock(td);
2253 		td->td_priority = td->td_user_pri;
2254 		td->td_base_pri = td->td_user_pri;
2255 		tdq_setlowpri(TDQ_SELF(), td);
2256 		thread_unlock(td);
2257         }
2258 }
2259 
2260 /*
2261  * Handle a stathz tick.  This is really only relevant for timeshare
2262  * threads.
2263  */
2264 void
2265 sched_clock(struct thread *td)
2266 {
2267 	struct tdq *tdq;
2268 	struct td_sched *ts;
2269 
2270 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2271 	tdq = TDQ_SELF();
2272 #ifdef SMP
2273 	/*
2274 	 * We run the long term load balancer infrequently on the first cpu.
2275 	 */
2276 	if (balance_tdq == tdq) {
2277 		if (balance_ticks && --balance_ticks == 0)
2278 			sched_balance();
2279 	}
2280 #endif
2281 	/*
2282 	 * Save the old switch count so we have a record of the last ticks
2283 	 * activity.   Initialize the new switch count based on our load.
2284 	 * If there is some activity seed it to reflect that.
2285 	 */
2286 	tdq->tdq_oldswitchcnt = tdq->tdq_switchcnt;
2287 	tdq->tdq_switchcnt = tdq->tdq_load;
2288 	/*
2289 	 * Advance the insert index once for each tick to ensure that all
2290 	 * threads get a chance to run.
2291 	 */
2292 	if (tdq->tdq_idx == tdq->tdq_ridx) {
2293 		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
2294 		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
2295 			tdq->tdq_ridx = tdq->tdq_idx;
2296 	}
2297 	ts = td_get_sched(td);
2298 	sched_pctcpu_update(ts, 1);
2299 	if (td->td_pri_class & PRI_FIFO_BIT)
2300 		return;
2301 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE) {
2302 		/*
2303 		 * We used a tick; charge it to the thread so
2304 		 * that we can compute our interactivity.
2305 		 */
2306 		td_get_sched(td)->ts_runtime += tickincr;
2307 		sched_interact_update(td);
2308 		sched_priority(td);
2309 	}
2310 
2311 	/*
2312 	 * Force a context switch if the current thread has used up a full
2313 	 * time slice (default is 100ms).
2314 	 */
2315 	if (!TD_IS_IDLETHREAD(td) && ++ts->ts_slice >= tdq_slice(tdq)) {
2316 		ts->ts_slice = 0;
2317 		td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
2318 	}
2319 }
2320 
2321 u_int
2322 sched_estcpu(struct thread *td __unused)
2323 {
2324 
2325 	return (0);
2326 }
2327 
2328 /*
2329  * Return whether the current CPU has runnable tasks.  Used for in-kernel
2330  * cooperative idle threads.
2331  */
2332 int
2333 sched_runnable(void)
2334 {
2335 	struct tdq *tdq;
2336 	int load;
2337 
2338 	load = 1;
2339 
2340 	tdq = TDQ_SELF();
2341 	if ((curthread->td_flags & TDF_IDLETD) != 0) {
2342 		if (tdq->tdq_load > 0)
2343 			goto out;
2344 	} else
2345 		if (tdq->tdq_load - 1 > 0)
2346 			goto out;
2347 	load = 0;
2348 out:
2349 	return (load);
2350 }
2351 
2352 /*
2353  * Choose the highest priority thread to run.  The thread is removed from
2354  * the run-queue while running however the load remains.  For SMP we set
2355  * the tdq in the global idle bitmask if it idles here.
2356  */
2357 struct thread *
2358 sched_choose(void)
2359 {
2360 	struct thread *td;
2361 	struct tdq *tdq;
2362 
2363 	tdq = TDQ_SELF();
2364 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2365 	td = tdq_choose(tdq);
2366 	if (td) {
2367 		tdq_runq_rem(tdq, td);
2368 		tdq->tdq_lowpri = td->td_priority;
2369 		return (td);
2370 	}
2371 	tdq->tdq_lowpri = PRI_MAX_IDLE;
2372 	return (PCPU_GET(idlethread));
2373 }
2374 
2375 /*
2376  * Set owepreempt if necessary.  Preemption never happens directly in ULE,
2377  * we always request it once we exit a critical section.
2378  */
2379 static inline void
2380 sched_setpreempt(struct thread *td)
2381 {
2382 	struct thread *ctd;
2383 	int cpri;
2384 	int pri;
2385 
2386 	THREAD_LOCK_ASSERT(curthread, MA_OWNED);
2387 
2388 	ctd = curthread;
2389 	pri = td->td_priority;
2390 	cpri = ctd->td_priority;
2391 	if (pri < cpri)
2392 		ctd->td_flags |= TDF_NEEDRESCHED;
2393 	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
2394 		return;
2395 	if (!sched_shouldpreempt(pri, cpri, 0))
2396 		return;
2397 	ctd->td_owepreempt = 1;
2398 }
2399 
2400 /*
2401  * Add a thread to a thread queue.  Select the appropriate runq and add the
2402  * thread to it.  This is the internal function called when the tdq is
2403  * predetermined.
2404  */
2405 void
2406 tdq_add(struct tdq *tdq, struct thread *td, int flags)
2407 {
2408 
2409 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2410 	KASSERT((td->td_inhibitors == 0),
2411 	    ("sched_add: trying to run inhibited thread"));
2412 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
2413 	    ("sched_add: bad thread state"));
2414 	KASSERT(td->td_flags & TDF_INMEM,
2415 	    ("sched_add: thread swapped out"));
2416 
2417 	if (td->td_priority < tdq->tdq_lowpri)
2418 		tdq->tdq_lowpri = td->td_priority;
2419 	tdq_runq_add(tdq, td, flags);
2420 	tdq_load_add(tdq, td);
2421 }
2422 
2423 /*
2424  * Select the target thread queue and add a thread to it.  Request
2425  * preemption or IPI a remote processor if required.
2426  */
2427 void
2428 sched_add(struct thread *td, int flags)
2429 {
2430 	struct tdq *tdq;
2431 #ifdef SMP
2432 	int cpu;
2433 #endif
2434 
2435 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
2436 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
2437 	    sched_tdname(curthread));
2438 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
2439 	    KTR_ATTR_LINKED, sched_tdname(td));
2440 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
2441 	    flags & SRQ_PREEMPTED);
2442 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2443 	/*
2444 	 * Recalculate the priority before we select the target cpu or
2445 	 * run-queue.
2446 	 */
2447 	if (PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
2448 		sched_priority(td);
2449 #ifdef SMP
2450 	/*
2451 	 * Pick the destination cpu and if it isn't ours transfer to the
2452 	 * target cpu.
2453 	 */
2454 	td_get_sched(td)->ts_cpu = curcpu; /* Pick something valid to start */
2455 	cpu = sched_pickcpu(td, flags);
2456 	tdq = sched_setcpu(td, cpu, flags);
2457 	tdq_add(tdq, td, flags);
2458 	if (cpu != PCPU_GET(cpuid)) {
2459 		tdq_notify(tdq, td);
2460 		return;
2461 	}
2462 #else
2463 	tdq = TDQ_SELF();
2464 	TDQ_LOCK(tdq);
2465 	/*
2466 	 * Now that the thread is moving to the run-queue, set the lock
2467 	 * to the scheduler's lock.
2468 	 */
2469 	thread_lock_set(td, TDQ_LOCKPTR(tdq));
2470 	tdq_add(tdq, td, flags);
2471 #endif
2472 	if (!(flags & SRQ_YIELDING))
2473 		sched_setpreempt(td);
2474 }
2475 
2476 /*
2477  * Remove a thread from a run-queue without running it.  This is used
2478  * when we're stealing a thread from a remote queue.  Otherwise all threads
2479  * exit by calling sched_exit_thread() and sched_throw() themselves.
2480  */
2481 void
2482 sched_rem(struct thread *td)
2483 {
2484 	struct tdq *tdq;
2485 
2486 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
2487 	    "prio:%d", td->td_priority);
2488 	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
2489 	tdq = TDQ_CPU(td_get_sched(td)->ts_cpu);
2490 	TDQ_LOCK_ASSERT(tdq, MA_OWNED);
2491 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2492 	KASSERT(TD_ON_RUNQ(td),
2493 	    ("sched_rem: thread not on run queue"));
2494 	tdq_runq_rem(tdq, td);
2495 	tdq_load_rem(tdq, td);
2496 	TD_SET_CAN_RUN(td);
2497 	if (td->td_priority == tdq->tdq_lowpri)
2498 		tdq_setlowpri(tdq, NULL);
2499 }
2500 
2501 /*
2502  * Fetch cpu utilization information.  Updates on demand.
2503  */
2504 fixpt_t
2505 sched_pctcpu(struct thread *td)
2506 {
2507 	fixpt_t pctcpu;
2508 	struct td_sched *ts;
2509 
2510 	pctcpu = 0;
2511 	ts = td_get_sched(td);
2512 
2513 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2514 	sched_pctcpu_update(ts, TD_IS_RUNNING(td));
2515 	if (ts->ts_ticks) {
2516 		int rtick;
2517 
2518 		/* How many rtick per second ? */
2519 		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
2520 		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
2521 	}
2522 
2523 	return (pctcpu);
2524 }
2525 
2526 /*
2527  * Enforce affinity settings for a thread.  Called after adjustments to
2528  * cpumask.
2529  */
2530 void
2531 sched_affinity(struct thread *td)
2532 {
2533 #ifdef SMP
2534 	struct td_sched *ts;
2535 
2536 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2537 	ts = td_get_sched(td);
2538 	if (THREAD_CAN_SCHED(td, ts->ts_cpu))
2539 		return;
2540 	if (TD_ON_RUNQ(td)) {
2541 		sched_rem(td);
2542 		sched_add(td, SRQ_BORING);
2543 		return;
2544 	}
2545 	if (!TD_IS_RUNNING(td))
2546 		return;
2547 	/*
2548 	 * Force a switch before returning to userspace.  If the
2549 	 * target thread is not running locally send an ipi to force
2550 	 * the issue.
2551 	 */
2552 	td->td_flags |= TDF_NEEDRESCHED;
2553 	if (td != curthread)
2554 		ipi_cpu(ts->ts_cpu, IPI_PREEMPT);
2555 #endif
2556 }
2557 
2558 /*
2559  * Bind a thread to a target cpu.
2560  */
2561 void
2562 sched_bind(struct thread *td, int cpu)
2563 {
2564 	struct td_sched *ts;
2565 
2566 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
2567 	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
2568 	ts = td_get_sched(td);
2569 	if (ts->ts_flags & TSF_BOUND)
2570 		sched_unbind(td);
2571 	KASSERT(THREAD_CAN_MIGRATE(td), ("%p must be migratable", td));
2572 	ts->ts_flags |= TSF_BOUND;
2573 	sched_pin();
2574 	if (PCPU_GET(cpuid) == cpu)
2575 		return;
2576 	ts->ts_cpu = cpu;
2577 	/* When we return from mi_switch we'll be on the correct cpu. */
2578 	mi_switch(SW_VOL, NULL);
2579 }
2580 
2581 /*
2582  * Release a bound thread.
2583  */
2584 void
2585 sched_unbind(struct thread *td)
2586 {
2587 	struct td_sched *ts;
2588 
2589 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2590 	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
2591 	ts = td_get_sched(td);
2592 	if ((ts->ts_flags & TSF_BOUND) == 0)
2593 		return;
2594 	ts->ts_flags &= ~TSF_BOUND;
2595 	sched_unpin();
2596 }
2597 
2598 int
2599 sched_is_bound(struct thread *td)
2600 {
2601 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2602 	return (td_get_sched(td)->ts_flags & TSF_BOUND);
2603 }
2604 
2605 /*
2606  * Basic yield call.
2607  */
2608 void
2609 sched_relinquish(struct thread *td)
2610 {
2611 	thread_lock(td);
2612 	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
2613 	thread_unlock(td);
2614 }
2615 
2616 /*
2617  * Return the total system load.
2618  */
2619 int
2620 sched_load(void)
2621 {
2622 #ifdef SMP
2623 	int total;
2624 	int i;
2625 
2626 	total = 0;
2627 	CPU_FOREACH(i)
2628 		total += TDQ_CPU(i)->tdq_sysload;
2629 	return (total);
2630 #else
2631 	return (TDQ_SELF()->tdq_sysload);
2632 #endif
2633 }
2634 
2635 int
2636 sched_sizeof_proc(void)
2637 {
2638 	return (sizeof(struct proc));
2639 }
2640 
2641 int
2642 sched_sizeof_thread(void)
2643 {
2644 	return (sizeof(struct thread) + sizeof(struct td_sched));
2645 }
2646 
2647 #ifdef SMP
2648 #define	TDQ_IDLESPIN(tdq)						\
2649     ((tdq)->tdq_cg != NULL && ((tdq)->tdq_cg->cg_flags & CG_FLAG_THREAD) == 0)
2650 #else
2651 #define	TDQ_IDLESPIN(tdq)	1
2652 #endif
2653 
2654 /*
2655  * The actual idle process.
2656  */
2657 void
2658 sched_idletd(void *dummy)
2659 {
2660 	struct thread *td;
2661 	struct tdq *tdq;
2662 	int oldswitchcnt, switchcnt;
2663 	int i;
2664 
2665 	mtx_assert(&Giant, MA_NOTOWNED);
2666 	td = curthread;
2667 	tdq = TDQ_SELF();
2668 	THREAD_NO_SLEEPING();
2669 	oldswitchcnt = -1;
2670 	for (;;) {
2671 		if (tdq->tdq_load) {
2672 			thread_lock(td);
2673 			mi_switch(SW_VOL | SWT_IDLE, NULL);
2674 			thread_unlock(td);
2675 		}
2676 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2677 #ifdef SMP
2678 		if (switchcnt != oldswitchcnt) {
2679 			oldswitchcnt = switchcnt;
2680 			if (tdq_idled(tdq) == 0)
2681 				continue;
2682 		}
2683 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2684 #else
2685 		oldswitchcnt = switchcnt;
2686 #endif
2687 		/*
2688 		 * If we're switching very frequently, spin while checking
2689 		 * for load rather than entering a low power state that
2690 		 * may require an IPI.  However, don't do any busy
2691 		 * loops while on SMT machines as this simply steals
2692 		 * cycles from cores doing useful work.
2693 		 */
2694 		if (TDQ_IDLESPIN(tdq) && switchcnt > sched_idlespinthresh) {
2695 			for (i = 0; i < sched_idlespins; i++) {
2696 				if (tdq->tdq_load)
2697 					break;
2698 				cpu_spinwait();
2699 			}
2700 		}
2701 
2702 		/* If there was context switch during spin, restart it. */
2703 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2704 		if (tdq->tdq_load != 0 || switchcnt != oldswitchcnt)
2705 			continue;
2706 
2707 		/* Run main MD idle handler. */
2708 		tdq->tdq_cpu_idle = 1;
2709 		/*
2710 		 * Make sure that tdq_cpu_idle update is globally visible
2711 		 * before cpu_idle() read tdq_load.  The order is important
2712 		 * to avoid race with tdq_notify.
2713 		 */
2714 		atomic_thread_fence_seq_cst();
2715 		cpu_idle(switchcnt * 4 > sched_idlespinthresh);
2716 		tdq->tdq_cpu_idle = 0;
2717 
2718 		/*
2719 		 * Account thread-less hardware interrupts and
2720 		 * other wakeup reasons equal to context switches.
2721 		 */
2722 		switchcnt = tdq->tdq_switchcnt + tdq->tdq_oldswitchcnt;
2723 		if (switchcnt != oldswitchcnt)
2724 			continue;
2725 		tdq->tdq_switchcnt++;
2726 		oldswitchcnt++;
2727 	}
2728 }
2729 
2730 /*
2731  * A CPU is entering for the first time or a thread is exiting.
2732  */
2733 void
2734 sched_throw(struct thread *td)
2735 {
2736 	struct thread *newtd;
2737 	struct tdq *tdq;
2738 
2739 	tdq = TDQ_SELF();
2740 	if (td == NULL) {
2741 		/* Correct spinlock nesting and acquire the correct lock. */
2742 		TDQ_LOCK(tdq);
2743 		spinlock_exit();
2744 		PCPU_SET(switchtime, cpu_ticks());
2745 		PCPU_SET(switchticks, ticks);
2746 	} else {
2747 		MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2748 		tdq_load_rem(tdq, td);
2749 		lock_profile_release_lock(&TDQ_LOCKPTR(tdq)->lock_object);
2750 		td->td_lastcpu = td->td_oncpu;
2751 		td->td_oncpu = NOCPU;
2752 	}
2753 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2754 	newtd = choosethread();
2755 	TDQ_LOCKPTR(tdq)->mtx_lock = (uintptr_t)newtd;
2756 	cpu_throw(td, newtd);		/* doesn't return */
2757 }
2758 
2759 /*
2760  * This is called from fork_exit().  Just acquire the correct locks and
2761  * let fork do the rest of the work.
2762  */
2763 void
2764 sched_fork_exit(struct thread *td)
2765 {
2766 	struct tdq *tdq;
2767 	int cpuid;
2768 
2769 	/*
2770 	 * Finish setting up thread glue so that it begins execution in a
2771 	 * non-nested critical section with the scheduler lock held.
2772 	 */
2773 	cpuid = PCPU_GET(cpuid);
2774 	tdq = TDQ_CPU(cpuid);
2775 	if (TD_IS_IDLETHREAD(td))
2776 		td->td_lock = TDQ_LOCKPTR(tdq);
2777 	MPASS(td->td_lock == TDQ_LOCKPTR(tdq));
2778 	td->td_oncpu = cpuid;
2779 	TDQ_LOCK_ASSERT(tdq, MA_OWNED | MA_NOTRECURSED);
2780 	lock_profile_obtain_lock_success(
2781 	    &TDQ_LOCKPTR(tdq)->lock_object, 0, 0, __FILE__, __LINE__);
2782 
2783 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "running",
2784 	    "prio:%d", td->td_priority);
2785 	SDT_PROBE0(sched, , , on__cpu);
2786 }
2787 
2788 /*
2789  * Create on first use to catch odd startup conditons.
2790  */
2791 char *
2792 sched_tdname(struct thread *td)
2793 {
2794 #ifdef KTR
2795 	struct td_sched *ts;
2796 
2797 	ts = td_get_sched(td);
2798 	if (ts->ts_name[0] == '\0')
2799 		snprintf(ts->ts_name, sizeof(ts->ts_name),
2800 		    "%s tid %d", td->td_name, td->td_tid);
2801 	return (ts->ts_name);
2802 #else
2803 	return (td->td_name);
2804 #endif
2805 }
2806 
2807 #ifdef KTR
2808 void
2809 sched_clear_tdname(struct thread *td)
2810 {
2811 	struct td_sched *ts;
2812 
2813 	ts = td_get_sched(td);
2814 	ts->ts_name[0] = '\0';
2815 }
2816 #endif
2817 
2818 #ifdef SMP
2819 
2820 /*
2821  * Build the CPU topology dump string. Is recursively called to collect
2822  * the topology tree.
2823  */
2824 static int
2825 sysctl_kern_sched_topology_spec_internal(struct sbuf *sb, struct cpu_group *cg,
2826     int indent)
2827 {
2828 	char cpusetbuf[CPUSETBUFSIZ];
2829 	int i, first;
2830 
2831 	sbuf_printf(sb, "%*s<group level=\"%d\" cache-level=\"%d\">\n", indent,
2832 	    "", 1 + indent / 2, cg->cg_level);
2833 	sbuf_printf(sb, "%*s <cpu count=\"%d\" mask=\"%s\">", indent, "",
2834 	    cg->cg_count, cpusetobj_strprint(cpusetbuf, &cg->cg_mask));
2835 	first = TRUE;
2836 	for (i = 0; i < MAXCPU; i++) {
2837 		if (CPU_ISSET(i, &cg->cg_mask)) {
2838 			if (!first)
2839 				sbuf_printf(sb, ", ");
2840 			else
2841 				first = FALSE;
2842 			sbuf_printf(sb, "%d", i);
2843 		}
2844 	}
2845 	sbuf_printf(sb, "</cpu>\n");
2846 
2847 	if (cg->cg_flags != 0) {
2848 		sbuf_printf(sb, "%*s <flags>", indent, "");
2849 		if ((cg->cg_flags & CG_FLAG_HTT) != 0)
2850 			sbuf_printf(sb, "<flag name=\"HTT\">HTT group</flag>");
2851 		if ((cg->cg_flags & CG_FLAG_THREAD) != 0)
2852 			sbuf_printf(sb, "<flag name=\"THREAD\">THREAD group</flag>");
2853 		if ((cg->cg_flags & CG_FLAG_SMT) != 0)
2854 			sbuf_printf(sb, "<flag name=\"SMT\">SMT group</flag>");
2855 		sbuf_printf(sb, "</flags>\n");
2856 	}
2857 
2858 	if (cg->cg_children > 0) {
2859 		sbuf_printf(sb, "%*s <children>\n", indent, "");
2860 		for (i = 0; i < cg->cg_children; i++)
2861 			sysctl_kern_sched_topology_spec_internal(sb,
2862 			    &cg->cg_child[i], indent+2);
2863 		sbuf_printf(sb, "%*s </children>\n", indent, "");
2864 	}
2865 	sbuf_printf(sb, "%*s</group>\n", indent, "");
2866 	return (0);
2867 }
2868 
2869 /*
2870  * Sysctl handler for retrieving topology dump. It's a wrapper for
2871  * the recursive sysctl_kern_smp_topology_spec_internal().
2872  */
2873 static int
2874 sysctl_kern_sched_topology_spec(SYSCTL_HANDLER_ARGS)
2875 {
2876 	struct sbuf *topo;
2877 	int err;
2878 
2879 	KASSERT(cpu_top != NULL, ("cpu_top isn't initialized"));
2880 
2881 	topo = sbuf_new_for_sysctl(NULL, NULL, 512, req);
2882 	if (topo == NULL)
2883 		return (ENOMEM);
2884 
2885 	sbuf_printf(topo, "<groups>\n");
2886 	err = sysctl_kern_sched_topology_spec_internal(topo, cpu_top, 1);
2887 	sbuf_printf(topo, "</groups>\n");
2888 
2889 	if (err == 0) {
2890 		err = sbuf_finish(topo);
2891 	}
2892 	sbuf_delete(topo);
2893 	return (err);
2894 }
2895 
2896 #endif
2897 
2898 static int
2899 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
2900 {
2901 	int error, new_val, period;
2902 
2903 	period = 1000000 / realstathz;
2904 	new_val = period * sched_slice;
2905 	error = sysctl_handle_int(oidp, &new_val, 0, req);
2906 	if (error != 0 || req->newptr == NULL)
2907 		return (error);
2908 	if (new_val <= 0)
2909 		return (EINVAL);
2910 	sched_slice = imax(1, (new_val + period / 2) / period);
2911 	sched_slice_min = sched_slice / SCHED_SLICE_MIN_DIVISOR;
2912 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
2913 	    realstathz);
2914 	return (0);
2915 }
2916 
2917 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2918 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ULE", 0,
2919     "Scheduler name");
2920 SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
2921     NULL, 0, sysctl_kern_quantum, "I",
2922     "Quantum for timeshare threads in microseconds");
2923 SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
2924     "Quantum for timeshare threads in stathz ticks");
2925 SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0,
2926     "Interactivity score threshold");
2927 SYSCTL_INT(_kern_sched, OID_AUTO, preempt_thresh, CTLFLAG_RW,
2928     &preempt_thresh, 0,
2929     "Maximal (lowest) priority for preemption");
2930 SYSCTL_INT(_kern_sched, OID_AUTO, static_boost, CTLFLAG_RW, &static_boost, 0,
2931     "Assign static kernel priorities to sleeping threads");
2932 SYSCTL_INT(_kern_sched, OID_AUTO, idlespins, CTLFLAG_RW, &sched_idlespins, 0,
2933     "Number of times idle thread will spin waiting for new work");
2934 SYSCTL_INT(_kern_sched, OID_AUTO, idlespinthresh, CTLFLAG_RW,
2935     &sched_idlespinthresh, 0,
2936     "Threshold before we will permit idle thread spinning");
2937 #ifdef SMP
2938 SYSCTL_INT(_kern_sched, OID_AUTO, affinity, CTLFLAG_RW, &affinity, 0,
2939     "Number of hz ticks to keep thread affinity for");
2940 SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0,
2941     "Enables the long-term load balancer");
2942 SYSCTL_INT(_kern_sched, OID_AUTO, balance_interval, CTLFLAG_RW,
2943     &balance_interval, 0,
2944     "Average period in stathz ticks to run the long-term balancer");
2945 SYSCTL_INT(_kern_sched, OID_AUTO, steal_idle, CTLFLAG_RW, &steal_idle, 0,
2946     "Attempts to steal work from other cores before idling");
2947 SYSCTL_INT(_kern_sched, OID_AUTO, steal_thresh, CTLFLAG_RW, &steal_thresh, 0,
2948     "Minimum load on remote CPU before we'll steal");
2949 SYSCTL_PROC(_kern_sched, OID_AUTO, topology_spec, CTLTYPE_STRING |
2950     CTLFLAG_MPSAFE | CTLFLAG_RD, NULL, 0, sysctl_kern_sched_topology_spec, "A",
2951     "XML dump of detected CPU topology");
2952 #endif
2953 
2954 /* ps compat.  All cpu percentages from ULE are weighted. */
2955 static int ccpu = 0;
2956 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2957