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