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