xref: /openbsd-src/sys/kern/kern_clock.c (revision c46fd98e83c3f85ee585e9e7b62f29adddc53812)
1 /*	$OpenBSD: kern_clock.c,v 1.43 2004/06/09 20:18:28 art 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(struct clockframe *frame)
163 {
164 	struct proc *p;
165 	int delta;
166 	extern int tickdelta;
167 	extern long timedelta;
168 #ifdef __HAVE_CPUINFO
169 	struct cpu_info *ci = curcpu();
170 #endif
171 
172 	p = curproc;
173 	if (p) {
174 		register struct pstats *pstats;
175 
176 		/*
177 		 * Run current process's virtual and profile time, as needed.
178 		 */
179 		pstats = p->p_stats;
180 		if (CLKF_USERMODE(frame) &&
181 		    timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
182 		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
183 			psignal(p, SIGVTALRM);
184 		if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
185 		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
186 			psignal(p, SIGPROF);
187 	}
188 
189 	/*
190 	 * If no separate statistics clock is available, run it from here.
191 	 */
192 	if (stathz == 0)
193 		statclock(frame);
194 
195 #ifdef __HAVE_CPUINFO
196 	if (--ci->ci_schedstate.spc_rrticks <= 0)
197 		roundrobin(ci);
198 #endif
199 
200 	/*
201 	 * Increment the time-of-day.  The increment is normally just
202 	 * ``tick''.  If the machine is one which has a clock frequency
203 	 * such that ``hz'' would not divide the second evenly into
204 	 * milliseconds, a periodic adjustment must be applied.  Finally,
205 	 * if we are still adjusting the time (see adjtime()),
206 	 * ``tickdelta'' may also be added in.
207 	 */
208 	ticks++;
209 	delta = tick;
210 
211 	if (tickfix) {
212 		tickfixcnt += tickfix;
213 		if (tickfixcnt >= tickfixinterval) {
214 			delta++;
215 			tickfixcnt -= tickfixinterval;
216 		}
217 	}
218 	/* Imprecise 4bsd adjtime() handling */
219 	if (timedelta != 0) {
220 		delta += tickdelta;
221 		timedelta -= tickdelta;
222 	}
223 
224 #ifdef notyet
225 	microset();
226 #endif
227 
228 	BUMPTIME(&time, delta);
229 	BUMPTIME(&mono_time, delta);
230 
231 #ifdef CPU_CLOCKUPDATE
232 	CPU_CLOCKUPDATE();
233 #endif
234 
235 	/*
236 	 * Update real-time timeout queue.
237 	 * Process callouts at a very low cpu priority, so we don't keep the
238 	 * relatively high clock interrupt priority any longer than necessary.
239 	 */
240 	if (timeout_hardclock_update()) {
241 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
242 		softintr_schedule(softclock_si);
243 #else
244 		setsoftclock();
245 #endif
246 	}
247 }
248 
249 /*
250  * Compute number of hz until specified time.  Used to
251  * compute the second argument to timeout_add() from an absolute time.
252  */
253 int
254 hzto(tv)
255 	struct timeval *tv;
256 {
257 	unsigned long ticks;
258 	long sec, usec;
259 	int s;
260 
261 	/*
262 	 * If the number of usecs in the whole seconds part of the time
263 	 * difference fits in a long, then the total number of usecs will
264 	 * fit in an unsigned long.  Compute the total and convert it to
265 	 * ticks, rounding up and adding 1 to allow for the current tick
266 	 * to expire.  Rounding also depends on unsigned long arithmetic
267 	 * to avoid overflow.
268 	 *
269 	 * Otherwise, if the number of ticks in the whole seconds part of
270 	 * the time difference fits in a long, then convert the parts to
271 	 * ticks separately and add, using similar rounding methods and
272 	 * overflow avoidance.  This method would work in the previous
273 	 * case but it is slightly slower and assumes that hz is integral.
274 	 *
275 	 * Otherwise, round the time difference down to the maximum
276 	 * representable value.
277 	 *
278 	 * If ints have 32 bits, then the maximum value for any timeout in
279 	 * 10ms ticks is 248 days.
280 	 */
281 	s = splhigh();
282 	sec = tv->tv_sec - time.tv_sec;
283 	usec = tv->tv_usec - time.tv_usec;
284 	splx(s);
285 	if (usec < 0) {
286 		sec--;
287 		usec += 1000000;
288 	}
289 	if (sec < 0 || (sec == 0 && usec <= 0)) {
290 		ticks = 0;
291 	} else if (sec <= LONG_MAX / 1000000)
292 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
293 		    / tick + 1;
294 	else if (sec <= LONG_MAX / hz)
295 		ticks = sec * hz
296 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
297 	else
298 		ticks = LONG_MAX;
299 	if (ticks > INT_MAX)
300 		ticks = INT_MAX;
301 	return ((int)ticks);
302 }
303 
304 /*
305  * Compute number of hz in the specified amount of time.
306  */
307 int
308 tvtohz(struct timeval *tv)
309 {
310 	unsigned long ticks;
311 	long sec, usec;
312 
313 	/*
314 	 * If the number of usecs in the whole seconds part of the time
315 	 * fits in a long, then the total number of usecs will
316 	 * fit in an unsigned long.  Compute the total and convert it to
317 	 * ticks, rounding up and adding 1 to allow for the current tick
318 	 * to expire.  Rounding also depends on unsigned long arithmetic
319 	 * to avoid overflow.
320 	 *
321 	 * Otherwise, if the number of ticks in the whole seconds part of
322 	 * the time fits in a long, then convert the parts to
323 	 * ticks separately and add, using similar rounding methods and
324 	 * overflow avoidance.  This method would work in the previous
325 	 * case but it is slightly slower and assumes that hz is integral.
326 	 *
327 	 * Otherwise, round the time down to the maximum
328 	 * representable value.
329 	 *
330 	 * If ints have 32 bits, then the maximum value for any timeout in
331 	 * 10ms ticks is 248 days.
332 	 */
333 	sec = tv->tv_sec;
334 	usec = tv->tv_usec;
335 	if (sec < 0 || (sec == 0 && usec <= 0))
336 		ticks = 0;
337 	else if (sec <= LONG_MAX / 1000000)
338 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
339 		    / tick + 1;
340 	else if (sec <= LONG_MAX / hz)
341 		ticks = sec * hz
342 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
343 	else
344 		ticks = LONG_MAX;
345 	if (ticks > INT_MAX)
346 		ticks = INT_MAX;
347 	return ((int)ticks);
348 }
349 
350 /*
351  * Start profiling on a process.
352  *
353  * Kernel profiling passes proc0 which never exits and hence
354  * keeps the profile clock running constantly.
355  */
356 void
357 startprofclock(p)
358 	register struct proc *p;
359 {
360 	int s;
361 
362 	if ((p->p_flag & P_PROFIL) == 0) {
363 		p->p_flag |= P_PROFIL;
364 		if (++profprocs == 1 && stathz != 0) {
365 			s = splstatclock();
366 			psdiv = pscnt = psratio;
367 			setstatclockrate(profhz);
368 			splx(s);
369 		}
370 	}
371 }
372 
373 /*
374  * Stop profiling on a process.
375  */
376 void
377 stopprofclock(p)
378 	register struct proc *p;
379 {
380 	int s;
381 
382 	if (p->p_flag & P_PROFIL) {
383 		p->p_flag &= ~P_PROFIL;
384 		if (--profprocs == 0 && stathz != 0) {
385 			s = splstatclock();
386 			psdiv = pscnt = 1;
387 			setstatclockrate(stathz);
388 			splx(s);
389 		}
390 	}
391 }
392 
393 /*
394  * Statistics clock.  Grab profile sample, and if divider reaches 0,
395  * do process and kernel statistics.
396  */
397 void
398 statclock(struct clockframe *frame)
399 {
400 #ifdef GPROF
401 	struct gmonparam *g;
402 	int i;
403 #endif
404 #ifdef __HAVE_CPUINFO
405 	struct cpu_info *ci = curcpu();
406 	struct schedstate_percpu *spc = &ci->ci_schedstate;
407 #else
408 	static int schedclk;
409 #endif
410 	struct proc *p = curproc;
411 
412 #ifdef __HAVE_CPUINFO
413 	/*
414 	 * Notice changes in divisor frequency, and adjust clock
415 	 * frequency accordingly.
416 	 */
417 	if (spc->spc_psdiv != psdiv) {
418 		spc->spc_psdiv = psdiv;
419 		spc->spc_pscnt = psdiv;
420 		if (psdiv == 1) {
421 			setstatclockrate(stathz);
422 		} else {
423 			setstatclockrate(profhz);
424 		}
425 	}
426 /* XXX Kludgey */
427 #define pscnt spc->spc_pscnt
428 #define cp_time spc->spc_cp_time
429 #endif
430 
431 	if (CLKF_USERMODE(frame)) {
432 		if (p->p_flag & P_PROFIL)
433 			addupc_intr(p, CLKF_PC(frame));
434 		if (--pscnt > 0)
435 			return;
436 		/*
437 		 * Came from user mode; CPU was in user state.
438 		 * If this process is being profiled record the tick.
439 		 */
440 		p->p_uticks++;
441 		if (p->p_nice > NZERO)
442 			cp_time[CP_NICE]++;
443 		else
444 			cp_time[CP_USER]++;
445 	} else {
446 #ifdef GPROF
447 		/*
448 		 * Kernel statistics are just like addupc_intr, only easier.
449 		 */
450 		g = &_gmonparam;
451 		if (g->state == GMON_PROF_ON) {
452 			i = CLKF_PC(frame) - g->lowpc;
453 			if (i < g->textsize) {
454 				i /= HISTFRACTION * sizeof(*g->kcount);
455 				g->kcount[i]++;
456 			}
457 		}
458 #endif
459 		if (--pscnt > 0)
460 			return;
461 		/*
462 		 * Came from kernel mode, so we were:
463 		 * - handling an interrupt,
464 		 * - doing syscall or trap work on behalf of the current
465 		 *   user process, or
466 		 * - spinning in the idle loop.
467 		 * Whichever it is, charge the time as appropriate.
468 		 * Note that we charge interrupts to the current process,
469 		 * regardless of whether they are ``for'' that process,
470 		 * so that we know how much of its real time was spent
471 		 * in ``non-process'' (i.e., interrupt) work.
472 		 */
473 		if (CLKF_INTR(frame)) {
474 			if (p != NULL)
475 				p->p_iticks++;
476 			cp_time[CP_INTR]++;
477 		} else if (p != NULL) {
478 			p->p_sticks++;
479 			cp_time[CP_SYS]++;
480 		} else
481 			cp_time[CP_IDLE]++;
482 	}
483 	pscnt = psdiv;
484 
485 #ifdef __HAVE_CPUINFO
486 #undef pscnt
487 #undef cp_time
488 #endif
489 
490 	if (p != NULL) {
491 		p->p_cpticks++;
492 		/*
493 		 * If no schedclock is provided, call it here at ~~12-25 Hz;
494 		 * ~~16 Hz is best
495 		 */
496 		if (schedhz == 0) {
497 #ifdef __HAVE_CPUINFO
498 			if ((++curcpu()->ci_schedstate.spc_schedticks & 3) == 0)
499 				schedclock(p);
500 #else
501 			if ((++schedclk & 3) == 0)
502 				schedclock(p);
503 #endif
504 		}
505 	}
506 }
507 
508 /*
509  * Return information about system clocks.
510  */
511 int
512 sysctl_clockrate(where, sizep)
513 	register char *where;
514 	size_t *sizep;
515 {
516 	struct clockinfo clkinfo;
517 
518 	/*
519 	 * Construct clockinfo structure.
520 	 */
521 	clkinfo.tick = tick;
522 	clkinfo.tickadj = tickadj;
523 	clkinfo.hz = hz;
524 	clkinfo.profhz = profhz;
525 	clkinfo.stathz = stathz ? stathz : hz;
526 	return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
527 }
528