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