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