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