Initial import from FreeBSD RELENG_4:
[dragonfly.git] / sys / kern / kern_ntptime.c
1 /***********************************************************************
2  *                                                                     *
3  * Copyright (c) David L. Mills 1993-2001                              *
4  *                                                                     *
5  * Permission to use, copy, modify, and distribute this software and   *
6  * its documentation for any purpose and without fee is hereby         *
7  * granted, provided that the above copyright notice appears in all    *
8  * copies and that both the copyright notice and this permission       *
9  * notice appear in supporting documentation, and that the name        *
10  * University of Delaware not be used in advertising or publicity      *
11  * pertaining to distribution of the software without specific,        *
12  * written prior permission. The University of Delaware makes no       *
13  * representations about the suitability this software for any         *
14  * purpose. It is provided "as is" without express or implied          *
15  * warranty.                                                           *
16  *                                                                     *
17  **********************************************************************/
18
19 /*
20  * Adapted from the original sources for FreeBSD and timecounters by:
21  * Poul-Henning Kamp <phk@FreeBSD.org>.
22  *
23  * The 32bit version of the "LP" macros seems a bit past its "sell by" 
24  * date so I have retained only the 64bit version and included it directly
25  * in this file.
26  *
27  * Only minor changes done to interface with the timecounters over in
28  * sys/kern/kern_clock.c.   Some of the comments below may be (even more)
29  * confusing and/or plain wrong in that context.
30  *
31  * $FreeBSD: src/sys/kern/kern_ntptime.c,v 1.32.2.2 2001/04/22 11:19:46 jhay Exp $
32  */
33
34 #include "opt_ntp.h"
35
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/sysproto.h>
39 #include <sys/kernel.h>
40 #include <sys/proc.h>
41 #include <sys/time.h>
42 #include <sys/timex.h>
43 #include <sys/timepps.h>
44 #include <sys/sysctl.h>
45
46 /*
47  * Single-precision macros for 64-bit machines
48  */
49 typedef long long l_fp;
50 #define L_ADD(v, u)     ((v) += (u))
51 #define L_SUB(v, u)     ((v) -= (u))
52 #define L_ADDHI(v, a)   ((v) += (long long)(a) << 32)
53 #define L_NEG(v)        ((v) = -(v))
54 #define L_RSHIFT(v, n) \
55         do { \
56                 if ((v) < 0) \
57                         (v) = -(-(v) >> (n)); \
58                 else \
59                         (v) = (v) >> (n); \
60         } while (0)
61 #define L_MPY(v, a)     ((v) *= (a))
62 #define L_CLR(v)        ((v) = 0)
63 #define L_ISNEG(v)      ((v) < 0)
64 #define L_LINT(v, a)    ((v) = (long long)(a) << 32)
65 #define L_GINT(v)       ((v) < 0 ? -(-(v) >> 32) : (v) >> 32)
66
67 /*
68  * Generic NTP kernel interface
69  *
70  * These routines constitute the Network Time Protocol (NTP) interfaces
71  * for user and daemon application programs. The ntp_gettime() routine
72  * provides the time, maximum error (synch distance) and estimated error
73  * (dispersion) to client user application programs. The ntp_adjtime()
74  * routine is used by the NTP daemon to adjust the system clock to an
75  * externally derived time. The time offset and related variables set by
76  * this routine are used by other routines in this module to adjust the
77  * phase and frequency of the clock discipline loop which controls the
78  * system clock.
79  *
80  * When the kernel time is reckoned directly in nanoseconds (NTP_NANO
81  * defined), the time at each tick interrupt is derived directly from
82  * the kernel time variable. When the kernel time is reckoned in
83  * microseconds, (NTP_NANO undefined), the time is derived from the
84  * kernel time variable together with a variable representing the
85  * leftover nanoseconds at the last tick interrupt. In either case, the
86  * current nanosecond time is reckoned from these values plus an
87  * interpolated value derived by the clock routines in another
88  * architecture-specific module. The interpolation can use either a
89  * dedicated counter or a processor cycle counter (PCC) implemented in
90  * some architectures.
91  *
92  * Note that all routines must run at priority splclock or higher.
93  */
94 /*
95  * Phase/frequency-lock loop (PLL/FLL) definitions
96  *
97  * The nanosecond clock discipline uses two variable types, time
98  * variables and frequency variables. Both types are represented as 64-
99  * bit fixed-point quantities with the decimal point between two 32-bit
100  * halves. On a 32-bit machine, each half is represented as a single
101  * word and mathematical operations are done using multiple-precision
102  * arithmetic. On a 64-bit machine, ordinary computer arithmetic is
103  * used.
104  *
105  * A time variable is a signed 64-bit fixed-point number in ns and
106  * fraction. It represents the remaining time offset to be amortized
107  * over succeeding tick interrupts. The maximum time offset is about
108  * 0.5 s and the resolution is about 2.3e-10 ns.
109  *
110  *                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
111  *  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
112  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
113  * |s s s|                       ns                                |
114  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115  * |                        fraction                               |
116  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
117  *
118  * A frequency variable is a signed 64-bit fixed-point number in ns/s
119  * and fraction. It represents the ns and fraction to be added to the
120  * kernel time variable at each second. The maximum frequency offset is
121  * about +-500000 ns/s and the resolution is about 2.3e-10 ns/s.
122  *
123  *                      1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
124  *  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
125  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
126  * |s s s s s s s s s s s s s|            ns/s                     |
127  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
128  * |                        fraction                               |
129  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
130  */
131 /*
132  * The following variables establish the state of the PLL/FLL and the
133  * residual time and frequency offset of the local clock.
134  */
135 #define SHIFT_PLL       4               /* PLL loop gain (shift) */
136 #define SHIFT_FLL       2               /* FLL loop gain (shift) */
137
138 static int time_state = TIME_OK;        /* clock state */
139 static int time_status = STA_UNSYNC;    /* clock status bits */
140 static long time_tai;                   /* TAI offset (s) */
141 static long time_monitor;               /* last time offset scaled (ns) */
142 static long time_constant;              /* poll interval (shift) (s) */
143 static long time_precision = 1;         /* clock precision (ns) */
144 static long time_maxerror = MAXPHASE / 1000; /* maximum error (us) */
145 static long time_esterror = MAXPHASE / 1000; /* estimated error (us) */
146 static long time_reftime;               /* time at last adjustment (s) */
147 static long time_tick;                  /* nanoseconds per tick (ns) */
148 static l_fp time_offset;                /* time offset (ns) */
149 static l_fp time_freq;                  /* frequency offset (ns/s) */
150 static l_fp time_adj;                   /* tick adjust (ns/s) */
151
152 #ifdef PPS_SYNC
153 /*
154  * The following variables are used when a pulse-per-second (PPS) signal
155  * is available and connected via a modem control lead. They establish
156  * the engineering parameters of the clock discipline loop when
157  * controlled by the PPS signal.
158  */
159 #define PPS_FAVG        2               /* min freq avg interval (s) (shift) */
160 #define PPS_FAVGDEF     8               /* default freq avg int (s) (shift) */
161 #define PPS_FAVGMAX     15              /* max freq avg interval (s) (shift) */
162 #define PPS_PAVG        4               /* phase avg interval (s) (shift) */
163 #define PPS_VALID       120             /* PPS signal watchdog max (s) */
164 #define PPS_MAXWANDER   100000          /* max PPS wander (ns/s) */
165 #define PPS_POPCORN     2               /* popcorn spike threshold (shift) */
166
167 static struct timespec pps_tf[3];       /* phase median filter */
168 static l_fp pps_freq;                   /* scaled frequency offset (ns/s) */
169 static long pps_fcount;                 /* frequency accumulator */
170 static long pps_jitter;                 /* nominal jitter (ns) */
171 static long pps_stabil;                 /* nominal stability (scaled ns/s) */
172 static long pps_lastsec;                /* time at last calibration (s) */
173 static int pps_valid;                   /* signal watchdog counter */
174 static int pps_shift = PPS_FAVG;        /* interval duration (s) (shift) */
175 static int pps_shiftmax = PPS_FAVGDEF;  /* max interval duration (s) (shift) */
176 static int pps_intcnt;                  /* wander counter */
177
178 /*
179  * PPS signal quality monitors
180  */
181 static long pps_calcnt;                 /* calibration intervals */
182 static long pps_jitcnt;                 /* jitter limit exceeded */
183 static long pps_stbcnt;                 /* stability limit exceeded */
184 static long pps_errcnt;                 /* calibration errors */
185 #endif /* PPS_SYNC */
186 /*
187  * End of phase/frequency-lock loop (PLL/FLL) definitions
188  */
189
190 static void ntp_init(void);
191 static void hardupdate(long offset);
192
193 /*
194  * ntp_gettime() - NTP user application interface
195  *
196  * See the timex.h header file for synopsis and API description. Note
197  * that the TAI offset is returned in the ntvtimeval.tai structure
198  * member.
199  */
200 static int
201 ntp_sysctl(SYSCTL_HANDLER_ARGS)
202 {
203         struct ntptimeval ntv;  /* temporary structure */
204         struct timespec atv;    /* nanosecond time */
205
206         nanotime(&atv);
207         ntv.time.tv_sec = atv.tv_sec;
208         ntv.time.tv_nsec = atv.tv_nsec;
209         ntv.maxerror = time_maxerror;
210         ntv.esterror = time_esterror;
211         ntv.tai = time_tai;
212         ntv.time_state = time_state;
213
214         /*
215          * Status word error decode. If any of these conditions occur,
216          * an error is returned, instead of the status word. Most
217          * applications will care only about the fact the system clock
218          * may not be trusted, not about the details.
219          *
220          * Hardware or software error
221          */
222         if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
223
224         /*
225          * PPS signal lost when either time or frequency synchronization
226          * requested
227          */
228             (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
229             !(time_status & STA_PPSSIGNAL)) ||
230
231         /*
232          * PPS jitter exceeded when time synchronization requested
233          */
234             (time_status & STA_PPSTIME &&
235             time_status & STA_PPSJITTER) ||
236
237         /*
238          * PPS wander exceeded or calibration error when frequency
239          * synchronization requested
240          */
241             (time_status & STA_PPSFREQ &&
242             time_status & (STA_PPSWANDER | STA_PPSERROR)))
243                 ntv.time_state = TIME_ERROR;
244         return (sysctl_handle_opaque(oidp, &ntv, sizeof ntv, req));
245 }
246
247 SYSCTL_NODE(_kern, OID_AUTO, ntp_pll, CTLFLAG_RW, 0, "");
248 SYSCTL_PROC(_kern_ntp_pll, OID_AUTO, gettime, CTLTYPE_OPAQUE|CTLFLAG_RD,
249         0, sizeof(struct ntptimeval) , ntp_sysctl, "S,ntptimeval", "");
250
251 #ifdef PPS_SYNC
252 SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shiftmax, CTLFLAG_RW, &pps_shiftmax, 0, "");
253 SYSCTL_INT(_kern_ntp_pll, OID_AUTO, pps_shift, CTLFLAG_RW, &pps_shift, 0, "");
254 SYSCTL_INT(_kern_ntp_pll, OID_AUTO, time_monitor, CTLFLAG_RD, &time_monitor, 0, "");
255
256 SYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, pps_freq, CTLFLAG_RD, &pps_freq, sizeof(pps_freq), "I", "");
257 SYSCTL_OPAQUE(_kern_ntp_pll, OID_AUTO, time_freq, CTLFLAG_RD, &time_freq, sizeof(time_freq), "I", "");
258 #endif
259 /*
260  * ntp_adjtime() - NTP daemon application interface
261  *
262  * See the timex.h header file for synopsis and API description. Note
263  * that the timex.constant structure member has a dual purpose to set
264  * the time constant and to set the TAI offset.
265  */
266 #ifndef _SYS_SYSPROTO_H_
267 struct ntp_adjtime_args {
268         struct timex *tp;
269 };
270 #endif
271
272 int
273 ntp_adjtime(struct proc *p, struct ntp_adjtime_args *uap)
274 {
275         struct timex ntv;       /* temporary structure */
276         long freq;              /* frequency ns/s) */
277         int modes;              /* mode bits from structure */
278         int s;                  /* caller priority */
279         int error;
280
281         error = copyin((caddr_t)uap->tp, (caddr_t)&ntv, sizeof(ntv));
282         if (error)
283                 return(error);
284
285         /*
286          * Update selected clock variables - only the superuser can
287          * change anything. Note that there is no error checking here on
288          * the assumption the superuser should know what it is doing.
289          * Note that either the time constant or TAI offset are loaded
290          * from the ntv.constant member, depending on the mode bits. If
291          * the STA_PLL bit in the status word is cleared, the state and
292          * status words are reset to the initial values at boot.
293          */
294         modes = ntv.modes;
295         if (modes)
296                 error = suser(p);
297         if (error)
298                 return (error);
299         s = splclock();
300         if (modes & MOD_MAXERROR)
301                 time_maxerror = ntv.maxerror;
302         if (modes & MOD_ESTERROR)
303                 time_esterror = ntv.esterror;
304         if (modes & MOD_STATUS) {
305                 if (time_status & STA_PLL && !(ntv.status & STA_PLL)) {
306                         time_state = TIME_OK;
307                         time_status = STA_UNSYNC;
308 #ifdef PPS_SYNC
309                         pps_shift = PPS_FAVG;
310 #endif /* PPS_SYNC */
311                 }
312                 time_status &= STA_RONLY;
313                 time_status |= ntv.status & ~STA_RONLY;
314         }
315         if (modes & MOD_TIMECONST) {
316                 if (ntv.constant < 0)
317                         time_constant = 0;
318                 else if (ntv.constant > MAXTC)
319                         time_constant = MAXTC;
320                 else
321                         time_constant = ntv.constant;
322         }
323         if (modes & MOD_TAI) {
324                 if (ntv.constant > 0) /* XXX zero & negative numbers ? */
325                         time_tai = ntv.constant;
326         }
327 #ifdef PPS_SYNC
328         if (modes & MOD_PPSMAX) {
329                 if (ntv.shift < PPS_FAVG)
330                         pps_shiftmax = PPS_FAVG;
331                 else if (ntv.shift > PPS_FAVGMAX)
332                         pps_shiftmax = PPS_FAVGMAX;
333                 else
334                         pps_shiftmax = ntv.shift;
335         }
336 #endif /* PPS_SYNC */
337         if (modes & MOD_NANO)
338                 time_status |= STA_NANO;
339         if (modes & MOD_MICRO)
340                 time_status &= ~STA_NANO;
341         if (modes & MOD_CLKB)
342                 time_status |= STA_CLK;
343         if (modes & MOD_CLKA)
344                 time_status &= ~STA_CLK;
345         if (modes & MOD_OFFSET) {
346                 if (time_status & STA_NANO)
347                         hardupdate(ntv.offset);
348                 else
349                         hardupdate(ntv.offset * 1000);
350         }
351         if (modes & MOD_FREQUENCY) {
352                 freq = (ntv.freq * 1000LL) >> 16;
353                 if (freq > MAXFREQ)
354                         L_LINT(time_freq, MAXFREQ);
355                 else if (freq < -MAXFREQ)
356                         L_LINT(time_freq, -MAXFREQ);
357                 else
358                         L_LINT(time_freq, freq);
359 #ifdef PPS_SYNC
360                 pps_freq = time_freq;
361 #endif /* PPS_SYNC */
362         }
363
364         /*
365          * Retrieve all clock variables. Note that the TAI offset is
366          * returned only by ntp_gettime();
367          */
368         if (time_status & STA_NANO)
369                 ntv.offset = time_monitor;
370         else
371                 ntv.offset = time_monitor / 1000; /* XXX rounding ? */
372         ntv.freq = L_GINT((time_freq / 1000LL) << 16);
373         ntv.maxerror = time_maxerror;
374         ntv.esterror = time_esterror;
375         ntv.status = time_status;
376         ntv.constant = time_constant;
377         if (time_status & STA_NANO)
378                 ntv.precision = time_precision;
379         else
380                 ntv.precision = time_precision / 1000;
381         ntv.tolerance = MAXFREQ * SCALE_PPM;
382 #ifdef PPS_SYNC
383         ntv.shift = pps_shift;
384         ntv.ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
385         if (time_status & STA_NANO)
386                 ntv.jitter = pps_jitter;
387         else
388                 ntv.jitter = pps_jitter / 1000;
389         ntv.stabil = pps_stabil;
390         ntv.calcnt = pps_calcnt;
391         ntv.errcnt = pps_errcnt;
392         ntv.jitcnt = pps_jitcnt;
393         ntv.stbcnt = pps_stbcnt;
394 #endif /* PPS_SYNC */
395         splx(s);
396
397         error = copyout((caddr_t)&ntv, (caddr_t)uap->tp, sizeof(ntv));
398         if (error)
399                 return (error);
400
401         /*
402          * Status word error decode. See comments in
403          * ntp_gettime() routine.
404          */
405         if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
406             (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
407             !(time_status & STA_PPSSIGNAL)) ||
408             (time_status & STA_PPSTIME &&
409             time_status & STA_PPSJITTER) ||
410             (time_status & STA_PPSFREQ &&
411             time_status & (STA_PPSWANDER | STA_PPSERROR)))
412                 p->p_retval[0] = TIME_ERROR;
413         else
414                 p->p_retval[0] = time_state;
415         return (error);
416 }
417
418 /*
419  * second_overflow() - called after ntp_tick_adjust()
420  *
421  * This routine is ordinarily called immediately following the above
422  * routine ntp_tick_adjust(). While these two routines are normally
423  * combined, they are separated here only for the purposes of
424  * simulation.
425  */
426 void
427 ntp_update_second(struct timecounter *tcp)
428 {
429         u_int32_t *newsec;
430         l_fp ftemp;             /* 32/64-bit temporary */
431
432         newsec = &tcp->tc_offset_sec;
433         /*
434          * On rollover of the second both the nanosecond and microsecond
435          * clocks are updated and the state machine cranked as
436          * necessary. The phase adjustment to be used for the next
437          * second is calculated and the maximum error is increased by
438          * the tolerance.
439          */
440         time_maxerror += MAXFREQ / 1000;
441
442         /*
443          * Leap second processing. If in leap-insert state at
444          * the end of the day, the system clock is set back one
445          * second; if in leap-delete state, the system clock is
446          * set ahead one second. The nano_time() routine or
447          * external clock driver will insure that reported time
448          * is always monotonic.
449          */
450         switch (time_state) {
451
452                 /*
453                  * No warning.
454                  */
455                 case TIME_OK:
456                 if (time_status & STA_INS)
457                         time_state = TIME_INS;
458                 else if (time_status & STA_DEL)
459                         time_state = TIME_DEL;
460                 break;
461
462                 /*
463                  * Insert second 23:59:60 following second
464                  * 23:59:59.
465                  */
466                 case TIME_INS:
467                 if (!(time_status & STA_INS))
468                         time_state = TIME_OK;
469                 else if ((*newsec) % 86400 == 0) {
470                         (*newsec)--;
471                         time_state = TIME_OOP;
472                 }
473                 break;
474
475                 /*
476                  * Delete second 23:59:59.
477                  */
478                 case TIME_DEL:
479                 if (!(time_status & STA_DEL))
480                         time_state = TIME_OK;
481                 else if (((*newsec) + 1) % 86400 == 0) {
482                         (*newsec)++;
483                         time_tai--;
484                         time_state = TIME_WAIT;
485                 }
486                 break;
487
488                 /*
489                  * Insert second in progress.
490                  */
491                 case TIME_OOP:
492                         time_tai++;
493                         time_state = TIME_WAIT;
494                 break;
495
496                 /*
497                  * Wait for status bits to clear.
498                  */
499                 case TIME_WAIT:
500                 if (!(time_status & (STA_INS | STA_DEL)))
501                         time_state = TIME_OK;
502         }
503
504         /*
505          * Compute the total time adjustment for the next second
506          * in ns. The offset is reduced by a factor depending on
507          * whether the PPS signal is operating. Note that the
508          * value is in effect scaled by the clock frequency,
509          * since the adjustment is added at each tick interrupt.
510          */
511         ftemp = time_offset;
512 #ifdef PPS_SYNC
513         /* XXX even if PPS signal dies we should finish adjustment ? */
514         if (time_status & STA_PPSTIME && time_status &
515             STA_PPSSIGNAL)
516                 L_RSHIFT(ftemp, pps_shift);
517         else
518                 L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
519 #else
520                 L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
521 #endif /* PPS_SYNC */
522         time_adj = ftemp;
523         L_SUB(time_offset, ftemp);
524         L_ADD(time_adj, time_freq);
525         tcp->tc_adjustment = time_adj;
526 #ifdef PPS_SYNC
527         if (pps_valid > 0)
528                 pps_valid--;
529         else
530                 time_status &= ~STA_PPSSIGNAL;
531 #endif /* PPS_SYNC */
532 }
533
534 /*
535  * ntp_init() - initialize variables and structures
536  *
537  * This routine must be called after the kernel variables hz and tick
538  * are set or changed and before the next tick interrupt. In this
539  * particular implementation, these values are assumed set elsewhere in
540  * the kernel. The design allows the clock frequency and tick interval
541  * to be changed while the system is running. So, this routine should
542  * probably be integrated with the code that does that.
543  */
544 static void
545 ntp_init()
546 {
547
548         /*
549          * The following variable must be initialized any time the
550          * kernel variable hz is changed.
551          */
552         time_tick = NANOSECOND / hz;
553
554         /*
555          * The following variables are initialized only at startup. Only
556          * those structures not cleared by the compiler need to be
557          * initialized, and these only in the simulator. In the actual
558          * kernel, any nonzero values here will quickly evaporate.
559          */
560         L_CLR(time_offset);
561         L_CLR(time_freq);
562 #ifdef PPS_SYNC
563         pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
564         pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
565         pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
566         pps_fcount = 0;
567         L_CLR(pps_freq);
568 #endif /* PPS_SYNC */      
569 }
570
571 SYSINIT(ntpclocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, ntp_init, NULL)
572
573 /*
574  * hardupdate() - local clock update
575  *
576  * This routine is called by ntp_adjtime() to update the local clock
577  * phase and frequency. The implementation is of an adaptive-parameter,
578  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
579  * time and frequency offset estimates for each call. If the kernel PPS
580  * discipline code is configured (PPS_SYNC), the PPS signal itself
581  * determines the new time offset, instead of the calling argument.
582  * Presumably, calls to ntp_adjtime() occur only when the caller
583  * believes the local clock is valid within some bound (+-128 ms with
584  * NTP). If the caller's time is far different than the PPS time, an
585  * argument will ensue, and it's not clear who will lose.
586  *
587  * For uncompensated quartz crystal oscillators and nominal update
588  * intervals less than 256 s, operation should be in phase-lock mode,
589  * where the loop is disciplined to phase. For update intervals greater
590  * than 1024 s, operation should be in frequency-lock mode, where the
591  * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
592  * is selected by the STA_MODE status bit.
593  */
594 static void
595 hardupdate(offset)
596         long offset;            /* clock offset (ns) */
597 {
598         long mtemp;
599         l_fp ftemp;
600
601         /*
602          * Select how the phase is to be controlled and from which
603          * source. If the PPS signal is present and enabled to
604          * discipline the time, the PPS offset is used; otherwise, the
605          * argument offset is used.
606          */
607         if (!(time_status & STA_PLL))
608                 return;
609         if (!(time_status & STA_PPSTIME && time_status &
610             STA_PPSSIGNAL)) {
611                 if (offset > MAXPHASE)
612                         time_monitor = MAXPHASE;
613                 else if (offset < -MAXPHASE)
614                         time_monitor = -MAXPHASE;
615                 else
616                         time_monitor = offset;
617                 L_LINT(time_offset, time_monitor);
618         }
619
620         /*
621          * Select how the frequency is to be controlled and in which
622          * mode (PLL or FLL). If the PPS signal is present and enabled
623          * to discipline the frequency, the PPS frequency is used;
624          * otherwise, the argument offset is used to compute it.
625          */
626         if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
627                 time_reftime = time_second;
628                 return;
629         }
630         if (time_status & STA_FREQHOLD || time_reftime == 0)
631                 time_reftime = time_second;
632         mtemp = time_second - time_reftime;
633         L_LINT(ftemp, time_monitor);
634         L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
635         L_MPY(ftemp, mtemp);
636         L_ADD(time_freq, ftemp);
637         time_status &= ~STA_MODE;
638         if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp >
639             MAXSEC)) {
640                 L_LINT(ftemp, (time_monitor << 4) / mtemp);
641                 L_RSHIFT(ftemp, SHIFT_FLL + 4);
642                 L_ADD(time_freq, ftemp);
643                 time_status |= STA_MODE;
644         }
645         time_reftime = time_second;
646         if (L_GINT(time_freq) > MAXFREQ)
647                 L_LINT(time_freq, MAXFREQ);
648         else if (L_GINT(time_freq) < -MAXFREQ)
649                 L_LINT(time_freq, -MAXFREQ);
650 }
651
652 #ifdef PPS_SYNC
653 /*
654  * hardpps() - discipline CPU clock oscillator to external PPS signal
655  *
656  * This routine is called at each PPS interrupt in order to discipline
657  * the CPU clock oscillator to the PPS signal. There are two independent
658  * first-order feedback loops, one for the phase, the other for the
659  * frequency. The phase loop measures and grooms the PPS phase offset
660  * and leaves it in a handy spot for the seconds overflow routine. The
661  * frequency loop averages successive PPS phase differences and
662  * calculates the PPS frequency offset, which is also processed by the
663  * seconds overflow routine. The code requires the caller to capture the
664  * time and architecture-dependent hardware counter values in
665  * nanoseconds at the on-time PPS signal transition.
666  *
667  * Note that, on some Unix systems this routine runs at an interrupt
668  * priority level higher than the timer interrupt routine hardclock().
669  * Therefore, the variables used are distinct from the hardclock()
670  * variables, except for the actual time and frequency variables, which
671  * are determined by this routine and updated atomically.
672  */
673 void
674 hardpps(tsp, nsec)
675         struct timespec *tsp;   /* time at PPS */
676         long nsec;              /* hardware counter at PPS */
677 {
678         long u_sec, u_nsec, v_nsec; /* temps */
679         l_fp ftemp;
680
681         /*
682          * The signal is first processed by a range gate and frequency
683          * discriminator. The range gate rejects noise spikes outside
684          * the range +-500 us. The frequency discriminator rejects input
685          * signals with apparent frequency outside the range 1 +-500
686          * PPM. If two hits occur in the same second, we ignore the
687          * later hit; if not and a hit occurs outside the range gate,
688          * keep the later hit for later comparison, but do not process
689          * it.
690          */
691         time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
692         time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
693         pps_valid = PPS_VALID;
694         u_sec = tsp->tv_sec;
695         u_nsec = tsp->tv_nsec;
696         if (u_nsec >= (NANOSECOND >> 1)) {
697                 u_nsec -= NANOSECOND;
698                 u_sec++;
699         }
700         v_nsec = u_nsec - pps_tf[0].tv_nsec;
701         if (u_sec == pps_tf[0].tv_sec && v_nsec < NANOSECOND -
702             MAXFREQ)
703                 return;
704         pps_tf[2] = pps_tf[1];
705         pps_tf[1] = pps_tf[0];
706         pps_tf[0].tv_sec = u_sec;
707         pps_tf[0].tv_nsec = u_nsec;
708
709         /*
710          * Compute the difference between the current and previous
711          * counter values. If the difference exceeds 0.5 s, assume it
712          * has wrapped around, so correct 1.0 s. If the result exceeds
713          * the tick interval, the sample point has crossed a tick
714          * boundary during the last second, so correct the tick. Very
715          * intricate.
716          */
717         u_nsec = nsec;
718         if (u_nsec > (NANOSECOND >> 1))
719                 u_nsec -= NANOSECOND;
720         else if (u_nsec < -(NANOSECOND >> 1))
721                 u_nsec += NANOSECOND;
722         pps_fcount += u_nsec;
723         if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ)
724                 return;
725         time_status &= ~STA_PPSJITTER;
726
727         /*
728          * A three-stage median filter is used to help denoise the PPS
729          * time. The median sample becomes the time offset estimate; the
730          * difference between the other two samples becomes the time
731          * dispersion (jitter) estimate.
732          */
733         if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
734                 if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
735                         v_nsec = pps_tf[1].tv_nsec;     /* 0 1 2 */
736                         u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
737                 } else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
738                         v_nsec = pps_tf[0].tv_nsec;     /* 2 0 1 */
739                         u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
740                 } else {
741                         v_nsec = pps_tf[2].tv_nsec;     /* 0 2 1 */
742                         u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
743                 }
744         } else {
745                 if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
746                         v_nsec = pps_tf[1].tv_nsec;     /* 2 1 0 */
747                         u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
748                 } else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
749                         v_nsec = pps_tf[0].tv_nsec;     /* 1 0 2 */
750                         u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
751                 } else {
752                         v_nsec = pps_tf[2].tv_nsec;     /* 1 2 0 */
753                         u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
754                 }
755         }
756
757         /*
758          * Nominal jitter is due to PPS signal noise and interrupt
759          * latency. If it exceeds the popcorn threshold, the sample is
760          * discarded. otherwise, if so enabled, the time offset is
761          * updated. We can tolerate a modest loss of data here without
762          * much degrading time accuracy.
763          */
764         if (u_nsec > (pps_jitter << PPS_POPCORN)) {
765                 time_status |= STA_PPSJITTER;
766                 pps_jitcnt++;
767         } else if (time_status & STA_PPSTIME) {
768                 time_monitor = -v_nsec;
769                 L_LINT(time_offset, time_monitor);
770         }
771         pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
772         u_sec = pps_tf[0].tv_sec - pps_lastsec;
773         if (u_sec < (1 << pps_shift))
774                 return;
775
776         /*
777          * At the end of the calibration interval the difference between
778          * the first and last counter values becomes the scaled
779          * frequency. It will later be divided by the length of the
780          * interval to determine the frequency update. If the frequency
781          * exceeds a sanity threshold, or if the actual calibration
782          * interval is not equal to the expected length, the data are
783          * discarded. We can tolerate a modest loss of data here without
784          * much degrading frequency accuracy.
785          */
786         pps_calcnt++;
787         v_nsec = -pps_fcount;
788         pps_lastsec = pps_tf[0].tv_sec;
789         pps_fcount = 0;
790         u_nsec = MAXFREQ << pps_shift;
791         if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 <<
792             pps_shift)) {
793                 time_status |= STA_PPSERROR;
794                 pps_errcnt++;
795                 return;
796         }
797
798         /*
799          * Here the raw frequency offset and wander (stability) is
800          * calculated. If the wander is less than the wander threshold
801          * for four consecutive averaging intervals, the interval is
802          * doubled; if it is greater than the threshold for four
803          * consecutive intervals, the interval is halved. The scaled
804          * frequency offset is converted to frequency offset. The
805          * stability metric is calculated as the average of recent
806          * frequency changes, but is used only for performance
807          * monitoring.
808          */
809         L_LINT(ftemp, v_nsec);
810         L_RSHIFT(ftemp, pps_shift);
811         L_SUB(ftemp, pps_freq);
812         u_nsec = L_GINT(ftemp);
813         if (u_nsec > PPS_MAXWANDER) {
814                 L_LINT(ftemp, PPS_MAXWANDER);
815                 pps_intcnt--;
816                 time_status |= STA_PPSWANDER;
817                 pps_stbcnt++;
818         } else if (u_nsec < -PPS_MAXWANDER) {
819                 L_LINT(ftemp, -PPS_MAXWANDER);
820                 pps_intcnt--;
821                 time_status |= STA_PPSWANDER;
822                 pps_stbcnt++;
823         } else {
824                 pps_intcnt++;
825         }
826         if (pps_intcnt >= 4) {
827                 pps_intcnt = 4;
828                 if (pps_shift < pps_shiftmax) {
829                         pps_shift++;
830                         pps_intcnt = 0;
831                 }
832         } else if (pps_intcnt <= -4 || pps_shift > pps_shiftmax) {
833                 pps_intcnt = -4;
834                 if (pps_shift > PPS_FAVG) {
835                         pps_shift--;
836                         pps_intcnt = 0;
837                 }
838         }
839         if (u_nsec < 0)
840                 u_nsec = -u_nsec;
841         pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
842
843         /*
844          * The PPS frequency is recalculated and clamped to the maximum
845          * MAXFREQ. If enabled, the system clock frequency is updated as
846          * well.
847          */
848         L_ADD(pps_freq, ftemp);
849         u_nsec = L_GINT(pps_freq);
850         if (u_nsec > MAXFREQ)
851                 L_LINT(pps_freq, MAXFREQ);
852         else if (u_nsec < -MAXFREQ)
853                 L_LINT(pps_freq, -MAXFREQ);
854         if (time_status & STA_PPSFREQ)
855                 time_freq = pps_freq;
856 }
857 #endif /* PPS_SYNC */