xref: /openbsd-src/sys/kern/kern_clock.c (revision 061f668f8b0f1681065e7f34e5a11c06f054ac68)
1 /*	$OpenBSD: kern_clock.c,v 1.119 2023/09/14 22:27:09 cheloha 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/clockintr.h>
43 #include <sys/timeout.h>
44 #include <sys/kernel.h>
45 #include <sys/limits.h>
46 #include <sys/proc.h>
47 #include <sys/user.h>
48 #include <sys/resourcevar.h>
49 #include <sys/sysctl.h>
50 #include <sys/sched.h>
51 #include <sys/timetc.h>
52 
53 #include "dt.h"
54 #if NDT > 0
55 #include <dev/dt/dtvar.h>
56 #endif
57 
58 /*
59  * Clock handling routines.
60  *
61  * This code is written to operate with two timers that run independently of
62  * each other.  The main clock, running hz times per second, is used to keep
63  * track of real time.  The second timer handles kernel and user profiling,
64  * and does resource use estimation.  If the second timer is programmable,
65  * it is randomized to avoid aliasing between the two clocks.  For example,
66  * the randomization prevents an adversary from always giving up the cpu
67  * just before its quantum expires.  Otherwise, it would never accumulate
68  * cpu ticks.  The mean frequency of the second timer is stathz.
69  *
70  * If no second timer exists, stathz will be zero; in this case we drive
71  * profiling and statistics off the main clock.  This WILL NOT be accurate;
72  * do not do it unless absolutely necessary.
73  *
74  * The statistics clock may (or may not) be run at a higher rate while
75  * profiling.  This profile clock runs at profhz.  We require that profhz
76  * be an integral multiple of stathz.
77  *
78  * If the statistics clock is running fast, it must be divided by the ratio
79  * profhz/stathz for statistics.  (For profiling, every tick counts.)
80  */
81 
82 int	stathz;
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 uint32_t hardclock_period;	/* [I] hardclock period (ns) */
91 uint32_t statclock_avg;		/* [I] average statclock period (ns) */
92 uint32_t statclock_min;		/* [I] minimum statclock period (ns) */
93 uint32_t statclock_mask;	/* [I] set of allowed offsets */
94 int statclock_is_randomized;	/* [I] fixed or pseudorandom period? */
95 
96 /*
97  * Initialize clock frequencies and start both clocks running.
98  */
99 void
100 initclocks(void)
101 {
102 	uint32_t half_avg, var;
103 
104 	/*
105 	 * Let the machine-specific code do its bit.
106 	 */
107 	cpu_initclocks();
108 
109 	KASSERT(hz > 0 && hz <= 1000000000);
110 	hardclock_period = 1000000000 / hz;
111 	roundrobin_period = hardclock_period * 10;
112 
113 	KASSERT(stathz >= 1 && stathz <= 1000000000);
114 
115 	/*
116 	 * Compute the average statclock() period.  Then find var, the
117 	 * largest power of two such that var <= statclock_avg / 2.
118 	 */
119 	statclock_avg = 1000000000 / stathz;
120 	half_avg = statclock_avg / 2;
121 	for (var = 1U << 31; var > half_avg; var /= 2)
122 		continue;
123 
124 	/*
125 	 * Set a lower bound for the range using statclock_avg and var.
126 	 * The mask for that range is just (var - 1).
127 	 */
128 	statclock_min = statclock_avg - (var / 2);
129 	statclock_mask = var - 1;
130 
131 	KASSERT(profhz >= stathz && profhz <= 1000000000);
132 	KASSERT(profhz % stathz == 0);
133 	profclock_period = 1000000000 / profhz;
134 
135 	inittimecounter();
136 
137 	/* Start dispatching clock interrupts on the primary CPU. */
138 	cpu_startclock();
139 }
140 
141 /*
142  * The real-time timer, interrupting hz times per second.
143  */
144 void
145 hardclock(struct clockframe *frame)
146 {
147 #if NDT > 0
148 	DT_ENTER(profile, NULL);
149 	if (CPU_IS_PRIMARY(curcpu()))
150 		DT_ENTER(interval, NULL);
151 #endif
152 
153 	/*
154 	 * If we are not the primary CPU, we're not allowed to do
155 	 * any more work.
156 	 */
157 	if (CPU_IS_PRIMARY(curcpu()) == 0)
158 		return;
159 
160 	tc_ticktock();
161 	ticks++;
162 	jiffies++;
163 
164 	/*
165 	 * Update the timeout wheel.
166 	 */
167 	timeout_hardclock_update();
168 }
169 
170 /*
171  * Compute number of hz in the specified amount of time.
172  */
173 int
174 tvtohz(const struct timeval *tv)
175 {
176 	unsigned long nticks;
177 	time_t sec;
178 	long usec;
179 
180 	/*
181 	 * If the number of usecs in the whole seconds part of the time
182 	 * fits in a long, then the total number of usecs will
183 	 * fit in an unsigned long.  Compute the total and convert it to
184 	 * ticks, rounding up and adding 1 to allow for the current tick
185 	 * to expire.  Rounding also depends on unsigned long arithmetic
186 	 * to avoid overflow.
187 	 *
188 	 * Otherwise, if the number of ticks in the whole seconds part of
189 	 * the time fits in a long, then convert the parts to
190 	 * ticks separately and add, using similar rounding methods and
191 	 * overflow avoidance.  This method would work in the previous
192 	 * case but it is slightly slower and assumes that hz is integral.
193 	 *
194 	 * Otherwise, round the time down to the maximum
195 	 * representable value.
196 	 *
197 	 * If ints have 32 bits, then the maximum value for any timeout in
198 	 * 10ms ticks is 248 days.
199 	 */
200 	sec = tv->tv_sec;
201 	usec = tv->tv_usec;
202 	if (sec < 0 || (sec == 0 && usec <= 0))
203 		nticks = 0;
204 	else if (sec <= LONG_MAX / 1000000)
205 		nticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
206 		    / tick + 1;
207 	else if (sec <= LONG_MAX / hz)
208 		nticks = sec * hz
209 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
210 	else
211 		nticks = LONG_MAX;
212 	if (nticks > INT_MAX)
213 		nticks = INT_MAX;
214 	return ((int)nticks);
215 }
216 
217 int
218 tstohz(const struct timespec *ts)
219 {
220 	struct timeval tv;
221 	TIMESPEC_TO_TIMEVAL(&tv, ts);
222 
223 	/* Round up. */
224 	if ((ts->tv_nsec % 1000) != 0) {
225 		tv.tv_usec += 1;
226 		if (tv.tv_usec >= 1000000) {
227 			tv.tv_usec -= 1000000;
228 			tv.tv_sec += 1;
229 		}
230 	}
231 
232 	return (tvtohz(&tv));
233 }
234 
235 /*
236  * Start profiling on a process.
237  *
238  * Kernel profiling passes proc0 which never exits and hence
239  * keeps the profile clock running constantly.
240  */
241 void
242 startprofclock(struct process *pr)
243 {
244 	int s;
245 
246 	if ((pr->ps_flags & PS_PROFIL) == 0) {
247 		atomic_setbits_int(&pr->ps_flags, PS_PROFIL);
248 		if (++profprocs == 1) {
249 			s = splstatclock();
250 			setstatclockrate(profhz);
251 			splx(s);
252 		}
253 	}
254 }
255 
256 /*
257  * Stop profiling on a process.
258  */
259 void
260 stopprofclock(struct process *pr)
261 {
262 	int s;
263 
264 	if (pr->ps_flags & PS_PROFIL) {
265 		atomic_clearbits_int(&pr->ps_flags, PS_PROFIL);
266 		if (--profprocs == 0) {
267 			s = splstatclock();
268 			setstatclockrate(stathz);
269 			splx(s);
270 		}
271 	}
272 }
273 
274 /*
275  * Statistics clock.  Grab profile sample, and if divider reaches 0,
276  * do process and kernel statistics.
277  */
278 void
279 statclock(struct clockintr *cl, void *cf, void *arg)
280 {
281 	uint64_t count, i;
282 	struct clockframe *frame = cf;
283 	struct cpu_info *ci = curcpu();
284 	struct schedstate_percpu *spc = &ci->ci_schedstate;
285 	struct proc *p = curproc;
286 	struct process *pr;
287 
288 	if (statclock_is_randomized) {
289 		count = clockintr_advance_random(cl, statclock_min,
290 		    statclock_mask);
291 	} else {
292 		count = clockintr_advance(cl, statclock_avg);
293 	}
294 
295 	if (CLKF_USERMODE(frame)) {
296 		pr = p->p_p;
297 		/*
298 		 * Came from user mode; CPU was in user state.
299 		 * If this process is being profiled record the tick.
300 		 */
301 		p->p_uticks += count;
302 		if (pr->ps_nice > NZERO)
303 			spc->spc_cp_time[CP_NICE] += count;
304 		else
305 			spc->spc_cp_time[CP_USER] += count;
306 	} else {
307 		/*
308 		 * Came from kernel mode, so we were:
309 		 * - spinning on a lock
310 		 * - handling an interrupt,
311 		 * - doing syscall or trap work on behalf of the current
312 		 *   user process, or
313 		 * - spinning in the idle loop.
314 		 * Whichever it is, charge the time as appropriate.
315 		 * Note that we charge interrupts to the current process,
316 		 * regardless of whether they are ``for'' that process,
317 		 * so that we know how much of its real time was spent
318 		 * in ``non-process'' (i.e., interrupt) work.
319 		 */
320 		if (CLKF_INTR(frame)) {
321 			if (p != NULL)
322 				p->p_iticks += count;
323 			spc->spc_cp_time[spc->spc_spinning ?
324 			    CP_SPIN : CP_INTR] += count;
325 		} else if (p != NULL && p != spc->spc_idleproc) {
326 			p->p_sticks += count;
327 			spc->spc_cp_time[spc->spc_spinning ?
328 			    CP_SPIN : CP_SYS] += count;
329 		} else
330 			spc->spc_cp_time[spc->spc_spinning ?
331 			    CP_SPIN : CP_IDLE] += count;
332 	}
333 
334 	if (p != NULL) {
335 		p->p_cpticks += count;
336 		/*
337 		 * schedclock() runs every fourth statclock().
338 		 */
339 		for (i = 0; i < count; i++) {
340 			if ((++spc->spc_schedticks & 3) == 0)
341 				schedclock(p);
342 		}
343 	}
344 }
345 
346 /*
347  * Return information about system clocks.
348  */
349 int
350 sysctl_clockrate(char *where, size_t *sizep, void *newp)
351 {
352 	struct clockinfo clkinfo;
353 
354 	/*
355 	 * Construct clockinfo structure.
356 	 */
357 	memset(&clkinfo, 0, sizeof clkinfo);
358 	clkinfo.tick = tick;
359 	clkinfo.hz = hz;
360 	clkinfo.profhz = profhz;
361 	clkinfo.stathz = stathz;
362 	return (sysctl_rdstruct(where, sizep, newp, &clkinfo, sizeof(clkinfo)));
363 }
364