xref: /freebsd/sys/kern/sched_4bsd.c (revision 009a196247b29caa5eb892e3ff23f8dacef6c537)
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_estcpu = td->td_estcpu;
796 	childtd->td_lock = &sched_lock;
797 	childtd->td_cpuset = cpuset_ref(td->td_cpuset);
798 	childtd->td_priority = childtd->td_base_pri;
799 	ts = childtd->td_sched;
800 	bzero(ts, sizeof(*ts));
801 	ts->ts_flags |= (td->td_sched->ts_flags & TSF_AFFINITY);
802 	ts->ts_slice = 1;
803 }
804 
805 void
806 sched_nice(struct proc *p, int nice)
807 {
808 	struct thread *td;
809 
810 	PROC_LOCK_ASSERT(p, MA_OWNED);
811 	p->p_nice = nice;
812 	FOREACH_THREAD_IN_PROC(p, td) {
813 		thread_lock(td);
814 		resetpriority(td);
815 		resetpriority_thread(td);
816 		thread_unlock(td);
817 	}
818 }
819 
820 void
821 sched_class(struct thread *td, int class)
822 {
823 	THREAD_LOCK_ASSERT(td, MA_OWNED);
824 	td->td_pri_class = class;
825 }
826 
827 /*
828  * Adjust the priority of a thread.
829  */
830 static void
831 sched_priority(struct thread *td, u_char prio)
832 {
833 
834 
835 	KTR_POINT3(KTR_SCHED, "thread", sched_tdname(td), "priority change",
836 	    "prio:%d", td->td_priority, "new prio:%d", prio, KTR_ATTR_LINKED,
837 	    sched_tdname(curthread));
838 	SDT_PROBE3(sched, , , change__pri, td, td->td_proc, prio);
839 	if (td != curthread && prio > td->td_priority) {
840 		KTR_POINT3(KTR_SCHED, "thread", sched_tdname(curthread),
841 		    "lend prio", "prio:%d", td->td_priority, "new prio:%d",
842 		    prio, KTR_ATTR_LINKED, sched_tdname(td));
843 		SDT_PROBE4(sched, , , lend__pri, td, td->td_proc, prio,
844 		    curthread);
845 	}
846 	THREAD_LOCK_ASSERT(td, MA_OWNED);
847 	if (td->td_priority == prio)
848 		return;
849 	td->td_priority = prio;
850 	if (TD_ON_RUNQ(td) && td->td_rqindex != (prio / RQ_PPQ)) {
851 		sched_rem(td);
852 		sched_add(td, SRQ_BORING);
853 	}
854 }
855 
856 /*
857  * Update a thread's priority when it is lent another thread's
858  * priority.
859  */
860 void
861 sched_lend_prio(struct thread *td, u_char prio)
862 {
863 
864 	td->td_flags |= TDF_BORROWING;
865 	sched_priority(td, prio);
866 }
867 
868 /*
869  * Restore a thread's priority when priority propagation is
870  * over.  The prio argument is the minimum priority the thread
871  * needs to have to satisfy other possible priority lending
872  * requests.  If the thread's regulary priority is less
873  * important than prio the thread will keep a priority boost
874  * of prio.
875  */
876 void
877 sched_unlend_prio(struct thread *td, u_char prio)
878 {
879 	u_char base_pri;
880 
881 	if (td->td_base_pri >= PRI_MIN_TIMESHARE &&
882 	    td->td_base_pri <= PRI_MAX_TIMESHARE)
883 		base_pri = td->td_user_pri;
884 	else
885 		base_pri = td->td_base_pri;
886 	if (prio >= base_pri) {
887 		td->td_flags &= ~TDF_BORROWING;
888 		sched_prio(td, base_pri);
889 	} else
890 		sched_lend_prio(td, prio);
891 }
892 
893 void
894 sched_prio(struct thread *td, u_char prio)
895 {
896 	u_char oldprio;
897 
898 	/* First, update the base priority. */
899 	td->td_base_pri = prio;
900 
901 	/*
902 	 * If the thread is borrowing another thread's priority, don't ever
903 	 * lower the priority.
904 	 */
905 	if (td->td_flags & TDF_BORROWING && td->td_priority < prio)
906 		return;
907 
908 	/* Change the real priority. */
909 	oldprio = td->td_priority;
910 	sched_priority(td, prio);
911 
912 	/*
913 	 * If the thread is on a turnstile, then let the turnstile update
914 	 * its state.
915 	 */
916 	if (TD_ON_LOCK(td) && oldprio != prio)
917 		turnstile_adjust(td, oldprio);
918 }
919 
920 void
921 sched_user_prio(struct thread *td, u_char prio)
922 {
923 
924 	THREAD_LOCK_ASSERT(td, MA_OWNED);
925 	td->td_base_user_pri = prio;
926 	if (td->td_lend_user_pri <= prio)
927 		return;
928 	td->td_user_pri = prio;
929 }
930 
931 void
932 sched_lend_user_prio(struct thread *td, u_char prio)
933 {
934 
935 	THREAD_LOCK_ASSERT(td, MA_OWNED);
936 	td->td_lend_user_pri = prio;
937 	td->td_user_pri = min(prio, td->td_base_user_pri);
938 	if (td->td_priority > td->td_user_pri)
939 		sched_prio(td, td->td_user_pri);
940 	else if (td->td_priority != td->td_user_pri)
941 		td->td_flags |= TDF_NEEDRESCHED;
942 }
943 
944 void
945 sched_sleep(struct thread *td, int pri)
946 {
947 
948 	THREAD_LOCK_ASSERT(td, MA_OWNED);
949 	td->td_slptick = ticks;
950 	td->td_sched->ts_slptime = 0;
951 	if (pri != 0 && PRI_BASE(td->td_pri_class) == PRI_TIMESHARE)
952 		sched_prio(td, pri);
953 	if (TD_IS_SUSPENDED(td) || pri >= PSOCK)
954 		td->td_flags |= TDF_CANSWAP;
955 }
956 
957 void
958 sched_switch(struct thread *td, struct thread *newtd, int flags)
959 {
960 	struct mtx *tmtx;
961 	struct td_sched *ts;
962 	struct proc *p;
963 	int preempted;
964 
965 	tmtx = NULL;
966 	ts = td->td_sched;
967 	p = td->td_proc;
968 
969 	THREAD_LOCK_ASSERT(td, MA_OWNED);
970 
971 	/*
972 	 * Switch to the sched lock to fix things up and pick
973 	 * a new thread.
974 	 * Block the td_lock in order to avoid breaking the critical path.
975 	 */
976 	if (td->td_lock != &sched_lock) {
977 		mtx_lock_spin(&sched_lock);
978 		tmtx = thread_lock_block(td);
979 	}
980 
981 	if ((td->td_flags & TDF_NOLOAD) == 0)
982 		sched_load_rem();
983 
984 	td->td_lastcpu = td->td_oncpu;
985 	preempted = !(td->td_flags & TDF_SLICEEND);
986 	td->td_flags &= ~(TDF_NEEDRESCHED | TDF_SLICEEND);
987 	td->td_owepreempt = 0;
988 	td->td_oncpu = NOCPU;
989 
990 	/*
991 	 * At the last moment, if this thread is still marked RUNNING,
992 	 * then put it back on the run queue as it has not been suspended
993 	 * or stopped or any thing else similar.  We never put the idle
994 	 * threads on the run queue, however.
995 	 */
996 	if (td->td_flags & TDF_IDLETD) {
997 		TD_SET_CAN_RUN(td);
998 #ifdef SMP
999 		CPU_CLR(PCPU_GET(cpuid), &idle_cpus_mask);
1000 #endif
1001 	} else {
1002 		if (TD_IS_RUNNING(td)) {
1003 			/* Put us back on the run queue. */
1004 			sched_add(td, preempted ?
1005 			    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
1006 			    SRQ_OURSELF|SRQ_YIELDING);
1007 		}
1008 	}
1009 	if (newtd) {
1010 		/*
1011 		 * The thread we are about to run needs to be counted
1012 		 * as if it had been added to the run queue and selected.
1013 		 * It came from:
1014 		 * * A preemption
1015 		 * * An upcall
1016 		 * * A followon
1017 		 */
1018 		KASSERT((newtd->td_inhibitors == 0),
1019 			("trying to run inhibited thread"));
1020 		newtd->td_flags |= TDF_DIDRUN;
1021         	TD_SET_RUNNING(newtd);
1022 		if ((newtd->td_flags & TDF_NOLOAD) == 0)
1023 			sched_load_add();
1024 	} else {
1025 		newtd = choosethread();
1026 		MPASS(newtd->td_lock == &sched_lock);
1027 	}
1028 
1029 	if (td != newtd) {
1030 #ifdef	HWPMC_HOOKS
1031 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1032 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_OUT);
1033 #endif
1034 
1035 		SDT_PROBE2(sched, , , off__cpu, newtd, newtd->td_proc);
1036 
1037                 /* I feel sleepy */
1038 		lock_profile_release_lock(&sched_lock.lock_object);
1039 #ifdef KDTRACE_HOOKS
1040 		/*
1041 		 * If DTrace has set the active vtime enum to anything
1042 		 * other than INACTIVE (0), then it should have set the
1043 		 * function to call.
1044 		 */
1045 		if (dtrace_vtime_active)
1046 			(*dtrace_vtime_switch_func)(newtd);
1047 #endif
1048 
1049 		cpu_switch(td, newtd, tmtx != NULL ? tmtx : td->td_lock);
1050 		lock_profile_obtain_lock_success(&sched_lock.lock_object,
1051 		    0, 0, __FILE__, __LINE__);
1052 		/*
1053 		 * Where am I?  What year is it?
1054 		 * We are in the same thread that went to sleep above,
1055 		 * but any amount of time may have passed. All our context
1056 		 * will still be available as will local variables.
1057 		 * PCPU values however may have changed as we may have
1058 		 * changed CPU so don't trust cached values of them.
1059 		 * New threads will go to fork_exit() instead of here
1060 		 * so if you change things here you may need to change
1061 		 * things there too.
1062 		 *
1063 		 * If the thread above was exiting it will never wake
1064 		 * up again here, so either it has saved everything it
1065 		 * needed to, or the thread_wait() or wait() will
1066 		 * need to reap it.
1067 		 */
1068 
1069 		SDT_PROBE0(sched, , , on__cpu);
1070 #ifdef	HWPMC_HOOKS
1071 		if (PMC_PROC_IS_USING_PMCS(td->td_proc))
1072 			PMC_SWITCH_CONTEXT(td, PMC_FN_CSW_IN);
1073 #endif
1074 	} else
1075 		SDT_PROBE0(sched, , , remain__cpu);
1076 
1077 #ifdef SMP
1078 	if (td->td_flags & TDF_IDLETD)
1079 		CPU_SET(PCPU_GET(cpuid), &idle_cpus_mask);
1080 #endif
1081 	sched_lock.mtx_lock = (uintptr_t)td;
1082 	td->td_oncpu = PCPU_GET(cpuid);
1083 	MPASS(td->td_lock == &sched_lock);
1084 }
1085 
1086 void
1087 sched_wakeup(struct thread *td)
1088 {
1089 	struct td_sched *ts;
1090 
1091 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1092 	ts = td->td_sched;
1093 	td->td_flags &= ~TDF_CANSWAP;
1094 	if (ts->ts_slptime > 1) {
1095 		updatepri(td);
1096 		resetpriority(td);
1097 	}
1098 	td->td_slptick = 0;
1099 	ts->ts_slptime = 0;
1100 	ts->ts_slice = sched_slice;
1101 	sched_add(td, SRQ_BORING);
1102 }
1103 
1104 #ifdef SMP
1105 static int
1106 forward_wakeup(int cpunum)
1107 {
1108 	struct pcpu *pc;
1109 	cpuset_t dontuse, map, map2;
1110 	u_int id, me;
1111 	int iscpuset;
1112 
1113 	mtx_assert(&sched_lock, MA_OWNED);
1114 
1115 	CTR0(KTR_RUNQ, "forward_wakeup()");
1116 
1117 	if ((!forward_wakeup_enabled) ||
1118 	     (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
1119 		return (0);
1120 	if (!smp_started || cold || panicstr)
1121 		return (0);
1122 
1123 	forward_wakeups_requested++;
1124 
1125 	/*
1126 	 * Check the idle mask we received against what we calculated
1127 	 * before in the old version.
1128 	 */
1129 	me = PCPU_GET(cpuid);
1130 
1131 	/* Don't bother if we should be doing it ourself. */
1132 	if (CPU_ISSET(me, &idle_cpus_mask) &&
1133 	    (cpunum == NOCPU || me == cpunum))
1134 		return (0);
1135 
1136 	CPU_SETOF(me, &dontuse);
1137 	CPU_OR(&dontuse, &stopped_cpus);
1138 	CPU_OR(&dontuse, &hlt_cpus_mask);
1139 	CPU_ZERO(&map2);
1140 	if (forward_wakeup_use_loop) {
1141 		STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1142 			id = pc->pc_cpuid;
1143 			if (!CPU_ISSET(id, &dontuse) &&
1144 			    pc->pc_curthread == pc->pc_idlethread) {
1145 				CPU_SET(id, &map2);
1146 			}
1147 		}
1148 	}
1149 
1150 	if (forward_wakeup_use_mask) {
1151 		map = idle_cpus_mask;
1152 		CPU_NAND(&map, &dontuse);
1153 
1154 		/* If they are both on, compare and use loop if different. */
1155 		if (forward_wakeup_use_loop) {
1156 			if (CPU_CMP(&map, &map2)) {
1157 				printf("map != map2, loop method preferred\n");
1158 				map = map2;
1159 			}
1160 		}
1161 	} else {
1162 		map = map2;
1163 	}
1164 
1165 	/* If we only allow a specific CPU, then mask off all the others. */
1166 	if (cpunum != NOCPU) {
1167 		KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
1168 		iscpuset = CPU_ISSET(cpunum, &map);
1169 		if (iscpuset == 0)
1170 			CPU_ZERO(&map);
1171 		else
1172 			CPU_SETOF(cpunum, &map);
1173 	}
1174 	if (!CPU_EMPTY(&map)) {
1175 		forward_wakeups_delivered++;
1176 		STAILQ_FOREACH(pc, &cpuhead, pc_allcpu) {
1177 			id = pc->pc_cpuid;
1178 			if (!CPU_ISSET(id, &map))
1179 				continue;
1180 			if (cpu_idle_wakeup(pc->pc_cpuid))
1181 				CPU_CLR(id, &map);
1182 		}
1183 		if (!CPU_EMPTY(&map))
1184 			ipi_selected(map, IPI_AST);
1185 		return (1);
1186 	}
1187 	if (cpunum == NOCPU)
1188 		printf("forward_wakeup: Idle processor not found\n");
1189 	return (0);
1190 }
1191 
1192 static void
1193 kick_other_cpu(int pri, int cpuid)
1194 {
1195 	struct pcpu *pcpu;
1196 	int cpri;
1197 
1198 	pcpu = pcpu_find(cpuid);
1199 	if (CPU_ISSET(cpuid, &idle_cpus_mask)) {
1200 		forward_wakeups_delivered++;
1201 		if (!cpu_idle_wakeup(cpuid))
1202 			ipi_cpu(cpuid, IPI_AST);
1203 		return;
1204 	}
1205 
1206 	cpri = pcpu->pc_curthread->td_priority;
1207 	if (pri >= cpri)
1208 		return;
1209 
1210 #if defined(IPI_PREEMPTION) && defined(PREEMPTION)
1211 #if !defined(FULL_PREEMPTION)
1212 	if (pri <= PRI_MAX_ITHD)
1213 #endif /* ! FULL_PREEMPTION */
1214 	{
1215 		ipi_cpu(cpuid, IPI_PREEMPT);
1216 		return;
1217 	}
1218 #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
1219 
1220 	pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
1221 	ipi_cpu(cpuid, IPI_AST);
1222 	return;
1223 }
1224 #endif /* SMP */
1225 
1226 #ifdef SMP
1227 static int
1228 sched_pickcpu(struct thread *td)
1229 {
1230 	int best, cpu;
1231 
1232 	mtx_assert(&sched_lock, MA_OWNED);
1233 
1234 	if (THREAD_CAN_SCHED(td, td->td_lastcpu))
1235 		best = td->td_lastcpu;
1236 	else
1237 		best = NOCPU;
1238 	CPU_FOREACH(cpu) {
1239 		if (!THREAD_CAN_SCHED(td, cpu))
1240 			continue;
1241 
1242 		if (best == NOCPU)
1243 			best = cpu;
1244 		else if (runq_length[cpu] < runq_length[best])
1245 			best = cpu;
1246 	}
1247 	KASSERT(best != NOCPU, ("no valid CPUs"));
1248 
1249 	return (best);
1250 }
1251 #endif
1252 
1253 void
1254 sched_add(struct thread *td, int flags)
1255 #ifdef SMP
1256 {
1257 	cpuset_t tidlemsk;
1258 	struct td_sched *ts;
1259 	u_int cpu, cpuid;
1260 	int forwarded = 0;
1261 	int single_cpu = 0;
1262 
1263 	ts = td->td_sched;
1264 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1265 	KASSERT((td->td_inhibitors == 0),
1266 	    ("sched_add: trying to run inhibited thread"));
1267 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1268 	    ("sched_add: bad thread state"));
1269 	KASSERT(td->td_flags & TDF_INMEM,
1270 	    ("sched_add: thread swapped out"));
1271 
1272 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
1273 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1274 	    sched_tdname(curthread));
1275 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
1276 	    KTR_ATTR_LINKED, sched_tdname(td));
1277 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1278 	    flags & SRQ_PREEMPTED);
1279 
1280 
1281 	/*
1282 	 * Now that the thread is moving to the run-queue, set the lock
1283 	 * to the scheduler's lock.
1284 	 */
1285 	if (td->td_lock != &sched_lock) {
1286 		mtx_lock_spin(&sched_lock);
1287 		thread_lock_set(td, &sched_lock);
1288 	}
1289 	TD_SET_RUNQ(td);
1290 
1291 	/*
1292 	 * If SMP is started and the thread is pinned or otherwise limited to
1293 	 * a specific set of CPUs, queue the thread to a per-CPU run queue.
1294 	 * Otherwise, queue the thread to the global run queue.
1295 	 *
1296 	 * If SMP has not yet been started we must use the global run queue
1297 	 * as per-CPU state may not be initialized yet and we may crash if we
1298 	 * try to access the per-CPU run queues.
1299 	 */
1300 	if (smp_started && (td->td_pinned != 0 || td->td_flags & TDF_BOUND ||
1301 	    ts->ts_flags & TSF_AFFINITY)) {
1302 		if (td->td_pinned != 0)
1303 			cpu = td->td_lastcpu;
1304 		else if (td->td_flags & TDF_BOUND) {
1305 			/* Find CPU from bound runq. */
1306 			KASSERT(SKE_RUNQ_PCPU(ts),
1307 			    ("sched_add: bound td_sched not on cpu runq"));
1308 			cpu = ts->ts_runq - &runq_pcpu[0];
1309 		} else
1310 			/* Find a valid CPU for our cpuset */
1311 			cpu = sched_pickcpu(td);
1312 		ts->ts_runq = &runq_pcpu[cpu];
1313 		single_cpu = 1;
1314 		CTR3(KTR_RUNQ,
1315 		    "sched_add: Put td_sched:%p(td:%p) on cpu%d runq", ts, td,
1316 		    cpu);
1317 	} else {
1318 		CTR2(KTR_RUNQ,
1319 		    "sched_add: adding td_sched:%p (td:%p) to gbl runq", ts,
1320 		    td);
1321 		cpu = NOCPU;
1322 		ts->ts_runq = &runq;
1323 	}
1324 
1325 	cpuid = PCPU_GET(cpuid);
1326 	if (single_cpu && cpu != cpuid) {
1327 	        kick_other_cpu(td->td_priority, cpu);
1328 	} else {
1329 		if (!single_cpu) {
1330 			tidlemsk = idle_cpus_mask;
1331 			CPU_NAND(&tidlemsk, &hlt_cpus_mask);
1332 			CPU_CLR(cpuid, &tidlemsk);
1333 
1334 			if (!CPU_ISSET(cpuid, &idle_cpus_mask) &&
1335 			    ((flags & SRQ_INTR) == 0) &&
1336 			    !CPU_EMPTY(&tidlemsk))
1337 				forwarded = forward_wakeup(cpu);
1338 		}
1339 
1340 		if (!forwarded) {
1341 			if ((flags & SRQ_YIELDING) == 0 && maybe_preempt(td))
1342 				return;
1343 			else
1344 				maybe_resched(td);
1345 		}
1346 	}
1347 
1348 	if ((td->td_flags & TDF_NOLOAD) == 0)
1349 		sched_load_add();
1350 	runq_add(ts->ts_runq, td, flags);
1351 	if (cpu != NOCPU)
1352 		runq_length[cpu]++;
1353 }
1354 #else /* SMP */
1355 {
1356 	struct td_sched *ts;
1357 
1358 	ts = td->td_sched;
1359 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1360 	KASSERT((td->td_inhibitors == 0),
1361 	    ("sched_add: trying to run inhibited thread"));
1362 	KASSERT((TD_CAN_RUN(td) || TD_IS_RUNNING(td)),
1363 	    ("sched_add: bad thread state"));
1364 	KASSERT(td->td_flags & TDF_INMEM,
1365 	    ("sched_add: thread swapped out"));
1366 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq add",
1367 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1368 	    sched_tdname(curthread));
1369 	KTR_POINT1(KTR_SCHED, "thread", sched_tdname(curthread), "wokeup",
1370 	    KTR_ATTR_LINKED, sched_tdname(td));
1371 	SDT_PROBE4(sched, , , enqueue, td, td->td_proc, NULL,
1372 	    flags & SRQ_PREEMPTED);
1373 
1374 	/*
1375 	 * Now that the thread is moving to the run-queue, set the lock
1376 	 * to the scheduler's lock.
1377 	 */
1378 	if (td->td_lock != &sched_lock) {
1379 		mtx_lock_spin(&sched_lock);
1380 		thread_lock_set(td, &sched_lock);
1381 	}
1382 	TD_SET_RUNQ(td);
1383 	CTR2(KTR_RUNQ, "sched_add: adding td_sched:%p (td:%p) to runq", ts, td);
1384 	ts->ts_runq = &runq;
1385 
1386 	/*
1387 	 * If we are yielding (on the way out anyhow) or the thread
1388 	 * being saved is US, then don't try be smart about preemption
1389 	 * or kicking off another CPU as it won't help and may hinder.
1390 	 * In the YIEDLING case, we are about to run whoever is being
1391 	 * put in the queue anyhow, and in the OURSELF case, we are
1392 	 * puting ourself on the run queue which also only happens
1393 	 * when we are about to yield.
1394 	 */
1395 	if ((flags & SRQ_YIELDING) == 0) {
1396 		if (maybe_preempt(td))
1397 			return;
1398 	}
1399 	if ((td->td_flags & TDF_NOLOAD) == 0)
1400 		sched_load_add();
1401 	runq_add(ts->ts_runq, td, flags);
1402 	maybe_resched(td);
1403 }
1404 #endif /* SMP */
1405 
1406 void
1407 sched_rem(struct thread *td)
1408 {
1409 	struct td_sched *ts;
1410 
1411 	ts = td->td_sched;
1412 	KASSERT(td->td_flags & TDF_INMEM,
1413 	    ("sched_rem: thread swapped out"));
1414 	KASSERT(TD_ON_RUNQ(td),
1415 	    ("sched_rem: thread not on run queue"));
1416 	mtx_assert(&sched_lock, MA_OWNED);
1417 	KTR_STATE2(KTR_SCHED, "thread", sched_tdname(td), "runq rem",
1418 	    "prio:%d", td->td_priority, KTR_ATTR_LINKED,
1419 	    sched_tdname(curthread));
1420 	SDT_PROBE3(sched, , , dequeue, td, td->td_proc, NULL);
1421 
1422 	if ((td->td_flags & TDF_NOLOAD) == 0)
1423 		sched_load_rem();
1424 #ifdef SMP
1425 	if (ts->ts_runq != &runq)
1426 		runq_length[ts->ts_runq - runq_pcpu]--;
1427 #endif
1428 	runq_remove(ts->ts_runq, td);
1429 	TD_SET_CAN_RUN(td);
1430 }
1431 
1432 /*
1433  * Select threads to run.  Note that running threads still consume a
1434  * slot.
1435  */
1436 struct thread *
1437 sched_choose(void)
1438 {
1439 	struct thread *td;
1440 	struct runq *rq;
1441 
1442 	mtx_assert(&sched_lock,  MA_OWNED);
1443 #ifdef SMP
1444 	struct thread *tdcpu;
1445 
1446 	rq = &runq;
1447 	td = runq_choose_fuzz(&runq, runq_fuzz);
1448 	tdcpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1449 
1450 	if (td == NULL ||
1451 	    (tdcpu != NULL &&
1452 	     tdcpu->td_priority < td->td_priority)) {
1453 		CTR2(KTR_RUNQ, "choosing td %p from pcpu runq %d", tdcpu,
1454 		     PCPU_GET(cpuid));
1455 		td = tdcpu;
1456 		rq = &runq_pcpu[PCPU_GET(cpuid)];
1457 	} else {
1458 		CTR1(KTR_RUNQ, "choosing td_sched %p from main runq", td);
1459 	}
1460 
1461 #else
1462 	rq = &runq;
1463 	td = runq_choose(&runq);
1464 #endif
1465 
1466 	if (td) {
1467 #ifdef SMP
1468 		if (td == tdcpu)
1469 			runq_length[PCPU_GET(cpuid)]--;
1470 #endif
1471 		runq_remove(rq, td);
1472 		td->td_flags |= TDF_DIDRUN;
1473 
1474 		KASSERT(td->td_flags & TDF_INMEM,
1475 		    ("sched_choose: thread swapped out"));
1476 		return (td);
1477 	}
1478 	return (PCPU_GET(idlethread));
1479 }
1480 
1481 void
1482 sched_preempt(struct thread *td)
1483 {
1484 
1485 	SDT_PROBE2(sched, , , surrender, td, td->td_proc);
1486 	thread_lock(td);
1487 	if (td->td_critnest > 1)
1488 		td->td_owepreempt = 1;
1489 	else
1490 		mi_switch(SW_INVOL | SW_PREEMPT | SWT_PREEMPT, NULL);
1491 	thread_unlock(td);
1492 }
1493 
1494 void
1495 sched_userret(struct thread *td)
1496 {
1497 	/*
1498 	 * XXX we cheat slightly on the locking here to avoid locking in
1499 	 * the usual case.  Setting td_priority here is essentially an
1500 	 * incomplete workaround for not setting it properly elsewhere.
1501 	 * Now that some interrupt handlers are threads, not setting it
1502 	 * properly elsewhere can clobber it in the window between setting
1503 	 * it here and returning to user mode, so don't waste time setting
1504 	 * it perfectly here.
1505 	 */
1506 	KASSERT((td->td_flags & TDF_BORROWING) == 0,
1507 	    ("thread with borrowed priority returning to userland"));
1508 	if (td->td_priority != td->td_user_pri) {
1509 		thread_lock(td);
1510 		td->td_priority = td->td_user_pri;
1511 		td->td_base_pri = td->td_user_pri;
1512 		thread_unlock(td);
1513 	}
1514 }
1515 
1516 void
1517 sched_bind(struct thread *td, int cpu)
1518 {
1519 	struct td_sched *ts;
1520 
1521 	THREAD_LOCK_ASSERT(td, MA_OWNED|MA_NOTRECURSED);
1522 	KASSERT(td == curthread, ("sched_bind: can only bind curthread"));
1523 
1524 	ts = td->td_sched;
1525 
1526 	td->td_flags |= TDF_BOUND;
1527 #ifdef SMP
1528 	ts->ts_runq = &runq_pcpu[cpu];
1529 	if (PCPU_GET(cpuid) == cpu)
1530 		return;
1531 
1532 	mi_switch(SW_VOL, NULL);
1533 #endif
1534 }
1535 
1536 void
1537 sched_unbind(struct thread* td)
1538 {
1539 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1540 	KASSERT(td == curthread, ("sched_unbind: can only bind curthread"));
1541 	td->td_flags &= ~TDF_BOUND;
1542 }
1543 
1544 int
1545 sched_is_bound(struct thread *td)
1546 {
1547 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1548 	return (td->td_flags & TDF_BOUND);
1549 }
1550 
1551 void
1552 sched_relinquish(struct thread *td)
1553 {
1554 	thread_lock(td);
1555 	mi_switch(SW_VOL | SWT_RELINQUISH, NULL);
1556 	thread_unlock(td);
1557 }
1558 
1559 int
1560 sched_load(void)
1561 {
1562 	return (sched_tdcnt);
1563 }
1564 
1565 int
1566 sched_sizeof_proc(void)
1567 {
1568 	return (sizeof(struct proc));
1569 }
1570 
1571 int
1572 sched_sizeof_thread(void)
1573 {
1574 	return (sizeof(struct thread) + sizeof(struct td_sched));
1575 }
1576 
1577 fixpt_t
1578 sched_pctcpu(struct thread *td)
1579 {
1580 	struct td_sched *ts;
1581 
1582 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1583 	ts = td->td_sched;
1584 	return (ts->ts_pctcpu);
1585 }
1586 
1587 #ifdef	RACCT
1588 /*
1589  * Calculates the contribution to the thread cpu usage for the latest
1590  * (unfinished) second.
1591  */
1592 fixpt_t
1593 sched_pctcpu_delta(struct thread *td)
1594 {
1595 	struct td_sched *ts;
1596 	fixpt_t delta;
1597 	int realstathz;
1598 
1599 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1600 	ts = td->td_sched;
1601 	delta = 0;
1602 	realstathz = stathz ? stathz : hz;
1603 	if (ts->ts_cpticks != 0) {
1604 #if	(FSHIFT >= CCPU_SHIFT)
1605 		delta = (realstathz == 100)
1606 		    ? ((fixpt_t) ts->ts_cpticks) <<
1607 		    (FSHIFT - CCPU_SHIFT) :
1608 		    100 * (((fixpt_t) ts->ts_cpticks)
1609 		    << (FSHIFT - CCPU_SHIFT)) / realstathz;
1610 #else
1611 		delta = ((FSCALE - ccpu) *
1612 		    (ts->ts_cpticks *
1613 		    FSCALE / realstathz)) >> FSHIFT;
1614 #endif
1615 	}
1616 
1617 	return (delta);
1618 }
1619 #endif
1620 
1621 void
1622 sched_tick(int cnt)
1623 {
1624 }
1625 
1626 /*
1627  * The actual idle process.
1628  */
1629 void
1630 sched_idletd(void *dummy)
1631 {
1632 	struct pcpuidlestat *stat;
1633 
1634 	THREAD_NO_SLEEPING();
1635 	stat = DPCPU_PTR(idlestat);
1636 	for (;;) {
1637 		mtx_assert(&Giant, MA_NOTOWNED);
1638 
1639 		while (sched_runnable() == 0) {
1640 			cpu_idle(stat->idlecalls + stat->oldidlecalls > 64);
1641 			stat->idlecalls++;
1642 		}
1643 
1644 		mtx_lock_spin(&sched_lock);
1645 		mi_switch(SW_VOL | SWT_IDLE, NULL);
1646 		mtx_unlock_spin(&sched_lock);
1647 	}
1648 }
1649 
1650 /*
1651  * A CPU is entering for the first time or a thread is exiting.
1652  */
1653 void
1654 sched_throw(struct thread *td)
1655 {
1656 	/*
1657 	 * Correct spinlock nesting.  The idle thread context that we are
1658 	 * borrowing was created so that it would start out with a single
1659 	 * spin lock (sched_lock) held in fork_trampoline().  Since we've
1660 	 * explicitly acquired locks in this function, the nesting count
1661 	 * is now 2 rather than 1.  Since we are nested, calling
1662 	 * spinlock_exit() will simply adjust the counts without allowing
1663 	 * spin lock using code to interrupt us.
1664 	 */
1665 	if (td == NULL) {
1666 		mtx_lock_spin(&sched_lock);
1667 		spinlock_exit();
1668 		PCPU_SET(switchtime, cpu_ticks());
1669 		PCPU_SET(switchticks, ticks);
1670 	} else {
1671 		lock_profile_release_lock(&sched_lock.lock_object);
1672 		MPASS(td->td_lock == &sched_lock);
1673 	}
1674 	mtx_assert(&sched_lock, MA_OWNED);
1675 	KASSERT(curthread->td_md.md_spinlock_count == 1, ("invalid count"));
1676 	cpu_throw(td, choosethread());	/* doesn't return */
1677 }
1678 
1679 void
1680 sched_fork_exit(struct thread *td)
1681 {
1682 
1683 	/*
1684 	 * Finish setting up thread glue so that it begins execution in a
1685 	 * non-nested critical section with sched_lock held but not recursed.
1686 	 */
1687 	td->td_oncpu = PCPU_GET(cpuid);
1688 	sched_lock.mtx_lock = (uintptr_t)td;
1689 	lock_profile_obtain_lock_success(&sched_lock.lock_object,
1690 	    0, 0, __FILE__, __LINE__);
1691 	THREAD_LOCK_ASSERT(td, MA_OWNED | MA_NOTRECURSED);
1692 }
1693 
1694 char *
1695 sched_tdname(struct thread *td)
1696 {
1697 #ifdef KTR
1698 	struct td_sched *ts;
1699 
1700 	ts = td->td_sched;
1701 	if (ts->ts_name[0] == '\0')
1702 		snprintf(ts->ts_name, sizeof(ts->ts_name),
1703 		    "%s tid %d", td->td_name, td->td_tid);
1704 	return (ts->ts_name);
1705 #else
1706 	return (td->td_name);
1707 #endif
1708 }
1709 
1710 #ifdef KTR
1711 void
1712 sched_clear_tdname(struct thread *td)
1713 {
1714 	struct td_sched *ts;
1715 
1716 	ts = td->td_sched;
1717 	ts->ts_name[0] = '\0';
1718 }
1719 #endif
1720 
1721 void
1722 sched_affinity(struct thread *td)
1723 {
1724 #ifdef SMP
1725 	struct td_sched *ts;
1726 	int cpu;
1727 
1728 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1729 
1730 	/*
1731 	 * Set the TSF_AFFINITY flag if there is at least one CPU this
1732 	 * thread can't run on.
1733 	 */
1734 	ts = td->td_sched;
1735 	ts->ts_flags &= ~TSF_AFFINITY;
1736 	CPU_FOREACH(cpu) {
1737 		if (!THREAD_CAN_SCHED(td, cpu)) {
1738 			ts->ts_flags |= TSF_AFFINITY;
1739 			break;
1740 		}
1741 	}
1742 
1743 	/*
1744 	 * If this thread can run on all CPUs, nothing else to do.
1745 	 */
1746 	if (!(ts->ts_flags & TSF_AFFINITY))
1747 		return;
1748 
1749 	/* Pinned threads and bound threads should be left alone. */
1750 	if (td->td_pinned != 0 || td->td_flags & TDF_BOUND)
1751 		return;
1752 
1753 	switch (td->td_state) {
1754 	case TDS_RUNQ:
1755 		/*
1756 		 * If we are on a per-CPU runqueue that is in the set,
1757 		 * then nothing needs to be done.
1758 		 */
1759 		if (ts->ts_runq != &runq &&
1760 		    THREAD_CAN_SCHED(td, ts->ts_runq - runq_pcpu))
1761 			return;
1762 
1763 		/* Put this thread on a valid per-CPU runqueue. */
1764 		sched_rem(td);
1765 		sched_add(td, SRQ_BORING);
1766 		break;
1767 	case TDS_RUNNING:
1768 		/*
1769 		 * See if our current CPU is in the set.  If not, force a
1770 		 * context switch.
1771 		 */
1772 		if (THREAD_CAN_SCHED(td, td->td_oncpu))
1773 			return;
1774 
1775 		td->td_flags |= TDF_NEEDRESCHED;
1776 		if (td != curthread)
1777 			ipi_cpu(cpu, IPI_AST);
1778 		break;
1779 	default:
1780 		break;
1781 	}
1782 #endif
1783 }
1784