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