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