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