Home | History | Annotate | Line # | Download | only in kern
kern_ntptime.c revision 1.44.2.1
      1 /*	$NetBSD: kern_ntptime.c,v 1.44.2.1 2008/02/18 21:06:46 mjf 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.44.2.1 2008/02/18 21:06:46 mjf 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(ntv)
    217 	struct ntptimeval *ntv;
    218 {
    219 	nanotime(&ntv->time);
    220 	ntv->maxerror = time_maxerror;
    221 	ntv->esterror = time_esterror;
    222 	ntv->tai = time_tai;
    223 	ntv->time_state = time_state;
    224 }
    225 
    226 /* ARGSUSED */
    227 /*
    228  * ntp_adjtime() - NTP daemon application interface
    229  */
    230 int
    231 sys_ntp_adjtime(l, v, retval)
    232 	struct lwp *l;
    233 	void *v;
    234 	register_t *retval;
    235 {
    236 	struct sys_ntp_adjtime_args /* {
    237 		syscallarg(struct timex *) tp;
    238 	} */ *uap = v;
    239 	struct timex ntv;
    240 	int error = 0;
    241 
    242 	error = copyin((void *)SCARG(uap, tp), (void *)&ntv, sizeof(ntv));
    243 	if (error != 0)
    244 		return (error);
    245 
    246 	if (ntv.modes != 0 && (error = kauth_authorize_system(l->l_cred,
    247 	    KAUTH_SYSTEM_TIME, KAUTH_REQ_SYSTEM_TIME_NTPADJTIME, NULL,
    248 	    NULL, NULL)) != 0)
    249 		return (error);
    250 
    251 	ntp_adjtime1(&ntv);
    252 
    253 	error = copyout((void *)&ntv, (void *)SCARG(uap, tp), sizeof(ntv));
    254 	if (!error)
    255 		*retval = ntp_timestatus();
    256 
    257 	return error;
    258 }
    259 
    260 void
    261 ntp_adjtime1(ntv)
    262 	struct timex *ntv;
    263 {
    264 	long freq;
    265 	int modes;
    266 	int s;
    267 
    268 	/*
    269 	 * Update selected clock variables - only the superuser can
    270 	 * change anything. Note that there is no error checking here on
    271 	 * the assumption the superuser should know what it is doing.
    272 	 * Note that either the time constant or TAI offset are loaded
    273 	 * from the ntv.constant member, depending on the mode bits. If
    274 	 * the STA_PLL bit in the status word is cleared, the state and
    275 	 * status words are reset to the initial values at boot.
    276 	 */
    277 	modes = ntv->modes;
    278 	if (modes != 0)
    279 		/* We need to save the system time during shutdown */
    280 		time_adjusted |= 2;
    281 	s = splclock();
    282 	if (modes & MOD_MAXERROR)
    283 		time_maxerror = ntv->maxerror;
    284 	if (modes & MOD_ESTERROR)
    285 		time_esterror = ntv->esterror;
    286 	if (modes & MOD_STATUS) {
    287 		if (time_status & STA_PLL && !(ntv->status & STA_PLL)) {
    288 			time_state = TIME_OK;
    289 			time_status = STA_UNSYNC;
    290 #ifdef PPS_SYNC
    291 			pps_shift = PPS_FAVG;
    292 #endif /* PPS_SYNC */
    293 		}
    294 		time_status &= STA_RONLY;
    295 		time_status |= ntv->status & ~STA_RONLY;
    296 	}
    297 	if (modes & MOD_TIMECONST) {
    298 		if (ntv->constant < 0)
    299 			time_constant = 0;
    300 		else if (ntv->constant > MAXTC)
    301 			time_constant = MAXTC;
    302 		else
    303 			time_constant = ntv->constant;
    304 	}
    305 	if (modes & MOD_TAI) {
    306 		if (ntv->constant > 0)	/* XXX zero & negative numbers ? */
    307 			time_tai = ntv->constant;
    308 	}
    309 #ifdef PPS_SYNC
    310 	if (modes & MOD_PPSMAX) {
    311 		if (ntv->shift < PPS_FAVG)
    312 			pps_shiftmax = PPS_FAVG;
    313 		else if (ntv->shift > PPS_FAVGMAX)
    314 			pps_shiftmax = PPS_FAVGMAX;
    315 		else
    316 			pps_shiftmax = ntv->shift;
    317 	}
    318 #endif /* PPS_SYNC */
    319 	if (modes & MOD_NANO)
    320 		time_status |= STA_NANO;
    321 	if (modes & MOD_MICRO)
    322 		time_status &= ~STA_NANO;
    323 	if (modes & MOD_CLKB)
    324 		time_status |= STA_CLK;
    325 	if (modes & MOD_CLKA)
    326 		time_status &= ~STA_CLK;
    327 	if (modes & MOD_FREQUENCY) {
    328 		freq = (ntv->freq * 1000LL) >> 16;
    329 		if (freq > MAXFREQ)
    330 			L_LINT(time_freq, MAXFREQ);
    331 		else if (freq < -MAXFREQ)
    332 			L_LINT(time_freq, -MAXFREQ);
    333 		else {
    334 			/*
    335 			 * ntv.freq is [PPM * 2^16] = [us/s * 2^16]
    336 			 * time_freq is [ns/s * 2^32]
    337 			 */
    338 			time_freq = ntv->freq * 1000LL * 65536LL;
    339 		}
    340 #ifdef PPS_SYNC
    341 		pps_freq = time_freq;
    342 #endif /* PPS_SYNC */
    343 	}
    344 	if (modes & MOD_OFFSET) {
    345 		if (time_status & STA_NANO)
    346 			hardupdate(ntv->offset);
    347 		else
    348 			hardupdate(ntv->offset * 1000);
    349 	}
    350 
    351 	/*
    352 	 * Retrieve all clock variables. Note that the TAI offset is
    353 	 * returned only by ntp_gettime();
    354 	 */
    355 	if (time_status & STA_NANO)
    356 		ntv->offset = L_GINT(time_offset);
    357 	else
    358 		ntv->offset = L_GINT(time_offset) / 1000; /* XXX rounding ? */
    359 	ntv->freq = L_GINT((time_freq / 1000LL) << 16);
    360 	ntv->maxerror = time_maxerror;
    361 	ntv->esterror = time_esterror;
    362 	ntv->status = time_status;
    363 	ntv->constant = time_constant;
    364 	if (time_status & STA_NANO)
    365 		ntv->precision = time_precision;
    366 	else
    367 		ntv->precision = time_precision / 1000;
    368 	ntv->tolerance = MAXFREQ * SCALE_PPM;
    369 #ifdef PPS_SYNC
    370 	ntv->shift = pps_shift;
    371 	ntv->ppsfreq = L_GINT((pps_freq / 1000LL) << 16);
    372 	if (time_status & STA_NANO)
    373 		ntv->jitter = pps_jitter;
    374 	else
    375 		ntv->jitter = pps_jitter / 1000;
    376 	ntv->stabil = pps_stabil;
    377 	ntv->calcnt = pps_calcnt;
    378 	ntv->errcnt = pps_errcnt;
    379 	ntv->jitcnt = pps_jitcnt;
    380 	ntv->stbcnt = pps_stbcnt;
    381 #endif /* PPS_SYNC */
    382 	splx(s);
    383 }
    384 #endif /* NTP */
    385 
    386 /*
    387  * second_overflow() - called after ntp_tick_adjust()
    388  *
    389  * This routine is ordinarily called immediately following the above
    390  * routine ntp_tick_adjust(). While these two routines are normally
    391  * combined, they are separated here only for the purposes of
    392  * simulation.
    393  */
    394 void
    395 ntp_update_second(int64_t *adjustment, time_t *newsec)
    396 {
    397 	int tickrate;
    398 	l_fp ftemp;		/* 32/64-bit temporary */
    399 
    400 #ifdef NTP
    401 
    402 	/*
    403 	 * On rollover of the second both the nanosecond and microsecond
    404 	 * clocks are updated and the state machine cranked as
    405 	 * necessary. The phase adjustment to be used for the next
    406 	 * second is calculated and the maximum error is increased by
    407 	 * the tolerance.
    408 	 */
    409 	time_maxerror += MAXFREQ / 1000;
    410 
    411 	/*
    412 	 * Leap second processing. If in leap-insert state at
    413 	 * the end of the day, the system clock is set back one
    414 	 * second; if in leap-delete state, the system clock is
    415 	 * set ahead one second. The nano_time() routine or
    416 	 * external clock driver will insure that reported time
    417 	 * is always monotonic.
    418 	 */
    419 	switch (time_state) {
    420 
    421 		/*
    422 		 * No warning.
    423 		 */
    424 		case TIME_OK:
    425 		if (time_status & STA_INS)
    426 			time_state = TIME_INS;
    427 		else if (time_status & STA_DEL)
    428 			time_state = TIME_DEL;
    429 		break;
    430 
    431 		/*
    432 		 * Insert second 23:59:60 following second
    433 		 * 23:59:59.
    434 		 */
    435 		case TIME_INS:
    436 		if (!(time_status & STA_INS))
    437 			time_state = TIME_OK;
    438 		else if ((*newsec) % 86400 == 0) {
    439 			(*newsec)--;
    440 			time_state = TIME_OOP;
    441 			time_tai++;
    442 		}
    443 		break;
    444 
    445 		/*
    446 		 * Delete second 23:59:59.
    447 		 */
    448 		case TIME_DEL:
    449 		if (!(time_status & STA_DEL))
    450 			time_state = TIME_OK;
    451 		else if (((*newsec) + 1) % 86400 == 0) {
    452 			(*newsec)++;
    453 			time_tai--;
    454 			time_state = TIME_WAIT;
    455 		}
    456 		break;
    457 
    458 		/*
    459 		 * Insert second in progress.
    460 		 */
    461 		case TIME_OOP:
    462 			time_state = TIME_WAIT;
    463 		break;
    464 
    465 		/*
    466 		 * Wait for status bits to clear.
    467 		 */
    468 		case TIME_WAIT:
    469 		if (!(time_status & (STA_INS | STA_DEL)))
    470 			time_state = TIME_OK;
    471 	}
    472 
    473 	/*
    474 	 * Compute the total time adjustment for the next second
    475 	 * in ns. The offset is reduced by a factor depending on
    476 	 * whether the PPS signal is operating. Note that the
    477 	 * value is in effect scaled by the clock frequency,
    478 	 * since the adjustment is added at each tick interrupt.
    479 	 */
    480 	ftemp = time_offset;
    481 #ifdef PPS_SYNC
    482 	/* XXX even if PPS signal dies we should finish adjustment ? */
    483 	if (time_status & STA_PPSTIME && time_status &
    484 	    STA_PPSSIGNAL)
    485 		L_RSHIFT(ftemp, pps_shift);
    486 	else
    487 		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
    488 #else
    489 		L_RSHIFT(ftemp, SHIFT_PLL + time_constant);
    490 #endif /* PPS_SYNC */
    491 	time_adj = ftemp;
    492 	L_SUB(time_offset, ftemp);
    493 	L_ADD(time_adj, time_freq);
    494 
    495 #ifdef PPS_SYNC
    496 	if (pps_valid > 0)
    497 		pps_valid--;
    498 	else
    499 		time_status &= ~STA_PPSSIGNAL;
    500 #endif /* PPS_SYNC */
    501 #else  /* !NTP */
    502 	L_CLR(time_adj);
    503 #endif /* !NTP */
    504 
    505 	/*
    506 	 * Apply any correction from adjtime(2).  If more than one second
    507 	 * off we slew at a rate of 5ms/s (5000 PPM) else 500us/s (500PPM)
    508 	 * until the last second is slewed the final < 500 usecs.
    509 	 */
    510 	if (time_adjtime != 0) {
    511 		if (time_adjtime > 1000000)
    512 			tickrate = 5000;
    513 		else if (time_adjtime < -1000000)
    514 			tickrate = -5000;
    515 		else if (time_adjtime > 500)
    516 			tickrate = 500;
    517 		else if (time_adjtime < -500)
    518 			tickrate = -500;
    519 		else
    520 			tickrate = time_adjtime;
    521 		time_adjtime -= tickrate;
    522 		L_LINT(ftemp, tickrate * 1000);
    523 		L_ADD(time_adj, ftemp);
    524 	}
    525 	*adjustment = time_adj;
    526 }
    527 
    528 /*
    529  * ntp_init() - initialize variables and structures
    530  *
    531  * This routine must be called after the kernel variables hz and tick
    532  * are set or changed and before the next tick interrupt. In this
    533  * particular implementation, these values are assumed set elsewhere in
    534  * the kernel. The design allows the clock frequency and tick interval
    535  * to be changed while the system is running. So, this routine should
    536  * probably be integrated with the code that does that.
    537  */
    538 void
    539 ntp_init(void)
    540 {
    541 
    542 	/*
    543 	 * The following variables are initialized only at startup. Only
    544 	 * those structures not cleared by the compiler need to be
    545 	 * initialized, and these only in the simulator. In the actual
    546 	 * kernel, any nonzero values here will quickly evaporate.
    547 	 */
    548 	L_CLR(time_adj);
    549 #ifdef NTP
    550 	L_CLR(time_offset);
    551 	L_CLR(time_freq);
    552 #ifdef PPS_SYNC
    553 	pps_tf[0].tv_sec = pps_tf[0].tv_nsec = 0;
    554 	pps_tf[1].tv_sec = pps_tf[1].tv_nsec = 0;
    555 	pps_tf[2].tv_sec = pps_tf[2].tv_nsec = 0;
    556 	pps_fcount = 0;
    557 	L_CLR(pps_freq);
    558 #endif /* PPS_SYNC */
    559 #endif
    560 }
    561 
    562 #ifdef NTP
    563 /*
    564  * hardupdate() - local clock update
    565  *
    566  * This routine is called by ntp_adjtime() to update the local clock
    567  * phase and frequency. The implementation is of an adaptive-parameter,
    568  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
    569  * time and frequency offset estimates for each call. If the kernel PPS
    570  * discipline code is configured (PPS_SYNC), the PPS signal itself
    571  * determines the new time offset, instead of the calling argument.
    572  * Presumably, calls to ntp_adjtime() occur only when the caller
    573  * believes the local clock is valid within some bound (+-128 ms with
    574  * NTP). If the caller's time is far different than the PPS time, an
    575  * argument will ensue, and it's not clear who will lose.
    576  *
    577  * For uncompensated quartz crystal oscillators and nominal update
    578  * intervals less than 256 s, operation should be in phase-lock mode,
    579  * where the loop is disciplined to phase. For update intervals greater
    580  * than 1024 s, operation should be in frequency-lock mode, where the
    581  * loop is disciplined to frequency. Between 256 s and 1024 s, the mode
    582  * is selected by the STA_MODE status bit.
    583  *
    584  * Note: splclock() is in effect.
    585  */
    586 void
    587 hardupdate(long offset)
    588 {
    589 	long mtemp;
    590 	l_fp ftemp;
    591 
    592 	/*
    593 	 * Select how the phase is to be controlled and from which
    594 	 * source. If the PPS signal is present and enabled to
    595 	 * discipline the time, the PPS offset is used; otherwise, the
    596 	 * argument offset is used.
    597 	 */
    598 	if (!(time_status & STA_PLL))
    599 		return;
    600 	if (!(time_status & STA_PPSTIME && time_status &
    601 	    STA_PPSSIGNAL)) {
    602 		if (offset > MAXPHASE)
    603 			time_monitor = MAXPHASE;
    604 		else if (offset < -MAXPHASE)
    605 			time_monitor = -MAXPHASE;
    606 		else
    607 			time_monitor = offset;
    608 		L_LINT(time_offset, time_monitor);
    609 	}
    610 
    611 	/*
    612 	 * Select how the frequency is to be controlled and in which
    613 	 * mode (PLL or FLL). If the PPS signal is present and enabled
    614 	 * to discipline the frequency, the PPS frequency is used;
    615 	 * otherwise, the argument offset is used to compute it.
    616 	 */
    617 	if (time_status & STA_PPSFREQ && time_status & STA_PPSSIGNAL) {
    618 		time_reftime = time_second;
    619 		return;
    620 	}
    621 	if (time_status & STA_FREQHOLD || time_reftime == 0)
    622 		time_reftime = time_second;
    623 	mtemp = time_second - time_reftime;
    624 	L_LINT(ftemp, time_monitor);
    625 	L_RSHIFT(ftemp, (SHIFT_PLL + 2 + time_constant) << 1);
    626 	L_MPY(ftemp, mtemp);
    627 	L_ADD(time_freq, ftemp);
    628 	time_status &= ~STA_MODE;
    629 	if (mtemp >= MINSEC && (time_status & STA_FLL || mtemp >
    630 	    MAXSEC)) {
    631 		L_LINT(ftemp, (time_monitor << 4) / mtemp);
    632 		L_RSHIFT(ftemp, SHIFT_FLL + 4);
    633 		L_ADD(time_freq, ftemp);
    634 		time_status |= STA_MODE;
    635 	}
    636 	time_reftime = time_second;
    637 	if (L_GINT(time_freq) > MAXFREQ)
    638 		L_LINT(time_freq, MAXFREQ);
    639 	else if (L_GINT(time_freq) < -MAXFREQ)
    640 		L_LINT(time_freq, -MAXFREQ);
    641 }
    642 
    643 #ifdef PPS_SYNC
    644 /*
    645  * hardpps() - discipline CPU clock oscillator to external PPS signal
    646  *
    647  * This routine is called at each PPS interrupt in order to discipline
    648  * the CPU clock oscillator to the PPS signal. It measures the PPS phase
    649  * and leaves it in a handy spot for the hardclock() routine. It
    650  * integrates successive PPS phase differences and calculates the
    651  * frequency offset. This is used in hardclock() to discipline the CPU
    652  * clock oscillator so that intrinsic frequency error is cancelled out.
    653  * The code requires the caller to capture the time and hardware counter
    654  * value at the on-time PPS signal transition.
    655  *
    656  * Note that, on some Unix systems, this routine runs at an interrupt
    657  * priority level higher than the timer interrupt routine hardclock().
    658  * Therefore, the variables used are distinct from the hardclock()
    659  * variables, except for certain exceptions: The PPS frequency pps_freq
    660  * and phase pps_offset variables are determined by this routine and
    661  * updated atomically. The time_tolerance variable can be considered a
    662  * constant, since it is infrequently changed, and then only when the
    663  * PPS signal is disabled. The watchdog counter pps_valid is updated
    664  * once per second by hardclock() and is atomically cleared in this
    665  * routine.
    666  */
    667 void
    668 hardpps(struct timespec *tsp,		/* time at PPS */
    669 	long nsec			/* hardware counter at PPS */)
    670 {
    671 	long u_sec, u_nsec, v_nsec; /* temps */
    672 	l_fp ftemp;
    673 
    674 	/*
    675 	 * The signal is first processed by a range gate and frequency
    676 	 * discriminator. The range gate rejects noise spikes outside
    677 	 * the range +-500 us. The frequency discriminator rejects input
    678 	 * signals with apparent frequency outside the range 1 +-500
    679 	 * PPM. If two hits occur in the same second, we ignore the
    680 	 * later hit; if not and a hit occurs outside the range gate,
    681 	 * keep the later hit for later comparison, but do not process
    682 	 * it.
    683 	 */
    684 	time_status |= STA_PPSSIGNAL | STA_PPSJITTER;
    685 	time_status &= ~(STA_PPSWANDER | STA_PPSERROR);
    686 	pps_valid = PPS_VALID;
    687 	u_sec = tsp->tv_sec;
    688 	u_nsec = tsp->tv_nsec;
    689 	if (u_nsec >= (NANOSECOND >> 1)) {
    690 		u_nsec -= NANOSECOND;
    691 		u_sec++;
    692 	}
    693 	v_nsec = u_nsec - pps_tf[0].tv_nsec;
    694 	if (u_sec == pps_tf[0].tv_sec && v_nsec < NANOSECOND -
    695 	    MAXFREQ)
    696 		return;
    697 	pps_tf[2] = pps_tf[1];
    698 	pps_tf[1] = pps_tf[0];
    699 	pps_tf[0].tv_sec = u_sec;
    700 	pps_tf[0].tv_nsec = u_nsec;
    701 
    702 	/*
    703 	 * Compute the difference between the current and previous
    704 	 * counter values. If the difference exceeds 0.5 s, assume it
    705 	 * has wrapped around, so correct 1.0 s. If the result exceeds
    706 	 * the tick interval, the sample point has crossed a tick
    707 	 * boundary during the last second, so correct the tick. Very
    708 	 * intricate.
    709 	 */
    710 	u_nsec = nsec;
    711 	if (u_nsec > (NANOSECOND >> 1))
    712 		u_nsec -= NANOSECOND;
    713 	else if (u_nsec < -(NANOSECOND >> 1))
    714 		u_nsec += NANOSECOND;
    715 	pps_fcount += u_nsec;
    716 	if (v_nsec > MAXFREQ || v_nsec < -MAXFREQ)
    717 		return;
    718 	time_status &= ~STA_PPSJITTER;
    719 
    720 	/*
    721 	 * A three-stage median filter is used to help denoise the PPS
    722 	 * time. The median sample becomes the time offset estimate; the
    723 	 * difference between the other two samples becomes the time
    724 	 * dispersion (jitter) estimate.
    725 	 */
    726 	if (pps_tf[0].tv_nsec > pps_tf[1].tv_nsec) {
    727 		if (pps_tf[1].tv_nsec > pps_tf[2].tv_nsec) {
    728 			v_nsec = pps_tf[1].tv_nsec;	/* 0 1 2 */
    729 			u_nsec = pps_tf[0].tv_nsec - pps_tf[2].tv_nsec;
    730 		} else if (pps_tf[2].tv_nsec > pps_tf[0].tv_nsec) {
    731 			v_nsec = pps_tf[0].tv_nsec;	/* 2 0 1 */
    732 			u_nsec = pps_tf[2].tv_nsec - pps_tf[1].tv_nsec;
    733 		} else {
    734 			v_nsec = pps_tf[2].tv_nsec;	/* 0 2 1 */
    735 			u_nsec = pps_tf[0].tv_nsec - pps_tf[1].tv_nsec;
    736 		}
    737 	} else {
    738 		if (pps_tf[1].tv_nsec < pps_tf[2].tv_nsec) {
    739 			v_nsec = pps_tf[1].tv_nsec;	/* 2 1 0 */
    740 			u_nsec = pps_tf[2].tv_nsec - pps_tf[0].tv_nsec;
    741 		} else if (pps_tf[2].tv_nsec < pps_tf[0].tv_nsec) {
    742 			v_nsec = pps_tf[0].tv_nsec;	/* 1 0 2 */
    743 			u_nsec = pps_tf[1].tv_nsec - pps_tf[2].tv_nsec;
    744 		} else {
    745 			v_nsec = pps_tf[2].tv_nsec;	/* 1 2 0 */
    746 			u_nsec = pps_tf[1].tv_nsec - pps_tf[0].tv_nsec;
    747 		}
    748 	}
    749 
    750 	/*
    751 	 * Nominal jitter is due to PPS signal noise and interrupt
    752 	 * latency. If it exceeds the popcorn threshold, the sample is
    753 	 * discarded. otherwise, if so enabled, the time offset is
    754 	 * updated. We can tolerate a modest loss of data here without
    755 	 * much degrading time accuracy.
    756 	 */
    757 	if (u_nsec > (pps_jitter << PPS_POPCORN)) {
    758 		time_status |= STA_PPSJITTER;
    759 		pps_jitcnt++;
    760 	} else if (time_status & STA_PPSTIME) {
    761 		time_monitor = -v_nsec;
    762 		L_LINT(time_offset, time_monitor);
    763 	}
    764 	pps_jitter += (u_nsec - pps_jitter) >> PPS_FAVG;
    765 	u_sec = pps_tf[0].tv_sec - pps_lastsec;
    766 	if (u_sec < (1 << pps_shift))
    767 		return;
    768 
    769 	/*
    770 	 * At the end of the calibration interval the difference between
    771 	 * the first and last counter values becomes the scaled
    772 	 * frequency. It will later be divided by the length of the
    773 	 * interval to determine the frequency update. If the frequency
    774 	 * exceeds a sanity threshold, or if the actual calibration
    775 	 * interval is not equal to the expected length, the data are
    776 	 * discarded. We can tolerate a modest loss of data here without
    777 	 * much degrading frequency accuracy.
    778 	 */
    779 	pps_calcnt++;
    780 	v_nsec = -pps_fcount;
    781 	pps_lastsec = pps_tf[0].tv_sec;
    782 	pps_fcount = 0;
    783 	u_nsec = MAXFREQ << pps_shift;
    784 	if (v_nsec > u_nsec || v_nsec < -u_nsec || u_sec != (1 <<
    785 	    pps_shift)) {
    786 		time_status |= STA_PPSERROR;
    787 		pps_errcnt++;
    788 		return;
    789 	}
    790 
    791 	/*
    792 	 * Here the raw frequency offset and wander (stability) is
    793 	 * calculated. If the wander is less than the wander threshold
    794 	 * for four consecutive averaging intervals, the interval is
    795 	 * doubled; if it is greater than the threshold for four
    796 	 * consecutive intervals, the interval is halved. The scaled
    797 	 * frequency offset is converted to frequency offset. The
    798 	 * stability metric is calculated as the average of recent
    799 	 * frequency changes, but is used only for performance
    800 	 * monitoring.
    801 	 */
    802 	L_LINT(ftemp, v_nsec);
    803 	L_RSHIFT(ftemp, pps_shift);
    804 	L_SUB(ftemp, pps_freq);
    805 	u_nsec = L_GINT(ftemp);
    806 	if (u_nsec > PPS_MAXWANDER) {
    807 		L_LINT(ftemp, PPS_MAXWANDER);
    808 		pps_intcnt--;
    809 		time_status |= STA_PPSWANDER;
    810 		pps_stbcnt++;
    811 	} else if (u_nsec < -PPS_MAXWANDER) {
    812 		L_LINT(ftemp, -PPS_MAXWANDER);
    813 		pps_intcnt--;
    814 		time_status |= STA_PPSWANDER;
    815 		pps_stbcnt++;
    816 	} else {
    817 		pps_intcnt++;
    818 	}
    819 	if (pps_intcnt >= 4) {
    820 		pps_intcnt = 4;
    821 		if (pps_shift < pps_shiftmax) {
    822 			pps_shift++;
    823 			pps_intcnt = 0;
    824 		}
    825 	} else if (pps_intcnt <= -4 || pps_shift > pps_shiftmax) {
    826 		pps_intcnt = -4;
    827 		if (pps_shift > PPS_FAVG) {
    828 			pps_shift--;
    829 			pps_intcnt = 0;
    830 		}
    831 	}
    832 	if (u_nsec < 0)
    833 		u_nsec = -u_nsec;
    834 	pps_stabil += (u_nsec * SCALE_PPM - pps_stabil) >> PPS_FAVG;
    835 
    836 	/*
    837 	 * The PPS frequency is recalculated and clamped to the maximum
    838 	 * MAXFREQ. If enabled, the system clock frequency is updated as
    839 	 * well.
    840 	 */
    841 	L_ADD(pps_freq, ftemp);
    842 	u_nsec = L_GINT(pps_freq);
    843 	if (u_nsec > MAXFREQ)
    844 		L_LINT(pps_freq, MAXFREQ);
    845 	else if (u_nsec < -MAXFREQ)
    846 		L_LINT(pps_freq, -MAXFREQ);
    847 	if (time_status & STA_PPSFREQ)
    848 		time_freq = pps_freq;
    849 }
    850 #endif /* PPS_SYNC */
    851 #endif /* NTP */
    852 
    853 #ifdef NTP
    854 int
    855 ntp_timestatus()
    856 {
    857 	/*
    858 	 * Status word error decode. If any of these conditions
    859 	 * occur, an error is returned, instead of the status
    860 	 * word. Most applications will care only about the fact
    861 	 * the system clock may not be trusted, not about the
    862 	 * details.
    863 	 *
    864 	 * Hardware or software error
    865 	 */
    866 	if ((time_status & (STA_UNSYNC | STA_CLOCKERR)) ||
    867 
    868 	/*
    869 	 * PPS signal lost when either time or frequency
    870 	 * synchronization requested
    871 	 */
    872 	    (time_status & (STA_PPSFREQ | STA_PPSTIME) &&
    873 	     !(time_status & STA_PPSSIGNAL)) ||
    874 
    875 	/*
    876 	 * PPS jitter exceeded when time synchronization
    877 	 * requested
    878 	 */
    879 	    (time_status & STA_PPSTIME &&
    880 	     time_status & STA_PPSJITTER) ||
    881 
    882 	/*
    883 	 * PPS wander exceeded or calibration error when
    884 	 * frequency synchronization requested
    885 	 */
    886 	    (time_status & STA_PPSFREQ &&
    887 	     time_status & (STA_PPSWANDER | STA_PPSERROR)))
    888 		return (TIME_ERROR);
    889 	else
    890 		return (time_state);
    891 }
    892 
    893 /*ARGSUSED*/
    894 /*
    895  * ntp_gettime() - NTP user application interface
    896  */
    897 int
    898 sys___ntp_gettime30(struct lwp *l, void *v, register_t *retval)
    899 {
    900 	struct sys___ntp_gettime30_args /* {
    901 		syscallarg(struct ntptimeval *) ntvp;
    902 	} */ *uap = v;
    903 	struct ntptimeval ntv;
    904 	int error = 0;
    905 
    906 	if (SCARG(uap, ntvp)) {
    907 		ntp_gettime(&ntv);
    908 
    909 		error = copyout((void *)&ntv, (void *)SCARG(uap, ntvp),
    910 				sizeof(ntv));
    911 	}
    912 	if (!error) {
    913 		*retval = ntp_timestatus();
    914 	}
    915 	return(error);
    916 }
    917 
    918 #ifdef COMPAT_30
    919 int
    920 compat_30_sys_ntp_gettime(struct lwp *l, void *v, register_t *retval)
    921 {
    922 	struct compat_30_sys_ntp_gettime_args /* {
    923 		syscallarg(struct ntptimeval30 *) ontvp;
    924 	} */ *uap = v;
    925 	struct ntptimeval ntv;
    926 	struct ntptimeval30 ontv;
    927 	int error = 0;
    928 
    929 	if (SCARG(uap, ntvp)) {
    930 		ntp_gettime(&ntv);
    931 		TIMESPEC_TO_TIMEVAL(&ontv.time, &ntv.time);
    932 		ontv.maxerror = ntv.maxerror;
    933 		ontv.esterror = ntv.esterror;
    934 
    935 		error = copyout((void *)&ontv, (void *)SCARG(uap, ntvp),
    936 				sizeof(ontv));
    937  	}
    938 	if (!error)
    939 		*retval = ntp_timestatus();
    940 
    941 	return (error);
    942 }
    943 #endif
    944 
    945 /*
    946  * return information about kernel precision timekeeping
    947  */
    948 static int
    949 sysctl_kern_ntptime(SYSCTLFN_ARGS)
    950 {
    951 	struct sysctlnode node;
    952 	struct ntptimeval ntv;
    953 
    954 	ntp_gettime(&ntv);
    955 
    956 	node = *rnode;
    957 	node.sysctl_data = &ntv;
    958 	node.sysctl_size = sizeof(ntv);
    959 	return (sysctl_lookup(SYSCTLFN_CALL(&node)));
    960 }
    961 
    962 SYSCTL_SETUP(sysctl_kern_ntptime_setup, "sysctl kern.ntptime node setup")
    963 {
    964 
    965 	sysctl_createv(clog, 0, NULL, NULL,
    966 		       CTLFLAG_PERMANENT,
    967 		       CTLTYPE_NODE, "kern", NULL,
    968 		       NULL, 0, NULL, 0,
    969 		       CTL_KERN, CTL_EOL);
    970 
    971 	sysctl_createv(clog, 0, NULL, NULL,
    972 		       CTLFLAG_PERMANENT,
    973 		       CTLTYPE_STRUCT, "ntptime",
    974 		       SYSCTL_DESCR("Kernel clock values for NTP"),
    975 		       sysctl_kern_ntptime, 0, NULL,
    976 		       sizeof(struct ntptimeval),
    977 		       CTL_KERN, KERN_NTPTIME, CTL_EOL);
    978 }
    979 #else /* !NTP */
    980 /* For some reason, raising SIGSYS (as sys_nosys would) is problematic. */
    981 
    982 int
    983 sys___ntp_gettime30(struct lwp *l, void *v, register_t *retval)
    984 {
    985 
    986 	return(ENOSYS);
    987 }
    988 
    989 #ifdef COMPAT_30
    990 int
    991 compat_30_sys_ntp_gettime(struct lwp *l, void *v, register_t *retval)
    992 {
    993 
    994  	return(ENOSYS);
    995 }
    996 #endif
    997 #endif /* !NTP */
    998