kern_tc.c revision 31016
1/*-
2 * Copyright (c) 1982, 1986, 1991, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 *    must display the following acknowledgement:
20 *	This product includes software developed by the University of
21 *	California, Berkeley and its contributors.
22 * 4. Neither the name of the University nor the names of its contributors
23 *    may be used to endorse or promote products derived from this software
24 *    without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 *
38 *	@(#)kern_clock.c	8.5 (Berkeley) 1/21/94
39 * $Id: kern_clock.c,v 1.42 1997/09/24 16:39:16 gibbs Exp $
40 */
41
42/* Portions of this software are covered by the following: */
43/******************************************************************************
44 *                                                                            *
45 * Copyright (c) David L. Mills 1993, 1994                                    *
46 *                                                                            *
47 * Permission to use, copy, modify, and distribute this software and its      *
48 * documentation for any purpose and without fee is hereby granted, provided  *
49 * that the above copyright notice appears in all copies and that both the    *
50 * copyright notice and this permission notice appear in supporting           *
51 * documentation, and that the name University of Delaware not be used in     *
52 * advertising or publicity pertaining to distribution of the software        *
53 * without specific, written prior permission.  The University of Delaware    *
54 * makes no representations about the suitability this software for any       *
55 * purpose.  It is provided "as is" without express or implied warranty.      *
56 *                                                                            *
57 *****************************************************************************/
58
59#include "opt_cpu.h"		/* XXX */
60
61#include <sys/param.h>
62#include <sys/systm.h>
63#include <sys/dkstat.h>
64#include <sys/callout.h>
65#include <sys/kernel.h>
66#include <sys/proc.h>
67#include <sys/resourcevar.h>
68#include <sys/signalvar.h>
69#include <sys/timex.h>
70#include <vm/vm.h>
71#include <sys/lock.h>
72#include <vm/pmap.h>
73#include <vm/vm_map.h>
74#include <sys/sysctl.h>
75
76#include <machine/cpu.h>
77#define CLOCK_HAIR		/* XXX */
78#include <machine/clock.h>
79#include <machine/limits.h>
80
81#ifdef GPROF
82#include <sys/gmon.h>
83#endif
84
85static void initclocks __P((void *dummy));
86SYSINIT(clocks, SI_SUB_CLOCKS, SI_ORDER_FIRST, initclocks, NULL)
87
88/* Exported to machdep.c. */
89struct callout *callout;
90struct callout_list callfree;
91int callwheelsize, callwheelbits, callwheelmask;
92struct callout_tailq *callwheel;
93
94
95/* Some of these don't belong here, but it's easiest to concentrate them. */
96static long cp_time[CPUSTATES];
97long dk_seek[DK_NDRIVE];
98static long dk_time[DK_NDRIVE];	/* time busy (in statclock ticks) */
99long dk_wds[DK_NDRIVE];
100long dk_wpms[DK_NDRIVE];
101long dk_xfer[DK_NDRIVE];
102
103int dk_busy;
104int dk_ndrive = 0;
105char dk_names[DK_NDRIVE][DK_NAMELEN];
106
107long tk_cancc;
108long tk_nin;
109long tk_nout;
110long tk_rawcc;
111
112/*
113 * Clock handling routines.
114 *
115 * This code is written to operate with two timers that run independently of
116 * each other.  The main clock, running hz times per second, is used to keep
117 * track of real time.  The second timer handles kernel and user profiling,
118 * and does resource use estimation.  If the second timer is programmable,
119 * it is randomized to avoid aliasing between the two clocks.  For example,
120 * the randomization prevents an adversary from always giving up the cpu
121 * just before its quantum expires.  Otherwise, it would never accumulate
122 * cpu ticks.  The mean frequency of the second timer is stathz.
123 *
124 * If no second timer exists, stathz will be zero; in this case we drive
125 * profiling and statistics off the main clock.  This WILL NOT be accurate;
126 * do not do it unless absolutely necessary.
127 *
128 * The statistics clock may (or may not) be run at a higher rate while
129 * profiling.  This profile clock runs at profhz.  We require that profhz
130 * be an integral multiple of stathz.
131 *
132 * If the statistics clock is running fast, it must be divided by the ratio
133 * profhz/stathz for statistics.  (For profiling, every tick counts.)
134 */
135
136/*
137 * TODO:
138 *	allocate more timeout table slots when table overflows.
139 */
140
141/*
142 * Bump a timeval by a small number of usec's.
143 */
144#define BUMPTIME(t, usec) { \
145	register volatile struct timeval *tp = (t); \
146	register long us; \
147 \
148	tp->tv_usec = us = tp->tv_usec + (usec); \
149	if (us >= 1000000) { \
150		tp->tv_usec = us - 1000000; \
151		tp->tv_sec++; \
152	} \
153}
154
155int	stathz;
156int	profhz;
157static int profprocs;
158int	ticks;
159static int softticks;			/* Like ticks, but for softclock(). */
160static struct callout *nextsoftcheck;	/* Next callout to be checked. */
161static int psdiv, pscnt;		/* prof => stat divider */
162int psratio;				/* ratio: prof / stat */
163
164volatile struct	timeval time;
165volatile struct	timeval mono_time;
166
167/*
168 * Phase/frequency-lock loop (PLL/FLL) definitions
169 *
170 * The following variables are read and set by the ntp_adjtime() system
171 * call.
172 *
173 * time_state shows the state of the system clock, with values defined
174 * in the timex.h header file.
175 *
176 * time_status shows the status of the system clock, with bits defined
177 * in the timex.h header file.
178 *
179 * time_offset is used by the PLL/FLL to adjust the system time in small
180 * increments.
181 *
182 * time_constant determines the bandwidth or "stiffness" of the PLL.
183 *
184 * time_tolerance determines maximum frequency error or tolerance of the
185 * CPU clock oscillator and is a property of the architecture; however,
186 * in principle it could change as result of the presence of external
187 * discipline signals, for instance.
188 *
189 * time_precision is usually equal to the kernel tick variable; however,
190 * in cases where a precision clock counter or external clock is
191 * available, the resolution can be much less than this and depend on
192 * whether the external clock is working or not.
193 *
194 * time_maxerror is initialized by a ntp_adjtime() call and increased by
195 * the kernel once each second to reflect the maximum error
196 * bound growth.
197 *
198 * time_esterror is set and read by the ntp_adjtime() call, but
199 * otherwise not used by the kernel.
200 */
201int time_status = STA_UNSYNC;	/* clock status bits */
202int time_state = TIME_OK;	/* clock state */
203long time_offset = 0;		/* time offset (us) */
204long time_constant = 0;		/* pll time constant */
205long time_tolerance = MAXFREQ;	/* frequency tolerance (scaled ppm) */
206long time_precision = 1;	/* clock precision (us) */
207long time_maxerror = MAXPHASE;	/* maximum error (us) */
208long time_esterror = MAXPHASE;	/* estimated error (us) */
209
210/*
211 * The following variables establish the state of the PLL/FLL and the
212 * residual time and frequency offset of the local clock. The scale
213 * factors are defined in the timex.h header file.
214 *
215 * time_phase and time_freq are the phase increment and the frequency
216 * increment, respectively, of the kernel time variable at each tick of
217 * the clock.
218 *
219 * time_freq is set via ntp_adjtime() from a value stored in a file when
220 * the synchronization daemon is first started. Its value is retrieved
221 * via ntp_adjtime() and written to the file about once per hour by the
222 * daemon.
223 *
224 * time_adj is the adjustment added to the value of tick at each timer
225 * interrupt and is recomputed from time_phase and time_freq at each
226 * seconds rollover.
227 *
228 * time_reftime is the second's portion of the system time on the last
229 * call to ntp_adjtime(). It is used to adjust the time_freq variable
230 * and to increase the time_maxerror as the time since last update
231 * increases.
232 */
233static long time_phase = 0;		/* phase offset (scaled us) */
234long time_freq = 0;			/* frequency offset (scaled ppm) */
235static long time_adj = 0;		/* tick adjust (scaled 1 / hz) */
236static long time_reftime = 0;		/* time at last adjustment (s) */
237
238#ifdef PPS_SYNC
239/*
240 * The following variables are used only if the kernel PPS discipline
241 * code is configured (PPS_SYNC). The scale factors are defined in the
242 * timex.h header file.
243 *
244 * pps_time contains the time at each calibration interval, as read by
245 * microtime(). pps_count counts the seconds of the calibration
246 * interval, the duration of which is nominally pps_shift in powers of
247 * two.
248 *
249 * pps_offset is the time offset produced by the time median filter
250 * pps_tf[], while pps_jitter is the dispersion (jitter) measured by
251 * this filter.
252 *
253 * pps_freq is the frequency offset produced by the frequency median
254 * filter pps_ff[], while pps_stabil is the dispersion (wander) measured
255 * by this filter.
256 *
257 * pps_usec is latched from a high resolution counter or external clock
258 * at pps_time. Here we want the hardware counter contents only, not the
259 * contents plus the time_tv.usec as usual.
260 *
261 * pps_valid counts the number of seconds since the last PPS update. It
262 * is used as a watchdog timer to disable the PPS discipline should the
263 * PPS signal be lost.
264 *
265 * pps_glitch counts the number of seconds since the beginning of an
266 * offset burst more than tick/2 from current nominal offset. It is used
267 * mainly to suppress error bursts due to priority conflicts between the
268 * PPS interrupt and timer interrupt.
269 *
270 * pps_intcnt counts the calibration intervals for use in the interval-
271 * adaptation algorithm. It's just too complicated for words.
272 */
273struct timeval pps_time;	/* kernel time at last interval */
274long pps_offset = 0;		/* pps time offset (us) */
275long pps_jitter = MAXTIME;	/* pps time dispersion (jitter) (us) */
276long pps_tf[] = {0, 0, 0};	/* pps time offset median filter (us) */
277long pps_freq = 0;		/* frequency offset (scaled ppm) */
278long pps_stabil = MAXFREQ;	/* frequency dispersion (scaled ppm) */
279long pps_ff[] = {0, 0, 0};	/* frequency offset median filter */
280long pps_usec = 0;		/* microsec counter at last interval */
281long pps_valid = PPS_VALID;	/* pps signal watchdog counter */
282int pps_glitch = 0;		/* pps signal glitch counter */
283int pps_count = 0;		/* calibration interval counter (s) */
284int pps_shift = PPS_SHIFT;	/* interval duration (s) (shift) */
285int pps_intcnt = 0;		/* intervals at current duration */
286
287/*
288 * PPS signal quality monitors
289 *
290 * pps_jitcnt counts the seconds that have been discarded because the
291 * jitter measured by the time median filter exceeds the limit MAXTIME
292 * (100 us).
293 *
294 * pps_calcnt counts the frequency calibration intervals, which are
295 * variable from 4 s to 256 s.
296 *
297 * pps_errcnt counts the calibration intervals which have been discarded
298 * because the wander exceeds the limit MAXFREQ (100 ppm) or where the
299 * calibration interval jitter exceeds two ticks.
300 *
301 * pps_stbcnt counts the calibration intervals that have been discarded
302 * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us).
303 */
304long pps_jitcnt = 0;		/* jitter limit exceeded */
305long pps_calcnt = 0;		/* calibration intervals */
306long pps_errcnt = 0;		/* calibration errors */
307long pps_stbcnt = 0;		/* stability limit exceeded */
308#endif /* PPS_SYNC */
309
310/* XXX none of this stuff works under FreeBSD */
311#ifdef EXT_CLOCK
312/*
313 * External clock definitions
314 *
315 * The following definitions and declarations are used only if an
316 * external clock (HIGHBALL or TPRO) is configured on the system.
317 */
318#define CLOCK_INTERVAL 30	/* CPU clock update interval (s) */
319
320/*
321 * The clock_count variable is set to CLOCK_INTERVAL at each PPS
322 * interrupt and decremented once each second.
323 */
324int clock_count = 0;		/* CPU clock counter */
325
326#ifdef HIGHBALL
327/*
328 * The clock_offset and clock_cpu variables are used by the HIGHBALL
329 * interface. The clock_offset variable defines the offset between
330 * system time and the HIGBALL counters. The clock_cpu variable contains
331 * the offset between the system clock and the HIGHBALL clock for use in
332 * disciplining the kernel time variable.
333 */
334extern struct timeval clock_offset; /* Highball clock offset */
335long clock_cpu = 0;		/* CPU clock adjust */
336#endif /* HIGHBALL */
337#endif /* EXT_CLOCK */
338
339/*
340 * hardupdate() - local clock update
341 *
342 * This routine is called by ntp_adjtime() to update the local clock
343 * phase and frequency. The implementation is of an adaptive-parameter,
344 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
345 * time and frequency offset estimates for each call. If the kernel PPS
346 * discipline code is configured (PPS_SYNC), the PPS signal itself
347 * determines the new time offset, instead of the calling argument.
348 * Presumably, calls to ntp_adjtime() occur only when the caller
349 * believes the local clock is valid within some bound (+-128 ms with
350 * NTP). If the caller's time is far different than the PPS time, an
351 * argument will ensue, and it's not clear who will lose.
352 *
353 * For uncompensated quartz crystal oscillatores and nominal update
354 * intervals less than 1024 s, operation should be in phase-lock mode
355 * (STA_FLL = 0), where the loop is disciplined to phase. For update
356 * intervals greater than thiss, operation should be in frequency-lock
357 * mode (STA_FLL = 1), where the loop is disciplined to frequency.
358 *
359 * Note: splclock() is in effect.
360 */
361void
362hardupdate(offset)
363	long offset;
364{
365	long ltemp, mtemp;
366
367	if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
368		return;
369	ltemp = offset;
370#ifdef PPS_SYNC
371	if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
372		ltemp = pps_offset;
373#endif /* PPS_SYNC */
374
375	/*
376	 * Scale the phase adjustment and clamp to the operating range.
377	 */
378	if (ltemp > MAXPHASE)
379		time_offset = MAXPHASE << SHIFT_UPDATE;
380	else if (ltemp < -MAXPHASE)
381		time_offset = -(MAXPHASE << SHIFT_UPDATE);
382	else
383		time_offset = ltemp << SHIFT_UPDATE;
384
385	/*
386	 * Select whether the frequency is to be controlled and in which
387	 * mode (PLL or FLL). Clamp to the operating range. Ugly
388	 * multiply/divide should be replaced someday.
389	 */
390	if (time_status & STA_FREQHOLD || time_reftime == 0)
391		time_reftime = time.tv_sec;
392	mtemp = time.tv_sec - time_reftime;
393	time_reftime = time.tv_sec;
394	if (time_status & STA_FLL) {
395		if (mtemp >= MINSEC) {
396			ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
397			    SHIFT_UPDATE));
398			if (ltemp < 0)
399				time_freq -= -ltemp >> SHIFT_KH;
400			else
401				time_freq += ltemp >> SHIFT_KH;
402		}
403	} else {
404		if (mtemp < MAXSEC) {
405			ltemp *= mtemp;
406			if (ltemp < 0)
407				time_freq -= -ltemp >> (time_constant +
408				    time_constant + SHIFT_KF -
409				    SHIFT_USEC);
410			else
411				time_freq += ltemp >> (time_constant +
412				    time_constant + SHIFT_KF -
413				    SHIFT_USEC);
414		}
415	}
416	if (time_freq > time_tolerance)
417		time_freq = time_tolerance;
418	else if (time_freq < -time_tolerance)
419		time_freq = -time_tolerance;
420}
421
422
423
424/*
425 * Initialize clock frequencies and start both clocks running.
426 */
427/* ARGSUSED*/
428static void
429initclocks(dummy)
430	void *dummy;
431{
432	register int i;
433
434	/*
435	 * Set divisors to 1 (normal case) and let the machine-specific
436	 * code do its bit.
437	 */
438	psdiv = pscnt = 1;
439	cpu_initclocks();
440
441	/*
442	 * Compute profhz/stathz, and fix profhz if needed.
443	 */
444	i = stathz ? stathz : hz;
445	if (profhz == 0)
446		profhz = i;
447	psratio = profhz / i;
448}
449
450/*
451 * The real-time timer, interrupting hz times per second.
452 */
453void
454hardclock(frame)
455	register struct clockframe *frame;
456{
457	register struct proc *p;
458
459	p = curproc;
460	if (p) {
461		register struct pstats *pstats;
462
463		/*
464		 * Run current process's virtual and profile time, as needed.
465		 */
466		pstats = p->p_stats;
467		if (CLKF_USERMODE(frame) &&
468		    timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
469		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
470			psignal(p, SIGVTALRM);
471		if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
472		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
473			psignal(p, SIGPROF);
474	}
475
476	/*
477	 * If no separate statistics clock is available, run it from here.
478	 */
479	if (stathz == 0)
480		statclock(frame);
481
482	/*
483	 * Increment the time-of-day.
484	 */
485	ticks++;
486	{
487		int time_update;
488		struct timeval newtime = time;
489		long ltemp;
490
491		if (timedelta == 0) {
492			time_update = CPU_THISTICKLEN(tick);
493		} else {
494			time_update = CPU_THISTICKLEN(tick) + tickdelta;
495			timedelta -= tickdelta;
496		}
497		BUMPTIME(&mono_time, time_update);
498
499		/*
500		 * Compute the phase adjustment. If the low-order bits
501		 * (time_phase) of the update overflow, bump the high-order bits
502		 * (time_update).
503		 */
504		time_phase += time_adj;
505		if (time_phase <= -FINEUSEC) {
506		  ltemp = -time_phase >> SHIFT_SCALE;
507		  time_phase += ltemp << SHIFT_SCALE;
508		  time_update -= ltemp;
509		}
510		else if (time_phase >= FINEUSEC) {
511		  ltemp = time_phase >> SHIFT_SCALE;
512		  time_phase -= ltemp << SHIFT_SCALE;
513		  time_update += ltemp;
514		}
515
516		newtime.tv_usec += time_update;
517		/*
518		 * On rollover of the second the phase adjustment to be used for
519		 * the next second is calculated. Also, the maximum error is
520		 * increased by the tolerance. If the PPS frequency discipline
521		 * code is present, the phase is increased to compensate for the
522		 * CPU clock oscillator frequency error.
523		 *
524		 * On a 32-bit machine and given parameters in the timex.h
525		 * header file, the maximum phase adjustment is +-512 ms and
526		 * maximum frequency offset is a tad less than) +-512 ppm. On a
527		 * 64-bit machine, you shouldn't need to ask.
528		 */
529		if (newtime.tv_usec >= 1000000) {
530		  newtime.tv_usec -= 1000000;
531		  newtime.tv_sec++;
532		  time_maxerror += time_tolerance >> SHIFT_USEC;
533
534		  /*
535		   * Compute the phase adjustment for the next second. In
536		   * PLL mode, the offset is reduced by a fixed factor
537		   * times the time constant. In FLL mode the offset is
538		   * used directly. In either mode, the maximum phase
539		   * adjustment for each second is clamped so as to spread
540		   * the adjustment over not more than the number of
541		   * seconds between updates.
542		   */
543		  if (time_offset < 0) {
544		    ltemp = -time_offset;
545		    if (!(time_status & STA_FLL))
546			ltemp >>= SHIFT_KG + time_constant;
547		    if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
548			ltemp = (MAXPHASE / MINSEC) <<
549			    SHIFT_UPDATE;
550		    time_offset += ltemp;
551		    time_adj = -ltemp << (SHIFT_SCALE - SHIFT_HZ -
552			SHIFT_UPDATE);
553		    } else {
554		        ltemp = time_offset;
555			if (!(time_status & STA_FLL))
556				ltemp >>= SHIFT_KG + time_constant;
557			if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
558				ltemp = (MAXPHASE / MINSEC) <<
559				    SHIFT_UPDATE;
560			time_offset -= ltemp;
561			time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ -
562			    SHIFT_UPDATE);
563		    }
564
565		  /*
566		   * Compute the frequency estimate and additional phase
567		   * adjustment due to frequency error for the next
568		   * second. When the PPS signal is engaged, gnaw on the
569		   * watchdog counter and update the frequency computed by
570		   * the pll and the PPS signal.
571		   */
572#ifdef PPS_SYNC
573		  pps_valid++;
574		  if (pps_valid == PPS_VALID) {
575		    pps_jitter = MAXTIME;
576		    pps_stabil = MAXFREQ;
577		    time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
578				     STA_PPSWANDER | STA_PPSERROR);
579		  }
580		  ltemp = time_freq + pps_freq;
581#else
582		  ltemp = time_freq;
583#endif /* PPS_SYNC */
584		  if (ltemp < 0)
585		    time_adj -= -ltemp >>
586		      (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
587		  else
588		    time_adj += ltemp >>
589		      (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
590
591#if SHIFT_HZ == 7
592		  /*
593		   * When the CPU clock oscillator frequency is not a
594		   * power of two in Hz, the SHIFT_HZ is only an
595		   * approximate scale factor. In the SunOS kernel, this
596		   * results in a PLL gain factor of 1/1.28 = 0.78 what it
597		   * should be. In the following code the overall gain is
598		   * increased by a factor of 1.25, which results in a
599		   * residual error less than 3 percent.
600		   */
601		  /* Same thing applies for FreeBSD --GAW */
602		  if (hz == 100) {
603		    if (time_adj < 0)
604		      time_adj -= -time_adj >> 2;
605		    else
606		      time_adj += time_adj >> 2;
607		  }
608#endif /* SHIFT_HZ */
609
610		  /* XXX - this is really bogus, but can't be fixed until
611		     xntpd's idea of the system clock is fixed to know how
612		     the user wants leap seconds handled; in the mean time,
613		     we assume that users of NTP are running without proper
614		     leap second support (this is now the default anyway) */
615		  /*
616		   * Leap second processing. If in leap-insert state at
617		   * the end of the day, the system clock is set back one
618		   * second; if in leap-delete state, the system clock is
619		   * set ahead one second. The microtime() routine or
620		   * external clock driver will insure that reported time
621		   * is always monotonic. The ugly divides should be
622		   * replaced.
623		   */
624		  switch (time_state) {
625
626		  case TIME_OK:
627		    if (time_status & STA_INS)
628		      time_state = TIME_INS;
629		    else if (time_status & STA_DEL)
630		      time_state = TIME_DEL;
631		    break;
632
633		  case TIME_INS:
634		    if (newtime.tv_sec % 86400 == 0) {
635		      newtime.tv_sec--;
636		      time_state = TIME_OOP;
637		    }
638		    break;
639
640		  case TIME_DEL:
641		    if ((newtime.tv_sec + 1) % 86400 == 0) {
642		      newtime.tv_sec++;
643		      time_state = TIME_WAIT;
644		    }
645		    break;
646
647		  case TIME_OOP:
648		    time_state = TIME_WAIT;
649		    break;
650
651		  case TIME_WAIT:
652		    if (!(time_status & (STA_INS | STA_DEL)))
653		      time_state = TIME_OK;
654		  }
655		}
656		CPU_CLOCKUPDATE(&time, &newtime);
657	}
658
659	/*
660	 * Process callouts at a very low cpu priority, so we don't keep the
661	 * relatively high clock interrupt priority any longer than necessary.
662	 */
663	if (TAILQ_FIRST(&callwheel[ticks & callwheelmask]) != NULL) {
664		if (CLKF_BASEPRI(frame)) {
665			/*
666			 * Save the overhead of a software interrupt;
667			 * it will happen as soon as we return, so do it now.
668			 */
669			(void)splsoftclock();
670			softclock();
671		} else
672			setsoftclock();
673	} else if (softticks + 1 == ticks) {
674		++softticks;
675	}
676}
677
678/*
679 * The callout mechanism is based on the work of Adam M. Costello and
680 * George Varghese, published in a technical report entitled "Redesigning
681 * the BSD Callout and Timer Facilities" and modified slightly for inclusion
682 * in FreeBSD by Justin T. Gibbs.  The original work on the data structures
683 * used in this implementation was published by G.Varghese and A. Lauck in
684 * the paper "Hashed and Hierarchical Timing Wheels: Data Structures for
685 * the Efficient Implementation of a Timer Facility" in the Proceedings of
686 * the 11th ACM Annual Symposium on Operating Systems Principles,
687 * Austin, Texas Nov 1987.
688 */
689/*
690 * Software (low priority) clock interrupt.
691 * Run periodic events from timeout queue.
692 */
693/*ARGSUSED*/
694void
695softclock()
696{
697	register struct callout *c;
698	register struct callout_tailq *bucket;
699	register int s;
700	register int curticks;
701	register int steps;	/*
702				 * Number of steps taken since
703				 * we last allowed interrupts.
704				 */
705
706	#ifndef MAX_SOFTCLOCK_STEPS
707	#define MAX_SOFTCLOCK_STEPS 100 /* Maximum allowed value of steps. */
708	#endif /* MAX_SOFTCLOCK_STEPS */
709
710	steps = 0;
711	s = splhigh();
712	while (softticks != ticks) {
713		softticks++;
714		/*
715		 * softticks may be modified by hard clock, so cache
716		 * it while we work on a given bucket.
717		 */
718		curticks = softticks;
719		bucket = &callwheel[curticks & callwheelmask];
720		c = TAILQ_FIRST(bucket);
721		while (c) {
722			if (c->c_time != curticks) {
723				c = TAILQ_NEXT(c, c_links.tqe);
724				++steps;
725				if (steps >= MAX_SOFTCLOCK_STEPS) {
726					nextsoftcheck = c;
727					/* Give interrupts a chance. */
728					splx(s);
729					s = splhigh();
730					c = nextsoftcheck;
731					steps = 0;
732				}
733			} else {
734				void (*c_func)(void *);
735				void *c_arg;
736
737				nextsoftcheck = TAILQ_NEXT(c, c_links.tqe);
738				TAILQ_REMOVE(bucket, c, c_links.tqe);
739				c_func = c->c_func;
740				c_arg = c->c_arg;
741				c->c_func = NULL;
742				SLIST_INSERT_HEAD(&callfree, c, c_links.sle);
743				splx(s);
744				c_func(c_arg);
745				s = splhigh();
746				steps = 0;
747				c = nextsoftcheck;
748			}
749		}
750	}
751	nextsoftcheck = NULL;
752	splx(s);
753}
754
755/*
756 * timeout --
757 *	Execute a function after a specified length of time.
758 *
759 * untimeout --
760 *	Cancel previous timeout function call.
761 *
762 * callout_handle_init --
763 *	Initialize a handle so that using it with untimeout is benign.
764 *
765 *	See AT&T BCI Driver Reference Manual for specification.  This
766 *	implementation differs from that one in that although an
767 *	identification value is returned from timeout, the original
768 *	arguments to timeout as well as the identifier are used to
769 *	identify entries for untimeout.
770 */
771struct callout_handle
772timeout(ftn, arg, to_ticks)
773	timeout_t ftn;
774	void *arg;
775	register int to_ticks;
776{
777	int s;
778	struct callout *new;
779	struct callout_handle handle;
780
781	if (to_ticks <= 0)
782		to_ticks = 1;
783
784	/* Lock out the clock. */
785	s = splhigh();
786
787	/* Fill in the next free callout structure. */
788	new = SLIST_FIRST(&callfree);
789	if (new == NULL)
790		/* XXX Attempt to malloc first */
791		panic("timeout table full");
792
793	SLIST_REMOVE_HEAD(&callfree, c_links.sle);
794	new->c_arg = arg;
795	new->c_func = ftn;
796	new->c_time = ticks + to_ticks;
797	TAILQ_INSERT_TAIL(&callwheel[new->c_time & callwheelmask],
798			  new, c_links.tqe);
799
800	splx(s);
801	handle.callout = new;
802	return (handle);
803}
804
805void
806untimeout(ftn, arg, handle)
807	timeout_t ftn;
808	void *arg;
809	struct callout_handle handle;
810{
811	register int s;
812
813	/*
814	 * Check for a handle that was initialized
815	 * by callout_handle_init, but never used
816	 * for a real timeout.
817	 */
818	if (handle.callout == NULL)
819		return;
820
821	s = splhigh();
822	if ((handle.callout->c_func == ftn)
823	 && (handle.callout->c_arg == arg)) {
824		if (nextsoftcheck == handle.callout) {
825			nextsoftcheck = TAILQ_NEXT(handle.callout, c_links.tqe);
826		}
827		TAILQ_REMOVE(&callwheel[handle.callout->c_time & callwheelmask],
828			     handle.callout, c_links.tqe);
829		handle.callout->c_func = NULL;
830		SLIST_INSERT_HEAD(&callfree, handle.callout, c_links.sle);
831	}
832	splx(s);
833}
834
835void
836callout_handle_init(struct callout_handle *handle)
837{
838	handle->callout = NULL;
839}
840
841void
842gettime(struct timeval *tvp)
843{
844	int s;
845
846	s = splclock();
847	/* XXX should use microtime() iff tv_usec is used. */
848	*tvp = time;
849	splx(s);
850}
851
852/*
853 * Compute number of hz until specified time.  Used to
854 * compute third argument to timeout() from an absolute time.
855 */
856int
857hzto(tv)
858	struct timeval *tv;
859{
860	register unsigned long ticks;
861	register long sec, usec;
862	int s;
863
864	/*
865	 * If the number of usecs in the whole seconds part of the time
866	 * difference fits in a long, then the total number of usecs will
867	 * fit in an unsigned long.  Compute the total and convert it to
868	 * ticks, rounding up and adding 1 to allow for the current tick
869	 * to expire.  Rounding also depends on unsigned long arithmetic
870	 * to avoid overflow.
871	 *
872	 * Otherwise, if the number of ticks in the whole seconds part of
873	 * the time difference fits in a long, then convert the parts to
874	 * ticks separately and add, using similar rounding methods and
875	 * overflow avoidance.  This method would work in the previous
876	 * case but it is slightly slower and assumes that hz is integral.
877	 *
878	 * Otherwise, round the time difference down to the maximum
879	 * representable value.
880	 *
881	 * If ints have 32 bits, then the maximum value for any timeout in
882	 * 10ms ticks is 248 days.
883	 */
884	s = splclock();
885	sec = tv->tv_sec - time.tv_sec;
886	usec = tv->tv_usec - time.tv_usec;
887	splx(s);
888	if (usec < 0) {
889		sec--;
890		usec += 1000000;
891	}
892	if (sec < 0) {
893#ifdef DIAGNOSTIC
894		printf("hzto: negative time difference %ld sec %ld usec\n",
895		       sec, usec);
896#endif
897		ticks = 1;
898	} else if (sec <= LONG_MAX / 1000000)
899		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
900			/ tick + 1;
901	else if (sec <= LONG_MAX / hz)
902		ticks = sec * hz
903			+ ((unsigned long)usec + (tick - 1)) / tick + 1;
904	else
905		ticks = LONG_MAX;
906	if (ticks > INT_MAX)
907		ticks = INT_MAX;
908	return (ticks);
909}
910
911/*
912 * Start profiling on a process.
913 *
914 * Kernel profiling passes proc0 which never exits and hence
915 * keeps the profile clock running constantly.
916 */
917void
918startprofclock(p)
919	register struct proc *p;
920{
921	int s;
922
923	if ((p->p_flag & P_PROFIL) == 0) {
924		p->p_flag |= P_PROFIL;
925		if (++profprocs == 1 && stathz != 0) {
926			s = splstatclock();
927			psdiv = pscnt = psratio;
928			setstatclockrate(profhz);
929			splx(s);
930		}
931	}
932}
933
934/*
935 * Stop profiling on a process.
936 */
937void
938stopprofclock(p)
939	register struct proc *p;
940{
941	int s;
942
943	if (p->p_flag & P_PROFIL) {
944		p->p_flag &= ~P_PROFIL;
945		if (--profprocs == 0 && stathz != 0) {
946			s = splstatclock();
947			psdiv = pscnt = 1;
948			setstatclockrate(stathz);
949			splx(s);
950		}
951	}
952}
953
954/*
955 * Statistics clock.  Grab profile sample, and if divider reaches 0,
956 * do process and kernel statistics.
957 */
958void
959statclock(frame)
960	register struct clockframe *frame;
961{
962#ifdef GPROF
963	register struct gmonparam *g;
964#endif
965	register struct proc *p;
966	register int i;
967	struct pstats *pstats;
968	long rss;
969	struct rusage *ru;
970	struct vmspace *vm;
971
972	if (CLKF_USERMODE(frame)) {
973		p = curproc;
974		if (p->p_flag & P_PROFIL)
975			addupc_intr(p, CLKF_PC(frame), 1);
976		if (--pscnt > 0)
977			return;
978		/*
979		 * Came from user mode; CPU was in user state.
980		 * If this process is being profiled record the tick.
981		 */
982		p->p_uticks++;
983		if (p->p_nice > NZERO)
984			cp_time[CP_NICE]++;
985		else
986			cp_time[CP_USER]++;
987	} else {
988#ifdef GPROF
989		/*
990		 * Kernel statistics are just like addupc_intr, only easier.
991		 */
992		g = &_gmonparam;
993		if (g->state == GMON_PROF_ON) {
994			i = CLKF_PC(frame) - g->lowpc;
995			if (i < g->textsize) {
996				i /= HISTFRACTION * sizeof(*g->kcount);
997				g->kcount[i]++;
998			}
999		}
1000#endif
1001		if (--pscnt > 0)
1002			return;
1003		/*
1004		 * Came from kernel mode, so we were:
1005		 * - handling an interrupt,
1006		 * - doing syscall or trap work on behalf of the current
1007		 *   user process, or
1008		 * - spinning in the idle loop.
1009		 * Whichever it is, charge the time as appropriate.
1010		 * Note that we charge interrupts to the current process,
1011		 * regardless of whether they are ``for'' that process,
1012		 * so that we know how much of its real time was spent
1013		 * in ``non-process'' (i.e., interrupt) work.
1014		 */
1015		p = curproc;
1016		if (CLKF_INTR(frame)) {
1017			if (p != NULL)
1018				p->p_iticks++;
1019			cp_time[CP_INTR]++;
1020		} else if (p != NULL && !(p->p_flag & P_IDLEPROC)) {
1021			p->p_sticks++;
1022			cp_time[CP_SYS]++;
1023		} else
1024			cp_time[CP_IDLE]++;
1025	}
1026	pscnt = psdiv;
1027
1028	/*
1029	 * We maintain statistics shown by user-level statistics
1030	 * programs:  the amount of time in each cpu state, and
1031	 * the amount of time each of DK_NDRIVE ``drives'' is busy.
1032	 *
1033	 * XXX	should either run linked list of drives, or (better)
1034	 *	grab timestamps in the start & done code.
1035	 */
1036	for (i = 0; i < DK_NDRIVE; i++)
1037		if (dk_busy & (1 << i))
1038			dk_time[i]++;
1039
1040	/*
1041	 * We adjust the priority of the current process.  The priority of
1042	 * a process gets worse as it accumulates CPU time.  The cpu usage
1043	 * estimator (p_estcpu) is increased here.  The formula for computing
1044	 * priorities (in kern_synch.c) will compute a different value each
1045	 * time p_estcpu increases by 4.  The cpu usage estimator ramps up
1046	 * quite quickly when the process is running (linearly), and decays
1047	 * away exponentially, at a rate which is proportionally slower when
1048	 * the system is busy.  The basic principal is that the system will
1049	 * 90% forget that the process used a lot of CPU time in 5 * loadav
1050	 * seconds.  This causes the system to favor processes which haven't
1051	 * run much recently, and to round-robin among other processes.
1052	 */
1053	if (p != NULL) {
1054		p->p_cpticks++;
1055		if (++p->p_estcpu == 0)
1056			p->p_estcpu--;
1057		if ((p->p_estcpu & 3) == 0) {
1058			resetpriority(p);
1059			if (p->p_priority >= PUSER)
1060				p->p_priority = p->p_usrpri;
1061		}
1062
1063		/* Update resource usage integrals and maximums. */
1064		if ((pstats = p->p_stats) != NULL &&
1065		    (ru = &pstats->p_ru) != NULL &&
1066		    (vm = p->p_vmspace) != NULL) {
1067			ru->ru_ixrss += vm->vm_tsize * PAGE_SIZE / 1024;
1068			ru->ru_idrss += vm->vm_dsize * PAGE_SIZE / 1024;
1069			ru->ru_isrss += vm->vm_ssize * PAGE_SIZE / 1024;
1070			rss = vm->vm_pmap.pm_stats.resident_count *
1071			      PAGE_SIZE / 1024;
1072			if (ru->ru_maxrss < rss)
1073				ru->ru_maxrss = rss;
1074        	}
1075	}
1076}
1077
1078/*
1079 * Return information about system clocks.
1080 */
1081static int
1082sysctl_kern_clockrate SYSCTL_HANDLER_ARGS
1083{
1084	struct clockinfo clkinfo;
1085	/*
1086	 * Construct clockinfo structure.
1087	 */
1088	clkinfo.hz = hz;
1089	clkinfo.tick = tick;
1090	clkinfo.tickadj = tickadj;
1091	clkinfo.profhz = profhz;
1092	clkinfo.stathz = stathz ? stathz : hz;
1093	return (sysctl_handle_opaque(oidp, &clkinfo, sizeof clkinfo, req));
1094}
1095
1096SYSCTL_PROC(_kern, KERN_CLOCKRATE, clockrate, CTLTYPE_STRUCT|CTLFLAG_RD,
1097	0, 0, sysctl_kern_clockrate, "S,clockinfo","");
1098
1099#ifdef PPS_SYNC
1100/*
1101 * hardpps() - discipline CPU clock oscillator to external PPS signal
1102 *
1103 * This routine is called at each PPS interrupt in order to discipline
1104 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
1105 * and leaves it in a handy spot for the hardclock() routine. It
1106 * integrates successive PPS phase differences and calculates the
1107 * frequency offset. This is used in hardclock() to discipline the CPU
1108 * clock oscillator so that intrinsic frequency error is cancelled out.
1109 * The code requires the caller to capture the time and hardware counter
1110 * value at the on-time PPS signal transition.
1111 *
1112 * Note that, on some Unix systems, this routine runs at an interrupt
1113 * priority level higher than the timer interrupt routine hardclock().
1114 * Therefore, the variables used are distinct from the hardclock()
1115 * variables, except for certain exceptions: The PPS frequency pps_freq
1116 * and phase pps_offset variables are determined by this routine and
1117 * updated atomically. The time_tolerance variable can be considered a
1118 * constant, since it is infrequently changed, and then only when the
1119 * PPS signal is disabled. The watchdog counter pps_valid is updated
1120 * once per second by hardclock() and is atomically cleared in this
1121 * routine.
1122 */
1123void
1124hardpps(tvp, usec)
1125	struct timeval *tvp;		/* time at PPS */
1126	long usec;			/* hardware counter at PPS */
1127{
1128	long u_usec, v_usec, bigtick;
1129	long cal_sec, cal_usec;
1130
1131	/*
1132	 * An occasional glitch can be produced when the PPS interrupt
1133	 * occurs in the hardclock() routine before the time variable is
1134	 * updated. Here the offset is discarded when the difference
1135	 * between it and the last one is greater than tick/2, but not
1136	 * if the interval since the first discard exceeds 30 s.
1137	 */
1138	time_status |= STA_PPSSIGNAL;
1139	time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1140	pps_valid = 0;
1141	u_usec = -tvp->tv_usec;
1142	if (u_usec < -500000)
1143		u_usec += 1000000;
1144	v_usec = pps_offset - u_usec;
1145	if (v_usec < 0)
1146		v_usec = -v_usec;
1147	if (v_usec > (tick >> 1)) {
1148		if (pps_glitch > MAXGLITCH) {
1149			pps_glitch = 0;
1150			pps_tf[2] = u_usec;
1151			pps_tf[1] = u_usec;
1152		} else {
1153			pps_glitch++;
1154			u_usec = pps_offset;
1155		}
1156	} else
1157		pps_glitch = 0;
1158
1159	/*
1160	 * A three-stage median filter is used to help deglitch the pps
1161	 * time. The median sample becomes the time offset estimate; the
1162	 * difference between the other two samples becomes the time
1163	 * dispersion (jitter) estimate.
1164	 */
1165	pps_tf[2] = pps_tf[1];
1166	pps_tf[1] = pps_tf[0];
1167	pps_tf[0] = u_usec;
1168	if (pps_tf[0] > pps_tf[1]) {
1169		if (pps_tf[1] > pps_tf[2]) {
1170			pps_offset = pps_tf[1];		/* 0 1 2 */
1171			v_usec = pps_tf[0] - pps_tf[2];
1172		} else if (pps_tf[2] > pps_tf[0]) {
1173			pps_offset = pps_tf[0];		/* 2 0 1 */
1174			v_usec = pps_tf[2] - pps_tf[1];
1175		} else {
1176			pps_offset = pps_tf[2];		/* 0 2 1 */
1177			v_usec = pps_tf[0] - pps_tf[1];
1178		}
1179	} else {
1180		if (pps_tf[1] < pps_tf[2]) {
1181			pps_offset = pps_tf[1];		/* 2 1 0 */
1182			v_usec = pps_tf[2] - pps_tf[0];
1183		} else  if (pps_tf[2] < pps_tf[0]) {
1184			pps_offset = pps_tf[0];		/* 1 0 2 */
1185			v_usec = pps_tf[1] - pps_tf[2];
1186		} else {
1187			pps_offset = pps_tf[2];		/* 1 2 0 */
1188			v_usec = pps_tf[1] - pps_tf[0];
1189		}
1190	}
1191	if (v_usec > MAXTIME)
1192		pps_jitcnt++;
1193	v_usec = (v_usec << PPS_AVG) - pps_jitter;
1194	if (v_usec < 0)
1195		pps_jitter -= -v_usec >> PPS_AVG;
1196	else
1197		pps_jitter += v_usec >> PPS_AVG;
1198	if (pps_jitter > (MAXTIME >> 1))
1199		time_status |= STA_PPSJITTER;
1200
1201	/*
1202	 * During the calibration interval adjust the starting time when
1203	 * the tick overflows. At the end of the interval compute the
1204	 * duration of the interval and the difference of the hardware
1205	 * counters at the beginning and end of the interval. This code
1206	 * is deliciously complicated by the fact valid differences may
1207	 * exceed the value of tick when using long calibration
1208	 * intervals and small ticks. Note that the counter can be
1209	 * greater than tick if caught at just the wrong instant, but
1210	 * the values returned and used here are correct.
1211	 */
1212	bigtick = (long)tick << SHIFT_USEC;
1213	pps_usec -= pps_freq;
1214	if (pps_usec >= bigtick)
1215		pps_usec -= bigtick;
1216	if (pps_usec < 0)
1217		pps_usec += bigtick;
1218	pps_time.tv_sec++;
1219	pps_count++;
1220	if (pps_count < (1 << pps_shift))
1221		return;
1222	pps_count = 0;
1223	pps_calcnt++;
1224	u_usec = usec << SHIFT_USEC;
1225	v_usec = pps_usec - u_usec;
1226	if (v_usec >= bigtick >> 1)
1227		v_usec -= bigtick;
1228	if (v_usec < -(bigtick >> 1))
1229		v_usec += bigtick;
1230	if (v_usec < 0)
1231		v_usec = -(-v_usec >> pps_shift);
1232	else
1233		v_usec = v_usec >> pps_shift;
1234	pps_usec = u_usec;
1235	cal_sec = tvp->tv_sec;
1236	cal_usec = tvp->tv_usec;
1237	cal_sec -= pps_time.tv_sec;
1238	cal_usec -= pps_time.tv_usec;
1239	if (cal_usec < 0) {
1240		cal_usec += 1000000;
1241		cal_sec--;
1242	}
1243	pps_time = *tvp;
1244
1245	/*
1246	 * Check for lost interrupts, noise, excessive jitter and
1247	 * excessive frequency error. The number of timer ticks during
1248	 * the interval may vary +-1 tick. Add to this a margin of one
1249	 * tick for the PPS signal jitter and maximum frequency
1250	 * deviation. If the limits are exceeded, the calibration
1251	 * interval is reset to the minimum and we start over.
1252	 */
1253	u_usec = (long)tick << 1;
1254	if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
1255	    || (cal_sec == 0 && cal_usec < u_usec))
1256	    || v_usec > time_tolerance || v_usec < -time_tolerance) {
1257		pps_errcnt++;
1258		pps_shift = PPS_SHIFT;
1259		pps_intcnt = 0;
1260		time_status |= STA_PPSERROR;
1261		return;
1262	}
1263
1264	/*
1265	 * A three-stage median filter is used to help deglitch the pps
1266	 * frequency. The median sample becomes the frequency offset
1267	 * estimate; the difference between the other two samples
1268	 * becomes the frequency dispersion (stability) estimate.
1269	 */
1270	pps_ff[2] = pps_ff[1];
1271	pps_ff[1] = pps_ff[0];
1272	pps_ff[0] = v_usec;
1273	if (pps_ff[0] > pps_ff[1]) {
1274		if (pps_ff[1] > pps_ff[2]) {
1275			u_usec = pps_ff[1];		/* 0 1 2 */
1276			v_usec = pps_ff[0] - pps_ff[2];
1277		} else if (pps_ff[2] > pps_ff[0]) {
1278			u_usec = pps_ff[0];		/* 2 0 1 */
1279			v_usec = pps_ff[2] - pps_ff[1];
1280		} else {
1281			u_usec = pps_ff[2];		/* 0 2 1 */
1282			v_usec = pps_ff[0] - pps_ff[1];
1283		}
1284	} else {
1285		if (pps_ff[1] < pps_ff[2]) {
1286			u_usec = pps_ff[1];		/* 2 1 0 */
1287			v_usec = pps_ff[2] - pps_ff[0];
1288		} else  if (pps_ff[2] < pps_ff[0]) {
1289			u_usec = pps_ff[0];		/* 1 0 2 */
1290			v_usec = pps_ff[1] - pps_ff[2];
1291		} else {
1292			u_usec = pps_ff[2];		/* 1 2 0 */
1293			v_usec = pps_ff[1] - pps_ff[0];
1294		}
1295	}
1296
1297	/*
1298	 * Here the frequency dispersion (stability) is updated. If it
1299	 * is less than one-fourth the maximum (MAXFREQ), the frequency
1300	 * offset is updated as well, but clamped to the tolerance. It
1301	 * will be processed later by the hardclock() routine.
1302	 */
1303	v_usec = (v_usec >> 1) - pps_stabil;
1304	if (v_usec < 0)
1305		pps_stabil -= -v_usec >> PPS_AVG;
1306	else
1307		pps_stabil += v_usec >> PPS_AVG;
1308	if (pps_stabil > MAXFREQ >> 2) {
1309		pps_stbcnt++;
1310		time_status |= STA_PPSWANDER;
1311		return;
1312	}
1313	if (time_status & STA_PPSFREQ) {
1314		if (u_usec < 0) {
1315			pps_freq -= -u_usec >> PPS_AVG;
1316			if (pps_freq < -time_tolerance)
1317				pps_freq = -time_tolerance;
1318			u_usec = -u_usec;
1319		} else {
1320			pps_freq += u_usec >> PPS_AVG;
1321			if (pps_freq > time_tolerance)
1322				pps_freq = time_tolerance;
1323		}
1324	}
1325
1326	/*
1327	 * Here the calibration interval is adjusted. If the maximum
1328	 * time difference is greater than tick / 4, reduce the interval
1329	 * by half. If this is not the case for four consecutive
1330	 * intervals, double the interval.
1331	 */
1332	if (u_usec << pps_shift > bigtick >> 2) {
1333		pps_intcnt = 0;
1334		if (pps_shift > PPS_SHIFT)
1335			pps_shift--;
1336	} else if (pps_intcnt >= 4) {
1337		pps_intcnt = 0;
1338		if (pps_shift < PPS_SHIFTMAX)
1339			pps_shift++;
1340	} else
1341		pps_intcnt++;
1342}
1343#endif /* PPS_SYNC */
1344