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