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