Home | History | Annotate | Line # | Download | only in kern
kern_clock.c revision 1.106.6.5
      1 /*	$NetBSD: kern_clock.c,v 1.106.6.5 2007/08/20 21:27:28 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2000, 2004, 2006, 2007 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center.
     10  * This code is derived from software contributed to The NetBSD Foundation
     11  * by Charles M. Hannum.
     12  *
     13  * Redistribution and use in source and binary forms, with or without
     14  * modification, are permitted provided that the following conditions
     15  * are met:
     16  * 1. Redistributions of source code must retain the above copyright
     17  *    notice, this list of conditions and the following disclaimer.
     18  * 2. Redistributions in binary form must reproduce the above copyright
     19  *    notice, this list of conditions and the following disclaimer in the
     20  *    documentation and/or other materials provided with the distribution.
     21  * 3. All advertising materials mentioning features or use of this software
     22  *    must display the following acknowledgement:
     23  *	This product includes software developed by the NetBSD
     24  *	Foundation, Inc. and its contributors.
     25  * 4. Neither the name of The NetBSD Foundation nor the names of its
     26  *    contributors may be used to endorse or promote products derived
     27  *    from this software without specific prior written permission.
     28  *
     29  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     30  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     31  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     32  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     33  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     34  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     35  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     36  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     37  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     39  * POSSIBILITY OF SUCH DAMAGE.
     40  */
     41 
     42 /*-
     43  * Copyright (c) 1982, 1986, 1991, 1993
     44  *	The Regents of the University of California.  All rights reserved.
     45  * (c) UNIX System Laboratories, Inc.
     46  * All or some portions of this file are derived from material licensed
     47  * to the University of California by American Telephone and Telegraph
     48  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     49  * the permission of UNIX System Laboratories, Inc.
     50  *
     51  * Redistribution and use in source and binary forms, with or without
     52  * modification, are permitted provided that the following conditions
     53  * are met:
     54  * 1. Redistributions of source code must retain the above copyright
     55  *    notice, this list of conditions and the following disclaimer.
     56  * 2. Redistributions in binary form must reproduce the above copyright
     57  *    notice, this list of conditions and the following disclaimer in the
     58  *    documentation and/or other materials provided with the distribution.
     59  * 3. Neither the name of the University nor the names of its contributors
     60  *    may be used to endorse or promote products derived from this software
     61  *    without specific prior written permission.
     62  *
     63  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     64  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     65  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     66  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     67  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     68  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     69  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     70  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     71  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     72  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     73  * SUCH DAMAGE.
     74  *
     75  *	@(#)kern_clock.c	8.5 (Berkeley) 1/21/94
     76  */
     77 
     78 #include <sys/cdefs.h>
     79 __KERNEL_RCSID(0, "$NetBSD: kern_clock.c,v 1.106.6.5 2007/08/20 21:27:28 ad Exp $");
     80 
     81 #include "opt_ntp.h"
     82 #include "opt_multiprocessor.h"
     83 #include "opt_perfctrs.h"
     84 
     85 #include <sys/param.h>
     86 #include <sys/systm.h>
     87 #include <sys/callout.h>
     88 #include <sys/kernel.h>
     89 #include <sys/proc.h>
     90 #include <sys/resourcevar.h>
     91 #include <sys/signalvar.h>
     92 #include <sys/sysctl.h>
     93 #include <sys/timex.h>
     94 #include <sys/sched.h>
     95 #include <sys/time.h>
     96 #include <sys/timetc.h>
     97 #include <sys/cpu.h>
     98 #include <sys/intr.h>
     99 
    100 #ifdef GPROF
    101 #include <sys/gmon.h>
    102 #endif
    103 
    104 /*
    105  * Clock handling routines.
    106  *
    107  * This code is written to operate with two timers that run independently of
    108  * each other.  The main clock, running hz times per second, is used to keep
    109  * track of real time.  The second timer handles kernel and user profiling,
    110  * and does resource use estimation.  If the second timer is programmable,
    111  * it is randomized to avoid aliasing between the two clocks.  For example,
    112  * the randomization prevents an adversary from always giving up the CPU
    113  * just before its quantum expires.  Otherwise, it would never accumulate
    114  * CPU ticks.  The mean frequency of the second timer is stathz.
    115  *
    116  * If no second timer exists, stathz will be zero; in this case we drive
    117  * profiling and statistics off the main clock.  This WILL NOT be accurate;
    118  * do not do it unless absolutely necessary.
    119  *
    120  * The statistics clock may (or may not) be run at a higher rate while
    121  * profiling.  This profile clock runs at profhz.  We require that profhz
    122  * be an integral multiple of stathz.
    123  *
    124  * If the statistics clock is running fast, it must be divided by the ratio
    125  * profhz/stathz for statistics.  (For profiling, every tick counts.)
    126  */
    127 
    128 #ifndef __HAVE_TIMECOUNTER
    129 #ifdef NTP	/* NTP phase-locked loop in kernel */
    130 /*
    131  * Phase/frequency-lock loop (PLL/FLL) definitions
    132  *
    133  * The following variables are read and set by the ntp_adjtime() system
    134  * call.
    135  *
    136  * time_state shows the state of the system clock, with values defined
    137  * in the timex.h header file.
    138  *
    139  * time_status shows the status of the system clock, with bits defined
    140  * in the timex.h header file.
    141  *
    142  * time_offset is used by the PLL/FLL to adjust the system time in small
    143  * increments.
    144  *
    145  * time_constant determines the bandwidth or "stiffness" of the PLL.
    146  *
    147  * time_tolerance determines maximum frequency error or tolerance of the
    148  * CPU clock oscillator and is a property of the architecture; however,
    149  * in principle it could change as result of the presence of external
    150  * discipline signals, for instance.
    151  *
    152  * time_precision is usually equal to the kernel tick variable; however,
    153  * in cases where a precision clock counter or external clock is
    154  * available, the resolution can be much less than this and depend on
    155  * whether the external clock is working or not.
    156  *
    157  * time_maxerror is initialized by a ntp_adjtime() call and increased by
    158  * the kernel once each second to reflect the maximum error bound
    159  * growth.
    160  *
    161  * time_esterror is set and read by the ntp_adjtime() call, but
    162  * otherwise not used by the kernel.
    163  */
    164 int time_state = TIME_OK;	/* clock state */
    165 int time_status = STA_UNSYNC;	/* clock status bits */
    166 long time_offset = 0;		/* time offset (us) */
    167 long time_constant = 0;		/* pll time constant */
    168 long time_tolerance = MAXFREQ;	/* frequency tolerance (scaled ppm) */
    169 long time_precision = 1;	/* clock precision (us) */
    170 long time_maxerror = MAXPHASE;	/* maximum error (us) */
    171 long time_esterror = MAXPHASE;	/* estimated error (us) */
    172 
    173 /*
    174  * The following variables establish the state of the PLL/FLL and the
    175  * residual time and frequency offset of the local clock. The scale
    176  * factors are defined in the timex.h header file.
    177  *
    178  * time_phase and time_freq are the phase increment and the frequency
    179  * increment, respectively, of the kernel time variable.
    180  *
    181  * time_freq is set via ntp_adjtime() from a value stored in a file when
    182  * the synchronization daemon is first started. Its value is retrieved
    183  * via ntp_adjtime() and written to the file about once per hour by the
    184  * daemon.
    185  *
    186  * time_adj is the adjustment added to the value of tick at each timer
    187  * interrupt and is recomputed from time_phase and time_freq at each
    188  * seconds rollover.
    189  *
    190  * time_reftime is the second's portion of the system time at the last
    191  * call to ntp_adjtime(). It is used to adjust the time_freq variable
    192  * and to increase the time_maxerror as the time since last update
    193  * increases.
    194  */
    195 long time_phase = 0;		/* phase offset (scaled us) */
    196 long time_freq = 0;		/* frequency offset (scaled ppm) */
    197 long time_adj = 0;		/* tick adjust (scaled 1 / hz) */
    198 long time_reftime = 0;		/* time at last adjustment (s) */
    199 
    200 #ifdef PPS_SYNC
    201 /*
    202  * The following variables are used only if the kernel PPS discipline
    203  * code is configured (PPS_SYNC). The scale factors are defined in the
    204  * timex.h header file.
    205  *
    206  * pps_time contains the time at each calibration interval, as read by
    207  * microtime(). pps_count counts the seconds of the calibration
    208  * interval, the duration of which is nominally pps_shift in powers of
    209  * two.
    210  *
    211  * pps_offset is the time offset produced by the time median filter
    212  * pps_tf[], while pps_jitter is the dispersion (jitter) measured by
    213  * this filter.
    214  *
    215  * pps_freq is the frequency offset produced by the frequency median
    216  * filter pps_ff[], while pps_stabil is the dispersion (wander) measured
    217  * by this filter.
    218  *
    219  * pps_usec is latched from a high resolution counter or external clock
    220  * at pps_time. Here we want the hardware counter contents only, not the
    221  * contents plus the time_tv.usec as usual.
    222  *
    223  * pps_valid counts the number of seconds since the last PPS update. It
    224  * is used as a watchdog timer to disable the PPS discipline should the
    225  * PPS signal be lost.
    226  *
    227  * pps_glitch counts the number of seconds since the beginning of an
    228  * offset burst more than tick/2 from current nominal offset. It is used
    229  * mainly to suppress error bursts due to priority conflicts between the
    230  * PPS interrupt and timer interrupt.
    231  *
    232  * pps_intcnt counts the calibration intervals for use in the interval-
    233  * adaptation algorithm. It's just too complicated for words.
    234  *
    235  * pps_kc_hardpps_source contains an arbitrary value that uniquely
    236  * identifies the currently bound source of the PPS signal, or NULL
    237  * if no source is bound.
    238  *
    239  * pps_kc_hardpps_mode indicates which transitions, if any, of the PPS
    240  * signal should be reported.
    241  */
    242 struct timeval pps_time;	/* kernel time at last interval */
    243 long pps_tf[] = {0, 0, 0};	/* pps time offset median filter (us) */
    244 long pps_offset = 0;		/* pps time offset (us) */
    245 long pps_jitter = MAXTIME;	/* time dispersion (jitter) (us) */
    246 long pps_ff[] = {0, 0, 0};	/* pps frequency offset median filter */
    247 long pps_freq = 0;		/* frequency offset (scaled ppm) */
    248 long pps_stabil = MAXFREQ;	/* frequency dispersion (scaled ppm) */
    249 long pps_usec = 0;		/* microsec counter at last interval */
    250 long pps_valid = PPS_VALID;	/* pps signal watchdog counter */
    251 int pps_glitch = 0;		/* pps signal glitch counter */
    252 int pps_count = 0;		/* calibration interval counter (s) */
    253 int pps_shift = PPS_SHIFT;	/* interval duration (s) (shift) */
    254 int pps_intcnt = 0;		/* intervals at current duration */
    255 void *pps_kc_hardpps_source = NULL; /* current PPS supplier's identifier */
    256 int pps_kc_hardpps_mode = 0;	/* interesting edges of PPS signal */
    257 
    258 /*
    259  * PPS signal quality monitors
    260  *
    261  * pps_jitcnt counts the seconds that have been discarded because the
    262  * jitter measured by the time median filter exceeds the limit MAXTIME
    263  * (100 us).
    264  *
    265  * pps_calcnt counts the frequency calibration intervals, which are
    266  * variable from 4 s to 256 s.
    267  *
    268  * pps_errcnt counts the calibration intervals which have been discarded
    269  * because the wander exceeds the limit MAXFREQ (100 ppm) or where the
    270  * calibration interval jitter exceeds two ticks.
    271  *
    272  * pps_stbcnt counts the calibration intervals that have been discarded
    273  * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us).
    274  */
    275 long pps_jitcnt = 0;		/* jitter limit exceeded */
    276 long pps_calcnt = 0;		/* calibration intervals */
    277 long pps_errcnt = 0;		/* calibration errors */
    278 long pps_stbcnt = 0;		/* stability limit exceeded */
    279 #endif /* PPS_SYNC */
    280 
    281 #ifdef EXT_CLOCK
    282 /*
    283  * External clock definitions
    284  *
    285  * The following definitions and declarations are used only if an
    286  * external clock is configured on the system.
    287  */
    288 #define CLOCK_INTERVAL 30	/* CPU clock update interval (s) */
    289 
    290 /*
    291  * The clock_count variable is set to CLOCK_INTERVAL at each PPS
    292  * interrupt and decremented once each second.
    293  */
    294 int clock_count = 0;		/* CPU clock counter */
    295 
    296 #ifdef HIGHBALL
    297 /*
    298  * The clock_offset and clock_cpu variables are used by the HIGHBALL
    299  * interface. The clock_offset variable defines the offset between
    300  * system time and the HIGBALL counters. The clock_cpu variable contains
    301  * the offset between the system clock and the HIGHBALL clock for use in
    302  * disciplining the kernel time variable.
    303  */
    304 extern struct timeval clock_offset; /* Highball clock offset */
    305 long clock_cpu = 0;		/* CPU clock adjust */
    306 #endif /* HIGHBALL */
    307 #endif /* EXT_CLOCK */
    308 #endif /* NTP */
    309 
    310 /*
    311  * Bump a timeval by a small number of usec's.
    312  */
    313 #define BUMPTIME(t, usec) { \
    314 	volatile struct timeval *tp = (t); \
    315 	long us; \
    316  \
    317 	tp->tv_usec = us = tp->tv_usec + (usec); \
    318 	if (us >= 1000000) { \
    319 		tp->tv_usec = us - 1000000; \
    320 		tp->tv_sec++; \
    321 	} \
    322 }
    323 #endif /* !__HAVE_TIMECOUNTER */
    324 
    325 int	stathz;
    326 int	profhz;
    327 int	profsrc;
    328 int	schedhz;
    329 int	profprocs;
    330 int	hardclock_ticks;
    331 static int statscheddiv; /* stat => sched divider (used if schedhz == 0) */
    332 static int psdiv;			/* prof => stat divider */
    333 int	psratio;			/* ratio: prof / stat */
    334 #ifndef __HAVE_TIMECOUNTER
    335 int	tickfix, tickfixinterval;	/* used if tick not really integral */
    336 #ifndef NTP
    337 static int tickfixcnt;			/* accumulated fractional error */
    338 #else
    339 int	fixtick;			/* used by NTP for same */
    340 int	shifthz;
    341 #endif
    342 
    343 /*
    344  * We might want ldd to load the both words from time at once.
    345  * To succeed we need to be quadword aligned.
    346  * The sparc already does that, and that it has worked so far is a fluke.
    347  */
    348 volatile struct	timeval time  __attribute__((__aligned__(__alignof__(quad_t))));
    349 volatile struct	timeval mono_time;
    350 #endif /* !__HAVE_TIMECOUNTER */
    351 
    352 #ifdef __HAVE_TIMECOUNTER
    353 static u_int get_intr_timecount(struct timecounter *);
    354 
    355 static struct timecounter intr_timecounter = {
    356 	get_intr_timecount,	/* get_timecount */
    357 	0,			/* no poll_pps */
    358 	~0u,			/* counter_mask */
    359 	0,		        /* frequency */
    360 	"clockinterrupt",	/* name */
    361 	0,			/* quality - minimum implementation level for a clock */
    362 	NULL,			/* prev */
    363 	NULL,			/* next */
    364 };
    365 
    366 static u_int
    367 get_intr_timecount(struct timecounter *tc)
    368 {
    369 
    370 	return (u_int)hardclock_ticks;
    371 }
    372 #endif
    373 
    374 /*
    375  * Initialize clock frequencies and start both clocks running.
    376  */
    377 void
    378 initclocks(void)
    379 {
    380 	int i;
    381 
    382 	/*
    383 	 * Set divisors to 1 (normal case) and let the machine-specific
    384 	 * code do its bit.
    385 	 */
    386 	psdiv = 1;
    387 #ifdef __HAVE_TIMECOUNTER
    388 	/*
    389 	 * provide minimum default time counter
    390 	 * will only run at interrupt resolution
    391 	 */
    392 	intr_timecounter.tc_frequency = hz;
    393 	tc_init(&intr_timecounter);
    394 #endif
    395 	cpu_initclocks();
    396 
    397 	/*
    398 	 * Compute profhz and stathz, fix profhz if needed.
    399 	 */
    400 	i = stathz ? stathz : hz;
    401 	if (profhz == 0)
    402 		profhz = i;
    403 	psratio = profhz / i;
    404 	if (schedhz == 0) {
    405 		/* 16Hz is best */
    406 		statscheddiv = i / 16;
    407 		if (statscheddiv <= 0)
    408 			panic("statscheddiv");
    409 	}
    410 
    411 #ifndef __HAVE_TIMECOUNTER
    412 #ifdef NTP
    413 	switch (hz) {
    414 	case 1:
    415 		shifthz = SHIFT_SCALE - 0;
    416 		break;
    417 	case 2:
    418 		shifthz = SHIFT_SCALE - 1;
    419 		break;
    420 	case 4:
    421 		shifthz = SHIFT_SCALE - 2;
    422 		break;
    423 	case 8:
    424 		shifthz = SHIFT_SCALE - 3;
    425 		break;
    426 	case 16:
    427 		shifthz = SHIFT_SCALE - 4;
    428 		break;
    429 	case 32:
    430 		shifthz = SHIFT_SCALE - 5;
    431 		break;
    432 	case 50:
    433 	case 60:
    434 	case 64:
    435 		shifthz = SHIFT_SCALE - 6;
    436 		break;
    437 	case 96:
    438 	case 100:
    439 	case 128:
    440 		shifthz = SHIFT_SCALE - 7;
    441 		break;
    442 	case 256:
    443 		shifthz = SHIFT_SCALE - 8;
    444 		break;
    445 	case 512:
    446 		shifthz = SHIFT_SCALE - 9;
    447 		break;
    448 	case 1000:
    449 	case 1024:
    450 		shifthz = SHIFT_SCALE - 10;
    451 		break;
    452 	case 1200:
    453 	case 2048:
    454 		shifthz = SHIFT_SCALE - 11;
    455 		break;
    456 	case 4096:
    457 		shifthz = SHIFT_SCALE - 12;
    458 		break;
    459 	case 8192:
    460 		shifthz = SHIFT_SCALE - 13;
    461 		break;
    462 	case 16384:
    463 		shifthz = SHIFT_SCALE - 14;
    464 		break;
    465 	case 32768:
    466 		shifthz = SHIFT_SCALE - 15;
    467 		break;
    468 	case 65536:
    469 		shifthz = SHIFT_SCALE - 16;
    470 		break;
    471 	default:
    472 		panic("weird hz");
    473 	}
    474 	if (fixtick == 0) {
    475 		/*
    476 		 * Give MD code a chance to set this to a better
    477 		 * value; but, if it doesn't, we should.
    478 		 */
    479 		fixtick = (1000000 - (hz*tick));
    480 	}
    481 #endif /* NTP */
    482 #endif /* !__HAVE_TIMECOUNTER */
    483 }
    484 
    485 /*
    486  * The real-time timer, interrupting hz times per second.
    487  */
    488 void
    489 hardclock(struct clockframe *frame)
    490 {
    491 	struct lwp *l;
    492 	struct proc *p;
    493 	struct cpu_info *ci = curcpu();
    494 	struct ptimer *pt;
    495 #ifndef __HAVE_TIMECOUNTER
    496 	int delta;
    497 	extern int tickdelta;
    498 	extern long timedelta;
    499 #ifdef NTP
    500 	int time_update;
    501 	int ltemp;
    502 #endif /* NTP */
    503 #endif /* __HAVE_TIMECOUNTER */
    504 
    505 	l = curlwp;
    506 	if (!CURCPU_IDLE_P()) {
    507 		p = l->l_proc;
    508 		/*
    509 		 * Run current process's virtual and profile time, as needed.
    510 		 */
    511 		if (CLKF_USERMODE(frame) && p->p_timers &&
    512 		    (pt = LIST_FIRST(&p->p_timers->pts_virtual)) != NULL)
    513 			if (itimerdecr(pt, tick) == 0)
    514 				itimerfire(pt);
    515 		if (p->p_timers &&
    516 		    (pt = LIST_FIRST(&p->p_timers->pts_prof)) != NULL)
    517 			if (itimerdecr(pt, tick) == 0)
    518 				itimerfire(pt);
    519 	}
    520 
    521 	/*
    522 	 * If no separate statistics clock is available, run it from here.
    523 	 */
    524 	if (stathz == 0)
    525 		statclock(frame);
    526 	if ((--ci->ci_schedstate.spc_ticks) <= 0)
    527 		sched_tick(ci);
    528 
    529 #if defined(MULTIPROCESSOR)
    530 	/*
    531 	 * If we are not the primary CPU, we're not allowed to do
    532 	 * any more work.
    533 	 */
    534 	if (CPU_IS_PRIMARY(ci) == 0)
    535 		return;
    536 #endif
    537 
    538 	hardclock_ticks++;
    539 
    540 #ifdef __HAVE_TIMECOUNTER
    541 	tc_ticktock();
    542 #else /* __HAVE_TIMECOUNTER */
    543 	/*
    544 	 * Increment the time-of-day.  The increment is normally just
    545 	 * ``tick''.  If the machine is one which has a clock frequency
    546 	 * such that ``hz'' would not divide the second evenly into
    547 	 * milliseconds, a periodic adjustment must be applied.  Finally,
    548 	 * if we are still adjusting the time (see adjtime()),
    549 	 * ``tickdelta'' may also be added in.
    550 	 */
    551 	delta = tick;
    552 
    553 #ifndef NTP
    554 	if (tickfix) {
    555 		tickfixcnt += tickfix;
    556 		if (tickfixcnt >= tickfixinterval) {
    557 			delta++;
    558 			tickfixcnt -= tickfixinterval;
    559 		}
    560 	}
    561 #endif /* !NTP */
    562 	/* Imprecise 4bsd adjtime() handling */
    563 	if (timedelta != 0) {
    564 		delta += tickdelta;
    565 		timedelta -= tickdelta;
    566 	}
    567 
    568 #ifdef notyet
    569 	microset();
    570 #endif
    571 
    572 #ifndef NTP
    573 	BUMPTIME(&time, delta);		/* XXX Now done using NTP code below */
    574 #endif
    575 	BUMPTIME(&mono_time, delta);
    576 
    577 #ifdef NTP
    578 	time_update = delta;
    579 
    580 	/*
    581 	 * Compute the phase adjustment. If the low-order bits
    582 	 * (time_phase) of the update overflow, bump the high-order bits
    583 	 * (time_update).
    584 	 */
    585 	time_phase += time_adj;
    586 	if (time_phase <= -FINEUSEC) {
    587 		ltemp = -time_phase >> SHIFT_SCALE;
    588 		time_phase += ltemp << SHIFT_SCALE;
    589 		time_update -= ltemp;
    590 	} else if (time_phase >= FINEUSEC) {
    591 		ltemp = time_phase >> SHIFT_SCALE;
    592 		time_phase -= ltemp << SHIFT_SCALE;
    593 		time_update += ltemp;
    594 	}
    595 
    596 #ifdef HIGHBALL
    597 	/*
    598 	 * If the HIGHBALL board is installed, we need to adjust the
    599 	 * external clock offset in order to close the hardware feedback
    600 	 * loop. This will adjust the external clock phase and frequency
    601 	 * in small amounts. The additional phase noise and frequency
    602 	 * wander this causes should be minimal. We also need to
    603 	 * discipline the kernel time variable, since the PLL is used to
    604 	 * discipline the external clock. If the Highball board is not
    605 	 * present, we discipline kernel time with the PLL as usual. We
    606 	 * assume that the external clock phase adjustment (time_update)
    607 	 * and kernel phase adjustment (clock_cpu) are less than the
    608 	 * value of tick.
    609 	 */
    610 	clock_offset.tv_usec += time_update;
    611 	if (clock_offset.tv_usec >= 1000000) {
    612 		clock_offset.tv_sec++;
    613 		clock_offset.tv_usec -= 1000000;
    614 	}
    615 	if (clock_offset.tv_usec < 0) {
    616 		clock_offset.tv_sec--;
    617 		clock_offset.tv_usec += 1000000;
    618 	}
    619 	time.tv_usec += clock_cpu;
    620 	clock_cpu = 0;
    621 #else
    622 	time.tv_usec += time_update;
    623 #endif /* HIGHBALL */
    624 
    625 	/*
    626 	 * On rollover of the second the phase adjustment to be used for
    627 	 * the next second is calculated. Also, the maximum error is
    628 	 * increased by the tolerance. If the PPS frequency discipline
    629 	 * code is present, the phase is increased to compensate for the
    630 	 * CPU clock oscillator frequency error.
    631 	 *
    632  	 * On a 32-bit machine and given parameters in the timex.h
    633 	 * header file, the maximum phase adjustment is +-512 ms and
    634 	 * maximum frequency offset is a tad less than) +-512 ppm. On a
    635 	 * 64-bit machine, you shouldn't need to ask.
    636 	 */
    637 	if (time.tv_usec >= 1000000) {
    638 		time.tv_usec -= 1000000;
    639 		time.tv_sec++;
    640 		time_maxerror += time_tolerance >> SHIFT_USEC;
    641 
    642 		/*
    643 		 * Leap second processing. If in leap-insert state at
    644 		 * the end of the day, the system clock is set back one
    645 		 * second; if in leap-delete state, the system clock is
    646 		 * set ahead one second. The microtime() routine or
    647 		 * external clock driver will insure that reported time
    648 		 * is always monotonic. The ugly divides should be
    649 		 * replaced.
    650 		 */
    651 		switch (time_state) {
    652 		case TIME_OK:
    653 			if (time_status & STA_INS)
    654 				time_state = TIME_INS;
    655 			else if (time_status & STA_DEL)
    656 				time_state = TIME_DEL;
    657 			break;
    658 
    659 		case TIME_INS:
    660 			if (time.tv_sec % 86400 == 0) {
    661 				time.tv_sec--;
    662 				time_state = TIME_OOP;
    663 			}
    664 			break;
    665 
    666 		case TIME_DEL:
    667 			if ((time.tv_sec + 1) % 86400 == 0) {
    668 				time.tv_sec++;
    669 				time_state = TIME_WAIT;
    670 			}
    671 			break;
    672 
    673 		case TIME_OOP:
    674 			time_state = TIME_WAIT;
    675 			break;
    676 
    677 		case TIME_WAIT:
    678 			if (!(time_status & (STA_INS | STA_DEL)))
    679 				time_state = TIME_OK;
    680 			break;
    681 		}
    682 
    683 		/*
    684 		 * Compute the phase adjustment for the next second. In
    685 		 * PLL mode, the offset is reduced by a fixed factor
    686 		 * times the time constant. In FLL mode the offset is
    687 		 * used directly. In either mode, the maximum phase
    688 		 * adjustment for each second is clamped so as to spread
    689 		 * the adjustment over not more than the number of
    690 		 * seconds between updates.
    691 		 */
    692 		if (time_offset < 0) {
    693 			ltemp = -time_offset;
    694 			if (!(time_status & STA_FLL))
    695 				ltemp >>= SHIFT_KG + time_constant;
    696 			if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
    697 				ltemp = (MAXPHASE / MINSEC) <<
    698 				    SHIFT_UPDATE;
    699 			time_offset += ltemp;
    700 			time_adj = -ltemp << (shifthz - SHIFT_UPDATE);
    701 		} else if (time_offset > 0) {
    702 			ltemp = time_offset;
    703 			if (!(time_status & STA_FLL))
    704 				ltemp >>= SHIFT_KG + time_constant;
    705 			if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
    706 				ltemp = (MAXPHASE / MINSEC) <<
    707 				    SHIFT_UPDATE;
    708 			time_offset -= ltemp;
    709 			time_adj = ltemp << (shifthz - SHIFT_UPDATE);
    710 		} else
    711 			time_adj = 0;
    712 
    713 		/*
    714 		 * Compute the frequency estimate and additional phase
    715 		 * adjustment due to frequency error for the next
    716 		 * second. When the PPS signal is engaged, gnaw on the
    717 		 * watchdog counter and update the frequency computed by
    718 		 * the pll and the PPS signal.
    719 		 */
    720 #ifdef PPS_SYNC
    721 		pps_valid++;
    722 		if (pps_valid == PPS_VALID) {
    723 			pps_jitter = MAXTIME;
    724 			pps_stabil = MAXFREQ;
    725 			time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
    726 			    STA_PPSWANDER | STA_PPSERROR);
    727 		}
    728 		ltemp = time_freq + pps_freq;
    729 #else
    730 		ltemp = time_freq;
    731 #endif /* PPS_SYNC */
    732 
    733 		if (ltemp < 0)
    734 			time_adj -= -ltemp >> (SHIFT_USEC - shifthz);
    735 		else
    736 			time_adj += ltemp >> (SHIFT_USEC - shifthz);
    737 		time_adj += (long)fixtick << shifthz;
    738 
    739 		/*
    740 		 * When the CPU clock oscillator frequency is not a
    741 		 * power of 2 in Hz, shifthz is only an approximate
    742 		 * scale factor.
    743 		 *
    744 		 * To determine the adjustment, you can do the following:
    745 		 *   bc -q
    746 		 *   scale=24
    747 		 *   obase=2
    748 		 *   idealhz/realhz
    749 		 * where `idealhz' is the next higher power of 2, and `realhz'
    750 		 * is the actual value.  You may need to factor this result
    751 		 * into a sequence of 2 multipliers to get better precision.
    752 		 *
    753 		 * Likewise, the error can be calculated with (e.g. for 100Hz):
    754 		 *   bc -q
    755 		 *   scale=24
    756 		 *   ((1+2^-2+2^-5)*(1-2^-10)*realhz-idealhz)/idealhz
    757 		 * (and then multiply by 1000000 to get ppm).
    758 		 */
    759 		switch (hz) {
    760 		case 60:
    761 			/* A factor of 1.000100010001 gives about 15ppm
    762 			   error. */
    763 			if (time_adj < 0) {
    764 				time_adj -= (-time_adj >> 4);
    765 				time_adj -= (-time_adj >> 8);
    766 			} else {
    767 				time_adj += (time_adj >> 4);
    768 				time_adj += (time_adj >> 8);
    769 			}
    770 			break;
    771 
    772 		case 96:
    773 			/* A factor of 1.0101010101 gives about 244ppm error. */
    774 			if (time_adj < 0) {
    775 				time_adj -= (-time_adj >> 2);
    776 				time_adj -= (-time_adj >> 4) + (-time_adj >> 8);
    777 			} else {
    778 				time_adj += (time_adj >> 2);
    779 				time_adj += (time_adj >> 4) + (time_adj >> 8);
    780 			}
    781 			break;
    782 
    783 		case 50:
    784 		case 100:
    785 			/* A factor of 1.010001111010111 gives about 1ppm
    786 			   error. */
    787 			if (time_adj < 0) {
    788 				time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
    789 				time_adj += (-time_adj >> 10);
    790 			} else {
    791 				time_adj += (time_adj >> 2) + (time_adj >> 5);
    792 				time_adj -= (time_adj >> 10);
    793 			}
    794 			break;
    795 
    796 		case 1000:
    797 			/* A factor of 1.000001100010100001 gives about 50ppm
    798 			   error. */
    799 			if (time_adj < 0) {
    800 				time_adj -= (-time_adj >> 6) + (-time_adj >> 11);
    801 				time_adj -= (-time_adj >> 7);
    802 			} else {
    803 				time_adj += (time_adj >> 6) + (time_adj >> 11);
    804 				time_adj += (time_adj >> 7);
    805 			}
    806 			break;
    807 
    808 		case 1200:
    809 			/* A factor of 1.1011010011100001 gives about 64ppm
    810 			   error. */
    811 			if (time_adj < 0) {
    812 				time_adj -= (-time_adj >> 1) + (-time_adj >> 6);
    813 				time_adj -= (-time_adj >> 3) + (-time_adj >> 10);
    814 			} else {
    815 				time_adj += (time_adj >> 1) + (time_adj >> 6);
    816 				time_adj += (time_adj >> 3) + (time_adj >> 10);
    817 			}
    818 			break;
    819 		}
    820 
    821 #ifdef EXT_CLOCK
    822 		/*
    823 		 * If an external clock is present, it is necessary to
    824 		 * discipline the kernel time variable anyway, since not
    825 		 * all system components use the microtime() interface.
    826 		 * Here, the time offset between the external clock and
    827 		 * kernel time variable is computed every so often.
    828 		 */
    829 		clock_count++;
    830 		if (clock_count > CLOCK_INTERVAL) {
    831 			clock_count = 0;
    832 			microtime(&clock_ext);
    833 			delta.tv_sec = clock_ext.tv_sec - time.tv_sec;
    834 			delta.tv_usec = clock_ext.tv_usec -
    835 			    time.tv_usec;
    836 			if (delta.tv_usec < 0)
    837 				delta.tv_sec--;
    838 			if (delta.tv_usec >= 500000) {
    839 				delta.tv_usec -= 1000000;
    840 				delta.tv_sec++;
    841 			}
    842 			if (delta.tv_usec < -500000) {
    843 				delta.tv_usec += 1000000;
    844 				delta.tv_sec--;
    845 			}
    846 			if (delta.tv_sec > 0 || (delta.tv_sec == 0 &&
    847 			    delta.tv_usec > MAXPHASE) ||
    848 			    delta.tv_sec < -1 || (delta.tv_sec == -1 &&
    849 			    delta.tv_usec < -MAXPHASE)) {
    850 				time = clock_ext;
    851 				delta.tv_sec = 0;
    852 				delta.tv_usec = 0;
    853 			}
    854 #ifdef HIGHBALL
    855 			clock_cpu = delta.tv_usec;
    856 #else /* HIGHBALL */
    857 			hardupdate(delta.tv_usec);
    858 #endif /* HIGHBALL */
    859 		}
    860 #endif /* EXT_CLOCK */
    861 	}
    862 
    863 #endif /* NTP */
    864 #endif /* !__HAVE_TIMECOUNTER */
    865 
    866 	/*
    867 	 * Update real-time timeout queue.  Callouts are processed at a
    868 	 * very low CPU priority, so we don't keep the relatively high
    869 	 * clock interrupt priority any longer than necessary.
    870 	 */
    871 	callout_hardclock();
    872 }
    873 
    874 /*
    875  * Start profiling on a process.
    876  *
    877  * Kernel profiling passes proc0 which never exits and hence
    878  * keeps the profile clock running constantly.
    879  */
    880 void
    881 startprofclock(struct proc *p)
    882 {
    883 
    884 	KASSERT(mutex_owned(&p->p_stmutex));
    885 
    886 	if ((p->p_stflag & PST_PROFIL) == 0) {
    887 		p->p_stflag |= PST_PROFIL;
    888 		/*
    889 		 * This is only necessary if using the clock as the
    890 		 * profiling source.
    891 		 */
    892 		if (++profprocs == 1 && stathz != 0)
    893 			psdiv = psratio;
    894 	}
    895 }
    896 
    897 /*
    898  * Stop profiling on a process.
    899  */
    900 void
    901 stopprofclock(struct proc *p)
    902 {
    903 
    904 	KASSERT(mutex_owned(&p->p_stmutex));
    905 
    906 	if (p->p_stflag & PST_PROFIL) {
    907 		p->p_stflag &= ~PST_PROFIL;
    908 		/*
    909 		 * This is only necessary if using the clock as the
    910 		 * profiling source.
    911 		 */
    912 		if (--profprocs == 0 && stathz != 0)
    913 			psdiv = 1;
    914 	}
    915 }
    916 
    917 #if defined(PERFCTRS)
    918 /*
    919  * Independent profiling "tick" in case we're using a separate
    920  * clock or profiling event source.  Currently, that's just
    921  * performance counters--hence the wrapper.
    922  */
    923 void
    924 proftick(struct clockframe *frame)
    925 {
    926 #ifdef GPROF
    927         struct gmonparam *g;
    928         intptr_t i;
    929 #endif
    930 	struct lwp *l;
    931 	struct proc *p;
    932 
    933 	l = curlwp;
    934 	p = (l ? l->l_proc : NULL);
    935 	if (CLKF_USERMODE(frame)) {
    936 		mutex_spin_enter(&p->p_stmutex);
    937 		if (p->p_stflag & PST_PROFIL)
    938 			addupc_intr(l, CLKF_PC(frame));
    939 		mutex_spin_exit(&p->p_stmutex);
    940 	} else {
    941 #ifdef GPROF
    942 		g = &_gmonparam;
    943 		if (g->state == GMON_PROF_ON) {
    944 			i = CLKF_PC(frame) - g->lowpc;
    945 			if (i < g->textsize) {
    946 				i /= HISTFRACTION * sizeof(*g->kcount);
    947 				g->kcount[i]++;
    948 			}
    949 		}
    950 #endif
    951 #ifdef PROC_PC
    952 		if (p != NULL) {
    953 			mutex_spin_enter(&p->p_stmutex);
    954 			if (p->p_stflag & PST_PROFIL))
    955 				addupc_intr(l, PROC_PC(p));
    956 			mutex_spin_exit(&p->p_stmutex);
    957 		}
    958 #endif
    959 	}
    960 }
    961 #endif
    962 
    963 void
    964 schedclock(struct lwp *l)
    965 {
    966 
    967 	if ((l->l_flag & LW_IDLE) != 0)
    968 		return;
    969 
    970 	sched_schedclock(l);
    971 }
    972 
    973 /*
    974  * Statistics clock.  Grab profile sample, and if divider reaches 0,
    975  * do process and kernel statistics.
    976  */
    977 void
    978 statclock(struct clockframe *frame)
    979 {
    980 #ifdef GPROF
    981 	struct gmonparam *g;
    982 	intptr_t i;
    983 #endif
    984 	struct cpu_info *ci = curcpu();
    985 	struct schedstate_percpu *spc = &ci->ci_schedstate;
    986 	struct proc *p;
    987 	struct lwp *l;
    988 
    989 	/*
    990 	 * Notice changes in divisor frequency, and adjust clock
    991 	 * frequency accordingly.
    992 	 */
    993 	if (spc->spc_psdiv != psdiv) {
    994 		spc->spc_psdiv = psdiv;
    995 		spc->spc_pscnt = psdiv;
    996 		if (psdiv == 1) {
    997 			setstatclockrate(stathz);
    998 		} else {
    999 			setstatclockrate(profhz);
   1000 		}
   1001 	}
   1002 	l = curlwp;
   1003 	if ((l->l_flag & LW_IDLE) != 0) {
   1004 		/*
   1005 		 * don't account idle lwps as swapper.
   1006 		 */
   1007 		p = NULL;
   1008 	} else {
   1009 		p = l->l_proc;
   1010 		mutex_spin_enter(&p->p_stmutex);
   1011 	}
   1012 
   1013 	if (CLKF_USERMODE(frame)) {
   1014 		if ((p->p_stflag & PST_PROFIL) && profsrc == PROFSRC_CLOCK)
   1015 			addupc_intr(l, CLKF_PC(frame));
   1016 		if (--spc->spc_pscnt > 0) {
   1017 			mutex_spin_exit(&p->p_stmutex);
   1018 			return;
   1019 		}
   1020 
   1021 		/*
   1022 		 * Came from user mode; CPU was in user state.
   1023 		 * If this process is being profiled record the tick.
   1024 		 */
   1025 		p->p_uticks++;
   1026 		if (p->p_nice > NZERO)
   1027 			spc->spc_cp_time[CP_NICE]++;
   1028 		else
   1029 			spc->spc_cp_time[CP_USER]++;
   1030 	} else {
   1031 #ifdef GPROF
   1032 		/*
   1033 		 * Kernel statistics are just like addupc_intr, only easier.
   1034 		 */
   1035 		g = &_gmonparam;
   1036 		if (profsrc == PROFSRC_CLOCK && g->state == GMON_PROF_ON) {
   1037 			i = CLKF_PC(frame) - g->lowpc;
   1038 			if (i < g->textsize) {
   1039 				i /= HISTFRACTION * sizeof(*g->kcount);
   1040 				g->kcount[i]++;
   1041 			}
   1042 		}
   1043 #endif
   1044 #ifdef LWP_PC
   1045 		if (p != NULL && profsrc == PROFSRC_CLOCK &&
   1046 		    (p->p_stflag & PST_PROFIL)) {
   1047 			addupc_intr(l, LWP_PC(l));
   1048 		}
   1049 #endif
   1050 		if (--spc->spc_pscnt > 0) {
   1051 			if (p != NULL)
   1052 				mutex_spin_exit(&p->p_stmutex);
   1053 			return;
   1054 		}
   1055 		/*
   1056 		 * Came from kernel mode, so we were:
   1057 		 * - handling an interrupt,
   1058 		 * - doing syscall or trap work on behalf of the current
   1059 		 *   user process, or
   1060 		 * - spinning in the idle loop.
   1061 		 * Whichever it is, charge the time as appropriate.
   1062 		 * Note that we charge interrupts to the current process,
   1063 		 * regardless of whether they are ``for'' that process,
   1064 		 * so that we know how much of its real time was spent
   1065 		 * in ``non-process'' (i.e., interrupt) work.
   1066 		 */
   1067 		if (CLKF_INTR(frame) || (l->l_flag & LW_INTR) != 0) {
   1068 			if (p != NULL) {
   1069 				p->p_iticks++;
   1070 			}
   1071 			spc->spc_cp_time[CP_INTR]++;
   1072 		} else if (p != NULL) {
   1073 			p->p_sticks++;
   1074 			spc->spc_cp_time[CP_SYS]++;
   1075 		} else {
   1076 			spc->spc_cp_time[CP_IDLE]++;
   1077 		}
   1078 	}
   1079 	spc->spc_pscnt = psdiv;
   1080 
   1081 	if (p != NULL) {
   1082 		++l->l_cpticks;
   1083 		mutex_spin_exit(&p->p_stmutex);
   1084 	}
   1085 
   1086 	/*
   1087 	 * If no separate schedclock is provided, call it here
   1088 	 * at about 16 Hz.
   1089 	 */
   1090 	if (schedhz == 0) {
   1091 		if ((int)(--ci->ci_schedstate.spc_schedticks) <= 0) {
   1092 			schedclock(l);
   1093 			ci->ci_schedstate.spc_schedticks = statscheddiv;
   1094 		}
   1095 	}
   1096 }
   1097 
   1098 #ifndef __HAVE_TIMECOUNTER
   1099 #ifdef NTP	/* NTP phase-locked loop in kernel */
   1100 /*
   1101  * hardupdate() - local clock update
   1102  *
   1103  * This routine is called by ntp_adjtime() to update the local clock
   1104  * phase and frequency. The implementation is of an adaptive-parameter,
   1105  * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
   1106  * time and frequency offset estimates for each call. If the kernel PPS
   1107  * discipline code is configured (PPS_SYNC), the PPS signal itself
   1108  * determines the new time offset, instead of the calling argument.
   1109  * Presumably, calls to ntp_adjtime() occur only when the caller
   1110  * believes the local clock is valid within some bound (+-128 ms with
   1111  * NTP). If the caller's time is far different than the PPS time, an
   1112  * argument will ensue, and it's not clear who will lose.
   1113  *
   1114  * For uncompensated quartz crystal oscillatores and nominal update
   1115  * intervals less than 1024 s, operation should be in phase-lock mode
   1116  * (STA_FLL = 0), where the loop is disciplined to phase. For update
   1117  * intervals greater than thiss, operation should be in frequency-lock
   1118  * mode (STA_FLL = 1), where the loop is disciplined to frequency.
   1119  *
   1120  * Note: splclock() is in effect.
   1121  */
   1122 void
   1123 hardupdate(long offset)
   1124 {
   1125 	long ltemp, mtemp;
   1126 
   1127 	if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
   1128 		return;
   1129 	ltemp = offset;
   1130 #ifdef PPS_SYNC
   1131 	if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
   1132 		ltemp = pps_offset;
   1133 #endif /* PPS_SYNC */
   1134 
   1135 	/*
   1136 	 * Scale the phase adjustment and clamp to the operating range.
   1137 	 */
   1138 	if (ltemp > MAXPHASE)
   1139 		time_offset = MAXPHASE << SHIFT_UPDATE;
   1140 	else if (ltemp < -MAXPHASE)
   1141 		time_offset = -(MAXPHASE << SHIFT_UPDATE);
   1142 	else
   1143 		time_offset = ltemp << SHIFT_UPDATE;
   1144 
   1145 	/*
   1146 	 * Select whether the frequency is to be controlled and in which
   1147 	 * mode (PLL or FLL). Clamp to the operating range. Ugly
   1148 	 * multiply/divide should be replaced someday.
   1149 	 */
   1150 	if (time_status & STA_FREQHOLD || time_reftime == 0)
   1151 		time_reftime = time.tv_sec;
   1152 	mtemp = time.tv_sec - time_reftime;
   1153 	time_reftime = time.tv_sec;
   1154 	if (time_status & STA_FLL) {
   1155 		if (mtemp >= MINSEC) {
   1156 			ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
   1157 			    SHIFT_UPDATE));
   1158 			if (ltemp < 0)
   1159 				time_freq -= -ltemp >> SHIFT_KH;
   1160 			else
   1161 				time_freq += ltemp >> SHIFT_KH;
   1162 		}
   1163 	} else {
   1164 		if (mtemp < MAXSEC) {
   1165 			ltemp *= mtemp;
   1166 			if (ltemp < 0)
   1167 				time_freq -= -ltemp >> (time_constant +
   1168 				    time_constant + SHIFT_KF -
   1169 				    SHIFT_USEC);
   1170 			else
   1171 				time_freq += ltemp >> (time_constant +
   1172 				    time_constant + SHIFT_KF -
   1173 				    SHIFT_USEC);
   1174 		}
   1175 	}
   1176 	if (time_freq > time_tolerance)
   1177 		time_freq = time_tolerance;
   1178 	else if (time_freq < -time_tolerance)
   1179 		time_freq = -time_tolerance;
   1180 }
   1181 
   1182 #ifdef PPS_SYNC
   1183 /*
   1184  * hardpps() - discipline CPU clock oscillator to external PPS signal
   1185  *
   1186  * This routine is called at each PPS interrupt in order to discipline
   1187  * the CPU clock oscillator to the PPS signal. It measures the PPS phase
   1188  * and leaves it in a handy spot for the hardclock() routine. It
   1189  * integrates successive PPS phase differences and calculates the
   1190  * frequency offset. This is used in hardclock() to discipline the CPU
   1191  * clock oscillator so that intrinsic frequency error is cancelled out.
   1192  * The code requires the caller to capture the time and hardware counter
   1193  * value at the on-time PPS signal transition.
   1194  *
   1195  * Note that, on some Unix systems, this routine runs at an interrupt
   1196  * priority level higher than the timer interrupt routine hardclock().
   1197  * Therefore, the variables used are distinct from the hardclock()
   1198  * variables, except for certain exceptions: The PPS frequency pps_freq
   1199  * and phase pps_offset variables are determined by this routine and
   1200  * updated atomically. The time_tolerance variable can be considered a
   1201  * constant, since it is infrequently changed, and then only when the
   1202  * PPS signal is disabled. The watchdog counter pps_valid is updated
   1203  * once per second by hardclock() and is atomically cleared in this
   1204  * routine.
   1205  */
   1206 void
   1207 hardpps(struct timeval *tvp,		/* time at PPS */
   1208 	long usec			/* hardware counter at PPS */)
   1209 {
   1210 	long u_usec, v_usec, bigtick;
   1211 	long cal_sec, cal_usec;
   1212 
   1213 	/*
   1214 	 * An occasional glitch can be produced when the PPS interrupt
   1215 	 * occurs in the hardclock() routine before the time variable is
   1216 	 * updated. Here the offset is discarded when the difference
   1217 	 * between it and the last one is greater than tick/2, but not
   1218 	 * if the interval since the first discard exceeds 30 s.
   1219 	 */
   1220 	time_status |= STA_PPSSIGNAL;
   1221 	time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
   1222 	pps_valid = 0;
   1223 	u_usec = -tvp->tv_usec;
   1224 	if (u_usec < -500000)
   1225 		u_usec += 1000000;
   1226 	v_usec = pps_offset - u_usec;
   1227 	if (v_usec < 0)
   1228 		v_usec = -v_usec;
   1229 	if (v_usec > (tick >> 1)) {
   1230 		if (pps_glitch > MAXGLITCH) {
   1231 			pps_glitch = 0;
   1232 			pps_tf[2] = u_usec;
   1233 			pps_tf[1] = u_usec;
   1234 		} else {
   1235 			pps_glitch++;
   1236 			u_usec = pps_offset;
   1237 		}
   1238 	} else
   1239 		pps_glitch = 0;
   1240 
   1241 	/*
   1242 	 * A three-stage median filter is used to help deglitch the pps
   1243 	 * time. The median sample becomes the time offset estimate; the
   1244 	 * difference between the other two samples becomes the time
   1245 	 * dispersion (jitter) estimate.
   1246 	 */
   1247 	pps_tf[2] = pps_tf[1];
   1248 	pps_tf[1] = pps_tf[0];
   1249 	pps_tf[0] = u_usec;
   1250 	if (pps_tf[0] > pps_tf[1]) {
   1251 		if (pps_tf[1] > pps_tf[2]) {
   1252 			pps_offset = pps_tf[1];		/* 0 1 2 */
   1253 			v_usec = pps_tf[0] - pps_tf[2];
   1254 		} else if (pps_tf[2] > pps_tf[0]) {
   1255 			pps_offset = pps_tf[0];		/* 2 0 1 */
   1256 			v_usec = pps_tf[2] - pps_tf[1];
   1257 		} else {
   1258 			pps_offset = pps_tf[2];		/* 0 2 1 */
   1259 			v_usec = pps_tf[0] - pps_tf[1];
   1260 		}
   1261 	} else {
   1262 		if (pps_tf[1] < pps_tf[2]) {
   1263 			pps_offset = pps_tf[1];		/* 2 1 0 */
   1264 			v_usec = pps_tf[2] - pps_tf[0];
   1265 		} else  if (pps_tf[2] < pps_tf[0]) {
   1266 			pps_offset = pps_tf[0];		/* 1 0 2 */
   1267 			v_usec = pps_tf[1] - pps_tf[2];
   1268 		} else {
   1269 			pps_offset = pps_tf[2];		/* 1 2 0 */
   1270 			v_usec = pps_tf[1] - pps_tf[0];
   1271 		}
   1272 	}
   1273 	if (v_usec > MAXTIME)
   1274 		pps_jitcnt++;
   1275 	v_usec = (v_usec << PPS_AVG) - pps_jitter;
   1276 	if (v_usec < 0)
   1277 		pps_jitter -= -v_usec >> PPS_AVG;
   1278 	else
   1279 		pps_jitter += v_usec >> PPS_AVG;
   1280 	if (pps_jitter > (MAXTIME >> 1))
   1281 		time_status |= STA_PPSJITTER;
   1282 
   1283 	/*
   1284 	 * During the calibration interval adjust the starting time when
   1285 	 * the tick overflows. At the end of the interval compute the
   1286 	 * duration of the interval and the difference of the hardware
   1287 	 * counters at the beginning and end of the interval. This code
   1288 	 * is deliciously complicated by the fact valid differences may
   1289 	 * exceed the value of tick when using long calibration
   1290 	 * intervals and small ticks. Note that the counter can be
   1291 	 * greater than tick if caught at just the wrong instant, but
   1292 	 * the values returned and used here are correct.
   1293 	 */
   1294 	bigtick = (long)tick << SHIFT_USEC;
   1295 	pps_usec -= pps_freq;
   1296 	if (pps_usec >= bigtick)
   1297 		pps_usec -= bigtick;
   1298 	if (pps_usec < 0)
   1299 		pps_usec += bigtick;
   1300 	pps_time.tv_sec++;
   1301 	pps_count++;
   1302 	if (pps_count < (1 << pps_shift))
   1303 		return;
   1304 	pps_count = 0;
   1305 	pps_calcnt++;
   1306 	u_usec = usec << SHIFT_USEC;
   1307 	v_usec = pps_usec - u_usec;
   1308 	if (v_usec >= bigtick >> 1)
   1309 		v_usec -= bigtick;
   1310 	if (v_usec < -(bigtick >> 1))
   1311 		v_usec += bigtick;
   1312 	if (v_usec < 0)
   1313 		v_usec = -(-v_usec >> pps_shift);
   1314 	else
   1315 		v_usec = v_usec >> pps_shift;
   1316 	pps_usec = u_usec;
   1317 	cal_sec = tvp->tv_sec;
   1318 	cal_usec = tvp->tv_usec;
   1319 	cal_sec -= pps_time.tv_sec;
   1320 	cal_usec -= pps_time.tv_usec;
   1321 	if (cal_usec < 0) {
   1322 		cal_usec += 1000000;
   1323 		cal_sec--;
   1324 	}
   1325 	pps_time = *tvp;
   1326 
   1327 	/*
   1328 	 * Check for lost interrupts, noise, excessive jitter and
   1329 	 * excessive frequency error. The number of timer ticks during
   1330 	 * the interval may vary +-1 tick. Add to this a margin of one
   1331 	 * tick for the PPS signal jitter and maximum frequency
   1332 	 * deviation. If the limits are exceeded, the calibration
   1333 	 * interval is reset to the minimum and we start over.
   1334 	 */
   1335 	u_usec = (long)tick << 1;
   1336 	if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
   1337 	    || (cal_sec == 0 && cal_usec < u_usec))
   1338 	    || v_usec > time_tolerance || v_usec < -time_tolerance) {
   1339 		pps_errcnt++;
   1340 		pps_shift = PPS_SHIFT;
   1341 		pps_intcnt = 0;
   1342 		time_status |= STA_PPSERROR;
   1343 		return;
   1344 	}
   1345 
   1346 	/*
   1347 	 * A three-stage median filter is used to help deglitch the pps
   1348 	 * frequency. The median sample becomes the frequency offset
   1349 	 * estimate; the difference between the other two samples
   1350 	 * becomes the frequency dispersion (stability) estimate.
   1351 	 */
   1352 	pps_ff[2] = pps_ff[1];
   1353 	pps_ff[1] = pps_ff[0];
   1354 	pps_ff[0] = v_usec;
   1355 	if (pps_ff[0] > pps_ff[1]) {
   1356 		if (pps_ff[1] > pps_ff[2]) {
   1357 			u_usec = pps_ff[1];		/* 0 1 2 */
   1358 			v_usec = pps_ff[0] - pps_ff[2];
   1359 		} else if (pps_ff[2] > pps_ff[0]) {
   1360 			u_usec = pps_ff[0];		/* 2 0 1 */
   1361 			v_usec = pps_ff[2] - pps_ff[1];
   1362 		} else {
   1363 			u_usec = pps_ff[2];		/* 0 2 1 */
   1364 			v_usec = pps_ff[0] - pps_ff[1];
   1365 		}
   1366 	} else {
   1367 		if (pps_ff[1] < pps_ff[2]) {
   1368 			u_usec = pps_ff[1];		/* 2 1 0 */
   1369 			v_usec = pps_ff[2] - pps_ff[0];
   1370 		} else  if (pps_ff[2] < pps_ff[0]) {
   1371 			u_usec = pps_ff[0];		/* 1 0 2 */
   1372 			v_usec = pps_ff[1] - pps_ff[2];
   1373 		} else {
   1374 			u_usec = pps_ff[2];		/* 1 2 0 */
   1375 			v_usec = pps_ff[1] - pps_ff[0];
   1376 		}
   1377 	}
   1378 
   1379 	/*
   1380 	 * Here the frequency dispersion (stability) is updated. If it
   1381 	 * is less than one-fourth the maximum (MAXFREQ), the frequency
   1382 	 * offset is updated as well, but clamped to the tolerance. It
   1383 	 * will be processed later by the hardclock() routine.
   1384 	 */
   1385 	v_usec = (v_usec >> 1) - pps_stabil;
   1386 	if (v_usec < 0)
   1387 		pps_stabil -= -v_usec >> PPS_AVG;
   1388 	else
   1389 		pps_stabil += v_usec >> PPS_AVG;
   1390 	if (pps_stabil > MAXFREQ >> 2) {
   1391 		pps_stbcnt++;
   1392 		time_status |= STA_PPSWANDER;
   1393 		return;
   1394 	}
   1395 	if (time_status & STA_PPSFREQ) {
   1396 		if (u_usec < 0) {
   1397 			pps_freq -= -u_usec >> PPS_AVG;
   1398 			if (pps_freq < -time_tolerance)
   1399 				pps_freq = -time_tolerance;
   1400 			u_usec = -u_usec;
   1401 		} else {
   1402 			pps_freq += u_usec >> PPS_AVG;
   1403 			if (pps_freq > time_tolerance)
   1404 				pps_freq = time_tolerance;
   1405 		}
   1406 	}
   1407 
   1408 	/*
   1409 	 * Here the calibration interval is adjusted. If the maximum
   1410 	 * time difference is greater than tick / 4, reduce the interval
   1411 	 * by half. If this is not the case for four consecutive
   1412 	 * intervals, double the interval.
   1413 	 */
   1414 	if (u_usec << pps_shift > bigtick >> 2) {
   1415 		pps_intcnt = 0;
   1416 		if (pps_shift > PPS_SHIFT)
   1417 			pps_shift--;
   1418 	} else if (pps_intcnt >= 4) {
   1419 		pps_intcnt = 0;
   1420 		if (pps_shift < PPS_SHIFTMAX)
   1421 			pps_shift++;
   1422 	} else
   1423 		pps_intcnt++;
   1424 }
   1425 #endif /* PPS_SYNC */
   1426 #endif /* NTP  */
   1427 
   1428 /* timecounter compat functions */
   1429 void
   1430 nanotime(struct timespec *ts)
   1431 {
   1432 	struct timeval tv;
   1433 
   1434 	microtime(&tv);
   1435 	TIMEVAL_TO_TIMESPEC(&tv, ts);
   1436 }
   1437 
   1438 void
   1439 getbinuptime(struct bintime *bt)
   1440 {
   1441 	struct timeval tv;
   1442 
   1443 	microtime(&tv);
   1444 	timeval2bintime(&tv, bt);
   1445 }
   1446 
   1447 void
   1448 nanouptime(struct timespec *tsp)
   1449 {
   1450 	int s;
   1451 
   1452 	s = splclock();
   1453 	TIMEVAL_TO_TIMESPEC(&mono_time, tsp);
   1454 	splx(s);
   1455 }
   1456 
   1457 void
   1458 getnanouptime(struct timespec *tsp)
   1459 {
   1460 	int s;
   1461 
   1462 	s = splclock();
   1463 	TIMEVAL_TO_TIMESPEC(&mono_time, tsp);
   1464 	splx(s);
   1465 }
   1466 
   1467 void
   1468 getmicrouptime(struct timeval *tvp)
   1469 {
   1470 	int s;
   1471 
   1472 	s = splclock();
   1473 	*tvp = mono_time;
   1474 	splx(s);
   1475 }
   1476 
   1477 void
   1478 getnanotime(struct timespec *tsp)
   1479 {
   1480 	int s;
   1481 
   1482 	s = splclock();
   1483 	TIMEVAL_TO_TIMESPEC(&time, tsp);
   1484 	splx(s);
   1485 }
   1486 
   1487 void
   1488 getmicrotime(struct timeval *tvp)
   1489 {
   1490 	int s;
   1491 
   1492 	s = splclock();
   1493 	*tvp = time;
   1494 	splx(s);
   1495 }
   1496 
   1497 u_int64_t
   1498 tc_getfrequency(void)
   1499 {
   1500 	return hz;
   1501 }
   1502 #endif /* !__HAVE_TIMECOUNTER */
   1503