xref: /freebsd/sys/kern/kern_clock.c (revision d056fa046c6a91b90cd98165face0e42a33a5173)
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 	if (p->p_flag & P_SA) {
206 		/* XXXKSE What to do? */
207 	} else {
208 		pstats = p->p_stats;
209 		if (usermode &&
210 		    timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
211 		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0) {
212 			p->p_sflag |= PS_ALRMPEND;
213 			td->td_flags |= TDF_ASTPENDING;
214 		}
215 		if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
216 		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0) {
217 			p->p_sflag |= PS_PROFPEND;
218 			td->td_flags |= TDF_ASTPENDING;
219 		}
220 	}
221 	mtx_unlock_spin_flags(&sched_lock, MTX_QUIET);
222 
223 #ifdef	HWPMC_HOOKS
224 	if (PMC_CPU_HAS_SAMPLES(PCPU_GET(cpuid)))
225 		PMC_CALL_HOOK_UNLOCKED(curthread, PMC_FN_DO_SAMPLES, NULL);
226 #endif
227 }
228 
229 /*
230  * The real-time timer, interrupting hz times per second.
231  */
232 void
233 hardclock(int usermode, uintfptr_t pc)
234 {
235 	int need_softclock = 0;
236 
237 	hardclock_cpu(usermode);
238 
239 	tc_ticktock();
240 	/*
241 	 * If no separate statistics clock is available, run it from here.
242 	 *
243 	 * XXX: this only works for UP
244 	 */
245 	if (stathz == 0) {
246 		profclock(usermode, pc);
247 		statclock(usermode);
248 	}
249 
250 #ifdef DEVICE_POLLING
251 	hardclock_device_poll();	/* this is very short and quick */
252 #endif /* DEVICE_POLLING */
253 
254 	/*
255 	 * Process callouts at a very low cpu priority, so we don't keep the
256 	 * relatively high clock interrupt priority any longer than necessary.
257 	 */
258 	mtx_lock_spin_flags(&callout_lock, MTX_QUIET);
259 	ticks++;
260 	if (!TAILQ_EMPTY(&callwheel[ticks & callwheelmask])) {
261 		need_softclock = 1;
262 	} else if (softticks + 1 == ticks)
263 		++softticks;
264 	mtx_unlock_spin_flags(&callout_lock, MTX_QUIET);
265 
266 	/*
267 	 * swi_sched acquires sched_lock, so we don't want to call it with
268 	 * callout_lock held; incorrect locking order.
269 	 */
270 	if (need_softclock)
271 		swi_sched(softclock_ih, 0);
272 
273 #ifdef SW_WATCHDOG
274 	if (watchdog_enabled > 0 && --watchdog_ticks <= 0)
275 		watchdog_fire();
276 #endif /* SW_WATCHDOG */
277 }
278 
279 /*
280  * Compute number of ticks in the specified amount of time.
281  */
282 int
283 tvtohz(tv)
284 	struct timeval *tv;
285 {
286 	register unsigned long ticks;
287 	register long sec, usec;
288 
289 	/*
290 	 * If the number of usecs in the whole seconds part of the time
291 	 * difference fits in a long, then the total number of usecs will
292 	 * fit in an unsigned long.  Compute the total and convert it to
293 	 * ticks, rounding up and adding 1 to allow for the current tick
294 	 * to expire.  Rounding also depends on unsigned long arithmetic
295 	 * to avoid overflow.
296 	 *
297 	 * Otherwise, if the number of ticks in the whole seconds part of
298 	 * the time difference fits in a long, then convert the parts to
299 	 * ticks separately and add, using similar rounding methods and
300 	 * overflow avoidance.  This method would work in the previous
301 	 * case but it is slightly slower and assumes that hz is integral.
302 	 *
303 	 * Otherwise, round the time difference down to the maximum
304 	 * representable value.
305 	 *
306 	 * If ints have 32 bits, then the maximum value for any timeout in
307 	 * 10ms ticks is 248 days.
308 	 */
309 	sec = tv->tv_sec;
310 	usec = tv->tv_usec;
311 	if (usec < 0) {
312 		sec--;
313 		usec += 1000000;
314 	}
315 	if (sec < 0) {
316 #ifdef DIAGNOSTIC
317 		if (usec > 0) {
318 			sec++;
319 			usec -= 1000000;
320 		}
321 		printf("tvotohz: negative time difference %ld sec %ld usec\n",
322 		       sec, usec);
323 #endif
324 		ticks = 1;
325 	} else if (sec <= LONG_MAX / 1000000)
326 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
327 			/ tick + 1;
328 	else if (sec <= LONG_MAX / hz)
329 		ticks = sec * hz
330 			+ ((unsigned long)usec + (tick - 1)) / tick + 1;
331 	else
332 		ticks = LONG_MAX;
333 	if (ticks > INT_MAX)
334 		ticks = INT_MAX;
335 	return ((int)ticks);
336 }
337 
338 /*
339  * Start profiling on a process.
340  *
341  * Kernel profiling passes proc0 which never exits and hence
342  * keeps the profile clock running constantly.
343  */
344 void
345 startprofclock(p)
346 	register struct proc *p;
347 {
348 
349 	/*
350 	 * XXX; Right now sched_lock protects statclock(), but perhaps
351 	 * it should be protected later on by a time_lock, which would
352 	 * cover psdiv, etc. as well.
353 	 */
354 	PROC_LOCK_ASSERT(p, MA_OWNED);
355 	if (p->p_flag & P_STOPPROF)
356 		return;
357 	if ((p->p_flag & P_PROFIL) == 0) {
358 		mtx_lock_spin(&sched_lock);
359 		p->p_flag |= P_PROFIL;
360 		if (++profprocs == 1)
361 			cpu_startprofclock();
362 		mtx_unlock_spin(&sched_lock);
363 	}
364 }
365 
366 /*
367  * Stop profiling on a process.
368  */
369 void
370 stopprofclock(p)
371 	register struct proc *p;
372 {
373 
374 	PROC_LOCK_ASSERT(p, MA_OWNED);
375 	if (p->p_flag & P_PROFIL) {
376 		if (p->p_profthreads != 0) {
377 			p->p_flag |= P_STOPPROF;
378 			while (p->p_profthreads != 0)
379 				msleep(&p->p_profthreads, &p->p_mtx, PPAUSE,
380 				    "stopprof", 0);
381 			p->p_flag &= ~P_STOPPROF;
382 		}
383 		if ((p->p_flag & P_PROFIL) == 0)
384 			return;
385 		mtx_lock_spin(&sched_lock);
386 		p->p_flag &= ~P_PROFIL;
387 		if (--profprocs == 0)
388 			cpu_stopprofclock();
389 		mtx_unlock_spin(&sched_lock);
390 	}
391 }
392 
393 /*
394  * Statistics clock.  Grab profile sample, and if divider reaches 0,
395  * do process and kernel statistics.  Most of the statistics are only
396  * used by user-level statistics programs.  The main exceptions are
397  * ke->ke_uticks, p->p_rux.rux_sticks, p->p_rux.rux_iticks, and p->p_estcpu.
398  * This should be called by all active processors.
399  */
400 void
401 statclock(int usermode)
402 {
403 	struct rusage *ru;
404 	struct vmspace *vm;
405 	struct thread *td;
406 	struct proc *p;
407 	long rss;
408 
409 	td = curthread;
410 	p = td->td_proc;
411 
412 	mtx_lock_spin_flags(&sched_lock, MTX_QUIET);
413 	if (usermode) {
414 		/*
415 		 * Charge the time as appropriate.
416 		 */
417 		if (p->p_flag & P_SA)
418 			thread_statclock(1);
419 		td->td_uticks++;
420 		if (p->p_nice > NZERO)
421 			cp_time[CP_NICE]++;
422 		else
423 			cp_time[CP_USER]++;
424 	} else {
425 		/*
426 		 * Came from kernel mode, so we were:
427 		 * - handling an interrupt,
428 		 * - doing syscall or trap work on behalf of the current
429 		 *   user process, or
430 		 * - spinning in the idle loop.
431 		 * Whichever it is, charge the time as appropriate.
432 		 * Note that we charge interrupts to the current process,
433 		 * regardless of whether they are ``for'' that process,
434 		 * so that we know how much of its real time was spent
435 		 * in ``non-process'' (i.e., interrupt) work.
436 		 */
437 		if ((td->td_pflags & TDP_ITHREAD) ||
438 		    td->td_intr_nesting_level >= 2) {
439 			td->td_iticks++;
440 			cp_time[CP_INTR]++;
441 		} else {
442 			if (p->p_flag & P_SA)
443 				thread_statclock(0);
444 			td->td_pticks++;
445 			td->td_sticks++;
446 			if (td != PCPU_GET(idlethread))
447 				cp_time[CP_SYS]++;
448 			else
449 				cp_time[CP_IDLE]++;
450 		}
451 	}
452 	CTR4(KTR_SCHED, "statclock: %p(%s) prio %d stathz %d",
453 	    td, td->td_proc->p_comm, td->td_priority, (stathz)?stathz:hz);
454 
455 	sched_clock(td);
456 
457 	/* Update resource usage integrals and maximums. */
458 	MPASS(p->p_stats != NULL);
459 	MPASS(p->p_vmspace != NULL);
460 	vm = p->p_vmspace;
461 	ru = &p->p_stats->p_ru;
462 	ru->ru_ixrss += pgtok(vm->vm_tsize);
463 	ru->ru_idrss += pgtok(vm->vm_dsize);
464 	ru->ru_isrss += pgtok(vm->vm_ssize);
465 	rss = pgtok(vmspace_resident_count(vm));
466 	if (ru->ru_maxrss < rss)
467 		ru->ru_maxrss = rss;
468 	mtx_unlock_spin_flags(&sched_lock, MTX_QUIET);
469 }
470 
471 void
472 profclock(int usermode, uintfptr_t pc)
473 {
474 	struct thread *td;
475 #ifdef GPROF
476 	struct gmonparam *g;
477 	uintfptr_t i;
478 #endif
479 
480 	td = curthread;
481 	if (usermode) {
482 		/*
483 		 * Came from user mode; CPU was in user state.
484 		 * If this process is being profiled, record the tick.
485 		 * if there is no related user location yet, don't
486 		 * bother trying to count it.
487 		 */
488 		if (td->td_proc->p_flag & P_PROFIL)
489 			addupc_intr(td, pc, 1);
490 	}
491 #ifdef GPROF
492 	else {
493 		/*
494 		 * Kernel statistics are just like addupc_intr, only easier.
495 		 */
496 		g = &_gmonparam;
497 		if (g->state == GMON_PROF_ON && pc >= g->lowpc) {
498 			i = PC_TO_I(g, pc);
499 			if (i < g->textsize) {
500 				KCOUNT(g, i)++;
501 			}
502 		}
503 	}
504 #endif
505 }
506 
507 /*
508  * Return information about system clocks.
509  */
510 static int
511 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
512 {
513 	struct clockinfo clkinfo;
514 	/*
515 	 * Construct clockinfo structure.
516 	 */
517 	bzero(&clkinfo, sizeof(clkinfo));
518 	clkinfo.hz = hz;
519 	clkinfo.tick = tick;
520 	clkinfo.profhz = profhz;
521 	clkinfo.stathz = stathz ? stathz : hz;
522 	return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
523 }
524 
525 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
526 	0, 0, sysctl_kern_clockrate, "S,clockinfo",
527 	"Rate and period of various kernel clocks");
528 
529 #ifdef SW_WATCHDOG
530 
531 static void
532 watchdog_config(void *unused __unused, u_int cmd, int *err)
533 {
534 	u_int u;
535 
536 	u = cmd & WD_INTERVAL;
537 	if ((cmd & WD_ACTIVE) && u >= WD_TO_1SEC) {
538 		watchdog_ticks = (1 << (u - WD_TO_1SEC)) * hz;
539 		watchdog_enabled = 1;
540 		*err = 0;
541 	} else {
542 		watchdog_enabled = 0;
543 	}
544 }
545 
546 /*
547  * Handle a watchdog timeout by dumping interrupt information and
548  * then either dropping to DDB or panicing.
549  */
550 static void
551 watchdog_fire(void)
552 {
553 	int nintr;
554 	u_int64_t inttotal;
555 	u_long *curintr;
556 	char *curname;
557 
558 	curintr = intrcnt;
559 	curname = intrnames;
560 	inttotal = 0;
561 	nintr = eintrcnt - intrcnt;
562 
563 	printf("interrupt                   total\n");
564 	while (--nintr >= 0) {
565 		if (*curintr)
566 			printf("%-12s %20lu\n", curname, *curintr);
567 		curname += strlen(curname) + 1;
568 		inttotal += *curintr++;
569 	}
570 	printf("Total        %20ju\n", (uintmax_t)inttotal);
571 
572 #ifdef KDB
573 	kdb_backtrace();
574 	kdb_enter("watchdog timeout");
575 #else
576 	panic("watchdog timeout");
577 #endif /* KDB */
578 }
579 
580 #endif /* SW_WATCHDOG */
581