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