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