2 * ----------------------------------------------------------------------------
3 * "THE BEER-WARE LICENSE" (Revision 42):
4 * <phk@FreeBSD.ORG> wrote this file. As long as you retain this notice you
5 * can do whatever you want with this stuff. If we meet some day, and you think
6 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
7 * ----------------------------------------------------------------------------
9 * Copyright (c) 2011 The FreeBSD Foundation
10 * All rights reserved.
12 * Portions of this software were developed by Julien Ridoux at the University
13 * of Melbourne under sponsorship from the FreeBSD Foundation.
16 #include <sys/cdefs.h>
17 __FBSDID("$FreeBSD$");
19 #include "opt_compat.h"
21 #include "opt_ffclock.h"
23 #include <sys/param.h>
24 #include <sys/kernel.h>
25 #include <sys/limits.h>
27 #include <sys/mutex.h>
29 #include <sys/sysctl.h>
30 #include <sys/syslog.h>
31 #include <sys/systm.h>
32 #include <sys/timeffc.h>
33 #include <sys/timepps.h>
34 #include <sys/timetc.h>
35 #include <sys/timex.h>
39 * A large step happens on boot. This constant detects such steps.
40 * It is relatively small so that ntp_update_second gets called enough
41 * in the typical 'missed a couple of seconds' case, but doesn't loop
42 * forever when the time step is large.
44 #define LARGE_STEP 200
47 * Implement a dummy timecounter which we can use until we get a real one
48 * in the air. This allows the console and other early stuff to use
53 dummy_get_timecount(struct timecounter *tc)
60 static struct timecounter dummy_timecounter = {
61 dummy_get_timecount, 0, ~0u, 1000000, "dummy", -1000000
65 /* These fields must be initialized by the driver. */
66 struct timecounter *th_counter;
67 int64_t th_adjustment;
69 u_int th_offset_count;
70 struct bintime th_offset;
71 struct timeval th_microtime;
72 struct timespec th_nanotime;
73 /* Fields not to be copied in tc_windup start with th_generation. */
75 struct timehands *th_next;
78 static struct timehands th0;
79 static struct timehands th9 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th0};
80 static struct timehands th8 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th9};
81 static struct timehands th7 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th8};
82 static struct timehands th6 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th7};
83 static struct timehands th5 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th6};
84 static struct timehands th4 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th5};
85 static struct timehands th3 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th4};
86 static struct timehands th2 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th3};
87 static struct timehands th1 = { NULL, 0, 0, 0, {0, 0}, {0, 0}, {0, 0}, 0, &th2};
88 static struct timehands th0 = {
91 (uint64_t)-1 / 1000000,
100 static struct timehands *volatile timehands = &th0;
101 struct timecounter *timecounter = &dummy_timecounter;
102 static struct timecounter *timecounters = &dummy_timecounter;
104 int tc_min_ticktock_freq = 1;
106 volatile time_t time_second = 1;
107 volatile time_t time_uptime = 1;
109 struct bintime boottimebin;
110 struct timeval boottime;
111 static int sysctl_kern_boottime(SYSCTL_HANDLER_ARGS);
112 SYSCTL_PROC(_kern, KERN_BOOTTIME, boottime, CTLTYPE_STRUCT|CTLFLAG_RD,
113 NULL, 0, sysctl_kern_boottime, "S,timeval", "System boottime");
115 SYSCTL_NODE(_kern, OID_AUTO, timecounter, CTLFLAG_RW, 0, "");
116 static SYSCTL_NODE(_kern_timecounter, OID_AUTO, tc, CTLFLAG_RW, 0, "");
118 static int timestepwarnings;
119 SYSCTL_INT(_kern_timecounter, OID_AUTO, stepwarnings, CTLFLAG_RW,
120 ×tepwarnings, 0, "Log time steps");
122 struct bintime bt_timethreshold;
123 struct bintime bt_tickthreshold;
124 sbintime_t sbt_timethreshold;
125 sbintime_t sbt_tickthreshold;
126 struct bintime tc_tick_bt;
127 sbintime_t tc_tick_sbt;
129 int tc_timepercentage = TC_DEFAULTPERC;
130 static int sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS);
131 SYSCTL_PROC(_kern_timecounter, OID_AUTO, alloweddeviation,
132 CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE, 0, 0,
133 sysctl_kern_timecounter_adjprecision, "I",
134 "Allowed time interval deviation in percents");
136 static int tc_chosen; /* Non-zero if a specific tc was chosen via sysctl. */
138 static void tc_windup(void);
139 static void cpu_tick_calibrate(int);
141 void dtrace_getnanotime(struct timespec *tsp);
144 sysctl_kern_boottime(SYSCTL_HANDLER_ARGS)
150 if (req->flags & SCTL_MASK32) {
151 tv[0] = boottime.tv_sec;
152 tv[1] = boottime.tv_usec;
153 return SYSCTL_OUT(req, tv, sizeof(tv));
157 return SYSCTL_OUT(req, &boottime, sizeof(boottime));
161 sysctl_kern_timecounter_get(SYSCTL_HANDLER_ARGS)
164 struct timecounter *tc = arg1;
166 ncount = tc->tc_get_timecount(tc);
167 return sysctl_handle_int(oidp, &ncount, 0, req);
171 sysctl_kern_timecounter_freq(SYSCTL_HANDLER_ARGS)
174 struct timecounter *tc = arg1;
176 freq = tc->tc_frequency;
177 return sysctl_handle_64(oidp, &freq, 0, req);
181 * Return the difference between the timehands' counter value now and what
182 * was when we copied it to the timehands' offset_count.
184 static __inline u_int
185 tc_delta(struct timehands *th)
187 struct timecounter *tc;
190 return ((tc->tc_get_timecount(tc) - th->th_offset_count) &
191 tc->tc_counter_mask);
195 * Functions for reading the time. We have to loop until we are sure that
196 * the timehands that we operated on was not updated under our feet. See
197 * the comment in <sys/time.h> for a description of these 12 functions.
202 fbclock_binuptime(struct bintime *bt)
204 struct timehands *th;
209 gen = atomic_load_acq_int(&th->th_generation);
211 bintime_addx(bt, th->th_scale * tc_delta(th));
212 atomic_thread_fence_acq();
213 } while (gen == 0 || gen != th->th_generation);
217 fbclock_nanouptime(struct timespec *tsp)
221 fbclock_binuptime(&bt);
222 bintime2timespec(&bt, tsp);
226 fbclock_microuptime(struct timeval *tvp)
230 fbclock_binuptime(&bt);
231 bintime2timeval(&bt, tvp);
235 fbclock_bintime(struct bintime *bt)
238 fbclock_binuptime(bt);
239 bintime_add(bt, &boottimebin);
243 fbclock_nanotime(struct timespec *tsp)
247 fbclock_bintime(&bt);
248 bintime2timespec(&bt, tsp);
252 fbclock_microtime(struct timeval *tvp)
256 fbclock_bintime(&bt);
257 bintime2timeval(&bt, tvp);
261 fbclock_getbinuptime(struct bintime *bt)
263 struct timehands *th;
268 gen = atomic_load_acq_int(&th->th_generation);
270 atomic_thread_fence_acq();
271 } while (gen == 0 || gen != th->th_generation);
275 fbclock_getnanouptime(struct timespec *tsp)
277 struct timehands *th;
282 gen = atomic_load_acq_int(&th->th_generation);
283 bintime2timespec(&th->th_offset, tsp);
284 atomic_thread_fence_acq();
285 } while (gen == 0 || gen != th->th_generation);
289 fbclock_getmicrouptime(struct timeval *tvp)
291 struct timehands *th;
296 gen = atomic_load_acq_int(&th->th_generation);
297 bintime2timeval(&th->th_offset, tvp);
298 atomic_thread_fence_acq();
299 } while (gen == 0 || gen != th->th_generation);
303 fbclock_getbintime(struct bintime *bt)
305 struct timehands *th;
310 gen = atomic_load_acq_int(&th->th_generation);
312 atomic_thread_fence_acq();
313 } while (gen == 0 || gen != th->th_generation);
314 bintime_add(bt, &boottimebin);
318 fbclock_getnanotime(struct timespec *tsp)
320 struct timehands *th;
325 gen = atomic_load_acq_int(&th->th_generation);
326 *tsp = th->th_nanotime;
327 atomic_thread_fence_acq();
328 } while (gen == 0 || gen != th->th_generation);
332 fbclock_getmicrotime(struct timeval *tvp)
334 struct timehands *th;
339 gen = atomic_load_acq_int(&th->th_generation);
340 *tvp = th->th_microtime;
341 atomic_thread_fence_acq();
342 } while (gen == 0 || gen != th->th_generation);
346 binuptime(struct bintime *bt)
348 struct timehands *th;
353 gen = atomic_load_acq_int(&th->th_generation);
355 bintime_addx(bt, th->th_scale * tc_delta(th));
356 atomic_thread_fence_acq();
357 } while (gen == 0 || gen != th->th_generation);
361 nanouptime(struct timespec *tsp)
366 bintime2timespec(&bt, tsp);
370 microuptime(struct timeval *tvp)
375 bintime2timeval(&bt, tvp);
379 bintime(struct bintime *bt)
383 bintime_add(bt, &boottimebin);
387 nanotime(struct timespec *tsp)
392 bintime2timespec(&bt, tsp);
396 microtime(struct timeval *tvp)
401 bintime2timeval(&bt, tvp);
405 getbinuptime(struct bintime *bt)
407 struct timehands *th;
412 gen = atomic_load_acq_int(&th->th_generation);
414 atomic_thread_fence_acq();
415 } while (gen == 0 || gen != th->th_generation);
419 getnanouptime(struct timespec *tsp)
421 struct timehands *th;
426 gen = atomic_load_acq_int(&th->th_generation);
427 bintime2timespec(&th->th_offset, tsp);
428 atomic_thread_fence_acq();
429 } while (gen == 0 || gen != th->th_generation);
433 getmicrouptime(struct timeval *tvp)
435 struct timehands *th;
440 gen = atomic_load_acq_int(&th->th_generation);
441 bintime2timeval(&th->th_offset, tvp);
442 atomic_thread_fence_acq();
443 } while (gen == 0 || gen != th->th_generation);
447 getbintime(struct bintime *bt)
449 struct timehands *th;
454 gen = atomic_load_acq_int(&th->th_generation);
456 atomic_thread_fence_acq();
457 } while (gen == 0 || gen != th->th_generation);
458 bintime_add(bt, &boottimebin);
462 getnanotime(struct timespec *tsp)
464 struct timehands *th;
469 gen = atomic_load_acq_int(&th->th_generation);
470 *tsp = th->th_nanotime;
471 atomic_thread_fence_acq();
472 } while (gen == 0 || gen != th->th_generation);
476 getmicrotime(struct timeval *tvp)
478 struct timehands *th;
483 gen = atomic_load_acq_int(&th->th_generation);
484 *tvp = th->th_microtime;
485 atomic_thread_fence_acq();
486 } while (gen == 0 || gen != th->th_generation);
492 * Support for feed-forward synchronization algorithms. This is heavily inspired
493 * by the timehands mechanism but kept independent from it. *_windup() functions
494 * have some connection to avoid accessing the timecounter hardware more than
498 /* Feed-forward clock estimates kept updated by the synchronization daemon. */
499 struct ffclock_estimate ffclock_estimate;
500 struct bintime ffclock_boottime; /* Feed-forward boot time estimate. */
501 uint32_t ffclock_status; /* Feed-forward clock status. */
502 int8_t ffclock_updated; /* New estimates are available. */
503 struct mtx ffclock_mtx; /* Mutex on ffclock_estimate. */
506 struct ffclock_estimate cest;
507 struct bintime tick_time;
508 struct bintime tick_time_lerp;
509 ffcounter tick_ffcount;
510 uint64_t period_lerp;
511 volatile uint8_t gen;
512 struct fftimehands *next;
515 #define NUM_ELEMENTS(x) (sizeof(x) / sizeof(*x))
517 static struct fftimehands ffth[10];
518 static struct fftimehands *volatile fftimehands = ffth;
523 struct fftimehands *cur;
524 struct fftimehands *last;
526 memset(ffth, 0, sizeof(ffth));
528 last = ffth + NUM_ELEMENTS(ffth) - 1;
529 for (cur = ffth; cur < last; cur++)
534 ffclock_status = FFCLOCK_STA_UNSYNC;
535 mtx_init(&ffclock_mtx, "ffclock lock", NULL, MTX_DEF);
539 * Reset the feed-forward clock estimates. Called from inittodr() to get things
540 * kick started and uses the timecounter nominal frequency as a first period
541 * estimate. Note: this function may be called several time just after boot.
542 * Note: this is the only function that sets the value of boot time for the
543 * monotonic (i.e. uptime) version of the feed-forward clock.
546 ffclock_reset_clock(struct timespec *ts)
548 struct timecounter *tc;
549 struct ffclock_estimate cest;
551 tc = timehands->th_counter;
552 memset(&cest, 0, sizeof(struct ffclock_estimate));
554 timespec2bintime(ts, &ffclock_boottime);
555 timespec2bintime(ts, &(cest.update_time));
556 ffclock_read_counter(&cest.update_ffcount);
557 cest.leapsec_next = 0;
558 cest.period = ((1ULL << 63) / tc->tc_frequency) << 1;
561 cest.status = FFCLOCK_STA_UNSYNC;
562 cest.leapsec_total = 0;
565 mtx_lock(&ffclock_mtx);
566 bcopy(&cest, &ffclock_estimate, sizeof(struct ffclock_estimate));
567 ffclock_updated = INT8_MAX;
568 mtx_unlock(&ffclock_mtx);
570 printf("ffclock reset: %s (%llu Hz), time = %ld.%09lu\n", tc->tc_name,
571 (unsigned long long)tc->tc_frequency, (long)ts->tv_sec,
572 (unsigned long)ts->tv_nsec);
576 * Sub-routine to convert a time interval measured in RAW counter units to time
577 * in seconds stored in bintime format.
578 * NOTE: bintime_mul requires u_int, but the value of the ffcounter may be
579 * larger than the max value of u_int (on 32 bit architecture). Loop to consume
583 ffclock_convert_delta(ffcounter ffdelta, uint64_t period, struct bintime *bt)
586 ffcounter delta, delta_max;
588 delta_max = (1ULL << (8 * sizeof(unsigned int))) - 1;
591 if (ffdelta > delta_max)
597 bintime_mul(&bt2, (unsigned int)delta);
598 bintime_add(bt, &bt2);
600 } while (ffdelta > 0);
604 * Update the fftimehands.
605 * Push the tick ffcount and time(s) forward based on current clock estimate.
606 * The conversion from ffcounter to bintime relies on the difference clock
607 * principle, whose accuracy relies on computing small time intervals. If a new
608 * clock estimate has been passed by the synchronisation daemon, make it
609 * current, and compute the linear interpolation for monotonic time if needed.
612 ffclock_windup(unsigned int delta)
614 struct ffclock_estimate *cest;
615 struct fftimehands *ffth;
616 struct bintime bt, gap_lerp;
619 unsigned int polling;
620 uint8_t forward_jump, ogen;
623 * Pick the next timehand, copy current ffclock estimates and move tick
624 * times and counter forward.
627 ffth = fftimehands->next;
631 bcopy(&fftimehands->cest, cest, sizeof(struct ffclock_estimate));
632 ffdelta = (ffcounter)delta;
633 ffth->period_lerp = fftimehands->period_lerp;
635 ffth->tick_time = fftimehands->tick_time;
636 ffclock_convert_delta(ffdelta, cest->period, &bt);
637 bintime_add(&ffth->tick_time, &bt);
639 ffth->tick_time_lerp = fftimehands->tick_time_lerp;
640 ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt);
641 bintime_add(&ffth->tick_time_lerp, &bt);
643 ffth->tick_ffcount = fftimehands->tick_ffcount + ffdelta;
646 * Assess the status of the clock, if the last update is too old, it is
647 * likely the synchronisation daemon is dead and the clock is free
650 if (ffclock_updated == 0) {
651 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
652 ffclock_convert_delta(ffdelta, cest->period, &bt);
653 if (bt.sec > 2 * FFCLOCK_SKM_SCALE)
654 ffclock_status |= FFCLOCK_STA_UNSYNC;
658 * If available, grab updated clock estimates and make them current.
659 * Recompute time at this tick using the updated estimates. The clock
660 * estimates passed the feed-forward synchronisation daemon may result
661 * in time conversion that is not monotonically increasing (just after
662 * the update). time_lerp is a particular linear interpolation over the
663 * synchronisation algo polling period that ensures monotonicity for the
664 * clock ids requesting it.
666 if (ffclock_updated > 0) {
667 bcopy(&ffclock_estimate, cest, sizeof(struct ffclock_estimate));
668 ffdelta = ffth->tick_ffcount - cest->update_ffcount;
669 ffth->tick_time = cest->update_time;
670 ffclock_convert_delta(ffdelta, cest->period, &bt);
671 bintime_add(&ffth->tick_time, &bt);
673 /* ffclock_reset sets ffclock_updated to INT8_MAX */
674 if (ffclock_updated == INT8_MAX)
675 ffth->tick_time_lerp = ffth->tick_time;
677 if (bintime_cmp(&ffth->tick_time, &ffth->tick_time_lerp, >))
682 bintime_clear(&gap_lerp);
684 gap_lerp = ffth->tick_time;
685 bintime_sub(&gap_lerp, &ffth->tick_time_lerp);
687 gap_lerp = ffth->tick_time_lerp;
688 bintime_sub(&gap_lerp, &ffth->tick_time);
692 * The reset from the RTC clock may be far from accurate, and
693 * reducing the gap between real time and interpolated time
694 * could take a very long time if the interpolated clock insists
695 * on strict monotonicity. The clock is reset under very strict
696 * conditions (kernel time is known to be wrong and
697 * synchronization daemon has been restarted recently.
698 * ffclock_boottime absorbs the jump to ensure boot time is
699 * correct and uptime functions stay consistent.
701 if (((ffclock_status & FFCLOCK_STA_UNSYNC) == FFCLOCK_STA_UNSYNC) &&
702 ((cest->status & FFCLOCK_STA_UNSYNC) == 0) &&
703 ((cest->status & FFCLOCK_STA_WARMUP) == FFCLOCK_STA_WARMUP)) {
705 bintime_add(&ffclock_boottime, &gap_lerp);
707 bintime_sub(&ffclock_boottime, &gap_lerp);
708 ffth->tick_time_lerp = ffth->tick_time;
709 bintime_clear(&gap_lerp);
712 ffclock_status = cest->status;
713 ffth->period_lerp = cest->period;
716 * Compute corrected period used for the linear interpolation of
717 * time. The rate of linear interpolation is capped to 5000PPM
720 if (bintime_isset(&gap_lerp)) {
721 ffdelta = cest->update_ffcount;
722 ffdelta -= fftimehands->cest.update_ffcount;
723 ffclock_convert_delta(ffdelta, cest->period, &bt);
726 bt.frac = 5000000 * (uint64_t)18446744073LL;
727 bintime_mul(&bt, polling);
728 if (bintime_cmp(&gap_lerp, &bt, >))
731 /* Approximate 1 sec by 1-(1/2^64) to ease arithmetic */
733 if (gap_lerp.sec > 0) {
735 frac /= ffdelta / gap_lerp.sec;
737 frac += gap_lerp.frac / ffdelta;
740 ffth->period_lerp += frac;
742 ffth->period_lerp -= frac;
754 * Adjust the fftimehands when the timecounter is changed. Stating the obvious,
755 * the old and new hardware counter cannot be read simultaneously. tc_windup()
756 * does read the two counters 'back to back', but a few cycles are effectively
757 * lost, and not accumulated in tick_ffcount. This is a fairly radical
758 * operation for a feed-forward synchronization daemon, and it is its job to not
759 * pushing irrelevant data to the kernel. Because there is no locking here,
760 * simply force to ignore pending or next update to give daemon a chance to
761 * realize the counter has changed.
764 ffclock_change_tc(struct timehands *th)
766 struct fftimehands *ffth;
767 struct ffclock_estimate *cest;
768 struct timecounter *tc;
772 ffth = fftimehands->next;
777 bcopy(&(fftimehands->cest), cest, sizeof(struct ffclock_estimate));
778 cest->period = ((1ULL << 63) / tc->tc_frequency ) << 1;
781 cest->status |= FFCLOCK_STA_UNSYNC;
783 ffth->tick_ffcount = fftimehands->tick_ffcount;
784 ffth->tick_time_lerp = fftimehands->tick_time_lerp;
785 ffth->tick_time = fftimehands->tick_time;
786 ffth->period_lerp = cest->period;
788 /* Do not lock but ignore next update from synchronization daemon. */
798 * Retrieve feed-forward counter and time of last kernel tick.
801 ffclock_last_tick(ffcounter *ffcount, struct bintime *bt, uint32_t flags)
803 struct fftimehands *ffth;
807 * No locking but check generation has not changed. Also need to make
808 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
813 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP)
814 *bt = ffth->tick_time_lerp;
816 *bt = ffth->tick_time;
817 *ffcount = ffth->tick_ffcount;
818 } while (gen == 0 || gen != ffth->gen);
822 * Absolute clock conversion. Low level function to convert ffcounter to
823 * bintime. The ffcounter is converted using the current ffclock period estimate
824 * or the "interpolated period" to ensure monotonicity.
825 * NOTE: this conversion may have been deferred, and the clock updated since the
826 * hardware counter has been read.
829 ffclock_convert_abs(ffcounter ffcount, struct bintime *bt, uint32_t flags)
831 struct fftimehands *ffth;
837 * No locking but check generation has not changed. Also need to make
838 * sure ffdelta is positive, i.e. ffcount > tick_ffcount.
843 if (ffcount > ffth->tick_ffcount)
844 ffdelta = ffcount - ffth->tick_ffcount;
846 ffdelta = ffth->tick_ffcount - ffcount;
848 if ((flags & FFCLOCK_LERP) == FFCLOCK_LERP) {
849 *bt = ffth->tick_time_lerp;
850 ffclock_convert_delta(ffdelta, ffth->period_lerp, &bt2);
852 *bt = ffth->tick_time;
853 ffclock_convert_delta(ffdelta, ffth->cest.period, &bt2);
856 if (ffcount > ffth->tick_ffcount)
857 bintime_add(bt, &bt2);
859 bintime_sub(bt, &bt2);
860 } while (gen == 0 || gen != ffth->gen);
864 * Difference clock conversion.
865 * Low level function to Convert a time interval measured in RAW counter units
866 * into bintime. The difference clock allows measuring small intervals much more
867 * reliably than the absolute clock.
870 ffclock_convert_diff(ffcounter ffdelta, struct bintime *bt)
872 struct fftimehands *ffth;
875 /* No locking but check generation has not changed. */
879 ffclock_convert_delta(ffdelta, ffth->cest.period, bt);
880 } while (gen == 0 || gen != ffth->gen);
884 * Access to current ffcounter value.
887 ffclock_read_counter(ffcounter *ffcount)
889 struct timehands *th;
890 struct fftimehands *ffth;
891 unsigned int gen, delta;
894 * ffclock_windup() called from tc_windup(), safe to rely on
895 * th->th_generation only, for correct delta and ffcounter.
899 gen = atomic_load_acq_int(&th->th_generation);
901 delta = tc_delta(th);
902 *ffcount = ffth->tick_ffcount;
903 atomic_thread_fence_acq();
904 } while (gen == 0 || gen != th->th_generation);
910 binuptime(struct bintime *bt)
913 binuptime_fromclock(bt, sysclock_active);
917 nanouptime(struct timespec *tsp)
920 nanouptime_fromclock(tsp, sysclock_active);
924 microuptime(struct timeval *tvp)
927 microuptime_fromclock(tvp, sysclock_active);
931 bintime(struct bintime *bt)
934 bintime_fromclock(bt, sysclock_active);
938 nanotime(struct timespec *tsp)
941 nanotime_fromclock(tsp, sysclock_active);
945 microtime(struct timeval *tvp)
948 microtime_fromclock(tvp, sysclock_active);
952 getbinuptime(struct bintime *bt)
955 getbinuptime_fromclock(bt, sysclock_active);
959 getnanouptime(struct timespec *tsp)
962 getnanouptime_fromclock(tsp, sysclock_active);
966 getmicrouptime(struct timeval *tvp)
969 getmicrouptime_fromclock(tvp, sysclock_active);
973 getbintime(struct bintime *bt)
976 getbintime_fromclock(bt, sysclock_active);
980 getnanotime(struct timespec *tsp)
983 getnanotime_fromclock(tsp, sysclock_active);
987 getmicrotime(struct timeval *tvp)
990 getmicrouptime_fromclock(tvp, sysclock_active);
996 * This is a clone of getnanotime and used for walltimestamps.
997 * The dtrace_ prefix prevents fbt from creating probes for
998 * it so walltimestamp can be safely used in all fbt probes.
1001 dtrace_getnanotime(struct timespec *tsp)
1003 struct timehands *th;
1008 gen = atomic_load_acq_int(&th->th_generation);
1009 *tsp = th->th_nanotime;
1010 atomic_thread_fence_acq();
1011 } while (gen == 0 || gen != th->th_generation);
1015 * System clock currently providing time to the system. Modifiable via sysctl
1016 * when the FFCLOCK option is defined.
1018 int sysclock_active = SYSCLOCK_FBCK;
1020 /* Internal NTP status and error estimates. */
1021 extern int time_status;
1022 extern long time_esterror;
1025 * Take a snapshot of sysclock data which can be used to compare system clocks
1026 * and generate timestamps after the fact.
1029 sysclock_getsnapshot(struct sysclock_snap *clock_snap, int fast)
1031 struct fbclock_info *fbi;
1032 struct timehands *th;
1034 unsigned int delta, gen;
1037 struct fftimehands *ffth;
1038 struct ffclock_info *ffi;
1039 struct ffclock_estimate cest;
1041 ffi = &clock_snap->ff_info;
1044 fbi = &clock_snap->fb_info;
1049 gen = atomic_load_acq_int(&th->th_generation);
1050 fbi->th_scale = th->th_scale;
1051 fbi->tick_time = th->th_offset;
1054 ffi->tick_time = ffth->tick_time_lerp;
1055 ffi->tick_time_lerp = ffth->tick_time_lerp;
1056 ffi->period = ffth->cest.period;
1057 ffi->period_lerp = ffth->period_lerp;
1058 clock_snap->ffcount = ffth->tick_ffcount;
1062 delta = tc_delta(th);
1063 atomic_thread_fence_acq();
1064 } while (gen == 0 || gen != th->th_generation);
1066 clock_snap->delta = delta;
1067 clock_snap->sysclock_active = sysclock_active;
1069 /* Record feedback clock status and error. */
1070 clock_snap->fb_info.status = time_status;
1071 /* XXX: Very crude estimate of feedback clock error. */
1072 bt.sec = time_esterror / 1000000;
1073 bt.frac = ((time_esterror - bt.sec) * 1000000) *
1074 (uint64_t)18446744073709ULL;
1075 clock_snap->fb_info.error = bt;
1079 clock_snap->ffcount += delta;
1081 /* Record feed-forward clock leap second adjustment. */
1082 ffi->leapsec_adjustment = cest.leapsec_total;
1083 if (clock_snap->ffcount > cest.leapsec_next)
1084 ffi->leapsec_adjustment -= cest.leapsec;
1086 /* Record feed-forward clock status and error. */
1087 clock_snap->ff_info.status = cest.status;
1088 ffcount = clock_snap->ffcount - cest.update_ffcount;
1089 ffclock_convert_delta(ffcount, cest.period, &bt);
1090 /* 18446744073709 = int(2^64/1e12), err_bound_rate in [ps/s]. */
1091 bintime_mul(&bt, cest.errb_rate * (uint64_t)18446744073709ULL);
1092 /* 18446744073 = int(2^64 / 1e9), since err_abs in [ns]. */
1093 bintime_addx(&bt, cest.errb_abs * (uint64_t)18446744073ULL);
1094 clock_snap->ff_info.error = bt;
1099 * Convert a sysclock snapshot into a struct bintime based on the specified
1100 * clock source and flags.
1103 sysclock_snap2bintime(struct sysclock_snap *cs, struct bintime *bt,
1104 int whichclock, uint32_t flags)
1111 switch (whichclock) {
1113 *bt = cs->fb_info.tick_time;
1115 /* If snapshot was created with !fast, delta will be >0. */
1117 bintime_addx(bt, cs->fb_info.th_scale * cs->delta);
1119 if ((flags & FBCLOCK_UPTIME) == 0)
1120 bintime_add(bt, &boottimebin);
1124 if (flags & FFCLOCK_LERP) {
1125 *bt = cs->ff_info.tick_time_lerp;
1126 period = cs->ff_info.period_lerp;
1128 *bt = cs->ff_info.tick_time;
1129 period = cs->ff_info.period;
1132 /* If snapshot was created with !fast, delta will be >0. */
1133 if (cs->delta > 0) {
1134 ffclock_convert_delta(cs->delta, period, &bt2);
1135 bintime_add(bt, &bt2);
1138 /* Leap second adjustment. */
1139 if (flags & FFCLOCK_LEAPSEC)
1140 bt->sec -= cs->ff_info.leapsec_adjustment;
1142 /* Boot time adjustment, for uptime/monotonic clocks. */
1143 if (flags & FFCLOCK_UPTIME)
1144 bintime_sub(bt, &ffclock_boottime);
1156 * Initialize a new timecounter and possibly use it.
1159 tc_init(struct timecounter *tc)
1162 struct sysctl_oid *tc_root;
1164 u = tc->tc_frequency / tc->tc_counter_mask;
1165 /* XXX: We need some margin here, 10% is a guess */
1168 if (u > hz && tc->tc_quality >= 0) {
1169 tc->tc_quality = -2000;
1171 printf("Timecounter \"%s\" frequency %ju Hz",
1172 tc->tc_name, (uintmax_t)tc->tc_frequency);
1173 printf(" -- Insufficient hz, needs at least %u\n", u);
1175 } else if (tc->tc_quality >= 0 || bootverbose) {
1176 printf("Timecounter \"%s\" frequency %ju Hz quality %d\n",
1177 tc->tc_name, (uintmax_t)tc->tc_frequency,
1181 tc->tc_next = timecounters;
1184 * Set up sysctl tree for this counter.
1186 tc_root = SYSCTL_ADD_NODE(NULL,
1187 SYSCTL_STATIC_CHILDREN(_kern_timecounter_tc), OID_AUTO, tc->tc_name,
1188 CTLFLAG_RW, 0, "timecounter description");
1189 SYSCTL_ADD_UINT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1190 "mask", CTLFLAG_RD, &(tc->tc_counter_mask), 0,
1191 "mask for implemented bits");
1192 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1193 "counter", CTLTYPE_UINT | CTLFLAG_RD, tc, sizeof(*tc),
1194 sysctl_kern_timecounter_get, "IU", "current timecounter value");
1195 SYSCTL_ADD_PROC(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1196 "frequency", CTLTYPE_U64 | CTLFLAG_RD, tc, sizeof(*tc),
1197 sysctl_kern_timecounter_freq, "QU", "timecounter frequency");
1198 SYSCTL_ADD_INT(NULL, SYSCTL_CHILDREN(tc_root), OID_AUTO,
1199 "quality", CTLFLAG_RD, &(tc->tc_quality), 0,
1200 "goodness of time counter");
1202 * Do not automatically switch if the current tc was specifically
1203 * chosen. Never automatically use a timecounter with negative quality.
1204 * Even though we run on the dummy counter, switching here may be
1205 * worse since this timecounter may not be monotonic.
1209 if (tc->tc_quality < 0)
1211 if (tc->tc_quality < timecounter->tc_quality)
1213 if (tc->tc_quality == timecounter->tc_quality &&
1214 tc->tc_frequency < timecounter->tc_frequency)
1216 (void)tc->tc_get_timecount(tc);
1217 (void)tc->tc_get_timecount(tc);
1221 /* Report the frequency of the current timecounter. */
1223 tc_getfrequency(void)
1226 return (timehands->th_counter->tc_frequency);
1230 * Step our concept of UTC. This is done by modifying our estimate of
1235 tc_setclock(struct timespec *ts)
1237 struct timespec tbef, taft;
1238 struct bintime bt, bt2;
1240 cpu_tick_calibrate(1);
1242 timespec2bintime(ts, &bt);
1244 bintime_sub(&bt, &bt2);
1245 bintime_add(&bt2, &boottimebin);
1247 bintime2timeval(&bt, &boottime);
1249 /* XXX fiddle all the little crinkly bits around the fiords... */
1252 if (timestepwarnings) {
1254 "Time stepped from %jd.%09ld to %jd.%09ld (%jd.%09ld)\n",
1255 (intmax_t)tbef.tv_sec, tbef.tv_nsec,
1256 (intmax_t)taft.tv_sec, taft.tv_nsec,
1257 (intmax_t)ts->tv_sec, ts->tv_nsec);
1259 cpu_tick_calibrate(1);
1263 * Initialize the next struct timehands in the ring and make
1264 * it the active timehands. Along the way we might switch to a different
1265 * timecounter and/or do seconds processing in NTP. Slightly magic.
1271 struct timehands *th, *tho;
1273 u_int delta, ncount, ogen;
1278 * Make the next timehands a copy of the current one, but do
1279 * not overwrite the generation or next pointer. While we
1280 * update the contents, the generation must be zero. We need
1281 * to ensure that the zero generation is visible before the
1282 * data updates become visible, which requires release fence.
1283 * For similar reasons, re-reading of the generation after the
1284 * data is read should use acquire fence.
1288 ogen = th->th_generation;
1289 th->th_generation = 0;
1290 atomic_thread_fence_rel();
1291 bcopy(tho, th, offsetof(struct timehands, th_generation));
1294 * Capture a timecounter delta on the current timecounter and if
1295 * changing timecounters, a counter value from the new timecounter.
1296 * Update the offset fields accordingly.
1298 delta = tc_delta(th);
1299 if (th->th_counter != timecounter)
1300 ncount = timecounter->tc_get_timecount(timecounter);
1304 ffclock_windup(delta);
1306 th->th_offset_count += delta;
1307 th->th_offset_count &= th->th_counter->tc_counter_mask;
1308 while (delta > th->th_counter->tc_frequency) {
1309 /* Eat complete unadjusted seconds. */
1310 delta -= th->th_counter->tc_frequency;
1311 th->th_offset.sec++;
1313 if ((delta > th->th_counter->tc_frequency / 2) &&
1314 (th->th_scale * delta < ((uint64_t)1 << 63))) {
1315 /* The product th_scale * delta just barely overflows. */
1316 th->th_offset.sec++;
1318 bintime_addx(&th->th_offset, th->th_scale * delta);
1321 * Hardware latching timecounters may not generate interrupts on
1322 * PPS events, so instead we poll them. There is a finite risk that
1323 * the hardware might capture a count which is later than the one we
1324 * got above, and therefore possibly in the next NTP second which might
1325 * have a different rate than the current NTP second. It doesn't
1326 * matter in practice.
1328 if (tho->th_counter->tc_poll_pps)
1329 tho->th_counter->tc_poll_pps(tho->th_counter);
1332 * Deal with NTP second processing. The for loop normally
1333 * iterates at most once, but in extreme situations it might
1334 * keep NTP sane if timeouts are not run for several seconds.
1335 * At boot, the time step can be large when the TOD hardware
1336 * has been read, so on really large steps, we call
1337 * ntp_update_second only twice. We need to call it twice in
1338 * case we missed a leap second.
1341 bintime_add(&bt, &boottimebin);
1342 i = bt.sec - tho->th_microtime.tv_sec;
1345 for (; i > 0; i--) {
1347 ntp_update_second(&th->th_adjustment, &bt.sec);
1349 boottimebin.sec += bt.sec - t;
1351 /* Update the UTC timestamps used by the get*() functions. */
1352 /* XXX shouldn't do this here. Should force non-`get' versions. */
1353 bintime2timeval(&bt, &th->th_microtime);
1354 bintime2timespec(&bt, &th->th_nanotime);
1356 /* Now is a good time to change timecounters. */
1357 if (th->th_counter != timecounter) {
1359 if ((timecounter->tc_flags & TC_FLAGS_C2STOP) != 0)
1360 cpu_disable_c2_sleep++;
1361 if ((th->th_counter->tc_flags & TC_FLAGS_C2STOP) != 0)
1362 cpu_disable_c2_sleep--;
1364 th->th_counter = timecounter;
1365 th->th_offset_count = ncount;
1366 tc_min_ticktock_freq = max(1, timecounter->tc_frequency /
1367 (((uint64_t)timecounter->tc_counter_mask + 1) / 3));
1369 ffclock_change_tc(th);
1374 * Recalculate the scaling factor. We want the number of 1/2^64
1375 * fractions of a second per period of the hardware counter, taking
1376 * into account the th_adjustment factor which the NTP PLL/adjtime(2)
1377 * processing provides us with.
1379 * The th_adjustment is nanoseconds per second with 32 bit binary
1380 * fraction and we want 64 bit binary fraction of second:
1382 * x = a * 2^32 / 10^9 = a * 4.294967296
1384 * The range of th_adjustment is +/- 5000PPM so inside a 64bit int
1385 * we can only multiply by about 850 without overflowing, that
1386 * leaves no suitably precise fractions for multiply before divide.
1388 * Divide before multiply with a fraction of 2199/512 results in a
1389 * systematic undercompensation of 10PPM of th_adjustment. On a
1390 * 5000PPM adjustment this is a 0.05PPM error. This is acceptable.
1392 * We happily sacrifice the lowest of the 64 bits of our result
1393 * to the goddess of code clarity.
1396 scale = (uint64_t)1 << 63;
1397 scale += (th->th_adjustment / 1024) * 2199;
1398 scale /= th->th_counter->tc_frequency;
1399 th->th_scale = scale * 2;
1402 * Now that the struct timehands is again consistent, set the new
1403 * generation number, making sure to not make it zero.
1407 atomic_store_rel_int(&th->th_generation, ogen);
1409 /* Go live with the new struct timehands. */
1411 switch (sysclock_active) {
1414 time_second = th->th_microtime.tv_sec;
1415 time_uptime = th->th_offset.sec;
1419 time_second = fftimehands->tick_time_lerp.sec;
1420 time_uptime = fftimehands->tick_time_lerp.sec - ffclock_boottime.sec;
1426 timekeep_push_vdso();
1429 /* Report or change the active timecounter hardware. */
1431 sysctl_kern_timecounter_hardware(SYSCTL_HANDLER_ARGS)
1434 struct timecounter *newtc, *tc;
1438 strlcpy(newname, tc->tc_name, sizeof(newname));
1440 error = sysctl_handle_string(oidp, &newname[0], sizeof(newname), req);
1441 if (error != 0 || req->newptr == NULL)
1443 /* Record that the tc in use now was specifically chosen. */
1445 if (strcmp(newname, tc->tc_name) == 0)
1447 for (newtc = timecounters; newtc != NULL; newtc = newtc->tc_next) {
1448 if (strcmp(newname, newtc->tc_name) != 0)
1451 /* Warm up new timecounter. */
1452 (void)newtc->tc_get_timecount(newtc);
1453 (void)newtc->tc_get_timecount(newtc);
1455 timecounter = newtc;
1458 * The vdso timehands update is deferred until the next
1461 * This is prudent given that 'timekeep_push_vdso()' does not
1462 * use any locking and that it can be called in hard interrupt
1463 * context via 'tc_windup()'.
1470 SYSCTL_PROC(_kern_timecounter, OID_AUTO, hardware, CTLTYPE_STRING | CTLFLAG_RW,
1471 0, 0, sysctl_kern_timecounter_hardware, "A",
1472 "Timecounter hardware selected");
1475 /* Report the available timecounter hardware. */
1477 sysctl_kern_timecounter_choice(SYSCTL_HANDLER_ARGS)
1480 struct timecounter *tc;
1483 sbuf_new_for_sysctl(&sb, NULL, 0, req);
1484 for (tc = timecounters; tc != NULL; tc = tc->tc_next) {
1485 if (tc != timecounters)
1486 sbuf_putc(&sb, ' ');
1487 sbuf_printf(&sb, "%s(%d)", tc->tc_name, tc->tc_quality);
1489 error = sbuf_finish(&sb);
1494 SYSCTL_PROC(_kern_timecounter, OID_AUTO, choice, CTLTYPE_STRING | CTLFLAG_RD,
1495 0, 0, sysctl_kern_timecounter_choice, "A", "Timecounter hardware detected");
1498 * RFC 2783 PPS-API implementation.
1502 * Return true if the driver is aware of the abi version extensions in the
1503 * pps_state structure, and it supports at least the given abi version number.
1506 abi_aware(struct pps_state *pps, int vers)
1509 return ((pps->kcmode & KCMODE_ABIFLAG) && pps->driver_abi >= vers);
1513 pps_fetch(struct pps_fetch_args *fapi, struct pps_state *pps)
1516 pps_seq_t aseq, cseq;
1519 if (fapi->tsformat && fapi->tsformat != PPS_TSFMT_TSPEC)
1523 * If no timeout is requested, immediately return whatever values were
1524 * most recently captured. If timeout seconds is -1, that's a request
1525 * to block without a timeout. WITNESS won't let us sleep forever
1526 * without a lock (we really don't need a lock), so just repeatedly
1527 * sleep a long time.
1529 if (fapi->timeout.tv_sec || fapi->timeout.tv_nsec) {
1530 if (fapi->timeout.tv_sec == -1)
1533 tv.tv_sec = fapi->timeout.tv_sec;
1534 tv.tv_usec = fapi->timeout.tv_nsec / 1000;
1537 aseq = pps->ppsinfo.assert_sequence;
1538 cseq = pps->ppsinfo.clear_sequence;
1539 while (aseq == pps->ppsinfo.assert_sequence &&
1540 cseq == pps->ppsinfo.clear_sequence) {
1541 if (abi_aware(pps, 1) && pps->driver_mtx != NULL) {
1542 if (pps->flags & PPSFLAG_MTX_SPIN) {
1543 err = msleep_spin(pps, pps->driver_mtx,
1546 err = msleep(pps, pps->driver_mtx, PCATCH,
1550 err = tsleep(pps, PCATCH, "ppsfch", timo);
1552 if (err == EWOULDBLOCK) {
1553 if (fapi->timeout.tv_sec == -1) {
1558 } else if (err != 0) {
1564 pps->ppsinfo.current_mode = pps->ppsparam.mode;
1565 fapi->pps_info_buf = pps->ppsinfo;
1571 pps_ioctl(u_long cmd, caddr_t data, struct pps_state *pps)
1574 struct pps_fetch_args *fapi;
1576 struct pps_fetch_ffc_args *fapi_ffc;
1579 struct pps_kcbind_args *kapi;
1582 KASSERT(pps != NULL, ("NULL pps pointer in pps_ioctl"));
1584 case PPS_IOC_CREATE:
1586 case PPS_IOC_DESTROY:
1588 case PPS_IOC_SETPARAMS:
1589 app = (pps_params_t *)data;
1590 if (app->mode & ~pps->ppscap)
1593 /* Ensure only a single clock is selected for ffc timestamp. */
1594 if ((app->mode & PPS_TSCLK_MASK) == PPS_TSCLK_MASK)
1597 pps->ppsparam = *app;
1599 case PPS_IOC_GETPARAMS:
1600 app = (pps_params_t *)data;
1601 *app = pps->ppsparam;
1602 app->api_version = PPS_API_VERS_1;
1604 case PPS_IOC_GETCAP:
1605 *(int*)data = pps->ppscap;
1608 fapi = (struct pps_fetch_args *)data;
1609 return (pps_fetch(fapi, pps));
1611 case PPS_IOC_FETCH_FFCOUNTER:
1612 fapi_ffc = (struct pps_fetch_ffc_args *)data;
1613 if (fapi_ffc->tsformat && fapi_ffc->tsformat !=
1616 if (fapi_ffc->timeout.tv_sec || fapi_ffc->timeout.tv_nsec)
1617 return (EOPNOTSUPP);
1618 pps->ppsinfo_ffc.current_mode = pps->ppsparam.mode;
1619 fapi_ffc->pps_info_buf_ffc = pps->ppsinfo_ffc;
1620 /* Overwrite timestamps if feedback clock selected. */
1621 switch (pps->ppsparam.mode & PPS_TSCLK_MASK) {
1622 case PPS_TSCLK_FBCK:
1623 fapi_ffc->pps_info_buf_ffc.assert_timestamp =
1624 pps->ppsinfo.assert_timestamp;
1625 fapi_ffc->pps_info_buf_ffc.clear_timestamp =
1626 pps->ppsinfo.clear_timestamp;
1628 case PPS_TSCLK_FFWD:
1634 #endif /* FFCLOCK */
1635 case PPS_IOC_KCBIND:
1637 kapi = (struct pps_kcbind_args *)data;
1638 /* XXX Only root should be able to do this */
1639 if (kapi->tsformat && kapi->tsformat != PPS_TSFMT_TSPEC)
1641 if (kapi->kernel_consumer != PPS_KC_HARDPPS)
1643 if (kapi->edge & ~pps->ppscap)
1645 pps->kcmode = (kapi->edge & KCMODE_EDGEMASK) |
1646 (pps->kcmode & KCMODE_ABIFLAG);
1649 return (EOPNOTSUPP);
1657 pps_init(struct pps_state *pps)
1659 pps->ppscap |= PPS_TSFMT_TSPEC | PPS_CANWAIT;
1660 if (pps->ppscap & PPS_CAPTUREASSERT)
1661 pps->ppscap |= PPS_OFFSETASSERT;
1662 if (pps->ppscap & PPS_CAPTURECLEAR)
1663 pps->ppscap |= PPS_OFFSETCLEAR;
1665 pps->ppscap |= PPS_TSCLK_MASK;
1667 pps->kcmode &= ~KCMODE_ABIFLAG;
1671 pps_init_abi(struct pps_state *pps)
1675 if (pps->driver_abi > 0) {
1676 pps->kcmode |= KCMODE_ABIFLAG;
1677 pps->kernel_abi = PPS_ABI_VERSION;
1682 pps_capture(struct pps_state *pps)
1684 struct timehands *th;
1686 KASSERT(pps != NULL, ("NULL pps pointer in pps_capture"));
1688 pps->capgen = atomic_load_acq_int(&th->th_generation);
1691 pps->capffth = fftimehands;
1693 pps->capcount = th->th_counter->tc_get_timecount(th->th_counter);
1694 atomic_thread_fence_acq();
1695 if (pps->capgen != th->th_generation)
1700 pps_event(struct pps_state *pps, int event)
1703 struct timespec ts, *tsp, *osp;
1704 u_int tcount, *pcount;
1708 struct timespec *tsp_ffc;
1709 pps_seq_t *pseq_ffc;
1713 KASSERT(pps != NULL, ("NULL pps pointer in pps_event"));
1714 /* Nothing to do if not currently set to capture this event type. */
1715 if ((event & pps->ppsparam.mode) == 0)
1717 /* If the timecounter was wound up underneath us, bail out. */
1718 if (pps->capgen == 0 || pps->capgen !=
1719 atomic_load_acq_int(&pps->capth->th_generation))
1722 /* Things would be easier with arrays. */
1723 if (event == PPS_CAPTUREASSERT) {
1724 tsp = &pps->ppsinfo.assert_timestamp;
1725 osp = &pps->ppsparam.assert_offset;
1726 foff = pps->ppsparam.mode & PPS_OFFSETASSERT;
1727 fhard = pps->kcmode & PPS_CAPTUREASSERT;
1728 pcount = &pps->ppscount[0];
1729 pseq = &pps->ppsinfo.assert_sequence;
1731 ffcount = &pps->ppsinfo_ffc.assert_ffcount;
1732 tsp_ffc = &pps->ppsinfo_ffc.assert_timestamp;
1733 pseq_ffc = &pps->ppsinfo_ffc.assert_sequence;
1736 tsp = &pps->ppsinfo.clear_timestamp;
1737 osp = &pps->ppsparam.clear_offset;
1738 foff = pps->ppsparam.mode & PPS_OFFSETCLEAR;
1739 fhard = pps->kcmode & PPS_CAPTURECLEAR;
1740 pcount = &pps->ppscount[1];
1741 pseq = &pps->ppsinfo.clear_sequence;
1743 ffcount = &pps->ppsinfo_ffc.clear_ffcount;
1744 tsp_ffc = &pps->ppsinfo_ffc.clear_timestamp;
1745 pseq_ffc = &pps->ppsinfo_ffc.clear_sequence;
1750 * If the timecounter changed, we cannot compare the count values, so
1751 * we have to drop the rest of the PPS-stuff until the next event.
1753 if (pps->ppstc != pps->capth->th_counter) {
1754 pps->ppstc = pps->capth->th_counter;
1755 *pcount = pps->capcount;
1756 pps->ppscount[2] = pps->capcount;
1760 /* Convert the count to a timespec. */
1761 tcount = pps->capcount - pps->capth->th_offset_count;
1762 tcount &= pps->capth->th_counter->tc_counter_mask;
1763 bt = pps->capth->th_offset;
1764 bintime_addx(&bt, pps->capth->th_scale * tcount);
1765 bintime_add(&bt, &boottimebin);
1766 bintime2timespec(&bt, &ts);
1768 /* If the timecounter was wound up underneath us, bail out. */
1769 atomic_thread_fence_acq();
1770 if (pps->capgen != pps->capth->th_generation)
1773 *pcount = pps->capcount;
1778 timespecadd(tsp, osp);
1779 if (tsp->tv_nsec < 0) {
1780 tsp->tv_nsec += 1000000000;
1786 *ffcount = pps->capffth->tick_ffcount + tcount;
1787 bt = pps->capffth->tick_time;
1788 ffclock_convert_delta(tcount, pps->capffth->cest.period, &bt);
1789 bintime_add(&bt, &pps->capffth->tick_time);
1790 bintime2timespec(&bt, &ts);
1800 * Feed the NTP PLL/FLL.
1801 * The FLL wants to know how many (hardware) nanoseconds
1802 * elapsed since the previous event.
1804 tcount = pps->capcount - pps->ppscount[2];
1805 pps->ppscount[2] = pps->capcount;
1806 tcount &= pps->capth->th_counter->tc_counter_mask;
1807 scale = (uint64_t)1 << 63;
1808 scale /= pps->capth->th_counter->tc_frequency;
1812 bintime_addx(&bt, scale * tcount);
1813 bintime2timespec(&bt, &ts);
1814 hardpps(tsp, ts.tv_nsec + 1000000000 * ts.tv_sec);
1818 /* Wakeup anyone sleeping in pps_fetch(). */
1823 * Timecounters need to be updated every so often to prevent the hardware
1824 * counter from overflowing. Updating also recalculates the cached values
1825 * used by the get*() family of functions, so their precision depends on
1826 * the update frequency.
1830 SYSCTL_INT(_kern_timecounter, OID_AUTO, tick, CTLFLAG_RD, &tc_tick, 0,
1831 "Approximate number of hardclock ticks in a millisecond");
1834 tc_ticktock(int cnt)
1839 if (count < tc_tick)
1845 static void __inline
1846 tc_adjprecision(void)
1850 if (tc_timepercentage > 0) {
1851 t = (99 + tc_timepercentage) / tc_timepercentage;
1852 tc_precexp = fls(t + (t >> 1)) - 1;
1853 FREQ2BT(hz / tc_tick, &bt_timethreshold);
1854 FREQ2BT(hz, &bt_tickthreshold);
1855 bintime_shift(&bt_timethreshold, tc_precexp);
1856 bintime_shift(&bt_tickthreshold, tc_precexp);
1859 bt_timethreshold.sec = INT_MAX;
1860 bt_timethreshold.frac = ~(uint64_t)0;
1861 bt_tickthreshold = bt_timethreshold;
1863 sbt_timethreshold = bttosbt(bt_timethreshold);
1864 sbt_tickthreshold = bttosbt(bt_tickthreshold);
1868 sysctl_kern_timecounter_adjprecision(SYSCTL_HANDLER_ARGS)
1872 val = tc_timepercentage;
1873 error = sysctl_handle_int(oidp, &val, 0, req);
1874 if (error != 0 || req->newptr == NULL)
1876 tc_timepercentage = val;
1885 inittimecounter(void *dummy)
1891 * Set the initial timeout to
1892 * max(1, <approx. number of hardclock ticks in a millisecond>).
1893 * People should probably not use the sysctl to set the timeout
1894 * to smaller than its inital value, since that value is the
1895 * smallest reasonable one. If they want better timestamps they
1896 * should use the non-"get"* functions.
1899 tc_tick = (hz + 500) / 1000;
1903 FREQ2BT(hz, &tick_bt);
1904 tick_sbt = bttosbt(tick_bt);
1905 tick_rate = hz / tc_tick;
1906 FREQ2BT(tick_rate, &tc_tick_bt);
1907 tc_tick_sbt = bttosbt(tc_tick_bt);
1908 p = (tc_tick * 1000000) / hz;
1909 printf("Timecounters tick every %d.%03u msec\n", p / 1000, p % 1000);
1914 /* warm up new timecounter (again) and get rolling. */
1915 (void)timecounter->tc_get_timecount(timecounter);
1916 (void)timecounter->tc_get_timecount(timecounter);
1920 SYSINIT(timecounter, SI_SUB_CLOCKS, SI_ORDER_SECOND, inittimecounter, NULL);
1922 /* Cpu tick handling -------------------------------------------------*/
1924 static int cpu_tick_variable;
1925 static uint64_t cpu_tick_frequency;
1930 static uint64_t base;
1931 static unsigned last;
1933 struct timecounter *tc;
1935 tc = timehands->th_counter;
1936 u = tc->tc_get_timecount(tc) & tc->tc_counter_mask;
1938 base += (uint64_t)tc->tc_counter_mask + 1;
1944 cpu_tick_calibration(void)
1946 static time_t last_calib;
1948 if (time_uptime != last_calib && !(time_uptime & 0xf)) {
1949 cpu_tick_calibrate(0);
1950 last_calib = time_uptime;
1955 * This function gets called every 16 seconds on only one designated
1956 * CPU in the system from hardclock() via cpu_tick_calibration()().
1958 * Whenever the real time clock is stepped we get called with reset=1
1959 * to make sure we handle suspend/resume and similar events correctly.
1963 cpu_tick_calibrate(int reset)
1965 static uint64_t c_last;
1966 uint64_t c_this, c_delta;
1967 static struct bintime t_last;
1968 struct bintime t_this, t_delta;
1972 /* The clock was stepped, abort & reset */
1977 /* we don't calibrate fixed rate cputicks */
1978 if (!cpu_tick_variable)
1981 getbinuptime(&t_this);
1982 c_this = cpu_ticks();
1983 if (t_last.sec != 0) {
1984 c_delta = c_this - c_last;
1986 bintime_sub(&t_delta, &t_last);
1989 * 2^(64-20) / 16[s] =
1991 * 17.592.186.044.416 / 16 =
1992 * 1.099.511.627.776 [Hz]
1994 divi = t_delta.sec << 20;
1995 divi |= t_delta.frac >> (64 - 20);
1998 if (c_delta > cpu_tick_frequency) {
1999 if (0 && bootverbose)
2000 printf("cpu_tick increased to %ju Hz\n",
2002 cpu_tick_frequency = c_delta;
2010 set_cputicker(cpu_tick_f *func, uint64_t freq, unsigned var)
2014 cpu_ticks = tc_cpu_ticks;
2016 cpu_tick_frequency = freq;
2017 cpu_tick_variable = var;
2026 if (cpu_ticks == tc_cpu_ticks)
2027 return (tc_getfrequency());
2028 return (cpu_tick_frequency);
2032 * We need to be slightly careful converting cputicks to microseconds.
2033 * There is plenty of margin in 64 bits of microseconds (half a million
2034 * years) and in 64 bits at 4 GHz (146 years), but if we do a multiply
2035 * before divide conversion (to retain precision) we find that the
2036 * margin shrinks to 1.5 hours (one millionth of 146y).
2037 * With a three prong approach we never lose significant bits, no
2038 * matter what the cputick rate and length of timeinterval is.
2042 cputick2usec(uint64_t tick)
2045 if (tick > 18446744073709551LL) /* floor(2^64 / 1000) */
2046 return (tick / (cpu_tickrate() / 1000000LL));
2047 else if (tick > 18446744073709LL) /* floor(2^64 / 1000000) */
2048 return ((tick * 1000LL) / (cpu_tickrate() / 1000LL));
2050 return ((tick * 1000000LL) / cpu_tickrate());
2053 cpu_tick_f *cpu_ticks = tc_cpu_ticks;
2055 static int vdso_th_enable = 1;
2057 sysctl_fast_gettime(SYSCTL_HANDLER_ARGS)
2059 int old_vdso_th_enable, error;
2061 old_vdso_th_enable = vdso_th_enable;
2062 error = sysctl_handle_int(oidp, &old_vdso_th_enable, 0, req);
2065 vdso_th_enable = old_vdso_th_enable;
2068 SYSCTL_PROC(_kern_timecounter, OID_AUTO, fast_gettime,
2069 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
2070 NULL, 0, sysctl_fast_gettime, "I", "Enable fast time of day");
2073 tc_fill_vdso_timehands(struct vdso_timehands *vdso_th)
2075 struct timehands *th;
2079 vdso_th->th_algo = VDSO_TH_ALGO_1;
2080 vdso_th->th_scale = th->th_scale;
2081 vdso_th->th_offset_count = th->th_offset_count;
2082 vdso_th->th_counter_mask = th->th_counter->tc_counter_mask;
2083 vdso_th->th_offset = th->th_offset;
2084 vdso_th->th_boottime = boottimebin;
2085 enabled = cpu_fill_vdso_timehands(vdso_th, th->th_counter);
2086 if (!vdso_th_enable)
2091 #ifdef COMPAT_FREEBSD32
2093 tc_fill_vdso_timehands32(struct vdso_timehands32 *vdso_th32)
2095 struct timehands *th;
2099 vdso_th32->th_algo = VDSO_TH_ALGO_1;
2100 *(uint64_t *)&vdso_th32->th_scale[0] = th->th_scale;
2101 vdso_th32->th_offset_count = th->th_offset_count;
2102 vdso_th32->th_counter_mask = th->th_counter->tc_counter_mask;
2103 vdso_th32->th_offset.sec = th->th_offset.sec;
2104 *(uint64_t *)&vdso_th32->th_offset.frac[0] = th->th_offset.frac;
2105 vdso_th32->th_boottime.sec = boottimebin.sec;
2106 *(uint64_t *)&vdso_th32->th_boottime.frac[0] = boottimebin.frac;
2107 enabled = cpu_fill_vdso_timehands32(vdso_th32, th->th_counter);
2108 if (!vdso_th_enable)