xref: /openbsd/sys/kern/kern_clock.c (revision 73471bf0)
1 /*	$OpenBSD: kern_clock.c,v 1.102 2021/01/13 16:28:49 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/signalvar.h>
49 #include <sys/sysctl.h>
50 #include <sys/sched.h>
51 #include <sys/timetc.h>
52 
53 
54 #if defined(GPROF) || defined(DDBPROF)
55 #include <sys/gmon.h>
56 #endif
57 
58 #include "dt.h"
59 #if NDT > 0
60 #include <dev/dt/dtvar.h>
61 #endif
62 
63 /*
64  * Clock handling routines.
65  *
66  * This code is written to operate with two timers that run independently of
67  * each other.  The main clock, running hz times per second, is used to keep
68  * track of real time.  The second timer handles kernel and user profiling,
69  * and does resource use estimation.  If the second timer is programmable,
70  * it is randomized to avoid aliasing between the two clocks.  For example,
71  * the randomization prevents an adversary from always giving up the cpu
72  * just before its quantum expires.  Otherwise, it would never accumulate
73  * cpu ticks.  The mean frequency of the second timer is stathz.
74  *
75  * If no second timer exists, stathz will be zero; in this case we drive
76  * profiling and statistics off the main clock.  This WILL NOT be accurate;
77  * do not do it unless absolutely necessary.
78  *
79  * The statistics clock may (or may not) be run at a higher rate while
80  * profiling.  This profile clock runs at profhz.  We require that profhz
81  * be an integral multiple of stathz.
82  *
83  * If the statistics clock is running fast, it must be divided by the ratio
84  * profhz/stathz for statistics.  (For profiling, every tick counts.)
85  */
86 
87 int	stathz;
88 int	schedhz;
89 int	profhz;
90 int	profprocs;
91 int	ticks;
92 static int psdiv, pscnt;		/* prof => stat divider */
93 int	psratio;			/* ratio: prof / stat */
94 
95 volatile unsigned long jiffies;		/* XXX Linux API for drm(4) */
96 
97 /*
98  * Initialize clock frequencies and start both clocks running.
99  */
100 void
101 initclocks(void)
102 {
103 	int i;
104 
105 	ticks = INT_MAX - (15 * 60 * hz);
106 	jiffies = ULONG_MAX - (10 * 60 * hz);
107 
108 	/*
109 	 * Set divisors to 1 (normal case) and let the machine-specific
110 	 * code do its bit.
111 	 */
112 	psdiv = pscnt = 1;
113 	cpu_initclocks();
114 
115 	/*
116 	 * Compute profhz/stathz, and fix profhz if needed.
117 	 */
118 	i = stathz ? stathz : hz;
119 	if (profhz == 0)
120 		profhz = i;
121 	psratio = profhz / i;
122 
123 	inittimecounter();
124 }
125 
126 /*
127  * hardclock does the accounting needed for ITIMER_PROF and ITIMER_VIRTUAL.
128  * We don't want to send signals with psignal from hardclock because it makes
129  * MULTIPROCESSOR locking very complicated. Instead, to use an idea from
130  * FreeBSD, we set a flag on the thread and when it goes to return to
131  * userspace it signals itself.
132  */
133 
134 /*
135  * The real-time timer, interrupting hz times per second.
136  */
137 void
138 hardclock(struct clockframe *frame)
139 {
140 	struct proc *p;
141 	struct cpu_info *ci = curcpu();
142 
143 	p = curproc;
144 	if (p && ((p->p_flag & (P_SYSTEM | P_WEXIT)) == 0)) {
145 		struct process *pr = p->p_p;
146 
147 		/*
148 		 * Run current process's virtual and profile time, as needed.
149 		 */
150 		if (CLKF_USERMODE(frame) &&
151 		    timespecisset(&pr->ps_timer[ITIMER_VIRTUAL].it_value) &&
152 		    itimerdecr(&pr->ps_timer[ITIMER_VIRTUAL], tick_nsec) == 0) {
153 			atomic_setbits_int(&p->p_flag, P_ALRMPEND);
154 			need_proftick(p);
155 		}
156 		if (timespecisset(&pr->ps_timer[ITIMER_PROF].it_value) &&
157 		    itimerdecr(&pr->ps_timer[ITIMER_PROF], tick_nsec) == 0) {
158 			atomic_setbits_int(&p->p_flag, P_PROFPEND);
159 			need_proftick(p);
160 		}
161 	}
162 
163 	/*
164 	 * If no separate statistics clock is available, run it from here.
165 	 */
166 	if (stathz == 0)
167 		statclock(frame);
168 
169 	if (--ci->ci_schedstate.spc_rrticks <= 0)
170 		roundrobin(ci);
171 
172 #if NDT > 0
173 	DT_ENTER(profile, NULL);
174 	if (CPU_IS_PRIMARY(ci))
175 		DT_ENTER(interval, NULL);
176 #endif
177 
178 	/*
179 	 * If we are not the primary CPU, we're not allowed to do
180 	 * any more work.
181 	 */
182 	if (CPU_IS_PRIMARY(ci) == 0)
183 		return;
184 
185 	tc_ticktock();
186 	ticks++;
187 	jiffies++;
188 
189 	/*
190 	 * Update the timeout wheel.
191 	 */
192 	timeout_hardclock_update();
193 }
194 
195 /*
196  * Compute number of hz in the specified amount of time.
197  */
198 int
199 tvtohz(const struct timeval *tv)
200 {
201 	unsigned long nticks;
202 	time_t sec;
203 	long usec;
204 
205 	/*
206 	 * If the number of usecs in the whole seconds part of the time
207 	 * fits in a long, then the total number of usecs will
208 	 * fit in an unsigned long.  Compute the total and convert it to
209 	 * ticks, rounding up and adding 1 to allow for the current tick
210 	 * to expire.  Rounding also depends on unsigned long arithmetic
211 	 * to avoid overflow.
212 	 *
213 	 * Otherwise, if the number of ticks in the whole seconds part of
214 	 * the time fits in a long, then convert the parts to
215 	 * ticks separately and add, using similar rounding methods and
216 	 * overflow avoidance.  This method would work in the previous
217 	 * case but it is slightly slower and assumes that hz is integral.
218 	 *
219 	 * Otherwise, round the time down to the maximum
220 	 * representable value.
221 	 *
222 	 * If ints have 32 bits, then the maximum value for any timeout in
223 	 * 10ms ticks is 248 days.
224 	 */
225 	sec = tv->tv_sec;
226 	usec = tv->tv_usec;
227 	if (sec < 0 || (sec == 0 && usec <= 0))
228 		nticks = 0;
229 	else if (sec <= LONG_MAX / 1000000)
230 		nticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
231 		    / tick + 1;
232 	else if (sec <= LONG_MAX / hz)
233 		nticks = sec * hz
234 		    + ((unsigned long)usec + (tick - 1)) / tick + 1;
235 	else
236 		nticks = LONG_MAX;
237 	if (nticks > INT_MAX)
238 		nticks = INT_MAX;
239 	return ((int)nticks);
240 }
241 
242 int
243 tstohz(const struct timespec *ts)
244 {
245 	struct timeval tv;
246 	TIMESPEC_TO_TIMEVAL(&tv, ts);
247 
248 	/* Round up. */
249 	if ((ts->tv_nsec % 1000) != 0) {
250 		tv.tv_usec += 1;
251 		if (tv.tv_usec >= 1000000) {
252 			tv.tv_usec -= 1000000;
253 			tv.tv_sec += 1;
254 		}
255 	}
256 
257 	return (tvtohz(&tv));
258 }
259 
260 /*
261  * Start profiling on a process.
262  *
263  * Kernel profiling passes proc0 which never exits and hence
264  * keeps the profile clock running constantly.
265  */
266 void
267 startprofclock(struct process *pr)
268 {
269 	int s;
270 
271 	if ((pr->ps_flags & PS_PROFIL) == 0) {
272 		atomic_setbits_int(&pr->ps_flags, PS_PROFIL);
273 		if (++profprocs == 1 && stathz != 0) {
274 			s = splstatclock();
275 			psdiv = pscnt = psratio;
276 			setstatclockrate(profhz);
277 			splx(s);
278 		}
279 	}
280 }
281 
282 /*
283  * Stop profiling on a process.
284  */
285 void
286 stopprofclock(struct process *pr)
287 {
288 	int s;
289 
290 	if (pr->ps_flags & PS_PROFIL) {
291 		atomic_clearbits_int(&pr->ps_flags, PS_PROFIL);
292 		if (--profprocs == 0 && stathz != 0) {
293 			s = splstatclock();
294 			psdiv = pscnt = 1;
295 			setstatclockrate(stathz);
296 			splx(s);
297 		}
298 	}
299 }
300 
301 /*
302  * Statistics clock.  Grab profile sample, and if divider reaches 0,
303  * do process and kernel statistics.
304  */
305 void
306 statclock(struct clockframe *frame)
307 {
308 #if defined(GPROF) || defined(DDBPROF)
309 	struct gmonparam *g;
310 	u_long i;
311 #endif
312 	struct cpu_info *ci = curcpu();
313 	struct schedstate_percpu *spc = &ci->ci_schedstate;
314 	struct proc *p = curproc;
315 	struct process *pr;
316 
317 	/*
318 	 * Notice changes in divisor frequency, and adjust clock
319 	 * frequency accordingly.
320 	 */
321 	if (spc->spc_psdiv != psdiv) {
322 		spc->spc_psdiv = psdiv;
323 		spc->spc_pscnt = psdiv;
324 		if (psdiv == 1) {
325 			setstatclockrate(stathz);
326 		} else {
327 			setstatclockrate(profhz);
328 		}
329 	}
330 
331 	if (CLKF_USERMODE(frame)) {
332 		pr = p->p_p;
333 		if (pr->ps_flags & PS_PROFIL)
334 			addupc_intr(p, CLKF_PC(frame));
335 		if (--spc->spc_pscnt > 0)
336 			return;
337 		/*
338 		 * Came from user mode; CPU was in user state.
339 		 * If this process is being profiled record the tick.
340 		 */
341 		p->p_uticks++;
342 		if (pr->ps_nice > NZERO)
343 			spc->spc_cp_time[CP_NICE]++;
344 		else
345 			spc->spc_cp_time[CP_USER]++;
346 	} else {
347 #if defined(GPROF) || defined(DDBPROF)
348 		/*
349 		 * Kernel statistics are just like addupc_intr, only easier.
350 		 */
351 		g = ci->ci_gmon;
352 		if (g != NULL && g->state == GMON_PROF_ON) {
353 			i = CLKF_PC(frame) - g->lowpc;
354 			if (i < g->textsize) {
355 				i /= HISTFRACTION * sizeof(*g->kcount);
356 				g->kcount[i]++;
357 			}
358 		}
359 #endif
360 #if defined(PROC_PC)
361 		if (p != NULL && p->p_p->ps_flags & PS_PROFIL)
362 			addupc_intr(p, PROC_PC(p));
363 #endif
364 		if (--spc->spc_pscnt > 0)
365 			return;
366 		/*
367 		 * Came from kernel mode, so we were:
368 		 * - spinning on a lock
369 		 * - handling an interrupt,
370 		 * - doing syscall or trap work on behalf of the current
371 		 *   user process, or
372 		 * - spinning in the idle loop.
373 		 * Whichever it is, charge the time as appropriate.
374 		 * Note that we charge interrupts to the current process,
375 		 * regardless of whether they are ``for'' that process,
376 		 * so that we know how much of its real time was spent
377 		 * in ``non-process'' (i.e., interrupt) work.
378 		 */
379 		if (CLKF_INTR(frame)) {
380 			if (p != NULL)
381 				p->p_iticks++;
382 			spc->spc_cp_time[spc->spc_spinning ?
383 			    CP_SPIN : CP_INTR]++;
384 		} else if (p != NULL && p != spc->spc_idleproc) {
385 			p->p_sticks++;
386 			spc->spc_cp_time[spc->spc_spinning ?
387 			    CP_SPIN : CP_SYS]++;
388 		} else
389 			spc->spc_cp_time[spc->spc_spinning ?
390 			    CP_SPIN : CP_IDLE]++;
391 	}
392 	spc->spc_pscnt = psdiv;
393 
394 	if (p != NULL) {
395 		p->p_cpticks++;
396 		/*
397 		 * If no schedclock is provided, call it here at ~~12-25 Hz;
398 		 * ~~16 Hz is best
399 		 */
400 		if (schedhz == 0) {
401 			if ((++spc->spc_schedticks & 3) == 0)
402 				schedclock(p);
403 		}
404 	}
405 }
406 
407 /*
408  * Return information about system clocks.
409  */
410 int
411 sysctl_clockrate(char *where, size_t *sizep, void *newp)
412 {
413 	struct clockinfo clkinfo;
414 
415 	/*
416 	 * Construct clockinfo structure.
417 	 */
418 	memset(&clkinfo, 0, sizeof clkinfo);
419 	clkinfo.tick = tick;
420 	clkinfo.hz = hz;
421 	clkinfo.profhz = profhz;
422 	clkinfo.stathz = stathz ? stathz : hz;
423 	return (sysctl_rdstruct(where, sizep, newp, &clkinfo, sizeof(clkinfo)));
424 }
425