xref: /freebsd/sys/kern/kern_clock.c (revision 77a0943ded95b9e6438f7db70c4a28e4d93946d4)
1 /*-
2  * Copyright (c) 1982, 1986, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. 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  * $FreeBSD$
40  */
41 
42 #include "opt_ntp.h"
43 
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/dkstat.h>
47 #include <sys/callout.h>
48 #include <sys/ipl.h>
49 #include <sys/kernel.h>
50 #include <sys/mutex.h>
51 #include <sys/proc.h>
52 #include <sys/resourcevar.h>
53 #include <sys/signalvar.h>
54 #include <sys/timetc.h>
55 #include <sys/timepps.h>
56 #include <vm/vm.h>
57 #include <sys/lock.h>
58 #include <vm/pmap.h>
59 #include <vm/vm_map.h>
60 #include <sys/sysctl.h>
61 #include <sys/bus.h>
62 #include <sys/interrupt.h>
63 
64 #include <machine/cpu.h>
65 #include <machine/limits.h>
66 #include <machine/smp.h>
67 
68 #ifdef GPROF
69 #include <sys/gmon.h>
70 #endif
71 
72 
73 static void initclocks __P((void *dummy));
74 SYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL)
75 
76 /* Some of these don't belong here, but it's easiest to concentrate them. */
77 long cp_time[CPUSTATES];
78 
79 SYSCTL_OPAQUE(_kern, OID_AUTO, cp_time, CTLFLAG_RD, &cp_time, sizeof(cp_time),
80     "LU", "CPU time statistics");
81 
82 long tk_cancc;
83 long tk_nin;
84 long tk_nout;
85 long tk_rawcc;
86 
87 /*
88  * Clock handling routines.
89  *
90  * This code is written to operate with two timers that run independently of
91  * each other.
92  *
93  * The main timer, running hz times per second, is used to trigger interval
94  * timers, timeouts and rescheduling as needed.
95  *
96  * The second timer handles kernel and user profiling,
97  * and does resource use estimation.  If the second timer is programmable,
98  * it is randomized to avoid aliasing between the two clocks.  For example,
99  * the randomization prevents an adversary from always giving up the cpu
100  * just before its quantum expires.  Otherwise, it would never accumulate
101  * cpu ticks.  The mean frequency of the second timer is stathz.
102  *
103  * If no second timer exists, stathz will be zero; in this case we drive
104  * profiling and statistics off the main clock.  This WILL NOT be accurate;
105  * do not do it unless absolutely necessary.
106  *
107  * The statistics clock may (or may not) be run at a higher rate while
108  * profiling.  This profile clock runs at profhz.  We require that profhz
109  * be an integral multiple of stathz.
110  *
111  * If the statistics clock is running fast, it must be divided by the ratio
112  * profhz/stathz for statistics.  (For profiling, every tick counts.)
113  *
114  * Time-of-day is maintained using a "timecounter", which may or may
115  * not be related to the hardware generating the above mentioned
116  * interrupts.
117  */
118 
119 int	stathz;
120 int	profhz;
121 static int profprocs;
122 int	ticks;
123 static int psdiv, pscnt;		/* prof => stat divider */
124 int	psratio;			/* ratio: prof / stat */
125 
126 /*
127  * Initialize clock frequencies and start both clocks running.
128  */
129 /* ARGSUSED*/
130 static void
131 initclocks(dummy)
132 	void *dummy;
133 {
134 	register int i;
135 
136 	/*
137 	 * Set divisors to 1 (normal case) and let the machine-specific
138 	 * code do its bit.
139 	 */
140 	psdiv = pscnt = 1;
141 	cpu_initclocks();
142 
143 	/*
144 	 * Compute profhz/stathz, and fix profhz if needed.
145 	 */
146 	i = stathz ? stathz : hz;
147 	if (profhz == 0)
148 		profhz = i;
149 	psratio = profhz / i;
150 }
151 
152 /*
153  * The real-time timer, interrupting hz times per second.
154  */
155 void
156 hardclock(frame)
157 	register struct clockframe *frame;
158 {
159 	register struct proc *p;
160 	int need_softclock = 0;
161 
162 	p = curproc;
163 	if (p != idleproc) {
164 		register struct pstats *pstats;
165 
166 		/*
167 		 * Run current process's virtual and profile time, as needed.
168 		 */
169 		pstats = p->p_stats;
170 		if (CLKF_USERMODE(frame) &&
171 		    timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
172 		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0) {
173 			p->p_flag |= P_ALRMPEND;
174 			aston();
175 		}
176 		if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
177 		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0) {
178 			p->p_flag |= P_PROFPEND;
179 			aston();
180 		}
181 	}
182 
183 #if defined(SMP) && defined(BETTER_CLOCK)
184 	forward_hardclock(pscnt);
185 #endif
186 
187 	/*
188 	 * If no separate statistics clock is available, run it from here.
189 	 */
190 	if (stathz == 0)
191 		statclock(frame);
192 
193 	tc_windup();
194 
195 	/*
196 	 * Process callouts at a very low cpu priority, so we don't keep the
197 	 * relatively high clock interrupt priority any longer than necessary.
198 	 */
199 	mtx_enter(&callout_lock, MTX_SPIN);
200 	ticks++;
201 	if (TAILQ_FIRST(&callwheel[ticks & callwheelmask]) != NULL) {
202 		need_softclock = 1;
203 	} else if (softticks + 1 == ticks)
204 		++softticks;
205 	mtx_exit(&callout_lock, MTX_SPIN);
206 
207 	/*
208 	 * sched_swi acquires sched_lock, so we don't want to call it with
209 	 * callout_lock held; incorrect locking order.
210 	 */
211 	if (need_softclock)
212 		sched_swi(softclock_ih, SWI_NOSWITCH);
213 }
214 
215 /*
216  * Compute number of ticks in the specified amount of time.
217  */
218 int
219 tvtohz(tv)
220 	struct timeval *tv;
221 {
222 	register unsigned long ticks;
223 	register long sec, usec;
224 
225 	/*
226 	 * If the number of usecs in the whole seconds part of the time
227 	 * difference fits in a long, then the total number of usecs will
228 	 * fit in an unsigned long.  Compute the total and convert it to
229 	 * ticks, rounding up and adding 1 to allow for the current tick
230 	 * to expire.  Rounding also depends on unsigned long arithmetic
231 	 * to avoid overflow.
232 	 *
233 	 * Otherwise, if the number of ticks in the whole seconds part of
234 	 * the time difference fits in a long, then convert the parts to
235 	 * ticks separately and add, using similar rounding methods and
236 	 * overflow avoidance.  This method would work in the previous
237 	 * case but it is slightly slower and assumes that hz is integral.
238 	 *
239 	 * Otherwise, round the time difference down to the maximum
240 	 * representable value.
241 	 *
242 	 * If ints have 32 bits, then the maximum value for any timeout in
243 	 * 10ms ticks is 248 days.
244 	 */
245 	sec = tv->tv_sec;
246 	usec = tv->tv_usec;
247 	if (usec < 0) {
248 		sec--;
249 		usec += 1000000;
250 	}
251 	if (sec < 0) {
252 #ifdef DIAGNOSTIC
253 		if (usec > 0) {
254 			sec++;
255 			usec -= 1000000;
256 		}
257 		printf("tvotohz: negative time difference %ld sec %ld usec\n",
258 		       sec, usec);
259 #endif
260 		ticks = 1;
261 	} else if (sec <= LONG_MAX / 1000000)
262 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
263 			/ tick + 1;
264 	else if (sec <= LONG_MAX / hz)
265 		ticks = sec * hz
266 			+ ((unsigned long)usec + (tick - 1)) / tick + 1;
267 	else
268 		ticks = LONG_MAX;
269 	if (ticks > INT_MAX)
270 		ticks = INT_MAX;
271 	return ((int)ticks);
272 }
273 
274 /*
275  * Start profiling on a process.
276  *
277  * Kernel profiling passes proc0 which never exits and hence
278  * keeps the profile clock running constantly.
279  */
280 void
281 startprofclock(p)
282 	register struct proc *p;
283 {
284 	int s;
285 
286 	if ((p->p_flag & P_PROFIL) == 0) {
287 		p->p_flag |= P_PROFIL;
288 		if (++profprocs == 1 && stathz != 0) {
289 			s = splstatclock();
290 			psdiv = pscnt = psratio;
291 			setstatclockrate(profhz);
292 			splx(s);
293 		}
294 	}
295 }
296 
297 /*
298  * Stop profiling on a process.
299  */
300 void
301 stopprofclock(p)
302 	register struct proc *p;
303 {
304 	int s;
305 
306 	if (p->p_flag & P_PROFIL) {
307 		p->p_flag &= ~P_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.  Most of the statistics are only
320  * used by user-level statistics programs.  The main exceptions are
321  * p->p_uticks, p->p_sticks, p->p_iticks, and p->p_estcpu.
322  */
323 void
324 statclock(frame)
325 	register struct clockframe *frame;
326 {
327 #ifdef GPROF
328 	register struct gmonparam *g;
329 	int i;
330 #endif
331 	register struct proc *p;
332 	struct pstats *pstats;
333 	long rss;
334 	struct rusage *ru;
335 	struct vmspace *vm;
336 
337 	mtx_enter(&sched_lock, MTX_SPIN);
338 
339 	if (CLKF_USERMODE(frame)) {
340 		/*
341 		 * Came from user mode; CPU was in user state.
342 		 * If this process is being profiled, record the tick.
343 		 */
344 		p = curproc;
345 		if (p->p_flag & P_PROFIL)
346 			addupc_intr(p, CLKF_PC(frame), 1);
347 #if defined(SMP) && defined(BETTER_CLOCK)
348 		if (stathz != 0)
349 			forward_statclock(pscnt);
350 #endif
351 		if (--pscnt > 0) {
352 			mtx_exit(&sched_lock, MTX_SPIN);
353 			return;
354 		}
355 		/*
356 		 * Charge the time as appropriate.
357 		 */
358 		p->p_uticks++;
359 		if (p->p_nice > NZERO)
360 			cp_time[CP_NICE]++;
361 		else
362 			cp_time[CP_USER]++;
363 	} else {
364 #ifdef GPROF
365 		/*
366 		 * Kernel statistics are just like addupc_intr, only easier.
367 		 */
368 		g = &_gmonparam;
369 		if (g->state == GMON_PROF_ON) {
370 			i = CLKF_PC(frame) - g->lowpc;
371 			if (i < g->textsize) {
372 				i /= HISTFRACTION * sizeof(*g->kcount);
373 				g->kcount[i]++;
374 			}
375 		}
376 #endif
377 #if defined(SMP) && defined(BETTER_CLOCK)
378 		if (stathz != 0)
379 			forward_statclock(pscnt);
380 #endif
381 		if (--pscnt > 0) {
382 			mtx_exit(&sched_lock, MTX_SPIN);
383 			return;
384 		}
385 		/*
386 		 * Came from kernel mode, so we were:
387 		 * - handling an interrupt,
388 		 * - doing syscall or trap work on behalf of the current
389 		 *   user process, or
390 		 * - spinning in the idle loop.
391 		 * Whichever it is, charge the time as appropriate.
392 		 * Note that we charge interrupts to the current process,
393 		 * regardless of whether they are ``for'' that process,
394 		 * so that we know how much of its real time was spent
395 		 * in ``non-process'' (i.e., interrupt) work.
396 		 */
397 		p = curproc;
398 		if ((p->p_ithd != NULL) || CLKF_INTR(frame)) {
399 			p->p_iticks++;
400 			cp_time[CP_INTR]++;
401 		} else {
402 			p->p_sticks++;
403 			if (p != idleproc)
404 				cp_time[CP_SYS]++;
405 			else
406 				cp_time[CP_IDLE]++;
407 		}
408 	}
409 	pscnt = psdiv;
410 
411 	schedclock(p);
412 
413 	/* Update resource usage integrals and maximums. */
414 	if ((pstats = p->p_stats) != NULL &&
415 	    (ru = &pstats->p_ru) != NULL &&
416 	    (vm = p->p_vmspace) != NULL) {
417 		ru->ru_ixrss += pgtok(vm->vm_tsize);
418 		ru->ru_idrss += pgtok(vm->vm_dsize);
419 		ru->ru_isrss += pgtok(vm->vm_ssize);
420 		rss = pgtok(vmspace_resident_count(vm));
421 		if (ru->ru_maxrss < rss)
422 			ru->ru_maxrss = rss;
423 	}
424 
425 	mtx_exit(&sched_lock, MTX_SPIN);
426 }
427 
428 /*
429  * Return information about system clocks.
430  */
431 static int
432 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
433 {
434 	struct clockinfo clkinfo;
435 	/*
436 	 * Construct clockinfo structure.
437 	 */
438 	clkinfo.hz = hz;
439 	clkinfo.tick = tick;
440 	clkinfo.tickadj = tickadj;
441 	clkinfo.profhz = profhz;
442 	clkinfo.stathz = stathz ? stathz : hz;
443 	return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
444 }
445 
446 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
447 	0, 0, sysctl_kern_clockrate, "S,clockinfo","");
448