xref: /freebsd/sys/kern/kern_clock.c (revision 2a4a1db342263067035ce69a4017c645da63455d)
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/kernel.h>
49 #include <sys/lock.h>
50 #include <sys/ktr.h>
51 #include <sys/mutex.h>
52 #include <sys/proc.h>
53 #include <sys/resourcevar.h>
54 #include <sys/signalvar.h>
55 #include <sys/smp.h>
56 #include <vm/vm.h>
57 #include <vm/pmap.h>
58 #include <vm/vm_map.h>
59 #include <sys/sysctl.h>
60 #include <sys/bus.h>
61 #include <sys/interrupt.h>
62 
63 #include <machine/cpu.h>
64 #include <machine/limits.h>
65 
66 #ifdef GPROF
67 #include <sys/gmon.h>
68 #endif
69 
70 #ifdef DEVICE_POLLING
71 extern void init_device_poll(void);
72 extern void hardclock_device_poll(void);
73 #endif /* DEVICE_POLLING */
74 
75 static void initclocks(void *dummy);
76 SYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL)
77 
78 /* Some of these don't belong here, but it's easiest to concentrate them. */
79 long cp_time[CPUSTATES];
80 
81 SYSCTL_OPAQUE(_kern, OID_AUTO, cp_time, CTLFLAG_RD, &cp_time, sizeof(cp_time),
82     "LU", "CPU time statistics");
83 
84 long tk_cancc;
85 long tk_nin;
86 long tk_nout;
87 long tk_rawcc;
88 
89 /*
90  * Clock handling routines.
91  *
92  * This code is written to operate with two timers that run independently of
93  * each other.
94  *
95  * The main timer, running hz times per second, is used to trigger interval
96  * timers, timeouts and rescheduling as needed.
97  *
98  * The second timer handles kernel and user profiling,
99  * and does resource use estimation.  If the second timer is programmable,
100  * it is randomized to avoid aliasing between the two clocks.  For example,
101  * the randomization prevents an adversary from always giving up the cpu
102  * just before its quantum expires.  Otherwise, it would never accumulate
103  * cpu ticks.  The mean frequency of the second timer is stathz.
104  *
105  * If no second timer exists, stathz will be zero; in this case we drive
106  * profiling and statistics off the main clock.  This WILL NOT be accurate;
107  * do not do it unless absolutely necessary.
108  *
109  * The statistics clock may (or may not) be run at a higher rate while
110  * profiling.  This profile clock runs at profhz.  We require that profhz
111  * be an integral multiple of stathz.
112  *
113  * If the statistics clock is running fast, it must be divided by the ratio
114  * profhz/stathz for statistics.  (For profiling, every tick counts.)
115  *
116  * Time-of-day is maintained using a "timecounter", which may or may
117  * not be related to the hardware generating the above mentioned
118  * interrupts.
119  */
120 
121 int	stathz;
122 int	profhz;
123 static int profprocs;
124 int	ticks;
125 static int psdiv, pscnt;		/* prof => stat divider */
126 int	psratio;			/* ratio: prof / stat */
127 
128 /*
129  * Initialize clock frequencies and start both clocks running.
130  */
131 /* ARGSUSED*/
132 static void
133 initclocks(dummy)
134 	void *dummy;
135 {
136 	register int i;
137 
138 	/*
139 	 * Set divisors to 1 (normal case) and let the machine-specific
140 	 * code do its bit.
141 	 */
142 	psdiv = pscnt = 1;
143 	cpu_initclocks();
144 
145 #ifdef DEVICE_POLLING
146 	init_device_poll();
147 #endif
148 	/*
149 	 * Compute profhz/stathz, and fix profhz if needed.
150 	 */
151 	i = stathz ? stathz : hz;
152 	if (profhz == 0)
153 		profhz = i;
154 	psratio = profhz / i;
155 }
156 
157 /*
158  * Each time the real-time timer fires, this function is called on all CPUs
159  * with each CPU passing in its curthread as the first argument.  If possible
160  * a nice optimization in the future would be to allow the CPU receiving the
161  * actual real-time timer interrupt to call this function on behalf of the
162  * other CPUs rather than sending an IPI to all other CPUs so that they
163  * can call this function.  Note that hardclock() calls hardclock_process()
164  * for the CPU receiving the timer interrupt, so only the other CPUs in the
165  * system need to call this function (or have it called on their behalf.
166  */
167 void
168 hardclock_process(td, user)
169 	struct thread *td;
170 	int user;
171 {
172 	struct pstats *pstats;
173 	struct proc *p = td->td_proc;
174 
175 	/*
176 	 * Run current process's virtual and profile time, as needed.
177 	 */
178 	mtx_assert(&sched_lock, MA_OWNED);
179 	if (p->p_flag & P_KSES) {
180 		/* XXXKSE What to do? */
181 	} else {
182 		pstats = p->p_stats;
183 		if (user &&
184 		    timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
185 		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0) {
186 			p->p_sflag |= PS_ALRMPEND;
187 			td->td_kse->ke_flags |= KEF_ASTPENDING;
188 		}
189 		if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
190 		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0) {
191 			p->p_sflag |= PS_PROFPEND;
192 			td->td_kse->ke_flags |= KEF_ASTPENDING;
193 		}
194 	}
195 }
196 
197 /*
198  * The real-time timer, interrupting hz times per second.
199  */
200 void
201 hardclock(frame)
202 	register struct clockframe *frame;
203 {
204 	int need_softclock = 0;
205 
206 	CTR0(KTR_CLK, "hardclock fired");
207 	mtx_lock_spin_flags(&sched_lock, MTX_QUIET);
208 	hardclock_process(curthread, CLKF_USERMODE(frame));
209 	mtx_unlock_spin_flags(&sched_lock, MTX_QUIET);
210 
211 	/*
212 	 * If no separate statistics clock is available, run it from here.
213 	 *
214 	 * XXX: this only works for UP
215 	 */
216 	if (stathz == 0)
217 		statclock(frame);
218 
219 #ifdef DEVICE_POLLING
220 	hardclock_device_poll();	/* this is very short and quick */
221 #endif /* DEVICE_POLLING */
222 
223 	/*
224 	 * Process callouts at a very low cpu priority, so we don't keep the
225 	 * relatively high clock interrupt priority any longer than necessary.
226 	 */
227 	mtx_lock_spin_flags(&callout_lock, MTX_QUIET);
228 	ticks++;
229 	if (TAILQ_FIRST(&callwheel[ticks & callwheelmask]) != NULL) {
230 		need_softclock = 1;
231 	} else if (softticks + 1 == ticks)
232 		++softticks;
233 	mtx_unlock_spin_flags(&callout_lock, MTX_QUIET);
234 
235 	/*
236 	 * swi_sched acquires sched_lock, so we don't want to call it with
237 	 * callout_lock held; incorrect locking order.
238 	 */
239 	if (need_softclock)
240 		swi_sched(softclock_ih, 0);
241 }
242 
243 /*
244  * Compute number of ticks in the specified amount of time.
245  */
246 int
247 tvtohz(tv)
248 	struct timeval *tv;
249 {
250 	register unsigned long ticks;
251 	register long sec, usec;
252 
253 	/*
254 	 * If the number of usecs in the whole seconds part of the time
255 	 * difference fits in a long, then the total number of usecs will
256 	 * fit in an unsigned long.  Compute the total and convert it to
257 	 * ticks, rounding up and adding 1 to allow for the current tick
258 	 * to expire.  Rounding also depends on unsigned long arithmetic
259 	 * to avoid overflow.
260 	 *
261 	 * Otherwise, if the number of ticks in the whole seconds part of
262 	 * the time difference fits in a long, then convert the parts to
263 	 * ticks separately and add, using similar rounding methods and
264 	 * overflow avoidance.  This method would work in the previous
265 	 * case but it is slightly slower and assumes that hz is integral.
266 	 *
267 	 * Otherwise, round the time difference down to the maximum
268 	 * representable value.
269 	 *
270 	 * If ints have 32 bits, then the maximum value for any timeout in
271 	 * 10ms ticks is 248 days.
272 	 */
273 	sec = tv->tv_sec;
274 	usec = tv->tv_usec;
275 	if (usec < 0) {
276 		sec--;
277 		usec += 1000000;
278 	}
279 	if (sec < 0) {
280 #ifdef DIAGNOSTIC
281 		if (usec > 0) {
282 			sec++;
283 			usec -= 1000000;
284 		}
285 		printf("tvotohz: negative time difference %ld sec %ld usec\n",
286 		       sec, usec);
287 #endif
288 		ticks = 1;
289 	} else if (sec <= LONG_MAX / 1000000)
290 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
291 			/ tick + 1;
292 	else if (sec <= LONG_MAX / hz)
293 		ticks = sec * hz
294 			+ ((unsigned long)usec + (tick - 1)) / tick + 1;
295 	else
296 		ticks = LONG_MAX;
297 	if (ticks > INT_MAX)
298 		ticks = INT_MAX;
299 	return ((int)ticks);
300 }
301 
302 /*
303  * Start profiling on a process.
304  *
305  * Kernel profiling passes proc0 which never exits and hence
306  * keeps the profile clock running constantly.
307  */
308 void
309 startprofclock(p)
310 	register struct proc *p;
311 {
312 	int s;
313 
314 	/*
315 	 * XXX; Right now sched_lock protects statclock(), but perhaps
316 	 * it should be protected later on by a time_lock, which would
317 	 * cover psdiv, etc. as well.
318 	 */
319 	mtx_lock_spin(&sched_lock);
320 	if ((p->p_sflag & PS_PROFIL) == 0) {
321 		p->p_sflag |= PS_PROFIL;
322 		if (++profprocs == 1 && stathz != 0) {
323 			s = splstatclock();
324 			psdiv = pscnt = psratio;
325 			setstatclockrate(profhz);
326 			splx(s);
327 		}
328 	}
329 	mtx_unlock_spin(&sched_lock);
330 }
331 
332 /*
333  * Stop profiling on a process.
334  */
335 void
336 stopprofclock(p)
337 	register struct proc *p;
338 {
339 	int s;
340 
341 	mtx_lock_spin(&sched_lock);
342 	if (p->p_sflag & PS_PROFIL) {
343 		p->p_sflag &= ~PS_PROFIL;
344 		if (--profprocs == 0 && stathz != 0) {
345 			s = splstatclock();
346 			psdiv = pscnt = 1;
347 			setstatclockrate(stathz);
348 			splx(s);
349 		}
350 	}
351 	mtx_unlock_spin(&sched_lock);
352 }
353 
354 /*
355  * Do process and kernel statistics.  Most of the statistics are only
356  * used by user-level statistics programs.  The main exceptions are
357  * ke->ke_uticks, p->p_sticks, p->p_iticks, and p->p_estcpu.  This function
358  * should be called by all CPUs in the system for each statistics clock
359  * interrupt.  See the description of hardclock_process for more detail on
360  * this function's relationship to statclock.
361  */
362 void
363 statclock_process(ke, pc, user)
364 	struct kse *ke;
365 	register_t pc;
366 	int user;
367 {
368 #ifdef GPROF
369 	struct gmonparam *g;
370 	int i;
371 #endif
372 	struct pstats *pstats;
373 	long rss;
374 	struct rusage *ru;
375 	struct vmspace *vm;
376 	struct proc *p = ke->ke_proc;
377 	struct thread *td = ke->ke_thread; /* current thread */
378 
379 	KASSERT(ke == curthread->td_kse, ("statclock_process: td != curthread"));
380 	mtx_assert(&sched_lock, MA_OWNED);
381 	if (user) {
382 		/*
383 		 * Came from user mode; CPU was in user state.
384 		 * If this process is being profiled, record the tick.
385 		 */
386 		if (p->p_sflag & PS_PROFIL)
387 			addupc_intr(ke, pc, 1);
388 		if (pscnt < psdiv)
389 			return;
390 		/*
391 		 * Charge the time as appropriate.
392 		 */
393 		ke->ke_uticks++;
394 		if (ke->ke_ksegrp->kg_nice > NZERO)
395 			cp_time[CP_NICE]++;
396 		else
397 			cp_time[CP_USER]++;
398 	} else {
399 #ifdef GPROF
400 		/*
401 		 * Kernel statistics are just like addupc_intr, only easier.
402 		 */
403 		g = &_gmonparam;
404 		if (g->state == GMON_PROF_ON) {
405 			i = pc - g->lowpc;
406 			if (i < g->textsize) {
407 				i /= HISTFRACTION * sizeof(*g->kcount);
408 				g->kcount[i]++;
409 			}
410 		}
411 #endif
412 		if (pscnt < psdiv)
413 			return;
414 		/*
415 		 * Came from kernel mode, so we were:
416 		 * - handling an interrupt,
417 		 * - doing syscall or trap work on behalf of the current
418 		 *   user process, or
419 		 * - spinning in the idle loop.
420 		 * Whichever it is, charge the time as appropriate.
421 		 * Note that we charge interrupts to the current process,
422 		 * regardless of whether they are ``for'' that process,
423 		 * so that we know how much of its real time was spent
424 		 * in ``non-process'' (i.e., interrupt) work.
425 		 */
426 		if ((td->td_ithd != NULL) || td->td_intr_nesting_level >= 2) {
427 			ke->ke_iticks++;
428 			cp_time[CP_INTR]++;
429 		} else {
430 			ke->ke_sticks++;
431 			if (p != PCPU_GET(idlethread)->td_proc)
432 				cp_time[CP_SYS]++;
433 			else
434 				cp_time[CP_IDLE]++;
435 		}
436 	}
437 
438 	schedclock(ke->ke_thread);
439 
440 	/* Update resource usage integrals and maximums. */
441 	if ((pstats = p->p_stats) != NULL &&
442 	    (ru = &pstats->p_ru) != NULL &&
443 	    (vm = p->p_vmspace) != NULL) {
444 		ru->ru_ixrss += pgtok(vm->vm_tsize);
445 		ru->ru_idrss += pgtok(vm->vm_dsize);
446 		ru->ru_isrss += pgtok(vm->vm_ssize);
447 		rss = pgtok(vmspace_resident_count(vm));
448 		if (ru->ru_maxrss < rss)
449 			ru->ru_maxrss = rss;
450 	}
451 }
452 
453 /*
454  * Statistics clock.  Grab profile sample, and if divider reaches 0,
455  * do process and kernel statistics.  Most of the statistics are only
456  * used by user-level statistics programs.  The main exceptions are
457  * ke->ke_uticks, p->p_sticks, p->p_iticks, and p->p_estcpu.
458  */
459 void
460 statclock(frame)
461 	register struct clockframe *frame;
462 {
463 
464 	CTR0(KTR_CLK, "statclock fired");
465 	mtx_lock_spin_flags(&sched_lock, MTX_QUIET);
466 	if (--pscnt == 0)
467 		pscnt = psdiv;
468 	statclock_process(curthread->td_kse, CLKF_PC(frame), CLKF_USERMODE(frame));
469 	mtx_unlock_spin_flags(&sched_lock, MTX_QUIET);
470 }
471 
472 /*
473  * Return information about system clocks.
474  */
475 static int
476 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
477 {
478 	struct clockinfo clkinfo;
479 	/*
480 	 * Construct clockinfo structure.
481 	 */
482 	bzero(&clkinfo, sizeof(clkinfo));
483 	clkinfo.hz = hz;
484 	clkinfo.tick = tick;
485 	clkinfo.profhz = profhz;
486 	clkinfo.stathz = stathz ? stathz : hz;
487 	return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
488 }
489 
490 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
491 	0, 0, sysctl_kern_clockrate, "S,clockinfo",
492 	"Rate and period of various kernel clocks");
493