xref: /freebsd/sys/kern/kern_clock.c (revision ee41f1b1cf5e3d4f586cb85b46123b416275862c)
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 != PCPU_GET(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 			mtx_lock_spin(&sched_lock);
174 			p->p_sflag |= PS_ALRMPEND;
175 			aston();
176 			mtx_unlock_spin(&sched_lock);
177 		}
178 		if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
179 		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0) {
180 			mtx_lock_spin(&sched_lock);
181 			p->p_sflag |= PS_PROFPEND;
182 			aston();
183 			mtx_unlock_spin(&sched_lock);
184 		}
185 	}
186 
187 #if defined(SMP) && defined(BETTER_CLOCK)
188 	forward_hardclock(pscnt);
189 #endif
190 
191 	/*
192 	 * If no separate statistics clock is available, run it from here.
193 	 */
194 	if (stathz == 0)
195 		statclock(frame);
196 
197 	tc_windup();
198 
199 	/*
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 	mtx_lock_spin(&callout_lock);
204 	ticks++;
205 	if (TAILQ_FIRST(&callwheel[ticks & callwheelmask]) != NULL) {
206 		need_softclock = 1;
207 	} else if (softticks + 1 == ticks)
208 		++softticks;
209 	mtx_unlock_spin(&callout_lock);
210 
211 	/*
212 	 * swi_sched acquires sched_lock, so we don't want to call it with
213 	 * callout_lock held; incorrect locking order.
214 	 */
215 	if (need_softclock)
216 		swi_sched(softclock_ih, SWI_NOSWITCH);
217 }
218 
219 /*
220  * Compute number of ticks in the specified amount of time.
221  */
222 int
223 tvtohz(tv)
224 	struct timeval *tv;
225 {
226 	register unsigned long ticks;
227 	register long sec, usec;
228 
229 	/*
230 	 * If the number of usecs in the whole seconds part of the time
231 	 * difference fits in a long, then the total number of usecs will
232 	 * fit in an unsigned long.  Compute the total and convert it to
233 	 * ticks, rounding up and adding 1 to allow for the current tick
234 	 * to expire.  Rounding also depends on unsigned long arithmetic
235 	 * to avoid overflow.
236 	 *
237 	 * Otherwise, if the number of ticks in the whole seconds part of
238 	 * the time difference fits in a long, then convert the parts to
239 	 * ticks separately and add, using similar rounding methods and
240 	 * overflow avoidance.  This method would work in the previous
241 	 * case but it is slightly slower and assumes that hz is integral.
242 	 *
243 	 * Otherwise, round the time difference down to the maximum
244 	 * representable value.
245 	 *
246 	 * If ints have 32 bits, then the maximum value for any timeout in
247 	 * 10ms ticks is 248 days.
248 	 */
249 	sec = tv->tv_sec;
250 	usec = tv->tv_usec;
251 	if (usec < 0) {
252 		sec--;
253 		usec += 1000000;
254 	}
255 	if (sec < 0) {
256 #ifdef DIAGNOSTIC
257 		if (usec > 0) {
258 			sec++;
259 			usec -= 1000000;
260 		}
261 		printf("tvotohz: negative time difference %ld sec %ld usec\n",
262 		       sec, usec);
263 #endif
264 		ticks = 1;
265 	} else if (sec <= LONG_MAX / 1000000)
266 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
267 			/ tick + 1;
268 	else if (sec <= LONG_MAX / hz)
269 		ticks = sec * hz
270 			+ ((unsigned long)usec + (tick - 1)) / tick + 1;
271 	else
272 		ticks = LONG_MAX;
273 	if (ticks > INT_MAX)
274 		ticks = INT_MAX;
275 	return ((int)ticks);
276 }
277 
278 /*
279  * Start profiling on a process.
280  *
281  * Kernel profiling passes proc0 which never exits and hence
282  * keeps the profile clock running constantly.
283  */
284 void
285 startprofclock(p)
286 	register struct proc *p;
287 {
288 	int s;
289 
290 	/*
291 	 * XXX; Right now sched_lock protects statclock(), but perhaps
292 	 * it should be protected later on by a time_lock, which would
293 	 * cover psdiv, etc. as well.
294 	 */
295 	mtx_lock_spin(&sched_lock);
296 	if ((p->p_sflag & PS_PROFIL) == 0) {
297 		p->p_sflag |= PS_PROFIL;
298 		if (++profprocs == 1 && stathz != 0) {
299 			s = splstatclock();
300 			psdiv = pscnt = psratio;
301 			setstatclockrate(profhz);
302 			splx(s);
303 		}
304 	}
305 	mtx_unlock_spin(&sched_lock);
306 }
307 
308 /*
309  * Stop profiling on a process.
310  */
311 void
312 stopprofclock(p)
313 	register struct proc *p;
314 {
315 	int s;
316 
317 	mtx_lock_spin(&sched_lock);
318 	if (p->p_sflag & PS_PROFIL) {
319 		p->p_sflag &= ~PS_PROFIL;
320 		if (--profprocs == 0 && stathz != 0) {
321 			s = splstatclock();
322 			psdiv = pscnt = 1;
323 			setstatclockrate(stathz);
324 			splx(s);
325 		}
326 	}
327 	mtx_unlock_spin(&sched_lock);
328 }
329 
330 /*
331  * Statistics clock.  Grab profile sample, and if divider reaches 0,
332  * do process and kernel statistics.  Most of the statistics are only
333  * used by user-level statistics programs.  The main exceptions are
334  * p->p_uticks, p->p_sticks, p->p_iticks, and p->p_estcpu.
335  */
336 void
337 statclock(frame)
338 	register struct clockframe *frame;
339 {
340 #ifdef GPROF
341 	register struct gmonparam *g;
342 	int i;
343 #endif
344 	register struct proc *p;
345 	struct pstats *pstats;
346 	long rss;
347 	struct rusage *ru;
348 	struct vmspace *vm;
349 
350 	mtx_lock_spin(&sched_lock);
351 
352 	if (CLKF_USERMODE(frame)) {
353 		/*
354 		 * Came from user mode; CPU was in user state.
355 		 * If this process is being profiled, record the tick.
356 		 */
357 		p = curproc;
358 		if (p->p_sflag & PS_PROFIL)
359 			addupc_intr(p, CLKF_PC(frame), 1);
360 #if defined(SMP) && defined(BETTER_CLOCK)
361 		if (stathz != 0)
362 			forward_statclock(pscnt);
363 #endif
364 		if (--pscnt > 0) {
365 			mtx_unlock_spin(&sched_lock);
366 			return;
367 		}
368 		/*
369 		 * Charge the time as appropriate.
370 		 */
371 		p->p_uticks++;
372 		if (p->p_nice > NZERO)
373 			cp_time[CP_NICE]++;
374 		else
375 			cp_time[CP_USER]++;
376 	} else {
377 #ifdef GPROF
378 		/*
379 		 * Kernel statistics are just like addupc_intr, only easier.
380 		 */
381 		g = &_gmonparam;
382 		if (g->state == GMON_PROF_ON) {
383 			i = CLKF_PC(frame) - g->lowpc;
384 			if (i < g->textsize) {
385 				i /= HISTFRACTION * sizeof(*g->kcount);
386 				g->kcount[i]++;
387 			}
388 		}
389 #endif
390 #if defined(SMP) && defined(BETTER_CLOCK)
391 		if (stathz != 0)
392 			forward_statclock(pscnt);
393 #endif
394 		if (--pscnt > 0) {
395 			mtx_unlock_spin(&sched_lock);
396 			return;
397 		}
398 		/*
399 		 * Came from kernel mode, so we were:
400 		 * - handling an interrupt,
401 		 * - doing syscall or trap work on behalf of the current
402 		 *   user process, or
403 		 * - spinning in the idle loop.
404 		 * Whichever it is, charge the time as appropriate.
405 		 * Note that we charge interrupts to the current process,
406 		 * regardless of whether they are ``for'' that process,
407 		 * so that we know how much of its real time was spent
408 		 * in ``non-process'' (i.e., interrupt) work.
409 		 */
410 		p = curproc;
411 		if ((p->p_ithd != NULL) || CLKF_INTR(frame)) {
412 			p->p_iticks++;
413 			cp_time[CP_INTR]++;
414 		} else {
415 			p->p_sticks++;
416 			if (p != PCPU_GET(idleproc))
417 				cp_time[CP_SYS]++;
418 			else
419 				cp_time[CP_IDLE]++;
420 		}
421 	}
422 	pscnt = psdiv;
423 
424 	schedclock(p);
425 
426 	/* Update resource usage integrals and maximums. */
427 	if ((pstats = p->p_stats) != NULL &&
428 	    (ru = &pstats->p_ru) != NULL &&
429 	    (vm = p->p_vmspace) != NULL) {
430 		ru->ru_ixrss += pgtok(vm->vm_tsize);
431 		ru->ru_idrss += pgtok(vm->vm_dsize);
432 		ru->ru_isrss += pgtok(vm->vm_ssize);
433 		rss = pgtok(vmspace_resident_count(vm));
434 		if (ru->ru_maxrss < rss)
435 			ru->ru_maxrss = rss;
436 	}
437 
438 	mtx_unlock_spin(&sched_lock);
439 }
440 
441 /*
442  * Return information about system clocks.
443  */
444 static int
445 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
446 {
447 	struct clockinfo clkinfo;
448 	/*
449 	 * Construct clockinfo structure.
450 	 */
451 	clkinfo.hz = hz;
452 	clkinfo.tick = tick;
453 	clkinfo.tickadj = tickadj;
454 	clkinfo.profhz = profhz;
455 	clkinfo.stathz = stathz ? stathz : hz;
456 	return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
457 }
458 
459 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
460 	0, 0, sysctl_kern_clockrate, "S,clockinfo","");
461