xref: /openbsd-src/sys/kern/kern_clock.c (revision 8afcf90fb39e4a84606e93137c2b6c20f44312cb)
1 /*	$OpenBSD: kern_clock.c,v 1.113 2023/08/12 13:19:28 miod 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 defined(MULTIPROCESSOR) || defined(__hppa__) /* XXX */
115 	struct cpu_info *ci = curcpu();
116 #endif
117 
118 #if NDT > 0
119 	DT_ENTER(profile, NULL);
120 	if (CPU_IS_PRIMARY(ci))
121 		DT_ENTER(interval, NULL);
122 #endif
123 
124 	/*
125 	 * If we are not the primary CPU, we're not allowed to do
126 	 * any more work.
127 	 */
128 	if (CPU_IS_PRIMARY(ci) == 0)
129 		return;
130 
131 	tc_ticktock();
132 	ticks++;
133 	jiffies++;
134 
135 	/*
136 	 * Update the timeout wheel.
137 	 */
138 	timeout_hardclock_update();
139 }
140 
141 /*
142  * Compute number of hz in the specified amount of time.
143  */
144 int
145 tvtohz(const struct timeval *tv)
146 {
147 	unsigned long nticks;
148 	time_t sec;
149 	long usec;
150 
151 	/*
152 	 * If the number of usecs in the whole seconds part of the time
153 	 * fits in a long, then the total number of usecs will
154 	 * fit in an unsigned long.  Compute the total and convert it to
155 	 * ticks, rounding up and adding 1 to allow for the current tick
156 	 * to expire.  Rounding also depends on unsigned long arithmetic
157 	 * to avoid overflow.
158 	 *
159 	 * Otherwise, if the number of ticks in the whole seconds part of
160 	 * the time fits in a long, then convert the parts to
161 	 * ticks separately and add, using similar rounding methods and
162 	 * overflow avoidance.  This method would work in the previous
163 	 * case but it is slightly slower and assumes that hz is integral.
164 	 *
165 	 * Otherwise, round the time down to the maximum
166 	 * representable value.
167 	 *
168 	 * If ints have 32 bits, then the maximum value for any timeout in
169 	 * 10ms ticks is 248 days.
170 	 */
171 	sec = tv->tv_sec;
172 	usec = tv->tv_usec;
173 	if (sec < 0 || (sec == 0 && usec <= 0))
174 		nticks = 0;
175 	else if (sec <= LONG_MAX / 1000000)
176 		nticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
177 		    / tick + 1;
178 	else if (sec <= LONG_MAX / hz)
179 		nticks = sec * hz
180 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
181 	else
182 		nticks = LONG_MAX;
183 	if (nticks > INT_MAX)
184 		nticks = INT_MAX;
185 	return ((int)nticks);
186 }
187 
188 int
189 tstohz(const struct timespec *ts)
190 {
191 	struct timeval tv;
192 	TIMESPEC_TO_TIMEVAL(&tv, ts);
193 
194 	/* Round up. */
195 	if ((ts->tv_nsec % 1000) != 0) {
196 		tv.tv_usec += 1;
197 		if (tv.tv_usec >= 1000000) {
198 			tv.tv_usec -= 1000000;
199 			tv.tv_sec += 1;
200 		}
201 	}
202 
203 	return (tvtohz(&tv));
204 }
205 
206 /*
207  * Start profiling on a process.
208  *
209  * Kernel profiling passes proc0 which never exits and hence
210  * keeps the profile clock running constantly.
211  */
212 void
213 startprofclock(struct process *pr)
214 {
215 	int s;
216 
217 	if ((pr->ps_flags & PS_PROFIL) == 0) {
218 		atomic_setbits_int(&pr->ps_flags, PS_PROFIL);
219 		if (++profprocs == 1) {
220 			s = splstatclock();
221 			setstatclockrate(profhz);
222 			splx(s);
223 		}
224 	}
225 }
226 
227 /*
228  * Stop profiling on a process.
229  */
230 void
231 stopprofclock(struct process *pr)
232 {
233 	int s;
234 
235 	if (pr->ps_flags & PS_PROFIL) {
236 		atomic_clearbits_int(&pr->ps_flags, PS_PROFIL);
237 		if (--profprocs == 0) {
238 			s = splstatclock();
239 			setstatclockrate(stathz);
240 			splx(s);
241 		}
242 	}
243 }
244 
245 /*
246  * Statistics clock.  Grab profile sample, and if divider reaches 0,
247  * do process and kernel statistics.
248  */
249 void
250 statclock(struct clockframe *frame)
251 {
252 	struct cpu_info *ci = curcpu();
253 	struct schedstate_percpu *spc = &ci->ci_schedstate;
254 	struct proc *p = curproc;
255 	struct process *pr;
256 
257 	if (CLKF_USERMODE(frame)) {
258 		pr = p->p_p;
259 		/*
260 		 * Came from user mode; CPU was in user state.
261 		 * If this process is being profiled record the tick.
262 		 */
263 		p->p_uticks++;
264 		if (pr->ps_nice > NZERO)
265 			spc->spc_cp_time[CP_NICE]++;
266 		else
267 			spc->spc_cp_time[CP_USER]++;
268 	} else {
269 		/*
270 		 * Came from kernel mode, so we were:
271 		 * - spinning on a lock
272 		 * - handling an interrupt,
273 		 * - doing syscall or trap work on behalf of the current
274 		 *   user process, or
275 		 * - spinning in the idle loop.
276 		 * Whichever it is, charge the time as appropriate.
277 		 * Note that we charge interrupts to the current process,
278 		 * regardless of whether they are ``for'' that process,
279 		 * so that we know how much of its real time was spent
280 		 * in ``non-process'' (i.e., interrupt) work.
281 		 */
282 		if (CLKF_INTR(frame)) {
283 			if (p != NULL)
284 				p->p_iticks++;
285 			spc->spc_cp_time[spc->spc_spinning ?
286 			    CP_SPIN : CP_INTR]++;
287 		} else if (p != NULL && p != spc->spc_idleproc) {
288 			p->p_sticks++;
289 			spc->spc_cp_time[spc->spc_spinning ?
290 			    CP_SPIN : CP_SYS]++;
291 		} else
292 			spc->spc_cp_time[spc->spc_spinning ?
293 			    CP_SPIN : CP_IDLE]++;
294 	}
295 
296 	if (p != NULL) {
297 		p->p_cpticks++;
298 		/*
299 		 * If no schedclock is provided, call it here at ~~12-25 Hz;
300 		 * ~~16 Hz is best
301 		 */
302 		if (schedhz == 0) {
303 			if ((++spc->spc_schedticks & 3) == 0)
304 				schedclock(p);
305 		}
306 	}
307 }
308 
309 /*
310  * Return information about system clocks.
311  */
312 int
313 sysctl_clockrate(char *where, size_t *sizep, void *newp)
314 {
315 	struct clockinfo clkinfo;
316 
317 	/*
318 	 * Construct clockinfo structure.
319 	 */
320 	memset(&clkinfo, 0, sizeof clkinfo);
321 	clkinfo.tick = tick;
322 	clkinfo.hz = hz;
323 	clkinfo.profhz = profhz;
324 	clkinfo.stathz = stathz;
325 	return (sysctl_rdstruct(where, sizep, newp, &clkinfo, sizeof(clkinfo)));
326 }
327