Sync userland up with the kernel. This primarily adjusts ps, etc to handle
[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 $
26a0694b 40 * $DragonFly: src/sys/kern/kern_synch.c,v 1.12 2003/06/30 19:50:31 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
64static void sched_setup __P((void *dummy));
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
984263bc
MD
86static void endtsleep __P((void *));
87static void loadav __P((void *arg));
88static void maybe_resched __P((struct proc *chk));
89static void roundrobin __P((void *arg));
90static void schedcpu __P((void *arg));
91static void updatepri __P((struct proc *p));
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 112/*
26a0694b
MD
113 * Arrange to reschedule if necessary by checking to see if the current
114 * process is on the highest priority user scheduling queue. This may
115 * be run from an interrupt so we have to follow any preemption chains
116 * back to the original process.
984263bc
MD
117 */
118static void
26a0694b 119maybe_resched(struct proc *chk)
984263bc 120{
26a0694b
MD
121 struct proc *cur = lwkt_preempted_proc();
122
123 if (cur == NULL)
124 return;
984263bc
MD
125
126 /*
26a0694b
MD
127 * Check the user queue (realtime, normal, idle). Lower numbers
128 * indicate higher priority queues. Lower numbers are also better
129 * for p_priority.
984263bc 130 */
26a0694b 131 if (chk->p_rtprio.type < cur->p_rtprio.type) {
984263bc 132 need_resched();
26a0694b
MD
133 } else if (chk->p_rtprio.type == cur->p_rtprio.type) {
134 if (chk->p_rtprio.type == RTP_PRIO_NORMAL) {
135 if (chk->p_priority / PPQ < cur->p_priority / PPQ)
136 need_resched();
137 } else {
138 if (chk->p_rtprio.prio < cur->p_rtprio.prio)
139 need_resched();
140 }
141 }
984263bc
MD
142}
143
144int
145roundrobin_interval(void)
146{
147 return (sched_quantum);
148}
149
150/*
151 * Force switch among equal priority processes every 100ms.
152 */
153/* ARGSUSED */
154static void
155roundrobin(arg)
156 void *arg;
157{
158#ifndef SMP
159 struct proc *p = curproc; /* XXX */
160#endif
161
162#ifdef SMP
163 need_resched();
164 forward_roundrobin();
165#else
166 if (p == 0 || RTP_PRIO_NEED_RR(p->p_rtprio.type))
167 need_resched();
168#endif
169
170 timeout(roundrobin, NULL, sched_quantum);
171}
172
173/*
174 * Constants for digital decay and forget:
175 * 90% of (p_estcpu) usage in 5 * loadav time
176 * 95% of (p_pctcpu) usage in 60 seconds (load insensitive)
177 * Note that, as ps(1) mentions, this can let percentages
178 * total over 100% (I've seen 137.9% for 3 processes).
179 *
180 * Note that schedclock() updates p_estcpu and p_cpticks asynchronously.
181 *
182 * We wish to decay away 90% of p_estcpu in (5 * loadavg) seconds.
183 * That is, the system wants to compute a value of decay such
184 * that the following for loop:
185 * for (i = 0; i < (5 * loadavg); i++)
186 * p_estcpu *= decay;
187 * will compute
188 * p_estcpu *= 0.1;
189 * for all values of loadavg:
190 *
191 * Mathematically this loop can be expressed by saying:
192 * decay ** (5 * loadavg) ~= .1
193 *
194 * The system computes decay as:
195 * decay = (2 * loadavg) / (2 * loadavg + 1)
196 *
197 * We wish to prove that the system's computation of decay
198 * will always fulfill the equation:
199 * decay ** (5 * loadavg) ~= .1
200 *
201 * If we compute b as:
202 * b = 2 * loadavg
203 * then
204 * decay = b / (b + 1)
205 *
206 * We now need to prove two things:
207 * 1) Given factor ** (5 * loadavg) ~= .1, prove factor == b/(b+1)
208 * 2) Given b/(b+1) ** power ~= .1, prove power == (5 * loadavg)
209 *
210 * Facts:
211 * For x close to zero, exp(x) =~ 1 + x, since
212 * exp(x) = 0! + x**1/1! + x**2/2! + ... .
213 * therefore exp(-1/b) =~ 1 - (1/b) = (b-1)/b.
214 * For x close to zero, ln(1+x) =~ x, since
215 * ln(1+x) = x - x**2/2 + x**3/3 - ... -1 < x < 1
216 * therefore ln(b/(b+1)) = ln(1 - 1/(b+1)) =~ -1/(b+1).
217 * ln(.1) =~ -2.30
218 *
219 * Proof of (1):
220 * Solve (factor)**(power) =~ .1 given power (5*loadav):
221 * solving for factor,
222 * ln(factor) =~ (-2.30/5*loadav), or
223 * factor =~ exp(-1/((5/2.30)*loadav)) =~ exp(-1/(2*loadav)) =
224 * exp(-1/b) =~ (b-1)/b =~ b/(b+1). QED
225 *
226 * Proof of (2):
227 * Solve (factor)**(power) =~ .1 given factor == (b/(b+1)):
228 * solving for power,
229 * power*ln(b/(b+1)) =~ -2.30, or
230 * power =~ 2.3 * (b + 1) = 4.6*loadav + 2.3 =~ 5*loadav. QED
231 *
232 * Actual power values for the implemented algorithm are as follows:
233 * loadav: 1 2 3 4
234 * power: 5.68 10.32 14.94 19.55
235 */
236
237/* calculations for digital decay to forget 90% of usage in 5*loadav sec */
238#define loadfactor(loadav) (2 * (loadav))
239#define decay_cpu(loadfac, cpu) (((loadfac) * (cpu)) / ((loadfac) + FSCALE))
240
241/* decay 95% of `p_pctcpu' in 60 seconds; see CCPU_SHIFT before changing */
242static fixpt_t ccpu = 0.95122942450071400909 * FSCALE; /* exp(-1/20) */
243SYSCTL_INT(_kern, OID_AUTO, ccpu, CTLFLAG_RD, &ccpu, 0, "");
244
245/* kernel uses `FSCALE', userland (SHOULD) use kern.fscale */
246static int fscale __unused = FSCALE;
247SYSCTL_INT(_kern, OID_AUTO, fscale, CTLFLAG_RD, 0, FSCALE, "");
248
249/*
250 * If `ccpu' is not equal to `exp(-1/20)' and you still want to use the
251 * faster/more-accurate formula, you'll have to estimate CCPU_SHIFT below
252 * and possibly adjust FSHIFT in "param.h" so that (FSHIFT >= CCPU_SHIFT).
253 *
254 * To estimate CCPU_SHIFT for exp(-1/20), the following formula was used:
255 * 1 - exp(-1/20) ~= 0.0487 ~= 0.0488 == 1 (fixed pt, *11* bits).
256 *
257 * If you don't want to bother with the faster/more-accurate formula, you
258 * can set CCPU_SHIFT to (FSHIFT + 1) which will use a slower/less-accurate
259 * (more general) method of calculating the %age of CPU used by a process.
260 */
261#define CCPU_SHIFT 11
262
263/*
264 * Recompute process priorities, every hz ticks.
265 */
266/* ARGSUSED */
267static void
26a0694b 268schedcpu(void *arg)
984263bc 269{
4b5f931b
MD
270 fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
271 struct proc *p;
272 struct proc *curp;
273 int realstathz, s;
274
275 curp = lwkt_preempted_proc(); /* YYY temporary hack */
984263bc
MD
276
277 realstathz = stathz ? stathz : hz;
278 LIST_FOREACH(p, &allproc, p_list) {
279 /*
280 * Increment time in/out of memory and sleep time
281 * (if sleeping). We ignore overflow; with 16-bit int's
282 * (remember them?) overflow takes 45 days.
283 */
284 p->p_swtime++;
285 if (p->p_stat == SSLEEP || p->p_stat == SSTOP)
286 p->p_slptime++;
287 p->p_pctcpu = (p->p_pctcpu * ccpu) >> FSHIFT;
288 /*
289 * If the process has slept the entire second,
290 * stop recalculating its priority until it wakes up.
291 */
292 if (p->p_slptime > 1)
293 continue;
294 s = splhigh(); /* prevent state changes and protect run queue */
295 /*
296 * p_pctcpu is only for ps.
297 */
298#if (FSHIFT >= CCPU_SHIFT)
299 p->p_pctcpu += (realstathz == 100)?
300 ((fixpt_t) p->p_cpticks) << (FSHIFT - CCPU_SHIFT):
301 100 * (((fixpt_t) p->p_cpticks)
302 << (FSHIFT - CCPU_SHIFT)) / realstathz;
303#else
304 p->p_pctcpu += ((FSCALE - ccpu) *
305 (p->p_cpticks * FSCALE / realstathz)) >> FSHIFT;
306#endif
307 p->p_cpticks = 0;
308 p->p_estcpu = decay_cpu(loadfac, p->p_estcpu);
309 resetpriority(p);
984263bc
MD
310 splx(s);
311 }
312 wakeup((caddr_t)&lbolt);
313 timeout(schedcpu, (void *)0, hz);
314}
315
316/*
317 * Recalculate the priority of a process after it has slept for a while.
318 * For all load averages >= 1 and max p_estcpu of 255, sleeping for at
319 * least six times the loadfactor will decay p_estcpu to zero.
320 */
321static void
26a0694b 322updatepri(struct proc *p)
984263bc 323{
26a0694b
MD
324 unsigned int newcpu = p->p_estcpu;
325 fixpt_t loadfac = loadfactor(averunnable.ldavg[0]);
984263bc 326
26a0694b 327 if (p->p_slptime > 5 * loadfac) {
984263bc 328 p->p_estcpu = 0;
26a0694b 329 } else {
984263bc
MD
330 p->p_slptime--; /* the first time was done in schedcpu */
331 while (newcpu && --p->p_slptime)
332 newcpu = decay_cpu(loadfac, newcpu);
333 p->p_estcpu = newcpu;
334 }
335 resetpriority(p);
336}
337
338/*
339 * We're only looking at 7 bits of the address; everything is
340 * aligned to 4, lots of things are aligned to greater powers
341 * of 2. Shift right by 8, i.e. drop the bottom 256 worth.
342 */
343#define TABLESIZE 128
0cfcada1 344static TAILQ_HEAD(slpquehead, thread) slpque[TABLESIZE];
984263bc
MD
345#define LOOKUP(x) (((intptr_t)(x) >> 8) & (TABLESIZE - 1))
346
347/*
348 * During autoconfiguration or after a panic, a sleep will simply
349 * lower the priority briefly to allow interrupts, then return.
350 * The priority to be used (safepri) is machine-dependent, thus this
351 * value is initialized and maintained in the machine-dependent layers.
352 * This priority will typically be 0, or the lowest priority
353 * that is safe for use on the interrupt stack; it can be made
354 * higher to block network software interrupts after panics.
355 */
356int safepri;
357
358void
359sleepinit(void)
360{
361 int i;
362
363 sched_quantum = hz/10;
364 hogticks = 2 * sched_quantum;
365 for (i = 0; i < TABLESIZE; i++)
366 TAILQ_INIT(&slpque[i]);
367}
368
369/*
370 * General sleep call. Suspends the current process until a wakeup is
371 * performed on the specified identifier. The process will then be made
372 * runnable with the specified priority. Sleeps at most timo/hz seconds
373 * (0 means no timeout). If pri includes PCATCH flag, signals are checked
374 * before and after sleeping, else signals are not checked. Returns 0 if
375 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
376 * signal needs to be delivered, ERESTART is returned if the current system
377 * call should be restarted if possible, and EINTR is returned if the system
378 * call should be interrupted by the signal (return EINTR).
26a0694b
MD
379 *
380 * If the process has P_CURPROC set mi_switch() will not re-queue it to
381 * the userland scheduler queues because we are in a SSLEEP state. If
382 * we are not the current process then we have to remove ourselves from
383 * the scheduler queues.
384 *
385 * YYY priority now unused
984263bc
MD
386 */
387int
388tsleep(ident, priority, wmesg, timo)
389 void *ident;
390 int priority, timo;
391 const char *wmesg;
392{
dadab5e9 393 struct thread *td = curthread;
0cfcada1
MD
394 struct proc *p = td->td_proc; /* may be NULL */
395 int s, sig = 0, catch = priority & PCATCH;
f1d1c3fa 396 int id = LOOKUP(ident);
984263bc
MD
397 struct callout_handle thandle;
398
0cfcada1
MD
399 /*
400 * NOTE: removed KTRPOINT, it could cause races due to blocking
401 * even in stable. Just scrap it for now.
402 */
984263bc 403 s = splhigh();
f1d1c3fa 404
984263bc
MD
405 if (cold || panicstr) {
406 /*
407 * After a panic, or during autoconfiguration,
408 * just give interrupts a chance, then just return;
409 * don't run any other procs or panic below,
410 * in case this is the idle process and already asleep.
411 */
412 splx(safepri);
413 splx(s);
414 return (0);
415 }
0cfcada1
MD
416 KASSERT(ident != NULL, ("tsleep: no ident"));
417 KASSERT(p == NULL || p->p_stat == SRUN, ("tsleep %p %s %d",
418 ident, wmesg, p->p_stat));
419
26a0694b 420 crit_enter();
0cfcada1
MD
421 td->td_wchan = ident;
422 td->td_wmesg = wmesg;
26a0694b 423 if (p)
0cfcada1 424 p->p_slptime = 0;
0cfcada1
MD
425 lwkt_deschedule_self();
426 TAILQ_INSERT_TAIL(&slpque[id], td, td_threadq);
984263bc 427 if (timo)
0cfcada1 428 thandle = timeout(endtsleep, (void *)td, timo);
984263bc
MD
429 /*
430 * We put ourselves on the sleep queue and start our timeout
431 * before calling CURSIG, as we could stop there, and a wakeup
432 * or a SIGCONT (or both) could occur while we were stopped.
433 * A SIGCONT would cause us to be marked as SSLEEP
434 * without resuming us, thus we must be ready for sleep
435 * when CURSIG is called. If the wakeup happens while we're
436 * stopped, p->p_wchan will be 0 upon return from CURSIG.
437 */
0cfcada1
MD
438 if (p) {
439 if (catch) {
440 p->p_flag |= P_SINTR;
441 if ((sig = CURSIG(p))) {
26a0694b 442 if (td->td_wchan) {
0cfcada1 443 unsleep(td);
26a0694b
MD
444 lwkt_schedule_self();
445 }
0cfcada1
MD
446 p->p_stat = SRUN;
447 goto resume;
448 }
26a0694b 449 if (p->p_wchan == NULL) {
0cfcada1
MD
450 catch = 0;
451 goto resume;
452 }
453 } else {
454 sig = 0;
984263bc 455 }
26a0694b
MD
456
457 /*
458 * If we are not the current process we have to remove ourself
459 * from the run queue.
460 */
461 KASSERT(p->p_stat == SRUN, ("PSTAT NOT SRUN %d %d", p->p_pid, p->p_stat));
462 /*
463 * If this is the current 'user' process schedule another one.
464 */
465 clrrunnable(p, SSLEEP);
0cfcada1
MD
466 p->p_stats->p_ru.ru_nvcsw++;
467 mi_switch();
26a0694b 468 KASSERT(p->p_stat == SRUN, ("tsleep: stat not srun"));
0cfcada1
MD
469 } else {
470 lwkt_switch();
471 }
984263bc 472resume:
26a0694b
MD
473 crit_exit();
474 if (p)
0cfcada1 475 p->p_flag &= ~P_SINTR;
984263bc 476 splx(s);
0cfcada1
MD
477 if (td->td_flags & TDF_TIMEOUT) {
478 td->td_flags &= ~TDF_TIMEOUT;
479 if (sig == 0)
984263bc 480 return (EWOULDBLOCK);
0cfcada1
MD
481 } else if (timo) {
482 untimeout(endtsleep, (void *)td, thandle);
483 }
484 if (p) {
485 if (catch && (sig != 0 || (sig = CURSIG(p)))) {
486 if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
487 return (EINTR);
488 return (ERESTART);
984263bc 489 }
984263bc 490 }
984263bc
MD
491 return (0);
492}
493
0cfcada1
MD
494#if 0
495
984263bc 496/*
f1d1c3fa
MD
497 * General sleep call. Suspends the current process until a wakeup is
498 * performed on the specified xwait structure. The process will then be made
499 * runnable with the specified priority. Sleeps at most timo/hz seconds
500 * (0 means no timeout). If pri includes PCATCH flag, signals are checked
501 * before and after sleeping, else signals are not checked. Returns 0 if
502 * awakened, EWOULDBLOCK if the timeout expires. If PCATCH is set and a
503 * signal needs to be delivered, ERESTART is returned if the current system
504 * call should be restarted if possible, and EINTR is returned if the system
505 * call should be interrupted by the signal (return EINTR).
984263bc 506 *
f1d1c3fa
MD
507 * If the passed generation number is different from the generation number
508 * in the xwait, return immediately.
984263bc 509 */
984263bc 510int
f1d1c3fa 511xsleep(struct xwait *w, int priority, const char *wmesg, int timo, int *gen)
984263bc 512{
dadab5e9
MD
513 struct thread *td = curthread;
514 struct proc *p = td->td_proc;
f1d1c3fa
MD
515 int s, sig, catch = priority & PCATCH;
516 struct callout_handle thandle;
984263bc 517
f1d1c3fa 518#ifdef KTRACE
dadab5e9 519 if (KTRPOINT(td, KTR_CSW))
f1d1c3fa
MD
520 ktrcsw(p->p_tracep, 1, 0);
521#endif
984263bc
MD
522 s = splhigh();
523
f1d1c3fa 524 if (cold || panicstr) {
984263bc 525 /*
f1d1c3fa
MD
526 * After a panic, or during autoconfiguration,
527 * just give interrupts a chance, then just return;
528 * don't run any other procs or panic below,
529 * in case this is the idle process and already asleep.
984263bc 530 */
f1d1c3fa
MD
531 splx(safepri);
532 splx(s);
533 return (0);
534 }
7d0bac62
MD
535 KASSERT(p != NULL, ("xsleep1"));
536 KASSERT(w != NULL && p->p_stat == SRUN, ("xsleep"));
984263bc 537
f1d1c3fa
MD
538 /*
539 * If the generation number does not match we return immediately.
540 */
541 if (*gen != w->gen) {
542 *gen = w->gen;
984263bc 543 splx(s);
984263bc 544#ifdef KTRACE
dadab5e9 545 if (KTRPOINT(td, KTR_CSW))
f1d1c3fa 546 ktrcsw(p->p_tracep, 0, 0);
984263bc 547#endif
f1d1c3fa
MD
548 return(0);
549 }
550
551 p->p_wchan = w;
552 p->p_wmesg = wmesg;
553 p->p_slptime = 0;
f1d1c3fa
MD
554 p->p_flag |= P_XSLEEP;
555 TAILQ_INSERT_TAIL(&w->waitq, p, p_procq);
556 if (timo)
557 thandle = timeout(endtsleep, (void *)p, timo);
558 /*
559 * We put ourselves on the sleep queue and start our timeout
560 * before calling CURSIG, as we could stop there, and a wakeup
561 * or a SIGCONT (or both) could occur while we were stopped.
562 * A SIGCONT would cause us to be marked as SSLEEP
563 * without resuming us, thus we must be ready for sleep
564 * when CURSIG is called. If the wakeup happens while we're
565 * stopped, p->p_wchan will be 0 upon return from CURSIG.
566 */
567 if (catch) {
568 p->p_flag |= P_SINTR;
569 if ((sig = CURSIG(p))) {
26a0694b 570 if (p->p_wchan) {
f1d1c3fa 571 unsleep(p);
26a0694b
MD
572 lwkt_schedule_self();
573 }
f1d1c3fa
MD
574 p->p_stat = SRUN;
575 goto resume;
576 }
577 if (p->p_wchan == NULL) {
578 catch = 0;
579 goto resume;
580 }
26a0694b 581 } else {
f1d1c3fa 582 sig = 0;
26a0694b
MD
583 }
584 clrrunnable(p, SSLEEP);
f1d1c3fa
MD
585 p->p_stats->p_ru.ru_nvcsw++;
586 mi_switch();
587resume:
f1d1c3fa
MD
588 *gen = w->gen; /* update generation number */
589 splx(s);
590 p->p_flag &= ~P_SINTR;
591 if (p->p_flag & P_TIMEOUT) {
592 p->p_flag &= ~P_TIMEOUT;
593 if (sig == 0) {
984263bc 594#ifdef KTRACE
dadab5e9 595 if (KTRPOINT(td, KTR_CSW))
984263bc
MD
596 ktrcsw(p->p_tracep, 0, 0);
597#endif
f1d1c3fa 598 return (EWOULDBLOCK);
984263bc 599 }
f1d1c3fa
MD
600 } else if (timo)
601 untimeout(endtsleep, (void *)p, thandle);
602 if (catch && (sig != 0 || (sig = CURSIG(p)))) {
984263bc 603#ifdef KTRACE
dadab5e9 604 if (KTRPOINT(td, KTR_CSW))
984263bc
MD
605 ktrcsw(p->p_tracep, 0, 0);
606#endif
f1d1c3fa
MD
607 if (SIGISMEMBER(p->p_sigacts->ps_sigintr, sig))
608 return (EINTR);
609 return (ERESTART);
984263bc 610 }
f1d1c3fa 611#ifdef KTRACE
dadab5e9 612 if (KTRPOINT(td, KTR_CSW))
f1d1c3fa
MD
613 ktrcsw(p->p_tracep, 0, 0);
614#endif
984263bc
MD
615 return (0);
616}
617
0cfcada1
MD
618#endif
619
984263bc 620/*
0cfcada1
MD
621 * Implement the timeout for tsleep. We interlock against
622 * wchan when setting TDF_TIMEOUT. For processes we remove
623 * the sleep if the process is stopped rather then sleeping,
624 * so it remains stopped.
984263bc
MD
625 */
626static void
0cfcada1 627endtsleep(void *arg)
984263bc 628{
0cfcada1
MD
629 thread_t td = arg;
630 struct proc *p;
984263bc
MD
631 int s;
632
984263bc 633 s = splhigh();
0cfcada1
MD
634 if (td->td_wchan) {
635 td->td_flags |= TDF_TIMEOUT;
636 if ((p = td->td_proc) != NULL) {
637 if (p->p_stat == SSLEEP)
638 setrunnable(p);
639 else
640 unsleep(td);
641 } else {
642 unsleep(td);
643 lwkt_schedule(td);
644 }
984263bc
MD
645 }
646 splx(s);
647}
648
649/*
650 * Remove a process from its wait queue
651 */
652void
0cfcada1 653unsleep(struct thread *td)
984263bc
MD
654{
655 int s;
656
657 s = splhigh();
0cfcada1
MD
658 if (td->td_wchan) {
659#if 0
f1d1c3fa
MD
660 if (p->p_flag & P_XSLEEP) {
661 struct xwait *w = p->p_wchan;
662 TAILQ_REMOVE(&w->waitq, p, p_procq);
663 p->p_flag &= ~P_XSLEEP;
0cfcada1
MD
664 } else
665#endif
666 TAILQ_REMOVE(&slpque[LOOKUP(td->td_wchan)], td, td_threadq);
667 td->td_wchan = NULL;
f1d1c3fa
MD
668 }
669 splx(s);
670}
671
0cfcada1 672#if 0
f1d1c3fa
MD
673/*
674 * Make all processes sleeping on the explicit lock structure runnable.
675 */
676void
677xwakeup(struct xwait *w)
678{
679 struct proc *p;
680 int s;
681
682 s = splhigh();
683 ++w->gen;
684 while ((p = TAILQ_FIRST(&w->waitq)) != NULL) {
685 TAILQ_REMOVE(&w->waitq, p, p_procq);
686 KASSERT(p->p_wchan == w && (p->p_flag & P_XSLEEP),
687 ("xwakeup: wchan mismatch for %p (%p/%p) %08x", p, p->p_wchan, w, p->p_flag & P_XSLEEP));
688 p->p_wchan = NULL;
689 p->p_flag &= ~P_XSLEEP;
690 if (p->p_stat == SSLEEP) {
691 /* OPTIMIZED EXPANSION OF setrunnable(p); */
692 if (p->p_slptime > 1)
693 updatepri(p);
694 p->p_slptime = 0;
695 p->p_stat = SRUN;
696 if (p->p_flag & P_INMEM) {
697 setrunqueue(p);
698 maybe_resched(p);
699 } else {
700 p->p_flag |= P_SWAPINREQ;
701 wakeup((caddr_t)&proc0);
702 }
703 }
984263bc
MD
704 }
705 splx(s);
706}
0cfcada1 707#endif
984263bc
MD
708
709/*
710 * Make all processes sleeping on the specified identifier runnable.
711 */
0cfcada1
MD
712static void
713_wakeup(void *ident, int count)
984263bc 714{
0cfcada1
MD
715 struct slpquehead *qp;
716 struct thread *td;
717 struct thread *ntd;
718 struct proc *p;
984263bc 719 int s;
f1d1c3fa 720 int id = LOOKUP(ident);
984263bc
MD
721
722 s = splhigh();
f1d1c3fa 723 qp = &slpque[id];
984263bc 724restart:
0cfcada1
MD
725 for (td = TAILQ_FIRST(qp); td != NULL; td = ntd) {
726 ntd = TAILQ_NEXT(td, td_threadq);
727 if (td->td_wchan == ident) {
728 TAILQ_REMOVE(qp, td, td_threadq);
729 td->td_wchan = NULL;
730 if ((p = td->td_proc) != NULL && p->p_stat == SSLEEP) {
984263bc
MD
731 /* OPTIMIZED EXPANSION OF setrunnable(p); */
732 if (p->p_slptime > 1)
733 updatepri(p);
734 p->p_slptime = 0;
735 p->p_stat = SRUN;
736 if (p->p_flag & P_INMEM) {
737 setrunqueue(p);
738 maybe_resched(p);
739 } else {
740 p->p_flag |= P_SWAPINREQ;
741 wakeup((caddr_t)&proc0);
742 }
743 /* END INLINE EXPANSION */
0cfcada1
MD
744 } else if (p == NULL) {
745 lwkt_schedule(td);
984263bc 746 }
0cfcada1
MD
747 if (--count == 0)
748 break;
749 goto restart;
984263bc
MD
750 }
751 }
752 splx(s);
753}
754
984263bc 755void
0cfcada1 756wakeup(void *ident)
984263bc 757{
0cfcada1
MD
758 _wakeup(ident, 0);
759}
984263bc 760
0cfcada1
MD
761void
762wakeup_one(void *ident)
763{
764 _wakeup(ident, 1);
984263bc
MD
765}
766
26a0694b
MD
767/*
768 * Release the P_CURPROC designation on a process in order to allow the
769 * userland scheduler to schedule another one. This places a runnable
770 * process back on the userland scheduler's run queue.
771 *
772 * Note that losing P_CURPROC does not effect LWKT scheduling, you can
773 * still tsleep/wakeup after having lost P_CURPROC, but userret() will
774 * not return to user mode until it gets it back.
775 */
776static __inline
777void
778_relscurproc(struct proc *p)
779{
780 struct proc *np;
781
782 if (p->p_flag & P_CURPROC) {
783 p->p_flag &= ~P_CURPROC;
784 lwkt_deschedule_self();
785 if (p->p_stat == SRUN && (p->p_flag & P_INMEM)) {
786 setrunqueue(p);
787 }
788 if ((np = chooseproc()) != NULL) {
789 np->p_flag |= P_CURPROC;
790 lwkt_schedule(np->p_thread);
791 } else {
792 KKASSERT(mycpu->gd_uprocscheduled == 1);
793 mycpu->gd_uprocscheduled = 0;
794 }
795 }
796}
797
798void
799relscurproc(struct proc *p)
800{
801 _relscurproc(p);
802}
803
984263bc
MD
804/*
805 * The machine independent parts of mi_switch().
806 * Must be called at splstatclock() or higher.
807 */
808void
809mi_switch()
810{
d16a8831
MD
811 struct thread *td = curthread;
812 struct proc *p = td->td_proc; /* XXX */
813 struct rlimit *rlim;
984263bc 814 int x;
d16a8831 815 u_int64_t ttime;
984263bc
MD
816
817 /*
818 * XXX this spl is almost unnecessary. It is partly to allow for
819 * sloppy callers that don't do it (issignal() via CURSIG() is the
820 * main offender). It is partly to work around a bug in the i386
821 * cpu_switch() (the ipl is not preserved). We ran for years
822 * without it. I think there was only a interrupt latency problem.
823 * The main caller, tsleep(), does an splx() a couple of instructions
824 * after calling here. The buggy caller, issignal(), usually calls
825 * here at spl0() and sometimes returns at splhigh(). The process
826 * then runs for a little too long at splhigh(). The ipl gets fixed
827 * when the process returns to user mode (or earlier).
828 *
829 * It would probably be better to always call here at spl0(). Callers
830 * are prepared to give up control to another process, so they must
831 * be prepared to be interrupted. The clock stuff here may not
832 * actually need splstatclock().
833 */
834 x = splstatclock();
8ad65e08 835 clear_resched();
984263bc 836
26a0694b
MD
837 /*
838 * If the process being switched out is the 'current' process then
839 * we have to lose the P_CURPROC designation and choose a new
840 * process. If the process is not being LWKT managed and it is in
841 * SRUN we have to setrunqueue it.
842 */
843 _relscurproc(p);
844
984263bc
MD
845#ifdef SIMPLELOCK_DEBUG
846 if (p->p_simple_locks)
847 printf("sleep: holding simple lock\n");
848#endif
984263bc
MD
849
850 /*
851 * Check if the process exceeds its cpu resource allocation.
d16a8831
MD
852 * If over max, kill it. Time spent in interrupts is not
853 * included. YYY 64 bit match is expensive. Ick.
984263bc 854 */
d16a8831 855 ttime = td->td_sticks + td->td_uticks;
984263bc 856 if (p->p_stat != SZOMB && p->p_limit->p_cpulimit != RLIM_INFINITY &&
d16a8831 857 ttime > p->p_limit->p_cpulimit) {
984263bc 858 rlim = &p->p_rlimit[RLIMIT_CPU];
d16a8831 859 if (ttime / (rlim_t)1000000 >= rlim->rlim_max) {
984263bc
MD
860 killproc(p, "exceeded maximum CPU limit");
861 } else {
862 psignal(p, SIGXCPU);
863 if (rlim->rlim_cur < rlim->rlim_max) {
864 /* XXX: we should make a private copy */
865 rlim->rlim_cur += 5;
866 }
867 }
868 }
869
870 /*
871 * Pick a new current process and record its start time.
8ad65e08
MD
872 * YYY lwkt_switch() will run the heavy weight process restoration
873 * code, which removes the target thread and process from their
874 * respective run queues to temporarily mimic 5.x behavior.
875 * YYY the userland scheduler should pick only one user process
876 * at a time to run per cpu.
984263bc
MD
877 */
878 cnt.v_swtch++;
8ad65e08 879 lwkt_switch();
984263bc
MD
880
881 splx(x);
882}
883
884/*
885 * Change process state to be runnable,
886 * placing it on the run queue if it is in memory,
887 * and awakening the swapper if it isn't in memory.
888 */
889void
0cfcada1 890setrunnable(struct proc *p)
984263bc 891{
0cfcada1 892 int s;
984263bc
MD
893
894 s = splhigh();
895 switch (p->p_stat) {
896 case 0:
897 case SRUN:
898 case SZOMB:
899 default:
900 panic("setrunnable");
901 case SSTOP:
902 case SSLEEP:
0cfcada1 903 unsleep(p->p_thread); /* e.g. when sending signals */
984263bc
MD
904 break;
905
906 case SIDL:
907 break;
908 }
909 p->p_stat = SRUN;
910 if (p->p_flag & P_INMEM)
911 setrunqueue(p);
912 splx(s);
913 if (p->p_slptime > 1)
914 updatepri(p);
915 p->p_slptime = 0;
916 if ((p->p_flag & P_INMEM) == 0) {
917 p->p_flag |= P_SWAPINREQ;
918 wakeup((caddr_t)&proc0);
26a0694b 919 } else {
984263bc 920 maybe_resched(p);
26a0694b
MD
921 }
922}
923
924/*
925 * Change the process state to NOT be runnable, removing it from the run
926 * queue. If P_CURPROC is not set and we are in SRUN the process is on the
927 * run queue (If P_INMEM is not set then it isn't because it is swapped).
928 */
929void
930clrrunnable(struct proc *p, int stat)
931{
932 int s;
933
934 s = splhigh();
935 switch(p->p_stat) {
936 case SRUN:
937 if ((p->p_flag & (P_INMEM|P_CURPROC)) == P_INMEM)
938 remrunqueue(p);
939 break;
940 default:
941 break;
942 }
943 p->p_stat = stat;
944 splx(s);
945}
946
947/*
948 * yield / synchronous reschedule
949 *
950 * Simply calling mi_switch() has the effect we want. mi_switch will
951 * deschedule the current thread, make sure the current process is on
952 * the run queue, and then choose and reschedule another process.
953 */
954void
955uio_yield()
956{
957 struct proc *p = curproc;
958 int s;
959
960 s = splhigh();
961#if 0
962 KKASSERT(p->p_stat == SRUN);
963 if ((p->p_flag & (P_INMEM|P_CURPROC)) == (P_INMEM|P_CURPROC))
964 setrunqueue(p);
965 lwkt_deschedule_self();
966#endif
967 p->p_stats->p_ru.ru_nivcsw++;
968 mi_switch();
969 splx(s);
984263bc
MD
970}
971
972/*
973 * Compute the priority of a process when running in user mode.
974 * Arrange to reschedule if the resulting priority is better
975 * than that of the current process.
26a0694b
MD
976 *
977 * YYY real time / idle procs do not use p_priority XXX
984263bc
MD
978 */
979void
26a0694b 980resetpriority(struct proc *p)
984263bc 981{
26a0694b
MD
982 unsigned int newpriority;
983 int opq;
984 int npq;
985
986 if (p->p_rtprio.type != RTP_PRIO_NORMAL)
987 return;
988 newpriority = PUSER + p->p_estcpu / INVERSE_ESTCPU_WEIGHT +
989 NICE_WEIGHT * p->p_nice;
990 newpriority = min(newpriority, MAXPRI);
991 opq = p->p_priority / PPQ;
992 npq = newpriority / PPQ;
993 if (p->p_stat == SRUN && (p->p_flag & (P_CURPROC|P_INMEM)) == P_INMEM
994 && opq != npq) {
995 /*
996 * We have to move the process to another queue
997 */
998 remrunqueue(p);
999 p->p_priority = newpriority;
1000 setrunqueue(p);
1001 } else {
1002 /*
1003 * Not on a queue or is on the same queue, we can just
1004 * set the priority.
1005 * YYY P_INMEM?
1006 */
1007 p->p_priority = newpriority;
984263bc
MD
1008 }
1009 maybe_resched(p);
1010}
1011
1012/*
1013 * Compute a tenex style load average of a quantity on
1014 * 1, 5 and 15 minute intervals.
1015 */
1016static void
1017loadav(void *arg)
1018{
1019 int i, nrun;
1020 struct loadavg *avg;
1021 struct proc *p;
1022
1023 avg = &averunnable;
1024 nrun = 0;
1025 LIST_FOREACH(p, &allproc, p_list) {
1026 switch (p->p_stat) {
1027 case SRUN:
1028 case SIDL:
1029 nrun++;
1030 }
1031 }
1032 for (i = 0; i < 3; i++)
1033 avg->ldavg[i] = (cexp[i] * avg->ldavg[i] +
1034 nrun * FSCALE * (FSCALE - cexp[i])) >> FSHIFT;
1035
1036 /*
1037 * Schedule the next update to occur after 5 seconds, but add a
1038 * random variation to avoid synchronisation with processes that
1039 * run at regular intervals.
1040 */
1041 callout_reset(&loadav_callout, hz * 4 + (int)(random() % (hz * 2 + 1)),
1042 loadav, NULL);
1043}
1044
1045/* ARGSUSED */
1046static void
1047sched_setup(dummy)
1048 void *dummy;
1049{
1050
1051 callout_init(&loadav_callout);
1052
1053 /* Kick off timeout driven events by calling first time. */
1054 roundrobin(NULL);
1055 schedcpu(NULL);
1056 loadav(NULL);
1057}
1058
1059/*
1060 * We adjust the priority of the current process. The priority of
1061 * a process gets worse as it accumulates CPU time. The cpu usage
1062 * estimator (p_estcpu) is increased here. resetpriority() will
1063 * compute a different priority each time p_estcpu increases by
1064 * INVERSE_ESTCPU_WEIGHT
1065 * (until MAXPRI is reached). The cpu usage estimator ramps up
1066 * quite quickly when the process is running (linearly), and decays
1067 * away exponentially, at a rate which is proportionally slower when
1068 * the system is busy. The basic principle is that the system will
1069 * 90% forget that the process used a lot of CPU time in 5 * loadav
1070 * seconds. This causes the system to favor processes which haven't
1071 * run much recently, and to round-robin among other processes.
1072 */
1073void
1074schedclock(p)
1075 struct proc *p;
1076{
1077
1078 p->p_cpticks++;
1079 p->p_estcpu = ESTCPULIM(p->p_estcpu + 1);
26a0694b 1080 if ((p->p_estcpu % INVERSE_ESTCPU_WEIGHT) == 0)
984263bc 1081 resetpriority(p);
984263bc 1082}