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