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