1 /*        $NetBSD: kern_clock.c,v 1.151 2023/09/02 17:44:59 riastradh 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.151 2023/09/02 17:44:59 riastradh Exp $");
73 
74 #ifdef _KERNEL_OPT
75 #include "opt_dtrace.h"
76 #include "opt_gprof.h"
77 #include "opt_multiprocessor.h"
78 #endif
79 
80 #include <sys/param.h>
81 #include <sys/systm.h>
82 #include <sys/callout.h>
83 #include <sys/kernel.h>
84 #include <sys/proc.h>
85 #include <sys/resourcevar.h>
86 #include <sys/signalvar.h>
87 #include <sys/sysctl.h>
88 #include <sys/timex.h>
89 #include <sys/sched.h>
90 #include <sys/time.h>
91 #include <sys/timetc.h>
92 #include <sys/cpu.h>
93 #include <sys/atomic.h>
94 #include <sys/rndsource.h>
95 #include <sys/heartbeat.h>
96 
97 #ifdef GPROF
98 #include <sys/gmon.h>
99 #endif
100 
101 #ifdef KDTRACE_HOOKS
102 #include <sys/dtrace_bsd.h>
103 #include <sys/cpu.h>
104 
105 cyclic_clock_func_t cyclic_clock_func[MAXCPUS];
106 #endif
107 
108 static int sysctl_kern_clockrate(SYSCTLFN_PROTO);
109 
110 /*
111  * Clock handling routines.
112  *
113  * This code is written to operate with two timers that run independently of
114  * each other.  The main clock, running hz times per second, is used to keep
115  * track of real time.  The second timer handles kernel and user profiling,
116  * and does resource use estimation.  If the second timer is programmable,
117  * it is randomized to avoid aliasing between the two clocks.  For example,
118  * the randomization prevents an adversary from always giving up the CPU
119  * just before its quantum expires.  Otherwise, it would never accumulate
120  * CPU ticks.  The mean frequency of the second timer is stathz.
121  *
122  * If no second timer exists, stathz will be zero; in this case we drive
123  * profiling and statistics off the main clock.  This WILL NOT be accurate;
124  * do not do it unless absolutely necessary.
125  *
126  * The statistics clock may (or may not) be run at a higher rate while
127  * profiling.  This profile clock runs at profhz.  We require that profhz
128  * be an integral multiple of stathz.
129  *
130  * If the statistics clock is running fast, it must be divided by the ratio
131  * profhz/stathz for statistics.  (For profiling, every tick counts.)
132  */
133 
134 int       stathz;
135 int       profhz;
136 int       profsrc;
137 int       schedhz;
138 int       profprocs;
139 static int hardclock_ticks;
140 static int hardscheddiv; /* hard => sched divider (used if schedhz == 0) */
141 static int psdiv;                       /* prof => stat divider */
142 int       psratio;                      /* ratio: prof / stat */
143 
144 struct clockrnd {
145           struct krndsource source;
146           unsigned needed;
147 };
148 
149 static struct clockrnd hardclockrnd __aligned(COHERENCY_UNIT);
150 static struct clockrnd statclockrnd __aligned(COHERENCY_UNIT);
151 
152 static void
clockrnd_get(size_t needed,void * cookie)153 clockrnd_get(size_t needed, void *cookie)
154 {
155           struct clockrnd *C = cookie;
156 
157           /* Start sampling.  */
158           atomic_store_relaxed(&C->needed, 2*NBBY*needed);
159 }
160 
161 static void
clockrnd_sample(struct clockrnd * C)162 clockrnd_sample(struct clockrnd *C)
163 {
164           struct cpu_info *ci = curcpu();
165 
166           /* If there's nothing needed right now, stop here.  */
167           if (__predict_true(atomic_load_relaxed(&C->needed) == 0))
168                     return;
169 
170           /*
171            * If we're not the primary core of a package, we're probably
172            * driven by the same clock as the primary core, so don't
173            * bother.
174            */
175           if (ci != ci->ci_package1st)
176                     return;
177 
178           /* Take a sample and enter it into the pool.  */
179           rnd_add_uint32(&C->source, 0);
180 
181           /*
182            * On the primary CPU, count down.  Using an atomic decrement
183            * here isn't really necessary -- on every platform we care
184            * about, stores to unsigned int are atomic, and the only other
185            * memory operation that could happen here is for another CPU
186            * to store a higher value for needed.  But using an atomic
187            * decrement avoids giving the impression of data races, and is
188            * unlikely to hurt because only one CPU will ever be writing
189            * to the location.
190            */
191           if (CPU_IS_PRIMARY(curcpu())) {
192                     unsigned needed __diagused;
193 
194                     needed = atomic_dec_uint_nv(&C->needed);
195                     KASSERT(needed != UINT_MAX);
196           }
197 }
198 
199 static u_int get_intr_timecount(struct timecounter *);
200 
201 static struct timecounter intr_timecounter = {
202           .tc_get_timecount   = get_intr_timecount,
203           .tc_poll_pps                  = NULL,
204           .tc_counter_mask    = ~0u,
205           .tc_frequency                 = 0,
206           .tc_name            = "clockinterrupt",
207           /* quality - minimum implementation level for a clock */
208           .tc_quality                   = 0,
209           .tc_priv            = NULL,
210 };
211 
212 static u_int
get_intr_timecount(struct timecounter * tc)213 get_intr_timecount(struct timecounter *tc)
214 {
215 
216           return (u_int)getticks();
217 }
218 
219 int
getticks(void)220 getticks(void)
221 {
222           return atomic_load_relaxed(&hardclock_ticks);
223 }
224 
225 /*
226  * Initialize clock frequencies and start both clocks running.
227  */
228 void
initclocks(void)229 initclocks(void)
230 {
231           static struct sysctllog *clog;
232           int i;
233 
234           /*
235            * Set divisors to 1 (normal case) and let the machine-specific
236            * code do its bit.
237            */
238           psdiv = 1;
239 
240           /*
241            * Call cpu_initclocks() before registering the default
242            * timecounter, in case it needs to adjust hz.
243            */
244           const int old_hz = hz;
245           cpu_initclocks();
246           if (old_hz != hz) {
247                     tick = 1000000 / hz;
248                     tickadj = (240000 / (60 * hz)) ? (240000 / (60 * hz)) : 1;
249           }
250 
251           /*
252            * provide minimum default time counter
253            * will only run at interrupt resolution
254            */
255           intr_timecounter.tc_frequency = hz;
256           tc_init(&intr_timecounter);
257 
258           /*
259            * Compute profhz and stathz, fix profhz if needed.
260            */
261           i = stathz ? stathz : hz;
262           if (profhz == 0)
263                     profhz = i;
264           psratio = profhz / i;
265           if (schedhz == 0) {
266                     /* 16Hz is best */
267                     hardscheddiv = hz / 16;
268                     if (hardscheddiv <= 0)
269                               panic("hardscheddiv");
270           }
271 
272           sysctl_createv(&clog, 0, NULL, NULL,
273                            CTLFLAG_PERMANENT,
274                            CTLTYPE_STRUCT, "clockrate",
275                            SYSCTL_DESCR("Kernel clock rates"),
276                            sysctl_kern_clockrate, 0, NULL,
277                            sizeof(struct clockinfo),
278                            CTL_KERN, KERN_CLOCKRATE, CTL_EOL);
279           sysctl_createv(&clog, 0, NULL, NULL,
280                            CTLFLAG_PERMANENT,
281                            CTLTYPE_INT, "hardclock_ticks",
282                            SYSCTL_DESCR("Number of hardclock ticks"),
283                            NULL, 0, &hardclock_ticks, sizeof(hardclock_ticks),
284                            CTL_KERN, KERN_HARDCLOCK_TICKS, CTL_EOL);
285 
286           rndsource_setcb(&hardclockrnd.source, clockrnd_get, &hardclockrnd);
287           rnd_attach_source(&hardclockrnd.source, "hardclock", RND_TYPE_SKEW,
288               RND_FLAG_COLLECT_TIME|RND_FLAG_ESTIMATE_TIME|RND_FLAG_HASCB);
289           if (stathz) {
290                     rndsource_setcb(&statclockrnd.source, clockrnd_get,
291                         &statclockrnd);
292                     rnd_attach_source(&statclockrnd.source, "statclock",
293                         RND_TYPE_SKEW,
294                         (RND_FLAG_COLLECT_TIME|RND_FLAG_ESTIMATE_TIME|
295                               RND_FLAG_HASCB));
296           }
297 }
298 
299 /*
300  * The real-time timer, interrupting hz times per second.
301  */
302 void
hardclock(struct clockframe * frame)303 hardclock(struct clockframe *frame)
304 {
305           struct lwp *l;
306           struct cpu_info *ci;
307 
308           clockrnd_sample(&hardclockrnd);
309 
310           ci = curcpu();
311           l = ci->ci_onproc;
312 
313           ptimer_tick(l, CLKF_USERMODE(frame));
314 
315           /*
316            * If no separate statistics clock is available, run it from here.
317            */
318           if (stathz == 0)
319                     statclock(frame);
320           /*
321            * If no separate schedclock is provided, call it here
322            * at about 16 Hz.
323            */
324           if (schedhz == 0) {
325                     if ((int)(--ci->ci_schedstate.spc_schedticks) <= 0) {
326                               schedclock(l);
327                               ci->ci_schedstate.spc_schedticks = hardscheddiv;
328                     }
329           }
330           if ((--ci->ci_schedstate.spc_ticks) <= 0)
331                     sched_tick(ci);
332 
333           if (CPU_IS_PRIMARY(ci)) {
334                     atomic_store_relaxed(&hardclock_ticks,
335                         atomic_load_relaxed(&hardclock_ticks) + 1);
336                     tc_ticktock();
337           }
338 
339           /*
340            * Make sure the CPUs and timecounter are making progress.
341            */
342           heartbeat();
343 
344           /*
345            * Update real-time timeout queue.
346            */
347           callout_hardclock();
348 }
349 
350 /*
351  * Start profiling on a process.
352  *
353  * Kernel profiling passes proc0 which never exits and hence
354  * keeps the profile clock running constantly.
355  */
356 void
startprofclock(struct proc * p)357 startprofclock(struct proc *p)
358 {
359 
360           KASSERT(mutex_owned(&p->p_stmutex));
361 
362           if ((p->p_stflag & PST_PROFIL) == 0) {
363                     p->p_stflag |= PST_PROFIL;
364                     /*
365                      * This is only necessary if using the clock as the
366                      * profiling source.
367                      */
368                     if (++profprocs == 1 && stathz != 0)
369                               psdiv = psratio;
370           }
371 }
372 
373 /*
374  * Stop profiling on a process.
375  */
376 void
stopprofclock(struct proc * p)377 stopprofclock(struct proc *p)
378 {
379 
380           KASSERT(mutex_owned(&p->p_stmutex));
381 
382           if (p->p_stflag & PST_PROFIL) {
383                     p->p_stflag &= ~PST_PROFIL;
384                     /*
385                      * This is only necessary if using the clock as the
386                      * profiling source.
387                      */
388                     if (--profprocs == 0 && stathz != 0)
389                               psdiv = 1;
390           }
391 }
392 
393 void
schedclock(struct lwp * l)394 schedclock(struct lwp *l)
395 {
396           if ((l->l_flag & LW_IDLE) != 0)
397                     return;
398 
399           sched_schedclock(l);
400 }
401 
402 /*
403  * Statistics clock.  Grab profile sample, and if divider reaches 0,
404  * do process and kernel statistics.
405  */
406 void
statclock(struct clockframe * frame)407 statclock(struct clockframe *frame)
408 {
409 #ifdef GPROF
410           struct gmonparam *g;
411           intptr_t i;
412 #endif
413           struct cpu_info *ci = curcpu();
414           struct schedstate_percpu *spc = &ci->ci_schedstate;
415           struct proc *p;
416           struct lwp *l;
417 
418           if (stathz)
419                     clockrnd_sample(&statclockrnd);
420 
421           /*
422            * Notice changes in divisor frequency, and adjust clock
423            * frequency accordingly.
424            */
425           if (spc->spc_psdiv != psdiv) {
426                     spc->spc_psdiv = psdiv;
427                     spc->spc_pscnt = psdiv;
428                     if (psdiv == 1) {
429                               setstatclockrate(stathz);
430                     } else {
431                               setstatclockrate(profhz);
432                     }
433           }
434           l = ci->ci_onproc;
435           if ((l->l_flag & LW_IDLE) != 0) {
436                     /*
437                      * don't account idle lwps as swapper.
438                      */
439                     p = NULL;
440           } else {
441                     p = l->l_proc;
442                     mutex_spin_enter(&p->p_stmutex);
443           }
444 
445           if (CLKF_USERMODE(frame)) {
446                     KASSERT(p != NULL);
447                     if ((p->p_stflag & PST_PROFIL) && profsrc == PROFSRC_CLOCK)
448                               addupc_intr(l, CLKF_PC(frame));
449                     if (--spc->spc_pscnt > 0) {
450                               mutex_spin_exit(&p->p_stmutex);
451                               return;
452                     }
453 
454                     /*
455                      * Came from user mode; CPU was in user state.
456                      * If this process is being profiled record the tick.
457                      */
458                     p->p_uticks++;
459                     if (p->p_nice > NZERO)
460                               spc->spc_cp_time[CP_NICE]++;
461                     else
462                               spc->spc_cp_time[CP_USER]++;
463           } else {
464 #ifdef GPROF
465                     /*
466                      * Kernel statistics are just like addupc_intr, only easier.
467                      */
468 #if defined(MULTIPROCESSOR) && !defined(_RUMPKERNEL)
469                     g = curcpu()->ci_gmon;
470                     if (g != NULL &&
471                         profsrc == PROFSRC_CLOCK && g->state == GMON_PROF_ON) {
472 #else
473                     g = &_gmonparam;
474                     if (profsrc == PROFSRC_CLOCK && g->state == GMON_PROF_ON) {
475 #endif
476                               i = CLKF_PC(frame) - g->lowpc;
477                               if (i < g->textsize) {
478                                         i /= HISTFRACTION * sizeof(*g->kcount);
479                                         g->kcount[i]++;
480                               }
481                     }
482 #endif
483 #ifdef LWP_PC
484                     if (p != NULL && profsrc == PROFSRC_CLOCK &&
485                         (p->p_stflag & PST_PROFIL)) {
486                               addupc_intr(l, LWP_PC(l));
487                     }
488 #endif
489                     if (--spc->spc_pscnt > 0) {
490                               if (p != NULL)
491                                         mutex_spin_exit(&p->p_stmutex);
492                               return;
493                     }
494                     /*
495                      * Came from kernel mode, so we were:
496                      * - handling an interrupt,
497                      * - doing syscall or trap work on behalf of the current
498                      *   user process, or
499                      * - spinning in the idle loop.
500                      * Whichever it is, charge the time as appropriate.
501                      * Note that we charge interrupts to the current process,
502                      * regardless of whether they are ``for'' that process,
503                      * so that we know how much of its real time was spent
504                      * in ``non-process'' (i.e., interrupt) work.
505                      */
506                     if (CLKF_INTR(frame) || (curlwp->l_pflag & LP_INTR) != 0) {
507                               if (p != NULL) {
508                                         p->p_iticks++;
509                               }
510                               spc->spc_cp_time[CP_INTR]++;
511                     } else if (p != NULL) {
512                               p->p_sticks++;
513                               spc->spc_cp_time[CP_SYS]++;
514                     } else {
515                               spc->spc_cp_time[CP_IDLE]++;
516                     }
517           }
518           spc->spc_pscnt = psdiv;
519 
520           if (p != NULL) {
521                     atomic_inc_uint(&l->l_cpticks);
522                     mutex_spin_exit(&p->p_stmutex);
523           }
524 
525 #ifdef KDTRACE_HOOKS
526           cyclic_clock_func_t func = cyclic_clock_func[cpu_index(ci)];
527           if (func) {
528                     (*func)((struct clockframe *)frame);
529           }
530 #endif
531 }
532 
533 /*
534  * sysctl helper routine for kern.clockrate. Assembles a struct on
535  * the fly to be returned to the caller.
536  */
537 static int
538 sysctl_kern_clockrate(SYSCTLFN_ARGS)
539 {
540           struct clockinfo clkinfo;
541           struct sysctlnode node;
542 
543           clkinfo.tick = tick;
544           clkinfo.tickadj = tickadj;
545           clkinfo.hz = hz;
546           clkinfo.profhz = profhz;
547           clkinfo.stathz = stathz ? stathz : hz;
548 
549           node = *rnode;
550           node.sysctl_data = &clkinfo;
551           return (sysctl_lookup(SYSCTLFN_CALL(&node)));
552 }
553