1 /**	$MirOS: src/sys/kern/kern_clock.c,v 1.8 2010/09/19 18:55:40 tg Exp $ */
2 /*	$OpenBSD: kern_clock.c,v 1.42 2003/06/02 23:28:05 millert Exp $	*/
3 /*	$NetBSD: kern_clock.c,v 1.34 1996/06/09 04:51:03 briggs Exp $	*/
4 
5 /*-
6  * Copyright (c) 1982, 1986, 1991, 1993
7  *	The Regents of the University of California.  All rights reserved.
8  * (c) UNIX System Laboratories, Inc.
9  * All or some portions of this file are derived from material licensed
10  * to the University of California by American Telephone and Telegraph
11  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
12  * the permission of UNIX System Laboratories, Inc.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)kern_clock.c	8.5 (Berkeley) 1/21/94
39  */
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/dkstat.h>
44 #include <sys/timeout.h>
45 #include <sys/kernel.h>
46 #include <sys/limits.h>
47 #include <sys/proc.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 
54 #include <crypto/randimpl.h>
55 #include <machine/cpu.h>
56 
57 #ifdef CPU_HARDCLOCKENT_DECL
58 CPU_HARDCLOCKENT_DECL;
59 static u_quad_t hce_value;
60 #define HARDCLOCKENT_APPLY(newvalue) do {				\
61 	u_quad_t hce_mask, hce_delta = hce_value;			\
62 	uint32_t hce_entropy = 0;					\
63 									\
64 	hce_value = (newvalue);						\
65 	hce_delta = hce_value - hce_delta;				\
66 	for (hce_mask = 1; hce_mask; hce_mask <<= 1)			\
67 		if (hce_delta & hce_mask) {				\
68 			hce_entropy <<= 1;				\
69 			if (hce_value & hce_mask)			\
70 				hce_entropy++;				\
71 		}							\
72 	rnd_lopool_addvq(hce_entropy);					\
73 } while (/* CONSTCOND */ 0)
74 #endif
75 
76 /*
77  * Clock handling routines.
78  *
79  * This code is written to operate with two timers that run independently of
80  * each other.  The main clock, running hz times per second, is used to keep
81  * track of real time.  The second timer handles kernel and user profiling,
82  * and does resource use estimation.  If the second timer is programmable,
83  * it is randomized to avoid aliasing between the two clocks.  For example,
84  * the randomization prevents an adversary from always giving up the cpu
85  * just before its quantum expires.  Otherwise, it would never accumulate
86  * cpu ticks.  The mean frequency of the second timer is stathz.
87  *
88  * If no second timer exists, stathz will be zero; in this case we drive
89  * profiling and statistics off the main clock.  This WILL NOT be accurate;
90  * do not do it unless absolutely necessary.
91  *
92  * The statistics clock may (or may not) be run at a higher rate while
93  * profiling.  This profile clock runs at profhz.  We require that profhz
94  * be an integral multiple of stathz.
95  *
96  * If the statistics clock is running fast, it must be divided by the ratio
97  * profhz/stathz for statistics.  (For profiling, every tick counts.)
98  */
99 
100 /*
101  * Bump a timeval by a small number of usec's.
102  */
103 #define BUMPTIME(t, usec) { \
104 	register volatile struct timeval *tp = (t); \
105 	register long us; \
106  \
107 	tp->tv_usec = us = tp->tv_usec + (usec); \
108 	if (us >= 1000000) { \
109 		tp->tv_usec = us - 1000000; \
110 		tp->tv_sec++; \
111 	} \
112 }
113 
114 int	stathz;
115 int	schedhz;
116 int	profhz;
117 int	profprocs;
118 int	ticks;
119 static int psdiv, pscnt;		/* prof => stat divider */
120 int	psratio;			/* ratio: prof / stat */
121 int	tickfix, tickfixinterval;	/* used if tick not really integral */
122 static int tickfixcnt;			/* accumulated fractional error */
123 
124 long cp_time[CPUSTATES];
125 
126 volatile struct	timeval time
127 	__attribute__((__aligned__(__alignof__(quad_t))));
128 volatile struct	timeval mono_time;
129 
130 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
131 void	*softclock_si;
132 void	generic_softclock(void *);
133 
134 void
generic_softclock(void * ignore)135 generic_softclock(void *ignore)
136 {
137 	/*
138 	 * XXX - dont' commit, just a dummy wrapper until we learn everyone
139 	 *       deal with a changed proto for softclock().
140 	 */
141 	softclock();
142 }
143 #endif
144 
145 /*
146  * Initialize clock frequencies and start both clocks running.
147  */
148 void
initclocks()149 initclocks()
150 {
151 	int i;
152 
153 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
154 	softclock_si = softintr_establish(IPL_SOFTCLOCK, generic_softclock, NULL);
155 	if (softclock_si == NULL)
156 		panic("initclocks: unable to register softclock intr");
157 #endif
158 
159 	/*
160 	 * Set divisors to 1 (normal case) and let the machine-specific
161 	 * code do its bit.
162 	 */
163 	psdiv = pscnt = 1;
164 	cpu_initclocks();
165 
166 	/*
167 	 * Compute profhz/stathz, and fix profhz if needed.
168 	 */
169 	i = stathz ? stathz : hz;
170 	if (profhz == 0)
171 		profhz = i;
172 	psratio = profhz / i;
173 }
174 
175 /*
176  * The real-time timer, interrupting hz times per second.
177  */
178 void
hardclock(frame)179 hardclock(frame)
180 	register struct clockframe *frame;
181 {
182 	register struct proc *p;
183 	register int delta;
184 	extern int tickdelta;
185 	extern long timedelta;
186 
187 #ifdef CPU_HARDCLOCKENT
188 	CPU_HARDCLOCKENT();
189 #endif
190 
191 	p = curproc;
192 	if (p) {
193 		register struct pstats *pstats;
194 
195 		/*
196 		 * Run current process's virtual and profile time, as needed.
197 		 */
198 		pstats = p->p_stats;
199 		if (CLKF_USERMODE(frame) &&
200 		    timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
201 		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
202 			psignal(p, SIGVTALRM);
203 		if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
204 		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
205 			psignal(p, SIGPROF);
206 	}
207 
208 	/*
209 	 * If no separate statistics clock is available, run it from here.
210 	 */
211 	if (stathz == 0)
212 		statclock(frame);
213 
214 	/*
215 	 * Increment the time-of-day.  The increment is normally just
216 	 * ``tick''.  If the machine is one which has a clock frequency
217 	 * such that ``hz'' would not divide the second evenly into
218 	 * milliseconds, a periodic adjustment must be applied.  Finally,
219 	 * if we are still adjusting the time (see adjtime()),
220 	 * ``tickdelta'' may also be added in.
221 	 */
222 	ticks++;
223 	delta = tick;
224 
225 	if (tickfix) {
226 		tickfixcnt += tickfix;
227 		if (tickfixcnt >= tickfixinterval) {
228 			delta++;
229 			tickfixcnt -= tickfixinterval;
230 		}
231 	}
232 	/* Imprecise 4bsd adjtime() handling */
233 	if (timedelta != 0) {
234 		delta += tickdelta;
235 		timedelta -= tickdelta;
236 	}
237 
238 #ifdef notyet
239 	microset();
240 #endif
241 
242 	BUMPTIME(&time, delta);
243 	BUMPTIME(&mono_time, delta);
244 
245 #ifdef CPU_CLOCKUPDATE
246 	CPU_CLOCKUPDATE();
247 #endif
248 
249 	/*
250 	 * Update real-time timeout queue.
251 	 * Process callouts at a very low cpu priority, so we don't keep the
252 	 * relatively high clock interrupt priority any longer than necessary.
253 	 */
254 	if (timeout_hardclock_update()) {
255 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
256 		softintr_schedule(softclock_si);
257 #else
258 		setsoftclock();
259 #endif
260 	}
261 }
262 
263 /*
264  * Compute number of hz until specified time.  Used to
265  * compute the second argument to timeout_add() from an absolute time.
266  */
267 int
hzto(struct timeval * tv)268 hzto(struct timeval *tv)
269 {
270 	unsigned long ticks;
271 	time_t sec;
272 	long usec;
273 	int s;
274 
275 	/*
276 	 * If the number of usecs in the whole seconds part of the time
277 	 * difference fits in a long, then the total number of usecs will
278 	 * fit in an unsigned long.  Compute the total and convert it to
279 	 * ticks, rounding up and adding 1 to allow for the current tick
280 	 * to expire.  Rounding also depends on unsigned long arithmetic
281 	 * to avoid overflow.
282 	 *
283 	 * Otherwise, if the number of ticks in the whole seconds part of
284 	 * the time difference fits in a long, then convert the parts to
285 	 * ticks separately and add, using similar rounding methods and
286 	 * overflow avoidance.  This method would work in the previous
287 	 * case but it is slightly slower and assumes that hz is integral.
288 	 *
289 	 * Otherwise, round the time difference down to the maximum
290 	 * representable value.
291 	 *
292 	 * If ints have 32 bits, then the maximum value for any timeout in
293 	 * 10ms ticks is 248 days.
294 	 */
295 	s = splhigh();
296 	sec = tv->tv_sec - time.tv_sec;
297 	usec = tv->tv_usec - time.tv_usec;
298 	splx(s);
299 	if (usec < 0) {
300 		sec--;
301 		usec += 1000000;
302 	}
303 	if (sec < 0 || (sec == 0 && usec <= 0)) {
304 		ticks = 0;
305 	} else if (sec <= LONG_MAX / 1000000)
306 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
307 		    / tick + 1;
308 	else if (sec <= LONG_MAX / hz)
309 		ticks = sec * hz
310 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
311 	else
312 		ticks = LONG_MAX;
313 	if (ticks > INT_MAX)
314 		ticks = INT_MAX;
315 	return ((int)ticks);
316 }
317 
318 /*
319  * Compute number of hz in the specified amount of time.
320  */
321 int
tvtohz(struct timeval * tv)322 tvtohz(struct timeval *tv)
323 {
324 	unsigned long ticks;
325 	long sec, usec;
326 
327 	/*
328 	 * If the number of usecs in the whole seconds part of the time
329 	 * fits in a long, then the total number of usecs will
330 	 * fit in an unsigned long.  Compute the total and convert it to
331 	 * ticks, rounding up and adding 1 to allow for the current tick
332 	 * to expire.  Rounding also depends on unsigned long arithmetic
333 	 * to avoid overflow.
334 	 *
335 	 * Otherwise, if the number of ticks in the whole seconds part of
336 	 * the time fits in a long, then convert the parts to
337 	 * ticks separately and add, using similar rounding methods and
338 	 * overflow avoidance.  This method would work in the previous
339 	 * case but it is slightly slower and assumes that hz is integral.
340 	 *
341 	 * Otherwise, round the time down to the maximum
342 	 * representable value.
343 	 *
344 	 * If ints have 32 bits, then the maximum value for any timeout in
345 	 * 10ms ticks is 248 days.
346 	 */
347 	sec = tv->tv_sec;
348 	usec = tv->tv_usec;
349 	if (sec < 0 || (sec == 0 && usec <= 0))
350 		ticks = 0;
351 	else if (sec <= LONG_MAX / 1000000)
352 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
353 		    / tick + 1;
354 	else if (sec <= LONG_MAX / hz)
355 		ticks = sec * hz
356 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
357 	else
358 		ticks = LONG_MAX;
359 	if (ticks > INT_MAX)
360 		ticks = INT_MAX;
361 	return ((int)ticks);
362 }
363 
364 /*
365  * Start profiling on a process.
366  *
367  * Kernel profiling passes proc0 which never exits and hence
368  * keeps the profile clock running constantly.
369  */
370 void
startprofclock(p)371 startprofclock(p)
372 	register struct proc *p;
373 {
374 	int s;
375 
376 	if ((p->p_flag & P_PROFIL) == 0) {
377 		p->p_flag |= P_PROFIL;
378 		if (++profprocs == 1 && stathz != 0) {
379 			s = splstatclock();
380 			psdiv = pscnt = psratio;
381 			setstatclockrate(profhz);
382 			splx(s);
383 		}
384 	}
385 }
386 
387 /*
388  * Stop profiling on a process.
389  */
390 void
stopprofclock(p)391 stopprofclock(p)
392 	register struct proc *p;
393 {
394 	int s;
395 
396 	if (p->p_flag & P_PROFIL) {
397 		p->p_flag &= ~P_PROFIL;
398 		if (--profprocs == 0 && stathz != 0) {
399 			s = splstatclock();
400 			psdiv = pscnt = 1;
401 			setstatclockrate(stathz);
402 			splx(s);
403 		}
404 	}
405 }
406 
407 /*
408  * Statistics clock.  Grab profile sample, and if divider reaches 0,
409  * do process and kernel statistics.
410  */
411 void
statclock(frame)412 statclock(frame)
413 	register struct clockframe *frame;
414 {
415 	static int schedclk;
416 	register struct proc *p;
417 
418 	if (CLKF_USERMODE(frame)) {
419 		p = curproc;
420 		if (p->p_flag & P_PROFIL)
421 			addupc_intr(p, CLKF_PC(frame));
422 		if (--pscnt > 0)
423 			return;
424 		/*
425 		 * Came from user mode; CPU was in user state.
426 		 * If this process is being profiled record the tick.
427 		 */
428 		p->p_uticks++;
429 		if (p->p_nice > NZERO)
430 			cp_time[CP_NICE]++;
431 		else
432 			cp_time[CP_USER]++;
433 	} else {
434 		if (--pscnt > 0)
435 			return;
436 		/*
437 		 * Came from kernel mode, so we were:
438 		 * - handling an interrupt,
439 		 * - doing syscall or trap work on behalf of the current
440 		 *   user process, or
441 		 * - spinning in the idle loop.
442 		 * Whichever it is, charge the time as appropriate.
443 		 * Note that we charge interrupts to the current process,
444 		 * regardless of whether they are ``for'' that process,
445 		 * so that we know how much of its real time was spent
446 		 * in ``non-process'' (i.e., interrupt) work.
447 		 */
448 		p = curproc;
449 		if (CLKF_INTR(frame)) {
450 			if (p != NULL)
451 				p->p_iticks++;
452 			cp_time[CP_INTR]++;
453 		} else if (p != NULL) {
454 			p->p_sticks++;
455 			cp_time[CP_SYS]++;
456 		} else
457 			cp_time[CP_IDLE]++;
458 	}
459 	pscnt = psdiv;
460 
461 	if (p != NULL) {
462 		p->p_cpticks++;
463 		/*
464 		 * If no schedclock is provided, call it here at ~~12-25 Hz;
465 		 * ~~16 Hz is best
466 		 */
467 		if (schedhz == 0)
468 			if ((++schedclk & 3) == 0)
469 				schedclock(p);
470 	}
471 }
472 
473 /*
474  * Return information about system clocks.
475  */
476 int
sysctl_clockrate(where,sizep)477 sysctl_clockrate(where, sizep)
478 	register char *where;
479 	size_t *sizep;
480 {
481 	struct clockinfo clkinfo;
482 
483 	/*
484 	 * Construct clockinfo structure.
485 	 */
486 	clkinfo.tick = tick;
487 	clkinfo.tickadj = tickadj;
488 	clkinfo.hz = hz;
489 	clkinfo.profhz = profhz;
490 	clkinfo.stathz = stathz ? stathz : hz;
491 	return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
492 }
493