xref: /openbsd-src/sys/kern/kern_clock.c (revision 5b707e820d80eb33e3911aaca96cc24b37e13e2e)
1 /*	$OpenBSD: kern_clock.c,v 1.114 2023/08/22 13:46:20 jsg Exp $	*/
2 /*	$NetBSD: kern_clock.c,v 1.34 1996/06/09 04:51:03 briggs Exp $	*/
3 
4 /*-
5  * Copyright (c) 1982, 1986, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  * (c) UNIX System Laboratories, Inc.
8  * All or some portions of this file are derived from material licensed
9  * to the University of California by American Telephone and Telegraph
10  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11  * the permission of UNIX System Laboratories, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)kern_clock.c	8.5 (Berkeley) 1/21/94
38  */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/timeout.h>
43 #include <sys/kernel.h>
44 #include <sys/limits.h>
45 #include <sys/proc.h>
46 #include <sys/user.h>
47 #include <sys/resourcevar.h>
48 #include <sys/sysctl.h>
49 #include <sys/sched.h>
50 #include <sys/timetc.h>
51 
52 #include "dt.h"
53 #if NDT > 0
54 #include <dev/dt/dtvar.h>
55 #endif
56 
57 /*
58  * Clock handling routines.
59  *
60  * This code is written to operate with two timers that run independently of
61  * each other.  The main clock, running hz times per second, is used to keep
62  * track of real time.  The second timer handles kernel and user profiling,
63  * and does resource use estimation.  If the second timer is programmable,
64  * it is randomized to avoid aliasing between the two clocks.  For example,
65  * the randomization prevents an adversary from always giving up the cpu
66  * just before its quantum expires.  Otherwise, it would never accumulate
67  * cpu ticks.  The mean frequency of the second timer is stathz.
68  *
69  * If no second timer exists, stathz will be zero; in this case we drive
70  * profiling and statistics off the main clock.  This WILL NOT be accurate;
71  * do not do it unless absolutely necessary.
72  *
73  * The statistics clock may (or may not) be run at a higher rate while
74  * profiling.  This profile clock runs at profhz.  We require that profhz
75  * be an integral multiple of stathz.
76  *
77  * If the statistics clock is running fast, it must be divided by the ratio
78  * profhz/stathz for statistics.  (For profiling, every tick counts.)
79  */
80 
81 int	stathz;
82 int	schedhz;
83 int	profhz;
84 int	profprocs;
85 int	ticks = INT_MAX - (15 * 60 * HZ);
86 
87 /* Don't force early wrap around, triggers bug in inteldrm */
88 volatile unsigned long jiffies;
89 
90 /*
91  * Initialize clock frequencies and start both clocks running.
92  */
93 void
94 initclocks(void)
95 {
96 	/*
97 	 * Let the machine-specific code do its bit.
98 	 */
99 	cpu_initclocks();
100 
101 	KASSERT(profhz >= stathz && profhz <= 1000000000);
102 	KASSERT(profhz % stathz == 0);
103 	profclock_period = 1000000000 / profhz;
104 
105 	inittimecounter();
106 }
107 
108 /*
109  * The real-time timer, interrupting hz times per second.
110  */
111 void
112 hardclock(struct clockframe *frame)
113 {
114 #if NDT > 0
115 	DT_ENTER(profile, NULL);
116 	if (CPU_IS_PRIMARY(curcpu()))
117 		DT_ENTER(interval, NULL);
118 #endif
119 
120 	/*
121 	 * If we are not the primary CPU, we're not allowed to do
122 	 * any more work.
123 	 */
124 	if (CPU_IS_PRIMARY(curcpu()) == 0)
125 		return;
126 
127 	tc_ticktock();
128 	ticks++;
129 	jiffies++;
130 
131 	/*
132 	 * Update the timeout wheel.
133 	 */
134 	timeout_hardclock_update();
135 }
136 
137 /*
138  * Compute number of hz in the specified amount of time.
139  */
140 int
141 tvtohz(const struct timeval *tv)
142 {
143 	unsigned long nticks;
144 	time_t sec;
145 	long usec;
146 
147 	/*
148 	 * If the number of usecs in the whole seconds part of the time
149 	 * fits in a long, then the total number of usecs will
150 	 * fit in an unsigned long.  Compute the total and convert it to
151 	 * ticks, rounding up and adding 1 to allow for the current tick
152 	 * to expire.  Rounding also depends on unsigned long arithmetic
153 	 * to avoid overflow.
154 	 *
155 	 * Otherwise, if the number of ticks in the whole seconds part of
156 	 * the time fits in a long, then convert the parts to
157 	 * ticks separately and add, using similar rounding methods and
158 	 * overflow avoidance.  This method would work in the previous
159 	 * case but it is slightly slower and assumes that hz is integral.
160 	 *
161 	 * Otherwise, round the time down to the maximum
162 	 * representable value.
163 	 *
164 	 * If ints have 32 bits, then the maximum value for any timeout in
165 	 * 10ms ticks is 248 days.
166 	 */
167 	sec = tv->tv_sec;
168 	usec = tv->tv_usec;
169 	if (sec < 0 || (sec == 0 && usec <= 0))
170 		nticks = 0;
171 	else if (sec <= LONG_MAX / 1000000)
172 		nticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
173 		    / tick + 1;
174 	else if (sec <= LONG_MAX / hz)
175 		nticks = sec * hz
176 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
177 	else
178 		nticks = LONG_MAX;
179 	if (nticks > INT_MAX)
180 		nticks = INT_MAX;
181 	return ((int)nticks);
182 }
183 
184 int
185 tstohz(const struct timespec *ts)
186 {
187 	struct timeval tv;
188 	TIMESPEC_TO_TIMEVAL(&tv, ts);
189 
190 	/* Round up. */
191 	if ((ts->tv_nsec % 1000) != 0) {
192 		tv.tv_usec += 1;
193 		if (tv.tv_usec >= 1000000) {
194 			tv.tv_usec -= 1000000;
195 			tv.tv_sec += 1;
196 		}
197 	}
198 
199 	return (tvtohz(&tv));
200 }
201 
202 /*
203  * Start profiling on a process.
204  *
205  * Kernel profiling passes proc0 which never exits and hence
206  * keeps the profile clock running constantly.
207  */
208 void
209 startprofclock(struct process *pr)
210 {
211 	int s;
212 
213 	if ((pr->ps_flags & PS_PROFIL) == 0) {
214 		atomic_setbits_int(&pr->ps_flags, PS_PROFIL);
215 		if (++profprocs == 1) {
216 			s = splstatclock();
217 			setstatclockrate(profhz);
218 			splx(s);
219 		}
220 	}
221 }
222 
223 /*
224  * Stop profiling on a process.
225  */
226 void
227 stopprofclock(struct process *pr)
228 {
229 	int s;
230 
231 	if (pr->ps_flags & PS_PROFIL) {
232 		atomic_clearbits_int(&pr->ps_flags, PS_PROFIL);
233 		if (--profprocs == 0) {
234 			s = splstatclock();
235 			setstatclockrate(stathz);
236 			splx(s);
237 		}
238 	}
239 }
240 
241 /*
242  * Statistics clock.  Grab profile sample, and if divider reaches 0,
243  * do process and kernel statistics.
244  */
245 void
246 statclock(struct clockframe *frame)
247 {
248 	struct cpu_info *ci = curcpu();
249 	struct schedstate_percpu *spc = &ci->ci_schedstate;
250 	struct proc *p = curproc;
251 	struct process *pr;
252 
253 	if (CLKF_USERMODE(frame)) {
254 		pr = p->p_p;
255 		/*
256 		 * Came from user mode; CPU was in user state.
257 		 * If this process is being profiled record the tick.
258 		 */
259 		p->p_uticks++;
260 		if (pr->ps_nice > NZERO)
261 			spc->spc_cp_time[CP_NICE]++;
262 		else
263 			spc->spc_cp_time[CP_USER]++;
264 	} else {
265 		/*
266 		 * Came from kernel mode, so we were:
267 		 * - spinning on a lock
268 		 * - handling an interrupt,
269 		 * - doing syscall or trap work on behalf of the current
270 		 *   user process, or
271 		 * - spinning in the idle loop.
272 		 * Whichever it is, charge the time as appropriate.
273 		 * Note that we charge interrupts to the current process,
274 		 * regardless of whether they are ``for'' that process,
275 		 * so that we know how much of its real time was spent
276 		 * in ``non-process'' (i.e., interrupt) work.
277 		 */
278 		if (CLKF_INTR(frame)) {
279 			if (p != NULL)
280 				p->p_iticks++;
281 			spc->spc_cp_time[spc->spc_spinning ?
282 			    CP_SPIN : CP_INTR]++;
283 		} else if (p != NULL && p != spc->spc_idleproc) {
284 			p->p_sticks++;
285 			spc->spc_cp_time[spc->spc_spinning ?
286 			    CP_SPIN : CP_SYS]++;
287 		} else
288 			spc->spc_cp_time[spc->spc_spinning ?
289 			    CP_SPIN : CP_IDLE]++;
290 	}
291 
292 	if (p != NULL) {
293 		p->p_cpticks++;
294 		/*
295 		 * If no schedclock is provided, call it here at ~~12-25 Hz;
296 		 * ~~16 Hz is best
297 		 */
298 		if (schedhz == 0) {
299 			if ((++spc->spc_schedticks & 3) == 0)
300 				schedclock(p);
301 		}
302 	}
303 }
304 
305 /*
306  * Return information about system clocks.
307  */
308 int
309 sysctl_clockrate(char *where, size_t *sizep, void *newp)
310 {
311 	struct clockinfo clkinfo;
312 
313 	/*
314 	 * Construct clockinfo structure.
315 	 */
316 	memset(&clkinfo, 0, sizeof clkinfo);
317 	clkinfo.tick = tick;
318 	clkinfo.hz = hz;
319 	clkinfo.profhz = profhz;
320 	clkinfo.stathz = stathz;
321 	return (sysctl_rdstruct(where, sizep, newp, &clkinfo, sizeof(clkinfo)));
322 }
323