xref: /freebsd/sys/kern/kern_clock.c (revision 7afc53b8dfcc7d5897920ce6cc7e842fbb4ab813)
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  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)kern_clock.c	8.5 (Berkeley) 1/21/94
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 #include "opt_ntp.h"
41 #include "opt_watchdog.h"
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/callout.h>
46 #include <sys/kdb.h>
47 #include <sys/kernel.h>
48 #include <sys/lock.h>
49 #include <sys/ktr.h>
50 #include <sys/mutex.h>
51 #include <sys/proc.h>
52 #include <sys/resource.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/limits.h>
64 #include <sys/timetc.h>
65 
66 #include <machine/cpu.h>
67 
68 #ifdef GPROF
69 #include <sys/gmon.h>
70 #endif
71 
72 #ifdef HWPMC_HOOKS
73 #include <sys/pmckern.h>
74 #endif
75 
76 #ifdef DEVICE_POLLING
77 extern void hardclock_device_poll(void);
78 #endif /* DEVICE_POLLING */
79 
80 static void initclocks(void *dummy);
81 SYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL)
82 
83 /* Some of these don't belong here, but it's easiest to concentrate them. */
84 long cp_time[CPUSTATES];
85 
86 SYSCTL_OPAQUE(_kern, OID_AUTO, cp_time, CTLFLAG_RD, &cp_time, sizeof(cp_time),
87     "LU", "CPU time statistics");
88 
89 #ifdef SW_WATCHDOG
90 #include <sys/watchdog.h>
91 
92 static int watchdog_ticks;
93 static int watchdog_enabled;
94 static void watchdog_fire(void);
95 static void watchdog_config(void *, u_int, int *);
96 #endif /* SW_WATCHDOG */
97 
98 /*
99  * Clock handling routines.
100  *
101  * This code is written to operate with two timers that run independently of
102  * each other.
103  *
104  * The main timer, running hz times per second, is used to trigger interval
105  * timers, timeouts and rescheduling as needed.
106  *
107  * The second timer handles kernel and user profiling,
108  * and does resource use estimation.  If the second timer is programmable,
109  * it is randomized to avoid aliasing between the two clocks.  For example,
110  * the randomization prevents an adversary from always giving up the cpu
111  * just before its quantum expires.  Otherwise, it would never accumulate
112  * cpu ticks.  The mean frequency of the second timer is stathz.
113  *
114  * If no second timer exists, stathz will be zero; in this case we drive
115  * profiling and statistics off the main clock.  This WILL NOT be accurate;
116  * do not do it unless absolutely necessary.
117  *
118  * The statistics clock may (or may not) be run at a higher rate while
119  * profiling.  This profile clock runs at profhz.  We require that profhz
120  * be an integral multiple of stathz.
121  *
122  * If the statistics clock is running fast, it must be divided by the ratio
123  * profhz/stathz for statistics.  (For profiling, every tick counts.)
124  *
125  * Time-of-day is maintained using a "timecounter", which may or may
126  * not be related to the hardware generating the above mentioned
127  * interrupts.
128  */
129 
130 int	stathz;
131 int	profhz;
132 int	profprocs;
133 int	ticks;
134 int	psratio;
135 
136 /*
137  * Initialize clock frequencies and start both clocks running.
138  */
139 /* ARGSUSED*/
140 static void
141 initclocks(dummy)
142 	void *dummy;
143 {
144 	register int i;
145 
146 	/*
147 	 * Set divisors to 1 (normal case) and let the machine-specific
148 	 * code do its bit.
149 	 */
150 	cpu_initclocks();
151 
152 	/*
153 	 * Compute profhz/stathz, and fix profhz if needed.
154 	 */
155 	i = stathz ? stathz : hz;
156 	if (profhz == 0)
157 		profhz = i;
158 	psratio = profhz / i;
159 #ifdef SW_WATCHDOG
160 	EVENTHANDLER_REGISTER(watchdog_list, watchdog_config, NULL, 0);
161 #endif
162 }
163 
164 /*
165  * Each time the real-time timer fires, this function is called on all CPUs.
166  * Note that hardclock() calls hardclock_process() for the boot CPU, so only
167  * the other CPUs in the system need to call this function.
168  */
169 void
170 hardclock_process(frame)
171 	register struct clockframe *frame;
172 {
173 	struct pstats *pstats;
174 	struct thread *td = curthread;
175 	struct proc *p = td->td_proc;
176 
177 	/*
178 	 * Run current process's virtual and profile time, as needed.
179 	 */
180 	mtx_lock_spin_flags(&sched_lock, MTX_QUIET);
181 	if (p->p_flag & P_SA) {
182 		/* XXXKSE What to do? */
183 	} else {
184 		pstats = p->p_stats;
185 		if (CLKF_USERMODE(frame) &&
186 		    timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
187 		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0) {
188 			p->p_sflag |= PS_ALRMPEND;
189 			td->td_flags |= TDF_ASTPENDING;
190 		}
191 		if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
192 		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0) {
193 			p->p_sflag |= PS_PROFPEND;
194 			td->td_flags |= TDF_ASTPENDING;
195 		}
196 	}
197 	mtx_unlock_spin_flags(&sched_lock, MTX_QUIET);
198 
199 #ifdef	HWPMC_HOOKS
200 	if (PMC_CPU_HAS_SAMPLES(PCPU_GET(cpuid)))
201 		PMC_CALL_HOOK_UNLOCKED(curthread, PMC_FN_DO_SAMPLES, NULL);
202 #endif
203 }
204 
205 /*
206  * The real-time timer, interrupting hz times per second.
207  */
208 void
209 hardclock(frame)
210 	register struct clockframe *frame;
211 {
212 	int need_softclock = 0;
213 
214 	CTR0(KTR_CLK, "hardclock fired");
215 	hardclock_process(frame);
216 
217 	tc_ticktock();
218 	/*
219 	 * If no separate statistics clock is available, run it from here.
220 	 *
221 	 * XXX: this only works for UP
222 	 */
223 	if (stathz == 0) {
224 		profclock(frame);
225 		statclock(frame);
226 	}
227 
228 #ifdef DEVICE_POLLING
229 	hardclock_device_poll();	/* this is very short and quick */
230 #endif /* DEVICE_POLLING */
231 
232 	/*
233 	 * Process callouts at a very low cpu priority, so we don't keep the
234 	 * relatively high clock interrupt priority any longer than necessary.
235 	 */
236 	mtx_lock_spin_flags(&callout_lock, MTX_QUIET);
237 	ticks++;
238 	if (TAILQ_FIRST(&callwheel[ticks & callwheelmask]) != NULL) {
239 		need_softclock = 1;
240 	} else if (softticks + 1 == ticks)
241 		++softticks;
242 	mtx_unlock_spin_flags(&callout_lock, MTX_QUIET);
243 
244 	/*
245 	 * swi_sched acquires sched_lock, so we don't want to call it with
246 	 * callout_lock held; incorrect locking order.
247 	 */
248 	if (need_softclock)
249 		swi_sched(softclock_ih, 0);
250 
251 #ifdef SW_WATCHDOG
252 	if (watchdog_enabled > 0 && --watchdog_ticks <= 0)
253 		watchdog_fire();
254 #endif /* SW_WATCHDOG */
255 }
256 
257 /*
258  * Compute number of ticks in the specified amount of time.
259  */
260 int
261 tvtohz(tv)
262 	struct timeval *tv;
263 {
264 	register unsigned long ticks;
265 	register long sec, usec;
266 
267 	/*
268 	 * If the number of usecs in the whole seconds part of the time
269 	 * difference fits in a long, then the total number of usecs will
270 	 * fit in an unsigned long.  Compute the total and convert it to
271 	 * ticks, rounding up and adding 1 to allow for the current tick
272 	 * to expire.  Rounding also depends on unsigned long arithmetic
273 	 * to avoid overflow.
274 	 *
275 	 * Otherwise, if the number of ticks in the whole seconds part of
276 	 * the time difference fits in a long, then convert the parts to
277 	 * ticks separately and add, using similar rounding methods and
278 	 * overflow avoidance.  This method would work in the previous
279 	 * case but it is slightly slower and assumes that hz is integral.
280 	 *
281 	 * Otherwise, round the time difference down to the maximum
282 	 * representable value.
283 	 *
284 	 * If ints have 32 bits, then the maximum value for any timeout in
285 	 * 10ms ticks is 248 days.
286 	 */
287 	sec = tv->tv_sec;
288 	usec = tv->tv_usec;
289 	if (usec < 0) {
290 		sec--;
291 		usec += 1000000;
292 	}
293 	if (sec < 0) {
294 #ifdef DIAGNOSTIC
295 		if (usec > 0) {
296 			sec++;
297 			usec -= 1000000;
298 		}
299 		printf("tvotohz: negative time difference %ld sec %ld usec\n",
300 		       sec, usec);
301 #endif
302 		ticks = 1;
303 	} else if (sec <= LONG_MAX / 1000000)
304 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
305 			/ tick + 1;
306 	else if (sec <= LONG_MAX / hz)
307 		ticks = sec * hz
308 			+ ((unsigned long)usec + (tick - 1)) / tick + 1;
309 	else
310 		ticks = LONG_MAX;
311 	if (ticks > INT_MAX)
312 		ticks = INT_MAX;
313 	return ((int)ticks);
314 }
315 
316 /*
317  * Start profiling on a process.
318  *
319  * Kernel profiling passes proc0 which never exits and hence
320  * keeps the profile clock running constantly.
321  */
322 void
323 startprofclock(p)
324 	register struct proc *p;
325 {
326 
327 	/*
328 	 * XXX; Right now sched_lock protects statclock(), but perhaps
329 	 * it should be protected later on by a time_lock, which would
330 	 * cover psdiv, etc. as well.
331 	 */
332 	PROC_LOCK_ASSERT(p, MA_OWNED);
333 	if (p->p_flag & P_STOPPROF)
334 		return;
335 	if ((p->p_flag & P_PROFIL) == 0) {
336 		mtx_lock_spin(&sched_lock);
337 		p->p_flag |= P_PROFIL;
338 		if (++profprocs == 1)
339 			cpu_startprofclock();
340 		mtx_unlock_spin(&sched_lock);
341 	}
342 }
343 
344 /*
345  * Stop profiling on a process.
346  */
347 void
348 stopprofclock(p)
349 	register struct proc *p;
350 {
351 
352 	PROC_LOCK_ASSERT(p, MA_OWNED);
353 	if (p->p_flag & P_PROFIL) {
354 		if (p->p_profthreads != 0) {
355 			p->p_flag |= P_STOPPROF;
356 			while (p->p_profthreads != 0)
357 				msleep(&p->p_profthreads, &p->p_mtx, PPAUSE,
358 				    "stopprof", 0);
359 			p->p_flag &= ~P_STOPPROF;
360 		}
361 		if ((p->p_flag & P_PROFIL) == 0)
362 			return;
363 		mtx_lock_spin(&sched_lock);
364 		p->p_flag &= ~P_PROFIL;
365 		if (--profprocs == 0)
366 			cpu_stopprofclock();
367 		mtx_unlock_spin(&sched_lock);
368 	}
369 }
370 
371 /*
372  * Statistics clock.  Grab profile sample, and if divider reaches 0,
373  * do process and kernel statistics.  Most of the statistics are only
374  * used by user-level statistics programs.  The main exceptions are
375  * ke->ke_uticks, p->p_rux.rux_sticks, p->p_rux.rux_iticks, and p->p_estcpu.
376  * This should be called by all active processors.
377  */
378 void
379 statclock(frame)
380 	register struct clockframe *frame;
381 {
382 	struct rusage *ru;
383 	struct vmspace *vm;
384 	struct thread *td;
385 	struct proc *p;
386 	long rss;
387 
388 	td = curthread;
389 	p = td->td_proc;
390 
391 	mtx_lock_spin_flags(&sched_lock, MTX_QUIET);
392 	if (CLKF_USERMODE(frame)) {
393 		/*
394 		 * Charge the time as appropriate.
395 		 */
396 		if (p->p_flag & P_SA)
397 			thread_statclock(1);
398 		p->p_rux.rux_uticks++;
399 		if (p->p_nice > NZERO)
400 			cp_time[CP_NICE]++;
401 		else
402 			cp_time[CP_USER]++;
403 	} else {
404 		/*
405 		 * Came from kernel mode, so we were:
406 		 * - handling an interrupt,
407 		 * - doing syscall or trap work on behalf of the current
408 		 *   user process, or
409 		 * - spinning in the idle loop.
410 		 * Whichever it is, charge the time as appropriate.
411 		 * Note that we charge interrupts to the current process,
412 		 * regardless of whether they are ``for'' that process,
413 		 * so that we know how much of its real time was spent
414 		 * in ``non-process'' (i.e., interrupt) work.
415 		 */
416 		if ((td->td_ithd != NULL) || td->td_intr_nesting_level >= 2) {
417 			p->p_rux.rux_iticks++;
418 			cp_time[CP_INTR]++;
419 		} else {
420 			if (p->p_flag & P_SA)
421 				thread_statclock(0);
422 			td->td_sticks++;
423 			p->p_rux.rux_sticks++;
424 			if (p != PCPU_GET(idlethread)->td_proc)
425 				cp_time[CP_SYS]++;
426 			else
427 				cp_time[CP_IDLE]++;
428 		}
429 	}
430 	CTR4(KTR_SCHED, "statclock: %p(%s) prio %d stathz %d",
431 	    td, td->td_proc->p_comm, td->td_priority, (stathz)?stathz:hz);
432 
433 	sched_clock(td);
434 
435 	/* Update resource usage integrals and maximums. */
436 	MPASS(p->p_stats != NULL);
437 	MPASS(p->p_vmspace != NULL);
438 	vm = p->p_vmspace;
439 	ru = &p->p_stats->p_ru;
440 	ru->ru_ixrss += pgtok(vm->vm_tsize);
441 	ru->ru_idrss += pgtok(vm->vm_dsize);
442 	ru->ru_isrss += pgtok(vm->vm_ssize);
443 	rss = pgtok(vmspace_resident_count(vm));
444 	if (ru->ru_maxrss < rss)
445 		ru->ru_maxrss = rss;
446 	mtx_unlock_spin_flags(&sched_lock, MTX_QUIET);
447 }
448 
449 void
450 profclock(frame)
451 	register struct clockframe *frame;
452 {
453 	struct thread *td;
454 #ifdef GPROF
455 	struct gmonparam *g;
456 	int i;
457 #endif
458 
459 	td = curthread;
460 	if (CLKF_USERMODE(frame)) {
461 		/*
462 		 * Came from user mode; CPU was in user state.
463 		 * If this process is being profiled, record the tick.
464 		 * if there is no related user location yet, don't
465 		 * bother trying to count it.
466 		 */
467 		if (td->td_proc->p_flag & P_PROFIL)
468 			addupc_intr(td, CLKF_PC(frame), 1);
469 	}
470 #ifdef GPROF
471 	else {
472 		/*
473 		 * Kernel statistics are just like addupc_intr, only easier.
474 		 */
475 		g = &_gmonparam;
476 		if (g->state == GMON_PROF_ON) {
477 			i = CLKF_PC(frame) - g->lowpc;
478 			if (i < g->textsize) {
479 				i /= HISTFRACTION * sizeof(*g->kcount);
480 				g->kcount[i]++;
481 			}
482 		}
483 	}
484 #endif
485 }
486 
487 /*
488  * Return information about system clocks.
489  */
490 static int
491 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
492 {
493 	struct clockinfo clkinfo;
494 	/*
495 	 * Construct clockinfo structure.
496 	 */
497 	bzero(&clkinfo, sizeof(clkinfo));
498 	clkinfo.hz = hz;
499 	clkinfo.tick = tick;
500 	clkinfo.profhz = profhz;
501 	clkinfo.stathz = stathz ? stathz : hz;
502 	return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
503 }
504 
505 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
506 	0, 0, sysctl_kern_clockrate, "S,clockinfo",
507 	"Rate and period of various kernel clocks");
508 
509 #ifdef SW_WATCHDOG
510 
511 static void
512 watchdog_config(void *unused __unused, u_int cmd, int *err)
513 {
514 	u_int u;
515 
516 	u = cmd & WD_INTERVAL;
517 	if (cmd && u >= WD_TO_1SEC) {
518 		u = cmd & WD_INTERVAL;
519 		watchdog_ticks = (1 << (u - WD_TO_1SEC)) * hz;
520 		watchdog_enabled = 1;
521 		*err = 0;
522 	} else {
523 		watchdog_enabled = 0;
524 	}
525 }
526 
527 /*
528  * Handle a watchdog timeout by dumping interrupt information and
529  * then either dropping to DDB or panicing.
530  */
531 static void
532 watchdog_fire(void)
533 {
534 	int nintr;
535 	u_int64_t inttotal;
536 	u_long *curintr;
537 	char *curname;
538 
539 	curintr = intrcnt;
540 	curname = intrnames;
541 	inttotal = 0;
542 	nintr = eintrcnt - intrcnt;
543 
544 	printf("interrupt                   total\n");
545 	while (--nintr >= 0) {
546 		if (*curintr)
547 			printf("%-12s %20lu\n", curname, *curintr);
548 		curname += strlen(curname) + 1;
549 		inttotal += *curintr++;
550 	}
551 	printf("Total        %20ju\n", (uintmax_t)inttotal);
552 
553 #ifdef KDB
554 	kdb_backtrace();
555 	kdb_enter("watchdog timeout");
556 #else
557 	panic("watchdog timeout");
558 #endif /* KDB */
559 }
560 
561 #endif /* SW_WATCHDOG */
562