xref: /freebsd/sys/kern/sched_4bsd.c (revision e653b48c80fb85b2a10372d664a4b55dbdc51dae)
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  * 4. 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 #define kse td_sched
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/kernel.h>
43 #include <sys/ktr.h>
44 #include <sys/lock.h>
45 #include <sys/kthread.h>
46 #include <sys/mutex.h>
47 #include <sys/proc.h>
48 #include <sys/resourcevar.h>
49 #include <sys/sched.h>
50 #include <sys/smp.h>
51 #include <sys/sysctl.h>
52 #include <sys/sx.h>
53 #include <machine/smp.h>
54 
55 /*
56  * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
57  * the range 100-256 Hz (approximately).
58  */
59 #define	ESTCPULIM(e) \
60     min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
61     RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
62 #ifdef SMP
63 #define	INVERSE_ESTCPU_WEIGHT	(8 * smp_cpus)
64 #else
65 #define	INVERSE_ESTCPU_WEIGHT	8	/* 1 / (priorities per estcpu level). */
66 #endif
67 #define	NICE_WEIGHT		1	/* Priorities per nice level. */
68 
69 /*
70  * The schedulable entity that can be given a context to run.
71  * A process may have several of these. Probably one per processor
72  * but posibly a few more. In this universe they are grouped
73  * with a KSEG that contains the priority and niceness
74  * for the group.
75  */
76 struct kse {
77 	TAILQ_ENTRY(kse) ke_procq;	/* (j/z) Run queue. */
78 	struct thread	*ke_thread;	/* (*) Active associated thread. */
79 	fixpt_t		ke_pctcpu;	/* (j) %cpu during p_swtime. */
80 	char		ke_rqindex;	/* (j) Run queue index. */
81 	enum {
82 		KES_THREAD = 0x0,	/* slaved to thread state */
83 		KES_ONRUNQ
84 	} ke_state;			/* (j) KSE status. */
85 	int		ke_cpticks;	/* (j) Ticks of cpu time. */
86 	struct runq	*ke_runq;	/* runq the kse is currently on */
87 };
88 
89 #define ke_proc		ke_thread->td_proc
90 #define ke_ksegrp	ke_thread->td_ksegrp
91 
92 #define td_kse td_sched
93 
94 /* flags kept in td_flags */
95 #define TDF_DIDRUN	TDF_SCHED0	/* KSE actually ran. */
96 #define TDF_EXIT	TDF_SCHED1	/* KSE is being killed. */
97 #define TDF_BOUND	TDF_SCHED2
98 
99 #define ke_flags	ke_thread->td_flags
100 #define KEF_DIDRUN	TDF_DIDRUN /* KSE actually ran. */
101 #define KEF_EXIT	TDF_EXIT /* KSE is being killed. */
102 #define KEF_BOUND	TDF_BOUND /* stuck to one CPU */
103 
104 #define SKE_RUNQ_PCPU(ke)						\
105     ((ke)->ke_runq != 0 && (ke)->ke_runq != &runq)
106 
107 struct kg_sched {
108 	struct thread	*skg_last_assigned; /* (j) Last thread assigned to */
109 					   /* the system scheduler. */
110 	int	skg_avail_opennings;	/* (j) Num KSEs requested in group. */
111 	int	skg_concurrency;	/* (j) Num KSEs requested in group. */
112 };
113 #define kg_last_assigned	kg_sched->skg_last_assigned
114 #define kg_avail_opennings	kg_sched->skg_avail_opennings
115 #define kg_concurrency		kg_sched->skg_concurrency
116 
117 #define SLOT_RELEASE(kg)						\
118 do {									\
119 	kg->kg_avail_opennings++; 					\
120 	CTR3(KTR_RUNQ, "kg %p(%d) Slot released (->%d)",		\
121 	kg,								\
122 	kg->kg_concurrency,						\
123 	 kg->kg_avail_opennings);					\
124 /*	KASSERT((kg->kg_avail_opennings <= kg->kg_concurrency),		\
125 	    ("slots out of whack"));*/					\
126 } while (0)
127 
128 #define SLOT_USE(kg)							\
129 do {									\
130 	kg->kg_avail_opennings--; 					\
131 	CTR3(KTR_RUNQ, "kg %p(%d) Slot used (->%d)",			\
132 	kg,								\
133 	kg->kg_concurrency,						\
134 	 kg->kg_avail_opennings);					\
135 /*	KASSERT((kg->kg_avail_opennings >= 0),				\
136 	    ("slots out of whack"));*/					\
137 } while (0)
138 
139 /*
140  * KSE_CAN_MIGRATE macro returns true if the kse can migrate between
141  * cpus.
142  */
143 #define KSE_CAN_MIGRATE(ke)						\
144     ((ke)->ke_thread->td_pinned == 0 && ((ke)->ke_flags & KEF_BOUND) == 0)
145 
146 static struct kse kse0;
147 static struct kg_sched kg_sched0;
148 
149 static int	sched_tdcnt;	/* Total runnable threads in the system. */
150 static int	sched_quantum;	/* Roundrobin scheduling quantum in ticks. */
151 #define	SCHED_QUANTUM	(hz / 10)	/* Default sched quantum */
152 
153 static struct callout roundrobin_callout;
154 
155 static void	slot_fill(struct ksegrp *kg);
156 static struct kse *sched_choose(void);		/* XXX Should be thread * */
157 
158 static void	setup_runqs(void);
159 static void	roundrobin(void *arg);
160 static void	schedcpu(void);
161 static void	schedcpu_thread(void);
162 static void	sched_setup(void *dummy);
163 static void	maybe_resched(struct thread *td);
164 static void	updatepri(struct ksegrp *kg);
165 static void	resetpriority(struct ksegrp *kg);
166 #ifdef SMP
167 static int	forward_wakeup(int  cpunum);
168 #endif
169 
170 static struct kproc_desc sched_kp = {
171         "schedcpu",
172         schedcpu_thread,
173         NULL
174 };
175 SYSINIT(schedcpu, SI_SUB_RUN_SCHEDULER, SI_ORDER_FIRST, kproc_start, &sched_kp)
176 SYSINIT(sched_setup, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, sched_setup, NULL)
177 
178 /*
179  * Global run queue.
180  */
181 static struct runq runq;
182 
183 #ifdef SMP
184 /*
185  * Per-CPU run queues
186  */
187 static struct runq runq_pcpu[MAXCPU];
188 #endif
189 
190 static void
191 setup_runqs(void)
192 {
193 #ifdef SMP
194 	int i;
195 
196 	for (i = 0; i < MAXCPU; ++i)
197 		runq_init(&runq_pcpu[i]);
198 #endif
199 
200 	runq_init(&runq);
201 }
202 
203 static int
204 sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
205 {
206 	int error, new_val;
207 
208 	new_val = sched_quantum * tick;
209 	error = sysctl_handle_int(oidp, &new_val, 0, req);
210         if (error != 0 || req->newptr == NULL)
211 		return (error);
212 	if (new_val < tick)
213 		return (EINVAL);
214 	sched_quantum = new_val / tick;
215 	hogticks = 2 * sched_quantum;
216 	return (0);
217 }
218 
219 SYSCTL_NODE(_kern, OID_AUTO, sched, CTLFLAG_RD, 0, "Scheduler");
220 
221 SYSCTL_STRING(_kern_sched, OID_AUTO, name, CTLFLAG_RD, "4BSD", 0,
222     "Scheduler name");
223 
224 SYSCTL_PROC(_kern_sched, OID_AUTO, quantum, CTLTYPE_INT | CTLFLAG_RW,
225     0, sizeof sched_quantum, sysctl_kern_quantum, "I",
226     "Roundrobin scheduling quantum in microseconds");
227 
228 #ifdef SMP
229 /* Enable forwarding of wakeups to all other cpus */
230 SYSCTL_NODE(_kern_sched, OID_AUTO, ipiwakeup, CTLFLAG_RD, NULL, "Kernel SMP");
231 
232 static int forward_wakeup_enabled = 1;
233 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, enabled, CTLFLAG_RW,
234 	   &forward_wakeup_enabled, 0,
235 	   "Forwarding of wakeup to idle CPUs");
236 
237 static int forward_wakeups_requested = 0;
238 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, requested, CTLFLAG_RD,
239 	   &forward_wakeups_requested, 0,
240 	   "Requests for Forwarding of wakeup to idle CPUs");
241 
242 static int forward_wakeups_delivered = 0;
243 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, delivered, CTLFLAG_RD,
244 	   &forward_wakeups_delivered, 0,
245 	   "Completed Forwarding of wakeup to idle CPUs");
246 
247 static int forward_wakeup_use_mask = 1;
248 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, usemask, CTLFLAG_RW,
249 	   &forward_wakeup_use_mask, 0,
250 	   "Use the mask of idle cpus");
251 
252 static int forward_wakeup_use_loop = 0;
253 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, useloop, CTLFLAG_RW,
254 	   &forward_wakeup_use_loop, 0,
255 	   "Use a loop to find idle cpus");
256 
257 static int forward_wakeup_use_single = 0;
258 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, onecpu, CTLFLAG_RW,
259 	   &forward_wakeup_use_single, 0,
260 	   "Only signal one idle cpu");
261 
262 static int forward_wakeup_use_htt = 0;
263 SYSCTL_INT(_kern_sched_ipiwakeup, OID_AUTO, htt2, CTLFLAG_RW,
264 	   &forward_wakeup_use_htt, 0,
265 	   "account for htt");
266 
267 #endif
268 static int sched_followon = 0;
269 SYSCTL_INT(_kern_sched, OID_AUTO, followon, CTLFLAG_RW,
270 	   &sched_followon, 0,
271 	   "allow threads to share a quantum");
272 
273 static int sched_pfollowons = 0;
274 SYSCTL_INT(_kern_sched, OID_AUTO, pfollowons, CTLFLAG_RD,
275 	   &sched_pfollowons, 0,
276 	   "number of followons done to a different ksegrp");
277 
278 static int sched_kgfollowons = 0;
279 SYSCTL_INT(_kern_sched, OID_AUTO, kgfollowons, CTLFLAG_RD,
280 	   &sched_kgfollowons, 0,
281 	   "number of followons done in a ksegrp");
282 
283 /*
284  * Arrange to reschedule if necessary, taking the priorities and
285  * schedulers into account.
286  */
287 static void
288 maybe_resched(struct thread *td)
289 {
290 
291 	mtx_assert(&sched_lock, MA_OWNED);
292 	if (td->td_priority < curthread->td_priority)
293 		curthread->td_flags |= TDF_NEEDRESCHED;
294 }
295 
296 /*
297  * Force switch among equal priority processes every 100ms.
298  * We don't actually need to force a context switch of the current process.
299  * The act of firing the event triggers a context switch to softclock() and
300  * then switching back out again which is equivalent to a preemption, thus
301  * no further work is needed on the local CPU.
302  */
303 /* ARGSUSED */
304 static void
305 roundrobin(void *arg)
306 {
307 
308 #ifdef SMP
309 	mtx_lock_spin(&sched_lock);
310 	forward_roundrobin();
311 	mtx_unlock_spin(&sched_lock);
312 #endif
313 
314 	callout_reset(&roundrobin_callout, sched_quantum, roundrobin, NULL);
315 }
316 
317 /*
318  * Constants for digital decay and forget:
319  *	90% of (kg_estcpu) usage in 5 * loadav time
320  *	95% of (ke_pctcpu) usage in 60 seconds (load insensitive)
321  *          Note that, as ps(1) mentions, this can let percentages
322  *          total over 100% (I've seen 137.9% for 3 processes).
323  *
324  * Note that schedclock() updates kg_estcpu and p_cpticks asynchronously.
325  *
326  * We wish to decay away 90% of kg_estcpu in (5 * loadavg) seconds.
327  * That is, the system wants to compute a value of decay such
328  * that the following for loop:
329  * 	for (i = 0; i < (5 * loadavg); i++)
330  * 		kg_estcpu *= decay;
331  * will compute
332  * 	kg_estcpu *= 0.1;
333  * for all values of loadavg:
334  *
335  * Mathematically this loop can be expressed by saying:
336  * 	decay ** (5 * loadavg) ~= .1
337  *
338  * The system computes decay as:
339  * 	decay = (2 * loadavg) / (2 * loadavg + 1)
340  *
341  * We wish to prove that the system's computation of decay
342  * will always fulfill the equation:
343  * 	decay ** (5 * loadavg) ~= .1
344  *
345  * If we compute b as:
346  * 	b = 2 * loadavg
347  * then
348  * 	decay = b / (b + 1)
349  *
350  * We now need to prove two things:
351  *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
352  *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
353  *
354  * Facts:
355  *         For x close to zero, exp(x) =~ 1 + x, since
356  *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
357  *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
358  *         For x close to zero, ln(1+x) =~ x, since
359  *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
360  *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
361  *         ln(.1) =~ -2.30
362  *
363  * Proof of (1):
364  *    Solve (factor)**(power) =~ .1 given power (5*loadav):
365  *	solving for factor,
366  *      ln(factor) =~ (-2.30/5*loadav), or
367  *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
368  *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
369  *
370  * Proof of (2):
371  *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
372  *	solving for power,
373  *      power*ln(b/(b+1)) =~ -2.30, or
374  *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
375  *
376  * Actual power values for the implemented algorithm are as follows:
377  *      loadav: 1       2       3       4
378  *      power:  5.68    10.32   14.94   19.55
379  */
380 
381 /* calculations for digital decay to forget 90% of usage in 5*loadav sec */
382 #define	loadfactor(loadav)	(2 * (loadav))
383 #define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
384 
385 /* decay 95% of `ke_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
386 static fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
387 SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
388 
389 /*
390  * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
391  * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
392  * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
393  *
394  * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
395  *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
396  *
397  * If you don't want to bother with the faster/more-accurate formula, you
398  * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
399  * (more general) method of calculating the %age of CPU used by a process.
400  */
401 #define	CCPU_SHIFT	11
402 
403 /*
404  * Recompute process priorities, every hz ticks.
405  * MP-safe, called without the Giant mutex.
406  */
407 /* ARGSUSED */
408 static void
409 schedcpu(void)
410 {
411 	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
412 	struct thread *td;
413 	struct proc *p;
414 	struct kse *ke;
415 	struct ksegrp *kg;
416 	int awake, realstathz;
417 
418 	realstathz = stathz ? stathz : hz;
419 	sx_slock(&allproc_lock);
420 	FOREACH_PROC_IN_SYSTEM(p) {
421 		/*
422 		 * Prevent state changes and protect run queue.
423 		 */
424 		mtx_lock_spin(&sched_lock);
425 		/*
426 		 * Increment time in/out of memory.  We ignore overflow; with
427 		 * 16-bit int's (remember them?) overflow takes 45 days.
428 		 */
429 		p->p_swtime++;
430 		FOREACH_KSEGRP_IN_PROC(p, kg) {
431 			awake = 0;
432 			FOREACH_THREAD_IN_GROUP(kg, td) {
433 				ke = td->td_kse;
434 				/*
435 				 * Increment sleep time (if sleeping).  We
436 				 * ignore overflow, as above.
437 				 */
438 				/*
439 				 * The kse slptimes are not touched in wakeup
440 				 * because the thread may not HAVE a KSE.
441 				 */
442 				if (ke->ke_state == KES_ONRUNQ) {
443 					awake = 1;
444 					ke->ke_flags &= ~KEF_DIDRUN;
445 				} else if ((ke->ke_state == KES_THREAD) &&
446 				    (TD_IS_RUNNING(td))) {
447 					awake = 1;
448 					/* Do not clear KEF_DIDRUN */
449 				} else if (ke->ke_flags & KEF_DIDRUN) {
450 					awake = 1;
451 					ke->ke_flags &= ~KEF_DIDRUN;
452 				}
453 
454 				/*
455 				 * ke_pctcpu is only for ps and ttyinfo().
456 				 * Do it per kse, and add them up at the end?
457 				 * XXXKSE
458 				 */
459 				ke->ke_pctcpu = (ke->ke_pctcpu * ccpu) >>
460 				    FSHIFT;
461 				/*
462 				 * If the kse has been idle the entire second,
463 				 * stop recalculating its priority until
464 				 * it wakes up.
465 				 */
466 				if (ke->ke_cpticks == 0)
467 					continue;
468 #if	(FSHIFT >= CCPU_SHIFT)
469 				ke->ke_pctcpu += (realstathz == 100)
470 				    ? ((fixpt_t) ke->ke_cpticks) <<
471 				    (FSHIFT - CCPU_SHIFT) :
472 				    100 * (((fixpt_t) ke->ke_cpticks)
473 				    << (FSHIFT - CCPU_SHIFT)) / realstathz;
474 #else
475 				ke->ke_pctcpu += ((FSCALE - ccpu) *
476 				    (ke->ke_cpticks *
477 				    FSCALE / realstathz)) >> FSHIFT;
478 #endif
479 				ke->ke_cpticks = 0;
480 			} /* end of kse loop */
481 			/*
482 			 * If there are ANY running threads in this KSEGRP,
483 			 * then don't count it as sleeping.
484 			 */
485 			if (awake) {
486 				if (kg->kg_slptime > 1) {
487 					/*
488 					 * In an ideal world, this should not
489 					 * happen, because whoever woke us
490 					 * up from the long sleep should have
491 					 * unwound the slptime and reset our
492 					 * priority before we run at the stale
493 					 * priority.  Should KASSERT at some
494 					 * point when all the cases are fixed.
495 					 */
496 					updatepri(kg);
497 				}
498 				kg->kg_slptime = 0;
499 			} else
500 				kg->kg_slptime++;
501 			if (kg->kg_slptime > 1)
502 				continue;
503 			kg->kg_estcpu = decay_cpu(loadfac, kg->kg_estcpu);
504 		      	resetpriority(kg);
505 			FOREACH_THREAD_IN_GROUP(kg, td) {
506 				if (td->td_priority >= PUSER) {
507 					sched_prio(td, kg->kg_user_pri);
508 				}
509 			}
510 		} /* end of ksegrp loop */
511 		mtx_unlock_spin(&sched_lock);
512 	} /* end of process loop */
513 	sx_sunlock(&allproc_lock);
514 }
515 
516 /*
517  * Main loop for a kthread that executes schedcpu once a second.
518  */
519 static void
520 schedcpu_thread(void)
521 {
522 	int nowake;
523 
524 	for (;;) {
525 		schedcpu();
526 		tsleep(&nowake, curthread->td_priority, "-", hz);
527 	}
528 }
529 
530 /*
531  * Recalculate the priority of a process after it has slept for a while.
532  * For all load averages >= 1 and max kg_estcpu of 255, sleeping for at
533  * least six times the loadfactor will decay kg_estcpu to zero.
534  */
535 static void
536 updatepri(struct ksegrp *kg)
537 {
538 	register fixpt_t loadfac;
539 	register unsigned int newcpu;
540 
541 	loadfac = loadfactor(averunnable.ldavg[0]);
542 	if (kg->kg_slptime > 5 * loadfac)
543 		kg->kg_estcpu = 0;
544 	else {
545 		newcpu = kg->kg_estcpu;
546 		kg->kg_slptime--;	/* was incremented in schedcpu() */
547 		while (newcpu && --kg->kg_slptime)
548 			newcpu = decay_cpu(loadfac, newcpu);
549 		kg->kg_estcpu = newcpu;
550 	}
551 	resetpriority(kg);
552 }
553 
554 /*
555  * Compute the priority of a process when running in user mode.
556  * Arrange to reschedule if the resulting priority is better
557  * than that of the current process.
558  */
559 static void
560 resetpriority(struct ksegrp *kg)
561 {
562 	register unsigned int newpriority;
563 	struct thread *td;
564 
565 	if (kg->kg_pri_class == PRI_TIMESHARE) {
566 		newpriority = PUSER + kg->kg_estcpu / INVERSE_ESTCPU_WEIGHT +
567 		    NICE_WEIGHT * (kg->kg_proc->p_nice - PRIO_MIN);
568 		newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
569 		    PRI_MAX_TIMESHARE);
570 		kg->kg_user_pri = newpriority;
571 	}
572 	FOREACH_THREAD_IN_GROUP(kg, td) {
573 		maybe_resched(td);			/* XXXKSE silly */
574 	}
575 }
576 
577 /* ARGSUSED */
578 static void
579 sched_setup(void *dummy)
580 {
581 	setup_runqs();
582 
583 	if (sched_quantum == 0)
584 		sched_quantum = SCHED_QUANTUM;
585 	hogticks = 2 * sched_quantum;
586 
587 	callout_init(&roundrobin_callout, CALLOUT_MPSAFE);
588 
589 	/* Kick off timeout driven events by calling first time. */
590 	roundrobin(NULL);
591 
592 	/* Account for thread0. */
593 	sched_tdcnt++;
594 }
595 
596 /* External interfaces start here */
597 /*
598  * Very early in the boot some setup of scheduler-specific
599  * parts of proc0 and of soem scheduler resources needs to be done.
600  * Called from:
601  *  proc0_init()
602  */
603 void
604 schedinit(void)
605 {
606 	/*
607 	 * Set up the scheduler specific parts of proc0.
608 	 */
609 	proc0.p_sched = NULL; /* XXX */
610 	ksegrp0.kg_sched = &kg_sched0;
611 	thread0.td_sched = &kse0;
612 	kse0.ke_thread = &thread0;
613 	kse0.ke_state = KES_THREAD;
614 	kg_sched0.skg_concurrency = 1;
615 	kg_sched0.skg_avail_opennings = 0; /* we are already running */
616 }
617 
618 int
619 sched_runnable(void)
620 {
621 #ifdef SMP
622 	return runq_check(&runq) + runq_check(&runq_pcpu[PCPU_GET(cpuid)]);
623 #else
624 	return runq_check(&runq);
625 #endif
626 }
627 
628 int
629 sched_rr_interval(void)
630 {
631 	if (sched_quantum == 0)
632 		sched_quantum = SCHED_QUANTUM;
633 	return (sched_quantum);
634 }
635 
636 /*
637  * We adjust the priority of the current process.  The priority of
638  * a process gets worse as it accumulates CPU time.  The cpu usage
639  * estimator (kg_estcpu) is increased here.  resetpriority() will
640  * compute a different priority each time kg_estcpu increases by
641  * INVERSE_ESTCPU_WEIGHT
642  * (until MAXPRI is reached).  The cpu usage estimator ramps up
643  * quite quickly when the process is running (linearly), and decays
644  * away exponentially, at a rate which is proportionally slower when
645  * the system is busy.  The basic principle is that the system will
646  * 90% forget that the process used a lot of CPU time in 5 * loadav
647  * seconds.  This causes the system to favor processes which haven't
648  * run much recently, and to round-robin among other processes.
649  */
650 void
651 sched_clock(struct thread *td)
652 {
653 	struct ksegrp *kg;
654 	struct kse *ke;
655 
656 	mtx_assert(&sched_lock, MA_OWNED);
657 	kg = td->td_ksegrp;
658 	ke = td->td_kse;
659 
660 	ke->ke_cpticks++;
661 	kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + 1);
662 	if ((kg->kg_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
663 		resetpriority(kg);
664 		if (td->td_priority >= PUSER)
665 			td->td_priority = kg->kg_user_pri;
666 	}
667 }
668 
669 /*
670  * charge childs scheduling cpu usage to parent.
671  *
672  * XXXKSE assume only one thread & kse & ksegrp keep estcpu in each ksegrp.
673  * Charge it to the ksegrp that did the wait since process estcpu is sum of
674  * all ksegrps, this is strictly as expected.  Assume that the child process
675  * aggregated all the estcpu into the 'built-in' ksegrp.
676  */
677 void
678 sched_exit(struct proc *p, struct thread *td)
679 {
680 	sched_exit_ksegrp(FIRST_KSEGRP_IN_PROC(p), td);
681 	sched_exit_thread(FIRST_THREAD_IN_PROC(p), td);
682 }
683 
684 void
685 sched_exit_ksegrp(struct ksegrp *kg, struct thread *childtd)
686 {
687 
688 	mtx_assert(&sched_lock, MA_OWNED);
689 	kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + childtd->td_ksegrp->kg_estcpu);
690 }
691 
692 void
693 sched_exit_thread(struct thread *td, struct thread *child)
694 {
695 	if ((child->td_proc->p_flag & P_NOLOAD) == 0)
696 		sched_tdcnt--;
697 }
698 
699 void
700 sched_fork(struct thread *td, struct thread *childtd)
701 {
702 	sched_fork_ksegrp(td, childtd->td_ksegrp);
703 	sched_fork_thread(td, childtd);
704 }
705 
706 void
707 sched_fork_ksegrp(struct thread *td, struct ksegrp *child)
708 {
709 	mtx_assert(&sched_lock, MA_OWNED);
710 	child->kg_estcpu = td->td_ksegrp->kg_estcpu;
711 }
712 
713 void
714 sched_fork_thread(struct thread *td, struct thread *childtd)
715 {
716 	sched_newthread(childtd);
717 }
718 
719 void
720 sched_nice(struct proc *p, int nice)
721 {
722 	struct ksegrp *kg;
723 
724 	PROC_LOCK_ASSERT(p, MA_OWNED);
725 	mtx_assert(&sched_lock, MA_OWNED);
726 	p->p_nice = nice;
727 	FOREACH_KSEGRP_IN_PROC(p, kg) {
728 		resetpriority(kg);
729 	}
730 }
731 
732 void
733 sched_class(struct ksegrp *kg, int class)
734 {
735 	mtx_assert(&sched_lock, MA_OWNED);
736 	kg->kg_pri_class = class;
737 }
738 
739 /*
740  * Adjust the priority of a thread.
741  * This may include moving the thread within the KSEGRP,
742  * changing the assignment of a kse to the thread,
743  * and moving a KSE in the system run queue.
744  */
745 void
746 sched_prio(struct thread *td, u_char prio)
747 {
748 
749 	mtx_assert(&sched_lock, MA_OWNED);
750 	if (TD_ON_RUNQ(td)) {
751 		adjustrunqueue(td, prio);
752 	} else {
753 		td->td_priority = prio;
754 	}
755 }
756 
757 void
758 sched_sleep(struct thread *td)
759 {
760 
761 	mtx_assert(&sched_lock, MA_OWNED);
762 	td->td_ksegrp->kg_slptime = 0;
763 	td->td_base_pri = td->td_priority;
764 }
765 
766 static void remrunqueue(struct thread *td);
767 
768 void
769 sched_switch(struct thread *td, struct thread *newtd, int flags)
770 {
771 	struct kse *ke;
772 	struct ksegrp *kg;
773 	struct proc *p;
774 
775 	ke = td->td_kse;
776 	p = td->td_proc;
777 
778 	mtx_assert(&sched_lock, MA_OWNED);
779 
780 	if ((p->p_flag & P_NOLOAD) == 0)
781 		sched_tdcnt--;
782 	/*
783 	 * We are volunteering to switch out so we get to nominate
784 	 * a successor for the rest of our quantum
785 	 * First try another thread in our ksegrp, and then look for
786 	 * other ksegrps in our process.
787 	 */
788 	if (sched_followon &&
789 	    (p->p_flag & P_HADTHREADS) &&
790 	    (flags & SW_VOL) &&
791 	    newtd == NULL) {
792 		/* lets schedule another thread from this process */
793 		 kg = td->td_ksegrp;
794 		 if ((newtd = TAILQ_FIRST(&kg->kg_runq))) {
795 			remrunqueue(newtd);
796 			sched_kgfollowons++;
797 		 } else {
798 			FOREACH_KSEGRP_IN_PROC(p, kg) {
799 				if ((newtd = TAILQ_FIRST(&kg->kg_runq))) {
800 					sched_pfollowons++;
801 					remrunqueue(newtd);
802 					break;
803 				}
804 			}
805 		}
806 	}
807 
808 	if (newtd)
809 		newtd->td_flags |= (td->td_flags & TDF_NEEDRESCHED);
810 
811 	td->td_lastcpu = td->td_oncpu;
812 	td->td_flags &= ~TDF_NEEDRESCHED;
813 	td->td_pflags &= ~TDP_OWEPREEMPT;
814 	td->td_oncpu = NOCPU;
815 	/*
816 	 * At the last moment, if this thread is still marked RUNNING,
817 	 * then put it back on the run queue as it has not been suspended
818 	 * or stopped or any thing else similar.  We never put the idle
819 	 * threads on the run queue, however.
820 	 */
821 	if (td == PCPU_GET(idlethread))
822 		TD_SET_CAN_RUN(td);
823 	else {
824 		SLOT_RELEASE(td->td_ksegrp);
825 		if (TD_IS_RUNNING(td)) {
826 			/* Put us back on the run queue (kse and all). */
827 			setrunqueue(td, (flags & SW_PREEMPT) ?
828 			    SRQ_OURSELF|SRQ_YIELDING|SRQ_PREEMPTED :
829 			    SRQ_OURSELF|SRQ_YIELDING);
830 		} else if (p->p_flag & P_HADTHREADS) {
831 			/*
832 			 * We will not be on the run queue. So we must be
833 			 * sleeping or similar. As it's available,
834 			 * someone else can use the KSE if they need it.
835 			 * It's NOT available if we are about to need it
836 			 */
837 			if (newtd == NULL || newtd->td_ksegrp != td->td_ksegrp)
838 				slot_fill(td->td_ksegrp);
839 		}
840 	}
841 	if (newtd) {
842 		/*
843 		 * The thread we are about to run needs to be counted
844 		 * as if it had been added to the run queue and selected.
845 		 * It came from:
846 		 * * A preemption
847 		 * * An upcall
848 		 * * A followon
849 		 */
850 		KASSERT((newtd->td_inhibitors == 0),
851 			("trying to run inhibitted thread"));
852 		SLOT_USE(newtd->td_ksegrp);
853 		newtd->td_kse->ke_flags |= KEF_DIDRUN;
854         	TD_SET_RUNNING(newtd);
855 		if ((newtd->td_proc->p_flag & P_NOLOAD) == 0)
856 			sched_tdcnt++;
857 	} else {
858 		newtd = choosethread();
859 	}
860 
861 	if (td != newtd)
862 		cpu_switch(td, newtd);
863 	sched_lock.mtx_lock = (uintptr_t)td;
864 	td->td_oncpu = PCPU_GET(cpuid);
865 }
866 
867 void
868 sched_wakeup(struct thread *td)
869 {
870 	struct ksegrp *kg;
871 
872 	mtx_assert(&sched_lock, MA_OWNED);
873 	kg = td->td_ksegrp;
874 	if (kg->kg_slptime > 1)
875 		updatepri(kg);
876 	kg->kg_slptime = 0;
877 	setrunqueue(td, SRQ_BORING);
878 }
879 
880 #ifdef SMP
881 /* enable HTT_2 if you have a 2-way HTT cpu.*/
882 static int
883 forward_wakeup(int  cpunum)
884 {
885 	cpumask_t map, me, dontuse;
886 	cpumask_t map2;
887 	struct pcpu *pc;
888 	cpumask_t id, map3;
889 
890 	mtx_assert(&sched_lock, MA_OWNED);
891 
892 	CTR0(KTR_RUNQ, "forward_wakeup()");
893 
894 	if ((!forward_wakeup_enabled) ||
895 	     (forward_wakeup_use_mask == 0 && forward_wakeup_use_loop == 0))
896 		return (0);
897 	if (!smp_started || cold || panicstr)
898 		return (0);
899 
900 	forward_wakeups_requested++;
901 
902 /*
903  * check the idle mask we received against what we calculated before
904  * in the old version.
905  */
906 	me = PCPU_GET(cpumask);
907 	/*
908 	 * don't bother if we should be doing it ourself..
909 	 */
910 	if ((me & idle_cpus_mask) && (cpunum == NOCPU || me == (1 << cpunum)))
911 		return (0);
912 
913 	dontuse = me | stopped_cpus | hlt_cpus_mask;
914 	map3 = 0;
915 	if (forward_wakeup_use_loop) {
916 		SLIST_FOREACH(pc, &cpuhead, pc_allcpu) {
917 			id = pc->pc_cpumask;
918 			if ( (id & dontuse) == 0 &&
919 			    pc->pc_curthread == pc->pc_idlethread) {
920 				map3 |= id;
921 			}
922 		}
923 	}
924 
925 	if (forward_wakeup_use_mask) {
926 		map = 0;
927 		map = idle_cpus_mask & ~dontuse;
928 
929 		/* If they are both on, compare and use loop if different */
930 		if (forward_wakeup_use_loop) {
931 			if (map != map3) {
932 				printf("map (%02X) != map3 (%02X)\n",
933 						map, map3);
934 				map = map3;
935 			}
936 		}
937 	} else {
938 		map = map3;
939 	}
940 	/* If we only allow a specific CPU, then mask off all the others */
941 	if (cpunum != NOCPU) {
942 		KASSERT((cpunum <= mp_maxcpus),("forward_wakeup: bad cpunum."));
943 		map &= (1 << cpunum);
944 	} else {
945 		/* Try choose an idle die. */
946 		if (forward_wakeup_use_htt) {
947 			map2 =  (map & (map >> 1)) & 0x5555;
948 			if (map2) {
949 				map = map2;
950 			}
951 		}
952 
953 		/* set only one bit */
954 		if (forward_wakeup_use_single) {
955 			map = map & ((~map) + 1);
956 		}
957 	}
958 	if (map) {
959 		forward_wakeups_delivered++;
960 		ipi_selected(map, IPI_AST);
961 		return (1);
962 	}
963 	if (cpunum == NOCPU)
964 		printf("forward_wakeup: Idle processor not found\n");
965 	return (0);
966 }
967 #endif
968 
969 void
970 sched_add(struct thread *td, int flags)
971 {
972 	struct kse *ke;
973 #ifdef SMP
974 	int forwarded = 0;
975 	int cpu;
976 #endif
977 
978 	ke = td->td_kse;
979 	mtx_assert(&sched_lock, MA_OWNED);
980 	KASSERT(ke->ke_state != KES_ONRUNQ,
981 	    ("sched_add: kse %p (%s) already in run queue", ke,
982 	    ke->ke_proc->p_comm));
983 	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
984 	    ("sched_add: process swapped out"));
985 
986 #ifdef SMP
987 	if (KSE_CAN_MIGRATE(ke)) {
988 		CTR2(KTR_RUNQ,
989 		    "sched_add: adding kse:%p (td:%p) to gbl runq", ke, td);
990 		cpu = NOCPU;
991 		ke->ke_runq = &runq;
992 	} else {
993 		if (!SKE_RUNQ_PCPU(ke))
994 			ke->ke_runq = &runq_pcpu[(cpu = PCPU_GET(cpuid))];
995 		else
996 			cpu = td->td_lastcpu;
997 		CTR3(KTR_RUNQ,
998 		    "sched_add: Put kse:%p(td:%p) on cpu%d runq", ke, td, cpu);
999 	}
1000 #else
1001 	CTR2(KTR_RUNQ, "sched_add: adding kse:%p (td:%p) to runq", ke, td);
1002 	ke->ke_runq = &runq;
1003 
1004 #endif
1005 	/*
1006 	 * If we are yielding (on the way out anyhow)
1007 	 * or the thread being saved is US,
1008 	 * then don't try be smart about preemption
1009 	 * or kicking off another CPU
1010 	 * as it won't help and may hinder.
1011 	 * In the YIEDLING case, we are about to run whoever is
1012 	 * being put in the queue anyhow, and in the
1013 	 * OURSELF case, we are puting ourself on the run queue
1014 	 * which also only happens when we are about to yield.
1015 	 */
1016 	if((flags & SRQ_YIELDING) == 0) {
1017 #ifdef SMP
1018 		cpumask_t me = PCPU_GET(cpumask);
1019 		int idle = idle_cpus_mask & me;
1020 		/*
1021 		 * Only try to kick off another CPU if
1022 		 * the thread is unpinned
1023 		 * or pinned to another cpu,
1024 		 * and there are other available and idle CPUs.
1025 		 * if we are idle, or it's an interrupt,
1026 		 * then skip straight to preemption.
1027 		 */
1028 		if ( (! idle) && ((flags & SRQ_INTR) == 0) &&
1029 		    (idle_cpus_mask & ~(hlt_cpus_mask | me)) &&
1030 		    ( KSE_CAN_MIGRATE(ke) ||
1031 		      ke->ke_runq != &runq_pcpu[PCPU_GET(cpuid)])) {
1032 			forwarded = forward_wakeup(cpu);
1033 		}
1034 		/*
1035 		 * If we failed to kick off another cpu, then look to
1036 		 * see if we should preempt this CPU. Only allow this
1037 		 * if it is not pinned or IS pinned to this CPU.
1038 		 * If we are the idle thread, we also try do preempt.
1039 		 * as it will be quicker and being idle, we won't
1040 		 * lose in doing so..
1041 		 */
1042 		if ((!forwarded) &&
1043 		    (ke->ke_runq == &runq ||
1044 		     ke->ke_runq == &runq_pcpu[PCPU_GET(cpuid)]))
1045 #endif
1046 
1047 		{
1048 			if (maybe_preempt(td))
1049 				return;
1050 		}
1051 	}
1052 	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1053 		sched_tdcnt++;
1054 	SLOT_USE(td->td_ksegrp);
1055 	runq_add(ke->ke_runq, ke, flags);
1056 	ke->ke_state = KES_ONRUNQ;
1057 	maybe_resched(td);
1058 }
1059 
1060 void
1061 sched_rem(struct thread *td)
1062 {
1063 	struct kse *ke;
1064 
1065 	ke = td->td_kse;
1066 	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1067 	    ("sched_rem: process swapped out"));
1068 	KASSERT((ke->ke_state == KES_ONRUNQ),
1069 	    ("sched_rem: KSE not on run queue"));
1070 	mtx_assert(&sched_lock, MA_OWNED);
1071 
1072 	if ((td->td_proc->p_flag & P_NOLOAD) == 0)
1073 		sched_tdcnt--;
1074 	SLOT_RELEASE(td->td_ksegrp);
1075 	runq_remove(ke->ke_runq, ke);
1076 
1077 	ke->ke_state = KES_THREAD;
1078 }
1079 
1080 /*
1081  * Select threads to run.
1082  * Notice that the running threads still consume a slot.
1083  */
1084 struct kse *
1085 sched_choose(void)
1086 {
1087 	struct kse *ke;
1088 	struct runq *rq;
1089 
1090 #ifdef SMP
1091 	struct kse *kecpu;
1092 
1093 	rq = &runq;
1094 	ke = runq_choose(&runq);
1095 	kecpu = runq_choose(&runq_pcpu[PCPU_GET(cpuid)]);
1096 
1097 	if (ke == NULL ||
1098 	    (kecpu != NULL &&
1099 	     kecpu->ke_thread->td_priority < ke->ke_thread->td_priority)) {
1100 		CTR2(KTR_RUNQ, "choosing kse %p from pcpu runq %d", kecpu,
1101 		     PCPU_GET(cpuid));
1102 		ke = kecpu;
1103 		rq = &runq_pcpu[PCPU_GET(cpuid)];
1104 	} else {
1105 		CTR1(KTR_RUNQ, "choosing kse %p from main runq", ke);
1106 	}
1107 
1108 #else
1109 	rq = &runq;
1110 	ke = runq_choose(&runq);
1111 #endif
1112 
1113 	if (ke != NULL) {
1114 		runq_remove(rq, ke);
1115 		ke->ke_state = KES_THREAD;
1116 
1117 		KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
1118 		    ("sched_choose: process swapped out"));
1119 	}
1120 	return (ke);
1121 }
1122 
1123 void
1124 sched_userret(struct thread *td)
1125 {
1126 	struct ksegrp *kg;
1127 	/*
1128 	 * XXX we cheat slightly on the locking here to avoid locking in
1129 	 * the usual case.  Setting td_priority here is essentially an
1130 	 * incomplete workaround for not setting it properly elsewhere.
1131 	 * Now that some interrupt handlers are threads, not setting it
1132 	 * properly elsewhere can clobber it in the window between setting
1133 	 * it here and returning to user mode, so don't waste time setting
1134 	 * it perfectly here.
1135 	 */
1136 	kg = td->td_ksegrp;
1137 	if (td->td_priority != kg->kg_user_pri) {
1138 		mtx_lock_spin(&sched_lock);
1139 		td->td_priority = kg->kg_user_pri;
1140 		mtx_unlock_spin(&sched_lock);
1141 	}
1142 }
1143 
1144 void
1145 sched_bind(struct thread *td, int cpu)
1146 {
1147 	struct kse *ke;
1148 
1149 	mtx_assert(&sched_lock, MA_OWNED);
1150 	KASSERT(TD_IS_RUNNING(td),
1151 	    ("sched_bind: cannot bind non-running thread"));
1152 
1153 	ke = td->td_kse;
1154 
1155 	ke->ke_flags |= KEF_BOUND;
1156 #ifdef SMP
1157 	ke->ke_runq = &runq_pcpu[cpu];
1158 	if (PCPU_GET(cpuid) == cpu)
1159 		return;
1160 
1161 	ke->ke_state = KES_THREAD;
1162 
1163 	mi_switch(SW_VOL, NULL);
1164 #endif
1165 }
1166 
1167 void
1168 sched_unbind(struct thread* td)
1169 {
1170 	mtx_assert(&sched_lock, MA_OWNED);
1171 	td->td_kse->ke_flags &= ~KEF_BOUND;
1172 }
1173 
1174 int
1175 sched_load(void)
1176 {
1177 	return (sched_tdcnt);
1178 }
1179 
1180 int
1181 sched_sizeof_ksegrp(void)
1182 {
1183 	return (sizeof(struct ksegrp) + sizeof(struct kg_sched));
1184 }
1185 int
1186 sched_sizeof_proc(void)
1187 {
1188 	return (sizeof(struct proc));
1189 }
1190 int
1191 sched_sizeof_thread(void)
1192 {
1193 	return (sizeof(struct thread) + sizeof(struct kse));
1194 }
1195 
1196 fixpt_t
1197 sched_pctcpu(struct thread *td)
1198 {
1199 	struct kse *ke;
1200 
1201 	ke = td->td_kse;
1202 	return (ke->ke_pctcpu);
1203 
1204 	return (0);
1205 }
1206 #define KERN_SWITCH_INCLUDE 1
1207 #include "kern/kern_switch.c"
1208