xref: /openbsd/sys/kern/kern_clock.c (revision 404b540a)
1 /*	$OpenBSD: kern_clock.c,v 1.68 2009/01/21 21:02:39 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. 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/user.h>
48 #include <sys/resourcevar.h>
49 #include <sys/signalvar.h>
50 #include <uvm/uvm_extern.h>
51 #include <sys/sysctl.h>
52 #include <sys/sched.h>
53 #ifdef __HAVE_TIMECOUNTER
54 #include <sys/timetc.h>
55 #endif
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 	volatile struct timeval *tp = (t); \
92 	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 
109 long cp_time[CPUSTATES];
110 
111 #ifndef __HAVE_TIMECOUNTER
112 int	tickfix, tickfixinterval;	/* used if tick not really integral */
113 static int tickfixcnt;			/* accumulated fractional error */
114 
115 volatile time_t time_second;
116 volatile time_t time_uptime;
117 
118 volatile struct	timeval time
119 	__attribute__((__aligned__(__alignof__(quad_t))));
120 volatile struct	timeval mono_time;
121 #endif
122 
123 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
124 void	*softclock_si;
125 void	generic_softclock(void *);
126 
127 void
128 generic_softclock(void *ignore)
129 {
130 	/*
131 	 * XXX - don't commit, just a dummy wrapper until we learn everyone
132 	 *       deal with a changed proto for softclock().
133 	 */
134 	softclock();
135 }
136 #endif
137 
138 /*
139  * Initialize clock frequencies and start both clocks running.
140  */
141 void
142 initclocks(void)
143 {
144 	int i;
145 #ifdef __HAVE_TIMECOUNTER
146 	extern void inittimecounter(void);
147 #endif
148 
149 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
150 	softclock_si = softintr_establish(IPL_SOFTCLOCK, generic_softclock, NULL);
151 	if (softclock_si == NULL)
152 		panic("initclocks: unable to register softclock intr");
153 #endif
154 
155 	/*
156 	 * Set divisors to 1 (normal case) and let the machine-specific
157 	 * code do its bit.
158 	 */
159 	psdiv = pscnt = 1;
160 	cpu_initclocks();
161 
162 	/*
163 	 * Compute profhz/stathz, and fix profhz if needed.
164 	 */
165 	i = stathz ? stathz : hz;
166 	if (profhz == 0)
167 		profhz = i;
168 	psratio = profhz / i;
169 
170 	/* For very large HZ, ensure that division by 0 does not occur later */
171 	if (tickadj == 0)
172 		tickadj = 1;
173 
174 #ifdef __HAVE_TIMECOUNTER
175 	inittimecounter();
176 #endif
177 }
178 
179 /*
180  * hardclock does the accounting needed for ITIMER_PROF and ITIMER_VIRTUAL.
181  * We don't want to send signals with psignal from hardclock because it makes
182  * MULTIPROCESSOR locking very complicated. Instead we use a small trick
183  * to send the signals safely and without blocking too many interrupts
184  * while doing that (signal handling can be heavy).
185  *
186  * hardclock detects that the itimer has expired, and schedules a timeout
187  * to deliver the signal. This works because of the following reasons:
188  *  - The timeout structures can be in struct pstats because the timers
189  *    can be only activated on curproc (never swapped). Swapout can
190  *    only happen from a kernel thread and softclock runs before threads
191  *    are scheduled.
192  *  - The timeout can be scheduled with a 1 tick time because we're
193  *    doing it before the timeout processing in hardclock. So it will
194  *    be scheduled to run as soon as possible.
195  *  - The timeout will be run in softclock which will run before we
196  *    return to userland and process pending signals.
197  *  - If the system is so busy that several VIRTUAL/PROF ticks are
198  *    sent before softclock processing, we'll send only one signal.
199  *    But if we'd send the signal from hardclock only one signal would
200  *    be delivered to the user process. So userland will only see one
201  *    signal anyway.
202  */
203 
204 void
205 virttimer_trampoline(void *v)
206 {
207 	struct proc *p = v;
208 
209 	psignal(p, SIGVTALRM);
210 }
211 
212 void
213 proftimer_trampoline(void *v)
214 {
215 	struct proc *p = v;
216 
217 	psignal(p, SIGPROF);
218 }
219 
220 /*
221  * The real-time timer, interrupting hz times per second.
222  */
223 void
224 hardclock(struct clockframe *frame)
225 {
226 	struct proc *p;
227 #ifndef __HAVE_TIMECOUNTER
228 	int delta;
229 	extern int tickdelta;
230 	extern long timedelta;
231 	extern int64_t ntp_tick_permanent;
232 	extern int64_t ntp_tick_acc;
233 #endif
234 	struct cpu_info *ci = curcpu();
235 
236 	p = curproc;
237 	if (p && ((p->p_flag & (P_SYSTEM | P_WEXIT)) == 0)) {
238 		struct pstats *pstats;
239 
240 		/*
241 		 * Run current process's virtual and profile time, as needed.
242 		 */
243 		pstats = p->p_stats;
244 		if (CLKF_USERMODE(frame) &&
245 		    timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
246 		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
247 			timeout_add(&pstats->p_virt_to, 1);
248 		if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
249 		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
250 			timeout_add(&pstats->p_prof_to, 1);
251 	}
252 
253 	/*
254 	 * If no separate statistics clock is available, run it from here.
255 	 */
256 	if (stathz == 0)
257 		statclock(frame);
258 
259 	if (--ci->ci_schedstate.spc_rrticks <= 0)
260 		roundrobin(ci);
261 
262 	/*
263 	 * If we are not the primary CPU, we're not allowed to do
264 	 * any more work.
265 	 */
266 	if (CPU_IS_PRIMARY(ci) == 0)
267 		return;
268 
269 #ifndef __HAVE_TIMECOUNTER
270 	/*
271 	 * Increment the time-of-day.  The increment is normally just
272 	 * ``tick''.  If the machine is one which has a clock frequency
273 	 * such that ``hz'' would not divide the second evenly into
274 	 * milliseconds, a periodic adjustment must be applied.  Finally,
275 	 * if we are still adjusting the time (see adjtime()),
276 	 * ``tickdelta'' may also be added in.
277 	 */
278 
279 	delta = tick;
280 
281 	if (tickfix) {
282 		tickfixcnt += tickfix;
283 		if (tickfixcnt >= tickfixinterval) {
284 			delta++;
285 			tickfixcnt -= tickfixinterval;
286 		}
287 	}
288 	/* Imprecise 4bsd adjtime() handling */
289 	if (timedelta != 0) {
290 		delta += tickdelta;
291 		timedelta -= tickdelta;
292 	}
293 
294 	/*
295 	 * ntp_tick_permanent accumulates the clock correction each
296 	 * tick. The unit is ns per tick shifted left 32 bits. If we have
297 	 * accumulated more than 1us, we bump delta in the right
298 	 * direction. Use a loop to avoid long long div; typicallly
299 	 * the loops will be executed 0 or 1 iteration.
300 	 */
301 	if (ntp_tick_permanent != 0) {
302 		ntp_tick_acc += ntp_tick_permanent;
303 		while (ntp_tick_acc >= (1000LL << 32)) {
304 			delta++;
305 			ntp_tick_acc -= (1000LL << 32);
306 		}
307 		while (ntp_tick_acc <= -(1000LL << 32)) {
308 			delta--;
309 			ntp_tick_acc += (1000LL << 32);
310 		}
311 	}
312 
313 	BUMPTIME(&time, delta);
314 	BUMPTIME(&mono_time, delta);
315 	time_second = time.tv_sec;
316 	time_uptime = mono_time.tv_sec;
317 #else
318 	tc_ticktock();
319 #endif
320 
321 	/*
322 	 * Update real-time timeout queue.
323 	 * Process callouts at a very low cpu priority, so we don't keep the
324 	 * relatively high clock interrupt priority any longer than necessary.
325 	 */
326 	if (timeout_hardclock_update()) {
327 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
328 		softintr_schedule(softclock_si);
329 #else
330 		setsoftclock();
331 #endif
332 	}
333 }
334 
335 /*
336  * Compute number of hz until specified time.  Used to
337  * compute the second argument to timeout_add() from an absolute time.
338  */
339 int
340 hzto(struct timeval *tv)
341 {
342 	struct timeval now;
343 	unsigned long ticks;
344 	long sec, usec;
345 
346 	/*
347 	 * If the number of usecs in the whole seconds part of the time
348 	 * difference fits in a long, then the total number of usecs will
349 	 * fit in an unsigned long.  Compute the total and convert it to
350 	 * ticks, rounding up and adding 1 to allow for the current tick
351 	 * to expire.  Rounding also depends on unsigned long arithmetic
352 	 * to avoid overflow.
353 	 *
354 	 * Otherwise, if the number of ticks in the whole seconds part of
355 	 * the time difference fits in a long, then convert the parts to
356 	 * ticks separately and add, using similar rounding methods and
357 	 * overflow avoidance.  This method would work in the previous
358 	 * case but it is slightly slower and assumes that hz is integral.
359 	 *
360 	 * Otherwise, round the time difference down to the maximum
361 	 * representable value.
362 	 *
363 	 * If ints have 32 bits, then the maximum value for any timeout in
364 	 * 10ms ticks is 248 days.
365 	 */
366 	getmicrotime(&now);
367 	sec = tv->tv_sec - now.tv_sec;
368 	usec = tv->tv_usec - now.tv_usec;
369 	if (usec < 0) {
370 		sec--;
371 		usec += 1000000;
372 	}
373 	if (sec < 0 || (sec == 0 && usec <= 0)) {
374 		ticks = 0;
375 	} else if (sec <= LONG_MAX / 1000000)
376 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
377 		    / tick + 1;
378 	else if (sec <= LONG_MAX / hz)
379 		ticks = sec * hz
380 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
381 	else
382 		ticks = LONG_MAX;
383 	if (ticks > INT_MAX)
384 		ticks = INT_MAX;
385 	return ((int)ticks);
386 }
387 
388 /*
389  * Compute number of hz in the specified amount of time.
390  */
391 int
392 tvtohz(struct timeval *tv)
393 {
394 	unsigned long ticks;
395 	long sec, usec;
396 
397 	/*
398 	 * If the number of usecs in the whole seconds part of the time
399 	 * fits in a long, then the total number of usecs will
400 	 * fit in an unsigned long.  Compute the total and convert it to
401 	 * ticks, rounding up and adding 1 to allow for the current tick
402 	 * to expire.  Rounding also depends on unsigned long arithmetic
403 	 * to avoid overflow.
404 	 *
405 	 * Otherwise, if the number of ticks in the whole seconds part of
406 	 * the time fits in a long, then convert the parts to
407 	 * ticks separately and add, using similar rounding methods and
408 	 * overflow avoidance.  This method would work in the previous
409 	 * case but it is slightly slower and assumes that hz is integral.
410 	 *
411 	 * Otherwise, round the time down to the maximum
412 	 * representable value.
413 	 *
414 	 * If ints have 32 bits, then the maximum value for any timeout in
415 	 * 10ms ticks is 248 days.
416 	 */
417 	sec = tv->tv_sec;
418 	usec = tv->tv_usec;
419 	if (sec < 0 || (sec == 0 && usec <= 0))
420 		ticks = 0;
421 	else if (sec <= LONG_MAX / 1000000)
422 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
423 		    / tick + 1;
424 	else if (sec <= LONG_MAX / hz)
425 		ticks = sec * hz
426 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
427 	else
428 		ticks = LONG_MAX;
429 	if (ticks > INT_MAX)
430 		ticks = INT_MAX;
431 	return ((int)ticks);
432 }
433 
434 /*
435  * Start profiling on a process.
436  *
437  * Kernel profiling passes proc0 which never exits and hence
438  * keeps the profile clock running constantly.
439  */
440 void
441 startprofclock(struct proc *p)
442 {
443 	int s;
444 
445 	if ((p->p_flag & P_PROFIL) == 0) {
446 		atomic_setbits_int(&p->p_flag, P_PROFIL);
447 		if (++profprocs == 1 && stathz != 0) {
448 			s = splstatclock();
449 			psdiv = pscnt = psratio;
450 			setstatclockrate(profhz);
451 			splx(s);
452 		}
453 	}
454 }
455 
456 /*
457  * Stop profiling on a process.
458  */
459 void
460 stopprofclock(struct proc *p)
461 {
462 	int s;
463 
464 	if (p->p_flag & P_PROFIL) {
465 		atomic_clearbits_int(&p->p_flag, P_PROFIL);
466 		if (--profprocs == 0 && stathz != 0) {
467 			s = splstatclock();
468 			psdiv = pscnt = 1;
469 			setstatclockrate(stathz);
470 			splx(s);
471 		}
472 	}
473 }
474 
475 /*
476  * Statistics clock.  Grab profile sample, and if divider reaches 0,
477  * do process and kernel statistics.
478  */
479 void
480 statclock(struct clockframe *frame)
481 {
482 #ifdef GPROF
483 	struct gmonparam *g;
484 	u_long i;
485 #endif
486 	struct cpu_info *ci = curcpu();
487 	struct schedstate_percpu *spc = &ci->ci_schedstate;
488 	struct proc *p = curproc;
489 
490 	/*
491 	 * Notice changes in divisor frequency, and adjust clock
492 	 * frequency accordingly.
493 	 */
494 	if (spc->spc_psdiv != psdiv) {
495 		spc->spc_psdiv = psdiv;
496 		spc->spc_pscnt = psdiv;
497 		if (psdiv == 1) {
498 			setstatclockrate(stathz);
499 		} else {
500 			setstatclockrate(profhz);
501 		}
502 	}
503 
504 	if (CLKF_USERMODE(frame)) {
505 		if (p->p_flag & P_PROFIL)
506 			addupc_intr(p, CLKF_PC(frame));
507 		if (--spc->spc_pscnt > 0)
508 			return;
509 		/*
510 		 * Came from user mode; CPU was in user state.
511 		 * If this process is being profiled record the tick.
512 		 */
513 		p->p_uticks++;
514 		if (p->p_nice > NZERO)
515 			spc->spc_cp_time[CP_NICE]++;
516 		else
517 			spc->spc_cp_time[CP_USER]++;
518 	} else {
519 #ifdef GPROF
520 		/*
521 		 * Kernel statistics are just like addupc_intr, only easier.
522 		 */
523 		g = &_gmonparam;
524 		if (g->state == GMON_PROF_ON) {
525 			i = CLKF_PC(frame) - g->lowpc;
526 			if (i < g->textsize) {
527 				i /= HISTFRACTION * sizeof(*g->kcount);
528 				g->kcount[i]++;
529 			}
530 		}
531 #endif
532 #if defined(PROC_PC)
533 		if (p != NULL && p->p_flag & P_PROFIL)
534 			addupc_intr(p, PROC_PC(p));
535 #endif
536 		if (--spc->spc_pscnt > 0)
537 			return;
538 		/*
539 		 * Came from kernel mode, so we were:
540 		 * - handling an interrupt,
541 		 * - doing syscall or trap work on behalf of the current
542 		 *   user process, or
543 		 * - spinning in the idle loop.
544 		 * Whichever it is, charge the time as appropriate.
545 		 * Note that we charge interrupts to the current process,
546 		 * regardless of whether they are ``for'' that process,
547 		 * so that we know how much of its real time was spent
548 		 * in ``non-process'' (i.e., interrupt) work.
549 		 */
550 		if (CLKF_INTR(frame)) {
551 			if (p != NULL)
552 				p->p_iticks++;
553 			spc->spc_cp_time[CP_INTR]++;
554 		} else if (p != NULL && p != spc->spc_idleproc) {
555 			p->p_sticks++;
556 			spc->spc_cp_time[CP_SYS]++;
557 		} else
558 			spc->spc_cp_time[CP_IDLE]++;
559 	}
560 	spc->spc_pscnt = psdiv;
561 
562 	if (p != NULL) {
563 		p->p_cpticks++;
564 		/*
565 		 * If no schedclock is provided, call it here at ~~12-25 Hz;
566 		 * ~~16 Hz is best
567 		 */
568 		if (schedhz == 0) {
569 			if ((++curcpu()->ci_schedstate.spc_schedticks & 3) ==
570 			    0)
571 				schedclock(p);
572 		}
573 	}
574 }
575 
576 /*
577  * Return information about system clocks.
578  */
579 int
580 sysctl_clockrate(char *where, size_t *sizep, void *newp)
581 {
582 	struct clockinfo clkinfo;
583 
584 	/*
585 	 * Construct clockinfo structure.
586 	 */
587 	clkinfo.tick = tick;
588 	clkinfo.tickadj = tickadj;
589 	clkinfo.hz = hz;
590 	clkinfo.profhz = profhz;
591 	clkinfo.stathz = stathz ? stathz : hz;
592 	return (sysctl_rdstruct(where, sizep, newp, &clkinfo, sizeof(clkinfo)));
593 }
594 
595 #ifndef __HAVE_TIMECOUNTER
596 /*
597  * Placeholders until everyone uses the timecounters code.
598  * Won't improve anything except maybe removing a bunch of bugs in fixed code.
599  */
600 
601 void
602 getmicrotime(struct timeval *tvp)
603 {
604 	int s;
605 
606 	s = splhigh();
607 	*tvp = time;
608 	splx(s);
609 }
610 
611 void
612 nanotime(struct timespec *tsp)
613 {
614 	struct timeval tv;
615 
616 	microtime(&tv);
617 	TIMEVAL_TO_TIMESPEC(&tv, tsp);
618 }
619 
620 void
621 getnanotime(struct timespec *tsp)
622 {
623 	struct timeval tv;
624 
625 	getmicrotime(&tv);
626 	TIMEVAL_TO_TIMESPEC(&tv, tsp);
627 }
628 
629 void
630 nanouptime(struct timespec *tsp)
631 {
632 	struct timeval tv;
633 
634 	microuptime(&tv);
635 	TIMEVAL_TO_TIMESPEC(&tv, tsp);
636 }
637 
638 
639 void
640 getnanouptime(struct timespec *tsp)
641 {
642 	struct timeval tv;
643 
644 	getmicrouptime(&tv);
645 	TIMEVAL_TO_TIMESPEC(&tv, tsp);
646 }
647 
648 void
649 microuptime(struct timeval *tvp)
650 {
651 	struct timeval tv;
652 
653 	microtime(&tv);
654 	timersub(&tv, &boottime, tvp);
655 }
656 
657 void
658 getmicrouptime(struct timeval *tvp)
659 {
660 	int s;
661 
662 	s = splhigh();
663 	*tvp = mono_time;
664 	splx(s);
665 }
666 #endif /* __HAVE_TIMECOUNTER */
667