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