1 /* $NetBSD: kern_ntptime.c,v 1.51 2009/01/11 02:45:52 christos Exp $ */
4 * Copyright (c) 2008 The NetBSD Foundation, Inc.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
17 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
20 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26 * POSSIBILITY OF SUCH DAMAGE.
30 ***********************************************************************
32 * Copyright (c) David L. Mills 1993-2001 *
34 * Permission to use, copy, modify, and distribute this software and *
35 * its documentation for any purpose and without fee is hereby *
36 * granted, provided that the above copyright notice appears in all *
37 * copies and that both the copyright notice and this permission *
38 * notice appear in supporting documentation, and that the name *
39 * University of Delaware not be used in advertising or publicity *
40 * pertaining to distribution of the software without specific, *
41 * written prior permission. The University of Delaware makes no *
42 * representations about the suitability this software for any *
43 * purpose. It is provided "as is" without express or implied *
46 **********************************************************************/
49 * Adapted from the original sources for FreeBSD and timecounters by:
50 * Poul-Henning Kamp <phk@FreeBSD.org>.
52 * The 32bit version of the "LP" macros seems a bit past its "sell by"
53 * date so I have retained only the 64bit version and included it directly
56 * Only minor changes done to interface with the timecounters over in
57 * sys/kern/kern_clock.c. Some of the comments below may be (even more)
58 * confusing and/or plain wrong in that context.
61 #include <sys/cdefs.h>
62 /* __FBSDID("$FreeBSD: src/sys/kern/kern_ntptime.c,v 1.59 2005/05/28 14:34:41 rwatson Exp $"); */
63 __KERNEL_RCSID(0, "$NetBSD: kern_ntptime.c,v 1.51 2009/01/11 02:45:52 christos Exp $");
67 #include <sys/param.h>
68 #include <sys/resourcevar.h>
69 #include <sys/systm.h>
70 #include <sys/kernel.h>
72 #include <sys/sysctl.h>
73 #include <sys/timex.h>
74 #include <sys/vnode.h>
75 #include <sys/kauth.h>
76 #include <sys/mount.h>
77 #include <sys/syscallargs.h>
80 #include <compat/sys/timex.h>
83 * Single-precision macros for 64-bit machines
86 #define L_ADD(v, u) ((v) += (u))
87 #define L_SUB(v, u) ((v) -= (u))
88 #define L_ADDHI(v, a) ((v) += (int64_t)(a) << 32)
89 #define L_NEG(v) ((v) = -(v))
90 #define L_RSHIFT(v, n) \
93 (v) = -(-(v) >> (n)); \
97 #define L_MPY(v, a) ((v) *= (a))
98 #define L_CLR(v) ((v) = 0)
99 #define L_ISNEG(v) ((v) < 0)
100 #define L_LINT(v, a) ((v) = (int64_t)(a) << 32)
101 #define L_GINT(v) ((v) < 0 ? -(-(v) >> 32) : (v) >> 32)
105 * Generic NTP kernel interface
107 * These routines constitute the Network Time Protocol (NTP) interfaces
108 * for user and daemon application programs. The ntp_gettime() routine
109 * provides the time, maximum error (synch distance) and estimated error
110 * (dispersion) to client user application programs. The ntp_adjtime()
111 * routine is used by the NTP daemon to adjust the system clock to an
112 * externally derived time. The time offset and related variables set by
113 * this routine are used by other routines in this module to adjust the
114 * phase and frequency of the clock discipline loop which controls the
117 * When the kernel time is reckoned directly in nanoseconds (NTP_NANO
118 * defined), the time at each tick interrupt is derived directly from
119 * the kernel time variable. When the kernel time is reckoned in
120 * microseconds, (NTP_NANO undefined), the time is derived from the
121 * kernel time variable together with a variable representing the
122 * leftover nanoseconds at the last tick interrupt. In either case, the
123 * current nanosecond time is reckoned from these values plus an
124 * interpolated value derived by the clock routines in another
125 * architecture-specific module. The interpolation can use either a
126 * dedicated counter or a processor cycle counter (PCC) implemented in
127 * some architectures.
129 * Note that all routines must run at priority splclock or higher.
132 * Phase/frequency-lock loop (PLL/FLL) definitions
134 * The nanosecond clock discipline uses two variable types, time
135 * variables and frequency variables. Both types are represented as 64-
136 * bit fixed-point quantities with the decimal point between two 32-bit
137 * halves. On a 32-bit machine, each half is represented as a single
138 * word and mathematical operations are done using multiple-precision
139 * arithmetic. On a 64-bit machine, ordinary computer arithmetic is
142 * A time variable is a signed 64-bit fixed-point number in ns and
143 * fraction. It represents the remaining time offset to be amortized
144 * over succeeding tick interrupts. The maximum time offset is about
145 * 0.5 s and the resolution is about 2.3e-10 ns.
147 * 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
148 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
149 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
151 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
153 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
155 * A frequency variable is a signed 64-bit fixed-point number in ns/s
156 * and fraction. It represents the ns and fraction to be added to the
157 * kernel time variable at each second. The maximum frequency offset is
158 * about +-500000 ns/s and the resolution is about 2.3e-10 ns/s.
160 * 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
161 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
162 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
163 * |s s s s s s s s s s s s s| ns/s |
164 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
166 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
169 * The following variables establish the state of the PLL/FLL and the
170 * residual time and frequency offset of the local clock.
172 #define SHIFT_PLL 4 /* PLL loop gain (shift) */
173 #define SHIFT_FLL 2 /* FLL loop gain (shift) */
175 static int time_state
= TIME_OK
; /* clock state */
176 static int time_status
= STA_UNSYNC
; /* clock status bits */
177 static long time_tai
; /* TAI offset (s) */
178 static long time_monitor
; /* last time offset scaled (ns) */
179 static long time_constant
; /* poll interval (shift) (s) */
180 static long time_precision
= 1; /* clock precision (ns) */
181 static long time_maxerror
= MAXPHASE
/ 1000; /* maximum error (us) */
182 static long time_esterror
= MAXPHASE
/ 1000; /* estimated error (us) */
183 static long time_reftime
; /* time at last adjustment (s) */
184 static l_fp time_offset
; /* time offset (ns) */
185 static l_fp time_freq
; /* frequency offset (ns/s) */
188 static l_fp time_adj
; /* tick adjust (ns/s) */
189 int64_t time_adjtime
; /* correction from adjtime(2) (usec) */
191 extern int time_adjusted
; /* ntp might have changed the system time */
196 * The following variables are used when a pulse-per-second (PPS) signal
197 * is available and connected via a modem control lead. They establish
198 * the engineering parameters of the clock discipline loop when
199 * controlled by the PPS signal.
201 #define PPS_FAVG 2 /* min freq avg interval (s) (shift) */
202 #define PPS_FAVGDEF 8 /* default freq avg int (s) (shift) */
203 #define PPS_FAVGMAX 15 /* max freq avg interval (s) (shift) */
204 #define PPS_PAVG 4 /* phase avg interval (s) (shift) */
205 #define PPS_VALID 120 /* PPS signal watchdog max (s) */
206 #define PPS_MAXWANDER 100000 /* max PPS wander (ns/s) */
207 #define PPS_POPCORN 2 /* popcorn spike threshold (shift) */
209 static struct timespec pps_tf
[3]; /* phase median filter */
210 static l_fp pps_freq
; /* scaled frequency offset (ns/s) */
211 static long pps_fcount
; /* frequency accumulator */
212 static long pps_jitter
; /* nominal jitter (ns) */
213 static long pps_stabil
; /* nominal stability (scaled ns/s) */
214 static long pps_lastsec
; /* time at last calibration (s) */
215 static int pps_valid
; /* signal watchdog counter */
216 static int pps_shift
= PPS_FAVG
; /* interval duration (s) (shift) */
217 static int pps_shiftmax
= PPS_FAVGDEF
; /* max interval duration (s) (shift) */
218 static int pps_intcnt
; /* wander counter */
221 * PPS signal quality monitors
223 static long pps_calcnt
; /* calibration intervals */
224 static long pps_jitcnt
; /* jitter limit exceeded */
225 static long pps_stbcnt
; /* stability limit exceeded */
226 static long pps_errcnt
; /* calibration errors */
227 #endif /* PPS_SYNC */
229 * End of phase/frequency-lock loop (PLL/FLL) definitions
232 static void hardupdate(long offset
);
235 * ntp_gettime() - NTP user application interface
238 ntp_gettime(struct ntptimeval
*ntv
)
241 mutex_spin_enter(&timecounter_lock
);
242 nanotime(&ntv
->time
);
243 ntv
->maxerror
= time_maxerror
;
244 ntv
->esterror
= time_esterror
;
246 ntv
->time_state
= time_state
;
247 mutex_spin_exit(&timecounter_lock
);
252 * ntp_adjtime() - NTP daemon application interface
255 sys_ntp_adjtime(struct lwp
*l
, const struct sys_ntp_adjtime_args
*uap
, register_t
*retval
)
258 syscallarg(struct timex *) tp;
263 error
= copyin((void *)SCARG(uap
, tp
), (void *)&ntv
, sizeof(ntv
));
267 if (ntv
.modes
!= 0 && (error
= kauth_authorize_system(l
->l_cred
,
268 KAUTH_SYSTEM_TIME
, KAUTH_REQ_SYSTEM_TIME_NTPADJTIME
, NULL
,
274 error
= copyout((void *)&ntv
, (void *)SCARG(uap
, tp
), sizeof(ntv
));
276 *retval
= ntp_timestatus();
282 ntp_adjtime1(struct timex
*ntv
)
288 * Update selected clock variables - only the superuser can
289 * change anything. Note that there is no error checking here on
290 * the assumption the superuser should know what it is doing.
291 * Note that either the time constant or TAI offset are loaded
292 * from the ntv.constant member, depending on the mode bits. If
293 * the STA_PLL bit in the status word is cleared, the state and
294 * status words are reset to the initial values at boot.
296 mutex_spin_enter(&timecounter_lock
);
299 /* We need to save the system time during shutdown */
301 if (modes
& MOD_MAXERROR
)
302 time_maxerror
= ntv
->maxerror
;
303 if (modes
& MOD_ESTERROR
)
304 time_esterror
= ntv
->esterror
;
305 if (modes
& MOD_STATUS
) {
306 if (time_status
& STA_PLL
&& !(ntv
->status
& STA_PLL
)) {
307 time_state
= TIME_OK
;
308 time_status
= STA_UNSYNC
;
310 pps_shift
= PPS_FAVG
;
311 #endif /* PPS_SYNC */
313 time_status
&= STA_RONLY
;
314 time_status
|= ntv
->status
& ~STA_RONLY
;
316 if (modes
& MOD_TIMECONST
) {
317 if (ntv
->constant
< 0)
319 else if (ntv
->constant
> MAXTC
)
320 time_constant
= MAXTC
;
322 time_constant
= ntv
->constant
;
324 if (modes
& MOD_TAI
) {
325 if (ntv
->constant
> 0) /* XXX zero & negative numbers ? */
326 time_tai
= ntv
->constant
;
329 if (modes
& MOD_PPSMAX
) {
330 if (ntv
->shift
< PPS_FAVG
)
331 pps_shiftmax
= PPS_FAVG
;
332 else if (ntv
->shift
> PPS_FAVGMAX
)
333 pps_shiftmax
= PPS_FAVGMAX
;
335 pps_shiftmax
= ntv
->shift
;
337 #endif /* PPS_SYNC */
338 if (modes
& MOD_NANO
)
339 time_status
|= STA_NANO
;
340 if (modes
& MOD_MICRO
)
341 time_status
&= ~STA_NANO
;
342 if (modes
& MOD_CLKB
)
343 time_status
|= STA_CLK
;
344 if (modes
& MOD_CLKA
)
345 time_status
&= ~STA_CLK
;
346 if (modes
& MOD_FREQUENCY
) {
347 freq
= (ntv
->freq
* 1000LL) >> 16;
349 L_LINT(time_freq
, MAXFREQ
);
350 else if (freq
< -MAXFREQ
)
351 L_LINT(time_freq
, -MAXFREQ
);
354 * ntv.freq is [PPM * 2^16] = [us/s * 2^16]
355 * time_freq is [ns/s * 2^32]
357 time_freq
= ntv
->freq
* 1000LL * 65536LL;
360 pps_freq
= time_freq
;
361 #endif /* PPS_SYNC */
363 if (modes
& MOD_OFFSET
) {
364 if (time_status
& STA_NANO
)
365 hardupdate(ntv
->offset
);
367 hardupdate(ntv
->offset
* 1000);
371 * Retrieve all clock variables. Note that the TAI offset is
372 * returned only by ntp_gettime();
374 if (time_status
& STA_NANO
)
375 ntv
->offset
= L_GINT(time_offset
);
377 ntv
->offset
= L_GINT(time_offset
) / 1000; /* XXX rounding ? */
378 ntv
->freq
= L_GINT((time_freq
/ 1000LL) << 16);
379 ntv
->maxerror
= time_maxerror
;
380 ntv
->esterror
= time_esterror
;
381 ntv
->status
= time_status
;
382 ntv
->constant
= time_constant
;
383 if (time_status
& STA_NANO
)
384 ntv
->precision
= time_precision
;
386 ntv
->precision
= time_precision
/ 1000;
387 ntv
->tolerance
= MAXFREQ
* SCALE_PPM
;
389 ntv
->shift
= pps_shift
;
390 ntv
->ppsfreq
= L_GINT((pps_freq
/ 1000LL) << 16);
391 if (time_status
& STA_NANO
)
392 ntv
->jitter
= pps_jitter
;
394 ntv
->jitter
= pps_jitter
/ 1000;
395 ntv
->stabil
= pps_stabil
;
396 ntv
->calcnt
= pps_calcnt
;
397 ntv
->errcnt
= pps_errcnt
;
398 ntv
->jitcnt
= pps_jitcnt
;
399 ntv
->stbcnt
= pps_stbcnt
;
400 #endif /* PPS_SYNC */
401 mutex_spin_exit(&timecounter_lock
);
406 * second_overflow() - called after ntp_tick_adjust()
408 * This routine is ordinarily called immediately following the above
409 * routine ntp_tick_adjust(). While these two routines are normally
410 * combined, they are separated here only for the purposes of
414 ntp_update_second(int64_t *adjustment
, time_t *newsec
)
417 l_fp ftemp
; /* 32/64-bit temporary */
419 KASSERT(mutex_owned(&timecounter_lock
));
424 * On rollover of the second both the nanosecond and microsecond
425 * clocks are updated and the state machine cranked as
426 * necessary. The phase adjustment to be used for the next
427 * second is calculated and the maximum error is increased by
430 time_maxerror
+= MAXFREQ
/ 1000;
433 * Leap second processing. If in leap-insert state at
434 * the end of the day, the system clock is set back one
435 * second; if in leap-delete state, the system clock is
436 * set ahead one second. The nano_time() routine or
437 * external clock driver will insure that reported time
438 * is always monotonic.
440 switch (time_state
) {
446 if (time_status
& STA_INS
)
447 time_state
= TIME_INS
;
448 else if (time_status
& STA_DEL
)
449 time_state
= TIME_DEL
;
453 * Insert second 23:59:60 following second
457 if (!(time_status
& STA_INS
))
458 time_state
= TIME_OK
;
459 else if ((*newsec
) % 86400 == 0) {
461 time_state
= TIME_OOP
;
467 * Delete second 23:59:59.
470 if (!(time_status
& STA_DEL
))
471 time_state
= TIME_OK
;
472 else if (((*newsec
) + 1) % 86400 == 0) {
475 time_state
= TIME_WAIT
;
480 * Insert second in progress.
483 time_state
= TIME_WAIT
;
487 * Wait for status bits to clear.
490 if (!(time_status
& (STA_INS
| STA_DEL
)))
491 time_state
= TIME_OK
;
495 * Compute the total time adjustment for the next second
496 * in ns. The offset is reduced by a factor depending on
497 * whether the PPS signal is operating. Note that the
498 * value is in effect scaled by the clock frequency,
499 * since the adjustment is added at each tick interrupt.
503 /* XXX even if PPS signal dies we should finish adjustment ? */
504 if (time_status
& STA_PPSTIME
&& time_status
&
506 L_RSHIFT(ftemp
, pps_shift
);
508 L_RSHIFT(ftemp
, SHIFT_PLL
+ time_constant
);
510 L_RSHIFT(ftemp
, SHIFT_PLL
+ time_constant
);
511 #endif /* PPS_SYNC */
513 L_SUB(time_offset
, ftemp
);
514 L_ADD(time_adj
, time_freq
);
520 time_status
&= ~STA_PPSSIGNAL
;
521 #endif /* PPS_SYNC */
527 * Apply any correction from adjtime(2). If more than one second
528 * off we slew at a rate of 5ms/s (5000 PPM) else 500us/s (500PPM)
529 * until the last second is slewed the final < 500 usecs.
531 if (time_adjtime
!= 0) {
532 if (time_adjtime
> 1000000)
534 else if (time_adjtime
< -1000000)
536 else if (time_adjtime
> 500)
538 else if (time_adjtime
< -500)
541 tickrate
= time_adjtime
;
542 time_adjtime
-= tickrate
;
543 L_LINT(ftemp
, tickrate
* 1000);
544 L_ADD(time_adj
, ftemp
);
546 *adjustment
= time_adj
;
550 * ntp_init() - initialize variables and structures
552 * This routine must be called after the kernel variables hz and tick
553 * are set or changed and before the next tick interrupt. In this
554 * particular implementation, these values are assumed set elsewhere in
555 * the kernel. The design allows the clock frequency and tick interval
556 * to be changed while the system is running. So, this routine should
557 * probably be integrated with the code that does that.
564 * The following variables are initialized only at startup. Only
565 * those structures not cleared by the compiler need to be
566 * initialized, and these only in the simulator. In the actual
567 * kernel, any nonzero values here will quickly evaporate.
574 pps_tf
[0].tv_sec
= pps_tf
[0].tv_nsec
= 0;
575 pps_tf
[1].tv_sec
= pps_tf
[1].tv_nsec
= 0;
576 pps_tf
[2].tv_sec
= pps_tf
[2].tv_nsec
= 0;
579 #endif /* PPS_SYNC */
585 * hardupdate() - local clock update
587 * This routine is called by ntp_adjtime() to update the local clock
588 * phase and frequency. The implementation is of an adaptive-parameter,
589 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
590 * time and frequency offset estimates for each call. If the kernel PPS
591 * discipline code is configured (PPS_SYNC), the PPS signal itself
592 * determines the new time offset, instead of the calling argument.
593 * Presumably, calls to ntp_adjtime() occur only when the caller
594 * believes the local clock is valid within some bound (+-128 ms with
595 * NTP). If the caller's time is far different than the PPS time, an
596 * argument will ensue, and it's not clear who will lose.
598 * For uncompensated quartz crystal oscillators and nominal update
599 * intervals less than 256 s, operation should be in phase-lock mode,
600 * where the loop is disciplined to phase. For update intervals greater
601 * than 1024 s, operation should be in frequency-lock mode, where the
602 * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
603 * is selected by the STA_MODE status bit.
605 * Note: splclock() is in effect.
608 hardupdate(long offset
)
613 KASSERT(mutex_owned(&timecounter_lock
));
616 * Select how the phase is to be controlled and from which
617 * source. If the PPS signal is present and enabled to
618 * discipline the time, the PPS offset is used; otherwise, the
619 * argument offset is used.
621 if (!(time_status
& STA_PLL
))
623 if (!(time_status
& STA_PPSTIME
&& time_status
&
625 if (offset
> MAXPHASE
)
626 time_monitor
= MAXPHASE
;
627 else if (offset
< -MAXPHASE
)
628 time_monitor
= -MAXPHASE
;
630 time_monitor
= offset
;
631 L_LINT(time_offset
, time_monitor
);
635 * Select how the frequency is to be controlled and in which
636 * mode (PLL or FLL). If the PPS signal is present and enabled
637 * to discipline the frequency, the PPS frequency is used;
638 * otherwise, the argument offset is used to compute it.
640 if (time_status
& STA_PPSFREQ
&& time_status
& STA_PPSSIGNAL
) {
641 time_reftime
= time_second
;
644 if (time_status
& STA_FREQHOLD
|| time_reftime
== 0)
645 time_reftime
= time_second
;
646 mtemp
= time_second
- time_reftime
;
647 L_LINT(ftemp
, time_monitor
);
648 L_RSHIFT(ftemp
, (SHIFT_PLL
+ 2 + time_constant
) << 1);
650 L_ADD(time_freq
, ftemp
);
651 time_status
&= ~STA_MODE
;
652 if (mtemp
>= MINSEC
&& (time_status
& STA_FLL
|| mtemp
>
654 L_LINT(ftemp
, (time_monitor
<< 4) / mtemp
);
655 L_RSHIFT(ftemp
, SHIFT_FLL
+ 4);
656 L_ADD(time_freq
, ftemp
);
657 time_status
|= STA_MODE
;
659 time_reftime
= time_second
;
660 if (L_GINT(time_freq
) > MAXFREQ
)
661 L_LINT(time_freq
, MAXFREQ
);
662 else if (L_GINT(time_freq
) < -MAXFREQ
)
663 L_LINT(time_freq
, -MAXFREQ
);
668 * hardpps() - discipline CPU clock oscillator to external PPS signal
670 * This routine is called at each PPS interrupt in order to discipline
671 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
672 * and leaves it in a handy spot for the hardclock() routine. It
673 * integrates successive PPS phase differences and calculates the
674 * frequency offset. This is used in hardclock() to discipline the CPU
675 * clock oscillator so that intrinsic frequency error is cancelled out.
676 * The code requires the caller to capture the time and hardware counter
677 * value at the on-time PPS signal transition.
679 * Note that, on some Unix systems, this routine runs at an interrupt
680 * priority level higher than the timer interrupt routine hardclock().
681 * Therefore, the variables used are distinct from the hardclock()
682 * variables, except for certain exceptions: The PPS frequency pps_freq
683 * and phase pps_offset variables are determined by this routine and
684 * updated atomically. The time_tolerance variable can be considered a
685 * constant, since it is infrequently changed, and then only when the
686 * PPS signal is disabled. The watchdog counter pps_valid is updated
687 * once per second by hardclock() and is atomically cleared in this
691 hardpps(struct timespec
*tsp
, /* time at PPS */
692 long nsec
/* hardware counter at PPS */)
694 long u_sec
, u_nsec
, v_nsec
; /* temps */
697 KASSERT(mutex_owned(&timecounter_lock
));
700 * The signal is first processed by a range gate and frequency
701 * discriminator. The range gate rejects noise spikes outside
702 * the range +-500 us. The frequency discriminator rejects input
703 * signals with apparent frequency outside the range 1 +-500
704 * PPM. If two hits occur in the same second, we ignore the
705 * later hit; if not and a hit occurs outside the range gate,
706 * keep the later hit for later comparison, but do not process
709 time_status
|= STA_PPSSIGNAL
| STA_PPSJITTER
;
710 time_status
&= ~(STA_PPSWANDER
| STA_PPSERROR
);
711 pps_valid
= PPS_VALID
;
713 u_nsec
= tsp
->tv_nsec
;
714 if (u_nsec
>= (NANOSECOND
>> 1)) {
715 u_nsec
-= NANOSECOND
;
718 v_nsec
= u_nsec
- pps_tf
[0].tv_nsec
;
719 if (u_sec
== pps_tf
[0].tv_sec
&& v_nsec
< NANOSECOND
-
722 pps_tf
[2] = pps_tf
[1];
723 pps_tf
[1] = pps_tf
[0];
724 pps_tf
[0].tv_sec
= u_sec
;
725 pps_tf
[0].tv_nsec
= u_nsec
;
728 * Compute the difference between the current and previous
729 * counter values. If the difference exceeds 0.5 s, assume it
730 * has wrapped around, so correct 1.0 s. If the result exceeds
731 * the tick interval, the sample point has crossed a tick
732 * boundary during the last second, so correct the tick. Very
736 if (u_nsec
> (NANOSECOND
>> 1))
737 u_nsec
-= NANOSECOND
;
738 else if (u_nsec
< -(NANOSECOND
>> 1))
739 u_nsec
+= NANOSECOND
;
740 pps_fcount
+= u_nsec
;
741 if (v_nsec
> MAXFREQ
|| v_nsec
< -MAXFREQ
)
743 time_status
&= ~STA_PPSJITTER
;
746 * A three-stage median filter is used to help denoise the PPS
747 * time. The median sample becomes the time offset estimate; the
748 * difference between the other two samples becomes the time
749 * dispersion (jitter) estimate.
751 if (pps_tf
[0].tv_nsec
> pps_tf
[1].tv_nsec
) {
752 if (pps_tf
[1].tv_nsec
> pps_tf
[2].tv_nsec
) {
753 v_nsec
= pps_tf
[1].tv_nsec
; /* 0 1 2 */
754 u_nsec
= pps_tf
[0].tv_nsec
- pps_tf
[2].tv_nsec
;
755 } else if (pps_tf
[2].tv_nsec
> pps_tf
[0].tv_nsec
) {
756 v_nsec
= pps_tf
[0].tv_nsec
; /* 2 0 1 */
757 u_nsec
= pps_tf
[2].tv_nsec
- pps_tf
[1].tv_nsec
;
759 v_nsec
= pps_tf
[2].tv_nsec
; /* 0 2 1 */
760 u_nsec
= pps_tf
[0].tv_nsec
- pps_tf
[1].tv_nsec
;
763 if (pps_tf
[1].tv_nsec
< pps_tf
[2].tv_nsec
) {
764 v_nsec
= pps_tf
[1].tv_nsec
; /* 2 1 0 */
765 u_nsec
= pps_tf
[2].tv_nsec
- pps_tf
[0].tv_nsec
;
766 } else if (pps_tf
[2].tv_nsec
< pps_tf
[0].tv_nsec
) {
767 v_nsec
= pps_tf
[0].tv_nsec
; /* 1 0 2 */
768 u_nsec
= pps_tf
[1].tv_nsec
- pps_tf
[2].tv_nsec
;
770 v_nsec
= pps_tf
[2].tv_nsec
; /* 1 2 0 */
771 u_nsec
= pps_tf
[1].tv_nsec
- pps_tf
[0].tv_nsec
;
776 * Nominal jitter is due to PPS signal noise and interrupt
777 * latency. If it exceeds the popcorn threshold, the sample is
778 * discarded. otherwise, if so enabled, the time offset is
779 * updated. We can tolerate a modest loss of data here without
780 * much degrading time accuracy.
782 if (u_nsec
> (pps_jitter
<< PPS_POPCORN
)) {
783 time_status
|= STA_PPSJITTER
;
785 } else if (time_status
& STA_PPSTIME
) {
786 time_monitor
= -v_nsec
;
787 L_LINT(time_offset
, time_monitor
);
789 pps_jitter
+= (u_nsec
- pps_jitter
) >> PPS_FAVG
;
790 u_sec
= pps_tf
[0].tv_sec
- pps_lastsec
;
791 if (u_sec
< (1 << pps_shift
))
795 * At the end of the calibration interval the difference between
796 * the first and last counter values becomes the scaled
797 * frequency. It will later be divided by the length of the
798 * interval to determine the frequency update. If the frequency
799 * exceeds a sanity threshold, or if the actual calibration
800 * interval is not equal to the expected length, the data are
801 * discarded. We can tolerate a modest loss of data here without
802 * much degrading frequency accuracy.
805 v_nsec
= -pps_fcount
;
806 pps_lastsec
= pps_tf
[0].tv_sec
;
808 u_nsec
= MAXFREQ
<< pps_shift
;
809 if (v_nsec
> u_nsec
|| v_nsec
< -u_nsec
|| u_sec
!= (1 <<
811 time_status
|= STA_PPSERROR
;
817 * Here the raw frequency offset and wander (stability) is
818 * calculated. If the wander is less than the wander threshold
819 * for four consecutive averaging intervals, the interval is
820 * doubled; if it is greater than the threshold for four
821 * consecutive intervals, the interval is halved. The scaled
822 * frequency offset is converted to frequency offset. The
823 * stability metric is calculated as the average of recent
824 * frequency changes, but is used only for performance
827 L_LINT(ftemp
, v_nsec
);
828 L_RSHIFT(ftemp
, pps_shift
);
829 L_SUB(ftemp
, pps_freq
);
830 u_nsec
= L_GINT(ftemp
);
831 if (u_nsec
> PPS_MAXWANDER
) {
832 L_LINT(ftemp
, PPS_MAXWANDER
);
834 time_status
|= STA_PPSWANDER
;
836 } else if (u_nsec
< -PPS_MAXWANDER
) {
837 L_LINT(ftemp
, -PPS_MAXWANDER
);
839 time_status
|= STA_PPSWANDER
;
844 if (pps_intcnt
>= 4) {
846 if (pps_shift
< pps_shiftmax
) {
850 } else if (pps_intcnt
<= -4 || pps_shift
> pps_shiftmax
) {
852 if (pps_shift
> PPS_FAVG
) {
859 pps_stabil
+= (u_nsec
* SCALE_PPM
- pps_stabil
) >> PPS_FAVG
;
862 * The PPS frequency is recalculated and clamped to the maximum
863 * MAXFREQ. If enabled, the system clock frequency is updated as
866 L_ADD(pps_freq
, ftemp
);
867 u_nsec
= L_GINT(pps_freq
);
868 if (u_nsec
> MAXFREQ
)
869 L_LINT(pps_freq
, MAXFREQ
);
870 else if (u_nsec
< -MAXFREQ
)
871 L_LINT(pps_freq
, -MAXFREQ
);
872 if (time_status
& STA_PPSFREQ
)
873 time_freq
= pps_freq
;
875 #endif /* PPS_SYNC */
885 * Status word error decode. If any of these conditions
886 * occur, an error is returned, instead of the status
887 * word. Most applications will care only about the fact
888 * the system clock may not be trusted, not about the
891 * Hardware or software error
893 mutex_spin_enter(&timecounter_lock
);
894 if ((time_status
& (STA_UNSYNC
| STA_CLOCKERR
)) ||
897 * PPS signal lost when either time or frequency
898 * synchronization requested
900 (time_status
& (STA_PPSFREQ
| STA_PPSTIME
) &&
901 !(time_status
& STA_PPSSIGNAL
)) ||
904 * PPS jitter exceeded when time synchronization
907 (time_status
& STA_PPSTIME
&&
908 time_status
& STA_PPSJITTER
) ||
911 * PPS wander exceeded or calibration error when
912 * frequency synchronization requested
914 (time_status
& STA_PPSFREQ
&&
915 time_status
& (STA_PPSWANDER
| STA_PPSERROR
)))
919 mutex_spin_exit(&timecounter_lock
);
926 * ntp_gettime() - NTP user application interface
929 sys___ntp_gettime50(struct lwp
*l
, const struct sys___ntp_gettime50_args
*uap
, register_t
*retval
)
932 syscallarg(struct ntptimeval *) ntvp;
934 struct ntptimeval ntv
;
937 if (SCARG(uap
, ntvp
)) {
940 error
= copyout((void *)&ntv
, (void *)SCARG(uap
, ntvp
),
944 *retval
= ntp_timestatus();
950 * return information about kernel precision timekeeping
953 sysctl_kern_ntptime(SYSCTLFN_ARGS
)
955 struct sysctlnode node
;
956 struct ntptimeval ntv
;
961 node
.sysctl_data
= &ntv
;
962 node
.sysctl_size
= sizeof(ntv
);
963 return (sysctl_lookup(SYSCTLFN_CALL(&node
)));
966 SYSCTL_SETUP(sysctl_kern_ntptime_setup
, "sysctl kern.ntptime node setup")
969 sysctl_createv(clog
, 0, NULL
, NULL
,
971 CTLTYPE_NODE
, "kern", NULL
,
975 sysctl_createv(clog
, 0, NULL
, NULL
,
977 CTLTYPE_STRUCT
, "ntptime",
978 SYSCTL_DESCR("Kernel clock values for NTP"),
979 sysctl_kern_ntptime
, 0, NULL
,
980 sizeof(struct ntptimeval
),
981 CTL_KERN
, KERN_NTPTIME
, CTL_EOL
);