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