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