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