xref: /openbsd-src/sys/kern/kern_clock.c (revision f2cca587c738bd5e1cda0abe0fdf37f7dd1b509d)
1 /*	$OpenBSD: kern_clock.c,v 1.41 2003/05/13 20:31:59 miod Exp $	*/
2 /*	$NetBSD: kern_clock.c,v 1.34 1996/06/09 04:51:03 briggs Exp $	*/
3 
4 /*-
5  * Copyright (c) 1982, 1986, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. All advertising materials mentioning features or use of this software
22  *    must display the following acknowledgement:
23  *	This product includes software developed by the University of
24  *	California, Berkeley and its contributors.
25  * 4. Neither the name of the University nor the names of its contributors
26  *    may be used to endorse or promote products derived from this software
27  *    without specific prior written permission.
28  *
29  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
30  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
31  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
32  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
33  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
34  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
35  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
37  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
38  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39  * SUCH DAMAGE.
40  *
41  *	@(#)kern_clock.c	8.5 (Berkeley) 1/21/94
42  */
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/dkstat.h>
47 #include <sys/timeout.h>
48 #include <sys/kernel.h>
49 #include <sys/limits.h>
50 #include <sys/proc.h>
51 #include <sys/resourcevar.h>
52 #include <sys/signalvar.h>
53 #include <uvm/uvm_extern.h>
54 #include <sys/sysctl.h>
55 #include <sys/sched.h>
56 
57 #include <machine/cpu.h>
58 
59 #ifdef GPROF
60 #include <sys/gmon.h>
61 #endif
62 
63 /*
64  * Clock handling routines.
65  *
66  * This code is written to operate with two timers that run independently of
67  * each other.  The main clock, running hz times per second, is used to keep
68  * track of real time.  The second timer handles kernel and user profiling,
69  * and does resource use estimation.  If the second timer is programmable,
70  * it is randomized to avoid aliasing between the two clocks.  For example,
71  * the randomization prevents an adversary from always giving up the cpu
72  * just before its quantum expires.  Otherwise, it would never accumulate
73  * cpu ticks.  The mean frequency of the second timer is stathz.
74  *
75  * If no second timer exists, stathz will be zero; in this case we drive
76  * profiling and statistics off the main clock.  This WILL NOT be accurate;
77  * do not do it unless absolutely necessary.
78  *
79  * The statistics clock may (or may not) be run at a higher rate while
80  * profiling.  This profile clock runs at profhz.  We require that profhz
81  * be an integral multiple of stathz.
82  *
83  * If the statistics clock is running fast, it must be divided by the ratio
84  * profhz/stathz for statistics.  (For profiling, every tick counts.)
85  */
86 
87 /*
88  * Bump a timeval by a small number of usec's.
89  */
90 #define BUMPTIME(t, usec) { \
91 	register volatile struct timeval *tp = (t); \
92 	register long us; \
93  \
94 	tp->tv_usec = us = tp->tv_usec + (usec); \
95 	if (us >= 1000000) { \
96 		tp->tv_usec = us - 1000000; \
97 		tp->tv_sec++; \
98 	} \
99 }
100 
101 int	stathz;
102 int	schedhz;
103 int	profhz;
104 int	profprocs;
105 int	ticks;
106 static int psdiv, pscnt;		/* prof => stat divider */
107 int	psratio;			/* ratio: prof / stat */
108 int	tickfix, tickfixinterval;	/* used if tick not really integral */
109 static int tickfixcnt;			/* accumulated fractional error */
110 
111 long cp_time[CPUSTATES];
112 
113 volatile struct	timeval time
114 	__attribute__((__aligned__(__alignof__(quad_t))));
115 volatile struct	timeval mono_time;
116 
117 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
118 void	*softclock_si;
119 void	generic_softclock(void *);
120 
121 void
122 generic_softclock(void *ignore)
123 {
124 	/*
125 	 * XXX - dont' commit, just a dummy wrapper until we learn everyone
126 	 *       deal with a changed proto for softclock().
127 	 */
128 	softclock();
129 }
130 #endif
131 
132 /*
133  * Initialize clock frequencies and start both clocks running.
134  */
135 void
136 initclocks()
137 {
138 	int i;
139 
140 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
141 	softclock_si = softintr_establish(IPL_SOFTCLOCK, generic_softclock, NULL);
142 	if (softclock_si == NULL)
143 		panic("initclocks: unable to register softclock intr");
144 #endif
145 
146 	/*
147 	 * Set divisors to 1 (normal case) and let the machine-specific
148 	 * code do its bit.
149 	 */
150 	psdiv = pscnt = 1;
151 	cpu_initclocks();
152 
153 	/*
154 	 * Compute profhz/stathz, and fix profhz if needed.
155 	 */
156 	i = stathz ? stathz : hz;
157 	if (profhz == 0)
158 		profhz = i;
159 	psratio = profhz / i;
160 }
161 
162 /*
163  * The real-time timer, interrupting hz times per second.
164  */
165 void
166 hardclock(frame)
167 	register struct clockframe *frame;
168 {
169 	register struct proc *p;
170 	register int delta;
171 	extern int tickdelta;
172 	extern long timedelta;
173 
174 	p = curproc;
175 	if (p) {
176 		register struct pstats *pstats;
177 
178 		/*
179 		 * Run current process's virtual and profile time, as needed.
180 		 */
181 		pstats = p->p_stats;
182 		if (CLKF_USERMODE(frame) &&
183 		    timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
184 		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
185 			psignal(p, SIGVTALRM);
186 		if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
187 		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
188 			psignal(p, SIGPROF);
189 	}
190 
191 	/*
192 	 * If no separate statistics clock is available, run it from here.
193 	 */
194 	if (stathz == 0)
195 		statclock(frame);
196 
197 	/*
198 	 * Increment the time-of-day.  The increment is normally just
199 	 * ``tick''.  If the machine is one which has a clock frequency
200 	 * such that ``hz'' would not divide the second evenly into
201 	 * milliseconds, a periodic adjustment must be applied.  Finally,
202 	 * if we are still adjusting the time (see adjtime()),
203 	 * ``tickdelta'' may also be added in.
204 	 */
205 	ticks++;
206 	delta = tick;
207 
208 	if (tickfix) {
209 		tickfixcnt += tickfix;
210 		if (tickfixcnt >= tickfixinterval) {
211 			delta++;
212 			tickfixcnt -= tickfixinterval;
213 		}
214 	}
215 	/* Imprecise 4bsd adjtime() handling */
216 	if (timedelta != 0) {
217 		delta += tickdelta;
218 		timedelta -= tickdelta;
219 	}
220 
221 #ifdef notyet
222 	microset();
223 #endif
224 
225 	BUMPTIME(&time, delta);
226 	BUMPTIME(&mono_time, delta);
227 
228 #ifdef CPU_CLOCKUPDATE
229 	CPU_CLOCKUPDATE();
230 #endif
231 
232 	/*
233 	 * Update real-time timeout queue.
234 	 * Process callouts at a very low cpu priority, so we don't keep the
235 	 * relatively high clock interrupt priority any longer than necessary.
236 	 */
237 	if (timeout_hardclock_update()) {
238 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
239 		softintr_schedule(softclock_si);
240 #else
241 		setsoftclock();
242 #endif
243 	}
244 }
245 
246 /*
247  * Compute number of hz until specified time.  Used to
248  * compute the second argument to timeout_add() from an absolute time.
249  */
250 int
251 hzto(tv)
252 	struct timeval *tv;
253 {
254 	unsigned long ticks;
255 	long sec, usec;
256 	int s;
257 
258 	/*
259 	 * If the number of usecs in the whole seconds part of the time
260 	 * difference fits in a long, then the total number of usecs will
261 	 * fit in an unsigned long.  Compute the total and convert it to
262 	 * ticks, rounding up and adding 1 to allow for the current tick
263 	 * to expire.  Rounding also depends on unsigned long arithmetic
264 	 * to avoid overflow.
265 	 *
266 	 * Otherwise, if the number of ticks in the whole seconds part of
267 	 * the time difference fits in a long, then convert the parts to
268 	 * ticks separately and add, using similar rounding methods and
269 	 * overflow avoidance.  This method would work in the previous
270 	 * case but it is slightly slower and assumes that hz is integral.
271 	 *
272 	 * Otherwise, round the time difference down to the maximum
273 	 * representable value.
274 	 *
275 	 * If ints have 32 bits, then the maximum value for any timeout in
276 	 * 10ms ticks is 248 days.
277 	 */
278 	s = splhigh();
279 	sec = tv->tv_sec - time.tv_sec;
280 	usec = tv->tv_usec - time.tv_usec;
281 	splx(s);
282 	if (usec < 0) {
283 		sec--;
284 		usec += 1000000;
285 	}
286 	if (sec < 0 || (sec == 0 && usec <= 0)) {
287 		ticks = 0;
288 	} else if (sec <= LONG_MAX / 1000000)
289 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
290 		    / tick + 1;
291 	else if (sec <= LONG_MAX / hz)
292 		ticks = sec * hz
293 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
294 	else
295 		ticks = LONG_MAX;
296 	if (ticks > INT_MAX)
297 		ticks = INT_MAX;
298 	return ((int)ticks);
299 }
300 
301 /*
302  * Compute number of hz in the specified amount of time.
303  */
304 int
305 tvtohz(struct timeval *tv)
306 {
307 	unsigned long ticks;
308 	long sec, usec;
309 
310 	/*
311 	 * If the number of usecs in the whole seconds part of the time
312 	 * fits in a long, then the total number of usecs will
313 	 * fit in an unsigned long.  Compute the total and convert it to
314 	 * ticks, rounding up and adding 1 to allow for the current tick
315 	 * to expire.  Rounding also depends on unsigned long arithmetic
316 	 * to avoid overflow.
317 	 *
318 	 * Otherwise, if the number of ticks in the whole seconds part of
319 	 * the time fits in a long, then convert the parts to
320 	 * ticks separately and add, using similar rounding methods and
321 	 * overflow avoidance.  This method would work in the previous
322 	 * case but it is slightly slower and assumes that hz is integral.
323 	 *
324 	 * Otherwise, round the time down to the maximum
325 	 * representable value.
326 	 *
327 	 * If ints have 32 bits, then the maximum value for any timeout in
328 	 * 10ms ticks is 248 days.
329 	 */
330 	sec = tv->tv_sec;
331 	usec = tv->tv_usec;
332 	if (sec < 0 || (sec == 0 && usec <= 0))
333 		ticks = 0;
334 	else if (sec <= LONG_MAX / 1000000)
335 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
336 		    / tick + 1;
337 	else if (sec <= LONG_MAX / hz)
338 		ticks = sec * hz
339 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
340 	else
341 		ticks = LONG_MAX;
342 	if (ticks > INT_MAX)
343 		ticks = INT_MAX;
344 	return ((int)ticks);
345 }
346 
347 /*
348  * Start profiling on a process.
349  *
350  * Kernel profiling passes proc0 which never exits and hence
351  * keeps the profile clock running constantly.
352  */
353 void
354 startprofclock(p)
355 	register struct proc *p;
356 {
357 	int s;
358 
359 	if ((p->p_flag & P_PROFIL) == 0) {
360 		p->p_flag |= P_PROFIL;
361 		if (++profprocs == 1 && stathz != 0) {
362 			s = splstatclock();
363 			psdiv = pscnt = psratio;
364 			setstatclockrate(profhz);
365 			splx(s);
366 		}
367 	}
368 }
369 
370 /*
371  * Stop profiling on a process.
372  */
373 void
374 stopprofclock(p)
375 	register struct proc *p;
376 {
377 	int s;
378 
379 	if (p->p_flag & P_PROFIL) {
380 		p->p_flag &= ~P_PROFIL;
381 		if (--profprocs == 0 && stathz != 0) {
382 			s = splstatclock();
383 			psdiv = pscnt = 1;
384 			setstatclockrate(stathz);
385 			splx(s);
386 		}
387 	}
388 }
389 
390 /*
391  * Statistics clock.  Grab profile sample, and if divider reaches 0,
392  * do process and kernel statistics.
393  */
394 void
395 statclock(frame)
396 	register struct clockframe *frame;
397 {
398 #ifdef GPROF
399 	register struct gmonparam *g;
400 	register int i;
401 #endif
402 	static int schedclk;
403 	register struct proc *p;
404 
405 	if (CLKF_USERMODE(frame)) {
406 		p = curproc;
407 		if (p->p_flag & P_PROFIL)
408 			addupc_intr(p, CLKF_PC(frame));
409 		if (--pscnt > 0)
410 			return;
411 		/*
412 		 * Came from user mode; CPU was in user state.
413 		 * If this process is being profiled record the tick.
414 		 */
415 		p->p_uticks++;
416 		if (p->p_nice > NZERO)
417 			cp_time[CP_NICE]++;
418 		else
419 			cp_time[CP_USER]++;
420 	} else {
421 #ifdef GPROF
422 		/*
423 		 * Kernel statistics are just like addupc_intr, only easier.
424 		 */
425 		g = &_gmonparam;
426 		if (g->state == GMON_PROF_ON) {
427 			i = CLKF_PC(frame) - g->lowpc;
428 			if (i < g->textsize) {
429 				i /= HISTFRACTION * sizeof(*g->kcount);
430 				g->kcount[i]++;
431 			}
432 		}
433 #endif
434 		if (--pscnt > 0)
435 			return;
436 		/*
437 		 * Came from kernel mode, so we were:
438 		 * - handling an interrupt,
439 		 * - doing syscall or trap work on behalf of the current
440 		 *   user process, or
441 		 * - spinning in the idle loop.
442 		 * Whichever it is, charge the time as appropriate.
443 		 * Note that we charge interrupts to the current process,
444 		 * regardless of whether they are ``for'' that process,
445 		 * so that we know how much of its real time was spent
446 		 * in ``non-process'' (i.e., interrupt) work.
447 		 */
448 		p = curproc;
449 		if (CLKF_INTR(frame)) {
450 			if (p != NULL)
451 				p->p_iticks++;
452 			cp_time[CP_INTR]++;
453 		} else if (p != NULL) {
454 			p->p_sticks++;
455 			cp_time[CP_SYS]++;
456 		} else
457 			cp_time[CP_IDLE]++;
458 	}
459 	pscnt = psdiv;
460 
461 	if (p != NULL) {
462 		p->p_cpticks++;
463 		/*
464 		 * If no schedclock is provided, call it here at ~~12-25 Hz;
465 		 * ~~16 Hz is best
466 		 */
467 		if (schedhz == 0)
468 			if ((++schedclk & 3) == 0)
469 				schedclock(p);
470 	}
471 }
472 
473 /*
474  * Return information about system clocks.
475  */
476 int
477 sysctl_clockrate(where, sizep)
478 	register char *where;
479 	size_t *sizep;
480 {
481 	struct clockinfo clkinfo;
482 
483 	/*
484 	 * Construct clockinfo structure.
485 	 */
486 	clkinfo.tick = tick;
487 	clkinfo.tickadj = tickadj;
488 	clkinfo.hz = hz;
489 	clkinfo.profhz = profhz;
490 	clkinfo.stathz = stathz ? stathz : hz;
491 	return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
492 }
493