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