xref: /netbsd-src/sys/kern/kern_clock.c (revision e5d758f832e07a177fa24707c434b7ce26d0f762)
1 /*	$NetBSD: kern_clock.c,v 1.143 2020/12/05 18:17:01 thorpej Exp $	*/
2 
3 /*-
4  * Copyright (c) 2000, 2004, 2006, 2007, 2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9  * NASA Ames Research Center.
10  * This code is derived from software contributed to The NetBSD Foundation
11  * by Charles M. Hannum.
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  *
22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 /*-
36  * Copyright (c) 1982, 1986, 1991, 1993
37  *	The Regents of the University of California.  All rights reserved.
38  * (c) UNIX System Laboratories, Inc.
39  * All or some portions of this file are derived from material licensed
40  * to the University of California by American Telephone and Telegraph
41  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
42  * the permission of UNIX System Laboratories, Inc.
43  *
44  * Redistribution and use in source and binary forms, with or without
45  * modification, are permitted provided that the following conditions
46  * are met:
47  * 1. Redistributions of source code must retain the above copyright
48  *    notice, this list of conditions and the following disclaimer.
49  * 2. Redistributions in binary form must reproduce the above copyright
50  *    notice, this list of conditions and the following disclaimer in the
51  *    documentation and/or other materials provided with the distribution.
52  * 3. Neither the name of the University nor the names of its contributors
53  *    may be used to endorse or promote products derived from this software
54  *    without specific prior written permission.
55  *
56  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
57  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
58  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
59  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
60  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
61  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
62  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
63  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
64  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
65  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66  * SUCH DAMAGE.
67  *
68  *	@(#)kern_clock.c	8.5 (Berkeley) 1/21/94
69  */
70 
71 #include <sys/cdefs.h>
72 __KERNEL_RCSID(0, "$NetBSD: kern_clock.c,v 1.143 2020/12/05 18:17:01 thorpej Exp $");
73 
74 #ifdef _KERNEL_OPT
75 #include "opt_dtrace.h"
76 #include "opt_gprof.h"
77 #endif
78 
79 #include <sys/param.h>
80 #include <sys/systm.h>
81 #include <sys/callout.h>
82 #include <sys/kernel.h>
83 #include <sys/proc.h>
84 #include <sys/resourcevar.h>
85 #include <sys/signalvar.h>
86 #include <sys/sysctl.h>
87 #include <sys/timex.h>
88 #include <sys/sched.h>
89 #include <sys/time.h>
90 #include <sys/timetc.h>
91 #include <sys/cpu.h>
92 #include <sys/atomic.h>
93 
94 #ifdef GPROF
95 #include <sys/gmon.h>
96 #endif
97 
98 #ifdef KDTRACE_HOOKS
99 #include <sys/dtrace_bsd.h>
100 #include <sys/cpu.h>
101 
102 cyclic_clock_func_t	cyclic_clock_func[MAXCPUS];
103 #endif
104 
105 static int sysctl_kern_clockrate(SYSCTLFN_PROTO);
106 
107 /*
108  * Clock handling routines.
109  *
110  * This code is written to operate with two timers that run independently of
111  * each other.  The main clock, running hz times per second, is used to keep
112  * track of real time.  The second timer handles kernel and user profiling,
113  * and does resource use estimation.  If the second timer is programmable,
114  * it is randomized to avoid aliasing between the two clocks.  For example,
115  * the randomization prevents an adversary from always giving up the CPU
116  * just before its quantum expires.  Otherwise, it would never accumulate
117  * CPU ticks.  The mean frequency of the second timer is stathz.
118  *
119  * If no second timer exists, stathz will be zero; in this case we drive
120  * profiling and statistics off the main clock.  This WILL NOT be accurate;
121  * do not do it unless absolutely necessary.
122  *
123  * The statistics clock may (or may not) be run at a higher rate while
124  * profiling.  This profile clock runs at profhz.  We require that profhz
125  * be an integral multiple of stathz.
126  *
127  * If the statistics clock is running fast, it must be divided by the ratio
128  * profhz/stathz for statistics.  (For profiling, every tick counts.)
129  */
130 
131 int	stathz;
132 int	profhz;
133 int	profsrc;
134 int	schedhz;
135 int	profprocs;
136 int	hardclock_ticks;
137 static int hardscheddiv; /* hard => sched divider (used if schedhz == 0) */
138 static int psdiv;			/* prof => stat divider */
139 int	psratio;			/* ratio: prof / stat */
140 
141 static u_int get_intr_timecount(struct timecounter *);
142 
143 static struct timecounter intr_timecounter = {
144 	.tc_get_timecount	= get_intr_timecount,
145 	.tc_poll_pps		= NULL,
146 	.tc_counter_mask	= ~0u,
147 	.tc_frequency		= 0,
148 	.tc_name		= "clockinterrupt",
149 	/* quality - minimum implementation level for a clock */
150 	.tc_quality		= 0,
151 	.tc_priv		= NULL,
152 };
153 
154 static u_int
155 get_intr_timecount(struct timecounter *tc)
156 {
157 
158 	return (u_int)getticks();
159 }
160 
161 int
162 getticks(void)
163 {
164 	return atomic_load_relaxed(&hardclock_ticks);
165 }
166 
167 /*
168  * Initialize clock frequencies and start both clocks running.
169  */
170 void
171 initclocks(void)
172 {
173 	static struct sysctllog *clog;
174 	int i;
175 
176 	/*
177 	 * Set divisors to 1 (normal case) and let the machine-specific
178 	 * code do its bit.
179 	 */
180 	psdiv = 1;
181 
182 	/*
183 	 * Call cpu_initclocks() before registering the default
184 	 * timecounter, in case it needs to adjust hz.
185 	 */
186 	const int old_hz = hz;
187 	cpu_initclocks();
188 	if (old_hz != hz) {
189 		tick = 1000000 / hz;
190 		tickadj = (240000 / (60 * hz)) ? (240000 / (60 * hz)) : 1;
191 	}
192 
193 	/*
194 	 * provide minimum default time counter
195 	 * will only run at interrupt resolution
196 	 */
197 	intr_timecounter.tc_frequency = hz;
198 	tc_init(&intr_timecounter);
199 
200 	/*
201 	 * Compute profhz and stathz, fix profhz if needed.
202 	 */
203 	i = stathz ? stathz : hz;
204 	if (profhz == 0)
205 		profhz = i;
206 	psratio = profhz / i;
207 	if (schedhz == 0) {
208 		/* 16Hz is best */
209 		hardscheddiv = hz / 16;
210 		if (hardscheddiv <= 0)
211 			panic("hardscheddiv");
212 	}
213 
214 	sysctl_createv(&clog, 0, NULL, NULL,
215 		       CTLFLAG_PERMANENT,
216 		       CTLTYPE_STRUCT, "clockrate",
217 		       SYSCTL_DESCR("Kernel clock rates"),
218 		       sysctl_kern_clockrate, 0, NULL,
219 		       sizeof(struct clockinfo),
220 		       CTL_KERN, KERN_CLOCKRATE, CTL_EOL);
221 	sysctl_createv(&clog, 0, NULL, NULL,
222 		       CTLFLAG_PERMANENT,
223 		       CTLTYPE_INT, "hardclock_ticks",
224 		       SYSCTL_DESCR("Number of hardclock ticks"),
225 		       NULL, 0, &hardclock_ticks, sizeof(hardclock_ticks),
226 		       CTL_KERN, KERN_HARDCLOCK_TICKS, CTL_EOL);
227 }
228 
229 /*
230  * The real-time timer, interrupting hz times per second.
231  */
232 void
233 hardclock(struct clockframe *frame)
234 {
235 	struct lwp *l;
236 	struct cpu_info *ci;
237 
238 	ci = curcpu();
239 	l = ci->ci_onproc;
240 
241 	ptimer_tick(l, CLKF_USERMODE(frame));
242 
243 	/*
244 	 * If no separate statistics clock is available, run it from here.
245 	 */
246 	if (stathz == 0)
247 		statclock(frame);
248 	/*
249 	 * If no separate schedclock is provided, call it here
250 	 * at about 16 Hz.
251 	 */
252 	if (schedhz == 0) {
253 		if ((int)(--ci->ci_schedstate.spc_schedticks) <= 0) {
254 			schedclock(l);
255 			ci->ci_schedstate.spc_schedticks = hardscheddiv;
256 		}
257 	}
258 	if ((--ci->ci_schedstate.spc_ticks) <= 0)
259 		sched_tick(ci);
260 
261 	if (CPU_IS_PRIMARY(ci)) {
262 		atomic_store_relaxed(&hardclock_ticks,
263 		    atomic_load_relaxed(&hardclock_ticks) + 1);
264 		tc_ticktock();
265 	}
266 
267 	/*
268 	 * Update real-time timeout queue.
269 	 */
270 	callout_hardclock();
271 }
272 
273 /*
274  * Start profiling on a process.
275  *
276  * Kernel profiling passes proc0 which never exits and hence
277  * keeps the profile clock running constantly.
278  */
279 void
280 startprofclock(struct proc *p)
281 {
282 
283 	KASSERT(mutex_owned(&p->p_stmutex));
284 
285 	if ((p->p_stflag & PST_PROFIL) == 0) {
286 		p->p_stflag |= PST_PROFIL;
287 		/*
288 		 * This is only necessary if using the clock as the
289 		 * profiling source.
290 		 */
291 		if (++profprocs == 1 && stathz != 0)
292 			psdiv = psratio;
293 	}
294 }
295 
296 /*
297  * Stop profiling on a process.
298  */
299 void
300 stopprofclock(struct proc *p)
301 {
302 
303 	KASSERT(mutex_owned(&p->p_stmutex));
304 
305 	if (p->p_stflag & PST_PROFIL) {
306 		p->p_stflag &= ~PST_PROFIL;
307 		/*
308 		 * This is only necessary if using the clock as the
309 		 * profiling source.
310 		 */
311 		if (--profprocs == 0 && stathz != 0)
312 			psdiv = 1;
313 	}
314 }
315 
316 void
317 schedclock(struct lwp *l)
318 {
319 	if ((l->l_flag & LW_IDLE) != 0)
320 		return;
321 
322 	sched_schedclock(l);
323 }
324 
325 /*
326  * Statistics clock.  Grab profile sample, and if divider reaches 0,
327  * do process and kernel statistics.
328  */
329 void
330 statclock(struct clockframe *frame)
331 {
332 #ifdef GPROF
333 	struct gmonparam *g;
334 	intptr_t i;
335 #endif
336 	struct cpu_info *ci = curcpu();
337 	struct schedstate_percpu *spc = &ci->ci_schedstate;
338 	struct proc *p;
339 	struct lwp *l;
340 
341 	/*
342 	 * Notice changes in divisor frequency, and adjust clock
343 	 * frequency accordingly.
344 	 */
345 	if (spc->spc_psdiv != psdiv) {
346 		spc->spc_psdiv = psdiv;
347 		spc->spc_pscnt = psdiv;
348 		if (psdiv == 1) {
349 			setstatclockrate(stathz);
350 		} else {
351 			setstatclockrate(profhz);
352 		}
353 	}
354 	l = ci->ci_onproc;
355 	if ((l->l_flag & LW_IDLE) != 0) {
356 		/*
357 		 * don't account idle lwps as swapper.
358 		 */
359 		p = NULL;
360 	} else {
361 		p = l->l_proc;
362 		mutex_spin_enter(&p->p_stmutex);
363 	}
364 
365 	if (CLKF_USERMODE(frame)) {
366 		KASSERT(p != NULL);
367 		if ((p->p_stflag & PST_PROFIL) && profsrc == PROFSRC_CLOCK)
368 			addupc_intr(l, CLKF_PC(frame));
369 		if (--spc->spc_pscnt > 0) {
370 			mutex_spin_exit(&p->p_stmutex);
371 			return;
372 		}
373 
374 		/*
375 		 * Came from user mode; CPU was in user state.
376 		 * If this process is being profiled record the tick.
377 		 */
378 		p->p_uticks++;
379 		if (p->p_nice > NZERO)
380 			spc->spc_cp_time[CP_NICE]++;
381 		else
382 			spc->spc_cp_time[CP_USER]++;
383 	} else {
384 #ifdef GPROF
385 		/*
386 		 * Kernel statistics are just like addupc_intr, only easier.
387 		 */
388 		g = &_gmonparam;
389 		if (profsrc == PROFSRC_CLOCK && g->state == GMON_PROF_ON) {
390 			i = CLKF_PC(frame) - g->lowpc;
391 			if (i < g->textsize) {
392 				i /= HISTFRACTION * sizeof(*g->kcount);
393 				g->kcount[i]++;
394 			}
395 		}
396 #endif
397 #ifdef LWP_PC
398 		if (p != NULL && profsrc == PROFSRC_CLOCK &&
399 		    (p->p_stflag & PST_PROFIL)) {
400 			addupc_intr(l, LWP_PC(l));
401 		}
402 #endif
403 		if (--spc->spc_pscnt > 0) {
404 			if (p != NULL)
405 				mutex_spin_exit(&p->p_stmutex);
406 			return;
407 		}
408 		/*
409 		 * Came from kernel mode, so we were:
410 		 * - handling an interrupt,
411 		 * - doing syscall or trap work on behalf of the current
412 		 *   user process, or
413 		 * - spinning in the idle loop.
414 		 * Whichever it is, charge the time as appropriate.
415 		 * Note that we charge interrupts to the current process,
416 		 * regardless of whether they are ``for'' that process,
417 		 * so that we know how much of its real time was spent
418 		 * in ``non-process'' (i.e., interrupt) work.
419 		 */
420 		if (CLKF_INTR(frame) || (curlwp->l_pflag & LP_INTR) != 0) {
421 			if (p != NULL) {
422 				p->p_iticks++;
423 			}
424 			spc->spc_cp_time[CP_INTR]++;
425 		} else if (p != NULL) {
426 			p->p_sticks++;
427 			spc->spc_cp_time[CP_SYS]++;
428 		} else {
429 			spc->spc_cp_time[CP_IDLE]++;
430 		}
431 	}
432 	spc->spc_pscnt = psdiv;
433 
434 	if (p != NULL) {
435 		atomic_inc_uint(&l->l_cpticks);
436 		mutex_spin_exit(&p->p_stmutex);
437 	}
438 
439 #ifdef KDTRACE_HOOKS
440 	cyclic_clock_func_t func = cyclic_clock_func[cpu_index(ci)];
441 	if (func) {
442 		(*func)((struct clockframe *)frame);
443 	}
444 #endif
445 }
446 
447 /*
448  * sysctl helper routine for kern.clockrate. Assembles a struct on
449  * the fly to be returned to the caller.
450  */
451 static int
452 sysctl_kern_clockrate(SYSCTLFN_ARGS)
453 {
454 	struct clockinfo clkinfo;
455 	struct sysctlnode node;
456 
457 	clkinfo.tick = tick;
458 	clkinfo.tickadj = tickadj;
459 	clkinfo.hz = hz;
460 	clkinfo.profhz = profhz;
461 	clkinfo.stathz = stathz ? stathz : hz;
462 
463 	node = *rnode;
464 	node.sysctl_data = &clkinfo;
465 	return (sysctl_lookup(SYSCTLFN_CALL(&node)));
466 }
467