xref: /freebsd/sys/kern/kern_tc.c (revision a316b26e50bbed7cf655fbba726ab87d8ab7599d)
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.10 1994/10/16 03:52:12 wollman 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 	extern int tickdelta;
419 	extern long timedelta;
420 
421 	/*
422 	 * Update real-time timeout queue.
423 	 * At front of queue are some number of events which are ``due''.
424 	 * The time to these is <= 0 and if negative represents the
425 	 * number of ticks which have passed since it was supposed to happen.
426 	 * The rest of the q elements (times > 0) are events yet to happen,
427 	 * where the time for each is given as a delta from the previous.
428 	 * Decrementing just the first of these serves to decrement the time
429 	 * to all events.
430 	 */
431 	needsoft = 0;
432 	for (p1 = calltodo.c_next; p1 != NULL; p1 = p1->c_next) {
433 		if (--p1->c_time > 0)
434 			break;
435 		needsoft = 1;
436 		if (p1->c_time == 0)
437 			break;
438 	}
439 
440 	p = curproc;
441 	if (p) {
442 		register struct pstats *pstats;
443 
444 		/*
445 		 * Run current process's virtual and profile time, as needed.
446 		 */
447 		pstats = p->p_stats;
448 		if (CLKF_USERMODE(frame) &&
449 		    timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
450 		    itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
451 			psignal(p, SIGVTALRM);
452 		if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
453 		    itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
454 			psignal(p, SIGPROF);
455 	}
456 
457 	/*
458 	 * If no separate statistics clock is available, run it from here.
459 	 */
460 	if (stathz == 0)
461 		statclock(frame);
462 
463 	/*
464 	 * Increment the time-of-day.
465 	 */
466 	ticks++;
467 	{
468 		int time_update;
469 		struct timeval newtime = time;
470 		long ltemp;
471 
472 		if (timedelta == 0) {
473 			time_update = tick;
474 		} else {
475 			time_update = tick + tickdelta;
476 			timedelta -= tickdelta;
477 		}
478 		BUMPTIME(&mono_time, time_update);
479 
480 		/*
481 		 * Compute the phase adjustment. If the low-order bits
482 		 * (time_phase) of the update overflow, bump the high-order bits
483 		 * (time_update).
484 		 */
485 		time_phase += time_adj;
486 		if (time_phase <= -FINEUSEC) {
487 		  ltemp = -time_phase >> SHIFT_SCALE;
488 		  time_phase += ltemp << SHIFT_SCALE;
489 		  time_update -= ltemp;
490 		}
491 		else if (time_phase >= FINEUSEC) {
492 		  ltemp = time_phase >> SHIFT_SCALE;
493 		  time_phase -= ltemp << SHIFT_SCALE;
494 		  time_update += ltemp;
495 		}
496 
497 		newtime.tv_usec += time_update;
498 		/*
499 		 * On rollover of the second the phase adjustment to be used for
500 		 * the next second is calculated. Also, the maximum error is
501 		 * increased by the tolerance. If the PPS frequency discipline
502 		 * code is present, the phase is increased to compensate for the
503 		 * CPU clock oscillator frequency error.
504 		 *
505 		 * With SHIFT_SCALE = 23, the maximum frequency adjustment is
506 		 * +-256 us per tick, or 25.6 ms/s at a clock frequency of 100
507 		 * Hz. The time contribution is shifted right a minimum of two
508 		 * bits, while the frequency contribution is a right shift.
509 		 * Thus, overflow is prevented if the frequency contribution is
510 		 * limited to half the maximum or 15.625 ms/s.
511 		 */
512 		if (newtime.tv_usec >= 1000000) {
513 		  newtime.tv_usec -= 1000000;
514 		  newtime.tv_sec++;
515 		  time_maxerror += time_tolerance >> SHIFT_USEC;
516 		  if (time_offset < 0) {
517 		    ltemp = -time_offset >>
518 		      (SHIFT_KG + time_constant);
519 		    time_offset += ltemp;
520 		    time_adj = -ltemp <<
521 		      (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
522 		  } else {
523 		    ltemp = time_offset >>
524 		      (SHIFT_KG + time_constant);
525 		    time_offset -= ltemp;
526 		    time_adj = ltemp <<
527 		      (SHIFT_SCALE - SHIFT_HZ - SHIFT_UPDATE);
528 		  }
529 #ifdef PPS_SYNC
530 		  /*
531 		   * Gnaw on the watchdog counter and update the frequency
532 		   * computed by the pll and the PPS signal.
533 		   */
534 		  pps_valid++;
535 		  if (pps_valid == PPS_VALID) {
536 		    pps_jitter = MAXTIME;
537 		    pps_stabil = MAXFREQ;
538 		    time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
539 				     STA_PPSWANDER | STA_PPSERROR);
540 		  }
541 		  ltemp = time_freq + pps_freq;
542 #else
543 		  ltemp = time_freq;
544 #endif /* PPS_SYNC */
545 		  if (ltemp < 0)
546 		    time_adj -= -ltemp >>
547 		      (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
548 		  else
549 		    time_adj += ltemp >>
550 		      (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
551 
552 		  /*
553 		   * When the CPU clock oscillator frequency is not a
554 		   * power of two in Hz, the SHIFT_HZ is only an
555 		   * approximate scale factor. In the SunOS kernel, this
556 		   * results in a PLL gain factor of 1/1.28 = 0.78 what it
557 		   * should be. In the following code the overall gain is
558 		   * increased by a factor of 1.25, which results in a
559 		   * residual error less than 3 percent.
560 		   */
561 		  /* Same thing applies for FreeBSD --GAW */
562 		  if (hz == 100) {
563 		    if (time_adj < 0)
564 		      time_adj -= -time_adj >> 2;
565 		    else
566 		      time_adj += time_adj >> 2;
567 		  }
568 
569 		  /* XXX - this is really bogus, but can't be fixed until
570 		     xntpd's idea of the system clock is fixed to know how
571 		     the user wants leap seconds handled; in the mean time,
572 		     we assume that users of NTP are running without proper
573 		     leap second support (this is now the default anyway) */
574 		  /*
575 		   * Leap second processing. If in leap-insert state at
576 		   * the end of the day, the system clock is set back one
577 		   * second; if in leap-delete state, the system clock is
578 		   * set ahead one second. The microtime() routine or
579 		   * external clock driver will insure that reported time
580 		   * is always monotonic. The ugly divides should be
581 		   * replaced.
582 		   */
583 		  switch (time_state) {
584 
585 		  case TIME_OK:
586 		    if (time_status & STA_INS)
587 		      time_state = TIME_INS;
588 		    else if (time_status & STA_DEL)
589 		      time_state = TIME_DEL;
590 		    break;
591 
592 		  case TIME_INS:
593 		    if (newtime.tv_sec % 86400 == 0) {
594 		      newtime.tv_sec--;
595 		      time_state = TIME_OOP;
596 		    }
597 		    break;
598 
599 		  case TIME_DEL:
600 		    if ((newtime.tv_sec + 1) % 86400 == 0) {
601 		      newtime.tv_sec++;
602 		      time_state = TIME_WAIT;
603 		    }
604 		    break;
605 
606 		  case TIME_OOP:
607 		    time_state = TIME_WAIT;
608 		    break;
609 
610 		  case TIME_WAIT:
611 		    if (!(time_status & (STA_INS | STA_DEL)))
612 		      time_state = TIME_OK;
613 		  }
614 		}
615 		CPU_CLOCKUPDATE(&time, &newtime);
616 	}
617 
618 	/*
619 	 * Process callouts at a very low cpu priority, so we don't keep the
620 	 * relatively high clock interrupt priority any longer than necessary.
621 	 */
622 	if (needsoft) {
623 		if (CLKF_BASEPRI(frame)) {
624 			/*
625 			 * Save the overhead of a software interrupt;
626 			 * it will happen as soon as we return, so do it now.
627 			 */
628 			(void)splsoftclock();
629 			softclock();
630 		} else
631 			setsoftclock();
632 	}
633 }
634 
635 /*
636  * Software (low priority) clock interrupt.
637  * Run periodic events from timeout queue.
638  */
639 /*ARGSUSED*/
640 void
641 softclock()
642 {
643 	register struct callout *c;
644 	register void *arg;
645 	register void (*func) __P((void *));
646 	register int s;
647 
648 	s = splhigh();
649 	while ((c = calltodo.c_next) != NULL && c->c_time <= 0) {
650 		func = c->c_func;
651 		arg = c->c_arg;
652 		calltodo.c_next = c->c_next;
653 		c->c_next = callfree;
654 		callfree = c;
655 		splx(s);
656 		(*func)(arg);
657 		(void) splhigh();
658 	}
659 	splx(s);
660 }
661 
662 /*
663  * timeout --
664  *	Execute a function after a specified length of time.
665  *
666  * untimeout --
667  *	Cancel previous timeout function call.
668  *
669  *	See AT&T BCI Driver Reference Manual for specification.  This
670  *	implementation differs from that one in that no identification
671  *	value is returned from timeout, rather, the original arguments
672  *	to timeout are used to identify entries for untimeout.
673  */
674 void
675 timeout(ftn, arg, ticks)
676 	timeout_t ftn;
677 	void *arg;
678 	register int ticks;
679 {
680 	register struct callout *new, *p, *t;
681 	register int s;
682 
683 	if (ticks <= 0)
684 		ticks = 1;
685 
686 	/* Lock out the clock. */
687 	s = splhigh();
688 
689 	/* Fill in the next free callout structure. */
690 	if (callfree == NULL)
691 		panic("timeout table full");
692 	new = callfree;
693 	callfree = new->c_next;
694 	new->c_arg = arg;
695 	new->c_func = ftn;
696 
697 	/*
698 	 * The time for each event is stored as a difference from the time
699 	 * of the previous event on the queue.  Walk the queue, correcting
700 	 * the ticks argument for queue entries passed.  Correct the ticks
701 	 * value for the queue entry immediately after the insertion point
702 	 * as well.  Watch out for negative c_time values; these represent
703 	 * overdue events.
704 	 */
705 	for (p = &calltodo;
706 	    (t = p->c_next) != NULL && ticks > t->c_time; p = t)
707 		if (t->c_time > 0)
708 			ticks -= t->c_time;
709 	new->c_time = ticks;
710 	if (t != NULL)
711 		t->c_time -= ticks;
712 
713 	/* Insert the new entry into the queue. */
714 	p->c_next = new;
715 	new->c_next = t;
716 	splx(s);
717 }
718 
719 void
720 untimeout(ftn, arg)
721 	timeout_t ftn;
722 	void *arg;
723 {
724 	register struct callout *p, *t;
725 	register int s;
726 
727 	s = splhigh();
728 	for (p = &calltodo; (t = p->c_next) != NULL; p = t)
729 		if (t->c_func == ftn && t->c_arg == arg) {
730 			/* Increment next entry's tick count. */
731 			if (t->c_next && t->c_time > 0)
732 				t->c_next->c_time += t->c_time;
733 
734 			/* Move entry from callout queue to callfree queue. */
735 			p->c_next = t->c_next;
736 			t->c_next = callfree;
737 			callfree = t;
738 			break;
739 		}
740 	splx(s);
741 }
742 
743 /*
744  * Compute number of hz until specified time.  Used to
745  * compute third argument to timeout() from an absolute time.
746  */
747 int
748 hzto(tv)
749 	struct timeval *tv;
750 {
751 	register unsigned long ticks;
752 	register long sec, usec;
753 	int s;
754 
755 	/*
756 	 * If the number of usecs in the whole seconds part of the time
757 	 * difference fits in a long, then the total number of usecs will
758 	 * fit in an unsigned long.  Compute the total and convert it to
759 	 * ticks, rounding up and adding 1 to allow for the current tick
760 	 * to expire.  Rounding also depends on unsigned long arithmetic
761 	 * to avoid overflow.
762 	 *
763 	 * Otherwise, if the number of ticks in the whole seconds part of
764 	 * the time difference fits in a long, then convert the parts to
765 	 * ticks separately and add, using similar rounding methods and
766 	 * overflow avoidance.  This method would work in the previous
767 	 * case but it is slightly slower and assumes that hz is integral.
768 	 *
769 	 * Otherwise, round the time difference down to the maximum
770 	 * representable value.
771 	 *
772 	 * If ints have 32 bits, then the maximum value for any timeout in
773 	 * 10ms ticks is 248 days.
774 	 */
775 	s = splclock();
776 	sec = tv->tv_sec - time.tv_sec;
777 	usec = tv->tv_usec - time.tv_usec;
778 	splx(s);
779 	if (usec < 0) {
780 		sec--;
781 		usec += 1000000;
782 	}
783 	if (sec < 0) {
784 #ifdef DIAGNOSTIC
785 		printf("hzto: negative time difference %ld sec %ld usec\n",
786 		       sec, usec);
787 #endif
788 		ticks = 1;
789 	} else if (sec <= LONG_MAX / 1000000)
790 		ticks = (sec * 1000000 + (unsigned long)usec + (tick - 1))
791 			/ tick + 1;
792 	else if (sec <= LONG_MAX / hz)
793 		ticks = sec * hz
794 			+ ((unsigned long)usec + (tick - 1)) / tick + 1;
795 	else
796 		ticks = LONG_MAX;
797 	if (ticks > INT_MAX)
798 		ticks = INT_MAX;
799 	return (ticks);
800 }
801 
802 /*
803  * Start profiling on a process.
804  *
805  * Kernel profiling passes proc0 which never exits and hence
806  * keeps the profile clock running constantly.
807  */
808 void
809 startprofclock(p)
810 	register struct proc *p;
811 {
812 	int s;
813 
814 	if ((p->p_flag & P_PROFIL) == 0) {
815 		p->p_flag |= P_PROFIL;
816 		if (++profprocs == 1 && stathz != 0) {
817 			s = splstatclock();
818 			psdiv = pscnt = psratio;
819 			setstatclockrate(profhz);
820 			splx(s);
821 		}
822 	}
823 }
824 
825 /*
826  * Stop profiling on a process.
827  */
828 void
829 stopprofclock(p)
830 	register struct proc *p;
831 {
832 	int s;
833 
834 	if (p->p_flag & P_PROFIL) {
835 		p->p_flag &= ~P_PROFIL;
836 		if (--profprocs == 0 && stathz != 0) {
837 			s = splstatclock();
838 			psdiv = pscnt = 1;
839 			setstatclockrate(stathz);
840 			splx(s);
841 		}
842 	}
843 }
844 
845 /*
846  * Statistics clock.  Grab profile sample, and if divider reaches 0,
847  * do process and kernel statistics.
848  */
849 void
850 statclock(frame)
851 	register struct clockframe *frame;
852 {
853 #ifdef GPROF
854 	register struct gmonparam *g;
855 #endif
856 	register struct proc *p = curproc;
857 	register int i;
858 
859 	if (p) {
860 		struct pstats *pstats;
861 		struct rusage *ru;
862 		struct vmspace *vm;
863 
864 		/* bump the resource usage of integral space use */
865 		if ((pstats = p->p_stats) && (ru = &pstats->p_ru) && (vm = p->p_vmspace)) {
866 			ru->ru_ixrss += vm->vm_tsize * PAGE_SIZE / 1024;
867 			ru->ru_idrss += vm->vm_dsize * PAGE_SIZE / 1024;
868 			ru->ru_isrss += vm->vm_ssize * PAGE_SIZE / 1024;
869 			if ((vm->vm_pmap.pm_stats.resident_count * PAGE_SIZE / 1024) >
870 			    ru->ru_maxrss) {
871 				ru->ru_maxrss =
872 				    vm->vm_pmap.pm_stats.resident_count * PAGE_SIZE / 1024;
873 			}
874         	}
875 	}
876 
877 	if (CLKF_USERMODE(frame)) {
878 		if (p->p_flag & P_PROFIL)
879 			addupc_intr(p, CLKF_PC(frame), 1);
880 		if (--pscnt > 0)
881 			return;
882 		/*
883 		 * Came from user mode; CPU was in user state.
884 		 * If this process is being profiled record the tick.
885 		 */
886 		p->p_uticks++;
887 		if (p->p_nice > NZERO)
888 			cp_time[CP_NICE]++;
889 		else
890 			cp_time[CP_USER]++;
891 	} else {
892 #ifdef GPROF
893 		/*
894 		 * Kernel statistics are just like addupc_intr, only easier.
895 		 */
896 		g = &_gmonparam;
897 		if (g->state == GMON_PROF_ON) {
898 			i = CLKF_PC(frame) - g->lowpc;
899 			if (i < g->textsize) {
900 				i /= HISTFRACTION * sizeof(*g->kcount);
901 				g->kcount[i]++;
902 			}
903 		}
904 #endif
905 		if (--pscnt > 0)
906 			return;
907 		/*
908 		 * Came from kernel mode, so we were:
909 		 * - handling an interrupt,
910 		 * - doing syscall or trap work on behalf of the current
911 		 *   user process, or
912 		 * - spinning in the idle loop.
913 		 * Whichever it is, charge the time as appropriate.
914 		 * Note that we charge interrupts to the current process,
915 		 * regardless of whether they are ``for'' that process,
916 		 * so that we know how much of its real time was spent
917 		 * in ``non-process'' (i.e., interrupt) work.
918 		 */
919 		if (CLKF_INTR(frame)) {
920 			if (p != NULL)
921 				p->p_iticks++;
922 			cp_time[CP_INTR]++;
923 		} else if (p != NULL) {
924 			p->p_sticks++;
925 			cp_time[CP_SYS]++;
926 		} else
927 			cp_time[CP_IDLE]++;
928 	}
929 	pscnt = psdiv;
930 
931 	/*
932 	 * We maintain statistics shown by user-level statistics
933 	 * programs:  the amount of time in each cpu state, and
934 	 * the amount of time each of DK_NDRIVE ``drives'' is busy.
935 	 *
936 	 * XXX	should either run linked list of drives, or (better)
937 	 *	grab timestamps in the start & done code.
938 	 */
939 	for (i = 0; i < DK_NDRIVE; i++)
940 		if (dk_busy & (1 << i))
941 			dk_time[i]++;
942 
943 	/*
944 	 * We adjust the priority of the current process.  The priority of
945 	 * a process gets worse as it accumulates CPU time.  The cpu usage
946 	 * estimator (p_estcpu) is increased here.  The formula for computing
947 	 * priorities (in kern_synch.c) will compute a different value each
948 	 * time p_estcpu increases by 4.  The cpu usage estimator ramps up
949 	 * quite quickly when the process is running (linearly), and decays
950 	 * away exponentially, at a rate which is proportionally slower when
951 	 * the system is busy.  The basic principal is that the system will
952 	 * 90% forget that the process used a lot of CPU time in 5 * loadav
953 	 * seconds.  This causes the system to favor processes which haven't
954 	 * run much recently, and to round-robin among other processes.
955 	 */
956 	if (p != NULL) {
957 		p->p_cpticks++;
958 		if (++p->p_estcpu == 0)
959 			p->p_estcpu--;
960 		if ((p->p_estcpu & 3) == 0) {
961 			resetpriority(p);
962 			if (p->p_priority >= PUSER)
963 				p->p_priority = p->p_usrpri;
964 		}
965 	}
966 }
967 
968 /*
969  * Return information about system clocks.
970  */
971 int
972 sysctl_clockrate(where, sizep)
973 	register char *where;
974 	size_t *sizep;
975 {
976 	struct clockinfo clkinfo;
977 
978 	/*
979 	 * Construct clockinfo structure.
980 	 */
981 	clkinfo.hz = hz;
982 	clkinfo.tick = tick;
983 	clkinfo.profhz = profhz;
984 	clkinfo.stathz = stathz ? stathz : hz;
985 	return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
986 }
987 
988 /*#ifdef PPS_SYNC*/
989 #if 0
990 /* This code is completely bogus; if anybody ever wants to use it, get
991  * the current version from Dave Mills. */
992 
993 /*
994  * hardpps() - discipline CPU clock oscillator to external pps signal
995  *
996  * This routine is called at each PPS interrupt in order to discipline
997  * the CPU clock oscillator to the PPS signal. It integrates successive
998  * phase differences between the two oscillators and calculates the
999  * frequency offset. This is used in hardclock() to discipline the CPU
1000  * clock oscillator so that intrinsic frequency error is cancelled out.
1001  * The code requires the caller to capture the time and hardware
1002  * counter value at the designated PPS signal transition.
1003  */
1004 void
1005 hardpps(tvp, usec)
1006 	struct timeval *tvp;		/* time at PPS */
1007 	long usec;			/* hardware counter at PPS */
1008 {
1009 	long u_usec, v_usec, bigtick;
1010 	long cal_sec, cal_usec;
1011 
1012 	/*
1013 	 * During the calibration interval adjust the starting time when
1014 	 * the tick overflows. At the end of the interval compute the
1015 	 * duration of the interval and the difference of the hardware
1016 	 * counters at the beginning and end of the interval. This code
1017 	 * is deliciously complicated by the fact valid differences may
1018 	 * exceed the value of tick when using long calibration
1019 	 * intervals and small ticks. Note that the counter can be
1020 	 * greater than tick if caught at just the wrong instant, but
1021 	 * the values returned and used here are correct.
1022 	 */
1023 	bigtick = (long)tick << SHIFT_USEC;
1024 	pps_usec -= ntp_pll.ybar;
1025 	if (pps_usec >= bigtick)
1026 		pps_usec -= bigtick;
1027 	if (pps_usec < 0)
1028 		pps_usec += bigtick;
1029 	pps_time.tv_sec++;
1030 	pps_count++;
1031 	if (pps_count < (1 << pps_shift))
1032 		return;
1033 	pps_count = 0;
1034 	ntp_pll.calcnt++;
1035 	u_usec = usec << SHIFT_USEC;
1036 	v_usec = pps_usec - u_usec;
1037 	if (v_usec >= bigtick >> 1)
1038 		v_usec -= bigtick;
1039 	if (v_usec < -(bigtick >> 1))
1040 		v_usec += bigtick;
1041 	if (v_usec < 0)
1042 		v_usec = -(-v_usec >> ntp_pll.shift);
1043 	else
1044 		v_usec = v_usec >> ntp_pll.shift;
1045 	pps_usec = u_usec;
1046 	cal_sec = tvp->tv_sec;
1047 	cal_usec = tvp->tv_usec;
1048 	cal_sec -= pps_time.tv_sec;
1049 	cal_usec -= pps_time.tv_usec;
1050 	if (cal_usec < 0) {
1051 		cal_usec += 1000000;
1052 		cal_sec--;
1053 	}
1054 	pps_time = *tvp;
1055 
1056 	/*
1057 	 * Check for lost interrupts, noise, excessive jitter and
1058 	 * excessive frequency error. The number of timer ticks during
1059 	 * the interval may vary +-1 tick. Add to this a margin of one
1060 	 * tick for the PPS signal jitter and maximum frequency
1061 	 * deviation. If the limits are exceeded, the calibration
1062 	 * interval is reset to the minimum and we start over.
1063 	 */
1064 	u_usec = (long)tick << 1;
1065 	if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
1066 	    || (cal_sec == 0 && cal_usec < u_usec))
1067 	    || v_usec > ntp_pll.tolerance || v_usec < -ntp_pll.tolerance) {
1068 		ntp_pll.jitcnt++;
1069 		ntp_pll.shift = NTP_PLL.SHIFT;
1070 		pps_dispinc = PPS_DISPINC;
1071 		ntp_pll.intcnt = 0;
1072 		return;
1073 	}
1074 
1075 	/*
1076 	 * A three-stage median filter is used to help deglitch the pps
1077 	 * signal. The median sample becomes the offset estimate; the
1078 	 * difference between the other two samples becomes the
1079 	 * dispersion estimate.
1080 	 */
1081 	pps_mf[2] = pps_mf[1];
1082 	pps_mf[1] = pps_mf[0];
1083 	pps_mf[0] = v_usec;
1084 	if (pps_mf[0] > pps_mf[1]) {
1085 		if (pps_mf[1] > pps_mf[2]) {
1086 			u_usec = pps_mf[1];		/* 0 1 2 */
1087 			v_usec = pps_mf[0] - pps_mf[2];
1088 		} else if (pps_mf[2] > pps_mf[0]) {
1089 			u_usec = pps_mf[0];		/* 2 0 1 */
1090 			v_usec = pps_mf[2] - pps_mf[1];
1091 		} else {
1092 			u_usec = pps_mf[2];		/* 0 2 1 */
1093 			v_usec = pps_mf[0] - pps_mf[1];
1094 		}
1095 	} else {
1096 		if (pps_mf[1] < pps_mf[2]) {
1097 			u_usec = pps_mf[1];		/* 2 1 0 */
1098 			v_usec = pps_mf[2] - pps_mf[0];
1099 		} else  if (pps_mf[2] < pps_mf[0]) {
1100 			u_usec = pps_mf[0];		/* 1 0 2 */
1101 			v_usec = pps_mf[1] - pps_mf[2];
1102 		} else {
1103 			u_usec = pps_mf[2];		/* 1 2 0 */
1104 			v_usec = pps_mf[1] - pps_mf[0];
1105 		}
1106 	}
1107 
1108 	/*
1109 	 * Here the dispersion average is updated. If it is less than
1110 	 * the threshold pps_dispmax, the frequency average is updated
1111 	 * as well, but clamped to the tolerance.
1112 	 */
1113 	v_usec = (v_usec >> 1) - ntp_pll.disp;
1114 	if (v_usec < 0)
1115 		ntp_pll.disp -= -v_usec >> PPS_AVG;
1116 	else
1117 		ntp_pll.disp += v_usec >> PPS_AVG;
1118 	if (ntp_pll.disp > pps_dispmax) {
1119 		ntp_pll.discnt++;
1120 		return;
1121 	}
1122 	if (u_usec < 0) {
1123 		ntp_pll.ybar -= -u_usec >> PPS_AVG;
1124 		if (ntp_pll.ybar < -ntp_pll.tolerance)
1125 			ntp_pll.ybar = -ntp_pll.tolerance;
1126 		u_usec = -u_usec;
1127 	} else {
1128 		ntp_pll.ybar += u_usec >> PPS_AVG;
1129 		if (ntp_pll.ybar > ntp_pll.tolerance)
1130 			ntp_pll.ybar = ntp_pll.tolerance;
1131 	}
1132 
1133 	/*
1134 	 * Here the calibration interval is adjusted. If the maximum
1135 	 * time difference is greater than tick/4, reduce the interval
1136 	 * by half. If this is not the case for four consecutive
1137 	 * intervals, double the interval.
1138 	 */
1139 	if (u_usec << ntp_pll.shift > bigtick >> 2) {
1140 		ntp_pll.intcnt = 0;
1141 		if (ntp_pll.shift > NTP_PLL.SHIFT) {
1142 			ntp_pll.shift--;
1143 			pps_dispinc <<= 1;
1144 		}
1145 	} else if (ntp_pll.intcnt >= 4) {
1146 		ntp_pll.intcnt = 0;
1147 		if (ntp_pll.shift < NTP_PLL.SHIFTMAX) {
1148 			ntp_pll.shift++;
1149 			pps_dispinc >>= 1;
1150 		}
1151 	} else
1152 		ntp_pll.intcnt++;
1153 }
1154 #endif /* PPS_SYNC */
1155