kern_clock.c revision 1.25 1 /* $NetBSD: kern_clock.c,v 1.25 1996/02/04 02:15:15 christos Exp $ */
2
3 /*-
4 * Copyright (c) 1982, 1986, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. All advertising materials mentioning features or use of this software
21 * must display the following acknowledgement:
22 * This product includes software developed by the University of
23 * California, Berkeley and its contributors.
24 * 4. Neither the name of the University nor the names of its contributors
25 * may be used to endorse or promote products derived from this software
26 * without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
39 *
40 * @(#)kern_clock.c 8.5 (Berkeley) 1/21/94
41 */
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/dkstat.h>
46 #include <sys/callout.h>
47 #include <sys/kernel.h>
48 #include <sys/proc.h>
49 #include <sys/resourcevar.h>
50 #include <sys/signalvar.h>
51
52 #include <machine/cpu.h>
53
54 #include <kern/kern_extern.h>
55
56 #ifdef GPROF
57 #include <sys/gmon.h>
58 #endif
59
60 /*
61 * Clock handling routines.
62 *
63 * This code is written to operate with two timers that run independently of
64 * each other. The main clock, running hz times per second, is used to keep
65 * track of real time. The second timer handles kernel and user profiling,
66 * and does resource use estimation. If the second timer is programmable,
67 * it is randomized to avoid aliasing between the two clocks. For example,
68 * the randomization prevents an adversary from always giving up the cpu
69 * just before its quantum expires. Otherwise, it would never accumulate
70 * cpu ticks. The mean frequency of the second timer is stathz.
71 *
72 * If no second timer exists, stathz will be zero; in this case we drive
73 * profiling and statistics off the main clock. This WILL NOT be accurate;
74 * do not do it unless absolutely necessary.
75 *
76 * The statistics clock may (or may not) be run at a higher rate while
77 * profiling. This profile clock runs at profhz. We require that profhz
78 * be an integral multiple of stathz.
79 *
80 * If the statistics clock is running fast, it must be divided by the ratio
81 * profhz/stathz for statistics. (For profiling, every tick counts.)
82 */
83
84 /*
85 * TODO:
86 * allocate more timeout table slots when table overflows.
87 */
88
89 /*
90 * Bump a timeval by a small number of usec's.
91 */
92 #define BUMPTIME(t, usec) { \
93 register volatile struct timeval *tp = (t); \
94 register long us; \
95 \
96 tp->tv_usec = us = tp->tv_usec + (usec); \
97 if (us >= 1000000) { \
98 tp->tv_usec = us - 1000000; \
99 tp->tv_sec++; \
100 } \
101 }
102
103 int stathz;
104 int profhz;
105 int profprocs;
106 int ticks;
107 static int psdiv, pscnt; /* prof => stat divider */
108 int psratio; /* ratio: prof / stat */
109 int tickfix, tickfixinterval; /* used if tick not really integral */
110 static int tickfixcnt; /* number of ticks since last fix */
111
112 volatile struct timeval time;
113 volatile struct timeval mono_time;
114
115 /*
116 * Initialize clock frequencies and start both clocks running.
117 */
118 void
119 initclocks()
120 {
121 register int i;
122
123 /*
124 * Set divisors to 1 (normal case) and let the machine-specific
125 * code do its bit.
126 */
127 psdiv = pscnt = 1;
128 cpu_initclocks();
129
130 /*
131 * Compute profhz/stathz, and fix profhz if needed.
132 */
133 i = stathz ? stathz : hz;
134 if (profhz == 0)
135 profhz = i;
136 psratio = profhz / i;
137 }
138
139 /*
140 * The real-time timer, interrupting hz times per second.
141 */
142 void
143 hardclock(frame)
144 register struct clockframe *frame;
145 {
146 register struct callout *p1;
147 register struct proc *p;
148 register int delta, needsoft;
149 extern int tickdelta;
150 extern long timedelta;
151
152 /*
153 * Update real-time timeout queue.
154 * At front of queue are some number of events which are ``due''.
155 * The time to these is <= 0 and if negative represents the
156 * number of ticks which have passed since it was supposed to happen.
157 * The rest of the q elements (times > 0) are events yet to happen,
158 * where the time for each is given as a delta from the previous.
159 * Decrementing just the first of these serves to decrement the time
160 * to all events.
161 */
162 needsoft = 0;
163 for (p1 = calltodo.c_next; p1 != NULL; p1 = p1->c_next) {
164 if (--p1->c_time > 0)
165 break;
166 needsoft = 1;
167 if (p1->c_time == 0)
168 break;
169 }
170
171 p = curproc;
172 if (p) {
173 register struct pstats *pstats;
174
175 /*
176 * Run current process's virtual and profile time, as needed.
177 */
178 pstats = p->p_stats;
179 if (CLKF_USERMODE(frame) &&
180 timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
181 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
182 psignal(p, SIGVTALRM);
183 if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
184 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
185 psignal(p, SIGPROF);
186 }
187
188 /*
189 * If no separate statistics clock is available, run it from here.
190 */
191 if (stathz == 0)
192 statclock(frame);
193
194 /*
195 * Increment the time-of-day. The increment is normally just
196 * ``tick''. If the machine is one which has a clock frequency
197 * such that ``hz'' would not divide the second evenly into
198 * milliseconds, a periodic adjustment must be applied. Finally,
199 * if we are still adjusting the time (see adjtime()),
200 * ``tickdelta'' may also be added in.
201 */
202 ticks++;
203 delta = tick;
204 if (tickfix) {
205 tickfixcnt++;
206 if (tickfixcnt >= tickfixinterval) {
207 delta += tickfix;
208 tickfixcnt = 0;
209 }
210 }
211 if (timedelta != 0) {
212 delta = tick + tickdelta;
213 timedelta -= tickdelta;
214 }
215 BUMPTIME(&time, delta);
216 BUMPTIME(&mono_time, delta);
217
218 /*
219 * Process callouts at a very low cpu priority, so we don't keep the
220 * relatively high clock interrupt priority any longer than necessary.
221 */
222 if (needsoft) {
223 if (CLKF_BASEPRI(frame)) {
224 /*
225 * Save the overhead of a software interrupt;
226 * it will happen as soon as we return, so do it now.
227 */
228 (void)splsoftclock();
229 softclock();
230 } else
231 setsoftclock();
232 }
233 }
234
235 /*
236 * Software (low priority) clock interrupt.
237 * Run periodic events from timeout queue.
238 */
239 /*ARGSUSED*/
240 void
241 softclock()
242 {
243 register struct callout *c;
244 register void *arg;
245 register void (*func) __P((void *));
246 register int s;
247
248 s = splhigh();
249 while ((c = calltodo.c_next) != NULL && c->c_time <= 0) {
250 func = c->c_func;
251 arg = c->c_arg;
252 calltodo.c_next = c->c_next;
253 c->c_next = callfree;
254 callfree = c;
255 splx(s);
256 (*func)(arg);
257 (void) splhigh();
258 }
259 splx(s);
260 }
261
262 /*
263 * timeout --
264 * Execute a function after a specified length of time.
265 *
266 * untimeout --
267 * Cancel previous timeout function call.
268 *
269 * See AT&T BCI Driver Reference Manual for specification. This
270 * implementation differs from that one in that no identification
271 * value is returned from timeout, rather, the original arguments
272 * to timeout are used to identify entries for untimeout.
273 */
274 void
275 timeout(ftn, arg, ticks)
276 void (*ftn) __P((void *));
277 void *arg;
278 register int ticks;
279 {
280 register struct callout *new, *p, *t;
281 register int s;
282
283 if (ticks <= 0)
284 ticks = 1;
285
286 /* Lock out the clock. */
287 s = splhigh();
288
289 /* Fill in the next free callout structure. */
290 if (callfree == NULL)
291 panic("timeout table full");
292 new = callfree;
293 callfree = new->c_next;
294 new->c_arg = arg;
295 new->c_func = ftn;
296
297 /*
298 * The time for each event is stored as a difference from the time
299 * of the previous event on the queue. Walk the queue, correcting
300 * the ticks argument for queue entries passed. Correct the ticks
301 * value for the queue entry immediately after the insertion point
302 * as well. Watch out for negative c_time values; these represent
303 * overdue events.
304 */
305 for (p = &calltodo;
306 (t = p->c_next) != NULL && ticks > t->c_time; p = t)
307 if (t->c_time > 0)
308 ticks -= t->c_time;
309 new->c_time = ticks;
310 if (t != NULL)
311 t->c_time -= ticks;
312
313 /* Insert the new entry into the queue. */
314 p->c_next = new;
315 new->c_next = t;
316 splx(s);
317 }
318
319 void
320 untimeout(ftn, arg)
321 void (*ftn) __P((void *));
322 void *arg;
323 {
324 register struct callout *p, *t;
325 register int s;
326
327 s = splhigh();
328 for (p = &calltodo; (t = p->c_next) != NULL; p = t)
329 if (t->c_func == ftn && t->c_arg == arg) {
330 /* Increment next entry's tick count. */
331 if (t->c_next && t->c_time > 0)
332 t->c_next->c_time += t->c_time;
333
334 /* Move entry from callout queue to callfree queue. */
335 p->c_next = t->c_next;
336 t->c_next = callfree;
337 callfree = t;
338 break;
339 }
340 splx(s);
341 }
342
343 /*
344 * Compute number of hz until specified time. Used to
345 * compute third argument to timeout() from an absolute time.
346 */
347 int
348 hzto(tv)
349 struct timeval *tv;
350 {
351 register long ticks, sec;
352 int s;
353
354 /*
355 * If number of microseconds will fit in 32 bit arithmetic,
356 * then compute number of microseconds to time and scale to
357 * ticks. Otherwise just compute number of hz in time, rounding
358 * times greater than representible to maximum value. (We must
359 * compute in microseconds, because hz can be greater than 1000,
360 * and thus tick can be less than one millisecond).
361 *
362 * Delta times less than 14 hours can be computed ``exactly''.
363 * (Note that if hz would yeild a non-integral number of us per
364 * tick, i.e. tickfix is nonzero, timouts can be a tick longer
365 * than they should be.) Maximum value for any timeout in 10ms
366 * ticks is 250 days.
367 */
368 s = splhigh();
369 sec = tv->tv_sec - time.tv_sec;
370 if (sec <= 0x7fffffff / 1000000 - 1)
371 ticks = ((tv->tv_sec - time.tv_sec) * 1000000 +
372 (tv->tv_usec - time.tv_usec)) / tick;
373 else if (sec <= 0x7fffffff / hz)
374 ticks = sec * hz;
375 else
376 ticks = 0x7fffffff;
377 splx(s);
378 return (ticks);
379 }
380
381 /*
382 * Start profiling on a process.
383 *
384 * Kernel profiling passes proc0 which never exits and hence
385 * keeps the profile clock running constantly.
386 */
387 void
388 startprofclock(p)
389 register struct proc *p;
390 {
391 int s;
392
393 if ((p->p_flag & P_PROFIL) == 0) {
394 p->p_flag |= P_PROFIL;
395 if (++profprocs == 1 && stathz != 0) {
396 s = splstatclock();
397 psdiv = pscnt = psratio;
398 setstatclockrate(profhz);
399 splx(s);
400 }
401 }
402 }
403
404 /*
405 * Stop profiling on a process.
406 */
407 void
408 stopprofclock(p)
409 register struct proc *p;
410 {
411 int s;
412
413 if (p->p_flag & P_PROFIL) {
414 p->p_flag &= ~P_PROFIL;
415 if (--profprocs == 0 && stathz != 0) {
416 s = splstatclock();
417 psdiv = pscnt = 1;
418 setstatclockrate(stathz);
419 splx(s);
420 }
421 }
422 }
423
424 /*
425 * Statistics clock. Grab profile sample, and if divider reaches 0,
426 * do process and kernel statistics.
427 */
428 void
429 statclock(frame)
430 register struct clockframe *frame;
431 {
432 #ifdef GPROF
433 register struct gmonparam *g;
434 #endif
435 register struct proc *p;
436 register int i;
437
438 if (CLKF_USERMODE(frame)) {
439 p = curproc;
440 if (p->p_flag & P_PROFIL)
441 addupc_intr(p, CLKF_PC(frame), 1);
442 if (--pscnt > 0)
443 return;
444 /*
445 * Came from user mode; CPU was in user state.
446 * If this process is being profiled record the tick.
447 */
448 p->p_uticks++;
449 if (p->p_nice > NZERO)
450 cp_time[CP_NICE]++;
451 else
452 cp_time[CP_USER]++;
453 } else {
454 #ifdef GPROF
455 /*
456 * Kernel statistics are just like addupc_intr, only easier.
457 */
458 g = &_gmonparam;
459 if (g->state == GMON_PROF_ON) {
460 i = CLKF_PC(frame) - g->lowpc;
461 if (i < g->textsize) {
462 i /= HISTFRACTION * sizeof(*g->kcount);
463 g->kcount[i]++;
464 }
465 }
466 #endif
467 if (--pscnt > 0)
468 return;
469 /*
470 * Came from kernel mode, so we were:
471 * - handling an interrupt,
472 * - doing syscall or trap work on behalf of the current
473 * user process, or
474 * - spinning in the idle loop.
475 * Whichever it is, charge the time as appropriate.
476 * Note that we charge interrupts to the current process,
477 * regardless of whether they are ``for'' that process,
478 * so that we know how much of its real time was spent
479 * in ``non-process'' (i.e., interrupt) work.
480 */
481 p = curproc;
482 if (CLKF_INTR(frame)) {
483 if (p != NULL)
484 p->p_iticks++;
485 cp_time[CP_INTR]++;
486 } else if (p != NULL) {
487 p->p_sticks++;
488 cp_time[CP_SYS]++;
489 } else
490 cp_time[CP_IDLE]++;
491 }
492 pscnt = psdiv;
493
494 /*
495 * XXX Support old-style instrumentation for now.
496 *
497 * We maintain statistics shown by user-level statistics
498 * programs: the amount of time in each cpu state, and
499 * the amount of time each of DK_NDRIVE ``drives'' is busy.
500 *
501 * XXX should either run linked list of drives, or (better)
502 * grab timestamps in the start & done code.
503 */
504 for (i = 0; i < DK_NDRIVE; i++)
505 if (dk_busy & (1 << i))
506 dk_time[i]++;
507
508 /*
509 * We adjust the priority of the current process. The priority of
510 * a process gets worse as it accumulates CPU time. The cpu usage
511 * estimator (p_estcpu) is increased here. The formula for computing
512 * priorities (in kern_synch.c) will compute a different value each
513 * time p_estcpu increases by 4. The cpu usage estimator ramps up
514 * quite quickly when the process is running (linearly), and decays
515 * away exponentially, at a rate which is proportionally slower when
516 * the system is busy. The basic principal is that the system will
517 * 90% forget that the process used a lot of CPU time in 5 * loadav
518 * seconds. This causes the system to favor processes which haven't
519 * run much recently, and to round-robin among other processes.
520 */
521 if (p != NULL) {
522 p->p_cpticks++;
523 if (++p->p_estcpu == 0)
524 p->p_estcpu--;
525 if ((p->p_estcpu & 3) == 0) {
526 resetpriority(p);
527 if (p->p_priority >= PUSER)
528 p->p_priority = p->p_usrpri;
529 }
530 }
531 }
532
533 /*
534 * Return information about system clocks.
535 */
536 int
537 sysctl_clockrate(where, sizep)
538 register char *where;
539 size_t *sizep;
540 {
541 struct clockinfo clkinfo;
542
543 /*
544 * Construct clockinfo structure.
545 */
546 clkinfo.tick = tick;
547 clkinfo.tickadj = tickadj;
548 clkinfo.hz = hz;
549 clkinfo.profhz = profhz;
550 clkinfo.stathz = stathz ? stathz : hz;
551 return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
552 }
553
554 #ifdef DDB
555 #include <machine/db_machdep.h>
556
557 #include <ddb/db_interface.h>
558 #include <ddb/db_access.h>
559 #include <ddb/db_sym.h>
560 #include <ddb/db_output.h>
561
562 void db_show_callout(addr, haddr, count, modif)
563 db_expr_t addr;
564 int haddr;
565 db_expr_t count;
566 char *modif;
567 {
568 register struct callout *p1;
569 register int cum;
570 register int s;
571 db_expr_t offset;
572 char *name;
573
574 db_printf(" cum ticks arg func\n");
575 s = splhigh();
576 for (cum = 0, p1 = calltodo.c_next; p1; p1 = p1->c_next) {
577 register int t = p1->c_time;
578
579 if (t > 0)
580 cum += t;
581
582 db_find_sym_and_offset((db_addr_t)p1->c_func, &name, &offset);
583 if (name == NULL)
584 name = "?";
585
586 db_printf("%9d %9d %8x %s (%x)\n",
587 cum, t, p1->c_arg, name, p1->c_func);
588 }
589 splx(s);
590 }
591 #endif
592