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