kern_clock.c revision 1.96.6.4 1 /* $NetBSD: kern_clock.c,v 1.96.6.4 2006/04/24 08:37:35 kardel Exp $ */
2
3 /*-
4 * Copyright (c) 2000, 2004 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 * 3. All advertising materials mentioning features or use of this software
22 * must display the following acknowledgement:
23 * This product includes software developed by the NetBSD
24 * Foundation, Inc. and its contributors.
25 * 4. Neither the name of The NetBSD Foundation nor the names of its
26 * contributors may be used to endorse or promote products derived
27 * from this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
30 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
31 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
32 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
33 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
34 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
35 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
36 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
37 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
39 * POSSIBILITY OF SUCH DAMAGE.
40 */
41
42 /*-
43 * Copyright (c) 1982, 1986, 1991, 1993
44 * The Regents of the University of California. All rights reserved.
45 * (c) UNIX System Laboratories, Inc.
46 * All or some portions of this file are derived from material licensed
47 * to the University of California by American Telephone and Telegraph
48 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
49 * the permission of UNIX System Laboratories, Inc.
50 *
51 * Redistribution and use in source and binary forms, with or without
52 * modification, are permitted provided that the following conditions
53 * are met:
54 * 1. Redistributions of source code must retain the above copyright
55 * notice, this list of conditions and the following disclaimer.
56 * 2. Redistributions in binary form must reproduce the above copyright
57 * notice, this list of conditions and the following disclaimer in the
58 * documentation and/or other materials provided with the distribution.
59 * 3. Neither the name of the University nor the names of its contributors
60 * may be used to endorse or promote products derived from this software
61 * without specific prior written permission.
62 *
63 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
64 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
65 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
66 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
67 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
68 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
69 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
70 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
71 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
72 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
73 * SUCH DAMAGE.
74 *
75 * @(#)kern_clock.c 8.5 (Berkeley) 1/21/94
76 */
77
78 #include <sys/cdefs.h>
79 __KERNEL_RCSID(0, "$NetBSD: kern_clock.c,v 1.96.6.4 2006/04/24 08:37:35 kardel Exp $");
80
81 #include "opt_ntp.h"
82 #include "opt_multiprocessor.h"
83 #include "opt_perfctrs.h"
84
85 #include <sys/param.h>
86 #include <sys/systm.h>
87 #include <sys/callout.h>
88 #include <sys/kernel.h>
89 #include <sys/proc.h>
90 #include <sys/resourcevar.h>
91 #include <sys/signalvar.h>
92 #include <sys/sysctl.h>
93 #include <sys/timex.h>
94 #include <sys/sched.h>
95 #include <sys/time.h>
96 #ifdef __HAVE_TIMECOUNTER
97 #include <sys/timetc.h>
98 #endif
99
100 #include <machine/cpu.h>
101 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
102 #include <machine/intr.h>
103 #endif
104
105 #ifdef GPROF
106 #include <sys/gmon.h>
107 #endif
108
109 /*
110 * Clock handling routines.
111 *
112 * This code is written to operate with two timers that run independently of
113 * each other. The main clock, running hz times per second, is used to keep
114 * track of real time. The second timer handles kernel and user profiling,
115 * and does resource use estimation. If the second timer is programmable,
116 * it is randomized to avoid aliasing between the two clocks. For example,
117 * the randomization prevents an adversary from always giving up the CPU
118 * just before its quantum expires. Otherwise, it would never accumulate
119 * CPU ticks. The mean frequency of the second timer is stathz.
120 *
121 * If no second timer exists, stathz will be zero; in this case we drive
122 * profiling and statistics off the main clock. This WILL NOT be accurate;
123 * do not do it unless absolutely necessary.
124 *
125 * The statistics clock may (or may not) be run at a higher rate while
126 * profiling. This profile clock runs at profhz. We require that profhz
127 * be an integral multiple of stathz.
128 *
129 * If the statistics clock is running fast, it must be divided by the ratio
130 * profhz/stathz for statistics. (For profiling, every tick counts.)
131 */
132
133 #ifndef __HAVE_TIMECOUNTER
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 * pps_kc_hardpps_source contains an arbitrary value that uniquely
241 * identifies the currently bound source of the PPS signal, or NULL
242 * if no source is bound.
243 *
244 * pps_kc_hardpps_mode indicates which transitions, if any, of the PPS
245 * signal should be reported.
246 */
247 struct timeval pps_time; /* kernel time at last interval */
248 long pps_tf[] = {0, 0, 0}; /* pps time offset median filter (us) */
249 long pps_offset = 0; /* pps time offset (us) */
250 long pps_jitter = MAXTIME; /* time dispersion (jitter) (us) */
251 long pps_ff[] = {0, 0, 0}; /* pps frequency offset median filter */
252 long pps_freq = 0; /* frequency offset (scaled ppm) */
253 long pps_stabil = MAXFREQ; /* frequency dispersion (scaled ppm) */
254 long pps_usec = 0; /* microsec counter at last interval */
255 long pps_valid = PPS_VALID; /* pps signal watchdog counter */
256 int pps_glitch = 0; /* pps signal glitch counter */
257 int pps_count = 0; /* calibration interval counter (s) */
258 int pps_shift = PPS_SHIFT; /* interval duration (s) (shift) */
259 int pps_intcnt = 0; /* intervals at current duration */
260 void *pps_kc_hardpps_source = NULL; /* current PPS supplier's identifier */
261 int pps_kc_hardpps_mode = 0; /* interesting edges of PPS signal */
262
263 /*
264 * PPS signal quality monitors
265 *
266 * pps_jitcnt counts the seconds that have been discarded because the
267 * jitter measured by the time median filter exceeds the limit MAXTIME
268 * (100 us).
269 *
270 * pps_calcnt counts the frequency calibration intervals, which are
271 * variable from 4 s to 256 s.
272 *
273 * pps_errcnt counts the calibration intervals which have been discarded
274 * because the wander exceeds the limit MAXFREQ (100 ppm) or where the
275 * calibration interval jitter exceeds two ticks.
276 *
277 * pps_stbcnt counts the calibration intervals that have been discarded
278 * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us).
279 */
280 long pps_jitcnt = 0; /* jitter limit exceeded */
281 long pps_calcnt = 0; /* calibration intervals */
282 long pps_errcnt = 0; /* calibration errors */
283 long pps_stbcnt = 0; /* stability limit exceeded */
284 #endif /* PPS_SYNC */
285
286 #ifdef EXT_CLOCK
287 /*
288 * External clock definitions
289 *
290 * The following definitions and declarations are used only if an
291 * external clock is configured on the system.
292 */
293 #define CLOCK_INTERVAL 30 /* CPU clock update interval (s) */
294
295 /*
296 * The clock_count variable is set to CLOCK_INTERVAL at each PPS
297 * interrupt and decremented once each second.
298 */
299 int clock_count = 0; /* CPU clock counter */
300
301 #ifdef HIGHBALL
302 /*
303 * The clock_offset and clock_cpu variables are used by the HIGHBALL
304 * interface. The clock_offset variable defines the offset between
305 * system time and the HIGBALL counters. The clock_cpu variable contains
306 * the offset between the system clock and the HIGHBALL clock for use in
307 * disciplining the kernel time variable.
308 */
309 extern struct timeval clock_offset; /* Highball clock offset */
310 long clock_cpu = 0; /* CPU clock adjust */
311 #endif /* HIGHBALL */
312 #endif /* EXT_CLOCK */
313 #endif /* NTP */
314
315 /*
316 * Bump a timeval by a small number of usec's.
317 */
318 #define BUMPTIME(t, usec) { \
319 volatile struct timeval *tp = (t); \
320 long us; \
321 \
322 tp->tv_usec = us = tp->tv_usec + (usec); \
323 if (us >= 1000000) { \
324 tp->tv_usec = us - 1000000; \
325 tp->tv_sec++; \
326 } \
327 }
328 #endif /* !__HAVE_TIMECOUNTER */
329
330 int stathz;
331 int profhz;
332 int profsrc;
333 int schedhz;
334 int profprocs;
335 int hardclock_ticks;
336 static int statscheddiv; /* stat => sched divider (used if schedhz == 0) */
337 static int psdiv; /* prof => stat divider */
338 int psratio; /* ratio: prof / stat */
339 #ifndef __HAVE_TIMECOUNTER
340 int tickfix, tickfixinterval; /* used if tick not really integral */
341 #ifndef NTP
342 static int tickfixcnt; /* accumulated fractional error */
343 #else
344 int fixtick; /* used by NTP for same */
345 int shifthz;
346 #endif
347
348 /*
349 * We might want ldd to load the both words from time at once.
350 * To succeed we need to be quadword aligned.
351 * The sparc already does that, and that it has worked so far is a fluke.
352 */
353 volatile struct timeval time __attribute__((__aligned__(__alignof__(quad_t))));
354 volatile struct timeval mono_time;
355 #endif /* !__HAVE_TIMECOUNTER */
356
357 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
358 void *softclock_si;
359 #endif
360
361 /*
362 * Initialize clock frequencies and start both clocks running.
363 */
364 void
365 initclocks(void)
366 {
367 int i;
368
369 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
370 softclock_si = softintr_establish(IPL_SOFTCLOCK, softclock, NULL);
371 if (softclock_si == NULL)
372 panic("initclocks: unable to register softclock intr");
373 #endif
374
375 /*
376 * Set divisors to 1 (normal case) and let the machine-specific
377 * code do its bit.
378 */
379 psdiv = 1;
380 #ifdef __HAVE_TIMECOUNTER
381 inittimecounter();
382 #endif
383 cpu_initclocks();
384
385 /*
386 * Compute profhz/stathz/rrticks, and fix profhz if needed.
387 */
388 i = stathz ? stathz : hz;
389 if (profhz == 0)
390 profhz = i;
391 psratio = profhz / i;
392 rrticks = hz / 10;
393 if (schedhz == 0) {
394 /* 16Hz is best */
395 statscheddiv = i / 16;
396 if (statscheddiv <= 0)
397 panic("statscheddiv");
398 }
399
400 #ifndef __HAVE_TIMECOUNTER
401 #ifdef NTP
402 switch (hz) {
403 case 1:
404 shifthz = SHIFT_SCALE - 0;
405 break;
406 case 2:
407 shifthz = SHIFT_SCALE - 1;
408 break;
409 case 4:
410 shifthz = SHIFT_SCALE - 2;
411 break;
412 case 8:
413 shifthz = SHIFT_SCALE - 3;
414 break;
415 case 16:
416 shifthz = SHIFT_SCALE - 4;
417 break;
418 case 32:
419 shifthz = SHIFT_SCALE - 5;
420 break;
421 case 50:
422 case 60:
423 case 64:
424 shifthz = SHIFT_SCALE - 6;
425 break;
426 case 96:
427 case 100:
428 case 128:
429 shifthz = SHIFT_SCALE - 7;
430 break;
431 case 256:
432 shifthz = SHIFT_SCALE - 8;
433 break;
434 case 512:
435 shifthz = SHIFT_SCALE - 9;
436 break;
437 case 1000:
438 case 1024:
439 shifthz = SHIFT_SCALE - 10;
440 break;
441 case 1200:
442 case 2048:
443 shifthz = SHIFT_SCALE - 11;
444 break;
445 case 4096:
446 shifthz = SHIFT_SCALE - 12;
447 break;
448 case 8192:
449 shifthz = SHIFT_SCALE - 13;
450 break;
451 case 16384:
452 shifthz = SHIFT_SCALE - 14;
453 break;
454 case 32768:
455 shifthz = SHIFT_SCALE - 15;
456 break;
457 case 65536:
458 shifthz = SHIFT_SCALE - 16;
459 break;
460 default:
461 panic("weird hz");
462 }
463 if (fixtick == 0) {
464 /*
465 * Give MD code a chance to set this to a better
466 * value; but, if it doesn't, we should.
467 */
468 fixtick = (1000000 - (hz*tick));
469 }
470 #endif /* NTP */
471 #endif /* !__HAVE_TIMECOUNTER */
472 }
473
474 /*
475 * The real-time timer, interrupting hz times per second.
476 */
477 void
478 hardclock(struct clockframe *frame)
479 {
480 struct lwp *l;
481 struct proc *p;
482 struct cpu_info *ci = curcpu();
483 struct ptimer *pt;
484 #ifndef __HAVE_TIMECOUNTER
485 int delta;
486 extern int tickdelta;
487 extern long timedelta;
488 #ifdef NTP
489 int time_update;
490 int ltemp;
491 #endif /* NTP */
492 #endif /* __HAVE_TIMECOUNTER */
493
494 l = curlwp;
495 if (l) {
496 p = l->l_proc;
497 /*
498 * Run current process's virtual and profile time, as needed.
499 */
500 if (CLKF_USERMODE(frame) && p->p_timers &&
501 (pt = LIST_FIRST(&p->p_timers->pts_virtual)) != NULL)
502 if (itimerdecr(pt, tick) == 0)
503 itimerfire(pt);
504 if (p->p_timers &&
505 (pt = LIST_FIRST(&p->p_timers->pts_prof)) != NULL)
506 if (itimerdecr(pt, tick) == 0)
507 itimerfire(pt);
508 }
509
510 /*
511 * If no separate statistics clock is available, run it from here.
512 */
513 if (stathz == 0)
514 statclock(frame);
515 if ((--ci->ci_schedstate.spc_rrticks) <= 0)
516 roundrobin(ci);
517
518 #if defined(MULTIPROCESSOR)
519 /*
520 * If we are not the primary CPU, we're not allowed to do
521 * any more work.
522 */
523 if (CPU_IS_PRIMARY(ci) == 0)
524 return;
525 #endif
526
527 hardclock_ticks++;
528
529 #ifdef __HAVE_TIMECOUNTER
530 tc_ticktock();
531 #else /* __HAVE_TIMECOUNTER */
532 /*
533 * Increment the time-of-day. The increment is normally just
534 * ``tick''. If the machine is one which has a clock frequency
535 * such that ``hz'' would not divide the second evenly into
536 * milliseconds, a periodic adjustment must be applied. Finally,
537 * if we are still adjusting the time (see adjtime()),
538 * ``tickdelta'' may also be added in.
539 */
540 delta = tick;
541
542 #ifndef NTP
543 if (tickfix) {
544 tickfixcnt += tickfix;
545 if (tickfixcnt >= tickfixinterval) {
546 delta++;
547 tickfixcnt -= tickfixinterval;
548 }
549 }
550 #endif /* !NTP */
551 /* Imprecise 4bsd adjtime() handling */
552 if (timedelta != 0) {
553 delta += tickdelta;
554 timedelta -= tickdelta;
555 }
556
557 #ifdef notyet
558 microset();
559 #endif
560
561 #ifndef NTP
562 BUMPTIME(&time, delta); /* XXX Now done using NTP code below */
563 #endif
564 BUMPTIME(&mono_time, delta);
565
566 #ifdef NTP
567 time_update = delta;
568
569 /*
570 * Compute the phase adjustment. If the low-order bits
571 * (time_phase) of the update overflow, bump the high-order bits
572 * (time_update).
573 */
574 time_phase += time_adj;
575 if (time_phase <= -FINEUSEC) {
576 ltemp = -time_phase >> SHIFT_SCALE;
577 time_phase += ltemp << SHIFT_SCALE;
578 time_update -= ltemp;
579 } else if (time_phase >= FINEUSEC) {
580 ltemp = time_phase >> SHIFT_SCALE;
581 time_phase -= ltemp << SHIFT_SCALE;
582 time_update += ltemp;
583 }
584
585 #ifdef HIGHBALL
586 /*
587 * If the HIGHBALL board is installed, we need to adjust the
588 * external clock offset in order to close the hardware feedback
589 * loop. This will adjust the external clock phase and frequency
590 * in small amounts. The additional phase noise and frequency
591 * wander this causes should be minimal. We also need to
592 * discipline the kernel time variable, since the PLL is used to
593 * discipline the external clock. If the Highball board is not
594 * present, we discipline kernel time with the PLL as usual. We
595 * assume that the external clock phase adjustment (time_update)
596 * and kernel phase adjustment (clock_cpu) are less than the
597 * value of tick.
598 */
599 clock_offset.tv_usec += time_update;
600 if (clock_offset.tv_usec >= 1000000) {
601 clock_offset.tv_sec++;
602 clock_offset.tv_usec -= 1000000;
603 }
604 if (clock_offset.tv_usec < 0) {
605 clock_offset.tv_sec--;
606 clock_offset.tv_usec += 1000000;
607 }
608 time.tv_usec += clock_cpu;
609 clock_cpu = 0;
610 #else
611 time.tv_usec += time_update;
612 #endif /* HIGHBALL */
613
614 /*
615 * On rollover of the second the phase adjustment to be used for
616 * the next second is calculated. Also, the maximum error is
617 * increased by the tolerance. If the PPS frequency discipline
618 * code is present, the phase is increased to compensate for the
619 * CPU clock oscillator frequency error.
620 *
621 * On a 32-bit machine and given parameters in the timex.h
622 * header file, the maximum phase adjustment is +-512 ms and
623 * maximum frequency offset is a tad less than) +-512 ppm. On a
624 * 64-bit machine, you shouldn't need to ask.
625 */
626 if (time.tv_usec >= 1000000) {
627 time.tv_usec -= 1000000;
628 time.tv_sec++;
629 time_maxerror += time_tolerance >> SHIFT_USEC;
630
631 /*
632 * Leap second processing. If in leap-insert state at
633 * the end of the day, the system clock is set back one
634 * second; if in leap-delete state, the system clock is
635 * set ahead one second. The microtime() routine or
636 * external clock driver will insure that reported time
637 * is always monotonic. The ugly divides should be
638 * replaced.
639 */
640 switch (time_state) {
641 case TIME_OK:
642 if (time_status & STA_INS)
643 time_state = TIME_INS;
644 else if (time_status & STA_DEL)
645 time_state = TIME_DEL;
646 break;
647
648 case TIME_INS:
649 if (time.tv_sec % 86400 == 0) {
650 time.tv_sec--;
651 time_state = TIME_OOP;
652 }
653 break;
654
655 case TIME_DEL:
656 if ((time.tv_sec + 1) % 86400 == 0) {
657 time.tv_sec++;
658 time_state = TIME_WAIT;
659 }
660 break;
661
662 case TIME_OOP:
663 time_state = TIME_WAIT;
664 break;
665
666 case TIME_WAIT:
667 if (!(time_status & (STA_INS | STA_DEL)))
668 time_state = TIME_OK;
669 break;
670 }
671
672 /*
673 * Compute the phase adjustment for the next second. In
674 * PLL mode, the offset is reduced by a fixed factor
675 * times the time constant. In FLL mode the offset is
676 * used directly. In either mode, the maximum phase
677 * adjustment for each second is clamped so as to spread
678 * the adjustment over not more than the number of
679 * seconds between updates.
680 */
681 if (time_offset < 0) {
682 ltemp = -time_offset;
683 if (!(time_status & STA_FLL))
684 ltemp >>= SHIFT_KG + time_constant;
685 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
686 ltemp = (MAXPHASE / MINSEC) <<
687 SHIFT_UPDATE;
688 time_offset += ltemp;
689 time_adj = -ltemp << (shifthz - SHIFT_UPDATE);
690 } else if (time_offset > 0) {
691 ltemp = time_offset;
692 if (!(time_status & STA_FLL))
693 ltemp >>= SHIFT_KG + time_constant;
694 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
695 ltemp = (MAXPHASE / MINSEC) <<
696 SHIFT_UPDATE;
697 time_offset -= ltemp;
698 time_adj = ltemp << (shifthz - SHIFT_UPDATE);
699 } else
700 time_adj = 0;
701
702 /*
703 * Compute the frequency estimate and additional phase
704 * adjustment due to frequency error for the next
705 * second. When the PPS signal is engaged, gnaw on the
706 * watchdog counter and update the frequency computed by
707 * the pll and the PPS signal.
708 */
709 #ifdef PPS_SYNC
710 pps_valid++;
711 if (pps_valid == PPS_VALID) {
712 pps_jitter = MAXTIME;
713 pps_stabil = MAXFREQ;
714 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
715 STA_PPSWANDER | STA_PPSERROR);
716 }
717 ltemp = time_freq + pps_freq;
718 #else
719 ltemp = time_freq;
720 #endif /* PPS_SYNC */
721
722 if (ltemp < 0)
723 time_adj -= -ltemp >> (SHIFT_USEC - shifthz);
724 else
725 time_adj += ltemp >> (SHIFT_USEC - shifthz);
726 time_adj += (long)fixtick << shifthz;
727
728 /*
729 * When the CPU clock oscillator frequency is not a
730 * power of 2 in Hz, shifthz is only an approximate
731 * scale factor.
732 *
733 * To determine the adjustment, you can do the following:
734 * bc -q
735 * scale=24
736 * obase=2
737 * idealhz/realhz
738 * where `idealhz' is the next higher power of 2, and `realhz'
739 * is the actual value. You may need to factor this result
740 * into a sequence of 2 multipliers to get better precision.
741 *
742 * Likewise, the error can be calculated with (e.g. for 100Hz):
743 * bc -q
744 * scale=24
745 * ((1+2^-2+2^-5)*(1-2^-10)*realhz-idealhz)/idealhz
746 * (and then multiply by 1000000 to get ppm).
747 */
748 switch (hz) {
749 case 60:
750 /* A factor of 1.000100010001 gives about 15ppm
751 error. */
752 if (time_adj < 0) {
753 time_adj -= (-time_adj >> 4);
754 time_adj -= (-time_adj >> 8);
755 } else {
756 time_adj += (time_adj >> 4);
757 time_adj += (time_adj >> 8);
758 }
759 break;
760
761 case 96:
762 /* A factor of 1.0101010101 gives about 244ppm error. */
763 if (time_adj < 0) {
764 time_adj -= (-time_adj >> 2);
765 time_adj -= (-time_adj >> 4) + (-time_adj >> 8);
766 } else {
767 time_adj += (time_adj >> 2);
768 time_adj += (time_adj >> 4) + (time_adj >> 8);
769 }
770 break;
771
772 case 50:
773 case 100:
774 /* A factor of 1.010001111010111 gives about 1ppm
775 error. */
776 if (time_adj < 0) {
777 time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
778 time_adj += (-time_adj >> 10);
779 } else {
780 time_adj += (time_adj >> 2) + (time_adj >> 5);
781 time_adj -= (time_adj >> 10);
782 }
783 break;
784
785 case 1000:
786 /* A factor of 1.000001100010100001 gives about 50ppm
787 error. */
788 if (time_adj < 0) {
789 time_adj -= (-time_adj >> 6) + (-time_adj >> 11);
790 time_adj -= (-time_adj >> 7);
791 } else {
792 time_adj += (time_adj >> 6) + (time_adj >> 11);
793 time_adj += (time_adj >> 7);
794 }
795 break;
796
797 case 1200:
798 /* A factor of 1.1011010011100001 gives about 64ppm
799 error. */
800 if (time_adj < 0) {
801 time_adj -= (-time_adj >> 1) + (-time_adj >> 6);
802 time_adj -= (-time_adj >> 3) + (-time_adj >> 10);
803 } else {
804 time_adj += (time_adj >> 1) + (time_adj >> 6);
805 time_adj += (time_adj >> 3) + (time_adj >> 10);
806 }
807 break;
808 }
809
810 #ifdef EXT_CLOCK
811 /*
812 * If an external clock is present, it is necessary to
813 * discipline the kernel time variable anyway, since not
814 * all system components use the microtime() interface.
815 * Here, the time offset between the external clock and
816 * kernel time variable is computed every so often.
817 */
818 clock_count++;
819 if (clock_count > CLOCK_INTERVAL) {
820 clock_count = 0;
821 microtime(&clock_ext);
822 delta.tv_sec = clock_ext.tv_sec - time.tv_sec;
823 delta.tv_usec = clock_ext.tv_usec -
824 time.tv_usec;
825 if (delta.tv_usec < 0)
826 delta.tv_sec--;
827 if (delta.tv_usec >= 500000) {
828 delta.tv_usec -= 1000000;
829 delta.tv_sec++;
830 }
831 if (delta.tv_usec < -500000) {
832 delta.tv_usec += 1000000;
833 delta.tv_sec--;
834 }
835 if (delta.tv_sec > 0 || (delta.tv_sec == 0 &&
836 delta.tv_usec > MAXPHASE) ||
837 delta.tv_sec < -1 || (delta.tv_sec == -1 &&
838 delta.tv_usec < -MAXPHASE)) {
839 time = clock_ext;
840 delta.tv_sec = 0;
841 delta.tv_usec = 0;
842 }
843 #ifdef HIGHBALL
844 clock_cpu = delta.tv_usec;
845 #else /* HIGHBALL */
846 hardupdate(delta.tv_usec);
847 #endif /* HIGHBALL */
848 }
849 #endif /* EXT_CLOCK */
850 }
851
852 #endif /* NTP */
853 #endif /* !__HAVE_TIMECOUNTER */
854
855 /*
856 * Update real-time timeout queue.
857 * Process callouts at a very low CPU priority, so we don't keep the
858 * relatively high clock interrupt priority any longer than necessary.
859 */
860 if (callout_hardclock()) {
861 if (CLKF_BASEPRI(frame)) {
862 /*
863 * Save the overhead of a software interrupt;
864 * it will happen as soon as we return, so do
865 * it now.
866 */
867 spllowersoftclock();
868 KERNEL_LOCK(LK_CANRECURSE|LK_EXCLUSIVE);
869 softclock(NULL);
870 KERNEL_UNLOCK();
871 } else {
872 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
873 softintr_schedule(softclock_si);
874 #else
875 setsoftclock();
876 #endif
877 }
878 }
879 }
880
881 #ifdef __HAVE_TIMECOUNTER
882 /*
883 * Compute number of hz until specified time. Used to compute second
884 * argument to callout_reset() from an absolute time.
885 */
886 int
887 hzto(struct timeval *tvp)
888 {
889 struct timeval now, tv;
890
891 tv = *tvp; /* Don't modify original tvp. */
892 getmicrotime(&now);
893 timersub(&tv, &now, &tv);
894 return tvtohz(&tv);
895 }
896 #endif /* __HAVE_TIMECOUNTER */
897
898 /*
899 * Compute number of ticks in the specified amount of time.
900 */
901 int
902 tvtohz(struct timeval *tv)
903 {
904 unsigned long ticks;
905 long sec, usec;
906
907 /*
908 * If the number of usecs in the whole seconds part of the time
909 * difference fits in a long, then the total number of usecs will
910 * fit in an unsigned long. Compute the total and convert it to
911 * ticks, rounding up and adding 1 to allow for the current tick
912 * to expire. Rounding also depends on unsigned long arithmetic
913 * to avoid overflow.
914 *
915 * Otherwise, if the number of ticks in the whole seconds part of
916 * the time difference fits in a long, then convert the parts to
917 * ticks separately and add, using similar rounding methods and
918 * overflow avoidance. This method would work in the previous
919 * case, but it is slightly slower and assumes that hz is integral.
920 *
921 * Otherwise, round the time difference down to the maximum
922 * representable value.
923 *
924 * If ints are 32-bit, then the maximum value for any timeout in
925 * 10ms ticks is 248 days.
926 */
927 sec = tv->tv_sec;
928 usec = tv->tv_usec;
929
930 if (usec < 0) {
931 sec--;
932 usec += 1000000;
933 }
934
935 if (sec < 0 || (sec == 0 && usec <= 0)) {
936 /*
937 * Would expire now or in the past. Return 0 ticks.
938 * This is different from the legacy hzto() interface,
939 * and callers need to check for it.
940 */
941 ticks = 0;
942 } else if (sec <= (LONG_MAX / 1000000))
943 ticks = (((sec * 1000000) + (unsigned long)usec + (tick - 1))
944 / tick) + 1;
945 else if (sec <= (LONG_MAX / hz))
946 ticks = (sec * hz) +
947 (((unsigned long)usec + (tick - 1)) / tick) + 1;
948 else
949 ticks = LONG_MAX;
950
951 if (ticks > INT_MAX)
952 ticks = INT_MAX;
953
954 return ((int)ticks);
955 }
956
957 #ifndef __HAVE_TIMECOUNTER
958 /*
959 * Compute number of hz until specified time. Used to compute second
960 * argument to callout_reset() from an absolute time.
961 */
962 int
963 hzto(struct timeval *tv)
964 {
965 unsigned long ticks;
966 long sec, usec;
967 int s;
968
969 /*
970 * If the number of usecs in the whole seconds part of the time
971 * difference fits in a long, then the total number of usecs will
972 * fit in an unsigned long. Compute the total and convert it to
973 * ticks, rounding up and adding 1 to allow for the current tick
974 * to expire. Rounding also depends on unsigned long arithmetic
975 * to avoid overflow.
976 *
977 * Otherwise, if the number of ticks in the whole seconds part of
978 * the time difference fits in a long, then convert the parts to
979 * ticks separately and add, using similar rounding methods and
980 * overflow avoidance. This method would work in the previous
981 * case, but it is slightly slower and assume that hz is integral.
982 *
983 * Otherwise, round the time difference down to the maximum
984 * representable value.
985 *
986 * If ints are 32-bit, then the maximum value for any timeout in
987 * 10ms ticks is 248 days.
988 */
989 s = splclock();
990 sec = tv->tv_sec - time.tv_sec;
991 usec = tv->tv_usec - time.tv_usec;
992 splx(s);
993
994 if (usec < 0) {
995 sec--;
996 usec += 1000000;
997 }
998
999 if (sec < 0 || (sec == 0 && usec <= 0)) {
1000 /*
1001 * Would expire now or in the past. Return 0 ticks.
1002 * This is different from the legacy hzto() interface,
1003 * and callers need to check for it.
1004 */
1005 ticks = 0;
1006 } else if (sec <= (LONG_MAX / 1000000))
1007 ticks = (((sec * 1000000) + (unsigned long)usec + (tick - 1))
1008 / tick) + 1;
1009 else if (sec <= (LONG_MAX / hz))
1010 ticks = (sec * hz) +
1011 (((unsigned long)usec + (tick - 1)) / tick) + 1;
1012 else
1013 ticks = LONG_MAX;
1014
1015 if (ticks > INT_MAX)
1016 ticks = INT_MAX;
1017
1018 return ((int)ticks);
1019 }
1020 #endif /* !__HAVE_TIMECOUNTER */
1021
1022 /*
1023 * Compute number of ticks in the specified amount of time.
1024 */
1025 int
1026 tstohz(struct timespec *ts)
1027 {
1028 struct timeval tv;
1029
1030 /*
1031 * usec has great enough resolution for hz, so convert to a
1032 * timeval and use tvtohz() above.
1033 */
1034 TIMESPEC_TO_TIMEVAL(&tv, ts);
1035 return tvtohz(&tv);
1036 }
1037
1038 /*
1039 * Start profiling on a process.
1040 *
1041 * Kernel profiling passes proc0 which never exits and hence
1042 * keeps the profile clock running constantly.
1043 */
1044 void
1045 startprofclock(struct proc *p)
1046 {
1047
1048 if ((p->p_flag & P_PROFIL) == 0) {
1049 p->p_flag |= P_PROFIL;
1050 /*
1051 * This is only necessary if using the clock as the
1052 * profiling source.
1053 */
1054 if (++profprocs == 1 && stathz != 0)
1055 psdiv = psratio;
1056 }
1057 }
1058
1059 /*
1060 * Stop profiling on a process.
1061 */
1062 void
1063 stopprofclock(struct proc *p)
1064 {
1065
1066 if (p->p_flag & P_PROFIL) {
1067 p->p_flag &= ~P_PROFIL;
1068 /*
1069 * This is only necessary if using the clock as the
1070 * profiling source.
1071 */
1072 if (--profprocs == 0 && stathz != 0)
1073 psdiv = 1;
1074 }
1075 }
1076
1077 #if defined(PERFCTRS)
1078 /*
1079 * Independent profiling "tick" in case we're using a separate
1080 * clock or profiling event source. Currently, that's just
1081 * performance counters--hence the wrapper.
1082 */
1083 void
1084 proftick(struct clockframe *frame)
1085 {
1086 #ifdef GPROF
1087 struct gmonparam *g;
1088 intptr_t i;
1089 #endif
1090 struct proc *p;
1091
1092 p = curproc;
1093 if (CLKF_USERMODE(frame)) {
1094 if (p->p_flag & P_PROFIL)
1095 addupc_intr(p, CLKF_PC(frame));
1096 } else {
1097 #ifdef GPROF
1098 g = &_gmonparam;
1099 if (g->state == GMON_PROF_ON) {
1100 i = CLKF_PC(frame) - g->lowpc;
1101 if (i < g->textsize) {
1102 i /= HISTFRACTION * sizeof(*g->kcount);
1103 g->kcount[i]++;
1104 }
1105 }
1106 #endif
1107 #ifdef PROC_PC
1108 if (p && (p->p_flag & P_PROFIL))
1109 addupc_intr(p, PROC_PC(p));
1110 #endif
1111 }
1112 }
1113 #endif
1114
1115 /*
1116 * Statistics clock. Grab profile sample, and if divider reaches 0,
1117 * do process and kernel statistics.
1118 */
1119 void
1120 statclock(struct clockframe *frame)
1121 {
1122 #ifdef GPROF
1123 struct gmonparam *g;
1124 intptr_t i;
1125 #endif
1126 struct cpu_info *ci = curcpu();
1127 struct schedstate_percpu *spc = &ci->ci_schedstate;
1128 struct proc *p;
1129 struct lwp *l;
1130
1131 /*
1132 * Notice changes in divisor frequency, and adjust clock
1133 * frequency accordingly.
1134 */
1135 if (spc->spc_psdiv != psdiv) {
1136 spc->spc_psdiv = psdiv;
1137 spc->spc_pscnt = psdiv;
1138 if (psdiv == 1) {
1139 setstatclockrate(stathz);
1140 } else {
1141 setstatclockrate(profhz);
1142 }
1143 }
1144 l = curlwp;
1145 p = (l ? l->l_proc : NULL);
1146 if (CLKF_USERMODE(frame)) {
1147 KASSERT(p != NULL);
1148
1149 if ((p->p_flag & P_PROFIL) && profsrc == PROFSRC_CLOCK)
1150 addupc_intr(p, CLKF_PC(frame));
1151 if (--spc->spc_pscnt > 0)
1152 return;
1153 /*
1154 * Came from user mode; CPU was in user state.
1155 * If this process is being profiled record the tick.
1156 */
1157 p->p_uticks++;
1158 if (p->p_nice > NZERO)
1159 spc->spc_cp_time[CP_NICE]++;
1160 else
1161 spc->spc_cp_time[CP_USER]++;
1162 } else {
1163 #ifdef GPROF
1164 /*
1165 * Kernel statistics are just like addupc_intr, only easier.
1166 */
1167 g = &_gmonparam;
1168 if (profsrc == PROFSRC_CLOCK && g->state == GMON_PROF_ON) {
1169 i = CLKF_PC(frame) - g->lowpc;
1170 if (i < g->textsize) {
1171 i /= HISTFRACTION * sizeof(*g->kcount);
1172 g->kcount[i]++;
1173 }
1174 }
1175 #endif
1176 #ifdef LWP_PC
1177 if (p && profsrc == PROFSRC_CLOCK && (p->p_flag & P_PROFIL))
1178 addupc_intr(p, LWP_PC(l));
1179 #endif
1180 if (--spc->spc_pscnt > 0)
1181 return;
1182 /*
1183 * Came from kernel mode, so we were:
1184 * - handling an interrupt,
1185 * - doing syscall or trap work on behalf of the current
1186 * user process, or
1187 * - spinning in the idle loop.
1188 * Whichever it is, charge the time as appropriate.
1189 * Note that we charge interrupts to the current process,
1190 * regardless of whether they are ``for'' that process,
1191 * so that we know how much of its real time was spent
1192 * in ``non-process'' (i.e., interrupt) work.
1193 */
1194 if (CLKF_INTR(frame)) {
1195 if (p != NULL)
1196 p->p_iticks++;
1197 spc->spc_cp_time[CP_INTR]++;
1198 } else if (p != NULL) {
1199 p->p_sticks++;
1200 spc->spc_cp_time[CP_SYS]++;
1201 } else
1202 spc->spc_cp_time[CP_IDLE]++;
1203 }
1204 spc->spc_pscnt = psdiv;
1205
1206 if (p != NULL) {
1207 ++p->p_cpticks;
1208 /*
1209 * If no separate schedclock is provided, call it here
1210 * at about 16 Hz.
1211 */
1212 if (schedhz == 0)
1213 if ((int)(--ci->ci_schedstate.spc_schedticks) <= 0) {
1214 schedclock(l);
1215 ci->ci_schedstate.spc_schedticks = statscheddiv;
1216 }
1217 }
1218 }
1219
1220 #ifndef __HAVE_TIMECOUNTER
1221 #ifdef NTP /* NTP phase-locked loop in kernel */
1222 /*
1223 * hardupdate() - local clock update
1224 *
1225 * This routine is called by ntp_adjtime() to update the local clock
1226 * phase and frequency. The implementation is of an adaptive-parameter,
1227 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
1228 * time and frequency offset estimates for each call. If the kernel PPS
1229 * discipline code is configured (PPS_SYNC), the PPS signal itself
1230 * determines the new time offset, instead of the calling argument.
1231 * Presumably, calls to ntp_adjtime() occur only when the caller
1232 * believes the local clock is valid within some bound (+-128 ms with
1233 * NTP). If the caller's time is far different than the PPS time, an
1234 * argument will ensue, and it's not clear who will lose.
1235 *
1236 * For uncompensated quartz crystal oscillatores and nominal update
1237 * intervals less than 1024 s, operation should be in phase-lock mode
1238 * (STA_FLL = 0), where the loop is disciplined to phase. For update
1239 * intervals greater than thiss, operation should be in frequency-lock
1240 * mode (STA_FLL = 1), where the loop is disciplined to frequency.
1241 *
1242 * Note: splclock() is in effect.
1243 */
1244 void
1245 hardupdate(long offset)
1246 {
1247 long ltemp, mtemp;
1248
1249 if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
1250 return;
1251 ltemp = offset;
1252 #ifdef PPS_SYNC
1253 if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
1254 ltemp = pps_offset;
1255 #endif /* PPS_SYNC */
1256
1257 /*
1258 * Scale the phase adjustment and clamp to the operating range.
1259 */
1260 if (ltemp > MAXPHASE)
1261 time_offset = MAXPHASE << SHIFT_UPDATE;
1262 else if (ltemp < -MAXPHASE)
1263 time_offset = -(MAXPHASE << SHIFT_UPDATE);
1264 else
1265 time_offset = ltemp << SHIFT_UPDATE;
1266
1267 /*
1268 * Select whether the frequency is to be controlled and in which
1269 * mode (PLL or FLL). Clamp to the operating range. Ugly
1270 * multiply/divide should be replaced someday.
1271 */
1272 if (time_status & STA_FREQHOLD || time_reftime == 0)
1273 time_reftime = time.tv_sec;
1274 mtemp = time.tv_sec - time_reftime;
1275 time_reftime = time.tv_sec;
1276 if (time_status & STA_FLL) {
1277 if (mtemp >= MINSEC) {
1278 ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
1279 SHIFT_UPDATE));
1280 if (ltemp < 0)
1281 time_freq -= -ltemp >> SHIFT_KH;
1282 else
1283 time_freq += ltemp >> SHIFT_KH;
1284 }
1285 } else {
1286 if (mtemp < MAXSEC) {
1287 ltemp *= mtemp;
1288 if (ltemp < 0)
1289 time_freq -= -ltemp >> (time_constant +
1290 time_constant + SHIFT_KF -
1291 SHIFT_USEC);
1292 else
1293 time_freq += ltemp >> (time_constant +
1294 time_constant + SHIFT_KF -
1295 SHIFT_USEC);
1296 }
1297 }
1298 if (time_freq > time_tolerance)
1299 time_freq = time_tolerance;
1300 else if (time_freq < -time_tolerance)
1301 time_freq = -time_tolerance;
1302 }
1303
1304 #ifdef PPS_SYNC
1305 /*
1306 * hardpps() - discipline CPU clock oscillator to external PPS signal
1307 *
1308 * This routine is called at each PPS interrupt in order to discipline
1309 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
1310 * and leaves it in a handy spot for the hardclock() routine. It
1311 * integrates successive PPS phase differences and calculates the
1312 * frequency offset. This is used in hardclock() to discipline the CPU
1313 * clock oscillator so that intrinsic frequency error is cancelled out.
1314 * The code requires the caller to capture the time and hardware counter
1315 * value at the on-time PPS signal transition.
1316 *
1317 * Note that, on some Unix systems, this routine runs at an interrupt
1318 * priority level higher than the timer interrupt routine hardclock().
1319 * Therefore, the variables used are distinct from the hardclock()
1320 * variables, except for certain exceptions: The PPS frequency pps_freq
1321 * and phase pps_offset variables are determined by this routine and
1322 * updated atomically. The time_tolerance variable can be considered a
1323 * constant, since it is infrequently changed, and then only when the
1324 * PPS signal is disabled. The watchdog counter pps_valid is updated
1325 * once per second by hardclock() and is atomically cleared in this
1326 * routine.
1327 */
1328 void
1329 hardpps(struct timeval *tvp, /* time at PPS */
1330 long usec /* hardware counter at PPS */)
1331 {
1332 long u_usec, v_usec, bigtick;
1333 long cal_sec, cal_usec;
1334
1335 /*
1336 * An occasional glitch can be produced when the PPS interrupt
1337 * occurs in the hardclock() routine before the time variable is
1338 * updated. Here the offset is discarded when the difference
1339 * between it and the last one is greater than tick/2, but not
1340 * if the interval since the first discard exceeds 30 s.
1341 */
1342 time_status |= STA_PPSSIGNAL;
1343 time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1344 pps_valid = 0;
1345 u_usec = -tvp->tv_usec;
1346 if (u_usec < -500000)
1347 u_usec += 1000000;
1348 v_usec = pps_offset - u_usec;
1349 if (v_usec < 0)
1350 v_usec = -v_usec;
1351 if (v_usec > (tick >> 1)) {
1352 if (pps_glitch > MAXGLITCH) {
1353 pps_glitch = 0;
1354 pps_tf[2] = u_usec;
1355 pps_tf[1] = u_usec;
1356 } else {
1357 pps_glitch++;
1358 u_usec = pps_offset;
1359 }
1360 } else
1361 pps_glitch = 0;
1362
1363 /*
1364 * A three-stage median filter is used to help deglitch the pps
1365 * time. The median sample becomes the time offset estimate; the
1366 * difference between the other two samples becomes the time
1367 * dispersion (jitter) estimate.
1368 */
1369 pps_tf[2] = pps_tf[1];
1370 pps_tf[1] = pps_tf[0];
1371 pps_tf[0] = u_usec;
1372 if (pps_tf[0] > pps_tf[1]) {
1373 if (pps_tf[1] > pps_tf[2]) {
1374 pps_offset = pps_tf[1]; /* 0 1 2 */
1375 v_usec = pps_tf[0] - pps_tf[2];
1376 } else if (pps_tf[2] > pps_tf[0]) {
1377 pps_offset = pps_tf[0]; /* 2 0 1 */
1378 v_usec = pps_tf[2] - pps_tf[1];
1379 } else {
1380 pps_offset = pps_tf[2]; /* 0 2 1 */
1381 v_usec = pps_tf[0] - pps_tf[1];
1382 }
1383 } else {
1384 if (pps_tf[1] < pps_tf[2]) {
1385 pps_offset = pps_tf[1]; /* 2 1 0 */
1386 v_usec = pps_tf[2] - pps_tf[0];
1387 } else if (pps_tf[2] < pps_tf[0]) {
1388 pps_offset = pps_tf[0]; /* 1 0 2 */
1389 v_usec = pps_tf[1] - pps_tf[2];
1390 } else {
1391 pps_offset = pps_tf[2]; /* 1 2 0 */
1392 v_usec = pps_tf[1] - pps_tf[0];
1393 }
1394 }
1395 if (v_usec > MAXTIME)
1396 pps_jitcnt++;
1397 v_usec = (v_usec << PPS_AVG) - pps_jitter;
1398 if (v_usec < 0)
1399 pps_jitter -= -v_usec >> PPS_AVG;
1400 else
1401 pps_jitter += v_usec >> PPS_AVG;
1402 if (pps_jitter > (MAXTIME >> 1))
1403 time_status |= STA_PPSJITTER;
1404
1405 /*
1406 * During the calibration interval adjust the starting time when
1407 * the tick overflows. At the end of the interval compute the
1408 * duration of the interval and the difference of the hardware
1409 * counters at the beginning and end of the interval. This code
1410 * is deliciously complicated by the fact valid differences may
1411 * exceed the value of tick when using long calibration
1412 * intervals and small ticks. Note that the counter can be
1413 * greater than tick if caught at just the wrong instant, but
1414 * the values returned and used here are correct.
1415 */
1416 bigtick = (long)tick << SHIFT_USEC;
1417 pps_usec -= pps_freq;
1418 if (pps_usec >= bigtick)
1419 pps_usec -= bigtick;
1420 if (pps_usec < 0)
1421 pps_usec += bigtick;
1422 pps_time.tv_sec++;
1423 pps_count++;
1424 if (pps_count < (1 << pps_shift))
1425 return;
1426 pps_count = 0;
1427 pps_calcnt++;
1428 u_usec = usec << SHIFT_USEC;
1429 v_usec = pps_usec - u_usec;
1430 if (v_usec >= bigtick >> 1)
1431 v_usec -= bigtick;
1432 if (v_usec < -(bigtick >> 1))
1433 v_usec += bigtick;
1434 if (v_usec < 0)
1435 v_usec = -(-v_usec >> pps_shift);
1436 else
1437 v_usec = v_usec >> pps_shift;
1438 pps_usec = u_usec;
1439 cal_sec = tvp->tv_sec;
1440 cal_usec = tvp->tv_usec;
1441 cal_sec -= pps_time.tv_sec;
1442 cal_usec -= pps_time.tv_usec;
1443 if (cal_usec < 0) {
1444 cal_usec += 1000000;
1445 cal_sec--;
1446 }
1447 pps_time = *tvp;
1448
1449 /*
1450 * Check for lost interrupts, noise, excessive jitter and
1451 * excessive frequency error. The number of timer ticks during
1452 * the interval may vary +-1 tick. Add to this a margin of one
1453 * tick for the PPS signal jitter and maximum frequency
1454 * deviation. If the limits are exceeded, the calibration
1455 * interval is reset to the minimum and we start over.
1456 */
1457 u_usec = (long)tick << 1;
1458 if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
1459 || (cal_sec == 0 && cal_usec < u_usec))
1460 || v_usec > time_tolerance || v_usec < -time_tolerance) {
1461 pps_errcnt++;
1462 pps_shift = PPS_SHIFT;
1463 pps_intcnt = 0;
1464 time_status |= STA_PPSERROR;
1465 return;
1466 }
1467
1468 /*
1469 * A three-stage median filter is used to help deglitch the pps
1470 * frequency. The median sample becomes the frequency offset
1471 * estimate; the difference between the other two samples
1472 * becomes the frequency dispersion (stability) estimate.
1473 */
1474 pps_ff[2] = pps_ff[1];
1475 pps_ff[1] = pps_ff[0];
1476 pps_ff[0] = v_usec;
1477 if (pps_ff[0] > pps_ff[1]) {
1478 if (pps_ff[1] > pps_ff[2]) {
1479 u_usec = pps_ff[1]; /* 0 1 2 */
1480 v_usec = pps_ff[0] - pps_ff[2];
1481 } else if (pps_ff[2] > pps_ff[0]) {
1482 u_usec = pps_ff[0]; /* 2 0 1 */
1483 v_usec = pps_ff[2] - pps_ff[1];
1484 } else {
1485 u_usec = pps_ff[2]; /* 0 2 1 */
1486 v_usec = pps_ff[0] - pps_ff[1];
1487 }
1488 } else {
1489 if (pps_ff[1] < pps_ff[2]) {
1490 u_usec = pps_ff[1]; /* 2 1 0 */
1491 v_usec = pps_ff[2] - pps_ff[0];
1492 } else if (pps_ff[2] < pps_ff[0]) {
1493 u_usec = pps_ff[0]; /* 1 0 2 */
1494 v_usec = pps_ff[1] - pps_ff[2];
1495 } else {
1496 u_usec = pps_ff[2]; /* 1 2 0 */
1497 v_usec = pps_ff[1] - pps_ff[0];
1498 }
1499 }
1500
1501 /*
1502 * Here the frequency dispersion (stability) is updated. If it
1503 * is less than one-fourth the maximum (MAXFREQ), the frequency
1504 * offset is updated as well, but clamped to the tolerance. It
1505 * will be processed later by the hardclock() routine.
1506 */
1507 v_usec = (v_usec >> 1) - pps_stabil;
1508 if (v_usec < 0)
1509 pps_stabil -= -v_usec >> PPS_AVG;
1510 else
1511 pps_stabil += v_usec >> PPS_AVG;
1512 if (pps_stabil > MAXFREQ >> 2) {
1513 pps_stbcnt++;
1514 time_status |= STA_PPSWANDER;
1515 return;
1516 }
1517 if (time_status & STA_PPSFREQ) {
1518 if (u_usec < 0) {
1519 pps_freq -= -u_usec >> PPS_AVG;
1520 if (pps_freq < -time_tolerance)
1521 pps_freq = -time_tolerance;
1522 u_usec = -u_usec;
1523 } else {
1524 pps_freq += u_usec >> PPS_AVG;
1525 if (pps_freq > time_tolerance)
1526 pps_freq = time_tolerance;
1527 }
1528 }
1529
1530 /*
1531 * Here the calibration interval is adjusted. If the maximum
1532 * time difference is greater than tick / 4, reduce the interval
1533 * by half. If this is not the case for four consecutive
1534 * intervals, double the interval.
1535 */
1536 if (u_usec << pps_shift > bigtick >> 2) {
1537 pps_intcnt = 0;
1538 if (pps_shift > PPS_SHIFT)
1539 pps_shift--;
1540 } else if (pps_intcnt >= 4) {
1541 pps_intcnt = 0;
1542 if (pps_shift < PPS_SHIFTMAX)
1543 pps_shift++;
1544 } else
1545 pps_intcnt++;
1546 }
1547 #endif /* PPS_SYNC */
1548 #endif /* NTP */
1549
1550 /* timecounter compat functions */
1551 void
1552 nanotime(struct timespec *ts)
1553 {
1554 struct timeval tv;
1555
1556 microtime(&tv);
1557 TIMEVAL_TO_TIMESPEC(&tv, ts);
1558 }
1559
1560 void
1561 getbinuptime(struct bintime *bt)
1562 {
1563 struct timeval tv;
1564
1565 microtime(&tv);
1566 timeval2bintime(&tv, bt);
1567 }
1568
1569 void
1570 nanouptime(struct timespec *tsp)
1571 {
1572 int s;
1573
1574 s = splclock();
1575 TIMEVAL_TO_TIMESPEC(&mono_time, tsp);
1576 splx(s);
1577 }
1578
1579 void
1580 getnanouptime(struct timespec *tsp)
1581 {
1582 int s;
1583
1584 s = splclock();
1585 TIMEVAL_TO_TIMESPEC(&mono_time, tsp);
1586 splx(s);
1587 }
1588
1589 void
1590 getmicrouptime(struct timeval *tvp)
1591 {
1592 int s;
1593
1594 s = splclock();
1595 *tvp = mono_time;
1596 splx(s);
1597 }
1598
1599 void
1600 getnanotime(struct timespec *tsp)
1601 {
1602 int s;
1603
1604 s = splclock();
1605 TIMEVAL_TO_TIMESPEC(&time, tsp);
1606 splx(s);
1607 }
1608
1609 void
1610 getmicrotime(struct timeval *tvp)
1611 {
1612 int s;
1613
1614 s = splclock();
1615 *tvp = time;
1616 splx(s);
1617 }
1618 #endif /* !__HAVE_TIMECOUNTER */
1619