This should hopefully fix current issues with bootstrap buildworlds from
[dragonfly.git] / sys / kern / kern_synch.c
CommitLineData
984263bc
MD
1/*-
2 * Copyright (c) 1982, 1986, 1990, 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the University of
21 * California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 * may be used to endorse or promote products derived from this software
24 * without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 *
38 * @(#)kern_synch.c 8.9 (Berkeley) 5/19/95
39 * $FreeBSD: src/sys/kern/kern_synch.c,v 1.87.2.6 2002/10/13 07:29:53 kbyanc Exp $
a94976ad 40 * $DragonFly: src/sys/kern/kern_synch.c,v 1.26 2004/01/07 11:04:18 dillon Exp $
984263bc
MD
41 */
42
43#include "opt_ktrace.h"
44
45#include <sys/param.h>
46#include <sys/systm.h>
47#include <sys/proc.h>
48#include <sys/kernel.h>
49#include <sys/signalvar.h>
50#include <sys/resourcevar.h>
51#include <sys/vmmeter.h>
52#include <sys/sysctl.h>
26a0694b 53#include <sys/thread2.h>
984263bc
MD
54#ifdef KTRACE
55#include <sys/uio.h>
56#include <sys/ktrace.h>
57#endif
f1d1c3fa 58#include <sys/xwait.h>
984263bc
MD
59
60#include <machine/cpu.h>
61#include <machine/ipl.h>
62#include <machine/smp.h>
63
402ed7e1 64static void sched_setup (void *dummy);
984263bc
MD
65SYSINIT(sched_setup, SI_SUB_KICK_SCHEDULER, SI_ORDER_FIRST, sched_setup, NULL)
66
984263bc
MD
67int hogticks;
68int lbolt;
69int sched_quantum; /* Roundrobin scheduling quantum in ticks. */
17a9f566 70int ncpus;
984263bc
MD
71
72static struct callout loadav_callout;
73
74struct loadavg averunnable =
75 { {0, 0, 0}, FSCALE }; /* load average, of runnable procs */
76/*
77 * Constants for averages over 1, 5, and 15 minutes
78 * when sampling at 5 second intervals.
79 */
80static fixpt_t cexp[3] = {
81 0.9200444146293232 * FSCALE, /* exp(-1/12) */
82 0.9834714538216174 * FSCALE, /* exp(-1/60) */
83 0.9944598480048967 * FSCALE, /* exp(-1/180) */
84};
85
402ed7e1
RG
86static void endtsleep (void *);
87static void loadav (void *arg);
402ed7e1
RG
88static void roundrobin (void *arg);
89static void schedcpu (void *arg);
90static void updatepri (struct proc *p);
8a8d5d85 91static void crit_panicints(void);
984263bc
MD
92
93static int
94sysctl_kern_quantum(SYSCTL_HANDLER_ARGS)
95{
96 int error, new_val;
97
98 new_val = sched_quantum * tick;
99 error = sysctl_handle_int(oidp, &new_val, 0, req);
100 if (error != 0 || req->newptr == NULL)
101 return (error);
102 if (new_val < tick)
103 return (EINVAL);
104 sched_quantum = new_val / tick;
105 hogticks = 2 * sched_quantum;
106 return (0);
107}
108
109SYSCTL_PROC(_kern, OID_AUTO, quantum, CTLTYPE_INT|CTLFLAG_RW,
110 0, sizeof sched_quantum, sysctl_kern_quantum, "I", "");
111
984263bc
MD
112int
113roundrobin_interval(void)
114{
115 return (sched_quantum);
116}
117
118/*
9ae9ee8d
MD
119 * Force switch among equal priority processes every 100ms.
120 *
121 * WARNING! The MP lock is not held on ipi message remotes.
984263bc 122 */
cb973d15
MD
123#ifdef SMP
124
984263bc 125static void
cb973d15 126roundrobin_remote(void *arg)
984263bc 127{
8a8d5d85 128 struct proc *p = lwkt_preempted_proc();
8a8d5d85
MD
129 if (p == NULL || RTP_PRIO_NEED_RR(p->p_rtprio.type))
130 need_resched();
cb973d15
MD
131}
132
133#endif
134
135static void
136roundrobin(void *arg)
137{
138 struct proc *p = lwkt_preempted_proc();
8a8d5d85 139 if (p == NULL || RTP_PRIO_NEED_RR(p->p_rtprio.type))
cb973d15
MD
140 need_resched();
141#ifdef SMP
142 lwkt_send_ipiq_mask(mycpu->gd_other_cpus, roundrobin_remote, NULL);
984263bc 143#endif
984263bc
MD
144 timeout(roundrobin, NULL, sched_quantum);
145}
146
d9eea1a5
MD
147#ifdef SMP
148
cb973d15
MD
149void
150resched_cpus(u_int32_t mask)
151{
152 lwkt_send_ipiq_mask(mask, roundrobin_remote, NULL);
153}
154
d9eea1a5
MD
155#endif
156
984263bc
MD
157/*
158 * Constants for digital decay and forget:
159 * 90% of (p_estcpu) usage in 5 * loadav time
160 * 95% of (p_pctcpu) usage in 60 seconds (load insensitive)
161 * Note that, as ps(1) mentions, this can let percentages
162 * total over 100% (I've seen 137.9% for 3 processes).
163 *
164 * Note that schedclock() updates p_estcpu and p_cpticks asynchronously.
165 *
166 * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
167 * That is, the system wants to compute a value of decay such
168 * that the following for loop:
169 * for (i = 0; i < (5 * loadavg); i++)
170 * p_estcpu *= decay;
171 * will compute
172 * p_estcpu *= 0.1;
173 * for all values of loadavg:
174 *
175 * Mathematically this loop can be expressed by saying:
176 * decay ** (5 * loadavg) ~= .1
177 *
178 * The system computes decay as:
179 * decay = (2 * loadavg) / (2 * loadavg + 1)
180 *
181 * We wish to prove that the system's computation of decay
182 * will always fulfill the equation:
183 * decay ** (5 * loadavg) ~= .1
184 *
185 * If we compute b as:
186 * b = 2 * loadavg
187 * then
188 * decay = b / (b + 1)
189 *
190 * We now need to prove two things:
191 * 1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
192 * 2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
193 *
194 * Facts:
195 * For x close to zero, exp(x) =~ 1 + x, since
196 * exp(x) = 0! + x**1/1! + x**2/2! + ... .
197 * therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
198 * For x close to zero, ln(1+x) =~ x, since
199 * ln(1+x) = x - x**2/2 + x**3/3 - ... -1 < x < 1
200 * therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
201 * ln(.1) =~ -2.30
202 *
203 * Proof of (1):
204 * Solve (factor)**(power) =~ .1 given power (5*loadav):
205 * solving for factor,
206 * ln(factor) =~ (-2.30/5*loadav), or
207 * factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
208 * exp(-1/b) =~ (b-1)/b =~ b/(b+1). QED
209 *
210 * Proof of (2):
211 * Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
212 * solving for power,
213 * power*ln(b/(b+1)) =~ -2.30, or
214 * power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav. QED
215 *
216 * Actual power values for the implemented algorithm are as follows:
217 * loadav: 1 2 3 4
218 * power: 5.68 10.32 14.94 19.55
219 */
220
221/* calculations for digital decay to forget 90% of usage in 5*loadav sec */
222#define loadfactor(loadav) (2 * (loadav))
223#define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
224
225/* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
226static fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
227SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
228
229/* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
230static int fscale __unused = FSCALE;
231SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
232
233/*
234 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
235 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
236 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
237 *
238 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
239 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
240 *
241 * If you don't want to bother with the faster/more-accurate formula, you
242 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
243 * (more general) method of calculating the %age of CPU used by a process.
244 */
245#define CCPU_SHIFT 11
246
247/*
248 * Recompute process priorities, every hz ticks.
249 */
250/* ARGSUSED */
251static void
26a0694b 252schedcpu(void *arg)
984263bc 253{
4b5f931b
MD
254 fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
255 struct proc *p;
4b5f931b
MD
256 int realstathz, s;
257
984263bc 258 realstathz = stathz ? stathz : hz;
f62004ad 259 FOREACH_PROC_IN_SYSTEM(p) {
984263bc
MD
260 /*
261 * Increment time in/out of memory and sleep time
262 * (if sleeping). We ignore overflow; with 16-bit int's
263 * (remember them?) overflow takes 45 days.
264 */
265 p->p_swtime++;
266 if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
267 p->p_slptime++;
268 p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
269 /*
270 * If the process has slept the entire second,
271 * stop recalculating its priority until it wakes up.
272 */
273 if (p->p_slptime > 1)
274 continue;
275 s = splhigh(); /* prevent state changes and protect run queue */
276 /*
277 * p_pctcpu is only for ps.
278 */
279#if (FSHIFT >= CCPU_SHIFT)
280 p->p_pctcpu += (realstathz == 100)?
281 ((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
282 100 * (((fixpt_t) p->p_cpticks)
283 << (FSHIFT - CCPU_SHIFT)) / realstathz;
284#else
285 p->p_pctcpu += ((FSCALE - ccpu) *
286 (p->p_cpticks * FSCALE / realstathz)) >> FSHIFT;
287#endif
288 p->p_cpticks = 0;
289 p->p_estcpu = decay_cpu(loadfac, p->p_estcpu);
290 resetpriority(p);
984263bc
MD
291 splx(s);
292 }
293 wakeup((caddr_t)&lbolt);
294 timeout(schedcpu, (void *)0, hz);
295}
296
297/*
298 * Recalculate the priority of a process after it has slept for a while.
299 * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
300 * least six times the loadfactor will decay p_estcpu to zero.
301 */
302static void
26a0694b 303updatepri(struct proc *p)
984263bc 304{
26a0694b
MD
305 unsigned int newcpu = p->p_estcpu;
306 fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
984263bc 307
26a0694b 308 if (p->p_slptime > 5 * loadfac) {
984263bc 309 p->p_estcpu = 0;
26a0694b 310 } else {
984263bc
MD
311 p->p_slptime--; /* the first time was done in schedcpu */
312 while (newcpu && --p->p_slptime)
313 newcpu = decay_cpu(loadfac, newcpu);
314 p->p_estcpu = newcpu;
315 }
316 resetpriority(p);
317}
318
319/*
320 * We're only looking at 7 bits of the address; everything is
321 * aligned to 4, lots of things are aligned to greater powers
322 * of 2. Shift right by 8, i.e. drop the bottom 256 worth.
323 */
324#define TABLESIZE 128
0cfcada1 325static TAILQ_HEAD(slpquehead, thread) slpque[TABLESIZE];
984263bc
MD
326#define LOOKUP(x) (((intptr_t)(x) >> 8) & (TABLESIZE - 1))
327
328/*
329 * During autoconfiguration or after a panic, a sleep will simply
330 * lower the priority briefly to allow interrupts, then return.
331 * The priority to be used (safepri) is machine-dependent, thus this
332 * value is initialized and maintained in the machine-dependent layers.
333 * This priority will typically be 0, or the lowest priority
334 * that is safe for use on the interrupt stack; it can be made
335 * higher to block network software interrupts after panics.
336 */
337int safepri;
338
339void
340sleepinit(void)
341{
342 int i;
343
344 sched_quantum = hz/10;
345 hogticks = 2 * sched_quantum;
346 for (i = 0; i < TABLESIZE; i++)
347 TAILQ_INIT(&slpque[i]);
348}
349
350/*
351 * General sleep call. Suspends the current process until a wakeup is
352 * performed on the specified identifier. The process will then be made
353 * runnable with the specified priority. Sleeps at most timo/hz seconds
377d4740 354 * (0 means no timeout). If flags includes PCATCH flag, signals are checked
984263bc
MD
355 * before and after sleeping, else signals are not checked. Returns 0 if
356 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
357 * signal needs to be delivered, ERESTART is returned if the current system
358 * call should be restarted if possible, and EINTR is returned if the system
359 * call should be interrupted by the signal (return EINTR).
26a0694b
MD
360 *
361 * If the process has P_CURPROC set mi_switch() will not re-queue it to
362 * the userland scheduler queues because we are in a SSLEEP state. If
363 * we are not the current process then we have to remove ourselves from
364 * the scheduler queues.
365 *
366 * YYY priority now unused
984263bc
MD
367 */
368int
377d4740 369tsleep(ident, flags, wmesg, timo)
984263bc 370 void *ident;
377d4740 371 int flags, timo;
984263bc
MD
372 const char *wmesg;
373{
dadab5e9 374 struct thread *td = curthread;
0cfcada1 375 struct proc *p = td->td_proc; /* may be NULL */
377d4740 376 int s, sig = 0, catch = flags & PCATCH;
f1d1c3fa 377 int id = LOOKUP(ident);
984263bc
MD
378 struct callout_handle thandle;
379
0cfcada1
MD
380 /*
381 * NOTE: removed KTRPOINT, it could cause races due to blocking
382 * even in stable. Just scrap it for now.
383 */
984263bc
MD
384 if (cold || panicstr) {
385 /*
386 * After a panic, or during autoconfiguration,
387 * just give interrupts a chance, then just return;
388 * don't run any other procs or panic below,
389 * in case this is the idle process and already asleep.
390 */
8a8d5d85 391 crit_panicints();
984263bc
MD
392 return (0);
393 }
a2a5ad0d 394 KKASSERT(td != &mycpu->gd_idlethread); /* you must be kidding! */
8a8d5d85 395 s = splhigh();
0cfcada1
MD
396 KASSERT(ident != NULL, ("tsleep: no ident"));
397 KASSERT(p == NULL || p->p_stat == SRUN, ("tsleep %p %s %d",
398 ident, wmesg, p->p_stat));
399
26a0694b 400 crit_enter();
0cfcada1
MD
401 td->td_wchan = ident;
402 td->td_wmesg = wmesg;
26a0694b 403 if (p)
0cfcada1 404 p->p_slptime = 0;
0cfcada1
MD
405 lwkt_deschedule_self();
406 TAILQ_INSERT_TAIL(&slpque[id], td, td_threadq);
984263bc 407 if (timo)
0cfcada1 408 thandle = timeout(endtsleep, (void *)td, timo);
984263bc
MD
409 /*
410 * We put ourselves on the sleep queue and start our timeout
411 * before calling CURSIG, as we could stop there, and a wakeup
412 * or a SIGCONT (or both) could occur while we were stopped.
413 * A SIGCONT would cause us to be marked as SSLEEP
414 * without resuming us, thus we must be ready for sleep
415 * when CURSIG is called. If the wakeup happens while we're
a2a5ad0d 416 * stopped, td->td_wchan will be 0 upon return from CURSIG.
984263bc 417 */
0cfcada1
MD
418 if (p) {
419 if (catch) {
420 p->p_flag |= P_SINTR;
421 if ((sig = CURSIG(p))) {
26a0694b 422 if (td->td_wchan) {
0cfcada1 423 unsleep(td);
26a0694b
MD
424 lwkt_schedule_self();
425 }
0cfcada1
MD
426 p->p_stat = SRUN;
427 goto resume;
428 }
a2a5ad0d 429 if (td->td_wchan == NULL) {
0cfcada1
MD
430 catch = 0;
431 goto resume;
432 }
433 } else {
434 sig = 0;
984263bc 435 }
26a0694b
MD
436
437 /*
438 * If we are not the current process we have to remove ourself
439 * from the run queue.
440 */
441 KASSERT(p->p_stat == SRUN, ("PSTAT NOT SRUN %d %d", p->p_pid, p->p_stat));
442 /*
443 * If this is the current 'user' process schedule another one.
444 */
445 clrrunnable(p, SSLEEP);
0cfcada1 446 p->p_stats->p_ru.ru_nvcsw++;
a2a5ad0d 447 KKASSERT(td->td_release || (p->p_flag & P_CURPROC) == 0);
0cfcada1 448 mi_switch();
26a0694b 449 KASSERT(p->p_stat == SRUN, ("tsleep: stat not srun"));
0cfcada1
MD
450 } else {
451 lwkt_switch();
452 }
984263bc 453resume:
26a0694b
MD
454 crit_exit();
455 if (p)
0cfcada1 456 p->p_flag &= ~P_SINTR;
984263bc 457 splx(s);
0cfcada1
MD
458 if (td->td_flags & TDF_TIMEOUT) {
459 td->td_flags &= ~TDF_TIMEOUT;
460 if (sig == 0)
984263bc 461 return (EWOULDBLOCK);
0cfcada1
MD
462 } else if (timo) {
463 untimeout(endtsleep, (void *)td, thandle);
ab44e20a
MD
464 } else if (td->td_wmesg) {
465 /*
466 * This can happen if a thread is woken up directly. Clear
467 * wmesg to avoid debugging confusion.
468 */
469 td->td_wmesg = NULL;
0cfcada1 470 }
a94976ad 471 /* inline of iscaught() */
0cfcada1
MD
472 if (p) {
473 if (catch && (sig != 0 || (sig = CURSIG(p)))) {
474 if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
475 return (EINTR);
476 return (ERESTART);
984263bc 477 }
984263bc 478 }
984263bc
MD
479 return (0);
480}
481
984263bc 482/*
0cfcada1
MD
483 * Implement the timeout for tsleep. We interlock against
484 * wchan when setting TDF_TIMEOUT. For processes we remove
485 * the sleep if the process is stopped rather then sleeping,
486 * so it remains stopped.
984263bc
MD
487 */
488static void
0cfcada1 489endtsleep(void *arg)
984263bc 490{
0cfcada1
MD
491 thread_t td = arg;
492 struct proc *p;
984263bc
MD
493 int s;
494
984263bc 495 s = splhigh();
0cfcada1
MD
496 if (td->td_wchan) {
497 td->td_flags |= TDF_TIMEOUT;
498 if ((p = td->td_proc) != NULL) {
499 if (p->p_stat == SSLEEP)
500 setrunnable(p);
501 else
502 unsleep(td);
503 } else {
504 unsleep(td);
505 lwkt_schedule(td);
506 }
984263bc
MD
507 }
508 splx(s);
509}
510
511/*
512 * Remove a process from its wait queue
513 */
514void
0cfcada1 515unsleep(struct thread *td)
984263bc
MD
516{
517 int s;
518
519 s = splhigh();
0cfcada1
MD
520 if (td->td_wchan) {
521#if 0
f1d1c3fa
MD
522 if (p->p_flag & P_XSLEEP) {
523 struct xwait *w = p->p_wchan;
524 TAILQ_REMOVE(&w->waitq, p, p_procq);
525 p->p_flag &= ~P_XSLEEP;
0cfcada1
MD
526 } else
527#endif
528 TAILQ_REMOVE(&slpque[LOOKUP(td->td_wchan)], td, td_threadq);
529 td->td_wchan = NULL;
f1d1c3fa
MD
530 }
531 splx(s);
532}
533
0cfcada1 534#if 0
f1d1c3fa
MD
535/*
536 * Make all processes sleeping on the explicit lock structure runnable.
537 */
538void
539xwakeup(struct xwait *w)
540{
541 struct proc *p;
542 int s;
543
544 s = splhigh();
545 ++w->gen;
546 while ((p = TAILQ_FIRST(&w->waitq)) != NULL) {
547 TAILQ_REMOVE(&w->waitq, p, p_procq);
548 KASSERT(p->p_wchan == w && (p->p_flag & P_XSLEEP),
549 ("xwakeup: wchan mismatch for %p (%p/%p) %08x", p, p->p_wchan, w, p->p_flag & P_XSLEEP));
550 p->p_wchan = NULL;
551 p->p_flag &= ~P_XSLEEP;
552 if (p->p_stat == SSLEEP) {
553 /* OPTIMIZED EXPANSION OF setrunnable(p); */
554 if (p->p_slptime > 1)
555 updatepri(p);
556 p->p_slptime = 0;
557 p->p_stat = SRUN;
558 if (p->p_flag & P_INMEM) {
559 setrunqueue(p);
f1d1c3fa
MD
560 } else {
561 p->p_flag |= P_SWAPINREQ;
562 wakeup((caddr_t)&proc0);
563 }
564 }
984263bc
MD
565 }
566 splx(s);
567}
0cfcada1 568#endif
984263bc
MD
569
570/*
571 * Make all processes sleeping on the specified identifier runnable.
572 */
0cfcada1
MD
573static void
574_wakeup(void *ident, int count)
984263bc 575{
0cfcada1
MD
576 struct slpquehead *qp;
577 struct thread *td;
578 struct thread *ntd;
579 struct proc *p;
984263bc 580 int s;
f1d1c3fa 581 int id = LOOKUP(ident);
984263bc
MD
582
583 s = splhigh();
f1d1c3fa 584 qp = &slpque[id];
984263bc 585restart:
0cfcada1
MD
586 for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) {
587 ntd = TAILQ_NEXT(td, td_threadq);
588 if (td->td_wchan == ident) {
589 TAILQ_REMOVE(qp, td, td_threadq);
590 td->td_wchan = NULL;
591 if ((p = td->td_proc) != NULL && p->p_stat == SSLEEP) {
984263bc
MD
592 /* OPTIMIZED EXPANSION OF setrunnable(p); */
593 if (p->p_slptime > 1)
594 updatepri(p);
595 p->p_slptime = 0;
596 p->p_stat = SRUN;
597 if (p->p_flag & P_INMEM) {
598 setrunqueue(p);
984263bc
MD
599 } else {
600 p->p_flag |= P_SWAPINREQ;
601 wakeup((caddr_t)&proc0);
602 }
603 /* END INLINE EXPANSION */
0cfcada1
MD
604 } else if (p == NULL) {
605 lwkt_schedule(td);
984263bc 606 }
0cfcada1
MD
607 if (--count == 0)
608 break;
609 goto restart;
984263bc
MD
610 }
611 }
612 splx(s);
613}
614
984263bc 615void
0cfcada1 616wakeup(void *ident)
984263bc 617{
0cfcada1
MD
618 _wakeup(ident, 0);
619}
984263bc 620
0cfcada1
MD
621void
622wakeup_one(void *ident)
623{
624 _wakeup(ident, 1);
984263bc
MD
625}
626
627/*
628 * The machine independent parts of mi_switch().
629 * Must be called at splstatclock() or higher.
630 */
631void
632mi_switch()
633{
d16a8831
MD
634 struct thread *td = curthread;
635 struct proc *p = td->td_proc; /* XXX */
636 struct rlimit *rlim;
984263bc 637 int x;
d16a8831 638 u_int64_t ttime;
984263bc
MD
639
640 /*
641 * XXX this spl is almost unnecessary. It is partly to allow for
642 * sloppy callers that don't do it (issignal() via CURSIG() is the
643 * main offender). It is partly to work around a bug in the i386
644 * cpu_switch() (the ipl is not preserved). We ran for years
645 * without it. I think there was only a interrupt latency problem.
646 * The main caller, tsleep(), does an splx() a couple of instructions
647 * after calling here. The buggy caller, issignal(), usually calls
648 * here at spl0() and sometimes returns at splhigh(). The process
649 * then runs for a little too long at splhigh(). The ipl gets fixed
650 * when the process returns to user mode (or earlier).
651 *
652 * It would probably be better to always call here at spl0(). Callers
653 * are prepared to give up control to another process, so they must
654 * be prepared to be interrupted. The clock stuff here may not
655 * actually need splstatclock().
656 */
657 x = splstatclock();
8ad65e08 658 clear_resched();
984263bc 659
984263bc
MD
660 /*
661 * Check if the process exceeds its cpu resource allocation.
d16a8831
MD
662 * If over max, kill it. Time spent in interrupts is not
663 * included. YYY 64 bit match is expensive. Ick.
984263bc 664 */
d16a8831 665 ttime = td->td_sticks + td->td_uticks;
984263bc 666 if (p->p_stat != SZOMB && p->p_limit->p_cpulimit != RLIM_INFINITY &&
d16a8831 667 ttime > p->p_limit->p_cpulimit) {
984263bc 668 rlim = &p->p_rlimit[RLIMIT_CPU];
d16a8831 669 if (ttime / (rlim_t)1000000 >= rlim->rlim_max) {
984263bc
MD
670 killproc(p, "exceeded maximum CPU limit");
671 } else {
672 psignal(p, SIGXCPU);
673 if (rlim->rlim_cur < rlim->rlim_max) {
674 /* XXX: we should make a private copy */
675 rlim->rlim_cur += 5;
676 }
677 }
678 }
679
680 /*
a2a5ad0d
MD
681 * Pick a new current process and record its start time. If we
682 * are in a SSTOPped state we deschedule ourselves. YYY this needs
683 * to be cleaned up, remember that LWKTs stay on their run queue
684 * which works differently then the user scheduler which removes
685 * the process from the runq when it runs it.
984263bc 686 */
12e4aaff 687 mycpu->gd_cnt.v_swtch++;
a2a5ad0d
MD
688 if (p->p_stat == SSTOP)
689 lwkt_deschedule_self();
8ad65e08 690 lwkt_switch();
984263bc
MD
691
692 splx(x);
693}
694
695/*
696 * Change process state to be runnable,
697 * placing it on the run queue if it is in memory,
698 * and awakening the swapper if it isn't in memory.
699 */
700void
0cfcada1 701setrunnable(struct proc *p)
984263bc 702{
0cfcada1 703 int s;
984263bc
MD
704
705 s = splhigh();
706 switch (p->p_stat) {
707 case 0:
708 case SRUN:
709 case SZOMB:
710 default:
711 panic("setrunnable");
712 case SSTOP:
713 case SSLEEP:
0cfcada1 714 unsleep(p->p_thread); /* e.g. when sending signals */
984263bc
MD
715 break;
716
717 case SIDL:
718 break;
719 }
720 p->p_stat = SRUN;
721 if (p->p_flag & P_INMEM)
722 setrunqueue(p);
723 splx(s);
724 if (p->p_slptime > 1)
725 updatepri(p);
726 p->p_slptime = 0;
727 if ((p->p_flag & P_INMEM) == 0) {
728 p->p_flag |= P_SWAPINREQ;
729 wakeup((caddr_t)&proc0);
26a0694b
MD
730 }
731}
732
733/*
734 * Change the process state to NOT be runnable, removing it from the run
735 * queue. If P_CURPROC is not set and we are in SRUN the process is on the
736 * run queue (If P_INMEM is not set then it isn't because it is swapped).
737 */
738void
739clrrunnable(struct proc *p, int stat)
740{
741 int s;
742
743 s = splhigh();
744 switch(p->p_stat) {
745 case SRUN:
a2a5ad0d 746 if (p->p_flag & P_ONRUNQ)
26a0694b
MD
747 remrunqueue(p);
748 break;
749 default:
750 break;
751 }
752 p->p_stat = stat;
753 splx(s);
754}
755
984263bc
MD
756/*
757 * Compute the priority of a process when running in user mode.
758 * Arrange to reschedule if the resulting priority is better
759 * than that of the current process.
760 */
761void
26a0694b 762resetpriority(struct proc *p)
984263bc 763{
26a0694b
MD
764 unsigned int newpriority;
765 int opq;
766 int npq;
767
435ff993
MD
768 /*
769 * Set p_priority for general process comparisons
770 */
771 switch(p->p_rtprio.type) {
772 case RTP_PRIO_REALTIME:
773 p->p_priority = PRIBASE_REALTIME + p->p_rtprio.prio;
774 return;
775 case RTP_PRIO_NORMAL:
776 break;
777 case RTP_PRIO_IDLE:
778 p->p_priority = PRIBASE_IDLE + p->p_rtprio.prio;
26a0694b 779 return;
435ff993
MD
780 case RTP_PRIO_THREAD:
781 p->p_priority = PRIBASE_THREAD + p->p_rtprio.prio;
782 return;
783 }
784
785 /*
786 * NORMAL priorities fall through. These are based on niceness
787 * and cpu use.
788 */
49d50643
MD
789 newpriority = NICE_ADJUST(p->p_nice - PRIO_MIN) +
790 p->p_estcpu / ESTCPURAMP;
26a0694b 791 newpriority = min(newpriority, MAXPRI);
26a0694b 792 npq = newpriority / PPQ;
d6dd2af9 793 crit_enter();
435ff993 794 opq = (p->p_priority & PRIMASK) / PPQ;
a2a5ad0d 795 if (p->p_stat == SRUN && (p->p_flag & P_ONRUNQ) && opq != npq) {
26a0694b
MD
796 /*
797 * We have to move the process to another queue
798 */
799 remrunqueue(p);
435ff993 800 p->p_priority = PRIBASE_NORMAL + newpriority;
26a0694b
MD
801 setrunqueue(p);
802 } else {
803 /*
a2a5ad0d
MD
804 * We can just adjust the priority and it will be picked
805 * up later.
26a0694b 806 */
a2a5ad0d 807 KKASSERT(opq == npq || (p->p_flag & P_ONRUNQ) == 0);
435ff993 808 p->p_priority = PRIBASE_NORMAL + newpriority;
984263bc 809 }
d6dd2af9 810 crit_exit();
984263bc
MD
811}
812
813/*
814 * Compute a tenex style load average of a quantity on
815 * 1, 5 and 15 minute intervals.
816 */
817static void
818loadav(void *arg)
819{
820 int i, nrun;
821 struct loadavg *avg;
822 struct proc *p;
823
824 avg = &averunnable;
825 nrun = 0;
f62004ad 826 FOREACH_PROC_IN_SYSTEM(p) {
984263bc
MD
827 switch (p->p_stat) {
828 case SRUN:
829 case SIDL:
830 nrun++;
831 }
832 }
833 for (i = 0; i < 3; i++)
834 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
835 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
836
837 /*
838 * Schedule the next update to occur after 5 seconds, but add a
839 * random variation to avoid synchronisation with processes that
840 * run at regular intervals.
841 */
842 callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
843 loadav, NULL);
844}
845
846/* ARGSUSED */
847static void
848sched_setup(dummy)
849 void *dummy;
850{
851
852 callout_init(&loadav_callout);
853
854 /* Kick off timeout driven events by calling first time. */
855 roundrobin(NULL);
856 schedcpu(NULL);
857 loadav(NULL);
858}
859
860/*
861 * We adjust the priority of the current process. The priority of
862 * a process gets worse as it accumulates CPU time. The cpu usage
863 * estimator (p_estcpu) is increased here. resetpriority() will
864 * compute a different priority each time p_estcpu increases by
49d50643
MD
865 * INVERSE_ESTCPU_WEIGHT * (until MAXPRI is reached).
866 *
867 * The cpu usage estimator ramps up quite quickly when the process is
868 * running (linearly), and decays away exponentially, at a rate which
869 * is proportionally slower when the system is busy. The basic principle
870 * is that the system will 90% forget that the process used a lot of CPU
871 * time in 5 * loadav seconds. This causes the system to favor processes
872 * which haven't run much recently, and to round-robin among other processes.
435ff993
MD
873 *
874 * WARNING!
984263bc
MD
875 */
876void
435ff993 877schedclock(void *dummy)
984263bc 878{
435ff993
MD
879 struct thread *td;
880 struct proc *p;
881
882 td = curthread;
883 if ((p = td->td_proc) != NULL) {
884 p->p_cpticks++;
885 p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
886 if ((p->p_estcpu % PPQ) == 0 && try_mplock()) {
887 resetpriority(p);
888 rel_mplock();
889 }
890 }
984263bc 891}
8a8d5d85
MD
892
893static
894void
895crit_panicints(void)
896{
897 int s;
898 int cpri;
899
900 s = splhigh();
901 cpri = crit_panic_save();
902 splx(safepri);
903 crit_panic_restore(cpri);
904 splx(s);
905}
906