Home | History | Annotate | Line # | Download | only in kern
kern_ntptime.c revision 1.47
      1 /*	$NetBSD: kern_ntptime.c,v 1.47 2008/02/27 19:55:59 matt Exp $	*/
      2 
      3 /*-
      4  ***********************************************************************
      5  *								       *
      6  * Copyright (c) David L. Mills 1993-2001			       *
      7  *								       *
      8  * Permission to use, copy, modify, and distribute this software and   *
      9  * its documentation for any purpose and without fee is hereby	       *
     10  * granted, provided that the above copyright notice appears in all    *
     11  * copies and that both the copyright notice and this permission       *
     12  * notice appear in supporting documentation, and that the name	       *
     13  * University of Delaware not be used in advertising or publicity      *
     14  * pertaining to distribution of the software without specific,	       *
     15  * written prior permission. The University of Delaware makes no       *
     16  * representations about the suitability this software for any	       *
     17  * purpose. It is provided "as is" without express or implied	       *
     18  * warranty.							       *
     19  *								       *
     20  **********************************************************************/
     21 
     22 /*
     23  * Adapted from the original sources for FreeBSD and timecounters by:
     24  * Poul-Henning Kamp <phk (at) FreeBSD.org>.
     25  *
     26  * The 32bit version of the "LP" macros seems a bit past its "sell by"
     27  * date so I have retained only the 64bit version and included it directly
     28  * in this file.
     29  *
     30  * Only minor changes done to interface with the timecounters over in
     31  * sys/kern/kern_clock.c.   Some of the comments below may be (even more)
     32  * confusing and/or plain wrong in that context.
     33  */
     34 
     35 #include <sys/cdefs.h>
     36 /* __FBSDID("$FreeBSD: src/sys/kern/kern_ntptime.c,v 1.59 2005/05/28 14:34:41 rwatson Exp $"); */
     37 __KERNEL_RCSID(0, "$NetBSD: kern_ntptime.c,v 1.47 2008/02/27 19:55:59 matt Exp $");
     38 
     39 #include "opt_ntp.h"
     40 #include "opt_compat_netbsd.h"
     41 
     42 #include <sys/param.h>
     43 #include <sys/resourcevar.h>
     44 #include <sys/systm.h>
     45 #include <sys/kernel.h>
     46 #include <sys/proc.h>
     47 #include <sys/sysctl.h>
     48 #include <sys/timex.h>
     49 #ifdef COMPAT_30
     50 #include <compat/sys/timex.h>
     51 #endif
     52 #include <sys/vnode.h>
     53 #include <sys/kauth.h>
     54 
     55 #include <sys/mount.h>
     56 #include <sys/syscallargs.h>
     57 
     58 #include <sys/cpu.h>
     59 
     60 /*
     61  * Single-precision macros for 64-bit machines
     62  */
     63 typedef int64_t l_fp;
     64 #define L_ADD(v, u)	((v) += (u))
     65 #define L_SUB(v, u)	((v) -= (u))
     66 #define L_ADDHI(v, a)	((v) += (int64_t)(a) << 32)
     67 #define L_NEG(v)	((v) = -(v))
     68 #define L_RSHIFT(v, n) \
     69 	do { \
     70 		if ((v) < 0) \
     71 			(v) = -(-(v) >> (n)); \
     72 		else \
     73 			(v) = (v) >> (n); \
     74 	} while (0)
     75 #define L_MPY(v, a)	((v) *= (a))
     76 #define L_CLR(v)	((v) = 0)
     77 #define L_ISNEG(v)	((v) < 0)
     78 #define L_LINT(v, a)	((v) = (int64_t)(a) << 32)
     79 #define L_GINT(v)	((v) < 0 ? -(-(v) >> 32) : (v) >> 32)
     80 
     81 #ifdef NTP
     82 /*
     83  * Generic NTP kernel interface
     84  *
     85  * These routines constitute the Network Time Protocol (NTP) interfaces
     86  * for user and daemon application programs. The ntp_gettime() routine
     87  * provides the time, maximum error (synch distance) and estimated error
     88  * (dispersion) to client user application programs. The ntp_adjtime()
     89  * routine is used by the NTP daemon to adjust the system clock to an
     90  * externally derived time. The time offset and related variables set by
     91  * this routine are used by other routines in this module to adjust the
     92  * phase and frequency of the clock discipline loop which controls the
     93  * system clock.
     94  *
     95  * When the kernel time is reckoned directly in nanoseconds (NTP_NANO
     96  * defined), the time at each tick interrupt is derived directly from
     97  * the kernel time variable. When the kernel time is reckoned in
     98  * microseconds, (NTP_NANO undefined), the time is derived from the
     99  * kernel time variable together with a variable representing the
    100  * leftover nanoseconds at the last tick interrupt. In either case, the
    101  * current nanosecond time is reckoned from these values plus an
    102  * interpolated value derived by the clock routines in another
    103  * architecture-specific module. The interpolation can use either a
    104  * dedicated counter or a processor cycle counter (PCC) implemented in
    105  * some architectures.
    106  *
    107  * Note that all routines must run at priority splclock or higher.
    108  */
    109 /*
    110  * Phase/frequency-lock loop (PLL/FLL) definitions
    111  *
    112  * The nanosecond clock discipline uses two variable types, time
    113  * variables and frequency variables. Both types are represented as 64-
    114  * bit fixed-point quantities with the decimal point between two 32-bit
    115  * halves. On a 32-bit machine, each half is represented as a single
    116  * word and mathematical operations are done using multiple-precision
    117  * arithmetic. On a 64-bit machine, ordinary computer arithmetic is
    118  * used.
    119  *
    120  * A time variable is a signed 64-bit fixed-point number in ns and
    121  * fraction. It represents the remaining time offset to be amortized
    122  * over succeeding tick interrupts. The maximum time offset is about
    123  * 0.5 s and the resolution is about 2.3e-10 ns.
    124  *
    125  *			1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
    126  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    127  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    128  * |s s s|			 ns				   |
    129  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    130  * |			    fraction				   |
    131  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    132  *
    133  * A frequency variable is a signed 64-bit fixed-point number in ns/s
    134  * and fraction. It represents the ns and fraction to be added to the
    135  * kernel time variable at each second. The maximum frequency offset is
    136  * about +-500000 ns/s and the resolution is about 2.3e-10 ns/s.
    137  *
    138  *			1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
    139  *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    140  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    141  * |s s s s s s s s s s s s s|	          ns/s			   |
    142  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    143  * |			    fraction				   |
    144  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    145  */
    146 /*
    147  * The following variables establish the state of the PLL/FLL and the
    148  * residual time and frequency offset of the local clock.
    149  */
    150 #define SHIFT_PLL	4		/* PLL loop gain (shift) */
    151 #define SHIFT_FLL	2		/* FLL loop gain (shift) */
    152 
    153 static int time_state = TIME_OK;	/* clock state */
    154 static int time_status = STA_UNSYNC;	/* clock status bits */
    155 static long time_tai;			/* TAI offset (s) */
    156 static long time_monitor;		/* last time offset scaled (ns) */
    157 static long time_constant;		/* poll interval (shift) (s) */
    158 static long time_precision = 1;		/* clock precision (ns) */
    159 static long time_maxerror = MAXPHASE / 1000; /* maximum error (us) */
    160 static long time_esterror = MAXPHASE / 1000; /* estimated error (us) */
    161 static long time_reftime;		/* time at last adjustment (s) */
    162 static l_fp time_offset;		/* time offset (ns) */
    163 static l_fp time_freq;			/* frequency offset (ns/s) */
    164 #endif /* NTP */
    165 
    166 static l_fp time_adj;			/* tick adjust (ns/s) */
    167 int64_t time_adjtime;		/* correction from adjtime(2) (usec) */
    168 
    169 extern int time_adjusted;	/* ntp might have changed the system time */
    170 
    171 #ifdef NTP
    172 #ifdef PPS_SYNC
    173 /*
    174  * The following variables are used when a pulse-per-second (PPS) signal
    175  * is available and connected via a modem control lead. They establish
    176  * the engineering parameters of the clock discipline loop when
    177  * controlled by the PPS signal.
    178  */
    179 #define PPS_FAVG	2		/* min freq avg interval (s) (shift) */
    180 #define PPS_FAVGDEF	8		/* default freq avg int (s) (shift) */
    181 #define PPS_FAVGMAX	15		/* max freq avg interval (s) (shift) */
    182 #define PPS_PAVG	4		/* phase avg interval (s) (shift) */
    183 #define PPS_VALID	120		/* PPS signal watchdog max (s) */
    184 #define PPS_MAXWANDER	100000		/* max PPS wander (ns/s) */
    185 #define PPS_POPCORN	2		/* popcorn spike threshold (shift) */
    186 
    187 static struct timespec pps_tf[3];	/* phase median filter */
    188 static l_fp pps_freq;			/* scaled frequency offset (ns/s) */
    189 static long pps_fcount;			/* frequency accumulator */
    190 static long pps_jitter;			/* nominal jitter (ns) */
    191 static long pps_stabil;			/* nominal stability (scaled ns/s) */
    192 static long pps_lastsec;		/* time at last calibration (s) */
    193 static int pps_valid;			/* signal watchdog counter */
    194 static int pps_shift = PPS_FAVG;	/* interval duration (s) (shift) */
    195 static int pps_shiftmax = PPS_FAVGDEF;	/* max interval duration (s) (shift) */
    196 static int pps_intcnt;			/* wander counter */
    197 
    198 /*
    199  * PPS signal quality monitors
    200  */
    201 static long pps_calcnt;			/* calibration intervals */
    202 static long pps_jitcnt;			/* jitter limit exceeded */
    203 static long pps_stbcnt;			/* stability limit exceeded */
    204 static long pps_errcnt;			/* calibration errors */
    205 #endif /* PPS_SYNC */
    206 /*
    207  * End of phase/frequency-lock loop (PLL/FLL) definitions
    208  */
    209 
    210 static void hardupdate(long offset);
    211 
    212 /*
    213  * ntp_gettime() - NTP user application interface
    214  */
    215 void
    216 ntp_gettime(struct ntptimeval *ntv)
    217 {
    218 	nanotime(&ntv->time);
    219 	ntv->maxerror = time_maxerror;
    220 	ntv->esterror = time_esterror;
    221 	ntv->tai = time_tai;
    222 	ntv->time_state = time_state;
    223 }
    224 
    225 /* ARGSUSED */
    226 /*
    227  * ntp_adjtime() - NTP daemon application interface
    228  */
    229 int
    230 sys_ntp_adjtime(struct lwp *l, const struct sys_ntp_adjtime_args *uap, register_t *retval)
    231 {
    232 	/* {
    233 		syscallarg(struct timex *) tp;
    234 	} */
    235 	struct timex ntv;
    236 	int error = 0;
    237 
    238 	error = copyin((void *)SCARG(uap, tp), (void *)&ntv, sizeof(ntv));
    239 	if (error != 0)
    240 		return (error);
    241 
    242 	if (ntv.modes != 0 && (error = kauth_authorize_system(l->l_cred,
    243 	    KAUTH_SYSTEM_TIME, KAUTH_REQ_SYSTEM_TIME_NTPADJTIME, NULL,
    244 	    NULL, NULL)) != 0)
    245 		return (error);
    246 
    247 	ntp_adjtime1(&ntv);
    248 
    249 	error = copyout((void *)&ntv, (void *)SCARG(uap, tp), sizeof(ntv));
    250 	if (!error)
    251 		*retval = ntp_timestatus();
    252 
    253 	return error;
    254 }
    255 
    256 void
    257 ntp_adjtime1(struct timex *ntv)
    258 {
    259 	long freq;
    260 	int modes;
    261 	int s;
    262 
    263 	/*
    264 	 * Update selected clock variables - only the superuser can
    265 	 * change anything. Note that there is no error checking here on
    266 	 * the assumption the superuser should know what it is doing.
    267 	 * Note that either the time constant or TAI offset are loaded
    268 	 * from the ntv.constant member, depending on the mode bits. If
    269 	 * the STA_PLL bit in the status word is cleared, the state and
    270 	 * status words are reset to the initial values at boot.
    271 	 */
    272 	modes = ntv->modes;
    273 	if (modes != 0)
    274 		/* We need to save the system time during shutdown */
    275 		time_adjusted |= 2;
    276 	s = splclock();
    277 	if (modes & MOD_MAXERROR)
    278 		time_maxerror = ntv->maxerror;
    279 	if (modes & MOD_ESTERROR)
    280 		time_esterror = ntv->esterror;
    281 	if (modes & MOD_STATUS) {
    282 		if (time_status & STA_PLL && !(ntv->status & STA_PLL)) {
    283 			time_state = TIME_OK;
    284 			time_status = STA_UNSYNC;
    285 #ifdef PPS_SYNC
    286 			pps_shift = PPS_FAVG;
    287 #endif /* PPS_SYNC */
    288 		}
    289 		time_status &= STA_RONLY;
    290 		time_status |= ntv->status & ~STA_RONLY;
    291 	}
    292 	if (modes & MOD_TIMECONST) {
    293 		if (ntv->constant < 0)
    294 			time_constant = 0;
    295 		else if (ntv->constant > MAXTC)
    296 			time_constant = MAXTC;
    297 		else
    298 			time_constant = ntv->constant;
    299 	}
    300 	if (modes & MOD_TAI) {
    301 		if (ntv->constant > 0)	/* XXX zero & negative numbers ? */
    302 			time_tai = ntv->constant;
    303 	}
    304 #ifdef PPS_SYNC
    305 	if (modes & MOD_PPSMAX) {
    306 		if (ntv->shift < PPS_FAVG)
    307 			pps_shiftmax = PPS_FAVG;
    308 		else if (ntv->shift > PPS_FAVGMAX)
    309 			pps_shiftmax = PPS_FAVGMAX;
    310 		else
    311 			pps_shiftmax = ntv->shift;
    312 	}
    313 #endif /* PPS_SYNC */
    314 	if (modes & MOD_NANO)
    315 		time_status |= STA_NANO;
    316 	if (modes & MOD_MICRO)
    317 		time_status &= ~STA_NANO;
    318 	if (modes & MOD_CLKB)
    319 		time_status |= STA_CLK;
    320 	if (modes & MOD_CLKA)
    321 		time_status &= ~STA_CLK;
    322 	if (modes & MOD_FREQUENCY) {
    323 		freq = (ntv->freq * 1000LL) >> 16;
    324 		if (freq > MAXFREQ)
    325 			L_LINT(time_freq, MAXFREQ);
    326 		else if (freq < -MAXFREQ)
    327 			L_LINT(time_freq, -MAXFREQ);
    328 		else {
    329 			/*
    330 			 * ntv.freq is [PPM * 2^16] = [us/s * 2^16]
    331 			 * time_freq is [ns/s * 2^32]
    332 			 */
    333 			time_freq = ntv->freq * 1000LL * 65536LL;
    334 		}
    335 #ifdef PPS_SYNC
    336 		pps_freq = time_freq;
    337 #endif /* PPS_SYNC */
    338 	}
    339 	if (modes & MOD_OFFSET) {
    340 		if (time_status & STA_NANO)
    341 			hardupdate(ntv->offset);
    342 		else
    343 			hardupdate(ntv->offset * 1000);
    344 	}
    345 
    346 	/*
    347 	 * Retrieve all clock variables. Note that the TAI offset is
    348 	 * returned only by ntp_gettime();
    349 	 */
    350 	if (time_status & STA_NANO)
    351 		ntv->offset = L_GINT(time_offset);
    352 	else
    353 		ntv->offset = L_GINT(time_offset) / 1000; /* XXX rounding ? */
    354 	ntv->freq = L_GINT((time_freq / 1000LL) << 16);
    355 	ntv->maxerror = time_maxerror;
    356 	ntv->esterror = time_esterror;
    357 	ntv->status = time_status;
    358 	ntv->constant = time_constant;
    359 	if (time_status & STA_NANO)
    360 		ntv->precision = time_precision;
    361 	else
    362 		ntv->precision = time_precision / 1000;
    363 	ntv->tolerance = MAXFREQ * SCALE_PPM;
    364 #ifdef PPS_SYNC
    365 	ntv->shift = pps_shift;
    366 	ntv->ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
    367 	if (time_status & STA_NANO)
    368 		ntv->jitter = pps_jitter;
    369 	else
    370 		ntv->jitter = pps_jitter / 1000;
    371 	ntv->stabil = pps_stabil;
    372 	ntv->calcnt = pps_calcnt;
    373 	ntv->errcnt = pps_errcnt;
    374 	ntv->jitcnt = pps_jitcnt;
    375 	ntv->stbcnt = pps_stbcnt;
    376 #endif /* PPS_SYNC */
    377 	splx(s);
    378 }
    379 #endif /* NTP */
    380 
    381 /*
    382  * second_overflow() - called after ntp_tick_adjust()
    383  *
    384  * This routine is ordinarily called immediately following the above
    385  * routine ntp_tick_adjust(). While these two routines are normally
    386  * combined, they are separated here only for the purposes of
    387  * simulation.
    388  */
    389 void
    390 ntp_update_second(int64_t *adjustment, time_t *newsec)
    391 {
    392 	int tickrate;
    393 	l_fp ftemp;		/* 32/64-bit temporary */
    394 
    395 #ifdef NTP
    396 
    397 	/*
    398 	 * On rollover of the second both the nanosecond and microsecond
    399 	 * clocks are updated and the state machine cranked as
    400 	 * necessary. The phase adjustment to be used for the next
    401 	 * second is calculated and the maximum error is increased by
    402 	 * the tolerance.
    403 	 */
    404 	time_maxerror += MAXFREQ / 1000;
    405 
    406 	/*
    407 	 * Leap second processing. If in leap-insert state at
    408 	 * the end of the day, the system clock is set back one
    409 	 * second; if in leap-delete state, the system clock is
    410 	 * set ahead one second. The nano_time() routine or
    411 	 * external clock driver will insure that reported time
    412 	 * is always monotonic.
    413 	 */
    414 	switch (time_state) {
    415 
    416 		/*
    417 		 * No warning.
    418 		 */
    419 		case TIME_OK:
    420 		if (time_status & STA_INS)
    421 			time_state = TIME_INS;
    422 		else if (time_status & STA_DEL)
    423 			time_state = TIME_DEL;
    424 		break;
    425 
    426 		/*
    427 		 * Insert second 23:59:60 following second
    428 		 * 23:59:59.
    429 		 */
    430 		case TIME_INS:
    431 		if (!(time_status & STA_INS))
    432 			time_state = TIME_OK;
    433 		else if ((*newsec) % 86400 == 0) {
    434 			(*newsec)--;
    435 			time_state = TIME_OOP;
    436 			time_tai++;
    437 		}
    438 		break;
    439 
    440 		/*
    441 		 * Delete second 23:59:59.
    442 		 */
    443 		case TIME_DEL:
    444 		if (!(time_status & STA_DEL))
    445 			time_state = TIME_OK;
    446 		else if (((*newsec) + 1) % 86400 == 0) {
    447 			(*newsec)++;
    448 			time_tai--;
    449 			time_state = TIME_WAIT;
    450 		}
    451 		break;
    452 
    453 		/*
    454 		 * Insert second in progress.
    455 		 */
    456 		case TIME_OOP:
    457 			time_state = TIME_WAIT;
    458 		break;
    459 
    460 		/*
    461 		 * Wait for status bits to clear.
    462 		 */
    463 		case TIME_WAIT:
    464 		if (!(time_status & (STA_INS | STA_DEL)))
    465 			time_state = TIME_OK;
    466 	}
    467 
    468 	/*
    469 	 * Compute the total time adjustment for the next second
    470 	 * in ns. The offset is reduced by a factor depending on
    471 	 * whether the PPS signal is operating. Note that the
    472 	 * value is in effect scaled by the clock frequency,
    473 	 * since the adjustment is added at each tick interrupt.
    474 	 */
    475 	ftemp = time_offset;
    476 #ifdef PPS_SYNC
    477 	/* XXX even if PPS signal dies we should finish adjustment ? */
    478 	if (time_status & STA_PPSTIME && time_status &
    479 	    STA_PPSSIGNAL)
    480 		L_RSHIFT(ftemp, pps_shift);
    481 	else
    482 		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
    483 #else
    484 		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
    485 #endif /* PPS_SYNC */
    486 	time_adj = ftemp;
    487 	L_SUB(time_offset, ftemp);
    488 	L_ADD(time_adj, time_freq);
    489 
    490 #ifdef PPS_SYNC
    491 	if (pps_valid > 0)
    492 		pps_valid--;
    493 	else
    494 		time_status &= ~STA_PPSSIGNAL;
    495 #endif /* PPS_SYNC */
    496 #else  /* !NTP */
    497 	L_CLR(time_adj);
    498 #endif /* !NTP */
    499 
    500 	/*
    501 	 * Apply any correction from adjtime(2).  If more than one second
    502 	 * off we slew at a rate of 5ms/s (5000 PPM) else 500us/s (500PPM)
    503 	 * until the last second is slewed the final < 500 usecs.
    504 	 */
    505 	if (time_adjtime != 0) {
    506 		if (time_adjtime > 1000000)
    507 			tickrate = 5000;
    508 		else if (time_adjtime < -1000000)
    509 			tickrate = -5000;
    510 		else if (time_adjtime > 500)
    511 			tickrate = 500;
    512 		else if (time_adjtime < -500)
    513 			tickrate = -500;
    514 		else
    515 			tickrate = time_adjtime;
    516 		time_adjtime -= tickrate;
    517 		L_LINT(ftemp, tickrate * 1000);
    518 		L_ADD(time_adj, ftemp);
    519 	}
    520 	*adjustment = time_adj;
    521 }
    522 
    523 /*
    524  * ntp_init() - initialize variables and structures
    525  *
    526  * This routine must be called after the kernel variables hz and tick
    527  * are set or changed and before the next tick interrupt. In this
    528  * particular implementation, these values are assumed set elsewhere in
    529  * the kernel. The design allows the clock frequency and tick interval
    530  * to be changed while the system is running. So, this routine should
    531  * probably be integrated with the code that does that.
    532  */
    533 void
    534 ntp_init(void)
    535 {
    536 
    537 	/*
    538 	 * The following variables are initialized only at startup. Only
    539 	 * those structures not cleared by the compiler need to be
    540 	 * initialized, and these only in the simulator. In the actual
    541 	 * kernel, any nonzero values here will quickly evaporate.
    542 	 */
    543 	L_CLR(time_adj);
    544 #ifdef NTP
    545 	L_CLR(time_offset);
    546 	L_CLR(time_freq);
    547 #ifdef PPS_SYNC
    548 	pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
    549 	pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
    550 	pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
    551 	pps_fcount = 0;
    552 	L_CLR(pps_freq);
    553 #endif /* PPS_SYNC */
    554 #endif
    555 }
    556 
    557 #ifdef NTP
    558 /*
    559  * hardupdate() - local clock update
    560  *
    561  * This routine is called by ntp_adjtime() to update the local clock
    562  * phase and frequency. The implementation is of an adaptive-parameter,
    563  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
    564  * time and frequency offset estimates for each call. If the kernel PPS
    565  * discipline code is configured (PPS_SYNC), the PPS signal itself
    566  * determines the new time offset, instead of the calling argument.
    567  * Presumably, calls to ntp_adjtime() occur only when the caller
    568  * believes the local clock is valid within some bound (+-128 ms with
    569  * NTP). If the caller's time is far different than the PPS time, an
    570  * argument will ensue, and it's not clear who will lose.
    571  *
    572  * For uncompensated quartz crystal oscillators and nominal update
    573  * intervals less than 256 s, operation should be in phase-lock mode,
    574  * where the loop is disciplined to phase. For update intervals greater
    575  * than 1024 s, operation should be in frequency-lock mode, where the
    576  * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
    577  * is selected by the STA_MODE status bit.
    578  *
    579  * Note: splclock() is in effect.
    580  */
    581 void
    582 hardupdate(long offset)
    583 {
    584 	long mtemp;
    585 	l_fp ftemp;
    586 
    587 	/*
    588 	 * Select how the phase is to be controlled and from which
    589 	 * source. If the PPS signal is present and enabled to
    590 	 * discipline the time, the PPS offset is used; otherwise, the
    591 	 * argument offset is used.
    592 	 */
    593 	if (!(time_status & STA_PLL))
    594 		return;
    595 	if (!(time_status & STA_PPSTIME && time_status &
    596 	    STA_PPSSIGNAL)) {
    597 		if (offset > MAXPHASE)
    598 			time_monitor = MAXPHASE;
    599 		else if (offset < -MAXPHASE)
    600 			time_monitor = -MAXPHASE;
    601 		else
    602 			time_monitor = offset;
    603 		L_LINT(time_offset, time_monitor);
    604 	}
    605 
    606 	/*
    607 	 * Select how the frequency is to be controlled and in which
    608 	 * mode (PLL or FLL). If the PPS signal is present and enabled
    609 	 * to discipline the frequency, the PPS frequency is used;
    610 	 * otherwise, the argument offset is used to compute it.
    611 	 */
    612 	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
    613 		time_reftime = time_second;
    614 		return;
    615 	}
    616 	if (time_status & STA_FREQHOLD || time_reftime == 0)
    617 		time_reftime = time_second;
    618 	mtemp = time_second - time_reftime;
    619 	L_LINT(ftemp, time_monitor);
    620 	L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
    621 	L_MPY(ftemp, mtemp);
    622 	L_ADD(time_freq, ftemp);
    623 	time_status &= ~STA_MODE;
    624 	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp >
    625 	    MAXSEC)) {
    626 		L_LINT(ftemp, (time_monitor << 4) / mtemp);
    627 		L_RSHIFT(ftemp, SHIFT_FLL + 4);
    628 		L_ADD(time_freq, ftemp);
    629 		time_status |= STA_MODE;
    630 	}
    631 	time_reftime = time_second;
    632 	if (L_GINT(time_freq) > MAXFREQ)
    633 		L_LINT(time_freq, MAXFREQ);
    634 	else if (L_GINT(time_freq) < -MAXFREQ)
    635 		L_LINT(time_freq, -MAXFREQ);
    636 }
    637 
    638 #ifdef PPS_SYNC
    639 /*
    640  * hardpps() - discipline CPU clock oscillator to external PPS signal
    641  *
    642  * This routine is called at each PPS interrupt in order to discipline
    643  * the CPU clock oscillator to the PPS signal. It measures the PPS phase
    644  * and leaves it in a handy spot for the hardclock() routine. It
    645  * integrates successive PPS phase differences and calculates the
    646  * frequency offset. This is used in hardclock() to discipline the CPU
    647  * clock oscillator so that intrinsic frequency error is cancelled out.
    648  * The code requires the caller to capture the time and hardware counter
    649  * value at the on-time PPS signal transition.
    650  *
    651  * Note that, on some Unix systems, this routine runs at an interrupt
    652  * priority level higher than the timer interrupt routine hardclock().
    653  * Therefore, the variables used are distinct from the hardclock()
    654  * variables, except for certain exceptions: The PPS frequency pps_freq
    655  * and phase pps_offset variables are determined by this routine and
    656  * updated atomically. The time_tolerance variable can be considered a
    657  * constant, since it is infrequently changed, and then only when the
    658  * PPS signal is disabled. The watchdog counter pps_valid is updated
    659  * once per second by hardclock() and is atomically cleared in this
    660  * routine.
    661  */
    662 void
    663 hardpps(struct timespec *tsp,		/* time at PPS */
    664 	long nsec			/* hardware counter at PPS */)
    665 {
    666 	long u_sec, u_nsec, v_nsec; /* temps */
    667 	l_fp ftemp;
    668 
    669 	/*
    670 	 * The signal is first processed by a range gate and frequency
    671 	 * discriminator. The range gate rejects noise spikes outside
    672 	 * the range +-500 us. The frequency discriminator rejects input
    673 	 * signals with apparent frequency outside the range 1 +-500
    674 	 * PPM. If two hits occur in the same second, we ignore the
    675 	 * later hit; if not and a hit occurs outside the range gate,
    676 	 * keep the later hit for later comparison, but do not process
    677 	 * it.
    678 	 */
    679 	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
    680 	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
    681 	pps_valid = PPS_VALID;
    682 	u_sec = tsp->tv_sec;
    683 	u_nsec = tsp->tv_nsec;
    684 	if (u_nsec >= (NANOSECOND >> 1)) {
    685 		u_nsec -= NANOSECOND;
    686 		u_sec++;
    687 	}
    688 	v_nsec = u_nsec - pps_tf[0].tv_nsec;
    689 	if (u_sec == pps_tf[0].tv_sec && v_nsec < NANOSECOND -
    690 	    MAXFREQ)
    691 		return;
    692 	pps_tf[2] = pps_tf[1];
    693 	pps_tf[1] = pps_tf[0];
    694 	pps_tf[0].tv_sec = u_sec;
    695 	pps_tf[0].tv_nsec = u_nsec;
    696 
    697 	/*
    698 	 * Compute the difference between the current and previous
    699 	 * counter values. If the difference exceeds 0.5 s, assume it
    700 	 * has wrapped around, so correct 1.0 s. If the result exceeds
    701 	 * the tick interval, the sample point has crossed a tick
    702 	 * boundary during the last second, so correct the tick. Very
    703 	 * intricate.
    704 	 */
    705 	u_nsec = nsec;
    706 	if (u_nsec > (NANOSECOND >> 1))
    707 		u_nsec -= NANOSECOND;
    708 	else if (u_nsec < -(NANOSECOND >> 1))
    709 		u_nsec += NANOSECOND;
    710 	pps_fcount += u_nsec;
    711 	if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ)
    712 		return;
    713 	time_status &= ~STA_PPSJITTER;
    714 
    715 	/*
    716 	 * A three-stage median filter is used to help denoise the PPS
    717 	 * time. The median sample becomes the time offset estimate; the
    718 	 * difference between the other two samples becomes the time
    719 	 * dispersion (jitter) estimate.
    720 	 */
    721 	if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
    722 		if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
    723 			v_nsec = pps_tf[1].tv_nsec;	/* 0 1 2 */
    724 			u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
    725 		} else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
    726 			v_nsec = pps_tf[0].tv_nsec;	/* 2 0 1 */
    727 			u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
    728 		} else {
    729 			v_nsec = pps_tf[2].tv_nsec;	/* 0 2 1 */
    730 			u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
    731 		}
    732 	} else {
    733 		if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
    734 			v_nsec = pps_tf[1].tv_nsec;	/* 2 1 0 */
    735 			u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
    736 		} else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
    737 			v_nsec = pps_tf[0].tv_nsec;	/* 1 0 2 */
    738 			u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
    739 		} else {
    740 			v_nsec = pps_tf[2].tv_nsec;	/* 1 2 0 */
    741 			u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
    742 		}
    743 	}
    744 
    745 	/*
    746 	 * Nominal jitter is due to PPS signal noise and interrupt
    747 	 * latency. If it exceeds the popcorn threshold, the sample is
    748 	 * discarded. otherwise, if so enabled, the time offset is
    749 	 * updated. We can tolerate a modest loss of data here without
    750 	 * much degrading time accuracy.
    751 	 */
    752 	if (u_nsec > (pps_jitter << PPS_POPCORN)) {
    753 		time_status |= STA_PPSJITTER;
    754 		pps_jitcnt++;
    755 	} else if (time_status & STA_PPSTIME) {
    756 		time_monitor = -v_nsec;
    757 		L_LINT(time_offset, time_monitor);
    758 	}
    759 	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
    760 	u_sec = pps_tf[0].tv_sec - pps_lastsec;
    761 	if (u_sec < (1 << pps_shift))
    762 		return;
    763 
    764 	/*
    765 	 * At the end of the calibration interval the difference between
    766 	 * the first and last counter values becomes the scaled
    767 	 * frequency. It will later be divided by the length of the
    768 	 * interval to determine the frequency update. If the frequency
    769 	 * exceeds a sanity threshold, or if the actual calibration
    770 	 * interval is not equal to the expected length, the data are
    771 	 * discarded. We can tolerate a modest loss of data here without
    772 	 * much degrading frequency accuracy.
    773 	 */
    774 	pps_calcnt++;
    775 	v_nsec = -pps_fcount;
    776 	pps_lastsec = pps_tf[0].tv_sec;
    777 	pps_fcount = 0;
    778 	u_nsec = MAXFREQ << pps_shift;
    779 	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 <<
    780 	    pps_shift)) {
    781 		time_status |= STA_PPSERROR;
    782 		pps_errcnt++;
    783 		return;
    784 	}
    785 
    786 	/*
    787 	 * Here the raw frequency offset and wander (stability) is
    788 	 * calculated. If the wander is less than the wander threshold
    789 	 * for four consecutive averaging intervals, the interval is
    790 	 * doubled; if it is greater than the threshold for four
    791 	 * consecutive intervals, the interval is halved. The scaled
    792 	 * frequency offset is converted to frequency offset. The
    793 	 * stability metric is calculated as the average of recent
    794 	 * frequency changes, but is used only for performance
    795 	 * monitoring.
    796 	 */
    797 	L_LINT(ftemp, v_nsec);
    798 	L_RSHIFT(ftemp, pps_shift);
    799 	L_SUB(ftemp, pps_freq);
    800 	u_nsec = L_GINT(ftemp);
    801 	if (u_nsec > PPS_MAXWANDER) {
    802 		L_LINT(ftemp, PPS_MAXWANDER);
    803 		pps_intcnt--;
    804 		time_status |= STA_PPSWANDER;
    805 		pps_stbcnt++;
    806 	} else if (u_nsec < -PPS_MAXWANDER) {
    807 		L_LINT(ftemp, -PPS_MAXWANDER);
    808 		pps_intcnt--;
    809 		time_status |= STA_PPSWANDER;
    810 		pps_stbcnt++;
    811 	} else {
    812 		pps_intcnt++;
    813 	}
    814 	if (pps_intcnt >= 4) {
    815 		pps_intcnt = 4;
    816 		if (pps_shift < pps_shiftmax) {
    817 			pps_shift++;
    818 			pps_intcnt = 0;
    819 		}
    820 	} else if (pps_intcnt <= -4 || pps_shift > pps_shiftmax) {
    821 		pps_intcnt = -4;
    822 		if (pps_shift > PPS_FAVG) {
    823 			pps_shift--;
    824 			pps_intcnt = 0;
    825 		}
    826 	}
    827 	if (u_nsec < 0)
    828 		u_nsec = -u_nsec;
    829 	pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
    830 
    831 	/*
    832 	 * The PPS frequency is recalculated and clamped to the maximum
    833 	 * MAXFREQ. If enabled, the system clock frequency is updated as
    834 	 * well.
    835 	 */
    836 	L_ADD(pps_freq, ftemp);
    837 	u_nsec = L_GINT(pps_freq);
    838 	if (u_nsec > MAXFREQ)
    839 		L_LINT(pps_freq, MAXFREQ);
    840 	else if (u_nsec < -MAXFREQ)
    841 		L_LINT(pps_freq, -MAXFREQ);
    842 	if (time_status & STA_PPSFREQ)
    843 		time_freq = pps_freq;
    844 }
    845 #endif /* PPS_SYNC */
    846 #endif /* NTP */
    847 
    848 #ifdef NTP
    849 int
    850 ntp_timestatus(void)
    851 {
    852 	/*
    853 	 * Status word error decode. If any of these conditions
    854 	 * occur, an error is returned, instead of the status
    855 	 * word. Most applications will care only about the fact
    856 	 * the system clock may not be trusted, not about the
    857 	 * details.
    858 	 *
    859 	 * Hardware or software error
    860 	 */
    861 	if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
    862 
    863 	/*
    864 	 * PPS signal lost when either time or frequency
    865 	 * synchronization requested
    866 	 */
    867 	    (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
    868 	     !(time_status & STA_PPSSIGNAL)) ||
    869 
    870 	/*
    871 	 * PPS jitter exceeded when time synchronization
    872 	 * requested
    873 	 */
    874 	    (time_status & STA_PPSTIME &&
    875 	     time_status & STA_PPSJITTER) ||
    876 
    877 	/*
    878 	 * PPS wander exceeded or calibration error when
    879 	 * frequency synchronization requested
    880 	 */
    881 	    (time_status & STA_PPSFREQ &&
    882 	     time_status & (STA_PPSWANDER | STA_PPSERROR)))
    883 		return (TIME_ERROR);
    884 	else
    885 		return (time_state);
    886 }
    887 
    888 /*ARGSUSED*/
    889 /*
    890  * ntp_gettime() - NTP user application interface
    891  */
    892 int
    893 sys___ntp_gettime30(struct lwp *l, const struct sys___ntp_gettime30_args *uap, register_t *retval)
    894 {
    895 	/* {
    896 		syscallarg(struct ntptimeval *) ntvp;
    897 	} */
    898 	struct ntptimeval ntv;
    899 	int error = 0;
    900 
    901 	if (SCARG(uap, ntvp)) {
    902 		ntp_gettime(&ntv);
    903 
    904 		error = copyout((void *)&ntv, (void *)SCARG(uap, ntvp),
    905 				sizeof(ntv));
    906 	}
    907 	if (!error) {
    908 		*retval = ntp_timestatus();
    909 	}
    910 	return(error);
    911 }
    912 
    913 #ifdef COMPAT_30
    914 int
    915 compat_30_sys_ntp_gettime(struct lwp *l, const struct compat_30_sys_ntp_gettime_args *uap, register_t *retval)
    916 {
    917 	/* {
    918 		syscallarg(struct ntptimeval30 *) ontvp;
    919 	} */
    920 	struct ntptimeval ntv;
    921 	struct ntptimeval30 ontv;
    922 	int error = 0;
    923 
    924 	if (SCARG(uap, ntvp)) {
    925 		ntp_gettime(&ntv);
    926 		TIMESPEC_TO_TIMEVAL(&ontv.time, &ntv.time);
    927 		ontv.maxerror = ntv.maxerror;
    928 		ontv.esterror = ntv.esterror;
    929 
    930 		error = copyout((void *)&ontv, (void *)SCARG(uap, ntvp),
    931 				sizeof(ontv));
    932  	}
    933 	if (!error)
    934 		*retval = ntp_timestatus();
    935 
    936 	return (error);
    937 }
    938 #endif
    939 
    940 /*
    941  * return information about kernel precision timekeeping
    942  */
    943 static int
    944 sysctl_kern_ntptime(SYSCTLFN_ARGS)
    945 {
    946 	struct sysctlnode node;
    947 	struct ntptimeval ntv;
    948 
    949 	ntp_gettime(&ntv);
    950 
    951 	node = *rnode;
    952 	node.sysctl_data = &ntv;
    953 	node.sysctl_size = sizeof(ntv);
    954 	return (sysctl_lookup(SYSCTLFN_CALL(&node)));
    955 }
    956 
    957 SYSCTL_SETUP(sysctl_kern_ntptime_setup, "sysctl kern.ntptime node setup")
    958 {
    959 
    960 	sysctl_createv(clog, 0, NULL, NULL,
    961 		       CTLFLAG_PERMANENT,
    962 		       CTLTYPE_NODE, "kern", NULL,
    963 		       NULL, 0, NULL, 0,
    964 		       CTL_KERN, CTL_EOL);
    965 
    966 	sysctl_createv(clog, 0, NULL, NULL,
    967 		       CTLFLAG_PERMANENT,
    968 		       CTLTYPE_STRUCT, "ntptime",
    969 		       SYSCTL_DESCR("Kernel clock values for NTP"),
    970 		       sysctl_kern_ntptime, 0, NULL,
    971 		       sizeof(struct ntptimeval),
    972 		       CTL_KERN, KERN_NTPTIME, CTL_EOL);
    973 }
    974 #else /* !NTP */
    975 /* For some reason, raising SIGSYS (as sys_nosys would) is problematic. */
    976 
    977 int
    978 sys___ntp_gettime30(struct lwp *l, const struct sys___ntp_gettime30_args *uap, register_t *retval)
    979 {
    980 
    981 	return(ENOSYS);
    982 }
    983 
    984 #ifdef COMPAT_30
    985 int
    986 compat_30_sys_ntp_gettime(struct lwp *l, const struct compat_30_sys_ntp_gettime_args *uap, register_t *retval)
    987 {
    988 
    989  	return(ENOSYS);
    990 }
    991 #endif
    992 #endif /* !NTP */
    993