Home | History | Annotate | Line # | Download | only in kern
kern_clock.c revision 1.106.2.2
      1 /*	$NetBSD: kern_clock.c,v 1.106.2.2 2007/02/20 21:48:44 rmind Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2000, 2004, 2006, 2007 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center.
     10  * This code is derived from software contributed to The NetBSD Foundation
     11  * by Charles M. Hannum.
     12  *
     13  * Redistribution and use in source and binary forms, with or without
     14  * modification, are permitted provided that the following conditions
     15  * are met:
     16  * 1. Redistributions of source code must retain the above copyright
     17  *    notice, this list of conditions and the following disclaimer.
     18  * 2. Redistributions in binary form must reproduce the above copyright
     19  *    notice, this list of conditions and the following disclaimer in the
     20  *    documentation and/or other materials provided with the distribution.
     21  * 3. All advertising materials mentioning features or use of this software
     22  *    must display the following acknowledgement:
     23  *	This product includes software developed by the NetBSD
     24  *	Foundation, Inc. and its contributors.
     25  * 4. Neither the name of The NetBSD Foundation nor the names of its
     26  *    contributors may be used to endorse or promote products derived
     27  *    from this software without specific prior written permission.
     28  *
     29  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     30  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     31  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     32  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     33  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     34  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     35  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     36  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     37  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     39  * POSSIBILITY OF SUCH DAMAGE.
     40  */
     41 
     42 /*-
     43  * Copyright (c) 1982, 1986, 1991, 1993
     44  *	The Regents of the University of California.  All rights reserved.
     45  * (c) UNIX System Laboratories, Inc.
     46  * All or some portions of this file are derived from material licensed
     47  * to the University of California by American Telephone and Telegraph
     48  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     49  * the permission of UNIX System Laboratories, Inc.
     50  *
     51  * Redistribution and use in source and binary forms, with or without
     52  * modification, are permitted provided that the following conditions
     53  * are met:
     54  * 1. Redistributions of source code must retain the above copyright
     55  *    notice, this list of conditions and the following disclaimer.
     56  * 2. Redistributions in binary form must reproduce the above copyright
     57  *    notice, this list of conditions and the following disclaimer in the
     58  *    documentation and/or other materials provided with the distribution.
     59  * 3. Neither the name of the University nor the names of its contributors
     60  *    may be used to endorse or promote products derived from this software
     61  *    without specific prior written permission.
     62  *
     63  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     64  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     65  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     66  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     67  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     68  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     69  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     70  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     71  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     72  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     73  * SUCH DAMAGE.
     74  *
     75  *	@(#)kern_clock.c	8.5 (Berkeley) 1/21/94
     76  */
     77 
     78 #include <sys/cdefs.h>
     79 __KERNEL_RCSID(0, "$NetBSD: kern_clock.c,v 1.106.2.2 2007/02/20 21:48:44 rmind 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 #ifdef SCHED_4BSD
    335 static int statscheddiv; /* stat => sched divider (used if schedhz == 0) */
    336 #endif
    337 static int psdiv;			/* prof => stat divider */
    338 int	psratio;			/* ratio: prof / stat */
    339 #ifndef __HAVE_TIMECOUNTER
    340 int	tickfix, tickfixinterval;	/* used if tick not really integral */
    341 #ifndef NTP
    342 static int tickfixcnt;			/* accumulated fractional error */
    343 #else
    344 int	fixtick;			/* used by NTP for same */
    345 int	shifthz;
    346 #endif
    347 
    348 /*
    349  * We might want ldd to load the both words from time at once.
    350  * To succeed we need to be quadword aligned.
    351  * The sparc already does that, and that it has worked so far is a fluke.
    352  */
    353 volatile struct	timeval time  __attribute__((__aligned__(__alignof__(quad_t))));
    354 volatile struct	timeval mono_time;
    355 #endif /* !__HAVE_TIMECOUNTER */
    356 
    357 void	*softclock_si;
    358 
    359 #ifdef __HAVE_TIMECOUNTER
    360 static u_int get_intr_timecount(struct timecounter *);
    361 
    362 static struct timecounter intr_timecounter = {
    363 	get_intr_timecount,	/* get_timecount */
    364 	0,			/* no poll_pps */
    365 	~0u,			/* counter_mask */
    366 	0,		        /* frequency */
    367 	"clockinterrupt",	/* name */
    368 	0,			/* quality - minimum implementation level for a clock */
    369 	NULL,			/* prev */
    370 	NULL,			/* next */
    371 };
    372 
    373 static u_int
    374 get_intr_timecount(struct timecounter *tc)
    375 {
    376 
    377 	return (u_int)hardclock_ticks;
    378 }
    379 #endif
    380 
    381 /*
    382  * Initialize clock frequencies and start both clocks running.
    383  */
    384 void
    385 initclocks(void)
    386 {
    387 	int i;
    388 
    389 	softclock_si = softintr_establish(IPL_SOFTCLOCK, softclock, NULL);
    390 	if (softclock_si == NULL)
    391 		panic("initclocks: unable to register softclock intr");
    392 
    393 	/*
    394 	 * Set divisors to 1 (normal case) and let the machine-specific
    395 	 * code do its bit.
    396 	 */
    397 	psdiv = 1;
    398 #ifdef __HAVE_TIMECOUNTER
    399 	/*
    400 	 * provide minimum default time counter
    401 	 * will only run at interrupt resolution
    402 	 */
    403 	intr_timecounter.tc_frequency = hz;
    404 	tc_init(&intr_timecounter);
    405 #endif
    406 	cpu_initclocks();
    407 
    408 	/*
    409 	 * Compute profhz and stathz, fix profhz if needed.
    410 	 */
    411 	i = stathz ? stathz : hz;
    412 	if (profhz == 0)
    413 		profhz = i;
    414 	psratio = profhz / i;
    415 #ifdef SCHED_4BSD
    416 	if (schedhz == 0) {
    417 		/* 16Hz is best */
    418 		statscheddiv = i / 16;
    419 		if (statscheddiv <= 0)
    420 			panic("statscheddiv");
    421 	}
    422 #endif /* SCHED_4BSD */
    423 
    424 #ifndef __HAVE_TIMECOUNTER
    425 #ifdef NTP
    426 	switch (hz) {
    427 	case 1:
    428 		shifthz = SHIFT_SCALE - 0;
    429 		break;
    430 	case 2:
    431 		shifthz = SHIFT_SCALE - 1;
    432 		break;
    433 	case 4:
    434 		shifthz = SHIFT_SCALE - 2;
    435 		break;
    436 	case 8:
    437 		shifthz = SHIFT_SCALE - 3;
    438 		break;
    439 	case 16:
    440 		shifthz = SHIFT_SCALE - 4;
    441 		break;
    442 	case 32:
    443 		shifthz = SHIFT_SCALE - 5;
    444 		break;
    445 	case 50:
    446 	case 60:
    447 	case 64:
    448 		shifthz = SHIFT_SCALE - 6;
    449 		break;
    450 	case 96:
    451 	case 100:
    452 	case 128:
    453 		shifthz = SHIFT_SCALE - 7;
    454 		break;
    455 	case 256:
    456 		shifthz = SHIFT_SCALE - 8;
    457 		break;
    458 	case 512:
    459 		shifthz = SHIFT_SCALE - 9;
    460 		break;
    461 	case 1000:
    462 	case 1024:
    463 		shifthz = SHIFT_SCALE - 10;
    464 		break;
    465 	case 1200:
    466 	case 2048:
    467 		shifthz = SHIFT_SCALE - 11;
    468 		break;
    469 	case 4096:
    470 		shifthz = SHIFT_SCALE - 12;
    471 		break;
    472 	case 8192:
    473 		shifthz = SHIFT_SCALE - 13;
    474 		break;
    475 	case 16384:
    476 		shifthz = SHIFT_SCALE - 14;
    477 		break;
    478 	case 32768:
    479 		shifthz = SHIFT_SCALE - 15;
    480 		break;
    481 	case 65536:
    482 		shifthz = SHIFT_SCALE - 16;
    483 		break;
    484 	default:
    485 		panic("weird hz");
    486 	}
    487 	if (fixtick == 0) {
    488 		/*
    489 		 * Give MD code a chance to set this to a better
    490 		 * value; but, if it doesn't, we should.
    491 		 */
    492 		fixtick = (1000000 - (hz*tick));
    493 	}
    494 #endif /* NTP */
    495 #endif /* !__HAVE_TIMECOUNTER */
    496 }
    497 
    498 /*
    499  * The real-time timer, interrupting hz times per second.
    500  */
    501 void
    502 hardclock(struct clockframe *frame)
    503 {
    504 	struct lwp *l;
    505 	struct proc *p;
    506 	struct cpu_info *ci = curcpu();
    507 	struct ptimer *pt;
    508 #ifndef __HAVE_TIMECOUNTER
    509 	int delta;
    510 	extern int tickdelta;
    511 	extern long timedelta;
    512 #ifdef NTP
    513 	int time_update;
    514 	int ltemp;
    515 #endif /* NTP */
    516 #endif /* __HAVE_TIMECOUNTER */
    517 
    518 	l = curlwp;
    519 	if (!CURCPU_IDLE_P()) {
    520 		p = l->l_proc;
    521 		/*
    522 		 * Run current process's virtual and profile time, as needed.
    523 		 */
    524 		if (CLKF_USERMODE(frame) && p->p_timers &&
    525 		    (pt = LIST_FIRST(&p->p_timers->pts_virtual)) != NULL)
    526 			if (itimerdecr(pt, tick) == 0)
    527 				itimerfire(pt);
    528 		if (p->p_timers &&
    529 		    (pt = LIST_FIRST(&p->p_timers->pts_prof)) != NULL)
    530 			if (itimerdecr(pt, tick) == 0)
    531 				itimerfire(pt);
    532 	}
    533 
    534 	/*
    535 	 * If no separate statistics clock is available, run it from here.
    536 	 */
    537 	if (stathz == 0)
    538 		statclock(frame);
    539 	if ((--ci->ci_schedstate.spc_ticks) <= 0)
    540 		sched_tick(ci);
    541 
    542 #if defined(MULTIPROCESSOR)
    543 	/*
    544 	 * If we are not the primary CPU, we're not allowed to do
    545 	 * any more work.
    546 	 */
    547 	if (CPU_IS_PRIMARY(ci) == 0)
    548 		return;
    549 #endif
    550 
    551 	hardclock_ticks++;
    552 
    553 #ifdef __HAVE_TIMECOUNTER
    554 	tc_ticktock();
    555 #else /* __HAVE_TIMECOUNTER */
    556 	/*
    557 	 * Increment the time-of-day.  The increment is normally just
    558 	 * ``tick''.  If the machine is one which has a clock frequency
    559 	 * such that ``hz'' would not divide the second evenly into
    560 	 * milliseconds, a periodic adjustment must be applied.  Finally,
    561 	 * if we are still adjusting the time (see adjtime()),
    562 	 * ``tickdelta'' may also be added in.
    563 	 */
    564 	delta = tick;
    565 
    566 #ifndef NTP
    567 	if (tickfix) {
    568 		tickfixcnt += tickfix;
    569 		if (tickfixcnt >= tickfixinterval) {
    570 			delta++;
    571 			tickfixcnt -= tickfixinterval;
    572 		}
    573 	}
    574 #endif /* !NTP */
    575 	/* Imprecise 4bsd adjtime() handling */
    576 	if (timedelta != 0) {
    577 		delta += tickdelta;
    578 		timedelta -= tickdelta;
    579 	}
    580 
    581 #ifdef notyet
    582 	microset();
    583 #endif
    584 
    585 #ifndef NTP
    586 	BUMPTIME(&time, delta);		/* XXX Now done using NTP code below */
    587 #endif
    588 	BUMPTIME(&mono_time, delta);
    589 
    590 #ifdef NTP
    591 	time_update = delta;
    592 
    593 	/*
    594 	 * Compute the phase adjustment. If the low-order bits
    595 	 * (time_phase) of the update overflow, bump the high-order bits
    596 	 * (time_update).
    597 	 */
    598 	time_phase += time_adj;
    599 	if (time_phase <= -FINEUSEC) {
    600 		ltemp = -time_phase >> SHIFT_SCALE;
    601 		time_phase += ltemp << SHIFT_SCALE;
    602 		time_update -= ltemp;
    603 	} else if (time_phase >= FINEUSEC) {
    604 		ltemp = time_phase >> SHIFT_SCALE;
    605 		time_phase -= ltemp << SHIFT_SCALE;
    606 		time_update += ltemp;
    607 	}
    608 
    609 #ifdef HIGHBALL
    610 	/*
    611 	 * If the HIGHBALL board is installed, we need to adjust the
    612 	 * external clock offset in order to close the hardware feedback
    613 	 * loop. This will adjust the external clock phase and frequency
    614 	 * in small amounts. The additional phase noise and frequency
    615 	 * wander this causes should be minimal. We also need to
    616 	 * discipline the kernel time variable, since the PLL is used to
    617 	 * discipline the external clock. If the Highball board is not
    618 	 * present, we discipline kernel time with the PLL as usual. We
    619 	 * assume that the external clock phase adjustment (time_update)
    620 	 * and kernel phase adjustment (clock_cpu) are less than the
    621 	 * value of tick.
    622 	 */
    623 	clock_offset.tv_usec += time_update;
    624 	if (clock_offset.tv_usec >= 1000000) {
    625 		clock_offset.tv_sec++;
    626 		clock_offset.tv_usec -= 1000000;
    627 	}
    628 	if (clock_offset.tv_usec < 0) {
    629 		clock_offset.tv_sec--;
    630 		clock_offset.tv_usec += 1000000;
    631 	}
    632 	time.tv_usec += clock_cpu;
    633 	clock_cpu = 0;
    634 #else
    635 	time.tv_usec += time_update;
    636 #endif /* HIGHBALL */
    637 
    638 	/*
    639 	 * On rollover of the second the phase adjustment to be used for
    640 	 * the next second is calculated. Also, the maximum error is
    641 	 * increased by the tolerance. If the PPS frequency discipline
    642 	 * code is present, the phase is increased to compensate for the
    643 	 * CPU clock oscillator frequency error.
    644 	 *
    645  	 * On a 32-bit machine and given parameters in the timex.h
    646 	 * header file, the maximum phase adjustment is +-512 ms and
    647 	 * maximum frequency offset is a tad less than) +-512 ppm. On a
    648 	 * 64-bit machine, you shouldn't need to ask.
    649 	 */
    650 	if (time.tv_usec >= 1000000) {
    651 		time.tv_usec -= 1000000;
    652 		time.tv_sec++;
    653 		time_maxerror += time_tolerance >> SHIFT_USEC;
    654 
    655 		/*
    656 		 * Leap second processing. If in leap-insert state at
    657 		 * the end of the day, the system clock is set back one
    658 		 * second; if in leap-delete state, the system clock is
    659 		 * set ahead one second. The microtime() routine or
    660 		 * external clock driver will insure that reported time
    661 		 * is always monotonic. The ugly divides should be
    662 		 * replaced.
    663 		 */
    664 		switch (time_state) {
    665 		case TIME_OK:
    666 			if (time_status & STA_INS)
    667 				time_state = TIME_INS;
    668 			else if (time_status & STA_DEL)
    669 				time_state = TIME_DEL;
    670 			break;
    671 
    672 		case TIME_INS:
    673 			if (time.tv_sec % 86400 == 0) {
    674 				time.tv_sec--;
    675 				time_state = TIME_OOP;
    676 			}
    677 			break;
    678 
    679 		case TIME_DEL:
    680 			if ((time.tv_sec + 1) % 86400 == 0) {
    681 				time.tv_sec++;
    682 				time_state = TIME_WAIT;
    683 			}
    684 			break;
    685 
    686 		case TIME_OOP:
    687 			time_state = TIME_WAIT;
    688 			break;
    689 
    690 		case TIME_WAIT:
    691 			if (!(time_status & (STA_INS | STA_DEL)))
    692 				time_state = TIME_OK;
    693 			break;
    694 		}
    695 
    696 		/*
    697 		 * Compute the phase adjustment for the next second. In
    698 		 * PLL mode, the offset is reduced by a fixed factor
    699 		 * times the time constant. In FLL mode the offset is
    700 		 * used directly. In either mode, the maximum phase
    701 		 * adjustment for each second is clamped so as to spread
    702 		 * the adjustment over not more than the number of
    703 		 * seconds between updates.
    704 		 */
    705 		if (time_offset < 0) {
    706 			ltemp = -time_offset;
    707 			if (!(time_status & STA_FLL))
    708 				ltemp >>= SHIFT_KG + time_constant;
    709 			if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
    710 				ltemp = (MAXPHASE / MINSEC) <<
    711 				    SHIFT_UPDATE;
    712 			time_offset += ltemp;
    713 			time_adj = -ltemp << (shifthz - SHIFT_UPDATE);
    714 		} else if (time_offset > 0) {
    715 			ltemp = time_offset;
    716 			if (!(time_status & STA_FLL))
    717 				ltemp >>= SHIFT_KG + time_constant;
    718 			if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
    719 				ltemp = (MAXPHASE / MINSEC) <<
    720 				    SHIFT_UPDATE;
    721 			time_offset -= ltemp;
    722 			time_adj = ltemp << (shifthz - SHIFT_UPDATE);
    723 		} else
    724 			time_adj = 0;
    725 
    726 		/*
    727 		 * Compute the frequency estimate and additional phase
    728 		 * adjustment due to frequency error for the next
    729 		 * second. When the PPS signal is engaged, gnaw on the
    730 		 * watchdog counter and update the frequency computed by
    731 		 * the pll and the PPS signal.
    732 		 */
    733 #ifdef PPS_SYNC
    734 		pps_valid++;
    735 		if (pps_valid == PPS_VALID) {
    736 			pps_jitter = MAXTIME;
    737 			pps_stabil = MAXFREQ;
    738 			time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
    739 			    STA_PPSWANDER | STA_PPSERROR);
    740 		}
    741 		ltemp = time_freq + pps_freq;
    742 #else
    743 		ltemp = time_freq;
    744 #endif /* PPS_SYNC */
    745 
    746 		if (ltemp < 0)
    747 			time_adj -= -ltemp >> (SHIFT_USEC - shifthz);
    748 		else
    749 			time_adj += ltemp >> (SHIFT_USEC - shifthz);
    750 		time_adj += (long)fixtick << shifthz;
    751 
    752 		/*
    753 		 * When the CPU clock oscillator frequency is not a
    754 		 * power of 2 in Hz, shifthz is only an approximate
    755 		 * scale factor.
    756 		 *
    757 		 * To determine the adjustment, you can do the following:
    758 		 *   bc -q
    759 		 *   scale=24
    760 		 *   obase=2
    761 		 *   idealhz/realhz
    762 		 * where `idealhz' is the next higher power of 2, and `realhz'
    763 		 * is the actual value.  You may need to factor this result
    764 		 * into a sequence of 2 multipliers to get better precision.
    765 		 *
    766 		 * Likewise, the error can be calculated with (e.g. for 100Hz):
    767 		 *   bc -q
    768 		 *   scale=24
    769 		 *   ((1+2^-2+2^-5)*(1-2^-10)*realhz-idealhz)/idealhz
    770 		 * (and then multiply by 1000000 to get ppm).
    771 		 */
    772 		switch (hz) {
    773 		case 60:
    774 			/* A factor of 1.000100010001 gives about 15ppm
    775 			   error. */
    776 			if (time_adj < 0) {
    777 				time_adj -= (-time_adj >> 4);
    778 				time_adj -= (-time_adj >> 8);
    779 			} else {
    780 				time_adj += (time_adj >> 4);
    781 				time_adj += (time_adj >> 8);
    782 			}
    783 			break;
    784 
    785 		case 96:
    786 			/* A factor of 1.0101010101 gives about 244ppm error. */
    787 			if (time_adj < 0) {
    788 				time_adj -= (-time_adj >> 2);
    789 				time_adj -= (-time_adj >> 4) + (-time_adj >> 8);
    790 			} else {
    791 				time_adj += (time_adj >> 2);
    792 				time_adj += (time_adj >> 4) + (time_adj >> 8);
    793 			}
    794 			break;
    795 
    796 		case 50:
    797 		case 100:
    798 			/* A factor of 1.010001111010111 gives about 1ppm
    799 			   error. */
    800 			if (time_adj < 0) {
    801 				time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
    802 				time_adj += (-time_adj >> 10);
    803 			} else {
    804 				time_adj += (time_adj >> 2) + (time_adj >> 5);
    805 				time_adj -= (time_adj >> 10);
    806 			}
    807 			break;
    808 
    809 		case 1000:
    810 			/* A factor of 1.000001100010100001 gives about 50ppm
    811 			   error. */
    812 			if (time_adj < 0) {
    813 				time_adj -= (-time_adj >> 6) + (-time_adj >> 11);
    814 				time_adj -= (-time_adj >> 7);
    815 			} else {
    816 				time_adj += (time_adj >> 6) + (time_adj >> 11);
    817 				time_adj += (time_adj >> 7);
    818 			}
    819 			break;
    820 
    821 		case 1200:
    822 			/* A factor of 1.1011010011100001 gives about 64ppm
    823 			   error. */
    824 			if (time_adj < 0) {
    825 				time_adj -= (-time_adj >> 1) + (-time_adj >> 6);
    826 				time_adj -= (-time_adj >> 3) + (-time_adj >> 10);
    827 			} else {
    828 				time_adj += (time_adj >> 1) + (time_adj >> 6);
    829 				time_adj += (time_adj >> 3) + (time_adj >> 10);
    830 			}
    831 			break;
    832 		}
    833 
    834 #ifdef EXT_CLOCK
    835 		/*
    836 		 * If an external clock is present, it is necessary to
    837 		 * discipline the kernel time variable anyway, since not
    838 		 * all system components use the microtime() interface.
    839 		 * Here, the time offset between the external clock and
    840 		 * kernel time variable is computed every so often.
    841 		 */
    842 		clock_count++;
    843 		if (clock_count > CLOCK_INTERVAL) {
    844 			clock_count = 0;
    845 			microtime(&clock_ext);
    846 			delta.tv_sec = clock_ext.tv_sec - time.tv_sec;
    847 			delta.tv_usec = clock_ext.tv_usec -
    848 			    time.tv_usec;
    849 			if (delta.tv_usec < 0)
    850 				delta.tv_sec--;
    851 			if (delta.tv_usec >= 500000) {
    852 				delta.tv_usec -= 1000000;
    853 				delta.tv_sec++;
    854 			}
    855 			if (delta.tv_usec < -500000) {
    856 				delta.tv_usec += 1000000;
    857 				delta.tv_sec--;
    858 			}
    859 			if (delta.tv_sec > 0 || (delta.tv_sec == 0 &&
    860 			    delta.tv_usec > MAXPHASE) ||
    861 			    delta.tv_sec < -1 || (delta.tv_sec == -1 &&
    862 			    delta.tv_usec < -MAXPHASE)) {
    863 				time = clock_ext;
    864 				delta.tv_sec = 0;
    865 				delta.tv_usec = 0;
    866 			}
    867 #ifdef HIGHBALL
    868 			clock_cpu = delta.tv_usec;
    869 #else /* HIGHBALL */
    870 			hardupdate(delta.tv_usec);
    871 #endif /* HIGHBALL */
    872 		}
    873 #endif /* EXT_CLOCK */
    874 	}
    875 
    876 #endif /* NTP */
    877 #endif /* !__HAVE_TIMECOUNTER */
    878 
    879 	/*
    880 	 * Update real-time timeout queue.  Callouts are processed at a
    881 	 * very low CPU priority, so we don't keep the relatively high
    882 	 * clock interrupt priority any longer than necessary.
    883 	 */
    884 	if (callout_hardclock())
    885 		softintr_schedule(softclock_si);
    886 }
    887 
    888 #ifdef __HAVE_TIMECOUNTER
    889 /*
    890  * Compute number of hz until specified time.  Used to compute second
    891  * argument to callout_reset() from an absolute time.
    892  */
    893 int
    894 hzto(struct timeval *tvp)
    895 {
    896 	struct timeval now, tv;
    897 
    898 	tv = *tvp;	/* Don't modify original tvp. */
    899 	getmicrotime(&now);
    900 	timersub(&tv, &now, &tv);
    901 	return tvtohz(&tv);
    902 }
    903 #endif /* __HAVE_TIMECOUNTER */
    904 
    905 /*
    906  * Compute number of ticks in the specified amount of time.
    907  */
    908 int
    909 tvtohz(struct timeval *tv)
    910 {
    911 	unsigned long ticks;
    912 	long sec, usec;
    913 
    914 	/*
    915 	 * If the number of usecs in the whole seconds part of the time
    916 	 * difference fits in a long, then the total number of usecs will
    917 	 * fit in an unsigned long.  Compute the total and convert it to
    918 	 * ticks, rounding up and adding 1 to allow for the current tick
    919 	 * to expire.  Rounding also depends on unsigned long arithmetic
    920 	 * to avoid overflow.
    921 	 *
    922 	 * Otherwise, if the number of ticks in the whole seconds part of
    923 	 * the time difference fits in a long, then convert the parts to
    924 	 * ticks separately and add, using similar rounding methods and
    925 	 * overflow avoidance.  This method would work in the previous
    926 	 * case, but it is slightly slower and assumes that hz is integral.
    927 	 *
    928 	 * Otherwise, round the time difference down to the maximum
    929 	 * representable value.
    930 	 *
    931 	 * If ints are 32-bit, then the maximum value for any timeout in
    932 	 * 10ms ticks is 248 days.
    933 	 */
    934 	sec = tv->tv_sec;
    935 	usec = tv->tv_usec;
    936 
    937 	if (usec < 0) {
    938 		sec--;
    939 		usec += 1000000;
    940 	}
    941 
    942 	if (sec < 0 || (sec == 0 && usec <= 0)) {
    943 		/*
    944 		 * Would expire now or in the past.  Return 0 ticks.
    945 		 * This is different from the legacy hzto() interface,
    946 		 * and callers need to check for it.
    947 		 */
    948 		ticks = 0;
    949 	} else if (sec <= (LONG_MAX / 1000000))
    950 		ticks = (((sec * 1000000) + (unsigned long)usec + (tick - 1))
    951 		    / tick) + 1;
    952 	else if (sec <= (LONG_MAX / hz))
    953 		ticks = (sec * hz) +
    954 		    (((unsigned long)usec + (tick - 1)) / tick) + 1;
    955 	else
    956 		ticks = LONG_MAX;
    957 
    958 	if (ticks > INT_MAX)
    959 		ticks = INT_MAX;
    960 
    961 	return ((int)ticks);
    962 }
    963 
    964 #ifndef __HAVE_TIMECOUNTER
    965 /*
    966  * Compute number of hz until specified time.  Used to compute second
    967  * argument to callout_reset() from an absolute time.
    968  */
    969 int
    970 hzto(struct timeval *tv)
    971 {
    972 	unsigned long ticks;
    973 	long sec, usec;
    974 	int s;
    975 
    976 	/*
    977 	 * If the number of usecs in the whole seconds part of the time
    978 	 * difference fits in a long, then the total number of usecs will
    979 	 * fit in an unsigned long.  Compute the total and convert it to
    980 	 * ticks, rounding up and adding 1 to allow for the current tick
    981 	 * to expire.  Rounding also depends on unsigned long arithmetic
    982 	 * to avoid overflow.
    983 	 *
    984 	 * Otherwise, if the number of ticks in the whole seconds part of
    985 	 * the time difference fits in a long, then convert the parts to
    986 	 * ticks separately and add, using similar rounding methods and
    987 	 * overflow avoidance.  This method would work in the previous
    988 	 * case, but it is slightly slower and assume that hz is integral.
    989 	 *
    990 	 * Otherwise, round the time difference down to the maximum
    991 	 * representable value.
    992 	 *
    993 	 * If ints are 32-bit, then the maximum value for any timeout in
    994 	 * 10ms ticks is 248 days.
    995 	 */
    996 	s = splclock();
    997 	sec = tv->tv_sec - time.tv_sec;
    998 	usec = tv->tv_usec - time.tv_usec;
    999 	splx(s);
   1000 
   1001 	if (usec < 0) {
   1002 		sec--;
   1003 		usec += 1000000;
   1004 	}
   1005 
   1006 	if (sec < 0 || (sec == 0 && usec <= 0)) {
   1007 		/*
   1008 		 * Would expire now or in the past.  Return 0 ticks.
   1009 		 * This is different from the legacy hzto() interface,
   1010 		 * and callers need to check for it.
   1011 		 */
   1012 		ticks = 0;
   1013 	} else if (sec <= (LONG_MAX / 1000000))
   1014 		ticks = (((sec * 1000000) + (unsigned long)usec + (tick - 1))
   1015 		    / tick) + 1;
   1016 	else if (sec <= (LONG_MAX / hz))
   1017 		ticks = (sec * hz) +
   1018 		    (((unsigned long)usec + (tick - 1)) / tick) + 1;
   1019 	else
   1020 		ticks = LONG_MAX;
   1021 
   1022 	if (ticks > INT_MAX)
   1023 		ticks = INT_MAX;
   1024 
   1025 	return ((int)ticks);
   1026 }
   1027 #endif /* !__HAVE_TIMECOUNTER */
   1028 
   1029 /*
   1030  * Compute number of ticks in the specified amount of time.
   1031  */
   1032 int
   1033 tstohz(struct timespec *ts)
   1034 {
   1035 	struct timeval tv;
   1036 
   1037 	/*
   1038 	 * usec has great enough resolution for hz, so convert to a
   1039 	 * timeval and use tvtohz() above.
   1040 	 */
   1041 	TIMESPEC_TO_TIMEVAL(&tv, ts);
   1042 	return tvtohz(&tv);
   1043 }
   1044 
   1045 /*
   1046  * Start profiling on a process.
   1047  *
   1048  * Kernel profiling passes proc0 which never exits and hence
   1049  * keeps the profile clock running constantly.
   1050  */
   1051 void
   1052 startprofclock(struct proc *p)
   1053 {
   1054 
   1055 	LOCK_ASSERT(mutex_owned(&p->p_stmutex));
   1056 
   1057 	if ((p->p_stflag & PST_PROFIL) == 0) {
   1058 		p->p_stflag |= PST_PROFIL;
   1059 		/*
   1060 		 * This is only necessary if using the clock as the
   1061 		 * profiling source.
   1062 		 */
   1063 		if (++profprocs == 1 && stathz != 0)
   1064 			psdiv = psratio;
   1065 	}
   1066 }
   1067 
   1068 /*
   1069  * Stop profiling on a process.
   1070  */
   1071 void
   1072 stopprofclock(struct proc *p)
   1073 {
   1074 
   1075 	LOCK_ASSERT(mutex_owned(&p->p_stmutex));
   1076 
   1077 	if (p->p_stflag & PST_PROFIL) {
   1078 		p->p_stflag &= ~PST_PROFIL;
   1079 		/*
   1080 		 * This is only necessary if using the clock as the
   1081 		 * profiling source.
   1082 		 */
   1083 		if (--profprocs == 0 && stathz != 0)
   1084 			psdiv = 1;
   1085 	}
   1086 }
   1087 
   1088 #if defined(PERFCTRS)
   1089 /*
   1090  * Independent profiling "tick" in case we're using a separate
   1091  * clock or profiling event source.  Currently, that's just
   1092  * performance counters--hence the wrapper.
   1093  */
   1094 void
   1095 proftick(struct clockframe *frame)
   1096 {
   1097 #ifdef GPROF
   1098         struct gmonparam *g;
   1099         intptr_t i;
   1100 #endif
   1101 	struct lwp *l;
   1102 	struct proc *p;
   1103 
   1104 	l = curlwp;
   1105 	p = (l ? l->l_proc : NULL);
   1106 	if (CLKF_USERMODE(frame)) {
   1107 		mutex_spin_enter(&p->p_stmutex);
   1108 		if (p->p_stflag & PST_PROFIL)
   1109 			addupc_intr(l, CLKF_PC(frame));
   1110 		mutex_spin_exit(&p->p_stmutex);
   1111 	} else {
   1112 #ifdef GPROF
   1113 		g = &_gmonparam;
   1114 		if (g->state == GMON_PROF_ON) {
   1115 			i = CLKF_PC(frame) - g->lowpc;
   1116 			if (i < g->textsize) {
   1117 				i /= HISTFRACTION * sizeof(*g->kcount);
   1118 				g->kcount[i]++;
   1119 			}
   1120 		}
   1121 #endif
   1122 #ifdef PROC_PC
   1123 		if (p != NULL) {
   1124 			mutex_spin_enter(&p->p_stmutex);
   1125 			if (p->p_stflag & PST_PROFIL))
   1126 				addupc_intr(l, PROC_PC(p));
   1127 			mutex_spin_exit(&p->p_stmutex);
   1128 		}
   1129 #endif
   1130 	}
   1131 }
   1132 #endif
   1133 
   1134 /*
   1135  * Statistics clock.  Grab profile sample, and if divider reaches 0,
   1136  * do process and kernel statistics.
   1137  */
   1138 void
   1139 statclock(struct clockframe *frame)
   1140 {
   1141 #ifdef GPROF
   1142 	struct gmonparam *g;
   1143 	intptr_t i;
   1144 #endif
   1145 	struct cpu_info *ci = curcpu();
   1146 	struct schedstate_percpu *spc = &ci->ci_schedstate;
   1147 	struct proc *p;
   1148 	struct lwp *l;
   1149 
   1150 	/*
   1151 	 * Notice changes in divisor frequency, and adjust clock
   1152 	 * frequency accordingly.
   1153 	 */
   1154 	if (spc->spc_psdiv != psdiv) {
   1155 		spc->spc_psdiv = psdiv;
   1156 		spc->spc_pscnt = psdiv;
   1157 		if (psdiv == 1) {
   1158 			setstatclockrate(stathz);
   1159 		} else {
   1160 			setstatclockrate(profhz);
   1161 		}
   1162 	}
   1163 	l = curlwp;
   1164 	if ((l->l_flag & L_IDLE) != 0) {
   1165 		/*
   1166 		 * don't account idle lwps as swapper.
   1167 		 */
   1168 		p = NULL;
   1169 	} else {
   1170 		p = l->l_proc;
   1171 		mutex_spin_enter(&p->p_stmutex);
   1172 	}
   1173 
   1174 	if (CLKF_USERMODE(frame)) {
   1175 		if ((p->p_stflag & PST_PROFIL) && profsrc == PROFSRC_CLOCK)
   1176 			addupc_intr(l, CLKF_PC(frame));
   1177 		if (--spc->spc_pscnt > 0) {
   1178 			mutex_spin_exit(&p->p_stmutex);
   1179 			return;
   1180 		}
   1181 
   1182 		/*
   1183 		 * Came from user mode; CPU was in user state.
   1184 		 * If this process is being profiled record the tick.
   1185 		 */
   1186 		p->p_uticks++;
   1187 		if (p->p_nice > NZERO)
   1188 			spc->spc_cp_time[CP_NICE]++;
   1189 		else
   1190 			spc->spc_cp_time[CP_USER]++;
   1191 	} else {
   1192 #ifdef GPROF
   1193 		/*
   1194 		 * Kernel statistics are just like addupc_intr, only easier.
   1195 		 */
   1196 		g = &_gmonparam;
   1197 		if (profsrc == PROFSRC_CLOCK && g->state == GMON_PROF_ON) {
   1198 			i = CLKF_PC(frame) - g->lowpc;
   1199 			if (i < g->textsize) {
   1200 				i /= HISTFRACTION * sizeof(*g->kcount);
   1201 				g->kcount[i]++;
   1202 			}
   1203 		}
   1204 #endif
   1205 #ifdef LWP_PC
   1206 		if (p != NULL && profsrc == PROFSRC_CLOCK &&
   1207 		    (p->p_stflag & PST_PROFIL)) {
   1208 			addupc_intr(l, LWP_PC(l));
   1209 		}
   1210 #endif
   1211 		if (--spc->spc_pscnt > 0) {
   1212 			if (p != NULL)
   1213 				mutex_spin_exit(&p->p_stmutex);
   1214 			return;
   1215 		}
   1216 		/*
   1217 		 * Came from kernel mode, so we were:
   1218 		 * - handling an interrupt,
   1219 		 * - doing syscall or trap work on behalf of the current
   1220 		 *   user process, or
   1221 		 * - spinning in the idle loop.
   1222 		 * Whichever it is, charge the time as appropriate.
   1223 		 * Note that we charge interrupts to the current process,
   1224 		 * regardless of whether they are ``for'' that process,
   1225 		 * so that we know how much of its real time was spent
   1226 		 * in ``non-process'' (i.e., interrupt) work.
   1227 		 */
   1228 		if (CLKF_INTR(frame)) {
   1229 			if (p != NULL) {
   1230 				p->p_iticks++;
   1231 			}
   1232 			spc->spc_cp_time[CP_INTR]++;
   1233 		} else if (p != NULL) {
   1234 			p->p_sticks++;
   1235 			spc->spc_cp_time[CP_SYS]++;
   1236 		} else {
   1237 			spc->spc_cp_time[CP_IDLE]++;
   1238 		}
   1239 	}
   1240 	spc->spc_pscnt = psdiv;
   1241 
   1242 	if (p == NULL) {
   1243 		return;
   1244 	}
   1245 
   1246 	++p->p_cpticks;
   1247 	mutex_spin_exit(&p->p_stmutex);
   1248 
   1249 #ifdef SCHED_4BSD
   1250 	/*
   1251 	 * If no separate schedclock is provided, call it here
   1252 	 * at about 16 Hz.
   1253 	 */
   1254 	if (schedhz == 0) {
   1255 		if ((int)(--ci->ci_schedstate.spc_schedticks) <= 0) {
   1256 			schedclock(l);
   1257 			ci->ci_schedstate.spc_schedticks = statscheddiv;
   1258 		}
   1259 	}
   1260 #endif /* SCHED_4BSD */
   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 #endif /* !__HAVE_TIMECOUNTER */
   1662