xref: /freebsd/sys/kern/sched_ule.c (revision dda713dfb8db17ba96a6c9d184b766a5be3d6e37)
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 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include "opt_hwpmc_hooks.h"
31 #include "opt_sched.h"
32 
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/kdb.h>
36 #include <sys/kernel.h>
37 #include <sys/ktr.h>
38 #include <sys/lock.h>
39 #include <sys/mutex.h>
40 #include <sys/proc.h>
41 #include <sys/resource.h>
42 #include <sys/resourcevar.h>
43 #include <sys/sched.h>
44 #include <sys/smp.h>
45 #include <sys/sx.h>
46 #include <sys/sysctl.h>
47 #include <sys/sysproto.h>
48 #include <sys/turnstile.h>
49 #include <sys/umtx.h>
50 #include <sys/vmmeter.h>
51 #ifdef KTRACE
52 #include <sys/uio.h>
53 #include <sys/ktrace.h>
54 #endif
55 
56 #ifdef HWPMC_HOOKS
57 #include <sys/pmckern.h>
58 #endif
59 
60 #include <machine/cpu.h>
61 #include <machine/smp.h>
62 
63 #ifndef PREEMPTION
64 #error	"SCHED_ULE requires options PREEMPTION"
65 #endif
66 
67 /*
68  * TODO:
69  *	Pick idle from affinity group or self group first.
70  *	Implement pick_score.
71  */
72 
73 #define	KTR_ULE	0x0		/* Enable for pickpri debugging. */
74 
75 /*
76  * Thread scheduler specific section.
77  */
78 struct td_sched {
79 	TAILQ_ENTRY(td_sched) ts_procq;	/* (j/z) Run queue. */
80 	int		ts_flags;	/* (j) TSF_* flags. */
81 	struct thread	*ts_thread;	/* (*) Active associated thread. */
82 	u_char		ts_rqindex;	/* (j) Run queue index. */
83 	int		ts_slptime;
84 	int		ts_slice;
85 	struct runq	*ts_runq;
86 	u_char		ts_cpu;		/* CPU that we have affinity for. */
87 	/* The following variables are only used for pctcpu calculation */
88 	int		ts_ltick;	/* Last tick that we were running on */
89 	int		ts_ftick;	/* First tick that we were running on */
90 	int		ts_ticks;	/* Tick count */
91 #ifdef SMP
92 	int		ts_rltick;	/* Real last tick, for affinity. */
93 #endif
94 
95 	/* originally from kg_sched */
96 	u_int	skg_slptime;		/* Number of ticks we vol. slept */
97 	u_int	skg_runtime;		/* Number of ticks we were running */
98 };
99 /* flags kept in ts_flags */
100 #define	TSF_BOUND	0x0001		/* Thread can not migrate. */
101 #define	TSF_XFERABLE	0x0002		/* Thread was added as transferable. */
102 
103 static struct td_sched td_sched0;
104 
105 /*
106  * Cpu percentage computation macros and defines.
107  *
108  * SCHED_TICK_SECS:	Number of seconds to average the cpu usage across.
109  * SCHED_TICK_TARG:	Number of hz ticks to average the cpu usage across.
110  * SCHED_TICK_MAX:	Maximum number of ticks before scaling back.
111  * SCHED_TICK_SHIFT:	Shift factor to avoid rounding away results.
112  * SCHED_TICK_HZ:	Compute the number of hz ticks for a given ticks count.
113  * SCHED_TICK_TOTAL:	Gives the amount of time we've been recording ticks.
114  */
115 #define	SCHED_TICK_SECS		10
116 #define	SCHED_TICK_TARG		(hz * SCHED_TICK_SECS)
117 #define	SCHED_TICK_MAX		(SCHED_TICK_TARG + hz)
118 #define	SCHED_TICK_SHIFT	10
119 #define	SCHED_TICK_HZ(ts)	((ts)->ts_ticks >> SCHED_TICK_SHIFT)
120 #define	SCHED_TICK_TOTAL(ts)	(max((ts)->ts_ltick - (ts)->ts_ftick, hz))
121 
122 /*
123  * These macros determine priorities for non-interactive threads.  They are
124  * assigned a priority based on their recent cpu utilization as expressed
125  * by the ratio of ticks to the tick total.  NHALF priorities at the start
126  * and end of the MIN to MAX timeshare range are only reachable with negative
127  * or positive nice respectively.
128  *
129  * PRI_RANGE:	Priority range for utilization dependent priorities.
130  * PRI_NRESV:	Number of nice values.
131  * PRI_TICKS:	Compute a priority in PRI_RANGE from the ticks count and total.
132  * PRI_NICE:	Determines the part of the priority inherited from nice.
133  */
134 #define	SCHED_PRI_NRESV		(PRIO_MAX - PRIO_MIN)
135 #define	SCHED_PRI_NHALF		(SCHED_PRI_NRESV / 2)
136 #define	SCHED_PRI_MIN		(PRI_MIN_TIMESHARE + SCHED_PRI_NHALF)
137 #define	SCHED_PRI_MAX		(PRI_MAX_TIMESHARE - SCHED_PRI_NHALF)
138 #define	SCHED_PRI_RANGE		(SCHED_PRI_MAX - SCHED_PRI_MIN)
139 #define	SCHED_PRI_TICKS(ts)						\
140     (SCHED_TICK_HZ((ts)) /						\
141     (roundup(SCHED_TICK_TOTAL((ts)), SCHED_PRI_RANGE) / SCHED_PRI_RANGE))
142 #define	SCHED_PRI_NICE(nice)	(nice)
143 
144 /*
145  * These determine the interactivity of a process.  Interactivity differs from
146  * cpu utilization in that it expresses the voluntary time slept vs time ran
147  * while cpu utilization includes all time not running.  This more accurately
148  * models the intent of the thread.
149  *
150  * SLP_RUN_MAX:	Maximum amount of sleep time + run time we'll accumulate
151  *		before throttling back.
152  * SLP_RUN_FORK:	Maximum slp+run time to inherit at fork time.
153  * INTERACT_MAX:	Maximum interactivity value.  Smaller is better.
154  * INTERACT_THRESH:	Threshhold for placement on the current runq.
155  */
156 #define	SCHED_SLP_RUN_MAX	((hz * 5) << SCHED_TICK_SHIFT)
157 #define	SCHED_SLP_RUN_FORK	((hz / 2) << SCHED_TICK_SHIFT)
158 #define	SCHED_INTERACT_MAX	(100)
159 #define	SCHED_INTERACT_HALF	(SCHED_INTERACT_MAX / 2)
160 #define	SCHED_INTERACT_THRESH	(30)
161 
162 /*
163  * tickincr:		Converts a stathz tick into a hz domain scaled by
164  *			the shift factor.  Without the shift the error rate
165  *			due to rounding would be unacceptably high.
166  * realstathz:		stathz is sometimes 0 and run off of hz.
167  * sched_slice:		Runtime of each thread before rescheduling.
168  */
169 static int sched_interact = SCHED_INTERACT_THRESH;
170 static int realstathz;
171 static int tickincr;
172 static int sched_slice;
173 
174 /*
175  * tdq - per processor runqs and statistics.
176  */
177 struct tdq {
178 	struct runq	tdq_idle;		/* Queue of IDLE threads. */
179 	struct runq	tdq_timeshare;		/* timeshare run queue. */
180 	struct runq	tdq_realtime;		/* real-time run queue. */
181 	u_char		tdq_idx;		/* Current insert index. */
182 	u_char		tdq_ridx;		/* Current removal index. */
183 	short		tdq_flags;		/* Thread queue flags */
184 	int		tdq_load;		/* Aggregate load. */
185 #ifdef SMP
186 	int		tdq_transferable;
187 	LIST_ENTRY(tdq)	tdq_siblings;		/* Next in tdq group. */
188 	struct tdq_group *tdq_group;		/* Our processor group. */
189 #else
190 	int		tdq_sysload;		/* For loadavg, !ITHD load. */
191 #endif
192 };
193 
194 #define	TDQF_BUSY	0x0001			/* Queue is marked as busy */
195 
196 #ifdef SMP
197 /*
198  * tdq groups are groups of processors which can cheaply share threads.  When
199  * one processor in the group goes idle it will check the runqs of the other
200  * processors in its group prior to halting and waiting for an interrupt.
201  * These groups are suitable for SMT (Symetric Multi-Threading) and not NUMA.
202  * In a numa environment we'd want an idle bitmap per group and a two tiered
203  * load balancer.
204  */
205 struct tdq_group {
206 	int	tdg_cpus;		/* Count of CPUs in this tdq group. */
207 	cpumask_t tdg_cpumask;		/* Mask of cpus in this group. */
208 	cpumask_t tdg_idlemask;		/* Idle cpus in this group. */
209 	cpumask_t tdg_mask;		/* Bit mask for first cpu. */
210 	int	tdg_load;		/* Total load of this group. */
211 	int	tdg_transferable;	/* Transferable load of this group. */
212 	LIST_HEAD(, tdq) tdg_members;	/* Linked list of all members. */
213 };
214 
215 #define	SCHED_AFFINITY_DEFAULT	(hz / 100)
216 #define	SCHED_AFFINITY(ts)	((ts)->ts_rltick > ticks - affinity)
217 
218 /*
219  * Run-time tunables.
220  */
221 static int rebalance = 0;
222 static int pick_pri = 0;
223 static int affinity;
224 static int tryself = 1;
225 static int tryselfidle = 1;
226 static int ipi_ast = 0;
227 static int ipi_preempt = 1;
228 static int ipi_thresh = PRI_MIN_KERN;
229 static int steal_htt = 1;
230 static int steal_busy = 1;
231 static int busy_thresh = 4;
232 static int topology = 0;
233 
234 /*
235  * One thread queue per processor.
236  */
237 static volatile cpumask_t tdq_idle;
238 static volatile cpumask_t tdq_busy;
239 static int tdg_maxid;
240 static struct tdq	tdq_cpu[MAXCPU];
241 static struct tdq_group tdq_groups[MAXCPU];
242 static int bal_tick;
243 static int gbal_tick;
244 static int balance_groups;
245 
246 #define	TDQ_SELF()	(&tdq_cpu[PCPU_GET(cpuid)])
247 #define	TDQ_CPU(x)	(&tdq_cpu[(x)])
248 #define	TDQ_ID(x)	((x) - tdq_cpu)
249 #define	TDQ_GROUP(x)	(&tdq_groups[(x)])
250 #else	/* !SMP */
251 static struct tdq	tdq_cpu;
252 
253 #define	TDQ_ID(x)	(0)
254 #define	TDQ_SELF()	(&tdq_cpu)
255 #define	TDQ_CPU(x)	(&tdq_cpu)
256 #endif
257 
258 static void sched_priority(struct thread *);
259 static void sched_thread_priority(struct thread *, u_char);
260 static int sched_interact_score(struct thread *);
261 static void sched_interact_update(struct thread *);
262 static void sched_interact_fork(struct thread *);
263 static void sched_pctcpu_update(struct td_sched *);
264 static inline void sched_pin_td(struct thread *td);
265 static inline void sched_unpin_td(struct thread *td);
266 
267 /* Operations on per processor queues */
268 static struct td_sched * tdq_choose(struct tdq *);
269 static void tdq_setup(struct tdq *);
270 static void tdq_load_add(struct tdq *, struct td_sched *);
271 static void tdq_load_rem(struct tdq *, struct td_sched *);
272 static __inline void tdq_runq_add(struct tdq *, struct td_sched *, int);
273 static __inline void tdq_runq_rem(struct tdq *, struct td_sched *);
274 void tdq_print(int cpu);
275 static void runq_print(struct runq *rq);
276 #ifdef SMP
277 static int tdq_pickidle(struct tdq *, struct td_sched *);
278 static int tdq_pickpri(struct tdq *, struct td_sched *, int);
279 static struct td_sched *runq_steal(struct runq *);
280 static void sched_balance(void);
281 static void sched_balance_groups(void);
282 static void sched_balance_group(struct tdq_group *);
283 static void sched_balance_pair(struct tdq *, struct tdq *);
284 static void sched_smp_tick(struct thread *);
285 static void tdq_move(struct tdq *, int);
286 static int tdq_idled(struct tdq *);
287 static void tdq_notify(struct td_sched *);
288 static struct td_sched *tdq_steal(struct tdq *, int);
289 
290 #define	THREAD_CAN_MIGRATE(td)	 ((td)->td_pinned == 0)
291 #endif
292 
293 static void sched_setup(void *dummy);
294 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
295 
296 static void sched_initticks(void *dummy);
297 SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks, NULL)
298 
299 static inline void
300 sched_pin_td(struct thread *td)
301 {
302 	td->td_pinned++;
303 }
304 
305 static inline void
306 sched_unpin_td(struct thread *td)
307 {
308 	td->td_pinned--;
309 }
310 
311 static void
312 runq_print(struct runq *rq)
313 {
314 	struct rqhead *rqh;
315 	struct td_sched *ts;
316 	int pri;
317 	int j;
318 	int i;
319 
320 	for (i = 0; i < RQB_LEN; i++) {
321 		printf("\t\trunq bits %d 0x%zx\n",
322 		    i, rq->rq_status.rqb_bits[i]);
323 		for (j = 0; j < RQB_BPW; j++)
324 			if (rq->rq_status.rqb_bits[i] & (1ul << j)) {
325 				pri = j + (i << RQB_L2BPW);
326 				rqh = &rq->rq_queues[pri];
327 				TAILQ_FOREACH(ts, rqh, ts_procq) {
328 					printf("\t\t\ttd %p(%s) priority %d rqindex %d pri %d\n",
329 					    ts->ts_thread, ts->ts_thread->td_proc->p_comm, ts->ts_thread->td_priority, ts->ts_rqindex, pri);
330 				}
331 			}
332 	}
333 }
334 
335 void
336 tdq_print(int cpu)
337 {
338 	struct tdq *tdq;
339 
340 	tdq = TDQ_CPU(cpu);
341 
342 	printf("tdq:\n");
343 	printf("\tload:           %d\n", tdq->tdq_load);
344 	printf("\ttimeshare idx: %d\n", tdq->tdq_idx);
345 	printf("\ttimeshare ridx: %d\n", tdq->tdq_ridx);
346 	printf("\trealtime runq:\n");
347 	runq_print(&tdq->tdq_realtime);
348 	printf("\ttimeshare runq:\n");
349 	runq_print(&tdq->tdq_timeshare);
350 	printf("\tidle runq:\n");
351 	runq_print(&tdq->tdq_idle);
352 #ifdef SMP
353 	printf("\tload transferable: %d\n", tdq->tdq_transferable);
354 #endif
355 }
356 
357 static __inline void
358 tdq_runq_add(struct tdq *tdq, struct td_sched *ts, int flags)
359 {
360 #ifdef SMP
361 	if (THREAD_CAN_MIGRATE(ts->ts_thread)) {
362 		tdq->tdq_transferable++;
363 		tdq->tdq_group->tdg_transferable++;
364 		ts->ts_flags |= TSF_XFERABLE;
365 		if (tdq->tdq_transferable >= busy_thresh &&
366 		    (tdq->tdq_flags & TDQF_BUSY) == 0) {
367 			tdq->tdq_flags |= TDQF_BUSY;
368 			atomic_set_int(&tdq_busy, 1 << TDQ_ID(tdq));
369 		}
370 	}
371 #endif
372 	if (ts->ts_runq == &tdq->tdq_timeshare) {
373 		u_char pri;
374 
375 		pri = ts->ts_thread->td_priority;
376 		KASSERT(pri <= PRI_MAX_TIMESHARE && pri >= PRI_MIN_TIMESHARE,
377 			("Invalid priority %d on timeshare runq", pri));
378 		/*
379 		 * This queue contains only priorities between MIN and MAX
380 		 * realtime.  Use the whole queue to represent these values.
381 		 */
382 #define	TS_RQ_PPQ	(((PRI_MAX_TIMESHARE - PRI_MIN_TIMESHARE) + 1) / RQ_NQS)
383 		if ((flags & SRQ_BORROWING) == 0) {
384 			pri = (pri - PRI_MIN_TIMESHARE) / TS_RQ_PPQ;
385 			pri = (pri + tdq->tdq_idx) % RQ_NQS;
386 			/*
387 			 * This effectively shortens the queue by one so we
388 			 * can have a one slot difference between idx and
389 			 * ridx while we wait for threads to drain.
390 			 */
391 			if (tdq->tdq_ridx != tdq->tdq_idx &&
392 			    pri == tdq->tdq_ridx)
393 				pri = (unsigned char)(pri - 1) % RQ_NQS;
394 		} else
395 			pri = tdq->tdq_ridx;
396 		runq_add_pri(ts->ts_runq, ts, pri, flags);
397 	} else
398 		runq_add(ts->ts_runq, ts, flags);
399 }
400 
401 static __inline void
402 tdq_runq_rem(struct tdq *tdq, struct td_sched *ts)
403 {
404 #ifdef SMP
405 	if (ts->ts_flags & TSF_XFERABLE) {
406 		tdq->tdq_transferable--;
407 		tdq->tdq_group->tdg_transferable--;
408 		ts->ts_flags &= ~TSF_XFERABLE;
409 		if (tdq->tdq_transferable < busy_thresh &&
410 		    (tdq->tdq_flags & TDQF_BUSY)) {
411 			atomic_clear_int(&tdq_busy, 1 << TDQ_ID(tdq));
412 			tdq->tdq_flags &= ~TDQF_BUSY;
413 		}
414 	}
415 #endif
416 	if (ts->ts_runq == &tdq->tdq_timeshare) {
417 		if (tdq->tdq_idx != tdq->tdq_ridx)
418 			runq_remove_idx(ts->ts_runq, ts, &tdq->tdq_ridx);
419 		else
420 			runq_remove_idx(ts->ts_runq, ts, NULL);
421 		/*
422 		 * For timeshare threads we update the priority here so
423 		 * the priority reflects the time we've been sleeping.
424 		 */
425 		ts->ts_ltick = ticks;
426 		sched_pctcpu_update(ts);
427 		sched_priority(ts->ts_thread);
428 	} else
429 		runq_remove(ts->ts_runq, ts);
430 }
431 
432 static void
433 tdq_load_add(struct tdq *tdq, struct td_sched *ts)
434 {
435 	int class;
436 	mtx_assert(&sched_lock, MA_OWNED);
437 	class = PRI_BASE(ts->ts_thread->td_pri_class);
438 	tdq->tdq_load++;
439 	CTR2(KTR_SCHED, "cpu %jd load: %d", TDQ_ID(tdq), tdq->tdq_load);
440 	if (class != PRI_ITHD &&
441 	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
442 #ifdef SMP
443 		tdq->tdq_group->tdg_load++;
444 #else
445 		tdq->tdq_sysload++;
446 #endif
447 }
448 
449 static void
450 tdq_load_rem(struct tdq *tdq, struct td_sched *ts)
451 {
452 	int class;
453 	mtx_assert(&sched_lock, MA_OWNED);
454 	class = PRI_BASE(ts->ts_thread->td_pri_class);
455 	if (class != PRI_ITHD &&
456 	    (ts->ts_thread->td_proc->p_flag & P_NOLOAD) == 0)
457 #ifdef SMP
458 		tdq->tdq_group->tdg_load--;
459 #else
460 		tdq->tdq_sysload--;
461 #endif
462 	tdq->tdq_load--;
463 	CTR1(KTR_SCHED, "load: %d", tdq->tdq_load);
464 	ts->ts_runq = NULL;
465 }
466 
467 #ifdef SMP
468 static void
469 sched_smp_tick(struct thread *td)
470 {
471 	struct tdq *tdq;
472 
473 	tdq = TDQ_SELF();
474 	if (rebalance) {
475 		if (ticks >= bal_tick)
476 			sched_balance();
477 		if (ticks >= gbal_tick && balance_groups)
478 			sched_balance_groups();
479 	}
480 	td->td_sched->ts_rltick = ticks;
481 }
482 
483 /*
484  * sched_balance is a simple CPU load balancing algorithm.  It operates by
485  * finding the least loaded and most loaded cpu and equalizing their load
486  * by migrating some processes.
487  *
488  * Dealing only with two CPUs at a time has two advantages.  Firstly, most
489  * installations will only have 2 cpus.  Secondly, load balancing too much at
490  * once can have an unpleasant effect on the system.  The scheduler rarely has
491  * enough information to make perfect decisions.  So this algorithm chooses
492  * algorithm simplicity and more gradual effects on load in larger systems.
493  *
494  * It could be improved by considering the priorities and slices assigned to
495  * each task prior to balancing them.  There are many pathological cases with
496  * any approach and so the semi random algorithm below may work as well as any.
497  *
498  */
499 static void
500 sched_balance(void)
501 {
502 	struct tdq_group *high;
503 	struct tdq_group *low;
504 	struct tdq_group *tdg;
505 	int cnt;
506 	int i;
507 
508 	bal_tick = ticks + (random() % (hz * 2));
509 	if (smp_started == 0)
510 		return;
511 	low = high = NULL;
512 	i = random() % (tdg_maxid + 1);
513 	for (cnt = 0; cnt <= tdg_maxid; cnt++) {
514 		tdg = TDQ_GROUP(i);
515 		/*
516 		 * Find the CPU with the highest load that has some
517 		 * threads to transfer.
518 		 */
519 		if ((high == NULL || tdg->tdg_load > high->tdg_load)
520 		    && tdg->tdg_transferable)
521 			high = tdg;
522 		if (low == NULL || tdg->tdg_load < low->tdg_load)
523 			low = tdg;
524 		if (++i > tdg_maxid)
525 			i = 0;
526 	}
527 	if (low != NULL && high != NULL && high != low)
528 		sched_balance_pair(LIST_FIRST(&high->tdg_members),
529 		    LIST_FIRST(&low->tdg_members));
530 }
531 
532 static void
533 sched_balance_groups(void)
534 {
535 	int i;
536 
537 	gbal_tick = ticks + (random() % (hz * 2));
538 	mtx_assert(&sched_lock, MA_OWNED);
539 	if (smp_started)
540 		for (i = 0; i <= tdg_maxid; i++)
541 			sched_balance_group(TDQ_GROUP(i));
542 }
543 
544 static void
545 sched_balance_group(struct tdq_group *tdg)
546 {
547 	struct tdq *tdq;
548 	struct tdq *high;
549 	struct tdq *low;
550 	int load;
551 
552 	if (tdg->tdg_transferable == 0)
553 		return;
554 	low = NULL;
555 	high = NULL;
556 	LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
557 		load = tdq->tdq_load;
558 		if (high == NULL || load > high->tdq_load)
559 			high = tdq;
560 		if (low == NULL || load < low->tdq_load)
561 			low = tdq;
562 	}
563 	if (high != NULL && low != NULL && high != low)
564 		sched_balance_pair(high, low);
565 }
566 
567 static void
568 sched_balance_pair(struct tdq *high, struct tdq *low)
569 {
570 	int transferable;
571 	int high_load;
572 	int low_load;
573 	int move;
574 	int diff;
575 	int i;
576 
577 	/*
578 	 * If we're transfering within a group we have to use this specific
579 	 * tdq's transferable count, otherwise we can steal from other members
580 	 * of the group.
581 	 */
582 	if (high->tdq_group == low->tdq_group) {
583 		transferable = high->tdq_transferable;
584 		high_load = high->tdq_load;
585 		low_load = low->tdq_load;
586 	} else {
587 		transferable = high->tdq_group->tdg_transferable;
588 		high_load = high->tdq_group->tdg_load;
589 		low_load = low->tdq_group->tdg_load;
590 	}
591 	if (transferable == 0)
592 		return;
593 	/*
594 	 * Determine what the imbalance is and then adjust that to how many
595 	 * threads we actually have to give up (transferable).
596 	 */
597 	diff = high_load - low_load;
598 	move = diff / 2;
599 	if (diff & 0x1)
600 		move++;
601 	move = min(move, transferable);
602 	for (i = 0; i < move; i++)
603 		tdq_move(high, TDQ_ID(low));
604 	return;
605 }
606 
607 static void
608 tdq_move(struct tdq *from, int cpu)
609 {
610 	struct tdq *tdq;
611 	struct tdq *to;
612 	struct td_sched *ts;
613 
614 	tdq = from;
615 	to = TDQ_CPU(cpu);
616 	ts = tdq_steal(tdq, 1);
617 	if (ts == NULL) {
618 		struct tdq_group *tdg;
619 
620 		tdg = tdq->tdq_group;
621 		LIST_FOREACH(tdq, &tdg->tdg_members, tdq_siblings) {
622 			if (tdq == from || tdq->tdq_transferable == 0)
623 				continue;
624 			ts = tdq_steal(tdq, 1);
625 			break;
626 		}
627 		if (ts == NULL)
628 			panic("tdq_move: No threads available with a "
629 			    "transferable count of %d\n",
630 			    tdg->tdg_transferable);
631 	}
632 	if (tdq == to)
633 		return;
634 	sched_rem(ts->ts_thread);
635 	ts->ts_cpu = cpu;
636 	sched_pin_td(ts->ts_thread);
637 	sched_add(ts->ts_thread, SRQ_YIELDING);
638 	sched_unpin_td(ts->ts_thread);
639 }
640 
641 static int
642 tdq_idled(struct tdq *tdq)
643 {
644 	struct tdq_group *tdg;
645 	struct tdq *steal;
646 	struct td_sched *ts;
647 
648 	tdg = tdq->tdq_group;
649 	/*
650 	 * If we're in a cpu group, try and steal threads from another cpu in
651 	 * the group before idling.
652 	 */
653 	if (steal_htt && tdg->tdg_cpus > 1 && tdg->tdg_transferable) {
654 		LIST_FOREACH(steal, &tdg->tdg_members, tdq_siblings) {
655 			if (steal == tdq || steal->tdq_transferable == 0)
656 				continue;
657 			ts = tdq_steal(steal, 0);
658 			if (ts)
659 				goto steal;
660 		}
661 	}
662 	if (steal_busy) {
663 		while (tdq_busy) {
664 			int cpu;
665 
666 			cpu = ffs(tdq_busy);
667 			if (cpu == 0)
668 				break;
669 			cpu--;
670 			steal = TDQ_CPU(cpu);
671 			if (steal->tdq_transferable == 0)
672 				continue;
673 			ts = tdq_steal(steal, 1);
674 			if (ts == NULL)
675 				continue;
676 			CTR5(KTR_ULE,
677 			    "tdq_idled: stealing td %p(%s) pri %d from %d busy 0x%X",
678 			    ts->ts_thread, ts->ts_thread->td_proc->p_comm,
679 			    ts->ts_thread->td_priority, cpu, tdq_busy);
680 			goto steal;
681 		}
682 	}
683 	/*
684 	 * We only set the idled bit when all of the cpus in the group are
685 	 * idle.  Otherwise we could get into a situation where a thread bounces
686 	 * back and forth between two idle cores on seperate physical CPUs.
687 	 */
688 	tdg->tdg_idlemask |= PCPU_GET(cpumask);
689 	if (tdg->tdg_idlemask == tdg->tdg_cpumask)
690 		atomic_set_int(&tdq_idle, tdg->tdg_mask);
691 	return (1);
692 steal:
693 	sched_rem(ts->ts_thread);
694 	ts->ts_cpu = PCPU_GET(cpuid);
695 	sched_pin_td(ts->ts_thread);
696 	sched_add(ts->ts_thread, SRQ_YIELDING);
697 	sched_unpin_td(ts->ts_thread);
698 
699 	return (0);
700 }
701 
702 static void
703 tdq_notify(struct td_sched *ts)
704 {
705 	struct thread *ctd;
706 	struct pcpu *pcpu;
707 	int cpri;
708 	int pri;
709 	int cpu;
710 
711 	cpu = ts->ts_cpu;
712 	pri = ts->ts_thread->td_priority;
713 	pcpu = pcpu_find(cpu);
714 	ctd = pcpu->pc_curthread;
715 	cpri = ctd->td_priority;
716 
717 	/*
718 	 * If our priority is not better than the current priority there is
719 	 * nothing to do.
720 	 */
721 	if (pri > cpri)
722 		return;
723 	/*
724 	 * Always IPI idle.
725 	 */
726 	if (cpri > PRI_MIN_IDLE)
727 		goto sendipi;
728 	/*
729 	 * If we're realtime or better and there is timeshare or worse running
730 	 * send an IPI.
731 	 */
732 	if (pri < PRI_MAX_REALTIME && cpri > PRI_MAX_REALTIME)
733 		goto sendipi;
734 	/*
735 	 * Otherwise only IPI if we exceed the threshold.
736 	 */
737 	if (pri > ipi_thresh)
738 		return;
739 sendipi:
740 	ctd->td_flags |= TDF_NEEDRESCHED;
741 	if (cpri < PRI_MIN_IDLE) {
742 		if (ipi_ast)
743 			ipi_selected(1 << cpu, IPI_AST);
744 		else if (ipi_preempt)
745 			ipi_selected(1 << cpu, IPI_PREEMPT);
746 	} else
747 		ipi_selected(1 << cpu, IPI_PREEMPT);
748 }
749 
750 static struct td_sched *
751 runq_steal(struct runq *rq)
752 {
753 	struct rqhead *rqh;
754 	struct rqbits *rqb;
755 	struct td_sched *ts;
756 	int word;
757 	int bit;
758 
759 	mtx_assert(&sched_lock, MA_OWNED);
760 	rqb = &rq->rq_status;
761 	for (word = 0; word < RQB_LEN; word++) {
762 		if (rqb->rqb_bits[word] == 0)
763 			continue;
764 		for (bit = 0; bit < RQB_BPW; bit++) {
765 			if ((rqb->rqb_bits[word] & (1ul << bit)) == 0)
766 				continue;
767 			rqh = &rq->rq_queues[bit + (word << RQB_L2BPW)];
768 			TAILQ_FOREACH(ts, rqh, ts_procq) {
769 				if (THREAD_CAN_MIGRATE(ts->ts_thread))
770 					return (ts);
771 			}
772 		}
773 	}
774 	return (NULL);
775 }
776 
777 static struct td_sched *
778 tdq_steal(struct tdq *tdq, int stealidle)
779 {
780 	struct td_sched *ts;
781 
782 	/*
783 	 * Steal from next first to try to get a non-interactive task that
784 	 * may not have run for a while.
785 	 * XXX Need to effect steal order for timeshare threads.
786 	 */
787 	if ((ts = runq_steal(&tdq->tdq_realtime)) != NULL)
788 		return (ts);
789 	if ((ts = runq_steal(&tdq->tdq_timeshare)) != NULL)
790 		return (ts);
791 	if (stealidle)
792 		return (runq_steal(&tdq->tdq_idle));
793 	return (NULL);
794 }
795 
796 int
797 tdq_pickidle(struct tdq *tdq, struct td_sched *ts)
798 {
799 	struct tdq_group *tdg;
800 	int self;
801 	int cpu;
802 
803 	self = PCPU_GET(cpuid);
804 	if (smp_started == 0)
805 		return (self);
806 	/*
807 	 * If the current CPU has idled, just run it here.
808 	 */
809 	if ((tdq->tdq_group->tdg_idlemask & PCPU_GET(cpumask)) != 0)
810 		return (self);
811 	/*
812 	 * Try the last group we ran on.
813 	 */
814 	tdg = TDQ_CPU(ts->ts_cpu)->tdq_group;
815 	cpu = ffs(tdg->tdg_idlemask);
816 	if (cpu)
817 		return (cpu - 1);
818 	/*
819 	 * Search for an idle group.
820 	 */
821 	cpu = ffs(tdq_idle);
822 	if (cpu)
823 		return (cpu - 1);
824 	/*
825 	 * XXX If there are no idle groups, check for an idle core.
826 	 */
827 	/*
828 	 * No idle CPUs?
829 	 */
830 	return (self);
831 }
832 
833 static int
834 tdq_pickpri(struct tdq *tdq, struct td_sched *ts, int flags)
835 {
836 	struct pcpu *pcpu;
837 	int lowpri;
838 	int lowcpu;
839 	int lowload;
840 	int load;
841 	int self;
842 	int pri;
843 	int cpu;
844 
845 	self = PCPU_GET(cpuid);
846 	if (smp_started == 0)
847 		return (self);
848 
849 	pri = ts->ts_thread->td_priority;
850 	/*
851 	 * Regardless of affinity, if the last cpu is idle send it there.
852 	 */
853 	pcpu = pcpu_find(ts->ts_cpu);
854 	if (pcpu->pc_curthread->td_priority > PRI_MIN_IDLE) {
855 		CTR5(KTR_ULE,
856 		    "ts_cpu %d idle, ltick %d ticks %d pri %d curthread %d",
857 		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
858 		    pcpu->pc_curthread->td_priority);
859 		return (ts->ts_cpu);
860 	}
861 	/*
862 	 * If we have affinity, try to place it on the cpu we last ran on.
863 	 */
864 	if (SCHED_AFFINITY(ts) && pcpu->pc_curthread->td_priority > pri) {
865 		CTR5(KTR_ULE,
866 		    "affinity for %d, ltick %d ticks %d pri %d curthread %d",
867 		    ts->ts_cpu, ts->ts_rltick, ticks, pri,
868 		    pcpu->pc_curthread->td_priority);
869 		return (ts->ts_cpu);
870 	}
871 	/*
872 	 * Try ourself first; If we're running something lower priority this
873 	 * may have some locality with the waking thread and execute faster
874 	 * here.
875 	 */
876 	if (tryself) {
877 		/*
878 		 * If we're being awoken by an interrupt thread or the waker
879 		 * is going right to sleep run here as well.
880 		 */
881 		if ((TDQ_SELF()->tdq_load == 1) && (flags & SRQ_YIELDING ||
882 		    curthread->td_pri_class == PRI_ITHD)) {
883 			CTR2(KTR_ULE, "tryself load %d flags %d",
884 			    TDQ_SELF()->tdq_load, flags);
885 			return (self);
886 		}
887 	}
888 	/*
889 	 * Look for an idle group.
890 	 */
891 	CTR1(KTR_ULE, "tdq_idle %X", tdq_idle);
892 	cpu = ffs(tdq_idle);
893 	if (cpu)
894 		return (cpu - 1);
895 	if (tryselfidle && pri < curthread->td_priority) {
896 		CTR1(KTR_ULE, "tryself %d",
897 		    curthread->td_priority);
898 		return (self);
899 	}
900 	/*
901  	 * Now search for the cpu running the lowest priority thread with
902 	 * the least load.
903 	 */
904 	lowload = 0;
905 	lowpri = lowcpu = 0;
906 	for (cpu = 0; cpu <= mp_maxid; cpu++) {
907 		if (CPU_ABSENT(cpu))
908 			continue;
909 		pcpu = pcpu_find(cpu);
910 		pri = pcpu->pc_curthread->td_priority;
911 		CTR4(KTR_ULE,
912 		    "cpu %d pri %d lowcpu %d lowpri %d",
913 		    cpu, pri, lowcpu, lowpri);
914 		if (pri < lowpri)
915 			continue;
916 		load = TDQ_CPU(cpu)->tdq_load;
917 		if (lowpri && lowpri == pri && load > lowload)
918 			continue;
919 		lowpri = pri;
920 		lowcpu = cpu;
921 		lowload = load;
922 	}
923 
924 	return (lowcpu);
925 }
926 
927 #endif	/* SMP */
928 
929 /*
930  * Pick the highest priority task we have and return it.
931  */
932 
933 static struct td_sched *
934 tdq_choose(struct tdq *tdq)
935 {
936 	struct td_sched *ts;
937 
938 	mtx_assert(&sched_lock, MA_OWNED);
939 
940 	ts = runq_choose(&tdq->tdq_realtime);
941 	if (ts != NULL)
942 		return (ts);
943 	ts = runq_choose_from(&tdq->tdq_timeshare, tdq->tdq_ridx);
944 	if (ts != NULL) {
945 		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_TIMESHARE,
946 		    ("tdq_choose: Invalid priority on timeshare queue %d",
947 		    ts->ts_thread->td_priority));
948 		return (ts);
949 	}
950 
951 	ts = runq_choose(&tdq->tdq_idle);
952 	if (ts != NULL) {
953 		KASSERT(ts->ts_thread->td_priority >= PRI_MIN_IDLE,
954 		    ("tdq_choose: Invalid priority on idle queue %d",
955 		    ts->ts_thread->td_priority));
956 		return (ts);
957 	}
958 
959 	return (NULL);
960 }
961 
962 static void
963 tdq_setup(struct tdq *tdq)
964 {
965 	runq_init(&tdq->tdq_realtime);
966 	runq_init(&tdq->tdq_timeshare);
967 	runq_init(&tdq->tdq_idle);
968 	tdq->tdq_load = 0;
969 }
970 
971 static void
972 sched_setup(void *dummy)
973 {
974 #ifdef SMP
975 	int i;
976 #endif
977 
978 	/*
979 	 * To avoid divide-by-zero, we set realstathz a dummy value
980 	 * in case which sched_clock() called before sched_initticks().
981 	 */
982 	realstathz = hz;
983 	sched_slice = (realstathz/10);	/* ~100ms */
984 	tickincr = 1 << SCHED_TICK_SHIFT;
985 
986 #ifdef SMP
987 	balance_groups = 0;
988 	/*
989 	 * Initialize the tdqs.
990 	 */
991 	for (i = 0; i < MAXCPU; i++) {
992 		struct tdq *tdq;
993 
994 		tdq = &tdq_cpu[i];
995 		tdq_setup(&tdq_cpu[i]);
996 	}
997 	if (smp_topology == NULL) {
998 		struct tdq_group *tdg;
999 		struct tdq *tdq;
1000 		int cpus;
1001 
1002 		for (cpus = 0, i = 0; i < MAXCPU; i++) {
1003 			if (CPU_ABSENT(i))
1004 				continue;
1005 			tdq = &tdq_cpu[i];
1006 			tdg = &tdq_groups[cpus];
1007 			/*
1008 			 * Setup a tdq group with one member.
1009 			 */
1010 			tdq->tdq_transferable = 0;
1011 			tdq->tdq_group = tdg;
1012 			tdg->tdg_cpus = 1;
1013 			tdg->tdg_idlemask = 0;
1014 			tdg->tdg_cpumask = tdg->tdg_mask = 1 << i;
1015 			tdg->tdg_load = 0;
1016 			tdg->tdg_transferable = 0;
1017 			LIST_INIT(&tdg->tdg_members);
1018 			LIST_INSERT_HEAD(&tdg->tdg_members, tdq, tdq_siblings);
1019 			cpus++;
1020 		}
1021 		tdg_maxid = cpus - 1;
1022 	} else {
1023 		struct tdq_group *tdg;
1024 		struct cpu_group *cg;
1025 		int j;
1026 
1027 		topology = 1;
1028 		for (i = 0; i < smp_topology->ct_count; i++) {
1029 			cg = &smp_topology->ct_group[i];
1030 			tdg = &tdq_groups[i];
1031 			/*
1032 			 * Initialize the group.
1033 			 */
1034 			tdg->tdg_idlemask = 0;
1035 			tdg->tdg_load = 0;
1036 			tdg->tdg_transferable = 0;
1037 			tdg->tdg_cpus = cg->cg_count;
1038 			tdg->tdg_cpumask = cg->cg_mask;
1039 			LIST_INIT(&tdg->tdg_members);
1040 			/*
1041 			 * Find all of the group members and add them.
1042 			 */
1043 			for (j = 0; j < MAXCPU; j++) {
1044 				if ((cg->cg_mask & (1 << j)) != 0) {
1045 					if (tdg->tdg_mask == 0)
1046 						tdg->tdg_mask = 1 << j;
1047 					tdq_cpu[j].tdq_transferable = 0;
1048 					tdq_cpu[j].tdq_group = tdg;
1049 					LIST_INSERT_HEAD(&tdg->tdg_members,
1050 					    &tdq_cpu[j], tdq_siblings);
1051 				}
1052 			}
1053 			if (tdg->tdg_cpus > 1)
1054 				balance_groups = 1;
1055 		}
1056 		tdg_maxid = smp_topology->ct_count - 1;
1057 	}
1058 	/*
1059 	 * Stagger the group and global load balancer so they do not
1060 	 * interfere with each other.
1061 	 */
1062 	bal_tick = ticks + hz;
1063 	if (balance_groups)
1064 		gbal_tick = ticks + (hz / 2);
1065 #else
1066 	tdq_setup(TDQ_SELF());
1067 #endif
1068 	mtx_lock_spin(&sched_lock);
1069 	tdq_load_add(TDQ_SELF(), &td_sched0);
1070 	mtx_unlock_spin(&sched_lock);
1071 }
1072 
1073 /* ARGSUSED */
1074 static void
1075 sched_initticks(void *dummy)
1076 {
1077 	mtx_lock_spin(&sched_lock);
1078 	realstathz = stathz ? stathz : hz;
1079 	sched_slice = (realstathz/10);	/* ~100ms */
1080 
1081 	/*
1082 	 * tickincr is shifted out by 10 to avoid rounding errors due to
1083 	 * hz not being evenly divisible by stathz on all platforms.
1084 	 */
1085 	tickincr = (hz << SCHED_TICK_SHIFT) / realstathz;
1086 	/*
1087 	 * This does not work for values of stathz that are more than
1088 	 * 1 << SCHED_TICK_SHIFT * hz.  In practice this does not happen.
1089 	 */
1090 	if (tickincr == 0)
1091 		tickincr = 1;
1092 #ifdef SMP
1093 	affinity = SCHED_AFFINITY_DEFAULT;
1094 #endif
1095 	mtx_unlock_spin(&sched_lock);
1096 }
1097 
1098 
1099 /*
1100  * Scale the scheduling priority according to the "interactivity" of this
1101  * process.
1102  */
1103 static void
1104 sched_priority(struct thread *td)
1105 {
1106 	int score;
1107 	int pri;
1108 
1109 	if (td->td_pri_class != PRI_TIMESHARE)
1110 		return;
1111 	/*
1112 	 * If the score is interactive we place the thread in the realtime
1113 	 * queue with a priority that is less than kernel and interrupt
1114 	 * priorities.  These threads are not subject to nice restrictions.
1115 	 *
1116 	 * Scores greater than this are placed on the normal realtime queue
1117 	 * where the priority is partially decided by the most recent cpu
1118 	 * utilization and the rest is decided by nice value.
1119 	 */
1120 	score = sched_interact_score(td);
1121 	if (score < sched_interact) {
1122 		pri = PRI_MIN_REALTIME;
1123 		pri += ((PRI_MAX_REALTIME - PRI_MIN_REALTIME) / sched_interact)
1124 		    * score;
1125 		KASSERT(pri >= PRI_MIN_REALTIME && pri <= PRI_MAX_REALTIME,
1126 		    ("sched_priority: invalid interactive priority %d score %d",
1127 		    pri, score));
1128 	} else {
1129 		pri = SCHED_PRI_MIN;
1130 		if (td->td_sched->ts_ticks)
1131 			pri += SCHED_PRI_TICKS(td->td_sched);
1132 		pri += SCHED_PRI_NICE(td->td_proc->p_nice);
1133 		if (!(pri >= PRI_MIN_TIMESHARE && pri <= PRI_MAX_TIMESHARE)) {
1134 			static int once = 1;
1135 			if (once) {
1136 				printf("sched_priority: invalid priority %d",
1137 				    pri);
1138 				printf("nice %d, ticks %d ftick %d ltick %d tick pri %d\n",
1139 				    td->td_proc->p_nice,
1140 				    td->td_sched->ts_ticks,
1141 				    td->td_sched->ts_ftick,
1142 				    td->td_sched->ts_ltick,
1143 				    SCHED_PRI_TICKS(td->td_sched));
1144 				once = 0;
1145 			}
1146 			pri = min(max(pri, PRI_MIN_TIMESHARE),
1147 			    PRI_MAX_TIMESHARE);
1148 		}
1149 	}
1150 	sched_user_prio(td, pri);
1151 
1152 	return;
1153 }
1154 
1155 /*
1156  * This routine enforces a maximum limit on the amount of scheduling history
1157  * kept.  It is called after either the slptime or runtime is adjusted.
1158  */
1159 static void
1160 sched_interact_update(struct thread *td)
1161 {
1162 	struct td_sched *ts;
1163 	u_int sum;
1164 
1165 	ts = td->td_sched;
1166 	sum = ts->skg_runtime + ts->skg_slptime;
1167 	if (sum < SCHED_SLP_RUN_MAX)
1168 		return;
1169 	/*
1170 	 * This only happens from two places:
1171 	 * 1) We have added an unusual amount of run time from fork_exit.
1172 	 * 2) We have added an unusual amount of sleep time from sched_sleep().
1173 	 */
1174 	if (sum > SCHED_SLP_RUN_MAX * 2) {
1175 		if (ts->skg_runtime > ts->skg_slptime) {
1176 			ts->skg_runtime = SCHED_SLP_RUN_MAX;
1177 			ts->skg_slptime = 1;
1178 		} else {
1179 			ts->skg_slptime = SCHED_SLP_RUN_MAX;
1180 			ts->skg_runtime = 1;
1181 		}
1182 		return;
1183 	}
1184 	/*
1185 	 * If we have exceeded by more than 1/5th then the algorithm below
1186 	 * will not bring us back into range.  Dividing by two here forces
1187 	 * us into the range of [4/5 * SCHED_INTERACT_MAX, SCHED_INTERACT_MAX]
1188 	 */
1189 	if (sum > (SCHED_SLP_RUN_MAX / 5) * 6) {
1190 		ts->skg_runtime /= 2;
1191 		ts->skg_slptime /= 2;
1192 		return;
1193 	}
1194 	ts->skg_runtime = (ts->skg_runtime / 5) * 4;
1195 	ts->skg_slptime = (ts->skg_slptime / 5) * 4;
1196 }
1197 
1198 static void
1199 sched_interact_fork(struct thread *td)
1200 {
1201 	int ratio;
1202 	int sum;
1203 
1204 	sum = td->td_sched->skg_runtime + td->td_sched->skg_slptime;
1205 	if (sum > SCHED_SLP_RUN_FORK) {
1206 		ratio = sum / SCHED_SLP_RUN_FORK;
1207 		td->td_sched->skg_runtime /= ratio;
1208 		td->td_sched->skg_slptime /= ratio;
1209 	}
1210 }
1211 
1212 static int
1213 sched_interact_score(struct thread *td)
1214 {
1215 	int div;
1216 
1217 	if (td->td_sched->skg_runtime > td->td_sched->skg_slptime) {
1218 		div = max(1, td->td_sched->skg_runtime / SCHED_INTERACT_HALF);
1219 		return (SCHED_INTERACT_HALF +
1220 		    (SCHED_INTERACT_HALF - (td->td_sched->skg_slptime / div)));
1221 	}
1222 	if (td->td_sched->skg_slptime > td->td_sched->skg_runtime) {
1223 		div = max(1, td->td_sched->skg_slptime / SCHED_INTERACT_HALF);
1224 		return (td->td_sched->skg_runtime / div);
1225 	}
1226 	/* runtime == slptime */
1227 	if (td->td_sched->skg_runtime)
1228 		return (SCHED_INTERACT_HALF);
1229 
1230 	/*
1231 	 * This can happen if slptime and runtime are 0.
1232 	 */
1233 	return (0);
1234 
1235 }
1236 
1237 /*
1238  * Called from proc0_init() to bootstrap the scheduler.
1239  */
1240 void
1241 schedinit(void)
1242 {
1243 
1244 	/*
1245 	 * Set up the scheduler specific parts of proc0.
1246 	 */
1247 	proc0.p_sched = NULL; /* XXX */
1248 	thread0.td_sched = &td_sched0;
1249 	thread0.td_lock = &sched_lock;
1250 	td_sched0.ts_ltick = ticks;
1251 	td_sched0.ts_ftick = ticks;
1252 	td_sched0.ts_thread = &thread0;
1253 }
1254 
1255 /*
1256  * This is only somewhat accurate since given many processes of the same
1257  * priority they will switch when their slices run out, which will be
1258  * at most sched_slice stathz ticks.
1259  */
1260 int
1261 sched_rr_interval(void)
1262 {
1263 
1264 	/* Convert sched_slice to hz */
1265 	return (hz/(realstathz/sched_slice));
1266 }
1267 
1268 static void
1269 sched_pctcpu_update(struct td_sched *ts)
1270 {
1271 
1272 	if (ts->ts_ticks == 0)
1273 		return;
1274 	if (ticks - (hz / 10) < ts->ts_ltick &&
1275 	    SCHED_TICK_TOTAL(ts) < SCHED_TICK_MAX)
1276 		return;
1277 	/*
1278 	 * Adjust counters and watermark for pctcpu calc.
1279 	 */
1280 	if (ts->ts_ltick > ticks - SCHED_TICK_TARG)
1281 		ts->ts_ticks = (ts->ts_ticks / (ticks - ts->ts_ftick)) *
1282 			    SCHED_TICK_TARG;
1283 	else
1284 		ts->ts_ticks = 0;
1285 	ts->ts_ltick = ticks;
1286 	ts->ts_ftick = ts->ts_ltick - SCHED_TICK_TARG;
1287 }
1288 
1289 static void
1290 sched_thread_priority(struct thread *td, u_char prio)
1291 {
1292 	struct td_sched *ts;
1293 
1294 	CTR6(KTR_SCHED, "sched_prio: %p(%s) prio %d newprio %d by %p(%s)",
1295 	    td, td->td_proc->p_comm, td->td_priority, prio, curthread,
1296 	    curthread->td_proc->p_comm);
1297 	ts = td->td_sched;
1298 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1299 	if (td->td_priority == prio)
1300 		return;
1301 
1302 	if (TD_ON_RUNQ(td) && prio < td->td_priority) {
1303 		/*
1304 		 * If the priority has been elevated due to priority
1305 		 * propagation, we may have to move ourselves to a new
1306 		 * queue.  This could be optimized to not re-add in some
1307 		 * cases.
1308 		 */
1309 		MPASS(td->td_lock == &sched_lock);
1310 		sched_rem(td);
1311 		td->td_priority = prio;
1312 		sched_add(td, SRQ_BORROWING|SRQ_OURSELF);
1313 	} else
1314 		td->td_priority = prio;
1315 }
1316 
1317 /*
1318  * Update a thread's priority when it is lent another thread's
1319  * priority.
1320  */
1321 void
1322 sched_lend_prio(struct thread *td, u_char prio)
1323 {
1324 
1325 	td->td_flags |= TDF_BORROWING;
1326 	sched_thread_priority(td, prio);
1327 }
1328 
1329 /*
1330  * Restore a thread's priority when priority propagation is
1331  * over.  The prio argument is the minimum priority the thread
1332  * needs to have to satisfy other possible priority lending
1333  * requests.  If the thread's regular priority is less
1334  * important than prio, the thread will keep a priority boost
1335  * of prio.
1336  */
1337 void
1338 sched_unlend_prio(struct thread *td, u_char prio)
1339 {
1340 	u_char base_pri;
1341 
1342 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
1343 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
1344 		base_pri = td->td_user_pri;
1345 	else
1346 		base_pri = td->td_base_pri;
1347 	if (prio >= base_pri) {
1348 		td->td_flags &= ~TDF_BORROWING;
1349 		sched_thread_priority(td, base_pri);
1350 	} else
1351 		sched_lend_prio(td, prio);
1352 }
1353 
1354 void
1355 sched_prio(struct thread *td, u_char prio)
1356 {
1357 	u_char oldprio;
1358 
1359 	/* First, update the base priority. */
1360 	td->td_base_pri = prio;
1361 
1362 	/*
1363 	 * If the thread is borrowing another thread's priority, don't
1364 	 * ever lower the priority.
1365 	 */
1366 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
1367 		return;
1368 
1369 	/* Change the real priority. */
1370 	oldprio = td->td_priority;
1371 	sched_thread_priority(td, prio);
1372 
1373 	/*
1374 	 * If the thread is on a turnstile, then let the turnstile update
1375 	 * its state.
1376 	 */
1377 	if (TD_ON_LOCK(td) && oldprio != prio)
1378 		turnstile_adjust(td, oldprio);
1379 }
1380 
1381 void
1382 sched_user_prio(struct thread *td, u_char prio)
1383 {
1384 	u_char oldprio;
1385 
1386 	td->td_base_user_pri = prio;
1387 	if (td->td_flags & TDF_UBORROWING && td->td_user_pri <= prio)
1388                 return;
1389 	oldprio = td->td_user_pri;
1390 	td->td_user_pri = prio;
1391 
1392 	if (TD_ON_UPILOCK(td) && oldprio != prio)
1393 		umtx_pi_adjust(td, oldprio);
1394 }
1395 
1396 void
1397 sched_lend_user_prio(struct thread *td, u_char prio)
1398 {
1399 	u_char oldprio;
1400 
1401 	td->td_flags |= TDF_UBORROWING;
1402 
1403 	oldprio = td->td_user_pri;
1404 	td->td_user_pri = prio;
1405 
1406 	if (TD_ON_UPILOCK(td) && oldprio != prio)
1407 		umtx_pi_adjust(td, oldprio);
1408 }
1409 
1410 void
1411 sched_unlend_user_prio(struct thread *td, u_char prio)
1412 {
1413 	u_char base_pri;
1414 
1415 	base_pri = td->td_base_user_pri;
1416 	if (prio >= base_pri) {
1417 		td->td_flags &= ~TDF_UBORROWING;
1418 		sched_user_prio(td, base_pri);
1419 	} else
1420 		sched_lend_user_prio(td, prio);
1421 }
1422 
1423 void
1424 sched_switch(struct thread *td, struct thread *newtd, int flags)
1425 {
1426 	struct tdq *tdq;
1427 	struct td_sched *ts;
1428 	int preempt;
1429 
1430 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1431 
1432 	preempt = flags & SW_PREEMPT;
1433 	tdq = TDQ_SELF();
1434 	ts = td->td_sched;
1435 	td->td_lastcpu = td->td_oncpu;
1436 	td->td_oncpu = NOCPU;
1437 	td->td_flags &= ~TDF_NEEDRESCHED;
1438 	td->td_owepreempt = 0;
1439 	/*
1440 	 * If the thread has been assigned it may be in the process of switching
1441 	 * to the new cpu.  This is the case in sched_bind().
1442 	 */
1443 	/*
1444 	 * Switch to the sched lock to fix things up and pick
1445 	 * a new thread.
1446 	 */
1447 	if (td->td_lock != &sched_lock) {
1448 		mtx_lock_spin(&sched_lock);
1449 		thread_unlock(td);
1450 	}
1451 	if (TD_IS_IDLETHREAD(td)) {
1452 		MPASS(td->td_lock == &sched_lock);
1453 		TD_SET_CAN_RUN(td);
1454 	} else if (TD_IS_RUNNING(td)) {
1455 		/*
1456 		 * Don't allow the thread to migrate
1457 		 * from a preemption.
1458 		 */
1459 		tdq_load_rem(tdq, ts);
1460 		if (preempt)
1461 			sched_pin_td(td);
1462 		sched_add(td, preempt ?
1463 		    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1464 		    SRQ_OURSELF|SRQ_YIELDING);
1465 		if (preempt)
1466 			sched_unpin_td(td);
1467 	} else
1468 		tdq_load_rem(tdq, ts);
1469 	mtx_assert(&sched_lock, MA_OWNED);
1470 	if (newtd != NULL) {
1471 		/*
1472 		 * If we bring in a thread account for it as if it had been
1473 		 * added to the run queue and then chosen.
1474 		 */
1475 		TD_SET_RUNNING(newtd);
1476 		tdq_load_add(TDQ_SELF(), newtd->td_sched);
1477 	} else
1478 		newtd = choosethread();
1479 	if (td != newtd) {
1480 #ifdef	HWPMC_HOOKS
1481 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1482 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1483 #endif
1484 
1485 		cpu_switch(td, newtd, td->td_lock);
1486 #ifdef	HWPMC_HOOKS
1487 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1488 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1489 #endif
1490 	}
1491 	sched_lock.mtx_lock = (uintptr_t)td;
1492 	td->td_oncpu = PCPU_GET(cpuid);
1493 	MPASS(td->td_lock == &sched_lock);
1494 }
1495 
1496 void
1497 sched_nice(struct proc *p, int nice)
1498 {
1499 	struct thread *td;
1500 
1501 	PROC_LOCK_ASSERT(p, MA_OWNED);
1502 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1503 
1504 	p->p_nice = nice;
1505 	FOREACH_THREAD_IN_PROC(p, td) {
1506 		thread_lock(td);
1507 		sched_priority(td);
1508 		sched_prio(td, td->td_base_user_pri);
1509 		thread_unlock(td);
1510 	}
1511 }
1512 
1513 void
1514 sched_sleep(struct thread *td)
1515 {
1516 
1517 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1518 
1519 	td->td_sched->ts_slptime = ticks;
1520 }
1521 
1522 void
1523 sched_wakeup(struct thread *td)
1524 {
1525 	struct td_sched *ts;
1526 	int slptime;
1527 
1528 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1529 	ts = td->td_sched;
1530 	/*
1531 	 * If we slept for more than a tick update our interactivity and
1532 	 * priority.
1533 	 */
1534 	slptime = ts->ts_slptime;
1535 	ts->ts_slptime = 0;
1536 	if (slptime && slptime != ticks) {
1537 		u_int hzticks;
1538 
1539 		hzticks = (ticks - slptime) << SCHED_TICK_SHIFT;
1540 		ts->skg_slptime += hzticks;
1541 		sched_interact_update(td);
1542 		sched_pctcpu_update(ts);
1543 		sched_priority(td);
1544 	}
1545 	/* Reset the slice value after we sleep. */
1546 	ts->ts_slice = sched_slice;
1547 	sched_add(td, SRQ_BORING);
1548 }
1549 
1550 /*
1551  * Penalize the parent for creating a new child and initialize the child's
1552  * priority.
1553  */
1554 void
1555 sched_fork(struct thread *td, struct thread *child)
1556 {
1557 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1558 	sched_fork_thread(td, child);
1559 	/*
1560 	 * Penalize the parent and child for forking.
1561 	 */
1562 	sched_interact_fork(child);
1563 	sched_priority(child);
1564 	td->td_sched->skg_runtime += tickincr;
1565 	sched_interact_update(td);
1566 	sched_priority(td);
1567 }
1568 
1569 void
1570 sched_fork_thread(struct thread *td, struct thread *child)
1571 {
1572 	struct td_sched *ts;
1573 	struct td_sched *ts2;
1574 
1575 	/*
1576 	 * Initialize child.
1577 	 */
1578 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1579 	sched_newthread(child);
1580 	child->td_lock = &sched_lock;
1581 	ts = td->td_sched;
1582 	ts2 = child->td_sched;
1583 	ts2->ts_cpu = ts->ts_cpu;
1584 	ts2->ts_runq = NULL;
1585 	/*
1586 	 * Grab our parents cpu estimation information and priority.
1587 	 */
1588 	ts2->ts_ticks = ts->ts_ticks;
1589 	ts2->ts_ltick = ts->ts_ltick;
1590 	ts2->ts_ftick = ts->ts_ftick;
1591 	child->td_user_pri = td->td_user_pri;
1592 	child->td_base_user_pri = td->td_base_user_pri;
1593 	/*
1594 	 * And update interactivity score.
1595 	 */
1596 	ts2->skg_slptime = ts->skg_slptime;
1597 	ts2->skg_runtime = ts->skg_runtime;
1598 	ts2->ts_slice = 1;	/* Attempt to quickly learn interactivity. */
1599 }
1600 
1601 void
1602 sched_class(struct thread *td, int class)
1603 {
1604 
1605 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1606 	if (td->td_pri_class == class)
1607 		return;
1608 
1609 #ifdef SMP
1610 	/*
1611 	 * On SMP if we're on the RUNQ we must adjust the transferable
1612 	 * count because could be changing to or from an interrupt
1613 	 * class.
1614 	 */
1615 	if (TD_ON_RUNQ(td)) {
1616 		struct tdq *tdq;
1617 
1618 		tdq = TDQ_CPU(td->td_sched->ts_cpu);
1619 		if (THREAD_CAN_MIGRATE(td)) {
1620 			tdq->tdq_transferable--;
1621 			tdq->tdq_group->tdg_transferable--;
1622 		}
1623 		td->td_pri_class = class;
1624 		if (THREAD_CAN_MIGRATE(td)) {
1625 			tdq->tdq_transferable++;
1626 			tdq->tdq_group->tdg_transferable++;
1627 		}
1628 	}
1629 #endif
1630 	td->td_pri_class = class;
1631 }
1632 
1633 /*
1634  * Return some of the child's priority and interactivity to the parent.
1635  */
1636 void
1637 sched_exit(struct proc *p, struct thread *child)
1638 {
1639 	struct thread *td;
1640 
1641 	CTR3(KTR_SCHED, "sched_exit: %p(%s) prio %d",
1642 	    child, child->td_proc->p_comm, child->td_priority);
1643 
1644 	PROC_SLOCK_ASSERT(p, MA_OWNED);
1645 	td = FIRST_THREAD_IN_PROC(p);
1646 	sched_exit_thread(td, child);
1647 }
1648 
1649 void
1650 sched_exit_thread(struct thread *td, struct thread *child)
1651 {
1652 
1653 	CTR3(KTR_SCHED, "sched_exit_thread: %p(%s) prio %d",
1654 	    child, child->td_proc->p_comm, child->td_priority);
1655 
1656 	thread_lock(child);
1657 	tdq_load_rem(TDQ_CPU(child->td_sched->ts_cpu), child->td_sched);
1658 	thread_unlock(child);
1659 #ifdef KSE
1660 	/*
1661 	 * KSE forks and exits so often that this penalty causes short-lived
1662 	 * threads to always be non-interactive.  This causes mozilla to
1663 	 * crawl under load.
1664 	 */
1665 	if ((td->td_pflags & TDP_SA) && td->td_proc == child->td_proc)
1666 		return;
1667 #endif
1668 	/*
1669 	 * Give the child's runtime to the parent without returning the
1670 	 * sleep time as a penalty to the parent.  This causes shells that
1671 	 * launch expensive things to mark their children as expensive.
1672 	 */
1673 	thread_lock(td);
1674 	td->td_sched->skg_runtime += child->td_sched->skg_runtime;
1675 	sched_interact_update(td);
1676 	sched_priority(td);
1677 	thread_unlock(td);
1678 }
1679 
1680 void
1681 sched_userret(struct thread *td)
1682 {
1683 	/*
1684 	 * XXX we cheat slightly on the locking here to avoid locking in
1685 	 * the usual case.  Setting td_priority here is essentially an
1686 	 * incomplete workaround for not setting it properly elsewhere.
1687 	 * Now that some interrupt handlers are threads, not setting it
1688 	 * properly elsewhere can clobber it in the window between setting
1689 	 * it here and returning to user mode, so don't waste time setting
1690 	 * it perfectly here.
1691 	 */
1692 	KASSERT((td->td_flags & TDF_BORROWING) == 0,
1693 	    ("thread with borrowed priority returning to userland"));
1694 	if (td->td_priority != td->td_user_pri) {
1695 		thread_lock(td);
1696 		td->td_priority = td->td_user_pri;
1697 		td->td_base_pri = td->td_user_pri;
1698 		thread_unlock(td);
1699         }
1700 }
1701 
1702 void
1703 sched_clock(struct thread *td)
1704 {
1705 	struct tdq *tdq;
1706 	struct td_sched *ts;
1707 
1708 	mtx_assert(&sched_lock, MA_OWNED);
1709 #ifdef SMP
1710 	sched_smp_tick(td);
1711 #endif
1712 	tdq = TDQ_SELF();
1713 	/*
1714 	 * Advance the insert index once for each tick to ensure that all
1715 	 * threads get a chance to run.
1716 	 */
1717 	if (tdq->tdq_idx == tdq->tdq_ridx) {
1718 		tdq->tdq_idx = (tdq->tdq_idx + 1) % RQ_NQS;
1719 		if (TAILQ_EMPTY(&tdq->tdq_timeshare.rq_queues[tdq->tdq_ridx]))
1720 			tdq->tdq_ridx = tdq->tdq_idx;
1721 	}
1722 	ts = td->td_sched;
1723 	/*
1724 	 * We only do slicing code for TIMESHARE threads.
1725 	 */
1726 	if (td->td_pri_class != PRI_TIMESHARE)
1727 		return;
1728 	/*
1729 	 * We used a tick; charge it to the thread so that we can compute our
1730 	 * interactivity.
1731 	 */
1732 	td->td_sched->skg_runtime += tickincr;
1733 	sched_interact_update(td);
1734 	/*
1735 	 * We used up one time slice.
1736 	 */
1737 	if (--ts->ts_slice > 0)
1738 		return;
1739 	/*
1740 	 * We're out of time, recompute priorities and requeue.
1741 	 */
1742 	sched_priority(td);
1743 	td->td_flags |= TDF_NEEDRESCHED;
1744 }
1745 
1746 int
1747 sched_runnable(void)
1748 {
1749 	struct tdq *tdq;
1750 	int load;
1751 
1752 	load = 1;
1753 
1754 	tdq = TDQ_SELF();
1755 #ifdef SMP
1756 	if (tdq_busy)
1757 		goto out;
1758 #endif
1759 	if ((curthread->td_flags & TDF_IDLETD) != 0) {
1760 		if (tdq->tdq_load > 0)
1761 			goto out;
1762 	} else
1763 		if (tdq->tdq_load - 1 > 0)
1764 			goto out;
1765 	load = 0;
1766 out:
1767 	return (load);
1768 }
1769 
1770 struct thread *
1771 sched_choose(void)
1772 {
1773 	struct tdq *tdq;
1774 	struct td_sched *ts;
1775 
1776 	mtx_assert(&sched_lock, MA_OWNED);
1777 	tdq = TDQ_SELF();
1778 #ifdef SMP
1779 restart:
1780 #endif
1781 	ts = tdq_choose(tdq);
1782 	if (ts) {
1783 #ifdef SMP
1784 		if (ts->ts_thread->td_priority > PRI_MIN_IDLE)
1785 			if (tdq_idled(tdq) == 0)
1786 				goto restart;
1787 #endif
1788 		tdq_runq_rem(tdq, ts);
1789 		return (ts->ts_thread);
1790 	}
1791 #ifdef SMP
1792 	if (tdq_idled(tdq) == 0)
1793 		goto restart;
1794 #endif
1795 	return (PCPU_GET(idlethread));
1796 }
1797 
1798 static int
1799 sched_preempt(struct thread *td)
1800 {
1801 	struct thread *ctd;
1802 	int cpri;
1803 	int pri;
1804 
1805 	ctd = curthread;
1806 	pri = td->td_priority;
1807 	cpri = ctd->td_priority;
1808 	if (panicstr != NULL || pri >= cpri || cold || TD_IS_INHIBITED(ctd))
1809 		return (0);
1810 	/*
1811 	 * Always preempt IDLE threads.  Otherwise only if the preempting
1812 	 * thread is an ithread.
1813 	 */
1814 	if (pri > PRI_MAX_ITHD && cpri < PRI_MIN_IDLE)
1815 		return (0);
1816 	if (ctd->td_critnest > 1) {
1817 		CTR1(KTR_PROC, "sched_preempt: in critical section %d",
1818 		    ctd->td_critnest);
1819 		ctd->td_owepreempt = 1;
1820 		return (0);
1821 	}
1822 	/*
1823 	 * Thread is runnable but not yet put on system run queue.
1824 	 */
1825 	MPASS(TD_ON_RUNQ(td));
1826 	TD_SET_RUNNING(td);
1827 	MPASS(ctd->td_lock == &sched_lock);
1828 	MPASS(td->td_lock == &sched_lock);
1829 	CTR3(KTR_PROC, "preempting to thread %p (pid %d, %s)\n", td,
1830 	    td->td_proc->p_pid, td->td_proc->p_comm);
1831 	/*
1832 	 * We enter the switch with two runnable threads that both have
1833 	 * the same lock.  When we return td may be sleeping so we need
1834 	 * to switch locks to make sure he's locked correctly.
1835 	 */
1836 	SCHED_STAT_INC(switch_preempt);
1837 	mi_switch(SW_INVOL|SW_PREEMPT, td);
1838 	spinlock_enter();
1839 	thread_unlock(ctd);
1840 	thread_lock(td);
1841 	spinlock_exit();
1842 
1843 	return (1);
1844 }
1845 
1846 void
1847 sched_add(struct thread *td, int flags)
1848 {
1849 	struct tdq *tdq;
1850 	struct td_sched *ts;
1851 	int preemptive;
1852 	int class;
1853 #ifdef SMP
1854 	int cpuid;
1855 	int cpumask;
1856 #endif
1857 	ts = td->td_sched;
1858 
1859 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1860 	CTR5(KTR_SCHED, "sched_add: %p(%s) prio %d by %p(%s)",
1861 	    td, td->td_proc->p_comm, td->td_priority, curthread,
1862 	    curthread->td_proc->p_comm);
1863 	KASSERT((td->td_inhibitors == 0),
1864 	    ("sched_add: trying to run inhibited thread"));
1865 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1866 	    ("sched_add: bad thread state"));
1867 	KASSERT(td->td_proc->p_sflag & PS_INMEM,
1868 	    ("sched_add: process swapped out"));
1869 	/*
1870 	 * Now that the thread is moving to the run-queue, set the lock
1871 	 * to the scheduler's lock.
1872 	 */
1873 	if (td->td_lock != &sched_lock) {
1874 		mtx_lock_spin(&sched_lock);
1875 		thread_lock_set(td, &sched_lock);
1876 	}
1877 	mtx_assert(&sched_lock, MA_OWNED);
1878         TD_SET_RUNQ(td);
1879 	tdq = TDQ_SELF();
1880 	class = PRI_BASE(td->td_pri_class);
1881 	preemptive = !(flags & SRQ_YIELDING);
1882 	/*
1883 	 * Recalculate the priority before we select the target cpu or
1884 	 * run-queue.
1885 	 */
1886 	if (class == PRI_TIMESHARE)
1887 		sched_priority(td);
1888 	if (ts->ts_slice == 0)
1889 		ts->ts_slice = sched_slice;
1890 #ifdef SMP
1891 	cpuid = PCPU_GET(cpuid);
1892 	/*
1893 	 * Pick the destination cpu and if it isn't ours transfer to the
1894 	 * target cpu.
1895 	 */
1896 	if (THREAD_CAN_MIGRATE(td)) {
1897 		if (td->td_priority <= PRI_MAX_ITHD) {
1898 			CTR2(KTR_ULE, "ithd %d < %d",
1899 			    td->td_priority, PRI_MAX_ITHD);
1900 			ts->ts_cpu = cpuid;
1901 		} else if (pick_pri)
1902 			ts->ts_cpu = tdq_pickpri(tdq, ts, flags);
1903 		else
1904 			ts->ts_cpu = tdq_pickidle(tdq, ts);
1905 	} else
1906 		CTR1(KTR_ULE, "pinned %d", td->td_pinned);
1907 	if (ts->ts_cpu != cpuid)
1908 		preemptive = 0;
1909 	tdq = TDQ_CPU(ts->ts_cpu);
1910 	cpumask = 1 << ts->ts_cpu;
1911 	/*
1912 	 * If we had been idle, clear our bit in the group and potentially
1913 	 * the global bitmap.
1914 	 */
1915 	if ((class != PRI_IDLE && class != PRI_ITHD) &&
1916 	    (tdq->tdq_group->tdg_idlemask & cpumask) != 0) {
1917 		/*
1918 		 * Check to see if our group is unidling, and if so, remove it
1919 		 * from the global idle mask.
1920 		 */
1921 		if (tdq->tdq_group->tdg_idlemask ==
1922 		    tdq->tdq_group->tdg_cpumask)
1923 			atomic_clear_int(&tdq_idle, tdq->tdq_group->tdg_mask);
1924 		/*
1925 		 * Now remove ourselves from the group specific idle mask.
1926 		 */
1927 		tdq->tdq_group->tdg_idlemask &= ~cpumask;
1928 	}
1929 #endif
1930 	/*
1931 	 * Pick the run queue based on priority.
1932 	 */
1933 	if (td->td_priority <= PRI_MAX_REALTIME)
1934 		ts->ts_runq = &tdq->tdq_realtime;
1935 	else if (td->td_priority <= PRI_MAX_TIMESHARE)
1936 		ts->ts_runq = &tdq->tdq_timeshare;
1937 	else
1938 		ts->ts_runq = &tdq->tdq_idle;
1939 	if (preemptive && sched_preempt(td))
1940 		return;
1941 	tdq_runq_add(tdq, ts, flags);
1942 	tdq_load_add(tdq, ts);
1943 #ifdef SMP
1944 	if (ts->ts_cpu != cpuid) {
1945 		tdq_notify(ts);
1946 		return;
1947 	}
1948 #endif
1949 	if (td->td_priority < curthread->td_priority)
1950 		curthread->td_flags |= TDF_NEEDRESCHED;
1951 }
1952 
1953 void
1954 sched_rem(struct thread *td)
1955 {
1956 	struct tdq *tdq;
1957 	struct td_sched *ts;
1958 
1959 	CTR5(KTR_SCHED, "sched_rem: %p(%s) prio %d by %p(%s)",
1960 	    td, td->td_proc->p_comm, td->td_priority, curthread,
1961 	    curthread->td_proc->p_comm);
1962 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1963 	ts = td->td_sched;
1964 	KASSERT(TD_ON_RUNQ(td),
1965 	    ("sched_rem: thread not on run queue"));
1966 
1967 	tdq = TDQ_CPU(ts->ts_cpu);
1968 	tdq_runq_rem(tdq, ts);
1969 	tdq_load_rem(tdq, ts);
1970 	TD_SET_CAN_RUN(td);
1971 }
1972 
1973 fixpt_t
1974 sched_pctcpu(struct thread *td)
1975 {
1976 	fixpt_t pctcpu;
1977 	struct td_sched *ts;
1978 
1979 	pctcpu = 0;
1980 	ts = td->td_sched;
1981 	if (ts == NULL)
1982 		return (0);
1983 
1984 	thread_lock(td);
1985 	if (ts->ts_ticks) {
1986 		int rtick;
1987 
1988 		sched_pctcpu_update(ts);
1989 		/* How many rtick per second ? */
1990 		rtick = min(SCHED_TICK_HZ(ts) / SCHED_TICK_SECS, hz);
1991 		pctcpu = (FSCALE * ((FSCALE * rtick)/hz)) >> FSHIFT;
1992 	}
1993 	td->td_proc->p_swtime = ts->ts_ltick - ts->ts_ftick;
1994 	thread_unlock(td);
1995 
1996 	return (pctcpu);
1997 }
1998 
1999 void
2000 sched_bind(struct thread *td, int cpu)
2001 {
2002 	struct td_sched *ts;
2003 
2004 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2005 	ts = td->td_sched;
2006 	if (ts->ts_flags & TSF_BOUND)
2007 		sched_unbind(td);
2008 	ts->ts_flags |= TSF_BOUND;
2009 #ifdef SMP
2010 	sched_pin();
2011 	if (PCPU_GET(cpuid) == cpu)
2012 		return;
2013 	ts->ts_cpu = cpu;
2014 	/* When we return from mi_switch we'll be on the correct cpu. */
2015 	mi_switch(SW_VOL, NULL);
2016 #endif
2017 }
2018 
2019 void
2020 sched_unbind(struct thread *td)
2021 {
2022 	struct td_sched *ts;
2023 
2024 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2025 	ts = td->td_sched;
2026 	if ((ts->ts_flags & TSF_BOUND) == 0)
2027 		return;
2028 	ts->ts_flags &= ~TSF_BOUND;
2029 #ifdef SMP
2030 	sched_unpin();
2031 #endif
2032 }
2033 
2034 int
2035 sched_is_bound(struct thread *td)
2036 {
2037 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2038 	return (td->td_sched->ts_flags & TSF_BOUND);
2039 }
2040 
2041 void
2042 sched_relinquish(struct thread *td)
2043 {
2044 	thread_lock(td);
2045 	if (td->td_pri_class == PRI_TIMESHARE)
2046 		sched_prio(td, PRI_MAX_TIMESHARE);
2047 	SCHED_STAT_INC(switch_relinquish);
2048 	mi_switch(SW_VOL, NULL);
2049 	thread_unlock(td);
2050 }
2051 
2052 int
2053 sched_load(void)
2054 {
2055 #ifdef SMP
2056 	int total;
2057 	int i;
2058 
2059 	total = 0;
2060 	for (i = 0; i <= tdg_maxid; i++)
2061 		total += TDQ_GROUP(i)->tdg_load;
2062 	return (total);
2063 #else
2064 	return (TDQ_SELF()->tdq_sysload);
2065 #endif
2066 }
2067 
2068 int
2069 sched_sizeof_proc(void)
2070 {
2071 	return (sizeof(struct proc));
2072 }
2073 
2074 int
2075 sched_sizeof_thread(void)
2076 {
2077 	return (sizeof(struct thread) + sizeof(struct td_sched));
2078 }
2079 
2080 void
2081 sched_tick(void)
2082 {
2083 	struct td_sched *ts;
2084 
2085 	ts = curthread->td_sched;
2086 	/* Adjust ticks for pctcpu */
2087 	ts->ts_ticks += 1 << SCHED_TICK_SHIFT;
2088 	ts->ts_ltick = ticks;
2089 	/*
2090 	 * Update if we've exceeded our desired tick threshhold by over one
2091 	 * second.
2092 	 */
2093 	if (ts->ts_ftick + SCHED_TICK_MAX < ts->ts_ltick)
2094 		sched_pctcpu_update(ts);
2095 }
2096 
2097 /*
2098  * The actual idle process.
2099  */
2100 void
2101 sched_idletd(void *dummy)
2102 {
2103 	struct proc *p;
2104 	struct thread *td;
2105 
2106 	td = curthread;
2107 	p = td->td_proc;
2108 	mtx_assert(&Giant, MA_NOTOWNED);
2109 	/* ULE Relies on preemption for idle interruption. */
2110 	for (;;)
2111 		cpu_idle();
2112 }
2113 
2114 /*
2115  * A CPU is entering for the first time or a thread is exiting.
2116  */
2117 void
2118 sched_throw(struct thread *td)
2119 {
2120 	/*
2121 	 * Correct spinlock nesting.  The idle thread context that we are
2122 	 * borrowing was created so that it would start out with a single
2123 	 * spin lock (sched_lock) held in fork_trampoline().  Since we've
2124 	 * explicitly acquired locks in this function, the nesting count
2125 	 * is now 2 rather than 1.  Since we are nested, calling
2126 	 * spinlock_exit() will simply adjust the counts without allowing
2127 	 * spin lock using code to interrupt us.
2128 	 */
2129 	if (td == NULL) {
2130 		mtx_lock_spin(&sched_lock);
2131 		spinlock_exit();
2132 	} else {
2133 		MPASS(td->td_lock == &sched_lock);
2134 	}
2135 	mtx_assert(&sched_lock, MA_OWNED);
2136 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
2137 	PCPU_SET(switchtime, cpu_ticks());
2138 	PCPU_SET(switchticks, ticks);
2139 	cpu_throw(td, choosethread());	/* doesn't return */
2140 }
2141 
2142 void
2143 sched_fork_exit(struct thread *td)
2144 {
2145 
2146 	/*
2147 	 * Finish setting up thread glue so that it begins execution in a
2148 	 * non-nested critical section with sched_lock held but not recursed.
2149 	 */
2150 	td->td_oncpu = PCPU_GET(cpuid);
2151 	sched_lock.mtx_lock = (uintptr_t)td;
2152 	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
2153 }
2154 
2155 static SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RW, 0, "Scheduler");
2156 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "ule", 0,
2157     "Scheduler name");
2158 SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0, "");
2159 SYSCTL_INT(_kern_sched, OID_AUTO, interact, CTLFLAG_RW, &sched_interact, 0, "");
2160 SYSCTL_INT(_kern_sched, OID_AUTO, tickincr, CTLFLAG_RD, &tickincr, 0, "");
2161 SYSCTL_INT(_kern_sched, OID_AUTO, realstathz, CTLFLAG_RD, &realstathz, 0, "");
2162 #ifdef SMP
2163 SYSCTL_INT(_kern_sched, OID_AUTO, pick_pri, CTLFLAG_RW, &pick_pri, 0, "");
2164 SYSCTL_INT(_kern_sched, OID_AUTO, pick_pri_affinity, CTLFLAG_RW,
2165     &affinity, 0, "");
2166 SYSCTL_INT(_kern_sched, OID_AUTO, pick_pri_tryself, CTLFLAG_RW,
2167     &tryself, 0, "");
2168 SYSCTL_INT(_kern_sched, OID_AUTO, pick_pri_tryselfidle, CTLFLAG_RW,
2169     &tryselfidle, 0, "");
2170 SYSCTL_INT(_kern_sched, OID_AUTO, balance, CTLFLAG_RW, &rebalance, 0, "");
2171 SYSCTL_INT(_kern_sched, OID_AUTO, ipi_preempt, CTLFLAG_RW, &ipi_preempt, 0, "");
2172 SYSCTL_INT(_kern_sched, OID_AUTO, ipi_ast, CTLFLAG_RW, &ipi_ast, 0, "");
2173 SYSCTL_INT(_kern_sched, OID_AUTO, ipi_thresh, CTLFLAG_RW, &ipi_thresh, 0, "");
2174 SYSCTL_INT(_kern_sched, OID_AUTO, steal_htt, CTLFLAG_RW, &steal_htt, 0, "");
2175 SYSCTL_INT(_kern_sched, OID_AUTO, steal_busy, CTLFLAG_RW, &steal_busy, 0, "");
2176 SYSCTL_INT(_kern_sched, OID_AUTO, busy_thresh, CTLFLAG_RW, &busy_thresh, 0, "");
2177 SYSCTL_INT(_kern_sched, OID_AUTO, topology, CTLFLAG_RD, &topology, 0, "");
2178 #endif
2179 
2180 /* ps compat */
2181 static fixpt_t  ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
2182 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
2183 
2184 
2185 #define KERN_SWITCH_INCLUDE 1
2186 #include "kern/kern_switch.c"
2187