kern_clock.c revision 1.79.6.1 1 /* $NetBSD: kern_clock.c,v 1.79.6.1 2003/10/22 06:06:50 jmc Exp $ */
2
3 /*-
4 * Copyright (c) 2000 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 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the NetBSD
22 * Foundation, Inc. and its contributors.
23 * 4. Neither the name of The NetBSD Foundation nor the names of its
24 * contributors may be used to endorse or promote products derived
25 * from this software without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37 * POSSIBILITY OF SUCH DAMAGE.
38 */
39
40 /*-
41 * Copyright (c) 1982, 1986, 1991, 1993
42 * The Regents of the University of California. All rights reserved.
43 * (c) UNIX System Laboratories, Inc.
44 * All or some portions of this file are derived from material licensed
45 * to the University of California by American Telephone and Telegraph
46 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
47 * the permission of UNIX System Laboratories, Inc.
48 *
49 * Redistribution and use in source and binary forms, with or without
50 * modification, are permitted provided that the following conditions
51 * are met:
52 * 1. Redistributions of source code must retain the above copyright
53 * notice, this list of conditions and the following disclaimer.
54 * 2. Redistributions in binary form must reproduce the above copyright
55 * notice, this list of conditions and the following disclaimer in the
56 * documentation and/or other materials provided with the distribution.
57 * 3. All advertising materials mentioning features or use of this software
58 * must display the following acknowledgement:
59 * This product includes software developed by the University of
60 * California, Berkeley and its contributors.
61 * 4. Neither the name of the University nor the names of its contributors
62 * may be used to endorse or promote products derived from this software
63 * without specific prior written permission.
64 *
65 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
66 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
67 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
68 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
69 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
70 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
71 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
72 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
73 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
74 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
75 * SUCH DAMAGE.
76 *
77 * @(#)kern_clock.c 8.5 (Berkeley) 1/21/94
78 */
79
80 #include <sys/cdefs.h>
81 __KERNEL_RCSID(0, "$NetBSD: kern_clock.c,v 1.79.6.1 2003/10/22 06:06:50 jmc Exp $");
82
83 #include "opt_callout.h"
84 #include "opt_ntp.h"
85
86 #include <sys/param.h>
87 #include <sys/systm.h>
88 #include <sys/dkstat.h>
89 #include <sys/callout.h>
90 #include <sys/kernel.h>
91 #include <sys/proc.h>
92 #include <sys/resourcevar.h>
93 #include <sys/signalvar.h>
94 #include <sys/sysctl.h>
95 #include <sys/timex.h>
96 #include <sys/sched.h>
97 #ifdef CALLWHEEL_STATS
98 #include <sys/device.h>
99 #endif
100
101 #include <machine/cpu.h>
102 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
103 #include <machine/intr.h>
104 #endif
105
106 #ifdef GPROF
107 #include <sys/gmon.h>
108 #endif
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 #ifdef NTP /* NTP phase-locked loop in kernel */
135 /*
136 * Phase/frequency-lock loop (PLL/FLL) definitions
137 *
138 * The following variables are read and set by the ntp_adjtime() system
139 * call.
140 *
141 * time_state shows the state of the system clock, with values defined
142 * in the timex.h header file.
143 *
144 * time_status shows the status of the system clock, with bits defined
145 * in the timex.h header file.
146 *
147 * time_offset is used by the PLL/FLL to adjust the system time in small
148 * increments.
149 *
150 * time_constant determines the bandwidth or "stiffness" of the PLL.
151 *
152 * time_tolerance determines maximum frequency error or tolerance of the
153 * CPU clock oscillator and is a property of the architecture; however,
154 * in principle it could change as result of the presence of external
155 * discipline signals, for instance.
156 *
157 * time_precision is usually equal to the kernel tick variable; however,
158 * in cases where a precision clock counter or external clock is
159 * available, the resolution can be much less than this and depend on
160 * whether the external clock is working or not.
161 *
162 * time_maxerror is initialized by a ntp_adjtime() call and increased by
163 * the kernel once each second to reflect the maximum error bound
164 * growth.
165 *
166 * time_esterror is set and read by the ntp_adjtime() call, but
167 * otherwise not used by the kernel.
168 */
169 int time_state = TIME_OK; /* clock state */
170 int time_status = STA_UNSYNC; /* clock status bits */
171 long time_offset = 0; /* time offset (us) */
172 long time_constant = 0; /* pll time constant */
173 long time_tolerance = MAXFREQ; /* frequency tolerance (scaled ppm) */
174 long time_precision = 1; /* clock precision (us) */
175 long time_maxerror = MAXPHASE; /* maximum error (us) */
176 long time_esterror = MAXPHASE; /* estimated error (us) */
177
178 /*
179 * The following variables establish the state of the PLL/FLL and the
180 * residual time and frequency offset of the local clock. The scale
181 * factors are defined in the timex.h header file.
182 *
183 * time_phase and time_freq are the phase increment and the frequency
184 * increment, respectively, of the kernel time variable.
185 *
186 * time_freq is set via ntp_adjtime() from a value stored in a file when
187 * the synchronization daemon is first started. Its value is retrieved
188 * via ntp_adjtime() and written to the file about once per hour by the
189 * daemon.
190 *
191 * time_adj is the adjustment added to the value of tick at each timer
192 * interrupt and is recomputed from time_phase and time_freq at each
193 * seconds rollover.
194 *
195 * time_reftime is the second's portion of the system time at the last
196 * call to ntp_adjtime(). It is used to adjust the time_freq variable
197 * and to increase the time_maxerror as the time since last update
198 * increases.
199 */
200 long time_phase = 0; /* phase offset (scaled us) */
201 long time_freq = 0; /* frequency offset (scaled ppm) */
202 long time_adj = 0; /* tick adjust (scaled 1 / hz) */
203 long time_reftime = 0; /* time at last adjustment (s) */
204
205 #ifdef PPS_SYNC
206 /*
207 * The following variables are used only if the kernel PPS discipline
208 * code is configured (PPS_SYNC). The scale factors are defined in the
209 * timex.h header file.
210 *
211 * pps_time contains the time at each calibration interval, as read by
212 * microtime(). pps_count counts the seconds of the calibration
213 * interval, the duration of which is nominally pps_shift in powers of
214 * two.
215 *
216 * pps_offset is the time offset produced by the time median filter
217 * pps_tf[], while pps_jitter is the dispersion (jitter) measured by
218 * this filter.
219 *
220 * pps_freq is the frequency offset produced by the frequency median
221 * filter pps_ff[], while pps_stabil is the dispersion (wander) measured
222 * by this filter.
223 *
224 * pps_usec is latched from a high resolution counter or external clock
225 * at pps_time. Here we want the hardware counter contents only, not the
226 * contents plus the time_tv.usec as usual.
227 *
228 * pps_valid counts the number of seconds since the last PPS update. It
229 * is used as a watchdog timer to disable the PPS discipline should the
230 * PPS signal be lost.
231 *
232 * pps_glitch counts the number of seconds since the beginning of an
233 * offset burst more than tick/2 from current nominal offset. It is used
234 * mainly to suppress error bursts due to priority conflicts between the
235 * PPS interrupt and timer interrupt.
236 *
237 * pps_intcnt counts the calibration intervals for use in the interval-
238 * adaptation algorithm. It's just too complicated for words.
239 */
240 struct timeval pps_time; /* kernel time at last interval */
241 long pps_tf[] = {0, 0, 0}; /* pps time offset median filter (us) */
242 long pps_offset = 0; /* pps time offset (us) */
243 long pps_jitter = MAXTIME; /* time dispersion (jitter) (us) */
244 long pps_ff[] = {0, 0, 0}; /* pps frequency offset median filter */
245 long pps_freq = 0; /* frequency offset (scaled ppm) */
246 long pps_stabil = MAXFREQ; /* frequency dispersion (scaled ppm) */
247 long pps_usec = 0; /* microsec counter at last interval */
248 long pps_valid = PPS_VALID; /* pps signal watchdog counter */
249 int pps_glitch = 0; /* pps signal glitch counter */
250 int pps_count = 0; /* calibration interval counter (s) */
251 int pps_shift = PPS_SHIFT; /* interval duration (s) (shift) */
252 int pps_intcnt = 0; /* intervals at current duration */
253
254 /*
255 * PPS signal quality monitors
256 *
257 * pps_jitcnt counts the seconds that have been discarded because the
258 * jitter measured by the time median filter exceeds the limit MAXTIME
259 * (100 us).
260 *
261 * pps_calcnt counts the frequency calibration intervals, which are
262 * variable from 4 s to 256 s.
263 *
264 * pps_errcnt counts the calibration intervals which have been discarded
265 * because the wander exceeds the limit MAXFREQ (100 ppm) or where the
266 * calibration interval jitter exceeds two ticks.
267 *
268 * pps_stbcnt counts the calibration intervals that have been discarded
269 * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us).
270 */
271 long pps_jitcnt = 0; /* jitter limit exceeded */
272 long pps_calcnt = 0; /* calibration intervals */
273 long pps_errcnt = 0; /* calibration errors */
274 long pps_stbcnt = 0; /* stability limit exceeded */
275 #endif /* PPS_SYNC */
276
277 #ifdef EXT_CLOCK
278 /*
279 * External clock definitions
280 *
281 * The following definitions and declarations are used only if an
282 * external clock is configured on the system.
283 */
284 #define CLOCK_INTERVAL 30 /* CPU clock update interval (s) */
285
286 /*
287 * The clock_count variable is set to CLOCK_INTERVAL at each PPS
288 * interrupt and decremented once each second.
289 */
290 int clock_count = 0; /* CPU clock counter */
291
292 #ifdef HIGHBALL
293 /*
294 * The clock_offset and clock_cpu variables are used by the HIGHBALL
295 * interface. The clock_offset variable defines the offset between
296 * system time and the HIGBALL counters. The clock_cpu variable contains
297 * the offset between the system clock and the HIGHBALL clock for use in
298 * disciplining the kernel time variable.
299 */
300 extern struct timeval clock_offset; /* Highball clock offset */
301 long clock_cpu = 0; /* CPU clock adjust */
302 #endif /* HIGHBALL */
303 #endif /* EXT_CLOCK */
304 #endif /* NTP */
305
306
307 /*
308 * Bump a timeval by a small number of usec's.
309 */
310 #define BUMPTIME(t, usec) { \
311 volatile struct timeval *tp = (t); \
312 long us; \
313 \
314 tp->tv_usec = us = tp->tv_usec + (usec); \
315 if (us >= 1000000) { \
316 tp->tv_usec = us - 1000000; \
317 tp->tv_sec++; \
318 } \
319 }
320
321 int stathz;
322 int profhz;
323 int schedhz;
324 int profprocs;
325 int softclock_running; /* 1 => softclock() is running */
326 static int psdiv; /* prof => stat divider */
327 int psratio; /* ratio: prof / stat */
328 int tickfix, tickfixinterval; /* used if tick not really integral */
329 #ifndef NTP
330 static int tickfixcnt; /* accumulated fractional error */
331 #else
332 int fixtick; /* used by NTP for same */
333 int shifthz;
334 #endif
335
336 /*
337 * We might want ldd to load the both words from time at once.
338 * To succeed we need to be quadword aligned.
339 * The sparc already does that, and that it has worked so far is a fluke.
340 */
341 volatile struct timeval time __attribute__((__aligned__(__alignof__(quad_t))));
342 volatile struct timeval mono_time;
343
344 /*
345 * The callout mechanism is based on the work of Adam M. Costello and
346 * George Varghese, published in a technical report entitled "Redesigning
347 * the BSD Callout and Timer Facilities", and Justin Gibbs's subsequent
348 * integration into FreeBSD, modified for NetBSD by Jason R. Thorpe.
349 *
350 * The original work on the data structures used in this implementation
351 * was published by G. Varghese and A. Lauck in the paper "Hashed and
352 * Hierarchical Timing Wheels: Data Structures for the Efficient
353 * Implementation of a Timer Facility" in the Proceedings of the 11th
354 * ACM Annual Symposium on Operating System Principles, Austin, Texas,
355 * November 1987.
356 */
357 struct callout_queue *callwheel;
358 int callwheelsize, callwheelbits, callwheelmask;
359
360 static struct callout *nextsoftcheck; /* next callout to be checked */
361
362 #ifdef CALLWHEEL_STATS
363 int *callwheel_sizes; /* per-bucket length count */
364 struct evcnt callwheel_collisions; /* number of hash collisions */
365 struct evcnt callwheel_maxlength; /* length of the longest hash chain */
366 struct evcnt callwheel_count; /* # callouts currently */
367 struct evcnt callwheel_established; /* # callouts established */
368 struct evcnt callwheel_fired; /* # callouts that fired */
369 struct evcnt callwheel_disestablished; /* # callouts disestablished */
370 struct evcnt callwheel_changed; /* # callouts changed */
371 struct evcnt callwheel_softclocks; /* # times softclock() called */
372 struct evcnt callwheel_softchecks; /* # checks per softclock() */
373 struct evcnt callwheel_softempty; /* # empty buckets seen */
374 struct evcnt callwheel_hintworked; /* # times hint saved scan */
375 #endif /* CALLWHEEL_STATS */
376
377 /*
378 * This value indicates the number of consecutive callouts that
379 * will be checked before we allow interrupts to have a chance
380 * again.
381 */
382 #ifndef MAX_SOFTCLOCK_STEPS
383 #define MAX_SOFTCLOCK_STEPS 100
384 #endif
385
386 struct simplelock callwheel_slock;
387
388 #define CALLWHEEL_LOCK(s) \
389 do { \
390 s = splclock(); \
391 simple_lock(&callwheel_slock); \
392 } while (0)
393
394 #define CALLWHEEL_UNLOCK(s) \
395 do { \
396 simple_unlock(&callwheel_slock); \
397 splx(s); \
398 } while (0)
399
400 static void callout_stop_locked(struct callout *);
401
402 /*
403 * These are both protected by callwheel_lock.
404 * XXX SHOULD BE STATIC!!
405 */
406 u_int64_t hardclock_ticks, softclock_ticks;
407
408 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
409 void softclock(void *);
410 void *softclock_si;
411 #endif
412
413 /*
414 * Initialize clock frequencies and start both clocks running.
415 */
416 void
417 initclocks(void)
418 {
419 int i;
420
421 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
422 softclock_si = softintr_establish(IPL_SOFTCLOCK, softclock, NULL);
423 if (softclock_si == NULL)
424 panic("initclocks: unable to register softclock intr");
425 #endif
426
427 /*
428 * Set divisors to 1 (normal case) and let the machine-specific
429 * code do its bit.
430 */
431 psdiv = 1;
432 cpu_initclocks();
433
434 /*
435 * Compute profhz/stathz/rrticks, and fix profhz if needed.
436 */
437 i = stathz ? stathz : hz;
438 if (profhz == 0)
439 profhz = i;
440 psratio = profhz / i;
441 rrticks = hz / 10;
442
443 #ifdef NTP
444 switch (hz) {
445 case 1:
446 shifthz = SHIFT_SCALE - 0;
447 break;
448 case 2:
449 shifthz = SHIFT_SCALE - 1;
450 break;
451 case 4:
452 shifthz = SHIFT_SCALE - 2;
453 break;
454 case 8:
455 shifthz = SHIFT_SCALE - 3;
456 break;
457 case 16:
458 shifthz = SHIFT_SCALE - 4;
459 break;
460 case 32:
461 shifthz = SHIFT_SCALE - 5;
462 break;
463 case 60:
464 case 64:
465 shifthz = SHIFT_SCALE - 6;
466 break;
467 case 96:
468 case 100:
469 case 128:
470 shifthz = SHIFT_SCALE - 7;
471 break;
472 case 256:
473 shifthz = SHIFT_SCALE - 8;
474 break;
475 case 512:
476 shifthz = SHIFT_SCALE - 9;
477 break;
478 case 1000:
479 case 1024:
480 shifthz = SHIFT_SCALE - 10;
481 break;
482 case 1200:
483 case 2048:
484 shifthz = SHIFT_SCALE - 11;
485 break;
486 case 4096:
487 shifthz = SHIFT_SCALE - 12;
488 break;
489 case 8192:
490 shifthz = SHIFT_SCALE - 13;
491 break;
492 case 16384:
493 shifthz = SHIFT_SCALE - 14;
494 break;
495 case 32768:
496 shifthz = SHIFT_SCALE - 15;
497 break;
498 case 65536:
499 shifthz = SHIFT_SCALE - 16;
500 break;
501 default:
502 panic("weird hz");
503 }
504 if (fixtick == 0) {
505 /*
506 * Give MD code a chance to set this to a better
507 * value; but, if it doesn't, we should.
508 */
509 fixtick = (1000000 - (hz*tick));
510 }
511 #endif
512 }
513
514 /*
515 * The real-time timer, interrupting hz times per second.
516 */
517 void
518 hardclock(struct clockframe *frame)
519 {
520 struct proc *p;
521 int delta;
522 extern int tickdelta;
523 extern long timedelta;
524 struct cpu_info *ci = curcpu();
525 #ifdef NTP
526 int time_update;
527 int ltemp;
528 #endif
529
530 p = curproc;
531 if (p) {
532 struct pstats *pstats;
533
534 /*
535 * Run current process's virtual and profile time, as needed.
536 */
537 pstats = p->p_stats;
538 if (CLKF_USERMODE(frame) &&
539 timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
540 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
541 psignal(p, SIGVTALRM);
542 if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
543 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
544 psignal(p, SIGPROF);
545 }
546
547 /*
548 * If no separate statistics clock is available, run it from here.
549 */
550 if (stathz == 0)
551 statclock(frame);
552 if ((--ci->ci_schedstate.spc_rrticks) <= 0)
553 roundrobin(ci);
554
555 #if defined(MULTIPROCESSOR)
556 /*
557 * If we are not the primary CPU, we're not allowed to do
558 * any more work.
559 */
560 if (CPU_IS_PRIMARY(ci) == 0)
561 return;
562 #endif
563
564 /*
565 * Increment the time-of-day. The increment is normally just
566 * ``tick''. If the machine is one which has a clock frequency
567 * such that ``hz'' would not divide the second evenly into
568 * milliseconds, a periodic adjustment must be applied. Finally,
569 * if we are still adjusting the time (see adjtime()),
570 * ``tickdelta'' may also be added in.
571 */
572 delta = tick;
573
574 #ifndef NTP
575 if (tickfix) {
576 tickfixcnt += tickfix;
577 if (tickfixcnt >= tickfixinterval) {
578 delta++;
579 tickfixcnt -= tickfixinterval;
580 }
581 }
582 #endif /* !NTP */
583 /* Imprecise 4bsd adjtime() handling */
584 if (timedelta != 0) {
585 delta += tickdelta;
586 timedelta -= tickdelta;
587 }
588
589 #ifdef notyet
590 microset();
591 #endif
592
593 #ifndef NTP
594 BUMPTIME(&time, delta); /* XXX Now done using NTP code below */
595 #endif
596 BUMPTIME(&mono_time, delta);
597
598 #ifdef NTP
599 time_update = delta;
600
601 /*
602 * Compute the phase adjustment. If the low-order bits
603 * (time_phase) of the update overflow, bump the high-order bits
604 * (time_update).
605 */
606 time_phase += time_adj;
607 if (time_phase <= -FINEUSEC) {
608 ltemp = -time_phase >> SHIFT_SCALE;
609 time_phase += ltemp << SHIFT_SCALE;
610 time_update -= ltemp;
611 } else if (time_phase >= FINEUSEC) {
612 ltemp = time_phase >> SHIFT_SCALE;
613 time_phase -= ltemp << SHIFT_SCALE;
614 time_update += ltemp;
615 }
616
617 #ifdef HIGHBALL
618 /*
619 * If the HIGHBALL board is installed, we need to adjust the
620 * external clock offset in order to close the hardware feedback
621 * loop. This will adjust the external clock phase and frequency
622 * in small amounts. The additional phase noise and frequency
623 * wander this causes should be minimal. We also need to
624 * discipline the kernel time variable, since the PLL is used to
625 * discipline the external clock. If the Highball board is not
626 * present, we discipline kernel time with the PLL as usual. We
627 * assume that the external clock phase adjustment (time_update)
628 * and kernel phase adjustment (clock_cpu) are less than the
629 * value of tick.
630 */
631 clock_offset.tv_usec += time_update;
632 if (clock_offset.tv_usec >= 1000000) {
633 clock_offset.tv_sec++;
634 clock_offset.tv_usec -= 1000000;
635 }
636 if (clock_offset.tv_usec < 0) {
637 clock_offset.tv_sec--;
638 clock_offset.tv_usec += 1000000;
639 }
640 time.tv_usec += clock_cpu;
641 clock_cpu = 0;
642 #else
643 time.tv_usec += time_update;
644 #endif /* HIGHBALL */
645
646 /*
647 * On rollover of the second the phase adjustment to be used for
648 * the next second is calculated. Also, the maximum error is
649 * increased by the tolerance. If the PPS frequency discipline
650 * code is present, the phase is increased to compensate for the
651 * CPU clock oscillator frequency error.
652 *
653 * On a 32-bit machine and given parameters in the timex.h
654 * header file, the maximum phase adjustment is +-512 ms and
655 * maximum frequency offset is a tad less than) +-512 ppm. On a
656 * 64-bit machine, you shouldn't need to ask.
657 */
658 if (time.tv_usec >= 1000000) {
659 time.tv_usec -= 1000000;
660 time.tv_sec++;
661 time_maxerror += time_tolerance >> SHIFT_USEC;
662
663 /*
664 * Leap second processing. If in leap-insert state at
665 * the end of the day, the system clock is set back one
666 * second; if in leap-delete state, the system clock is
667 * set ahead one second. The microtime() routine or
668 * external clock driver will insure that reported time
669 * is always monotonic. The ugly divides should be
670 * replaced.
671 */
672 switch (time_state) {
673 case TIME_OK:
674 if (time_status & STA_INS)
675 time_state = TIME_INS;
676 else if (time_status & STA_DEL)
677 time_state = TIME_DEL;
678 break;
679
680 case TIME_INS:
681 if (time.tv_sec % 86400 == 0) {
682 time.tv_sec--;
683 time_state = TIME_OOP;
684 }
685 break;
686
687 case TIME_DEL:
688 if ((time.tv_sec + 1) % 86400 == 0) {
689 time.tv_sec++;
690 time_state = TIME_WAIT;
691 }
692 break;
693
694 case TIME_OOP:
695 time_state = TIME_WAIT;
696 break;
697
698 case TIME_WAIT:
699 if (!(time_status & (STA_INS | STA_DEL)))
700 time_state = TIME_OK;
701 break;
702 }
703
704 /*
705 * Compute the phase adjustment for the next second. In
706 * PLL mode, the offset is reduced by a fixed factor
707 * times the time constant. In FLL mode the offset is
708 * used directly. In either mode, the maximum phase
709 * adjustment for each second is clamped so as to spread
710 * the adjustment over not more than the number of
711 * seconds between updates.
712 */
713 if (time_offset < 0) {
714 ltemp = -time_offset;
715 if (!(time_status & STA_FLL))
716 ltemp >>= SHIFT_KG + time_constant;
717 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
718 ltemp = (MAXPHASE / MINSEC) <<
719 SHIFT_UPDATE;
720 time_offset += ltemp;
721 time_adj = -ltemp << (shifthz - SHIFT_UPDATE);
722 } else if (time_offset > 0) {
723 ltemp = time_offset;
724 if (!(time_status & STA_FLL))
725 ltemp >>= SHIFT_KG + time_constant;
726 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
727 ltemp = (MAXPHASE / MINSEC) <<
728 SHIFT_UPDATE;
729 time_offset -= ltemp;
730 time_adj = ltemp << (shifthz - SHIFT_UPDATE);
731 } else
732 time_adj = 0;
733
734 /*
735 * Compute the frequency estimate and additional phase
736 * adjustment due to frequency error for the next
737 * second. When the PPS signal is engaged, gnaw on the
738 * watchdog counter and update the frequency computed by
739 * the pll and the PPS signal.
740 */
741 #ifdef PPS_SYNC
742 pps_valid++;
743 if (pps_valid == PPS_VALID) {
744 pps_jitter = MAXTIME;
745 pps_stabil = MAXFREQ;
746 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
747 STA_PPSWANDER | STA_PPSERROR);
748 }
749 ltemp = time_freq + pps_freq;
750 #else
751 ltemp = time_freq;
752 #endif /* PPS_SYNC */
753
754 if (ltemp < 0)
755 time_adj -= -ltemp >> (SHIFT_USEC - shifthz);
756 else
757 time_adj += ltemp >> (SHIFT_USEC - shifthz);
758 time_adj += (long)fixtick << shifthz;
759
760 /*
761 * When the CPU clock oscillator frequency is not a
762 * power of 2 in Hz, shifthz is only an approximate
763 * scale factor.
764 *
765 * To determine the adjustment, you can do the following:
766 * bc -q
767 * scale=24
768 * obase=2
769 * idealhz/realhz
770 * where `idealhz' is the next higher power of 2, and `realhz'
771 * is the actual value. You may need to factor this result
772 * into a sequence of 2 multipliers to get better precision.
773 *
774 * Likewise, the error can be calculated with (e.g. for 100Hz):
775 * bc -q
776 * scale=24
777 * ((1+2^-2+2^-5)*(1-2^-10)*realhz-idealhz)/idealhz
778 * (and then multiply by 1000000 to get ppm).
779 */
780 switch (hz) {
781 case 60:
782 /* A factor of 1.000100010001 gives about 15ppm
783 error. */
784 if (time_adj < 0) {
785 time_adj -= (-time_adj >> 4);
786 time_adj -= (-time_adj >> 8);
787 } else {
788 time_adj += (time_adj >> 4);
789 time_adj += (time_adj >> 8);
790 }
791 break;
792
793 case 96:
794 /* A factor of 1.0101010101 gives about 244ppm error. */
795 if (time_adj < 0) {
796 time_adj -= (-time_adj >> 2);
797 time_adj -= (-time_adj >> 4) + (-time_adj >> 8);
798 } else {
799 time_adj += (time_adj >> 2);
800 time_adj += (time_adj >> 4) + (time_adj >> 8);
801 }
802 break;
803
804 case 100:
805 /* A factor of 1.010001111010111 gives about 1ppm
806 error. */
807 if (time_adj < 0) {
808 time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
809 time_adj += (-time_adj >> 10);
810 } else {
811 time_adj += (time_adj >> 2) + (time_adj >> 5);
812 time_adj -= (time_adj >> 10);
813 }
814 break;
815
816 case 1000:
817 /* A factor of 1.000001100010100001 gives about 50ppm
818 error. */
819 if (time_adj < 0) {
820 time_adj -= (-time_adj >> 6) + (-time_adj >> 11);
821 time_adj -= (-time_adj >> 7);
822 } else {
823 time_adj += (time_adj >> 6) + (time_adj >> 11);
824 time_adj += (time_adj >> 7);
825 }
826 break;
827
828 case 1200:
829 /* A factor of 1.1011010011100001 gives about 64ppm
830 error. */
831 if (time_adj < 0) {
832 time_adj -= (-time_adj >> 1) + (-time_adj >> 6);
833 time_adj -= (-time_adj >> 3) + (-time_adj >> 10);
834 } else {
835 time_adj += (time_adj >> 1) + (time_adj >> 6);
836 time_adj += (time_adj >> 3) + (time_adj >> 10);
837 }
838 break;
839 }
840
841 #ifdef EXT_CLOCK
842 /*
843 * If an external clock is present, it is necessary to
844 * discipline the kernel time variable anyway, since not
845 * all system components use the microtime() interface.
846 * Here, the time offset between the external clock and
847 * kernel time variable is computed every so often.
848 */
849 clock_count++;
850 if (clock_count > CLOCK_INTERVAL) {
851 clock_count = 0;
852 microtime(&clock_ext);
853 delta.tv_sec = clock_ext.tv_sec - time.tv_sec;
854 delta.tv_usec = clock_ext.tv_usec -
855 time.tv_usec;
856 if (delta.tv_usec < 0)
857 delta.tv_sec--;
858 if (delta.tv_usec >= 500000) {
859 delta.tv_usec -= 1000000;
860 delta.tv_sec++;
861 }
862 if (delta.tv_usec < -500000) {
863 delta.tv_usec += 1000000;
864 delta.tv_sec--;
865 }
866 if (delta.tv_sec > 0 || (delta.tv_sec == 0 &&
867 delta.tv_usec > MAXPHASE) ||
868 delta.tv_sec < -1 || (delta.tv_sec == -1 &&
869 delta.tv_usec < -MAXPHASE)) {
870 time = clock_ext;
871 delta.tv_sec = 0;
872 delta.tv_usec = 0;
873 }
874 #ifdef HIGHBALL
875 clock_cpu = delta.tv_usec;
876 #else /* HIGHBALL */
877 hardupdate(delta.tv_usec);
878 #endif /* HIGHBALL */
879 }
880 #endif /* EXT_CLOCK */
881 }
882
883 #endif /* NTP */
884
885 /*
886 * Process callouts at a very low cpu priority, so we don't keep the
887 * relatively high clock interrupt priority any longer than necessary.
888 */
889 simple_lock(&callwheel_slock); /* already at splclock() */
890 hardclock_ticks++;
891 if (! TAILQ_EMPTY(&callwheel[hardclock_ticks & callwheelmask].cq_q)) {
892 simple_unlock(&callwheel_slock);
893 if (CLKF_BASEPRI(frame)) {
894 /*
895 * Save the overhead of a software interrupt;
896 * it will happen as soon as we return, so do
897 * it now.
898 *
899 * NOTE: If we're at ``base priority'', softclock()
900 * was not already running.
901 */
902 spllowersoftclock();
903 KERNEL_LOCK(LK_CANRECURSE|LK_EXCLUSIVE);
904 softclock(NULL);
905 KERNEL_UNLOCK();
906 } else {
907 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
908 softintr_schedule(softclock_si);
909 #else
910 setsoftclock();
911 #endif
912 }
913 return;
914 } else if (softclock_running == 0 &&
915 (softclock_ticks + 1) == hardclock_ticks) {
916 softclock_ticks++;
917 }
918 simple_unlock(&callwheel_slock);
919 }
920
921 /*
922 * Software (low priority) clock interrupt.
923 * Run periodic events from timeout queue.
924 */
925 /*ARGSUSED*/
926 void
927 softclock(void *v)
928 {
929 struct callout_queue *bucket;
930 struct callout *c;
931 void (*func)(void *);
932 void *arg;
933 int s, idx;
934 int steps = 0;
935
936 CALLWHEEL_LOCK(s);
937
938 softclock_running = 1;
939
940 #ifdef CALLWHEEL_STATS
941 callwheel_softclocks.ev_count++;
942 #endif
943
944 while (softclock_ticks != hardclock_ticks) {
945 softclock_ticks++;
946 idx = (int)(softclock_ticks & callwheelmask);
947 bucket = &callwheel[idx];
948 c = TAILQ_FIRST(&bucket->cq_q);
949 if (c == NULL) {
950 #ifdef CALLWHEEL_STATS
951 callwheel_softempty.ev_count++;
952 #endif
953 continue;
954 }
955 if (softclock_ticks < bucket->cq_hint) {
956 #ifdef CALLWHEEL_STATS
957 callwheel_hintworked.ev_count++;
958 #endif
959 continue;
960 }
961 bucket->cq_hint = UQUAD_MAX;
962 while (c != NULL) {
963 #ifdef CALLWHEEL_STATS
964 callwheel_softchecks.ev_count++;
965 #endif
966 if (c->c_time != softclock_ticks) {
967 if (c->c_time < bucket->cq_hint)
968 bucket->cq_hint = c->c_time;
969 c = TAILQ_NEXT(c, c_link);
970 if (++steps >= MAX_SOFTCLOCK_STEPS) {
971 nextsoftcheck = c;
972 /* Give interrupts a chance. */
973 CALLWHEEL_UNLOCK(s);
974 CALLWHEEL_LOCK(s);
975 c = nextsoftcheck;
976 steps = 0;
977 }
978 } else {
979 nextsoftcheck = TAILQ_NEXT(c, c_link);
980 TAILQ_REMOVE(&bucket->cq_q, c, c_link);
981 #ifdef CALLWHEEL_STATS
982 callwheel_sizes[idx]--;
983 callwheel_fired.ev_count++;
984 callwheel_count.ev_count--;
985 #endif
986 func = c->c_func;
987 arg = c->c_arg;
988 c->c_func = NULL;
989 c->c_flags &= ~CALLOUT_PENDING;
990 c->c_flags |= CALLOUT_INVOKING;
991 CALLWHEEL_UNLOCK(s);
992 (*func)(arg);
993 CALLWHEEL_LOCK(s);
994 steps = 0;
995 c = nextsoftcheck;
996 }
997 }
998 if (TAILQ_EMPTY(&bucket->cq_q))
999 bucket->cq_hint = UQUAD_MAX;
1000 }
1001 nextsoftcheck = NULL;
1002 softclock_running = 0;
1003 CALLWHEEL_UNLOCK(s);
1004 }
1005
1006 /*
1007 * callout_setsize:
1008 *
1009 * Determine how many callwheels are necessary and
1010 * set hash mask. Called from allocsys().
1011 */
1012 void
1013 callout_setsize(void)
1014 {
1015
1016 for (callwheelsize = 1; callwheelsize < ncallout; callwheelsize <<= 1)
1017 /* loop */ ;
1018 callwheelmask = callwheelsize - 1;
1019 }
1020
1021 /*
1022 * callout_startup:
1023 *
1024 * Initialize the callwheel buckets.
1025 */
1026 void
1027 callout_startup(void)
1028 {
1029 int i;
1030
1031 for (i = 0; i < callwheelsize; i++) {
1032 callwheel[i].cq_hint = UQUAD_MAX;
1033 TAILQ_INIT(&callwheel[i].cq_q);
1034 }
1035
1036 simple_lock_init(&callwheel_slock);
1037
1038 #ifdef CALLWHEEL_STATS
1039 evcnt_attach_dynamic(&callwheel_collisions, EVCNT_TYPE_MISC,
1040 NULL, "callwheel", "collisions");
1041 evcnt_attach_dynamic(&callwheel_maxlength, EVCNT_TYPE_MISC,
1042 NULL, "callwheel", "maxlength");
1043 evcnt_attach_dynamic(&callwheel_count, EVCNT_TYPE_MISC,
1044 NULL, "callwheel", "count");
1045 evcnt_attach_dynamic(&callwheel_established, EVCNT_TYPE_MISC,
1046 NULL, "callwheel", "established");
1047 evcnt_attach_dynamic(&callwheel_fired, EVCNT_TYPE_MISC,
1048 NULL, "callwheel", "fired");
1049 evcnt_attach_dynamic(&callwheel_disestablished, EVCNT_TYPE_MISC,
1050 NULL, "callwheel", "disestablished");
1051 evcnt_attach_dynamic(&callwheel_changed, EVCNT_TYPE_MISC,
1052 NULL, "callwheel", "changed");
1053 evcnt_attach_dynamic(&callwheel_softclocks, EVCNT_TYPE_MISC,
1054 NULL, "callwheel", "softclocks");
1055 evcnt_attach_dynamic(&callwheel_softempty, EVCNT_TYPE_MISC,
1056 NULL, "callwheel", "softempty");
1057 evcnt_attach_dynamic(&callwheel_hintworked, EVCNT_TYPE_MISC,
1058 NULL, "callwheel", "hintworked");
1059 #endif /* CALLWHEEL_STATS */
1060 }
1061
1062 /*
1063 * callout_init:
1064 *
1065 * Initialize a callout structure so that it can be used
1066 * by callout_reset() and callout_stop().
1067 */
1068 void
1069 callout_init(struct callout *c)
1070 {
1071
1072 memset(c, 0, sizeof(*c));
1073 }
1074
1075 /*
1076 * callout_reset:
1077 *
1078 * Establish or change a timeout.
1079 */
1080 void
1081 callout_reset(struct callout *c, int ticks, void (*func)(void *), void *arg)
1082 {
1083 struct callout_queue *bucket;
1084 int s;
1085
1086 if (ticks <= 0)
1087 ticks = 1;
1088
1089 CALLWHEEL_LOCK(s);
1090
1091 /*
1092 * If this callout's timer is already running, cancel it
1093 * before we modify it.
1094 */
1095 if (c->c_flags & CALLOUT_PENDING) {
1096 callout_stop_locked(c); /* Already locked */
1097 #ifdef CALLWHEEL_STATS
1098 callwheel_changed.ev_count++;
1099 #endif
1100 }
1101
1102 c->c_arg = arg;
1103 c->c_func = func;
1104 c->c_flags = CALLOUT_ACTIVE | CALLOUT_PENDING;
1105 c->c_time = hardclock_ticks + ticks;
1106
1107 bucket = &callwheel[c->c_time & callwheelmask];
1108
1109 #ifdef CALLWHEEL_STATS
1110 if (! TAILQ_EMPTY(&bucket->cq_q))
1111 callwheel_collisions.ev_count++;
1112 #endif
1113
1114 TAILQ_INSERT_TAIL(&bucket->cq_q, c, c_link);
1115 if (c->c_time < bucket->cq_hint)
1116 bucket->cq_hint = c->c_time;
1117
1118 #ifdef CALLWHEEL_STATS
1119 callwheel_count.ev_count++;
1120 callwheel_established.ev_count++;
1121 if (++callwheel_sizes[c->c_time & callwheelmask] >
1122 callwheel_maxlength.ev_count)
1123 callwheel_maxlength.ev_count =
1124 callwheel_sizes[c->c_time & callwheelmask];
1125 #endif
1126
1127 CALLWHEEL_UNLOCK(s);
1128 }
1129
1130 /*
1131 * callout_stop_locked:
1132 *
1133 * Disestablish a timeout. Callwheel is locked.
1134 */
1135 static void
1136 callout_stop_locked(struct callout *c)
1137 {
1138 struct callout_queue *bucket;
1139
1140 /*
1141 * Don't attempt to delete a callout that's not on the queue.
1142 */
1143 if ((c->c_flags & CALLOUT_PENDING) == 0) {
1144 c->c_flags &= ~CALLOUT_ACTIVE;
1145 return;
1146 }
1147
1148 c->c_flags &= ~(CALLOUT_ACTIVE | CALLOUT_PENDING);
1149
1150 if (nextsoftcheck == c)
1151 nextsoftcheck = TAILQ_NEXT(c, c_link);
1152
1153 bucket = &callwheel[c->c_time & callwheelmask];
1154 TAILQ_REMOVE(&bucket->cq_q, c, c_link);
1155 if (TAILQ_EMPTY(&bucket->cq_q))
1156 bucket->cq_hint = UQUAD_MAX;
1157 #ifdef CALLWHEEL_STATS
1158 callwheel_count.ev_count--;
1159 callwheel_disestablished.ev_count++;
1160 callwheel_sizes[c->c_time & callwheelmask]--;
1161 #endif
1162
1163 c->c_func = NULL;
1164 }
1165
1166 /*
1167 * callout_stop:
1168 *
1169 * Disestablish a timeout. Callwheel is unlocked. This is
1170 * the standard entry point.
1171 */
1172 void
1173 callout_stop(struct callout *c)
1174 {
1175 int s;
1176
1177 CALLWHEEL_LOCK(s);
1178 callout_stop_locked(c);
1179 CALLWHEEL_UNLOCK(s);
1180 }
1181
1182 #ifdef CALLWHEEL_STATS
1183 /*
1184 * callout_showstats:
1185 *
1186 * Display callout statistics. Call it from DDB.
1187 */
1188 void
1189 callout_showstats(void)
1190 {
1191 u_int64_t curticks;
1192 int s;
1193
1194 s = splclock();
1195 curticks = softclock_ticks;
1196 splx(s);
1197
1198 printf("Callwheel statistics:\n");
1199 printf("\tCallouts currently queued: %llu\n",
1200 (long long) callwheel_count.ev_count);
1201 printf("\tCallouts established: %llu\n",
1202 (long long) callwheel_established.ev_count);
1203 printf("\tCallouts disestablished: %llu\n",
1204 (long long) callwheel_disestablished.ev_count);
1205 if (callwheel_changed.ev_count != 0)
1206 printf("\t\tOf those, %llu were changes\n",
1207 (long long) callwheel_changed.ev_count);
1208 printf("\tCallouts that fired: %llu\n",
1209 (long long) callwheel_fired.ev_count);
1210 printf("\tNumber of buckets: %d\n", callwheelsize);
1211 printf("\tNumber of hash collisions: %llu\n",
1212 (long long) callwheel_collisions.ev_count);
1213 printf("\tMaximum hash chain length: %llu\n",
1214 (long long) callwheel_maxlength.ev_count);
1215 printf("\tSoftclocks: %llu, Softchecks: %llu\n",
1216 (long long) callwheel_softclocks.ev_count,
1217 (long long) callwheel_softchecks.ev_count);
1218 printf("\t\tEmpty buckets seen: %llu\n",
1219 (long long) callwheel_softempty.ev_count);
1220 printf("\t\tTimes hint saved scan: %llu\n",
1221 (long long) callwheel_hintworked.ev_count);
1222 }
1223 #endif
1224
1225 /*
1226 * Compute number of hz until specified time. Used to compute second
1227 * argument to callout_reset() from an absolute time.
1228 */
1229 int
1230 hzto(struct timeval *tv)
1231 {
1232 unsigned long ticks;
1233 long sec, usec;
1234 int s;
1235
1236 /*
1237 * If the number of usecs in the whole seconds part of the time
1238 * difference fits in a long, then the total number of usecs will
1239 * fit in an unsigned long. Compute the total and convert it to
1240 * ticks, rounding up and adding 1 to allow for the current tick
1241 * to expire. Rounding also depends on unsigned long arithmetic
1242 * to avoid overflow.
1243 *
1244 * Otherwise, if the number of ticks in the whole seconds part of
1245 * the time difference fits in a long, then convert the parts to
1246 * ticks separately and add, using similar rounding methods and
1247 * overflow avoidance. This method would work in the previous
1248 * case, but it is slightly slower and assume that hz is integral.
1249 *
1250 * Otherwise, round the time difference down to the maximum
1251 * representable value.
1252 *
1253 * If ints are 32-bit, then the maximum value for any timeout in
1254 * 10ms ticks is 248 days.
1255 */
1256 s = splclock();
1257 sec = tv->tv_sec - time.tv_sec;
1258 usec = tv->tv_usec - time.tv_usec;
1259 splx(s);
1260
1261 if (usec < 0) {
1262 sec--;
1263 usec += 1000000;
1264 }
1265
1266 if (sec < 0 || (sec == 0 && usec <= 0)) {
1267 /*
1268 * Would expire now or in the past. Return 0 ticks.
1269 * This is different from the legacy hzto() interface,
1270 * and callers need to check for it.
1271 */
1272 ticks = 0;
1273 } else if (sec <= (LONG_MAX / 1000000))
1274 ticks = (((sec * 1000000) + (unsigned long)usec + (tick - 1))
1275 / tick) + 1;
1276 else if (sec <= (LONG_MAX / hz))
1277 ticks = (sec * hz) +
1278 (((unsigned long)usec + (tick - 1)) / tick) + 1;
1279 else
1280 ticks = LONG_MAX;
1281
1282 if (ticks > INT_MAX)
1283 ticks = INT_MAX;
1284
1285 return ((int)ticks);
1286 }
1287
1288 /*
1289 * Start profiling on a process.
1290 *
1291 * Kernel profiling passes proc0 which never exits and hence
1292 * keeps the profile clock running constantly.
1293 */
1294 void
1295 startprofclock(struct proc *p)
1296 {
1297
1298 if ((p->p_flag & P_PROFIL) == 0) {
1299 p->p_flag |= P_PROFIL;
1300 if (++profprocs == 1 && stathz != 0)
1301 psdiv = psratio;
1302 }
1303 }
1304
1305 /*
1306 * Stop profiling on a process.
1307 */
1308 void
1309 stopprofclock(struct proc *p)
1310 {
1311
1312 if (p->p_flag & P_PROFIL) {
1313 p->p_flag &= ~P_PROFIL;
1314 if (--profprocs == 0 && stathz != 0)
1315 psdiv = 1;
1316 }
1317 }
1318
1319 /*
1320 * Statistics clock. Grab profile sample, and if divider reaches 0,
1321 * do process and kernel statistics.
1322 */
1323 void
1324 statclock(struct clockframe *frame)
1325 {
1326 #ifdef GPROF
1327 struct gmonparam *g;
1328 intptr_t i;
1329 #endif
1330 struct cpu_info *ci = curcpu();
1331 struct schedstate_percpu *spc = &ci->ci_schedstate;
1332 struct proc *p;
1333
1334 /*
1335 * Notice changes in divisor frequency, and adjust clock
1336 * frequency accordingly.
1337 */
1338 if (spc->spc_psdiv != psdiv) {
1339 spc->spc_psdiv = psdiv;
1340 spc->spc_pscnt = psdiv;
1341 if (psdiv == 1) {
1342 setstatclockrate(stathz);
1343 } else {
1344 setstatclockrate(profhz);
1345 }
1346 }
1347 p = curproc;
1348 if (CLKF_USERMODE(frame)) {
1349 if (p->p_flag & P_PROFIL)
1350 addupc_intr(p, CLKF_PC(frame));
1351 if (--spc->spc_pscnt > 0)
1352 return;
1353 /*
1354 * Came from user mode; CPU was in user state.
1355 * If this process is being profiled record the tick.
1356 */
1357 p->p_uticks++;
1358 if (p->p_nice > NZERO)
1359 spc->spc_cp_time[CP_NICE]++;
1360 else
1361 spc->spc_cp_time[CP_USER]++;
1362 } else {
1363 #ifdef GPROF
1364 /*
1365 * Kernel statistics are just like addupc_intr, only easier.
1366 */
1367 g = &_gmonparam;
1368 if (g->state == GMON_PROF_ON) {
1369 i = CLKF_PC(frame) - g->lowpc;
1370 if (i < g->textsize) {
1371 i /= HISTFRACTION * sizeof(*g->kcount);
1372 g->kcount[i]++;
1373 }
1374 }
1375 #endif
1376 #ifdef PROC_PC
1377 if (p && p->p_flag & P_PROFIL)
1378 addupc_intr(p, PROC_PC(p));
1379 #endif
1380 if (--spc->spc_pscnt > 0)
1381 return;
1382 /*
1383 * Came from kernel mode, so we were:
1384 * - handling an interrupt,
1385 * - doing syscall or trap work on behalf of the current
1386 * user process, or
1387 * - spinning in the idle loop.
1388 * Whichever it is, charge the time as appropriate.
1389 * Note that we charge interrupts to the current process,
1390 * regardless of whether they are ``for'' that process,
1391 * so that we know how much of its real time was spent
1392 * in ``non-process'' (i.e., interrupt) work.
1393 */
1394 if (CLKF_INTR(frame)) {
1395 if (p != NULL)
1396 p->p_iticks++;
1397 spc->spc_cp_time[CP_INTR]++;
1398 } else if (p != NULL) {
1399 p->p_sticks++;
1400 spc->spc_cp_time[CP_SYS]++;
1401 } else
1402 spc->spc_cp_time[CP_IDLE]++;
1403 }
1404 spc->spc_pscnt = psdiv;
1405
1406 if (p != NULL) {
1407 ++p->p_cpticks;
1408 /*
1409 * If no separate schedclock is provided, call it here
1410 * at ~~12-25 Hz, ~~16 Hz is best
1411 */
1412 if (schedhz == 0)
1413 if ((++ci->ci_schedstate.spc_schedticks & 3) == 0)
1414 schedclock(p);
1415 }
1416 }
1417
1418
1419 #ifdef NTP /* NTP phase-locked loop in kernel */
1420
1421 /*
1422 * hardupdate() - local clock update
1423 *
1424 * This routine is called by ntp_adjtime() to update the local clock
1425 * phase and frequency. The implementation is of an adaptive-parameter,
1426 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
1427 * time and frequency offset estimates for each call. If the kernel PPS
1428 * discipline code is configured (PPS_SYNC), the PPS signal itself
1429 * determines the new time offset, instead of the calling argument.
1430 * Presumably, calls to ntp_adjtime() occur only when the caller
1431 * believes the local clock is valid within some bound (+-128 ms with
1432 * NTP). If the caller's time is far different than the PPS time, an
1433 * argument will ensue, and it's not clear who will lose.
1434 *
1435 * For uncompensated quartz crystal oscillatores and nominal update
1436 * intervals less than 1024 s, operation should be in phase-lock mode
1437 * (STA_FLL = 0), where the loop is disciplined to phase. For update
1438 * intervals greater than thiss, operation should be in frequency-lock
1439 * mode (STA_FLL = 1), where the loop is disciplined to frequency.
1440 *
1441 * Note: splclock() is in effect.
1442 */
1443 void
1444 hardupdate(long offset)
1445 {
1446 long ltemp, mtemp;
1447
1448 if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
1449 return;
1450 ltemp = offset;
1451 #ifdef PPS_SYNC
1452 if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
1453 ltemp = pps_offset;
1454 #endif /* PPS_SYNC */
1455
1456 /*
1457 * Scale the phase adjustment and clamp to the operating range.
1458 */
1459 if (ltemp > MAXPHASE)
1460 time_offset = MAXPHASE << SHIFT_UPDATE;
1461 else if (ltemp < -MAXPHASE)
1462 time_offset = -(MAXPHASE << SHIFT_UPDATE);
1463 else
1464 time_offset = ltemp << SHIFT_UPDATE;
1465
1466 /*
1467 * Select whether the frequency is to be controlled and in which
1468 * mode (PLL or FLL). Clamp to the operating range. Ugly
1469 * multiply/divide should be replaced someday.
1470 */
1471 if (time_status & STA_FREQHOLD || time_reftime == 0)
1472 time_reftime = time.tv_sec;
1473 mtemp = time.tv_sec - time_reftime;
1474 time_reftime = time.tv_sec;
1475 if (time_status & STA_FLL) {
1476 if (mtemp >= MINSEC) {
1477 ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
1478 SHIFT_UPDATE));
1479 if (ltemp < 0)
1480 time_freq -= -ltemp >> SHIFT_KH;
1481 else
1482 time_freq += ltemp >> SHIFT_KH;
1483 }
1484 } else {
1485 if (mtemp < MAXSEC) {
1486 ltemp *= mtemp;
1487 if (ltemp < 0)
1488 time_freq -= -ltemp >> (time_constant +
1489 time_constant + SHIFT_KF -
1490 SHIFT_USEC);
1491 else
1492 time_freq += ltemp >> (time_constant +
1493 time_constant + SHIFT_KF -
1494 SHIFT_USEC);
1495 }
1496 }
1497 if (time_freq > time_tolerance)
1498 time_freq = time_tolerance;
1499 else if (time_freq < -time_tolerance)
1500 time_freq = -time_tolerance;
1501 }
1502
1503 #ifdef PPS_SYNC
1504 /*
1505 * hardpps() - discipline CPU clock oscillator to external PPS signal
1506 *
1507 * This routine is called at each PPS interrupt in order to discipline
1508 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
1509 * and leaves it in a handy spot for the hardclock() routine. It
1510 * integrates successive PPS phase differences and calculates the
1511 * frequency offset. This is used in hardclock() to discipline the CPU
1512 * clock oscillator so that intrinsic frequency error is cancelled out.
1513 * The code requires the caller to capture the time and hardware counter
1514 * value at the on-time PPS signal transition.
1515 *
1516 * Note that, on some Unix systems, this routine runs at an interrupt
1517 * priority level higher than the timer interrupt routine hardclock().
1518 * Therefore, the variables used are distinct from the hardclock()
1519 * variables, except for certain exceptions: The PPS frequency pps_freq
1520 * and phase pps_offset variables are determined by this routine and
1521 * updated atomically. The time_tolerance variable can be considered a
1522 * constant, since it is infrequently changed, and then only when the
1523 * PPS signal is disabled. The watchdog counter pps_valid is updated
1524 * once per second by hardclock() and is atomically cleared in this
1525 * routine.
1526 */
1527 void
1528 hardpps(struct timeval *tvp, /* time at PPS */
1529 long usec /* hardware counter at PPS */)
1530 {
1531 long u_usec, v_usec, bigtick;
1532 long cal_sec, cal_usec;
1533
1534 /*
1535 * An occasional glitch can be produced when the PPS interrupt
1536 * occurs in the hardclock() routine before the time variable is
1537 * updated. Here the offset is discarded when the difference
1538 * between it and the last one is greater than tick/2, but not
1539 * if the interval since the first discard exceeds 30 s.
1540 */
1541 time_status |= STA_PPSSIGNAL;
1542 time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1543 pps_valid = 0;
1544 u_usec = -tvp->tv_usec;
1545 if (u_usec < -500000)
1546 u_usec += 1000000;
1547 v_usec = pps_offset - u_usec;
1548 if (v_usec < 0)
1549 v_usec = -v_usec;
1550 if (v_usec > (tick >> 1)) {
1551 if (pps_glitch > MAXGLITCH) {
1552 pps_glitch = 0;
1553 pps_tf[2] = u_usec;
1554 pps_tf[1] = u_usec;
1555 } else {
1556 pps_glitch++;
1557 u_usec = pps_offset;
1558 }
1559 } else
1560 pps_glitch = 0;
1561
1562 /*
1563 * A three-stage median filter is used to help deglitch the pps
1564 * time. The median sample becomes the time offset estimate; the
1565 * difference between the other two samples becomes the time
1566 * dispersion (jitter) estimate.
1567 */
1568 pps_tf[2] = pps_tf[1];
1569 pps_tf[1] = pps_tf[0];
1570 pps_tf[0] = u_usec;
1571 if (pps_tf[0] > pps_tf[1]) {
1572 if (pps_tf[1] > pps_tf[2]) {
1573 pps_offset = pps_tf[1]; /* 0 1 2 */
1574 v_usec = pps_tf[0] - pps_tf[2];
1575 } else if (pps_tf[2] > pps_tf[0]) {
1576 pps_offset = pps_tf[0]; /* 2 0 1 */
1577 v_usec = pps_tf[2] - pps_tf[1];
1578 } else {
1579 pps_offset = pps_tf[2]; /* 0 2 1 */
1580 v_usec = pps_tf[0] - pps_tf[1];
1581 }
1582 } else {
1583 if (pps_tf[1] < pps_tf[2]) {
1584 pps_offset = pps_tf[1]; /* 2 1 0 */
1585 v_usec = pps_tf[2] - pps_tf[0];
1586 } else if (pps_tf[2] < pps_tf[0]) {
1587 pps_offset = pps_tf[0]; /* 1 0 2 */
1588 v_usec = pps_tf[1] - pps_tf[2];
1589 } else {
1590 pps_offset = pps_tf[2]; /* 1 2 0 */
1591 v_usec = pps_tf[1] - pps_tf[0];
1592 }
1593 }
1594 if (v_usec > MAXTIME)
1595 pps_jitcnt++;
1596 v_usec = (v_usec << PPS_AVG) - pps_jitter;
1597 if (v_usec < 0)
1598 pps_jitter -= -v_usec >> PPS_AVG;
1599 else
1600 pps_jitter += v_usec >> PPS_AVG;
1601 if (pps_jitter > (MAXTIME >> 1))
1602 time_status |= STA_PPSJITTER;
1603
1604 /*
1605 * During the calibration interval adjust the starting time when
1606 * the tick overflows. At the end of the interval compute the
1607 * duration of the interval and the difference of the hardware
1608 * counters at the beginning and end of the interval. This code
1609 * is deliciously complicated by the fact valid differences may
1610 * exceed the value of tick when using long calibration
1611 * intervals and small ticks. Note that the counter can be
1612 * greater than tick if caught at just the wrong instant, but
1613 * the values returned and used here are correct.
1614 */
1615 bigtick = (long)tick << SHIFT_USEC;
1616 pps_usec -= pps_freq;
1617 if (pps_usec >= bigtick)
1618 pps_usec -= bigtick;
1619 if (pps_usec < 0)
1620 pps_usec += bigtick;
1621 pps_time.tv_sec++;
1622 pps_count++;
1623 if (pps_count < (1 << pps_shift))
1624 return;
1625 pps_count = 0;
1626 pps_calcnt++;
1627 u_usec = usec << SHIFT_USEC;
1628 v_usec = pps_usec - u_usec;
1629 if (v_usec >= bigtick >> 1)
1630 v_usec -= bigtick;
1631 if (v_usec < -(bigtick >> 1))
1632 v_usec += bigtick;
1633 if (v_usec < 0)
1634 v_usec = -(-v_usec >> pps_shift);
1635 else
1636 v_usec = v_usec >> pps_shift;
1637 pps_usec = u_usec;
1638 cal_sec = tvp->tv_sec;
1639 cal_usec = tvp->tv_usec;
1640 cal_sec -= pps_time.tv_sec;
1641 cal_usec -= pps_time.tv_usec;
1642 if (cal_usec < 0) {
1643 cal_usec += 1000000;
1644 cal_sec--;
1645 }
1646 pps_time = *tvp;
1647
1648 /*
1649 * Check for lost interrupts, noise, excessive jitter and
1650 * excessive frequency error. The number of timer ticks during
1651 * the interval may vary +-1 tick. Add to this a margin of one
1652 * tick for the PPS signal jitter and maximum frequency
1653 * deviation. If the limits are exceeded, the calibration
1654 * interval is reset to the minimum and we start over.
1655 */
1656 u_usec = (long)tick << 1;
1657 if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
1658 || (cal_sec == 0 && cal_usec < u_usec))
1659 || v_usec > time_tolerance || v_usec < -time_tolerance) {
1660 pps_errcnt++;
1661 pps_shift = PPS_SHIFT;
1662 pps_intcnt = 0;
1663 time_status |= STA_PPSERROR;
1664 return;
1665 }
1666
1667 /*
1668 * A three-stage median filter is used to help deglitch the pps
1669 * frequency. The median sample becomes the frequency offset
1670 * estimate; the difference between the other two samples
1671 * becomes the frequency dispersion (stability) estimate.
1672 */
1673 pps_ff[2] = pps_ff[1];
1674 pps_ff[1] = pps_ff[0];
1675 pps_ff[0] = v_usec;
1676 if (pps_ff[0] > pps_ff[1]) {
1677 if (pps_ff[1] > pps_ff[2]) {
1678 u_usec = pps_ff[1]; /* 0 1 2 */
1679 v_usec = pps_ff[0] - pps_ff[2];
1680 } else if (pps_ff[2] > pps_ff[0]) {
1681 u_usec = pps_ff[0]; /* 2 0 1 */
1682 v_usec = pps_ff[2] - pps_ff[1];
1683 } else {
1684 u_usec = pps_ff[2]; /* 0 2 1 */
1685 v_usec = pps_ff[0] - pps_ff[1];
1686 }
1687 } else {
1688 if (pps_ff[1] < pps_ff[2]) {
1689 u_usec = pps_ff[1]; /* 2 1 0 */
1690 v_usec = pps_ff[2] - pps_ff[0];
1691 } else if (pps_ff[2] < pps_ff[0]) {
1692 u_usec = pps_ff[0]; /* 1 0 2 */
1693 v_usec = pps_ff[1] - pps_ff[2];
1694 } else {
1695 u_usec = pps_ff[2]; /* 1 2 0 */
1696 v_usec = pps_ff[1] - pps_ff[0];
1697 }
1698 }
1699
1700 /*
1701 * Here the frequency dispersion (stability) is updated. If it
1702 * is less than one-fourth the maximum (MAXFREQ), the frequency
1703 * offset is updated as well, but clamped to the tolerance. It
1704 * will be processed later by the hardclock() routine.
1705 */
1706 v_usec = (v_usec >> 1) - pps_stabil;
1707 if (v_usec < 0)
1708 pps_stabil -= -v_usec >> PPS_AVG;
1709 else
1710 pps_stabil += v_usec >> PPS_AVG;
1711 if (pps_stabil > MAXFREQ >> 2) {
1712 pps_stbcnt++;
1713 time_status |= STA_PPSWANDER;
1714 return;
1715 }
1716 if (time_status & STA_PPSFREQ) {
1717 if (u_usec < 0) {
1718 pps_freq -= -u_usec >> PPS_AVG;
1719 if (pps_freq < -time_tolerance)
1720 pps_freq = -time_tolerance;
1721 u_usec = -u_usec;
1722 } else {
1723 pps_freq += u_usec >> PPS_AVG;
1724 if (pps_freq > time_tolerance)
1725 pps_freq = time_tolerance;
1726 }
1727 }
1728
1729 /*
1730 * Here the calibration interval is adjusted. If the maximum
1731 * time difference is greater than tick / 4, reduce the interval
1732 * by half. If this is not the case for four consecutive
1733 * intervals, double the interval.
1734 */
1735 if (u_usec << pps_shift > bigtick >> 2) {
1736 pps_intcnt = 0;
1737 if (pps_shift > PPS_SHIFT)
1738 pps_shift--;
1739 } else if (pps_intcnt >= 4) {
1740 pps_intcnt = 0;
1741 if (pps_shift < PPS_SHIFTMAX)
1742 pps_shift++;
1743 } else
1744 pps_intcnt++;
1745 }
1746 #endif /* PPS_SYNC */
1747 #endif /* NTP */
1748
1749 /*
1750 * Return information about system clocks.
1751 */
1752 int
1753 sysctl_clockrate(void *where, size_t *sizep)
1754 {
1755 struct clockinfo clkinfo;
1756
1757 /*
1758 * Construct clockinfo structure.
1759 */
1760 clkinfo.tick = tick;
1761 clkinfo.tickadj = tickadj;
1762 clkinfo.hz = hz;
1763 clkinfo.profhz = profhz;
1764 clkinfo.stathz = stathz ? stathz : hz;
1765 return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
1766 }
1767