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