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