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