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