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