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 */
251 switch (saved_errno) {
253 msyslog(LOG_ERR, "%s: %s line %d: invalid struct timex pointer: 0x%lx",
254 caller, file_name(), line,
255 (long)((void *)ptimex)
259 msyslog(LOG_ERR, "%s: %s line %d: invalid struct timex \"constant\" element value: %ld",
260 caller, file_name(), line,
261 (long)(ptimex->constant)
268 "%s: ntp_adjtime(TAI) failed: %m",
272 msyslog(LOG_ERR, "%s: %s line %d: ntp_adjtime: %m",
273 caller, file_name(), line
277 msyslog(LOG_NOTICE, "%s: %s line %d: unhandled errno value %d after failed ntp_adjtime call",
278 caller, file_name(), line,
285 case TIME_OK: /* 0: synchronized, no leap second warning */
286 /* msyslog(LOG_INFO, "kernel reports time is synchronized normally"); */
289 # warning TIME_OK is not defined
292 case TIME_INS: /* 1: positive leap second warning */
293 msyslog(LOG_INFO, "kernel reports leap second insertion scheduled");
296 # warning TIME_INS is not defined
299 case TIME_DEL: /* 2: negative leap second warning */
300 msyslog(LOG_INFO, "kernel reports leap second deletion scheduled");
303 # warning TIME_DEL is not defined
306 case TIME_OOP: /* 3: leap second in progress */
307 msyslog(LOG_INFO, "kernel reports leap second in progress");
310 # warning TIME_OOP is not defined
313 case TIME_WAIT: /* 4: leap second has occured */
314 msyslog(LOG_INFO, "kernel reports leap second has occurred");
317 # warning TIME_WAIT is not defined
320 case TIME_ERROR: /* 5: unsynchronized, or loss of synchronization */
321 /* error (see status word) */
322 if (pps_call && !(ptimex->status & STA_PPSSIGNAL))
323 report_event(EVNT_KERN, NULL,
326 DPRINTF(1, ("kernel loop status (%s) %d %m\n",
327 k_st_flags(ptimex->status), errno));
329 * This code may be returned when ntp_adjtime() has just
330 * been called for the first time, quite a while after
331 * startup, when ntpd just starts to discipline the kernel
332 * time. In this case the occurrence of this message
333 * can be pretty confusing.
335 * HMS: How about a message when we begin kernel processing:
336 * Determining kernel clock state...
337 * so an initial TIME_ERROR message is less confising,
338 * or skipping the first message (ugh),
340 * msyslog(LOG_INFO, "kernel reports time synchronization lost");
342 errno = saved_errno; /* may not be needed */
343 msyslog(LOG_INFO, "kernel reports TIME_ERROR: %#x: %s %m",
344 ptimex->status, k_st_flags(ptimex->status));
347 # warning TIME_ERROR is not defined
350 msyslog(LOG_NOTICE, "%s: %s line %d: unhandled return value %d from ntp_adjtime in %s at line %d",
351 caller, file_name(), line,
362 * local_clock - the NTP logical clock loop filter.
365 * -1 update ignored: exceeds panic threshold
366 * 0 update ignored: popcorn or exceeds step threshold
368 * 2 clock was stepped
370 * LOCKCLOCK: The only thing this routine does is set the
371 * sys_rootdisp variable equal to the peer dispersion.
375 struct peer *peer, /* synch source peer structure */
376 double fp_offset /* clock offset (s) */
379 int rval; /* return code */
380 int osys_poll; /* old system poll */
381 int ntp_adj_ret; /* returned by ntp_adjtime */
382 double mu; /* interval since last update */
383 double clock_frequency; /* clock frequency */
384 double dtemp, etemp; /* double temps */
385 char tbuf[80]; /* report buffer */
388 * If the loop is opened or the NIST LOCKCLOCK is in use,
389 * monitor and record the offsets anyway in order to determine
390 * the open-loop response and then go home.
396 #endif /* LOCKCLOCK */
397 record_loop_stats(fp_offset, drift_comp, clock_jitter,
398 clock_stability, sys_poll);
404 * If the clock is way off, panic is declared. The clock_panic
405 * defaults to 1000 s; if set to zero, the panic will never
406 * occur. The allow_panic defaults to FALSE, so the first panic
407 * will exit. It can be set TRUE by a command line option, in
408 * which case the clock will be set anyway and time marches on.
409 * But, allow_panic will be set FALSE when the update is less
410 * than the step threshold; so, subsequent panics will exit.
412 if (fabs(fp_offset) > clock_panic && clock_panic > 0 &&
414 snprintf(tbuf, sizeof(tbuf),
415 "%+.0f s; set clock manually within %.0f s.",
416 fp_offset, clock_panic);
417 report_event(EVNT_SYSFAULT, NULL, tbuf);
422 * This section simulates ntpdate. If the offset exceeds the
423 * step threshold (128 ms), step the clock to that time and
424 * exit. Otherwise, slew the clock to that time and exit. Note
425 * that the slew will persist and eventually complete beyond the
426 * life of this program. Note that while ntpdate is active, the
427 * terminal does not detach, so the termination message prints
428 * directly to the terminal.
431 if ( ( fp_offset > clock_max_fwd && clock_max_fwd > 0)
432 || (-fp_offset > clock_max_back && clock_max_back > 0)) {
433 step_systime(fp_offset);
434 msyslog(LOG_NOTICE, "ntpd: time set %+.6f s",
436 printf("ntpd: time set %+.6fs\n", fp_offset);
438 adj_systime(fp_offset);
439 msyslog(LOG_NOTICE, "ntpd: time slew %+.6f s",
441 printf("ntpd: time slew %+.6fs\n", fp_offset);
443 record_loop_stats(fp_offset, drift_comp, clock_jitter,
444 clock_stability, sys_poll);
449 * The huff-n'-puff filter finds the lowest delay in the recent
450 * interval. This is used to correct the offset by one-half the
451 * difference between the sample delay and minimum delay. This
452 * is most effective if the delays are highly assymetric and
453 * clockhopping is avoided and the clock frequency wander is
456 if (sys_huffpuff != NULL) {
457 if (peer->delay < sys_huffpuff[sys_huffptr])
458 sys_huffpuff[sys_huffptr] = peer->delay;
459 if (peer->delay < sys_mindly)
460 sys_mindly = peer->delay;
462 dtemp = -(peer->delay - sys_mindly) / 2;
464 dtemp = (peer->delay - sys_mindly) / 2;
469 "local_clock: size %d mindly %.6f huffpuff %.6f\n",
470 sys_hufflen, sys_mindly, dtemp);
475 * Clock state machine transition function which defines how the
476 * system reacts to large phase and frequency excursion. There
477 * are two main regimes: when the offset exceeds the step
478 * threshold (128 ms) and when it does not. Under certain
479 * conditions updates are suspended until the stepout theshold
480 * (900 s) is exceeded. See the documentation on how these
481 * thresholds interact with commands and command line options.
483 * Note the kernel is disabled if step is disabled or greater
484 * than 0.5 s or in ntpdate mode.
486 osys_poll = sys_poll;
487 if (sys_poll < peer->minpoll)
488 sys_poll = peer->minpoll;
489 if (sys_poll > peer->maxpoll)
490 sys_poll = peer->maxpoll;
491 mu = current_time - clock_epoch;
492 clock_frequency = drift_comp;
494 if ( ( fp_offset > clock_max_fwd && clock_max_fwd > 0)
495 || (-fp_offset > clock_max_back && clock_max_back > 0)
496 || force_step_once ) {
497 if (force_step_once) {
498 force_step_once = FALSE; /* we want this only once after startup */
499 msyslog(LOG_NOTICE, "Doing intital time step" );
505 * In SYNC state we ignore the first outlyer and switch
509 snprintf(tbuf, sizeof(tbuf), "%+.6f s",
511 report_event(EVNT_SPIK, NULL, tbuf);
516 * In FREQ state we ignore outlyers and inlyers. At the
517 * first outlyer after the stepout threshold, compute
518 * the apparent frequency correction and step the phase.
521 if (mu < clock_minstep)
524 clock_frequency = direct_freq(fp_offset);
526 /* fall through to EVNT_SPIK */
529 * In SPIK state we ignore succeeding outlyers until
530 * either an inlyer is found or the stepout threshold is
534 if (mu < clock_minstep)
537 /* fall through to default */
540 * We get here by default in NSET and FSET states and
541 * from above in FREQ or SPIK states.
543 * In NSET state an initial frequency correction is not
544 * available, usually because the frequency file has not
545 * yet been written. Since the time is outside the step
546 * threshold, the clock is stepped. The frequency will
547 * be set directly following the stepout interval.
549 * In FSET state the initial frequency has been set from
550 * the frequency file. Since the time is outside the
551 * step threshold, the clock is stepped immediately,
552 * rather than after the stepout interval. Guys get
553 * nervous if it takes 15 minutes to set the clock for
556 * In FREQ and SPIK states the stepout threshold has
557 * expired and the phase is still above the step
558 * threshold. Note that a single spike greater than the
559 * step threshold is always suppressed, even with a
560 * long time constant.
563 snprintf(tbuf, sizeof(tbuf), "%+.6f s",
565 report_event(EVNT_CLOCKRESET, NULL, tbuf);
566 step_systime(fp_offset);
569 clock_jitter = LOGTOD(sys_precision);
571 if (state == EVNT_NSET) {
572 rstclock(EVNT_FREQ, 0);
577 rstclock(EVNT_SYNC, 0);
580 * The offset is less than the step threshold. Calculate
581 * the jitter as the exponentially weighted offset
584 etemp = SQUARE(clock_jitter);
585 dtemp = SQUARE(max(fabs(fp_offset - last_offset),
586 LOGTOD(sys_precision)));
587 clock_jitter = SQRT(etemp + (dtemp - etemp) /
592 * In NSET state this is the first update received and
593 * the frequency has not been initialized. Adjust the
594 * phase, but do not adjust the frequency until after
595 * the stepout threshold.
598 adj_systime(fp_offset);
599 rstclock(EVNT_FREQ, fp_offset);
603 * In FREQ state ignore updates until the stepout
604 * threshold. After that, compute the new frequency, but
605 * do not adjust the frequency until the holdoff counter
606 * decrements to zero.
609 if (mu < clock_minstep)
612 clock_frequency = direct_freq(fp_offset);
616 * We get here by default in FSET, SPIK and SYNC states.
617 * Here compute the frequency update due to PLL and FLL
618 * contributions. Note, we avoid frequency discipline at
619 * startup until the initial transient has subsided.
626 * The FLL and PLL frequency gain constants
627 * depend on the time constant and Allan
628 * intercept. The PLL is always used, but
629 * becomes ineffective above the Allan intercept
630 * where the FLL becomes effective.
632 if (sys_poll >= allan_xpt)
633 clock_frequency += (fp_offset -
634 clock_offset) / max(ULOGTOD(sys_poll),
638 * The PLL frequency gain (numerator) depends on
639 * the minimum of the update interval and Allan
640 * intercept. This reduces the PLL gain when the
641 * FLL becomes effective.
643 etemp = min(ULOGTOD(allan_xpt), mu);
644 dtemp = 4 * CLOCK_PLL * ULOGTOD(sys_poll);
645 clock_frequency += fp_offset * etemp / (dtemp *
648 rstclock(EVNT_SYNC, fp_offset);
649 if (fabs(fp_offset) < CLOCK_FLOOR)
657 * This code segment works when clock adjustments are made using
658 * precision time kernel support and the ntp_adjtime() system
659 * call. This support is available in Solaris 2.6 and later,
660 * Digital Unix 4.0 and later, FreeBSD, Linux and specially
661 * modified kernels for HP-UX 9 and Ultrix 4. In the case of the
662 * DECstation 5000/240 and Alpha AXP, additional kernel
663 * modifications provide a true microsecond clock and nanosecond
664 * clock, respectively.
666 * Important note: The kernel discipline is used only if the
667 * step threshold is less than 0.5 s, as anything higher can
668 * lead to overflow problems. This might occur if some misguided
669 * lad set the step threshold to something ridiculous.
671 if (pll_control && kern_enable && freq_cnt == 0) {
674 * We initialize the structure for the ntp_adjtime()
675 * system call. We have to convert everything to
676 * microseconds or nanoseconds first. Do not update the
677 * system variables if the ext_enable flag is set. In
678 * this case, the external clock driver will update the
679 * variables, which will be read later by the local
680 * clock driver. Afterwards, remember the time and
681 * frequency offsets for jitter and stability values and
682 * to update the frequency file.
686 ntv.modes = MOD_STATUS;
689 ntv.modes = MOD_BITS | MOD_NANO;
691 ntv.modes = MOD_BITS;
692 #endif /* STA_NANO */
693 if (clock_offset < 0)
698 ntv.offset = (int32)(clock_offset * 1e9 +
700 ntv.constant = sys_poll;
702 ntv.offset = (int32)(clock_offset * 1e6 +
704 ntv.constant = sys_poll - 4;
705 #endif /* STA_NANO */
706 if (ntv.constant < 0)
709 ntv.esterror = (u_int32)(clock_jitter * 1e6);
710 ntv.maxerror = (u_int32)((sys_rootdelay / 2 +
711 sys_rootdisp) * 1e6);
712 ntv.status = STA_PLL;
715 * Enable/disable the PPS if requested.
717 if (hardpps_enable) {
718 ntv.status |= (STA_PPSTIME | STA_PPSFREQ);
719 if (!(pll_status & STA_PPSTIME))
720 sync_status("PPS enabled",
724 ntv.status &= ~(STA_PPSTIME | STA_PPSFREQ);
725 if (pll_status & STA_PPSTIME)
726 sync_status("PPS disabled",
730 if (sys_leap == LEAP_ADDSECOND)
731 ntv.status |= STA_INS;
732 else if (sys_leap == LEAP_DELSECOND)
733 ntv.status |= STA_DEL;
737 * Pass the stuff to the kernel. If it squeals, turn off
738 * the pps. In any case, fetch the kernel offset,
739 * frequency and jitter.
741 ntp_adj_ret = ntp_adjtime(&ntv);
743 * A squeal is a return status < 0, or a state change.
745 if ((0 > ntp_adj_ret) || (ntp_adj_ret != kernel_status)) {
746 kernel_status = ntp_adj_ret;
747 ntp_adjtime_error_handler(__func__, &ntv, ntp_adj_ret, errno, hardpps_enable, 0, __LINE__ - 1);
749 pll_status = ntv.status;
751 clock_offset = ntv.offset / 1e9;
753 clock_offset = ntv.offset / 1e6;
754 #endif /* STA_NANO */
755 clock_frequency = FREQTOD(ntv.freq);
758 * If the kernel PPS is lit, monitor its performance.
760 if (ntv.status & STA_PPSTIME) {
762 clock_jitter = ntv.jitter / 1e9;
764 clock_jitter = ntv.jitter / 1e6;
765 #endif /* STA_NANO */
768 #if defined(STA_NANO) && NTP_API == 4
770 * If the TAI changes, update the kernel TAI.
772 if (loop_tai != sys_tai) {
775 ntv.constant = sys_tai;
776 if ((ntp_adj_ret = ntp_adjtime(&ntv)) != 0) {
777 ntp_adjtime_error_handler(__func__, &ntv, ntp_adj_ret, errno, 0, 1, __LINE__ - 1);
780 #endif /* STA_NANO */
782 #endif /* KERNEL_PLL */
785 * Clamp the frequency within the tolerance range and calculate
786 * the frequency difference since the last update.
788 if (fabs(clock_frequency) > NTP_MAXFREQ)
790 "frequency error %.0f PPM exceeds tolerance %.0f PPM",
791 clock_frequency * 1e6, NTP_MAXFREQ * 1e6);
792 dtemp = SQUARE(clock_frequency - drift_comp);
793 if (clock_frequency > NTP_MAXFREQ)
794 drift_comp = NTP_MAXFREQ;
795 else if (clock_frequency < -NTP_MAXFREQ)
796 drift_comp = -NTP_MAXFREQ;
798 drift_comp = clock_frequency;
801 * Calculate the wander as the exponentially weighted RMS
802 * frequency differences. Record the change for the frequency
805 etemp = SQUARE(clock_stability);
806 clock_stability = SQRT(etemp + (dtemp - etemp) / CLOCK_AVG);
809 * Here we adjust the time constant by comparing the current
810 * offset with the clock jitter. If the offset is less than the
811 * clock jitter times a constant, then the averaging interval is
812 * increased, otherwise it is decreased. A bit of hysteresis
813 * helps calm the dance. Works best using burst mode. Don't
814 * fiddle with the poll during the startup clamp period.
818 } else if (fabs(clock_offset) < CLOCK_PGATE * clock_jitter) {
819 tc_counter += sys_poll;
820 if (tc_counter > CLOCK_LIMIT) {
821 tc_counter = CLOCK_LIMIT;
822 if (sys_poll < peer->maxpoll) {
828 tc_counter -= sys_poll << 1;
829 if (tc_counter < -CLOCK_LIMIT) {
830 tc_counter = -CLOCK_LIMIT;
831 if (sys_poll > peer->minpoll) {
839 * If the time constant has changed, update the poll variables.
841 if (osys_poll != sys_poll)
842 poll_update(peer, sys_poll);
845 * Yibbidy, yibbbidy, yibbidy; that'h all folks.
847 record_loop_stats(clock_offset, drift_comp, clock_jitter,
848 clock_stability, sys_poll);
852 "local_clock: offset %.9f jit %.9f freq %.3f stab %.3f poll %d\n",
853 clock_offset, clock_jitter, drift_comp * 1e6,
854 clock_stability * 1e6, sys_poll);
857 #endif /* LOCKCLOCK */
862 * adj_host_clock - Called once every second to update the local clock.
864 * LOCKCLOCK: The only thing this routine does is increment the
865 * sys_rootdisp variable.
876 * Update the dispersion since the last update. In contrast to
877 * NTPv3, NTPv4 does not declare unsynchronized after one day,
878 * since the dispersion check serves this function. Also,
879 * since the poll interval can exceed one day, the old test
880 * would be counterproductive. During the startup clamp period, the
881 * time constant is clamped at 2.
883 sys_rootdisp += clock_phi;
885 if (!ntp_enable || mode_ntpdate)
888 * Determine the phase adjustment. The gain factor (denominator)
889 * increases with poll interval, so is dominated by the FLL
890 * above the Allan intercept. Note the reduced time constant at
893 if (state != EVNT_SYNC) {
895 } else if (freq_cnt > 0) {
896 offset_adj = clock_offset / (CLOCK_PLL * ULOGTOD(1));
899 } else if (pll_control && kern_enable) {
901 #endif /* KERNEL_PLL */
903 offset_adj = clock_offset / (CLOCK_PLL * ULOGTOD(sys_poll));
907 * If the kernel discipline is enabled the frequency correction
908 * drift_comp has already been engaged via ntp_adjtime() in
909 * set_freq(). Otherwise it is a component of the adj_systime()
913 if (pll_control && kern_enable)
916 #endif /* KERNEL_PLL */
917 freq_adj = drift_comp;
919 /* Bound absolute value of total adjustment to NTP_MAXFREQ. */
920 if (offset_adj + freq_adj > NTP_MAXFREQ)
921 offset_adj = NTP_MAXFREQ - freq_adj;
922 else if (offset_adj + freq_adj < -NTP_MAXFREQ)
923 offset_adj = -NTP_MAXFREQ - freq_adj;
925 clock_offset -= offset_adj;
927 * Windows port adj_systime() must be called each second,
928 * even if the argument is zero, to ease emulation of
929 * adjtime() using Windows' slew API which controls the rate
930 * but does not automatically stop slewing when an offset
931 * has decayed to zero.
933 adj_systime(offset_adj + freq_adj);
934 #endif /* LOCKCLOCK */
939 * Clock state machine. Enter new state and set state variables.
943 int trans, /* new state */
944 double offset /* new offset */
949 printf("local_clock: mu %lu state %d poll %d count %d\n",
950 current_time - clock_epoch, trans, sys_poll,
953 if (trans != state && trans != EVNT_FSET)
954 report_event(trans, NULL, NULL);
956 last_offset = clock_offset = offset;
957 clock_epoch = current_time;
962 * calc_freq - calculate frequency directly
964 * This is very carefully done. When the offset is first computed at the
965 * first update, a residual frequency component results. Subsequently,
966 * updates are suppresed until the end of the measurement interval while
967 * the offset is amortized. At the end of the interval the frequency is
968 * calculated from the current offset, residual offset, length of the
969 * interval and residual frequency component. At the same time the
970 * frequenchy file is armed for update at the next hourly stats.
977 set_freq(fp_offset / (current_time - clock_epoch));
984 * set_freq - set clock frequency correction
986 * Used to step the frequency correction at startup, possibly again once
987 * the frequency is measured (that is, transitioning from EVNT_NSET to
988 * EVNT_FSET), and finally to switch between daemon and kernel loop
989 * discipline at runtime.
991 * When the kernel loop discipline is available but the daemon loop is
992 * in use, the kernel frequency correction is disabled (set to 0) to
993 * ensure drift_comp is applied by only one of the loops.
997 double freq /* frequency update */
1000 const char * loop_desc;
1008 ntv.modes = MOD_FREQUENCY;
1010 loop_desc = "kernel";
1011 ntv.freq = DTOFREQ(drift_comp);
1013 if ((ntp_adj_ret = ntp_adjtime(&ntv)) != 0) {
1014 ntp_adjtime_error_handler(__func__, &ntv, ntp_adj_ret, errno, 0, 0, __LINE__ - 1);
1017 #endif /* KERNEL_PLL */
1018 mprintf_event(EVNT_FSET, NULL, "%s %.3f PPM", loop_desc,
1025 start_kern_loop(void)
1027 static int atexit_done;
1032 ntv.modes = MOD_BITS;
1033 ntv.status = STA_PLL;
1034 ntv.maxerror = MAXDISPERSE;
1035 ntv.esterror = MAXDISPERSE;
1036 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? */
1039 * Use sigsetjmp() to save state and then call ntp_adjtime(); if
1040 * it fails, then pll_trap() will set pll_control FALSE before
1041 * returning control using siglogjmp().
1043 newsigsys.sa_handler = pll_trap;
1044 newsigsys.sa_flags = 0;
1045 if (sigaction(SIGSYS, &newsigsys, &sigsys)) {
1046 msyslog(LOG_ERR, "sigaction() trap SIGSYS: %m");
1047 pll_control = FALSE;
1049 if (sigsetjmp(env, 1) == 0) {
1050 if ((ntp_adj_ret = ntp_adjtime(&ntv)) != 0) {
1051 ntp_adjtime_error_handler(__func__, &ntv, ntp_adj_ret, errno, 0, 0, __LINE__ - 1);
1054 if (sigaction(SIGSYS, &sigsys, NULL)) {
1056 "sigaction() restore SIGSYS: %m");
1057 pll_control = FALSE;
1061 if ((ntp_adj_ret = ntp_adjtime(&ntv)) != 0) {
1062 ntp_adjtime_error_handler(__func__, &ntv, ntp_adj_ret, errno, 0, 0, __LINE__ - 1);
1067 * Save the result status and light up an external clock
1070 pll_status = ntv.status;
1074 atexit(&stop_kern_loop);
1077 if (pll_status & STA_CLK)
1079 #endif /* STA_NANO */
1080 report_event(EVNT_KERN, NULL,
1081 "kernel time sync enabled");
1084 #endif /* KERNEL_PLL */
1089 stop_kern_loop(void)
1091 if (pll_control && kern_enable)
1092 report_event(EVNT_KERN, NULL,
1093 "kernel time sync disabled");
1095 #endif /* KERNEL_PLL */
1099 * select_loop() - choose kernel or daemon loop discipline.
1106 if (kern_enable == use_kern_loop)
1109 if (pll_control && !use_kern_loop)
1112 kern_enable = use_kern_loop;
1114 if (pll_control && use_kern_loop)
1118 * If this loop selection change occurs after initial startup,
1119 * call set_freq() to switch the frequency compensation to or
1120 * from the kernel loop.
1123 if (pll_control && loop_started)
1124 set_freq(drift_comp);
1130 * huff-n'-puff filter
1137 if (sys_huffpuff == NULL)
1140 sys_huffptr = (sys_huffptr + 1) % sys_hufflen;
1141 sys_huffpuff[sys_huffptr] = 1e9;
1143 for (i = 0; i < sys_hufflen; i++) {
1144 if (sys_huffpuff[i] < sys_mindly)
1145 sys_mindly = sys_huffpuff[i];
1151 * loop_config - configure the loop filter
1153 * LOCKCLOCK: The LOOP_DRIFTINIT and LOOP_DRIFTCOMP cases are no-ops.
1166 printf("loop_config: item %d freq %f\n", item, freq);
1171 * We first assume the kernel supports the ntp_adjtime()
1172 * syscall. If that syscall works, initialize the kernel time
1173 * variables. Otherwise, continue leaving no harm behind.
1175 case LOOP_DRIFTINIT:
1182 #endif /* KERNEL_PLL */
1185 * Initialize frequency if given; otherwise, begin frequency
1186 * calibration phase.
1188 ftemp = init_drift_comp / 1e6;
1189 if (ftemp > NTP_MAXFREQ)
1190 ftemp = NTP_MAXFREQ;
1191 else if (ftemp < -NTP_MAXFREQ)
1192 ftemp = -NTP_MAXFREQ;
1195 rstclock(EVNT_FSET, 0);
1197 rstclock(EVNT_NSET, 0);
1198 loop_started = TRUE;
1199 #endif /* LOCKCLOCK */
1202 case LOOP_KERN_CLEAR:
1203 #if 0 /* XXX: needs more review, and how can we get here? */
1206 if (pll_control && kern_enable) {
1207 memset((char *)&ntv, 0, sizeof(ntv));
1208 ntv.modes = MOD_STATUS;
1209 ntv.status = STA_UNSYNC;
1211 sync_status("kernel time sync disabled",
1215 # endif /* KERNEL_PLL */
1216 #endif /* LOCKCLOCK */
1221 * Tinker command variables for Ulrich Windl. Very dangerous.
1223 case LOOP_ALLAN: /* Allan intercept (log2) (allan) */
1224 allan_xpt = (u_char)freq;
1227 case LOOP_CODEC: /* audio codec frequency (codec) */
1228 clock_codec = freq / 1e6;
1231 case LOOP_PHI: /* dispersion threshold (dispersion) */
1232 clock_phi = freq / 1e6;
1235 case LOOP_FREQ: /* initial frequency (freq) */
1236 init_drift_comp = freq;
1240 case LOOP_HUFFPUFF: /* huff-n'-puff length (huffpuff) */
1241 if (freq < HUFFPUFF)
1243 sys_hufflen = (int)(freq / HUFFPUFF);
1244 sys_huffpuff = emalloc(sizeof(sys_huffpuff[0]) *
1246 for (i = 0; i < sys_hufflen; i++)
1247 sys_huffpuff[i] = 1e9;
1251 case LOOP_PANIC: /* panic threshold (panic) */
1255 case LOOP_MAX: /* step threshold (step) */
1256 clock_max_fwd = clock_max_back = freq;
1257 if (freq == 0 || freq > 0.5)
1261 case LOOP_MAX_BACK: /* step threshold (step) */
1262 clock_max_back = freq;
1264 * Leave using the kernel discipline code unless both
1265 * limits are massive. This assumes the reason to stop
1266 * using it is that it's pointless, not that it goes wrong.
1268 if ( (clock_max_back == 0 || clock_max_back > 0.5)
1269 || (clock_max_fwd == 0 || clock_max_fwd > 0.5))
1273 case LOOP_MAX_FWD: /* step threshold (step) */
1274 clock_max_fwd = freq;
1275 if ( (clock_max_back == 0 || clock_max_back > 0.5)
1276 || (clock_max_fwd == 0 || clock_max_fwd > 0.5))
1280 case LOOP_MINSTEP: /* stepout threshold (stepout) */
1281 if (freq < CLOCK_MINSTEP)
1282 clock_minstep = CLOCK_MINSTEP;
1284 clock_minstep = freq;
1287 case LOOP_TICK: /* tick increment (tick) */
1288 set_sys_tick_precision(freq);
1291 case LOOP_LEAP: /* not used, fall through */
1294 "loop_config: unsupported option %d", item);
1299 #if defined(KERNEL_PLL) && defined(SIGSYS)
1301 * _trap - trap processor for undefined syscalls
1303 * This nugget is called by the kernel when the SYS_ntp_adjtime()
1304 * syscall bombs because the silly thing has not been implemented in
1305 * the kernel. In this case the phase-lock loop is emulated by
1306 * the stock adjtime() syscall and a lot of indelicate abuse.
1313 pll_control = FALSE;
1316 #endif /* KERNEL_PLL && SIGSYS */