2 * ntp_loopfilter.c - implements the NTP loop filter algorithm
4 * ATTENTION: Get approval from Dave Mills on all changes to this file!
13 #include "ntp_unixtime.h"
14 #include "ntp_stdlib.h"
22 #if defined(VMS) && defined(VMS_LOCALUNIT) /*wjm*/
23 #include "ntp_refclock.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 900. /* 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 (NTP_MAXPOLL + CLOCK_AVG) /* FLL loop gain */
44 #define CLOCK_ALLAN 1500. /* compromise Allan intercept (s) */
45 #define CLOCK_DAY 86400. /* one day in seconds (s) */
46 #define CLOCK_JUNE (CLOCK_DAY * 30) /* June in seconds (s) */
47 #define CLOCK_LIMIT 30 /* poll-adjust threshold */
48 #define CLOCK_PGATE 4. /* poll-adjust gate */
49 #define PPS_MAXAGE 120 /* kernel pps signal timeout (s) */
52 * Clock discipline state machine. This is used to control the
53 * synchronization behavior during initialization and following a
56 * State < step > step Comments
57 * ====================================================
58 * NSET FREQ step, FREQ no ntp.drift
60 * FSET SYNC step, SYNC ntp.drift
62 * FREQ if (mu < 900) if (mu < 900) set freq
65 * freq, SYNC freq, step, SYNC
67 * SYNC SYNC if (mu < 900) adjust phase/freq
72 * SPIK SYNC step, SYNC set phase
74 #define S_NSET 0 /* clock never set */
75 #define S_FSET 1 /* frequency set from the drift file */
76 #define S_SPIK 2 /* spike detected */
77 #define S_FREQ 3 /* frequency mode */
78 #define S_SYNC 4 /* clock synchronized */
81 * Kernel PLL/PPS state machine. This is used with the kernel PLL
82 * modifications described in the README.kernel file.
84 * If kernel support for the ntp_adjtime() system call is available, the
85 * ntp_control flag is set. The ntp_enable and kern_enable flags can be
86 * set at configuration time or run time using ntpdc. If ntp_enable is
87 * false, the discipline loop is unlocked and no corrections of any kind
88 * are made. If both ntp_control and kern_enable are set, the kernel
89 * support is used as described above; if false, the kernel is bypassed
90 * entirely and the daemon discipline used instead.
92 * There have been three versions of the kernel discipline code. The
93 * first (microkernel) now in Solaris discipilnes the microseconds. The
94 * second and third (nanokernel) disciplines the clock in nanoseconds.
95 * These versions are identifed if the symbol STA_PLL is present in the
96 * header file /usr/include/sys/timex.h. The third and current version
97 * includes TAI offset and is identified by the symbol NTP_API with
100 * Each update to a prefer peer sets pps_stratum if it survives the
101 * intersection algorithm and its time is within range. The PPS time
102 * discipline is enabled (STA_PPSTIME bit set in the status word) when
103 * pps_stratum is true and the PPS frequency discipline is enabled. If
104 * the PPS time discipline is enabled and the kernel reports a PPS
105 * signal is present, the pps_control variable is set to the current
106 * time. If the current time is later than pps_control by PPS_MAXAGE
107 * (120 s), this variable is set to zero.
109 * If an external clock is present, the clock driver sets STA_CLK in the
110 * status word. When the local clock driver sees this bit, it updates
111 * via this routine, which then calls ntp_adjtime() with the STA_PLL bit
112 * set to zero, in which case the system clock is not adjusted. This is
113 * also a signal for the external clock driver to discipline the system
117 * Program variables that can be tinkered.
119 double clock_max = CLOCK_MAX; /* step threshold (s) */
120 double clock_minstep = CLOCK_MINSTEP; /* stepout threshold (s) */
121 double clock_panic = CLOCK_PANIC; /* panic threshold (s) */
122 double clock_phi = CLOCK_PHI; /* dispersion rate (s/s) */
123 double allan_xpt = CLOCK_ALLAN; /* Allan intercept (s) */
128 static double clock_offset; /* offset (s) */
129 double clock_jitter; /* offset jitter (s) */
130 double drift_comp; /* frequency (s/s) */
131 double clock_stability; /* frequency stability (wander) (s/s) */
132 u_long sys_clocktime; /* last system clock update */
133 u_long pps_control; /* last pps update */
134 u_long sys_tai; /* UTC offset from TAI (s) */
135 static void rstclock P((int, u_long, double)); /* transition function */
138 struct timex ntv; /* kernel API parameters */
139 int pll_status; /* status bits for kernel pll */
140 #endif /* KERNEL_PLL */
143 * Clock state machine control flags
145 int ntp_enable; /* clock discipline enabled */
146 int pll_control; /* kernel support available */
147 int kern_enable; /* kernel support enabled */
148 int pps_enable; /* kernel PPS discipline enabled */
149 int ext_enable; /* external clock enabled */
150 int pps_stratum; /* pps stratum */
151 int allow_panic = FALSE; /* allow panic correction */
152 int mode_ntpdate = FALSE; /* exit on first clock set */
155 * Clock state machine variables
157 int state; /* clock discipline state */
158 u_char sys_poll = NTP_MINDPOLL; /* time constant/poll (log2 s) */
159 int tc_counter; /* jiggle counter */
160 double last_offset; /* last offset (s) */
163 * Huff-n'-puff filter variables
165 static double *sys_huffpuff; /* huff-n'-puff filter */
166 static int sys_hufflen; /* huff-n'-puff filter stages */
167 static int sys_huffptr; /* huff-n'-puff filter pointer */
168 static double sys_mindly; /* huff-n'-puff filter min delay */
170 #if defined(KERNEL_PLL)
171 /* Emacs cc-mode goes nuts if we split the next line... */
172 #define MOD_BITS (MOD_OFFSET | MOD_MAXERROR | MOD_ESTERROR | \
173 MOD_STATUS | MOD_TIMECONST)
175 static void pll_trap P((int)); /* configuration trap */
176 static struct sigaction sigsys; /* current sigaction status */
177 static struct sigaction newsigsys; /* new sigaction status */
178 static sigjmp_buf env; /* environment var. for pll_trap() */
180 #endif /* KERNEL_PLL */
183 * init_loopfilter - initialize loop filter data
186 init_loopfilter(void)
189 * Initialize state variables. Initially, we expect no drift
190 * file, so set the state to S_NSET. If a drift file is present,
191 * it will be detected later and the state set to S_FSET.
193 rstclock(S_NSET, 0, 0);
194 clock_jitter = LOGTOD(sys_precision);
198 * local_clock - the NTP logical clock loop filter.
201 * -1 update ignored: exceeds panic threshold
202 * 0 update ignored: popcorn or exceeds step threshold
204 * 2 clock was stepped
206 * LOCKCLOCK: The only thing this routine does is set the
207 * sys_rootdispersion variable equal to the peer dispersion.
211 struct peer *peer, /* synch source peer structure */
212 double fp_offset /* clock offset (s) */
215 int rval; /* return code */
216 u_long mu; /* interval since last update (s) */
217 double flladj; /* FLL frequency adjustment (ppm) */
218 double plladj; /* PLL frequency adjustment (ppm) */
219 double clock_frequency; /* clock frequency adjustment (ppm) */
220 double dtemp, etemp; /* double temps */
229 * If the loop is opened or the NIST LOCKCLOCK is in use,
230 * monitor and record the offsets anyway in order to determine
231 * the open-loop response and then go home.
236 "local_clock: assocID %d offset %.9f freq %.3f state %d\n",
237 peer->associd, fp_offset, drift_comp * 1e6, state);
242 #else /* LOCKCLOCK */
244 record_loop_stats(fp_offset, drift_comp, clock_jitter,
245 clock_stability, sys_poll);
250 * If the clock is way off, panic is declared. The clock_panic
251 * defaults to 1000 s; if set to zero, the panic will never
252 * occur. The allow_panic defaults to FALSE, so the first panic
253 * will exit. It can be set TRUE by a command line option, in
254 * which case the clock will be set anyway and time marches on.
255 * But, allow_panic will be set FALSE when the update is less
256 * than the step threshold; so, subsequent panics will exit.
258 if (fabs(fp_offset) > clock_panic && clock_panic > 0 &&
261 "time correction of %.0f seconds exceeds sanity limit (%.0f); set clock manually to the correct UTC time.",
262 fp_offset, clock_panic);
267 * If simulating ntpdate, set the clock directly, rather than
268 * using the discipline. The clock_max defines the step
269 * threshold, above which the clock will be stepped instead of
270 * slewed. The value defaults to 128 ms, but can be set to even
271 * unreasonable values. If set to zero, the clock will never be
272 * stepped. Note that a slew will persist beyond the life of
275 * Note that if ntpdate is active, the terminal does not detach,
276 * so the termination comments print directly to the console.
279 if (fabs(fp_offset) > clock_max && clock_max > 0) {
280 step_systime(fp_offset);
281 msyslog(LOG_NOTICE, "time reset %+.6f s",
283 printf("ntpd: time set %+.6fs\n", fp_offset);
285 adj_systime(fp_offset);
286 msyslog(LOG_NOTICE, "time slew %+.6f s",
288 printf("ntpd: time slew %+.6fs\n", fp_offset);
290 record_loop_stats(fp_offset, drift_comp, clock_jitter,
291 clock_stability, sys_poll);
296 * The huff-n'-puff filter finds the lowest delay in the recent
297 * interval. This is used to correct the offset by one-half the
298 * difference between the sample delay and minimum delay. This
299 * is most effective if the delays are highly assymetric and
300 * clockhopping is avoided and the clock frequency wander is
303 * Note either there is no prefer peer or this update is from
306 if (sys_huffpuff != NULL && (sys_prefer == NULL || sys_prefer ==
308 if (peer->delay < sys_huffpuff[sys_huffptr])
309 sys_huffpuff[sys_huffptr] = peer->delay;
310 if (peer->delay < sys_mindly)
311 sys_mindly = peer->delay;
313 dtemp = -(peer->delay - sys_mindly) / 2;
315 dtemp = (peer->delay - sys_mindly) / 2;
320 "local_clock: size %d mindly %.6f huffpuff %.6f\n",
321 sys_hufflen, sys_mindly, dtemp);
326 * Clock state machine transition function. This is where the
327 * action is and defines how the system reacts to large phase
328 * and frequency errors. There are two main regimes: when the
329 * offset exceeds the step threshold and when it does not.
330 * However, if the step threshold is set to zero, a step will
331 * never occur. See the instruction manual for the details how
332 * these actions interact with the command line options.
334 * Note the system poll is set to minpoll only if the clock is
335 * stepped. Note also the kernel is disabled if step is
336 * disabled or greater than 0.5 s.
338 clock_frequency = flladj = plladj = 0;
339 mu = peer->epoch - sys_clocktime;
340 if (clock_max == 0 || clock_max > 0.5)
343 if (fabs(fp_offset) > clock_max && clock_max > 0) {
347 * In S_SYNC state we ignore the first outlyer amd
348 * switch to S_SPIK state.
355 * In S_FREQ state we ignore outlyers and inlyers. At
356 * the first outlyer after the stepout threshold,
357 * compute the apparent frequency correction and step
361 if (mu < clock_minstep)
364 clock_frequency = (fp_offset - clock_offset) /
367 /* fall through to S_SPIK */
370 * In S_SPIK state we ignore succeeding outlyers until
371 * either an inlyer is found or the stepout threshold is
375 if (mu < clock_minstep)
378 /* fall through to default */
381 * We get here by default in S_NSET and S_FSET states
382 * and from above in S_FREQ or S_SPIK states.
384 * In S_NSET state an initial frequency correction is
385 * not available, usually because the frequency file has
386 * not yet been written. Since the time is outside the
387 * step threshold, the clock is stepped. The frequency
388 * will be set directly following the stepout interval.
390 * In S_FSET state the initial frequency has been set
391 * from the frequency file. Since the time is outside
392 * the step threshold, the clock is stepped immediately,
393 * rather than after the stepout interval. Guys get
394 * nervous if it takes 17 minutes to set the clock for
397 * In S_FREQ and S_SPIK states the stepout threshold has
398 * expired and the phase is still above the step
399 * threshold. Note that a single spike greater than the
400 * step threshold is always suppressed, even at the
401 * longer poll intervals.
404 step_systime(fp_offset);
405 msyslog(LOG_NOTICE, "time reset %+.6f s",
409 sys_poll = NTP_MINPOLL;
411 clock_jitter = LOGTOD(sys_precision);
413 if (state == S_NSET) {
414 rstclock(S_FREQ, peer->epoch, 0);
419 rstclock(S_SYNC, peer->epoch, 0);
423 * The offset is less than the step threshold. Calculate
424 * the jitter as the exponentially weighted offset
427 etemp = SQUARE(clock_jitter);
428 dtemp = SQUARE(max(fabs(fp_offset - last_offset),
429 LOGTOD(sys_precision)));
430 clock_jitter = SQRT(etemp + (dtemp - etemp) /
435 * In S_NSET state this is the first update received and
436 * the frequency has not been initialized. Adjust the
437 * phase, but do not adjust the frequency until after
438 * the stepout threshold.
441 rstclock(S_FREQ, peer->epoch, fp_offset);
445 * In S_FSET state this is the first update received and
446 * the frequency has been initialized. Adjust the phase,
447 * but do not adjust the frequency until the next
451 rstclock(S_SYNC, peer->epoch, fp_offset);
455 * In S_FREQ state ignore updates until the stepout
456 * threshold. After that, correct the phase and
457 * frequency and switch to S_SYNC state.
460 if (mu < clock_minstep)
463 clock_frequency = (fp_offset - clock_offset) /
465 rstclock(S_SYNC, peer->epoch, fp_offset);
469 * We get here by default in S_SYNC and S_SPIK states.
470 * Here we compute the frequency update due to PLL and
477 * The FLL and PLL frequency gain constants
478 * depend on the poll interval and Allan
479 * intercept. The PLL is always used, but
480 * becomes ineffective above the Allan
481 * intercept. The FLL is not used below one-half
482 * the Allan intercept. Above that the loop gain
483 * increases in steps to 1 / CLOCK_AVG.
485 if (ULOGTOD(sys_poll) > allan_xpt / 2) {
486 dtemp = CLOCK_FLL - sys_poll;
487 flladj = (fp_offset - clock_offset) /
488 (max(mu, allan_xpt) * dtemp);
492 * For the PLL the integration interval
493 * (numerator) is the minimum of the update
494 * interval and poll interval. This allows
495 * oversampling, but not undersampling.
497 etemp = min(mu, (u_long)ULOGTOD(sys_poll));
498 dtemp = 4 * CLOCK_PLL * ULOGTOD(sys_poll);
499 plladj = fp_offset * etemp / (dtemp * dtemp);
500 rstclock(S_SYNC, peer->epoch, fp_offset);
507 * Scan the loopsecond table to determine the TAI offset. If
508 * there is a scheduled leap in future, set the leap warning,
509 * but only if less than 30 days before the leap.
511 tpt = (u_int32 *)tai_leap.ptr;
512 len = ntohl(tai_leap.vallen) / sizeof(u_int32);
514 for (i = 0; i < len; i++) {
515 togo = (long)ntohl(tpt[i]) -
516 (long)peer->rec.l_ui;
518 if (togo < CLOCK_JUNE)
519 leap_next |= LEAP_ADDSECOND;
523 #if defined(STA_NANO) && NTP_API == 4
524 if (pll_control && kern_enable && sys_tai == 0) {
525 memset(&ntv, 0, sizeof(ntv));
527 ntv.constant = i + TAI_1972 - 1;
530 #endif /* STA_NANO */
531 sys_tai = i + TAI_1972 - 1;
536 * This code segment works when clock adjustments are made using
537 * precision time kernel support and the ntp_adjtime() system
538 * call. This support is available in Solaris 2.6 and later,
539 * Digital Unix 4.0 and later, FreeBSD, Linux and specially
540 * modified kernels for HP-UX 9 and Ultrix 4. In the case of the
541 * DECstation 5000/240 and Alpha AXP, additional kernel
542 * modifications provide a true microsecond clock and nanosecond
543 * clock, respectively.
545 * Important note: The kernel discipline is used only if the
546 * step threshold is less than 0.5 s, as anything higher can
547 * lead to overflow problems. This might occur if some misguided
548 * lad set the step threshold to something ridiculous.
550 if (pll_control && kern_enable) {
553 * We initialize the structure for the ntp_adjtime()
554 * system call. We have to convert everything to
555 * microseconds or nanoseconds first. Do not update the
556 * system variables if the ext_enable flag is set. In
557 * this case, the external clock driver will update the
558 * variables, which will be read later by the local
559 * clock driver. Afterwards, remember the time and
560 * frequency offsets for jitter and stability values and
561 * to update the frequency file.
563 memset(&ntv, 0, sizeof(ntv));
565 ntv.modes = MOD_STATUS;
567 struct tm *tm = NULL;
571 ntv.modes = MOD_BITS | MOD_NANO;
573 ntv.modes = MOD_BITS;
574 #endif /* STA_NANO */
575 if (clock_offset < 0)
580 ntv.offset = (int32)(clock_offset * 1e9 +
582 ntv.constant = sys_poll;
584 ntv.offset = (int32)(clock_offset * 1e6 +
586 ntv.constant = sys_poll - 4;
587 #endif /* STA_NANO */
590 * The frequency is set directly only if
591 * clock_frequency is nonzero coming out of FREQ
594 if (clock_frequency != 0) {
595 ntv.modes |= MOD_FREQUENCY;
596 ntv.freq = (int32)((clock_frequency +
597 drift_comp) * 65536e6);
599 ntv.esterror = (u_int32)(clock_jitter * 1e6);
600 ntv.maxerror = (u_int32)((sys_rootdelay / 2 +
601 sys_rootdispersion) * 1e6);
602 ntv.status = STA_PLL;
605 * Set the leap bits in the status word, but
606 * only on the last day of June or December.
608 tstamp = peer->rec.l_ui - JAN_1970;
609 tm = gmtime(&tstamp);
611 if ((tm->tm_mon + 1 == 6 &&
612 tm->tm_mday == 30) || (tm->tm_mon +
613 1 == 12 && tm->tm_mday == 31)) {
614 if (leap_next & LEAP_ADDSECOND)
615 ntv.status |= STA_INS;
618 ntv.status |= STA_DEL;
623 * If the PPS signal is up and enabled, light
624 * the frequency bit. If the PPS driver is
625 * working, light the phase bit as well. If not,
626 * douse the lights, since somebody else may
627 * have left the switch on.
629 if (pps_enable && pll_status & STA_PPSSIGNAL) {
630 ntv.status |= STA_PPSFREQ;
631 if (pps_stratum < STRATUM_UNSPEC)
632 ntv.status |= STA_PPSTIME;
634 ntv.status &= ~(STA_PPSFREQ |
640 * Pass the stuff to the kernel. If it squeals, turn off
641 * the pig. In any case, fetch the kernel offset and
642 * frequency and pretend we did it here.
644 if (ntp_adjtime(&ntv) == TIME_ERROR) {
645 NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
647 "kernel time sync error %04x", ntv.status);
648 ntv.status &= ~(STA_PPSFREQ | STA_PPSTIME);
650 pll_status = ntv.status;
652 clock_offset = ntv.offset / 1e9;
654 clock_offset = ntv.offset / 1e6;
655 #endif /* STA_NANO */
656 clock_frequency = ntv.freq / 65536e6;
660 * If the kernel PPS is lit, monitor its performance.
662 if (ntv.status & STA_PPSTIME) {
663 pps_control = current_time;
665 clock_jitter = ntv.jitter / 1e9;
667 clock_jitter = ntv.jitter / 1e6;
668 #endif /* STA_NANO */
671 #endif /* KERNEL_PLL */
674 * We get here if the kernel discipline is not enabled.
675 * Adjust the clock frequency as the sum of the directly
676 * computed frequency (if measured) and the PLL and FLL
679 clock_frequency = drift_comp + clock_frequency +
683 #endif /* KERNEL_PLL */
686 * Clamp the frequency within the tolerance range and calculate
687 * the frequency change since the last update.
689 if (fabs(clock_frequency) > NTP_MAXFREQ)
690 NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
692 "frequency error %.0f PPM exceeds tolerance %.0f PPM",
693 clock_frequency * 1e6, NTP_MAXFREQ * 1e6);
694 dtemp = SQUARE(clock_frequency - drift_comp);
695 if (clock_frequency > NTP_MAXFREQ)
696 drift_comp = NTP_MAXFREQ;
697 else if (clock_frequency < -NTP_MAXFREQ)
698 drift_comp = -NTP_MAXFREQ;
700 drift_comp = clock_frequency;
703 * Calculate the wander as the exponentially weighted frequency
706 etemp = SQUARE(clock_stability);
707 clock_stability = SQRT(etemp + (dtemp - etemp) / CLOCK_AVG);
710 * Here we adjust the poll interval by comparing the current
711 * offset with the clock jitter. If the offset is less than the
712 * clock jitter times a constant, then the averaging interval is
713 * increased, otherwise it is decreased. A bit of hysteresis
714 * helps calm the dance. Works best using burst mode.
716 if (fabs(clock_offset) < CLOCK_PGATE * clock_jitter) {
717 tc_counter += sys_poll;
718 if (tc_counter > CLOCK_LIMIT) {
719 tc_counter = CLOCK_LIMIT;
720 if (sys_poll < peer->maxpoll) {
726 tc_counter -= sys_poll << 1;
727 if (tc_counter < -CLOCK_LIMIT) {
728 tc_counter = -CLOCK_LIMIT;
729 if (sys_poll > peer->minpoll) {
737 * Yibbidy, yibbbidy, yibbidy; that'h all folks.
739 record_loop_stats(clock_offset, drift_comp, clock_jitter,
740 clock_stability, sys_poll);
744 "local_clock: mu %lu jitr %.6f freq %.3f stab %.6f poll %d count %d\n",
745 mu, clock_jitter, drift_comp * 1e6,
746 clock_stability * 1e6, sys_poll, tc_counter);
749 #endif /* LOCKCLOCK */
754 * adj_host_clock - Called once every second to update the local clock.
756 * LOCKCLOCK: The only thing this routine does is increment the
757 * sys_rootdispersion variable.
767 * Update the dispersion since the last update. In contrast to
768 * NTPv3, NTPv4 does not declare unsynchronized after one day,
769 * since the dispersion check serves this function. Also,
770 * since the poll interval can exceed one day, the old test
771 * would be counterproductive. Note we do this even with
772 * external clocks, since the clock driver will recompute the
773 * maximum error and the local clock driver will pick it up and
774 * pass to the common refclock routines. Very elegant.
776 sys_rootdispersion += clock_phi;
780 * If clock discipline is disabled or if the kernel is enabled,
781 * get out of Dodge quick.
783 if (!ntp_enable || mode_ntpdate || (pll_control &&
788 * Declare PPS kernel unsync if the pps signal has not been
789 * heard for a few minutes.
791 if (pps_control && current_time - pps_control > PPS_MAXAGE) {
793 NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
794 msyslog(LOG_NOTICE, "pps sync disabled");
799 * Implement the phase and frequency adjustments. The gain
800 * factor (denominator) is not allowed to increase beyond the
801 * Allan intercept. It doesn't make sense to average phase noise
802 * beyond this point and it helps to damp residual offset at the
803 * longer poll intervals.
805 adjustment = clock_offset / (CLOCK_PLL * min(ULOGTOD(sys_poll),
807 clock_offset -= adjustment;
808 adj_systime(adjustment + drift_comp);
809 #endif /* LOCKCLOCK */
814 * Clock state machine. Enter new state and set state variables. Note we
815 * use the time of the last clock filter sample, which may be earlier
816 * than the current time.
820 int trans, /* new state */
821 u_long update, /* new update time */
822 double offset /* new offset */
827 printf("local_clock: time %lu offset %.6f freq %.3f state %d\n",
828 update, offset, drift_comp * 1e6, trans);
831 sys_clocktime = update;
832 last_offset = clock_offset = offset;
837 * huff-n'-puff filter
844 if (sys_huffpuff == NULL)
847 sys_huffptr = (sys_huffptr + 1) % sys_hufflen;
848 sys_huffpuff[sys_huffptr] = 1e9;
850 for (i = 0; i < sys_hufflen; i++) {
851 if (sys_huffpuff[i] < sys_mindly)
852 sys_mindly = sys_huffpuff[i];
858 * loop_config - configure the loop filter
860 * LOCKCLOCK: The LOOP_DRIFTINIT and LOOP_DRIFTCOMP cases are no-ops.
877 * Assume the kernel supports the ntp_adjtime() syscall.
878 * If that syscall works, initialize the kernel time
879 * variables. Otherwise, continue leaving no harm
880 * behind. While at it, ask to set nanosecond mode. If
881 * the kernel agrees, rejoice; othewise, it does only
888 memset(&ntv, 0, sizeof(ntv));
890 ntv.modes = MOD_BITS | MOD_NANO;
892 ntv.modes = MOD_BITS;
893 #endif /* STA_NANO */
894 ntv.maxerror = MAXDISPERSE;
895 ntv.esterror = MAXDISPERSE;
896 ntv.status = STA_UNSYNC;
899 * Use sigsetjmp() to save state and then call
900 * ntp_adjtime(); if it fails, then siglongjmp() is used
903 newsigsys.sa_handler = pll_trap;
904 newsigsys.sa_flags = 0;
905 if (sigaction(SIGSYS, &newsigsys, &sigsys)) {
907 "sigaction() fails to save SIGSYS trap: %m");
910 if (sigsetjmp(env, 1) == 0)
912 if ((sigaction(SIGSYS, &sigsys,
913 (struct sigaction *)NULL))) {
915 "sigaction() fails to restore SIGSYS trap: %m");
923 * Save the result status and light up an external clock
926 pll_status = ntv.status;
929 if (pll_status & STA_CLK)
931 #endif /* STA_NANO */
932 NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
934 "kernel time sync status %04x",
937 #endif /* KERNEL_PLL */
938 #endif /* LOCKCLOCK */
945 * If the frequency value is reasonable, set the initial
946 * frequency to the given value and the state to S_FSET.
947 * Otherwise, the drift file may be missing or broken,
948 * so set the frequency to zero. This erases past
949 * history should somebody break something.
951 if (freq <= NTP_MAXFREQ && freq >= -NTP_MAXFREQ) {
953 rstclock(S_FSET, 0, 0);
960 * Sanity check. If the kernel is available, load the
961 * frequency and light up the loop. Make sure the offset
962 * is zero to cancel any previous nonsense. If you don't
963 * want this initialization, remove the ntp.drift file.
965 if (pll_control && kern_enable) {
966 memset((char *)&ntv, 0, sizeof(ntv));
967 ntv.modes = MOD_OFFSET | MOD_FREQUENCY;
968 ntv.freq = (int32)(drift_comp * 65536e6);
971 #endif /* KERNEL_PLL */
972 #endif /* LOCKCLOCK */
975 case LOOP_KERN_CLEAR:
978 /* Completely turn off the kernel time adjustments. */
980 memset((char *)&ntv, 0, sizeof(ntv));
981 ntv.modes = MOD_BITS | MOD_OFFSET | MOD_FREQUENCY;
982 ntv.status = STA_UNSYNC;
984 NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
986 "kernel time sync disabled %04x",
989 #endif /* KERNEL_PLL */
990 #endif /* LOCKCLOCK */
994 * Special tinker variables for Ulrich Windl. Very dangerous.
996 case LOOP_MAX: /* step threshold */
1000 case LOOP_PANIC: /* panic threshold */
1004 case LOOP_PHI: /* dispersion rate */
1008 case LOOP_MINSTEP: /* watchdog bark */
1009 clock_minstep = freq;
1012 case LOOP_ALLAN: /* Allan intercept */
1016 case LOOP_HUFFPUFF: /* huff-n'-puff filter length */
1017 if (freq < HUFFPUFF)
1019 sys_hufflen = (int)(freq / HUFFPUFF);
1020 sys_huffpuff = (double *)emalloc(sizeof(double) *
1022 for (i = 0; i < sys_hufflen; i++)
1023 sys_huffpuff[i] = 1e9;
1027 case LOOP_FREQ: /* initial frequency */
1028 drift_comp = freq / 1e6;
1029 rstclock(S_FSET, 0, 0);
1035 #if defined(KERNEL_PLL) && defined(SIGSYS)
1037 * _trap - trap processor for undefined syscalls
1039 * This nugget is called by the kernel when the SYS_ntp_adjtime()
1040 * syscall bombs because the silly thing has not been implemented in
1041 * the kernel. In this case the phase-lock loop is emulated by
1042 * the stock adjtime() syscall and a lot of indelicate abuse.
1052 #endif /* KERNEL_PLL && SIGSYS */