xref: /freebsd/sys/kern/kern_clock.c (revision 6b82130e6c9add4a8892ca897df5a0ec04663ea2)
1df8bae1dSRodney W. Grimes /*-
251369649SPedro F. Giffuni  * SPDX-License-Identifier: BSD-3-Clause
351369649SPedro F. Giffuni  *
4df8bae1dSRodney W. Grimes  * Copyright (c) 1982, 1986, 1991, 1993
5df8bae1dSRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
6df8bae1dSRodney W. Grimes  * (c) UNIX System Laboratories, Inc.
7df8bae1dSRodney W. Grimes  * All or some portions of this file are derived from material licensed
8df8bae1dSRodney W. Grimes  * to the University of California by American Telephone and Telegraph
9df8bae1dSRodney W. Grimes  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10df8bae1dSRodney W. Grimes  * the permission of UNIX System Laboratories, Inc.
11df8bae1dSRodney W. Grimes  *
12df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
13df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
14df8bae1dSRodney W. Grimes  * are met:
15df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
16df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
17df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
18df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
19df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
2069a28758SEd Maste  * 3. Neither the name of the University nor the names of its contributors
21df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
22df8bae1dSRodney W. Grimes  *    without specific prior written permission.
23df8bae1dSRodney W. Grimes  *
24df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
35df8bae1dSRodney W. Grimes  */
36df8bae1dSRodney W. Grimes 
37677b542eSDavid E. O'Brien #include <sys/cdefs.h>
38911d16b8SEd Maste #include "opt_kdb.h"
39f0796cd2SGleb Smirnoff #include "opt_device_polling.h"
404da0d332SPeter Wemm #include "opt_hwpmc_hooks.h"
4132c20357SPoul-Henning Kamp #include "opt_ntp.h"
42370c3cb5SSean Kelly #include "opt_watchdog.h"
4332c20357SPoul-Henning Kamp 
44df8bae1dSRodney W. Grimes #include <sys/param.h>
45df8bae1dSRodney W. Grimes #include <sys/systm.h>
46df8bae1dSRodney W. Grimes #include <sys/callout.h>
47c4d901e9SMatt Macy #include <sys/epoch.h>
48e2e050c8SConrad Meyer #include <sys/eventhandler.h>
49a5f10424SMatt Macy #include <sys/gtaskqueue.h>
502d50560aSMarcel Moolenaar #include <sys/kdb.h>
51df8bae1dSRodney W. Grimes #include <sys/kernel.h>
52f7829d0dSAttilio Rao #include <sys/kthread.h>
5361d80e90SJohn Baldwin #include <sys/ktr.h>
54f7829d0dSAttilio Rao #include <sys/lock.h>
5535e0e5b3SJohn Baldwin #include <sys/mutex.h>
56df8bae1dSRodney W. Grimes #include <sys/proc.h>
57e4625663SJeff Roberson #include <sys/resource.h>
58df8bae1dSRodney W. Grimes #include <sys/resourcevar.h>
59b43179fbSJeff Roberson #include <sys/sched.h>
60b3e9e682SRyan Stone #include <sys/sdt.h>
61797f2d22SPoul-Henning Kamp #include <sys/signalvar.h>
62f7829d0dSAttilio Rao #include <sys/sleepqueue.h>
636caa8a15SJohn Baldwin #include <sys/smp.h>
648a129caeSDavid Greenman #include <vm/vm.h>
65efeaf95aSDavid Greenman #include <vm/pmap.h>
66efeaf95aSDavid Greenman #include <vm/vm_map.h>
67797f2d22SPoul-Henning Kamp #include <sys/sysctl.h>
688088699fSJohn Baldwin #include <sys/bus.h>
698088699fSJohn Baldwin #include <sys/interrupt.h>
70104a9b7eSAlexander Kabaev #include <sys/limits.h>
71e7fa55afSPoul-Henning Kamp #include <sys/timetc.h>
72df8bae1dSRodney W. Grimes 
7336c0fd9dSJoseph Koshy #ifdef HWPMC_HOOKS
7436c0fd9dSJoseph Koshy #include <sys/pmckern.h>
75f5f9340bSFabien Thomas PMC_SOFT_DEFINE( , , clock, hard);
76f5f9340bSFabien Thomas PMC_SOFT_DEFINE( , , clock, stat);
77d49302aeSFabien Thomas PMC_SOFT_DEFINE_EX( , , clock, prof, \
78d49302aeSFabien Thomas     cpu_startprofclock, cpu_stopprofclock);
7936c0fd9dSJoseph Koshy #endif
8036c0fd9dSJoseph Koshy 
81e4fc250cSLuigi Rizzo #ifdef DEVICE_POLLING
82e4fc250cSLuigi Rizzo extern void hardclock_device_poll(void);
83e4fc250cSLuigi Rizzo #endif /* DEVICE_POLLING */
84eae8fc2cSSteve Passe 
858b98fec9SJeff Roberson /* Spin-lock protecting profiling statistics. */
8686a49deaSAttilio Rao static struct mtx time_lock;
878b98fec9SJeff Roberson 
88b3e9e682SRyan Stone SDT_PROVIDER_DECLARE(sched);
89d9fae5abSAndriy Gapon SDT_PROBE_DEFINE2(sched, , , tick, "struct thread *", "struct proc *");
90b3e9e682SRyan Stone 
9162919d78SPeter Wemm static int
sysctl_kern_cp_time(SYSCTL_HANDLER_ARGS)9262919d78SPeter Wemm sysctl_kern_cp_time(SYSCTL_HANDLER_ARGS)
9362919d78SPeter Wemm {
9462919d78SPeter Wemm 	int error;
957628402bSPeter Wemm 	long cp_time[CPUSTATES];
96cff2e749SPaul Saab #ifdef SCTL_MASK32
9762919d78SPeter Wemm 	int i;
9862919d78SPeter Wemm 	unsigned int cp_time32[CPUSTATES];
997628402bSPeter Wemm #endif
10062919d78SPeter Wemm 
1017628402bSPeter Wemm 	read_cpu_time(cp_time);
1027628402bSPeter Wemm #ifdef SCTL_MASK32
103cff2e749SPaul Saab 	if (req->flags & SCTL_MASK32) {
10462919d78SPeter Wemm 		if (!req->oldptr)
10562919d78SPeter Wemm 			return SYSCTL_OUT(req, 0, sizeof(cp_time32));
10662919d78SPeter Wemm 		for (i = 0; i < CPUSTATES; i++)
10762919d78SPeter Wemm 			cp_time32[i] = (unsigned int)cp_time[i];
10862919d78SPeter Wemm 		error = SYSCTL_OUT(req, cp_time32, sizeof(cp_time32));
10962919d78SPeter Wemm 	} else
11062919d78SPeter Wemm #endif
11162919d78SPeter Wemm 	{
11262919d78SPeter Wemm 		if (!req->oldptr)
11362919d78SPeter Wemm 			return SYSCTL_OUT(req, 0, sizeof(cp_time));
11462919d78SPeter Wemm 		error = SYSCTL_OUT(req, cp_time, sizeof(cp_time));
11562919d78SPeter Wemm 	}
11662919d78SPeter Wemm 	return error;
11762919d78SPeter Wemm }
11862919d78SPeter Wemm 
119c383c221SEd Schouten SYSCTL_PROC(_kern, OID_AUTO, cp_time, CTLTYPE_LONG|CTLFLAG_RD|CTLFLAG_MPSAFE,
12062919d78SPeter Wemm     0,0, sysctl_kern_cp_time, "LU", "CPU time statistics");
1217f112b04SRobert Watson 
1227628402bSPeter Wemm static long empty[CPUSTATES];
1237628402bSPeter Wemm 
1247628402bSPeter Wemm static int
sysctl_kern_cp_times(SYSCTL_HANDLER_ARGS)1257628402bSPeter Wemm sysctl_kern_cp_times(SYSCTL_HANDLER_ARGS)
1267628402bSPeter Wemm {
1277628402bSPeter Wemm 	struct pcpu *pcpu;
1287628402bSPeter Wemm 	int error;
129ef54068bSRobert Watson 	int c;
1307628402bSPeter Wemm 	long *cp_time;
1317628402bSPeter Wemm #ifdef SCTL_MASK32
1327628402bSPeter Wemm 	unsigned int cp_time32[CPUSTATES];
133ef54068bSRobert Watson 	int i;
1347628402bSPeter Wemm #endif
1357628402bSPeter Wemm 
1367628402bSPeter Wemm 	if (!req->oldptr) {
1377628402bSPeter Wemm #ifdef SCTL_MASK32
1387628402bSPeter Wemm 		if (req->flags & SCTL_MASK32)
1397628402bSPeter Wemm 			return SYSCTL_OUT(req, 0, sizeof(cp_time32) * (mp_maxid + 1));
1407628402bSPeter Wemm 		else
1417628402bSPeter Wemm #endif
1427628402bSPeter Wemm 			return SYSCTL_OUT(req, 0, sizeof(long) * CPUSTATES * (mp_maxid + 1));
1437628402bSPeter Wemm 	}
1447628402bSPeter Wemm 	for (error = 0, c = 0; error == 0 && c <= mp_maxid; c++) {
1457628402bSPeter Wemm 		if (!CPU_ABSENT(c)) {
1467628402bSPeter Wemm 			pcpu = pcpu_find(c);
1477628402bSPeter Wemm 			cp_time = pcpu->pc_cp_time;
1487628402bSPeter Wemm 		} else {
1497628402bSPeter Wemm 			cp_time = empty;
1507628402bSPeter Wemm 		}
1517628402bSPeter Wemm #ifdef SCTL_MASK32
1527628402bSPeter Wemm 		if (req->flags & SCTL_MASK32) {
1537628402bSPeter Wemm 			for (i = 0; i < CPUSTATES; i++)
1547628402bSPeter Wemm 				cp_time32[i] = (unsigned int)cp_time[i];
1557628402bSPeter Wemm 			error = SYSCTL_OUT(req, cp_time32, sizeof(cp_time32));
1567628402bSPeter Wemm 		} else
1577628402bSPeter Wemm #endif
1587628402bSPeter Wemm 			error = SYSCTL_OUT(req, cp_time, sizeof(long) * CPUSTATES);
1597628402bSPeter Wemm 	}
1607628402bSPeter Wemm 	return error;
1617628402bSPeter Wemm }
1627628402bSPeter Wemm 
163c383c221SEd Schouten SYSCTL_PROC(_kern, OID_AUTO, cp_times, CTLTYPE_LONG|CTLFLAG_RD|CTLFLAG_MPSAFE,
1647628402bSPeter Wemm     0,0, sysctl_kern_cp_times, "LU", "per-CPU time statistics");
1657628402bSPeter Wemm 
166f7829d0dSAttilio Rao #ifdef DEADLKRES
16736e51f65SAttilio Rao static const char *blessed[] = {
16895335fd8SAttilio Rao 	"getblk",
16936e51f65SAttilio Rao 	"so_snd_sx",
17036e51f65SAttilio Rao 	"so_rcv_sx",
17136e51f65SAttilio Rao 	NULL
17236e51f65SAttilio Rao };
173f7829d0dSAttilio Rao static int slptime_threshold = 1800;
174f7829d0dSAttilio Rao static int blktime_threshold = 900;
175f7829d0dSAttilio Rao static int sleepfreq = 3;
176f7829d0dSAttilio Rao 
177f7829d0dSAttilio Rao static void
deadlres_td_on_lock(struct proc * p,struct thread * td,int blkticks)1781534cd19SBjoern A. Zeeb deadlres_td_on_lock(struct proc *p, struct thread *td, int blkticks)
1791534cd19SBjoern A. Zeeb {
1801534cd19SBjoern A. Zeeb 	int tticks;
1811534cd19SBjoern A. Zeeb 
1821534cd19SBjoern A. Zeeb 	sx_assert(&allproc_lock, SX_LOCKED);
1831534cd19SBjoern A. Zeeb 	PROC_LOCK_ASSERT(p, MA_OWNED);
1841534cd19SBjoern A. Zeeb 	THREAD_LOCK_ASSERT(td, MA_OWNED);
1851534cd19SBjoern A. Zeeb 	/*
1861534cd19SBjoern A. Zeeb 	 * The thread should be blocked on a turnstile, simply check
1871534cd19SBjoern A. Zeeb 	 * if the turnstile channel is in good state.
1881534cd19SBjoern A. Zeeb 	 */
1891534cd19SBjoern A. Zeeb 	MPASS(td->td_blocked != NULL);
1901534cd19SBjoern A. Zeeb 
1911534cd19SBjoern A. Zeeb 	tticks = ticks - td->td_blktick;
1921534cd19SBjoern A. Zeeb 	if (tticks > blkticks)
1931534cd19SBjoern A. Zeeb 		/*
1941534cd19SBjoern A. Zeeb 		 * Accordingly with provided thresholds, this thread is stuck
1951534cd19SBjoern A. Zeeb 		 * for too long on a turnstile.
1961534cd19SBjoern A. Zeeb 		 */
1978abaf6a7SJason A. Harmening 		panic("%s: possible deadlock detected for %p (%s), "
1988abaf6a7SJason A. Harmening 		    "blocked for %d ticks\n", __func__,
1998abaf6a7SJason A. Harmening 		    td, sched_tdname(td), tticks);
2001534cd19SBjoern A. Zeeb }
2011534cd19SBjoern A. Zeeb 
2021534cd19SBjoern A. Zeeb static void
deadlres_td_sleep_q(struct proc * p,struct thread * td,int slpticks)2031534cd19SBjoern A. Zeeb deadlres_td_sleep_q(struct proc *p, struct thread *td, int slpticks)
2041534cd19SBjoern A. Zeeb {
205fea73412SConrad Meyer 	const void *wchan;
2061534cd19SBjoern A. Zeeb 	int i, slptype, tticks;
2071534cd19SBjoern A. Zeeb 
2081534cd19SBjoern A. Zeeb 	sx_assert(&allproc_lock, SX_LOCKED);
2091534cd19SBjoern A. Zeeb 	PROC_LOCK_ASSERT(p, MA_OWNED);
2101534cd19SBjoern A. Zeeb 	THREAD_LOCK_ASSERT(td, MA_OWNED);
2111534cd19SBjoern A. Zeeb 	/*
2121534cd19SBjoern A. Zeeb 	 * Check if the thread is sleeping on a lock, otherwise skip the check.
2131534cd19SBjoern A. Zeeb 	 * Drop the thread lock in order to avoid a LOR with the sleepqueue
2141534cd19SBjoern A. Zeeb 	 * spinlock.
2151534cd19SBjoern A. Zeeb 	 */
2161534cd19SBjoern A. Zeeb 	wchan = td->td_wchan;
2171534cd19SBjoern A. Zeeb 	tticks = ticks - td->td_slptick;
2181534cd19SBjoern A. Zeeb 	slptype = sleepq_type(wchan);
2191534cd19SBjoern A. Zeeb 	if ((slptype == SLEEPQ_SX || slptype == SLEEPQ_LK) &&
2201534cd19SBjoern A. Zeeb 	    tticks > slpticks) {
2211534cd19SBjoern A. Zeeb 		/*
2221534cd19SBjoern A. Zeeb 		 * Accordingly with provided thresholds, this thread is stuck
2231534cd19SBjoern A. Zeeb 		 * for too long on a sleepqueue.
2241534cd19SBjoern A. Zeeb 		 * However, being on a sleepqueue, we might still check for the
2251534cd19SBjoern A. Zeeb 		 * blessed list.
2261534cd19SBjoern A. Zeeb 		 */
2271534cd19SBjoern A. Zeeb 		for (i = 0; blessed[i] != NULL; i++)
2281534cd19SBjoern A. Zeeb 			if (!strcmp(blessed[i], td->td_wmesg))
2291534cd19SBjoern A. Zeeb 				return;
2301534cd19SBjoern A. Zeeb 
2318abaf6a7SJason A. Harmening 		panic("%s: possible deadlock detected for %p (%s), "
2328abaf6a7SJason A. Harmening 		    "blocked for %d ticks\n", __func__,
2338abaf6a7SJason A. Harmening 		    td, sched_tdname(td), tticks);
2341534cd19SBjoern A. Zeeb 	}
2351534cd19SBjoern A. Zeeb }
2361534cd19SBjoern A. Zeeb 
2371534cd19SBjoern A. Zeeb static void
deadlkres(void)238f7829d0dSAttilio Rao deadlkres(void)
239f7829d0dSAttilio Rao {
240f7829d0dSAttilio Rao 	struct proc *p;
241f7829d0dSAttilio Rao 	struct thread *td;
2421534cd19SBjoern A. Zeeb 	int blkticks, slpticks, tryl;
243f7829d0dSAttilio Rao 
244f7829d0dSAttilio Rao 	tryl = 0;
245f7829d0dSAttilio Rao 	for (;;) {
246f7829d0dSAttilio Rao 		blkticks = blktime_threshold * hz;
247f7829d0dSAttilio Rao 		slpticks = slptime_threshold * hz;
248f7829d0dSAttilio Rao 
249f7829d0dSAttilio Rao 		/*
2501534cd19SBjoern A. Zeeb 		 * Avoid to sleep on the sx_lock in order to avoid a
2511534cd19SBjoern A. Zeeb 		 * possible priority inversion problem leading to
2521534cd19SBjoern A. Zeeb 		 * starvation.
253f7829d0dSAttilio Rao 		 * If the lock can't be held after 100 tries, panic.
254f7829d0dSAttilio Rao 		 */
255f7829d0dSAttilio Rao 		if (!sx_try_slock(&allproc_lock)) {
256f7829d0dSAttilio Rao 			if (tryl > 100)
2571534cd19SBjoern A. Zeeb 				panic("%s: possible deadlock detected "
2581534cd19SBjoern A. Zeeb 				    "on allproc_lock\n", __func__);
259f7829d0dSAttilio Rao 			tryl++;
260b5850804SJohn Baldwin 			pause("allproc", sleepfreq * hz);
261f7829d0dSAttilio Rao 			continue;
262f7829d0dSAttilio Rao 		}
263f7829d0dSAttilio Rao 		tryl = 0;
264f7829d0dSAttilio Rao 		FOREACH_PROC_IN_SYSTEM(p) {
265f7829d0dSAttilio Rao 			PROC_LOCK(p);
266e806d352SJohn Baldwin 			if (p->p_state == PRS_NEW) {
267e806d352SJohn Baldwin 				PROC_UNLOCK(p);
268e806d352SJohn Baldwin 				continue;
269e806d352SJohn Baldwin 			}
270f7829d0dSAttilio Rao 			FOREACH_THREAD_IN_PROC(p, td) {
271f7829d0dSAttilio Rao 				thread_lock(td);
2721534cd19SBjoern A. Zeeb 				if (TD_ON_LOCK(td))
2731534cd19SBjoern A. Zeeb 					deadlres_td_on_lock(p, td,
2741534cd19SBjoern A. Zeeb 					    blkticks);
27561a74c5cSJeff Roberson 				else if (TD_IS_SLEEPING(td))
2761534cd19SBjoern A. Zeeb 					deadlres_td_sleep_q(p, td,
2771534cd19SBjoern A. Zeeb 					    slpticks);
278f7829d0dSAttilio Rao 				thread_unlock(td);
279f7829d0dSAttilio Rao 			}
280f7829d0dSAttilio Rao 			PROC_UNLOCK(p);
281f7829d0dSAttilio Rao 		}
282f7829d0dSAttilio Rao 		sx_sunlock(&allproc_lock);
283f7829d0dSAttilio Rao 
284f7829d0dSAttilio Rao 		/* Sleep for sleepfreq seconds. */
285b5850804SJohn Baldwin 		pause("-", sleepfreq * hz);
286f7829d0dSAttilio Rao 	}
287f7829d0dSAttilio Rao }
288f7829d0dSAttilio Rao 
289f7829d0dSAttilio Rao static struct kthread_desc deadlkres_kd = {
290f7829d0dSAttilio Rao 	"deadlkres",
291f7829d0dSAttilio Rao 	deadlkres,
292f7829d0dSAttilio Rao 	(struct thread **)NULL
293f7829d0dSAttilio Rao };
294f7829d0dSAttilio Rao 
295f7829d0dSAttilio Rao SYSINIT(deadlkres, SI_SUB_CLOCKS, SI_ORDER_ANY, kthread_start, &deadlkres_kd);
296f7829d0dSAttilio Rao 
2977029da5cSPawel Biernacki static SYSCTL_NODE(_debug, OID_AUTO, deadlkres, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
2986472ac3dSEd Schouten     "Deadlock resolver");
29983160177SMark Johnston SYSCTL_INT(_debug_deadlkres, OID_AUTO, slptime_threshold, CTLFLAG_RWTUN,
300f7829d0dSAttilio Rao     &slptime_threshold, 0,
301f7829d0dSAttilio Rao     "Number of seconds within is valid to sleep on a sleepqueue");
30283160177SMark Johnston SYSCTL_INT(_debug_deadlkres, OID_AUTO, blktime_threshold, CTLFLAG_RWTUN,
303f7829d0dSAttilio Rao     &blktime_threshold, 0,
304f7829d0dSAttilio Rao     "Number of seconds within is valid to block on a turnstile");
30583160177SMark Johnston SYSCTL_INT(_debug_deadlkres, OID_AUTO, sleepfreq, CTLFLAG_RWTUN, &sleepfreq, 0,
306f7829d0dSAttilio Rao     "Number of seconds between any deadlock resolver thread run");
307f7829d0dSAttilio Rao #endif	/* DEADLKRES */
308f7829d0dSAttilio Rao 
3097628402bSPeter Wemm void
read_cpu_time(long * cp_time)3107628402bSPeter Wemm read_cpu_time(long *cp_time)
3117628402bSPeter Wemm {
3127628402bSPeter Wemm 	struct pcpu *pc;
3137628402bSPeter Wemm 	int i, j;
3147628402bSPeter Wemm 
3157628402bSPeter Wemm 	/* Sum up global cp_time[]. */
3167628402bSPeter Wemm 	bzero(cp_time, sizeof(long) * CPUSTATES);
3173aa6d94eSJohn Baldwin 	CPU_FOREACH(i) {
3187628402bSPeter Wemm 		pc = pcpu_find(i);
3197628402bSPeter Wemm 		for (j = 0; j < CPUSTATES; j++)
3207628402bSPeter Wemm 			cp_time[j] += pc->pc_cp_time[j];
3217628402bSPeter Wemm 	}
3227628402bSPeter Wemm }
3237628402bSPeter Wemm 
3244103b765SPoul-Henning Kamp #include <sys/watchdog.h>
325370c3cb5SSean Kelly 
326*6b82130eSMark Johnston static long watchdog_ticks;
327370c3cb5SSean Kelly static int watchdog_enabled;
3284103b765SPoul-Henning Kamp static void watchdog_fire(void);
3294103b765SPoul-Henning Kamp static void watchdog_config(void *, u_int, int *);
330d626b50bSMike Karels 
331d626b50bSMike Karels static void
watchdog_attach(void)332d626b50bSMike Karels watchdog_attach(void)
333d626b50bSMike Karels {
334d626b50bSMike Karels 	EVENTHANDLER_REGISTER(watchdog_list, watchdog_config, NULL, 0);
335d626b50bSMike Karels }
336370c3cb5SSean Kelly 
3373bac064fSPoul-Henning Kamp /*
338df8bae1dSRodney W. Grimes  * Clock handling routines.
339df8bae1dSRodney W. Grimes  *
340b05dcf3cSPoul-Henning Kamp  * This code is written to operate with two timers that run independently of
341b05dcf3cSPoul-Henning Kamp  * each other.
3427ec73f64SPoul-Henning Kamp  *
343b05dcf3cSPoul-Henning Kamp  * The main timer, running hz times per second, is used to trigger interval
344b05dcf3cSPoul-Henning Kamp  * timers, timeouts and rescheduling as needed.
3457ec73f64SPoul-Henning Kamp  *
346b05dcf3cSPoul-Henning Kamp  * The second timer handles kernel and user profiling,
347b05dcf3cSPoul-Henning Kamp  * and does resource use estimation.  If the second timer is programmable,
348b05dcf3cSPoul-Henning Kamp  * it is randomized to avoid aliasing between the two clocks.  For example,
349b05dcf3cSPoul-Henning Kamp  * the randomization prevents an adversary from always giving up the cpu
350df8bae1dSRodney W. Grimes  * just before its quantum expires.  Otherwise, it would never accumulate
351df8bae1dSRodney W. Grimes  * cpu ticks.  The mean frequency of the second timer is stathz.
352b05dcf3cSPoul-Henning Kamp  *
353b05dcf3cSPoul-Henning Kamp  * If no second timer exists, stathz will be zero; in this case we drive
354b05dcf3cSPoul-Henning Kamp  * profiling and statistics off the main clock.  This WILL NOT be accurate;
355b05dcf3cSPoul-Henning Kamp  * do not do it unless absolutely necessary.
356b05dcf3cSPoul-Henning Kamp  *
357df8bae1dSRodney W. Grimes  * The statistics clock may (or may not) be run at a higher rate while
358b05dcf3cSPoul-Henning Kamp  * profiling.  This profile clock runs at profhz.  We require that profhz
359b05dcf3cSPoul-Henning Kamp  * be an integral multiple of stathz.
360b05dcf3cSPoul-Henning Kamp  *
361b05dcf3cSPoul-Henning Kamp  * If the statistics clock is running fast, it must be divided by the ratio
362b05dcf3cSPoul-Henning Kamp  * profhz/stathz for statistics.  (For profiling, every tick counts.)
363df8bae1dSRodney W. Grimes  *
3647ec73f64SPoul-Henning Kamp  * Time-of-day is maintained using a "timecounter", which may or may
3657ec73f64SPoul-Henning Kamp  * not be related to the hardware generating the above mentioned
3667ec73f64SPoul-Henning Kamp  * interrupts.
367df8bae1dSRodney W. Grimes  */
368df8bae1dSRodney W. Grimes 
369df8bae1dSRodney W. Grimes int	stathz;
370df8bae1dSRodney W. Grimes int	profhz;
371238dd320SJake Burkholder int	profprocs;
372238dd320SJake Burkholder int	psratio;
373df8bae1dSRodney W. Grimes 
374*6b82130eSMark Johnston DPCPU_DEFINE_STATIC(long, pcputicks);	/* Per-CPU version of ticks. */
3755760b029SKonstantin Belousov #ifdef DEVICE_POLLING
3765760b029SKonstantin Belousov static int devpoll_run = 0;
3775760b029SKonstantin Belousov #endif
378dbd55f3fSAlexander Motin 
379c6d31b83SKonstantin Belousov static void
ast_oweupc(struct thread * td,int tda __unused)380c6d31b83SKonstantin Belousov ast_oweupc(struct thread *td, int tda __unused)
381c6d31b83SKonstantin Belousov {
382c6d31b83SKonstantin Belousov 	if ((td->td_proc->p_flag & P_PROFIL) == 0)
383c6d31b83SKonstantin Belousov 		return;
384c6d31b83SKonstantin Belousov 	addupc_task(td, td->td_profil_addr, td->td_profil_ticks);
385c6d31b83SKonstantin Belousov 	td->td_profil_ticks = 0;
386c6d31b83SKonstantin Belousov 	td->td_pflags &= ~TDP_OWEUPC;
387c6d31b83SKonstantin Belousov }
388c6d31b83SKonstantin Belousov 
389c6d31b83SKonstantin Belousov static void
ast_alrm(struct thread * td,int tda __unused)390c6d31b83SKonstantin Belousov ast_alrm(struct thread *td, int tda __unused)
391c6d31b83SKonstantin Belousov {
392c6d31b83SKonstantin Belousov 	struct proc *p;
393c6d31b83SKonstantin Belousov 
394c6d31b83SKonstantin Belousov 	p = td->td_proc;
395c6d31b83SKonstantin Belousov 	PROC_LOCK(p);
396c6d31b83SKonstantin Belousov 	kern_psignal(p, SIGVTALRM);
397c6d31b83SKonstantin Belousov 	PROC_UNLOCK(p);
398c6d31b83SKonstantin Belousov }
399c6d31b83SKonstantin Belousov 
400c6d31b83SKonstantin Belousov static void
ast_prof(struct thread * td,int tda __unused)401c6d31b83SKonstantin Belousov ast_prof(struct thread *td, int tda __unused)
402c6d31b83SKonstantin Belousov {
403c6d31b83SKonstantin Belousov 	struct proc *p;
404c6d31b83SKonstantin Belousov 
405c6d31b83SKonstantin Belousov 	p = td->td_proc;
406c6d31b83SKonstantin Belousov 	PROC_LOCK(p);
407c6d31b83SKonstantin Belousov 	kern_psignal(p, SIGPROF);
408c6d31b83SKonstantin Belousov 	PROC_UNLOCK(p);
409c6d31b83SKonstantin Belousov }
410c6d31b83SKonstantin Belousov 
411df8bae1dSRodney W. Grimes /*
412df8bae1dSRodney W. Grimes  * Initialize clock frequencies and start both clocks running.
413df8bae1dSRodney W. Grimes  */
4142b14f991SJulian Elischer static void
initclocks(void * dummy __unused)4152287ced2SMark Johnston initclocks(void *dummy __unused)
416df8bae1dSRodney W. Grimes {
4173e85b721SEd Maste 	int i;
418df8bae1dSRodney W. Grimes 
419df8bae1dSRodney W. Grimes 	/*
420df8bae1dSRodney W. Grimes 	 * Set divisors to 1 (normal case) and let the machine-specific
421df8bae1dSRodney W. Grimes 	 * code do its bit.
422df8bae1dSRodney W. Grimes 	 */
423875b8844SAlexander Motin 	mtx_init(&time_lock, "time lock", NULL, MTX_DEF);
42463d69d25SRobert Watson 	cpu_initclocks();
425df8bae1dSRodney W. Grimes 
426df8bae1dSRodney W. Grimes 	/*
427df8bae1dSRodney W. Grimes 	 * Compute profhz/stathz, and fix profhz if needed.
428df8bae1dSRodney W. Grimes 	 */
429df8bae1dSRodney W. Grimes 	i = stathz ? stathz : hz;
430df8bae1dSRodney W. Grimes 	if (profhz == 0)
431df8bae1dSRodney W. Grimes 		profhz = i;
432df8bae1dSRodney W. Grimes 	psratio = profhz / i;
433d626b50bSMike Karels 
434c6d31b83SKonstantin Belousov 	ast_register(TDA_OWEUPC, ASTR_ASTF_REQUIRED, 0, ast_oweupc);
435c6d31b83SKonstantin Belousov 	ast_register(TDA_ALRM, ASTR_ASTF_REQUIRED, 0, ast_alrm);
436c6d31b83SKonstantin Belousov 	ast_register(TDA_PROF, ASTR_ASTF_REQUIRED, 0, ast_prof);
437c6d31b83SKonstantin Belousov 
4384103b765SPoul-Henning Kamp #ifdef SW_WATCHDOG
439d626b50bSMike Karels 	/* Enable hardclock watchdog now, even if a hardware watchdog exists. */
440d626b50bSMike Karels 	watchdog_attach();
441d626b50bSMike Karels #else
442d626b50bSMike Karels 	/* Volunteer to run a software watchdog. */
443d626b50bSMike Karels 	if (wdog_software_attach == NULL)
444d626b50bSMike Karels 		wdog_software_attach = watchdog_attach;
4454103b765SPoul-Henning Kamp #endif
446df8bae1dSRodney W. Grimes }
4472287ced2SMark Johnston SYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL);
448df8bae1dSRodney W. Grimes 
4493277792bSMateusz Guzik static __noinline void
hardclock_itimer(struct thread * td,struct pstats * pstats,int cnt,int usermode)4503277792bSMateusz Guzik hardclock_itimer(struct thread *td, struct pstats *pstats, int cnt, int usermode)
451a157e425SAlexander Motin {
4523277792bSMateusz Guzik 	struct proc *p;
453c6d31b83SKonstantin Belousov 	int ast;
454a157e425SAlexander Motin 
455c6d31b83SKonstantin Belousov 	ast = 0;
4563277792bSMateusz Guzik 	p = td->td_proc;
457a157e425SAlexander Motin 	if (usermode &&
458a157e425SAlexander Motin 	    timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value)) {
4595c7bebf9SKonstantin Belousov 		PROC_ITIMLOCK(p);
460a157e425SAlexander Motin 		if (itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL],
461a157e425SAlexander Motin 		    tick * cnt) == 0)
462c6d31b83SKonstantin Belousov 			ast |= TDAI(TDA_ALRM);
4635c7bebf9SKonstantin Belousov 		PROC_ITIMUNLOCK(p);
464a157e425SAlexander Motin 	}
465a157e425SAlexander Motin 	if (timevalisset(&pstats->p_timer[ITIMER_PROF].it_value)) {
4665c7bebf9SKonstantin Belousov 		PROC_ITIMLOCK(p);
467a157e425SAlexander Motin 		if (itimerdecr(&pstats->p_timer[ITIMER_PROF],
468a157e425SAlexander Motin 		    tick * cnt) == 0)
469c6d31b83SKonstantin Belousov 			ast |= TDAI(TDA_PROF);
4705c7bebf9SKonstantin Belousov 		PROC_ITIMUNLOCK(p);
471a157e425SAlexander Motin 	}
472c6d31b83SKonstantin Belousov 	if (ast != 0)
473c6d31b83SKonstantin Belousov 		ast_sched_mask(td, ast);
4743277792bSMateusz Guzik }
4753277792bSMateusz Guzik 
4763277792bSMateusz Guzik void
hardclock(int cnt,int usermode)4773277792bSMateusz Guzik hardclock(int cnt, int usermode)
4783277792bSMateusz Guzik {
4793277792bSMateusz Guzik 	struct pstats *pstats;
4803277792bSMateusz Guzik 	struct thread *td = curthread;
4813277792bSMateusz Guzik 	struct proc *p = td->td_proc;
482*6b82130eSMark Johnston 	long global, newticks, *t;
4833277792bSMateusz Guzik 
4843277792bSMateusz Guzik 	/*
4853277792bSMateusz Guzik 	 * Update per-CPU and possibly global ticks values.
4863277792bSMateusz Guzik 	 */
487*6b82130eSMark Johnston 	t = DPCPU_PTR(pcputicks);
4883277792bSMateusz Guzik 	*t += cnt;
489*6b82130eSMark Johnston 	global = atomic_load_long(&ticksl);
4903277792bSMateusz Guzik 	do {
4913277792bSMateusz Guzik 		newticks = *t - global;
4923277792bSMateusz Guzik 		if (newticks <= 0) {
4933277792bSMateusz Guzik 			if (newticks < -1)
4943277792bSMateusz Guzik 				*t = global - 1;
4953277792bSMateusz Guzik 			newticks = 0;
4963277792bSMateusz Guzik 			break;
4973277792bSMateusz Guzik 		}
498*6b82130eSMark Johnston 	} while (!atomic_fcmpset_long(&ticksl, &global, *t));
4993277792bSMateusz Guzik 
5003277792bSMateusz Guzik 	/*
5013277792bSMateusz Guzik 	 * Run current process's virtual and profile time, as needed.
5023277792bSMateusz Guzik 	 */
5033277792bSMateusz Guzik 	pstats = p->p_stats;
5043277792bSMateusz Guzik 	if (__predict_false(
5053277792bSMateusz Guzik 	    timevalisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) ||
5063277792bSMateusz Guzik 	    timevalisset(&pstats->p_timer[ITIMER_PROF].it_value)))
5073277792bSMateusz Guzik 		hardclock_itimer(td, pstats, cnt, usermode);
508a157e425SAlexander Motin 
509a157e425SAlexander Motin #ifdef	HWPMC_HOOKS
510a157e425SAlexander Motin 	if (PMC_CPU_HAS_SAMPLES(PCPU_GET(cpuid)))
511a157e425SAlexander Motin 		PMC_CALL_HOOK_UNLOCKED(curthread, PMC_FN_DO_SAMPLES, NULL);
512f5f9340bSFabien Thomas 	if (td->td_intr_frame != NULL)
513f5f9340bSFabien Thomas 		PMC_SOFT_CALL_TF( , , clock, hard, td->td_intr_frame);
514a157e425SAlexander Motin #endif
515a157e425SAlexander Motin 	/* We are in charge to handle this tick duty. */
516a157e425SAlexander Motin 	if (newticks > 0) {
5170e189873SAlexander Motin 		tc_ticktock(newticks);
518a157e425SAlexander Motin #ifdef DEVICE_POLLING
5195760b029SKonstantin Belousov 		/* Dangerous and no need to call these things concurrently. */
5205760b029SKonstantin Belousov 		if (atomic_cmpset_acq_int(&devpoll_run, 0, 1)) {
5214763a8b8SAlexander Motin 			/* This is very short and quick. */
5224763a8b8SAlexander Motin 			hardclock_device_poll();
5235760b029SKonstantin Belousov 			atomic_store_rel_int(&devpoll_run, 0);
5244763a8b8SAlexander Motin 		}
5255760b029SKonstantin Belousov #endif /* DEVICE_POLLING */
526a157e425SAlexander Motin 		if (watchdog_enabled > 0) {
527*6b82130eSMark Johnston 			long left;
528*6b82130eSMark Johnston 
529*6b82130eSMark Johnston 			left = atomic_fetchadd_long(&watchdog_ticks, -newticks);
530*6b82130eSMark Johnston 			if (left > 0 && left <= newticks)
531a157e425SAlexander Motin 				watchdog_fire();
532a157e425SAlexander Motin 		}
533aba10e13SAlexander Motin 		intr_event_handle(clk_intr_event, NULL);
534a157e425SAlexander Motin 	}
535a157e425SAlexander Motin 	if (curcpu == CPU_FIRST())
536a157e425SAlexander Motin 		cpu_tick_calibration();
537a5f10424SMatt Macy 	if (__predict_false(DPCPU_GET(epoch_cb_count)))
538a5f10424SMatt Macy 		GROUPTASK_ENQUEUE(DPCPU_PTR(epoch_cb_task));
539a157e425SAlexander Motin }
540a157e425SAlexander Motin 
541a157e425SAlexander Motin void
hardclock_sync(int cpu)542a157e425SAlexander Motin hardclock_sync(int cpu)
543a157e425SAlexander Motin {
544*6b82130eSMark Johnston 	long *t;
545a157e425SAlexander Motin 
546*6b82130eSMark Johnston 	KASSERT(!CPU_ABSENT(cpu), ("Absent CPU %d", cpu));
547*6b82130eSMark Johnston 
548*6b82130eSMark Johnston 	t = DPCPU_ID_PTR(cpu, pcputicks);
549*6b82130eSMark Johnston 	*t = ticksl;
550a157e425SAlexander Motin }
551a157e425SAlexander Motin 
552df8bae1dSRodney W. Grimes /*
553fdd95483SHans Petter Selasky  * Regular integer scaling formula without losing precision:
55435a33d14SHans Petter Selasky  */
55535a33d14SHans Petter Selasky #define	TIME_INT_SCALE(value, mul, div) \
55635a33d14SHans Petter Selasky 	(((value) / (div)) * (mul) + (((value) % (div)) * (mul)) / (div))
55735a33d14SHans Petter Selasky 
55835a33d14SHans Petter Selasky /*
55935a33d14SHans Petter Selasky  * Macro for converting seconds and microseconds into actual ticks,
56035a33d14SHans Petter Selasky  * based on the given hz value:
56135a33d14SHans Petter Selasky  */
56235a33d14SHans Petter Selasky #define	TIME_TO_TICKS(sec, usec, hz) \
56335a33d14SHans Petter Selasky 	((sec) * (hz) + TIME_INT_SCALE(usec, hz, 1 << 6) / (1000000 >> 6))
56435a33d14SHans Petter Selasky 
56535a33d14SHans Petter Selasky #define	TIME_ASSERT_VALID_HZ(hz)	\
56635a33d14SHans Petter Selasky 	_Static_assert(TIME_TO_TICKS(INT_MAX / (hz) - 1, 999999, hz) >= 0 && \
56735a33d14SHans Petter Selasky 		       TIME_TO_TICKS(INT_MAX / (hz) - 1, 999999, hz) < INT_MAX,	\
56835a33d14SHans Petter Selasky 		       "tvtohz() can overflow the regular integer type")
56935a33d14SHans Petter Selasky 
57035a33d14SHans Petter Selasky /*
57135a33d14SHans Petter Selasky  * Compile time assert the maximum and minimum values to fit into a
57235a33d14SHans Petter Selasky  * regular integer when computing TIME_TO_TICKS():
57335a33d14SHans Petter Selasky  */
57435a33d14SHans Petter Selasky TIME_ASSERT_VALID_HZ(HZ_MAXIMUM);
57535a33d14SHans Petter Selasky TIME_ASSERT_VALID_HZ(HZ_MINIMUM);
57635a33d14SHans Petter Selasky 
57735a33d14SHans Petter Selasky /*
578fdd95483SHans Petter Selasky  * The formula is mostly linear, but test some more common values just
57935a33d14SHans Petter Selasky  * in case:
58035a33d14SHans Petter Selasky  */
58135a33d14SHans Petter Selasky TIME_ASSERT_VALID_HZ(1024);
58235a33d14SHans Petter Selasky TIME_ASSERT_VALID_HZ(1000);
58335a33d14SHans Petter Selasky TIME_ASSERT_VALID_HZ(128);
58435a33d14SHans Petter Selasky TIME_ASSERT_VALID_HZ(100);
58535a33d14SHans Petter Selasky 
58635a33d14SHans Petter Selasky /*
58735a33d14SHans Petter Selasky  * Compute number of ticks representing the specified amount of time.
58835a33d14SHans Petter Selasky  * If the specified time is negative, a value of 1 is returned. This
58935a33d14SHans Petter Selasky  * function returns a value from 1 up to and including INT_MAX.
590df8bae1dSRodney W. Grimes  */
591df8bae1dSRodney W. Grimes int
tvtohz(struct timeval * tv)5923e85b721SEd Maste tvtohz(struct timeval *tv)
593df8bae1dSRodney W. Grimes {
59435a33d14SHans Petter Selasky 	int retval;
595df8bae1dSRodney W. Grimes 
596df8bae1dSRodney W. Grimes 	/*
59735a33d14SHans Petter Selasky 	 * The values passed here may come from user-space and these
59835a33d14SHans Petter Selasky 	 * checks ensure "tv_usec" is within its allowed range:
599df8bae1dSRodney W. Grimes 	 */
60035a33d14SHans Petter Selasky 
60135a33d14SHans Petter Selasky 	/* check for tv_usec underflow */
60235a33d14SHans Petter Selasky 	if (__predict_false(tv->tv_usec < 0)) {
60335a33d14SHans Petter Selasky 		tv->tv_sec += tv->tv_usec / 1000000;
60435a33d14SHans Petter Selasky 		tv->tv_usec = tv->tv_usec % 1000000;
60535a33d14SHans Petter Selasky 		/* convert tv_usec to a positive value */
60635a33d14SHans Petter Selasky 		if (__predict_true(tv->tv_usec < 0)) {
60735a33d14SHans Petter Selasky 			tv->tv_usec += 1000000;
60835a33d14SHans Petter Selasky 			tv->tv_sec -= 1;
6096976af69SBruce Evans 		}
61035a33d14SHans Petter Selasky 	/* check for tv_usec overflow */
61135a33d14SHans Petter Selasky 	} else if (__predict_false(tv->tv_usec >= 1000000)) {
61235a33d14SHans Petter Selasky 		tv->tv_sec += tv->tv_usec / 1000000;
61335a33d14SHans Petter Selasky 		tv->tv_usec = tv->tv_usec % 1000000;
6147ec73f64SPoul-Henning Kamp 	}
61535a33d14SHans Petter Selasky 
61635a33d14SHans Petter Selasky 	/* check for tv_sec underflow */
61735a33d14SHans Petter Selasky 	if (__predict_false(tv->tv_sec < 0))
61835a33d14SHans Petter Selasky 		return (1);
61935a33d14SHans Petter Selasky 	/* check for tv_sec overflow (including room for the tv_usec part) */
62035a33d14SHans Petter Selasky 	else if (__predict_false(tv->tv_sec >= tick_seconds_max))
62135a33d14SHans Petter Selasky 		return (INT_MAX);
62235a33d14SHans Petter Selasky 
62335a33d14SHans Petter Selasky 	/* cast to "int" to avoid platform differences */
62435a33d14SHans Petter Selasky 	retval = TIME_TO_TICKS((int)tv->tv_sec, (int)tv->tv_usec, hz);
62535a33d14SHans Petter Selasky 
62635a33d14SHans Petter Selasky 	/* add one additional tick */
62735a33d14SHans Petter Selasky 	return (retval + 1);
628df8bae1dSRodney W. Grimes }
629df8bae1dSRodney W. Grimes 
630df8bae1dSRodney W. Grimes /*
631df8bae1dSRodney W. Grimes  * Start profiling on a process.
632df8bae1dSRodney W. Grimes  *
633df8bae1dSRodney W. Grimes  * Kernel profiling passes proc0 which never exits and hence
634df8bae1dSRodney W. Grimes  * keeps the profile clock running constantly.
635df8bae1dSRodney W. Grimes  */
636df8bae1dSRodney W. Grimes void
startprofclock(struct proc * p)6373e85b721SEd Maste startprofclock(struct proc *p)
638df8bae1dSRodney W. Grimes {
639df8bae1dSRodney W. Grimes 
6409752f794SJohn Baldwin 	PROC_LOCK_ASSERT(p, MA_OWNED);
6419752f794SJohn Baldwin 	if (p->p_flag & P_STOPPROF)
642a282253aSJulian Elischer 		return;
6439752f794SJohn Baldwin 	if ((p->p_flag & P_PROFIL) == 0) {
6449752f794SJohn Baldwin 		p->p_flag |= P_PROFIL;
645875b8844SAlexander Motin 		mtx_lock(&time_lock);
646238dd320SJake Burkholder 		if (++profprocs == 1)
647238dd320SJake Burkholder 			cpu_startprofclock();
648875b8844SAlexander Motin 		mtx_unlock(&time_lock);
649df8bae1dSRodney W. Grimes 	}
6509752f794SJohn Baldwin }
651df8bae1dSRodney W. Grimes 
652df8bae1dSRodney W. Grimes /*
653df8bae1dSRodney W. Grimes  * Stop profiling on a process.
654df8bae1dSRodney W. Grimes  */
655df8bae1dSRodney W. Grimes void
stopprofclock(struct proc * p)6563e85b721SEd Maste stopprofclock(struct proc *p)
657df8bae1dSRodney W. Grimes {
658df8bae1dSRodney W. Grimes 
659a282253aSJulian Elischer 	PROC_LOCK_ASSERT(p, MA_OWNED);
6609752f794SJohn Baldwin 	if (p->p_flag & P_PROFIL) {
6619752f794SJohn Baldwin 		if (p->p_profthreads != 0) {
6620436fcb8SKonstantin Belousov 			while (p->p_profthreads != 0) {
6639752f794SJohn Baldwin 				p->p_flag |= P_STOPPROF;
664a282253aSJulian Elischer 				msleep(&p->p_profthreads, &p->p_mtx, PPAUSE,
665a89ec05eSPeter Wemm 				    "stopprof", 0);
6660436fcb8SKonstantin Belousov 			}
667a282253aSJulian Elischer 		}
668b62b2304SColin Percival 		if ((p->p_flag & P_PROFIL) == 0)
669b62b2304SColin Percival 			return;
6709752f794SJohn Baldwin 		p->p_flag &= ~P_PROFIL;
671875b8844SAlexander Motin 		mtx_lock(&time_lock);
672238dd320SJake Burkholder 		if (--profprocs == 0)
673238dd320SJake Burkholder 			cpu_stopprofclock();
674875b8844SAlexander Motin 		mtx_unlock(&time_lock);
675df8bae1dSRodney W. Grimes 	}
6769752f794SJohn Baldwin }
677df8bae1dSRodney W. Grimes 
678df8bae1dSRodney W. Grimes /*
6791c4bcd05SJeff Roberson  * Statistics clock.  Updates rusage information and calls the scheduler
6801c4bcd05SJeff Roberson  * to adjust priorities of the active thread.
6811c4bcd05SJeff Roberson  *
682238dd320SJake Burkholder  * This should be called by all active processors.
683df8bae1dSRodney W. Grimes  */
684df8bae1dSRodney W. Grimes void
statclock(int cnt,int usermode)685cc4f3d0aSMark Johnston statclock(int cnt, int usermode)
686bcfd016cSAlexander Motin {
6878a129caeSDavid Greenman 	struct rusage *ru;
6888a129caeSDavid Greenman 	struct vmspace *vm;
689238dd320SJake Burkholder 	struct thread *td;
690238dd320SJake Burkholder 	struct proc *p;
691238dd320SJake Burkholder 	long rss;
6927628402bSPeter Wemm 	long *cp_time;
693c80038a0SAlexander Motin 	uint64_t runtime, new_switchtime;
6948a129caeSDavid Greenman 
695238dd320SJake Burkholder 	td = curthread;
696238dd320SJake Burkholder 	p = td->td_proc;
697238dd320SJake Burkholder 
6987628402bSPeter Wemm 	cp_time = (long *)PCPU_PTR(cp_time);
699b439e431SJohn Baldwin 	if (usermode) {
700df8bae1dSRodney W. Grimes 		/*
70171a62f8aSBruce Evans 		 * Charge the time as appropriate.
702df8bae1dSRodney W. Grimes 		 */
703bcfd016cSAlexander Motin 		td->td_uticks += cnt;
704fa885116SJulian Elischer 		if (p->p_nice > NZERO)
705bcfd016cSAlexander Motin 			cp_time[CP_NICE] += cnt;
706df8bae1dSRodney W. Grimes 		else
707bcfd016cSAlexander Motin 			cp_time[CP_USER] += cnt;
708df8bae1dSRodney W. Grimes 	} else {
709df8bae1dSRodney W. Grimes 		/*
710df8bae1dSRodney W. Grimes 		 * Came from kernel mode, so we were:
711df8bae1dSRodney W. Grimes 		 * - handling an interrupt,
712df8bae1dSRodney W. Grimes 		 * - doing syscall or trap work on behalf of the current
713df8bae1dSRodney W. Grimes 		 *   user process, or
714df8bae1dSRodney W. Grimes 		 * - spinning in the idle loop.
715df8bae1dSRodney W. Grimes 		 * Whichever it is, charge the time as appropriate.
716df8bae1dSRodney W. Grimes 		 * Note that we charge interrupts to the current process,
717df8bae1dSRodney W. Grimes 		 * regardless of whether they are ``for'' that process,
718df8bae1dSRodney W. Grimes 		 * so that we know how much of its real time was spent
719df8bae1dSRodney W. Grimes 		 * in ``non-process'' (i.e., interrupt) work.
720df8bae1dSRodney W. Grimes 		 */
721e0f66ef8SJohn Baldwin 		if ((td->td_pflags & TDP_ITHREAD) ||
722e0f66ef8SJohn Baldwin 		    td->td_intr_nesting_level >= 2) {
723bcfd016cSAlexander Motin 			td->td_iticks += cnt;
724bcfd016cSAlexander Motin 			cp_time[CP_INTR] += cnt;
7250384fff8SJason Evans 		} else {
726bcfd016cSAlexander Motin 			td->td_pticks += cnt;
727bcfd016cSAlexander Motin 			td->td_sticks += cnt;
728486a9414SJulian Elischer 			if (!TD_IS_IDLETHREAD(td))
729bcfd016cSAlexander Motin 				cp_time[CP_SYS] += cnt;
7300384fff8SJason Evans 			else
731bcfd016cSAlexander Motin 				cp_time[CP_IDLE] += cnt;
732df8bae1dSRodney W. Grimes 		}
7330384fff8SJason Evans 	}
734f5e9e8ecSBruce Evans 
735f5e9e8ecSBruce Evans 	/* Update resource usage integrals and maximums. */
73616f9f205SJohn Baldwin 	MPASS(p->p_vmspace != NULL);
73716f9f205SJohn Baldwin 	vm = p->p_vmspace;
7381c4bcd05SJeff Roberson 	ru = &td->td_ru;
739bcfd016cSAlexander Motin 	ru->ru_ixrss += pgtok(vm->vm_tsize) * cnt;
740bcfd016cSAlexander Motin 	ru->ru_idrss += pgtok(vm->vm_dsize) * cnt;
741bcfd016cSAlexander Motin 	ru->ru_isrss += pgtok(vm->vm_ssize) * cnt;
7421c6d46f9SLuoqi Chen 	rss = pgtok(vmspace_resident_count(vm));
743f5e9e8ecSBruce Evans 	if (ru->ru_maxrss < rss)
744f5e9e8ecSBruce Evans 		ru->ru_maxrss = rss;
7458f51ad55SJeff Roberson 	KTR_POINT2(KTR_SCHED, "thread", sched_tdname(td), "statclock",
7468f51ad55SJeff Roberson 	    "prio:%d", td->td_priority, "stathz:%d", (stathz)?stathz:hz);
747b3e9e682SRyan Stone 	SDT_PROBE2(sched, , , tick, td, td->td_proc);
7487628402bSPeter Wemm 	thread_lock_flags(td, MTX_QUIET);
749c80038a0SAlexander Motin 
750c80038a0SAlexander Motin 	/*
751c80038a0SAlexander Motin 	 * Compute the amount of time during which the current
752c80038a0SAlexander Motin 	 * thread was running, and add that to its total so far.
753c80038a0SAlexander Motin 	 */
754c80038a0SAlexander Motin 	new_switchtime = cpu_ticks();
755c80038a0SAlexander Motin 	runtime = new_switchtime - PCPU_GET(switchtime);
756c80038a0SAlexander Motin 	td->td_runtime += runtime;
757c80038a0SAlexander Motin 	td->td_incruntime += runtime;
758c80038a0SAlexander Motin 	PCPU_SET(switchtime, new_switchtime);
759c80038a0SAlexander Motin 
760c3cccf95SJeff Roberson 	sched_clock(td, cnt);
76140acdeabSJeff Roberson 	thread_unlock(td);
762f5f9340bSFabien Thomas #ifdef HWPMC_HOOKS
763f5f9340bSFabien Thomas 	if (td->td_intr_frame != NULL)
764f5f9340bSFabien Thomas 		PMC_SOFT_CALL_TF( , , clock, stat, td->td_intr_frame);
765f5f9340bSFabien Thomas #endif
7666caa8a15SJohn Baldwin }
7676c567274SJohn Baldwin 
7686caa8a15SJohn Baldwin void
profclock(int cnt,int usermode,uintfptr_t pc)769cc4f3d0aSMark Johnston profclock(int cnt, int usermode, uintfptr_t pc)
770bcfd016cSAlexander Motin {
771238dd320SJake Burkholder 	struct thread *td;
7726caa8a15SJohn Baldwin 
7734a338afdSJulian Elischer 	td = curthread;
774b439e431SJohn Baldwin 	if (usermode) {
775238dd320SJake Burkholder 		/*
776238dd320SJake Burkholder 		 * Came from user mode; CPU was in user state.
777238dd320SJake Burkholder 		 * If this process is being profiled, record the tick.
778a282253aSJulian Elischer 		 * if there is no related user location yet, don't
779a282253aSJulian Elischer 		 * bother trying to count it.
780238dd320SJake Burkholder 		 */
7819752f794SJohn Baldwin 		if (td->td_proc->p_flag & P_PROFIL)
782bcfd016cSAlexander Motin 			addupc_intr(td, pc, cnt);
783238dd320SJake Burkholder 	}
7841af19ee4SAlexander Motin #ifdef HWPMC_HOOKS
7851af19ee4SAlexander Motin 	if (td->td_intr_frame != NULL)
7861af19ee4SAlexander Motin 		PMC_SOFT_CALL_TF( , , clock, prof, td->td_intr_frame);
7871af19ee4SAlexander Motin #endif
788df8bae1dSRodney W. Grimes }
789df8bae1dSRodney W. Grimes 
790df8bae1dSRodney W. Grimes /*
791df8bae1dSRodney W. Grimes  * Return information about system clocks.
792df8bae1dSRodney W. Grimes  */
793787d58f2SPoul-Henning Kamp static int
sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)79482d9ae4eSPoul-Henning Kamp sysctl_kern_clockrate(SYSCTL_HANDLER_ARGS)
795df8bae1dSRodney W. Grimes {
796df8bae1dSRodney W. Grimes 	struct clockinfo clkinfo;
797df8bae1dSRodney W. Grimes 	/*
798df8bae1dSRodney W. Grimes 	 * Construct clockinfo structure.
799df8bae1dSRodney W. Grimes 	 */
800a9a0f15aSBruce Evans 	bzero(&clkinfo, sizeof(clkinfo));
801df8bae1dSRodney W. Grimes 	clkinfo.hz = hz;
802df8bae1dSRodney W. Grimes 	clkinfo.tick = tick;
803df8bae1dSRodney W. Grimes 	clkinfo.profhz = profhz;
804df8bae1dSRodney W. Grimes 	clkinfo.stathz = stathz ? stathz : hz;
805ae0eb976SPoul-Henning Kamp 	return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
806df8bae1dSRodney W. Grimes }
8073f31c649SGarrett Wollman 
808c383c221SEd Schouten SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate,
809c383c221SEd Schouten 	CTLTYPE_STRUCT|CTLFLAG_RD|CTLFLAG_MPSAFE,
810af1408e3SLuigi Rizzo 	0, 0, sysctl_kern_clockrate, "S,clockinfo",
811af1408e3SLuigi Rizzo 	"Rate and period of various kernel clocks");
812370c3cb5SSean Kelly 
8134103b765SPoul-Henning Kamp static void
watchdog_config(void * unused __unused,u_int cmd,int * error)8149079fff5SNick Hibma watchdog_config(void *unused __unused, u_int cmd, int *error)
815370c3cb5SSean Kelly {
8164103b765SPoul-Henning Kamp 	u_int u;
817370c3cb5SSean Kelly 
8184103b765SPoul-Henning Kamp 	u = cmd & WD_INTERVAL;
8199079fff5SNick Hibma 	if (u >= WD_TO_1SEC) {
8204103b765SPoul-Henning Kamp 		watchdog_ticks = (1 << (u - WD_TO_1SEC)) * hz;
8214103b765SPoul-Henning Kamp 		watchdog_enabled = 1;
8229079fff5SNick Hibma 		*error = 0;
8234103b765SPoul-Henning Kamp 	} else {
8244103b765SPoul-Henning Kamp 		watchdog_enabled = 0;
825370c3cb5SSean Kelly 	}
8264103b765SPoul-Henning Kamp }
827370c3cb5SSean Kelly 
828370c3cb5SSean Kelly /*
8293aed0ffcSElliott Mitchell  * Handle a watchdog timeout by dropping to DDB or panicking.
830370c3cb5SSean Kelly  */
831370c3cb5SSean Kelly static void
watchdog_fire(void)832370c3cb5SSean Kelly watchdog_fire(void)
833370c3cb5SSean Kelly {
834911d16b8SEd Maste 
835911d16b8SEd Maste #if defined(KDB) && !defined(KDB_UNATTENDED)
836911d16b8SEd Maste 	kdb_backtrace();
8373de213ccSRobert Watson 	kdb_enter(KDB_WHY_WATCHDOG, "watchdog timeout");
838911d16b8SEd Maste #else
839370c3cb5SSean Kelly 	panic("watchdog timeout");
840911d16b8SEd Maste #endif
841370c3cb5SSean Kelly }
842