xref: /freebsd/contrib/ntp/ntpd/ntp_loopfilter.c (revision 9034852c)
1 /*
2  * ntp_loopfilter.c - implements the NTP loop filter algorithm
3  *
4  * ATTENTION: Get approval from Dave Mills on all changes to this file!
5  *
6  */
7 #ifdef HAVE_CONFIG_H
8 # include <config.h>
9 #endif
10 
11 #ifdef USE_SNPRINTB
12 # include <util.h>
13 #endif
14 #include "ntpd.h"
15 #include "ntp_io.h"
16 #include "ntp_unixtime.h"
17 #include "ntp_stdlib.h"
18 
19 #include <limits.h>
20 #include <stdio.h>
21 #include <ctype.h>
22 
23 #include <signal.h>
24 #include <setjmp.h>
25 
26 #ifdef KERNEL_PLL
27 #include "ntp_syscall.h"
28 #endif /* KERNEL_PLL */
29 
30 /*
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.
36  */
37 #define CLOCK_MAX	.128	/* default step threshold (s) */
38 #define CLOCK_MINSTEP	300.	/* default stepout threshold (s) */
39 #define CLOCK_PANIC	1000.	/* default panic threshold (s) */
40 #define	CLOCK_PHI	15e-6	/* max frequency error (s/s) */
41 #define CLOCK_PLL	16.	/* PLL loop gain (log2) */
42 #define CLOCK_AVG	8.	/* parameter averaging constant */
43 #define CLOCK_FLL	.25	/* FLL loop gain */
44 #define	CLOCK_FLOOR	.0005	/* startup offset floor (s) */
45 #define	CLOCK_ALLAN	11	/* Allan intercept (log2 s) */
46 #define CLOCK_LIMIT	30	/* poll-adjust threshold */
47 #define CLOCK_PGATE	4.	/* poll-adjust gate */
48 #define PPS_MAXAGE	120	/* kernel pps signal timeout (s) */
49 #define	FREQTOD(x)	((x) / 65536e6) /* NTP to double */
50 #define	DTOFREQ(x)	((int32)((x) * 65536e6)) /* double to NTP */
51 
52 /*
53  * Clock discipline state machine. This is used to control the
54  * synchronization behavior during initialization and following a
55  * timewarp.
56  *
57  *	State	< step		> step		Comments
58  *	========================================================
59  *	NSET	FREQ		step, FREQ	freq not set
60  *
61  *	FSET	SYNC		step, SYNC	freq set
62  *
63  *	FREQ	if (mu < 900)	if (mu < 900)	set freq direct
64  *		    ignore	    ignore
65  *		else		else
66  *		    freq, SYNC	    freq, step, SYNC
67  *
68  *	SYNC	SYNC		SPIK, ignore	adjust phase/freq
69  *
70  *	SPIK	SYNC		if (mu < 900)	adjust phase/freq
71  *				    ignore
72  *				step, SYNC
73  */
74 /*
75  * Kernel PLL/PPS state machine. This is used with the kernel PLL
76  * modifications described in the documentation.
77  *
78  * If kernel support for the ntp_adjtime() system call is available, the
79  * ntp_control flag is set. The ntp_enable and kern_enable flags can be
80  * set at configuration time or run time using ntpdc. If ntp_enable is
81  * false, the discipline loop is unlocked and no corrections of any kind
82  * are made. If both ntp_control and kern_enable are set, the kernel
83  * support is used as described above; if false, the kernel is bypassed
84  * entirely and the daemon discipline used instead.
85  *
86  * There have been three versions of the kernel discipline code. The
87  * first (microkernel) now in Solaris discipilnes the microseconds. The
88  * second and third (nanokernel) disciplines the clock in nanoseconds.
89  * These versions are identifed if the symbol STA_PLL is present in the
90  * header file /usr/include/sys/timex.h. The third and current version
91  * includes TAI offset and is identified by the symbol NTP_API with
92  * value 4.
93  *
94  * Each PPS time/frequency discipline can be enabled by the atom driver
95  * or another driver. If enabled, the STA_PPSTIME and STA_FREQ bits are
96  * set in the kernel status word; otherwise, these bits are cleared.
97  * These bits are also cleard if the kernel reports an error.
98  *
99  * If an external clock is present, the clock driver sets STA_CLK in the
100  * status word. When the local clock driver sees this bit, it updates
101  * via this routine, which then calls ntp_adjtime() with the STA_PLL bit
102  * set to zero, in which case the system clock is not adjusted. This is
103  * also a signal for the external clock driver to discipline the system
104  * clock. Unless specified otherwise, all times are in seconds.
105  */
106 /*
107  * Program variables that can be tinkered.
108  */
109 double	clock_max_back = CLOCK_MAX;	/* step threshold */
110 double	clock_max_fwd =  CLOCK_MAX;	/* step threshold */
111 double	clock_minstep = CLOCK_MINSTEP; /* stepout threshold */
112 double	clock_panic = CLOCK_PANIC; /* panic threshold */
113 double	clock_phi = CLOCK_PHI;	/* dispersion rate (s/s) */
114 u_char	allan_xpt = CLOCK_ALLAN; /* Allan intercept (log2 s) */
115 
116 /*
117  * Program variables
118  */
119 static double clock_offset;	/* offset */
120 double	clock_jitter;		/* offset jitter */
121 double	drift_comp;		/* frequency (s/s) */
122 static double init_drift_comp; /* initial frequency (PPM) */
123 double	clock_stability;	/* frequency stability (wander) (s/s) */
124 double	clock_codec;		/* audio codec frequency (samples/s) */
125 static u_long clock_epoch;	/* last update */
126 u_int	sys_tai;		/* TAI offset from UTC */
127 static int loop_started;	/* TRUE after LOOP_DRIFTINIT */
128 static void rstclock (int, double); /* transition function */
129 static double direct_freq(double); /* direct set frequency */
130 static void set_freq(double);	/* set frequency */
131 #ifndef PATH_MAX
132 # define PATH_MAX MAX_PATH
133 #endif
134 static char relative_path[PATH_MAX + 1]; /* relative path per recursive make */
135 static char *this_file = NULL;
136 
137 #ifdef KERNEL_PLL
138 static struct timex ntv;	/* ntp_adjtime() parameters */
139 int	pll_status;		/* last kernel status bits */
140 #if defined(STA_NANO) && NTP_API == 4
141 static u_int loop_tai;		/* last TAI offset */
142 #endif /* STA_NANO */
143 static	void	start_kern_loop(void);
144 static	void	stop_kern_loop(void);
145 #endif /* KERNEL_PLL */
146 
147 /*
148  * Clock state machine control flags
149  */
150 int	ntp_enable = TRUE;	/* clock discipline enabled */
151 int	pll_control;		/* kernel support available */
152 int	kern_enable = TRUE;	/* kernel support enabled */
153 int	hardpps_enable;		/* kernel PPS discipline enabled */
154 int	ext_enable;		/* external clock enabled */
155 int	pps_stratum;		/* pps stratum */
156 int	kernel_status;		/* from ntp_adjtime */
157 int	allow_panic = FALSE;	/* allow panic correction (-g) */
158 int	force_step_once = FALSE; /* always step time once at startup (-G) */
159 int	mode_ntpdate = FALSE;	/* exit on first clock set (-q) */
160 int	freq_cnt;		/* initial frequency clamp */
161 int	freq_set;		/* initial set frequency switch */
162 
163 /*
164  * Clock state machine variables
165  */
166 int	state = 0;		/* clock discipline state */
167 u_char	sys_poll;		/* time constant/poll (log2 s) */
168 int	tc_counter;		/* jiggle counter */
169 double	last_offset;		/* last offset (s) */
170 
171 /*
172  * Huff-n'-puff filter variables
173  */
174 static double *sys_huffpuff;	/* huff-n'-puff filter */
175 static int sys_hufflen;		/* huff-n'-puff filter stages */
176 static int sys_huffptr;		/* huff-n'-puff filter pointer */
177 static double sys_mindly;	/* huff-n'-puff filter min delay */
178 
179 #if defined(KERNEL_PLL)
180 /* Emacs cc-mode goes nuts if we split the next line... */
181 #define MOD_BITS (MOD_OFFSET | MOD_MAXERROR | MOD_ESTERROR | \
182     MOD_STATUS | MOD_TIMECONST)
183 #ifdef SIGSYS
184 static void pll_trap (int);	/* configuration trap */
185 static struct sigaction sigsys;	/* current sigaction status */
186 static struct sigaction newsigsys; /* new sigaction status */
187 static sigjmp_buf env;		/* environment var. for pll_trap() */
188 #endif /* SIGSYS */
189 #endif /* KERNEL_PLL */
190 
191 static void
192 sync_status(const char *what, int ostatus, int nstatus)
193 {
194 	char obuf[256], nbuf[256], tbuf[1024];
195 #if defined(USE_SNPRINTB) && defined (STA_FMT)
196 	snprintb(obuf, sizeof(obuf), STA_FMT, ostatus);
197 	snprintb(nbuf, sizeof(nbuf), STA_FMT, nstatus);
198 #else
199 	snprintf(obuf, sizeof(obuf), "%04x", ostatus);
200 	snprintf(nbuf, sizeof(nbuf), "%04x", nstatus);
201 #endif
202 	snprintf(tbuf, sizeof(tbuf), "%s status: %s -> %s", what, obuf, nbuf);
203 	report_event(EVNT_KERN, NULL, tbuf);
204 }
205 
206 /*
207  * file_name - return pointer to non-relative portion of this C file pathname
208  */
209 static char *file_name(void)
210 {
211 	if (this_file == NULL) {
212 	    (void)strncpy(relative_path, __FILE__, PATH_MAX);
213 	    for (this_file=relative_path;
214 		*this_file && ! isalnum((unsigned char)*this_file);
215 		this_file++) ;
216 	}
217 	return this_file;
218 }
219 
220 /*
221  * init_loopfilter - initialize loop filter data
222  */
223 void
224 init_loopfilter(void)
225 {
226 	/*
227 	 * Initialize state variables.
228 	 */
229 	sys_poll = ntp_minpoll;
230 	clock_jitter = LOGTOD(sys_precision);
231 	freq_cnt = (int)clock_minstep;
232 }
233 
234 #ifdef KERNEL_PLL
235 /*
236  * ntp_adjtime_error_handler - process errors from ntp_adjtime
237  */
238 static void
239 ntp_adjtime_error_handler(
240 	const char *caller,	/* name of calling function */
241 	struct timex *ptimex,	/* pointer to struct timex */
242 	int ret,		/* return value from ntp_adjtime */
243 	int saved_errno,	/* value of errno when ntp_adjtime returned */
244 	int pps_call,		/* ntp_adjtime call was PPS-related */
245 	int tai_call,		/* ntp_adjtime call was TAI-related */
246 	int line		/* line number of ntp_adjtime call */
247 	)
248 {
249 	char des[1024] = "";	/* Decoded Error Status */
250 
251 	switch (ret) {
252 	    case -1:
253 		switch (saved_errno) {
254 		    case EFAULT:
255 			msyslog(LOG_ERR, "%s: %s line %d: invalid struct timex pointer: 0x%lx",
256 			    caller, file_name(), line,
257 			    (long)((void *)ptimex)
258 			);
259 		    break;
260 		    case EINVAL:
261 			msyslog(LOG_ERR, "%s: %s line %d: invalid struct timex \"constant\" element value: %ld",
262 			    caller, file_name(), line,
263 			    (long)(ptimex->constant)
264 			);
265 		    break;
266 		    case EPERM:
267 			if (tai_call) {
268 			    errno = saved_errno;
269 			    msyslog(LOG_ERR,
270 				"%s: ntp_adjtime(TAI) failed: %m",
271 				caller);
272 			}
273 			errno = saved_errno;
274 			msyslog(LOG_ERR, "%s: %s line %d: ntp_adjtime: %m",
275 			    caller, file_name(), line
276 			);
277 		    break;
278 		    default:
279 			msyslog(LOG_NOTICE, "%s: %s line %d: unhandled errno value %d after failed ntp_adjtime call",
280 			    caller, file_name(), line,
281 			    saved_errno
282 			);
283 		    break;
284 		}
285 	    break;
286 #ifdef TIME_OK
287 	    case TIME_OK: /* 0: synchronized, no leap second warning */
288 		/* msyslog(LOG_INFO, "kernel reports time is synchronized normally"); */
289 	    break;
290 #else
291 # warning TIME_OK is not defined
292 #endif
293 #ifdef TIME_INS
294 	    case TIME_INS: /* 1: positive leap second warning */
295 		msyslog(LOG_INFO, "kernel reports leap second insertion scheduled");
296 	    break;
297 #else
298 # warning TIME_INS is not defined
299 #endif
300 #ifdef TIME_DEL
301 	    case TIME_DEL: /* 2: negative leap second warning */
302 		msyslog(LOG_INFO, "kernel reports leap second deletion scheduled");
303 	    break;
304 #else
305 # warning TIME_DEL is not defined
306 #endif
307 #ifdef TIME_OOP
308 	    case TIME_OOP: /* 3: leap second in progress */
309 		msyslog(LOG_INFO, "kernel reports leap second in progress");
310 	    break;
311 #else
312 # warning TIME_OOP is not defined
313 #endif
314 #ifdef TIME_WAIT
315 	    case TIME_WAIT: /* 4: leap second has occured */
316 		msyslog(LOG_INFO, "kernel reports leap second has occurred");
317 	    break;
318 #else
319 # warning TIME_WAIT is not defined
320 #endif
321 #ifdef TIME_ERROR
322 #if 0
323 
324 from the reference implementation of ntp_gettime():
325 
326 		// Hardware or software error
327         if ((time_status & (STA_UNSYNC | STA_CLOCKERR))
328 
329 	/*
330          * PPS signal lost when either time or frequency synchronization
331          * requested
332          */
333 	|| (time_status & (STA_PPSFREQ | STA_PPSTIME)
334 	    && !(time_status & STA_PPSSIGNAL))
335 
336         /*
337          * PPS jitter exceeded when time synchronization requested
338          */
339 	|| (time_status & STA_PPSTIME &&
340             time_status & STA_PPSJITTER)
341 
342         /*
343          * PPS wander exceeded or calibration error when frequency
344          * synchronization requested
345          */
346 	|| (time_status & STA_PPSFREQ &&
347             time_status & (STA_PPSWANDER | STA_PPSERROR)))
348                 return (TIME_ERROR);
349 
350 or, from ntp_adjtime():
351 
352 	if (  (time_status & (STA_UNSYNC | STA_CLOCKERR))
353 	    || (time_status & (STA_PPSFREQ | STA_PPSTIME)
354 		&& !(time_status & STA_PPSSIGNAL))
355 	    || (time_status & STA_PPSTIME
356 		&& time_status & STA_PPSJITTER)
357 	    || (time_status & STA_PPSFREQ
358 		&& time_status & (STA_PPSWANDER | STA_PPSERROR))
359 	   )
360 		return (TIME_ERROR);
361 #endif
362 
363 	    case TIME_ERROR: /* 5: unsynchronized, or loss of synchronization */
364 				/* error (see status word) */
365 
366 		if (ptimex->status & STA_UNSYNC)
367 			snprintf(des, sizeof(des), "%s%sClock Unsynchronized",
368 				des, (*des) ? "; " : "");
369 
370 		if (ptimex->status & STA_CLOCKERR)
371 			snprintf(des, sizeof(des), "%s%sClock Error",
372 				des, (*des) ? "; " : "");
373 
374 		if (!(ptimex->status & STA_PPSSIGNAL)
375 		    && ptimex->status & STA_PPSFREQ)
376 			snprintf(des, sizeof(des), "%s%sPPS Frequency Sync wanted but no PPS",
377 				des, (*des) ? "; " : "");
378 
379 		if (!(ptimex->status & STA_PPSSIGNAL)
380 		    && ptimex->status & STA_PPSTIME)
381 			snprintf(des, sizeof(des), "%s%sPPS Time Sync wanted but no PPS signal",
382 				des, (*des) ? "; " : "");
383 
384 		if (   ptimex->status & STA_PPSTIME
385 		    && ptimex->status & STA_PPSJITTER)
386 			snprintf(des, sizeof(des), "%s%sPPS Time Sync wanted but PPS Jitter exceeded",
387 				des, (*des) ? "; " : "");
388 
389 		if (   ptimex->status & STA_PPSFREQ
390 		    && ptimex->status & STA_PPSWANDER)
391 			snprintf(des, sizeof(des), "%s%sPPS Frequency Sync wanted but PPS Wander exceeded",
392 				des, (*des) ? "; " : "");
393 
394 		if (   ptimex->status & STA_PPSFREQ
395 		    && ptimex->status & STA_PPSERROR)
396 			snprintf(des, sizeof(des), "%s%sPPS Frequency Sync wanted but Calibration error detected",
397 				des, (*des) ? "; " : "");
398 
399 		if (pps_call && !(ptimex->status & STA_PPSSIGNAL))
400 			report_event(EVNT_KERN, NULL,
401 			    "no PPS signal");
402 		DPRINTF(1, ("kernel loop status %#x (%s)\n",
403 			ptimex->status, des));
404 		/*
405 		 * This code may be returned when ntp_adjtime() has just
406 		 * been called for the first time, quite a while after
407 		 * startup, when ntpd just starts to discipline the kernel
408 		 * time. In this case the occurrence of this message
409 		 * can be pretty confusing.
410 		 *
411 		 * HMS: How about a message when we begin kernel processing:
412 		 *    Determining kernel clock state...
413 		 * so an initial TIME_ERROR message is less confising,
414 		 * or skipping the first message (ugh),
415 		 * or ???
416 		 * msyslog(LOG_INFO, "kernel reports time synchronization lost");
417 		 */
418 		msyslog(LOG_INFO, "kernel reports TIME_ERROR: %#x: %s",
419 			ptimex->status, des);
420 	    break;
421 #else
422 # warning TIME_ERROR is not defined
423 #endif
424 	    default:
425 		msyslog(LOG_NOTICE, "%s: %s line %d: unhandled return value %d from ntp_adjtime() in %s at line %d",
426 		    caller, file_name(), line,
427 		    ret,
428 		    __func__, __LINE__
429 		);
430 	    break;
431 	}
432 	return;
433 }
434 #endif
435 
436 /*
437  * local_clock - the NTP logical clock loop filter.
438  *
439  * Return codes:
440  * -1	update ignored: exceeds panic threshold
441  * 0	update ignored: popcorn or exceeds step threshold
442  * 1	clock was slewed
443  * 2	clock was stepped
444  *
445  * LOCKCLOCK: The only thing this routine does is set the
446  * sys_rootdisp variable equal to the peer dispersion.
447  */
448 int
449 local_clock(
450 	struct	peer *peer,	/* synch source peer structure */
451 	double	fp_offset	/* clock offset (s) */
452 	)
453 {
454 	int	rval;		/* return code */
455 	int	osys_poll;	/* old system poll */
456 	int	ntp_adj_ret;	/* returned by ntp_adjtime */
457 	double	mu;		/* interval since last update */
458 	double	clock_frequency; /* clock frequency */
459 	double	dtemp, etemp;	/* double temps */
460 	char	tbuf[80];	/* report buffer */
461 
462 	/*
463 	 * If the loop is opened or the NIST LOCKCLOCK is in use,
464 	 * monitor and record the offsets anyway in order to determine
465 	 * the open-loop response and then go home.
466 	 */
467 #ifdef LOCKCLOCK
468 	{
469 #else
470 	if (!ntp_enable) {
471 #endif /* LOCKCLOCK */
472 		record_loop_stats(fp_offset, drift_comp, clock_jitter,
473 		    clock_stability, sys_poll);
474 		return (0);
475 	}
476 
477 #ifndef LOCKCLOCK
478 	/*
479 	 * If the clock is way off, panic is declared. The clock_panic
480 	 * defaults to 1000 s; if set to zero, the panic will never
481 	 * occur. The allow_panic defaults to FALSE, so the first panic
482 	 * will exit. It can be set TRUE by a command line option, in
483 	 * which case the clock will be set anyway and time marches on.
484 	 * But, allow_panic will be set FALSE when the update is less
485 	 * than the step threshold; so, subsequent panics will exit.
486 	 */
487 	if (fabs(fp_offset) > clock_panic && clock_panic > 0 &&
488 	    !allow_panic) {
489 		snprintf(tbuf, sizeof(tbuf),
490 		    "%+.0f s; set clock manually within %.0f s.",
491 		    fp_offset, clock_panic);
492 		report_event(EVNT_SYSFAULT, NULL, tbuf);
493 		return (-1);
494 	}
495 
496 	/*
497 	 * This section simulates ntpdate. If the offset exceeds the
498 	 * step threshold (128 ms), step the clock to that time and
499 	 * exit. Otherwise, slew the clock to that time and exit. Note
500 	 * that the slew will persist and eventually complete beyond the
501 	 * life of this program. Note that while ntpdate is active, the
502 	 * terminal does not detach, so the termination message prints
503 	 * directly to the terminal.
504 	 */
505 	if (mode_ntpdate) {
506 		if (  ( fp_offset > clock_max_fwd  && clock_max_fwd  > 0)
507 		   || (-fp_offset > clock_max_back && clock_max_back > 0)) {
508 			step_systime(fp_offset);
509 			msyslog(LOG_NOTICE, "ntpd: time set %+.6f s",
510 			    fp_offset);
511 			printf("ntpd: time set %+.6fs\n", fp_offset);
512 		} else {
513 			adj_systime(fp_offset);
514 			msyslog(LOG_NOTICE, "ntpd: time slew %+.6f s",
515 			    fp_offset);
516 			printf("ntpd: time slew %+.6fs\n", fp_offset);
517 		}
518 		record_loop_stats(fp_offset, drift_comp, clock_jitter,
519 		    clock_stability, sys_poll);
520 		exit (0);
521 	}
522 
523 	/*
524 	 * The huff-n'-puff filter finds the lowest delay in the recent
525 	 * interval. This is used to correct the offset by one-half the
526 	 * difference between the sample delay and minimum delay. This
527 	 * is most effective if the delays are highly assymetric and
528 	 * clockhopping is avoided and the clock frequency wander is
529 	 * relatively small.
530 	 */
531 	if (sys_huffpuff != NULL) {
532 		if (peer->delay < sys_huffpuff[sys_huffptr])
533 			sys_huffpuff[sys_huffptr] = peer->delay;
534 		if (peer->delay < sys_mindly)
535 			sys_mindly = peer->delay;
536 		if (fp_offset > 0)
537 			dtemp = -(peer->delay - sys_mindly) / 2;
538 		else
539 			dtemp = (peer->delay - sys_mindly) / 2;
540 		fp_offset += dtemp;
541 #ifdef DEBUG
542 		if (debug)
543 			printf(
544 		    "local_clock: size %d mindly %.6f huffpuff %.6f\n",
545 			    sys_hufflen, sys_mindly, dtemp);
546 #endif
547 	}
548 
549 	/*
550 	 * Clock state machine transition function which defines how the
551 	 * system reacts to large phase and frequency excursion. There
552 	 * are two main regimes: when the offset exceeds the step
553 	 * threshold (128 ms) and when it does not. Under certain
554 	 * conditions updates are suspended until the stepout theshold
555 	 * (900 s) is exceeded. See the documentation on how these
556 	 * thresholds interact with commands and command line options.
557 	 *
558 	 * Note the kernel is disabled if step is disabled or greater
559 	 * than 0.5 s or in ntpdate mode.
560 	 */
561 	osys_poll = sys_poll;
562 	if (sys_poll < peer->minpoll)
563 		sys_poll = peer->minpoll;
564 	if (sys_poll > peer->maxpoll)
565 		sys_poll = peer->maxpoll;
566 	mu = current_time - clock_epoch;
567 	clock_frequency = drift_comp;
568 	rval = 1;
569 	if (  ( fp_offset > clock_max_fwd  && clock_max_fwd  > 0)
570 	   || (-fp_offset > clock_max_back && clock_max_back > 0)
571 	   || force_step_once ) {
572 		if (force_step_once) {
573 			force_step_once = FALSE;  /* we want this only once after startup */
574 			msyslog(LOG_NOTICE, "Doing intital time step" );
575 		}
576 
577 		switch (state) {
578 
579 		/*
580 		 * In SYNC state we ignore the first outlier and switch
581 		 * to SPIK state.
582 		 */
583 		case EVNT_SYNC:
584 			snprintf(tbuf, sizeof(tbuf), "%+.6f s",
585 			    fp_offset);
586 			report_event(EVNT_SPIK, NULL, tbuf);
587 			state = EVNT_SPIK;
588 			return (0);
589 
590 		/*
591 		 * In FREQ state we ignore outliers and inlyers. At the
592 		 * first outlier after the stepout threshold, compute
593 		 * the apparent frequency correction and step the phase.
594 		 */
595 		case EVNT_FREQ:
596 			if (mu < clock_minstep)
597 				return (0);
598 
599 			clock_frequency = direct_freq(fp_offset);
600 
601 			/* fall through to EVNT_SPIK */
602 
603 		/*
604 		 * In SPIK state we ignore succeeding outliers until
605 		 * either an inlyer is found or the stepout threshold is
606 		 * exceeded.
607 		 */
608 		case EVNT_SPIK:
609 			if (mu < clock_minstep)
610 				return (0);
611 
612 			/* fall through to default */
613 
614 		/*
615 		 * We get here by default in NSET and FSET states and
616 		 * from above in FREQ or SPIK states.
617 		 *
618 		 * In NSET state an initial frequency correction is not
619 		 * available, usually because the frequency file has not
620 		 * yet been written. Since the time is outside the step
621 		 * threshold, the clock is stepped. The frequency will
622 		 * be set directly following the stepout interval.
623 		 *
624 		 * In FSET state the initial frequency has been set from
625 		 * the frequency file. Since the time is outside the
626 		 * step threshold, the clock is stepped immediately,
627 		 * rather than after the stepout interval. Guys get
628 		 * nervous if it takes 15 minutes to set the clock for
629 		 * the first time.
630 		 *
631 		 * In FREQ and SPIK states the stepout threshold has
632 		 * expired and the phase is still above the step
633 		 * threshold. Note that a single spike greater than the
634 		 * step threshold is always suppressed, even with a
635 		 * long time constant.
636 		 */
637 		default:
638 			snprintf(tbuf, sizeof(tbuf), "%+.6f s",
639 			    fp_offset);
640 			report_event(EVNT_CLOCKRESET, NULL, tbuf);
641 			step_systime(fp_offset);
642 			reinit_timer();
643 			tc_counter = 0;
644 			clock_jitter = LOGTOD(sys_precision);
645 			rval = 2;
646 			if (state == EVNT_NSET) {
647 				rstclock(EVNT_FREQ, 0);
648 				return (rval);
649 			}
650 			break;
651 		}
652 		rstclock(EVNT_SYNC, 0);
653 	} else {
654 		/*
655 		 * The offset is less than the step threshold. Calculate
656 		 * the jitter as the exponentially weighted offset
657 		 * differences.
658 		 */
659 		etemp = SQUARE(clock_jitter);
660 		dtemp = SQUARE(max(fabs(fp_offset - last_offset),
661 		    LOGTOD(sys_precision)));
662 		clock_jitter = SQRT(etemp + (dtemp - etemp) /
663 		    CLOCK_AVG);
664 		switch (state) {
665 
666 		/*
667 		 * In NSET state this is the first update received and
668 		 * the frequency has not been initialized. Adjust the
669 		 * phase, but do not adjust the frequency until after
670 		 * the stepout threshold.
671 		 */
672 		case EVNT_NSET:
673 			adj_systime(fp_offset);
674 			rstclock(EVNT_FREQ, fp_offset);
675 			break;
676 
677 		/*
678 		 * In FREQ state ignore updates until the stepout
679 		 * threshold. After that, compute the new frequency, but
680 		 * do not adjust the frequency until the holdoff counter
681 		 * decrements to zero.
682 		 */
683 		case EVNT_FREQ:
684 			if (mu < clock_minstep)
685 				return (0);
686 
687 			clock_frequency = direct_freq(fp_offset);
688 			/* fall through */
689 
690 		/*
691 		 * We get here by default in FSET, SPIK and SYNC states.
692 		 * Here compute the frequency update due to PLL and FLL
693 		 * contributions. Note, we avoid frequency discipline at
694 		 * startup until the initial transient has subsided.
695 		 */
696 		default:
697 			allow_panic = FALSE;
698 			if (freq_cnt == 0) {
699 
700 				/*
701 				 * The FLL and PLL frequency gain constants
702 				 * depend on the time constant and Allan
703 				 * intercept. The PLL is always used, but
704 				 * becomes ineffective above the Allan intercept
705 				 * where the FLL becomes effective.
706 				 */
707 				if (sys_poll >= allan_xpt)
708 					clock_frequency += (fp_offset -
709 					    clock_offset) / max(ULOGTOD(sys_poll),
710 					    mu) * CLOCK_FLL;
711 
712 				/*
713 				 * The PLL frequency gain (numerator) depends on
714 				 * the minimum of the update interval and Allan
715 				 * intercept. This reduces the PLL gain when the
716 				 * FLL becomes effective.
717 				 */
718 				etemp = min(ULOGTOD(allan_xpt), mu);
719 				dtemp = 4 * CLOCK_PLL * ULOGTOD(sys_poll);
720 				clock_frequency += fp_offset * etemp / (dtemp *
721 				    dtemp);
722 			}
723 			rstclock(EVNT_SYNC, fp_offset);
724 			if (fabs(fp_offset) < CLOCK_FLOOR)
725 				freq_cnt = 0;
726 			break;
727 		}
728 	}
729 
730 #ifdef KERNEL_PLL
731 	/*
732 	 * This code segment works when clock adjustments are made using
733 	 * precision time kernel support and the ntp_adjtime() system
734 	 * call. This support is available in Solaris 2.6 and later,
735 	 * Digital Unix 4.0 and later, FreeBSD, Linux and specially
736 	 * modified kernels for HP-UX 9 and Ultrix 4. In the case of the
737 	 * DECstation 5000/240 and Alpha AXP, additional kernel
738 	 * modifications provide a true microsecond clock and nanosecond
739 	 * clock, respectively.
740 	 *
741 	 * Important note: The kernel discipline is used only if the
742 	 * step threshold is less than 0.5 s, as anything higher can
743 	 * lead to overflow problems. This might occur if some misguided
744 	 * lad set the step threshold to something ridiculous.
745 	 */
746 	if (pll_control && kern_enable && freq_cnt == 0) {
747 
748 		/*
749 		 * We initialize the structure for the ntp_adjtime()
750 		 * system call. We have to convert everything to
751 		 * microseconds or nanoseconds first. Do not update the
752 		 * system variables if the ext_enable flag is set. In
753 		 * this case, the external clock driver will update the
754 		 * variables, which will be read later by the local
755 		 * clock driver. Afterwards, remember the time and
756 		 * frequency offsets for jitter and stability values and
757 		 * to update the frequency file.
758 		 */
759 		ZERO(ntv);
760 		if (ext_enable) {
761 			ntv.modes = MOD_STATUS;
762 		} else {
763 #ifdef STA_NANO
764 			ntv.modes = MOD_BITS | MOD_NANO;
765 #else /* STA_NANO */
766 			ntv.modes = MOD_BITS;
767 #endif /* STA_NANO */
768 			if (clock_offset < 0)
769 				dtemp = -.5;
770 			else
771 				dtemp = .5;
772 #ifdef STA_NANO
773 			ntv.offset = (int32)(clock_offset * 1e9 +
774 			    dtemp);
775 			ntv.constant = sys_poll;
776 #else /* STA_NANO */
777 			ntv.offset = (int32)(clock_offset * 1e6 +
778 			    dtemp);
779 			ntv.constant = sys_poll - 4;
780 #endif /* STA_NANO */
781 			if (ntv.constant < 0)
782 				ntv.constant = 0;
783 
784 			ntv.esterror = (u_int32)(clock_jitter * 1e6);
785 			ntv.maxerror = (u_int32)((sys_rootdelay / 2 +
786 			    sys_rootdisp) * 1e6);
787 			ntv.status = STA_PLL;
788 
789 			/*
790 			 * Enable/disable the PPS if requested.
791 			 */
792 			if (hardpps_enable) {
793 				ntv.status |= (STA_PPSTIME | STA_PPSFREQ);
794 				if (!(pll_status & STA_PPSTIME))
795 					sync_status("PPS enabled",
796 						pll_status,
797 						ntv.status);
798 			} else {
799 				ntv.status &= ~(STA_PPSTIME | STA_PPSFREQ);
800 				if (pll_status & STA_PPSTIME)
801 					sync_status("PPS disabled",
802 						pll_status,
803 						ntv.status);
804 			}
805 			if (sys_leap == LEAP_ADDSECOND)
806 				ntv.status |= STA_INS;
807 			else if (sys_leap == LEAP_DELSECOND)
808 				ntv.status |= STA_DEL;
809 		}
810 
811 		/*
812 		 * Pass the stuff to the kernel. If it squeals, turn off
813 		 * the pps. In any case, fetch the kernel offset,
814 		 * frequency and jitter.
815 		 */
816 		ntp_adj_ret = ntp_adjtime(&ntv);
817 		/*
818 		 * A squeal is a return status < 0, or a state change.
819 		 */
820 		if ((0 > ntp_adj_ret) || (ntp_adj_ret != kernel_status)) {
821 			kernel_status = ntp_adj_ret;
822 			ntp_adjtime_error_handler(__func__, &ntv, ntp_adj_ret, errno, hardpps_enable, 0, __LINE__ - 1);
823 		}
824 		pll_status = ntv.status;
825 #ifdef STA_NANO
826 		clock_offset = ntv.offset / 1e9;
827 #else /* STA_NANO */
828 		clock_offset = ntv.offset / 1e6;
829 #endif /* STA_NANO */
830 		clock_frequency = FREQTOD(ntv.freq);
831 
832 		/*
833 		 * If the kernel PPS is lit, monitor its performance.
834 		 */
835 		if (ntv.status & STA_PPSTIME) {
836 #ifdef STA_NANO
837 			clock_jitter = ntv.jitter / 1e9;
838 #else /* STA_NANO */
839 			clock_jitter = ntv.jitter / 1e6;
840 #endif /* STA_NANO */
841 		}
842 
843 #if defined(STA_NANO) && NTP_API == 4
844 		/*
845 		 * If the TAI changes, update the kernel TAI.
846 		 */
847 		if (loop_tai != sys_tai) {
848 			loop_tai = sys_tai;
849 			ntv.modes = MOD_TAI;
850 			ntv.constant = sys_tai;
851 			if ((ntp_adj_ret = ntp_adjtime(&ntv)) != 0) {
852 			    ntp_adjtime_error_handler(__func__, &ntv, ntp_adj_ret, errno, 0, 1, __LINE__ - 1);
853 			}
854 		}
855 #endif /* STA_NANO */
856 	}
857 #endif /* KERNEL_PLL */
858 
859 	/*
860 	 * Clamp the frequency within the tolerance range and calculate
861 	 * the frequency difference since the last update.
862 	 */
863 	if (fabs(clock_frequency) > NTP_MAXFREQ)
864 		msyslog(LOG_NOTICE,
865 		    "frequency error %.0f PPM exceeds tolerance %.0f PPM",
866 		    clock_frequency * 1e6, NTP_MAXFREQ * 1e6);
867 	dtemp = SQUARE(clock_frequency - drift_comp);
868 	if (clock_frequency > NTP_MAXFREQ)
869 		drift_comp = NTP_MAXFREQ;
870 	else if (clock_frequency < -NTP_MAXFREQ)
871 		drift_comp = -NTP_MAXFREQ;
872 	else
873 		drift_comp = clock_frequency;
874 
875 	/*
876 	 * Calculate the wander as the exponentially weighted RMS
877 	 * frequency differences. Record the change for the frequency
878 	 * file update.
879 	 */
880 	etemp = SQUARE(clock_stability);
881 	clock_stability = SQRT(etemp + (dtemp - etemp) / CLOCK_AVG);
882 
883 	/*
884 	 * Here we adjust the time constant by comparing the current
885 	 * offset with the clock jitter. If the offset is less than the
886 	 * clock jitter times a constant, then the averaging interval is
887 	 * increased, otherwise it is decreased. A bit of hysteresis
888 	 * helps calm the dance. Works best using burst mode. Don't
889 	 * fiddle with the poll during the startup clamp period.
890 	 */
891 	if (freq_cnt > 0) {
892 		tc_counter = 0;
893 	} else if (fabs(clock_offset) < CLOCK_PGATE * clock_jitter) {
894 		tc_counter += sys_poll;
895 		if (tc_counter > CLOCK_LIMIT) {
896 			tc_counter = CLOCK_LIMIT;
897 			if (sys_poll < peer->maxpoll) {
898 				tc_counter = 0;
899 				sys_poll++;
900 			}
901 		}
902 	} else {
903 		tc_counter -= sys_poll << 1;
904 		if (tc_counter < -CLOCK_LIMIT) {
905 			tc_counter = -CLOCK_LIMIT;
906 			if (sys_poll > peer->minpoll) {
907 				tc_counter = 0;
908 				sys_poll--;
909 			}
910 		}
911 	}
912 
913 	/*
914 	 * If the time constant has changed, update the poll variables.
915 	 */
916 	if (osys_poll != sys_poll)
917 		poll_update(peer, sys_poll);
918 
919 	/*
920 	 * Yibbidy, yibbbidy, yibbidy; that'h all folks.
921 	 */
922 	record_loop_stats(clock_offset, drift_comp, clock_jitter,
923 	    clock_stability, sys_poll);
924 #ifdef DEBUG
925 	if (debug)
926 		printf(
927 		    "local_clock: offset %.9f jit %.9f freq %.3f stab %.3f poll %d\n",
928 		    clock_offset, clock_jitter, drift_comp * 1e6,
929 		    clock_stability * 1e6, sys_poll);
930 #endif /* DEBUG */
931 	return (rval);
932 #endif /* LOCKCLOCK */
933 }
934 
935 
936 /*
937  * adj_host_clock - Called once every second to update the local clock.
938  *
939  * LOCKCLOCK: The only thing this routine does is increment the
940  * sys_rootdisp variable.
941  */
942 void
943 adj_host_clock(
944 	void
945 	)
946 {
947 	double	offset_adj;
948 	double	freq_adj;
949 
950 	/*
951 	 * Update the dispersion since the last update. In contrast to
952 	 * NTPv3, NTPv4 does not declare unsynchronized after one day,
953 	 * since the dispersion check serves this function. Also,
954 	 * since the poll interval can exceed one day, the old test
955 	 * would be counterproductive. During the startup clamp period, the
956 	 * time constant is clamped at 2.
957 	 */
958 	sys_rootdisp += clock_phi;
959 #ifndef LOCKCLOCK
960 	if (!ntp_enable || mode_ntpdate)
961 		return;
962 	/*
963 	 * Determine the phase adjustment. The gain factor (denominator)
964 	 * increases with poll interval, so is dominated by the FLL
965 	 * above the Allan intercept. Note the reduced time constant at
966 	 * startup.
967 	 */
968 	if (state != EVNT_SYNC) {
969 		offset_adj = 0.;
970 	} else if (freq_cnt > 0) {
971 		offset_adj = clock_offset / (CLOCK_PLL * ULOGTOD(1));
972 		freq_cnt--;
973 #ifdef KERNEL_PLL
974 	} else if (pll_control && kern_enable) {
975 		offset_adj = 0.;
976 #endif /* KERNEL_PLL */
977 	} else {
978 		offset_adj = clock_offset / (CLOCK_PLL * ULOGTOD(sys_poll));
979 	}
980 
981 	/*
982 	 * If the kernel discipline is enabled the frequency correction
983 	 * drift_comp has already been engaged via ntp_adjtime() in
984 	 * set_freq().  Otherwise it is a component of the adj_systime()
985 	 * offset.
986 	 */
987 #ifdef KERNEL_PLL
988 	if (pll_control && kern_enable)
989 		freq_adj = 0.;
990 	else
991 #endif /* KERNEL_PLL */
992 		freq_adj = drift_comp;
993 
994 	/* Bound absolute value of total adjustment to NTP_MAXFREQ. */
995 	if (offset_adj + freq_adj > NTP_MAXFREQ)
996 		offset_adj = NTP_MAXFREQ - freq_adj;
997 	else if (offset_adj + freq_adj < -NTP_MAXFREQ)
998 		offset_adj = -NTP_MAXFREQ - freq_adj;
999 
1000 	clock_offset -= offset_adj;
1001 	/*
1002 	 * Windows port adj_systime() must be called each second,
1003 	 * even if the argument is zero, to ease emulation of
1004 	 * adjtime() using Windows' slew API which controls the rate
1005 	 * but does not automatically stop slewing when an offset
1006 	 * has decayed to zero.
1007 	 */
1008 	adj_systime(offset_adj + freq_adj);
1009 #endif /* LOCKCLOCK */
1010 }
1011 
1012 
1013 /*
1014  * Clock state machine. Enter new state and set state variables.
1015  */
1016 static void
1017 rstclock(
1018 	int	trans,		/* new state */
1019 	double	offset		/* new offset */
1020 	)
1021 {
1022 #ifdef DEBUG
1023 	if (debug > 1)
1024 		printf("local_clock: mu %lu state %d poll %d count %d\n",
1025 		    current_time - clock_epoch, trans, sys_poll,
1026 		    tc_counter);
1027 #endif
1028 	if (trans != state && trans != EVNT_FSET)
1029 		report_event(trans, NULL, NULL);
1030 	state = trans;
1031 	last_offset = clock_offset = offset;
1032 	clock_epoch = current_time;
1033 }
1034 
1035 
1036 /*
1037  * calc_freq - calculate frequency directly
1038  *
1039  * This is very carefully done. When the offset is first computed at the
1040  * first update, a residual frequency component results. Subsequently,
1041  * updates are suppresed until the end of the measurement interval while
1042  * the offset is amortized. At the end of the interval the frequency is
1043  * calculated from the current offset, residual offset, length of the
1044  * interval and residual frequency component. At the same time the
1045  * frequenchy file is armed for update at the next hourly stats.
1046  */
1047 static double
1048 direct_freq(
1049 	double	fp_offset
1050 	)
1051 {
1052 	set_freq(fp_offset / (current_time - clock_epoch));
1053 
1054 	return drift_comp;
1055 }
1056 
1057 
1058 /*
1059  * set_freq - set clock frequency correction
1060  *
1061  * Used to step the frequency correction at startup, possibly again once
1062  * the frequency is measured (that is, transitioning from EVNT_NSET to
1063  * EVNT_FSET), and finally to switch between daemon and kernel loop
1064  * discipline at runtime.
1065  *
1066  * When the kernel loop discipline is available but the daemon loop is
1067  * in use, the kernel frequency correction is disabled (set to 0) to
1068  * ensure drift_comp is applied by only one of the loops.
1069  */
1070 static void
1071 set_freq(
1072 	double	freq		/* frequency update */
1073 	)
1074 {
1075 	const char *	loop_desc;
1076 	int ntp_adj_ret;
1077 
1078 	drift_comp = freq;
1079 	loop_desc = "ntpd";
1080 #ifdef KERNEL_PLL
1081 	if (pll_control) {
1082 		ZERO(ntv);
1083 		ntv.modes = MOD_FREQUENCY;
1084 		if (kern_enable) {
1085 			loop_desc = "kernel";
1086 			ntv.freq = DTOFREQ(drift_comp);
1087 		}
1088 		if ((ntp_adj_ret = ntp_adjtime(&ntv)) != 0) {
1089 		    ntp_adjtime_error_handler(__func__, &ntv, ntp_adj_ret, errno, 0, 0, __LINE__ - 1);
1090 		}
1091 	}
1092 #endif /* KERNEL_PLL */
1093 	mprintf_event(EVNT_FSET, NULL, "%s %.3f PPM", loop_desc,
1094 	    drift_comp * 1e6);
1095 }
1096 
1097 
1098 #ifdef KERNEL_PLL
1099 static void
1100 start_kern_loop(void)
1101 {
1102 	static int atexit_done;
1103 	int ntp_adj_ret;
1104 
1105 	pll_control = TRUE;
1106 	ZERO(ntv);
1107 	ntv.modes = MOD_BITS;
1108 	ntv.status = STA_PLL;
1109 	ntv.maxerror = MAXDISPERSE;
1110 	ntv.esterror = MAXDISPERSE;
1111 	ntv.constant = sys_poll; /* why is it that here constant is unconditionally set to sys_poll, whereas elsewhere is is modified depending on nanosecond vs. microsecond kernel? */
1112 #ifdef SIGSYS
1113 	/*
1114 	 * Use sigsetjmp() to save state and then call ntp_adjtime(); if
1115 	 * it fails, then pll_trap() will set pll_control FALSE before
1116 	 * returning control using siglogjmp().
1117 	 */
1118 	newsigsys.sa_handler = pll_trap;
1119 	newsigsys.sa_flags = 0;
1120 	if (sigaction(SIGSYS, &newsigsys, &sigsys)) {
1121 		msyslog(LOG_ERR, "sigaction() trap SIGSYS: %m");
1122 		pll_control = FALSE;
1123 	} else {
1124 		if (sigsetjmp(env, 1) == 0) {
1125 			if ((ntp_adj_ret = ntp_adjtime(&ntv)) != 0) {
1126 			    ntp_adjtime_error_handler(__func__, &ntv, ntp_adj_ret, errno, 0, 0, __LINE__ - 1);
1127 			}
1128 		}
1129 		if (sigaction(SIGSYS, &sigsys, NULL)) {
1130 			msyslog(LOG_ERR,
1131 			    "sigaction() restore SIGSYS: %m");
1132 			pll_control = FALSE;
1133 		}
1134 	}
1135 #else /* SIGSYS */
1136 	if ((ntp_adj_ret = ntp_adjtime(&ntv)) != 0) {
1137 	    ntp_adjtime_error_handler(__func__, &ntv, ntp_adj_ret, errno, 0, 0, __LINE__ - 1);
1138 	}
1139 #endif /* SIGSYS */
1140 
1141 	/*
1142 	 * Save the result status and light up an external clock
1143 	 * if available.
1144 	 */
1145 	pll_status = ntv.status;
1146 	if (pll_control) {
1147 		if (!atexit_done) {
1148 			atexit_done = TRUE;
1149 			atexit(&stop_kern_loop);
1150 		}
1151 #ifdef STA_NANO
1152 		if (pll_status & STA_CLK)
1153 			ext_enable = TRUE;
1154 #endif /* STA_NANO */
1155 		report_event(EVNT_KERN, NULL,
1156 	  	    "kernel time sync enabled");
1157 	}
1158 }
1159 #endif	/* KERNEL_PLL */
1160 
1161 
1162 #ifdef KERNEL_PLL
1163 static void
1164 stop_kern_loop(void)
1165 {
1166 	if (pll_control && kern_enable)
1167 		report_event(EVNT_KERN, NULL,
1168 		    "kernel time sync disabled");
1169 }
1170 #endif	/* KERNEL_PLL */
1171 
1172 
1173 /*
1174  * select_loop() - choose kernel or daemon loop discipline.
1175  */
1176 void
1177 select_loop(
1178 	int	use_kern_loop
1179 	)
1180 {
1181 	if (kern_enable == use_kern_loop)
1182 		return;
1183 #ifdef KERNEL_PLL
1184 	if (pll_control && !use_kern_loop)
1185 		stop_kern_loop();
1186 #endif
1187 	kern_enable = use_kern_loop;
1188 #ifdef KERNEL_PLL
1189 	if (pll_control && use_kern_loop)
1190 		start_kern_loop();
1191 #endif
1192 	/*
1193 	 * If this loop selection change occurs after initial startup,
1194 	 * call set_freq() to switch the frequency compensation to or
1195 	 * from the kernel loop.
1196 	 */
1197 #ifdef KERNEL_PLL
1198 	if (pll_control && loop_started)
1199 		set_freq(drift_comp);
1200 #endif
1201 }
1202 
1203 
1204 /*
1205  * huff-n'-puff filter
1206  */
1207 void
1208 huffpuff(void)
1209 {
1210 	int i;
1211 
1212 	if (sys_huffpuff == NULL)
1213 		return;
1214 
1215 	sys_huffptr = (sys_huffptr + 1) % sys_hufflen;
1216 	sys_huffpuff[sys_huffptr] = 1e9;
1217 	sys_mindly = 1e9;
1218 	for (i = 0; i < sys_hufflen; i++) {
1219 		if (sys_huffpuff[i] < sys_mindly)
1220 			sys_mindly = sys_huffpuff[i];
1221 	}
1222 }
1223 
1224 
1225 /*
1226  * loop_config - configure the loop filter
1227  *
1228  * LOCKCLOCK: The LOOP_DRIFTINIT and LOOP_DRIFTCOMP cases are no-ops.
1229  */
1230 void
1231 loop_config(
1232 	int	item,
1233 	double	freq
1234 	)
1235 {
1236 	int	i;
1237 	double	ftemp;
1238 
1239 #ifdef DEBUG
1240 	if (debug > 1)
1241 		printf("loop_config: item %d freq %f\n", item, freq);
1242 #endif
1243 	switch (item) {
1244 
1245 	/*
1246 	 * We first assume the kernel supports the ntp_adjtime()
1247 	 * syscall. If that syscall works, initialize the kernel time
1248 	 * variables. Otherwise, continue leaving no harm behind.
1249 	 */
1250 	case LOOP_DRIFTINIT:
1251 #ifndef LOCKCLOCK
1252 #ifdef KERNEL_PLL
1253 		if (mode_ntpdate)
1254 			break;
1255 
1256 		start_kern_loop();
1257 #endif /* KERNEL_PLL */
1258 
1259 		/*
1260 		 * Initialize frequency if given; otherwise, begin frequency
1261 		 * calibration phase.
1262 		 */
1263 		ftemp = init_drift_comp / 1e6;
1264 		if (ftemp > NTP_MAXFREQ)
1265 			ftemp = NTP_MAXFREQ;
1266 		else if (ftemp < -NTP_MAXFREQ)
1267 			ftemp = -NTP_MAXFREQ;
1268 		set_freq(ftemp);
1269 		if (freq_set)
1270 			rstclock(EVNT_FSET, 0);
1271 		else
1272 			rstclock(EVNT_NSET, 0);
1273 		loop_started = TRUE;
1274 #endif /* LOCKCLOCK */
1275 		break;
1276 
1277 	case LOOP_KERN_CLEAR:
1278 #if 0		/* XXX: needs more review, and how can we get here? */
1279 #ifndef LOCKCLOCK
1280 # ifdef KERNEL_PLL
1281 		if (pll_control && kern_enable) {
1282 			memset((char *)&ntv, 0, sizeof(ntv));
1283 			ntv.modes = MOD_STATUS;
1284 			ntv.status = STA_UNSYNC;
1285 			ntp_adjtime(&ntv);
1286 			sync_status("kernel time sync disabled",
1287 				pll_status,
1288 				ntv.status);
1289 		   }
1290 # endif /* KERNEL_PLL */
1291 #endif /* LOCKCLOCK */
1292 #endif
1293 		break;
1294 
1295 	/*
1296 	 * Tinker command variables for Ulrich Windl. Very dangerous.
1297 	 */
1298 	case LOOP_ALLAN:	/* Allan intercept (log2) (allan) */
1299 		allan_xpt = (u_char)freq;
1300 		break;
1301 
1302 	case LOOP_CODEC:	/* audio codec frequency (codec) */
1303 		clock_codec = freq / 1e6;
1304 		break;
1305 
1306 	case LOOP_PHI:		/* dispersion threshold (dispersion) */
1307 		clock_phi = freq / 1e6;
1308 		break;
1309 
1310 	case LOOP_FREQ:		/* initial frequency (freq) */
1311 		init_drift_comp = freq;
1312 		freq_set++;
1313 		break;
1314 
1315 	case LOOP_HUFFPUFF:	/* huff-n'-puff length (huffpuff) */
1316 		if (freq < HUFFPUFF)
1317 			freq = HUFFPUFF;
1318 		sys_hufflen = (int)(freq / HUFFPUFF);
1319 		sys_huffpuff = emalloc(sizeof(sys_huffpuff[0]) *
1320 		    sys_hufflen);
1321 		for (i = 0; i < sys_hufflen; i++)
1322 			sys_huffpuff[i] = 1e9;
1323 		sys_mindly = 1e9;
1324 		break;
1325 
1326 	case LOOP_PANIC:	/* panic threshold (panic) */
1327 		clock_panic = freq;
1328 		break;
1329 
1330 	case LOOP_MAX:		/* step threshold (step) */
1331 		clock_max_fwd = clock_max_back = freq;
1332 		if (freq == 0 || freq > 0.5)
1333 			select_loop(FALSE);
1334 		break;
1335 
1336 	case LOOP_MAX_BACK:	/* step threshold (step) */
1337 		clock_max_back = freq;
1338 		/*
1339 		 * Leave using the kernel discipline code unless both
1340 		 * limits are massive.  This assumes the reason to stop
1341 		 * using it is that it's pointless, not that it goes wrong.
1342 		 */
1343 		if (  (clock_max_back == 0 || clock_max_back > 0.5)
1344 		   || (clock_max_fwd  == 0 || clock_max_fwd  > 0.5))
1345 			select_loop(FALSE);
1346 		break;
1347 
1348 	case LOOP_MAX_FWD:	/* step threshold (step) */
1349 		clock_max_fwd = freq;
1350 		if (  (clock_max_back == 0 || clock_max_back > 0.5)
1351 		   || (clock_max_fwd  == 0 || clock_max_fwd  > 0.5))
1352 			select_loop(FALSE);
1353 		break;
1354 
1355 	case LOOP_MINSTEP:	/* stepout threshold (stepout) */
1356 		if (freq < CLOCK_MINSTEP)
1357 			clock_minstep = CLOCK_MINSTEP;
1358 		else
1359 			clock_minstep = freq;
1360 		break;
1361 
1362 	case LOOP_TICK:		/* tick increment (tick) */
1363 		set_sys_tick_precision(freq);
1364 		break;
1365 
1366 	case LOOP_LEAP:		/* not used, fall through */
1367 	default:
1368 		msyslog(LOG_NOTICE,
1369 		    "loop_config: unsupported option %d", item);
1370 	}
1371 }
1372 
1373 
1374 #if defined(KERNEL_PLL) && defined(SIGSYS)
1375 /*
1376  * _trap - trap processor for undefined syscalls
1377  *
1378  * This nugget is called by the kernel when the SYS_ntp_adjtime()
1379  * syscall bombs because the silly thing has not been implemented in
1380  * the kernel. In this case the phase-lock loop is emulated by
1381  * the stock adjtime() syscall and a lot of indelicate abuse.
1382  */
1383 static RETSIGTYPE
1384 pll_trap(
1385 	int arg
1386 	)
1387 {
1388 	pll_control = FALSE;
1389 	siglongjmp(env, 1);
1390 }
1391 #endif /* KERNEL_PLL && SIGSYS */
1392