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