sched_4bsd.c revision 121127
1104964Sjeff/*-
2104964Sjeff * Copyright (c) 1982, 1986, 1990, 1991, 1993
3104964Sjeff *	The Regents of the University of California.  All rights reserved.
4104964Sjeff * (c) UNIX System Laboratories, Inc.
5104964Sjeff * All or some portions of this file are derived from material licensed
6104964Sjeff * to the University of California by American Telephone and Telegraph
7104964Sjeff * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8104964Sjeff * the permission of UNIX System Laboratories, Inc.
9104964Sjeff *
10104964Sjeff * Redistribution and use in source and binary forms, with or without
11104964Sjeff * modification, are permitted provided that the following conditions
12104964Sjeff * are met:
13104964Sjeff * 1. Redistributions of source code must retain the above copyright
14104964Sjeff *    notice, this list of conditions and the following disclaimer.
15104964Sjeff * 2. Redistributions in binary form must reproduce the above copyright
16104964Sjeff *    notice, this list of conditions and the following disclaimer in the
17104964Sjeff *    documentation and/or other materials provided with the distribution.
18104964Sjeff * 3. All advertising materials mentioning features or use of this software
19104964Sjeff *    must display the following acknowledgement:
20104964Sjeff *	This product includes software developed by the University of
21104964Sjeff *	California, Berkeley and its contributors.
22104964Sjeff * 4. Neither the name of the University nor the names of its contributors
23104964Sjeff *    may be used to endorse or promote products derived from this software
24104964Sjeff *    without specific prior written permission.
25104964Sjeff *
26104964Sjeff * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27104964Sjeff * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28104964Sjeff * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29104964Sjeff * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30104964Sjeff * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31104964Sjeff * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32104964Sjeff * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33104964Sjeff * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34104964Sjeff * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35104964Sjeff * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36104964Sjeff * SUCH DAMAGE.
37104964Sjeff */
38104964Sjeff
39116182Sobrien#include <sys/cdefs.h>
40116182Sobrien__FBSDID("$FreeBSD: head/sys/kern/sched_4bsd.c 121127 2003-10-16 08:39:15Z jeff $");
41116182Sobrien
42104964Sjeff#include <sys/param.h>
43104964Sjeff#include <sys/systm.h>
44104964Sjeff#include <sys/kernel.h>
45104964Sjeff#include <sys/ktr.h>
46104964Sjeff#include <sys/lock.h>
47104964Sjeff#include <sys/mutex.h>
48104964Sjeff#include <sys/proc.h>
49104964Sjeff#include <sys/resourcevar.h>
50104964Sjeff#include <sys/sched.h>
51104964Sjeff#include <sys/smp.h>
52104964Sjeff#include <sys/sysctl.h>
53104964Sjeff#include <sys/sx.h>
54104964Sjeff
55107135Sjeff/*
56107135Sjeff * INVERSE_ESTCPU_WEIGHT is only suitable for statclock() frequencies in
57107135Sjeff * the range 100-256 Hz (approximately).
58107135Sjeff */
59107135Sjeff#define	ESTCPULIM(e) \
60107135Sjeff    min((e), INVERSE_ESTCPU_WEIGHT * (NICE_WEIGHT * (PRIO_MAX - PRIO_MIN) - \
61107135Sjeff    RQ_PPQ) + INVERSE_ESTCPU_WEIGHT - 1)
62107135Sjeff#define	INVERSE_ESTCPU_WEIGHT	8	/* 1 / (priorities per estcpu level). */
63107135Sjeff#define	NICE_WEIGHT		1	/* Priorities per nice level. */
64107135Sjeff
65109145Sjeffstruct ke_sched {
66109145Sjeff	int	ske_cpticks;	/* (j) Ticks of cpu time. */
67109145Sjeff};
68109145Sjeff
69114293Smarkmstatic struct ke_sched ke_sched;
70109145Sjeff
71109145Sjeffstruct ke_sched *kse0_sched = &ke_sched;
72107126Sjeffstruct kg_sched *ksegrp0_sched = NULL;
73107126Sjeffstruct p_sched *proc0_sched = NULL;
74107126Sjeffstruct td_sched *thread0_sched = NULL;
75104964Sjeff
76104964Sjeffstatic int	sched_quantum;	/* Roundrobin scheduling quantum in ticks. */
77112535Smux#define	SCHED_QUANTUM	(hz / 10)	/* Default sched quantum */
78104964Sjeff
79104964Sjeffstatic struct callout schedcpu_callout;
80104964Sjeffstatic struct callout roundrobin_callout;
81104964Sjeff
82104964Sjeffstatic void	roundrobin(void *arg);
83104964Sjeffstatic void	schedcpu(void *arg);
84104964Sjeffstatic void	sched_setup(void *dummy);
85104964Sjeffstatic void	maybe_resched(struct thread *td);
86104964Sjeffstatic void	updatepri(struct ksegrp *kg);
87104964Sjeffstatic void	resetpriority(struct ksegrp *kg);
88104964Sjeff
89104964SjeffSYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
90104964Sjeff
91104964Sjeff/*
92104964Sjeff * Global run queue.
93104964Sjeff */
94104964Sjeffstatic struct runq runq;
95104964SjeffSYSINIT(runq, SI_SUB_RUN_QUEUE, SI_ORDER_FIRST, runq_init, &runq)
96104964Sjeff
97104964Sjeffstatic int
98104964Sjeffsysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
99104964Sjeff{
100104964Sjeff	int error, new_val;
101104964Sjeff
102104964Sjeff	new_val = sched_quantum * tick;
103104964Sjeff	error = sysctl_handle_int(oidp, &new_val, 0, req);
104104964Sjeff        if (error != 0 || req->newptr == NULL)
105104964Sjeff		return (error);
106104964Sjeff	if (new_val < tick)
107104964Sjeff		return (EINVAL);
108104964Sjeff	sched_quantum = new_val / tick;
109104964Sjeff	hogticks = 2 * sched_quantum;
110104964Sjeff	return (0);
111104964Sjeff}
112104964Sjeff
113104964SjeffSYSCTL_PROC(_kern, OID_AUTO, quantum, CTLTYPE_INT|CTLFLAG_RW,
114104964Sjeff	0, sizeof sched_quantum, sysctl_kern_quantum, "I",
115104964Sjeff	"Roundrobin scheduling quantum in microseconds");
116104964Sjeff
117104964Sjeff/*
118104964Sjeff * Arrange to reschedule if necessary, taking the priorities and
119104964Sjeff * schedulers into account.
120104964Sjeff */
121104964Sjeffstatic void
122104964Sjeffmaybe_resched(struct thread *td)
123104964Sjeff{
124104964Sjeff
125104964Sjeff	mtx_assert(&sched_lock, MA_OWNED);
126108338Sjulian	if (td->td_priority < curthread->td_priority && curthread->td_kse)
127111032Sjulian		curthread->td_flags |= TDF_NEEDRESCHED;
128104964Sjeff}
129104964Sjeff
130104964Sjeff/*
131104964Sjeff * Force switch among equal priority processes every 100ms.
132104964Sjeff * We don't actually need to force a context switch of the current process.
133104964Sjeff * The act of firing the event triggers a context switch to softclock() and
134104964Sjeff * then switching back out again which is equivalent to a preemption, thus
135104964Sjeff * no further work is needed on the local CPU.
136104964Sjeff */
137104964Sjeff/* ARGSUSED */
138104964Sjeffstatic void
139104964Sjeffroundrobin(void *arg)
140104964Sjeff{
141104964Sjeff
142104964Sjeff#ifdef SMP
143104964Sjeff	mtx_lock_spin(&sched_lock);
144104964Sjeff	forward_roundrobin();
145104964Sjeff	mtx_unlock_spin(&sched_lock);
146104964Sjeff#endif
147104964Sjeff
148104964Sjeff	callout_reset(&roundrobin_callout, sched_quantum, roundrobin, NULL);
149104964Sjeff}
150104964Sjeff
151104964Sjeff/*
152104964Sjeff * Constants for digital decay and forget:
153118972Sjhb *	90% of (kg_estcpu) usage in 5 * loadav time
154118972Sjhb *	95% of (ke_pctcpu) usage in 60 seconds (load insensitive)
155104964Sjeff *          Note that, as ps(1) mentions, this can let percentages
156104964Sjeff *          total over 100% (I've seen 137.9% for 3 processes).
157104964Sjeff *
158118972Sjhb * Note that schedclock() updates kg_estcpu and p_cpticks asynchronously.
159104964Sjeff *
160118972Sjhb * We wish to decay away 90% of kg_estcpu in (5 * loadavg) seconds.
161104964Sjeff * That is, the system wants to compute a value of decay such
162104964Sjeff * that the following for loop:
163104964Sjeff * 	for (i = 0; i < (5 * loadavg); i++)
164118972Sjhb * 		kg_estcpu *= decay;
165104964Sjeff * will compute
166118972Sjhb * 	kg_estcpu *= 0.1;
167104964Sjeff * for all values of loadavg:
168104964Sjeff *
169104964Sjeff * Mathematically this loop can be expressed by saying:
170104964Sjeff * 	decay ** (5 * loadavg) ~= .1
171104964Sjeff *
172104964Sjeff * The system computes decay as:
173104964Sjeff * 	decay = (2 * loadavg) / (2 * loadavg + 1)
174104964Sjeff *
175104964Sjeff * We wish to prove that the system's computation of decay
176104964Sjeff * will always fulfill the equation:
177104964Sjeff * 	decay ** (5 * loadavg) ~= .1
178104964Sjeff *
179104964Sjeff * If we compute b as:
180104964Sjeff * 	b = 2 * loadavg
181104964Sjeff * then
182104964Sjeff * 	decay = b / (b + 1)
183104964Sjeff *
184104964Sjeff * We now need to prove two things:
185104964Sjeff *	1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
186104964Sjeff *	2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
187104964Sjeff *
188104964Sjeff * Facts:
189104964Sjeff *         For x close to zero, exp(x) =~ 1 + x, since
190104964Sjeff *              exp(x) = 0! + x**1/1! + x**2/2! + ... .
191104964Sjeff *              therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
192104964Sjeff *         For x close to zero, ln(1+x) =~ x, since
193104964Sjeff *              ln(1+x) = x - x**2/2 + x**3/3 - ...     -1 < x < 1
194104964Sjeff *              therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
195104964Sjeff *         ln(.1) =~ -2.30
196104964Sjeff *
197104964Sjeff * Proof of (1):
198104964Sjeff *    Solve (factor)**(power) =~ .1 given power (5*loadav):
199104964Sjeff *	solving for factor,
200104964Sjeff *      ln(factor) =~ (-2.30/5*loadav), or
201104964Sjeff *      factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
202104964Sjeff *          exp(-1/b) =~ (b-1)/b =~ b/(b+1).                    QED
203104964Sjeff *
204104964Sjeff * Proof of (2):
205104964Sjeff *    Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
206104964Sjeff *	solving for power,
207104964Sjeff *      power*ln(b/(b+1)) =~ -2.30, or
208104964Sjeff *      power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav.  QED
209104964Sjeff *
210104964Sjeff * Actual power values for the implemented algorithm are as follows:
211104964Sjeff *      loadav: 1       2       3       4
212104964Sjeff *      power:  5.68    10.32   14.94   19.55
213104964Sjeff */
214104964Sjeff
215104964Sjeff/* calculations for digital decay to forget 90% of usage in 5*loadav sec */
216104964Sjeff#define	loadfactor(loadav)	(2 * (loadav))
217104964Sjeff#define	decay_cpu(loadfac, cpu)	(((loadfac) * (cpu)) / ((loadfac) + FSCALE))
218104964Sjeff
219118972Sjhb/* decay 95% of `ke_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
220104964Sjeffstatic fixpt_t	ccpu = 0.95122942450071400909 * FSCALE;	/* exp(-1/20) */
221104964SjeffSYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
222104964Sjeff
223104964Sjeff/*
224104964Sjeff * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
225104964Sjeff * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
226104964Sjeff * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
227104964Sjeff *
228104964Sjeff * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
229104964Sjeff *	1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
230104964Sjeff *
231104964Sjeff * If you don't want to bother with the faster/more-accurate formula, you
232104964Sjeff * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
233104964Sjeff * (more general) method of calculating the %age of CPU used by a process.
234104964Sjeff */
235104964Sjeff#define	CCPU_SHIFT	11
236104964Sjeff
237104964Sjeff/*
238104964Sjeff * Recompute process priorities, every hz ticks.
239104964Sjeff * MP-safe, called without the Giant mutex.
240104964Sjeff */
241104964Sjeff/* ARGSUSED */
242104964Sjeffstatic void
243104964Sjeffschedcpu(void *arg)
244104964Sjeff{
245104964Sjeff	register fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
246104964Sjeff	struct thread *td;
247104964Sjeff	struct proc *p;
248104964Sjeff	struct kse *ke;
249104964Sjeff	struct ksegrp *kg;
250118972Sjhb	int awake, realstathz;
251104964Sjeff
252104964Sjeff	realstathz = stathz ? stathz : hz;
253104964Sjeff	sx_slock(&allproc_lock);
254104964Sjeff	FOREACH_PROC_IN_SYSTEM(p) {
255118972Sjhb		/*
256118972Sjhb		 * Prevent state changes and protect run queue.
257118972Sjhb		 */
258104964Sjeff		mtx_lock_spin(&sched_lock);
259118972Sjhb		/*
260118972Sjhb		 * Increment time in/out of memory.  We ignore overflow; with
261118972Sjhb		 * 16-bit int's (remember them?) overflow takes 45 days.
262118972Sjhb		 */
263104964Sjeff		p->p_swtime++;
264104964Sjeff		FOREACH_KSEGRP_IN_PROC(p, kg) {
265104964Sjeff			awake = 0;
266104964Sjeff			FOREACH_KSE_IN_GROUP(kg, ke) {
267104964Sjeff				/*
268118972Sjhb				 * Increment sleep time (if sleeping).  We
269118972Sjhb				 * ignore overflow, as above.
270104964Sjeff				 */
271104964Sjeff				/*
272104964Sjeff				 * The kse slptimes are not touched in wakeup
273104964Sjeff				 * because the thread may not HAVE a KSE.
274104964Sjeff				 */
275104964Sjeff				if (ke->ke_state == KES_ONRUNQ) {
276104964Sjeff					awake = 1;
277104964Sjeff					ke->ke_flags &= ~KEF_DIDRUN;
278104964Sjeff				} else if ((ke->ke_state == KES_THREAD) &&
279104964Sjeff				    (TD_IS_RUNNING(ke->ke_thread))) {
280104964Sjeff					awake = 1;
281104964Sjeff					/* Do not clear KEF_DIDRUN */
282104964Sjeff				} else if (ke->ke_flags & KEF_DIDRUN) {
283104964Sjeff					awake = 1;
284104964Sjeff					ke->ke_flags &= ~KEF_DIDRUN;
285104964Sjeff				}
286104964Sjeff
287104964Sjeff				/*
288118972Sjhb				 * ke_pctcpu is only for ps and ttyinfo().
289118972Sjhb				 * Do it per kse, and add them up at the end?
290104964Sjeff				 * XXXKSE
291104964Sjeff				 */
292118972Sjhb				ke->ke_pctcpu = (ke->ke_pctcpu * ccpu) >>
293109145Sjeff				    FSHIFT;
294104964Sjeff				/*
295104964Sjeff				 * If the kse has been idle the entire second,
296104964Sjeff				 * stop recalculating its priority until
297104964Sjeff				 * it wakes up.
298104964Sjeff				 */
299109145Sjeff				if (ke->ke_sched->ske_cpticks == 0)
300104964Sjeff					continue;
301104964Sjeff#if	(FSHIFT >= CCPU_SHIFT)
302109157Sjeff				ke->ke_pctcpu += (realstathz == 100)
303109145Sjeff				    ? ((fixpt_t) ke->ke_sched->ske_cpticks) <<
304104964Sjeff				    (FSHIFT - CCPU_SHIFT) :
305109145Sjeff				    100 * (((fixpt_t) ke->ke_sched->ske_cpticks)
306109145Sjeff				    << (FSHIFT - CCPU_SHIFT)) / realstathz;
307104964Sjeff#else
308109157Sjeff				ke->ke_pctcpu += ((FSCALE - ccpu) *
309109145Sjeff				    (ke->ke_sched->ske_cpticks *
310109145Sjeff				    FSCALE / realstathz)) >> FSHIFT;
311104964Sjeff#endif
312109145Sjeff				ke->ke_sched->ske_cpticks = 0;
313104964Sjeff			} /* end of kse loop */
314104964Sjeff			/*
315104964Sjeff			 * If there are ANY running threads in this KSEGRP,
316104964Sjeff			 * then don't count it as sleeping.
317104964Sjeff			 */
318104964Sjeff			if (awake) {
319104964Sjeff				if (kg->kg_slptime > 1) {
320104964Sjeff					/*
321104964Sjeff					 * In an ideal world, this should not
322104964Sjeff					 * happen, because whoever woke us
323104964Sjeff					 * up from the long sleep should have
324104964Sjeff					 * unwound the slptime and reset our
325104964Sjeff					 * priority before we run at the stale
326104964Sjeff					 * priority.  Should KASSERT at some
327104964Sjeff					 * point when all the cases are fixed.
328104964Sjeff					 */
329104964Sjeff					updatepri(kg);
330104964Sjeff				}
331104964Sjeff				kg->kg_slptime = 0;
332118972Sjhb			} else
333104964Sjeff				kg->kg_slptime++;
334104964Sjeff			if (kg->kg_slptime > 1)
335104964Sjeff				continue;
336104964Sjeff			kg->kg_estcpu = decay_cpu(loadfac, kg->kg_estcpu);
337104964Sjeff		      	resetpriority(kg);
338104964Sjeff			FOREACH_THREAD_IN_GROUP(kg, td) {
339104964Sjeff				if (td->td_priority >= PUSER) {
340105127Sjulian					sched_prio(td, kg->kg_user_pri);
341104964Sjeff				}
342104964Sjeff			}
343104964Sjeff		} /* end of ksegrp loop */
344104964Sjeff		mtx_unlock_spin(&sched_lock);
345104964Sjeff	} /* end of process loop */
346104964Sjeff	sx_sunlock(&allproc_lock);
347104964Sjeff	callout_reset(&schedcpu_callout, hz, schedcpu, NULL);
348104964Sjeff}
349104964Sjeff
350104964Sjeff/*
351104964Sjeff * Recalculate the priority of a process after it has slept for a while.
352118972Sjhb * For all load averages >= 1 and max kg_estcpu of 255, sleeping for at
353118972Sjhb * least six times the loadfactor will decay kg_estcpu to zero.
354104964Sjeff */
355104964Sjeffstatic void
356104964Sjeffupdatepri(struct ksegrp *kg)
357104964Sjeff{
358118972Sjhb	register fixpt_t loadfac;
359104964Sjeff	register unsigned int newcpu;
360104964Sjeff
361118972Sjhb	loadfac = loadfactor(averunnable.ldavg[0]);
362104964Sjeff	if (kg->kg_slptime > 5 * loadfac)
363104964Sjeff		kg->kg_estcpu = 0;
364104964Sjeff	else {
365118972Sjhb		newcpu = kg->kg_estcpu;
366118972Sjhb		kg->kg_slptime--;	/* was incremented in schedcpu() */
367104964Sjeff		while (newcpu && --kg->kg_slptime)
368104964Sjeff			newcpu = decay_cpu(loadfac, newcpu);
369104964Sjeff		kg->kg_estcpu = newcpu;
370104964Sjeff	}
371104964Sjeff	resetpriority(kg);
372104964Sjeff}
373104964Sjeff
374104964Sjeff/*
375104964Sjeff * Compute the priority of a process when running in user mode.
376104964Sjeff * Arrange to reschedule if the resulting priority is better
377104964Sjeff * than that of the current process.
378104964Sjeff */
379104964Sjeffstatic void
380104964Sjeffresetpriority(struct ksegrp *kg)
381104964Sjeff{
382104964Sjeff	register unsigned int newpriority;
383104964Sjeff	struct thread *td;
384104964Sjeff
385104964Sjeff	if (kg->kg_pri_class == PRI_TIMESHARE) {
386104964Sjeff		newpriority = PUSER + kg->kg_estcpu / INVERSE_ESTCPU_WEIGHT +
387104964Sjeff		    NICE_WEIGHT * (kg->kg_nice - PRIO_MIN);
388104964Sjeff		newpriority = min(max(newpriority, PRI_MIN_TIMESHARE),
389104964Sjeff		    PRI_MAX_TIMESHARE);
390104964Sjeff		kg->kg_user_pri = newpriority;
391104964Sjeff	}
392104964Sjeff	FOREACH_THREAD_IN_GROUP(kg, td) {
393104964Sjeff		maybe_resched(td);			/* XXXKSE silly */
394104964Sjeff	}
395104964Sjeff}
396104964Sjeff
397104964Sjeff/* ARGSUSED */
398104964Sjeffstatic void
399104964Sjeffsched_setup(void *dummy)
400104964Sjeff{
401118972Sjhb
402104964Sjeff	if (sched_quantum == 0)
403104964Sjeff		sched_quantum = SCHED_QUANTUM;
404104964Sjeff	hogticks = 2 * sched_quantum;
405104964Sjeff
406119137Ssam	callout_init(&schedcpu_callout, CALLOUT_MPSAFE);
407104964Sjeff	callout_init(&roundrobin_callout, 0);
408104964Sjeff
409104964Sjeff	/* Kick off timeout driven events by calling first time. */
410104964Sjeff	roundrobin(NULL);
411104964Sjeff	schedcpu(NULL);
412104964Sjeff}
413104964Sjeff
414104964Sjeff/* External interfaces start here */
415104964Sjeffint
416104964Sjeffsched_runnable(void)
417104964Sjeff{
418104964Sjeff        return runq_check(&runq);
419104964Sjeff}
420104964Sjeff
421104964Sjeffint
422104964Sjeffsched_rr_interval(void)
423104964Sjeff{
424104964Sjeff	if (sched_quantum == 0)
425104964Sjeff		sched_quantum = SCHED_QUANTUM;
426104964Sjeff	return (sched_quantum);
427104964Sjeff}
428104964Sjeff
429104964Sjeff/*
430104964Sjeff * We adjust the priority of the current process.  The priority of
431104964Sjeff * a process gets worse as it accumulates CPU time.  The cpu usage
432118972Sjhb * estimator (kg_estcpu) is increased here.  resetpriority() will
433118972Sjhb * compute a different priority each time kg_estcpu increases by
434104964Sjeff * INVERSE_ESTCPU_WEIGHT
435104964Sjeff * (until MAXPRI is reached).  The cpu usage estimator ramps up
436104964Sjeff * quite quickly when the process is running (linearly), and decays
437104964Sjeff * away exponentially, at a rate which is proportionally slower when
438104964Sjeff * the system is busy.  The basic principle is that the system will
439104964Sjeff * 90% forget that the process used a lot of CPU time in 5 * loadav
440104964Sjeff * seconds.  This causes the system to favor processes which haven't
441104964Sjeff * run much recently, and to round-robin among other processes.
442104964Sjeff */
443104964Sjeffvoid
444121127Sjeffsched_clock(struct thread *td)
445104964Sjeff{
446104964Sjeff	struct ksegrp *kg;
447121127Sjeff	struct kse *ke;
448104964Sjeff
449113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
450121127Sjeff	kg = td->td_ksegrp;
451121127Sjeff	ke = td->td_kse;
452113356Sjeff
453109145Sjeff	ke->ke_sched->ske_cpticks++;
454104964Sjeff	kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + 1);
455104964Sjeff	if ((kg->kg_estcpu % INVERSE_ESTCPU_WEIGHT) == 0) {
456104964Sjeff		resetpriority(kg);
457104964Sjeff		if (td->td_priority >= PUSER)
458104964Sjeff			td->td_priority = kg->kg_user_pri;
459104964Sjeff	}
460104964Sjeff}
461118972Sjhb
462104964Sjeff/*
463104964Sjeff * charge childs scheduling cpu usage to parent.
464104964Sjeff *
465104964Sjeff * XXXKSE assume only one thread & kse & ksegrp keep estcpu in each ksegrp.
466104964Sjeff * Charge it to the ksegrp that did the wait since process estcpu is sum of
467104964Sjeff * all ksegrps, this is strictly as expected.  Assume that the child process
468104964Sjeff * aggregated all the estcpu into the 'built-in' ksegrp.
469104964Sjeff */
470104964Sjeffvoid
471113356Sjeffsched_exit(struct proc *p, struct proc *p1)
472104964Sjeff{
473113356Sjeff	sched_exit_kse(FIRST_KSE_IN_PROC(p), FIRST_KSE_IN_PROC(p1));
474113356Sjeff	sched_exit_ksegrp(FIRST_KSEGRP_IN_PROC(p), FIRST_KSEGRP_IN_PROC(p1));
475113356Sjeff	sched_exit_thread(FIRST_THREAD_IN_PROC(p), FIRST_THREAD_IN_PROC(p1));
476113356Sjeff}
477113356Sjeff
478113356Sjeffvoid
479113356Sjeffsched_exit_kse(struct kse *ke, struct kse *child)
480113356Sjeff{
481113356Sjeff}
482113356Sjeff
483113356Sjeffvoid
484113356Sjeffsched_exit_ksegrp(struct ksegrp *kg, struct ksegrp *child)
485113356Sjeff{
486113923Sjhb
487113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
488104964Sjeff	kg->kg_estcpu = ESTCPULIM(kg->kg_estcpu + child->kg_estcpu);
489104964Sjeff}
490104964Sjeff
491104964Sjeffvoid
492113356Sjeffsched_exit_thread(struct thread *td, struct thread *child)
493104964Sjeff{
494113356Sjeff}
495109145Sjeff
496113356Sjeffvoid
497113356Sjeffsched_fork(struct proc *p, struct proc *p1)
498113356Sjeff{
499113356Sjeff	sched_fork_kse(FIRST_KSE_IN_PROC(p), FIRST_KSE_IN_PROC(p1));
500113356Sjeff	sched_fork_ksegrp(FIRST_KSEGRP_IN_PROC(p), FIRST_KSEGRP_IN_PROC(p1));
501113356Sjeff	sched_fork_thread(FIRST_THREAD_IN_PROC(p), FIRST_THREAD_IN_PROC(p1));
502113356Sjeff}
503113356Sjeff
504113356Sjeffvoid
505113356Sjeffsched_fork_kse(struct kse *ke, struct kse *child)
506113356Sjeff{
507113356Sjeff	child->ke_sched->ske_cpticks = 0;
508113356Sjeff}
509113356Sjeff
510113356Sjeffvoid
511113356Sjeffsched_fork_ksegrp(struct ksegrp *kg, struct ksegrp *child)
512113356Sjeff{
513113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
514104964Sjeff	child->kg_estcpu = kg->kg_estcpu;
515113356Sjeff}
516109145Sjeff
517113356Sjeffvoid
518113356Sjeffsched_fork_thread(struct thread *td, struct thread *child)
519113356Sjeff{
520104964Sjeff}
521104964Sjeff
522104964Sjeffvoid
523104964Sjeffsched_nice(struct ksegrp *kg, int nice)
524104964Sjeff{
525113873Sjhb
526113873Sjhb	PROC_LOCK_ASSERT(kg->kg_proc, MA_OWNED);
527113873Sjhb	mtx_assert(&sched_lock, MA_OWNED);
528104964Sjeff	kg->kg_nice = nice;
529104964Sjeff	resetpriority(kg);
530104964Sjeff}
531104964Sjeff
532113356Sjeffvoid
533113356Sjeffsched_class(struct ksegrp *kg, int class)
534113356Sjeff{
535113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
536113356Sjeff	kg->kg_pri_class = class;
537113356Sjeff}
538113356Sjeff
539105127Sjulian/*
540105127Sjulian * Adjust the priority of a thread.
541105127Sjulian * This may include moving the thread within the KSEGRP,
542105127Sjulian * changing the assignment of a kse to the thread,
543105127Sjulian * and moving a KSE in the system run queue.
544105127Sjulian */
545104964Sjeffvoid
546104964Sjeffsched_prio(struct thread *td, u_char prio)
547104964Sjeff{
548104964Sjeff
549113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
550104964Sjeff	if (TD_ON_RUNQ(td)) {
551105127Sjulian		adjustrunqueue(td, prio);
552105127Sjulian	} else {
553105127Sjulian		td->td_priority = prio;
554104964Sjeff	}
555104964Sjeff}
556104964Sjeff
557104964Sjeffvoid
558104964Sjeffsched_sleep(struct thread *td, u_char prio)
559104964Sjeff{
560113923Sjhb
561113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
562104964Sjeff	td->td_ksegrp->kg_slptime = 0;
563104964Sjeff	td->td_priority = prio;
564104964Sjeff}
565104964Sjeff
566104964Sjeffvoid
567104964Sjeffsched_switchin(struct thread *td)
568104964Sjeff{
569113923Sjhb
570113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
571113339Sjulian	td->td_oncpu = PCPU_GET(cpuid);
572104964Sjeff}
573104964Sjeff
574104964Sjeffvoid
575104964Sjeffsched_switchout(struct thread *td)
576104964Sjeff{
577104964Sjeff	struct kse *ke;
578104964Sjeff	struct proc *p;
579104964Sjeff
580104964Sjeff	ke = td->td_kse;
581104964Sjeff	p = td->td_proc;
582104964Sjeff
583113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
584104964Sjeff	KASSERT((ke->ke_state == KES_THREAD), ("mi_switch: kse state?"));
585104964Sjeff
586113339Sjulian	td->td_lastcpu = td->td_oncpu;
587105127Sjulian	td->td_last_kse = ke;
588113339Sjulian	td->td_oncpu = NOCPU;
589111032Sjulian	td->td_flags &= ~TDF_NEEDRESCHED;
590104964Sjeff	/*
591104964Sjeff	 * At the last moment, if this thread is still marked RUNNING,
592104964Sjeff	 * then put it back on the run queue as it has not been suspended
593104964Sjeff	 * or stopped or any thing else similar.
594104964Sjeff	 */
595104964Sjeff	if (TD_IS_RUNNING(td)) {
596104964Sjeff		/* Put us back on the run queue (kse and all). */
597104964Sjeff		setrunqueue(td);
598116361Sdavidxu	} else if (p->p_flag & P_SA) {
599104964Sjeff		/*
600104964Sjeff		 * We will not be on the run queue. So we must be
601104964Sjeff		 * sleeping or similar. As it's available,
602104964Sjeff		 * someone else can use the KSE if they need it.
603104964Sjeff		 */
604104964Sjeff		kse_reassign(ke);
605104964Sjeff	}
606104964Sjeff}
607104964Sjeff
608104964Sjeffvoid
609104964Sjeffsched_wakeup(struct thread *td)
610104964Sjeff{
611104964Sjeff	struct ksegrp *kg;
612104964Sjeff
613113923Sjhb	mtx_assert(&sched_lock, MA_OWNED);
614104964Sjeff	kg = td->td_ksegrp;
615104964Sjeff	if (kg->kg_slptime > 1)
616104964Sjeff		updatepri(kg);
617104964Sjeff	kg->kg_slptime = 0;
618104964Sjeff	setrunqueue(td);
619104964Sjeff	maybe_resched(td);
620104964Sjeff}
621104964Sjeff
622104964Sjeffvoid
623121127Sjeffsched_add(struct thread *td)
624104964Sjeff{
625121127Sjeff	struct kse *ke;
626121127Sjeff
627121127Sjeff	ke = td->td_kse;
628104964Sjeff	mtx_assert(&sched_lock, MA_OWNED);
629104964Sjeff	KASSERT((ke->ke_thread != NULL), ("runq_add: No thread on KSE"));
630104964Sjeff	KASSERT((ke->ke_thread->td_kse != NULL),
631104964Sjeff	    ("runq_add: No KSE on thread"));
632104964Sjeff	KASSERT(ke->ke_state != KES_ONRUNQ,
633104964Sjeff	    ("runq_add: kse %p (%s) already in run queue", ke,
634104964Sjeff	    ke->ke_proc->p_comm));
635104964Sjeff	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
636104964Sjeff	    ("runq_add: process swapped out"));
637104964Sjeff	ke->ke_ksegrp->kg_runq_kses++;
638104964Sjeff	ke->ke_state = KES_ONRUNQ;
639104964Sjeff
640104964Sjeff	runq_add(&runq, ke);
641104964Sjeff}
642104964Sjeff
643104964Sjeffvoid
644121127Sjeffsched_rem(struct thread *td)
645104964Sjeff{
646121127Sjeff	struct kse *ke;
647121127Sjeff
648121127Sjeff	ke = td->td_kse;
649104964Sjeff	KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
650104964Sjeff	    ("runq_remove: process swapped out"));
651104964Sjeff	KASSERT((ke->ke_state == KES_ONRUNQ), ("KSE not on run queue"));
652104964Sjeff	mtx_assert(&sched_lock, MA_OWNED);
653104964Sjeff
654104964Sjeff	runq_remove(&runq, ke);
655104964Sjeff	ke->ke_state = KES_THREAD;
656104964Sjeff	ke->ke_ksegrp->kg_runq_kses--;
657104964Sjeff}
658104964Sjeff
659104964Sjeffstruct kse *
660104964Sjeffsched_choose(void)
661104964Sjeff{
662104964Sjeff	struct kse *ke;
663104964Sjeff
664104964Sjeff	ke = runq_choose(&runq);
665104964Sjeff
666104964Sjeff	if (ke != NULL) {
667104964Sjeff		runq_remove(&runq, ke);
668104964Sjeff		ke->ke_state = KES_THREAD;
669104964Sjeff
670104964Sjeff		KASSERT((ke->ke_thread != NULL),
671104964Sjeff		    ("runq_choose: No thread on KSE"));
672104964Sjeff		KASSERT((ke->ke_thread->td_kse != NULL),
673104964Sjeff		    ("runq_choose: No KSE on thread"));
674104964Sjeff		KASSERT(ke->ke_proc->p_sflag & PS_INMEM,
675104964Sjeff		    ("runq_choose: process swapped out"));
676104964Sjeff	}
677104964Sjeff	return (ke);
678104964Sjeff}
679104964Sjeff
680104964Sjeffvoid
681104964Sjeffsched_userret(struct thread *td)
682104964Sjeff{
683104964Sjeff	struct ksegrp *kg;
684104964Sjeff	/*
685104964Sjeff	 * XXX we cheat slightly on the locking here to avoid locking in
686104964Sjeff	 * the usual case.  Setting td_priority here is essentially an
687104964Sjeff	 * incomplete workaround for not setting it properly elsewhere.
688104964Sjeff	 * Now that some interrupt handlers are threads, not setting it
689104964Sjeff	 * properly elsewhere can clobber it in the window between setting
690104964Sjeff	 * it here and returning to user mode, so don't waste time setting
691104964Sjeff	 * it perfectly here.
692104964Sjeff	 */
693104964Sjeff	kg = td->td_ksegrp;
694104964Sjeff	if (td->td_priority != kg->kg_user_pri) {
695104964Sjeff		mtx_lock_spin(&sched_lock);
696104964Sjeff		td->td_priority = kg->kg_user_pri;
697104964Sjeff		mtx_unlock_spin(&sched_lock);
698104964Sjeff	}
699104964Sjeff}
700107126Sjeff
701107126Sjeffint
702107126Sjeffsched_sizeof_kse(void)
703107126Sjeff{
704109145Sjeff	return (sizeof(struct kse) + sizeof(struct ke_sched));
705107126Sjeff}
706107126Sjeffint
707107126Sjeffsched_sizeof_ksegrp(void)
708107126Sjeff{
709107126Sjeff	return (sizeof(struct ksegrp));
710107126Sjeff}
711107126Sjeffint
712107126Sjeffsched_sizeof_proc(void)
713107126Sjeff{
714107126Sjeff	return (sizeof(struct proc));
715107126Sjeff}
716107126Sjeffint
717107126Sjeffsched_sizeof_thread(void)
718107126Sjeff{
719107126Sjeff	return (sizeof(struct thread));
720107126Sjeff}
721107137Sjeff
722107137Sjefffixpt_t
723121127Sjeffsched_pctcpu(struct thread *td)
724107137Sjeff{
725121127Sjeff	return (td->td_kse->ke_pctcpu);
726107137Sjeff}
727