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