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