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$");
41 #include "opt_device_polling.h"
42 #include "opt_hwpmc_hooks.h"
43 #include "opt_kdtrace.h"
45 #include "opt_watchdog.h"
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/callout.h>
51 #include <sys/kernel.h>
52 #include <sys/kthread.h>
55 #include <sys/mutex.h>
57 #include <sys/resource.h>
58 #include <sys/resourcevar.h>
59 #include <sys/sched.h>
61 #include <sys/signalvar.h>
62 #include <sys/sleepqueue.h>
66 #include <vm/vm_map.h>
67 #include <sys/sysctl.h>
69 #include <sys/interrupt.h>
70 #include <sys/limits.h>
71 #include <sys/timetc.h>
78 #include <sys/pmckern.h>
82 extern void hardclock_device_poll(void);
83 #endif /* DEVICE_POLLING */
85 static void initclocks(void *dummy);
86 SYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL);
88 /* Spin-lock protecting profiling statistics. */
89 static struct mtx time_lock;
91 SDT_PROVIDER_DECLARE(sched);
92 SDT_PROBE_DEFINE2(sched, , , tick, tick, "struct thread *", "struct proc *");
95 sysctl_kern_cp_time(SYSCTL_HANDLER_ARGS)
98 long cp_time[CPUSTATES];
101 unsigned int cp_time32[CPUSTATES];
104 read_cpu_time(cp_time);
106 if (req->flags & SCTL_MASK32) {
108 return SYSCTL_OUT(req, 0, sizeof(cp_time32));
109 for (i = 0; i < CPUSTATES; i++)
110 cp_time32[i] = (unsigned int)cp_time[i];
111 error = SYSCTL_OUT(req, cp_time32, sizeof(cp_time32));
116 return SYSCTL_OUT(req, 0, sizeof(cp_time));
117 error = SYSCTL_OUT(req, cp_time, sizeof(cp_time));
122 SYSCTL_PROC(_kern, OID_AUTO, cp_time, CTLTYPE_LONG|CTLFLAG_RD|CTLFLAG_MPSAFE,
123 0,0, sysctl_kern_cp_time, "LU", "CPU time statistics");
125 static long empty[CPUSTATES];
128 sysctl_kern_cp_times(SYSCTL_HANDLER_ARGS)
135 unsigned int cp_time32[CPUSTATES];
141 if (req->flags & SCTL_MASK32)
142 return SYSCTL_OUT(req, 0, sizeof(cp_time32) * (mp_maxid + 1));
145 return SYSCTL_OUT(req, 0, sizeof(long) * CPUSTATES * (mp_maxid + 1));
147 for (error = 0, c = 0; error == 0 && c <= mp_maxid; c++) {
148 if (!CPU_ABSENT(c)) {
150 cp_time = pcpu->pc_cp_time;
155 if (req->flags & SCTL_MASK32) {
156 for (i = 0; i < CPUSTATES; i++)
157 cp_time32[i] = (unsigned int)cp_time[i];
158 error = SYSCTL_OUT(req, cp_time32, sizeof(cp_time32));
161 error = SYSCTL_OUT(req, cp_time, sizeof(long) * CPUSTATES);
166 SYSCTL_PROC(_kern, OID_AUTO, cp_times, CTLTYPE_LONG|CTLFLAG_RD|CTLFLAG_MPSAFE,
167 0,0, sysctl_kern_cp_times, "LU", "per-CPU time statistics");
170 static const char *blessed[] = {
176 static int slptime_threshold = 1800;
177 static int blktime_threshold = 900;
178 static int sleepfreq = 3;
186 int blkticks, i, slpticks, slptype, tryl, tticks;
190 blkticks = blktime_threshold * hz;
191 slpticks = slptime_threshold * hz;
194 * Avoid to sleep on the sx_lock in order to avoid a possible
195 * priority inversion problem leading to starvation.
196 * If the lock can't be held after 100 tries, panic.
198 if (!sx_try_slock(&allproc_lock)) {
200 panic("%s: possible deadlock detected on allproc_lock\n",
203 pause("allproc", sleepfreq * hz);
207 FOREACH_PROC_IN_SYSTEM(p) {
209 if (p->p_state == PRS_NEW) {
213 FOREACH_THREAD_IN_PROC(p, td) {
216 * Once a thread is found in "interesting"
217 * state a possible ticks wrap-up needs to be
221 if (TD_ON_LOCK(td) && ticks < td->td_blktick) {
224 * The thread should be blocked on a
225 * turnstile, simply check if the
226 * turnstile channel is in good state.
228 MPASS(td->td_blocked != NULL);
230 tticks = ticks - td->td_blktick;
232 if (tticks > blkticks) {
235 * Accordingly with provided
236 * thresholds, this thread is
237 * stuck for too long on a
241 sx_sunlock(&allproc_lock);
242 panic("%s: possible deadlock detected for %p, blocked for %d ticks\n",
243 __func__, td, tticks);
245 } else if (TD_IS_SLEEPING(td) &&
247 ticks < td->td_blktick) {
250 * Check if the thread is sleeping on a
251 * lock, otherwise skip the check.
252 * Drop the thread lock in order to
253 * avoid a LOR with the sleepqueue
256 wchan = td->td_wchan;
257 tticks = ticks - td->td_slptick;
259 slptype = sleepq_type(wchan);
260 if ((slptype == SLEEPQ_SX ||
261 slptype == SLEEPQ_LK) &&
265 * Accordingly with provided
266 * thresholds, this thread is
267 * stuck for too long on a
269 * However, being on a
270 * sleepqueue, we might still
271 * check for the blessed
275 for (i = 0; blessed[i] != NULL;
277 if (!strcmp(blessed[i],
288 sx_sunlock(&allproc_lock);
289 panic("%s: possible deadlock detected for %p, blocked for %d ticks\n",
290 __func__, td, tticks);
297 sx_sunlock(&allproc_lock);
299 /* Sleep for sleepfreq seconds. */
300 pause("-", sleepfreq * hz);
304 static struct kthread_desc deadlkres_kd = {
307 (struct thread **)NULL
310 SYSINIT(deadlkres, SI_SUB_CLOCKS, SI_ORDER_ANY, kthread_start, &deadlkres_kd);
312 SYSCTL_NODE(_debug, OID_AUTO, deadlkres, CTLFLAG_RW, 0, "Deadlock resolver");
313 SYSCTL_INT(_debug_deadlkres, OID_AUTO, slptime_threshold, CTLFLAG_RW,
314 &slptime_threshold, 0,
315 "Number of seconds within is valid to sleep on a sleepqueue");
316 SYSCTL_INT(_debug_deadlkres, OID_AUTO, blktime_threshold, CTLFLAG_RW,
317 &blktime_threshold, 0,
318 "Number of seconds within is valid to block on a turnstile");
319 SYSCTL_INT(_debug_deadlkres, OID_AUTO, sleepfreq, CTLFLAG_RW, &sleepfreq, 0,
320 "Number of seconds between any deadlock resolver thread run");
321 #endif /* DEADLKRES */
324 read_cpu_time(long *cp_time)
329 /* Sum up global cp_time[]. */
330 bzero(cp_time, sizeof(long) * CPUSTATES);
333 for (j = 0; j < CPUSTATES; j++)
334 cp_time[j] += pc->pc_cp_time[j];
339 #include <sys/watchdog.h>
341 static int watchdog_ticks;
342 static int watchdog_enabled;
343 static void watchdog_fire(void);
344 static void watchdog_config(void *, u_int, int *);
345 #endif /* SW_WATCHDOG */
348 * Clock handling routines.
350 * This code is written to operate with two timers that run independently of
353 * The main timer, running hz times per second, is used to trigger interval
354 * timers, timeouts and rescheduling as needed.
356 * The second timer handles kernel and user profiling,
357 * and does resource use estimation. If the second timer is programmable,
358 * it is randomized to avoid aliasing between the two clocks. For example,
359 * the randomization prevents an adversary from always giving up the cpu
360 * just before its quantum expires. Otherwise, it would never accumulate
361 * cpu ticks. The mean frequency of the second timer is stathz.
363 * If no second timer exists, stathz will be zero; in this case we drive
364 * profiling and statistics off the main clock. This WILL NOT be accurate;
365 * do not do it unless absolutely necessary.
367 * The statistics clock may (or may not) be run at a higher rate while
368 * profiling. This profile clock runs at profhz. We require that profhz
369 * be an integral multiple of stathz.
371 * If the statistics clock is running fast, it must be divided by the ratio
372 * profhz/stathz for statistics. (For profiling, every tick counts.)
374 * Time-of-day is maintained using a "timecounter", which may or may
375 * not be related to the hardware generating the above mentioned
386 * Initialize clock frequencies and start both clocks running.
396 * Set divisors to 1 (normal case) and let the machine-specific
399 mtx_init(&time_lock, "time lock", NULL, MTX_SPIN);
403 * Compute profhz/stathz, and fix profhz if needed.
405 i = stathz ? stathz : hz;
408 psratio = profhz / i;
410 EVENTHANDLER_REGISTER(watchdog_list, watchdog_config, NULL, 0);
415 * Each time the real-time timer fires, this function is called on all CPUs.
416 * Note that hardclock() calls hardclock_cpu() for the boot CPU, so only
417 * the other CPUs in the system need to call this function.
420 hardclock_cpu(int usermode)
422 struct pstats *pstats;
423 struct thread *td = curthread;
424 struct proc *p = td->td_proc;
428 * Run current process's virtual and profile time, as needed.
433 timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value)) {
435 if (itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
436 flags |= TDF_ALRMPEND | TDF_ASTPENDING;
439 if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value)) {
441 if (itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
442 flags |= TDF_PROFPEND | TDF_ASTPENDING;
447 td->td_flags |= flags;
451 if (PMC_CPU_HAS_SAMPLES(PCPU_GET(cpuid)))
452 PMC_CALL_HOOK_UNLOCKED(curthread, PMC_FN_DO_SAMPLES, NULL);
458 * The real-time timer, interrupting hz times per second.
461 hardclock(int usermode, uintfptr_t pc)
464 atomic_add_int(&ticks, 1);
465 hardclock_cpu(usermode);
468 * If no separate statistics clock is available, run it from here.
470 * XXX: this only works for UP
473 profclock(usermode, pc);
476 #ifdef DEVICE_POLLING
477 hardclock_device_poll(); /* this is very short and quick */
478 #endif /* DEVICE_POLLING */
480 if (watchdog_enabled > 0 && --watchdog_ticks <= 0)
482 #endif /* SW_WATCHDOG */
486 * Compute number of ticks in the specified amount of time.
492 register unsigned long ticks;
493 register long sec, usec;
496 * If the number of usecs in the whole seconds part of the time
497 * difference fits in a long, then the total number of usecs will
498 * fit in an unsigned long. Compute the total and convert it to
499 * ticks, rounding up and adding 1 to allow for the current tick
500 * to expire. Rounding also depends on unsigned long arithmetic
503 * Otherwise, if the number of ticks in the whole seconds part of
504 * the time difference fits in a long, then convert the parts to
505 * ticks separately and add, using similar rounding methods and
506 * overflow avoidance. This method would work in the previous
507 * case but it is slightly slower and assumes that hz is integral.
509 * Otherwise, round the time difference down to the maximum
510 * representable value.
512 * If ints have 32 bits, then the maximum value for any timeout in
513 * 10ms ticks is 248 days.
527 printf("tvotohz: negative time difference %ld sec %ld usec\n",
531 } else if (sec <= LONG_MAX / 1000000)
532 ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
534 else if (sec <= LONG_MAX / hz)
536 + ((unsigned long)usec + (tick - 1)) / tick + 1;
545 * Start profiling on a process.
547 * Kernel profiling passes proc0 which never exits and hence
548 * keeps the profile clock running constantly.
552 register struct proc *p;
555 PROC_LOCK_ASSERT(p, MA_OWNED);
556 if (p->p_flag & P_STOPPROF)
558 if ((p->p_flag & P_PROFIL) == 0) {
559 p->p_flag |= P_PROFIL;
560 mtx_lock_spin(&time_lock);
561 if (++profprocs == 1)
562 cpu_startprofclock();
563 mtx_unlock_spin(&time_lock);
568 * Stop profiling on a process.
572 register struct proc *p;
575 PROC_LOCK_ASSERT(p, MA_OWNED);
576 if (p->p_flag & P_PROFIL) {
577 if (p->p_profthreads != 0) {
578 p->p_flag |= P_STOPPROF;
579 while (p->p_profthreads != 0)
580 msleep(&p->p_profthreads, &p->p_mtx, PPAUSE,
582 p->p_flag &= ~P_STOPPROF;
584 if ((p->p_flag & P_PROFIL) == 0)
586 p->p_flag &= ~P_PROFIL;
587 mtx_lock_spin(&time_lock);
588 if (--profprocs == 0)
590 mtx_unlock_spin(&time_lock);
595 * Statistics clock. Updates rusage information and calls the scheduler
596 * to adjust priorities of the active thread.
598 * This should be called by all active processors.
601 statclock(int usermode)
613 cp_time = (long *)PCPU_PTR(cp_time);
616 * Charge the time as appropriate.
619 if (p->p_nice > NZERO)
625 * Came from kernel mode, so we were:
626 * - handling an interrupt,
627 * - doing syscall or trap work on behalf of the current
629 * - spinning in the idle loop.
630 * Whichever it is, charge the time as appropriate.
631 * Note that we charge interrupts to the current process,
632 * regardless of whether they are ``for'' that process,
633 * so that we know how much of its real time was spent
634 * in ``non-process'' (i.e., interrupt) work.
636 if ((td->td_pflags & TDP_ITHREAD) ||
637 td->td_intr_nesting_level >= 2) {
643 if (!TD_IS_IDLETHREAD(td))
650 /* Update resource usage integrals and maximums. */
651 MPASS(p->p_vmspace != NULL);
654 ru->ru_ixrss += pgtok(vm->vm_tsize);
655 ru->ru_idrss += pgtok(vm->vm_dsize);
656 ru->ru_isrss += pgtok(vm->vm_ssize);
657 rss = pgtok(vmspace_resident_count(vm));
658 if (ru->ru_maxrss < rss)
660 KTR_POINT2(KTR_SCHED, "thread", sched_tdname(td), "statclock",
661 "prio:%d", td->td_priority, "stathz:%d", (stathz)?stathz:hz);
662 SDT_PROBE2(sched, , , tick, td, td->td_proc);
663 thread_lock_flags(td, MTX_QUIET);
669 profclock(int usermode, uintfptr_t pc)
680 * Came from user mode; CPU was in user state.
681 * If this process is being profiled, record the tick.
682 * if there is no related user location yet, don't
683 * bother trying to count it.
685 if (td->td_proc->p_flag & P_PROFIL)
686 addupc_intr(td, pc, 1);
691 * Kernel statistics are just like addupc_intr, only easier.
694 if (g->state == GMON_PROF_ON && pc >= g->lowpc) {
696 if (i < g->textsize) {
705 * Return information about system clocks.
708 sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
710 struct clockinfo clkinfo;
712 * Construct clockinfo structure.
714 bzero(&clkinfo, sizeof(clkinfo));
717 clkinfo.profhz = profhz;
718 clkinfo.stathz = stathz ? stathz : hz;
719 return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
722 SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate,
723 CTLTYPE_STRUCT|CTLFLAG_RD|CTLFLAG_MPSAFE,
724 0, 0, sysctl_kern_clockrate, "S,clockinfo",
725 "Rate and period of various kernel clocks");
730 watchdog_config(void *unused __unused, u_int cmd, int *error)
734 u = cmd & WD_INTERVAL;
735 if (u >= WD_TO_1SEC) {
736 watchdog_ticks = (1 << (u - WD_TO_1SEC)) * hz;
737 watchdog_enabled = 1;
740 watchdog_enabled = 0;
745 * Handle a watchdog timeout by dumping interrupt information and
746 * then either dropping to DDB or panicking.
759 nintr = eintrcnt - intrcnt;
761 printf("interrupt total\n");
762 while (--nintr >= 0) {
764 printf("%-12s %20lu\n", curname, *curintr);
765 curname += strlen(curname) + 1;
766 inttotal += *curintr++;
768 printf("Total %20ju\n", (uintmax_t)inttotal);
770 #if defined(KDB) && !defined(KDB_UNATTENDED)
772 kdb_enter(KDB_WHY_WATCHDOG, "watchdog timeout");
774 panic("watchdog timeout");
778 #endif /* SW_WATCHDOG */