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