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