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.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
34 * @(#)kern_clock.c 8.5 (Berkeley) 1/21/94
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
40 #include "opt_device_polling.h"
41 #include "opt_hwpmc_hooks.h"
43 #include "opt_watchdog.h"
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/callout.h>
49 #include <sys/kernel.h>
52 #include <sys/mutex.h>
54 #include <sys/resource.h>
55 #include <sys/resourcevar.h>
56 #include <sys/sched.h>
57 #include <sys/signalvar.h>
61 #include <vm/vm_map.h>
62 #include <sys/sysctl.h>
64 #include <sys/interrupt.h>
65 #include <sys/limits.h>
66 #include <sys/timetc.h>
73 #include <sys/pmckern.h>
77 extern void hardclock_device_poll(void);
78 #endif /* DEVICE_POLLING */
80 static void initclocks(void *dummy);
81 SYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL)
83 /* Some of these don't belong here, but it's easiest to concentrate them. */
84 long cp_time[CPUSTATES];
87 sysctl_kern_cp_time(SYSCTL_HANDLER_ARGS)
92 unsigned int cp_time32[CPUSTATES];
94 if (req->flags & SCTL_MASK32) {
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));
104 return SYSCTL_OUT(req, 0, sizeof(cp_time));
105 error = SYSCTL_OUT(req, cp_time, sizeof(cp_time));
110 SYSCTL_PROC(_kern, OID_AUTO, cp_time, CTLTYPE_LONG|CTLFLAG_RD,
111 0,0, sysctl_kern_cp_time, "LU", "CPU time statistics");
114 #include <sys/watchdog.h>
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 */
123 * Clock handling routines.
125 * This code is written to operate with two timers that run independently of
128 * The main timer, running hz times per second, is used to trigger interval
129 * timers, timeouts and rescheduling as needed.
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.
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.
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.
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.)
149 * Time-of-day is maintained using a "timecounter", which may or may
150 * not be related to the hardware generating the above mentioned
161 * Initialize clock frequencies and start both clocks running.
171 * Set divisors to 1 (normal case) and let the machine-specific
177 * Compute profhz/stathz, and fix profhz if needed.
179 i = stathz ? stathz : hz;
182 psratio = profhz / i;
184 EVENTHANDLER_REGISTER(watchdog_list, watchdog_config, NULL, 0);
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.
194 hardclock_cpu(int usermode)
196 struct pstats *pstats;
197 struct thread *td = curthread;
198 struct proc *p = td->td_proc;
201 * Run current process's virtual and profile time, as needed.
203 mtx_lock_spin_flags(&sched_lock, MTX_QUIET);
206 #if 0 /* for now do nothing */
207 if (p->p_flag & P_SA) {
208 /* XXXKSE What to do? Should do more. */
214 timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
215 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0) {
216 p->p_sflag |= PS_ALRMPEND;
217 td->td_flags |= TDF_ASTPENDING;
219 if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
220 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0) {
221 p->p_sflag |= PS_PROFPEND;
222 td->td_flags |= TDF_ASTPENDING;
224 mtx_unlock_spin_flags(&sched_lock, MTX_QUIET);
227 if (PMC_CPU_HAS_SAMPLES(PCPU_GET(cpuid)))
228 PMC_CALL_HOOK_UNLOCKED(curthread, PMC_FN_DO_SAMPLES, NULL);
233 * The real-time timer, interrupting hz times per second.
236 hardclock(int usermode, uintfptr_t pc)
238 int need_softclock = 0;
240 hardclock_cpu(usermode);
244 * If no separate statistics clock is available, run it from here.
246 * XXX: this only works for UP
249 profclock(usermode, pc);
253 #ifdef DEVICE_POLLING
254 hardclock_device_poll(); /* this is very short and quick */
255 #endif /* DEVICE_POLLING */
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.
261 mtx_lock_spin_flags(&callout_lock, MTX_QUIET);
263 if (!TAILQ_EMPTY(&callwheel[ticks & callwheelmask])) {
265 } else if (softticks + 1 == ticks)
267 mtx_unlock_spin_flags(&callout_lock, MTX_QUIET);
270 * swi_sched acquires sched_lock, so we don't want to call it with
271 * callout_lock held; incorrect locking order.
274 swi_sched(softclock_ih, 0);
277 if (watchdog_enabled > 0 && --watchdog_ticks <= 0)
279 #endif /* SW_WATCHDOG */
283 * Compute number of ticks in the specified amount of time.
289 register unsigned long ticks;
290 register long sec, usec;
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
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.
306 * Otherwise, round the time difference down to the maximum
307 * representable value.
309 * If ints have 32 bits, then the maximum value for any timeout in
310 * 10ms ticks is 248 days.
324 printf("tvotohz: negative time difference %ld sec %ld usec\n",
328 } else if (sec <= LONG_MAX / 1000000)
329 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
331 else if (sec <= LONG_MAX / hz)
333 + ((unsigned long)usec + (tick - 1)) / tick + 1;
342 * Start profiling on a process.
344 * Kernel profiling passes proc0 which never exits and hence
345 * keeps the profile clock running constantly.
349 register struct proc *p;
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.
357 PROC_LOCK_ASSERT(p, MA_OWNED);
358 if (p->p_flag & P_STOPPROF)
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);
370 * Stop profiling on a process.
374 register struct proc *p;
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,
384 p->p_flag &= ~P_STOPPROF;
386 if ((p->p_flag & P_PROFIL) == 0)
388 mtx_lock_spin(&sched_lock);
389 p->p_flag &= ~P_PROFIL;
390 if (--profprocs == 0)
392 mtx_unlock_spin(&sched_lock);
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.
404 statclock(int usermode)
415 mtx_lock_spin_flags(&sched_lock, MTX_QUIET);
418 * Charge the time as appropriate.
421 if (p->p_flag & P_SA)
425 if (p->p_nice > NZERO)
431 * Came from kernel mode, so we were:
432 * - handling an interrupt,
433 * - doing syscall or trap work on behalf of the current
435 * - spinning in the idle loop.
436 * Whichever it is, charge the time as appropriate.
437 * Note that we charge interrupts to the current process,
438 * regardless of whether they are ``for'' that process,
439 * so that we know how much of its real time was spent
440 * in ``non-process'' (i.e., interrupt) work.
442 if ((td->td_pflags & TDP_ITHREAD) ||
443 td->td_intr_nesting_level >= 2) {
448 if (p->p_flag & P_SA)
453 if (!TD_IS_IDLETHREAD(td))
459 CTR4(KTR_SCHED, "statclock: %p(%s) prio %d stathz %d",
460 td, td->td_proc->p_comm, td->td_priority, (stathz)?stathz:hz);
464 /* Update resource usage integrals and maximums. */
465 MPASS(p->p_stats != NULL);
466 MPASS(p->p_vmspace != NULL);
468 ru = &p->p_stats->p_ru;
469 ru->ru_ixrss += pgtok(vm->vm_tsize);
470 ru->ru_idrss += pgtok(vm->vm_dsize);
471 ru->ru_isrss += pgtok(vm->vm_ssize);
472 rss = pgtok(vmspace_resident_count(vm));
473 if (ru->ru_maxrss < rss)
475 mtx_unlock_spin_flags(&sched_lock, MTX_QUIET);
479 profclock(int usermode, uintfptr_t pc)
490 * Came from user mode; CPU was in user state.
491 * If this process is being profiled, record the tick.
492 * if there is no related user location yet, don't
493 * bother trying to count it.
495 if (td->td_proc->p_flag & P_PROFIL)
496 addupc_intr(td, pc, 1);
501 * Kernel statistics are just like addupc_intr, only easier.
504 if (g->state == GMON_PROF_ON && pc >= g->lowpc) {
506 if (i < g->textsize) {
515 * Return information about system clocks.
518 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
520 struct clockinfo clkinfo;
522 * Construct clockinfo structure.
524 bzero(&clkinfo, sizeof(clkinfo));
527 clkinfo.profhz = profhz;
528 clkinfo.stathz = stathz ? stathz : hz;
529 return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
532 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
533 0, 0, sysctl_kern_clockrate, "S,clockinfo",
534 "Rate and period of various kernel clocks");
539 watchdog_config(void *unused __unused, u_int cmd, int *error)
543 u = cmd & WD_INTERVAL;
544 if (u >= WD_TO_1SEC) {
545 watchdog_ticks = (1 << (u - WD_TO_1SEC)) * hz;
546 watchdog_enabled = 1;
549 watchdog_enabled = 0;
554 * Handle a watchdog timeout by dumping interrupt information and
555 * then either dropping to DDB or panicing.
568 nintr = eintrcnt - intrcnt;
570 printf("interrupt total\n");
571 while (--nintr >= 0) {
573 printf("%-12s %20lu\n", curname, *curintr);
574 curname += strlen(curname) + 1;
575 inttotal += *curintr++;
577 printf("Total %20ju\n", (uintmax_t)inttotal);
581 kdb_enter("watchdog timeout");
583 panic("watchdog timeout");
587 #endif /* SW_WATCHDOG */