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