2 * ntp_loopfilter.c - implements the NTP loop filter algorithm
4 * ATTENTION: Get approval from Dave Mills on all changes to this file!
16 #include "ntp_unixtime.h"
17 #include "ntp_stdlib.h"
27 #include "ntp_syscall.h"
28 #endif /* KERNEL_PLL */
31 * This is an implementation of the clock discipline algorithm described
32 * in UDel TR 97-4-3, as amended. It operates as an adaptive parameter,
33 * hybrid phase/frequency-lock loop. A number of sanity checks are
34 * included to protect against timewarps, timespikes and general mayhem.
35 * All units are in s and s/s, unless noted otherwise.
37 #define CLOCK_MAX .128 /* default step threshold (s) */
38 #define CLOCK_MINSTEP 300. /* default stepout threshold (s) */
39 #define CLOCK_PANIC 1000. /* default panic threshold (s) */
40 #define CLOCK_PHI 15e-6 /* max frequency error (s/s) */
41 #define CLOCK_PLL 16. /* PLL loop gain (log2) */
42 #define CLOCK_AVG 8. /* parameter averaging constant */
43 #define CLOCK_FLL .25 /* FLL loop gain */
44 #define CLOCK_FLOOR .0005 /* startup offset floor (s) */
45 #define CLOCK_ALLAN 11 /* Allan intercept (log2 s) */
46 #define CLOCK_LIMIT 30 /* poll-adjust threshold */
47 #define CLOCK_PGATE 4. /* poll-adjust gate */
48 #define PPS_MAXAGE 120 /* kernel pps signal timeout (s) */
49 #define FREQTOD(x) ((x) / 65536e6) /* NTP to double */
50 #define DTOFREQ(x) ((int32)((x) * 65536e6)) /* double to NTP */
53 * Clock discipline state machine. This is used to control the
54 * synchronization behavior during initialization and following a
57 * State < step > step Comments
58 * ========================================================
59 * NSET FREQ step, FREQ freq not set
61 * FSET SYNC step, SYNC freq set
63 * FREQ if (mu < 900) if (mu < 900) set freq direct
66 * freq, SYNC freq, step, SYNC
68 * SYNC SYNC SPIK, ignore adjust phase/freq
70 * SPIK SYNC if (mu < 900) adjust phase/freq
75 * Kernel PLL/PPS state machine. This is used with the kernel PLL
76 * modifications described in the documentation.
78 * If kernel support for the ntp_adjtime() system call is available, the
79 * ntp_control flag is set. The ntp_enable and kern_enable flags can be
80 * set at configuration time or run time using ntpdc. If ntp_enable is
81 * false, the discipline loop is unlocked and no corrections of any kind
82 * are made. If both ntp_control and kern_enable are set, the kernel
83 * support is used as described above; if false, the kernel is bypassed
84 * entirely and the daemon discipline used instead.
86 * There have been three versions of the kernel discipline code. The
87 * first (microkernel) now in Solaris discipilnes the microseconds. The
88 * second and third (nanokernel) disciplines the clock in nanoseconds.
89 * These versions are identifed if the symbol STA_PLL is present in the
90 * header file /usr/include/sys/timex.h. The third and current version
91 * includes TAI offset and is identified by the symbol NTP_API with
94 * Each PPS time/frequency discipline can be enabled by the atom driver
95 * or another driver. If enabled, the STA_PPSTIME and STA_FREQ bits are
96 * set in the kernel status word; otherwise, these bits are cleared.
97 * These bits are also cleard if the kernel reports an error.
99 * If an external clock is present, the clock driver sets STA_CLK in the
100 * status word. When the local clock driver sees this bit, it updates
101 * via this routine, which then calls ntp_adjtime() with the STA_PLL bit
102 * set to zero, in which case the system clock is not adjusted. This is
103 * also a signal for the external clock driver to discipline the system
104 * clock. Unless specified otherwise, all times are in seconds.
107 * Program variables that can be tinkered.
109 double clock_max_back = CLOCK_MAX; /* step threshold */
110 double clock_max_fwd = CLOCK_MAX; /* step threshold */
111 double clock_minstep = CLOCK_MINSTEP; /* stepout threshold */
112 double clock_panic = CLOCK_PANIC; /* panic threshold */
113 double clock_phi = CLOCK_PHI; /* dispersion rate (s/s) */
114 u_char allan_xpt = CLOCK_ALLAN; /* Allan intercept (log2 s) */
119 static double clock_offset; /* offset */
120 double clock_jitter; /* offset jitter */
121 double drift_comp; /* frequency (s/s) */
122 static double init_drift_comp; /* initial frequency (PPM) */
123 double clock_stability; /* frequency stability (wander) (s/s) */
124 double clock_codec; /* audio codec frequency (samples/s) */
125 static u_long clock_epoch; /* last update */
126 u_int sys_tai; /* TAI offset from UTC */
127 static int loop_started; /* TRUE after LOOP_DRIFTINIT */
128 static void rstclock (int, double); /* transition function */
129 static double direct_freq(double); /* direct set frequency */
130 static void set_freq(double); /* set frequency */
132 # define PATH_MAX MAX_PATH
134 static char relative_path[PATH_MAX + 1]; /* relative path per recursive make */
135 static char *this_file = NULL;
138 static struct timex ntv; /* ntp_adjtime() parameters */
139 int pll_status; /* last kernel status bits */
140 #if defined(STA_NANO) && NTP_API == 4
141 static u_int loop_tai; /* last TAI offset */
142 #endif /* STA_NANO */
143 static void start_kern_loop(void);
144 static void stop_kern_loop(void);
145 #endif /* KERNEL_PLL */
148 * Clock state machine control flags
150 int ntp_enable = TRUE; /* clock discipline enabled */
151 int pll_control; /* kernel support available */
152 int kern_enable = TRUE; /* kernel support enabled */
153 int hardpps_enable; /* kernel PPS discipline enabled */
154 int ext_enable; /* external clock enabled */
155 int pps_stratum; /* pps stratum */
156 int kernel_status; /* from ntp_adjtime */
157 int allow_panic = FALSE; /* allow panic correction (-g) */
158 int force_step_once = FALSE; /* always step time once at startup (-G) */
159 int mode_ntpdate = FALSE; /* exit on first clock set (-q) */
160 int freq_cnt; /* initial frequency clamp */
161 int freq_set; /* initial set frequency switch */
164 * Clock state machine variables
166 int state = 0; /* clock discipline state */
167 u_char sys_poll; /* time constant/poll (log2 s) */
168 int tc_counter; /* jiggle counter */
169 double last_offset; /* last offset (s) */
172 * Huff-n'-puff filter variables
174 static double *sys_huffpuff; /* huff-n'-puff filter */
175 static int sys_hufflen; /* huff-n'-puff filter stages */
176 static int sys_huffptr; /* huff-n'-puff filter pointer */
177 static double sys_mindly; /* huff-n'-puff filter min delay */
179 #if defined(KERNEL_PLL)
180 /* Emacs cc-mode goes nuts if we split the next line... */
181 #define MOD_BITS (MOD_OFFSET | MOD_MAXERROR | MOD_ESTERROR | \
182 MOD_STATUS | MOD_TIMECONST)
184 static void pll_trap (int); /* configuration trap */
185 static struct sigaction sigsys; /* current sigaction status */
186 static struct sigaction newsigsys; /* new sigaction status */
187 static sigjmp_buf env; /* environment var. for pll_trap() */
189 #endif /* KERNEL_PLL */
192 sync_status(const char *what, int ostatus, int nstatus)
194 char obuf[256], nbuf[256], tbuf[1024];
195 #if defined(USE_SNPRINTB) && defined (STA_FMT)
196 snprintb(obuf, sizeof(obuf), STA_FMT, ostatus);
197 snprintb(nbuf, sizeof(nbuf), STA_FMT, nstatus);
199 snprintf(obuf, sizeof(obuf), "%04x", ostatus);
200 snprintf(nbuf, sizeof(nbuf), "%04x", nstatus);
202 snprintf(tbuf, sizeof(tbuf), "%s status: %s -> %s", what, obuf, nbuf);
203 report_event(EVNT_KERN, NULL, tbuf);
207 * file_name - return pointer to non-relative portion of this C file pathname
209 static char *file_name(void)
211 if (this_file == NULL) {
212 (void)strncpy(relative_path, __FILE__, PATH_MAX);
213 for (this_file=relative_path;
214 *this_file && ! isalnum((unsigned char)*this_file);
221 * init_loopfilter - initialize loop filter data
224 init_loopfilter(void)
227 * Initialize state variables.
229 sys_poll = ntp_minpoll;
230 clock_jitter = LOGTOD(sys_precision);
231 freq_cnt = (int)clock_minstep;
236 * ntp_adjtime_error_handler - process errors from ntp_adjtime
239 ntp_adjtime_error_handler(
240 const char *caller, /* name of calling function */
241 struct timex *ptimex, /* pointer to struct timex */
242 int ret, /* return value from ntp_adjtime */
243 int saved_errno, /* value of errno when ntp_adjtime returned */
244 int pps_call, /* ntp_adjtime call was PPS-related */
245 int tai_call, /* ntp_adjtime call was TAI-related */
246 int line /* line number of ntp_adjtime call */
249 char des[1024] = ""; /* Decoded Error Status */
253 switch (saved_errno) {
255 msyslog(LOG_ERR, "%s: %s line %d: invalid struct timex pointer: 0x%lx",
256 caller, file_name(), line,
257 (long)((void *)ptimex)
261 msyslog(LOG_ERR, "%s: %s line %d: invalid struct timex \"constant\" element value: %ld",
262 caller, file_name(), line,
263 (long)(ptimex->constant)
270 "%s: ntp_adjtime(TAI) failed: %m",
274 msyslog(LOG_ERR, "%s: %s line %d: ntp_adjtime: %m",
275 caller, file_name(), line
279 msyslog(LOG_NOTICE, "%s: %s line %d: unhandled errno value %d after failed ntp_adjtime call",
280 caller, file_name(), line,
287 case TIME_OK: /* 0: synchronized, no leap second warning */
288 /* msyslog(LOG_INFO, "kernel reports time is synchronized normally"); */
291 # warning TIME_OK is not defined
294 case TIME_INS: /* 1: positive leap second warning */
295 msyslog(LOG_INFO, "kernel reports leap second insertion scheduled");
298 # warning TIME_INS is not defined
301 case TIME_DEL: /* 2: negative leap second warning */
302 msyslog(LOG_INFO, "kernel reports leap second deletion scheduled");
305 # warning TIME_DEL is not defined
308 case TIME_OOP: /* 3: leap second in progress */
309 msyslog(LOG_INFO, "kernel reports leap second in progress");
312 # warning TIME_OOP is not defined
315 case TIME_WAIT: /* 4: leap second has occured */
316 msyslog(LOG_INFO, "kernel reports leap second has occurred");
319 # warning TIME_WAIT is not defined
324 from the reference implementation of ntp_gettime():
326 // Hardware or software error
327 if ((time_status & (STA_UNSYNC | STA_CLOCKERR))
330 * PPS signal lost when either time or frequency synchronization
333 || (time_status & (STA_PPSFREQ | STA_PPSTIME)
334 && !(time_status & STA_PPSSIGNAL))
337 * PPS jitter exceeded when time synchronization requested
339 || (time_status & STA_PPSTIME &&
340 time_status & STA_PPSJITTER)
343 * PPS wander exceeded or calibration error when frequency
344 * synchronization requested
346 || (time_status & STA_PPSFREQ &&
347 time_status & (STA_PPSWANDER | STA_PPSERROR)))
350 or, from ntp_adjtime():
352 if ( (time_status & (STA_UNSYNC | STA_CLOCKERR))
353 || (time_status & (STA_PPSFREQ | STA_PPSTIME)
354 && !(time_status & STA_PPSSIGNAL))
355 || (time_status & STA_PPSTIME
356 && time_status & STA_PPSJITTER)
357 || (time_status & STA_PPSFREQ
358 && time_status & (STA_PPSWANDER | STA_PPSERROR))
363 case TIME_ERROR: /* 5: unsynchronized, or loss of synchronization */
364 /* error (see status word) */
366 if (ptimex->status & STA_UNSYNC)
367 snprintf(des, sizeof(des), "%s%sClock Unsynchronized",
368 des, (*des) ? "; " : "");
370 if (ptimex->status & STA_CLOCKERR)
371 snprintf(des, sizeof(des), "%s%sClock Error",
372 des, (*des) ? "; " : "");
374 if (!(ptimex->status & STA_PPSSIGNAL)
375 && ptimex->status & STA_PPSFREQ)
376 snprintf(des, sizeof(des), "%s%sPPS Frequency Sync wanted but no PPS",
377 des, (*des) ? "; " : "");
379 if (!(ptimex->status & STA_PPSSIGNAL)
380 && ptimex->status & STA_PPSTIME)
381 snprintf(des, sizeof(des), "%s%sPPS Time Sync wanted but no PPS signal",
382 des, (*des) ? "; " : "");
384 if ( ptimex->status & STA_PPSTIME
385 && ptimex->status & STA_PPSJITTER)
386 snprintf(des, sizeof(des), "%s%sPPS Time Sync wanted but PPS Jitter exceeded",
387 des, (*des) ? "; " : "");
389 if ( ptimex->status & STA_PPSFREQ
390 && ptimex->status & STA_PPSWANDER)
391 snprintf(des, sizeof(des), "%s%sPPS Frequency Sync wanted but PPS Wander exceeded",
392 des, (*des) ? "; " : "");
394 if ( ptimex->status & STA_PPSFREQ
395 && ptimex->status & STA_PPSERROR)
396 snprintf(des, sizeof(des), "%s%sPPS Frequency Sync wanted but Calibration error detected",
397 des, (*des) ? "; " : "");
399 if (pps_call && !(ptimex->status & STA_PPSSIGNAL))
400 report_event(EVNT_KERN, NULL,
402 DPRINTF(1, ("kernel loop status %#x (%s)\n",
403 ptimex->status, des));
405 * This code may be returned when ntp_adjtime() has just
406 * been called for the first time, quite a while after
407 * startup, when ntpd just starts to discipline the kernel
408 * time. In this case the occurrence of this message
409 * can be pretty confusing.
411 * HMS: How about a message when we begin kernel processing:
412 * Determining kernel clock state...
413 * so an initial TIME_ERROR message is less confising,
414 * or skipping the first message (ugh),
416 * msyslog(LOG_INFO, "kernel reports time synchronization lost");
418 msyslog(LOG_INFO, "kernel reports TIME_ERROR: %#x: %s",
419 ptimex->status, des);
422 # warning TIME_ERROR is not defined
425 msyslog(LOG_NOTICE, "%s: %s line %d: unhandled return value %d from ntp_adjtime() in %s at line %d",
426 caller, file_name(), line,
437 * local_clock - the NTP logical clock loop filter.
440 * -1 update ignored: exceeds panic threshold
441 * 0 update ignored: popcorn or exceeds step threshold
443 * 2 clock was stepped
445 * LOCKCLOCK: The only thing this routine does is set the
446 * sys_rootdisp variable equal to the peer dispersion.
450 struct peer *peer, /* synch source peer structure */
451 double fp_offset /* clock offset (s) */
454 int rval; /* return code */
455 int osys_poll; /* old system poll */
456 int ntp_adj_ret; /* returned by ntp_adjtime */
457 double mu; /* interval since last update */
458 double clock_frequency; /* clock frequency */
459 double dtemp, etemp; /* double temps */
460 char tbuf[80]; /* report buffer */
463 * If the loop is opened or the NIST LOCKCLOCK is in use,
464 * monitor and record the offsets anyway in order to determine
465 * the open-loop response and then go home.
471 #endif /* LOCKCLOCK */
472 record_loop_stats(fp_offset, drift_comp, clock_jitter,
473 clock_stability, sys_poll);
479 * If the clock is way off, panic is declared. The clock_panic
480 * defaults to 1000 s; if set to zero, the panic will never
481 * occur. The allow_panic defaults to FALSE, so the first panic
482 * will exit. It can be set TRUE by a command line option, in
483 * which case the clock will be set anyway and time marches on.
484 * But, allow_panic will be set FALSE when the update is less
485 * than the step threshold; so, subsequent panics will exit.
487 if (fabs(fp_offset) > clock_panic && clock_panic > 0 &&
489 snprintf(tbuf, sizeof(tbuf),
490 "%+.0f s; set clock manually within %.0f s.",
491 fp_offset, clock_panic);
492 report_event(EVNT_SYSFAULT, NULL, tbuf);
497 * This section simulates ntpdate. If the offset exceeds the
498 * step threshold (128 ms), step the clock to that time and
499 * exit. Otherwise, slew the clock to that time and exit. Note
500 * that the slew will persist and eventually complete beyond the
501 * life of this program. Note that while ntpdate is active, the
502 * terminal does not detach, so the termination message prints
503 * directly to the terminal.
506 if ( ( fp_offset > clock_max_fwd && clock_max_fwd > 0)
507 || (-fp_offset > clock_max_back && clock_max_back > 0)) {
508 step_systime(fp_offset);
509 msyslog(LOG_NOTICE, "ntpd: time set %+.6f s",
511 printf("ntpd: time set %+.6fs\n", fp_offset);
513 adj_systime(fp_offset);
514 msyslog(LOG_NOTICE, "ntpd: time slew %+.6f s",
516 printf("ntpd: time slew %+.6fs\n", fp_offset);
518 record_loop_stats(fp_offset, drift_comp, clock_jitter,
519 clock_stability, sys_poll);
524 * The huff-n'-puff filter finds the lowest delay in the recent
525 * interval. This is used to correct the offset by one-half the
526 * difference between the sample delay and minimum delay. This
527 * is most effective if the delays are highly assymetric and
528 * clockhopping is avoided and the clock frequency wander is
531 if (sys_huffpuff != NULL) {
532 if (peer->delay < sys_huffpuff[sys_huffptr])
533 sys_huffpuff[sys_huffptr] = peer->delay;
534 if (peer->delay < sys_mindly)
535 sys_mindly = peer->delay;
537 dtemp = -(peer->delay - sys_mindly) / 2;
539 dtemp = (peer->delay - sys_mindly) / 2;
544 "local_clock: size %d mindly %.6f huffpuff %.6f\n",
545 sys_hufflen, sys_mindly, dtemp);
550 * Clock state machine transition function which defines how the
551 * system reacts to large phase and frequency excursion. There
552 * are two main regimes: when the offset exceeds the step
553 * threshold (128 ms) and when it does not. Under certain
554 * conditions updates are suspended until the stepout theshold
555 * (900 s) is exceeded. See the documentation on how these
556 * thresholds interact with commands and command line options.
558 * Note the kernel is disabled if step is disabled or greater
559 * than 0.5 s or in ntpdate mode.
561 osys_poll = sys_poll;
562 if (sys_poll < peer->minpoll)
563 sys_poll = peer->minpoll;
564 if (sys_poll > peer->maxpoll)
565 sys_poll = peer->maxpoll;
566 mu = current_time - clock_epoch;
567 clock_frequency = drift_comp;
569 if ( ( fp_offset > clock_max_fwd && clock_max_fwd > 0)
570 || (-fp_offset > clock_max_back && clock_max_back > 0)
571 || force_step_once ) {
572 if (force_step_once) {
573 force_step_once = FALSE; /* we want this only once after startup */
574 msyslog(LOG_NOTICE, "Doing intital time step" );
580 * In SYNC state we ignore the first outlyer and switch
584 snprintf(tbuf, sizeof(tbuf), "%+.6f s",
586 report_event(EVNT_SPIK, NULL, tbuf);
591 * In FREQ state we ignore outlyers and inlyers. At the
592 * first outlyer after the stepout threshold, compute
593 * the apparent frequency correction and step the phase.
596 if (mu < clock_minstep)
599 clock_frequency = direct_freq(fp_offset);
601 /* fall through to EVNT_SPIK */
604 * In SPIK state we ignore succeeding outlyers until
605 * either an inlyer is found or the stepout threshold is
609 if (mu < clock_minstep)
612 /* fall through to default */
615 * We get here by default in NSET and FSET states and
616 * from above in FREQ or SPIK states.
618 * In NSET state an initial frequency correction is not
619 * available, usually because the frequency file has not
620 * yet been written. Since the time is outside the step
621 * threshold, the clock is stepped. The frequency will
622 * be set directly following the stepout interval.
624 * In FSET state the initial frequency has been set from
625 * the frequency file. Since the time is outside the
626 * step threshold, the clock is stepped immediately,
627 * rather than after the stepout interval. Guys get
628 * nervous if it takes 15 minutes to set the clock for
631 * In FREQ and SPIK states the stepout threshold has
632 * expired and the phase is still above the step
633 * threshold. Note that a single spike greater than the
634 * step threshold is always suppressed, even with a
635 * long time constant.
638 snprintf(tbuf, sizeof(tbuf), "%+.6f s",
640 report_event(EVNT_CLOCKRESET, NULL, tbuf);
641 step_systime(fp_offset);
644 clock_jitter = LOGTOD(sys_precision);
646 if (state == EVNT_NSET) {
647 rstclock(EVNT_FREQ, 0);
652 rstclock(EVNT_SYNC, 0);
655 * The offset is less than the step threshold. Calculate
656 * the jitter as the exponentially weighted offset
659 etemp = SQUARE(clock_jitter);
660 dtemp = SQUARE(max(fabs(fp_offset - last_offset),
661 LOGTOD(sys_precision)));
662 clock_jitter = SQRT(etemp + (dtemp - etemp) /
667 * In NSET state this is the first update received and
668 * the frequency has not been initialized. Adjust the
669 * phase, but do not adjust the frequency until after
670 * the stepout threshold.
673 adj_systime(fp_offset);
674 rstclock(EVNT_FREQ, fp_offset);
678 * In FREQ state ignore updates until the stepout
679 * threshold. After that, compute the new frequency, but
680 * do not adjust the frequency until the holdoff counter
681 * decrements to zero.
684 if (mu < clock_minstep)
687 clock_frequency = direct_freq(fp_offset);
691 * We get here by default in FSET, SPIK and SYNC states.
692 * Here compute the frequency update due to PLL and FLL
693 * contributions. Note, we avoid frequency discipline at
694 * startup until the initial transient has subsided.
701 * The FLL and PLL frequency gain constants
702 * depend on the time constant and Allan
703 * intercept. The PLL is always used, but
704 * becomes ineffective above the Allan intercept
705 * where the FLL becomes effective.
707 if (sys_poll >= allan_xpt)
708 clock_frequency += (fp_offset -
709 clock_offset) / max(ULOGTOD(sys_poll),
713 * The PLL frequency gain (numerator) depends on
714 * the minimum of the update interval and Allan
715 * intercept. This reduces the PLL gain when the
716 * FLL becomes effective.
718 etemp = min(ULOGTOD(allan_xpt), mu);
719 dtemp = 4 * CLOCK_PLL * ULOGTOD(sys_poll);
720 clock_frequency += fp_offset * etemp / (dtemp *
723 rstclock(EVNT_SYNC, fp_offset);
724 if (fabs(fp_offset) < CLOCK_FLOOR)
732 * This code segment works when clock adjustments are made using
733 * precision time kernel support and the ntp_adjtime() system
734 * call. This support is available in Solaris 2.6 and later,
735 * Digital Unix 4.0 and later, FreeBSD, Linux and specially
736 * modified kernels for HP-UX 9 and Ultrix 4. In the case of the
737 * DECstation 5000/240 and Alpha AXP, additional kernel
738 * modifications provide a true microsecond clock and nanosecond
739 * clock, respectively.
741 * Important note: The kernel discipline is used only if the
742 * step threshold is less than 0.5 s, as anything higher can
743 * lead to overflow problems. This might occur if some misguided
744 * lad set the step threshold to something ridiculous.
746 if (pll_control && kern_enable && freq_cnt == 0) {
749 * We initialize the structure for the ntp_adjtime()
750 * system call. We have to convert everything to
751 * microseconds or nanoseconds first. Do not update the
752 * system variables if the ext_enable flag is set. In
753 * this case, the external clock driver will update the
754 * variables, which will be read later by the local
755 * clock driver. Afterwards, remember the time and
756 * frequency offsets for jitter and stability values and
757 * to update the frequency file.
761 ntv.modes = MOD_STATUS;
764 ntv.modes = MOD_BITS | MOD_NANO;
766 ntv.modes = MOD_BITS;
767 #endif /* STA_NANO */
768 if (clock_offset < 0)
773 ntv.offset = (int32)(clock_offset * 1e9 +
775 ntv.constant = sys_poll;
777 ntv.offset = (int32)(clock_offset * 1e6 +
779 ntv.constant = sys_poll - 4;
780 #endif /* STA_NANO */
781 if (ntv.constant < 0)
784 ntv.esterror = (u_int32)(clock_jitter * 1e6);
785 ntv.maxerror = (u_int32)((sys_rootdelay / 2 +
786 sys_rootdisp) * 1e6);
787 ntv.status = STA_PLL;
790 * Enable/disable the PPS if requested.
792 if (hardpps_enable) {
793 ntv.status |= (STA_PPSTIME | STA_PPSFREQ);
794 if (!(pll_status & STA_PPSTIME))
795 sync_status("PPS enabled",
799 ntv.status &= ~(STA_PPSTIME | STA_PPSFREQ);
800 if (pll_status & STA_PPSTIME)
801 sync_status("PPS disabled",
805 if (sys_leap == LEAP_ADDSECOND)
806 ntv.status |= STA_INS;
807 else if (sys_leap == LEAP_DELSECOND)
808 ntv.status |= STA_DEL;
812 * Pass the stuff to the kernel. If it squeals, turn off
813 * the pps. In any case, fetch the kernel offset,
814 * frequency and jitter.
816 ntp_adj_ret = ntp_adjtime(&ntv);
818 * A squeal is a return status < 0, or a state change.
820 if ((0 > ntp_adj_ret) || (ntp_adj_ret != kernel_status)) {
821 kernel_status = ntp_adj_ret;
822 ntp_adjtime_error_handler(__func__, &ntv, ntp_adj_ret, errno, hardpps_enable, 0, __LINE__ - 1);
824 pll_status = ntv.status;
826 clock_offset = ntv.offset / 1e9;
828 clock_offset = ntv.offset / 1e6;
829 #endif /* STA_NANO */
830 clock_frequency = FREQTOD(ntv.freq);
833 * If the kernel PPS is lit, monitor its performance.
835 if (ntv.status & STA_PPSTIME) {
837 clock_jitter = ntv.jitter / 1e9;
839 clock_jitter = ntv.jitter / 1e6;
840 #endif /* STA_NANO */
843 #if defined(STA_NANO) && NTP_API == 4
845 * If the TAI changes, update the kernel TAI.
847 if (loop_tai != sys_tai) {
850 ntv.constant = sys_tai;
851 if ((ntp_adj_ret = ntp_adjtime(&ntv)) != 0) {
852 ntp_adjtime_error_handler(__func__, &ntv, ntp_adj_ret, errno, 0, 1, __LINE__ - 1);
855 #endif /* STA_NANO */
857 #endif /* KERNEL_PLL */
860 * Clamp the frequency within the tolerance range and calculate
861 * the frequency difference since the last update.
863 if (fabs(clock_frequency) > NTP_MAXFREQ)
865 "frequency error %.0f PPM exceeds tolerance %.0f PPM",
866 clock_frequency * 1e6, NTP_MAXFREQ * 1e6);
867 dtemp = SQUARE(clock_frequency - drift_comp);
868 if (clock_frequency > NTP_MAXFREQ)
869 drift_comp = NTP_MAXFREQ;
870 else if (clock_frequency < -NTP_MAXFREQ)
871 drift_comp = -NTP_MAXFREQ;
873 drift_comp = clock_frequency;
876 * Calculate the wander as the exponentially weighted RMS
877 * frequency differences. Record the change for the frequency
880 etemp = SQUARE(clock_stability);
881 clock_stability = SQRT(etemp + (dtemp - etemp) / CLOCK_AVG);
884 * Here we adjust the time constant by comparing the current
885 * offset with the clock jitter. If the offset is less than the
886 * clock jitter times a constant, then the averaging interval is
887 * increased, otherwise it is decreased. A bit of hysteresis
888 * helps calm the dance. Works best using burst mode. Don't
889 * fiddle with the poll during the startup clamp period.
893 } else if (fabs(clock_offset) < CLOCK_PGATE * clock_jitter) {
894 tc_counter += sys_poll;
895 if (tc_counter > CLOCK_LIMIT) {
896 tc_counter = CLOCK_LIMIT;
897 if (sys_poll < peer->maxpoll) {
903 tc_counter -= sys_poll << 1;
904 if (tc_counter < -CLOCK_LIMIT) {
905 tc_counter = -CLOCK_LIMIT;
906 if (sys_poll > peer->minpoll) {
914 * If the time constant has changed, update the poll variables.
916 if (osys_poll != sys_poll)
917 poll_update(peer, sys_poll);
920 * Yibbidy, yibbbidy, yibbidy; that'h all folks.
922 record_loop_stats(clock_offset, drift_comp, clock_jitter,
923 clock_stability, sys_poll);
927 "local_clock: offset %.9f jit %.9f freq %.3f stab %.3f poll %d\n",
928 clock_offset, clock_jitter, drift_comp * 1e6,
929 clock_stability * 1e6, sys_poll);
932 #endif /* LOCKCLOCK */
937 * adj_host_clock - Called once every second to update the local clock.
939 * LOCKCLOCK: The only thing this routine does is increment the
940 * sys_rootdisp variable.
951 * Update the dispersion since the last update. In contrast to
952 * NTPv3, NTPv4 does not declare unsynchronized after one day,
953 * since the dispersion check serves this function. Also,
954 * since the poll interval can exceed one day, the old test
955 * would be counterproductive. During the startup clamp period, the
956 * time constant is clamped at 2.
958 sys_rootdisp += clock_phi;
960 if (!ntp_enable || mode_ntpdate)
963 * Determine the phase adjustment. The gain factor (denominator)
964 * increases with poll interval, so is dominated by the FLL
965 * above the Allan intercept. Note the reduced time constant at
968 if (state != EVNT_SYNC) {
970 } else if (freq_cnt > 0) {
971 offset_adj = clock_offset / (CLOCK_PLL * ULOGTOD(1));
974 } else if (pll_control && kern_enable) {
976 #endif /* KERNEL_PLL */
978 offset_adj = clock_offset / (CLOCK_PLL * ULOGTOD(sys_poll));
982 * If the kernel discipline is enabled the frequency correction
983 * drift_comp has already been engaged via ntp_adjtime() in
984 * set_freq(). Otherwise it is a component of the adj_systime()
988 if (pll_control && kern_enable)
991 #endif /* KERNEL_PLL */
992 freq_adj = drift_comp;
994 /* Bound absolute value of total adjustment to NTP_MAXFREQ. */
995 if (offset_adj + freq_adj > NTP_MAXFREQ)
996 offset_adj = NTP_MAXFREQ - freq_adj;
997 else if (offset_adj + freq_adj < -NTP_MAXFREQ)
998 offset_adj = -NTP_MAXFREQ - freq_adj;
1000 clock_offset -= offset_adj;
1002 * Windows port adj_systime() must be called each second,
1003 * even if the argument is zero, to ease emulation of
1004 * adjtime() using Windows' slew API which controls the rate
1005 * but does not automatically stop slewing when an offset
1006 * has decayed to zero.
1008 adj_systime(offset_adj + freq_adj);
1009 #endif /* LOCKCLOCK */
1014 * Clock state machine. Enter new state and set state variables.
1018 int trans, /* new state */
1019 double offset /* new offset */
1024 printf("local_clock: mu %lu state %d poll %d count %d\n",
1025 current_time - clock_epoch, trans, sys_poll,
1028 if (trans != state && trans != EVNT_FSET)
1029 report_event(trans, NULL, NULL);
1031 last_offset = clock_offset = offset;
1032 clock_epoch = current_time;
1037 * calc_freq - calculate frequency directly
1039 * This is very carefully done. When the offset is first computed at the
1040 * first update, a residual frequency component results. Subsequently,
1041 * updates are suppresed until the end of the measurement interval while
1042 * the offset is amortized. At the end of the interval the frequency is
1043 * calculated from the current offset, residual offset, length of the
1044 * interval and residual frequency component. At the same time the
1045 * frequenchy file is armed for update at the next hourly stats.
1052 set_freq(fp_offset / (current_time - clock_epoch));
1059 * set_freq - set clock frequency correction
1061 * Used to step the frequency correction at startup, possibly again once
1062 * the frequency is measured (that is, transitioning from EVNT_NSET to
1063 * EVNT_FSET), and finally to switch between daemon and kernel loop
1064 * discipline at runtime.
1066 * When the kernel loop discipline is available but the daemon loop is
1067 * in use, the kernel frequency correction is disabled (set to 0) to
1068 * ensure drift_comp is applied by only one of the loops.
1072 double freq /* frequency update */
1075 const char * loop_desc;
1083 ntv.modes = MOD_FREQUENCY;
1085 loop_desc = "kernel";
1086 ntv.freq = DTOFREQ(drift_comp);
1088 if ((ntp_adj_ret = ntp_adjtime(&ntv)) != 0) {
1089 ntp_adjtime_error_handler(__func__, &ntv, ntp_adj_ret, errno, 0, 0, __LINE__ - 1);
1092 #endif /* KERNEL_PLL */
1093 mprintf_event(EVNT_FSET, NULL, "%s %.3f PPM", loop_desc,
1100 start_kern_loop(void)
1102 static int atexit_done;
1107 ntv.modes = MOD_BITS;
1108 ntv.status = STA_PLL;
1109 ntv.maxerror = MAXDISPERSE;
1110 ntv.esterror = MAXDISPERSE;
1111 ntv.constant = sys_poll; /* why is it that here constant is unconditionally set to sys_poll, whereas elsewhere is is modified depending on nanosecond vs. microsecond kernel? */
1114 * Use sigsetjmp() to save state and then call ntp_adjtime(); if
1115 * it fails, then pll_trap() will set pll_control FALSE before
1116 * returning control using siglogjmp().
1118 newsigsys.sa_handler = pll_trap;
1119 newsigsys.sa_flags = 0;
1120 if (sigaction(SIGSYS, &newsigsys, &sigsys)) {
1121 msyslog(LOG_ERR, "sigaction() trap SIGSYS: %m");
1122 pll_control = FALSE;
1124 if (sigsetjmp(env, 1) == 0) {
1125 if ((ntp_adj_ret = ntp_adjtime(&ntv)) != 0) {
1126 ntp_adjtime_error_handler(__func__, &ntv, ntp_adj_ret, errno, 0, 0, __LINE__ - 1);
1129 if (sigaction(SIGSYS, &sigsys, NULL)) {
1131 "sigaction() restore SIGSYS: %m");
1132 pll_control = FALSE;
1136 if ((ntp_adj_ret = ntp_adjtime(&ntv)) != 0) {
1137 ntp_adjtime_error_handler(__func__, &ntv, ntp_adj_ret, errno, 0, 0, __LINE__ - 1);
1142 * Save the result status and light up an external clock
1145 pll_status = ntv.status;
1149 atexit(&stop_kern_loop);
1152 if (pll_status & STA_CLK)
1154 #endif /* STA_NANO */
1155 report_event(EVNT_KERN, NULL,
1156 "kernel time sync enabled");
1159 #endif /* KERNEL_PLL */
1164 stop_kern_loop(void)
1166 if (pll_control && kern_enable)
1167 report_event(EVNT_KERN, NULL,
1168 "kernel time sync disabled");
1170 #endif /* KERNEL_PLL */
1174 * select_loop() - choose kernel or daemon loop discipline.
1181 if (kern_enable == use_kern_loop)
1184 if (pll_control && !use_kern_loop)
1187 kern_enable = use_kern_loop;
1189 if (pll_control && use_kern_loop)
1193 * If this loop selection change occurs after initial startup,
1194 * call set_freq() to switch the frequency compensation to or
1195 * from the kernel loop.
1198 if (pll_control && loop_started)
1199 set_freq(drift_comp);
1205 * huff-n'-puff filter
1212 if (sys_huffpuff == NULL)
1215 sys_huffptr = (sys_huffptr + 1) % sys_hufflen;
1216 sys_huffpuff[sys_huffptr] = 1e9;
1218 for (i = 0; i < sys_hufflen; i++) {
1219 if (sys_huffpuff[i] < sys_mindly)
1220 sys_mindly = sys_huffpuff[i];
1226 * loop_config - configure the loop filter
1228 * LOCKCLOCK: The LOOP_DRIFTINIT and LOOP_DRIFTCOMP cases are no-ops.
1241 printf("loop_config: item %d freq %f\n", item, freq);
1246 * We first assume the kernel supports the ntp_adjtime()
1247 * syscall. If that syscall works, initialize the kernel time
1248 * variables. Otherwise, continue leaving no harm behind.
1250 case LOOP_DRIFTINIT:
1257 #endif /* KERNEL_PLL */
1260 * Initialize frequency if given; otherwise, begin frequency
1261 * calibration phase.
1263 ftemp = init_drift_comp / 1e6;
1264 if (ftemp > NTP_MAXFREQ)
1265 ftemp = NTP_MAXFREQ;
1266 else if (ftemp < -NTP_MAXFREQ)
1267 ftemp = -NTP_MAXFREQ;
1270 rstclock(EVNT_FSET, 0);
1272 rstclock(EVNT_NSET, 0);
1273 loop_started = TRUE;
1274 #endif /* LOCKCLOCK */
1277 case LOOP_KERN_CLEAR:
1278 #if 0 /* XXX: needs more review, and how can we get here? */
1281 if (pll_control && kern_enable) {
1282 memset((char *)&ntv, 0, sizeof(ntv));
1283 ntv.modes = MOD_STATUS;
1284 ntv.status = STA_UNSYNC;
1286 sync_status("kernel time sync disabled",
1290 # endif /* KERNEL_PLL */
1291 #endif /* LOCKCLOCK */
1296 * Tinker command variables for Ulrich Windl. Very dangerous.
1298 case LOOP_ALLAN: /* Allan intercept (log2) (allan) */
1299 allan_xpt = (u_char)freq;
1302 case LOOP_CODEC: /* audio codec frequency (codec) */
1303 clock_codec = freq / 1e6;
1306 case LOOP_PHI: /* dispersion threshold (dispersion) */
1307 clock_phi = freq / 1e6;
1310 case LOOP_FREQ: /* initial frequency (freq) */
1311 init_drift_comp = freq;
1315 case LOOP_HUFFPUFF: /* huff-n'-puff length (huffpuff) */
1316 if (freq < HUFFPUFF)
1318 sys_hufflen = (int)(freq / HUFFPUFF);
1319 sys_huffpuff = emalloc(sizeof(sys_huffpuff[0]) *
1321 for (i = 0; i < sys_hufflen; i++)
1322 sys_huffpuff[i] = 1e9;
1326 case LOOP_PANIC: /* panic threshold (panic) */
1330 case LOOP_MAX: /* step threshold (step) */
1331 clock_max_fwd = clock_max_back = freq;
1332 if (freq == 0 || freq > 0.5)
1336 case LOOP_MAX_BACK: /* step threshold (step) */
1337 clock_max_back = freq;
1339 * Leave using the kernel discipline code unless both
1340 * limits are massive. This assumes the reason to stop
1341 * using it is that it's pointless, not that it goes wrong.
1343 if ( (clock_max_back == 0 || clock_max_back > 0.5)
1344 || (clock_max_fwd == 0 || clock_max_fwd > 0.5))
1348 case LOOP_MAX_FWD: /* step threshold (step) */
1349 clock_max_fwd = freq;
1350 if ( (clock_max_back == 0 || clock_max_back > 0.5)
1351 || (clock_max_fwd == 0 || clock_max_fwd > 0.5))
1355 case LOOP_MINSTEP: /* stepout threshold (stepout) */
1356 if (freq < CLOCK_MINSTEP)
1357 clock_minstep = CLOCK_MINSTEP;
1359 clock_minstep = freq;
1362 case LOOP_TICK: /* tick increment (tick) */
1363 set_sys_tick_precision(freq);
1366 case LOOP_LEAP: /* not used, fall through */
1369 "loop_config: unsupported option %d", item);
1374 #if defined(KERNEL_PLL) && defined(SIGSYS)
1376 * _trap - trap processor for undefined syscalls
1378 * This nugget is called by the kernel when the SYS_ntp_adjtime()
1379 * syscall bombs because the silly thing has not been implemented in
1380 * the kernel. In this case the phase-lock loop is emulated by
1381 * the stock adjtime() syscall and a lot of indelicate abuse.
1388 pll_control = FALSE;
1391 #endif /* KERNEL_PLL && SIGSYS */