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