kern_clock.c revision 1.47.2.1 1 /* $NetBSD: kern_clock.c,v 1.47.2.1 1999/10/10 23:21:19 cgd 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 "opt_ntp.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/dkstat.h>
48 #include <sys/callout.h>
49 #include <sys/kernel.h>
50 #include <sys/proc.h>
51 #include <sys/resourcevar.h>
52 #include <sys/signalvar.h>
53 #include <vm/vm.h>
54 #include <sys/sysctl.h>
55 #include <sys/timex.h>
56 #include <sys/sched.h>
57
58 #include <machine/cpu.h>
59
60 #ifdef GPROF
61 #include <sys/gmon.h>
62 #endif
63
64 /*
65 * Clock handling routines.
66 *
67 * This code is written to operate with two timers that run independently of
68 * each other. The main clock, running hz times per second, is used to keep
69 * track of real time. The second timer handles kernel and user profiling,
70 * and does resource use estimation. If the second timer is programmable,
71 * it is randomized to avoid aliasing between the two clocks. For example,
72 * the randomization prevents an adversary from always giving up the cpu
73 * just before its quantum expires. Otherwise, it would never accumulate
74 * cpu ticks. The mean frequency of the second timer is stathz.
75 *
76 * If no second timer exists, stathz will be zero; in this case we drive
77 * profiling and statistics off the main clock. This WILL NOT be accurate;
78 * do not do it unless absolutely necessary.
79 *
80 * The statistics clock may (or may not) be run at a higher rate while
81 * profiling. This profile clock runs at profhz. We require that profhz
82 * be an integral multiple of stathz.
83 *
84 * If the statistics clock is running fast, it must be divided by the ratio
85 * profhz/stathz for statistics. (For profiling, every tick counts.)
86 */
87
88 /*
89 * TODO:
90 * allocate more timeout table slots when table overflows.
91 */
92
93
94 #ifdef NTP /* NTP phase-locked loop in kernel */
95 /*
96 * Phase/frequency-lock loop (PLL/FLL) definitions
97 *
98 * The following variables are read and set by the ntp_adjtime() system
99 * call.
100 *
101 * time_state shows the state of the system clock, with values defined
102 * in the timex.h header file.
103 *
104 * time_status shows the status of the system clock, with bits defined
105 * in the timex.h header file.
106 *
107 * time_offset is used by the PLL/FLL to adjust the system time in small
108 * increments.
109 *
110 * time_constant determines the bandwidth or "stiffness" of the PLL.
111 *
112 * time_tolerance determines maximum frequency error or tolerance of the
113 * CPU clock oscillator and is a property of the architecture; however,
114 * in principle it could change as result of the presence of external
115 * discipline signals, for instance.
116 *
117 * time_precision is usually equal to the kernel tick variable; however,
118 * in cases where a precision clock counter or external clock is
119 * available, the resolution can be much less than this and depend on
120 * whether the external clock is working or not.
121 *
122 * time_maxerror is initialized by a ntp_adjtime() call and increased by
123 * the kernel once each second to reflect the maximum error bound
124 * growth.
125 *
126 * time_esterror is set and read by the ntp_adjtime() call, but
127 * otherwise not used by the kernel.
128 */
129 int time_state = TIME_OK; /* clock state */
130 int time_status = STA_UNSYNC; /* clock status bits */
131 long time_offset = 0; /* time offset (us) */
132 long time_constant = 0; /* pll time constant */
133 long time_tolerance = MAXFREQ; /* frequency tolerance (scaled ppm) */
134 long time_precision = 1; /* clock precision (us) */
135 long time_maxerror = MAXPHASE; /* maximum error (us) */
136 long time_esterror = MAXPHASE; /* estimated error (us) */
137
138 /*
139 * The following variables establish the state of the PLL/FLL and the
140 * residual time and frequency offset of the local clock. The scale
141 * factors are defined in the timex.h header file.
142 *
143 * time_phase and time_freq are the phase increment and the frequency
144 * increment, respectively, of the kernel time variable.
145 *
146 * time_freq is set via ntp_adjtime() from a value stored in a file when
147 * the synchronization daemon is first started. Its value is retrieved
148 * via ntp_adjtime() and written to the file about once per hour by the
149 * daemon.
150 *
151 * time_adj is the adjustment added to the value of tick at each timer
152 * interrupt and is recomputed from time_phase and time_freq at each
153 * seconds rollover.
154 *
155 * time_reftime is the second's portion of the system time at the last
156 * call to ntp_adjtime(). It is used to adjust the time_freq variable
157 * and to increase the time_maxerror as the time since last update
158 * increases.
159 */
160 long time_phase = 0; /* phase offset (scaled us) */
161 long time_freq = 0; /* frequency offset (scaled ppm) */
162 long time_adj = 0; /* tick adjust (scaled 1 / hz) */
163 long time_reftime = 0; /* time at last adjustment (s) */
164
165 #ifdef PPS_SYNC
166 /*
167 * The following variables are used only if the kernel PPS discipline
168 * code is configured (PPS_SYNC). The scale factors are defined in the
169 * timex.h header file.
170 *
171 * pps_time contains the time at each calibration interval, as read by
172 * microtime(). pps_count counts the seconds of the calibration
173 * interval, the duration of which is nominally pps_shift in powers of
174 * two.
175 *
176 * pps_offset is the time offset produced by the time median filter
177 * pps_tf[], while pps_jitter is the dispersion (jitter) measured by
178 * this filter.
179 *
180 * pps_freq is the frequency offset produced by the frequency median
181 * filter pps_ff[], while pps_stabil is the dispersion (wander) measured
182 * by this filter.
183 *
184 * pps_usec is latched from a high resolution counter or external clock
185 * at pps_time. Here we want the hardware counter contents only, not the
186 * contents plus the time_tv.usec as usual.
187 *
188 * pps_valid counts the number of seconds since the last PPS update. It
189 * is used as a watchdog timer to disable the PPS discipline should the
190 * PPS signal be lost.
191 *
192 * pps_glitch counts the number of seconds since the beginning of an
193 * offset burst more than tick/2 from current nominal offset. It is used
194 * mainly to suppress error bursts due to priority conflicts between the
195 * PPS interrupt and timer interrupt.
196 *
197 * pps_intcnt counts the calibration intervals for use in the interval-
198 * adaptation algorithm. It's just too complicated for words.
199 */
200 struct timeval pps_time; /* kernel time at last interval */
201 long pps_tf[] = {0, 0, 0}; /* pps time offset median filter (us) */
202 long pps_offset = 0; /* pps time offset (us) */
203 long pps_jitter = MAXTIME; /* time dispersion (jitter) (us) */
204 long pps_ff[] = {0, 0, 0}; /* pps frequency offset median filter */
205 long pps_freq = 0; /* frequency offset (scaled ppm) */
206 long pps_stabil = MAXFREQ; /* frequency dispersion (scaled ppm) */
207 long pps_usec = 0; /* microsec counter at last interval */
208 long pps_valid = PPS_VALID; /* pps signal watchdog counter */
209 int pps_glitch = 0; /* pps signal glitch counter */
210 int pps_count = 0; /* calibration interval counter (s) */
211 int pps_shift = PPS_SHIFT; /* interval duration (s) (shift) */
212 int pps_intcnt = 0; /* intervals at current duration */
213
214 /*
215 * PPS signal quality monitors
216 *
217 * pps_jitcnt counts the seconds that have been discarded because the
218 * jitter measured by the time median filter exceeds the limit MAXTIME
219 * (100 us).
220 *
221 * pps_calcnt counts the frequency calibration intervals, which are
222 * variable from 4 s to 256 s.
223 *
224 * pps_errcnt counts the calibration intervals which have been discarded
225 * because the wander exceeds the limit MAXFREQ (100 ppm) or where the
226 * calibration interval jitter exceeds two ticks.
227 *
228 * pps_stbcnt counts the calibration intervals that have been discarded
229 * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us).
230 */
231 long pps_jitcnt = 0; /* jitter limit exceeded */
232 long pps_calcnt = 0; /* calibration intervals */
233 long pps_errcnt = 0; /* calibration errors */
234 long pps_stbcnt = 0; /* stability limit exceeded */
235 #endif /* PPS_SYNC */
236
237 #ifdef EXT_CLOCK
238 /*
239 * External clock definitions
240 *
241 * The following definitions and declarations are used only if an
242 * external clock is configured on the system.
243 */
244 #define CLOCK_INTERVAL 30 /* CPU clock update interval (s) */
245
246 /*
247 * The clock_count variable is set to CLOCK_INTERVAL at each PPS
248 * interrupt and decremented once each second.
249 */
250 int clock_count = 0; /* CPU clock counter */
251
252 #ifdef HIGHBALL
253 /*
254 * The clock_offset and clock_cpu variables are used by the HIGHBALL
255 * interface. The clock_offset variable defines the offset between
256 * system time and the HIGBALL counters. The clock_cpu variable contains
257 * the offset between the system clock and the HIGHBALL clock for use in
258 * disciplining the kernel time variable.
259 */
260 extern struct timeval clock_offset; /* Highball clock offset */
261 long clock_cpu = 0; /* CPU clock adjust */
262 #endif /* HIGHBALL */
263 #endif /* EXT_CLOCK */
264 #endif /* NTP */
265
266
267 /*
268 * Bump a timeval by a small number of usec's.
269 */
270 #define BUMPTIME(t, usec) { \
271 register volatile struct timeval *tp = (t); \
272 register long us; \
273 \
274 tp->tv_usec = us = tp->tv_usec + (usec); \
275 if (us >= 1000000) { \
276 tp->tv_usec = us - 1000000; \
277 tp->tv_sec++; \
278 } \
279 }
280
281 int stathz;
282 int profhz;
283 int profprocs;
284 int ticks;
285 static int psdiv, pscnt; /* prof => stat divider */
286 int psratio; /* ratio: prof / stat */
287 int tickfix, tickfixinterval; /* used if tick not really integral */
288 #ifndef NTP
289 static int tickfixcnt; /* accumulated fractional error */
290 #else
291 int fixtick; /* used by NTP for same */
292 int shifthz;
293 #endif
294
295 volatile struct timeval time;
296 volatile struct timeval mono_time;
297
298 /*
299 * Initialize clock frequencies and start both clocks running.
300 */
301 void
302 initclocks()
303 {
304 register int i;
305
306 /*
307 * Set divisors to 1 (normal case) and let the machine-specific
308 * code do its bit.
309 */
310 psdiv = pscnt = 1;
311 cpu_initclocks();
312
313 /*
314 * Compute profhz/stathz, and fix profhz if needed.
315 */
316 i = stathz ? stathz : hz;
317 if (profhz == 0)
318 profhz = i;
319 psratio = profhz / i;
320
321 #ifdef NTP
322 switch (hz) {
323 case 60:
324 case 64:
325 shifthz = SHIFT_SCALE - 6;
326 break;
327 case 96:
328 case 100:
329 case 128:
330 shifthz = SHIFT_SCALE - 7;
331 break;
332 case 256:
333 shifthz = SHIFT_SCALE - 8;
334 break;
335 case 512:
336 shifthz = SHIFT_SCALE - 9;
337 break;
338 case 1000:
339 case 1024:
340 shifthz = SHIFT_SCALE - 10;
341 break;
342 default:
343 panic("weird hz");
344 }
345 if (fixtick == 0) {
346 /* give MD code a chance to set this to a better value; but, if it doesn't, we should.. */
347 fixtick = (1000000 - (hz*tick));
348 }
349 #endif
350 }
351
352 /*
353 * The real-time timer, interrupting hz times per second.
354 */
355 void
356 hardclock(frame)
357 register struct clockframe *frame;
358 {
359 register struct callout *p1;
360 register struct proc *p;
361 register int delta, needsoft;
362 extern int tickdelta;
363 extern long timedelta;
364 #ifdef NTP
365 register int time_update;
366 register int ltemp;
367 #endif
368
369 /*
370 * Update real-time timeout queue.
371 * At front of queue are some number of events which are ``due''.
372 * The time to these is <= 0 and if negative represents the
373 * number of ticks which have passed since it was supposed to happen.
374 * The rest of the q elements (times > 0) are events yet to happen,
375 * where the time for each is given as a delta from the previous.
376 * Decrementing just the first of these serves to decrement the time
377 * to all events.
378 */
379 needsoft = 0;
380 for (p1 = calltodo.c_next; p1 != NULL; p1 = p1->c_next) {
381 if (--p1->c_time > 0)
382 break;
383 needsoft = 1;
384 if (p1->c_time == 0)
385 break;
386 }
387
388 p = curproc;
389 if (p) {
390 register struct pstats *pstats;
391
392 /*
393 * Run current process's virtual and profile time, as needed.
394 */
395 pstats = p->p_stats;
396 if (CLKF_USERMODE(frame) &&
397 timerisset(&pstats->p_timer[ITIMER_VIRTUAL].it_value) &&
398 itimerdecr(&pstats->p_timer[ITIMER_VIRTUAL], tick) == 0)
399 psignal(p, SIGVTALRM);
400 if (timerisset(&pstats->p_timer[ITIMER_PROF].it_value) &&
401 itimerdecr(&pstats->p_timer[ITIMER_PROF], tick) == 0)
402 psignal(p, SIGPROF);
403 }
404
405 /*
406 * If no separate statistics clock is available, run it from here.
407 */
408 if (stathz == 0)
409 statclock(frame);
410
411 /*
412 * Increment the time-of-day. The increment is normally just
413 * ``tick''. If the machine is one which has a clock frequency
414 * such that ``hz'' would not divide the second evenly into
415 * milliseconds, a periodic adjustment must be applied. Finally,
416 * if we are still adjusting the time (see adjtime()),
417 * ``tickdelta'' may also be added in.
418 */
419 ticks++;
420 delta = tick;
421
422 #ifndef NTP
423 if (tickfix) {
424 tickfixcnt += tickfix;
425 if (tickfixcnt >= tickfixinterval) {
426 delta++;
427 tickfixcnt -= tickfixinterval;
428 }
429 }
430 #endif /* !NTP */
431 /* Imprecise 4bsd adjtime() handling */
432 if (timedelta != 0) {
433 delta += tickdelta;
434 timedelta -= tickdelta;
435 }
436
437 #ifdef notyet
438 microset();
439 #endif
440
441 #ifndef NTP
442 BUMPTIME(&time, delta); /* XXX Now done using NTP code below */
443 #endif
444 BUMPTIME(&mono_time, delta);
445
446 #ifdef NTP
447 time_update = delta;
448
449 /*
450 * Compute the phase adjustment. If the low-order bits
451 * (time_phase) of the update overflow, bump the high-order bits
452 * (time_update).
453 */
454 time_phase += time_adj;
455 if (time_phase <= -FINEUSEC) {
456 ltemp = -time_phase >> SHIFT_SCALE;
457 time_phase += ltemp << SHIFT_SCALE;
458 time_update -= ltemp;
459 } else if (time_phase >= FINEUSEC) {
460 ltemp = time_phase >> SHIFT_SCALE;
461 time_phase -= ltemp << SHIFT_SCALE;
462 time_update += ltemp;
463 }
464
465 #ifdef HIGHBALL
466 /*
467 * If the HIGHBALL board is installed, we need to adjust the
468 * external clock offset in order to close the hardware feedback
469 * loop. This will adjust the external clock phase and frequency
470 * in small amounts. The additional phase noise and frequency
471 * wander this causes should be minimal. We also need to
472 * discipline the kernel time variable, since the PLL is used to
473 * discipline the external clock. If the Highball board is not
474 * present, we discipline kernel time with the PLL as usual. We
475 * assume that the external clock phase adjustment (time_update)
476 * and kernel phase adjustment (clock_cpu) are less than the
477 * value of tick.
478 */
479 clock_offset.tv_usec += time_update;
480 if (clock_offset.tv_usec >= 1000000) {
481 clock_offset.tv_sec++;
482 clock_offset.tv_usec -= 1000000;
483 }
484 if (clock_offset.tv_usec < 0) {
485 clock_offset.tv_sec--;
486 clock_offset.tv_usec += 1000000;
487 }
488 time.tv_usec += clock_cpu;
489 clock_cpu = 0;
490 #else
491 time.tv_usec += time_update;
492 #endif /* HIGHBALL */
493
494 /*
495 * On rollover of the second the phase adjustment to be used for
496 * the next second is calculated. Also, the maximum error is
497 * increased by the tolerance. If the PPS frequency discipline
498 * code is present, the phase is increased to compensate for the
499 * CPU clock oscillator frequency error.
500 *
501 * On a 32-bit machine and given parameters in the timex.h
502 * header file, the maximum phase adjustment is +-512 ms and
503 * maximum frequency offset is a tad less than) +-512 ppm. On a
504 * 64-bit machine, you shouldn't need to ask.
505 */
506 if (time.tv_usec >= 1000000) {
507 time.tv_usec -= 1000000;
508 time.tv_sec++;
509 time_maxerror += time_tolerance >> SHIFT_USEC;
510
511 /*
512 * Leap second processing. If in leap-insert state at
513 * the end of the day, the system clock is set back one
514 * second; if in leap-delete state, the system clock is
515 * set ahead one second. The microtime() routine or
516 * external clock driver will insure that reported time
517 * is always monotonic. The ugly divides should be
518 * replaced.
519 */
520 switch (time_state) {
521 case TIME_OK:
522 if (time_status & STA_INS)
523 time_state = TIME_INS;
524 else if (time_status & STA_DEL)
525 time_state = TIME_DEL;
526 break;
527
528 case TIME_INS:
529 if (time.tv_sec % 86400 == 0) {
530 time.tv_sec--;
531 time_state = TIME_OOP;
532 }
533 break;
534
535 case TIME_DEL:
536 if ((time.tv_sec + 1) % 86400 == 0) {
537 time.tv_sec++;
538 time_state = TIME_WAIT;
539 }
540 break;
541
542 case TIME_OOP:
543 time_state = TIME_WAIT;
544 break;
545
546 case TIME_WAIT:
547 if (!(time_status & (STA_INS | STA_DEL)))
548 time_state = TIME_OK;
549 break;
550 }
551
552 /*
553 * Compute the phase adjustment for the next second. In
554 * PLL mode, the offset is reduced by a fixed factor
555 * times the time constant. In FLL mode the offset is
556 * used directly. In either mode, the maximum phase
557 * adjustment for each second is clamped so as to spread
558 * the adjustment over not more than the number of
559 * seconds between updates.
560 */
561 if (time_offset < 0) {
562 ltemp = -time_offset;
563 if (!(time_status & STA_FLL))
564 ltemp >>= SHIFT_KG + time_constant;
565 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
566 ltemp = (MAXPHASE / MINSEC) <<
567 SHIFT_UPDATE;
568 time_offset += ltemp;
569 time_adj = -ltemp << (shifthz - SHIFT_UPDATE);
570 } else if (time_offset > 0) {
571 ltemp = time_offset;
572 if (!(time_status & STA_FLL))
573 ltemp >>= SHIFT_KG + time_constant;
574 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
575 ltemp = (MAXPHASE / MINSEC) <<
576 SHIFT_UPDATE;
577 time_offset -= ltemp;
578 time_adj = ltemp << (shifthz - SHIFT_UPDATE);
579 } else
580 time_adj = 0;
581
582 /*
583 * Compute the frequency estimate and additional phase
584 * adjustment due to frequency error for the next
585 * second. When the PPS signal is engaged, gnaw on the
586 * watchdog counter and update the frequency computed by
587 * the pll and the PPS signal.
588 */
589 #ifdef PPS_SYNC
590 pps_valid++;
591 if (pps_valid == PPS_VALID) {
592 pps_jitter = MAXTIME;
593 pps_stabil = MAXFREQ;
594 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
595 STA_PPSWANDER | STA_PPSERROR);
596 }
597 ltemp = time_freq + pps_freq;
598 #else
599 ltemp = time_freq;
600 #endif /* PPS_SYNC */
601
602 if (ltemp < 0)
603 time_adj -= -ltemp >> (SHIFT_USEC - shifthz);
604 else
605 time_adj += ltemp >> (SHIFT_USEC - shifthz);
606 time_adj += (long)fixtick << shifthz;
607
608 /*
609 * When the CPU clock oscillator frequency is not a
610 * power of 2 in Hz, shifthz is only an approximate
611 * scale factor.
612 *
613 * To determine the adjustment, you can do the following:
614 * bc -q
615 * scale=24
616 * obase=2
617 * idealhz/realhz
618 * where `idealhz' is the next higher power of 2, and `realhz'
619 * is the actual value.
620 *
621 * Likewise, the error can be calculated with (e.g. for 100Hz):
622 * bc -q
623 * scale=24
624 * ((1+2^-2+2^-5)*realhz-idealhz)/idealhz
625 * (and then multiply by 100 to get %).
626 */
627 switch (hz) {
628 case 96:
629 /* A factor of 1.0101010101 gives about .025% error. */
630 if (time_adj < 0) {
631 time_adj -= (-time_adj >> 2);
632 time_adj -= (-time_adj >> 4) + (-time_adj >> 8);
633 } else {
634 time_adj += (time_adj >> 2);
635 time_adj += (time_adj >> 4) + (time_adj >> 8);
636 }
637 break;
638
639 case 100:
640 /* A factor of 1.01001 gives about .1% error. */
641 if (time_adj < 0)
642 time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
643 else
644 time_adj += (time_adj >> 2) + (time_adj >> 5);
645 break;
646
647 case 60:
648 /* A factor of 1.00010001 gives about .025% error. */
649 if (time_adj < 0)
650 time_adj -= (-time_adj >> 4) + (-time_adj >> 8);
651 else
652 time_adj += (time_adj >> 4) + (time_adj >> 8);
653 break;
654
655 case 1000:
656 /* A factor of 1.0000011 gives about .055% error. */
657 if (time_adj < 0)
658 time_adj -= (-time_adj >> 6) + (-time_adj >> 7);
659 else
660 time_adj += (time_adj >> 6) + (time_adj >> 7);
661 break;
662 }
663
664 #ifdef EXT_CLOCK
665 /*
666 * If an external clock is present, it is necessary to
667 * discipline the kernel time variable anyway, since not
668 * all system components use the microtime() interface.
669 * Here, the time offset between the external clock and
670 * kernel time variable is computed every so often.
671 */
672 clock_count++;
673 if (clock_count > CLOCK_INTERVAL) {
674 clock_count = 0;
675 microtime(&clock_ext);
676 delta.tv_sec = clock_ext.tv_sec - time.tv_sec;
677 delta.tv_usec = clock_ext.tv_usec -
678 time.tv_usec;
679 if (delta.tv_usec < 0)
680 delta.tv_sec--;
681 if (delta.tv_usec >= 500000) {
682 delta.tv_usec -= 1000000;
683 delta.tv_sec++;
684 }
685 if (delta.tv_usec < -500000) {
686 delta.tv_usec += 1000000;
687 delta.tv_sec--;
688 }
689 if (delta.tv_sec > 0 || (delta.tv_sec == 0 &&
690 delta.tv_usec > MAXPHASE) ||
691 delta.tv_sec < -1 || (delta.tv_sec == -1 &&
692 delta.tv_usec < -MAXPHASE)) {
693 time = clock_ext;
694 delta.tv_sec = 0;
695 delta.tv_usec = 0;
696 }
697 #ifdef HIGHBALL
698 clock_cpu = delta.tv_usec;
699 #else /* HIGHBALL */
700 hardupdate(delta.tv_usec);
701 #endif /* HIGHBALL */
702 }
703 #endif /* EXT_CLOCK */
704 }
705
706 #endif /* NTP */
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 = splclock();
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 register int i;
925 #endif
926 static int schedclk;
927 register struct proc *p;
928
929 if (CLKF_USERMODE(frame)) {
930 p = curproc;
931 if (p->p_flag & P_PROFIL)
932 addupc_intr(p, CLKF_PC(frame), 1);
933 if (--pscnt > 0)
934 return;
935 /*
936 * Came from user mode; CPU was in user state.
937 * If this process is being profiled record the tick.
938 */
939 p->p_uticks++;
940 if (p->p_nice > NZERO)
941 cp_time[CP_NICE]++;
942 else
943 cp_time[CP_USER]++;
944 } else {
945 #ifdef GPROF
946 /*
947 * Kernel statistics are just like addupc_intr, only easier.
948 */
949 g = &_gmonparam;
950 if (g->state == GMON_PROF_ON) {
951 i = CLKF_PC(frame) - g->lowpc;
952 if (i < g->textsize) {
953 i /= HISTFRACTION * sizeof(*g->kcount);
954 g->kcount[i]++;
955 }
956 }
957 #endif
958 if (--pscnt > 0)
959 return;
960 /*
961 * Came from kernel mode, so we were:
962 * - handling an interrupt,
963 * - doing syscall or trap work on behalf of the current
964 * user process, or
965 * - spinning in the idle loop.
966 * Whichever it is, charge the time as appropriate.
967 * Note that we charge interrupts to the current process,
968 * regardless of whether they are ``for'' that process,
969 * so that we know how much of its real time was spent
970 * in ``non-process'' (i.e., interrupt) work.
971 */
972 p = curproc;
973 if (CLKF_INTR(frame)) {
974 if (p != NULL)
975 p->p_iticks++;
976 cp_time[CP_INTR]++;
977 } else if (p != NULL) {
978 p->p_sticks++;
979 cp_time[CP_SYS]++;
980 } else
981 cp_time[CP_IDLE]++;
982 }
983 pscnt = psdiv;
984
985 if (p != NULL) {
986 ++p->p_cpticks;
987 /*
988 * If no schedclock is provided, call it here at ~~12-25 Hz,
989 * ~~16 Hz is best
990 */
991 if(schedhz == 0)
992 if ((++schedclk & 3) == 0)
993 schedclock(p);
994 }
995 }
996
997
998 #ifdef NTP /* NTP phase-locked loop in kernel */
999
1000 /*
1001 * hardupdate() - local clock update
1002 *
1003 * This routine is called by ntp_adjtime() to update the local clock
1004 * phase and frequency. The implementation is of an adaptive-parameter,
1005 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
1006 * time and frequency offset estimates for each call. If the kernel PPS
1007 * discipline code is configured (PPS_SYNC), the PPS signal itself
1008 * determines the new time offset, instead of the calling argument.
1009 * Presumably, calls to ntp_adjtime() occur only when the caller
1010 * believes the local clock is valid within some bound (+-128 ms with
1011 * NTP). If the caller's time is far different than the PPS time, an
1012 * argument will ensue, and it's not clear who will lose.
1013 *
1014 * For uncompensated quartz crystal oscillatores and nominal update
1015 * intervals less than 1024 s, operation should be in phase-lock mode
1016 * (STA_FLL = 0), where the loop is disciplined to phase. For update
1017 * intervals greater than thiss, operation should be in frequency-lock
1018 * mode (STA_FLL = 1), where the loop is disciplined to frequency.
1019 *
1020 * Note: splclock() is in effect.
1021 */
1022 void
1023 hardupdate(offset)
1024 long offset;
1025 {
1026 long ltemp, mtemp;
1027
1028 if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
1029 return;
1030 ltemp = offset;
1031 #ifdef PPS_SYNC
1032 if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
1033 ltemp = pps_offset;
1034 #endif /* PPS_SYNC */
1035
1036 /*
1037 * Scale the phase adjustment and clamp to the operating range.
1038 */
1039 if (ltemp > MAXPHASE)
1040 time_offset = MAXPHASE << SHIFT_UPDATE;
1041 else if (ltemp < -MAXPHASE)
1042 time_offset = -(MAXPHASE << SHIFT_UPDATE);
1043 else
1044 time_offset = ltemp << SHIFT_UPDATE;
1045
1046 /*
1047 * Select whether the frequency is to be controlled and in which
1048 * mode (PLL or FLL). Clamp to the operating range. Ugly
1049 * multiply/divide should be replaced someday.
1050 */
1051 if (time_status & STA_FREQHOLD || time_reftime == 0)
1052 time_reftime = time.tv_sec;
1053 mtemp = time.tv_sec - time_reftime;
1054 time_reftime = time.tv_sec;
1055 if (time_status & STA_FLL) {
1056 if (mtemp >= MINSEC) {
1057 ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
1058 SHIFT_UPDATE));
1059 if (ltemp < 0)
1060 time_freq -= -ltemp >> SHIFT_KH;
1061 else
1062 time_freq += ltemp >> SHIFT_KH;
1063 }
1064 } else {
1065 if (mtemp < MAXSEC) {
1066 ltemp *= mtemp;
1067 if (ltemp < 0)
1068 time_freq -= -ltemp >> (time_constant +
1069 time_constant + SHIFT_KF -
1070 SHIFT_USEC);
1071 else
1072 time_freq += ltemp >> (time_constant +
1073 time_constant + SHIFT_KF -
1074 SHIFT_USEC);
1075 }
1076 }
1077 if (time_freq > time_tolerance)
1078 time_freq = time_tolerance;
1079 else if (time_freq < -time_tolerance)
1080 time_freq = -time_tolerance;
1081 }
1082
1083 #ifdef PPS_SYNC
1084 /*
1085 * hardpps() - discipline CPU clock oscillator to external PPS signal
1086 *
1087 * This routine is called at each PPS interrupt in order to discipline
1088 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
1089 * and leaves it in a handy spot for the hardclock() routine. It
1090 * integrates successive PPS phase differences and calculates the
1091 * frequency offset. This is used in hardclock() to discipline the CPU
1092 * clock oscillator so that intrinsic frequency error is cancelled out.
1093 * The code requires the caller to capture the time and hardware counter
1094 * value at the on-time PPS signal transition.
1095 *
1096 * Note that, on some Unix systems, this routine runs at an interrupt
1097 * priority level higher than the timer interrupt routine hardclock().
1098 * Therefore, the variables used are distinct from the hardclock()
1099 * variables, except for certain exceptions: The PPS frequency pps_freq
1100 * and phase pps_offset variables are determined by this routine and
1101 * updated atomically. The time_tolerance variable can be considered a
1102 * constant, since it is infrequently changed, and then only when the
1103 * PPS signal is disabled. The watchdog counter pps_valid is updated
1104 * once per second by hardclock() and is atomically cleared in this
1105 * routine.
1106 */
1107 void
1108 hardpps(tvp, usec)
1109 struct timeval *tvp; /* time at PPS */
1110 long usec; /* hardware counter at PPS */
1111 {
1112 long u_usec, v_usec, bigtick;
1113 long cal_sec, cal_usec;
1114
1115 /*
1116 * An occasional glitch can be produced when the PPS interrupt
1117 * occurs in the hardclock() routine before the time variable is
1118 * updated. Here the offset is discarded when the difference
1119 * between it and the last one is greater than tick/2, but not
1120 * if the interval since the first discard exceeds 30 s.
1121 */
1122 time_status |= STA_PPSSIGNAL;
1123 time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1124 pps_valid = 0;
1125 u_usec = -tvp->tv_usec;
1126 if (u_usec < -500000)
1127 u_usec += 1000000;
1128 v_usec = pps_offset - u_usec;
1129 if (v_usec < 0)
1130 v_usec = -v_usec;
1131 if (v_usec > (tick >> 1)) {
1132 if (pps_glitch > MAXGLITCH) {
1133 pps_glitch = 0;
1134 pps_tf[2] = u_usec;
1135 pps_tf[1] = u_usec;
1136 } else {
1137 pps_glitch++;
1138 u_usec = pps_offset;
1139 }
1140 } else
1141 pps_glitch = 0;
1142
1143 /*
1144 * A three-stage median filter is used to help deglitch the pps
1145 * time. The median sample becomes the time offset estimate; the
1146 * difference between the other two samples becomes the time
1147 * dispersion (jitter) estimate.
1148 */
1149 pps_tf[2] = pps_tf[1];
1150 pps_tf[1] = pps_tf[0];
1151 pps_tf[0] = u_usec;
1152 if (pps_tf[0] > pps_tf[1]) {
1153 if (pps_tf[1] > pps_tf[2]) {
1154 pps_offset = pps_tf[1]; /* 0 1 2 */
1155 v_usec = pps_tf[0] - pps_tf[2];
1156 } else if (pps_tf[2] > pps_tf[0]) {
1157 pps_offset = pps_tf[0]; /* 2 0 1 */
1158 v_usec = pps_tf[2] - pps_tf[1];
1159 } else {
1160 pps_offset = pps_tf[2]; /* 0 2 1 */
1161 v_usec = pps_tf[0] - pps_tf[1];
1162 }
1163 } else {
1164 if (pps_tf[1] < pps_tf[2]) {
1165 pps_offset = pps_tf[1]; /* 2 1 0 */
1166 v_usec = pps_tf[2] - pps_tf[0];
1167 } else if (pps_tf[2] < pps_tf[0]) {
1168 pps_offset = pps_tf[0]; /* 1 0 2 */
1169 v_usec = pps_tf[1] - pps_tf[2];
1170 } else {
1171 pps_offset = pps_tf[2]; /* 1 2 0 */
1172 v_usec = pps_tf[1] - pps_tf[0];
1173 }
1174 }
1175 if (v_usec > MAXTIME)
1176 pps_jitcnt++;
1177 v_usec = (v_usec << PPS_AVG) - pps_jitter;
1178 if (v_usec < 0)
1179 pps_jitter -= -v_usec >> PPS_AVG;
1180 else
1181 pps_jitter += v_usec >> PPS_AVG;
1182 if (pps_jitter > (MAXTIME >> 1))
1183 time_status |= STA_PPSJITTER;
1184
1185 /*
1186 * During the calibration interval adjust the starting time when
1187 * the tick overflows. At the end of the interval compute the
1188 * duration of the interval and the difference of the hardware
1189 * counters at the beginning and end of the interval. This code
1190 * is deliciously complicated by the fact valid differences may
1191 * exceed the value of tick when using long calibration
1192 * intervals and small ticks. Note that the counter can be
1193 * greater than tick if caught at just the wrong instant, but
1194 * the values returned and used here are correct.
1195 */
1196 bigtick = (long)tick << SHIFT_USEC;
1197 pps_usec -= pps_freq;
1198 if (pps_usec >= bigtick)
1199 pps_usec -= bigtick;
1200 if (pps_usec < 0)
1201 pps_usec += bigtick;
1202 pps_time.tv_sec++;
1203 pps_count++;
1204 if (pps_count < (1 << pps_shift))
1205 return;
1206 pps_count = 0;
1207 pps_calcnt++;
1208 u_usec = usec << SHIFT_USEC;
1209 v_usec = pps_usec - u_usec;
1210 if (v_usec >= bigtick >> 1)
1211 v_usec -= bigtick;
1212 if (v_usec < -(bigtick >> 1))
1213 v_usec += bigtick;
1214 if (v_usec < 0)
1215 v_usec = -(-v_usec >> pps_shift);
1216 else
1217 v_usec = v_usec >> pps_shift;
1218 pps_usec = u_usec;
1219 cal_sec = tvp->tv_sec;
1220 cal_usec = tvp->tv_usec;
1221 cal_sec -= pps_time.tv_sec;
1222 cal_usec -= pps_time.tv_usec;
1223 if (cal_usec < 0) {
1224 cal_usec += 1000000;
1225 cal_sec--;
1226 }
1227 pps_time = *tvp;
1228
1229 /*
1230 * Check for lost interrupts, noise, excessive jitter and
1231 * excessive frequency error. The number of timer ticks during
1232 * the interval may vary +-1 tick. Add to this a margin of one
1233 * tick for the PPS signal jitter and maximum frequency
1234 * deviation. If the limits are exceeded, the calibration
1235 * interval is reset to the minimum and we start over.
1236 */
1237 u_usec = (long)tick << 1;
1238 if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
1239 || (cal_sec == 0 && cal_usec < u_usec))
1240 || v_usec > time_tolerance || v_usec < -time_tolerance) {
1241 pps_errcnt++;
1242 pps_shift = PPS_SHIFT;
1243 pps_intcnt = 0;
1244 time_status |= STA_PPSERROR;
1245 return;
1246 }
1247
1248 /*
1249 * A three-stage median filter is used to help deglitch the pps
1250 * frequency. The median sample becomes the frequency offset
1251 * estimate; the difference between the other two samples
1252 * becomes the frequency dispersion (stability) estimate.
1253 */
1254 pps_ff[2] = pps_ff[1];
1255 pps_ff[1] = pps_ff[0];
1256 pps_ff[0] = v_usec;
1257 if (pps_ff[0] > pps_ff[1]) {
1258 if (pps_ff[1] > pps_ff[2]) {
1259 u_usec = pps_ff[1]; /* 0 1 2 */
1260 v_usec = pps_ff[0] - pps_ff[2];
1261 } else if (pps_ff[2] > pps_ff[0]) {
1262 u_usec = pps_ff[0]; /* 2 0 1 */
1263 v_usec = pps_ff[2] - pps_ff[1];
1264 } else {
1265 u_usec = pps_ff[2]; /* 0 2 1 */
1266 v_usec = pps_ff[0] - pps_ff[1];
1267 }
1268 } else {
1269 if (pps_ff[1] < pps_ff[2]) {
1270 u_usec = pps_ff[1]; /* 2 1 0 */
1271 v_usec = pps_ff[2] - pps_ff[0];
1272 } else if (pps_ff[2] < pps_ff[0]) {
1273 u_usec = pps_ff[0]; /* 1 0 2 */
1274 v_usec = pps_ff[1] - pps_ff[2];
1275 } else {
1276 u_usec = pps_ff[2]; /* 1 2 0 */
1277 v_usec = pps_ff[1] - pps_ff[0];
1278 }
1279 }
1280
1281 /*
1282 * Here the frequency dispersion (stability) is updated. If it
1283 * is less than one-fourth the maximum (MAXFREQ), the frequency
1284 * offset is updated as well, but clamped to the tolerance. It
1285 * will be processed later by the hardclock() routine.
1286 */
1287 v_usec = (v_usec >> 1) - pps_stabil;
1288 if (v_usec < 0)
1289 pps_stabil -= -v_usec >> PPS_AVG;
1290 else
1291 pps_stabil += v_usec >> PPS_AVG;
1292 if (pps_stabil > MAXFREQ >> 2) {
1293 pps_stbcnt++;
1294 time_status |= STA_PPSWANDER;
1295 return;
1296 }
1297 if (time_status & STA_PPSFREQ) {
1298 if (u_usec < 0) {
1299 pps_freq -= -u_usec >> PPS_AVG;
1300 if (pps_freq < -time_tolerance)
1301 pps_freq = -time_tolerance;
1302 u_usec = -u_usec;
1303 } else {
1304 pps_freq += u_usec >> PPS_AVG;
1305 if (pps_freq > time_tolerance)
1306 pps_freq = time_tolerance;
1307 }
1308 }
1309
1310 /*
1311 * Here the calibration interval is adjusted. If the maximum
1312 * time difference is greater than tick / 4, reduce the interval
1313 * by half. If this is not the case for four consecutive
1314 * intervals, double the interval.
1315 */
1316 if (u_usec << pps_shift > bigtick >> 2) {
1317 pps_intcnt = 0;
1318 if (pps_shift > PPS_SHIFT)
1319 pps_shift--;
1320 } else if (pps_intcnt >= 4) {
1321 pps_intcnt = 0;
1322 if (pps_shift < PPS_SHIFTMAX)
1323 pps_shift++;
1324 } else
1325 pps_intcnt++;
1326 }
1327 #endif /* PPS_SYNC */
1328 #endif /* NTP */
1329
1330
1331 /*
1332 * Return information about system clocks.
1333 */
1334 int
1335 sysctl_clockrate(where, sizep)
1336 register char *where;
1337 size_t *sizep;
1338 {
1339 struct clockinfo clkinfo;
1340
1341 /*
1342 * Construct clockinfo structure.
1343 */
1344 clkinfo.tick = tick;
1345 clkinfo.tickadj = tickadj;
1346 clkinfo.hz = hz;
1347 clkinfo.profhz = profhz;
1348 clkinfo.stathz = stathz ? stathz : hz;
1349 return (sysctl_rdstruct(where, sizep, NULL, &clkinfo, sizeof(clkinfo)));
1350 }
1351
1352