xref: /freebsd/sys/kern/sched_4bsd.c (revision a0ee8cc636cd5c2374ec44ca71226564ea0bca95)
1 /*-
2  * Copyright (c) 1982, 1986, 1990, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37 
38 #include "opt_hwpmc_hooks.h"
39 #include "opt_sched.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/cpuset.h>
44 #include <sys/kernel.h>
45 #include <sys/ktr.h>
46 #include <sys/lock.h>
47 #include <sys/kthread.h>
48 #include <sys/mutex.h>
49 #include <sys/proc.h>
50 #include <sys/resourcevar.h>
51 #include <sys/sched.h>
52 #include <sys/sdt.h>
53 #include <sys/smp.h>
54 #include <sys/sysctl.h>
55 #include <sys/sx.h>
56 #include <sys/turnstile.h>
57 #include <sys/umtx.h>
58 #include <machine/pcb.h>
59 #include <machine/smp.h>
60 
61 #ifdef HWPMC_HOOKS
62 #include <sys/pmckern.h>
63 #endif
64 
65 #ifdef KDTRACE_HOOKS
66 #include <sys/dtrace_bsd.h>
67 int				dtrace_vtime_active;
68 dtrace_vtime_switch_func_t	dtrace_vtime_switch_func;
69 #endif
70 
71 /*
72  * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
73  * the range 100-256 Hz (approximately).
74  */
75 #define	ESTCPULIM(e) \
76     min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
77     RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
78 #ifdef SMP
79 #define	INVERSE_ESTCPU_WEIGHT	(8 * smp_cpus)
80 #else
81 #define	INVERSE_ESTCPU_WEIGHT	8	/* 1 / (priorities per estcpu level). */
82 #endif
83 #define	NICE_WEIGHT		1	/* Priorities per nice level. */
84 
85 #define	TS_NAME_LEN (MAXCOMLEN + sizeof(" td ") + sizeof(__XSTRING(UINT_MAX)))
86 
87 /*
88  * The schedulable entity that runs a context.
89  * This is  an extension to the thread structure and is tailored to
90  * the requirements of this scheduler
91  */
92 struct td_sched {
93 	fixpt_t		ts_pctcpu;	/* (j) %cpu during p_swtime. */
94 	int		ts_cpticks;	/* (j) Ticks of cpu time. */
95 	int		ts_slptime;	/* (j) Seconds !RUNNING. */
96 	int		ts_slice;	/* Remaining part of time slice. */
97 	int		ts_flags;
98 	struct runq	*ts_runq;	/* runq the thread is currently on */
99 #ifdef KTR
100 	char		ts_name[TS_NAME_LEN];
101 #endif
102 };
103 
104 /* flags kept in td_flags */
105 #define TDF_DIDRUN	TDF_SCHED0	/* thread actually ran. */
106 #define TDF_BOUND	TDF_SCHED1	/* Bound to one CPU. */
107 #define	TDF_SLICEEND	TDF_SCHED2	/* Thread time slice is over. */
108 
109 /* flags kept in ts_flags */
110 #define	TSF_AFFINITY	0x0001		/* Has a non-"full" CPU set. */
111 
112 #define SKE_RUNQ_PCPU(ts)						\
113     ((ts)->ts_runq != 0 && (ts)->ts_runq != &runq)
114 
115 #define	THREAD_CAN_SCHED(td, cpu)	\
116     CPU_ISSET((cpu), &(td)->td_cpuset->cs_mask)
117 
118 static struct td_sched td_sched0;
119 static struct mtx sched_lock;
120 
121 static int	realstathz = 127; /* stathz is sometimes 0 and run off of hz. */
122 static int	sched_tdcnt;	/* Total runnable threads in the system. */
123 static int	sched_slice = 12; /* Thread run time before rescheduling. */
124 
125 static void	setup_runqs(void);
126 static void	schedcpu(void);
127 static void	schedcpu_thread(void);
128 static void	sched_priority(struct thread *td, u_char prio);
129 static void	sched_setup(void *dummy);
130 static void	maybe_resched(struct thread *td);
131 static void	updatepri(struct thread *td);
132 static void	resetpriority(struct thread *td);
133 static void	resetpriority_thread(struct thread *td);
134 #ifdef SMP
135 static int	sched_pickcpu(struct thread *td);
136 static int	forward_wakeup(int cpunum);
137 static void	kick_other_cpu(int pri, int cpuid);
138 #endif
139 
140 static struct kproc_desc sched_kp = {
141         "schedcpu",
142         schedcpu_thread,
143         NULL
144 };
145 SYSINIT(schedcpu, SI_SUB_LAST, SI_ORDER_FIRST, kproc_start,
146     &sched_kp);
147 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL);
148 
149 static void sched_initticks(void *dummy);
150 SYSINIT(sched_initticks, SI_SUB_CLOCKS, SI_ORDER_THIRD, sched_initticks,
151     NULL);
152 
153 /*
154  * Global run queue.
155  */
156 static struct runq runq;
157 
158 #ifdef SMP
159 /*
160  * Per-CPU run queues
161  */
162 static struct runq runq_pcpu[MAXCPU];
163 long runq_length[MAXCPU];
164 
165 static cpuset_t idle_cpus_mask;
166 #endif
167 
168 struct pcpuidlestat {
169 	u_int idlecalls;
170 	u_int oldidlecalls;
171 };
172 static DPCPU_DEFINE(struct pcpuidlestat, idlestat);
173 
174 static void
175 setup_runqs(void)
176 {
177 #ifdef SMP
178 	int i;
179 
180 	for (i = 0; i < MAXCPU; ++i)
181 		runq_init(&runq_pcpu[i]);
182 #endif
183 
184 	runq_init(&runq);
185 }
186 
187 static int
188 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
189 {
190 	int error, new_val, period;
191 
192 	period = 1000000 / realstathz;
193 	new_val = period * sched_slice;
194 	error = sysctl_handle_int(oidp, &new_val, 0, req);
195 	if (error != 0 || req->newptr == NULL)
196 		return (error);
197 	if (new_val <= 0)
198 		return (EINVAL);
199 	sched_slice = imax(1, (new_val + period / 2) / period);
200 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
201 	    realstathz);
202 	return (0);
203 }
204 
205 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "Scheduler");
206 
207 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
208     "Scheduler name");
209 SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
210     NULL, 0, sysctl_kern_quantum, "I",
211     "Quantum for timeshare threads in microseconds");
212 SYSCTL_INT(_kern_sched, OID_AUTO, slice, CTLFLAG_RW, &sched_slice, 0,
213     "Quantum for timeshare threads in stathz ticks");
214 #ifdef SMP
215 /* Enable forwarding of wakeups to all other cpus */
216 static SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup, CTLFLAG_RD, NULL,
217     "Kernel SMP");
218 
219 static int runq_fuzz = 1;
220 SYSCTL_INT(_kern_sched, OID_AUTO, runq_fuzz, CTLFLAG_RW, &runq_fuzz, 0, "");
221 
222 static int forward_wakeup_enabled = 1;
223 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
224 	   &forward_wakeup_enabled, 0,
225 	   "Forwarding of wakeup to idle CPUs");
226 
227 static int forward_wakeups_requested = 0;
228 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
229 	   &forward_wakeups_requested, 0,
230 	   "Requests for Forwarding of wakeup to idle CPUs");
231 
232 static int forward_wakeups_delivered = 0;
233 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
234 	   &forward_wakeups_delivered, 0,
235 	   "Completed Forwarding of wakeup to idle CPUs");
236 
237 static int forward_wakeup_use_mask = 1;
238 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
239 	   &forward_wakeup_use_mask, 0,
240 	   "Use the mask of idle cpus");
241 
242 static int forward_wakeup_use_loop = 0;
243 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
244 	   &forward_wakeup_use_loop, 0,
245 	   "Use a loop to find idle cpus");
246 
247 #endif
248 #if 0
249 static int sched_followon = 0;
250 SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
251 	   &sched_followon, 0,
252 	   "allow threads to share a quantum");
253 #endif
254 
255 SDT_PROVIDER_DEFINE(sched);
256 
257 SDT_PROBE_DEFINE3(sched, , , change__pri, "struct thread *",
258     "struct proc *", "uint8_t");
259 SDT_PROBE_DEFINE3(sched, , , dequeue, "struct thread *",
260     "struct proc *", "void *");
261 SDT_PROBE_DEFINE4(sched, , , enqueue, "struct thread *",
262     "struct proc *", "void *", "int");
263 SDT_PROBE_DEFINE4(sched, , , lend__pri, "struct thread *",
264     "struct proc *", "uint8_t", "struct thread *");
265 SDT_PROBE_DEFINE2(sched, , , load__change, "int", "int");
266 SDT_PROBE_DEFINE2(sched, , , off__cpu, "struct thread *",
267     "struct proc *");
268 SDT_PROBE_DEFINE(sched, , , on__cpu);
269 SDT_PROBE_DEFINE(sched, , , remain__cpu);
270 SDT_PROBE_DEFINE2(sched, , , surrender, "struct thread *",
271     "struct proc *");
272 
273 static __inline void
274 sched_load_add(void)
275 {
276 
277 	sched_tdcnt++;
278 	KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
279 	SDT_PROBE2(sched, , , load__change, NOCPU, sched_tdcnt);
280 }
281 
282 static __inline void
283 sched_load_rem(void)
284 {
285 
286 	sched_tdcnt--;
287 	KTR_COUNTER0(KTR_SCHED, "load", "global load", sched_tdcnt);
288 	SDT_PROBE2(sched, , , load__change, NOCPU, sched_tdcnt);
289 }
290 /*
291  * Arrange to reschedule if necessary, taking the priorities and
292  * schedulers into account.
293  */
294 static void
295 maybe_resched(struct thread *td)
296 {
297 
298 	THREAD_LOCK_ASSERT(td, MA_OWNED);
299 	if (td->td_priority < curthread->td_priority)
300 		curthread->td_flags |= TDF_NEEDRESCHED;
301 }
302 
303 /*
304  * This function is called when a thread is about to be put on run queue
305  * because it has been made runnable or its priority has been adjusted.  It
306  * determines if the new thread should be immediately preempted to.  If so,
307  * it switches to it and eventually returns true.  If not, it returns false
308  * so that the caller may place the thread on an appropriate run queue.
309  */
310 int
311 maybe_preempt(struct thread *td)
312 {
313 #ifdef PREEMPTION
314 	struct thread *ctd;
315 	int cpri, pri;
316 
317 	/*
318 	 * The new thread should not preempt the current thread if any of the
319 	 * following conditions are true:
320 	 *
321 	 *  - The kernel is in the throes of crashing (panicstr).
322 	 *  - The current thread has a higher (numerically lower) or
323 	 *    equivalent priority.  Note that this prevents curthread from
324 	 *    trying to preempt to itself.
325 	 *  - It is too early in the boot for context switches (cold is set).
326 	 *  - The current thread has an inhibitor set or is in the process of
327 	 *    exiting.  In this case, the current thread is about to switch
328 	 *    out anyways, so there's no point in preempting.  If we did,
329 	 *    the current thread would not be properly resumed as well, so
330 	 *    just avoid that whole landmine.
331 	 *  - If the new thread's priority is not a realtime priority and
332 	 *    the current thread's priority is not an idle priority and
333 	 *    FULL_PREEMPTION is disabled.
334 	 *
335 	 * If all of these conditions are false, but the current thread is in
336 	 * a nested critical section, then we have to defer the preemption
337 	 * until we exit the critical section.  Otherwise, switch immediately
338 	 * to the new thread.
339 	 */
340 	ctd = curthread;
341 	THREAD_LOCK_ASSERT(td, MA_OWNED);
342 	KASSERT((td->td_inhibitors == 0),
343 			("maybe_preempt: trying to run inhibited thread"));
344 	pri = td->td_priority;
345 	cpri = ctd->td_priority;
346 	if (panicstr != NULL || pri >= cpri || cold /* || dumping */ ||
347 	    TD_IS_INHIBITED(ctd))
348 		return (0);
349 #ifndef FULL_PREEMPTION
350 	if (pri > PRI_MAX_ITHD && cpri < PRI_MIN_IDLE)
351 		return (0);
352 #endif
353 
354 	if (ctd->td_critnest > 1) {
355 		CTR1(KTR_PROC, "maybe_preempt: in critical section %d",
356 		    ctd->td_critnest);
357 		ctd->td_owepreempt = 1;
358 		return (0);
359 	}
360 	/*
361 	 * Thread is runnable but not yet put on system run queue.
362 	 */
363 	MPASS(ctd->td_lock == td->td_lock);
364 	MPASS(TD_ON_RUNQ(td));
365 	TD_SET_RUNNING(td);
366 	CTR3(KTR_PROC, "preempting to thread %p (pid %d, %s)\n", td,
367 	    td->td_proc->p_pid, td->td_name);
368 	mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, td);
369 	/*
370 	 * td's lock pointer may have changed.  We have to return with it
371 	 * locked.
372 	 */
373 	spinlock_enter();
374 	thread_unlock(ctd);
375 	thread_lock(td);
376 	spinlock_exit();
377 	return (1);
378 #else
379 	return (0);
380 #endif
381 }
382 
383 /*
384  * Constants for digital decay and forget:
385  *	90% of (td_estcpu) usage in 5 * loadav time
386  *	95% of (ts_pctcpu) usage in 60 seconds (load insensitive)
387  *          Note that, as ps(1) mentions, this can let percentages
388  *          total over 100% (I've seen 137.9% for 3 processes).
389  *
390  * Note that schedclock() updates td_estcpu and p_cpticks asynchronously.
391  *
392  * We wish to decay away 90% of td_estcpu in (5 * loadavg) seconds.
393  * That is, the system wants to compute a value of decay such
394  * that the following for loop:
395  * 	for (i = 0; i < (5 * loadavg); i++)
396  * 		td_estcpu *= decay;
397  * will compute
398  * 	td_estcpu *= 0.1;
399  * for all values of loadavg:
400  *
401  * Mathematically this loop can be expressed by saying:
402  * 	decay ** (5 * loadavg) ~= .1
403  *
404  * The system computes decay as:
405  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
406  *
407  * We wish to prove that the system's computation of decay
408  * will always fulfill the equation:
409  * 	decay ** (5 * loadavg) ~= .1
410  *
411  * If we compute b as:
412  * 	b = 2 * loadavg
413  * then
414  * 	decay = b / (b + 1)
415  *
416  * We now need to prove two things:
417  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
418  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
419  *
420  * Facts:
421  *         For x close to zero, exp(x) =~ 1 + x, since
422  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
423  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
424  *         For x close to zero, ln(1+x) =~ x, since
425  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
426  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
427  *         ln(.1) =~ -2.30
428  *
429  * Proof of (1):
430  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
431  *	solving for factor,
432  *      ln(factor) =~ (-2.30/5*loadav), or
433  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
434  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
435  *
436  * Proof of (2):
437  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
438  *	solving for power,
439  *      power*ln(b/(b+1)) =~ -2.30, or
440  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
441  *
442  * Actual power values for the implemented algorithm are as follows:
443  *      loadav: 1       2       3       4
444  *      power:  5.68    10.32   14.94   19.55
445  */
446 
447 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
448 #define	loadfactor(loadav)	(2 * (loadav))
449 #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
450 
451 /* decay 95% of `ts_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
452 static fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
453 SYSCTL_UINT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
454 
455 /*
456  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
457  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
458  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
459  *
460  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
461  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
462  *
463  * If you don't want to bother with the faster/more-accurate formula, you
464  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
465  * (more general) method of calculating the %age of CPU used by a process.
466  */
467 #define	CCPU_SHIFT	11
468 
469 /*
470  * Recompute process priorities, every hz ticks.
471  * MP-safe, called without the Giant mutex.
472  */
473 /* ARGSUSED */
474 static void
475 schedcpu(void)
476 {
477 	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
478 	struct thread *td;
479 	struct proc *p;
480 	struct td_sched *ts;
481 	int awake;
482 
483 	sx_slock(&allproc_lock);
484 	FOREACH_PROC_IN_SYSTEM(p) {
485 		PROC_LOCK(p);
486 		if (p->p_state == PRS_NEW) {
487 			PROC_UNLOCK(p);
488 			continue;
489 		}
490 		FOREACH_THREAD_IN_PROC(p, td) {
491 			awake = 0;
492 			thread_lock(td);
493 			ts = td->td_sched;
494 			/*
495 			 * Increment sleep time (if sleeping).  We
496 			 * ignore overflow, as above.
497 			 */
498 			/*
499 			 * The td_sched slptimes are not touched in wakeup
500 			 * because the thread may not HAVE everything in
501 			 * memory? XXX I think this is out of date.
502 			 */
503 			if (TD_ON_RUNQ(td)) {
504 				awake = 1;
505 				td->td_flags &= ~TDF_DIDRUN;
506 			} else if (TD_IS_RUNNING(td)) {
507 				awake = 1;
508 				/* Do not clear TDF_DIDRUN */
509 			} else if (td->td_flags & TDF_DIDRUN) {
510 				awake = 1;
511 				td->td_flags &= ~TDF_DIDRUN;
512 			}
513 
514 			/*
515 			 * ts_pctcpu is only for ps and ttyinfo().
516 			 */
517 			ts->ts_pctcpu = (ts->ts_pctcpu * ccpu) >> FSHIFT;
518 			/*
519 			 * If the td_sched has been idle the entire second,
520 			 * stop recalculating its priority until
521 			 * it wakes up.
522 			 */
523 			if (ts->ts_cpticks != 0) {
524 #if	(FSHIFT >= CCPU_SHIFT)
525 				ts->ts_pctcpu += (realstathz == 100)
526 				    ? ((fixpt_t) ts->ts_cpticks) <<
527 				    (FSHIFT - CCPU_SHIFT) :
528 				    100 * (((fixpt_t) ts->ts_cpticks)
529 				    << (FSHIFT - CCPU_SHIFT)) / realstathz;
530 #else
531 				ts->ts_pctcpu += ((FSCALE - ccpu) *
532 				    (ts->ts_cpticks *
533 				    FSCALE / realstathz)) >> FSHIFT;
534 #endif
535 				ts->ts_cpticks = 0;
536 			}
537 			/*
538 			 * If there are ANY running threads in this process,
539 			 * then don't count it as sleeping.
540 			 * XXX: this is broken.
541 			 */
542 			if (awake) {
543 				if (ts->ts_slptime > 1) {
544 					/*
545 					 * In an ideal world, this should not
546 					 * happen, because whoever woke us
547 					 * up from the long sleep should have
548 					 * unwound the slptime and reset our
549 					 * priority before we run at the stale
550 					 * priority.  Should KASSERT at some
551 					 * point when all the cases are fixed.
552 					 */
553 					updatepri(td);
554 				}
555 				ts->ts_slptime = 0;
556 			} else
557 				ts->ts_slptime++;
558 			if (ts->ts_slptime > 1) {
559 				thread_unlock(td);
560 				continue;
561 			}
562 			td->td_estcpu = decay_cpu(loadfac, td->td_estcpu);
563 		      	resetpriority(td);
564 			resetpriority_thread(td);
565 			thread_unlock(td);
566 		}
567 		PROC_UNLOCK(p);
568 	}
569 	sx_sunlock(&allproc_lock);
570 }
571 
572 /*
573  * Main loop for a kthread that executes schedcpu once a second.
574  */
575 static void
576 schedcpu_thread(void)
577 {
578 
579 	for (;;) {
580 		schedcpu();
581 		pause("-", hz);
582 	}
583 }
584 
585 /*
586  * Recalculate the priority of a process after it has slept for a while.
587  * For all load averages >= 1 and max td_estcpu of 255, sleeping for at
588  * least six times the loadfactor will decay td_estcpu to zero.
589  */
590 static void
591 updatepri(struct thread *td)
592 {
593 	struct td_sched *ts;
594 	fixpt_t loadfac;
595 	unsigned int newcpu;
596 
597 	ts = td->td_sched;
598 	loadfac = loadfactor(averunnable.ldavg[0]);
599 	if (ts->ts_slptime > 5 * loadfac)
600 		td->td_estcpu = 0;
601 	else {
602 		newcpu = td->td_estcpu;
603 		ts->ts_slptime--;	/* was incremented in schedcpu() */
604 		while (newcpu && --ts->ts_slptime)
605 			newcpu = decay_cpu(loadfac, newcpu);
606 		td->td_estcpu = newcpu;
607 	}
608 }
609 
610 /*
611  * Compute the priority of a process when running in user mode.
612  * Arrange to reschedule if the resulting priority is better
613  * than that of the current process.
614  */
615 static void
616 resetpriority(struct thread *td)
617 {
618 	register unsigned int newpriority;
619 
620 	if (td->td_pri_class == PRI_TIMESHARE) {
621 		newpriority = PUSER + td->td_estcpu / INVERSE_ESTCPU_WEIGHT +
622 		    NICE_WEIGHT * (td->td_proc->p_nice - PRIO_MIN);
623 		newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
624 		    PRI_MAX_TIMESHARE);
625 		sched_user_prio(td, newpriority);
626 	}
627 }
628 
629 /*
630  * Update the thread's priority when the associated process's user
631  * priority changes.
632  */
633 static void
634 resetpriority_thread(struct thread *td)
635 {
636 
637 	/* Only change threads with a time sharing user priority. */
638 	if (td->td_priority < PRI_MIN_TIMESHARE ||
639 	    td->td_priority > PRI_MAX_TIMESHARE)
640 		return;
641 
642 	/* XXX the whole needresched thing is broken, but not silly. */
643 	maybe_resched(td);
644 
645 	sched_prio(td, td->td_user_pri);
646 }
647 
648 /* ARGSUSED */
649 static void
650 sched_setup(void *dummy)
651 {
652 
653 	setup_runqs();
654 
655 	/* Account for thread0. */
656 	sched_load_add();
657 }
658 
659 /*
660  * This routine determines time constants after stathz and hz are setup.
661  */
662 static void
663 sched_initticks(void *dummy)
664 {
665 
666 	realstathz = stathz ? stathz : hz;
667 	sched_slice = realstathz / 10;	/* ~100ms */
668 	hogticks = imax(1, (2 * hz * sched_slice + realstathz / 2) /
669 	    realstathz);
670 }
671 
672 /* External interfaces start here */
673 
674 /*
675  * Very early in the boot some setup of scheduler-specific
676  * parts of proc0 and of some scheduler resources needs to be done.
677  * Called from:
678  *  proc0_init()
679  */
680 void
681 schedinit(void)
682 {
683 	/*
684 	 * Set up the scheduler specific parts of proc0.
685 	 */
686 	proc0.p_sched = NULL; /* XXX */
687 	thread0.td_sched = &td_sched0;
688 	thread0.td_lock = &sched_lock;
689 	td_sched0.ts_slice = sched_slice;
690 	mtx_init(&sched_lock, "sched lock", NULL, MTX_SPIN | MTX_RECURSE);
691 }
692 
693 int
694 sched_runnable(void)
695 {
696 #ifdef SMP
697 	return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
698 #else
699 	return runq_check(&runq);
700 #endif
701 }
702 
703 int
704 sched_rr_interval(void)
705 {
706 
707 	/* Convert sched_slice from stathz to hz. */
708 	return (imax(1, (sched_slice * hz + realstathz / 2) / realstathz));
709 }
710 
711 /*
712  * We adjust the priority of the current process.  The priority of
713  * a process gets worse as it accumulates CPU time.  The cpu usage
714  * estimator (td_estcpu) is increased here.  resetpriority() will
715  * compute a different priority each time td_estcpu increases by
716  * INVERSE_ESTCPU_WEIGHT
717  * (until MAXPRI is reached).  The cpu usage estimator ramps up
718  * quite quickly when the process is running (linearly), and decays
719  * away exponentially, at a rate which is proportionally slower when
720  * the system is busy.  The basic principle is that the system will
721  * 90% forget that the process used a lot of CPU time in 5 * loadav
722  * seconds.  This causes the system to favor processes which haven't
723  * run much recently, and to round-robin among other processes.
724  */
725 void
726 sched_clock(struct thread *td)
727 {
728 	struct pcpuidlestat *stat;
729 	struct td_sched *ts;
730 
731 	THREAD_LOCK_ASSERT(td, MA_OWNED);
732 	ts = td->td_sched;
733 
734 	ts->ts_cpticks++;
735 	td->td_estcpu = ESTCPULIM(td->td_estcpu + 1);
736 	if ((td->td_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
737 		resetpriority(td);
738 		resetpriority_thread(td);
739 	}
740 
741 	/*
742 	 * Force a context switch if the current thread has used up a full
743 	 * time slice (default is 100ms).
744 	 */
745 	if (!TD_IS_IDLETHREAD(td) && --ts->ts_slice <= 0) {
746 		ts->ts_slice = sched_slice;
747 		td->td_flags |= TDF_NEEDRESCHED | TDF_SLICEEND;
748 	}
749 
750 	stat = DPCPU_PTR(idlestat);
751 	stat->oldidlecalls = stat->idlecalls;
752 	stat->idlecalls = 0;
753 }
754 
755 /*
756  * Charge child's scheduling CPU usage to parent.
757  */
758 void
759 sched_exit(struct proc *p, struct thread *td)
760 {
761 
762 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(td), "proc exit",
763 	    "prio:%d", td->td_priority);
764 
765 	PROC_LOCK_ASSERT(p, MA_OWNED);
766 	sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
767 }
768 
769 void
770 sched_exit_thread(struct thread *td, struct thread *child)
771 {
772 
773 	KTR_STATE1(KTR_SCHED, "thread", sched_tdname(child), "exit",
774 	    "prio:%d", child->td_priority);
775 	thread_lock(td);
776 	td->td_estcpu = ESTCPULIM(td->td_estcpu + child->td_estcpu);
777 	thread_unlock(td);
778 	thread_lock(child);
779 	if ((child->td_flags & TDF_NOLOAD) == 0)
780 		sched_load_rem();
781 	thread_unlock(child);
782 }
783 
784 void
785 sched_fork(struct thread *td, struct thread *childtd)
786 {
787 	sched_fork_thread(td, childtd);
788 }
789 
790 void
791 sched_fork_thread(struct thread *td, struct thread *childtd)
792 {
793 	struct td_sched *ts;
794 
795 	childtd->td_oncpu = NOCPU;
796 	childtd->td_lastcpu = NOCPU;
797 	childtd->td_estcpu = td->td_estcpu;
798 	childtd->td_lock = &sched_lock;
799 	childtd->td_cpuset = cpuset_ref(td->td_cpuset);
800 	childtd->td_priority = childtd->td_base_pri;
801 	ts = childtd->td_sched;
802 	bzero(ts, sizeof(*ts));
803 	ts->ts_flags |= (td->td_sched->ts_flags & TSF_AFFINITY);
804 	ts->ts_slice = 1;
805 }
806 
807 void
808 sched_nice(struct proc *p, int nice)
809 {
810 	struct thread *td;
811 
812 	PROC_LOCK_ASSERT(p, MA_OWNED);
813 	p->p_nice = nice;
814 	FOREACH_THREAD_IN_PROC(p, td) {
815 		thread_lock(td);
816 		resetpriority(td);
817 		resetpriority_thread(td);
818 		thread_unlock(td);
819 	}
820 }
821 
822 void
823 sched_class(struct thread *td, int class)
824 {
825 	THREAD_LOCK_ASSERT(td, MA_OWNED);
826 	td->td_pri_class = class;
827 }
828 
829 /*
830  * Adjust the priority of a thread.
831  */
832 static void
833 sched_priority(struct thread *td, u_char prio)
834 {
835 
836 
837 	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "priority change",
838 	    "prio:%d", td->td_priority, "new prio:%d", prio, KTR_ATTR_LINKED,
839 	    sched_tdname(curthread));
840 	SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
841 	if (td != curthread && prio > td->td_priority) {
842 		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
843 		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
844 		    prio, KTR_ATTR_LINKED, sched_tdname(td));
845 		SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
846 		    curthread);
847 	}
848 	THREAD_LOCK_ASSERT(td, MA_OWNED);
849 	if (td->td_priority == prio)
850 		return;
851 	td->td_priority = prio;
852 	if (TD_ON_RUNQ(td) && td->td_rqindex != (prio / RQ_PPQ)) {
853 		sched_rem(td);
854 		sched_add(td, SRQ_BORING);
855 	}
856 }
857 
858 /*
859  * Update a thread's priority when it is lent another thread's
860  * priority.
861  */
862 void
863 sched_lend_prio(struct thread *td, u_char prio)
864 {
865 
866 	td->td_flags |= TDF_BORROWING;
867 	sched_priority(td, prio);
868 }
869 
870 /*
871  * Restore a thread's priority when priority propagation is
872  * over.  The prio argument is the minimum priority the thread
873  * needs to have to satisfy other possible priority lending
874  * requests.  If the thread's regulary priority is less
875  * important than prio the thread will keep a priority boost
876  * of prio.
877  */
878 void
879 sched_unlend_prio(struct thread *td, u_char prio)
880 {
881 	u_char base_pri;
882 
883 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
884 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
885 		base_pri = td->td_user_pri;
886 	else
887 		base_pri = td->td_base_pri;
888 	if (prio >= base_pri) {
889 		td->td_flags &= ~TDF_BORROWING;
890 		sched_prio(td, base_pri);
891 	} else
892 		sched_lend_prio(td, prio);
893 }
894 
895 void
896 sched_prio(struct thread *td, u_char prio)
897 {
898 	u_char oldprio;
899 
900 	/* First, update the base priority. */
901 	td->td_base_pri = prio;
902 
903 	/*
904 	 * If the thread is borrowing another thread's priority, don't ever
905 	 * lower the priority.
906 	 */
907 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
908 		return;
909 
910 	/* Change the real priority. */
911 	oldprio = td->td_priority;
912 	sched_priority(td, prio);
913 
914 	/*
915 	 * If the thread is on a turnstile, then let the turnstile update
916 	 * its state.
917 	 */
918 	if (TD_ON_LOCK(td) && oldprio != prio)
919 		turnstile_adjust(td, oldprio);
920 }
921 
922 void
923 sched_user_prio(struct thread *td, u_char prio)
924 {
925 
926 	THREAD_LOCK_ASSERT(td, MA_OWNED);
927 	td->td_base_user_pri = prio;
928 	if (td->td_lend_user_pri <= prio)
929 		return;
930 	td->td_user_pri = prio;
931 }
932 
933 void
934 sched_lend_user_prio(struct thread *td, u_char prio)
935 {
936 
937 	THREAD_LOCK_ASSERT(td, MA_OWNED);
938 	td->td_lend_user_pri = prio;
939 	td->td_user_pri = min(prio, td->td_base_user_pri);
940 	if (td->td_priority > td->td_user_pri)
941 		sched_prio(td, td->td_user_pri);
942 	else if (td->td_priority != td->td_user_pri)
943 		td->td_flags |= TDF_NEEDRESCHED;
944 }
945 
946 void
947 sched_sleep(struct thread *td, int pri)
948 {
949 
950 	THREAD_LOCK_ASSERT(td, MA_OWNED);
951 	td->td_slptick = ticks;
952 	td->td_sched->ts_slptime = 0;
953 	if (pri != 0 && PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
954 		sched_prio(td, pri);
955 	if (TD_IS_SUSPENDED(td) || pri >= PSOCK)
956 		td->td_flags |= TDF_CANSWAP;
957 }
958 
959 void
960 sched_switch(struct thread *td, struct thread *newtd, int flags)
961 {
962 	struct mtx *tmtx;
963 	struct td_sched *ts;
964 	struct proc *p;
965 	int preempted;
966 
967 	tmtx = NULL;
968 	ts = td->td_sched;
969 	p = td->td_proc;
970 
971 	THREAD_LOCK_ASSERT(td, MA_OWNED);
972 
973 	/*
974 	 * Switch to the sched lock to fix things up and pick
975 	 * a new thread.
976 	 * Block the td_lock in order to avoid breaking the critical path.
977 	 */
978 	if (td->td_lock != &sched_lock) {
979 		mtx_lock_spin(&sched_lock);
980 		tmtx = thread_lock_block(td);
981 	}
982 
983 	if ((td->td_flags & TDF_NOLOAD) == 0)
984 		sched_load_rem();
985 
986 	td->td_lastcpu = td->td_oncpu;
987 	preempted = !((td->td_flags & TDF_SLICEEND) ||
988 	    (flags & SWT_RELINQUISH));
989 	td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
990 	td->td_owepreempt = 0;
991 	td->td_oncpu = NOCPU;
992 
993 	/*
994 	 * At the last moment, if this thread is still marked RUNNING,
995 	 * then put it back on the run queue as it has not been suspended
996 	 * or stopped or any thing else similar.  We never put the idle
997 	 * threads on the run queue, however.
998 	 */
999 	if (td->td_flags & TDF_IDLETD) {
1000 		TD_SET_CAN_RUN(td);
1001 #ifdef SMP
1002 		CPU_CLR(PCPU_GET(cpuid), &idle_cpus_mask);
1003 #endif
1004 	} else {
1005 		if (TD_IS_RUNNING(td)) {
1006 			/* Put us back on the run queue. */
1007 			sched_add(td, preempted ?
1008 			    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1009 			    SRQ_OURSELF|SRQ_YIELDING);
1010 		}
1011 	}
1012 	if (newtd) {
1013 		/*
1014 		 * The thread we are about to run needs to be counted
1015 		 * as if it had been added to the run queue and selected.
1016 		 * It came from:
1017 		 * * A preemption
1018 		 * * An upcall
1019 		 * * A followon
1020 		 */
1021 		KASSERT((newtd->td_inhibitors == 0),
1022 			("trying to run inhibited thread"));
1023 		newtd->td_flags |= TDF_DIDRUN;
1024         	TD_SET_RUNNING(newtd);
1025 		if ((newtd->td_flags & TDF_NOLOAD) == 0)
1026 			sched_load_add();
1027 	} else {
1028 		newtd = choosethread();
1029 		MPASS(newtd->td_lock == &sched_lock);
1030 	}
1031 
1032 	if (td != newtd) {
1033 #ifdef	HWPMC_HOOKS
1034 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1035 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1036 #endif
1037 
1038 		SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
1039 
1040                 /* I feel sleepy */
1041 		lock_profile_release_lock(&sched_lock.lock_object);
1042 #ifdef KDTRACE_HOOKS
1043 		/*
1044 		 * If DTrace has set the active vtime enum to anything
1045 		 * other than INACTIVE (0), then it should have set the
1046 		 * function to call.
1047 		 */
1048 		if (dtrace_vtime_active)
1049 			(*dtrace_vtime_switch_func)(newtd);
1050 #endif
1051 
1052 		cpu_switch(td, newtd, tmtx != NULL ? tmtx : td->td_lock);
1053 		lock_profile_obtain_lock_success(&sched_lock.lock_object,
1054 		    0, 0, __FILE__, __LINE__);
1055 		/*
1056 		 * Where am I?  What year is it?
1057 		 * We are in the same thread that went to sleep above,
1058 		 * but any amount of time may have passed. All our context
1059 		 * will still be available as will local variables.
1060 		 * PCPU values however may have changed as we may have
1061 		 * changed CPU so don't trust cached values of them.
1062 		 * New threads will go to fork_exit() instead of here
1063 		 * so if you change things here you may need to change
1064 		 * things there too.
1065 		 *
1066 		 * If the thread above was exiting it will never wake
1067 		 * up again here, so either it has saved everything it
1068 		 * needed to, or the thread_wait() or wait() will
1069 		 * need to reap it.
1070 		 */
1071 
1072 		SDT_PROBE0(sched, , , on__cpu);
1073 #ifdef	HWPMC_HOOKS
1074 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1075 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1076 #endif
1077 	} else
1078 		SDT_PROBE0(sched, , , remain__cpu);
1079 
1080 #ifdef SMP
1081 	if (td->td_flags & TDF_IDLETD)
1082 		CPU_SET(PCPU_GET(cpuid), &idle_cpus_mask);
1083 #endif
1084 	sched_lock.mtx_lock = (uintptr_t)td;
1085 	td->td_oncpu = PCPU_GET(cpuid);
1086 	MPASS(td->td_lock == &sched_lock);
1087 }
1088 
1089 void
1090 sched_wakeup(struct thread *td)
1091 {
1092 	struct td_sched *ts;
1093 
1094 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1095 	ts = td->td_sched;
1096 	td->td_flags &= ~TDF_CANSWAP;
1097 	if (ts->ts_slptime > 1) {
1098 		updatepri(td);
1099 		resetpriority(td);
1100 	}
1101 	td->td_slptick = 0;
1102 	ts->ts_slptime = 0;
1103 	ts->ts_slice = sched_slice;
1104 	sched_add(td, SRQ_BORING);
1105 }
1106 
1107 #ifdef SMP
1108 static int
1109 forward_wakeup(int cpunum)
1110 {
1111 	struct pcpu *pc;
1112 	cpuset_t dontuse, map, map2;
1113 	u_int id, me;
1114 	int iscpuset;
1115 
1116 	mtx_assert(&sched_lock, MA_OWNED);
1117 
1118 	CTR0(KTR_RUNQ, "forward_wakeup()");
1119 
1120 	if ((!forward_wakeup_enabled) ||
1121 	     (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
1122 		return (0);
1123 	if (!smp_started || cold || panicstr)
1124 		return (0);
1125 
1126 	forward_wakeups_requested++;
1127 
1128 	/*
1129 	 * Check the idle mask we received against what we calculated
1130 	 * before in the old version.
1131 	 */
1132 	me = PCPU_GET(cpuid);
1133 
1134 	/* Don't bother if we should be doing it ourself. */
1135 	if (CPU_ISSET(me, &idle_cpus_mask) &&
1136 	    (cpunum == NOCPU || me == cpunum))
1137 		return (0);
1138 
1139 	CPU_SETOF(me, &dontuse);
1140 	CPU_OR(&dontuse, &stopped_cpus);
1141 	CPU_OR(&dontuse, &hlt_cpus_mask);
1142 	CPU_ZERO(&map2);
1143 	if (forward_wakeup_use_loop) {
1144 		STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1145 			id = pc->pc_cpuid;
1146 			if (!CPU_ISSET(id, &dontuse) &&
1147 			    pc->pc_curthread == pc->pc_idlethread) {
1148 				CPU_SET(id, &map2);
1149 			}
1150 		}
1151 	}
1152 
1153 	if (forward_wakeup_use_mask) {
1154 		map = idle_cpus_mask;
1155 		CPU_NAND(&map, &dontuse);
1156 
1157 		/* If they are both on, compare and use loop if different. */
1158 		if (forward_wakeup_use_loop) {
1159 			if (CPU_CMP(&map, &map2)) {
1160 				printf("map != map2, loop method preferred\n");
1161 				map = map2;
1162 			}
1163 		}
1164 	} else {
1165 		map = map2;
1166 	}
1167 
1168 	/* If we only allow a specific CPU, then mask off all the others. */
1169 	if (cpunum != NOCPU) {
1170 		KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
1171 		iscpuset = CPU_ISSET(cpunum, &map);
1172 		if (iscpuset == 0)
1173 			CPU_ZERO(&map);
1174 		else
1175 			CPU_SETOF(cpunum, &map);
1176 	}
1177 	if (!CPU_EMPTY(&map)) {
1178 		forward_wakeups_delivered++;
1179 		STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1180 			id = pc->pc_cpuid;
1181 			if (!CPU_ISSET(id, &map))
1182 				continue;
1183 			if (cpu_idle_wakeup(pc->pc_cpuid))
1184 				CPU_CLR(id, &map);
1185 		}
1186 		if (!CPU_EMPTY(&map))
1187 			ipi_selected(map, IPI_AST);
1188 		return (1);
1189 	}
1190 	if (cpunum == NOCPU)
1191 		printf("forward_wakeup: Idle processor not found\n");
1192 	return (0);
1193 }
1194 
1195 static void
1196 kick_other_cpu(int pri, int cpuid)
1197 {
1198 	struct pcpu *pcpu;
1199 	int cpri;
1200 
1201 	pcpu = pcpu_find(cpuid);
1202 	if (CPU_ISSET(cpuid, &idle_cpus_mask)) {
1203 		forward_wakeups_delivered++;
1204 		if (!cpu_idle_wakeup(cpuid))
1205 			ipi_cpu(cpuid, IPI_AST);
1206 		return;
1207 	}
1208 
1209 	cpri = pcpu->pc_curthread->td_priority;
1210 	if (pri >= cpri)
1211 		return;
1212 
1213 #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1214 #if !defined(FULL_PREEMPTION)
1215 	if (pri <= PRI_MAX_ITHD)
1216 #endif /* ! FULL_PREEMPTION */
1217 	{
1218 		ipi_cpu(cpuid, IPI_PREEMPT);
1219 		return;
1220 	}
1221 #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1222 
1223 	pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
1224 	ipi_cpu(cpuid, IPI_AST);
1225 	return;
1226 }
1227 #endif /* SMP */
1228 
1229 #ifdef SMP
1230 static int
1231 sched_pickcpu(struct thread *td)
1232 {
1233 	int best, cpu;
1234 
1235 	mtx_assert(&sched_lock, MA_OWNED);
1236 
1237 	if (THREAD_CAN_SCHED(td, td->td_lastcpu))
1238 		best = td->td_lastcpu;
1239 	else
1240 		best = NOCPU;
1241 	CPU_FOREACH(cpu) {
1242 		if (!THREAD_CAN_SCHED(td, cpu))
1243 			continue;
1244 
1245 		if (best == NOCPU)
1246 			best = cpu;
1247 		else if (runq_length[cpu] < runq_length[best])
1248 			best = cpu;
1249 	}
1250 	KASSERT(best != NOCPU, ("no valid CPUs"));
1251 
1252 	return (best);
1253 }
1254 #endif
1255 
1256 void
1257 sched_add(struct thread *td, int flags)
1258 #ifdef SMP
1259 {
1260 	cpuset_t tidlemsk;
1261 	struct td_sched *ts;
1262 	u_int cpu, cpuid;
1263 	int forwarded = 0;
1264 	int single_cpu = 0;
1265 
1266 	ts = td->td_sched;
1267 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1268 	KASSERT((td->td_inhibitors == 0),
1269 	    ("sched_add: trying to run inhibited thread"));
1270 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1271 	    ("sched_add: bad thread state"));
1272 	KASSERT(td->td_flags & TDF_INMEM,
1273 	    ("sched_add: thread swapped out"));
1274 
1275 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
1276 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1277 	    sched_tdname(curthread));
1278 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
1279 	    KTR_ATTR_LINKED, sched_tdname(td));
1280 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1281 	    flags & SRQ_PREEMPTED);
1282 
1283 
1284 	/*
1285 	 * Now that the thread is moving to the run-queue, set the lock
1286 	 * to the scheduler's lock.
1287 	 */
1288 	if (td->td_lock != &sched_lock) {
1289 		mtx_lock_spin(&sched_lock);
1290 		thread_lock_set(td, &sched_lock);
1291 	}
1292 	TD_SET_RUNQ(td);
1293 
1294 	/*
1295 	 * If SMP is started and the thread is pinned or otherwise limited to
1296 	 * a specific set of CPUs, queue the thread to a per-CPU run queue.
1297 	 * Otherwise, queue the thread to the global run queue.
1298 	 *
1299 	 * If SMP has not yet been started we must use the global run queue
1300 	 * as per-CPU state may not be initialized yet and we may crash if we
1301 	 * try to access the per-CPU run queues.
1302 	 */
1303 	if (smp_started && (td->td_pinned != 0 || td->td_flags & TDF_BOUND ||
1304 	    ts->ts_flags & TSF_AFFINITY)) {
1305 		if (td->td_pinned != 0)
1306 			cpu = td->td_lastcpu;
1307 		else if (td->td_flags & TDF_BOUND) {
1308 			/* Find CPU from bound runq. */
1309 			KASSERT(SKE_RUNQ_PCPU(ts),
1310 			    ("sched_add: bound td_sched not on cpu runq"));
1311 			cpu = ts->ts_runq - &runq_pcpu[0];
1312 		} else
1313 			/* Find a valid CPU for our cpuset */
1314 			cpu = sched_pickcpu(td);
1315 		ts->ts_runq = &runq_pcpu[cpu];
1316 		single_cpu = 1;
1317 		CTR3(KTR_RUNQ,
1318 		    "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td,
1319 		    cpu);
1320 	} else {
1321 		CTR2(KTR_RUNQ,
1322 		    "sched_add: adding td_sched:%p (td:%p) to gbl runq", ts,
1323 		    td);
1324 		cpu = NOCPU;
1325 		ts->ts_runq = &runq;
1326 	}
1327 
1328 	cpuid = PCPU_GET(cpuid);
1329 	if (single_cpu && cpu != cpuid) {
1330 	        kick_other_cpu(td->td_priority, cpu);
1331 	} else {
1332 		if (!single_cpu) {
1333 			tidlemsk = idle_cpus_mask;
1334 			CPU_NAND(&tidlemsk, &hlt_cpus_mask);
1335 			CPU_CLR(cpuid, &tidlemsk);
1336 
1337 			if (!CPU_ISSET(cpuid, &idle_cpus_mask) &&
1338 			    ((flags & SRQ_INTR) == 0) &&
1339 			    !CPU_EMPTY(&tidlemsk))
1340 				forwarded = forward_wakeup(cpu);
1341 		}
1342 
1343 		if (!forwarded) {
1344 			if ((flags & SRQ_YIELDING) == 0 && maybe_preempt(td))
1345 				return;
1346 			else
1347 				maybe_resched(td);
1348 		}
1349 	}
1350 
1351 	if ((td->td_flags & TDF_NOLOAD) == 0)
1352 		sched_load_add();
1353 	runq_add(ts->ts_runq, td, flags);
1354 	if (cpu != NOCPU)
1355 		runq_length[cpu]++;
1356 }
1357 #else /* SMP */
1358 {
1359 	struct td_sched *ts;
1360 
1361 	ts = td->td_sched;
1362 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1363 	KASSERT((td->td_inhibitors == 0),
1364 	    ("sched_add: trying to run inhibited thread"));
1365 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1366 	    ("sched_add: bad thread state"));
1367 	KASSERT(td->td_flags & TDF_INMEM,
1368 	    ("sched_add: thread swapped out"));
1369 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
1370 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1371 	    sched_tdname(curthread));
1372 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
1373 	    KTR_ATTR_LINKED, sched_tdname(td));
1374 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1375 	    flags & SRQ_PREEMPTED);
1376 
1377 	/*
1378 	 * Now that the thread is moving to the run-queue, set the lock
1379 	 * to the scheduler's lock.
1380 	 */
1381 	if (td->td_lock != &sched_lock) {
1382 		mtx_lock_spin(&sched_lock);
1383 		thread_lock_set(td, &sched_lock);
1384 	}
1385 	TD_SET_RUNQ(td);
1386 	CTR2(KTR_RUNQ, "sched_add: adding td_sched:%p (td:%p) to runq", ts, td);
1387 	ts->ts_runq = &runq;
1388 
1389 	/*
1390 	 * If we are yielding (on the way out anyhow) or the thread
1391 	 * being saved is US, then don't try be smart about preemption
1392 	 * or kicking off another CPU as it won't help and may hinder.
1393 	 * In the YIEDLING case, we are about to run whoever is being
1394 	 * put in the queue anyhow, and in the OURSELF case, we are
1395 	 * puting ourself on the run queue which also only happens
1396 	 * when we are about to yield.
1397 	 */
1398 	if ((flags & SRQ_YIELDING) == 0) {
1399 		if (maybe_preempt(td))
1400 			return;
1401 	}
1402 	if ((td->td_flags & TDF_NOLOAD) == 0)
1403 		sched_load_add();
1404 	runq_add(ts->ts_runq, td, flags);
1405 	maybe_resched(td);
1406 }
1407 #endif /* SMP */
1408 
1409 void
1410 sched_rem(struct thread *td)
1411 {
1412 	struct td_sched *ts;
1413 
1414 	ts = td->td_sched;
1415 	KASSERT(td->td_flags & TDF_INMEM,
1416 	    ("sched_rem: thread swapped out"));
1417 	KASSERT(TD_ON_RUNQ(td),
1418 	    ("sched_rem: thread not on run queue"));
1419 	mtx_assert(&sched_lock, MA_OWNED);
1420 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
1421 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1422 	    sched_tdname(curthread));
1423 	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
1424 
1425 	if ((td->td_flags & TDF_NOLOAD) == 0)
1426 		sched_load_rem();
1427 #ifdef SMP
1428 	if (ts->ts_runq != &runq)
1429 		runq_length[ts->ts_runq - runq_pcpu]--;
1430 #endif
1431 	runq_remove(ts->ts_runq, td);
1432 	TD_SET_CAN_RUN(td);
1433 }
1434 
1435 /*
1436  * Select threads to run.  Note that running threads still consume a
1437  * slot.
1438  */
1439 struct thread *
1440 sched_choose(void)
1441 {
1442 	struct thread *td;
1443 	struct runq *rq;
1444 
1445 	mtx_assert(&sched_lock,  MA_OWNED);
1446 #ifdef SMP
1447 	struct thread *tdcpu;
1448 
1449 	rq = &runq;
1450 	td = runq_choose_fuzz(&runq, runq_fuzz);
1451 	tdcpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1452 
1453 	if (td == NULL ||
1454 	    (tdcpu != NULL &&
1455 	     tdcpu->td_priority < td->td_priority)) {
1456 		CTR2(KTR_RUNQ, "choosing td %p from pcpu runq %d", tdcpu,
1457 		     PCPU_GET(cpuid));
1458 		td = tdcpu;
1459 		rq = &runq_pcpu[PCPU_GET(cpuid)];
1460 	} else {
1461 		CTR1(KTR_RUNQ, "choosing td_sched %p from main runq", td);
1462 	}
1463 
1464 #else
1465 	rq = &runq;
1466 	td = runq_choose(&runq);
1467 #endif
1468 
1469 	if (td) {
1470 #ifdef SMP
1471 		if (td == tdcpu)
1472 			runq_length[PCPU_GET(cpuid)]--;
1473 #endif
1474 		runq_remove(rq, td);
1475 		td->td_flags |= TDF_DIDRUN;
1476 
1477 		KASSERT(td->td_flags & TDF_INMEM,
1478 		    ("sched_choose: thread swapped out"));
1479 		return (td);
1480 	}
1481 	return (PCPU_GET(idlethread));
1482 }
1483 
1484 void
1485 sched_preempt(struct thread *td)
1486 {
1487 
1488 	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
1489 	thread_lock(td);
1490 	if (td->td_critnest > 1)
1491 		td->td_owepreempt = 1;
1492 	else
1493 		mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, NULL);
1494 	thread_unlock(td);
1495 }
1496 
1497 void
1498 sched_userret(struct thread *td)
1499 {
1500 	/*
1501 	 * XXX we cheat slightly on the locking here to avoid locking in
1502 	 * the usual case.  Setting td_priority here is essentially an
1503 	 * incomplete workaround for not setting it properly elsewhere.
1504 	 * Now that some interrupt handlers are threads, not setting it
1505 	 * properly elsewhere can clobber it in the window between setting
1506 	 * it here and returning to user mode, so don't waste time setting
1507 	 * it perfectly here.
1508 	 */
1509 	KASSERT((td->td_flags & TDF_BORROWING) == 0,
1510 	    ("thread with borrowed priority returning to userland"));
1511 	if (td->td_priority != td->td_user_pri) {
1512 		thread_lock(td);
1513 		td->td_priority = td->td_user_pri;
1514 		td->td_base_pri = td->td_user_pri;
1515 		thread_unlock(td);
1516 	}
1517 }
1518 
1519 void
1520 sched_bind(struct thread *td, int cpu)
1521 {
1522 	struct td_sched *ts;
1523 
1524 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
1525 	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
1526 
1527 	ts = td->td_sched;
1528 
1529 	td->td_flags |= TDF_BOUND;
1530 #ifdef SMP
1531 	ts->ts_runq = &runq_pcpu[cpu];
1532 	if (PCPU_GET(cpuid) == cpu)
1533 		return;
1534 
1535 	mi_switch(SW_VOL, NULL);
1536 #endif
1537 }
1538 
1539 void
1540 sched_unbind(struct thread* td)
1541 {
1542 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1543 	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
1544 	td->td_flags &= ~TDF_BOUND;
1545 }
1546 
1547 int
1548 sched_is_bound(struct thread *td)
1549 {
1550 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1551 	return (td->td_flags & TDF_BOUND);
1552 }
1553 
1554 void
1555 sched_relinquish(struct thread *td)
1556 {
1557 	thread_lock(td);
1558 	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
1559 	thread_unlock(td);
1560 }
1561 
1562 int
1563 sched_load(void)
1564 {
1565 	return (sched_tdcnt);
1566 }
1567 
1568 int
1569 sched_sizeof_proc(void)
1570 {
1571 	return (sizeof(struct proc));
1572 }
1573 
1574 int
1575 sched_sizeof_thread(void)
1576 {
1577 	return (sizeof(struct thread) + sizeof(struct td_sched));
1578 }
1579 
1580 fixpt_t
1581 sched_pctcpu(struct thread *td)
1582 {
1583 	struct td_sched *ts;
1584 
1585 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1586 	ts = td->td_sched;
1587 	return (ts->ts_pctcpu);
1588 }
1589 
1590 #ifdef RACCT
1591 /*
1592  * Calculates the contribution to the thread cpu usage for the latest
1593  * (unfinished) second.
1594  */
1595 fixpt_t
1596 sched_pctcpu_delta(struct thread *td)
1597 {
1598 	struct td_sched *ts;
1599 	fixpt_t delta;
1600 	int realstathz;
1601 
1602 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1603 	ts = td->td_sched;
1604 	delta = 0;
1605 	realstathz = stathz ? stathz : hz;
1606 	if (ts->ts_cpticks != 0) {
1607 #if	(FSHIFT >= CCPU_SHIFT)
1608 		delta = (realstathz == 100)
1609 		    ? ((fixpt_t) ts->ts_cpticks) <<
1610 		    (FSHIFT - CCPU_SHIFT) :
1611 		    100 * (((fixpt_t) ts->ts_cpticks)
1612 		    << (FSHIFT - CCPU_SHIFT)) / realstathz;
1613 #else
1614 		delta = ((FSCALE - ccpu) *
1615 		    (ts->ts_cpticks *
1616 		    FSCALE / realstathz)) >> FSHIFT;
1617 #endif
1618 	}
1619 
1620 	return (delta);
1621 }
1622 #endif
1623 
1624 void
1625 sched_tick(int cnt)
1626 {
1627 }
1628 
1629 /*
1630  * The actual idle process.
1631  */
1632 void
1633 sched_idletd(void *dummy)
1634 {
1635 	struct pcpuidlestat *stat;
1636 
1637 	THREAD_NO_SLEEPING();
1638 	stat = DPCPU_PTR(idlestat);
1639 	for (;;) {
1640 		mtx_assert(&Giant, MA_NOTOWNED);
1641 
1642 		while (sched_runnable() == 0) {
1643 			cpu_idle(stat->idlecalls + stat->oldidlecalls > 64);
1644 			stat->idlecalls++;
1645 		}
1646 
1647 		mtx_lock_spin(&sched_lock);
1648 		mi_switch(SW_VOL | SWT_IDLE, NULL);
1649 		mtx_unlock_spin(&sched_lock);
1650 	}
1651 }
1652 
1653 /*
1654  * A CPU is entering for the first time or a thread is exiting.
1655  */
1656 void
1657 sched_throw(struct thread *td)
1658 {
1659 	/*
1660 	 * Correct spinlock nesting.  The idle thread context that we are
1661 	 * borrowing was created so that it would start out with a single
1662 	 * spin lock (sched_lock) held in fork_trampoline().  Since we've
1663 	 * explicitly acquired locks in this function, the nesting count
1664 	 * is now 2 rather than 1.  Since we are nested, calling
1665 	 * spinlock_exit() will simply adjust the counts without allowing
1666 	 * spin lock using code to interrupt us.
1667 	 */
1668 	if (td == NULL) {
1669 		mtx_lock_spin(&sched_lock);
1670 		spinlock_exit();
1671 		PCPU_SET(switchtime, cpu_ticks());
1672 		PCPU_SET(switchticks, ticks);
1673 	} else {
1674 		lock_profile_release_lock(&sched_lock.lock_object);
1675 		MPASS(td->td_lock == &sched_lock);
1676 		td->td_lastcpu = td->td_oncpu;
1677 		td->td_oncpu = NOCPU;
1678 	}
1679 	mtx_assert(&sched_lock, MA_OWNED);
1680 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
1681 	cpu_throw(td, choosethread());	/* doesn't return */
1682 }
1683 
1684 void
1685 sched_fork_exit(struct thread *td)
1686 {
1687 
1688 	/*
1689 	 * Finish setting up thread glue so that it begins execution in a
1690 	 * non-nested critical section with sched_lock held but not recursed.
1691 	 */
1692 	td->td_oncpu = PCPU_GET(cpuid);
1693 	sched_lock.mtx_lock = (uintptr_t)td;
1694 	lock_profile_obtain_lock_success(&sched_lock.lock_object,
1695 	    0, 0, __FILE__, __LINE__);
1696 	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
1697 }
1698 
1699 char *
1700 sched_tdname(struct thread *td)
1701 {
1702 #ifdef KTR
1703 	struct td_sched *ts;
1704 
1705 	ts = td->td_sched;
1706 	if (ts->ts_name[0] == '\0')
1707 		snprintf(ts->ts_name, sizeof(ts->ts_name),
1708 		    "%s tid %d", td->td_name, td->td_tid);
1709 	return (ts->ts_name);
1710 #else
1711 	return (td->td_name);
1712 #endif
1713 }
1714 
1715 #ifdef KTR
1716 void
1717 sched_clear_tdname(struct thread *td)
1718 {
1719 	struct td_sched *ts;
1720 
1721 	ts = td->td_sched;
1722 	ts->ts_name[0] = '\0';
1723 }
1724 #endif
1725 
1726 void
1727 sched_affinity(struct thread *td)
1728 {
1729 #ifdef SMP
1730 	struct td_sched *ts;
1731 	int cpu;
1732 
1733 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1734 
1735 	/*
1736 	 * Set the TSF_AFFINITY flag if there is at least one CPU this
1737 	 * thread can't run on.
1738 	 */
1739 	ts = td->td_sched;
1740 	ts->ts_flags &= ~TSF_AFFINITY;
1741 	CPU_FOREACH(cpu) {
1742 		if (!THREAD_CAN_SCHED(td, cpu)) {
1743 			ts->ts_flags |= TSF_AFFINITY;
1744 			break;
1745 		}
1746 	}
1747 
1748 	/*
1749 	 * If this thread can run on all CPUs, nothing else to do.
1750 	 */
1751 	if (!(ts->ts_flags & TSF_AFFINITY))
1752 		return;
1753 
1754 	/* Pinned threads and bound threads should be left alone. */
1755 	if (td->td_pinned != 0 || td->td_flags & TDF_BOUND)
1756 		return;
1757 
1758 	switch (td->td_state) {
1759 	case TDS_RUNQ:
1760 		/*
1761 		 * If we are on a per-CPU runqueue that is in the set,
1762 		 * then nothing needs to be done.
1763 		 */
1764 		if (ts->ts_runq != &runq &&
1765 		    THREAD_CAN_SCHED(td, ts->ts_runq - runq_pcpu))
1766 			return;
1767 
1768 		/* Put this thread on a valid per-CPU runqueue. */
1769 		sched_rem(td);
1770 		sched_add(td, SRQ_BORING);
1771 		break;
1772 	case TDS_RUNNING:
1773 		/*
1774 		 * See if our current CPU is in the set.  If not, force a
1775 		 * context switch.
1776 		 */
1777 		if (THREAD_CAN_SCHED(td, td->td_oncpu))
1778 			return;
1779 
1780 		td->td_flags |= TDF_NEEDRESCHED;
1781 		if (td != curthread)
1782 			ipi_cpu(cpu, IPI_AST);
1783 		break;
1784 	default:
1785 		break;
1786 	}
1787 #endif
1788 }
1789