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