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