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