kern_clock.c revision 1.96.6.2 1 /* $NetBSD: kern_clock.c,v 1.96.6.2 2006/02/28 20:59:53 kardel Exp $ */
2
3 /*-
4 * Copyright (c) 2000, 2004 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9 * NASA Ames Research Center.
10 * This code is derived from software contributed to The NetBSD Foundation
11 * by Charles M. Hannum.
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. All advertising materials mentioning features or use of this software
22 * must display the following acknowledgement:
23 * This product includes software developed by the NetBSD
24 * Foundation, Inc. and its contributors.
25 * 4. Neither the name of The NetBSD Foundation nor the names of its
26 * contributors may be used to endorse or promote products derived
27 * from this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
30 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
31 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
32 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
33 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
34 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
35 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
36 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
37 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
39 * POSSIBILITY OF SUCH DAMAGE.
40 */
41
42 /*-
43 * Copyright (c) 1982, 1986, 1991, 1993
44 * The Regents of the University of California. All rights reserved.
45 * (c) UNIX System Laboratories, Inc.
46 * All or some portions of this file are derived from material licensed
47 * to the University of California by American Telephone and Telegraph
48 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
49 * the permission of UNIX System Laboratories, Inc.
50 *
51 * Redistribution and use in source and binary forms, with or without
52 * modification, are permitted provided that the following conditions
53 * are met:
54 * 1. Redistributions of source code must retain the above copyright
55 * notice, this list of conditions and the following disclaimer.
56 * 2. Redistributions in binary form must reproduce the above copyright
57 * notice, this list of conditions and the following disclaimer in the
58 * documentation and/or other materials provided with the distribution.
59 * 3. Neither the name of the University nor the names of its contributors
60 * may be used to endorse or promote products derived from this software
61 * without specific prior written permission.
62 *
63 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
64 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
65 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
66 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
67 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
68 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
69 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
70 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
71 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
72 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
73 * SUCH DAMAGE.
74 *
75 * @(#)kern_clock.c 8.5 (Berkeley) 1/21/94
76 */
77
78 #include <sys/cdefs.h>
79 __KERNEL_RCSID(0, "$NetBSD: kern_clock.c,v 1.96.6.2 2006/02/28 20:59:53 kardel Exp $");
80
81 #include "opt_ntp.h"
82 #include "opt_multiprocessor.h"
83 #include "opt_perfctrs.h"
84
85 #include <sys/param.h>
86 #include <sys/systm.h>
87 #include <sys/callout.h>
88 #include <sys/kernel.h>
89 #include <sys/proc.h>
90 #include <sys/resourcevar.h>
91 #include <sys/signalvar.h>
92 #include <sys/sysctl.h>
93 #include <sys/timex.h>
94 #include <sys/sched.h>
95 #include <sys/time.h>
96 #ifdef __HAVE_TIMECOUNTER
97 #include <sys/timetc.h>
98 #endif
99
100 #include <machine/cpu.h>
101 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
102 #include <machine/intr.h>
103 #endif
104
105 #ifdef GPROF
106 #include <sys/gmon.h>
107 #endif
108
109 /*
110 * Clock handling routines.
111 *
112 * This code is written to operate with two timers that run independently of
113 * each other. The main clock, running hz times per second, is used to keep
114 * track of real time. The second timer handles kernel and user profiling,
115 * and does resource use estimation. If the second timer is programmable,
116 * it is randomized to avoid aliasing between the two clocks. For example,
117 * the randomization prevents an adversary from always giving up the CPU
118 * just before its quantum expires. Otherwise, it would never accumulate
119 * CPU ticks. The mean frequency of the second timer is stathz.
120 *
121 * If no second timer exists, stathz will be zero; in this case we drive
122 * profiling and statistics off the main clock. This WILL NOT be accurate;
123 * do not do it unless absolutely necessary.
124 *
125 * The statistics clock may (or may not) be run at a higher rate while
126 * profiling. This profile clock runs at profhz. We require that profhz
127 * be an integral multiple of stathz.
128 *
129 * If the statistics clock is running fast, it must be divided by the ratio
130 * profhz/stathz for statistics. (For profiling, every tick counts.)
131 */
132
133 #ifndef __HAVE_TIMECOUNTER
134 #ifdef NTP /* NTP phase-locked loop in kernel */
135 /*
136 * Phase/frequency-lock loop (PLL/FLL) definitions
137 *
138 * The following variables are read and set by the ntp_adjtime() system
139 * call.
140 *
141 * time_state shows the state of the system clock, with values defined
142 * in the timex.h header file.
143 *
144 * time_status shows the status of the system clock, with bits defined
145 * in the timex.h header file.
146 *
147 * time_offset is used by the PLL/FLL to adjust the system time in small
148 * increments.
149 *
150 * time_constant determines the bandwidth or "stiffness" of the PLL.
151 *
152 * time_tolerance determines maximum frequency error or tolerance of the
153 * CPU clock oscillator and is a property of the architecture; however,
154 * in principle it could change as result of the presence of external
155 * discipline signals, for instance.
156 *
157 * time_precision is usually equal to the kernel tick variable; however,
158 * in cases where a precision clock counter or external clock is
159 * available, the resolution can be much less than this and depend on
160 * whether the external clock is working or not.
161 *
162 * time_maxerror is initialized by a ntp_adjtime() call and increased by
163 * the kernel once each second to reflect the maximum error bound
164 * growth.
165 *
166 * time_esterror is set and read by the ntp_adjtime() call, but
167 * otherwise not used by the kernel.
168 */
169 int time_state = TIME_OK; /* clock state */
170 int time_status = STA_UNSYNC; /* clock status bits */
171 long time_offset = 0; /* time offset (us) */
172 long time_constant = 0; /* pll time constant */
173 long time_tolerance = MAXFREQ; /* frequency tolerance (scaled ppm) */
174 long time_precision = 1; /* clock precision (us) */
175 long time_maxerror = MAXPHASE; /* maximum error (us) */
176 long time_esterror = MAXPHASE; /* estimated error (us) */
177
178 /*
179 * The following variables establish the state of the PLL/FLL and the
180 * residual time and frequency offset of the local clock. The scale
181 * factors are defined in the timex.h header file.
182 *
183 * time_phase and time_freq are the phase increment and the frequency
184 * increment, respectively, of the kernel time variable.
185 *
186 * time_freq is set via ntp_adjtime() from a value stored in a file when
187 * the synchronization daemon is first started. Its value is retrieved
188 * via ntp_adjtime() and written to the file about once per hour by the
189 * daemon.
190 *
191 * time_adj is the adjustment added to the value of tick at each timer
192 * interrupt and is recomputed from time_phase and time_freq at each
193 * seconds rollover.
194 *
195 * time_reftime is the second's portion of the system time at the last
196 * call to ntp_adjtime(). It is used to adjust the time_freq variable
197 * and to increase the time_maxerror as the time since last update
198 * increases.
199 */
200 long time_phase = 0; /* phase offset (scaled us) */
201 long time_freq = 0; /* frequency offset (scaled ppm) */
202 long time_adj = 0; /* tick adjust (scaled 1 / hz) */
203 long time_reftime = 0; /* time at last adjustment (s) */
204
205 #ifdef PPS_SYNC
206 /*
207 * The following variables are used only if the kernel PPS discipline
208 * code is configured (PPS_SYNC). The scale factors are defined in the
209 * timex.h header file.
210 *
211 * pps_time contains the time at each calibration interval, as read by
212 * microtime(). pps_count counts the seconds of the calibration
213 * interval, the duration of which is nominally pps_shift in powers of
214 * two.
215 *
216 * pps_offset is the time offset produced by the time median filter
217 * pps_tf[], while pps_jitter is the dispersion (jitter) measured by
218 * this filter.
219 *
220 * pps_freq is the frequency offset produced by the frequency median
221 * filter pps_ff[], while pps_stabil is the dispersion (wander) measured
222 * by this filter.
223 *
224 * pps_usec is latched from a high resolution counter or external clock
225 * at pps_time. Here we want the hardware counter contents only, not the
226 * contents plus the time_tv.usec as usual.
227 *
228 * pps_valid counts the number of seconds since the last PPS update. It
229 * is used as a watchdog timer to disable the PPS discipline should the
230 * PPS signal be lost.
231 *
232 * pps_glitch counts the number of seconds since the beginning of an
233 * offset burst more than tick/2 from current nominal offset. It is used
234 * mainly to suppress error bursts due to priority conflicts between the
235 * PPS interrupt and timer interrupt.
236 *
237 * pps_intcnt counts the calibration intervals for use in the interval-
238 * adaptation algorithm. It's just too complicated for words.
239 *
240 * pps_kc_hardpps_source contains an arbitrary value that uniquely
241 * identifies the currently bound source of the PPS signal, or NULL
242 * if no source is bound.
243 *
244 * pps_kc_hardpps_mode indicates which transitions, if any, of the PPS
245 * signal should be reported.
246 */
247 struct timeval pps_time; /* kernel time at last interval */
248 long pps_tf[] = {0, 0, 0}; /* pps time offset median filter (us) */
249 long pps_offset = 0; /* pps time offset (us) */
250 long pps_jitter = MAXTIME; /* time dispersion (jitter) (us) */
251 long pps_ff[] = {0, 0, 0}; /* pps frequency offset median filter */
252 long pps_freq = 0; /* frequency offset (scaled ppm) */
253 long pps_stabil = MAXFREQ; /* frequency dispersion (scaled ppm) */
254 long pps_usec = 0; /* microsec counter at last interval */
255 long pps_valid = PPS_VALID; /* pps signal watchdog counter */
256 int pps_glitch = 0; /* pps signal glitch counter */
257 int pps_count = 0; /* calibration interval counter (s) */
258 int pps_shift = PPS_SHIFT; /* interval duration (s) (shift) */
259 int pps_intcnt = 0; /* intervals at current duration */
260 void *pps_kc_hardpps_source = NULL; /* current PPS supplier's identifier */
261 int pps_kc_hardpps_mode = 0; /* interesting edges of PPS signal */
262
263 /*
264 * PPS signal quality monitors
265 *
266 * pps_jitcnt counts the seconds that have been discarded because the
267 * jitter measured by the time median filter exceeds the limit MAXTIME
268 * (100 us).
269 *
270 * pps_calcnt counts the frequency calibration intervals, which are
271 * variable from 4 s to 256 s.
272 *
273 * pps_errcnt counts the calibration intervals which have been discarded
274 * because the wander exceeds the limit MAXFREQ (100 ppm) or where the
275 * calibration interval jitter exceeds two ticks.
276 *
277 * pps_stbcnt counts the calibration intervals that have been discarded
278 * because the frequency wander exceeds the limit MAXFREQ / 4 (25 us).
279 */
280 long pps_jitcnt = 0; /* jitter limit exceeded */
281 long pps_calcnt = 0; /* calibration intervals */
282 long pps_errcnt = 0; /* calibration errors */
283 long pps_stbcnt = 0; /* stability limit exceeded */
284 #endif /* PPS_SYNC */
285
286 #ifdef EXT_CLOCK
287 /*
288 * External clock definitions
289 *
290 * The following definitions and declarations are used only if an
291 * external clock is configured on the system.
292 */
293 #define CLOCK_INTERVAL 30 /* CPU clock update interval (s) */
294
295 /*
296 * The clock_count variable is set to CLOCK_INTERVAL at each PPS
297 * interrupt and decremented once each second.
298 */
299 int clock_count = 0; /* CPU clock counter */
300
301 #ifdef HIGHBALL
302 /*
303 * The clock_offset and clock_cpu variables are used by the HIGHBALL
304 * interface. The clock_offset variable defines the offset between
305 * system time and the HIGBALL counters. The clock_cpu variable contains
306 * the offset between the system clock and the HIGHBALL clock for use in
307 * disciplining the kernel time variable.
308 */
309 extern struct timeval clock_offset; /* Highball clock offset */
310 long clock_cpu = 0; /* CPU clock adjust */
311 #endif /* HIGHBALL */
312 #endif /* EXT_CLOCK */
313 #endif /* NTP */
314
315 /*
316 * Bump a timeval by a small number of usec's.
317 */
318 #define BUMPTIME(t, usec) { \
319 volatile struct timeval *tp = (t); \
320 long us; \
321 \
322 tp->tv_usec = us = tp->tv_usec + (usec); \
323 if (us >= 1000000) { \
324 tp->tv_usec = us - 1000000; \
325 tp->tv_sec++; \
326 } \
327 }
328 #endif /* !__HAVE_TIMECOUNTER */
329
330 int stathz;
331 int profhz;
332 int profsrc;
333 int schedhz;
334 int profprocs;
335 int hardclock_ticks;
336 static int statscheddiv; /* stat => sched divider (used if schedhz == 0) */
337 static int psdiv; /* prof => stat divider */
338 int psratio; /* ratio: prof / stat */
339 #ifndef __HAVE_TIMECOUNTER
340 int tickfix, tickfixinterval; /* used if tick not really integral */
341 #ifndef NTP
342 static int tickfixcnt; /* accumulated fractional error */
343 #else
344 int fixtick; /* used by NTP for same */
345 int shifthz;
346 #endif
347
348 /*
349 * We might want ldd to load the both words from time at once.
350 * To succeed we need to be quadword aligned.
351 * The sparc already does that, and that it has worked so far is a fluke.
352 */
353 volatile struct timeval time __attribute__((__aligned__(__alignof__(quad_t))));
354 volatile struct timeval mono_time;
355 #endif /* !__HAVE_TIMECOUNTER */
356
357 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
358 void *softclock_si;
359 #endif
360
361 /*
362 * Initialize clock frequencies and start both clocks running.
363 */
364 void
365 initclocks(void)
366 {
367 int i;
368
369 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
370 softclock_si = softintr_establish(IPL_SOFTCLOCK, softclock, NULL);
371 if (softclock_si == NULL)
372 panic("initclocks: unable to register softclock intr");
373 #endif
374
375 /*
376 * Set divisors to 1 (normal case) and let the machine-specific
377 * code do its bit.
378 */
379 psdiv = 1;
380 #ifdef __HAVE_TIMECOUNTER
381 inittimecounter();
382 #endif
383 cpu_initclocks();
384
385 /*
386 * Compute profhz/stathz/rrticks, and fix profhz if needed.
387 */
388 i = stathz ? stathz : hz;
389 if (profhz == 0)
390 profhz = i;
391 psratio = profhz / i;
392 rrticks = hz / 10;
393 if (schedhz == 0) {
394 /* 16Hz is best */
395 statscheddiv = i / 16;
396 if (statscheddiv <= 0)
397 panic("statscheddiv");
398 }
399
400 #ifndef __HAVE_TIMECOUNTER
401 #ifdef NTP
402 switch (hz) {
403 case 1:
404 shifthz = SHIFT_SCALE - 0;
405 break;
406 case 2:
407 shifthz = SHIFT_SCALE - 1;
408 break;
409 case 4:
410 shifthz = SHIFT_SCALE - 2;
411 break;
412 case 8:
413 shifthz = SHIFT_SCALE - 3;
414 break;
415 case 16:
416 shifthz = SHIFT_SCALE - 4;
417 break;
418 case 32:
419 shifthz = SHIFT_SCALE - 5;
420 break;
421 case 50:
422 case 60:
423 case 64:
424 shifthz = SHIFT_SCALE - 6;
425 break;
426 case 96:
427 case 100:
428 case 128:
429 shifthz = SHIFT_SCALE - 7;
430 break;
431 case 256:
432 shifthz = SHIFT_SCALE - 8;
433 break;
434 case 512:
435 shifthz = SHIFT_SCALE - 9;
436 break;
437 case 1000:
438 case 1024:
439 shifthz = SHIFT_SCALE - 10;
440 break;
441 case 1200:
442 case 2048:
443 shifthz = SHIFT_SCALE - 11;
444 break;
445 case 4096:
446 shifthz = SHIFT_SCALE - 12;
447 break;
448 case 8192:
449 shifthz = SHIFT_SCALE - 13;
450 break;
451 case 16384:
452 shifthz = SHIFT_SCALE - 14;
453 break;
454 case 32768:
455 shifthz = SHIFT_SCALE - 15;
456 break;
457 case 65536:
458 shifthz = SHIFT_SCALE - 16;
459 break;
460 default:
461 panic("weird hz");
462 }
463 if (fixtick == 0) {
464 /*
465 * Give MD code a chance to set this to a better
466 * value; but, if it doesn't, we should.
467 */
468 fixtick = (1000000 - (hz*tick));
469 }
470 #endif /* NTP */
471 #endif /* !__HAVE_TIMECOUNTER */
472 }
473
474 /*
475 * The real-time timer, interrupting hz times per second.
476 */
477 void
478 hardclock(struct clockframe *frame)
479 {
480 struct lwp *l;
481 struct proc *p;
482 struct cpu_info *ci = curcpu();
483 struct ptimer *pt;
484 #ifndef __HAVE_TIMECOUNTER
485 int delta;
486 extern int tickdelta;
487 extern long timedelta;
488 #ifdef NTP
489 int time_update;
490 int ltemp;
491 #endif /* NTP */
492 #endif /* __HAVE_TIMECOUNTER */
493
494 l = curlwp;
495 if (l) {
496 p = l->l_proc;
497 /*
498 * Run current process's virtual and profile time, as needed.
499 */
500 if (CLKF_USERMODE(frame) && p->p_timers &&
501 (pt = LIST_FIRST(&p->p_timers->pts_virtual)) != NULL)
502 if (itimerdecr(pt, tick) == 0)
503 itimerfire(pt);
504 if (p->p_timers &&
505 (pt = LIST_FIRST(&p->p_timers->pts_prof)) != NULL)
506 if (itimerdecr(pt, tick) == 0)
507 itimerfire(pt);
508 }
509
510 /*
511 * If no separate statistics clock is available, run it from here.
512 */
513 if (stathz == 0)
514 statclock(frame);
515 if ((--ci->ci_schedstate.spc_rrticks) <= 0)
516 roundrobin(ci);
517
518 #if defined(MULTIPROCESSOR)
519 /*
520 * If we are not the primary CPU, we're not allowed to do
521 * any more work.
522 */
523 if (CPU_IS_PRIMARY(ci) == 0)
524 return;
525 #endif
526
527 hardclock_ticks++;
528
529 #ifdef __HAVE_TIMECOUNTER
530 tc_ticktock();
531 #else /* __HAVE_TIMECOUNTER */
532 /*
533 * Increment the time-of-day. The increment is normally just
534 * ``tick''. If the machine is one which has a clock frequency
535 * such that ``hz'' would not divide the second evenly into
536 * milliseconds, a periodic adjustment must be applied. Finally,
537 * if we are still adjusting the time (see adjtime()),
538 * ``tickdelta'' may also be added in.
539 */
540 delta = tick;
541
542 #ifndef NTP
543 if (tickfix) {
544 tickfixcnt += tickfix;
545 if (tickfixcnt >= tickfixinterval) {
546 delta++;
547 tickfixcnt -= tickfixinterval;
548 }
549 }
550 #endif /* !NTP */
551 /* Imprecise 4bsd adjtime() handling */
552 if (timedelta != 0) {
553 delta += tickdelta;
554 timedelta -= tickdelta;
555 }
556
557 #ifdef notyet
558 microset();
559 #endif
560
561 #ifndef NTP
562 BUMPTIME(&time, delta); /* XXX Now done using NTP code below */
563 #endif
564 BUMPTIME(&mono_time, delta);
565
566 #ifdef NTP
567 time_update = delta;
568
569 /*
570 * Compute the phase adjustment. If the low-order bits
571 * (time_phase) of the update overflow, bump the high-order bits
572 * (time_update).
573 */
574 time_phase += time_adj;
575 if (time_phase <= -FINEUSEC) {
576 ltemp = -time_phase >> SHIFT_SCALE;
577 time_phase += ltemp << SHIFT_SCALE;
578 time_update -= ltemp;
579 } else if (time_phase >= FINEUSEC) {
580 ltemp = time_phase >> SHIFT_SCALE;
581 time_phase -= ltemp << SHIFT_SCALE;
582 time_update += ltemp;
583 }
584
585 #ifdef HIGHBALL
586 /*
587 * If the HIGHBALL board is installed, we need to adjust the
588 * external clock offset in order to close the hardware feedback
589 * loop. This will adjust the external clock phase and frequency
590 * in small amounts. The additional phase noise and frequency
591 * wander this causes should be minimal. We also need to
592 * discipline the kernel time variable, since the PLL is used to
593 * discipline the external clock. If the Highball board is not
594 * present, we discipline kernel time with the PLL as usual. We
595 * assume that the external clock phase adjustment (time_update)
596 * and kernel phase adjustment (clock_cpu) are less than the
597 * value of tick.
598 */
599 clock_offset.tv_usec += time_update;
600 if (clock_offset.tv_usec >= 1000000) {
601 clock_offset.tv_sec++;
602 clock_offset.tv_usec -= 1000000;
603 }
604 if (clock_offset.tv_usec < 0) {
605 clock_offset.tv_sec--;
606 clock_offset.tv_usec += 1000000;
607 }
608 time.tv_usec += clock_cpu;
609 clock_cpu = 0;
610 #else
611 time.tv_usec += time_update;
612 #endif /* HIGHBALL */
613
614 /*
615 * On rollover of the second the phase adjustment to be used for
616 * the next second is calculated. Also, the maximum error is
617 * increased by the tolerance. If the PPS frequency discipline
618 * code is present, the phase is increased to compensate for the
619 * CPU clock oscillator frequency error.
620 *
621 * On a 32-bit machine and given parameters in the timex.h
622 * header file, the maximum phase adjustment is +-512 ms and
623 * maximum frequency offset is a tad less than) +-512 ppm. On a
624 * 64-bit machine, you shouldn't need to ask.
625 */
626 if (time.tv_usec >= 1000000) {
627 time.tv_usec -= 1000000;
628 time.tv_sec++;
629 time_maxerror += time_tolerance >> SHIFT_USEC;
630
631 /*
632 * Leap second processing. If in leap-insert state at
633 * the end of the day, the system clock is set back one
634 * second; if in leap-delete state, the system clock is
635 * set ahead one second. The microtime() routine or
636 * external clock driver will insure that reported time
637 * is always monotonic. The ugly divides should be
638 * replaced.
639 */
640 switch (time_state) {
641 case TIME_OK:
642 if (time_status & STA_INS)
643 time_state = TIME_INS;
644 else if (time_status & STA_DEL)
645 time_state = TIME_DEL;
646 break;
647
648 case TIME_INS:
649 if (time.tv_sec % 86400 == 0) {
650 time.tv_sec--;
651 time_state = TIME_OOP;
652 }
653 break;
654
655 case TIME_DEL:
656 if ((time.tv_sec + 1) % 86400 == 0) {
657 time.tv_sec++;
658 time_state = TIME_WAIT;
659 }
660 break;
661
662 case TIME_OOP:
663 time_state = TIME_WAIT;
664 break;
665
666 case TIME_WAIT:
667 if (!(time_status & (STA_INS | STA_DEL)))
668 time_state = TIME_OK;
669 break;
670 }
671
672 /*
673 * Compute the phase adjustment for the next second. In
674 * PLL mode, the offset is reduced by a fixed factor
675 * times the time constant. In FLL mode the offset is
676 * used directly. In either mode, the maximum phase
677 * adjustment for each second is clamped so as to spread
678 * the adjustment over not more than the number of
679 * seconds between updates.
680 */
681 if (time_offset < 0) {
682 ltemp = -time_offset;
683 if (!(time_status & STA_FLL))
684 ltemp >>= SHIFT_KG + time_constant;
685 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
686 ltemp = (MAXPHASE / MINSEC) <<
687 SHIFT_UPDATE;
688 time_offset += ltemp;
689 time_adj = -ltemp << (shifthz - SHIFT_UPDATE);
690 } else if (time_offset > 0) {
691 ltemp = time_offset;
692 if (!(time_status & STA_FLL))
693 ltemp >>= SHIFT_KG + time_constant;
694 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
695 ltemp = (MAXPHASE / MINSEC) <<
696 SHIFT_UPDATE;
697 time_offset -= ltemp;
698 time_adj = ltemp << (shifthz - SHIFT_UPDATE);
699 } else
700 time_adj = 0;
701
702 /*
703 * Compute the frequency estimate and additional phase
704 * adjustment due to frequency error for the next
705 * second. When the PPS signal is engaged, gnaw on the
706 * watchdog counter and update the frequency computed by
707 * the pll and the PPS signal.
708 */
709 #ifdef PPS_SYNC
710 pps_valid++;
711 if (pps_valid == PPS_VALID) {
712 pps_jitter = MAXTIME;
713 pps_stabil = MAXFREQ;
714 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
715 STA_PPSWANDER | STA_PPSERROR);
716 }
717 ltemp = time_freq + pps_freq;
718 #else
719 ltemp = time_freq;
720 #endif /* PPS_SYNC */
721
722 if (ltemp < 0)
723 time_adj -= -ltemp >> (SHIFT_USEC - shifthz);
724 else
725 time_adj += ltemp >> (SHIFT_USEC - shifthz);
726 time_adj += (long)fixtick << shifthz;
727
728 /*
729 * When the CPU clock oscillator frequency is not a
730 * power of 2 in Hz, shifthz is only an approximate
731 * scale factor.
732 *
733 * To determine the adjustment, you can do the following:
734 * bc -q
735 * scale=24
736 * obase=2
737 * idealhz/realhz
738 * where `idealhz' is the next higher power of 2, and `realhz'
739 * is the actual value. You may need to factor this result
740 * into a sequence of 2 multipliers to get better precision.
741 *
742 * Likewise, the error can be calculated with (e.g. for 100Hz):
743 * bc -q
744 * scale=24
745 * ((1+2^-2+2^-5)*(1-2^-10)*realhz-idealhz)/idealhz
746 * (and then multiply by 1000000 to get ppm).
747 */
748 switch (hz) {
749 case 60:
750 /* A factor of 1.000100010001 gives about 15ppm
751 error. */
752 if (time_adj < 0) {
753 time_adj -= (-time_adj >> 4);
754 time_adj -= (-time_adj >> 8);
755 } else {
756 time_adj += (time_adj >> 4);
757 time_adj += (time_adj >> 8);
758 }
759 break;
760
761 case 96:
762 /* A factor of 1.0101010101 gives about 244ppm error. */
763 if (time_adj < 0) {
764 time_adj -= (-time_adj >> 2);
765 time_adj -= (-time_adj >> 4) + (-time_adj >> 8);
766 } else {
767 time_adj += (time_adj >> 2);
768 time_adj += (time_adj >> 4) + (time_adj >> 8);
769 }
770 break;
771
772 case 50:
773 case 100:
774 /* A factor of 1.010001111010111 gives about 1ppm
775 error. */
776 if (time_adj < 0) {
777 time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
778 time_adj += (-time_adj >> 10);
779 } else {
780 time_adj += (time_adj >> 2) + (time_adj >> 5);
781 time_adj -= (time_adj >> 10);
782 }
783 break;
784
785 case 1000:
786 /* A factor of 1.000001100010100001 gives about 50ppm
787 error. */
788 if (time_adj < 0) {
789 time_adj -= (-time_adj >> 6) + (-time_adj >> 11);
790 time_adj -= (-time_adj >> 7);
791 } else {
792 time_adj += (time_adj >> 6) + (time_adj >> 11);
793 time_adj += (time_adj >> 7);
794 }
795 break;
796
797 case 1200:
798 /* A factor of 1.1011010011100001 gives about 64ppm
799 error. */
800 if (time_adj < 0) {
801 time_adj -= (-time_adj >> 1) + (-time_adj >> 6);
802 time_adj -= (-time_adj >> 3) + (-time_adj >> 10);
803 } else {
804 time_adj += (time_adj >> 1) + (time_adj >> 6);
805 time_adj += (time_adj >> 3) + (time_adj >> 10);
806 }
807 break;
808 }
809
810 #ifdef EXT_CLOCK
811 /*
812 * If an external clock is present, it is necessary to
813 * discipline the kernel time variable anyway, since not
814 * all system components use the microtime() interface.
815 * Here, the time offset between the external clock and
816 * kernel time variable is computed every so often.
817 */
818 clock_count++;
819 if (clock_count > CLOCK_INTERVAL) {
820 clock_count = 0;
821 microtime(&clock_ext);
822 delta.tv_sec = clock_ext.tv_sec - time.tv_sec;
823 delta.tv_usec = clock_ext.tv_usec -
824 time.tv_usec;
825 if (delta.tv_usec < 0)
826 delta.tv_sec--;
827 if (delta.tv_usec >= 500000) {
828 delta.tv_usec -= 1000000;
829 delta.tv_sec++;
830 }
831 if (delta.tv_usec < -500000) {
832 delta.tv_usec += 1000000;
833 delta.tv_sec--;
834 }
835 if (delta.tv_sec > 0 || (delta.tv_sec == 0 &&
836 delta.tv_usec > MAXPHASE) ||
837 delta.tv_sec < -1 || (delta.tv_sec == -1 &&
838 delta.tv_usec < -MAXPHASE)) {
839 time = clock_ext;
840 delta.tv_sec = 0;
841 delta.tv_usec = 0;
842 }
843 #ifdef HIGHBALL
844 clock_cpu = delta.tv_usec;
845 #else /* HIGHBALL */
846 hardupdate(delta.tv_usec);
847 #endif /* HIGHBALL */
848 }
849 #endif /* EXT_CLOCK */
850 }
851
852 #endif /* NTP */
853 #endif /* !__HAVE_TIMECOUNTER */
854
855 /*
856 * Update real-time timeout queue.
857 * Process callouts at a very low CPU priority, so we don't keep the
858 * relatively high clock interrupt priority any longer than necessary.
859 */
860 if (callout_hardclock()) {
861 if (CLKF_BASEPRI(frame)) {
862 /*
863 * Save the overhead of a software interrupt;
864 * it will happen as soon as we return, so do
865 * it now.
866 */
867 spllowersoftclock();
868 KERNEL_LOCK(LK_CANRECURSE|LK_EXCLUSIVE);
869 softclock(NULL);
870 KERNEL_UNLOCK();
871 } else {
872 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
873 softintr_schedule(softclock_si);
874 #else
875 setsoftclock();
876 #endif
877 }
878 }
879 }
880
881 #ifdef __HAVE_TIMECOUNTER
882 /*
883 * Compute number of hz until specified time. Used to compute second
884 * argument to callout_reset() from an absolute time.
885 */
886 int
887 hzto(struct timeval *tvp)
888 {
889 struct timeval now, tv;
890
891 tv = *tvp; /* Don't modify original tvp. */
892 getmicrotime(&now);
893 timersub(&tv, &now, &tv);
894 return tvtohz(&tv);
895 }
896 #endif /* __HAVE_TIMECOUNTER */
897
898 /*
899 * Compute number of ticks in the specified amount of time.
900 */
901 int
902 tvtohz(struct timeval *tv)
903 {
904 unsigned long ticks;
905 long sec, usec;
906
907 /*
908 * If the number of usecs in the whole seconds part of the time
909 * difference fits in a long, then the total number of usecs will
910 * fit in an unsigned long. Compute the total and convert it to
911 * ticks, rounding up and adding 1 to allow for the current tick
912 * to expire. Rounding also depends on unsigned long arithmetic
913 * to avoid overflow.
914 *
915 * Otherwise, if the number of ticks in the whole seconds part of
916 * the time difference fits in a long, then convert the parts to
917 * ticks separately and add, using similar rounding methods and
918 * overflow avoidance. This method would work in the previous
919 * case, but it is slightly slower and assumes that hz is integral.
920 *
921 * Otherwise, round the time difference down to the maximum
922 * representable value.
923 *
924 * If ints are 32-bit, then the maximum value for any timeout in
925 * 10ms ticks is 248 days.
926 */
927 sec = tv->tv_sec;
928 usec = tv->tv_usec;
929
930 if (usec < 0) {
931 sec--;
932 usec += 1000000;
933 }
934
935 if (sec < 0 || (sec == 0 && usec <= 0)) {
936 /*
937 * Would expire now or in the past. Return 0 ticks.
938 * This is different from the legacy hzto() interface,
939 * and callers need to check for it.
940 */
941 ticks = 0;
942 } else if (sec <= (LONG_MAX / 1000000))
943 ticks = (((sec * 1000000) + (unsigned long)usec + (tick - 1))
944 / tick) + 1;
945 else if (sec <= (LONG_MAX / hz))
946 ticks = (sec * hz) +
947 (((unsigned long)usec + (tick - 1)) / tick) + 1;
948 else
949 ticks = LONG_MAX;
950
951 if (ticks > INT_MAX)
952 ticks = INT_MAX;
953
954 return ((int)ticks);
955 }
956
957 #ifndef __HAVE_TIMECOUNTER
958 /*
959 * Compute number of hz until specified time. Used to compute second
960 * argument to callout_reset() from an absolute time.
961 */
962 int
963 hzto(struct timeval *tv)
964 {
965 unsigned long ticks;
966 long sec, usec;
967 int s;
968
969 /*
970 * If the number of usecs in the whole seconds part of the time
971 * difference fits in a long, then the total number of usecs will
972 * fit in an unsigned long. Compute the total and convert it to
973 * ticks, rounding up and adding 1 to allow for the current tick
974 * to expire. Rounding also depends on unsigned long arithmetic
975 * to avoid overflow.
976 *
977 * Otherwise, if the number of ticks in the whole seconds part of
978 * the time difference fits in a long, then convert the parts to
979 * ticks separately and add, using similar rounding methods and
980 * overflow avoidance. This method would work in the previous
981 * case, but it is slightly slower and assume that hz is integral.
982 *
983 * Otherwise, round the time difference down to the maximum
984 * representable value.
985 *
986 * If ints are 32-bit, then the maximum value for any timeout in
987 * 10ms ticks is 248 days.
988 */
989 s = splclock();
990 sec = tv->tv_sec - time.tv_sec;
991 usec = tv->tv_usec - time.tv_usec;
992 splx(s);
993
994 if (usec < 0) {
995 sec--;
996 usec += 1000000;
997 }
998
999 if (sec < 0 || (sec == 0 && usec <= 0)) {
1000 /*
1001 * Would expire now or in the past. Return 0 ticks.
1002 * This is different from the legacy hzto() interface,
1003 * and callers need to check for it.
1004 */
1005 ticks = 0;
1006 } else if (sec <= (LONG_MAX / 1000000))
1007 ticks = (((sec * 1000000) + (unsigned long)usec + (tick - 1))
1008 / tick) + 1;
1009 else if (sec <= (LONG_MAX / hz))
1010 ticks = (sec * hz) +
1011 (((unsigned long)usec + (tick - 1)) / tick) + 1;
1012 else
1013 ticks = LONG_MAX;
1014
1015 if (ticks > INT_MAX)
1016 ticks = INT_MAX;
1017
1018 return ((int)ticks);
1019 }
1020 #endif /* !__HAVE_TIMECOUNTER */
1021
1022 /*
1023 * Compute number of ticks in the specified amount of time.
1024 */
1025 int
1026 tstohz(struct timespec *ts)
1027 {
1028 struct timeval tv;
1029
1030 /*
1031 * usec has great enough resolution for hz, so convert to a
1032 * timeval and use tvtohz() above.
1033 */
1034 TIMESPEC_TO_TIMEVAL(&tv, ts);
1035 return tvtohz(&tv);
1036 }
1037
1038 /*
1039 * Start profiling on a process.
1040 *
1041 * Kernel profiling passes proc0 which never exits and hence
1042 * keeps the profile clock running constantly.
1043 */
1044 void
1045 startprofclock(struct proc *p)
1046 {
1047
1048 if ((p->p_flag & P_PROFIL) == 0) {
1049 p->p_flag |= P_PROFIL;
1050 /*
1051 * This is only necessary if using the clock as the
1052 * profiling source.
1053 */
1054 if (++profprocs == 1 && stathz != 0)
1055 psdiv = psratio;
1056 }
1057 }
1058
1059 /*
1060 * Stop profiling on a process.
1061 */
1062 void
1063 stopprofclock(struct proc *p)
1064 {
1065
1066 if (p->p_flag & P_PROFIL) {
1067 p->p_flag &= ~P_PROFIL;
1068 /*
1069 * This is only necessary if using the clock as the
1070 * profiling source.
1071 */
1072 if (--profprocs == 0 && stathz != 0)
1073 psdiv = 1;
1074 }
1075 }
1076
1077 #if defined(PERFCTRS)
1078 /*
1079 * Independent profiling "tick" in case we're using a separate
1080 * clock or profiling event source. Currently, that's just
1081 * performance counters--hence the wrapper.
1082 */
1083 void
1084 proftick(struct clockframe *frame)
1085 {
1086 #ifdef GPROF
1087 struct gmonparam *g;
1088 intptr_t i;
1089 #endif
1090 struct proc *p;
1091
1092 p = curproc;
1093 if (CLKF_USERMODE(frame)) {
1094 if (p->p_flag & P_PROFIL)
1095 addupc_intr(p, CLKF_PC(frame));
1096 } else {
1097 #ifdef GPROF
1098 g = &_gmonparam;
1099 if (g->state == GMON_PROF_ON) {
1100 i = CLKF_PC(frame) - g->lowpc;
1101 if (i < g->textsize) {
1102 i /= HISTFRACTION * sizeof(*g->kcount);
1103 g->kcount[i]++;
1104 }
1105 }
1106 #endif
1107 #ifdef PROC_PC
1108 if (p && p->p_flag & P_PROFIL)
1109 addupc_intr(p, PROC_PC(p));
1110 #endif
1111 }
1112 }
1113 #endif
1114
1115 /*
1116 * Statistics clock. Grab profile sample, and if divider reaches 0,
1117 * do process and kernel statistics.
1118 */
1119 void
1120 statclock(struct clockframe *frame)
1121 {
1122 #ifdef GPROF
1123 struct gmonparam *g;
1124 intptr_t i;
1125 #endif
1126 struct cpu_info *ci = curcpu();
1127 struct schedstate_percpu *spc = &ci->ci_schedstate;
1128 struct lwp *l;
1129 struct proc *p;
1130
1131 /*
1132 * Notice changes in divisor frequency, and adjust clock
1133 * frequency accordingly.
1134 */
1135 if (spc->spc_psdiv != psdiv) {
1136 spc->spc_psdiv = psdiv;
1137 spc->spc_pscnt = psdiv;
1138 if (psdiv == 1) {
1139 setstatclockrate(stathz);
1140 } else {
1141 setstatclockrate(profhz);
1142 }
1143 }
1144 l = curlwp;
1145 p = (l ? l->l_proc : 0);
1146 if (CLKF_USERMODE(frame)) {
1147 if (p->p_flag & P_PROFIL && profsrc == PROFSRC_CLOCK)
1148 addupc_intr(p, CLKF_PC(frame));
1149 if (--spc->spc_pscnt > 0)
1150 return;
1151 /*
1152 * Came from user mode; CPU was in user state.
1153 * If this process is being profiled record the tick.
1154 */
1155 p->p_uticks++;
1156 if (p->p_nice > NZERO)
1157 spc->spc_cp_time[CP_NICE]++;
1158 else
1159 spc->spc_cp_time[CP_USER]++;
1160 } else {
1161 #ifdef GPROF
1162 /*
1163 * Kernel statistics are just like addupc_intr, only easier.
1164 */
1165 g = &_gmonparam;
1166 if (profsrc == PROFSRC_CLOCK && g->state == GMON_PROF_ON) {
1167 i = CLKF_PC(frame) - g->lowpc;
1168 if (i < g->textsize) {
1169 i /= HISTFRACTION * sizeof(*g->kcount);
1170 g->kcount[i]++;
1171 }
1172 }
1173 #endif
1174 #ifdef LWP_PC
1175 if (p && profsrc == PROFSRC_CLOCK && p->p_flag & P_PROFIL)
1176 addupc_intr(p, LWP_PC(l));
1177 #endif
1178 if (--spc->spc_pscnt > 0)
1179 return;
1180 /*
1181 * Came from kernel mode, so we were:
1182 * - handling an interrupt,
1183 * - doing syscall or trap work on behalf of the current
1184 * user process, or
1185 * - spinning in the idle loop.
1186 * Whichever it is, charge the time as appropriate.
1187 * Note that we charge interrupts to the current process,
1188 * regardless of whether they are ``for'' that process,
1189 * so that we know how much of its real time was spent
1190 * in ``non-process'' (i.e., interrupt) work.
1191 */
1192 if (CLKF_INTR(frame)) {
1193 if (p != NULL)
1194 p->p_iticks++;
1195 spc->spc_cp_time[CP_INTR]++;
1196 } else if (p != NULL) {
1197 p->p_sticks++;
1198 spc->spc_cp_time[CP_SYS]++;
1199 } else
1200 spc->spc_cp_time[CP_IDLE]++;
1201 }
1202 spc->spc_pscnt = psdiv;
1203
1204 if (l != NULL) {
1205 ++p->p_cpticks;
1206 /*
1207 * If no separate schedclock is provided, call it here
1208 * at about 16 Hz.
1209 */
1210 if (schedhz == 0)
1211 if ((int)(--ci->ci_schedstate.spc_schedticks) <= 0) {
1212 schedclock(l);
1213 ci->ci_schedstate.spc_schedticks = statscheddiv;
1214 }
1215 }
1216 }
1217
1218 #ifndef __HAVE_TIMECOUNTER
1219 #ifdef NTP /* NTP phase-locked loop in kernel */
1220 /*
1221 * hardupdate() - local clock update
1222 *
1223 * This routine is called by ntp_adjtime() to update the local clock
1224 * phase and frequency. The implementation is of an adaptive-parameter,
1225 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
1226 * time and frequency offset estimates for each call. If the kernel PPS
1227 * discipline code is configured (PPS_SYNC), the PPS signal itself
1228 * determines the new time offset, instead of the calling argument.
1229 * Presumably, calls to ntp_adjtime() occur only when the caller
1230 * believes the local clock is valid within some bound (+-128 ms with
1231 * NTP). If the caller's time is far different than the PPS time, an
1232 * argument will ensue, and it's not clear who will lose.
1233 *
1234 * For uncompensated quartz crystal oscillatores and nominal update
1235 * intervals less than 1024 s, operation should be in phase-lock mode
1236 * (STA_FLL = 0), where the loop is disciplined to phase. For update
1237 * intervals greater than thiss, operation should be in frequency-lock
1238 * mode (STA_FLL = 1), where the loop is disciplined to frequency.
1239 *
1240 * Note: splclock() is in effect.
1241 */
1242 void
1243 hardupdate(long offset)
1244 {
1245 long ltemp, mtemp;
1246
1247 if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
1248 return;
1249 ltemp = offset;
1250 #ifdef PPS_SYNC
1251 if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
1252 ltemp = pps_offset;
1253 #endif /* PPS_SYNC */
1254
1255 /*
1256 * Scale the phase adjustment and clamp to the operating range.
1257 */
1258 if (ltemp > MAXPHASE)
1259 time_offset = MAXPHASE << SHIFT_UPDATE;
1260 else if (ltemp < -MAXPHASE)
1261 time_offset = -(MAXPHASE << SHIFT_UPDATE);
1262 else
1263 time_offset = ltemp << SHIFT_UPDATE;
1264
1265 /*
1266 * Select whether the frequency is to be controlled and in which
1267 * mode (PLL or FLL). Clamp to the operating range. Ugly
1268 * multiply/divide should be replaced someday.
1269 */
1270 if (time_status & STA_FREQHOLD || time_reftime == 0)
1271 time_reftime = time.tv_sec;
1272 mtemp = time.tv_sec - time_reftime;
1273 time_reftime = time.tv_sec;
1274 if (time_status & STA_FLL) {
1275 if (mtemp >= MINSEC) {
1276 ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
1277 SHIFT_UPDATE));
1278 if (ltemp < 0)
1279 time_freq -= -ltemp >> SHIFT_KH;
1280 else
1281 time_freq += ltemp >> SHIFT_KH;
1282 }
1283 } else {
1284 if (mtemp < MAXSEC) {
1285 ltemp *= mtemp;
1286 if (ltemp < 0)
1287 time_freq -= -ltemp >> (time_constant +
1288 time_constant + SHIFT_KF -
1289 SHIFT_USEC);
1290 else
1291 time_freq += ltemp >> (time_constant +
1292 time_constant + SHIFT_KF -
1293 SHIFT_USEC);
1294 }
1295 }
1296 if (time_freq > time_tolerance)
1297 time_freq = time_tolerance;
1298 else if (time_freq < -time_tolerance)
1299 time_freq = -time_tolerance;
1300 }
1301
1302 #ifdef PPS_SYNC
1303 /*
1304 * hardpps() - discipline CPU clock oscillator to external PPS signal
1305 *
1306 * This routine is called at each PPS interrupt in order to discipline
1307 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
1308 * and leaves it in a handy spot for the hardclock() routine. It
1309 * integrates successive PPS phase differences and calculates the
1310 * frequency offset. This is used in hardclock() to discipline the CPU
1311 * clock oscillator so that intrinsic frequency error is cancelled out.
1312 * The code requires the caller to capture the time and hardware counter
1313 * value at the on-time PPS signal transition.
1314 *
1315 * Note that, on some Unix systems, this routine runs at an interrupt
1316 * priority level higher than the timer interrupt routine hardclock().
1317 * Therefore, the variables used are distinct from the hardclock()
1318 * variables, except for certain exceptions: The PPS frequency pps_freq
1319 * and phase pps_offset variables are determined by this routine and
1320 * updated atomically. The time_tolerance variable can be considered a
1321 * constant, since it is infrequently changed, and then only when the
1322 * PPS signal is disabled. The watchdog counter pps_valid is updated
1323 * once per second by hardclock() and is atomically cleared in this
1324 * routine.
1325 */
1326 void
1327 hardpps(struct timeval *tvp, /* time at PPS */
1328 long usec /* hardware counter at PPS */)
1329 {
1330 long u_usec, v_usec, bigtick;
1331 long cal_sec, cal_usec;
1332
1333 /*
1334 * An occasional glitch can be produced when the PPS interrupt
1335 * occurs in the hardclock() routine before the time variable is
1336 * updated. Here the offset is discarded when the difference
1337 * between it and the last one is greater than tick/2, but not
1338 * if the interval since the first discard exceeds 30 s.
1339 */
1340 time_status |= STA_PPSSIGNAL;
1341 time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1342 pps_valid = 0;
1343 u_usec = -tvp->tv_usec;
1344 if (u_usec < -500000)
1345 u_usec += 1000000;
1346 v_usec = pps_offset - u_usec;
1347 if (v_usec < 0)
1348 v_usec = -v_usec;
1349 if (v_usec > (tick >> 1)) {
1350 if (pps_glitch > MAXGLITCH) {
1351 pps_glitch = 0;
1352 pps_tf[2] = u_usec;
1353 pps_tf[1] = u_usec;
1354 } else {
1355 pps_glitch++;
1356 u_usec = pps_offset;
1357 }
1358 } else
1359 pps_glitch = 0;
1360
1361 /*
1362 * A three-stage median filter is used to help deglitch the pps
1363 * time. The median sample becomes the time offset estimate; the
1364 * difference between the other two samples becomes the time
1365 * dispersion (jitter) estimate.
1366 */
1367 pps_tf[2] = pps_tf[1];
1368 pps_tf[1] = pps_tf[0];
1369 pps_tf[0] = u_usec;
1370 if (pps_tf[0] > pps_tf[1]) {
1371 if (pps_tf[1] > pps_tf[2]) {
1372 pps_offset = pps_tf[1]; /* 0 1 2 */
1373 v_usec = pps_tf[0] - pps_tf[2];
1374 } else if (pps_tf[2] > pps_tf[0]) {
1375 pps_offset = pps_tf[0]; /* 2 0 1 */
1376 v_usec = pps_tf[2] - pps_tf[1];
1377 } else {
1378 pps_offset = pps_tf[2]; /* 0 2 1 */
1379 v_usec = pps_tf[0] - pps_tf[1];
1380 }
1381 } else {
1382 if (pps_tf[1] < pps_tf[2]) {
1383 pps_offset = pps_tf[1]; /* 2 1 0 */
1384 v_usec = pps_tf[2] - pps_tf[0];
1385 } else if (pps_tf[2] < pps_tf[0]) {
1386 pps_offset = pps_tf[0]; /* 1 0 2 */
1387 v_usec = pps_tf[1] - pps_tf[2];
1388 } else {
1389 pps_offset = pps_tf[2]; /* 1 2 0 */
1390 v_usec = pps_tf[1] - pps_tf[0];
1391 }
1392 }
1393 if (v_usec > MAXTIME)
1394 pps_jitcnt++;
1395 v_usec = (v_usec << PPS_AVG) - pps_jitter;
1396 if (v_usec < 0)
1397 pps_jitter -= -v_usec >> PPS_AVG;
1398 else
1399 pps_jitter += v_usec >> PPS_AVG;
1400 if (pps_jitter > (MAXTIME >> 1))
1401 time_status |= STA_PPSJITTER;
1402
1403 /*
1404 * During the calibration interval adjust the starting time when
1405 * the tick overflows. At the end of the interval compute the
1406 * duration of the interval and the difference of the hardware
1407 * counters at the beginning and end of the interval. This code
1408 * is deliciously complicated by the fact valid differences may
1409 * exceed the value of tick when using long calibration
1410 * intervals and small ticks. Note that the counter can be
1411 * greater than tick if caught at just the wrong instant, but
1412 * the values returned and used here are correct.
1413 */
1414 bigtick = (long)tick << SHIFT_USEC;
1415 pps_usec -= pps_freq;
1416 if (pps_usec >= bigtick)
1417 pps_usec -= bigtick;
1418 if (pps_usec < 0)
1419 pps_usec += bigtick;
1420 pps_time.tv_sec++;
1421 pps_count++;
1422 if (pps_count < (1 << pps_shift))
1423 return;
1424 pps_count = 0;
1425 pps_calcnt++;
1426 u_usec = usec << SHIFT_USEC;
1427 v_usec = pps_usec - u_usec;
1428 if (v_usec >= bigtick >> 1)
1429 v_usec -= bigtick;
1430 if (v_usec < -(bigtick >> 1))
1431 v_usec += bigtick;
1432 if (v_usec < 0)
1433 v_usec = -(-v_usec >> pps_shift);
1434 else
1435 v_usec = v_usec >> pps_shift;
1436 pps_usec = u_usec;
1437 cal_sec = tvp->tv_sec;
1438 cal_usec = tvp->tv_usec;
1439 cal_sec -= pps_time.tv_sec;
1440 cal_usec -= pps_time.tv_usec;
1441 if (cal_usec < 0) {
1442 cal_usec += 1000000;
1443 cal_sec--;
1444 }
1445 pps_time = *tvp;
1446
1447 /*
1448 * Check for lost interrupts, noise, excessive jitter and
1449 * excessive frequency error. The number of timer ticks during
1450 * the interval may vary +-1 tick. Add to this a margin of one
1451 * tick for the PPS signal jitter and maximum frequency
1452 * deviation. If the limits are exceeded, the calibration
1453 * interval is reset to the minimum and we start over.
1454 */
1455 u_usec = (long)tick << 1;
1456 if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
1457 || (cal_sec == 0 && cal_usec < u_usec))
1458 || v_usec > time_tolerance || v_usec < -time_tolerance) {
1459 pps_errcnt++;
1460 pps_shift = PPS_SHIFT;
1461 pps_intcnt = 0;
1462 time_status |= STA_PPSERROR;
1463 return;
1464 }
1465
1466 /*
1467 * A three-stage median filter is used to help deglitch the pps
1468 * frequency. The median sample becomes the frequency offset
1469 * estimate; the difference between the other two samples
1470 * becomes the frequency dispersion (stability) estimate.
1471 */
1472 pps_ff[2] = pps_ff[1];
1473 pps_ff[1] = pps_ff[0];
1474 pps_ff[0] = v_usec;
1475 if (pps_ff[0] > pps_ff[1]) {
1476 if (pps_ff[1] > pps_ff[2]) {
1477 u_usec = pps_ff[1]; /* 0 1 2 */
1478 v_usec = pps_ff[0] - pps_ff[2];
1479 } else if (pps_ff[2] > pps_ff[0]) {
1480 u_usec = pps_ff[0]; /* 2 0 1 */
1481 v_usec = pps_ff[2] - pps_ff[1];
1482 } else {
1483 u_usec = pps_ff[2]; /* 0 2 1 */
1484 v_usec = pps_ff[0] - pps_ff[1];
1485 }
1486 } else {
1487 if (pps_ff[1] < pps_ff[2]) {
1488 u_usec = pps_ff[1]; /* 2 1 0 */
1489 v_usec = pps_ff[2] - pps_ff[0];
1490 } else if (pps_ff[2] < pps_ff[0]) {
1491 u_usec = pps_ff[0]; /* 1 0 2 */
1492 v_usec = pps_ff[1] - pps_ff[2];
1493 } else {
1494 u_usec = pps_ff[2]; /* 1 2 0 */
1495 v_usec = pps_ff[1] - pps_ff[0];
1496 }
1497 }
1498
1499 /*
1500 * Here the frequency dispersion (stability) is updated. If it
1501 * is less than one-fourth the maximum (MAXFREQ), the frequency
1502 * offset is updated as well, but clamped to the tolerance. It
1503 * will be processed later by the hardclock() routine.
1504 */
1505 v_usec = (v_usec >> 1) - pps_stabil;
1506 if (v_usec < 0)
1507 pps_stabil -= -v_usec >> PPS_AVG;
1508 else
1509 pps_stabil += v_usec >> PPS_AVG;
1510 if (pps_stabil > MAXFREQ >> 2) {
1511 pps_stbcnt++;
1512 time_status |= STA_PPSWANDER;
1513 return;
1514 }
1515 if (time_status & STA_PPSFREQ) {
1516 if (u_usec < 0) {
1517 pps_freq -= -u_usec >> PPS_AVG;
1518 if (pps_freq < -time_tolerance)
1519 pps_freq = -time_tolerance;
1520 u_usec = -u_usec;
1521 } else {
1522 pps_freq += u_usec >> PPS_AVG;
1523 if (pps_freq > time_tolerance)
1524 pps_freq = time_tolerance;
1525 }
1526 }
1527
1528 /*
1529 * Here the calibration interval is adjusted. If the maximum
1530 * time difference is greater than tick / 4, reduce the interval
1531 * by half. If this is not the case for four consecutive
1532 * intervals, double the interval.
1533 */
1534 if (u_usec << pps_shift > bigtick >> 2) {
1535 pps_intcnt = 0;
1536 if (pps_shift > PPS_SHIFT)
1537 pps_shift--;
1538 } else if (pps_intcnt >= 4) {
1539 pps_intcnt = 0;
1540 if (pps_shift < PPS_SHIFTMAX)
1541 pps_shift++;
1542 } else
1543 pps_intcnt++;
1544 }
1545 #endif /* PPS_SYNC */
1546 #endif /* NTP */
1547
1548 /* timecounter compat functions */
1549 void
1550 nanotime(struct timespec *ts)
1551 {
1552 struct timeval tv;
1553
1554 microtime(&tv);
1555 TIMEVAL_TO_TIMESPEC(&tv, ts);
1556 }
1557
1558 void
1559 getbinuptime(struct bintime *bt)
1560 {
1561 struct timeval tv;
1562
1563 microtime(&tv);
1564 timeval2bintime(&tv, bt);
1565 }
1566
1567 void
1568 getnanouptime(struct timespec *tsp)
1569 {
1570 int s;
1571
1572 s = splclock();
1573 TIMEVAL_TO_TIMESPEC(&mono_time, tsp);
1574 splx(s);
1575 }
1576
1577 void
1578 getmicrouptime(struct timeval *tvp)
1579 {
1580 int s;
1581
1582 s = splclock();
1583 *tvp = mono_time;
1584 splx(s);
1585 }
1586
1587 void
1588 getnanotime(struct timespec *tsp)
1589 {
1590 int s;
1591
1592 s = splclock();
1593 TIMEVAL_TO_TIMESPEC(&time, tsp);
1594 splx(s);
1595 }
1596
1597 void
1598 getmicrotime(struct timeval *tvp)
1599 {
1600 int s;
1601
1602 s = splclock();
1603 *tvp = time;
1604 splx(s);
1605 }
1606 #endif /* !__HAVE_TIMECOUNTER */
1607