adding GNU dc ("desk calculator")
[unix-history] / sys / kern / kern_clock.c
CommitLineData
15637ed4
RG
1/*-
2 * Copyright (c) 1982, 1986, 1991 The Regents of the University of California.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 * @(#)kern_clock.c 7.16 (Berkeley) 5/9/91
34 *
35 * PATCHES MAGIC LEVEL PATCH THAT GOT US HERE
36 * -------------------- ----- ----------------------
37 * CURRENT PATCH LEVEL: 2 00158
38 * -------------------- ----- ----------------------
39 *
40 * 08 Apr 93 Poul-Henning Kamp Add support for dcfclock
41 * 25 Apr 93 Bruce Evans Support new interrupt code (intr-0.1)
42 */
43
44#include "param.h"
45#include "systm.h"
46#include "dkstat.h"
47#include "callout.h"
48#include "kernel.h"
49#include "proc.h"
50#include "resourcevar.h"
51
52#include "machine/cpu.h"
53
54#ifdef GPROF
55#include "gprof.h"
56#endif
57
58/*
59 * Clock handling routines.
60 *
61 * This code is written to operate with two timers which run
62 * independently of each other. The main clock, running at hz
63 * times per second, is used to do scheduling and timeout calculations.
64 * The second timer does resource utilization estimation statistically
65 * based on the state of the machine phz times a second. Both functions
66 * can be performed by a single clock (ie hz == phz), however the
67 * statistics will be much more prone to errors. Ideally a machine
68 * would have separate clocks measuring time spent in user state, system
69 * state, interrupt state, and idle state. These clocks would allow a non-
70 * approximate measure of resource utilization.
71 */
72
73/*
74 * TODO:
75 * time of day, system/user timing, timeouts, profiling on separate timers
76 * allocate more timeout table slots when table overflows.
77 */
78
79/*
80 * Bump a timeval by a small number of usec's.
81 */
82#define BUMPTIME(t, usec) { \
83 register struct timeval *tp = (t); \
84 \
85 tp->tv_usec += (usec); \
86 if (tp->tv_usec >= 1000000) { \
87 tp->tv_usec -= 1000000; \
88 tp->tv_sec++; \
89 } \
90}
91
92/*
93 * The hz hardware interval timer.
94 * We update the events relating to real time.
95 * If this timer is also being used to gather statistics,
96 * we run through the statistics gathering routine as well.
97 */
98hardclock(frame)
99 clockframe frame;
100{
101 register struct callout *p1;
102 register struct proc *p = curproc;
103 register struct pstats *pstats;
104 register int s;
105 int needsoft = 0;
106 extern int tickdelta;
107 extern long timedelta;
108
109 /*
110 * Update real-time timeout queue.
111 * At front of queue are some number of events which are ``due''.
112 * The time to these is <= 0 and if negative represents the
113 * number of ticks which have passed since it was supposed to happen.
114 * The rest of the q elements (times > 0) are events yet to happen,
115 * where the time for each is given as a delta from the previous.
116 * Decrementing just the first of these serves to decrement the time
117 * to all events.
118 */
119 p1 = calltodo.c_next;
120 while (p1) {
121 if (--p1->c_time > 0)
122 break;
123 needsoft = 1;
124 if (p1->c_time == 0)
125 break;
126 p1 = p1->c_next;
127 }
128
129 /*
130 * Curproc (now in p) is null if no process is running.
131 * We assume that curproc is set in user mode!
132 */
133 if (p)
134 pstats = p->p_stats;
135 /*
136 * Charge the time out based on the mode the cpu is in.
137 * Here again we fudge for the lack of proper interval timers
138 * assuming that the current state has been around at least
139 * one tick.
140 */
141 if (CLKF_USERMODE(&frame)) {
142 if (pstats->p_prof.pr_scale)
143 needsoft = 1;
144 /*
145 * CPU was in user state. Increment
146 * user time counter, and process process-virtual time
147 * interval timer.
148 */
149 BUMPTIME(&p->p_utime, tick);
150 if (timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
151 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
152 psignal(p, SIGVTALRM);
153 } else {
154 /*
155 * CPU was in system state.
156 */
157 if (p)
158 BUMPTIME(&p->p_stime, tick);
159 }
160
161 /*
162 * If the cpu is currently scheduled to a process, then
163 * charge it with resource utilization for a tick, updating
164 * statistics which run in (user+system) virtual time,
165 * such as the cpu time limit and profiling timers.
166 * This assumes that the current process has been running
167 * the entire last tick.
168 */
169 if (p) {
170 if ((p->p_utime.tv_sec+p->p_stime.tv_sec+1) >
171 p->p_rlimit[RLIMIT_CPU].rlim_cur) {
172 psignal(p, SIGXCPU);
173 if (p->p_rlimit[RLIMIT_CPU].rlim_cur <
174 p->p_rlimit[RLIMIT_CPU].rlim_max)
175 p->p_rlimit[RLIMIT_CPU].rlim_cur += 5;
176 }
177 if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
178 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
179 psignal(p, SIGPROF);
180
181 /*
182 * We adjust the priority of the current process.
183 * The priority of a process gets worse as it accumulates
184 * CPU time. The cpu usage estimator (p_cpu) is increased here
185 * and the formula for computing priorities (in kern_synch.c)
186 * will compute a different value each time the p_cpu increases
187 * by 4. The cpu usage estimator ramps up quite quickly when
188 * the process is running (linearly), and decays away
189 * exponentially, * at a rate which is proportionally slower
190 * when the system is busy. The basic principal is that the
191 * system will 90% forget that a process used a lot of CPU
192 * time in 5*loadav seconds. This causes the system to favor
193 * processes which haven't run much recently, and to
194 * round-robin among other processes.
195 */
196 p->p_cpticks++;
197 if (++p->p_cpu == 0)
198 p->p_cpu--;
199 if ((p->p_cpu&3) == 0) {
200 setpri(p);
201 if (p->p_pri >= PUSER)
202 p->p_pri = p->p_usrpri;
203 }
204 }
205
206 /*
207 * If the alternate clock has not made itself known then
208 * we must gather the statistics.
209 */
210 if (phz == 0)
211 gatherstats(&frame);
212
213 /*
214 * Increment the time-of-day, and schedule
215 * processing of the callouts at a very low cpu priority,
216 * so we don't keep the relatively high clock interrupt
217 * priority any longer than necessary.
218 */
219 if (timedelta == 0)
220 BUMPTIME(&time, tick)
221 else {
222 register delta;
223
224 if (timedelta < 0) {
225 delta = tick - tickdelta;
226 timedelta += tickdelta;
227 } else {
228 delta = tick + tickdelta;
229 timedelta -= tickdelta;
230 }
231 BUMPTIME(&time, delta);
232 }
233#ifdef DCFCLK
234 /*
235 * This is lousy, but until I can get the $&^%&^(!!! signal onto one
236 * of the interrupt's I'll have to poll it. No, it will not work if
237 * you attempt -DHZ=1000, things break.
238 * But keep the NDCFCLK low, to avoid waste of cycles...
239 * phk@data.fls.dk
240 */
241 dcfclk_worker();
242#endif
243 if (needsoft) {
244#if 0
245/*
246 * XXX - hardclock runs at splhigh, so the splsoftclock is useless and
247 * softclock runs at splhigh as well if we do this. It is not much of
248 * an optimization, since the "software interrupt" is done with a call
249 * from doreti, and the overhead of checking there is sometimes less
250 * than checking here. Moreover, the whole %$$%$^ frame is passed by
251 * value here.
252 */
253 if (CLKF_BASEPRI(&frame)) {
254 /*
255 * Save the overhead of a software interrupt;
256 * it will happen as soon as we return, so do it now.
257 */
258 (void) splsoftclock();
259 softclock(frame);
260 } else
261#endif
262 setsoftclock();
263 }
264}
265
266int dk_ndrive = DK_NDRIVE;
267/*
268 * Gather statistics on resource utilization.
269 *
270 * We make a gross assumption: that the system has been in the
271 * state it is in (user state, kernel state, interrupt state,
272 * or idle state) for the entire last time interval, and
273 * update statistics accordingly.
274 */
275gatherstats(framep)
276 clockframe *framep;
277{
278 register int cpstate, s;
279
280 /*
281 * Determine what state the cpu is in.
282 */
283 if (CLKF_USERMODE(framep)) {
284 /*
285 * CPU was in user state.
286 */
287 if (curproc->p_nice > NZERO)
288 cpstate = CP_NICE;
289 else
290 cpstate = CP_USER;
291 } else {
292 /*
293 * CPU was in system state. If profiling kernel
294 * increment a counter. If no process is running
295 * then this is a system tick if we were running
296 * at a non-zero IPL (in a driver). If a process is running,
297 * then we charge it with system time even if we were
298 * at a non-zero IPL, since the system often runs
299 * this way during processing of system calls.
300 * This is approximate, but the lack of true interval
301 * timers makes doing anything else difficult.
302 */
303 cpstate = CP_SYS;
304 if (curproc == NULL && CLKF_BASEPRI(framep))
305 cpstate = CP_IDLE;
306#ifdef GPROF
307 s = (u_long) CLKF_PC(framep) - (u_long) s_lowpc;
308 if (profiling < 2 && s < s_textsize)
309 kcount[s / (HISTFRACTION * sizeof (*kcount))]++;
310#endif
311 }
312 /*
313 * We maintain statistics shown by user-level statistics
314 * programs: the amount of time in each cpu state, and
315 * the amount of time each of DK_NDRIVE ``drives'' is busy.
316 */
317 cp_time[cpstate]++;
318 for (s = 0; s < DK_NDRIVE; s++)
319 if (dk_busy&(1<<s))
320 dk_time[s]++;
321}
322
323/*
324 * Software priority level clock interrupt.
325 * Run periodic events from timeout queue.
326 */
327/*ARGSUSED*/
328softclock(frame)
329 clockframe frame;
330{
331
332 for (;;) {
333 register struct callout *p1;
334 register caddr_t arg;
335 register int (*func)();
336 register int a, s;
337
338 s = splhigh();
339 if ((p1 = calltodo.c_next) == 0 || p1->c_time > 0) {
340 splx(s);
341 break;
342 }
343 arg = p1->c_arg; func = p1->c_func; a = p1->c_time;
344 calltodo.c_next = p1->c_next;
345 p1->c_next = callfree;
346 callfree = p1;
347 splx(s);
348 (*func)(arg, a);
349 }
350
351 /*
352 * If no process to work with, we're finished.
353 */
354 if (curproc == 0) return;
355
356 /*
357 * If trapped user-mode and profiling, give it
358 * a profiling tick.
359 */
360 if (CLKF_USERMODE(&frame)) {
361 register struct proc *p = curproc;
362
363 if (p->p_stats->p_prof.pr_scale)
364 profile_tick(p, &frame);
365 /*
366 * Check to see if process has accumulated
367 * more than 10 minutes of user time. If so
368 * reduce priority to give others a chance.
369 */
370 if (p->p_ucred->cr_uid && p->p_nice == NZERO &&
371 p->p_utime.tv_sec > 10 * 60) {
372 p->p_nice = NZERO + 4;
373 setpri(p);
374 p->p_pri = p->p_usrpri;
375 }
376 }
377}
378
379/*
380 * Arrange that (*func)(arg) is called in t/hz seconds.
381 */
382timeout(func, arg, t)
383 int (*func)();
384 caddr_t arg;
385 register int t;
386{
387 register struct callout *p1, *p2, *pnew;
388 register int s = splhigh();
389
390 if (t <= 0)
391 t = 1;
392 pnew = callfree;
393 if (pnew == NULL)
394 panic("timeout table overflow");
395 callfree = pnew->c_next;
396 pnew->c_arg = arg;
397 pnew->c_func = func;
398 for (p1 = &calltodo; (p2 = p1->c_next) && p2->c_time < t; p1 = p2)
399 if (p2->c_time > 0)
400 t -= p2->c_time;
401 p1->c_next = pnew;
402 pnew->c_next = p2;
403 pnew->c_time = t;
404 if (p2)
405 p2->c_time -= t;
406 splx(s);
407}
408
409/*
410 * untimeout is called to remove a function timeout call
411 * from the callout structure.
412 */
413untimeout(func, arg)
414 int (*func)();
415 caddr_t arg;
416{
417 register struct callout *p1, *p2;
418 register int s;
419
420 s = splhigh();
421 for (p1 = &calltodo; (p2 = p1->c_next) != 0; p1 = p2) {
422 if (p2->c_func == func && p2->c_arg == arg) {
423 if (p2->c_next && p2->c_time > 0)
424 p2->c_next->c_time += p2->c_time;
425 p1->c_next = p2->c_next;
426 p2->c_next = callfree;
427 callfree = p2;
428 break;
429 }
430 }
431 splx(s);
432}
433
434/*
435 * Compute number of hz until specified time.
436 * Used to compute third argument to timeout() from an
437 * absolute time.
438 */
439hzto(tv)
440 struct timeval *tv;
441{
442 register long ticks;
443 register long sec;
444 int s = splhigh();
445
446 /*
447 * If number of milliseconds will fit in 32 bit arithmetic,
448 * then compute number of milliseconds to time and scale to
449 * ticks. Otherwise just compute number of hz in time, rounding
450 * times greater than representible to maximum value.
451 *
452 * Delta times less than 25 days can be computed ``exactly''.
453 * Maximum value for any timeout in 10ms ticks is 250 days.
454 */
455 sec = tv->tv_sec - time.tv_sec;
456 if (sec <= 0x7fffffff / 1000 - 1000)
457 ticks = ((tv->tv_sec - time.tv_sec) * 1000 +
458 (tv->tv_usec - time.tv_usec) / 1000) / (tick / 1000);
459 else if (sec <= 0x7fffffff / hz)
460 ticks = sec * hz;
461 else
462 ticks = 0x7fffffff;
463 splx(s);
464 return (ticks);
465}