kern_clock.c revision 1.99 1 /* $NetBSD: kern_clock.c,v 1.99 2006/06/07 22:33:39 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.99 2006/06/07 22:33:39 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 u_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 #ifdef __HAVE_TIMECOUNTER
362 static u_int get_intr_timecount(struct timecounter *);
363
364 static struct timecounter intr_timecounter = {
365 get_intr_timecount, /* get_timecount */
366 0, /* no poll_pps */
367 ~0u, /* counter_mask */
368 0, /* frequency */
369 "clockinterrupt", /* name */
370 0 /* quality - minimum implementation level for a clock */
371 };
372
373 static u_int
374 get_intr_timecount(struct timecounter *tc)
375 {
376 return hardclock_ticks;
377 }
378 #endif
379
380 /*
381 * Initialize clock frequencies and start both clocks running.
382 */
383 void
384 initclocks(void)
385 {
386 int i;
387
388 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
389 softclock_si = softintr_establish(IPL_SOFTCLOCK, softclock, NULL);
390 if (softclock_si == NULL)
391 panic("initclocks: unable to register softclock intr");
392 #endif
393
394 /*
395 * Set divisors to 1 (normal case) and let the machine-specific
396 * code do its bit.
397 */
398 psdiv = 1;
399 #ifdef __HAVE_TIMECOUNTER
400 inittimecounter();
401 /*
402 * provide minimum default time counter
403 * will only run at interrupt resolution
404 */
405 intr_timecounter.tc_frequency = hz;
406 tc_init(&intr_timecounter);
407 #endif
408 cpu_initclocks();
409
410 /*
411 * Compute profhz/stathz/rrticks, and fix profhz if needed.
412 */
413 i = stathz ? stathz : hz;
414 if (profhz == 0)
415 profhz = i;
416 psratio = profhz / i;
417 rrticks = hz / 10;
418 if (schedhz == 0) {
419 /* 16Hz is best */
420 statscheddiv = i / 16;
421 if (statscheddiv <= 0)
422 panic("statscheddiv");
423 }
424
425 #ifndef __HAVE_TIMECOUNTER
426 #ifdef NTP
427 switch (hz) {
428 case 1:
429 shifthz = SHIFT_SCALE - 0;
430 break;
431 case 2:
432 shifthz = SHIFT_SCALE - 1;
433 break;
434 case 4:
435 shifthz = SHIFT_SCALE - 2;
436 break;
437 case 8:
438 shifthz = SHIFT_SCALE - 3;
439 break;
440 case 16:
441 shifthz = SHIFT_SCALE - 4;
442 break;
443 case 32:
444 shifthz = SHIFT_SCALE - 5;
445 break;
446 case 50:
447 case 60:
448 case 64:
449 shifthz = SHIFT_SCALE - 6;
450 break;
451 case 96:
452 case 100:
453 case 128:
454 shifthz = SHIFT_SCALE - 7;
455 break;
456 case 256:
457 shifthz = SHIFT_SCALE - 8;
458 break;
459 case 512:
460 shifthz = SHIFT_SCALE - 9;
461 break;
462 case 1000:
463 case 1024:
464 shifthz = SHIFT_SCALE - 10;
465 break;
466 case 1200:
467 case 2048:
468 shifthz = SHIFT_SCALE - 11;
469 break;
470 case 4096:
471 shifthz = SHIFT_SCALE - 12;
472 break;
473 case 8192:
474 shifthz = SHIFT_SCALE - 13;
475 break;
476 case 16384:
477 shifthz = SHIFT_SCALE - 14;
478 break;
479 case 32768:
480 shifthz = SHIFT_SCALE - 15;
481 break;
482 case 65536:
483 shifthz = SHIFT_SCALE - 16;
484 break;
485 default:
486 panic("weird hz");
487 }
488 if (fixtick == 0) {
489 /*
490 * Give MD code a chance to set this to a better
491 * value; but, if it doesn't, we should.
492 */
493 fixtick = (1000000 - (hz*tick));
494 }
495 #endif /* NTP */
496 #endif /* !__HAVE_TIMECOUNTER */
497 }
498
499 /*
500 * The real-time timer, interrupting hz times per second.
501 */
502 void
503 hardclock(struct clockframe *frame)
504 {
505 struct lwp *l;
506 struct proc *p;
507 struct cpu_info *ci = curcpu();
508 struct ptimer *pt;
509 #ifndef __HAVE_TIMECOUNTER
510 int delta;
511 extern int tickdelta;
512 extern long timedelta;
513 #ifdef NTP
514 int time_update;
515 int ltemp;
516 #endif /* NTP */
517 #endif /* __HAVE_TIMECOUNTER */
518
519 l = curlwp;
520 if (l) {
521 p = l->l_proc;
522 /*
523 * Run current process's virtual and profile time, as needed.
524 */
525 if (CLKF_USERMODE(frame) && p->p_timers &&
526 (pt = LIST_FIRST(&p->p_timers->pts_virtual)) != NULL)
527 if (itimerdecr(pt, tick) == 0)
528 itimerfire(pt);
529 if (p->p_timers &&
530 (pt = LIST_FIRST(&p->p_timers->pts_prof)) != NULL)
531 if (itimerdecr(pt, tick) == 0)
532 itimerfire(pt);
533 }
534
535 /*
536 * If no separate statistics clock is available, run it from here.
537 */
538 if (stathz == 0)
539 statclock(frame);
540 if ((--ci->ci_schedstate.spc_rrticks) <= 0)
541 roundrobin(ci);
542
543 #if defined(MULTIPROCESSOR)
544 /*
545 * If we are not the primary CPU, we're not allowed to do
546 * any more work.
547 */
548 if (CPU_IS_PRIMARY(ci) == 0)
549 return;
550 #endif
551
552 hardclock_ticks++;
553
554 #ifdef __HAVE_TIMECOUNTER
555 tc_ticktock();
556 #else /* __HAVE_TIMECOUNTER */
557 /*
558 * Increment the time-of-day. The increment is normally just
559 * ``tick''. If the machine is one which has a clock frequency
560 * such that ``hz'' would not divide the second evenly into
561 * milliseconds, a periodic adjustment must be applied. Finally,
562 * if we are still adjusting the time (see adjtime()),
563 * ``tickdelta'' may also be added in.
564 */
565 delta = tick;
566
567 #ifndef NTP
568 if (tickfix) {
569 tickfixcnt += tickfix;
570 if (tickfixcnt >= tickfixinterval) {
571 delta++;
572 tickfixcnt -= tickfixinterval;
573 }
574 }
575 #endif /* !NTP */
576 /* Imprecise 4bsd adjtime() handling */
577 if (timedelta != 0) {
578 delta += tickdelta;
579 timedelta -= tickdelta;
580 }
581
582 #ifdef notyet
583 microset();
584 #endif
585
586 #ifndef NTP
587 BUMPTIME(&time, delta); /* XXX Now done using NTP code below */
588 #endif
589 BUMPTIME(&mono_time, delta);
590
591 #ifdef NTP
592 time_update = delta;
593
594 /*
595 * Compute the phase adjustment. If the low-order bits
596 * (time_phase) of the update overflow, bump the high-order bits
597 * (time_update).
598 */
599 time_phase += time_adj;
600 if (time_phase <= -FINEUSEC) {
601 ltemp = -time_phase >> SHIFT_SCALE;
602 time_phase += ltemp << SHIFT_SCALE;
603 time_update -= ltemp;
604 } else if (time_phase >= FINEUSEC) {
605 ltemp = time_phase >> SHIFT_SCALE;
606 time_phase -= ltemp << SHIFT_SCALE;
607 time_update += ltemp;
608 }
609
610 #ifdef HIGHBALL
611 /*
612 * If the HIGHBALL board is installed, we need to adjust the
613 * external clock offset in order to close the hardware feedback
614 * loop. This will adjust the external clock phase and frequency
615 * in small amounts. The additional phase noise and frequency
616 * wander this causes should be minimal. We also need to
617 * discipline the kernel time variable, since the PLL is used to
618 * discipline the external clock. If the Highball board is not
619 * present, we discipline kernel time with the PLL as usual. We
620 * assume that the external clock phase adjustment (time_update)
621 * and kernel phase adjustment (clock_cpu) are less than the
622 * value of tick.
623 */
624 clock_offset.tv_usec += time_update;
625 if (clock_offset.tv_usec >= 1000000) {
626 clock_offset.tv_sec++;
627 clock_offset.tv_usec -= 1000000;
628 }
629 if (clock_offset.tv_usec < 0) {
630 clock_offset.tv_sec--;
631 clock_offset.tv_usec += 1000000;
632 }
633 time.tv_usec += clock_cpu;
634 clock_cpu = 0;
635 #else
636 time.tv_usec += time_update;
637 #endif /* HIGHBALL */
638
639 /*
640 * On rollover of the second the phase adjustment to be used for
641 * the next second is calculated. Also, the maximum error is
642 * increased by the tolerance. If the PPS frequency discipline
643 * code is present, the phase is increased to compensate for the
644 * CPU clock oscillator frequency error.
645 *
646 * On a 32-bit machine and given parameters in the timex.h
647 * header file, the maximum phase adjustment is +-512 ms and
648 * maximum frequency offset is a tad less than) +-512 ppm. On a
649 * 64-bit machine, you shouldn't need to ask.
650 */
651 if (time.tv_usec >= 1000000) {
652 time.tv_usec -= 1000000;
653 time.tv_sec++;
654 time_maxerror += time_tolerance >> SHIFT_USEC;
655
656 /*
657 * Leap second processing. If in leap-insert state at
658 * the end of the day, the system clock is set back one
659 * second; if in leap-delete state, the system clock is
660 * set ahead one second. The microtime() routine or
661 * external clock driver will insure that reported time
662 * is always monotonic. The ugly divides should be
663 * replaced.
664 */
665 switch (time_state) {
666 case TIME_OK:
667 if (time_status & STA_INS)
668 time_state = TIME_INS;
669 else if (time_status & STA_DEL)
670 time_state = TIME_DEL;
671 break;
672
673 case TIME_INS:
674 if (time.tv_sec % 86400 == 0) {
675 time.tv_sec--;
676 time_state = TIME_OOP;
677 }
678 break;
679
680 case TIME_DEL:
681 if ((time.tv_sec + 1) % 86400 == 0) {
682 time.tv_sec++;
683 time_state = TIME_WAIT;
684 }
685 break;
686
687 case TIME_OOP:
688 time_state = TIME_WAIT;
689 break;
690
691 case TIME_WAIT:
692 if (!(time_status & (STA_INS | STA_DEL)))
693 time_state = TIME_OK;
694 break;
695 }
696
697 /*
698 * Compute the phase adjustment for the next second. In
699 * PLL mode, the offset is reduced by a fixed factor
700 * times the time constant. In FLL mode the offset is
701 * used directly. In either mode, the maximum phase
702 * adjustment for each second is clamped so as to spread
703 * the adjustment over not more than the number of
704 * seconds between updates.
705 */
706 if (time_offset < 0) {
707 ltemp = -time_offset;
708 if (!(time_status & STA_FLL))
709 ltemp >>= SHIFT_KG + time_constant;
710 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
711 ltemp = (MAXPHASE / MINSEC) <<
712 SHIFT_UPDATE;
713 time_offset += ltemp;
714 time_adj = -ltemp << (shifthz - SHIFT_UPDATE);
715 } else if (time_offset > 0) {
716 ltemp = time_offset;
717 if (!(time_status & STA_FLL))
718 ltemp >>= SHIFT_KG + time_constant;
719 if (ltemp > (MAXPHASE / MINSEC) << SHIFT_UPDATE)
720 ltemp = (MAXPHASE / MINSEC) <<
721 SHIFT_UPDATE;
722 time_offset -= ltemp;
723 time_adj = ltemp << (shifthz - SHIFT_UPDATE);
724 } else
725 time_adj = 0;
726
727 /*
728 * Compute the frequency estimate and additional phase
729 * adjustment due to frequency error for the next
730 * second. When the PPS signal is engaged, gnaw on the
731 * watchdog counter and update the frequency computed by
732 * the pll and the PPS signal.
733 */
734 #ifdef PPS_SYNC
735 pps_valid++;
736 if (pps_valid == PPS_VALID) {
737 pps_jitter = MAXTIME;
738 pps_stabil = MAXFREQ;
739 time_status &= ~(STA_PPSSIGNAL | STA_PPSJITTER |
740 STA_PPSWANDER | STA_PPSERROR);
741 }
742 ltemp = time_freq + pps_freq;
743 #else
744 ltemp = time_freq;
745 #endif /* PPS_SYNC */
746
747 if (ltemp < 0)
748 time_adj -= -ltemp >> (SHIFT_USEC - shifthz);
749 else
750 time_adj += ltemp >> (SHIFT_USEC - shifthz);
751 time_adj += (long)fixtick << shifthz;
752
753 /*
754 * When the CPU clock oscillator frequency is not a
755 * power of 2 in Hz, shifthz is only an approximate
756 * scale factor.
757 *
758 * To determine the adjustment, you can do the following:
759 * bc -q
760 * scale=24
761 * obase=2
762 * idealhz/realhz
763 * where `idealhz' is the next higher power of 2, and `realhz'
764 * is the actual value. You may need to factor this result
765 * into a sequence of 2 multipliers to get better precision.
766 *
767 * Likewise, the error can be calculated with (e.g. for 100Hz):
768 * bc -q
769 * scale=24
770 * ((1+2^-2+2^-5)*(1-2^-10)*realhz-idealhz)/idealhz
771 * (and then multiply by 1000000 to get ppm).
772 */
773 switch (hz) {
774 case 60:
775 /* A factor of 1.000100010001 gives about 15ppm
776 error. */
777 if (time_adj < 0) {
778 time_adj -= (-time_adj >> 4);
779 time_adj -= (-time_adj >> 8);
780 } else {
781 time_adj += (time_adj >> 4);
782 time_adj += (time_adj >> 8);
783 }
784 break;
785
786 case 96:
787 /* A factor of 1.0101010101 gives about 244ppm error. */
788 if (time_adj < 0) {
789 time_adj -= (-time_adj >> 2);
790 time_adj -= (-time_adj >> 4) + (-time_adj >> 8);
791 } else {
792 time_adj += (time_adj >> 2);
793 time_adj += (time_adj >> 4) + (time_adj >> 8);
794 }
795 break;
796
797 case 50:
798 case 100:
799 /* A factor of 1.010001111010111 gives about 1ppm
800 error. */
801 if (time_adj < 0) {
802 time_adj -= (-time_adj >> 2) + (-time_adj >> 5);
803 time_adj += (-time_adj >> 10);
804 } else {
805 time_adj += (time_adj >> 2) + (time_adj >> 5);
806 time_adj -= (time_adj >> 10);
807 }
808 break;
809
810 case 1000:
811 /* A factor of 1.000001100010100001 gives about 50ppm
812 error. */
813 if (time_adj < 0) {
814 time_adj -= (-time_adj >> 6) + (-time_adj >> 11);
815 time_adj -= (-time_adj >> 7);
816 } else {
817 time_adj += (time_adj >> 6) + (time_adj >> 11);
818 time_adj += (time_adj >> 7);
819 }
820 break;
821
822 case 1200:
823 /* A factor of 1.1011010011100001 gives about 64ppm
824 error. */
825 if (time_adj < 0) {
826 time_adj -= (-time_adj >> 1) + (-time_adj >> 6);
827 time_adj -= (-time_adj >> 3) + (-time_adj >> 10);
828 } else {
829 time_adj += (time_adj >> 1) + (time_adj >> 6);
830 time_adj += (time_adj >> 3) + (time_adj >> 10);
831 }
832 break;
833 }
834
835 #ifdef EXT_CLOCK
836 /*
837 * If an external clock is present, it is necessary to
838 * discipline the kernel time variable anyway, since not
839 * all system components use the microtime() interface.
840 * Here, the time offset between the external clock and
841 * kernel time variable is computed every so often.
842 */
843 clock_count++;
844 if (clock_count > CLOCK_INTERVAL) {
845 clock_count = 0;
846 microtime(&clock_ext);
847 delta.tv_sec = clock_ext.tv_sec - time.tv_sec;
848 delta.tv_usec = clock_ext.tv_usec -
849 time.tv_usec;
850 if (delta.tv_usec < 0)
851 delta.tv_sec--;
852 if (delta.tv_usec >= 500000) {
853 delta.tv_usec -= 1000000;
854 delta.tv_sec++;
855 }
856 if (delta.tv_usec < -500000) {
857 delta.tv_usec += 1000000;
858 delta.tv_sec--;
859 }
860 if (delta.tv_sec > 0 || (delta.tv_sec == 0 &&
861 delta.tv_usec > MAXPHASE) ||
862 delta.tv_sec < -1 || (delta.tv_sec == -1 &&
863 delta.tv_usec < -MAXPHASE)) {
864 time = clock_ext;
865 delta.tv_sec = 0;
866 delta.tv_usec = 0;
867 }
868 #ifdef HIGHBALL
869 clock_cpu = delta.tv_usec;
870 #else /* HIGHBALL */
871 hardupdate(delta.tv_usec);
872 #endif /* HIGHBALL */
873 }
874 #endif /* EXT_CLOCK */
875 }
876
877 #endif /* NTP */
878 #endif /* !__HAVE_TIMECOUNTER */
879
880 /*
881 * Update real-time timeout queue.
882 * Process callouts at a very low CPU priority, so we don't keep the
883 * relatively high clock interrupt priority any longer than necessary.
884 */
885 if (callout_hardclock()) {
886 if (CLKF_BASEPRI(frame)) {
887 /*
888 * Save the overhead of a software interrupt;
889 * it will happen as soon as we return, so do
890 * it now.
891 */
892 spllowersoftclock();
893 KERNEL_LOCK(LK_CANRECURSE|LK_EXCLUSIVE);
894 softclock(NULL);
895 KERNEL_UNLOCK();
896 } else {
897 #ifdef __HAVE_GENERIC_SOFT_INTERRUPTS
898 softintr_schedule(softclock_si);
899 #else
900 setsoftclock();
901 #endif
902 }
903 }
904 }
905
906 #ifdef __HAVE_TIMECOUNTER
907 /*
908 * Compute number of hz until specified time. Used to compute second
909 * argument to callout_reset() from an absolute time.
910 */
911 int
912 hzto(struct timeval *tvp)
913 {
914 struct timeval now, tv;
915
916 tv = *tvp; /* Don't modify original tvp. */
917 getmicrotime(&now);
918 timersub(&tv, &now, &tv);
919 return tvtohz(&tv);
920 }
921 #endif /* __HAVE_TIMECOUNTER */
922
923 /*
924 * Compute number of ticks in the specified amount of time.
925 */
926 int
927 tvtohz(struct timeval *tv)
928 {
929 unsigned long ticks;
930 long sec, usec;
931
932 /*
933 * If the number of usecs in the whole seconds part of the time
934 * difference fits in a long, then the total number of usecs will
935 * fit in an unsigned long. Compute the total and convert it to
936 * ticks, rounding up and adding 1 to allow for the current tick
937 * to expire. Rounding also depends on unsigned long arithmetic
938 * to avoid overflow.
939 *
940 * Otherwise, if the number of ticks in the whole seconds part of
941 * the time difference fits in a long, then convert the parts to
942 * ticks separately and add, using similar rounding methods and
943 * overflow avoidance. This method would work in the previous
944 * case, but it is slightly slower and assumes that hz is integral.
945 *
946 * Otherwise, round the time difference down to the maximum
947 * representable value.
948 *
949 * If ints are 32-bit, then the maximum value for any timeout in
950 * 10ms ticks is 248 days.
951 */
952 sec = tv->tv_sec;
953 usec = tv->tv_usec;
954
955 if (usec < 0) {
956 sec--;
957 usec += 1000000;
958 }
959
960 if (sec < 0 || (sec == 0 && usec <= 0)) {
961 /*
962 * Would expire now or in the past. Return 0 ticks.
963 * This is different from the legacy hzto() interface,
964 * and callers need to check for it.
965 */
966 ticks = 0;
967 } else if (sec <= (LONG_MAX / 1000000))
968 ticks = (((sec * 1000000) + (unsigned long)usec + (tick - 1))
969 / tick) + 1;
970 else if (sec <= (LONG_MAX / hz))
971 ticks = (sec * hz) +
972 (((unsigned long)usec + (tick - 1)) / tick) + 1;
973 else
974 ticks = LONG_MAX;
975
976 if (ticks > INT_MAX)
977 ticks = INT_MAX;
978
979 return ((int)ticks);
980 }
981
982 #ifndef __HAVE_TIMECOUNTER
983 /*
984 * Compute number of hz until specified time. Used to compute second
985 * argument to callout_reset() from an absolute time.
986 */
987 int
988 hzto(struct timeval *tv)
989 {
990 unsigned long ticks;
991 long sec, usec;
992 int s;
993
994 /*
995 * If the number of usecs in the whole seconds part of the time
996 * difference fits in a long, then the total number of usecs will
997 * fit in an unsigned long. Compute the total and convert it to
998 * ticks, rounding up and adding 1 to allow for the current tick
999 * to expire. Rounding also depends on unsigned long arithmetic
1000 * to avoid overflow.
1001 *
1002 * Otherwise, if the number of ticks in the whole seconds part of
1003 * the time difference fits in a long, then convert the parts to
1004 * ticks separately and add, using similar rounding methods and
1005 * overflow avoidance. This method would work in the previous
1006 * case, but it is slightly slower and assume that hz is integral.
1007 *
1008 * Otherwise, round the time difference down to the maximum
1009 * representable value.
1010 *
1011 * If ints are 32-bit, then the maximum value for any timeout in
1012 * 10ms ticks is 248 days.
1013 */
1014 s = splclock();
1015 sec = tv->tv_sec - time.tv_sec;
1016 usec = tv->tv_usec - time.tv_usec;
1017 splx(s);
1018
1019 if (usec < 0) {
1020 sec--;
1021 usec += 1000000;
1022 }
1023
1024 if (sec < 0 || (sec == 0 && usec <= 0)) {
1025 /*
1026 * Would expire now or in the past. Return 0 ticks.
1027 * This is different from the legacy hzto() interface,
1028 * and callers need to check for it.
1029 */
1030 ticks = 0;
1031 } else if (sec <= (LONG_MAX / 1000000))
1032 ticks = (((sec * 1000000) + (unsigned long)usec + (tick - 1))
1033 / tick) + 1;
1034 else if (sec <= (LONG_MAX / hz))
1035 ticks = (sec * hz) +
1036 (((unsigned long)usec + (tick - 1)) / tick) + 1;
1037 else
1038 ticks = LONG_MAX;
1039
1040 if (ticks > INT_MAX)
1041 ticks = INT_MAX;
1042
1043 return ((int)ticks);
1044 }
1045 #endif /* !__HAVE_TIMECOUNTER */
1046
1047 /*
1048 * Compute number of ticks in the specified amount of time.
1049 */
1050 int
1051 tstohz(struct timespec *ts)
1052 {
1053 struct timeval tv;
1054
1055 /*
1056 * usec has great enough resolution for hz, so convert to a
1057 * timeval and use tvtohz() above.
1058 */
1059 TIMESPEC_TO_TIMEVAL(&tv, ts);
1060 return tvtohz(&tv);
1061 }
1062
1063 /*
1064 * Start profiling on a process.
1065 *
1066 * Kernel profiling passes proc0 which never exits and hence
1067 * keeps the profile clock running constantly.
1068 */
1069 void
1070 startprofclock(struct proc *p)
1071 {
1072
1073 if ((p->p_flag & P_PROFIL) == 0) {
1074 p->p_flag |= P_PROFIL;
1075 /*
1076 * This is only necessary if using the clock as the
1077 * profiling source.
1078 */
1079 if (++profprocs == 1 && stathz != 0)
1080 psdiv = psratio;
1081 }
1082 }
1083
1084 /*
1085 * Stop profiling on a process.
1086 */
1087 void
1088 stopprofclock(struct proc *p)
1089 {
1090
1091 if (p->p_flag & P_PROFIL) {
1092 p->p_flag &= ~P_PROFIL;
1093 /*
1094 * This is only necessary if using the clock as the
1095 * profiling source.
1096 */
1097 if (--profprocs == 0 && stathz != 0)
1098 psdiv = 1;
1099 }
1100 }
1101
1102 #if defined(PERFCTRS)
1103 /*
1104 * Independent profiling "tick" in case we're using a separate
1105 * clock or profiling event source. Currently, that's just
1106 * performance counters--hence the wrapper.
1107 */
1108 void
1109 proftick(struct clockframe *frame)
1110 {
1111 #ifdef GPROF
1112 struct gmonparam *g;
1113 intptr_t i;
1114 #endif
1115 struct proc *p;
1116
1117 p = curproc;
1118 if (CLKF_USERMODE(frame)) {
1119 if (p->p_flag & P_PROFIL)
1120 addupc_intr(p, CLKF_PC(frame));
1121 } else {
1122 #ifdef GPROF
1123 g = &_gmonparam;
1124 if (g->state == GMON_PROF_ON) {
1125 i = CLKF_PC(frame) - g->lowpc;
1126 if (i < g->textsize) {
1127 i /= HISTFRACTION * sizeof(*g->kcount);
1128 g->kcount[i]++;
1129 }
1130 }
1131 #endif
1132 #ifdef PROC_PC
1133 if (p && (p->p_flag & P_PROFIL))
1134 addupc_intr(p, PROC_PC(p));
1135 #endif
1136 }
1137 }
1138 #endif
1139
1140 /*
1141 * Statistics clock. Grab profile sample, and if divider reaches 0,
1142 * do process and kernel statistics.
1143 */
1144 void
1145 statclock(struct clockframe *frame)
1146 {
1147 #ifdef GPROF
1148 struct gmonparam *g;
1149 intptr_t i;
1150 #endif
1151 struct cpu_info *ci = curcpu();
1152 struct schedstate_percpu *spc = &ci->ci_schedstate;
1153 struct proc *p;
1154 struct lwp *l;
1155
1156 /*
1157 * Notice changes in divisor frequency, and adjust clock
1158 * frequency accordingly.
1159 */
1160 if (spc->spc_psdiv != psdiv) {
1161 spc->spc_psdiv = psdiv;
1162 spc->spc_pscnt = psdiv;
1163 if (psdiv == 1) {
1164 setstatclockrate(stathz);
1165 } else {
1166 setstatclockrate(profhz);
1167 }
1168 }
1169 l = curlwp;
1170 p = (l ? l->l_proc : NULL);
1171 if (CLKF_USERMODE(frame)) {
1172 KASSERT(p != NULL);
1173
1174 if ((p->p_flag & P_PROFIL) && profsrc == PROFSRC_CLOCK)
1175 addupc_intr(p, CLKF_PC(frame));
1176 if (--spc->spc_pscnt > 0)
1177 return;
1178 /*
1179 * Came from user mode; CPU was in user state.
1180 * If this process is being profiled record the tick.
1181 */
1182 p->p_uticks++;
1183 if (p->p_nice > NZERO)
1184 spc->spc_cp_time[CP_NICE]++;
1185 else
1186 spc->spc_cp_time[CP_USER]++;
1187 } else {
1188 #ifdef GPROF
1189 /*
1190 * Kernel statistics are just like addupc_intr, only easier.
1191 */
1192 g = &_gmonparam;
1193 if (profsrc == PROFSRC_CLOCK && g->state == GMON_PROF_ON) {
1194 i = CLKF_PC(frame) - g->lowpc;
1195 if (i < g->textsize) {
1196 i /= HISTFRACTION * sizeof(*g->kcount);
1197 g->kcount[i]++;
1198 }
1199 }
1200 #endif
1201 #ifdef LWP_PC
1202 if (p && profsrc == PROFSRC_CLOCK && (p->p_flag & P_PROFIL))
1203 addupc_intr(p, LWP_PC(l));
1204 #endif
1205 if (--spc->spc_pscnt > 0)
1206 return;
1207 /*
1208 * Came from kernel mode, so we were:
1209 * - handling an interrupt,
1210 * - doing syscall or trap work on behalf of the current
1211 * user process, or
1212 * - spinning in the idle loop.
1213 * Whichever it is, charge the time as appropriate.
1214 * Note that we charge interrupts to the current process,
1215 * regardless of whether they are ``for'' that process,
1216 * so that we know how much of its real time was spent
1217 * in ``non-process'' (i.e., interrupt) work.
1218 */
1219 if (CLKF_INTR(frame)) {
1220 if (p != NULL)
1221 p->p_iticks++;
1222 spc->spc_cp_time[CP_INTR]++;
1223 } else if (p != NULL) {
1224 p->p_sticks++;
1225 spc->spc_cp_time[CP_SYS]++;
1226 } else
1227 spc->spc_cp_time[CP_IDLE]++;
1228 }
1229 spc->spc_pscnt = psdiv;
1230
1231 if (p != NULL) {
1232 ++p->p_cpticks;
1233 /*
1234 * If no separate schedclock is provided, call it here
1235 * at about 16 Hz.
1236 */
1237 if (schedhz == 0)
1238 if ((int)(--ci->ci_schedstate.spc_schedticks) <= 0) {
1239 schedclock(l);
1240 ci->ci_schedstate.spc_schedticks = statscheddiv;
1241 }
1242 }
1243 }
1244
1245 #ifndef __HAVE_TIMECOUNTER
1246 #ifdef NTP /* NTP phase-locked loop in kernel */
1247 /*
1248 * hardupdate() - local clock update
1249 *
1250 * This routine is called by ntp_adjtime() to update the local clock
1251 * phase and frequency. The implementation is of an adaptive-parameter,
1252 * hybrid phase/frequency-lock loop (PLL/FLL). The routine computes new
1253 * time and frequency offset estimates for each call. If the kernel PPS
1254 * discipline code is configured (PPS_SYNC), the PPS signal itself
1255 * determines the new time offset, instead of the calling argument.
1256 * Presumably, calls to ntp_adjtime() occur only when the caller
1257 * believes the local clock is valid within some bound (+-128 ms with
1258 * NTP). If the caller's time is far different than the PPS time, an
1259 * argument will ensue, and it's not clear who will lose.
1260 *
1261 * For uncompensated quartz crystal oscillatores and nominal update
1262 * intervals less than 1024 s, operation should be in phase-lock mode
1263 * (STA_FLL = 0), where the loop is disciplined to phase. For update
1264 * intervals greater than thiss, operation should be in frequency-lock
1265 * mode (STA_FLL = 1), where the loop is disciplined to frequency.
1266 *
1267 * Note: splclock() is in effect.
1268 */
1269 void
1270 hardupdate(long offset)
1271 {
1272 long ltemp, mtemp;
1273
1274 if (!(time_status & STA_PLL) && !(time_status & STA_PPSTIME))
1275 return;
1276 ltemp = offset;
1277 #ifdef PPS_SYNC
1278 if (time_status & STA_PPSTIME && time_status & STA_PPSSIGNAL)
1279 ltemp = pps_offset;
1280 #endif /* PPS_SYNC */
1281
1282 /*
1283 * Scale the phase adjustment and clamp to the operating range.
1284 */
1285 if (ltemp > MAXPHASE)
1286 time_offset = MAXPHASE << SHIFT_UPDATE;
1287 else if (ltemp < -MAXPHASE)
1288 time_offset = -(MAXPHASE << SHIFT_UPDATE);
1289 else
1290 time_offset = ltemp << SHIFT_UPDATE;
1291
1292 /*
1293 * Select whether the frequency is to be controlled and in which
1294 * mode (PLL or FLL). Clamp to the operating range. Ugly
1295 * multiply/divide should be replaced someday.
1296 */
1297 if (time_status & STA_FREQHOLD || time_reftime == 0)
1298 time_reftime = time.tv_sec;
1299 mtemp = time.tv_sec - time_reftime;
1300 time_reftime = time.tv_sec;
1301 if (time_status & STA_FLL) {
1302 if (mtemp >= MINSEC) {
1303 ltemp = ((time_offset / mtemp) << (SHIFT_USEC -
1304 SHIFT_UPDATE));
1305 if (ltemp < 0)
1306 time_freq -= -ltemp >> SHIFT_KH;
1307 else
1308 time_freq += ltemp >> SHIFT_KH;
1309 }
1310 } else {
1311 if (mtemp < MAXSEC) {
1312 ltemp *= mtemp;
1313 if (ltemp < 0)
1314 time_freq -= -ltemp >> (time_constant +
1315 time_constant + SHIFT_KF -
1316 SHIFT_USEC);
1317 else
1318 time_freq += ltemp >> (time_constant +
1319 time_constant + SHIFT_KF -
1320 SHIFT_USEC);
1321 }
1322 }
1323 if (time_freq > time_tolerance)
1324 time_freq = time_tolerance;
1325 else if (time_freq < -time_tolerance)
1326 time_freq = -time_tolerance;
1327 }
1328
1329 #ifdef PPS_SYNC
1330 /*
1331 * hardpps() - discipline CPU clock oscillator to external PPS signal
1332 *
1333 * This routine is called at each PPS interrupt in order to discipline
1334 * the CPU clock oscillator to the PPS signal. It measures the PPS phase
1335 * and leaves it in a handy spot for the hardclock() routine. It
1336 * integrates successive PPS phase differences and calculates the
1337 * frequency offset. This is used in hardclock() to discipline the CPU
1338 * clock oscillator so that intrinsic frequency error is cancelled out.
1339 * The code requires the caller to capture the time and hardware counter
1340 * value at the on-time PPS signal transition.
1341 *
1342 * Note that, on some Unix systems, this routine runs at an interrupt
1343 * priority level higher than the timer interrupt routine hardclock().
1344 * Therefore, the variables used are distinct from the hardclock()
1345 * variables, except for certain exceptions: The PPS frequency pps_freq
1346 * and phase pps_offset variables are determined by this routine and
1347 * updated atomically. The time_tolerance variable can be considered a
1348 * constant, since it is infrequently changed, and then only when the
1349 * PPS signal is disabled. The watchdog counter pps_valid is updated
1350 * once per second by hardclock() and is atomically cleared in this
1351 * routine.
1352 */
1353 void
1354 hardpps(struct timeval *tvp, /* time at PPS */
1355 long usec /* hardware counter at PPS */)
1356 {
1357 long u_usec, v_usec, bigtick;
1358 long cal_sec, cal_usec;
1359
1360 /*
1361 * An occasional glitch can be produced when the PPS interrupt
1362 * occurs in the hardclock() routine before the time variable is
1363 * updated. Here the offset is discarded when the difference
1364 * between it and the last one is greater than tick/2, but not
1365 * if the interval since the first discard exceeds 30 s.
1366 */
1367 time_status |= STA_PPSSIGNAL;
1368 time_status &= ~(STA_PPSJITTER | STA_PPSWANDER | STA_PPSERROR);
1369 pps_valid = 0;
1370 u_usec = -tvp->tv_usec;
1371 if (u_usec < -500000)
1372 u_usec += 1000000;
1373 v_usec = pps_offset - u_usec;
1374 if (v_usec < 0)
1375 v_usec = -v_usec;
1376 if (v_usec > (tick >> 1)) {
1377 if (pps_glitch > MAXGLITCH) {
1378 pps_glitch = 0;
1379 pps_tf[2] = u_usec;
1380 pps_tf[1] = u_usec;
1381 } else {
1382 pps_glitch++;
1383 u_usec = pps_offset;
1384 }
1385 } else
1386 pps_glitch = 0;
1387
1388 /*
1389 * A three-stage median filter is used to help deglitch the pps
1390 * time. The median sample becomes the time offset estimate; the
1391 * difference between the other two samples becomes the time
1392 * dispersion (jitter) estimate.
1393 */
1394 pps_tf[2] = pps_tf[1];
1395 pps_tf[1] = pps_tf[0];
1396 pps_tf[0] = u_usec;
1397 if (pps_tf[0] > pps_tf[1]) {
1398 if (pps_tf[1] > pps_tf[2]) {
1399 pps_offset = pps_tf[1]; /* 0 1 2 */
1400 v_usec = pps_tf[0] - pps_tf[2];
1401 } else if (pps_tf[2] > pps_tf[0]) {
1402 pps_offset = pps_tf[0]; /* 2 0 1 */
1403 v_usec = pps_tf[2] - pps_tf[1];
1404 } else {
1405 pps_offset = pps_tf[2]; /* 0 2 1 */
1406 v_usec = pps_tf[0] - pps_tf[1];
1407 }
1408 } else {
1409 if (pps_tf[1] < pps_tf[2]) {
1410 pps_offset = pps_tf[1]; /* 2 1 0 */
1411 v_usec = pps_tf[2] - pps_tf[0];
1412 } else if (pps_tf[2] < pps_tf[0]) {
1413 pps_offset = pps_tf[0]; /* 1 0 2 */
1414 v_usec = pps_tf[1] - pps_tf[2];
1415 } else {
1416 pps_offset = pps_tf[2]; /* 1 2 0 */
1417 v_usec = pps_tf[1] - pps_tf[0];
1418 }
1419 }
1420 if (v_usec > MAXTIME)
1421 pps_jitcnt++;
1422 v_usec = (v_usec << PPS_AVG) - pps_jitter;
1423 if (v_usec < 0)
1424 pps_jitter -= -v_usec >> PPS_AVG;
1425 else
1426 pps_jitter += v_usec >> PPS_AVG;
1427 if (pps_jitter > (MAXTIME >> 1))
1428 time_status |= STA_PPSJITTER;
1429
1430 /*
1431 * During the calibration interval adjust the starting time when
1432 * the tick overflows. At the end of the interval compute the
1433 * duration of the interval and the difference of the hardware
1434 * counters at the beginning and end of the interval. This code
1435 * is deliciously complicated by the fact valid differences may
1436 * exceed the value of tick when using long calibration
1437 * intervals and small ticks. Note that the counter can be
1438 * greater than tick if caught at just the wrong instant, but
1439 * the values returned and used here are correct.
1440 */
1441 bigtick = (long)tick << SHIFT_USEC;
1442 pps_usec -= pps_freq;
1443 if (pps_usec >= bigtick)
1444 pps_usec -= bigtick;
1445 if (pps_usec < 0)
1446 pps_usec += bigtick;
1447 pps_time.tv_sec++;
1448 pps_count++;
1449 if (pps_count < (1 << pps_shift))
1450 return;
1451 pps_count = 0;
1452 pps_calcnt++;
1453 u_usec = usec << SHIFT_USEC;
1454 v_usec = pps_usec - u_usec;
1455 if (v_usec >= bigtick >> 1)
1456 v_usec -= bigtick;
1457 if (v_usec < -(bigtick >> 1))
1458 v_usec += bigtick;
1459 if (v_usec < 0)
1460 v_usec = -(-v_usec >> pps_shift);
1461 else
1462 v_usec = v_usec >> pps_shift;
1463 pps_usec = u_usec;
1464 cal_sec = tvp->tv_sec;
1465 cal_usec = tvp->tv_usec;
1466 cal_sec -= pps_time.tv_sec;
1467 cal_usec -= pps_time.tv_usec;
1468 if (cal_usec < 0) {
1469 cal_usec += 1000000;
1470 cal_sec--;
1471 }
1472 pps_time = *tvp;
1473
1474 /*
1475 * Check for lost interrupts, noise, excessive jitter and
1476 * excessive frequency error. The number of timer ticks during
1477 * the interval may vary +-1 tick. Add to this a margin of one
1478 * tick for the PPS signal jitter and maximum frequency
1479 * deviation. If the limits are exceeded, the calibration
1480 * interval is reset to the minimum and we start over.
1481 */
1482 u_usec = (long)tick << 1;
1483 if (!((cal_sec == -1 && cal_usec > (1000000 - u_usec))
1484 || (cal_sec == 0 && cal_usec < u_usec))
1485 || v_usec > time_tolerance || v_usec < -time_tolerance) {
1486 pps_errcnt++;
1487 pps_shift = PPS_SHIFT;
1488 pps_intcnt = 0;
1489 time_status |= STA_PPSERROR;
1490 return;
1491 }
1492
1493 /*
1494 * A three-stage median filter is used to help deglitch the pps
1495 * frequency. The median sample becomes the frequency offset
1496 * estimate; the difference between the other two samples
1497 * becomes the frequency dispersion (stability) estimate.
1498 */
1499 pps_ff[2] = pps_ff[1];
1500 pps_ff[1] = pps_ff[0];
1501 pps_ff[0] = v_usec;
1502 if (pps_ff[0] > pps_ff[1]) {
1503 if (pps_ff[1] > pps_ff[2]) {
1504 u_usec = pps_ff[1]; /* 0 1 2 */
1505 v_usec = pps_ff[0] - pps_ff[2];
1506 } else if (pps_ff[2] > pps_ff[0]) {
1507 u_usec = pps_ff[0]; /* 2 0 1 */
1508 v_usec = pps_ff[2] - pps_ff[1];
1509 } else {
1510 u_usec = pps_ff[2]; /* 0 2 1 */
1511 v_usec = pps_ff[0] - pps_ff[1];
1512 }
1513 } else {
1514 if (pps_ff[1] < pps_ff[2]) {
1515 u_usec = pps_ff[1]; /* 2 1 0 */
1516 v_usec = pps_ff[2] - pps_ff[0];
1517 } else if (pps_ff[2] < pps_ff[0]) {
1518 u_usec = pps_ff[0]; /* 1 0 2 */
1519 v_usec = pps_ff[1] - pps_ff[2];
1520 } else {
1521 u_usec = pps_ff[2]; /* 1 2 0 */
1522 v_usec = pps_ff[1] - pps_ff[0];
1523 }
1524 }
1525
1526 /*
1527 * Here the frequency dispersion (stability) is updated. If it
1528 * is less than one-fourth the maximum (MAXFREQ), the frequency
1529 * offset is updated as well, but clamped to the tolerance. It
1530 * will be processed later by the hardclock() routine.
1531 */
1532 v_usec = (v_usec >> 1) - pps_stabil;
1533 if (v_usec < 0)
1534 pps_stabil -= -v_usec >> PPS_AVG;
1535 else
1536 pps_stabil += v_usec >> PPS_AVG;
1537 if (pps_stabil > MAXFREQ >> 2) {
1538 pps_stbcnt++;
1539 time_status |= STA_PPSWANDER;
1540 return;
1541 }
1542 if (time_status & STA_PPSFREQ) {
1543 if (u_usec < 0) {
1544 pps_freq -= -u_usec >> PPS_AVG;
1545 if (pps_freq < -time_tolerance)
1546 pps_freq = -time_tolerance;
1547 u_usec = -u_usec;
1548 } else {
1549 pps_freq += u_usec >> PPS_AVG;
1550 if (pps_freq > time_tolerance)
1551 pps_freq = time_tolerance;
1552 }
1553 }
1554
1555 /*
1556 * Here the calibration interval is adjusted. If the maximum
1557 * time difference is greater than tick / 4, reduce the interval
1558 * by half. If this is not the case for four consecutive
1559 * intervals, double the interval.
1560 */
1561 if (u_usec << pps_shift > bigtick >> 2) {
1562 pps_intcnt = 0;
1563 if (pps_shift > PPS_SHIFT)
1564 pps_shift--;
1565 } else if (pps_intcnt >= 4) {
1566 pps_intcnt = 0;
1567 if (pps_shift < PPS_SHIFTMAX)
1568 pps_shift++;
1569 } else
1570 pps_intcnt++;
1571 }
1572 #endif /* PPS_SYNC */
1573 #endif /* NTP */
1574
1575 /* timecounter compat functions */
1576 void
1577 nanotime(struct timespec *ts)
1578 {
1579 struct timeval tv;
1580
1581 microtime(&tv);
1582 TIMEVAL_TO_TIMESPEC(&tv, ts);
1583 }
1584
1585 void
1586 getbinuptime(struct bintime *bt)
1587 {
1588 struct timeval tv;
1589
1590 microtime(&tv);
1591 timeval2bintime(&tv, bt);
1592 }
1593
1594 void
1595 nanouptime(struct timespec *tsp)
1596 {
1597 int s;
1598
1599 s = splclock();
1600 TIMEVAL_TO_TIMESPEC(&mono_time, tsp);
1601 splx(s);
1602 }
1603
1604 void
1605 getnanouptime(struct timespec *tsp)
1606 {
1607 int s;
1608
1609 s = splclock();
1610 TIMEVAL_TO_TIMESPEC(&mono_time, tsp);
1611 splx(s);
1612 }
1613
1614 void
1615 getmicrouptime(struct timeval *tvp)
1616 {
1617 int s;
1618
1619 s = splclock();
1620 *tvp = mono_time;
1621 splx(s);
1622 }
1623
1624 void
1625 getnanotime(struct timespec *tsp)
1626 {
1627 int s;
1628
1629 s = splclock();
1630 TIMEVAL_TO_TIMESPEC(&time, tsp);
1631 splx(s);
1632 }
1633
1634 void
1635 getmicrotime(struct timeval *tvp)
1636 {
1637 int s;
1638
1639 s = splclock();
1640 *tvp = time;
1641 splx(s);
1642 }
1643 #endif /* !__HAVE_TIMECOUNTER */
1644