kern_clock.c revision 1.27 1 /* $NetBSD: kern_clock.c,v 1.27 1996/02/27 04:20:37 jonathan Exp $ */
2
3 /*-
4 * Copyright (c) 1982, 1986, 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 * (c) UNIX System Laboratories, Inc.
7 * All or some portions of this file are derived from material licensed
8 * to the University of California by American Telephone and Telegraph
9 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10 * the permission of UNIX System Laboratories, Inc.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. All advertising materials mentioning features or use of this software
21 * must display the following acknowledgement:
22 * This product includes software developed by the University of
23 * California, Berkeley and its contributors.
24 * 4. Neither the name of the University nor the names of its contributors
25 * may be used to endorse or promote products derived from this software
26 * without specific prior written permission.
27 *
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38 * SUCH DAMAGE.
39 *
40 * @(#)kern_clock.c 8.5 (Berkeley) 1/21/94
41 */
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/dkstat.h>
46 #include <sys/callout.h>
47 #include <sys/kernel.h>
48 #include <sys/proc.h>
49 #include <sys/resourcevar.h>
50 #include <sys/signalvar.h>
51 #include <sys/cpu.h>
52 #include <vm/vm.h>
53 #include <sys/sysctl.h>
54 #include <sys/timex.h>
55
56 #include <machine/cpu.h>
57
58 #ifdef GPROF
59 #include <sys/gmon.h>
60 #endif
61
62 /*
63 * Clock handling routines.
64 *
65 * This code is written to operate with two timers that run independently of
66 * each other. The main clock, running hz times per second, is used to keep
67 * track of real time. The second timer handles kernel and user profiling,
68 * and does resource use estimation. If the second timer is programmable,
69 * it is randomized to avoid aliasing between the two clocks. For example,
70 * the randomization prevents an adversary from always giving up the cpu
71 * just before its quantum expires. Otherwise, it would never accumulate
72 * cpu ticks. The mean frequency of the second timer is stathz.
73 *
74 * If no second timer exists, stathz will be zero; in this case we drive
75 * profiling and statistics off the main clock. This WILL NOT be accurate;
76 * do not do it unless absolutely necessary.
77 *
78 * The statistics clock may (or may not) be run at a higher rate while
79 * profiling. This profile clock runs at profhz. We require that profhz
80 * be an integral multiple of stathz.
81 *
82 * If the statistics clock is running fast, it must be divided by the ratio
83 * profhz/stathz for statistics. (For profiling, every tick counts.)
84 */
85
86 /*
87 * TODO:
88 * allocate more timeout table slots when table overflows.
89 */
90
91
92 #ifdef NTP /* NTP phase-locked loop in kernel */
93 /*
94 * Phase/frequency-lock loop (PLL/FLL) definitions
95 *
96 * The following variables are read and set by the ntp_adjtime() system
97 * call.
98 *
99 * time_state shows the state of the system clock, with values defined
100 * in the timex.h header file.
101 *
102 * time_status shows the status of the system clock, with bits defined
103 * in the timex.h header file.
104 *
105 * time_offset is used by the PLL/FLL to adjust the system time in small
106 * increments.
107 *
108 * time_constant determines the bandwidth or "stiffness" of the PLL.
109 *
110 * time_tolerance determines maximum frequency error or tolerance of the
111 * CPU clock oscillator and is a property of the architecture; however,
112 * in principle it could change as result of the presence of external
113 * discipline signals, for instance.
114 *
115 * time_precision is usually equal to the kernel tick variable; however,
116 * in cases where a precision clock counter or external clock is
117 * available, the resolution can be much less than this and depend on
118 * whether the external clock is working or not.
119 *
120 * time_maxerror is initialized by a ntp_adjtime() call and increased by
121 * the kernel once each second to reflect the maximum error bound
122 * growth.
123 *
124 * time_esterror is set and read by the ntp_adjtime() call, but
125 * otherwise not used by the kernel.
126 */
127 int time_state = TIME_OK; /* clock state */
128 int time_status = STA_UNSYNC; /* clock status bits */
129 long time_offset = 0; /* time offset (us) */
130 long time_constant = 0; /* pll time constant */
131 long time_tolerance = MAXFREQ; /* frequency tolerance (scaled ppm) */
132 long time_precision = 1; /* clock precision (us) */
133 long time_maxerror = MAXPHASE; /* maximum error (us) */
134 long time_esterror = MAXPHASE; /* estimated error (us) */
135
136 /*
137 * The following variables establish the state of the PLL/FLL and the
138 * residual time and frequency offset of the local clock. The scale
139 * factors are defined in the timex.h header file.
140 *
141 * time_phase and time_freq are the phase increment and the frequency
142 * increment, respectively, of the kernel time variable.
143 *
144 * time_freq is set via ntp_adjtime() from a value stored in a file when
145 * the synchronization daemon is first started. Its value is retrieved
146 * via ntp_adjtime() and written to the file about once per hour by the
147 * daemon.
148 *
149 * time_adj is the adjustment added to the value of tick at each timer
150 * interrupt and is recomputed from time_phase and time_freq at each
151 * seconds rollover.
152 *
153 * time_reftime is the second's portion of the system time at the last
154 * call to ntp_adjtime(). It is used to adjust the time_freq variable
155 * and to increase the time_maxerror as the time since last update
156 * increases.
157 */
158 long time_phase = 0; /* phase offset (scaled us) */
159 long time_freq = 0; /* frequency offset (scaled ppm) */
160 long time_adj = 0; /* tick adjust (scaled 1 / hz) */
161 long time_reftime = 0; /* time at last adjustment (s) */
162
163 #ifdef PPS_SYNC
164 /*
165 * The following variables are used only if the kernel PPS discipline
166 * code is configured (PPS_SYNC). The scale factors are defined in the
167 * timex.h header file.
168 *
169 * pps_time contains the time at each calibration interval, as read by
170 * microtime(). pps_count counts the seconds of the calibration
171 * interval, the duration of which is nominally pps_shift in powers of
172 * two.
173 *
174 * pps_offset is the time offset produced by the time median filter
175 * pps_tf[], while pps_jitter is the dispersion (jitter) measured by
176 * this filter.
177 *
178 * pps_freq is the frequency offset produced by the frequency median
179 * filter pps_ff[], while pps_stabil is the dispersion (wander) measured
180 * by this filter.
181 *
182 * pps_usec is latched from a high resolution counter or external clock
183 * at pps_time. Here we want the hardware counter contents only, not the
184 * contents plus the time_tv.usec as usual.
185 *
186 * pps_valid counts the number of seconds since the last PPS update. It
187 * is used as a watchdog timer to disable the PPS discipline should the
188 * PPS signal be lost.
189 *
190 * pps_glitch counts the number of seconds since the beginning of an
191 * offset burst more than tick/2 from current nominal offset. It is used
192 * mainly to suppress error bursts due to priority conflicts between the
193 * PPS interrupt and timer interrupt.
194 *
195 * pps_intcnt counts the calibration intervals for use in the interval-
196 * adaptation algorithm. It's just too complicated for words.
197 */
198 struct timeval pps_time; /* kernel time at last interval */
199 long pps_tf[] = {0, 0, 0}; /* pps time offset median filter (us) */
200 long pps_offset = 0; /* pps time offset (us) */
201 long pps_jitter = MAXTIME; /* time dispersion (jitter) (us) */
202 long pps_ff[] = {0, 0, 0}; /* pps frequency offset median filter */
203 long pps_freq = 0; /* frequency offset (scaled ppm) */
204 long pps_stabil = MAXFREQ; /* frequency dispersion (scaled ppm) */
205 long pps_usec = 0; /* microsec counter at last interval */
206 long pps_valid = PPS_VALID; /* pps signal watchdog counter */
207 int pps_glitch = 0; /* pps signal glitch counter */
208 int pps_count = 0; /* calibration interval counter (s) */
209 int pps_shift = PPS_SHIFT; /* interval duration (s) (shift) */
210 int pps_intcnt = 0; /* intervals at current duration */
211
212 /*
213 * PPS signal quality monitors
214 *
215 * pps_jitcnt counts the seconds that have been discarded because the
216 * jitter measured by the time median filter exceeds the limit MAXTIME
217 * (100 us).
218 *
219 * pps_calcnt counts the frequency calibration intervals, which are
220 * variable from 4 s to 256 s.
221 *
222 * pps_errcnt counts the calibration intervals which have been discarded
223 * because the wander exceeds the limit MAXFREQ (100 ppm) or where the
224 * calibration interval jitter exceeds two ticks.
225 *
226 * pps_stbcnt counts the calibration intervals that have been discarded
227 * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us).
228 */
229 long pps_jitcnt = 0; /* jitter limit exceeded */
230 long pps_calcnt = 0; /* calibration intervals */
231 long pps_errcnt = 0; /* calibration errors */
232 long pps_stbcnt = 0; /* stability limit exceeded */
233 #endif /* PPS_SYNC */
234
235 #ifdef EXT_CLOCK
236 /*
237 * External clock definitions
238 *
239 * The following definitions and declarations are used only if an
240 * external clock is configured on the system.
241 */
242 #define CLOCK_INTERVAL 30 /* CPU clock update interval (s) */
243
244 /*
245 * The clock_count variable is set to CLOCK_INTERVAL at each PPS
246 * interrupt and decremented once each second.
247 */
248 int clock_count = 0; /* CPU clock counter */
249
250 #ifdef HIGHBALL
251 /*
252 * The clock_offset and clock_cpu variables are used by the HIGHBALL
253 * interface. The clock_offset variable defines the offset between
254 * system time and the HIGBALL counters. The clock_cpu variable contains
255 * the offset between the system clock and the HIGHBALL clock for use in
256 * disciplining the kernel time variable.
257 */
258 extern struct timeval clock_offset; /* Highball clock offset */
259 long clock_cpu = 0; /* CPU clock adjust */
260 #endif /* HIGHBALL */
261 #endif /* EXT_CLOCK */
262
263 /*
264 * NetBSD notes:
265 *
266 * SHIFT_HZ is strongly recommended to be a constant, not a variable,
267 * for performance reasons, so we define it appropriately here.
268 * Ataris uses 48, or 96 Hz (as well as 64). Sparcs and Sun-3s use
269 * 100Hz. Non-power-of-two values for HZ are rounded up when
270 * we define SHIFT_HZ, and then special-cased in the kernel
271 * timekeeping code in kern_clock.c.
272 * Alphas use 1024. Decstations use 256, which covers all the powers
273 * of 2 from 64 to 1024, inclusive.
274 */
275 #if HZ == 64 || HZ == 60 /* Precision timekeeping does not support 48 Hz */
276 # define SHIFT_HZ 6 /* log2(hz) */
277 #if HZ == 128 || HZ == 100 HZ == 96
278 # define SHIFT_HZ 7 /* log2(hz) */
279 #else
280 #if HZ == 256 /* || !defined(HZ)*/
281 # define SHIFT_HZ 8 /* log2(hz) (default) */
282 #else
283 #if HZ == 1024
284 # define SHIFT_HZ 10
285 #else
286 #error HZ is not a supported value. Please change HZ in your kernel config file
287 #endif /* 1024Hz */
288 #endif /* 256Hz */
289 #endif /* 128HZ or 100Hz or 96Hz*/
290 #endif /* 64Hz or 60Hz or 48Hz*/
291 /*
292 * End of SHIFT_HZ computation
293 */
294
295 #endif /* NTP */
296
297
298 /*
299 * Bump a timeval by a small number of usec's.
300 */
301 #define BUMPTIME(t, usec) { \
302 register volatile struct timeval *tp = (t); \
303 register long us; \
304 \
305 tp->tv_usec = us = tp->tv_usec + (usec); \
306 if (us >= 1000000) { \
307 tp->tv_usec = us - 1000000; \
308 tp->tv_sec++; \
309 } \
310 }
311
312 int stathz;
313 int profhz;
314 int profprocs;
315 int ticks;
316 static int psdiv, pscnt; /* prof => stat divider */
317 int psratio; /* ratio: prof / stat */
318 int tickfix, tickfixinterval; /* used if tick not really integral */
319 static int tickfixcnt; /* number of ticks since last fix */
320 int fixtick; /* used by NTP for same */
321
322 volatile struct timeval time;
323 volatile struct timeval mono_time;
324
325 /*
326 * Initialize clock frequencies and start both clocks running.
327 */
328 void
329 initclocks()
330 {
331 register int i;
332
333 /*
334 * Set divisors to 1 (normal case) and let the machine-specific
335 * code do its bit.
336 */
337 psdiv = pscnt = 1;
338 cpu_initclocks();
339
340 /*
341 * Compute profhz/stathz, and fix profhz if needed.
342 */
343 i = stathz ? stathz : hz;
344 if (profhz == 0)
345 profhz = i;
346 psratio = profhz / i;
347 }
348
349 /*
350 * The real-time timer, interrupting hz times per second.
351 */
352 void
353 hardclock(frame)
354 register struct clockframe *frame;
355 {
356 register struct callout *p1;
357 register struct proc *p;
358 register int delta, needsoft;
359 extern int tickdelta;
360 extern long timedelta;
361 register int time_update, ltemp;
362
363 /*
364 * Update real-time timeout queue.
365 * At front of queue are some number of events which are ``due''.
366 * The time to these is <= 0 and if negative represents the
367 * number of ticks which have passed since it was supposed to happen.
368 * The rest of the q elements (times > 0) are events yet to happen,
369 * where the time for each is given as a delta from the previous.
370 * Decrementing just the first of these serves to decrement the time
371 * to all events.
372 */
373 needsoft = 0;
374 for (p1 = calltodo.c_next; p1 != NULL; p1 = p1->c_next) {
375 if (--p1->c_time > 0)
376 break;
377 needsoft = 1;
378 if (p1->c_time == 0)
379 break;
380 }
381
382 p = curproc;
383 if (p) {
384 register struct pstats *pstats;
385
386 /*
387 * Run current process's virtual and profile time, as needed.
388 */
389 pstats = p->p_stats;
390 if (CLKF_USERMODE(frame) &&
391 timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
392 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
393 psignal(p, SIGVTALRM);
394 if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
395 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
396 psignal(p, SIGPROF);
397 }
398
399 /*
400 * If no separate statistics clock is available, run it from here.
401 */
402 if (stathz == 0)
403 statclock(frame);
404
405 /*
406 * Increment the time-of-day. The increment is normally just
407 * ``tick''. If the machine is one which has a clock frequency
408 * such that ``hz'' would not divide the second evenly into
409 * milliseconds, a periodic adjustment must be applied. Finally,
410 * if we are still adjusting the time (see adjtime()),
411 * ``tickdelta'' may also be added in.
412 */
413 ticks++;
414 delta = tick;
415
416 #ifndef NTP
417 if (tickfix) {
418 tickfixcnt++;
419 if (tickfixcnt >= tickfixinterval) {
420 delta += tickfix;
421 tickfixcnt = 0;
422 }
423 }
424 #endif /* !NTP */
425 /* Imprecise 4bsd adjtime() handling */
426 if (timedelta != 0) {
427 delta = tick + tickdelta;
428 timedelta -= tickdelta;
429 }
430
431 #ifdef notyet
432 microset();
433 #endif
434
435 #ifndef NTP
436 BUMPTIME(&time, delta); /* XXX Now done using NTP code below */
437 #endif
438 BUMPTIME(&mono_time, delta);
439 time_update = delta;
440
441 #ifdef NTP /* XXX Start of David L. Mills' ntp precision-time fragment */
442
443 /*
444 * Beginning of precision-kernel code fragment
445 *
446 * Compute the phase adjustment. If the low-order bits
447 * (time_phase) of the update overflow, bump the high-order bits
448 * (time_update).
449 */
450 time_phase += time_adj;
451 if (time_phase <= -FINEUSEC) {
452 ltemp = -time_phase >> SHIFT_SCALE;
453 time_phase += ltemp << SHIFT_SCALE;
454 time_update -= ltemp;
455 }
456 else if (time_phase >= FINEUSEC) {
457 ltemp = time_phase >> SHIFT_SCALE;
458 time_phase -= ltemp << SHIFT_SCALE;
459 time_update += ltemp;
460 }
461
462 #ifdef HIGHBALL
463 /*
464 * If the HIGHBALL board is installed, we need to adjust the
465 * external clock offset in order to close the hardware feedback
466 * loop. This will adjust the external clock phase and frequency
467 * in small amounts. The additional phase noise and frequency
468 * wander this causes should be minimal. We also need to
469 * discipline the kernel time variable, since the PLL is used to
470 * discipline the external clock. If the Highball board is not
471 * present, we discipline kernel time with the PLL as usual. We
472 * assume that the external clock phase adjustment (time_update)
473 * and kernel phase adjustment (clock_cpu) are less than the
474 * value of tick.
475 */
476 clock_offset.tv_usec += time_update;
477 if (clock_offset.tv_usec >= 1000000) {
478 clock_offset.tv_sec++;
479 clock_offset.tv_usec -= 1000000;
480 }
481 if (clock_offset.tv_usec < 0) {
482 clock_offset.tv_sec--;
483 clock_offset.tv_usec += 1000000;
484 }
485 time.tv_usec += clock_cpu;
486 clock_cpu = 0;
487 #else
488 time.tv_usec += time_update;
489 #endif /* HIGHBALL */
490
491 /*
492 * End of precision-kernel code fragment
493 */
494
495 /*
496 * Beginning of precision-kernel code fragment
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 * On a 32-bit machine and given parameters in the timex.h
505 * header file, the maximum phase adjustment is +-512 ms and
506 * maximum frequency offset is a tad less than) +-512 ppm. On a
507 * 64-bit machine, you shouldn't need to ask.
508 */
509 if (time.tv_usec >= 1000000) {
510 time.tv_usec -= 1000000;
511 time.tv_sec++;
512 time_maxerror += time_tolerance >> SHIFT_USEC;
513
514 /*
515 * Leap second processing. If in leap-insert state at
516 * the end of the day, the system clock is set back one
517 * second; if in leap-delete state, the system clock is
518 * set ahead one second. The microtime() routine or
519 * external clock driver will insure that reported time
520 * is always monotonic. The ugly divides should be
521 * replaced.
522 */
523 switch (time_state) {
524
525 case TIME_OK:
526 if (time_status & STA_INS)
527 time_state = TIME_INS;
528 else if (time_status & STA_DEL)
529 time_state = TIME_DEL;
530 break;
531
532 case TIME_INS:
533 if (time.tv_sec % 86400 == 0) {
534 time.tv_sec--;
535 time_state = TIME_OOP;
536 }
537 break;
538
539 case TIME_DEL:
540 if ((time.tv_sec + 1) % 86400 == 0) {
541 time.tv_sec++;
542 time_state = TIME_WAIT;
543 }
544 break;
545
546 case TIME_OOP:
547 time_state = TIME_WAIT;
548 break;
549
550 case TIME_WAIT:
551 if (!(time_status & (STA_INS | STA_DEL)))
552 time_state = TIME_OK;
553 }
554
555 /*
556 * Compute the phase adjustment for the next second. In
557 * PLL mode, the offset is reduced by a fixed factor
558 * times the time constant. In FLL mode the offset is
559 * used directly. In either mode, the maximum phase
560 * adjustment for each second is clamped so as to spread
561 * the adjustment over not more than the number of
562 * seconds between updates.
563 */
564 if (time_offset < 0) {
565 ltemp = -time_offset;
566 if (!(time_status & STA_FLL))
567 ltemp >>= SHIFT_KG + time_constant;
568 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
569 ltemp = (MAXPHASE / MINSEC) <<
570 SHIFT_UPDATE;
571 time_offset += ltemp;
572 time_adj = -ltemp << (SHIFT_SCALE - SHIFT_HZ -
573 SHIFT_UPDATE);
574 } else {
575 ltemp = time_offset;
576 if (!(time_status & STA_FLL))
577 ltemp >>= SHIFT_KG + time_constant;
578 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
579 ltemp = (MAXPHASE / MINSEC) <<
580 SHIFT_UPDATE;
581 time_offset -= ltemp;
582 time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ -
583 SHIFT_UPDATE);
584 }
585
586 /*
587 * Compute the frequency estimate and additional phase
588 * adjustment due to frequency error for the next
589 * second. When the PPS signal is engaged, gnaw on the
590 * watchdog counter and update the frequency computed by
591 * the pll and the PPS signal.
592 */
593 #ifdef PPS_SYNC
594 pps_valid++;
595 if (pps_valid == PPS_VALID) {
596 pps_jitter = MAXTIME;
597 pps_stabil = MAXFREQ;
598 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
599 STA_PPSWANDER | STA_PPSERROR);
600 }
601 ltemp = time_freq + pps_freq;
602 #else
603 ltemp = time_freq;
604 #endif /* PPS_SYNC */
605
606 if (ltemp < 0)
607 time_adj -= -ltemp >>
608 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
609 else
610 time_adj += ltemp >>
611 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
612 time_adj += (long)fixtick << (SHIFT_SCALE - SHIFT_HZ);
613
614
615 #if SHIFT_HZ == 7
616 /*
617 * When the CPU clock oscillator frequency is not a
618 * power of 2 in Hz, the SHIFT_HZ is only an approximate
619 * scale factor. In the SunOS kernel, this results in a
620 * PLL gain factor of 1/1.28 = 0.78 what it should be.
621 * In the following code the overall gain is increased
622 * by a factor of 1.25, which results in a residual
623 * error less than 3 percent.
624 */
625 if (hz == 100) {
626 if (time_adj < 0)
627 time_adj -= -time_adj >> 2;
628 else
629 time_adj += time_adj >> 2;
630 }
631 else
632 if (hz == 96) {
633 if (time_adj < 0)
634 time_adj -= -time_adj >> 2;
635 else
636 time_adj += time_adj >> 2;
637 }
638
639 #endif /* SHIFT_HZ */
640 #if SHIFT_HZ == 6
641 /*
642 * 60 Hz m68k and vaxes have a PLL gain factor of of
643 * 60/64 (15/16) of what it should be. In the following code
644 * the overall gain is increased by a factor of 1.0625,
645 * (17/16) which results in a residual error of just less
646 * than 0.4 percent.
647 */
648 if (hz == 60) {
649 if (time_adj < 0)
650 time_adj -= -time_adj >> 4;
651 else
652 time_adj += time_adj >> 4;
653 }
654 #endif /* SHIFT_HZ */
655
656 #ifdef EXT_CLOCK
657 /*
658 * If an external clock is present, it is necessary to
659 * discipline the kernel time variable anyway, since not
660 * all system components use the microtime() interface.
661 * Here, the time offset between the external clock and
662 * kernel time variable is computed every so often.
663 */
664 clock_count++;
665 if (clock_count > CLOCK_INTERVAL) {
666 clock_count = 0;
667 microtime(&clock_ext);
668 delta.tv_sec = clock_ext.tv_sec - time.tv_sec;
669 delta.tv_usec = clock_ext.tv_usec -
670 time.tv_usec;
671 if (delta.tv_usec < 0)
672 delta.tv_sec--;
673 if (delta.tv_usec >= 500000) {
674 delta.tv_usec -= 1000000;
675 delta.tv_sec++;
676 }
677 if (delta.tv_usec < -500000) {
678 delta.tv_usec += 1000000;
679 delta.tv_sec--;
680 }
681 if (delta.tv_sec > 0 || (delta.tv_sec == 0 &&
682 delta.tv_usec > MAXPHASE) ||
683 delta.tv_sec < -1 || (delta.tv_sec == -1 &&
684 delta.tv_usec < -MAXPHASE)) {
685 time = clock_ext;
686 delta.tv_sec = 0;
687 delta.tv_usec = 0;
688 }
689 #ifdef HIGHBALL
690 clock_cpu = delta.tv_usec;
691 #else /* HIGHBALL */
692 hardupdate(delta.tv_usec);
693 #endif /* HIGHBALL */
694 }
695 #endif /* EXT_CLOCK */
696 }
697
698 /*
699 * End of precision-kernel code fragment
700 */
701 #endif /*NTP*/ /* XXX End of David L. Mills' ntp precision-time fragment */
702
703 /*
704 * Process callouts at a very low cpu priority, so we don't keep the
705 * relatively high clock interrupt priority any longer than necessary.
706 */
707 if (needsoft) {
708 if (CLKF_BASEPRI(frame)) {
709 /*
710 * Save the overhead of a software interrupt;
711 * it will happen as soon as we return, so do it now.
712 */
713 (void)splsoftclock();
714 softclock();
715 } else
716 setsoftclock();
717 }
718 }
719
720 /*
721 * Software (low priority) clock interrupt.
722 * Run periodic events from timeout queue.
723 */
724 /*ARGSUSED*/
725 void
726 softclock()
727 {
728 register struct callout *c;
729 register void *arg;
730 register void (*func) __P((void *));
731 register int s;
732
733 s = splhigh();
734 while ((c = calltodo.c_next) != NULL && c->c_time <= 0) {
735 func = c->c_func;
736 arg = c->c_arg;
737 calltodo.c_next = c->c_next;
738 c->c_next = callfree;
739 callfree = c;
740 splx(s);
741 (*func)(arg);
742 (void) splhigh();
743 }
744 splx(s);
745 }
746
747 /*
748 * timeout --
749 * Execute a function after a specified length of time.
750 *
751 * untimeout --
752 * Cancel previous timeout function call.
753 *
754 * See AT&T BCI Driver Reference Manual for specification. This
755 * implementation differs from that one in that no identification
756 * value is returned from timeout, rather, the original arguments
757 * to timeout are used to identify entries for untimeout.
758 */
759 void
760 timeout(ftn, arg, ticks)
761 void (*ftn) __P((void *));
762 void *arg;
763 register int ticks;
764 {
765 register struct callout *new, *p, *t;
766 register int s;
767
768 if (ticks <= 0)
769 ticks = 1;
770
771 /* Lock out the clock. */
772 s = splhigh();
773
774 /* Fill in the next free callout structure. */
775 if (callfree == NULL)
776 panic("timeout table full");
777 new = callfree;
778 callfree = new->c_next;
779 new->c_arg = arg;
780 new->c_func = ftn;
781
782 /*
783 * The time for each event is stored as a difference from the time
784 * of the previous event on the queue. Walk the queue, correcting
785 * the ticks argument for queue entries passed. Correct the ticks
786 * value for the queue entry immediately after the insertion point
787 * as well. Watch out for negative c_time values; these represent
788 * overdue events.
789 */
790 for (p = &calltodo;
791 (t = p->c_next) != NULL && ticks > t->c_time; p = t)
792 if (t->c_time > 0)
793 ticks -= t->c_time;
794 new->c_time = ticks;
795 if (t != NULL)
796 t->c_time -= ticks;
797
798 /* Insert the new entry into the queue. */
799 p->c_next = new;
800 new->c_next = t;
801 splx(s);
802 }
803
804 void
805 untimeout(ftn, arg)
806 void (*ftn) __P((void *));
807 void *arg;
808 {
809 register struct callout *p, *t;
810 register int s;
811
812 s = splhigh();
813 for (p = &calltodo; (t = p->c_next) != NULL; p = t)
814 if (t->c_func == ftn && t->c_arg == arg) {
815 /* Increment next entry's tick count. */
816 if (t->c_next && t->c_time > 0)
817 t->c_next->c_time += t->c_time;
818
819 /* Move entry from callout queue to callfree queue. */
820 p->c_next = t->c_next;
821 t->c_next = callfree;
822 callfree = t;
823 break;
824 }
825 splx(s);
826 }
827
828 /*
829 * Compute number of hz until specified time. Used to
830 * compute third argument to timeout() from an absolute time.
831 */
832 int
833 hzto(tv)
834 struct timeval *tv;
835 {
836 register long ticks, sec;
837 int s;
838
839 /*
840 * If number of microseconds will fit in 32 bit arithmetic,
841 * then compute number of microseconds to time and scale to
842 * ticks. Otherwise just compute number of hz in time, rounding
843 * times greater than representible to maximum value. (We must
844 * compute in microseconds, because hz can be greater than 1000,
845 * and thus tick can be less than one millisecond).
846 *
847 * Delta times less than 14 hours can be computed ``exactly''.
848 * (Note that if hz would yeild a non-integral number of us per
849 * tick, i.e. tickfix is nonzero, timouts can be a tick longer
850 * than they should be.) Maximum value for any timeout in 10ms
851 * ticks is 250 days.
852 */
853 s = splhigh();
854 sec = tv->tv_sec - time.tv_sec;
855 if (sec <= 0x7fffffff / 1000000 - 1)
856 ticks = ((tv->tv_sec - time.tv_sec) * 1000000 +
857 (tv->tv_usec - time.tv_usec)) / tick;
858 else if (sec <= 0x7fffffff / hz)
859 ticks = sec * hz;
860 else
861 ticks = 0x7fffffff;
862 splx(s);
863 return (ticks);
864 }
865
866 /*
867 * Start profiling on a process.
868 *
869 * Kernel profiling passes proc0 which never exits and hence
870 * keeps the profile clock running constantly.
871 */
872 void
873 startprofclock(p)
874 register struct proc *p;
875 {
876 int s;
877
878 if ((p->p_flag & P_PROFIL) == 0) {
879 p->p_flag |= P_PROFIL;
880 if (++profprocs == 1 && stathz != 0) {
881 s = splstatclock();
882 psdiv = pscnt = psratio;
883 setstatclockrate(profhz);
884 splx(s);
885 }
886 }
887 }
888
889 /*
890 * Stop profiling on a process.
891 */
892 void
893 stopprofclock(p)
894 register struct proc *p;
895 {
896 int s;
897
898 if (p->p_flag & P_PROFIL) {
899 p->p_flag &= ~P_PROFIL;
900 if (--profprocs == 0 && stathz != 0) {
901 s = splstatclock();
902 psdiv = pscnt = 1;
903 setstatclockrate(stathz);
904 splx(s);
905 }
906 }
907 }
908
909 /*
910 * Statistics clock. Grab profile sample, and if divider reaches 0,
911 * do process and kernel statistics.
912 */
913 void
914 statclock(frame)
915 register struct clockframe *frame;
916 {
917 #ifdef GPROF
918 register struct gmonparam *g;
919 #endif
920 register struct proc *p;
921 register int i;
922
923 if (CLKF_USERMODE(frame)) {
924 p = curproc;
925 if (p->p_flag & P_PROFIL)
926 addupc_intr(p, CLKF_PC(frame), 1);
927 if (--pscnt > 0)
928 return;
929 /*
930 * Came from user mode; CPU was in user state.
931 * If this process is being profiled record the tick.
932 */
933 p->p_uticks++;
934 if (p->p_nice > NZERO)
935 cp_time[CP_NICE]++;
936 else
937 cp_time[CP_USER]++;
938 } else {
939 #ifdef GPROF
940 /*
941 * Kernel statistics are just like addupc_intr, only easier.
942 */
943 g = &_gmonparam;
944 if (g->state == GMON_PROF_ON) {
945 i = CLKF_PC(frame) - g->lowpc;
946 if (i < g->textsize) {
947 i /= HISTFRACTION * sizeof(*g->kcount);
948 g->kcount[i]++;
949 }
950 }
951 #endif
952 if (--pscnt > 0)
953 return;
954 /*
955 * Came from kernel mode, so we were:
956 * - handling an interrupt,
957 * - doing syscall or trap work on behalf of the current
958 * user process, or
959 * - spinning in the idle loop.
960 * Whichever it is, charge the time as appropriate.
961 * Note that we charge interrupts to the current process,
962 * regardless of whether they are ``for'' that process,
963 * so that we know how much of its real time was spent
964 * in ``non-process'' (i.e., interrupt) work.
965 */
966 p = curproc;
967 if (CLKF_INTR(frame)) {
968 if (p != NULL)
969 p->p_iticks++;
970 cp_time[CP_INTR]++;
971 } else if (p != NULL) {
972 p->p_sticks++;
973 cp_time[CP_SYS]++;
974 } else
975 cp_time[CP_IDLE]++;
976 }
977 pscnt = psdiv;
978
979 /*
980 * XXX Support old-style instrumentation for now.
981 *
982 * We maintain statistics shown by user-level statistics
983 * programs: the amount of time in each cpu state, and
984 * the amount of time each of DK_NDRIVE ``drives'' is busy.
985 *
986 * XXX should either run linked list of drives, or (better)
987 * grab timestamps in the start & done code.
988 */
989 for (i = 0; i < DK_NDRIVE; i++)
990 if (dk_busy & (1 << i))
991 dk_time[i]++;
992
993 /*
994 * We adjust the priority of the current process. The priority of
995 * a process gets worse as it accumulates CPU time. The cpu usage
996 * estimator (p_estcpu) is increased here. The formula for computing
997 * priorities (in kern_synch.c) will compute a different value each
998 * time p_estcpu increases by 4. The cpu usage estimator ramps up
999 * quite quickly when the process is running (linearly), and decays
1000 * away exponentially, at a rate which is proportionally slower when
1001 * the system is busy. The basic principal is that the system will
1002 * 90% forget that the process used a lot of CPU time in 5 * loadav
1003 * seconds. This causes the system to favor processes which haven't
1004 * run much recently, and to round-robin among other processes.
1005 */
1006 if (p != NULL) {
1007 p->p_cpticks++;
1008 if (++p->p_estcpu == 0)
1009 p->p_estcpu--;
1010 if ((p->p_estcpu & 3) == 0) {
1011 resetpriority(p);
1012 if (p->p_priority >= PUSER)
1013 p->p_priority = p->p_usrpri;
1014 }
1015 }
1016 }
1017
1018
1019 #ifdef NTP /* NTP phase-locked loop in kernel */
1020
1021 /*
1022 * hardupdate() - local clock update
1023 *
1024 * This routine is called by ntp_adjtime() to update the local clock
1025 * phase and frequency. The implementation is of an adaptive-parameter,
1026 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
1027 * time and frequency offset estimates for each call. If the kernel PPS
1028 * discipline code is configured (PPS_SYNC), the PPS signal itself
1029 * determines the new time offset, instead of the calling argument.
1030 * Presumably, calls to ntp_adjtime() occur only when the caller
1031 * believes the local clock is valid within some bound (+-128 ms with
1032 * NTP). If the caller's time is far different than the PPS time, an
1033 * argument will ensue, and it's not clear who will lose.
1034 *
1035 * For uncompensated quartz crystal oscillatores and nominal update
1036 * intervals less than 1024 s, operation should be in phase-lock mode
1037 * (STA_FLL = 0), where the loop is disciplined to phase. For update
1038 * intervals greater than thiss, operation should be in frequency-lock
1039 * mode (STA_FLL = 1), where the loop is disciplined to frequency.
1040 *
1041 * Note: splclock() is in effect.
1042 */
1043 void
1044 hardupdate(offset)
1045 long offset;
1046 {
1047 long ltemp, mtemp;
1048
1049 if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
1050 return;
1051 ltemp = offset;
1052 #ifdef PPS_SYNC
1053 if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
1054 ltemp = pps_offset;
1055 #endif /* PPS_SYNC */
1056
1057 /*
1058 * Scale the phase adjustment and clamp to the operating range.
1059 */
1060 if (ltemp > MAXPHASE)
1061 time_offset = MAXPHASE << SHIFT_UPDATE;
1062 else if (ltemp < -MAXPHASE)
1063 time_offset = -(MAXPHASE << SHIFT_UPDATE);
1064 else
1065 time_offset = ltemp << SHIFT_UPDATE;
1066
1067 /*
1068 * Select whether the frequency is to be controlled and in which
1069 * mode (PLL or FLL). Clamp to the operating range. Ugly
1070 * multiply/divide should be replaced someday.
1071 */
1072 if (time_status & STA_FREQHOLD || time_reftime == 0)
1073 time_reftime = time.tv_sec;
1074 mtemp = time.tv_sec - time_reftime;
1075 time_reftime = time.tv_sec;
1076 if (time_status & STA_FLL) {
1077 if (mtemp >= MINSEC) {
1078 ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
1079 SHIFT_UPDATE));
1080 if (ltemp < 0)
1081 time_freq -= -ltemp >> SHIFT_KH;
1082 else
1083 time_freq += ltemp >> SHIFT_KH;
1084 }
1085 } else {
1086 if (mtemp < MAXSEC) {
1087 ltemp *= mtemp;
1088 if (ltemp < 0)
1089 time_freq -= -ltemp >> (time_constant +
1090 time_constant + SHIFT_KF -
1091 SHIFT_USEC);
1092 else
1093 time_freq += ltemp >> (time_constant +
1094 time_constant + SHIFT_KF -
1095 SHIFT_USEC);
1096 }
1097 }
1098 if (time_freq > time_tolerance)
1099 time_freq = time_tolerance;
1100 else if (time_freq < -time_tolerance)
1101 time_freq = -time_tolerance;
1102 }
1103
1104 #ifdef PPS_SYNC
1105 /*
1106 * hardpps() - discipline CPU clock oscillator to external PPS signal
1107 *
1108 * This routine is called at each PPS interrupt in order to discipline
1109 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
1110 * and leaves it in a handy spot for the hardclock() routine. It
1111 * integrates successive PPS phase differences and calculates the
1112 * frequency offset. This is used in hardclock() to discipline the CPU
1113 * clock oscillator so that intrinsic frequency error is cancelled out.
1114 * The code requires the caller to capture the time and hardware counter
1115 * value at the on-time PPS signal transition.
1116 *
1117 * Note that, on some Unix systems, this routine runs at an interrupt
1118 * priority level higher than the timer interrupt routine hardclock().
1119 * Therefore, the variables used are distinct from the hardclock()
1120 * variables, except for certain exceptions: The PPS frequency pps_freq
1121 * and phase pps_offset variables are determined by this routine and
1122 * updated atomically. The time_tolerance variable can be considered a
1123 * constant, since it is infrequently changed, and then only when the
1124 * PPS signal is disabled. The watchdog counter pps_valid is updated
1125 * once per second by hardclock() and is atomically cleared in this
1126 * routine.
1127 */
1128 void
1129 hardpps(tvp, usec)
1130 struct timeval *tvp; /* time at PPS */
1131 long usec; /* hardware counter at PPS */
1132 {
1133 long u_usec, v_usec, bigtick;
1134 long cal_sec, cal_usec;
1135
1136 /*
1137 * An occasional glitch can be produced when the PPS interrupt
1138 * occurs in the hardclock() routine before the time variable is
1139 * updated. Here the offset is discarded when the difference
1140 * between it and the last one is greater than tick/2, but not
1141 * if the interval since the first discard exceeds 30 s.
1142 */
1143 time_status |= STA_PPSSIGNAL;
1144 time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1145 pps_valid = 0;
1146 u_usec = -tvp->tv_usec;
1147 if (u_usec < -500000)
1148 u_usec += 1000000;
1149 v_usec = pps_offset - u_usec;
1150 if (v_usec < 0)
1151 v_usec = -v_usec;
1152 if (v_usec > (tick >> 1)) {
1153 if (pps_glitch > MAXGLITCH) {
1154 pps_glitch = 0;
1155 pps_tf[2] = u_usec;
1156 pps_tf[1] = u_usec;
1157 } else {
1158 pps_glitch++;
1159 u_usec = pps_offset;
1160 }
1161 } else
1162 pps_glitch = 0;
1163
1164 /*
1165 * A three-stage median filter is used to help deglitch the pps
1166 * time. The median sample becomes the time offset estimate; the
1167 * difference between the other two samples becomes the time
1168 * dispersion (jitter) estimate.
1169 */
1170 pps_tf[2] = pps_tf[1];
1171 pps_tf[1] = pps_tf[0];
1172 pps_tf[0] = u_usec;
1173 if (pps_tf[0] > pps_tf[1]) {
1174 if (pps_tf[1] > pps_tf[2]) {
1175 pps_offset = pps_tf[1]; /* 0 1 2 */
1176 v_usec = pps_tf[0] - pps_tf[2];
1177 } else if (pps_tf[2] > pps_tf[0]) {
1178 pps_offset = pps_tf[0]; /* 2 0 1 */
1179 v_usec = pps_tf[2] - pps_tf[1];
1180 } else {
1181 pps_offset = pps_tf[2]; /* 0 2 1 */
1182 v_usec = pps_tf[0] - pps_tf[1];
1183 }
1184 } else {
1185 if (pps_tf[1] < pps_tf[2]) {
1186 pps_offset = pps_tf[1]; /* 2 1 0 */
1187 v_usec = pps_tf[2] - pps_tf[0];
1188 } else if (pps_tf[2] < pps_tf[0]) {
1189 pps_offset = pps_tf[0]; /* 1 0 2 */
1190 v_usec = pps_tf[1] - pps_tf[2];
1191 } else {
1192 pps_offset = pps_tf[2]; /* 1 2 0 */
1193 v_usec = pps_tf[1] - pps_tf[0];
1194 }
1195 }
1196 if (v_usec > MAXTIME)
1197 pps_jitcnt++;
1198 v_usec = (v_usec << PPS_AVG) - pps_jitter;
1199 if (v_usec < 0)
1200 pps_jitter -= -v_usec >> PPS_AVG;
1201 else
1202 pps_jitter += v_usec >> PPS_AVG;
1203 if (pps_jitter > (MAXTIME >> 1))
1204 time_status |= STA_PPSJITTER;
1205
1206 /*
1207 * During the calibration interval adjust the starting time when
1208 * the tick overflows. At the end of the interval compute the
1209 * duration of the interval and the difference of the hardware
1210 * counters at the beginning and end of the interval. This code
1211 * is deliciously complicated by the fact valid differences may
1212 * exceed the value of tick when using long calibration
1213 * intervals and small ticks. Note that the counter can be
1214 * greater than tick if caught at just the wrong instant, but
1215 * the values returned and used here are correct.
1216 */
1217 bigtick = (long)tick << SHIFT_USEC;
1218 pps_usec -= pps_freq;
1219 if (pps_usec >= bigtick)
1220 pps_usec -= bigtick;
1221 if (pps_usec < 0)
1222 pps_usec += bigtick;
1223 pps_time.tv_sec++;
1224 pps_count++;
1225 if (pps_count < (1 << pps_shift))
1226 return;
1227 pps_count = 0;
1228 pps_calcnt++;
1229 u_usec = usec << SHIFT_USEC;
1230 v_usec = pps_usec - u_usec;
1231 if (v_usec >= bigtick >> 1)
1232 v_usec -= bigtick;
1233 if (v_usec < -(bigtick >> 1))
1234 v_usec += bigtick;
1235 if (v_usec < 0)
1236 v_usec = -(-v_usec >> pps_shift);
1237 else
1238 v_usec = v_usec >> pps_shift;
1239 pps_usec = u_usec;
1240 cal_sec = tvp->tv_sec;
1241 cal_usec = tvp->tv_usec;
1242 cal_sec -= pps_time.tv_sec;
1243 cal_usec -= pps_time.tv_usec;
1244 if (cal_usec < 0) {
1245 cal_usec += 1000000;
1246 cal_sec--;
1247 }
1248 pps_time = *tvp;
1249
1250 /*
1251 * Check for lost interrupts, noise, excessive jitter and
1252 * excessive frequency error. The number of timer ticks during
1253 * the interval may vary +-1 tick. Add to this a margin of one
1254 * tick for the PPS signal jitter and maximum frequency
1255 * deviation. If the limits are exceeded, the calibration
1256 * interval is reset to the minimum and we start over.
1257 */
1258 u_usec = (long)tick << 1;
1259 if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
1260 || (cal_sec == 0 && cal_usec < u_usec))
1261 || v_usec > time_tolerance || v_usec < -time_tolerance) {
1262 pps_errcnt++;
1263 pps_shift = PPS_SHIFT;
1264 pps_intcnt = 0;
1265 time_status |= STA_PPSERROR;
1266 return;
1267 }
1268
1269 /*
1270 * A three-stage median filter is used to help deglitch the pps
1271 * frequency. The median sample becomes the frequency offset
1272 * estimate; the difference between the other two samples
1273 * becomes the frequency dispersion (stability) estimate.
1274 */
1275 pps_ff[2] = pps_ff[1];
1276 pps_ff[1] = pps_ff[0];
1277 pps_ff[0] = v_usec;
1278 if (pps_ff[0] > pps_ff[1]) {
1279 if (pps_ff[1] > pps_ff[2]) {
1280 u_usec = pps_ff[1]; /* 0 1 2 */
1281 v_usec = pps_ff[0] - pps_ff[2];
1282 } else if (pps_ff[2] > pps_ff[0]) {
1283 u_usec = pps_ff[0]; /* 2 0 1 */
1284 v_usec = pps_ff[2] - pps_ff[1];
1285 } else {
1286 u_usec = pps_ff[2]; /* 0 2 1 */
1287 v_usec = pps_ff[0] - pps_ff[1];
1288 }
1289 } else {
1290 if (pps_ff[1] < pps_ff[2]) {
1291 u_usec = pps_ff[1]; /* 2 1 0 */
1292 v_usec = pps_ff[2] - pps_ff[0];
1293 } else if (pps_ff[2] < pps_ff[0]) {
1294 u_usec = pps_ff[0]; /* 1 0 2 */
1295 v_usec = pps_ff[1] - pps_ff[2];
1296 } else {
1297 u_usec = pps_ff[2]; /* 1 2 0 */
1298 v_usec = pps_ff[1] - pps_ff[0];
1299 }
1300 }
1301
1302 /*
1303 * Here the frequency dispersion (stability) is updated. If it
1304 * is less than one-fourth the maximum (MAXFREQ), the frequency
1305 * offset is updated as well, but clamped to the tolerance. It
1306 * will be processed later by the hardclock() routine.
1307 */
1308 v_usec = (v_usec >> 1) - pps_stabil;
1309 if (v_usec < 0)
1310 pps_stabil -= -v_usec >> PPS_AVG;
1311 else
1312 pps_stabil += v_usec >> PPS_AVG;
1313 if (pps_stabil > MAXFREQ >> 2) {
1314 pps_stbcnt++;
1315 time_status |= STA_PPSWANDER;
1316 return;
1317 }
1318 if (time_status & STA_PPSFREQ) {
1319 if (u_usec < 0) {
1320 pps_freq -= -u_usec >> PPS_AVG;
1321 if (pps_freq < -time_tolerance)
1322 pps_freq = -time_tolerance;
1323 u_usec = -u_usec;
1324 } else {
1325 pps_freq += u_usec >> PPS_AVG;
1326 if (pps_freq > time_tolerance)
1327 pps_freq = time_tolerance;
1328 }
1329 }
1330
1331 /*
1332 * Here the calibration interval is adjusted. If the maximum
1333 * time difference is greater than tick / 4, reduce the interval
1334 * by half. If this is not the case for four consecutive
1335 * intervals, double the interval.
1336 */
1337 if (u_usec << pps_shift > bigtick >> 2) {
1338 pps_intcnt = 0;
1339 if (pps_shift > PPS_SHIFT)
1340 pps_shift--;
1341 } else if (pps_intcnt >= 4) {
1342 pps_intcnt = 0;
1343 if (pps_shift < PPS_SHIFTMAX)
1344 pps_shift++;
1345 } else
1346 pps_intcnt++;
1347 }
1348 #endif /* PPS_SYNC */
1349 #endif /* NTP */
1350
1351
1352 /*
1353 * Return information about system clocks.
1354 */
1355 int
1356 sysctl_clockrate(where, sizep)
1357 register char *where;
1358 size_t *sizep;
1359 {
1360 struct clockinfo clkinfo;
1361
1362 /*
1363 * Construct clockinfo structure.
1364 */
1365 clkinfo.tick = tick;
1366 clkinfo.tickadj = tickadj;
1367 clkinfo.hz = hz;
1368 clkinfo.profhz = profhz;
1369 clkinfo.stathz = stathz ? stathz : hz;
1370 return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
1371 }
1372
1373 #ifdef DDB
1374 #include <machine/db_machdep.h>
1375
1376 #include <ddb/db_interface.h>
1377 #include <ddb/db_access.h>
1378 #include <ddb/db_sym.h>
1379 #include <ddb/db_output.h>
1380
1381 void db_show_callout(addr, haddr, count, modif)
1382 db_expr_t addr;
1383 int haddr;
1384 db_expr_t count;
1385 char *modif;
1386 {
1387 register struct callout *p1;
1388 register int cum;
1389 register int s;
1390 db_expr_t offset;
1391 char *name;
1392
1393 db_printf(" cum ticks arg func\n");
1394 s = splhigh();
1395 for (cum = 0, p1 = calltodo.c_next; p1; p1 = p1->c_next) {
1396 register int t = p1->c_time;
1397
1398 if (t > 0)
1399 cum += t;
1400
1401 db_find_sym_and_offset((db_addr_t)p1->c_func, &name, &offset);
1402 if (name == NULL)
1403 name = "?";
1404
1405 db_printf("%9d %9d %8x %s (%x)\n",
1406 cum, t, p1->c_arg, name, p1->c_func);
1407 }
1408 splx(s);
1409 }
1410 #endif
1411