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