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