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