Initial import from FreeBSD RELENG_4:
[dragonfly.git] / contrib / ntp / ntpd / ntp_loopfilter.c
1 /*
2  * ntp_loopfilter.c - implements the NTP loop filter algorithm
3  *
4  */
5 #ifdef HAVE_CONFIG_H
6 # include <config.h>
7 #endif
8
9 #include "ntpd.h"
10 #include "ntp_io.h"
11 #include "ntp_unixtime.h"
12 #include "ntp_stdlib.h"
13
14 #include <stdio.h>
15 #include <ctype.h>
16
17 #include <signal.h>
18 #include <setjmp.h>
19
20 #if defined(VMS) && defined(VMS_LOCALUNIT)      /*wjm*/
21 #include "ntp_refclock.h"
22 #endif /* VMS */
23
24 #ifdef KERNEL_PLL
25 #include "ntp_syscall.h"
26 #endif /* KERNEL_PLL */
27
28 /*
29  * This is an implementation of the clock discipline algorithm described
30  * in UDel TR 97-4-3, as amended. It operates as an adaptive parameter,
31  * hybrid phase/frequency-lock loop. A number of sanity checks are
32  * included to protect against timewarps, timespikes and general mayhem.
33  * All units are in s and s/s, unless noted otherwise.
34  */
35 #define CLOCK_MAX       .128    /* default max offset (s) */
36 #define CLOCK_PANIC     1000.   /* default panic offset (s) */
37 #define CLOCK_MAXSTAB   2e-6    /* max frequency stability (s/s) */
38 #define CLOCK_MAXERR    1e-2    /* max phase jitter (s) */
39 #define CLOCK_PHI       15e-6   /* max frequency error (s/s) */
40 #define SHIFT_PLL       4       /* PLL loop gain (shift) */
41 #define CLOCK_AVG       4.      /* FLL loop gain */
42 #define CLOCK_MINSEC    256.    /* min FLL update interval (s) */
43 #define CLOCK_MINSTEP   900.    /* step-change timeout (s) */
44 #define CLOCK_DAY       86400.  /* one day of seconds */
45 #define CLOCK_LIMIT     30      /* poll-adjust threshold */
46 #define CLOCK_PGATE     4.      /* poll-adjust gate */
47 #define CLOCK_ALLAN     1024.   /* min Allan intercept (s) */
48 #define CLOCK_ADF       1e11    /* Allan deviation factor */
49
50 /*
51  * Clock discipline state machine. This is used to control the
52  * synchronization behavior during initialization and following a
53  * timewarp.
54  *
55  *      State   < max   > max                   Comments
56  *      ====================================================
57  *      NSET    FREQ    FREQ                    no ntp.drift
58  *
59  *      FSET    TSET    if (allow) TSET,        ntp.drift
60  *                      else FREQ
61  *
62  *      TSET    SYNC    FREQ                    time set
63  *
64  *      FREQ    SYNC    if (mu < 900) FREQ      calculate frequency
65  *                      else if (allow) TSET
66  *                      else FREQ
67  *
68  *      SYNC    SYNC    if (mu < 900) SYNC      normal state
69  *                      else SPIK
70  *
71  *      SPIK    SYNC    if (allow) TSET         spike detector
72  *                      else FREQ
73  */
74 #define S_NSET  0               /* clock never set */
75 #define S_FSET  1               /* frequency set from the drift file */
76 #define S_TSET  2               /* time set */
77 #define S_FREQ  3               /* frequency mode */
78 #define S_SYNC  4               /* clock synchronized */
79 #define S_SPIK  5               /* spike detected */
80
81 /*
82  * Kernel PLL/PPS state machine. This is used with the kernel PLL
83  * modifications described in the README.kernel file.
84  *
85  * If kernel support for the ntp_adjtime() system call is available, the
86  * ntp_control flag is set. The ntp_enable and kern_enable flags can be
87  * set at configuration time or run time using ntpdc. If ntp_enable is
88  * false, the discipline loop is unlocked and no correctios of any kind
89  * are made. If both ntp_control and kern_enable are set, the kernel
90  * support is used as described above; if false, the kernel is bypassed
91  * entirely and the daemon PLL used instead.
92  *
93  * Each update to a prefer peer sets pps_stratum if it survives the
94  * intersection algorithm and its time is within range. The PPS time
95  * discipline is enabled (STA_PPSTIME bit set in the status word) when
96  * pps_stratum is true and the PPS frequency discipline is enabled. If
97  * the PPS time discipline is enabled and the kernel reports a PPS
98  * signal is present, the pps_control variable is set to the current
99  * time. If the current time is later than pps_control by PPS_MAXAGE
100  * (120 s), this variable is set to zero.
101  *
102  * If an external clock is present, the clock driver sets STA_CLK in the
103  * status word. When the local clock driver sees this bit, it updates
104  * via this routine, which then calls ntp_adjtime() with the STA_PLL bit
105  * set to zero, in which case the system clock is not adjusted. This is
106  * also a signal for the external clock driver to discipline the system
107  * clock.
108  */
109 #define PPS_MAXAGE 120          /* kernel pps signal timeout (s) */
110
111 /*
112  * Program variables that can be tinkered.
113  */
114 double  clock_max = CLOCK_MAX;  /* max offset before step (s) */
115 double  clock_panic = CLOCK_PANIC; /* max offset before panic (s) */
116 double  clock_phi = CLOCK_PHI;  /* dispersion rate (s/s) */
117 double  clock_minstep = CLOCK_MINSTEP; /* step timeout (s) */
118 double  allan_xpt = CLOCK_ALLAN; /* minimum Allan intercept (s) */
119
120 /*
121  * Program variables
122  */
123 static double clock_offset;     /* clock offset adjustment (s) */
124 double  drift_comp;             /* clock frequency (s/s) */
125 double  clock_stability;        /* clock stability (s/s) */
126 u_long  pps_control;            /* last pps sample time */
127 static void rstclock P((int, double, double)); /* transition function */
128
129 #ifdef KERNEL_PLL
130 struct timex ntv;               /* kernel API parameters */
131 int     pll_status;             /* status bits for kernel pll */
132 int     pll_nano;               /* nanosecond kernel switch */
133 #endif /* KERNEL_PLL */
134
135 /*
136  * Clock state machine control flags
137  */
138 int     ntp_enable;             /* clock discipline enabled */
139 int     pll_control;            /* kernel support available */
140 int     kern_enable;            /* kernel support enabled */
141 int     pps_enable;             /* kernel PPS discipline enabled */
142 int     ext_enable;             /* external clock enabled */
143 int     pps_stratum;            /* pps stratum */
144 int     allow_step = TRUE;      /* allow step correction */
145 int     allow_panic = FALSE;    /* allow panic correction */
146 int     mode_ntpdate = FALSE;   /* exit on first clock set */
147
148 /*
149  * Clock state machine variables
150  */
151 u_char  sys_minpoll = NTP_MINDPOLL; /* min sys poll interval (log2 s) */
152 u_char  sys_poll = NTP_MINDPOLL; /* system poll interval (log2 s) */
153 int     state;                  /* clock discipline state */
154 int     tc_counter;             /* poll-adjust counter */
155 u_long  last_time;              /* time of last clock update (s) */
156 double  last_offset;            /* last clock offset (s) */
157 double  sys_jitter;             /* system RMS jitter (s) */
158
159 /*
160  * Huff-n'-puff filter variables
161  */
162 static double *sys_huffpuff;    /* huff-n'-puff filter */
163 static int sys_hufflen;         /* huff-n'-puff filter stages */
164 static int sys_huffptr;         /* huff-n'-puff filter pointer */
165 static double sys_mindly;       /* huff-n'-puff filter min delay */
166
167 #if defined(KERNEL_PLL)
168 /* Emacs cc-mode goes nuts if we split the next line... */
169 #define MOD_BITS (MOD_OFFSET | MOD_MAXERROR | MOD_ESTERROR | \
170     MOD_STATUS | MOD_TIMECONST)
171 #ifdef SIGSYS
172 static void pll_trap P((int));  /* configuration trap */
173 static struct sigaction sigsys; /* current sigaction status */
174 static struct sigaction newsigsys; /* new sigaction status */
175 static sigjmp_buf env;          /* environment var. for pll_trap() */
176 #endif /* SIGSYS */
177 #endif /* KERNEL_PLL */
178
179 /*
180  * init_loopfilter - initialize loop filter data
181  */
182 void
183 init_loopfilter(void)
184 {
185         /*
186          * Initialize state variables. Initially, we expect no drift
187          * file, so set the state to S_NSET.
188          */
189         rstclock(S_NSET, current_time, 0);
190 }
191
192 /*
193  * local_clock - the NTP logical clock loop filter. Returns 1 if the
194  * clock was stepped, 0 if it was slewed and -1 if it is hopeless.
195  */
196 int
197 local_clock(
198         struct peer *peer,      /* synch source peer structure */
199         double fp_offset,       /* clock offset (s) */
200         double epsil            /* jittter (square s*s) */
201         )
202 {
203         double mu;              /* interval since last update (s) */
204         double oerror;          /* previous error estimate */
205         double flladj;          /* FLL frequency adjustment (ppm) */
206         double plladj;          /* PLL frequency adjustment (ppm) */
207         double clock_frequency; /* clock frequency adjustment (ppm) */
208         double dtemp, etemp;    /* double temps */
209         int retval;             /* return value */
210
211         /*
212          * If the loop is opened, monitor and record the offsets
213          * anyway in order to determine the open-loop response.
214          */
215 #ifdef DEBUG
216         if (debug)
217                 printf(
218                     "local_clock: assocID %d off %.6f jit %.6f sta %d\n",
219                     peer->associd, fp_offset, SQRT(epsil), state);
220 #endif
221         if (!ntp_enable) {
222                 record_loop_stats(fp_offset, drift_comp, SQRT(epsil),
223                     clock_stability, sys_poll);
224                 return (0);
225         }
226
227         /*
228          * If the clock is way off, panic is declared. The clock_panic
229          * defaults to 1000 s; if set to zero, the panic will never
230          * occur. The allow_panic defaults to FALSE, so the first panic
231          * will exit. It can be set TRUE by a command line option, in
232          * which case the clock will be set anyway and time marches on.
233          * But, allow_panic will be set it FALSE when the update is
234          * within the step range; so, subsequent panics will exit.
235          */
236         if (fabs(fp_offset) > clock_panic && clock_panic > 0 &&
237             !allow_panic) {
238                 msyslog(LOG_ERR,
239                     "time correction of %.0f seconds exceeds sanity limit (%.0f); set clock manually to the correct UTC time.",
240                     fp_offset, clock_panic);
241                 return (-1);
242         }
243
244         /*
245          * If simulating ntpdate, set the clock directly, rather than
246          * using the discipline. The clock_max defines the step
247          * threshold, above which the clock will be stepped instead of
248          * slewed. The value defaults to 128 ms, but can be set to even
249          * unreasonable values. If set to zero, the clock will never be
250          * stepped.
251          *
252          * Note that if ntpdate is active, the terminal does not detach,
253          * so the termination comments print directly to the console.
254          */
255         if (mode_ntpdate) {
256                 if (allow_step && fabs(fp_offset) > clock_max &&
257                     clock_max > 0) {
258                         step_systime(fp_offset);
259                         NLOG(NLOG_SYNCEVENT|NLOG_SYSEVENT)
260                             msyslog(LOG_NOTICE, "time reset %.6f s",
261                             fp_offset);
262                         printf("ntpd: time reset %.6fs\n", fp_offset);
263                 } else {
264                         adj_systime(fp_offset);
265                         NLOG(NLOG_SYNCEVENT|NLOG_SYSEVENT)
266                             msyslog(LOG_NOTICE, "time slew %.6f s",
267                             fp_offset);
268                         printf("ntpd: time slew %.6fs\n", fp_offset);
269                 }
270                 record_loop_stats(fp_offset, drift_comp, SQRT(epsil),
271                     clock_stability, sys_poll);
272                 exit (0);
273         }
274
275         /*
276          * If the clock has never been set, set it and initialize the
277          * discipline parameters. We then switch to frequency mode to
278          * speed the inital convergence process. If lucky, after an hour
279          * the ntp.drift file is created and initialized and we don't
280          * get here again.
281          */
282         if (state == S_NSET) {
283                 step_systime(fp_offset);
284                 NLOG(NLOG_SYNCEVENT|NLOG_SYSEVENT)
285                     msyslog(LOG_NOTICE, "time set %.6f s", fp_offset);
286                 rstclock(S_FREQ, peer->epoch, fp_offset);
287                 return (1);
288         }
289
290         /*
291          * Update the jitter estimate.
292          */
293         oerror = sys_jitter;
294         dtemp = SQUARE(sys_jitter);
295         sys_jitter = SQRT(dtemp + (epsil - dtemp) / CLOCK_AVG);
296
297         /*
298          * The huff-n'-puff filter finds the lowest delay in the recent
299          * interval. This is used to correct the offset by one-half the
300          * difference between the sample delay and minimum delay. This
301          * is most effective if the delays are highly assymetric and
302          * clockhopping is avoided and the clock frequency wander is
303          * relatively small.
304          */
305         if (sys_huffpuff != NULL) {
306                 if (peer->delay < sys_huffpuff[sys_huffptr])
307                         sys_huffpuff[sys_huffptr] = peer->delay;
308                 if (peer->delay < sys_mindly)
309                         sys_mindly = peer->delay;
310                 if (fp_offset > 0)
311                         dtemp = -(peer->delay - sys_mindly) / 2;
312                 else
313                         dtemp = (peer->delay - sys_mindly) / 2;
314                 fp_offset += dtemp;
315 #ifdef DEBUG
316                 if (debug)
317                         printf(
318                     "local_clock: size %d mindly %.6f huffpuff %.6f\n",
319                             sys_hufflen, sys_mindly, dtemp);
320 #endif
321         }
322
323         /*
324          * Clock state machine transition function. This is where the
325          * action is and defines how the system reacts to large phase
326          * and frequency errors. There are two main regimes: when the
327          * offset exceeds the step threshold and when it does not.
328          * However, if the step threshold is set to zero, a step will
329          * never occur. See the instruction manual for the details how
330          * these actions interact with the command line options.
331          */
332         retval = 0;
333         if (sys_poll > peer->maxpoll)
334                 sys_poll = peer->maxpoll;
335         else if (sys_poll < peer->minpoll)
336                 sys_poll = peer->minpoll;
337         clock_frequency = flladj = plladj = 0;
338         mu = peer->epoch - last_time;
339         if (fabs(fp_offset) > clock_max && clock_max > 0) {
340                 switch (state) {
341
342                 /*
343                  * In S_TSET state the time has been set at the last
344                  * valid update and the offset at that time set to zero.
345                  * If following that we cruise outside the capture
346                  * range, assume a really bad frequency error and switch
347                  * to S_FREQ state.
348                  */
349                 case S_TSET:
350                         state = S_FREQ;
351                         break;
352
353                 /*
354                  * In S_SYNC state we ignore outlyers. At the first
355                  * outlyer after the stepout threshold, switch to S_SPIK
356                  * state.
357                  */
358                 case S_SYNC:
359                         if (mu < clock_minstep)
360                                 return (0);
361                         state = S_SPIK;
362                         return (0);
363
364                 /*
365                  * In S_FREQ state we ignore outlyers. At the first
366                  * outlyer after 900 s, compute the apparent phase and
367                  * frequency correction.
368                  */
369                 case S_FREQ:
370                         if (mu < clock_minstep)
371                                 return (0);
372                         /* fall through to S_SPIK */
373
374                 /*
375                  * In S_SPIK state a large correction is necessary.
376                  * Since the outlyer may be due to a large frequency
377                  * error, compute the apparent frequency correction.
378                  */
379                 case S_SPIK:
380                         clock_frequency = (fp_offset - clock_offset) /
381                             mu;
382                         /* fall through to default */
383
384                 /*
385                  * We get here directly in S_FSET state and indirectly
386                  * from S_FREQ and S_SPIK states. The clock is either
387                  * reset or shaken, but never stirred.
388                  */
389                 default:
390                         if (allow_step) {
391                                 step_systime(fp_offset);
392                                 NLOG(NLOG_SYNCEVENT|NLOG_SYSEVENT)
393                                     msyslog(LOG_NOTICE, "time reset %.6f s",
394                                     fp_offset);
395                                 rstclock(S_TSET, peer->epoch, 0);
396                                 retval = 1;
397                         } else {
398                                 NLOG(NLOG_SYNCEVENT|NLOG_SYSEVENT)
399                                     msyslog(LOG_NOTICE, "time slew %.6f s",
400                                     fp_offset);
401                                 rstclock(S_FREQ, peer->epoch,
402                                     fp_offset);
403                         }
404                         break;
405                 }
406         } else {
407                 switch (state) {
408
409                 /*
410                  * In S_FSET state this is the first update. Adjust the
411                  * phase, but don't adjust the frequency until the next
412                  * update.
413                  */
414                 case S_FSET:
415                         rstclock(S_TSET, peer->epoch, fp_offset);
416                         break;
417
418                 /*
419                  * In S_FREQ state ignore updates until the stepout
420                  * threshold. After that, correct the phase and
421                  * frequency and switch to S_SYNC state.
422                  */
423                 case S_FREQ:
424                         if (mu < clock_minstep)
425                                 return (0);
426                         clock_frequency = (fp_offset - clock_offset) /
427                             mu;
428                         rstclock(S_SYNC, peer->epoch, fp_offset);
429                         break;
430
431                 /*
432                  * Either the clock has just been set or the previous
433                  * update was a spike and ignored. Since this update is
434                  * not an outlyer, fold the tent and resume life.
435                  */
436                 case S_TSET:
437                 case S_SPIK:
438                         state = S_SYNC;
439                         /* fall through to default */
440
441                 /*
442                  * We come here in the normal case for linear phase and
443                  * frequency adjustments. If the offset exceeds the
444                  * previous time error estimate by CLOCK_SGATE and the
445                  * interval since the last update is less than twice the
446                  * poll interval, consider the update a popcorn spike
447                  * and ignore it.
448                  */
449                 default:
450                         allow_panic = TRUE;
451                         if (fabs(fp_offset - last_offset) >
452                             CLOCK_SGATE * oerror && mu <
453                             ULOGTOD(sys_poll + 1)) {
454 #ifdef DEBUG
455                                 if (debug)
456                                         printf(
457                                     "local_clock: popcorn %.6f %.6f\n",
458                                             fabs(fp_offset -
459                                             last_offset), CLOCK_SGATE *
460                                             oerror);
461 #endif
462                                 last_offset = fp_offset;
463                                 return (0);
464                         }
465
466                         /*
467                          * Compute the FLL and PLL frequency adjustments
468                          * conditioned on intricate weighting factors.
469                          * For the FLL, the averaging interval is
470                          * clamped to a minimum of 1024 s and the gain
471                          * is decreased from unity for mu above 1024 s
472                          * to zero below 256 s. For the PLL, the
473                          * averaging interval is clamped not to exceed
474                          * the sustem poll interval. No gain factor is
475                          * necessary, since the frequency steering above
476                          * 1024 s is negligible. Particularly for the
477                          * PLL, these measures allow oversampling, but
478                          * not undersampling and insure stability even
479                          * when the rules of fair engagement are broken.
480                          */
481                         dtemp = max(mu, allan_xpt);
482                         etemp = min(max(0, mu - CLOCK_MINSEC) /
483                             allan_xpt, 1.);
484                         flladj = fp_offset * etemp / (dtemp *
485                             CLOCK_AVG);
486                         dtemp = ULOGTOD(SHIFT_PLL + 2 + sys_poll);
487                         etemp = min(mu, ULOGTOD(sys_poll));
488                         plladj = fp_offset * etemp / (dtemp * dtemp);
489                         last_time = peer->epoch;
490                         last_offset = clock_offset = fp_offset;
491                         break;
492                 }
493         }
494
495 #if defined(KERNEL_PLL)
496         /*
497          * This code segment works when clock adjustments are made using
498          * precision time kernel support and the ntp_adjtime() system
499          * call. This support is available in Solaris 2.6 and later,
500          * Digital Unix 4.0 and later, FreeBSD, Linux and specially
501          * modified kernels for HP-UX 9 and Ultrix 4. In the case of the
502          * DECstation 5000/240 and Alpha AXP, additional kernel
503          * modifications provide a true microsecond clock and nanosecond
504          * clock, respectively.
505          */
506         if (pll_control && kern_enable) {
507
508                 /*
509                  * We initialize the structure for the ntp_adjtime()
510                  * system call. We have to convert everything to
511                  * microseconds or nanoseconds first. Do not update the
512                  * system variables if the ext_enable flag is set. In
513                  * this case, the external clock driver will update the
514                  * variables, which will be read later by the local
515                  * clock driver. Afterwards, remember the time and
516                  * frequency offsets for jitter and stability values and
517                  * to update the drift file.
518                  */
519                 memset(&ntv,  0, sizeof(ntv));
520                 if (ext_enable) {
521                         ntv.modes = MOD_STATUS;
522                 } else {
523                         ntv.modes = MOD_BITS;
524                         if (clock_offset < 0)
525                                 dtemp = -.5;
526                         else
527                                 dtemp = .5;
528                         if (pll_nano) {
529                                 ntv.offset = (int32)(clock_offset *
530                                     1e9 + dtemp);
531                                 ntv.constant = sys_poll;
532                         } else {
533                                 ntv.offset = (int32)(clock_offset *
534                                     1e6 + dtemp);
535                                 ntv.constant = sys_poll - 4;
536                         }
537                         if (clock_frequency != 0) {
538                                 ntv.modes |= MOD_FREQUENCY;
539                                 ntv.freq = (int32)((clock_frequency +
540                                     drift_comp) * 65536e6);
541                         }
542                         ntv.esterror = (u_int32)(sys_jitter * 1e6);
543                         ntv.maxerror = (u_int32)((sys_rootdelay / 2 +
544                             sys_rootdispersion) * 1e6);
545                         ntv.status = STA_PLL;
546
547                         /*
548                          * Set the leap bits in the status word.
549                          */
550                         if (sys_leap == LEAP_NOTINSYNC) {
551                                 ntv.status |= STA_UNSYNC;
552                         } else if (calleapwhen(sys_reftime.l_ui) <
553                                     CLOCK_DAY) {
554                                 if (sys_leap & LEAP_ADDSECOND)
555                                         ntv.status |= STA_INS;
556                                 else if (sys_leap & LEAP_DELSECOND)
557                                         ntv.status |= STA_DEL;
558                         }
559
560                         /*
561                          * Switch to FLL mode if the poll interval is
562                          * greater than MAXDPOLL, so that the kernel
563                          * loop behaves as the daemon loop; viz.,
564                          * selects the FLL when necessary, etc. For
565                          * legacy only.
566                          */
567                         if (sys_poll > NTP_MAXDPOLL)
568                                 ntv.status |= STA_FLL;
569
570                         /*
571                          * If the PPS signal is up and enabled, light
572                          * the frequency bit. If the PPS driver is
573                          * working, light the phase bit as well. If not,
574                          * douse the lights, since somebody else may
575                          * have left the switch on.
576                          */
577                         if (pps_enable && pll_status & STA_PPSSIGNAL) {
578                                 ntv.status |= STA_PPSFREQ;
579                                 if (pps_stratum < STRATUM_UNSPEC)
580                                         ntv.status |= STA_PPSTIME;
581                         } else {
582                                 ntv.status &= ~(STA_PPSFREQ |
583                                     STA_PPSTIME);
584                         }
585                 }
586
587                 /*
588                  * Pass the stuff to the kernel. If it squeals, turn off
589                  * the pigs. In any case, fetch the kernel offset and
590                  * frequency and pretend we did it here.
591                  */
592                 if (ntp_adjtime(&ntv) == TIME_ERROR) {
593                         if (ntv.status != pll_status)
594                                 msyslog(LOG_ERR,
595                                     "kernel time discipline status change %x",
596                                     ntv.status);
597                         ntv.status &= ~(STA_PPSFREQ | STA_PPSTIME);
598                 }
599                 pll_status = ntv.status;
600                 if (pll_nano)
601                         clock_offset = ntv.offset / 1e9;
602                 else
603                         clock_offset = ntv.offset / 1e6;
604                 clock_frequency = ntv.freq / 65536e6 - drift_comp;
605                 flladj = plladj = 0;
606
607                 /*
608                  * If the kernel PPS is lit, monitor its performance.
609                  */
610                 if (ntv.status & STA_PPSTIME) {
611                         pps_control = current_time;
612                         if (pll_nano)
613                                 sys_jitter = ntv.jitter / 1e9;
614                         else
615                                 sys_jitter = ntv.jitter / 1e6;
616                 }
617         }
618 #endif /* KERNEL_PLL */
619  
620         /*
621          * Adjust the clock frequency and calculate the stability. If
622          * kernel support is available, we use the results of the kernel
623          * discipline instead of the PLL/FLL discipline. In this case,
624          * drift_comp is a sham and used only for updating the drift
625          * file and for billboard eye candy.
626          */
627         etemp = clock_frequency + flladj + plladj;
628         drift_comp += etemp;
629         if (drift_comp > NTP_MAXFREQ)
630                 drift_comp = NTP_MAXFREQ;
631         else if (drift_comp <= -NTP_MAXFREQ)
632                 drift_comp = -NTP_MAXFREQ;
633         dtemp = SQUARE(clock_stability);
634         etemp = SQUARE(etemp) - dtemp;
635         clock_stability = SQRT(dtemp + etemp / CLOCK_AVG);
636
637         /*
638          * In SYNC state, adjust the poll interval. The trick here is to
639          * compare the apparent frequency change induced by the system
640          * jitter over the poll interval, or fritter, to the frequency
641          * stability. If the fritter is greater than the stability,
642          * phase noise predominates and the averaging interval is
643          * increased; otherwise, it is decreased. A bit of hysteresis
644          * helps calm the dance. Works best using burst mode.
645          */
646         if (state == S_SYNC) {
647                 if (sys_jitter / ULOGTOD(sys_poll) > clock_stability &&
648                     fabs(clock_offset) < CLOCK_PGATE * sys_jitter) {
649                         tc_counter += sys_poll;
650                         if (tc_counter > CLOCK_LIMIT) {
651                                 tc_counter = CLOCK_LIMIT;
652                                 if (sys_poll < peer->maxpoll) {
653                                         tc_counter = 0;
654                                         sys_poll++;
655                                 }
656                         }
657                 } else {
658                         tc_counter -= sys_poll << 1;
659                         if (tc_counter < -CLOCK_LIMIT) {
660                                 tc_counter = -CLOCK_LIMIT;
661                                 if (sys_poll > peer->minpoll) {
662                                         tc_counter = 0;
663                                         sys_poll--;
664                                 }
665                         }
666                 }
667         }
668
669         /*
670          * Update the system time variables.
671          */
672         dtemp = peer->disp + sys_jitter;
673         if ((peer->flags & FLAG_REFCLOCK) == 0 && dtemp < MINDISPERSE)
674                 dtemp = MINDISPERSE;
675         sys_rootdispersion = peer->rootdispersion + dtemp;
676         record_loop_stats(last_offset, drift_comp, sys_jitter,
677             clock_stability, sys_poll);
678 #ifdef DEBUG
679         if (debug)
680                 printf(
681                     "local_clock: mu %.0f noi %.3f stb %.3f pol %d cnt %d\n",
682                     mu, sys_jitter * 1e6 / mu, clock_stability * 1e6,
683                     sys_poll, tc_counter);
684 #endif /* DEBUG */
685         return (retval);
686 }
687
688
689 /*
690  * adj_host_clock - Called once every second to update the local clock.
691  */
692 void
693 adj_host_clock(
694         void
695         )
696 {
697         double adjustment;
698
699         /*
700          * Update the dispersion since the last update. In contrast to
701          * NTPv3, NTPv4 does not declare unsynchronized after one day,
702          * since the dispersion check serves this function. Also,
703          * since the poll interval can exceed one day, the old test
704          * would be counterproductive. Note we do this even with
705          * external clocks, since the clock driver will recompute the
706          * maximum error and the local clock driver will pick it up and
707          * pass to the common refclock routines. Very elegant.
708          */
709         sys_rootdispersion += clock_phi;
710
711         /*
712          * Declare PPS kernel unsync if the pps signal has not been
713          * heard for a few minutes.
714          */
715         if (pps_control && current_time - pps_control > PPS_MAXAGE) {
716                 if (pps_control)
717                         NLOG(NLOG_SYSEVENT) /* conditional if clause */
718                             msyslog(LOG_INFO, "pps sync disabled");
719                 pps_control = 0;
720         }
721         if (!ntp_enable)
722                 return;
723
724         /*
725          * If the phase-lock loop is implemented in the kernel, we
726          * have no business going further.
727          */
728         if (pll_control && kern_enable)
729                 return;
730
731         /*
732          * Intricate wrinkle for legacy only. If the local clock driver
733          * is in use and selected for synchronization, somebody else may
734          * tinker the adjtime() syscall. If this is the case, the driver
735          * is marked prefer and we have to avoid calling adjtime(),
736          * since that may truncate the other guy's requests.
737          */
738         if (sys_peer != 0) {
739                 if (sys_peer->refclktype == REFCLK_LOCALCLOCK &&
740                     sys_peer->flags & FLAG_PREFER)
741                         return;
742         }
743         adjustment = clock_offset / ULOGTOD(SHIFT_PLL + sys_poll);
744         clock_offset -= adjustment;
745         adj_systime(adjustment + drift_comp);
746 }
747
748
749 /*
750  * Clock state machine. Enter new state and set state variables.
751  */
752 static void
753 rstclock(
754         int trans,              /* new state */
755         double epoch,           /* last time */
756         double offset           /* last offset */
757         )
758 {
759         tc_counter = 0;
760         sys_poll = NTP_MINPOLL;
761         state = trans;
762         last_time = epoch;
763         last_offset = clock_offset = offset;
764 }
765
766
767 /*
768  * huff-n'-puff filter
769  */
770 void
771 huffpuff()
772 {
773         int i;
774
775         if (sys_huffpuff == NULL)
776                 return;
777         sys_huffptr = (sys_huffptr + 1) % sys_hufflen;
778         sys_huffpuff[sys_huffptr] = 1e9;
779         sys_mindly = 1e9;
780         for (i = 0; i < sys_hufflen; i++) {
781                 if (sys_huffpuff[i] < sys_mindly)
782                         sys_mindly = sys_huffpuff[i];
783         }
784 }
785
786
787 /*
788  * loop_config - configure the loop filter
789  */
790 void
791 loop_config(
792         int item,
793         double freq
794         )
795 {
796         int i;
797
798         switch (item) {
799
800         case LOOP_DRIFTINIT:
801
802 #ifdef KERNEL_PLL
803                 /*
804                  * Assume the kernel supports the ntp_adjtime() syscall.
805                  * If that syscall works, initialize the kernel
806                  * variables. Otherwise, continue leaving no harm
807                  * behind. While at it, ask to set nanosecond mode. If
808                  * the kernel agrees, rejoice; othewise, it does only
809                  * microseconds.
810                  */
811                 pll_control = 1;
812                 memset(&ntv, 0, sizeof(ntv));
813 #ifdef STA_NANO
814                 ntv.modes = MOD_BITS | MOD_NANO;
815 #else
816                 ntv.modes = MOD_BITS;
817 #endif /* STA_NANO */
818                 ntv.maxerror = MAXDISPERSE;
819                 ntv.esterror = MAXDISPERSE;
820                 ntv.status = STA_UNSYNC;
821 #ifdef SIGSYS
822                 /*
823                  * Use sigsetjmp() to save state and then call
824                  * ntp_adjtime(); if it fails, then siglongjmp() is used
825                  * to return control
826                  */
827                 newsigsys.sa_handler = pll_trap;
828                 newsigsys.sa_flags = 0;
829                 if (sigaction(SIGSYS, &newsigsys, &sigsys)) {
830                         msyslog(LOG_ERR,
831                             "sigaction() fails to save SIGSYS trap: %m");
832                         pll_control = 0;
833                 }
834                 if (sigsetjmp(env, 1) == 0)
835                         ntp_adjtime(&ntv);
836                 if ((sigaction(SIGSYS, &sigsys,
837                     (struct sigaction *)NULL))) {
838                         msyslog(LOG_ERR,
839                             "sigaction() fails to restore SIGSYS trap: %m");
840                         pll_control = 0;
841                 }
842 #else /* SIGSYS */
843                 ntp_adjtime(&ntv);
844 #endif /* SIGSYS */
845                 pll_status = ntv.status;
846                 if (pll_control) {
847 #ifdef STA_NANO
848                         if (pll_status & STA_NANO)
849                                 pll_nano = 1;
850                         if (pll_status & STA_CLK)
851                                 ext_enable = 1;
852 #endif /* STA_NANO */
853                         msyslog(LOG_NOTICE,
854                            "kernel time discipline status %04x",
855                             pll_status);
856                 }
857 #endif /* KERNEL_PLL */
858                 break;
859
860         case LOOP_DRIFTCOMP:
861
862                 /*
863                  * Initialize the kernel frequency and clamp to
864                  * reasonable value. Also set the initial state to
865                  * S_FSET to indicated the frequency has been
866                  * initialized from the previously saved drift file.
867                  */
868                 rstclock(S_FSET, current_time, 0);
869                 drift_comp = freq;
870                 if (drift_comp > NTP_MAXFREQ)
871                         drift_comp = NTP_MAXFREQ;
872                 if (drift_comp < -NTP_MAXFREQ)
873                         drift_comp = -NTP_MAXFREQ;
874
875 #ifdef KERNEL_PLL
876                 /*
877                  * Sanity check. If the kernel is enabled, load the
878                  * frequency and light up the loop. If not, set the
879                  * kernel frequency to zero and leave the loop dark. In
880                  * either case set the time to zero to cancel any
881                  * previous nonsense.
882                  */
883                 if (pll_control) {
884                         memset((char *)&ntv, 0, sizeof(ntv));
885                         ntv.modes = MOD_OFFSET | MOD_FREQUENCY;
886                         if (kern_enable) {
887                                 ntv.modes |= MOD_STATUS;
888                                 ntv.status = STA_PLL;
889                                 ntv.freq = (int32)(drift_comp *
890                                     65536e6);
891                         }
892                         (void)ntp_adjtime(&ntv);
893                 }
894 #endif /* KERNEL_PLL */
895                 break;
896
897         /*
898          * Special tinker variables for Ulrich Windl. Very dangerous.
899          */
900         case LOOP_MAX:                  /* step threshold */
901                 clock_max = freq;
902                 break;
903
904         case LOOP_PANIC:                /* panic exit threshold */
905                 clock_panic = freq;
906                 break;
907
908         case LOOP_PHI:                  /* dispersion rate */
909                 clock_phi = freq;
910                 break;
911
912         case LOOP_MINSTEP:              /* watchdog bark */
913                 clock_minstep = freq; 
914                 break;
915
916         case LOOP_MINPOLL:              /* ephemeral association poll */
917                 if (freq < NTP_MINPOLL)
918                         freq = NTP_MINPOLL;
919                 sys_minpoll = (u_char)freq;
920                 break;
921
922         case LOOP_ALLAN:                /* minimum Allan intercept */
923                 if (freq < CLOCK_ALLAN)
924                         freq = CLOCK_ALLAN;
925                 allan_xpt = freq;
926                 break;
927         
928         case LOOP_HUFFPUFF:             /* huff-n'-puff filter length */
929                 if (freq < HUFFPUFF)
930                         freq = HUFFPUFF;
931                 sys_hufflen = (int)(freq / HUFFPUFF);
932                 sys_huffpuff = (double *)emalloc(sizeof(double) *
933                     sys_hufflen);
934                 for (i = 0; i < sys_hufflen; i++)
935                         sys_huffpuff[i] = 1e9;
936                 sys_mindly = 1e9;
937                 break;
938         }
939 }
940
941
942 #if defined(KERNEL_PLL) && defined(SIGSYS)
943 /*
944  * _trap - trap processor for undefined syscalls
945  *
946  * This nugget is called by the kernel when the SYS_ntp_adjtime()
947  * syscall bombs because the silly thing has not been implemented in
948  * the kernel. In this case the phase-lock loop is emulated by
949  * the stock adjtime() syscall and a lot of indelicate abuse.
950  */
951 static RETSIGTYPE
952 pll_trap(
953         int arg
954         )
955 {
956         pll_control = 0;
957         siglongjmp(env, 1);
958 }
959 #endif /* KERNEL_PLL && SIGSYS */