kern_clock.c revision 1.28 1 /* $NetBSD: kern_clock.c,v 1.28 1996/02/29 02:48:53 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 * Precision timekeeping does not support 48 Hz, so Ataris at 48Hz are
275 * out of luck.
276 */
277
278 #if HZ == 64 || HZ == 60
279 # define SHIFT_HZ 6 /* log2(64) */
280 #else
281 #if HZ == 128 || HZ == 100 || HZ == 96
282 # define SHIFT_HZ 7 /* log2(128), 100 and 96 are fudged. */
283 #else
284 #if HZ == 256
285 # define SHIFT_HZ 8 /* log2(256) */
286 #else
287 #if HZ == 1024
288 # define SHIFT_HZ 10 /* log2(1024) */
289 #else
290 #error HZ is not a supported value. Please change HZ in your kernel config file
291 #endif /* 1024Hz */
292 #endif /* 256Hz */
293 #endif /* 128HZ or 100Hz (or 96Hz, untested) */
294 #endif /* 64Hz or 60Hz */
295
296 /*
297 * End of SHIFT_HZ computation
298 */
299
300 #endif /* NTP */
301
302
303 /*
304 * Bump a timeval by a small number of usec's.
305 */
306 #define BUMPTIME(t, usec) { \
307 register volatile struct timeval *tp = (t); \
308 register long us; \
309 \
310 tp->tv_usec = us = tp->tv_usec + (usec); \
311 if (us >= 1000000) { \
312 tp->tv_usec = us - 1000000; \
313 tp->tv_sec++; \
314 } \
315 }
316
317 int stathz;
318 int profhz;
319 int profprocs;
320 int ticks;
321 static int psdiv, pscnt; /* prof => stat divider */
322 int psratio; /* ratio: prof / stat */
323 int tickfix, tickfixinterval; /* used if tick not really integral */
324 static int tickfixcnt; /* number of ticks since last fix */
325 int fixtick; /* used by NTP for same */
326
327 volatile struct timeval time;
328 volatile struct timeval mono_time;
329
330 /*
331 * Initialize clock frequencies and start both clocks running.
332 */
333 void
334 initclocks()
335 {
336 register int i;
337
338 /*
339 * Set divisors to 1 (normal case) and let the machine-specific
340 * code do its bit.
341 */
342 psdiv = pscnt = 1;
343 cpu_initclocks();
344
345 /*
346 * Compute profhz/stathz, and fix profhz if needed.
347 */
348 i = stathz ? stathz : hz;
349 if (profhz == 0)
350 profhz = i;
351 psratio = profhz / i;
352 }
353
354 /*
355 * The real-time timer, interrupting hz times per second.
356 */
357 void
358 hardclock(frame)
359 register struct clockframe *frame;
360 {
361 register struct callout *p1;
362 register struct proc *p;
363 register int delta, needsoft;
364 extern int tickdelta;
365 extern long timedelta;
366 register int time_update, ltemp;
367
368 /*
369 * Update real-time timeout queue.
370 * At front of queue are some number of events which are ``due''.
371 * The time to these is <= 0 and if negative represents the
372 * number of ticks which have passed since it was supposed to happen.
373 * The rest of the q elements (times > 0) are events yet to happen,
374 * where the time for each is given as a delta from the previous.
375 * Decrementing just the first of these serves to decrement the time
376 * to all events.
377 */
378 needsoft = 0;
379 for (p1 = calltodo.c_next; p1 != NULL; p1 = p1->c_next) {
380 if (--p1->c_time > 0)
381 break;
382 needsoft = 1;
383 if (p1->c_time == 0)
384 break;
385 }
386
387 p = curproc;
388 if (p) {
389 register struct pstats *pstats;
390
391 /*
392 * Run current process's virtual and profile time, as needed.
393 */
394 pstats = p->p_stats;
395 if (CLKF_USERMODE(frame) &&
396 timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
397 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
398 psignal(p, SIGVTALRM);
399 if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
400 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
401 psignal(p, SIGPROF);
402 }
403
404 /*
405 * If no separate statistics clock is available, run it from here.
406 */
407 if (stathz == 0)
408 statclock(frame);
409
410 /*
411 * Increment the time-of-day. The increment is normally just
412 * ``tick''. If the machine is one which has a clock frequency
413 * such that ``hz'' would not divide the second evenly into
414 * milliseconds, a periodic adjustment must be applied. Finally,
415 * if we are still adjusting the time (see adjtime()),
416 * ``tickdelta'' may also be added in.
417 */
418 ticks++;
419 delta = tick;
420
421 #ifndef NTP
422 if (tickfix) {
423 tickfixcnt++;
424 if (tickfixcnt >= tickfixinterval) {
425 delta += tickfix;
426 tickfixcnt = 0;
427 }
428 }
429 #endif /* !NTP */
430 /* Imprecise 4bsd adjtime() handling */
431 if (timedelta != 0) {
432 delta = tick + tickdelta;
433 timedelta -= tickdelta;
434 }
435
436 #ifdef notyet
437 microset();
438 #endif
439
440 #ifndef NTP
441 BUMPTIME(&time, delta); /* XXX Now done using NTP code below */
442 #endif
443 BUMPTIME(&mono_time, delta);
444 time_update = delta;
445
446 #ifdef NTP /* XXX Start of David L. Mills' ntp precision-time fragment */
447
448 /*
449 * Beginning of precision-kernel code fragment
450 *
451 * Compute the phase adjustment. If the low-order bits
452 * (time_phase) of the update overflow, bump the high-order bits
453 * (time_update).
454 */
455 time_phase += time_adj;
456 if (time_phase <= -FINEUSEC) {
457 ltemp = -time_phase >> SHIFT_SCALE;
458 time_phase += ltemp << SHIFT_SCALE;
459 time_update -= ltemp;
460 }
461 else if (time_phase >= FINEUSEC) {
462 ltemp = time_phase >> SHIFT_SCALE;
463 time_phase -= ltemp << SHIFT_SCALE;
464 time_update += ltemp;
465 }
466
467 #ifdef HIGHBALL
468 /*
469 * If the HIGHBALL board is installed, we need to adjust the
470 * external clock offset in order to close the hardware feedback
471 * loop. This will adjust the external clock phase and frequency
472 * in small amounts. The additional phase noise and frequency
473 * wander this causes should be minimal. We also need to
474 * discipline the kernel time variable, since the PLL is used to
475 * discipline the external clock. If the Highball board is not
476 * present, we discipline kernel time with the PLL as usual. We
477 * assume that the external clock phase adjustment (time_update)
478 * and kernel phase adjustment (clock_cpu) are less than the
479 * value of tick.
480 */
481 clock_offset.tv_usec += time_update;
482 if (clock_offset.tv_usec >= 1000000) {
483 clock_offset.tv_sec++;
484 clock_offset.tv_usec -= 1000000;
485 }
486 if (clock_offset.tv_usec < 0) {
487 clock_offset.tv_sec--;
488 clock_offset.tv_usec += 1000000;
489 }
490 time.tv_usec += clock_cpu;
491 clock_cpu = 0;
492 #else
493 time.tv_usec += time_update;
494 #endif /* HIGHBALL */
495
496 /*
497 * End of precision-kernel code fragment
498 */
499
500 /*
501 * Beginning of precision-kernel code fragment
502 *
503 * On rollover of the second the phase adjustment to be used for
504 * the next second is calculated. Also, the maximum error is
505 * increased by the tolerance. If the PPS frequency discipline
506 * code is present, the phase is increased to compensate for the
507 * CPU clock oscillator frequency error.
508 *
509 * On a 32-bit machine and given parameters in the timex.h
510 * header file, the maximum phase adjustment is +-512 ms and
511 * maximum frequency offset is a tad less than) +-512 ppm. On a
512 * 64-bit machine, you shouldn't need to ask.
513 */
514 if (time.tv_usec >= 1000000) {
515 time.tv_usec -= 1000000;
516 time.tv_sec++;
517 time_maxerror += time_tolerance >> SHIFT_USEC;
518
519 /*
520 * Leap second processing. If in leap-insert state at
521 * the end of the day, the system clock is set back one
522 * second; if in leap-delete state, the system clock is
523 * set ahead one second. The microtime() routine or
524 * external clock driver will insure that reported time
525 * is always monotonic. The ugly divides should be
526 * replaced.
527 */
528 switch (time_state) {
529
530 case TIME_OK:
531 if (time_status & STA_INS)
532 time_state = TIME_INS;
533 else if (time_status & STA_DEL)
534 time_state = TIME_DEL;
535 break;
536
537 case TIME_INS:
538 if (time.tv_sec % 86400 == 0) {
539 time.tv_sec--;
540 time_state = TIME_OOP;
541 }
542 break;
543
544 case TIME_DEL:
545 if ((time.tv_sec + 1) % 86400 == 0) {
546 time.tv_sec++;
547 time_state = TIME_WAIT;
548 }
549 break;
550
551 case TIME_OOP:
552 time_state = TIME_WAIT;
553 break;
554
555 case TIME_WAIT:
556 if (!(time_status & (STA_INS | STA_DEL)))
557 time_state = TIME_OK;
558 }
559
560 /*
561 * Compute the phase adjustment for the next second. In
562 * PLL mode, the offset is reduced by a fixed factor
563 * times the time constant. In FLL mode the offset is
564 * used directly. In either mode, the maximum phase
565 * adjustment for each second is clamped so as to spread
566 * the adjustment over not more than the number of
567 * seconds between updates.
568 */
569 if (time_offset < 0) {
570 ltemp = -time_offset;
571 if (!(time_status & STA_FLL))
572 ltemp >>= SHIFT_KG + time_constant;
573 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
574 ltemp = (MAXPHASE / MINSEC) <<
575 SHIFT_UPDATE;
576 time_offset += ltemp;
577 time_adj = -ltemp << (SHIFT_SCALE - SHIFT_HZ -
578 SHIFT_UPDATE);
579 } else {
580 ltemp = time_offset;
581 if (!(time_status & STA_FLL))
582 ltemp >>= SHIFT_KG + time_constant;
583 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
584 ltemp = (MAXPHASE / MINSEC) <<
585 SHIFT_UPDATE;
586 time_offset -= ltemp;
587 time_adj = ltemp << (SHIFT_SCALE - SHIFT_HZ -
588 SHIFT_UPDATE);
589 }
590
591 /*
592 * Compute the frequency estimate and additional phase
593 * adjustment due to frequency error for the next
594 * second. When the PPS signal is engaged, gnaw on the
595 * watchdog counter and update the frequency computed by
596 * the pll and the PPS signal.
597 */
598 #ifdef PPS_SYNC
599 pps_valid++;
600 if (pps_valid == PPS_VALID) {
601 pps_jitter = MAXTIME;
602 pps_stabil = MAXFREQ;
603 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
604 STA_PPSWANDER | STA_PPSERROR);
605 }
606 ltemp = time_freq + pps_freq;
607 #else
608 ltemp = time_freq;
609 #endif /* PPS_SYNC */
610
611 if (ltemp < 0)
612 time_adj -= -ltemp >>
613 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
614 else
615 time_adj += ltemp >>
616 (SHIFT_USEC + SHIFT_HZ - SHIFT_SCALE);
617 time_adj += (long)fixtick << (SHIFT_SCALE - SHIFT_HZ);
618
619
620 #if SHIFT_HZ == 7
621 /*
622 * When the CPU clock oscillator frequency is not a
623 * power of 2 in Hz, the SHIFT_HZ is only an approximate
624 * scale factor. In the SunOS kernel, this results in a
625 * PLL gain factor of 1/1.28 = 0.78 what it should be.
626 * In the following code the overall gain is increased
627 * by a factor of 1.25, which results in a residual
628 * error less than 3 percent.
629 */
630 if (hz == 100) {
631 if (time_adj < 0)
632 time_adj -= -time_adj >> 2;
633 else
634 time_adj += time_adj >> 2;
635 }
636 else
637 if (hz == 96) {
638 if (time_adj < 0)
639 time_adj -= -time_adj >> 2;
640 else
641 time_adj += time_adj >> 2;
642 }
643
644 #endif /* SHIFT_HZ */
645 #if SHIFT_HZ == 6
646 /*
647 * 60 Hz m68k and vaxes have a PLL gain factor of of
648 * 60/64 (15/16) of what it should be. In the following code
649 * the overall gain is increased by a factor of 1.0625,
650 * (17/16) which results in a residual error of just less
651 * than 0.4 percent.
652 */
653 if (hz == 60) {
654 if (time_adj < 0)
655 time_adj -= -time_adj >> 4;
656 else
657 time_adj += time_adj >> 4;
658 }
659 #endif /* SHIFT_HZ */
660
661 #ifdef EXT_CLOCK
662 /*
663 * If an external clock is present, it is necessary to
664 * discipline the kernel time variable anyway, since not
665 * all system components use the microtime() interface.
666 * Here, the time offset between the external clock and
667 * kernel time variable is computed every so often.
668 */
669 clock_count++;
670 if (clock_count > CLOCK_INTERVAL) {
671 clock_count = 0;
672 microtime(&clock_ext);
673 delta.tv_sec = clock_ext.tv_sec - time.tv_sec;
674 delta.tv_usec = clock_ext.tv_usec -
675 time.tv_usec;
676 if (delta.tv_usec < 0)
677 delta.tv_sec--;
678 if (delta.tv_usec >= 500000) {
679 delta.tv_usec -= 1000000;
680 delta.tv_sec++;
681 }
682 if (delta.tv_usec < -500000) {
683 delta.tv_usec += 1000000;
684 delta.tv_sec--;
685 }
686 if (delta.tv_sec > 0 || (delta.tv_sec == 0 &&
687 delta.tv_usec > MAXPHASE) ||
688 delta.tv_sec < -1 || (delta.tv_sec == -1 &&
689 delta.tv_usec < -MAXPHASE)) {
690 time = clock_ext;
691 delta.tv_sec = 0;
692 delta.tv_usec = 0;
693 }
694 #ifdef HIGHBALL
695 clock_cpu = delta.tv_usec;
696 #else /* HIGHBALL */
697 hardupdate(delta.tv_usec);
698 #endif /* HIGHBALL */
699 }
700 #endif /* EXT_CLOCK */
701 }
702
703 /*
704 * End of precision-kernel code fragment
705 */
706 #endif /*NTP*/ /* XXX End of David L. Mills' ntp precision-time fragment */
707
708 /*
709 * Process callouts at a very low cpu priority, so we don't keep the
710 * relatively high clock interrupt priority any longer than necessary.
711 */
712 if (needsoft) {
713 if (CLKF_BASEPRI(frame)) {
714 /*
715 * Save the overhead of a software interrupt;
716 * it will happen as soon as we return, so do it now.
717 */
718 (void)splsoftclock();
719 softclock();
720 } else
721 setsoftclock();
722 }
723 }
724
725 /*
726 * Software (low priority) clock interrupt.
727 * Run periodic events from timeout queue.
728 */
729 /*ARGSUSED*/
730 void
731 softclock()
732 {
733 register struct callout *c;
734 register void *arg;
735 register void (*func) __P((void *));
736 register int s;
737
738 s = splhigh();
739 while ((c = calltodo.c_next) != NULL && c->c_time <= 0) {
740 func = c->c_func;
741 arg = c->c_arg;
742 calltodo.c_next = c->c_next;
743 c->c_next = callfree;
744 callfree = c;
745 splx(s);
746 (*func)(arg);
747 (void) splhigh();
748 }
749 splx(s);
750 }
751
752 /*
753 * timeout --
754 * Execute a function after a specified length of time.
755 *
756 * untimeout --
757 * Cancel previous timeout function call.
758 *
759 * See AT&T BCI Driver Reference Manual for specification. This
760 * implementation differs from that one in that no identification
761 * value is returned from timeout, rather, the original arguments
762 * to timeout are used to identify entries for untimeout.
763 */
764 void
765 timeout(ftn, arg, ticks)
766 void (*ftn) __P((void *));
767 void *arg;
768 register int ticks;
769 {
770 register struct callout *new, *p, *t;
771 register int s;
772
773 if (ticks <= 0)
774 ticks = 1;
775
776 /* Lock out the clock. */
777 s = splhigh();
778
779 /* Fill in the next free callout structure. */
780 if (callfree == NULL)
781 panic("timeout table full");
782 new = callfree;
783 callfree = new->c_next;
784 new->c_arg = arg;
785 new->c_func = ftn;
786
787 /*
788 * The time for each event is stored as a difference from the time
789 * of the previous event on the queue. Walk the queue, correcting
790 * the ticks argument for queue entries passed. Correct the ticks
791 * value for the queue entry immediately after the insertion point
792 * as well. Watch out for negative c_time values; these represent
793 * overdue events.
794 */
795 for (p = &calltodo;
796 (t = p->c_next) != NULL && ticks > t->c_time; p = t)
797 if (t->c_time > 0)
798 ticks -= t->c_time;
799 new->c_time = ticks;
800 if (t != NULL)
801 t->c_time -= ticks;
802
803 /* Insert the new entry into the queue. */
804 p->c_next = new;
805 new->c_next = t;
806 splx(s);
807 }
808
809 void
810 untimeout(ftn, arg)
811 void (*ftn) __P((void *));
812 void *arg;
813 {
814 register struct callout *p, *t;
815 register int s;
816
817 s = splhigh();
818 for (p = &calltodo; (t = p->c_next) != NULL; p = t)
819 if (t->c_func == ftn && t->c_arg == arg) {
820 /* Increment next entry's tick count. */
821 if (t->c_next && t->c_time > 0)
822 t->c_next->c_time += t->c_time;
823
824 /* Move entry from callout queue to callfree queue. */
825 p->c_next = t->c_next;
826 t->c_next = callfree;
827 callfree = t;
828 break;
829 }
830 splx(s);
831 }
832
833 /*
834 * Compute number of hz until specified time. Used to
835 * compute third argument to timeout() from an absolute time.
836 */
837 int
838 hzto(tv)
839 struct timeval *tv;
840 {
841 register long ticks, sec;
842 int s;
843
844 /*
845 * If number of microseconds will fit in 32 bit arithmetic,
846 * then compute number of microseconds to time and scale to
847 * ticks. Otherwise just compute number of hz in time, rounding
848 * times greater than representible to maximum value. (We must
849 * compute in microseconds, because hz can be greater than 1000,
850 * and thus tick can be less than one millisecond).
851 *
852 * Delta times less than 14 hours can be computed ``exactly''.
853 * (Note that if hz would yeild a non-integral number of us per
854 * tick, i.e. tickfix is nonzero, timouts can be a tick longer
855 * than they should be.) Maximum value for any timeout in 10ms
856 * ticks is 250 days.
857 */
858 s = splhigh();
859 sec = tv->tv_sec - time.tv_sec;
860 if (sec <= 0x7fffffff / 1000000 - 1)
861 ticks = ((tv->tv_sec - time.tv_sec) * 1000000 +
862 (tv->tv_usec - time.tv_usec)) / tick;
863 else if (sec <= 0x7fffffff / hz)
864 ticks = sec * hz;
865 else
866 ticks = 0x7fffffff;
867 splx(s);
868 return (ticks);
869 }
870
871 /*
872 * Start profiling on a process.
873 *
874 * Kernel profiling passes proc0 which never exits and hence
875 * keeps the profile clock running constantly.
876 */
877 void
878 startprofclock(p)
879 register struct proc *p;
880 {
881 int s;
882
883 if ((p->p_flag & P_PROFIL) == 0) {
884 p->p_flag |= P_PROFIL;
885 if (++profprocs == 1 && stathz != 0) {
886 s = splstatclock();
887 psdiv = pscnt = psratio;
888 setstatclockrate(profhz);
889 splx(s);
890 }
891 }
892 }
893
894 /*
895 * Stop profiling on a process.
896 */
897 void
898 stopprofclock(p)
899 register struct proc *p;
900 {
901 int s;
902
903 if (p->p_flag & P_PROFIL) {
904 p->p_flag &= ~P_PROFIL;
905 if (--profprocs == 0 && stathz != 0) {
906 s = splstatclock();
907 psdiv = pscnt = 1;
908 setstatclockrate(stathz);
909 splx(s);
910 }
911 }
912 }
913
914 /*
915 * Statistics clock. Grab profile sample, and if divider reaches 0,
916 * do process and kernel statistics.
917 */
918 void
919 statclock(frame)
920 register struct clockframe *frame;
921 {
922 #ifdef GPROF
923 register struct gmonparam *g;
924 #endif
925 register struct proc *p;
926 register int i;
927
928 if (CLKF_USERMODE(frame)) {
929 p = curproc;
930 if (p->p_flag & P_PROFIL)
931 addupc_intr(p, CLKF_PC(frame), 1);
932 if (--pscnt > 0)
933 return;
934 /*
935 * Came from user mode; CPU was in user state.
936 * If this process is being profiled record the tick.
937 */
938 p->p_uticks++;
939 if (p->p_nice > NZERO)
940 cp_time[CP_NICE]++;
941 else
942 cp_time[CP_USER]++;
943 } else {
944 #ifdef GPROF
945 /*
946 * Kernel statistics are just like addupc_intr, only easier.
947 */
948 g = &_gmonparam;
949 if (g->state == GMON_PROF_ON) {
950 i = CLKF_PC(frame) - g->lowpc;
951 if (i < g->textsize) {
952 i /= HISTFRACTION * sizeof(*g->kcount);
953 g->kcount[i]++;
954 }
955 }
956 #endif
957 if (--pscnt > 0)
958 return;
959 /*
960 * Came from kernel mode, so we were:
961 * - handling an interrupt,
962 * - doing syscall or trap work on behalf of the current
963 * user process, or
964 * - spinning in the idle loop.
965 * Whichever it is, charge the time as appropriate.
966 * Note that we charge interrupts to the current process,
967 * regardless of whether they are ``for'' that process,
968 * so that we know how much of its real time was spent
969 * in ``non-process'' (i.e., interrupt) work.
970 */
971 p = curproc;
972 if (CLKF_INTR(frame)) {
973 if (p != NULL)
974 p->p_iticks++;
975 cp_time[CP_INTR]++;
976 } else if (p != NULL) {
977 p->p_sticks++;
978 cp_time[CP_SYS]++;
979 } else
980 cp_time[CP_IDLE]++;
981 }
982 pscnt = psdiv;
983
984 /*
985 * XXX Support old-style instrumentation for now.
986 *
987 * We maintain statistics shown by user-level statistics
988 * programs: the amount of time in each cpu state, and
989 * the amount of time each of DK_NDRIVE ``drives'' is busy.
990 *
991 * XXX should either run linked list of drives, or (better)
992 * grab timestamps in the start & done code.
993 */
994 for (i = 0; i < DK_NDRIVE; i++)
995 if (dk_busy & (1 << i))
996 dk_time[i]++;
997
998 /*
999 * We adjust the priority of the current process. The priority of
1000 * a process gets worse as it accumulates CPU time. The cpu usage
1001 * estimator (p_estcpu) is increased here. The formula for computing
1002 * priorities (in kern_synch.c) will compute a different value each
1003 * time p_estcpu increases by 4. The cpu usage estimator ramps up
1004 * quite quickly when the process is running (linearly), and decays
1005 * away exponentially, at a rate which is proportionally slower when
1006 * the system is busy. The basic principal is that the system will
1007 * 90% forget that the process used a lot of CPU time in 5 * loadav
1008 * seconds. This causes the system to favor processes which haven't
1009 * run much recently, and to round-robin among other processes.
1010 */
1011 if (p != NULL) {
1012 p->p_cpticks++;
1013 if (++p->p_estcpu == 0)
1014 p->p_estcpu--;
1015 if ((p->p_estcpu & 3) == 0) {
1016 resetpriority(p);
1017 if (p->p_priority >= PUSER)
1018 p->p_priority = p->p_usrpri;
1019 }
1020 }
1021 }
1022
1023
1024 #ifdef NTP /* NTP phase-locked loop in kernel */
1025
1026 /*
1027 * hardupdate() - local clock update
1028 *
1029 * This routine is called by ntp_adjtime() to update the local clock
1030 * phase and frequency. The implementation is of an adaptive-parameter,
1031 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
1032 * time and frequency offset estimates for each call. If the kernel PPS
1033 * discipline code is configured (PPS_SYNC), the PPS signal itself
1034 * determines the new time offset, instead of the calling argument.
1035 * Presumably, calls to ntp_adjtime() occur only when the caller
1036 * believes the local clock is valid within some bound (+-128 ms with
1037 * NTP). If the caller's time is far different than the PPS time, an
1038 * argument will ensue, and it's not clear who will lose.
1039 *
1040 * For uncompensated quartz crystal oscillatores and nominal update
1041 * intervals less than 1024 s, operation should be in phase-lock mode
1042 * (STA_FLL = 0), where the loop is disciplined to phase. For update
1043 * intervals greater than thiss, operation should be in frequency-lock
1044 * mode (STA_FLL = 1), where the loop is disciplined to frequency.
1045 *
1046 * Note: splclock() is in effect.
1047 */
1048 void
1049 hardupdate(offset)
1050 long offset;
1051 {
1052 long ltemp, mtemp;
1053
1054 if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
1055 return;
1056 ltemp = offset;
1057 #ifdef PPS_SYNC
1058 if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
1059 ltemp = pps_offset;
1060 #endif /* PPS_SYNC */
1061
1062 /*
1063 * Scale the phase adjustment and clamp to the operating range.
1064 */
1065 if (ltemp > MAXPHASE)
1066 time_offset = MAXPHASE << SHIFT_UPDATE;
1067 else if (ltemp < -MAXPHASE)
1068 time_offset = -(MAXPHASE << SHIFT_UPDATE);
1069 else
1070 time_offset = ltemp << SHIFT_UPDATE;
1071
1072 /*
1073 * Select whether the frequency is to be controlled and in which
1074 * mode (PLL or FLL). Clamp to the operating range. Ugly
1075 * multiply/divide should be replaced someday.
1076 */
1077 if (time_status & STA_FREQHOLD || time_reftime == 0)
1078 time_reftime = time.tv_sec;
1079 mtemp = time.tv_sec - time_reftime;
1080 time_reftime = time.tv_sec;
1081 if (time_status & STA_FLL) {
1082 if (mtemp >= MINSEC) {
1083 ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
1084 SHIFT_UPDATE));
1085 if (ltemp < 0)
1086 time_freq -= -ltemp >> SHIFT_KH;
1087 else
1088 time_freq += ltemp >> SHIFT_KH;
1089 }
1090 } else {
1091 if (mtemp < MAXSEC) {
1092 ltemp *= mtemp;
1093 if (ltemp < 0)
1094 time_freq -= -ltemp >> (time_constant +
1095 time_constant + SHIFT_KF -
1096 SHIFT_USEC);
1097 else
1098 time_freq += ltemp >> (time_constant +
1099 time_constant + SHIFT_KF -
1100 SHIFT_USEC);
1101 }
1102 }
1103 if (time_freq > time_tolerance)
1104 time_freq = time_tolerance;
1105 else if (time_freq < -time_tolerance)
1106 time_freq = -time_tolerance;
1107 }
1108
1109 #ifdef PPS_SYNC
1110 /*
1111 * hardpps() - discipline CPU clock oscillator to external PPS signal
1112 *
1113 * This routine is called at each PPS interrupt in order to discipline
1114 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
1115 * and leaves it in a handy spot for the hardclock() routine. It
1116 * integrates successive PPS phase differences and calculates the
1117 * frequency offset. This is used in hardclock() to discipline the CPU
1118 * clock oscillator so that intrinsic frequency error is cancelled out.
1119 * The code requires the caller to capture the time and hardware counter
1120 * value at the on-time PPS signal transition.
1121 *
1122 * Note that, on some Unix systems, this routine runs at an interrupt
1123 * priority level higher than the timer interrupt routine hardclock().
1124 * Therefore, the variables used are distinct from the hardclock()
1125 * variables, except for certain exceptions: The PPS frequency pps_freq
1126 * and phase pps_offset variables are determined by this routine and
1127 * updated atomically. The time_tolerance variable can be considered a
1128 * constant, since it is infrequently changed, and then only when the
1129 * PPS signal is disabled. The watchdog counter pps_valid is updated
1130 * once per second by hardclock() and is atomically cleared in this
1131 * routine.
1132 */
1133 void
1134 hardpps(tvp, usec)
1135 struct timeval *tvp; /* time at PPS */
1136 long usec; /* hardware counter at PPS */
1137 {
1138 long u_usec, v_usec, bigtick;
1139 long cal_sec, cal_usec;
1140
1141 /*
1142 * An occasional glitch can be produced when the PPS interrupt
1143 * occurs in the hardclock() routine before the time variable is
1144 * updated. Here the offset is discarded when the difference
1145 * between it and the last one is greater than tick/2, but not
1146 * if the interval since the first discard exceeds 30 s.
1147 */
1148 time_status |= STA_PPSSIGNAL;
1149 time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1150 pps_valid = 0;
1151 u_usec = -tvp->tv_usec;
1152 if (u_usec < -500000)
1153 u_usec += 1000000;
1154 v_usec = pps_offset - u_usec;
1155 if (v_usec < 0)
1156 v_usec = -v_usec;
1157 if (v_usec > (tick >> 1)) {
1158 if (pps_glitch > MAXGLITCH) {
1159 pps_glitch = 0;
1160 pps_tf[2] = u_usec;
1161 pps_tf[1] = u_usec;
1162 } else {
1163 pps_glitch++;
1164 u_usec = pps_offset;
1165 }
1166 } else
1167 pps_glitch = 0;
1168
1169 /*
1170 * A three-stage median filter is used to help deglitch the pps
1171 * time. The median sample becomes the time offset estimate; the
1172 * difference between the other two samples becomes the time
1173 * dispersion (jitter) estimate.
1174 */
1175 pps_tf[2] = pps_tf[1];
1176 pps_tf[1] = pps_tf[0];
1177 pps_tf[0] = u_usec;
1178 if (pps_tf[0] > pps_tf[1]) {
1179 if (pps_tf[1] > pps_tf[2]) {
1180 pps_offset = pps_tf[1]; /* 0 1 2 */
1181 v_usec = pps_tf[0] - pps_tf[2];
1182 } else if (pps_tf[2] > pps_tf[0]) {
1183 pps_offset = pps_tf[0]; /* 2 0 1 */
1184 v_usec = pps_tf[2] - pps_tf[1];
1185 } else {
1186 pps_offset = pps_tf[2]; /* 0 2 1 */
1187 v_usec = pps_tf[0] - pps_tf[1];
1188 }
1189 } else {
1190 if (pps_tf[1] < pps_tf[2]) {
1191 pps_offset = pps_tf[1]; /* 2 1 0 */
1192 v_usec = pps_tf[2] - pps_tf[0];
1193 } else if (pps_tf[2] < pps_tf[0]) {
1194 pps_offset = pps_tf[0]; /* 1 0 2 */
1195 v_usec = pps_tf[1] - pps_tf[2];
1196 } else {
1197 pps_offset = pps_tf[2]; /* 1 2 0 */
1198 v_usec = pps_tf[1] - pps_tf[0];
1199 }
1200 }
1201 if (v_usec > MAXTIME)
1202 pps_jitcnt++;
1203 v_usec = (v_usec << PPS_AVG) - pps_jitter;
1204 if (v_usec < 0)
1205 pps_jitter -= -v_usec >> PPS_AVG;
1206 else
1207 pps_jitter += v_usec >> PPS_AVG;
1208 if (pps_jitter > (MAXTIME >> 1))
1209 time_status |= STA_PPSJITTER;
1210
1211 /*
1212 * During the calibration interval adjust the starting time when
1213 * the tick overflows. At the end of the interval compute the
1214 * duration of the interval and the difference of the hardware
1215 * counters at the beginning and end of the interval. This code
1216 * is deliciously complicated by the fact valid differences may
1217 * exceed the value of tick when using long calibration
1218 * intervals and small ticks. Note that the counter can be
1219 * greater than tick if caught at just the wrong instant, but
1220 * the values returned and used here are correct.
1221 */
1222 bigtick = (long)tick << SHIFT_USEC;
1223 pps_usec -= pps_freq;
1224 if (pps_usec >= bigtick)
1225 pps_usec -= bigtick;
1226 if (pps_usec < 0)
1227 pps_usec += bigtick;
1228 pps_time.tv_sec++;
1229 pps_count++;
1230 if (pps_count < (1 << pps_shift))
1231 return;
1232 pps_count = 0;
1233 pps_calcnt++;
1234 u_usec = usec << SHIFT_USEC;
1235 v_usec = pps_usec - u_usec;
1236 if (v_usec >= bigtick >> 1)
1237 v_usec -= bigtick;
1238 if (v_usec < -(bigtick >> 1))
1239 v_usec += bigtick;
1240 if (v_usec < 0)
1241 v_usec = -(-v_usec >> pps_shift);
1242 else
1243 v_usec = v_usec >> pps_shift;
1244 pps_usec = u_usec;
1245 cal_sec = tvp->tv_sec;
1246 cal_usec = tvp->tv_usec;
1247 cal_sec -= pps_time.tv_sec;
1248 cal_usec -= pps_time.tv_usec;
1249 if (cal_usec < 0) {
1250 cal_usec += 1000000;
1251 cal_sec--;
1252 }
1253 pps_time = *tvp;
1254
1255 /*
1256 * Check for lost interrupts, noise, excessive jitter and
1257 * excessive frequency error. The number of timer ticks during
1258 * the interval may vary +-1 tick. Add to this a margin of one
1259 * tick for the PPS signal jitter and maximum frequency
1260 * deviation. If the limits are exceeded, the calibration
1261 * interval is reset to the minimum and we start over.
1262 */
1263 u_usec = (long)tick << 1;
1264 if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
1265 || (cal_sec == 0 && cal_usec < u_usec))
1266 || v_usec > time_tolerance || v_usec < -time_tolerance) {
1267 pps_errcnt++;
1268 pps_shift = PPS_SHIFT;
1269 pps_intcnt = 0;
1270 time_status |= STA_PPSERROR;
1271 return;
1272 }
1273
1274 /*
1275 * A three-stage median filter is used to help deglitch the pps
1276 * frequency. The median sample becomes the frequency offset
1277 * estimate; the difference between the other two samples
1278 * becomes the frequency dispersion (stability) estimate.
1279 */
1280 pps_ff[2] = pps_ff[1];
1281 pps_ff[1] = pps_ff[0];
1282 pps_ff[0] = v_usec;
1283 if (pps_ff[0] > pps_ff[1]) {
1284 if (pps_ff[1] > pps_ff[2]) {
1285 u_usec = pps_ff[1]; /* 0 1 2 */
1286 v_usec = pps_ff[0] - pps_ff[2];
1287 } else if (pps_ff[2] > pps_ff[0]) {
1288 u_usec = pps_ff[0]; /* 2 0 1 */
1289 v_usec = pps_ff[2] - pps_ff[1];
1290 } else {
1291 u_usec = pps_ff[2]; /* 0 2 1 */
1292 v_usec = pps_ff[0] - pps_ff[1];
1293 }
1294 } else {
1295 if (pps_ff[1] < pps_ff[2]) {
1296 u_usec = pps_ff[1]; /* 2 1 0 */
1297 v_usec = pps_ff[2] - pps_ff[0];
1298 } else if (pps_ff[2] < pps_ff[0]) {
1299 u_usec = pps_ff[0]; /* 1 0 2 */
1300 v_usec = pps_ff[1] - pps_ff[2];
1301 } else {
1302 u_usec = pps_ff[2]; /* 1 2 0 */
1303 v_usec = pps_ff[1] - pps_ff[0];
1304 }
1305 }
1306
1307 /*
1308 * Here the frequency dispersion (stability) is updated. If it
1309 * is less than one-fourth the maximum (MAXFREQ), the frequency
1310 * offset is updated as well, but clamped to the tolerance. It
1311 * will be processed later by the hardclock() routine.
1312 */
1313 v_usec = (v_usec >> 1) - pps_stabil;
1314 if (v_usec < 0)
1315 pps_stabil -= -v_usec >> PPS_AVG;
1316 else
1317 pps_stabil += v_usec >> PPS_AVG;
1318 if (pps_stabil > MAXFREQ >> 2) {
1319 pps_stbcnt++;
1320 time_status |= STA_PPSWANDER;
1321 return;
1322 }
1323 if (time_status & STA_PPSFREQ) {
1324 if (u_usec < 0) {
1325 pps_freq -= -u_usec >> PPS_AVG;
1326 if (pps_freq < -time_tolerance)
1327 pps_freq = -time_tolerance;
1328 u_usec = -u_usec;
1329 } else {
1330 pps_freq += u_usec >> PPS_AVG;
1331 if (pps_freq > time_tolerance)
1332 pps_freq = time_tolerance;
1333 }
1334 }
1335
1336 /*
1337 * Here the calibration interval is adjusted. If the maximum
1338 * time difference is greater than tick / 4, reduce the interval
1339 * by half. If this is not the case for four consecutive
1340 * intervals, double the interval.
1341 */
1342 if (u_usec << pps_shift > bigtick >> 2) {
1343 pps_intcnt = 0;
1344 if (pps_shift > PPS_SHIFT)
1345 pps_shift--;
1346 } else if (pps_intcnt >= 4) {
1347 pps_intcnt = 0;
1348 if (pps_shift < PPS_SHIFTMAX)
1349 pps_shift++;
1350 } else
1351 pps_intcnt++;
1352 }
1353 #endif /* PPS_SYNC */
1354 #endif /* NTP */
1355
1356
1357 /*
1358 * Return information about system clocks.
1359 */
1360 int
1361 sysctl_clockrate(where, sizep)
1362 register char *where;
1363 size_t *sizep;
1364 {
1365 struct clockinfo clkinfo;
1366
1367 /*
1368 * Construct clockinfo structure.
1369 */
1370 clkinfo.tick = tick;
1371 clkinfo.tickadj = tickadj;
1372 clkinfo.hz = hz;
1373 clkinfo.profhz = profhz;
1374 clkinfo.stathz = stathz ? stathz : hz;
1375 return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
1376 }
1377
1378 #ifdef DDB
1379 #include <machine/db_machdep.h>
1380
1381 #include <ddb/db_interface.h>
1382 #include <ddb/db_access.h>
1383 #include <ddb/db_sym.h>
1384 #include <ddb/db_output.h>
1385
1386 void db_show_callout(addr, haddr, count, modif)
1387 db_expr_t addr;
1388 int haddr;
1389 db_expr_t count;
1390 char *modif;
1391 {
1392 register struct callout *p1;
1393 register int cum;
1394 register int s;
1395 db_expr_t offset;
1396 char *name;
1397
1398 db_printf(" cum ticks arg func\n");
1399 s = splhigh();
1400 for (cum = 0, p1 = calltodo.c_next; p1; p1 = p1->c_next) {
1401 register int t = p1->c_time;
1402
1403 if (t > 0)
1404 cum += t;
1405
1406 db_find_sym_and_offset((db_addr_t)p1->c_func, &name, &offset);
1407 if (name == NULL)
1408 name = "?";
1409
1410 db_printf("%9d %9d %8x %s (%x)\n",
1411 cum, t, p1->c_arg, name, p1->c_func);
1412 }
1413 splx(s);
1414 }
1415 #endif
1416