xref: /openbsd-src/sys/kern/kern_clock.c (revision 91a535ff42f6347677741774730dc5ddcf7d5b93)
1 /*	$OpenBSD: kern_clock.c,v 1.82 2013/08/13 05:52:23 guenther 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 #include <sys/timetc.h>
54 
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  * Bump a timeval by a small number of usec's.
86  */
87 #define BUMPTIME(t, usec) { \
88 	volatile struct timeval *tp = (t); \
89 	long us; \
90  \
91 	tp->tv_usec = us = tp->tv_usec + (usec); \
92 	if (us >= 1000000) { \
93 		tp->tv_usec = us - 1000000; \
94 		tp->tv_sec++; \
95 	} \
96 }
97 
98 int	stathz;
99 int	schedhz;
100 int	profhz;
101 int	profprocs;
102 int	ticks;
103 static int psdiv, pscnt;		/* prof => stat divider */
104 int	psratio;			/* ratio: prof / stat */
105 
106 long cp_time[CPUSTATES];
107 
108 void	*softclock_si;
109 
110 /*
111  * Initialize clock frequencies and start both clocks running.
112  */
113 void
114 initclocks(void)
115 {
116 	int i;
117 
118 	softclock_si = softintr_establish(IPL_SOFTCLOCK, softclock, NULL);
119 	if (softclock_si == NULL)
120 		panic("initclocks: unable to register softclock intr");
121 
122 	/*
123 	 * Set divisors to 1 (normal case) and let the machine-specific
124 	 * code do its bit.
125 	 */
126 	psdiv = pscnt = 1;
127 	cpu_initclocks();
128 
129 	/*
130 	 * Compute profhz/stathz, and fix profhz if needed.
131 	 */
132 	i = stathz ? stathz : hz;
133 	if (profhz == 0)
134 		profhz = i;
135 	psratio = profhz / i;
136 
137 	/* For very large HZ, ensure that division by 0 does not occur later */
138 	if (tickadj == 0)
139 		tickadj = 1;
140 
141 	inittimecounter();
142 }
143 
144 /*
145  * hardclock does the accounting needed for ITIMER_PROF and ITIMER_VIRTUAL.
146  * We don't want to send signals with psignal from hardclock because it makes
147  * MULTIPROCESSOR locking very complicated. Instead we use a small trick
148  * to send the signals safely and without blocking too many interrupts
149  * while doing that (signal handling can be heavy).
150  *
151  * hardclock detects that the itimer has expired, and schedules a timeout
152  * to deliver the signal. This works because of the following reasons:
153  *  - The timeout can be scheduled with a 1 tick time because we're
154  *    doing it before the timeout processing in hardclock. So it will
155  *    be scheduled to run as soon as possible.
156  *  - The timeout will be run in softclock which will run before we
157  *    return to userland and process pending signals.
158  *  - If the system is so busy that several VIRTUAL/PROF ticks are
159  *    sent before softclock processing, we'll send only one signal.
160  *    But if we'd send the signal from hardclock only one signal would
161  *    be delivered to the user process. So userland will only see one
162  *    signal anyway.
163  */
164 
165 void
166 virttimer_trampoline(void *v)
167 {
168 	struct process *pr = v;
169 
170 	psignal(pr->ps_mainproc, SIGVTALRM);
171 }
172 
173 void
174 proftimer_trampoline(void *v)
175 {
176 	struct process *pr = v;
177 
178 	psignal(pr->ps_mainproc, SIGPROF);
179 }
180 
181 /*
182  * The real-time timer, interrupting hz times per second.
183  */
184 void
185 hardclock(struct clockframe *frame)
186 {
187 	struct proc *p;
188 	struct cpu_info *ci = curcpu();
189 
190 	p = curproc;
191 	if (p && ((p->p_flag & (P_SYSTEM | P_WEXIT)) == 0)) {
192 		struct process *pr = p->p_p;
193 
194 		/*
195 		 * Run current process's virtual and profile time, as needed.
196 		 */
197 		if (CLKF_USERMODE(frame) &&
198 		    timerisset(&pr->ps_timer[ITIMER_VIRTUAL].it_value) &&
199 		    itimerdecr(&pr->ps_timer[ITIMER_VIRTUAL], tick) == 0)
200 			timeout_add(&pr->ps_virt_to, 1);
201 		if (timerisset(&pr->ps_timer[ITIMER_PROF].it_value) &&
202 		    itimerdecr(&pr->ps_timer[ITIMER_PROF], tick) == 0)
203 			timeout_add(&pr->ps_prof_to, 1);
204 	}
205 
206 	/*
207 	 * If no separate statistics clock is available, run it from here.
208 	 */
209 	if (stathz == 0)
210 		statclock(frame);
211 
212 	if (--ci->ci_schedstate.spc_rrticks <= 0)
213 		roundrobin(ci);
214 
215 	/*
216 	 * If we are not the primary CPU, we're not allowed to do
217 	 * any more work.
218 	 */
219 	if (CPU_IS_PRIMARY(ci) == 0)
220 		return;
221 
222 	tc_ticktock();
223 
224 	/*
225 	 * Update real-time timeout queue.
226 	 * Process callouts at a very low cpu priority, so we don't keep the
227 	 * relatively high clock interrupt priority any longer than necessary.
228 	 */
229 	if (timeout_hardclock_update())
230 		softintr_schedule(softclock_si);
231 }
232 
233 /*
234  * Compute number of hz until specified time.  Used to
235  * compute the second argument to timeout_add() from an absolute time.
236  */
237 int
238 hzto(const struct timeval *tv)
239 {
240 	struct timeval now;
241 	unsigned long ticks;
242 	long sec, usec;
243 
244 	/*
245 	 * If the number of usecs in the whole seconds part of the time
246 	 * difference fits in a long, then the total number of usecs will
247 	 * fit in an unsigned long.  Compute the total and convert it to
248 	 * ticks, rounding up and adding 1 to allow for the current tick
249 	 * to expire.  Rounding also depends on unsigned long arithmetic
250 	 * to avoid overflow.
251 	 *
252 	 * Otherwise, if the number of ticks in the whole seconds part of
253 	 * the time difference fits in a long, then convert the parts to
254 	 * ticks separately and add, using similar rounding methods and
255 	 * overflow avoidance.  This method would work in the previous
256 	 * case but it is slightly slower and assumes that hz is integral.
257 	 *
258 	 * Otherwise, round the time difference down to the maximum
259 	 * representable value.
260 	 *
261 	 * If ints have 32 bits, then the maximum value for any timeout in
262 	 * 10ms ticks is 248 days.
263 	 */
264 	getmicrotime(&now);
265 	sec = tv->tv_sec - now.tv_sec;
266 	usec = tv->tv_usec - now.tv_usec;
267 	if (usec < 0) {
268 		sec--;
269 		usec += 1000000;
270 	}
271 	if (sec < 0 || (sec == 0 && usec <= 0)) {
272 		ticks = 0;
273 	} else if (sec <= LONG_MAX / 1000000)
274 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
275 		    / tick + 1;
276 	else if (sec <= LONG_MAX / hz)
277 		ticks = sec * hz
278 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
279 	else
280 		ticks = LONG_MAX;
281 	if (ticks > INT_MAX)
282 		ticks = INT_MAX;
283 	return ((int)ticks);
284 }
285 
286 /*
287  * Compute number of hz in the specified amount of time.
288  */
289 int
290 tvtohz(const struct timeval *tv)
291 {
292 	unsigned long ticks;
293 	time_t sec;
294 	long usec;
295 
296 	/*
297 	 * If the number of usecs in the whole seconds part of the time
298 	 * fits in a long, then the total number of usecs will
299 	 * fit in an unsigned long.  Compute the total and convert it to
300 	 * ticks, rounding up and adding 1 to allow for the current tick
301 	 * to expire.  Rounding also depends on unsigned long arithmetic
302 	 * to avoid overflow.
303 	 *
304 	 * Otherwise, if the number of ticks in the whole seconds part of
305 	 * the time fits in a long, then convert the parts to
306 	 * ticks separately and add, using similar rounding methods and
307 	 * overflow avoidance.  This method would work in the previous
308 	 * case but it is slightly slower and assumes that hz is integral.
309 	 *
310 	 * Otherwise, round the time down to the maximum
311 	 * representable value.
312 	 *
313 	 * If ints have 32 bits, then the maximum value for any timeout in
314 	 * 10ms ticks is 248 days.
315 	 */
316 	sec = tv->tv_sec;
317 	usec = tv->tv_usec;
318 	if (sec < 0 || (sec == 0 && usec <= 0))
319 		ticks = 0;
320 	else if (sec <= LONG_MAX / 1000000)
321 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
322 		    / tick + 1;
323 	else if (sec <= LONG_MAX / hz)
324 		ticks = sec * hz
325 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
326 	else
327 		ticks = LONG_MAX;
328 	if (ticks > INT_MAX)
329 		ticks = INT_MAX;
330 	return ((int)ticks);
331 }
332 
333 int
334 tstohz(const struct timespec *ts)
335 {
336 	struct timeval tv;
337 	TIMESPEC_TO_TIMEVAL(&tv, ts);
338 
339 	/* Round up. */
340 	if ((ts->tv_nsec % 1000) != 0) {
341 		tv.tv_usec += 1;
342 		if (tv.tv_usec >= 1000000) {
343 			tv.tv_usec -= 1000000;
344 			tv.tv_sec += 1;
345 		}
346 	}
347 
348 	return (tvtohz(&tv));
349 }
350 
351 /*
352  * Start profiling on a process.
353  *
354  * Kernel profiling passes proc0 which never exits and hence
355  * keeps the profile clock running constantly.
356  */
357 void
358 startprofclock(struct process *pr)
359 {
360 	int s;
361 
362 	if ((pr->ps_flags & PS_PROFIL) == 0) {
363 		atomic_setbits_int(&pr->ps_flags, PS_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(struct process *pr)
378 {
379 	int s;
380 
381 	if (pr->ps_flags & PS_PROFIL) {
382 		atomic_clearbits_int(&pr->ps_flags, PS_PROFIL);
383 		if (--profprocs == 0 && stathz != 0) {
384 			s = splstatclock();
385 			psdiv = pscnt = 1;
386 			setstatclockrate(stathz);
387 			splx(s);
388 		}
389 	}
390 }
391 
392 /*
393  * Statistics clock.  Grab profile sample, and if divider reaches 0,
394  * do process and kernel statistics.
395  */
396 void
397 statclock(struct clockframe *frame)
398 {
399 #ifdef GPROF
400 	struct gmonparam *g;
401 	u_long i;
402 #endif
403 	struct cpu_info *ci = curcpu();
404 	struct schedstate_percpu *spc = &ci->ci_schedstate;
405 	struct proc *p = curproc;
406 	struct process *pr;
407 
408 	/*
409 	 * Notice changes in divisor frequency, and adjust clock
410 	 * frequency accordingly.
411 	 */
412 	if (spc->spc_psdiv != psdiv) {
413 		spc->spc_psdiv = psdiv;
414 		spc->spc_pscnt = psdiv;
415 		if (psdiv == 1) {
416 			setstatclockrate(stathz);
417 		} else {
418 			setstatclockrate(profhz);
419 		}
420 	}
421 
422 	if (CLKF_USERMODE(frame)) {
423 		pr = p->p_p;
424 		if (pr->ps_flags & PS_PROFIL)
425 			addupc_intr(p, CLKF_PC(frame));
426 		if (--spc->spc_pscnt > 0)
427 			return;
428 		/*
429 		 * Came from user mode; CPU was in user state.
430 		 * If this process is being profiled record the tick.
431 		 */
432 		p->p_uticks++;
433 		if (pr->ps_nice > NZERO)
434 			spc->spc_cp_time[CP_NICE]++;
435 		else
436 			spc->spc_cp_time[CP_USER]++;
437 	} else {
438 #ifdef GPROF
439 		/*
440 		 * Kernel statistics are just like addupc_intr, only easier.
441 		 */
442 		g = ci->ci_gmon;
443 		if (g != NULL && g->state == GMON_PROF_ON) {
444 			i = CLKF_PC(frame) - g->lowpc;
445 			if (i < g->textsize) {
446 				i /= HISTFRACTION * sizeof(*g->kcount);
447 				g->kcount[i]++;
448 			}
449 		}
450 #endif
451 #if defined(PROC_PC)
452 		if (p != NULL && p->p_p->ps_flags & PS_PROFIL)
453 			addupc_intr(p, PROC_PC(p));
454 #endif
455 		if (--spc->spc_pscnt > 0)
456 			return;
457 		/*
458 		 * Came from kernel mode, so we were:
459 		 * - handling an interrupt,
460 		 * - doing syscall or trap work on behalf of the current
461 		 *   user process, or
462 		 * - spinning in the idle loop.
463 		 * Whichever it is, charge the time as appropriate.
464 		 * Note that we charge interrupts to the current process,
465 		 * regardless of whether they are ``for'' that process,
466 		 * so that we know how much of its real time was spent
467 		 * in ``non-process'' (i.e., interrupt) work.
468 		 */
469 		if (CLKF_INTR(frame)) {
470 			if (p != NULL)
471 				p->p_iticks++;
472 			spc->spc_cp_time[CP_INTR]++;
473 		} else if (p != NULL && p != spc->spc_idleproc) {
474 			p->p_sticks++;
475 			spc->spc_cp_time[CP_SYS]++;
476 		} else
477 			spc->spc_cp_time[CP_IDLE]++;
478 	}
479 	spc->spc_pscnt = psdiv;
480 
481 	if (p != NULL) {
482 		p->p_cpticks++;
483 		/*
484 		 * If no schedclock is provided, call it here at ~~12-25 Hz;
485 		 * ~~16 Hz is best
486 		 */
487 		if (schedhz == 0) {
488 			if ((++curcpu()->ci_schedstate.spc_schedticks & 3) ==
489 			    0)
490 				schedclock(p);
491 		}
492 	}
493 }
494 
495 /*
496  * Return information about system clocks.
497  */
498 int
499 sysctl_clockrate(char *where, size_t *sizep, void *newp)
500 {
501 	struct clockinfo clkinfo;
502 
503 	/*
504 	 * Construct clockinfo structure.
505 	 */
506 	clkinfo.tick = tick;
507 	clkinfo.tickadj = tickadj;
508 	clkinfo.hz = hz;
509 	clkinfo.profhz = profhz;
510 	clkinfo.stathz = stathz ? stathz : hz;
511 	return (sysctl_rdstruct(where, sizep, newp, &clkinfo, sizeof(clkinfo)));
512 }
513