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